Compare commits

...
32 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.8 7a3c1d6683 Clearer job status labels: 'Preparing your audio' for uploads + fix raw jobStatus.Processing key (#940)
## Why

Two frontend job-status **label** bugs, both surfaced while manually
driving the Vocal Star tenant flow:

1. **Tenant/upload jobs show "Downloading"** even though the operator
uploaded their own audio — there's nothing to download. (Andrew hit this
on a real job: "it's currently Downloading — what is there to download
though, since I uploaded the files?")
2. **Backlog item — raw i18n key rendered verbatim:** status sometimes
reads `[4/10] jobStatus.Processing`.

Both live in `frontend/lib/job-status.ts`.

## Fixes

**1. "Preparing your audio" for upload-based jobs.** The download stage
reused the consumer "Downloading" label. For jobs with a pre-supplied
instrumental (`existing_instrumental_gcs_path`), the staging stage now
shows **"Preparing your audio"**. Added `existing_instrumental_gcs_path`
to the job-list summary projection (`SUMMARY_FIELD_PATHS`) — it's a
top-level field (no `state_data` prune needed), so the list view can
detect upload jobs.

**2. No more raw `jobStatus.X`.** The "downloading + workers running"
path passed the **literal string `"Processing"`** (not a `jobStatus`
key) as the label, so `t("Processing")` missed and rendered
`jobStatus.Processing`. Now it uses a valid `processing` key, and when
only one parallel worker is reporting (tenant jobs run lyrics only — no
separation), it shows that worker's real status (e.g. "Transcribing
lyrics") instead of a generic label.

## Guardrail

Added a regression test asserting **every label `getJobStep` can emit
exists in `en.json` jobStatus** — so this whole class of raw-key bug
can't recur.

## Testing

- Frontend `job-status.test.ts`: 90/90 pass (new cases: upload-job
relabel, downloading_audio, advance-to-transcribing,
no-relabel-for-normal-jobs, raw-key regression, en.json completeness).
- Backend: new `SUMMARY_FIELD_PATHS` projection guard test.
- New keys `jobStatus.preparingAudio` + `jobStatus.processing`
translated to all 33 locales.
- Version bumped 0.199.2 → 0.199.3.
- CodeRabbit local review: 0 findings.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-24 23:05:41 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 c36bcb0850 Tenant flow: harden E2E invariants + retry transient Cloud Run Jobs trigger errors (#939)
## Why

FROG: validate the white-label tenant portals (Vocal Star) work
seamlessly end-to-end, and make the flow robust. Two related changes,
both about the exact flow tenant operators rely on.

## 1. Harden the tenant E2E to actually test the real scenario

The tenant happy-path E2E verified a job *completed and distributed
privately*, but **tolerated a regression in the tenant-specific flow**:
it "handled both" an instrumental-selection step appearing or not, so a
regression that forced audio separation / an instrumental-review step on
a tenant (who always uploads their own instrumental) would still have
passed — the same "looks done but is broken" class as the June latent
bugs.

Tightened `tenant-happy-path.spec.ts` to lock the real-world invariants:
- Assert the InstrumentalSelector **never** renders (no separation → no
stem to pick).
- Assert `state_data.instrumental_selection === 'custom'` (the uploaded
instrumental is used, not a separated stem).
- Assert `state_data.lyrics_complete` (transcription actually ran; not a
short-circuit).

Verified against a real completed vocalstar prod job (`ef72f5f8`): all
new assertions hold.

## 2. Retry transient Cloud Run Jobs Admin API errors when triggering
workers

During validation, a real singa job hit `Failed to trigger Cloud Run Job
lyrics-transcription-job: 503 The service is currently unavailable`.
Root cause: `JobsClient.run_job()` had **no retry** — a one-off
transient 5xx/429 from the Jobs Admin control plane hard-failed the
trigger (the except just logged + returned False). `run_job` only
*enqueues* an execution, so this is safe to retry. The daily E2E masked
it with a workflow-level retry; a real customer job would have just
failed at transcription.

Added `_run_job_with_retry` (bounded async retry, 3 attempts,
`asyncio.sleep` backoff) shared by **both** `run_job` call sites
(`_trigger_worker_cloud_run_job` — audio-download / separation / lyrics
/ video — and `trigger_bulk_search_worker`). Retries transient errors
only (503/500/504/429); permanent errors
(NotFound/PermissionDenied/InvalidArgument) fail fast; re-raises after
exhausting so the existing handler logs + returns False.

## Testing

- New unit tests: transient-then-success retries once; persistent
transient exhausts to False after N attempts; permanent error fails fast
without retry. `backend/tests/test_services.py -k trigger` → 13/13 pass.
- E2E assertions verified against a real completed prod job.
- CodeRabbit local review: 0 findings.
- Version bumped 0.199.1 → 0.199.2.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-24 22:01:11 -04:00
Andrew Beveridge ☄️andClaude Fable 5 e0e5959edc fix(review): surface relevance-filter rejection when pasting lyrics + Add Anyway force option (#937)
## Summary

Pasting reference lyrics in the review UI could silently do nothing: if
the relevance filter (30% anchor-match threshold) rejected the pasted
source during the correction rerun, the `add-lyrics` endpoint still
returned a generic success, so the paste tab cleared the box, closed the
modal, and no reference lyrics appeared — with zero feedback.

Observed in prod on job `0eebb248` ("Jonny Hill & Linda Feller –
Darling"): two "successful" add-lyrics calls, both sources rejected at
1.3% relevance (3/230 words), `reference_lyrics` left empty.

## Changes

- **Backend (`/api/review/{job_id}/add-lyrics`)**: when the source is
dropped by the relevance filter, return `{status: "rejected", rejection:
{relevance, matched_words, total_words}}` and skip persisting the no-op
rerun to GCS. Same change in the local `ReviewServer` (wheel/CLI review
mode), including `force` support it previously lacked.
- **Frontend**: `addLyrics` API client sends the `force` flag (as a
string — the endpoint body is `Dict[str, str]`, which also makes it
deploy-skew-safe). `PasteLyricsTab` keeps the pasted text on rejection,
shows a warning with the match %, and offers an **Add Anyway** button
that retries with `force=true`. Covers both the Add Lyrics modal and the
inline empty-state, which share the tab.
- **i18n**: new `pasteLyrics.rejectedWarning` / `addAnyway` strings
translated to all 33 locales.
- **Docs**: `docs/API.md` add-lyrics section documents the rejected
response.
- **Tests**: backend endpoint tests (success/rejected/force passthrough,
no-upload-on-reject), API client tests (force string, rejected
envelope), and `PasteLyricsTab` component tests (rejection UI, Add
Anyway flow, warning cleared on edit, legacy void result).

## Testing

- `make test`: full backend + frontend suite green (92 suites / 1158
frontend tests; backend 56 review-route tests incl. 3 new).
- Local CodeRabbit review completed; single finding was a pre-existing
translation nitpick (skipped).

@coderabbitai ignore

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 17:06:41 -04:00
Andrew Beveridge ☄️andClaude Fable 5 1755fa138c fix(review): correct vocal waveform time drift on 44.1kHz audio devices (#938)
## Summary

Fixes the vocal waveform in the lyrics-review timeline editor appearing
shifted ~0.4–0.5s late relative to the audio in some situations
(reported on job 0eebb248, segment 25 at ~171s).

**Root cause:** the client-side peak envelope in
`frontend/lib/audio-data.ts` floored samples-per-bucket to an integer.
At a 44.1kHz `AudioContext` (device-dependent — common on Macs and audio
interfaces) the exact stride is 110.25 samples but was floored to 110,
making the envelope's clock run ~0.23% fast. The waveform drifted late
by ~2.3ms per second of song — ~0.4s by the 3-minute mark. 48kHz devices
divide evenly (120) and were unaffected, which is why the bug only
appeared "in some situations".

## Changes

- Bucket boundaries are now computed from the fractional stride
(`Math.floor(bucket * samplesPerBucket)`), keeping every bucket within
one bucket (2.5ms, non-accumulating, sub-pixel) of its nominal 1/400s
position at any sample rate.
- Peak computation extracted into an exported pure `computePeaks()` so
it's unit-testable without a browser `AudioContext`.
- 7 new unit tests in `frontend/lib/__tests__/audio-data.test.ts`,
including a 44.1kHz drift regression test that fails against the old
floored-stride code (impulse landed 27 buckets / 67ms late at 29.5s).
- Version bump 0.198.4.

## Testing

- `make test`: all backend tests + 92 frontend suites (1158 tests) pass.
- New regression tests verified to fail against the pre-fix
implementation.
- Local 8-angle code review + CodeRabbit CLI review: no findings.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 16:50:33 -04:00
Andrew Beveridge ☄️andClaude Fable 5 b5461132d0 feat(admin): create users from admin UI + auto-create account on job user_email reassignment (#936)
## Summary

Lets admins provision user accounts before the user has ever logged in —
so we can grant free credits, submit jobs on their behalf, and
impersonate them — and fixes the gap where reassigning a job's
`user_email` to an unknown email left the job orphaned (no account, no
credits, impersonation 404s).

### Changes

- **`POST /api/users/admin/users`** — create a user account directly:
`email` (required), `display_name`, `initial_credits` (0-1000),
`credit_reason`. Returns 409 on duplicate. Initial credits set
`welcome_credits_granted` so the user doesn't also get the automatic
welcome credit on first login.
- **`PATCH /api/admin/jobs/{id}`** — `user_email` is now trimmed +
lowercased (account doc IDs are lowercased emails; mixed case would
silently orphan the job), blank/invalid values are rejected with 400,
and a `gen_users` account is auto-created when none exists. Response
message notes the creation.
- **Admin users page** — "Create User" button + dialog; on success the
list filters to the new user so Impersonate / Add Credits work
immediately.
- **Admin jobs page** — field-save toast surfaces the account-created
message; local state mirrors the backend's email normalization.

### Testing

- New `backend/tests/test_admin_create_user.py` (9 tests) +
`TestUpdateJobUserEmailAutoCreate` (5 tests) in
`test_admin_job_update.py`
- Full backend suite: 3917 passed. Frontend: 1151 Jest tests passed;
eslint/tsc clean on touched files
- CodeRabbit local review: 2 cycles, all findings addressed (PII
redaction, blank-email 400, masked audit log, normalized local state)

Version bump: 0.198.3 → 0.199.0

@coderabbitai ignore

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 16:03:15 -04:00
Andrew Beveridge ☄️andClaude Fable 5 0e5a7b60a6 fix(frontend): confirm backend unreachable via health probe before showing connectivity banner (#935)
## Summary

Slow-but-legitimate page loads (e.g. **first-time instrumental-analysis
/ lyrics-review loads**, which transcode audio stems server-side via
ffmpeg and can run 20–60s) were tripping the stall-based connectivity
banner, showing *"We're having trouble reaching our servers"* during a
perfectly normal load.

**Fix:** a stalled GET now only surfaces the banner once a cheap `GET
/api/health` probe confirms the backend is actually unreachable.

- When the oldest in-flight GET crosses the 10s stall threshold,
`lib/backend-status.ts` fires the probe registered by `lib/api.ts`
(`configureHealthProbe`).
- Probe answers OK (or no verdict yet) → backend is reachable, the read
is just a slow endpoint → **no banner**.
- Probe fails or times out (4s, `Promise.race`d so a hung origin can't
wedge it — during a Cloud Run recycle the origin *hangs* rather than
erroring) → outage confirmed → banner appears (~4s later than before).
- Probe re-fires every 10s while a stall persists, so recovery clears
the banner even if the original read is still hung.
- Dev-override hook and pure stall-based behavior (when no probe is
configured) are unchanged.

Also bumps version to 0.198.3 and adds an addendum to the 2026-08-22
design doc.

## Testing

- Reworked `__tests__/api-fetch.test.ts` stall test for the new
confirm-before-banner flow + new test: slow GET with healthy
`/api/health` never shows the banner.
- New `__tests__/backend-status.test.ts` suite: probe-OK suppression,
probe-fail escalation, stale-verdict re-probe + recovery clearing,
no-verdict hold-back.
- Full `make test` green: 91 suites / 1151 frontend tests + backend
suites.

@coderabbitai ignore
(Local CodeRabbit review completed on this branch — no findings.)

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 10:43:42 -04:00
Andrew Beveridge ☄️andClaude Fable 5 41a5ba5dd4 fix(review): poll for vocals waveform while audio separation is in progress (#934)
## Summary

Fixes the blank vocals waveform / console error `Failed to fetch vocals
audio: 404` seen on the lyrics review screen (reported on job
`d508adb6`).

**Root cause:** audio separation is intentionally decoupled from the
lyrics-review critical path — a job reaches `awaiting_review` as soon as
lyrics/screens are done, while stems keep uploading in the background.
On job `d508adb6` the user opened review at 06:51:21 but `vocals_clean`
wasn't uploaded until 06:53:40. The `/api/review/{job_id}/audio/vocals`
endpoint correctly found no vocal stem and returned a 404, which the
frontend treated as terminal — the edit-timeline waveform then stayed
blank for the whole session even though the stem arrived two minutes
later.

## Changes

- **Backend** (`review.py`): when no vocal stem exists yet **and**
`state_data.audio_complete` is false (separation still running), return
`202 Accepted` with `Retry-After: 15` instead of 404. A missing stem
with `audio_complete=true` (e.g. existing-instrumental jobs that skip
separation entirely) still 404s, so clients don't poll forever for a
stem that will never exist.
- **Frontend** (`VocalsAudioDataLoader`, `audio-data.ts`): a 202 now
throws a typed `AudioNotReadyError`; the loader retries every 15s
(capped at 10 minutes) and renders the waveform once the stem arrives.
Terminal errors (404/5xx) still fail once without polling, and polling
stops on unmount.

## Testing

- Backend: new tests for 202-while-separating and
404-when-separation-skipped; existing vocals-endpoint tests updated with
explicit `state_data` (91 passed across related review/transcoding test
files).
- Frontend: new `VocalsAudioDataLoader.test.tsx` covering success,
retry-then-load, terminal-error no-retry, and unmount cleanup. Full jest
suite: 1146 passed.
- Verified against prod: reproduced the exact 404 from Cloud Run logs
(trace-level), confirmed the stem-upload race timeline, and confirmed
the endpoint serves the proxied OGG once stems exist.

@coderabbitai ignore

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-23 07:24:40 +00:00
Andrew Beveridge ☄️ 723207070a fix(review): proxy vocals audio through the API (fixes waveform CORS) (#933)
Proxy vocals audio bytes through the API instead of 302-redirecting to GCS, fixing the waveform CORS failure (cross-origin redirect made the browser send Origin: null, which the bucket CORS rejects). Backend-only; input audio keeps the redirect.
2026-08-23 02:20:32 -04:00
Andrew Beveridge ☄️andClaude Fable 5 e3cbf0edbb perf(admin): dashboard stats overview 18s → ~1s (v0.197.2) (#931)
## Summary

The admin dashboard took ~26s to load. Root cause analysis (from the
network trace + prod measurements):

1. **`GET /api/admin/stats/overview?exclude_test=true` streamed every
user and job document in full** to filter test data in Python — ~110 MB
across 658 jobs (job docs carry `state_data`/timeline payloads).
Measured 15.0s for the jobs stream alone; ~18s warm for the endpoint.
2. **The sync streaming ran inside an async route**, blocking the event
loop — so `/me`, `/config`, and the payments summary (each 0.2s warm)
all stalled behind it on the same instance. That's why *every* request
in the dashboard trace showed ~26s.

## Fix

- Firestore `.select()` field masks on all three streams — jobs only
need `user_email`/`created_at`/`status` (15.0s → 1.1s measured); users
only `email`/`last_login_at`/`credit_transactions`
- The two independent streams (users, jobs) now run concurrently via a
2-worker `ThreadPoolExecutor`
- The whole computation runs in `asyncio.to_thread()` so it can never
stall other requests on the instance (same sync-over-async trap as the
Feb 2026 audio-search fix)

Benchmarked against production Firestore: **18s → 1.2–1.5s** (from a
laptop; in-region Cloud Run should be faster), with byte-identical
results (338 users / 608 jobs / 74 credits — matches the live
dashboard).

## Testing

- 4 new unit tests: counts + test-data filtering, empty collections,
endpoint wiring, and a regression guard asserting the field masks stay
in place
- Full backend suite: 3906 passed
- Local CodeRabbit review: no findings

@coderabbitai ignore

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-23 02:19:50 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 1e99f9e0d5 feat(admin): per-job/user locale badge + "emails sent to user" history (#930)
## Summary

Two admin-only features so support/intervention work can (a) know what
language/country a user is using the product in, and (b) see the exact
emails ever sent to a user, rendered as they appeared in the inbox with
full delivery metadata.

### A — Language / country visibility (admin-only)
- New `get_full_locale_from_request()` captures the real UI language
(any of 33, not the narrowed en/es/de email locale) on **every**
job-creation path (URL, upload, audio-search, bulk, made-for-you via
Stripe metadata). Stored as `Job.locale` (+ added to the dashboard
summary projection) and `User.ui_locale` (kept separate from
`User.locale`).
- `LocaleBadge` (flag + language) shown in the admin jobs table, admin
job detail (+ country via the existing `IpInfo` on the creation IP), the
user-detail header, and the customer `JobCard` **gated to admins only**
— regular users never see it.
- Country is derived from IP (existing `ip_geolocation_service`); no new
capture.

### B — "Emails sent to this user"
- Every send routes through one `EmailService._log_and_send` chokepoint
that persists each email to a new Firestore `email_log` collection
(rendered HTML + Postmark MessageID), best-effort so it can never break
or delay a send. Single-use auth/capability tokens (magic-link, review,
referral) are **redacted** before persistence.
- `PostmarkAdminService` merges the Postmark Messages API (last ~45
days: exact HTML + opens/clicks/bounce/delivery status, paginated) with
the Firestore log (permanent), de-duplicated by message id.
- Endpoints `GET /api/admin/users/{email}/emails` and `GET
/api/admin/emails/{id}`; the user-detail "Emails Sent" card opens a
modal rendering the email in a sandboxed `<iframe srcDoc>` with a
metadata side panel.
- New Firestore composite index (`email_log` recipient + created_at)
added to Pulumi.

## Testing
- **41 new backend tests** (locale capture incl. q=0, email logging +
token redaction, PostmarkAdminService incl. pagination + 45-day
fallback, job-locale persistence, admin endpoints) — all pass.
- **10 new frontend tests** (LocaleBadge, UserEmailsCard list +
sandboxed-iframe modal) — all pass.
- Regression sweep on related existing suites: green. Preview-email flow
smoke-tested through the new chokepoint.

## Notes
- `pulumi up` for the new `email_log` index should be applied before
merge (done locally).
- `Job.locale` populates for new jobs going forward; historical jobs
fall back to the submitting user's locale where shown.

Local CodeRabbit review completed and addressed (token redaction,
pagination, row a11y, locale-overwrite guard, q=0 handling).

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

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-23 01:51:42 -04:00
Andrew Beveridge ☄️ d445861aea fix(infra): allow GET/HEAD CORS on storage bucket for vocals waveform (#932)
Allow GET/HEAD CORS on the storage bucket so the vocals waveform's cross-origin fetch()+decodeAudioData can read the stem. Applied locally via pulumi up (update 830); CI re-applies as no-op.
2026-08-23 01:45:42 -04:00
Andrew Beveridge ☄️ 7729d30937 build: build frontend into the wheel in CI instead of committing out/ to git (supersedes #892) (#926)
Build the Next.js frontend into the wheel in CI instead of committing the generated out/ to git (fixes #876; supersedes #892). Validated: package-build-test green (npm ci → make build-frontend → poetry build → verify_wheel_frontend guard → install). Thanks @netux for surfacing it.
2026-08-23 01:19:11 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 6fa4400d3d feat(dr): back up all GitHub repos to S3 (survive a GitHub ban) (#929)
## Summary

Extends the nightly DR backup Cloud Function (`backup-to-aws`) to bundle
**every git repo under `github.com/nomadkaraoke` and
`github.com/beveradb`** into a per-repo `git bundle` on S3, so code +
full history survive a complete loss of GitHub access (e.g. an automated
copyright-strike account ban). Each bundle is directly cloneable —
restore is `git clone --mirror <bundle>` → `git push --mirror
<new-remote>`.

## Changes

- **`git_repos_export.py`** (new): enumerate repos via GitHub
`/user/repos` (includes private), mirror-clone + `git bundle create
--all`, upload to `git-repos/{owner}/{repo}.bundle` in staging, plus a
`manifest.json` inventory. Forks excluded, oversized/empty repos
skipped, per-repo errors non-fatal, org backed up **before** the
personal account for deadline resilience. PAT is read from Secret
Manager at **runtime** (not a deploy-time secret env var) so the
function deploys before the secret has a value and skips gracefully if
absent.
- **`main.py`**: new nightly Step 4b (between secrets export and S3
upload).
- **`infrastructure/modules/backup.py`**: bump function to 4Gi/2CPU
(mirror-clone uses in-memory `/tmp`); add `GIT_BACKUP_OWNERS` env.
- **`infrastructure/modules/secrets.py`**: new `github-backup-token`
secret (value added manually).
- **`.github/workflows/dr-backup-freshness.yml`**: monitor `git-repos/`
at 36h, counting only `.bundle` objects.
- **`docs/DISASTER-RECOVERY.md`**: new "Scenario 3: Loss of GitHub
access" + restore steps + token setup.

## Security

- The GitHub PAT is injected via a `GIT_CONFIG_*` `Authorization` header
(like `actions/checkout`), never in the clone URL/argv — so it can't
leak via `ps`, `TimeoutExpired`, or captured stderr. Token is also
redacted from any error text persisted into `manifest.json`.

## Testing

- 14 new unit tests for the module
(enumerate/filter/bundle/skip/error/security paths); full
`backup_to_aws` suite: **27 passing**.
- CodeRabbit local review (cycle 1) completed; all 4 findings (1
critical PAT leak, 2 major, 1 minor) addressed. Cycle-2 verification was
rate-limited (free-tier), so **left for the GitHub bot to review the
final diff**.

## Deploy notes

- **Pulumi already applied locally** (`github-backup-token` secret
created + function on 4Gi/2CPU) — CI re-run is a no-op.
- After merge, run `infrastructure/functions/backup_to_aws/deploy.sh` to
ship the new function source, then set the PAT:
`printf %s '<PAT>' | gcloud secrets versions add github-backup-token
--data-file=- --project=nomadkaraoke`
- Requires a classic GitHub PAT (owner: beveradb, member of nomadkaraoke
org) with `repo` + `read:org`.

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

---
@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-23 00:44:52 -04:00
Andrew Beveridge ☄️ d7482ee85a feat(review): vocals waveform in timeline editor — finished + fixed (takes over #895) (#927)
Vocals waveform in the timeline editor (finishes @netux's #895): backend stem-selection fix (vocals_clean), downsampled peak-envelope perf, edit-modal space reclaim, full i18n (33 locales), CodeRabbit fixes, and ReviewServer.vocals_filepath made optional. Reviewed + visually QA'd on a real job.
2026-08-23 00:23:18 -04:00
Andrew Beveridge ☄️andClaude Fable 5 0497168dda feat(admin): UX/UI overhaul — overflow fixes, mobile responsiveness, clickable dashboard (v0.197.0) (#928)
## Summary

UX/UI overhaul of the admin pages, focused on the most-used surfaces
(dashboard, jobs list/detail, users list/detail), fixing reported
overflow bugs and making everything usable on mobile.

### Job detail page (`/admin/jobs?id=...`)
- **Status timeline**: long timelines (retries/edits) collapse to the
last 6 stages behind a `+N earlier (M failed)` expander chip, with a
Collapse chip when expanded; resets when switching jobs
- **Source field overflow fixed**: info-grid cells get `min-w-0` so long
source strings truncate instead of bleeding across
Created/Progress/Total Time
- **Audio Source Details modal**: rebuilt with stacked wrap-safe rows
(no clipped values), scrollable, plus a prominent "Open in
YouTube/Spotify" link built from provider + source ID
- **Configuration fields**: click-to-edit values with always-visible
pencil (was hover-only); empty values show "— click to set"
- **Bug fix**: "Trigger Now" in the reset-result dialog called a deleted
`handleTriggerWorker` (runtime crash); reimplemented via
`adminApi.triggerWorker`
- 404 job load no longer shows a redundant error toast (also fixes a
pre-existing flaky e2e)
- Skips loading the 100-job list while viewing a single job
- `generating_screens` status gets a label + filter option

### Jobs list
- Search box jumps straight to the detail page when given a job ID
- Status filter synced to URL (`?status=failed` is shareable/linkable)
- Compact created dates; User/Progress/Created columns hidden on small
screens

### Dashboard
- Stat cards link to their pages; Job Status Breakdown rows link to the
pre-filtered jobs list

### Users list/detail + layout
- Responsive columns, truncation-safe email cells, mobile-stacking
detail header, break-all for long emails/fingerprints
- Breadcrumb shows "User Detail" instead of raw "detail" segment; header
no longer overflows on phones

## Testing
- 4 new e2e tests (timeline collapse/expand, short-timeline no-collapse,
provider link from source ID, job-ID search jump); full admin-job-detail
spec 28/28 passing
- Full regression e2e suite: 171 passed; frontend unit tests: 1132
passed
- Visually verified at 1280px and 390px widths with mocked-API renders
(worst-case long timeline + long source strings)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 23:54:59 -04:00
Martín Rodríguez 21c58289b6 fix(frontend): correct timeline editor collision checks (#893)
Reviewed, verified locally against fixture review data, and merged by maintainer. Thanks @netux!
2026-08-22 22:25:59 -04:00
Martín Rodríguez a3ab2a4048 fix(frontend): make only the word list scrollable in the lyrics review edit modal (#896)
Reviewed, verified locally against fixture review data, and merged by maintainer. Thanks @netux!
2026-08-22 22:25:56 -04:00
Martín Rodríguez 9ac53e32b6 feat(frontend): read API base url from query parameters in localhost frontend (#894)
Reviewed, verified locally against fixture review data, and merged by maintainer. Thanks @netux!
2026-08-22 22:25:53 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 d98e90c1d7 fix(audio-download): wire POSTMARK_SERVER_TOKEN into audio-download-job + resilient email construct (#925)
## Summary

Fixes production job `a453d1d5` (Regina Spektor – Laughing With), which
failed with:

> Audio download failed: POSTMARK_SERVER_TOKEN is not set in production.
Refusing to silently drop emails via the console provider — set the
Postmark token secret.

### Root cause
The audio download worker runs as its **own Cloud Run Job**
(`audio-download-job`) — a thin orchestrator that calls the flacfetch VM
over the VPC and waits, then triggers separation + lyrics. Each Cloud
Run Job has an **independent env block**, and `audio-download-job`'s
block omitted `POSTMARK_SERVER_TOKEN` (it was wired only into
`karaoke-backend` and `video-encoding-job`).

`audio_download_worker` → `reconcile_and_maybe_pause()` **eagerly**
builds `get_email_service()` on every no-edit download, even though
email is only sent in the rare over‑60‑min cancel branch.
`EmailService()` deliberately raises in production when the token is
absent (2026‑06‑09 fallback‑audit "fail loudly" guard), so the whole
download failed.

Blast radius was small (1 job in Firestore) because jobs that stop at
`AWAITING_AUDIO_EDIT` never reach reconcile — but it recurs for every
automated/no‑edit download.

## Changes
- **infra** (`infrastructure/modules/cloud_run.py`): add
`POSTMARK_SERVER_TOKEN` secret env to `audio-download-job` so the
over‑limit cancellation email works. *(Needs `pulumi up` — applied
locally before merge.)*
- **`backend/services/duration_reconciliation.py`**: wrap
`get_email_service()` in try/except → log and proceed with
`email_service=None`. A construct‑time email failure can no longer crash
an otherwise‑successful paid download (`reconcile_duration` already
tolerates `None`; over‑limit still cancels + refunds).
- **tests**: `survives-email-service-failure` (proceeds) and
`over-limit-still-cancels-without-email`.
- **`backend/config.py`**: corrected a stale comment claiming
`lyrics-transcription-job` needs `ANTHROPIC_API_KEY` — the LLM work
actually runs on the API service (`auto_correct_worker`), not the lyrics
job.
- version bump 0.196.9 → 0.196.10.

## Env audit
Audited **all** Cloud Run Jobs' env vs. their worker code paths. The
only production hard‑fail pattern is the `EmailService` guard; the
POSTMARK gap was **unique to `audio-download-job`**. `bulk-search-job`
and `lyrics-transcription-job` never construct `EmailService` on their
path; `video-encoding-job` already has the token and is doubly defended.
No other env vars need adding.

## Testing
- `test_duration_reconciliation.py` 14/14,
`test_audio_download_worker.py` 37/37, `test_email_service.py` included
— 94 passed.
- CodeRabbit local review: no findings.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-22 21:55:50 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 0bba4ff041 fix(made-for-you): isolate order emails from audio-acquisition failures (#924)
## Problem

Job `17dc6f48` (a Made-For-You order) failed on a YouTube "confirm
you're not a bot" download error, and the admin **never received the
"New Made-For-You Order Received!" email** — leaving no signal that a
paid order needed attention, and no certainty the customer got their
confirmation. The Discord error monitor also fired `'EmailService'
object has no attribute 'send_email'`.

Two root causes in `_handle_made_for_you_order`
(`backend/api/routes/users.py`):

1. **Emails were sent *after* audio acquisition.** Both the customer
confirmation and the admin notification ran only after the fallible
YouTube download / audio search. When acquisition raised, execution
jumped to the error handler, **skipping both emails.**
2. **The error fallback itself crashed.** It called
`email_service.send_email(...)`, but that method existed only on the
*provider* (`self.provider.send_email`), never on `EmailService` — so
even the failure alert was lost.

## Changes

- **Send the customer order-confirmation email up-front**, right after
job creation and *before* audio acquisition. The order is paid/confirmed
regardless of the download/search outcome. Resilient: a delivery failure
is logged, not fatal.
- **Wrap the admin notification** so an email hiccup on a successful
order can't fake a `[FAILED]` alert.
- **Route the outer failure handler through
`_send_mfy_failure_alert()`** — never raises, HTML-escapes user input,
tolerates `job_id=None`. Success → normal admin notification;
audio-acquisition failure → `[FAILED]` admin alert while the customer
stays confirmed.
- **Add a thin `EmailService.send_email()` passthrough** to the provider
(fixes the `AttributeError`).
- **Handle `False` provider results** (providers signal rejection by
returning `False`, not raising): log accurately instead of always
"Sent"; a rejected *customer* confirmation is escalated to the admin so
it can be resent manually.
- **Retry dropped paid orders:** if job creation fails (no `job_id`,
session never marked processed), re-raise after alerting so the Stripe
webhook returns non-2xx and Stripe retries. Post-creation failures keep
`job_id` set and return 200 to avoid duplicate jobs on retry.
- Idempotency preserved: the Stripe session is marked processed before
the confirmation send, so a webhook retry can't double-send.

## Out of scope

The YouTube "confirm you're not a bot" download error itself is a
separate flacfetch/yt-dlp cookies issue (credential keeper) — this PR
only makes the order emails resilient to it.

## Testing

- `make`-level backend suites for made-for-you, tenant/email,
admin-feedback, internal-webhook all green (138 passed locally).
- New/updated regression tests:
  - customer confirmation survives a YouTube download failure
- confirmation-email failure doesn't abort order processing (and is
escalated)
  - provider-returns-`False` confirmation is escalated
  - job-creation failure re-raises (Stripe retry) after alerting
  - `EmailService.send_email` passthrough delegates to the provider
- Local CodeRabbit review: 2 findings addressed, re-run clean (no new
findings).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-22 19:23:48 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 c76d58394d fix(fallbacks): T7 — prod fail-fast on missing config + tenant gate safe-by-default (#808)
## Summary
Theme 7 of the silent-fallback audit
(`docs/archive/2026-06-09-fallback-audit-plan.md`, in #805). A single
unset/rotated env var used to silently produce wrong behaviour in prod
with only a warning. Now production fails fast / is safe-by-default.
Verified against Pulumi infra: prod sets `ENVIRONMENT=production`,
`CLOUD_RUN_SERVICE_URL`, `GCS_BUCKET_NAME`, `GOOGLE_CLOUD_PROJECT`, and
Postmark (secret); Cloud Run also auto-sets `K_SERVICE`.

## Changes
- **`config.is_production()` + `validate_production_config()`** (called
from `main.py` lifespan): production refuses to boot if
`GOOGLE_CLOUD_PROJECT`, `GCS_BUCKET_NAME`, or `CLOUD_RUN_SERVICE_URL`
are unset — instead of silently using a dev default (wrong project for
secret lookups / wrong bucket / localhost worker URL). This **subsumes
7.3** (worker_service localhost fallback). `is_production()` treats
Cloud Run's auto-set `K_SERVICE` as production, so it's robust even if
`ENVIRONMENT` were unset.
- **Tenant middleware (7.4, security)**: the `?tenant=` override (a
spoofing vector) is now disabled whenever `K_SERVICE` is present, not
only when `ENVIRONMENT=production` — production-safe by default.
- **dropbox_service (7.1)**: `GOOGLE_CLOUD_PROJECT` default was the
**wrong literal** `"karaoke-gen"` (real project is `nomadkaraoke`);
replaced with an empty default (prod requires it via the startup gate).
- **email_service (7.5)**: a missing `POSTMARK_SERVER_TOKEN` in
production used to silently use the console provider (sends "succeed"
while emails vanish). Now raises in production; console fallback remains
for dev/test.

## Deferred (flagged)
**7.2** `GCS_TEMP_BUCKET` / `GCS_OUTPUT_BUCKET` — these are **not** set
via env in infra, so their config defaults are load-bearing. Requiring
or changing them risks prod, so deferred pending confirmation of whether
those buckets are actually used.

## Testing
- [x] New `backend/tests/test_fallback_prod_config.py` (is_production,
validate gate raise/pass/no-op, email prod-raise vs dev-console, tenant
K_SERVICE)
- [x] 111 related tests pass (email, tenant, config) — no regressions,
no cross-test pollution from the tenant module reload

## Review
- [x] CodeRabbit CLI review completed locally (0 findings)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-22 19:01:23 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 51d9233cb8 fix(fallbacks): T4 — fail loud on missing configured render asset (font dir, background) (#807)
## Summary
Theme 4 of the silent-fallback audit
(`docs/archive/2026-06-09-fallback-audit-plan.md`, in #805). A
*configured* branded render asset that is missing must not silently
substitute a different font/background on a paid deliverable. Mirrors
the existing background-image check in
`output/video.VideoGenerator.__init__` (which already raises).

## Changes
- **`output/video._build_ass_filter`** (4.1): when the theme's karaoke
`font_path` is set but the file is missing, the final MP4 used to
silently drop `:fontsdir` → libass resolves a system fallback font for
the whole song. Now raises `FileNotFoundError`. *(Unset `font_path` is
still fine — no fontsdir, no raise.)*
- **`video_generator._create_background`** (4.3): a set-but-missing
title/end-screen `background_image` used to silently fall back to a flat
color. Now raises `FileNotFoundError`. *(No background configured is
still fine — flat color.)*

## Scope (per your decision)
Only these two clean "configured-but-missing → raise" cases are changed.
The font **substitution** items (4.2 title/end font, 4.4 CDG→arial, 4.8
measurement font) and duet/colour items (4.5–4.7) are **left as-is** —
font substitution overlaps with legitimate CJK font fallback
(`test_video_generator_cjk_font.py`) and warrants per-item treatment.

## Testing
- [x] New `tests/unit/test_fallback_render_assets.py` (raise +
legitimate-unset cases)
- [x] 105 render/video tests pass

## Review
- [x] CodeRabbit CLI review completed locally (0 findings)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-22 18:50:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 6c374842f9 infra: Firestore composite index for jobs by request_metadata.client_id (#923)
## Problem

`karaoke-backend` started logging `400 The query requires an index` for
`GET /api/jobs?client_id=` (both "Error listing jobs" and "Error listing
jobs summary" patterns — one prod error alert). The query filters
`request_metadata.client_id` + `tenant_id` and orders by `created_at`,
with no composite index.

This surfaced because the **fiverr-agent** now tags the jobs it creates
with `client_id="fiverr:{order_id}"` and calls that endpoint for
idempotency (finding an existing job before creating one).

## Fix

Adds `firestore-index-jobs-client-id` to the IaC:
- `request_metadata.client_id` ASC
- `tenant_id` ASC
- `created_at` DESC

(matches the index Firestore's error link requested).

## Applied

Already applied to prod via `pulumi up` (`+1 created, 294 unchanged` —
clean preview, no other drift). Verified: `GET
/api/jobs?client_id=fiverr:…` now returns **200** (was 500/400). This PR
codifies the change to prevent IaC drift.

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

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Improved database query support for filtering jobs by client and
tenant while sorting by newest first.
  * Helps ensure relevant job results load reliably and efficiently.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-22 18:49:13 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 5fff6d67b0 fix(fallbacks): T1 — flacfetch sole downloader, no silent YouTube downgrade (#806)
## Summary
Theme 1 of the silent-fallback audit
(`docs/archive/2026-06-09-fallback-audit-plan.md`, added in #805).
flacfetch is the sole/lossless downloader — a configured-remote failure
must not silently downgrade to a local YouTube-only rip. This is the
exact class as the 2026-06-08 Facebook-URL incident.

## Changes
- **`audio_search_service._search_remote`**: a `FlacfetchServiceError`
from the remote service was swallowed and silently re-run against the
local YouTube-only fetcher. Now fails loudly (`AudioSearchError`) and
clears cached state. **No silent downgrade.**
- **`create_audio_fetcher`** (local CLI factory): a half-configured
remote (exactly one of `FLACFETCH_API_URL`/`FLACFETCH_API_KEY`) used to
warn and silently use local mode, masking a deploy/secret typo. Now
raises `AudioFetcherError`.

## Scope / deferred (needs your call)
Findings **1.2** (tracker configured-but-unusable → silently
YouTube-only) and **1.4** (`select_best` → first result on ranking
failure) live in the **shared local `FlacFetcher`** and have dedicated
tests asserting graceful local-CLI behaviour
(`test_select_best_handles_exception`). Your "fail loud" directive was
framed around the *cloud* silent-downgrade; hard-failing the local CLI
when a user simply has no usable tracker would change intentional local
behaviour. **Deferred for a per-item decision** rather than steamrolled
— see the audit plan doc.

## Testing
- [x] `backend/tests/test_audio_search.py` +
`tests/unit/test_audio_fetcher.py` pass (209)
- Added: remote-error-does-not-fall-back-to-local; updated the two
half-config factory tests to expect a raise.

## Review
- [x] CodeRabbit CLI review completed locally (1 major finding: clear
cached results on failure — fixed)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-22 18:35:12 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 27a5d8fdff fix(fallbacks): T8 — fail loud cleanups (docstrings, download errors, admin-token signal) (#805)
## Summary
First (low-risk) batch of the silent-fallback audit — see
`docs/archive/2026-06-09-fallback-audit-plan.md` for the full catalogue
and Andrew's per-theme decisions. This PR is **Theme 8**: fix
lying/stale docstrings, surface specific download-failure reasons, and
make an empty admin-token config a loud signal.

## Changes
- **Fail-open docstring lie → fail-closed**
(`credit_evaluation_service.py`, `config.py`): the AI credit evaluator
is fail-CLOSED (`pending_review`, no auto-grant) but its docstrings
claimed fail-open. Corrected so a future maintainer can't "fix" the code
into a free-credit-abuse hole.
- **Stale yt-dlp docstrings** (`youtube_download_service.py`,
`lyrics_worker.py`): removed text still describing the deleted
local-yt-dlp fallback. flacfetch is the sole downloader; the service
raises when unconfigured.
- **Specific download errors** (`audio_worker.py`, `lyrics_worker.py`):
`download_audio()` now raises a specific `DownloadError` per failure
mode instead of returning `None` → generic "Failed to download audio
file". Workers map it to a clear `Audio download failed: <reason>`
job-failure message.
- **Loud admin-token signal** (`auth_service.py`): empty `ADMIN_TOKENS`
now logs at ERROR (error-monitor → Discord) instead of a quiet warning.
It fails closed (403 everywhere) and looked like an auth bug rather than
a config error.
- Adds the audit plan doc + a `LESSONS-LEARNED` principle ("don't invent
silent fallbacks — ask or fail loud").

## Testing
- [x] Affected backend tests pass locally (85 passed): `test_workers`,
`test_workers_extended`, `test_audio_worker_download`,
`test_auth_admin_tokens`
- [x] Import sanity check (no circular import from new `DownloadError`
imports)
- Updated `test_download_audio_url_without_gcs_path_refuses` to expect
`DownloadError`; added no-source raise tests for both workers +
admin-token tests.

## Review
- [x] CodeRabbit CLI review completed locally (1 minor doc finding,
fixed)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-22 18:19:30 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 3d56dd4108 fix: connectivity banner only on real read stall (not slowness) (#922)
## Why

Follow-up to #921. In prod the connectivity banner was **too
sensitive**:
1. It fired during a normal lyrics-review load — the 2.5s "slow request"
hint tripped on any request taking >2.5s, even successful ones.
2. The "Preview Video" modal showed **"The server is temporarily
unavailable"** — the long-running preview-generation POST (video encode,
often >45s) hit apiFetch's blanket 45s hard-timeout and failed, even
though the backend was fine.

## What

- **`backend-status.ts` — status now derives purely from a real STALL.**
It tracks how long the *oldest in-flight tracked read* has been
outstanding: `reconnecting` at 10s, `unavailable` at 20s, back to
`online` the instant it settles. A read that completes — even a
normal-slow 3–5s one — surfaces **nothing**.
- **`apiFetch` — GET-only tracking + GET-only hard-timeout.**
- Only GETs feed the banner (a page waits on reads during a recycle;
long POSTs are legitimately slow).
- The 45s hard-timeout backstop applies to **GETs only** —
preview/generate/search POSTs run **untimed** to completion, fixing the
false "unavailable" error.
- New `opts.trackConnectivity: false` lets a known-slow read opt out;
`opts.timeoutMs` still time-boxes any call.

Retry semantics unchanged (GET-only, never replays a mutation).

## Testing
- Rewrote store + apiFetch unit tests for the stall model: POST
untracked, POST not hard-timed-out (signal not aborted after 60s), a
stalled GET → reconnecting→unavailable→clear, fast failures stay
`online`.
- Full suite green: **1132 passing**.
- Banner rendering re-verified locally.
- Local CodeRabbit review: **no findings**.

No infra changes in this PR.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-22 17:57:14 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 c65a920a59 feat: graceful backend-outage handling + soften uptime alert noise (#921)
## Why

A "Karaoke Backend - Service Unavailable" uptime alert fired at 06:06
UTC on 2026-08-22 and auto-recovered ~1m41s later. Investigation showed
it was a **routine Cloud Run instance recycle** on `--min-instances 1`:
the single warm instance (up ~9.6h) was reaped at 06:01:53, leaving a
~80s gap with no origin, so Cloudflare failed the health check from all
6 checker regions at once. No crash/OOM — a self-healing platform
recycle. (Full write-up:
`docs/archive/2026-08-22-health-check-alert-noise-and-graceful-degradation.md`.)

We're deliberately keeping `--min-instances 1` for cost, so this
addresses the two things we *can* control: alert noise, and how the UI
behaves during such a blip.

## What

**1. Soften the uptime alert** (`infrastructure/modules/monitoring.py`)
- Condition `duration` 60s → **300s**: a sub-5-min self-healing recycle
no longer pages; a sustained hard-down still fires (~5–6 min). Incident
documented in-code.

**2. Graceful frontend degradation**
- `lib/api.ts` — new **`apiFetch`** wrapping every backend call:
non-aborting 2.5s "reconnecting" hint, hard-timeout backstop, **safe
retries (GET only — never replays a mutation)**, transient-status
detection (502/503/504 + Cloudflare 52x), GCS/third-party passthrough.
Throws a typed `BackendUnavailableError`.
- `lib/backend-status.ts` — framework-agnostic connectivity store
(`online | reconnecting | unavailable`); escalates to `unavailable` on a
10s clock, clears to `online` on any success.
- `components/backend-status-banner.tsx` — one reassuring app-wide
banner (mounted under `[locale]`, covers landing + logged-in dashboard +
review screens), **i18n across all 33 locales**. `/admin/*`
intentionally excluded. Copy reassures that in-flight renders are
unaffected.

During a real recycle the dashboard's own polling drives the banner and
it self-heals when the backend returns — no refresh needed.

## Testing
- New unit tests: `__tests__/backend-status.test.ts`,
`__tests__/api-fetch.test.ts` (GET retry→10s escalation, transient 503,
transparent recovery, non-GET never retried, `Request`-input
method/signal, GCS passthrough, caller-abort passthrough). Updated
`completeJobUpload` assertion.
- Full suite green: **1130 passing**.
- Banner verified visually locally (reconnecting + unavailable, en +
es).
- Local CodeRabbit review: 5 findings (1 major, 4 minor) all addressed;
cycle 2 clean.

## Deploy notes
- Infra change: `pulumi up` run locally before merge to avoid IaC drift
(Pulumi CI re-runs as no-op).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-22 17:11:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 df93eb9f82 feat(status): opaque System Status modal + live encoding-worker instance type (#920)
## Summary

Two fixes to the **System Status** modal (opened from the version
footer):

### 1. Modal was transparent
The modal set `backgroundColor: var(--card-bg)` — but `--card-bg` is
**defined nowhere** in the codebase (the real vars are `--card` /
`--card-border`). An undefined CSS variable makes the property invalid,
so the modal fell back to `transparent` and the job list showed through
it (see the reported screenshot).

Fixed by using defined opaque surfaces:
- Dialog shell → `var(--bg)` (`#0f0f0f` dark / `#f8fafc` light)
- Service cards → `var(--card)` (`#1a1a1a` dark / `#ffffff` light)

This was the only usage of the phantom `var(--card-bg)` anywhere in the
frontend.

### 2. Show the currently-live encoding worker
Given the recent c4d stockout / multi-instance-family fallback work,
admins couldn't see **which** worker was actually serving or its
instance type. The live worker is the `active_override` VM when a
capacity fallback has routed off the primary, else the c4d blue-green
primary.

- **Backend** (`/health/system-status`): the admin-only encoder
`admin_details` now carries `active_vm`, `active_zone`,
`active_machine_type`, and `on_fallback`. The instance type is derived
via the existing `infer_machine_type` helper (primary →
`c4d-highcpu-32`; fallbacks decoded from the VM-name family token, e.g.
`…-fallback-n2c` → `n2-highcpu-32`).
- **Frontend**: a new `LiveWorkerSection` on the Encoder card shows the
instance type prominently, the serving `VM · zone`, and an amber
**"Fallback"** badge + notice when running off the primary due to a
stockout. The existing Blue-Green expander is unchanged.

## Changes
- `backend/api/routes/health.py` — compute live-worker fields (admin
only)
- `frontend/components/system-status-modal.tsx` — opaque vars +
`LiveWorkerSection`
- `frontend/lib/api.ts` — `ServiceStatus.admin_details` new fields
- `frontend/messages/*` — 3 new `status` keys translated to all 32
locales

## Testing
- `make test` — full suite green (backend 1741+3878+103, frontend 1115
tests / 86 suites)
- Added a capacity-fallback path test to
`test_system_status_endpoint.py`
- Added `frontend/__tests__/system-status-modal.test.tsx` (primary,
fallback badge/notice, non-admin omission)
- CodeRabbit reviewed locally; addressed 3 minor translation-grammar
findings (ja/sk/ro)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-20 22:47:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 3e666c28bb fix(e2e,submit): tolerate Stripe layout A/B + retry tenant upload-complete (#919)
## Problem

Two independent daily-E2E failures fired alerts:

- **E2E Daily #138/#139 (Credit Purchase)** — timed out 30s at
`stripe-checkout.ts` waiting for a top-frame `Pay` button.
- **Tenant E2E #80 (`vocalstar`; `singa` passed)** — timed out 120s
waiting for "Track Submitted".

## Root causes (both investigated to ground truth)

**1. Stripe Checkout layout flipped again (test-only).**
Stripe has now oscillated its hosted Checkout layout **three times**,
strongly implying A/B testing / staged rollout:
- Apr (#715): multi-method accordion of **radios**, card fields in
iframes, Pay in top frame
- Aug 17 (#916): **single-method**, direct textbox inputs, no chooser
- Now: multi-method **Payment Element** where the chooser is **buttons**
and the whole element — chooser, card fields **and the Pay button** — is
inside a **nested iframe**

`page.getByRole(...)` only searches the top frame, so the Pay button
(now nested) was invisible → 30s timeout. The real checkout rendered
correctly throughout (right product, referral 70% off, $3.00 total).

**2. Tenant submit: network blip on the final completion call (real,
transient).**
For `vocalstar` the submit **created the job + deducted a credit**, both
files reached GCS (verified in the bucket), but the final
`completeJobUpload()` `fetch` failed at the network layer — it never
reached the server (zero backend logs) — and threw a non-`ApiError`,
surfacing the generic "Something went wrong" while stranding the
paid-for job at "Setting up". `singa` passed the identical flow seconds
earlier.

## Changes (v0.196.2)

- **`frontend/e2e/helpers/stripe-checkout.ts`** — rewritten to be
**layout-agnostic**: searches **every frame** (top + nested iframes) for
the Pay button, the Card chooser (radio **or** button), card fields
(direct **or** iframe), ZIP and save-info toggle. Prominent doc-comment
cataloguing the three observed variants with a "do not narrow to one
layout" warning.
- **`frontend/lib/api.ts`** — `completeJobUpload` now retries
**network-level** failures (3 attempts, backoff). HTTP errors are never
retried (deterministic). Self-heals the exact failure observed.
- **`frontend/components/job/TenantJobFlow.tsx`** — logs the real error;
shows a network-specific message (`submitNetworkError`, translated to
all 33 locales).
- Tests: 3 new `completeJobUpload` retry tests; tenant error-mapping
tests updated. All pass; tsc/eslint clean on changed files.

## Verification

- Dispatched `e2e-daily.yml` on this branch (test code from branch,
driving **production**):
- **Stage 1: Credit Purchase — ✅ success** (real ~$3 charge through the
new nested-iframe Stripe layout — directly exercises the helper fix)
  - Stage 2: Happy Path — validating (orthogonal to these changes)
- Run:
https://github.com/nomadkaraoke/karaoke-gen/actions/runs/32394417473
- Local CodeRabbit review completed; one legit finding fixed (Hebrew
register), one false positive skipped (`ApiError` is exported at
`api.ts:3982`; the new `toBeInstanceOf(ApiError)` test passes).

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-20 13:18:04 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 03464145b5 fix(monitoring): replace flaky instance-count-absence alert with /api/health uptime check (#918)
## Summary
- The **"Karaoke Backend - Service Unavailable"** alert fired a false
page at 2026-08-19 03:15 UTC. Root cause: it alerted on *absence* of the
`run.googleapis.com/container/instance_count` metric, which is a sampled
series that legitimately blinks out for a `min-instances=1`, low-traffic
service. Logs confirmed the same instance was serving the scheduled
recover-stuck-jobs / retry-render crons with HTTP 200 the whole time —
zero errors, no instance replacement.
- Replaces the metric-absence condition with a real **Cloud Monitoring
uptime check** against `https://api.nomadkaraoke.com/api/health`
(through the Cloudflare edge, the same path real users take; body must
contain `"healthy"`).
- Pages only when the check **fails from more than one checker
location**, so a single flaky checker can't page us but a genuine
hard-down fires in ~1–2 min.

## Changes
- `infrastructure/modules/monitoring.py`:
- New `UptimeCheckConfig` `backend-health-uptime-check` (HTTPS GET
`/api/health`, 60s period, content matcher `"healthy"`).
- `service-unavailable-alert` condition changed from
`condition_absent(instance_count)` → `condition_threshold` on
`monitoring.googleapis.com/uptime_check/check_passed`
(`REDUCE_COUNT_FALSE` grouped by host, fire when `>1` failing checker
location).
  - Updated the alert documentation accordingly.

## Deployment status
- **Already applied to the `prod` stack** via targeted `pulumi up` (`+1
created` uptime check, `~1 updated` policy). Verified live: uptime check
passing 100% from all checker locations (`fraction_true=1.0`,
`COUNT_FALSE=0`) — confirms Cloudflare does not block Google's checkers.
This PR reconciles `main` with the deployed state; CI's pulumi apply is
a no-op.

## Testing
- [x] `pulumi preview` / `pulumi up` on prod stack (targeted; unrelated
runner-manager drift left untouched)
- [x] Uptime check verified passing from all checker locations
post-deploy
- [x] Alert policy condition + docs verified on the deployed policy
- N/A `make test` — infra-only Pulumi change, not covered by app test
suites

## Review
- [x] Local CodeRabbit review completed (1 major finding: "count checker
locations, not regions" — addressed by making the condition name + docs
accurately say "checker location")
- [x] Final CodeRabbit pass: no new findings

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-19 10:45:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 cd4c88ca3e fix(visibility): make public→private atomic; fix redistribute crash (NOMAD-1537 gap) (#917)
## Summary

Investigated a `⚠️ GDrive Validation: missing NOMAD-1537` alert. Root
cause was **not** a brand-code allocation race — it was a
**public→private visibility change** on job `25d076e5` (`Alma Nocturna –
Mejor Cállate`) that:

1. deleted the public YouTube/Dropbox/GDrive outputs and recycled
`NOMAD-1537`, **then**
2. crashed the private redistribution on an illegal `complete →
packaging` state transition (`redistribute_video` drove the normal
orchestrator progress path on an already-`complete` job).

So the flow was **delete-first with no rollback**: public files gone,
private archive never created. The gap self-closed when an unrelated
public job (`Luvcat – Spider`) reused the recycled number. The customer
track was fine (GCS-backed downloads intact + correctly private), but
every public→private conversion was silently failing its private-side
archive, and each leaked a `NOMADNP` code.

## Changes

- **A — fix the crash:** `OrchestratorConfig.redistribute_mode`;
`_update_progress` updates progress only and skips status transitions
when redistributing a `complete` job. `redistribute_video` sets it.
- **B — distribute-then-delete:** `change_to_private` captures the
public refs, redistributes to the private destination first, and only on
success deletes the public outputs + recycles the public number. On
redistribution failure it reverts to public — nothing deleted (YouTube
deletion is irreversible, so it must be last).
- **C — no leaked codes:** a redistribution that fails after allocating
a `NOMADNP` code recycles it.
- **Hardening (from local CodeRabbit review):** `redistribute_video`
verifies the archive actually materialized (brand code + Dropbox upload)
before reporting success — the orchestrator swallows those failures as
warnings; the public number is recycled only when every public deletion
succeeded; revert-to-public happens only pre-deletion.

**Validator intentionally unchanged.** Going-private is a rare,
legitimate cause of a transient gap that the next public track refills;
the owner wants to keep receiving that warning.

## Testing

- New/updated unit tests: distribute-then-delete ordering, real rollback
(no public deletion + revert on failure), `redistribute_mode` skips
status transition, public/private brand-code recycle, recycle-gating on
incomplete cleanup.
- Green: `test_change_visibility.py`,
`test_video_worker_orchestrator.py`, `test_brand_code_service.py`,
`test_private_tracks.py`, `test_cleanup_distribution.py`,
`test_admin_delete_outputs.py` (326 tests).

## Follow-up (post-merge, operational)

- Recover job `25d076e5`: re-run `redistribute_video('25d076e5')` (GCS
finals intact) to create its NonPublished archive + `NOMADNP` code.
- Recycle the leaked `NOMADNP-0214`.

Full analysis + plan:
`docs/archive/2026-08-18-visibility-change-recycle-dataloss-plan.md`.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-18 12:15:01 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 e78ba02e62 fix(e2e): handle Stripe Checkout single-payment-method layout (#916)
## Problem

The daily E2E test (`e2e-daily.yml` → **Stage 1: Credit Purchase**)
started failing, firing the "🚨 Payment flow is broken" alert (run #135).
All 3 attempts timed out at the same line:

```
TimeoutError: locator.check: Timeout 10000ms exceeded.
> 67 |   await cardRadio.check({ force: true, timeout: 10_000 });
```

## Root cause — test-only, prod is healthy

Stripe changed its **hosted Checkout** layout. It now serves a
**single-payment-method (Card-only)** page where the card fields render
directly — there is **no `radio` named "Card"** to select. The helper
unconditionally waited on that radio, which no longer exists, so it hung
for 10s × 3.

The failure snapshot shows the real customer checkout rendering
**correctly**: right product ("1 Karaoke Credit"), referral discount
applied ("Referral 70% off"), correct total ($3.00), and working card
inputs. The alert message is the workflow's generic worst-case text, not
an observed payment break. **No product/app code changed or needed to
change** — this is purely test-automation drift.

(On the hosted `checkout.stripe.com` page the card inputs are
same-origin **direct textboxes**, not cross-origin iframes.)

## Fix

`frontend/e2e/helpers/stripe-checkout.ts` — make
`completeStripeCheckout` resilient to **both** layouts:

- Only click the "Card" radio when one is actually present.
- If card fields are already visible (single-method layout), skip radio
selection entirely.
- Fill fields via direct locators (stable-field-name / id / placeholder
/ accessible name), keeping the existing iframe fallback for the legacy
accordion layout.
- Broaden cardholder-name and ZIP locators to match the new accessible
names.

## Verification

Dispatched `e2e-daily.yml` on this branch (test code from branch,
driving **production**). The changed helper is exercised on the real
Stripe page:

- **Stage 1: Credit Purchase — ✅ success** (real ~$3 charge; full flow:
checkout → submit → success page → credits allocated)
- **Stage 2: Happy Path — ✅ success**
- Run:
https://github.com/nomadkaraoke/karaoke-gen/actions/runs/32037148447

Test-helper-only change; no shipped code affected, so no
`pyproject.toml` version bump.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-17 12:23:22 -04:00
3740 changed files with 10878 additions and 43257 deletions

No files matched your search

+46
View File
@@ -515,12 +515,35 @@ jobs:
virtualenvs-create: true
virtualenvs-in-project: true
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- name: Install frontend dependencies
working-directory: frontend
run: npm ci --legacy-peer-deps
- name: Build frontend into the package
# The Next.js static export (karaoke_gen/nextjs_frontend/out) is gitignored
# (#876) and bundled into the wheel via pyproject `include`. Build it here,
# BEFORE `poetry build`, so the wheel contains the CLI local-review UI.
# node_modules is already installed above, so this just builds + copies.
# `make build-frontend` fails loudly if the frontend build fails.
run: make build-frontend
- name: Build package
# Wheel-only: we ship a universal py3-none-any wheel. The sdist bundles
# the 33-locale Next.js static export (~50 MB) as dead weight and pushed
# the PyPI project over its 10 GB cap. pip always installs from the wheel.
run: poetry build --format wheel
- name: Verify frontend is bundled in the wheel
# Guard against silently shipping a frontend-less wheel.
run: python scripts/verify_wheel_frontend.py dist/*.whl
- name: Test package installation
run: |
pip install dist/*.whl
@@ -833,6 +856,25 @@ jobs:
restore-keys: |
venv-package-${{ runner.os }}-py3.13-
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- name: Install frontend dependencies
working-directory: frontend
run: npm ci --legacy-peer-deps
- name: Build frontend into the package
# The Next.js static export (karaoke_gen/nextjs_frontend/out) is gitignored
# (#876) and bundled into the wheel via pyproject `include`. Build it here,
# BEFORE `poetry build`, so the shipped wheel contains the CLI local-review
# UI. node_modules is already installed above, so this just builds + copies.
# `make build-frontend` fails loudly if the frontend build fails.
run: make build-frontend
- name: Build package
# Wheel-only: we publish a universal py3-none-any wheel to PyPI. The
# sdist bundled the 33-locale Next.js static export (~50 MB/release) as
@@ -841,6 +883,10 @@ jobs:
# source (the GCE encoding worker pulls the wheel from GCS).
run: poetry build --format wheel
- name: Verify frontend is bundled in the wheel
# Loud guard against shipping a frontend-less wheel to PyPI / the GCE worker.
run: python scripts/verify_wheel_frontend.py dist/*.whl
- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
+13 -6
View File
@@ -53,7 +53,11 @@ jobs:
import os, sys, datetime, boto3
BUCKET = os.environ["BUCKET"]
# (label, prefix, max_age_hours)
# (label, prefix, max_age_hours, require_suffix)
# require_suffix: only objects with this key suffix count toward
# freshness (None = any object). git-repos/ requires ".bundle" so the
# always-written manifest.json can't mark the prefix fresh when every
# bundle failed / nothing was bundled — 0 bundles then reads as stale.
# NOTE: Firestore and BigQuery export to GCS staging nightly but are
# only uploaded to S3 *weekly* (Sundays) to cut cross-cloud egress —
# see backup_to_aws/main.py (firestore_to_s3_today). This monitor only
@@ -61,10 +65,11 @@ jobs:
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. GCS job
# files and secrets DO upload to S3 nightly, so they stay at 36h.
TARGETS = [
("Firestore", "firestore/", 192),
("GCS job files", "gcs/job-files/", 36),
("Encrypted secrets", "secrets/", 36),
("BigQuery weekly", "bigquery/daily-refresh/", 192),
("Firestore", "firestore/", 192, None),
("GCS job files", "gcs/job-files/", 36, None),
("Encrypted secrets", "secrets/", 36, None),
("BigQuery weekly", "bigquery/daily-refresh/", 192, None),
("Git repos", "git-repos/", 36, ".bundle"),
]
s3 = boto3.client("s3")
@@ -75,10 +80,12 @@ jobs:
# operates per-page, which silently breaks "newest across all pages"
# queries on prefixes with >1000 objects (e.g. firestore/ has ~22k).
paginator = s3.get_paginator("list_objects_v2")
for label, prefix, max_hours in TARGETS:
for label, prefix, max_hours, require_suffix in TARGETS:
latest = None
for page in paginator.paginate(Bucket=BUCKET, Prefix=prefix):
for obj in page.get("Contents", []):
if require_suffix and not obj["Key"].endswith(require_suffix):
continue
if latest is None or obj["LastModified"] > latest:
latest = obj["LastModified"]
+3
View File
@@ -28,6 +28,9 @@ frontend/.swc/
frontend/.turbo/
frontend/build/
frontend/dist/
# Generated Next.js static export copied into the Python package at build time (#876).
# Bundled into the wheel via pyproject `include`; must not be tracked in git.
karaoke_gen/nextjs_frontend/out/
# Next.js specific
frontend/*.tsbuildinfo
+98 -25
View File
@@ -7,7 +7,9 @@ Handles:
- Admin-only operations
- Audio search cache management
"""
import asyncio
import logging
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone
from typing import Tuple, List, Optional, Any, Dict
@@ -153,10 +155,23 @@ async def get_admin_stats_overview(
- Credit statistics
- Beta program stats
"""
# The Firestore streaming below is synchronous; run it in a worker thread so
# it can't block the event loop and stall every other request on this instance.
return await asyncio.to_thread(_compute_admin_stats_overview, user_service.db, exclude_test)
# Field masks for the overview stats streams. Job documents carry large payloads
# (state_data, timeline, corrections — ~100MB across the collection), so streaming
# full documents just to count statuses takes ~15-20s; with these masks it's ~1s.
_OVERVIEW_USER_FIELDS = ["email", "last_login_at", "credit_transactions"]
_OVERVIEW_JOB_FIELDS = ["user_email", "created_at", "status"]
def _compute_admin_stats_overview(db, exclude_test: bool) -> AdminStatsOverview:
"""Synchronous stats computation — called via asyncio.to_thread from the route."""
from google.cloud.firestore_v1 import FieldFilter
from google.cloud.firestore_v1 import aggregation
db = user_service.db
now = datetime.utcnow()
seven_days_ago = now - timedelta(days=7)
thirty_days_ago = now - timedelta(days=30)
@@ -180,20 +195,37 @@ async def get_admin_stats_overview(
if exclude_test:
# When excluding test data, we must stream and filter in Python
# because Firestore doesn't support "not ends with" queries
# because Firestore doesn't support "not ends with" queries.
# The two streams are independent, so run them concurrently.
# Stream all users and filter
all_users = []
users_fetched = 0
for doc in users_collection.limit(USERS_STREAM_LIMIT).stream():
users_fetched += 1
user_data = doc.to_dict()
email = user_data.get("email", "")
if not is_test_email(email):
all_users.append(user_data)
def _stream_users():
users, fetched = [], 0
for doc in users_collection.select(_OVERVIEW_USER_FIELDS).limit(USERS_STREAM_LIMIT).stream():
fetched += 1
user_data = doc.to_dict()
if not is_test_email(user_data.get("email", "")):
users.append(user_data)
return users, fetched
def _stream_jobs():
jobs, fetched = [], 0
for doc in jobs_collection.select(_OVERVIEW_JOB_FIELDS).limit(JOBS_STREAM_LIMIT).stream():
fetched += 1
job_data = doc.to_dict()
if not is_test_email(job_data.get("user_email", "")):
jobs.append(job_data)
return jobs, fetched
with ThreadPoolExecutor(max_workers=2) as executor:
users_future = executor.submit(_stream_users)
jobs_future = executor.submit(_stream_jobs)
all_users, users_fetched = users_future.result()
all_jobs, jobs_fetched = jobs_future.result()
if users_fetched >= USERS_STREAM_LIMIT:
logger.warning(f"Users stream hit limit ({USERS_STREAM_LIMIT}), stats may be incomplete")
if jobs_fetched >= JOBS_STREAM_LIMIT:
logger.warning(f"Jobs stream hit limit ({JOBS_STREAM_LIMIT}), stats may be incomplete")
# Calculate user stats from filtered list
total_users = len(all_users)
@@ -216,19 +248,6 @@ async def get_admin_stats_overview(
if amount > 0:
total_credits_issued_30d += amount
# Stream all jobs and filter by user_email
all_jobs = []
jobs_fetched = 0
for doc in jobs_collection.limit(JOBS_STREAM_LIMIT).stream():
jobs_fetched += 1
job_data = doc.to_dict()
user_email = job_data.get("user_email", "")
if not is_test_email(user_email):
all_jobs.append(job_data)
if jobs_fetched >= JOBS_STREAM_LIMIT:
logger.warning(f"Jobs stream hit limit ({JOBS_STREAM_LIMIT}), stats may be incomplete")
# Calculate job stats from filtered list
total_jobs = len(all_jobs)
jobs_last_7d = sum(
@@ -313,7 +332,7 @@ async def get_admin_stats_overview(
total_credits_issued_30d = 0
try:
users_fetched = 0
for user_doc in users_collection.limit(USERS_STREAM_LIMIT).stream():
for user_doc in users_collection.select(["credit_transactions"]).limit(USERS_STREAM_LIMIT).stream():
users_fetched += 1
user_data = user_doc.to_dict()
transactions = user_data.get("credit_transactions", [])
@@ -948,6 +967,27 @@ async def update_job(
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
# Reassigning a job to an email with no account would orphan it (the user
# couldn't log in to see it, and impersonation would 404) — so normalize the
# email and auto-create the account if needed.
user_created_email = None
if isinstance(updates.get("user_email"), str):
normalized_email = updates["user_email"].strip().lower()
if not normalized_email or "@" not in normalized_email:
raise HTTPException(
status_code=400,
detail="user_email must be a valid email address"
)
updates["user_email"] = normalized_email
user_service = get_user_service()
if not user_service.get_user(normalized_email):
user_service.get_or_create_user(normalized_email)
user_created_email = normalized_email
logger.info(
f"Admin {admin_email} reassigned job {job_id} to {normalized_email} — "
f"no account existed, created one"
)
# Check if we're toggling is_private from False to True on a completed job
# If so, auto-delete existing outputs (YouTube, Dropbox, GDrive)
toggling_to_private = (
@@ -997,6 +1037,8 @@ async def update_job(
)
message = f"Successfully updated {len(updates)} field(s)"
if user_created_email:
message += f". Created new user account for {user_created_email}."
if auto_deleted:
message += ". Existing outputs were auto-deleted (job set to private)."
@@ -2977,6 +3019,37 @@ async def get_user_payments(
return service.get_user_payment_history(email)
@router.get("/users/{email}/emails")
async def get_user_emails(
email: str,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
"""List every email ever sent to a user (Postmark + our persisted log)."""
from backend.services.postmark_admin_service import get_postmark_admin_service
service = get_postmark_admin_service()
return service.get_user_email_history(email)
@router.get("/emails/{message_id}")
async def get_email_detail(
message_id: str,
source: str = "postmark",
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
"""Full detail for a single email — rendered HTML + delivery metadata.
``source=log`` reads our persisted copy directly (for mail older than
Postmark's ~45-day retention); otherwise Postmark is queried with a
fallback to the stored log.
"""
from backend.services.postmark_admin_service import get_postmark_admin_service
service = get_postmark_admin_service()
result = service.get_email_detail(message_id, source=source)
if not result:
raise HTTPException(status_code=404, detail="Email not found")
return result
@router.get("/payments/{session_id}")
async def get_payment_detail(
session_id: str,
+2 -1
View File
@@ -55,7 +55,7 @@ from backend.services.firestore_service import FirestoreService
from backend.services.user_service import get_user_service
from backend.services.pricing import duration_to_credits, is_blocked
from pathlib import Path
from backend.i18n import t, get_locale_from_request
from backend.i18n import t, get_locale_from_request, get_full_locale_from_request
logger = logging.getLogger(__name__)
@@ -806,6 +806,7 @@ async def search_audio(
is_private=body.is_private,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else "",
locale=get_full_locale_from_request(request),
)
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
job_id = job.job_id
+2
View File
@@ -17,6 +17,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Request
from pydantic import BaseModel, Field
from backend.api.dependencies import require_auth
from backend.i18n import get_full_locale_from_request
from backend.services.auth_service import AuthResult
logger = logging.getLogger(__name__)
@@ -348,6 +349,7 @@ async def bulk_submit(
dropbox_path=settings.default_dropbox_path,
gdrive_folder_id=settings.default_gdrive_folder_id,
request_metadata=request_metadata,
locale=get_full_locale_from_request(request),
)
try:
job = job_manager.create_job(job_create, is_admin=is_admin)
+9 -1
View File
@@ -44,7 +44,7 @@ from backend.services.youtube_download_service import (
get_youtube_download_service,
YouTubeDownloadError,
)
from backend.i18n import t, get_locale_from_request
from backend.i18n import t, get_locale_from_request, get_full_locale_from_request
logger = logging.getLogger(__name__)
@@ -685,6 +685,8 @@ async def upload_and_create_job(
is_private=is_private,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else "",
# UI language the job was submitted in (admin-only signal)
locale=get_full_locale_from_request(request),
)
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
job_id = job.job_id
@@ -1269,6 +1271,8 @@ async def create_job_with_upload_urls(
is_private=effective_is_private,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else "",
# UI language the job was submitted in (admin-only signal)
locale=get_full_locale_from_request(request),
)
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
job_id = job.job_id
@@ -1897,6 +1901,8 @@ async def create_job_from_url(
is_private=body.is_private,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else "",
# UI language the job was submitted in (admin-only signal)
locale=get_full_locale_from_request(request),
)
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
job_id = job.job_id
@@ -2202,6 +2208,8 @@ async def create_finalise_only_job(
is_private=body.is_private,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else "",
# UI language the job was submitted in (admin-only signal)
locale=get_full_locale_from_request(request),
)
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
job_id = job.job_id
+26
View File
@@ -15,6 +15,7 @@ from backend.services.flacfetch_client import get_flacfetch_client
from backend.services.email_service import get_email_service
from backend.services.stripe_service import get_stripe_service
from backend.services.encoding_service import get_encoding_service
from backend.services.encoding_worker_preference import infer_machine_type, PRIMARY_MACHINE_TYPE
from backend.services.spacy_preloader import get_preloaded_model, is_model_preloaded
from backend.services.nltk_preloader import get_preloaded_cmudict, is_cmudict_preloaded
from backend.services.langfuse_preloader import get_preloaded_langfuse_handler, is_langfuse_preloaded, is_langfuse_configured
@@ -443,6 +444,26 @@ async def system_status(
if manager:
try:
config = manager.get_config()
# Which VM is actually serving right now? When a capacity
# fallback is active (e.g. a c4d stockout routed us to an
# alternate family) the override points at the live VM;
# otherwise it's the blue-green primary. The primary pair is
# always c4d — fallbacks carry their family in the VM name
# (…-fallback-n2c, …-fallback-c4a), which infer_machine_type
# decodes when no explicit machine_type is stored on the config.
on_fallback = bool(config.active_override_vm)
active_vm = config.active_override_vm or config.primary_vm
default_zone = getattr(manager, "_zone", "us-central1-c")
active_zone = config.active_override_zone or default_zone
if on_fallback:
active_machine_type = infer_machine_type({"vm": active_vm})
else:
active_machine_type = (
getattr(config, "primary_machine_type", None)
or PRIMARY_MACHINE_TYPE
)
encoder_svc["admin_details"] = {
"primary_vm": config.primary_vm,
"primary_ip": config.primary_ip,
@@ -456,6 +477,11 @@ async def system_status(
"deploy_in_progress": config.deploy_in_progress,
"active_jobs": encoding_status.get("active_jobs", 0),
"queue_length": encoding_status.get("queue_length", 0),
# Currently-serving worker (fallback-aware)
"active_vm": active_vm,
"active_zone": active_zone,
"active_machine_type": active_machine_type,
"on_fallback": on_fallback,
}
except Exception as e:
logger.warning(f"Failed to get blue-green config: {e}")
+3 -1
View File
@@ -39,7 +39,7 @@ from backend.services.tracing import add_span_attribute
from backend.api.dependencies import require_admin, require_auth
from backend.services.auth_service import AuthResult
from backend.services.metrics import metrics
from backend.i18n import t, get_locale_from_request
from backend.i18n import t, get_locale_from_request, get_full_locale_from_request
from backend.middleware.tenant import get_tenant_from_request
from backend.utils.test_data import is_test_email
from backend.exceptions import InsufficientCreditsError
@@ -164,6 +164,7 @@ async def create_job(
user_email=user_email,
is_private=request.is_private or False,
credits=credits,
locale=get_full_locale_from_request(http_request),
)
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
@@ -2541,6 +2542,7 @@ async def create_job_from_search(
request_metadata=request_metadata,
is_private=body.is_private,
tenant_id=tenant_id,
locale=get_full_locale_from_request(request),
)
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
job_id = job.job_id
+67 -7
View File
@@ -19,10 +19,10 @@ import json
import os
import tempfile
from pathlib import Path
from typing import Dict, Any, List, Optional, Set, Tuple
from typing import Dict, Any, List, Literal, Optional, Set, Tuple
from fastapi import APIRouter, HTTPException, Request, Depends, Form, File, UploadFile
from fastapi.responses import RedirectResponse
from fastapi.responses import RedirectResponse, Response
from backend.models.job import JobStatus
from backend.models.review_session import ReviewSession, ReviewSessionSummary
@@ -372,6 +372,15 @@ async def get_correction_data(
raise HTTPException(status_code=500, detail=t("en", "review.correctionsLoadFailed", error=str(e)))
@router.get("/{job_id}/audio/vocals")
async def get_vocals_audio(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""Stream the vocals audio file for playback."""
return await _stream_audio(job_id, stem="vocals")
@router.get("/{job_id}/audio/{audio_hash}")
async def get_audio_with_hash(
job_id: str,
@@ -392,7 +401,7 @@ async def get_audio_no_hash(
return await _stream_audio(job_id)
async def _stream_audio(job_id: str):
async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"] = "input"):
"""
Redirect to a signed GCS URL for audio playback in the review interface.
@@ -407,12 +416,50 @@ async def _stream_audio(job_id: str):
if not job:
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
audio_gcs_path = job.input_media_gcs_path
audio_gcs_path = None
if stem == "input":
audio_gcs_path = job.input_media_gcs_path
elif stem == "vocals":
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
# Stem keys vary by separation model. We want the full vocal mix
# (lead + backing) so every word can be lined up against the waveform:
# - "vocals" : full vocal from a 2-stem split (rare)
# - "vocals_clean" : full vocal from the primary vocal/instrumental
# split (present on essentially all cloud jobs)
# - "lead_vocals" : last-resort fallback (misses backing lines)
# Use .get() so a missing key yields a clean 404 below, not a KeyError/500.
for key in ("vocals", "vocals_clean", "lead_vocals"):
if stems.get(key):
audio_gcs_path = stems[key]
break
if not audio_gcs_path:
# Audio separation is decoupled from the lyrics-review critical path, so a
# user can open review before the vocal stems have been uploaded (the stem
# arrives a minute or two later). Signal "not ready yet, retry" with a 202
# so the frontend polls instead of treating it as a terminal 404.
# state_data.audio_complete is set both when separation finishes and when
# it's skipped entirely (existing-instrumental jobs), so a missing stem
# with audio_complete=True really is a permanent 404.
if stem == "vocals" and not job.state_data.get("audio_complete", False):
logger.info(f"Job {job_id}: Vocal stem not yet available (separation in progress), returning 202")
return Response(status_code=202, headers={"Retry-After": "15"})
raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound"))
try:
transcoding = AudioTranscodingService()
if stem == "vocals":
# Proxy the vocals bytes through the API rather than 302-redirecting to
# a signed GCS URL. The waveform visualizer fetch()es + decodeAudioData()s
# this (a cross-origin READ), and a cross-origin redirect makes the
# browser send `Origin: null`, which the bucket CORS rejects. Serving
# the (~3 MB) bytes from the API keeps it same-origin to api.* whose
# CORS already allows the frontend. <audio> playback (stem="input")
# doesn't need CORS, so it keeps the lighter redirect below.
audio_bytes, content_type = await transcoding.get_review_audio_bytes_async(audio_gcs_path)
logger.info(f"Job {job_id}: Proxying {len(audio_bytes)}B vocals audio for waveform")
return Response(content=audio_bytes, media_type=content_type)
signed_url = await transcoding.get_review_audio_url_async(audio_gcs_path, expiration_minutes=120)
logger.info(f"Job {job_id}: Redirecting to signed URL for audio review")
return RedirectResponse(url=signed_url, status_code=302)
@@ -851,16 +898,29 @@ async def add_lyrics(
updated_result.metadata['audio_hash'] = audio_hash
updated_result.metadata['artist'] = job.artist
updated_result.metadata['title'] = job.title
# The relevance filter may silently drop the new source during the
# correction rerun. Surface that as a "rejected" outcome (without
# persisting the no-op rerun) so the frontend can offer force-add.
source_kept = source in (updated_result.reference_lyrics or {})
if not source_kept:
rejection = (updated_result.metadata.get("rejected_sources") or {}).get(source) or {}
logger.info(
f"Job {job_id}: Lyrics source '{source}' rejected by relevance filter "
f"({rejection.get('matched_words')}/{rejection.get('total_words')} words matched)"
)
span.set_attribute("rejected", True)
return {"status": "rejected", "rejection": rejection, "data": updated_result.to_dict()}
# Upload updated corrections back to GCS
with create_span("upload-corrections") as upload_span:
updated_data = updated_result.to_dict()
storage.upload_json(corrections_gcs, updated_data)
upload_span.set_attribute("gcs_path", corrections_gcs)
logger.info(f"Job {job_id}: Successfully added lyrics source '{source}'")
span.set_attribute("success", True)
return {"status": "success", "data": updated_data}
except ValueError as e:
+251 -58
View File
@@ -9,6 +9,7 @@ Handles:
- Admin user management
"""
import hashlib
import html
import logging
import threading
from datetime import datetime
@@ -35,7 +36,7 @@ def _mask_email(email: str) -> str:
from fastapi import APIRouter, HTTPException, Depends, Request, Header
from pydantic import BaseModel, EmailStr
from backend.i18n import t, get_locale_from_request
from backend.i18n import t, get_locale_from_request, get_full_locale_from_request
from backend.services.email_validation_service import get_email_validation_service
from backend.models.user import (
UserRole,
@@ -47,6 +48,8 @@ from backend.models.user import (
ResendFromTokenResponse,
AddCreditsRequest,
AddCreditsResponse,
AdminCreateUserRequest,
AdminCreateUserResponse,
UserListResponse,
UserFeedback,
UserFeedbackRequest,
@@ -437,10 +440,22 @@ async def verify_magic_link(
except Exception as ref_err:
logger.warning(f"Referral attribution failed for {_mask_email(user.email)}: {ref_err}")
# Persist user's locale preference (from Accept-Language header)
if locale and locale != (user.locale or "en"):
# Persist user's locale preference (from Accept-Language header).
# `locale` is narrowed to en/es/de for email rendering; `ui_locale` is the
# full UI language (any of 33) so admins know what language to communicate in.
ui_locale = get_full_locale_from_request(http_request)
has_accept_language = bool(http_request.headers.get("accept-language"))
locale_updates = {}
# Only touch locale when the client actually sent an Accept-Language header —
# otherwise get_locale_from_request()'s "en" default would clobber a user's
# real stored locale on token-only logins (e.g. magic-link scanners).
if has_accept_language and locale and locale != (user.locale or "en"):
locale_updates["locale"] = locale
if ui_locale and ui_locale != user.ui_locale:
locale_updates["ui_locale"] = ui_locale
if locale_updates:
try:
user_service.update_user(user.email, locale=locale)
user_service.update_user(user.email, **locale_updates)
except Exception:
pass # Non-critical — don't block login
@@ -800,6 +815,7 @@ async def create_checkout(
@router.post("/made-for-you/checkout", response_model=CreateCheckoutResponse)
async def create_made_for_you_checkout(
request: MadeForYouCheckoutRequest,
http_request: Request,
stripe_service: StripeService = Depends(get_stripe_service),
):
"""
@@ -824,6 +840,7 @@ async def create_made_for_you_checkout(
source_type=request.source_type,
youtube_url=request.youtube_url,
notes=request.notes,
locale=get_full_locale_from_request(http_request),
)
if not success or not checkout_url:
@@ -844,6 +861,72 @@ async def create_made_for_you_checkout(
ADMIN_EMAIL = "madeforyou@nomadkaraoke.com"
def _send_mfy_failure_alert(
email_service: EmailService,
*,
customer_email: str,
artist: str,
title: str,
job_id: Optional[str],
error: Exception,
) -> None:
"""Best-effort admin alert when a made-for-you order can't be fully processed.
This never raises: a failure to send the alert must not mask the original
error, nor interfere with the customer-facing order-confirmation email
(which is sent independently, before audio acquisition is attempted).
"""
safe_customer = html.escape(customer_email or "")
safe_artist = html.escape(artist or "")
safe_title = html.escape(title or "")
safe_error = html.escape(str(error))
job_line_html = f"<li><strong>Job ID:</strong> {html.escape(job_id)}</li>" if job_id else ""
job_line_text = f"Job ID: {job_id}\n" if job_id else ""
remediation = (
"The customer's order-confirmation email is sent separately and up-front, so it "
"is unaffected by failures during processing. Please review this order and take "
"any needed manual action — e.g. provide/repair the audio source, or resend the "
"customer confirmation."
)
try:
sent = email_service.send_email(
to_email=ADMIN_EMAIL,
subject=f"[FAILED] Made For You Order: {artist} - {title}",
html_content=f"""
<h2>Made-For-You Order — Action Needed</h2>
<p>A problem occurred while processing this order:</p>
<ul>
<li><strong>Customer:</strong> {safe_customer}</li>
<li><strong>Artist:</strong> {safe_artist}</li>
<li><strong>Title:</strong> {safe_title}</li>
{job_line_html}
<li><strong>Error:</strong> {safe_error}</li>
</ul>
<p>{remediation}</p>
""",
text_content=(
"Made-For-You Order — Action Needed\n\n"
f"Customer: {customer_email}\n"
f"Artist: {artist}\n"
f"Title: {title}\n"
f"{job_line_text}"
f"Error: {error}\n\n"
f"{remediation}"
),
)
if sent:
logger.info(f"Sent made-for-you failure alert to admin for job {job_id}")
else:
logger.error(
f"Made-for-you failure alert to admin was rejected by the email provider (job {job_id})"
)
except Exception as email_error:
logger.error(
f"Failed to send made-for-you failure alert (job {job_id}): {email_error}",
exc_info=True,
)
async def _handle_made_for_you_order(
session_id: str,
metadata: dict,
@@ -892,6 +975,10 @@ async def _handle_made_for_you_order(
f"(session: {session_id}, source_type: {source_type})"
)
# Defined up-front so the outer failure handler can reference it even if job
# creation is what failed (job_id stays None until the job actually exists).
job_id = None
try:
job_manager = JobManager()
storage_service = StorageService()
@@ -937,6 +1024,8 @@ async def _handle_made_for_you_order(
brand_prefix=dist.brand_prefix,
discord_webhook_url=dist.discord_webhook_url,
youtube_description=dist.youtube_description,
# UI language the customer ordered in (captured at checkout, admin-only signal)
locale=metadata.get("locale") or None,
)
# Made-for-you jobs are created by admin (via Stripe webhook) - bypass rate limits
job = job_manager.create_job(job_create, is_admin=True)
@@ -977,6 +1066,48 @@ async def _handle_made_for_you_order(
# Initialize search_results for later use in email notification
search_results = None
# Send the customer's order-confirmation email NOW, before attempting audio
# acquisition. The order is paid and confirmed regardless of whether the
# (fallible) YouTube download / audio search succeeds, so a failure there must
# never rob the customer of their confirmation email. Resilient: a delivery
# failure is logged but does not abort order processing.
confirmation_ok = False
try:
# Providers return False (not an exception) when the send is rejected, so
# check the result rather than assuming success.
confirmation_ok = bool(email_service.send_made_for_you_order_confirmation(
to_email=customer_email,
artist=artist,
title=title,
job_id=job_id,
notes=notes,
))
if confirmation_ok:
logger.info(f"Sent made-for-you customer confirmation for job {job_id}")
else:
logger.error(
f"Job {job_id}: customer order-confirmation email was rejected by the email provider"
)
except Exception as confirm_error:
logger.error(
f"Job {job_id}: Failed to send customer order-confirmation email: {confirm_error}",
exc_info=True,
)
if not confirmation_ok:
# A paid customer must never silently miss their confirmation. Escalate to
# the admin so it can be resent manually. Order processing still continues.
_send_mfy_failure_alert(
email_service,
customer_email=customer_email,
artist=artist,
title=title,
job_id=job_id,
error=RuntimeError(
"Customer order-confirmation email failed to send — please resend it manually"
),
)
# Handle based on whether we have a YouTube URL or need to search
if youtube_url:
# URL provided - download audio first, then trigger workers
@@ -1099,66 +1230,59 @@ async def _handle_made_for_you_order(
# (search_results may be set from the search flow above, or None for YouTube URL orders)
audio_source_count = len(search_results) if search_results else 0
# Generate admin login token for one-click email access (24hr expiry)
admin_login = user_service.create_admin_login_token(
email=ADMIN_EMAIL,
expiry_hours=24,
)
# Send notification email to admin using professional template.
# Resilient: an email delivery error here must not turn a successfully-created
# order into a "[FAILED]" alert — it's logged and swallowed instead.
try:
# Generate admin login token for one-click email access (24hr expiry)
admin_login = user_service.create_admin_login_token(
email=ADMIN_EMAIL,
expiry_hours=24,
)
admin_notified = bool(email_service.send_made_for_you_admin_notification(
to_email=ADMIN_EMAIL,
customer_email=customer_email,
artist=artist,
title=title,
job_id=job_id,
admin_login_token=admin_login.token,
notes=notes,
audio_source_count=audio_source_count,
))
if admin_notified:
logger.info(f"Sent made-for-you admin notification for job {job_id}")
else:
logger.error(
f"Job {job_id}: admin order notification was rejected by the email provider"
)
except Exception as admin_email_error:
logger.error(
f"Job {job_id}: Failed to send admin order notification: {admin_email_error}",
exc_info=True,
)
# Send confirmation email to customer using professional template
email_service.send_made_for_you_order_confirmation(
to_email=customer_email,
artist=artist,
title=title,
job_id=job_id,
notes=notes,
)
# Send notification email to admin using professional template
email_service.send_made_for_you_admin_notification(
to_email=ADMIN_EMAIL,
except Exception as e:
# A hard failure in order processing (e.g. job creation, or audio acquisition
# raising after transitioning the job to FAILED). The customer confirmation is
# sent earlier and independently, so it is unaffected by failures here. Alert
# the admin so they can intervene manually.
logger.error(f"Error processing made-for-you order: {e}", exc_info=True)
_send_mfy_failure_alert(
email_service,
customer_email=customer_email,
artist=artist,
title=title,
job_id=job_id,
admin_login_token=admin_login.token,
notes=notes,
audio_source_count=audio_source_count,
error=e,
)
logger.info(f"Sent made-for-you order notifications for job {job_id}")
except Exception as e:
logger.error(f"Error processing made-for-you order: {e}", exc_info=True)
# Still try to notify Andrew of the failure
try:
email_service.send_email(
to_email=ADMIN_EMAIL,
subject=f"[FAILED] Made For You Order: {artist} - {title}",
html_content=f"""
<h2>Made-For-You Order Failed</h2>
<p>An error occurred processing this order:</p>
<ul>
<li><strong>Customer:</strong> {customer_email}</li>
<li><strong>Artist:</strong> {artist}</li>
<li><strong>Title:</strong> {title}</li>
<li><strong>Error:</strong> {str(e)}</li>
</ul>
<p>Please manually create this job and notify the customer.</p>
""",
text_content=f"""
Made-For-You Order Failed
Customer: {customer_email}
Artist: {artist}
Title: {title}
Error: {str(e)}
Please manually create this job and notify the customer.
""".strip(),
)
except Exception as email_error:
logger.error(f"Failed to send error notification: {email_error}")
# If we failed before the job was even created, no job exists and the Stripe
# session was never marked processed — re-raise so the webhook returns non-2xx
# and Stripe retries the (likely transient) failure rather than silently
# dropping a paid order. Post-creation failures keep job_id set: those return
# normally (job exists, session marked processed, admin already alerted), so a
# retry would be a no-op / risk a duplicate job.
if job_id is None:
raise
@router.post("/webhooks/stripe")
@@ -1652,6 +1776,10 @@ class UserDetailResponse(BaseModel):
display_name: Optional[str] = None
is_active: bool = True
email_verified: bool = False
# Language: `locale` is the email locale (en/es/de); `ui_locale` is the full UI
# language (any of 33) the user browses in — what admins should communicate in.
locale: Optional[str] = None
ui_locale: Optional[str] = None
created_at: Optional[str] = None
updated_at: Optional[str] = None
last_login_at: Optional[str] = None
@@ -1816,6 +1944,7 @@ async def get_user_detail(
"artist": job_data.get("artist"),
"title": job_data.get("title"),
"created_at": created_at_str,
"locale": job_data.get("locale"),
})
# Get active sessions with details
@@ -1852,6 +1981,8 @@ async def get_user_detail(
display_name=user.display_name,
is_active=user.is_active,
email_verified=user.email_verified,
locale=user.locale,
ui_locale=user.ui_locale,
created_at=user.created_at.isoformat() if user.created_at else None,
updated_at=user.updated_at.isoformat() if user.updated_at else None,
last_login_at=user.last_login_at.isoformat() if user.last_login_at else None,
@@ -1872,6 +2003,68 @@ async def get_user_detail(
)
@router.post("/admin/users", response_model=AdminCreateUserResponse, status_code=201)
async def admin_create_user(
request: AdminCreateUserRequest,
auth_data: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""
Create a user account directly (admin only).
Use this to set up an account for someone who has never logged in, so you can
grant them credits, submit jobs on their behalf, or impersonate them. The user
can later log in normally via magic link with the same email.
Users created this way with initial credits do NOT receive the automatic
welcome credit on first login (welcome_credits_granted is set to prevent
double-granting).
"""
admin_id = auth_data.user_email or "admin:unknown"
email = request.email.strip().lower()
if request.initial_credits < 0 or request.initial_credits > 1000:
raise HTTPException(status_code=400, detail="initial_credits must be between 0 and 1000")
if user_service.get_user(email):
raise HTTPException(status_code=409, detail=f"User {email} already exists")
user = user_service.get_or_create_user(email)
extra_updates = {}
if request.display_name and request.display_name.strip():
extra_updates["display_name"] = request.display_name.strip()
if request.initial_credits > 0:
success, new_balance, message = user_service.add_credits(
email=email,
amount=request.initial_credits,
reason=request.credit_reason,
admin_email=admin_id,
)
if not success:
raise HTTPException(status_code=500, detail=f"User created but adding credits failed: {message}")
user.credits = new_balance
# Admin-granted starter credits replace the automatic welcome credit
extra_updates["welcome_credits_granted"] = True
if extra_updates:
user_service.update_user(email, **extra_updates)
logger.info(
f"Admin {admin_id} created user {_mask_email(email)} "
f"(initial_credits={request.initial_credits})"
)
return AdminCreateUserResponse(
status="success",
email=email,
credits=user.credits,
message=f"Created user {email}"
+ (f" with {request.initial_credits} credit(s)" if request.initial_credits > 0 else ""),
)
@router.post("/admin/credits", response_model=AddCreditsResponse)
async def add_credits_to_user(
request: AddCreditsRequest,
+57 -6
View File
@@ -85,7 +85,8 @@ class Settings(BaseSettings):
# AI Credit Evaluation (anti-abuse gating for free credits)
# When enabled, welcome and feedback credit grants are evaluated by Gemini
# before granting. Fail-open: if evaluation fails, credits are granted anyway.
# before granting. Fail-CLOSED: if evaluation fails, the decision becomes
# "pending_review" (no auto-grant; an admin is notified to decide).
credit_eval_enabled: bool = os.getenv("CREDIT_EVAL_ENABLED", "true").lower() in ("true", "1", "yes")
credit_eval_model: str = os.getenv("CREDIT_EVAL_MODEL", "gemini-3.1-pro-preview")
@@ -106,11 +107,13 @@ class Settings(BaseSettings):
# Models used by the multi-model "compare" mode (semicolon-separated —
# Cloud Run --set-env-vars is comma-delimited). Empty = single-model only.
auto_correct_compare_models: str = os.getenv("AUTO_CORRECT_COMPARE_MODELS", "")
# Proactively generate (and cache) auto-correct suggestions in the lyrics
# worker once transcription + references are ready, so the review UI has
# them instantly. Best-effort: failures never block or fail the job. Only
# meaningful where ANTHROPIC_API_KEY + AUTO_CORRECT_COMPARE_MODELS are set
# (the lyrics-transcription-job, via ci.yml). Default off.
# Proactively generate (and cache) auto-correct suggestions once
# transcription + references are ready, so the review UI has them instantly.
# This flag gates whether the lyrics worker fires the trigger; the actual
# multi-model LLM call + caching runs on the API service (auto_correct_worker),
# which holds the model credentials — the lyrics-transcription-job itself does
# NOT need ANTHROPIC_API_KEY / AUTO_CORRECT_COMPARE_MODELS. Best-effort:
# failures never block or fail the job. Default off.
auto_correct_proactive_enabled: bool = os.getenv(
"AUTO_CORRECT_PROACTIVE_ENABLED", "false"
).lower() in ("true", "1", "yes")
@@ -306,3 +309,51 @@ def get_settings() -> Settings:
"""Get the global settings instance."""
return settings
def is_production() -> bool:
"""True when running in a deployed/production environment.
Cloud Run automatically sets ``K_SERVICE``, so we treat its presence as
production even if ``ENVIRONMENT`` were somehow unset — a production-safe
default. Local dev/test have no ``K_SERVICE`` and a non-"production"
``ENVIRONMENT``. (Fallback audit 2026-06-09, Theme 7.)
"""
env = (os.environ.get("ENVIRONMENT") or os.environ.get("ENV") or "").lower()
if env == "production":
return True
return bool(os.environ.get("K_SERVICE"))
# Env vars that MUST be explicitly set in production. A missing one used to
# silently fall back to a dev default and produce wrong behaviour with only a
# warning (wrong GCP project for secret lookups, wrong GCS bucket, localhost
# worker URL). We only require vars that infra confirms are set on every service
# (GCS temp/output buckets are intentionally excluded — their defaults are
# load-bearing and not set via env). (Fallback audit 2026-06-09, Theme 7.)
_REQUIRED_PRODUCTION_ENV_VARS = (
"GOOGLE_CLOUD_PROJECT",
"GCS_BUCKET_NAME",
"CLOUD_RUN_SERVICE_URL",
)
def validate_production_config() -> None:
"""Fail fast at startup if required production env vars are missing.
In production each var in ``_REQUIRED_PRODUCTION_ENV_VARS`` must be explicitly
set; otherwise the service would silently run with a dev default (wrong GCP
project / wrong GCS bucket / localhost worker URL) and appear to work while
doing the wrong thing. Raises RuntimeError listing every missing var. No-op
outside production. (Fallback audit 2026-06-09, Theme 7.)
"""
if not is_production():
return
missing = [v for v in _REQUIRED_PRODUCTION_ENV_VARS if not (os.environ.get(v) or "").strip()]
if missing:
raise RuntimeError(
"Production misconfiguration: required environment variable(s) not set: "
+ ", ".join(missing)
+ ". Refusing to start with silent dev defaults (wrong GCP project / "
"GCS bucket / localhost worker URL)."
)
+31
View File
@@ -92,6 +92,37 @@ def get_locale_from_request(request: Request) -> str:
return DEFAULT_LOCALE
def get_full_locale_from_request(request: Request) -> str | None:
"""Extract the user's actual UI language tag from Accept-Language.
Unlike :func:`get_locale_from_request`, this does NOT narrow to the 3
email-supported locales (en/es/de). It returns the primary language subtag
of the first entry in the header (e.g. ``pt``, ``ja``, ``zh``) so the admin
UI can show the real language a customer was using the product in.
Returns the lowercased language subtag, or ``None`` if the header is absent
or unparseable.
"""
accept_lang = request.headers.get("accept-language", "")
for part in accept_lang.split(","):
# Each part looks like "en-US;q=0.9" — take the language-region token
# before the quality factor, then the primary subtag before any region.
segments = part.split(";")
token = segments[0].strip()
if not token or token == "*":
continue
# Skip ranges the client explicitly rejects with q=0.
if any(seg.strip().lower().replace(" ", "") in ("q=0", "q=0.0", "q=0.00", "q=0.000")
for seg in segments[1:]):
continue
lang = token.split("-")[0].strip().lower()
if lang.isalpha() and len(lang) >= 2:
return lang
return None
def get_locale_prefix(locale: str) -> str:
"""Get URL locale prefix for frontend URLs (e.g., '/en', '/es')."""
if locale not in SUPPORTED_LOCALES:
+6 -1
View File
@@ -9,7 +9,7 @@ from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from backend.config import settings
from backend.config import settings, validate_production_config
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker, client_errors, bulk, parse_titles
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
from backend.services.structured_logging import setup_structured_logging
@@ -77,6 +77,11 @@ async def lifespan(app: FastAPI):
logger.info(f"GCS Bucket: {settings.gcs_bucket_name}")
logger.info(f"Tracing enabled: {tracing_enabled}")
# Fail fast if required production config is missing, rather than silently
# running on dev defaults (wrong GCP project / GCS bucket / localhost worker
# URL). No-op outside production. (Fallback audit 2026-06-09, Theme 7.)
validate_production_config()
# Preload NLP models and resources to avoid cold start delays
# See docs/archive/2026-01-08-performance-investigation.md for background
+7 -2
View File
@@ -26,9 +26,14 @@ from backend.models.tenant import TenantConfig
logger = logging.getLogger(__name__)
# Only allow query param tenant override in non-production environments
# Only allow the `?tenant=` query-param override in non-production environments —
# in production it is a tenant-spoofing vector. Production-safe by default: Cloud
# Run always sets K_SERVICE, so we treat its presence as production even if
# ENVIRONMENT were somehow unset (which would otherwise re-enable the override).
# (Fallback audit 2026-06-09, Theme 7.)
IS_PRODUCTION = os.environ.get("ENV", "").lower() == "production" or \
os.environ.get("ENVIRONMENT", "").lower() == "production"
os.environ.get("ENVIRONMENT", "").lower() == "production" or \
bool(os.environ.get("K_SERVICE"))
# Known non-tenant subdomains that should be treated as default Nomad Karaoke
+11 -1
View File
@@ -274,7 +274,13 @@ class Job(BaseModel):
# Multi-tenant support ("" = consumer portal, "vocalstar"/etc = tenant portal)
tenant_id: str = "" # Tenant ID for white-label portal scoping
# UI language the job was submitted in (primary Accept-Language subtag, e.g.
# "pt", "ja", "zh"). Any of the 33 supported UI locales — NOT narrowed to the
# 3 email locales. Admin-only signal for support/intervention. None for jobs
# created before this field existed or where the header was absent.
locale: Optional[str] = None
# Theme configuration (pre-made themes from GCS)
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
color_overrides: Dict[str, str] = Field(default_factory=dict)
@@ -631,6 +637,10 @@ class JobCreate(BaseModel):
# Tenant scoping for white-label portals ("" = consumer, "vocalstar"/etc = tenant)
tenant_id: str = "" # Tenant ID for job scoping
# UI language the job was submitted in (primary Accept-Language subtag, e.g.
# "pt", "ja"). Set by the API endpoint from the request header; admin-only.
locale: Optional[str] = None
@validator('url')
def validate_url(cls, v):
"""Validate URL is not empty."""
+25 -2
View File
@@ -10,7 +10,7 @@ Supports:
from datetime import datetime, timezone
from enum import Enum
from typing import Optional, List, Dict
from pydantic import BaseModel, Field
from pydantic import BaseModel, EmailStr, Field
class UserRole(str, Enum):
@@ -91,9 +91,16 @@ class User(BaseModel):
# Optional profile fields for future use
display_name: Optional[str] = None
# i18n locale preference (set from Accept-Language on login, used for emails/push)
# i18n locale preference (set from Accept-Language on login, used for emails/push).
# Narrowed to the 3 email-supported locales (en/es/de) — do NOT widen, email
# rendering depends on it.
locale: Optional[str] = None
# Actual UI language the user browses in (primary Accept-Language subtag, any
# of the 33 supported locales, e.g. "pt", "ja"). Captured on login and job
# creation. Admin-only signal so support knows what language to communicate in.
ui_locale: Optional[str] = None
# Push notification subscriptions (Web Push API)
# Users can subscribe from multiple devices/browsers
push_subscriptions: List[PushSubscription] = Field(default_factory=list)
@@ -250,6 +257,22 @@ class AddCreditsResponse(BaseModel):
message: str
class AdminCreateUserRequest(BaseModel):
"""Admin request to create a user account directly."""
email: EmailStr
display_name: Optional[str] = None
initial_credits: int = 0
credit_reason: str = "admin_grant"
class AdminCreateUserResponse(BaseModel):
"""Response after admin creates a user."""
status: str
email: str
credits: int
message: str
class UserListResponse(BaseModel):
"""Response for listing users (admin only)."""
users: List[UserPublic]
+10 -5
View File
@@ -368,12 +368,17 @@ class AudioSearchService:
return results
except FlacfetchServiceError as e:
logger.warning(f"Remote flacfetch search failed, falling back to local: {e}")
# Fallback to local search
# flacfetch is the sole downloader. The remote service was explicitly
# configured, so a failure here must NOT silently downgrade to the
# local YouTube-only fetcher — that hides the outage and ships a worse
# source than the user expected (the 2026-06-08 incident class).
# Fail loudly. (Fallback audit 2026-06-09, Theme 1.)
logger.error(f"Remote flacfetch search failed (not falling back to local): {e}")
# Clear cached state so a later download() can't consume stale results
# from a previous successful search on this (singleton) instance.
self._remote_search_id = None
results = self._fetcher.search(artist, title)
self._cached_results = results
return results
self._cached_results = []
raise AudioSearchError(f"Remote flacfetch search failed: {e}") from e
def select_best(self, results: List[AudioSearchResult]) -> int:
"""
@@ -137,6 +137,34 @@ class AudioTranscodingService:
self.get_review_audio_url, source_gcs_path, expiration_minutes
)
def get_review_audio_bytes(self, source_gcs_path: str) -> tuple[bytes, str]:
"""Return (bytes, content_type) of the transcoded review audio.
Used to proxy the audio through the API instead of 302-redirecting to a
signed GCS URL. The waveform visualizer fetch()es + decodeAudioData()s
this, which is a cross-origin read; a redirect to storage.googleapis.com
makes the browser send `Origin: null` on the redirected request, which
the bucket CORS rejects. Proxying keeps it same-origin to the API (which
sets the right CORS headers). The transcoded OGG is small (~3 MB), well
under Cloud Run's 32 MB response cap.
Falls back to the original (FLAC) source if transcoding fails, mirroring
get_review_audio_url, so a transient ffmpeg/cache error doesn't blank the
waveform while the source still exists. (A very long FLAC could exceed
Cloud Run's 32 MB cap on that rare fallback path — the frontend then just
hides the waveform, which is acceptable degradation.)
"""
try:
cache_path = self.transcode_if_needed(source_gcs_path)
return self.storage.download_bytes(cache_path), "audio/ogg"
except Exception as e:
logger.warning(f"Transcoding failed for {source_gcs_path}, serving source audio: {e}")
return self.storage.download_bytes(source_gcs_path), "audio/flac"
async def get_review_audio_bytes_async(self, source_gcs_path: str) -> tuple[bytes, str]:
"""Async wrapper around get_review_audio_bytes via asyncio.to_thread."""
return await asyncio.to_thread(self.get_review_audio_bytes, source_gcs_path)
def prepare_review_audio_for_job(self, job) -> list[str]:
"""
Transcode all review audio files for a job (eager transcoding).
+9 -1
View File
@@ -87,7 +87,15 @@ class AuthService:
if self.admin_tokens:
logger.info(f"Loaded {len(self.admin_tokens)} admin token(s)")
else:
logger.warning("No admin tokens configured! Set ADMIN_TOKENS environment variable.")
# Loud signal: with no admin tokens, every admin/internal-worker
# endpoint fails closed (403). That's safe but looks like an auth bug
# rather than a config error, so log at ERROR (picked up by the error
# monitor → Discord alert) instead of a quiet warning.
logger.error(
"No admin tokens configured! All admin and internal-worker "
"endpoints will reject every request (403). Set the ADMIN_TOKENS "
"secret/env var. This is almost certainly a misconfiguration."
)
def _validate_oidc_token(self, token: str) -> Optional[AuthResult]:
"""
@@ -2,8 +2,9 @@
AI-powered credit evaluation service.
Evaluates whether to grant free credits (welcome or feedback) by collecting
abuse signals and asking Gemini for a grant/deny decision. Fail-open: if
the AI call fails for any reason, credits are granted.
abuse signals and asking Gemini for a grant/deny decision. Fail-CLOSED: if
the AI call fails for any reason, the decision becomes "pending_review" (no
credits auto-granted; an admin is notified to decide manually).
"""
import json
import logging
@@ -25,7 +26,7 @@ class CreditEvaluation:
decision: str # "grant" or "deny"
reasoning: str
confidence: float
error: Optional[str] = None # Set if evaluation failed (decision defaults to "grant")
error: Optional[str] = None # Set if evaluation failed (decision defaults to "pending_review")
signals: Optional[dict] = None # Collected abuse signals (for admin review emails)
+7 -2
View File
@@ -30,8 +30,13 @@ class DropboxService:
"""Load OAuth credentials from Secret Manager."""
try:
client = secretmanager.SecretManagerServiceClient()
# Try to get the project ID from environment or use default
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "karaoke-gen")
# Use the configured GCP project. The old default "karaoke-gen" was a
# WRONG literal (the real project is "nomadkaraoke"); an unset var
# would silently target a non-existent project and disable Dropbox.
# Prod always sets GOOGLE_CLOUD_PROJECT (startup validation requires
# it), so use an empty default rather than a misleading wrong one.
# (Fallback audit 2026-06-09, Theme 7.)
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "")
name = f"projects/{project_id}/secrets/dropbox-oauth-credentials/versions/latest"
response = client.access_secret_version(request={"name": name})
return json.loads(response.payload.data.decode("UTF-8"))
+18 -1
View File
@@ -138,7 +138,24 @@ async def reconcile_and_maybe_pause(job_id: str) -> bool:
user_service = get_user_service()
storage = StorageService()
# JobManager/StorageService have no singleton accessor; instantiate directly (matches audio_download_worker).
email_service = get_email_service()
#
# Email is only actually sent on the rare over-limit *cancel* branch. Building
# the service must never crash an otherwise-successful download: EmailService()
# raises in production when POSTMARK_SERVER_TOKEN is unset (the "fail loudly"
# guard from the 2026-06-09 fallback audit), and this worker runs as the
# audio-download-job Cloud Run Job. If the provider can't be built, reconcile
# still proceeds (reconcile_duration tolerates email_service=None); we log
# loudly so a config regression is visible rather than silently dropping a
# customer notification. (Job a453d1d5: token missing on the job crashed the
# download entirely.)
try:
email_service = get_email_service()
except Exception as e:
logger.error(
"Job %s: could not construct email service for duration reconcile "
"(%s); proceeding without customer email notifications", job_id, e,
)
email_service = None
result = await asyncio.get_running_loop().run_in_executor(
None,
+253 -22
View File
@@ -10,14 +10,16 @@ Provider selection: POSTMARK_SERVER_TOKEN env var enables Postmark.
import html
import logging
import os
import re
import sys
from abc import ABC, abstractmethod
from datetime import datetime, timedelta, timezone
from typing import Optional, List
from typing import NamedTuple, Optional, List
from zoneinfo import ZoneInfo
import requests
from backend.config import get_settings
from backend.config import get_settings, is_production
from backend.i18n import t, get_locale_prefix
from karaoke_gen.utils import sanitize_filename
@@ -25,6 +27,18 @@ from karaoke_gen.utils import sanitize_filename
logger = logging.getLogger(__name__)
class SendResult(NamedTuple):
"""Outcome of a provider send.
``message_id`` is the provider's unique id for the sent message (Postmark's
``MessageID``) when available — used to link a send to its Postmark record and
to dedupe the persisted ``email_log`` entry. ``None`` for providers that don't
expose one (console/preview).
"""
success: bool
message_id: Optional[str] = None
class EmailProvider(ABC):
"""Abstract base class for email providers."""
@@ -53,6 +67,32 @@ class EmailProvider(ABC):
"""
pass
def send_email_detailed(
self,
to_email: str,
subject: str,
html_content: str,
text_content: Optional[str] = None,
cc_emails: Optional[List[str]] = None,
bcc_emails: Optional[List[str]] = None,
from_email_override: Optional[str] = None,
) -> SendResult:
"""Send an email and report the provider message id when available.
Default implementation delegates to :meth:`send_email` and reports no
message id. Providers that expose one (Postmark) override this.
"""
success = self.send_email(
to_email=to_email,
subject=subject,
html_content=html_content,
text_content=text_content,
cc_emails=cc_emails,
bcc_emails=bcc_emails,
from_email_override=from_email_override,
)
return SendResult(success=success, message_id=None)
class ConsoleEmailProvider(EmailProvider):
"""
@@ -133,6 +173,9 @@ class PostmarkEmailProvider(EmailProvider):
self.server_token = server_token
self.from_email = from_email
self.from_name = from_name
# Postmark MessageID of the most recent successful send, so the email_log
# chokepoint can link a persisted record to its Postmark message.
self.last_message_id: Optional[str] = None
def send_email(
self,
@@ -144,6 +187,26 @@ class PostmarkEmailProvider(EmailProvider):
bcc_emails: Optional[List[str]] = None,
from_email_override: Optional[str] = None,
) -> bool:
return self.send_email_detailed(
to_email=to_email,
subject=subject,
html_content=html_content,
text_content=text_content,
cc_emails=cc_emails,
bcc_emails=bcc_emails,
from_email_override=from_email_override,
).success
def send_email_detailed(
self,
to_email: str,
subject: str,
html_content: str,
text_content: Optional[str] = None,
cc_emails: Optional[List[str]] = None,
bcc_emails: Optional[List[str]] = None,
from_email_override: Optional[str] = None,
) -> SendResult:
try:
sender_email = from_email_override or self.from_email
payload = {
@@ -176,7 +239,15 @@ class PostmarkEmailProvider(EmailProvider):
cc_info = f" (CC: {', '.join(cc_emails)})" if cc_emails else ""
bcc_info = f" (BCC: {', '.join(bcc_emails)})" if bcc_emails else ""
logger.info(f"Email sent to {to_email}{cc_info}{bcc_info} via Postmark")
return True
# Capture Postmark's MessageID so the send can be linked to its
# Postmark record and the persisted email_log entry deduped.
message_id = None
try:
message_id = response.json().get("MessageID")
except ValueError:
pass
self.last_message_id = message_id
return SendResult(success=True, message_id=message_id)
# Surface Postmark's structured error so we can see suppressions, invalid signature, etc.
try:
@@ -187,11 +258,25 @@ class PostmarkEmailProvider(EmailProvider):
)
except ValueError:
logger.error(f"Postmark returned status {response.status_code}: {response.text[:200]}")
return False
return SendResult(success=False, message_id=None)
except requests.RequestException:
logger.exception("Failed to send email via Postmark")
return False
return SendResult(success=False, message_id=None)
# Query params that carry single-use auth/capability tokens (magic-link sign-in,
# lyrics/instrumental review access, referral codes). We persist a redacted copy
# so the admin email-history log never becomes a store of live credentials — the
# email still renders faithfully, only the secret value is masked.
_SENSITIVE_QUERY_PARAM = re.compile(r"([?&](?:token|ref|review_token|instrumental_token)=)[^&\"'\s<]+", re.IGNORECASE)
def _redact_sensitive_tokens(content: Optional[str]) -> Optional[str]:
"""Mask token/ref query-param values in email content before persistence."""
if not content:
return content
return _SENSITIVE_QUERY_PARAM.sub(r"\1[REDACTED]", content)
def _dedupe_emails(emails: List[str]) -> List[str]:
@@ -231,7 +316,7 @@ class EmailService:
"""Get the configured email provider.
Postmark is used when POSTMARK_SERVER_TOKEN is set; otherwise falls
back to console logging (dev/test).
back to console logging (dev/test only).
"""
postmark_token = os.getenv("POSTMARK_SERVER_TOKEN")
from_email = os.getenv("EMAIL_FROM", "gen@nomadkaraoke.com")
@@ -241,13 +326,159 @@ class EmailService:
logger.info("Using Postmark email provider")
return PostmarkEmailProvider(postmark_token, from_email, from_name)
logger.warning("No email provider configured, using console logging")
# In production a missing Postmark token used to silently fall back to
# console logging — every send "succeeded" while magic-link/completion/
# receipt emails vanished (users can't log in or get downloads). Fail
# loudly instead. (Fallback audit 2026-06-09, Theme 7.)
if is_production():
raise RuntimeError(
"POSTMARK_SERVER_TOKEN is not set in production. Refusing to "
"silently drop emails via the console provider — set the Postmark "
"token secret."
)
logger.warning("No email provider configured, using console logging (dev/test)")
return ConsoleEmailProvider()
def is_configured(self) -> bool:
"""Check if a real email provider is configured (not just console logging)."""
return isinstance(self.provider, PostmarkEmailProvider)
def send_email(
self,
to_email: str,
subject: str,
html_content: str,
text_content: Optional[str] = None,
cc_emails: Optional[List[str]] = None,
bcc_emails: Optional[List[str]] = None,
from_email_override: Optional[str] = None,
) -> bool:
"""Send a raw email via the configured provider.
Thin passthrough for callers that need to send an ad-hoc/plain email
(e.g. internal failure alerts) without a dedicated template method.
Prefer a dedicated ``send_*`` template method for customer-facing mail.
"""
return self._log_and_send(
to_email=to_email,
subject=subject,
html_content=html_content,
text_content=text_content,
cc_emails=cc_emails,
bcc_emails=bcc_emails,
from_email_override=from_email_override,
email_type="raw",
)
def _log_and_send(
self,
to_email: str,
subject: str,
html_content: str,
text_content: Optional[str] = None,
cc_emails: Optional[List[str]] = None,
bcc_emails: Optional[List[str]] = None,
from_email_override: Optional[str] = None,
email_type: Optional[str] = None,
) -> bool:
"""Single send chokepoint: dispatch via the provider, then persist a
record of the send for the admin email-history view.
Every ``send_*`` template method routes through here so the persisted
``email_log`` mirrors exactly what left the building. Persistence is
strictly best-effort — a Firestore failure must never break or delay a
real email send.
"""
# Categorize by the calling send_* method name (e.g. send_magic_link →
# "magic_link") so the admin UI can group emails without threading an
# explicit type through every template method.
if email_type is None:
try:
caller = sys._getframe(1).f_code.co_name
email_type = caller[len("send_"):] if caller.startswith("send_") else caller
except Exception:
email_type = None
# Dispatch via the provider's public send_email (as keyword args) so
# callers/mocks that observe that method still see it. PostmarkEmailProvider
# records the returned MessageID on ``last_message_id`` for us to link the
# log entry.
success = self.provider.send_email(
to_email=to_email,
subject=subject,
html_content=html_content,
text_content=text_content,
cc_emails=cc_emails,
bcc_emails=bcc_emails,
from_email_override=from_email_override,
)
# Only persist genuine outbound mail (Postmark). Console/preview providers
# are dev/test only and have no real inbox to reflect.
if success and isinstance(self.provider, PostmarkEmailProvider):
try:
self._record_sent_email(
to_email=to_email,
subject=subject,
html_content=html_content,
text_content=text_content,
cc_emails=cc_emails,
bcc_emails=bcc_emails,
from_email=from_email_override or getattr(self.provider, "from_email", None),
email_type=email_type,
message_id=getattr(self.provider, "last_message_id", None),
)
except Exception:
logger.exception(
"Failed to persist email_log record (the email itself was sent OK)"
)
return success
def _record_sent_email(
self,
*,
to_email: str,
subject: str,
html_content: str,
text_content: Optional[str],
cc_emails: Optional[List[str]],
bcc_emails: Optional[List[str]],
from_email: Optional[str],
email_type: Optional[str],
message_id: Optional[str],
) -> None:
"""Write one Firestore ``email_log`` doc mirroring a sent email.
Keyed by the Postmark MessageID when available (idempotent), else an
auto-id. Stores the rendered HTML so the admin UI can show older mail
after Postmark's ~45-day content retention expires — with single-use
auth/capability tokens redacted so the log never holds live credentials.
"""
from backend.services.firestore_service import FirestoreService
db = FirestoreService().db
doc = {
"recipient": (to_email or "").strip().lower(),
"recipient_raw": to_email,
"cc": _dedupe_emails(cc_emails) if cc_emails else [],
"bcc": _dedupe_emails(bcc_emails) if bcc_emails else [],
"from_email": from_email,
"subject": subject,
"html_content": _redact_sensitive_tokens(html_content),
"text_content": _redact_sensitive_tokens(text_content),
"email_type": email_type,
"message_stream": "outbound",
"postmark_message_id": message_id,
"created_at": datetime.now(timezone.utc),
}
collection = db.collection("email_log")
if message_id:
collection.document(message_id).set(doc)
else:
collection.add(doc)
def send_magic_link(
self,
email: str,
@@ -341,7 +572,7 @@ class EmailService:
© {self._get_year()} {brand_name}
"""
return self.provider.send_email(
return self._log_and_send(
email, subject, html_content, text_content, from_email_override=sender_email
)
@@ -414,7 +645,7 @@ class EmailService:
© {self._get_year()} Nomad Karaoke
"""
return self.provider.send_email(email, subject, html_content, text_content)
return self._log_and_send(email, subject, html_content, text_content)
def send_welcome_email(self, email: str, credits: int = 0, locale: str = "en") -> bool:
"""
@@ -556,7 +787,7 @@ class EmailService:
© {self._get_year()} Nomad Karaoke
"""
return self.provider.send_email(email, subject, html_content, text_content)
return self._log_and_send(email, subject, html_content, text_content)
def _get_year(self) -> int:
"""Get current year for copyright notices."""
@@ -936,7 +1167,7 @@ class EmailService:
cc_emails = ["gen@nomadkaraoke.com"] if cc_admin else None
return self.provider.send_email(
return self._log_and_send(
to_email=to_email,
subject=subject,
html_content=html_content,
@@ -1013,7 +1244,7 @@ class EmailService:
html_content = self._build_email_html(content, extra_styles, locale=locale)
return self.provider.send_email(
return self._log_and_send(
to_email=to_email,
subject=subject,
html_content=html_content,
@@ -1113,7 +1344,7 @@ class EmailService:
f"{t(locale, 'emails.reviewReminder.expiryWarning')}"
)
return self.provider.send_email(
return self._log_and_send(
to_email=to_email,
subject=subject,
html_content=html_content,
@@ -1255,7 +1486,7 @@ class EmailService:
f"If you have any questions, just reply to this email — we're happy to help."
)
return self.provider.send_email(
return self._log_and_send(
to_email=to_email,
subject=subject,
html_content=html_content,
@@ -1348,7 +1579,7 @@ class EmailService:
f"{t(locale, 'emails.reviewExpired.helpOffer')}"
)
return self.provider.send_email(
return self._log_and_send(
to_email=to_email,
subject=subject,
html_content=html_content,
@@ -1490,7 +1721,7 @@ class EmailService:
f"If you have any questions, just reply to this email — we're happy to help."
)
return self.provider.send_email(
return self._log_and_send(
to_email=to_email,
subject=subject,
html_content=html_content,
@@ -1540,7 +1771,7 @@ class EmailService:
html_content = self._build_email_html(content, extra_styles, locale=locale)
return self.provider.send_email(
return self._log_and_send(
to_email=to_email,
subject=subject,
html_content=html_content,
@@ -1633,7 +1864,7 @@ class EmailService:
html_content = self._build_email_html(content, extra_styles, locale=locale)
return self.provider.send_email(
return self._log_and_send(
to_email=to_email,
subject=subject,
html_content=html_content,
@@ -1743,7 +1974,7 @@ Open Job: {app_url}
html_content = self._build_email_html(content, extra_styles)
return self.provider.send_email(
return self._log_and_send(
to_email=to_email,
subject=subject,
html_content=html_content,
@@ -1875,7 +2106,7 @@ View all feedback: {admin_url}
html_content = self._build_email_html(content, extra_styles)
return self.provider.send_email(
return self._log_and_send(
to_email=admin_email,
subject=subject,
html_content=html_content,
@@ -1990,7 +2221,7 @@ If the user looks legitimate, grant them credits from their admin page.
html_content = self._build_email_html(content)
return self.provider.send_email(
return self._log_and_send(
to_email="andrew@beveridge.uk",
subject=subject,
html_content=html_content,
@@ -2045,7 +2276,7 @@ If the user looks legitimate, grant them credits from their admin page.
html_content = self._build_email_html(content, locale=locale)
return self.provider.send_email(
return self._log_and_send(
to_email=email,
subject=subject,
html_content=html_content,
+3 -2
View File
@@ -200,8 +200,9 @@ class FirestoreService:
SUMMARY_FIELD_PATHS = [
'job_id', 'status', 'progress', 'created_at', 'artist', 'title',
'error_message', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
'made_for_you', 'customer_email',
'url', 'filename', 'audio_search_artist', 'audio_search_title',
'made_for_you', 'customer_email', 'locale',
'url', 'filename', 'existing_instrumental_gcs_path',
'audio_search_artist', 'audio_search_title',
'audio_source_type', 'source_name', 'source_id', 'target_file', 'download_url',
'state_data.brand_code', 'state_data.youtube_url', 'state_data.dropbox_link',
'state_data.audio_progress', 'state_data.lyrics_progress',
+2
View File
@@ -119,6 +119,8 @@ class JobManager:
request_metadata=job_create.request_metadata,
# Tenant scoping
tenant_id=job_create.tenant_id,
# UI language the job was submitted in (admin-only signal)
locale=job_create.locale,
# Made-for-you order fields
made_for_you=job_create.made_for_you,
customer_email=job_create.customer_email,
+306
View File
@@ -0,0 +1,306 @@
"""Postmark admin service — email history for the admin user-detail view.
Surfaces "every email ever sent to a user" by merging two sources:
1. **Postmark Messages API** (``GET /messages/outbound``) — authoritative for the
last ~45 days, with the exact rendered HTML and rich delivery metadata
(delivered / opened / clicked / bounced).
2. **Our Firestore ``email_log``** — every send persisted at send time (see
``EmailService._record_sent_email``), so history survives beyond Postmark's
45-day content retention.
The same per-server ``POSTMARK_SERVER_TOKEN`` used for sending is sufficient to
read outbound message history (no separate Account API token needed).
"""
import logging
import os
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
import requests
from google.cloud import firestore
from google.cloud.firestore_v1 import FieldFilter
logger = logging.getLogger(__name__)
POSTMARK_API_BASE = "https://api.postmarkapp.com"
EMAIL_LOG_COLLECTION = "email_log"
# Postmark's outbound list is paginated (count+offset, count max 500). We page
# through until exhausted or the safety cap, so a user with a long history isn't
# silently truncated at one batch.
_PAGE_SIZE = 100
_MAX_RECORDS = 500 # safety cap per source (admin view; avoids unbounded fetches)
_HTTP_TIMEOUT = 12
def _iso(value: Any) -> Optional[str]:
"""Normalize a timestamp (datetime or str) to an ISO-8601 string."""
if value is None:
return None
if isinstance(value, datetime):
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.isoformat()
return str(value)
class PostmarkAdminService:
"""Read-only email history queries for the admin UI."""
def __init__(self, server_token: Optional[str] = None):
self.server_token = server_token if server_token is not None else os.getenv("POSTMARK_SERVER_TOKEN")
self._db: Optional[firestore.Client] = None
# -- infra -------------------------------------------------------------
@property
def db(self) -> firestore.Client:
# Lazy so the service can be constructed (and Postmark-only paths used)
# without a Firestore client in contexts that don't need one.
if self._db is None:
self._db = firestore.Client()
return self._db
def _postmark_headers(self) -> Dict[str, str]:
return {
"Accept": "application/json",
"X-Postmark-Server-Token": self.server_token or "",
}
# -- Postmark queries --------------------------------------------------
def _fetch_postmark_messages(self, email: str) -> List[Dict[str, Any]]:
"""List outbound Postmark messages sent to ``email`` (best-effort, paginated)."""
if not self.server_token:
return []
messages: List[Dict[str, Any]] = []
offset = 0
while len(messages) < _MAX_RECORDS:
try:
resp = requests.get(
f"{POSTMARK_API_BASE}/messages/outbound",
headers=self._postmark_headers(),
params={"recipient": email, "count": _PAGE_SIZE, "offset": offset},
timeout=_HTTP_TIMEOUT,
)
if resp.status_code != 200:
logger.warning(
"Postmark outbound list returned %s for recipient=%s: %s",
resp.status_code, email, resp.text[:200],
)
break
body = resp.json()
batch = body.get("Messages", []) or []
except (requests.RequestException, ValueError):
logger.exception("Failed to fetch Postmark outbound messages for %s", email)
break
messages.extend(batch)
total = body.get("TotalCount", 0)
offset += _PAGE_SIZE
# Stop when this batch was short or we've read everything Postmark has.
if len(batch) < _PAGE_SIZE or offset >= total:
break
if len(messages) >= _MAX_RECORDS:
logger.info("Postmark history for %s capped at %d records", email, _MAX_RECORDS)
summaries = []
for m in messages:
summaries.append({
"message_id": m.get("MessageID"),
"source": "postmark",
"subject": m.get("Subject"),
"to": ", ".join(m.get("Recipients") or []) or email,
"from_email": m.get("From"),
"sent_at": _iso(m.get("ReceivedAt")),
"status": m.get("Status"),
# Postmark tags map to our email_type when we set them; not used yet.
"email_type": (m.get("Metadata") or {}).get("email_type"),
"has_stored_html": False,
})
return summaries
def _fetch_log_docs(self, email: str) -> List[Dict[str, Any]]:
"""Read persisted email_log docs for ``email`` (best-effort)."""
recipient = (email or "").strip().lower()
try:
query = (
self.db.collection(EMAIL_LOG_COLLECTION)
.where(filter=FieldFilter("recipient", "==", recipient))
.order_by("created_at", direction=firestore.Query.DESCENDING)
.limit(_MAX_RECORDS)
)
docs = list(query.stream())
except Exception:
# Missing composite index or emulator quirk — degrade gracefully.
logger.exception("Failed to read email_log for %s", email)
return []
out = []
for doc in docs:
data = doc.to_dict() or {}
out.append({
"doc_id": doc.id,
"message_id": data.get("postmark_message_id"),
"source": "log",
"subject": data.get("subject"),
"to": data.get("recipient_raw") or data.get("recipient"),
"from_email": data.get("from_email"),
"sent_at": _iso(data.get("created_at")),
"status": None,
"email_type": data.get("email_type"),
"has_stored_html": bool(data.get("html_content")),
})
return out
# -- public API --------------------------------------------------------
def get_user_email_history(self, email: str) -> Dict[str, Any]:
"""Merged, de-duplicated list of emails sent to ``email`` (newest first)."""
postmark = self._fetch_postmark_messages(email)
logged = self._fetch_log_docs(email)
# Postmark wins for a message present in both (richer status); note that we
# also have stored HTML so the UI can fall back after the 45-day window.
by_id: Dict[str, Dict[str, Any]] = {}
logged_by_mid: Dict[str, Dict[str, Any]] = {
d["message_id"]: d for d in logged if d.get("message_id")
}
for pm in postmark:
mid = pm.get("message_id")
if mid and mid in logged_by_mid:
pm["has_stored_html"] = True
if mid:
by_id[mid] = pm
merged = list(by_id.values())
for d in logged:
mid = d.get("message_id")
if mid and mid in by_id:
continue # already represented by the Postmark summary
merged.append(d)
merged.sort(key=lambda x: x.get("sent_at") or "", reverse=True)
return {
"email": email,
"count": len(merged),
"postmark_available": bool(self.server_token),
"emails": merged,
}
def _log_doc_to_detail(self, data: Dict[str, Any]) -> Dict[str, Any]:
return {
"message_id": data.get("postmark_message_id"),
"source": "log",
"subject": data.get("subject"),
"from_email": data.get("from_email"),
"to": data.get("recipient_raw") or data.get("recipient"),
"cc": data.get("cc") or [],
"bcc": data.get("bcc") or [],
"sent_at": _iso(data.get("created_at")),
"email_type": data.get("email_type"),
"message_stream": data.get("message_stream"),
"html_body": data.get("html_content"),
"text_body": data.get("text_content"),
"status": None,
"events": [],
}
def _fetch_log_detail_by_message_id(self, message_id: str) -> Optional[Dict[str, Any]]:
try:
snap = self.db.collection(EMAIL_LOG_COLLECTION).document(message_id).get()
if snap.exists:
return self._log_doc_to_detail(snap.to_dict() or {})
except Exception:
logger.exception("email_log fallback lookup failed for %s", message_id)
return None
def get_email_detail(self, message_id: str, source: str = "postmark") -> Optional[Dict[str, Any]]:
"""Full detail for one email — rendered HTML + delivery metadata.
``source="log"`` reads our Firestore record directly (for messages older
than Postmark's retention). Otherwise we query Postmark and fall back to
the Firestore log on 404/unavailable.
"""
if source == "log":
return self._fetch_log_detail_by_message_id(message_id)
if self.server_token:
try:
resp = requests.get(
f"{POSTMARK_API_BASE}/messages/outbound/{message_id}/details",
headers=self._postmark_headers(),
timeout=_HTTP_TIMEOUT,
)
if resp.status_code == 200:
return self._postmark_detail(resp.json())
logger.info(
"Postmark message %s details returned %s; trying stored log",
message_id, resp.status_code,
)
except (requests.RequestException, ValueError):
logger.exception("Failed to fetch Postmark details for %s", message_id)
# Fallback: our persisted copy (older than 45 days, or Postmark down).
return self._fetch_log_detail_by_message_id(message_id)
def _postmark_detail(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""Shape a Postmark message-details payload for the admin modal."""
events = []
opened = 0
clicked = 0
bounced_detail = None
delivered_at = None
for ev in data.get("MessageEvents", []) or []:
etype = ev.get("Type")
events.append({
"type": etype,
"received_at": _iso(ev.get("ReceivedAt")),
"details": ev.get("Details") or {},
})
if etype == "Delivered":
delivered_at = _iso(ev.get("ReceivedAt"))
elif etype == "Opened":
opened += 1
elif etype in ("LinkClicked", "Clicked"):
clicked += 1
elif etype == "Bounced":
bounced_detail = ev.get("Details") or {}
# Derive a coarse status from events when present.
status = data.get("Status")
if bounced_detail:
status = "Bounced"
elif delivered_at:
status = "Delivered"
return {
"message_id": data.get("MessageID"),
"source": "postmark",
"subject": data.get("Subject"),
"from_email": data.get("From"),
"to": ", ".join(data.get("Recipients") or []) or data.get("To"),
"cc": data.get("Cc"),
"bcc": data.get("Bcc"),
"sent_at": _iso(data.get("ReceivedAt")),
"message_stream": data.get("MessageStream"),
"html_body": data.get("HtmlBody"),
"text_body": data.get("TextBody"),
"status": status,
"delivered_at": delivered_at,
"open_count": opened,
"click_count": clicked,
"bounce": bounced_detail,
"events": events,
}
_postmark_admin_service: Optional[PostmarkAdminService] = None
def get_postmark_admin_service() -> PostmarkAdminService:
"""Get the global Postmark admin service instance."""
global _postmark_admin_service
if _postmark_admin_service is None:
_postmark_admin_service = PostmarkAdminService()
return _postmark_admin_service
+14 -1
View File
@@ -64,7 +64,20 @@ class StorageService:
except Exception as e:
logger.error(f"Error downloading file {source_path}: {e}")
raise
def download_bytes(self, source_path: str) -> bytes:
"""Download an object from GCS fully into memory. Only use for small
objects (e.g. transcoded review audio); large files should stream."""
try:
blob = self.bucket.blob(source_path)
return blob.download_as_bytes()
except NotFound:
logger.warning(f"Object not found downloading {source_path}")
raise
except Exception as e:
logger.error(f"Error downloading bytes {source_path}: {e}")
raise
def copy_blob(self, source_path: str, destination_path: str) -> str:
"""Server-side copy of a blob within the bucket (no download/upload)."""
try:
+4
View File
@@ -185,6 +185,7 @@ class StripeService:
notes: Optional[str] = None,
success_url: Optional[str] = None,
cancel_url: Optional[str] = None,
locale: Optional[str] = None,
) -> Tuple[bool, Optional[str], str]:
"""
Create a Stripe Checkout session for a made-for-you order.
@@ -228,6 +229,9 @@ class StripeService:
if notes:
# Truncate notes to fit Stripe's 500 char limit per metadata value
metadata['notes'] = notes[:500] if len(notes) > 500 else notes
if locale:
# UI language the customer ordered in — surfaced admin-side on the job
metadata['locale'] = locale
# Build checkout session params
session_params = {
+166 -37
View File
@@ -57,61 +57,93 @@ class VisibilityChangeService:
"""
Change a public job to private (fast path).
Deletes distributed outputs (YouTube/Dropbox/GDrive) but keeps GCS finals,
then redistributes to private destination.
Distribute-then-delete: the track is first redistributed to the private
destination (private Dropbox archive + NOMADNP code, no YouTube/GDrive),
and only *after* that succeeds are the public outputs (YouTube, public
Dropbox folder, public GDrive files) deleted and the public NOMAD number
recycled. GCS finals are always kept.
This ordering is deliberate: YouTube deletion is irreversible, so nothing
public may be destroyed until the private archive exists. If redistribution
fails, the job is reverted to public and left fully intact (no partial
deletion, no leaked NOMADNP code — see redistribute_video's failure path).
"""
logger.info(f"[job:{job_id}] Starting visibility change: public -> private (by {user_email})")
db = self.job_manager.firestore.db
job_ref = db.collection("jobs").document(job_id)
# Set guard flag
# Capture the public output references BEFORE redistribution overwrites
# state_data with the new private values — we need them to delete the
# public outputs afterwards.
state_data = job.state_data or {}
public_outputs = {
"youtube_url": state_data.get("youtube_url"),
"brand_code": state_data.get("brand_code"),
"gdrive_files": state_data.get("gdrive_files"),
"dropbox_path": getattr(job, "dropbox_path", None),
"artist": job.artist,
"title": job.title,
}
# Set guard flag + flip to private so redistribution targets the private
# destination. Public outputs remain live until the private archive exists.
# No "changed to private" timeline event yet — it is only recorded once the
# move actually succeeds (this is reverted if redistribution fails).
job_ref.update({
"state_data.visibility_change_in_progress": True,
"is_private": True,
"updated_at": datetime.now(timezone.utc),
})
# Step 1: Redistribute to the private destination FIRST (public outputs
# still live). This is the only phase whose failure is safe to fully roll
# back — nothing public has been touched yet. redistribute_video verifies
# the archive actually materialized and recycles any NOMADNP code it
# allocated on failure, so a False return means "no-op, still public".
try:
# Step 1: Delete distributed outputs (keep GCS finals)
await self._delete_distributed_outputs(job_id, job, keep_gcs_finals=True)
# Step 2: Update job to private
job_ref.update({
"is_private": True,
"updated_at": datetime.now(timezone.utc),
"timeline": ArrayUnion([{
"status": "complete",
"timestamp": datetime.now(timezone.utc).isoformat(),
"message": f"Visibility changed to private by {user_email}",
}]),
})
# Step 3: Trigger redistribution via video worker
from backend.workers.video_worker import redistribute_video
success = await redistribute_video(job_id)
if not success:
raise RuntimeError("Redistribution failed - check worker logs")
# Clear guard flag (redistribution updates state_data with new brand_code etc.)
job_ref.update({
"state_data.visibility_change_in_progress": DELETE_FIELD,
})
logger.info(f"[job:{job_id}] Visibility change to private complete")
return {
"status": "success",
"message": "Job changed to private. Outputs redistributed to private destination.",
"reprocessing_required": False,
}
except Exception as e:
logger.error(f"[job:{job_id}] Visibility change to private failed: {e}", exc_info=True)
# Clear guard flag on failure
logger.error(f"[job:{job_id}] Redistribution raised during visibility change: {e}", exc_info=True)
success = False
if not success:
# Roll back to public: no public outputs were deleted, so restoring
# is_private=False leaves the job fully intact and public.
logger.error(f"[job:{job_id}] Visibility change to private failed: redistribution did not succeed")
job_ref.update({
"is_private": False,
"state_data.visibility_change_in_progress": DELETE_FIELD,
"updated_at": datetime.now(timezone.utc),
})
raise
raise RuntimeError("Redistribution failed - check worker logs")
# Step 2: Private archive now exists. From here we do NOT revert to public,
# even if public cleanup hiccups — the private move has committed. Deleting
# the public outputs + recycling the public NOMAD number is best-effort
# (each failure is logged inside the helper, never raised), so a stray
# orphaned public artifact cannot undo the successful private move.
await self._delete_public_outputs(job_id, public_outputs)
# Record the completed move and clear the guard flag. redistribute_video
# already updated state_data with the new private brand_code etc.
job_ref.update({
"state_data.visibility_change_in_progress": DELETE_FIELD,
"updated_at": datetime.now(timezone.utc),
"timeline": ArrayUnion([{
"status": "complete",
"timestamp": datetime.now(timezone.utc).isoformat(),
"message": f"Visibility changed to private by {user_email}",
}]),
})
logger.info(f"[job:{job_id}] Visibility change to private complete")
return {
"status": "success",
"message": "Job changed to private. Outputs redistributed to private destination.",
"reprocessing_required": False,
}
async def change_to_public(self, job_id: str, job, user_email: str) -> dict:
"""
@@ -216,6 +248,103 @@ class VisibilityChangeService:
"reprocessing_required": True,
}
async def _delete_public_outputs(self, job_id: str, public_outputs: dict):
"""Delete the captured PUBLIC outputs and recycle the public NOMAD number.
Used by change_to_private AFTER a successful private redistribution. Operates
on references captured before redistribution (which overwrites state_data with
private values). Does not touch GCS finals and does not clear state_data keys
(redistribution already set the new private values). Best-effort: individual
failures are logged, not raised, so one orphaned artifact can't undo the move.
"""
import re
# Track whether each public destination was fully cleaned. The NOMAD number
# is only recycled when every deletion succeeded — otherwise a future public
# track could reuse the number while the old public files still linger,
# producing a duplicate. (Mirrors the admin delete-outputs recycle gate.)
youtube_ok = True
dropbox_ok = True
gdrive_ok = True
youtube_url = public_outputs.get("youtube_url")
if youtube_url:
try:
video_id_match = re.search(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)', youtube_url)
if video_id_match:
video_id = video_id_match.group(1)
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
from backend.services.youtube_service import get_youtube_service
youtube_service = get_youtube_service()
if youtube_service.is_configured:
finalise = KaraokeFinalise(
dry_run=False, non_interactive=True,
user_youtube_credentials=youtube_service.get_credentials_dict()
)
finalise.delete_youtube_video(video_id)
logger.info(f"[job:{job_id}] Deleted public YouTube video {video_id}")
except Exception as e:
youtube_ok = False
logger.warning(f"[job:{job_id}] Failed to delete public YouTube video: {e}")
brand_code = public_outputs.get("brand_code")
dropbox_path = public_outputs.get("dropbox_path")
if brand_code and dropbox_path:
try:
from backend.services.dropbox_service import get_dropbox_service
dropbox = get_dropbox_service()
if dropbox.is_configured:
from karaoke_gen.utils import sanitize_filename
safe_artist = sanitize_filename(public_outputs.get("artist")) if public_outputs.get("artist") else "Unknown"
safe_title = sanitize_filename(public_outputs.get("title")) if public_outputs.get("title") else "Unknown"
folder_name = f"{brand_code} - {safe_artist} - {safe_title}"
full_path = f"{dropbox_path}/{folder_name}"
dropbox.delete_folder(full_path)
logger.info(f"[job:{job_id}] Deleted public Dropbox folder {full_path}")
except Exception as e:
dropbox_ok = False
logger.warning(f"[job:{job_id}] Failed to delete public Dropbox folder: {e}")
gdrive_files = public_outputs.get("gdrive_files")
if gdrive_files:
try:
from backend.services.gdrive_service import get_gdrive_service
gdrive = get_gdrive_service()
if gdrive.is_configured:
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
gdrive.delete_files(file_ids)
logger.info(f"[job:{job_id}] Deleted public Google Drive files")
except Exception as e:
gdrive_ok = False
logger.warning(f"[job:{job_id}] Failed to delete public Google Drive files: {e}")
# A track going private should also leave the public Nomad GCS fast-sync
# mirror (and thus kjbox). Prefix-keyed by the public brand_code, non-fatal.
if brand_code:
try:
from backend.services.nomad_master_mirror import cleanup_nomad_masters
cleanup_nomad_masters(brand_code)
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to clean up Nomad mirror for {brand_code}: {e}")
# Recycle the public NOMAD number so the next public track fills the gap —
# but only if every public deletion succeeded. If any lingered, keep the
# number reserved (a permanent gap the validator will flag) rather than
# risk a future duplicate; the leftover artifacts can then be cleaned up.
if brand_code and youtube_ok and dropbox_ok and gdrive_ok:
try:
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
prefix, number = BrandCodeService.parse_brand_code(brand_code)
get_brand_code_service().recycle_brand_code(prefix, number)
logger.info(f"[job:{job_id}] Recycled public brand code {brand_code}")
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to recycle public brand code {brand_code}: {e}")
elif brand_code:
logger.warning(
f"[job:{job_id}] NOT recycling public brand code {brand_code}: "
f"public cleanup incomplete (youtube={youtube_ok}, dropbox={dropbox_ok}, gdrive={gdrive_ok})"
)
async def _delete_distributed_outputs(self, job_id: str, job, keep_gcs_finals: bool = False):
"""Delete distributed outputs (YouTube, Dropbox, GDrive) and recycle brand code."""
import re
+51 -3
View File
@@ -15,11 +15,13 @@ Observability:
- Propagates trace context through Cloud Tasks for distributed tracing
- All worker invocations create spans linked to original request trace
"""
import asyncio
import logging
import os
import json
from typing import Optional
import httpx
from google.api_core import exceptions as gcp_exceptions
from google.protobuf import duration_pb2
from backend.config import get_settings
@@ -29,6 +31,21 @@ from backend.services.tracing import inject_trace_context
logger = logging.getLogger(__name__)
# Transient control-plane errors from the Cloud Run Jobs Admin API (`JobsClient.run_job`)
# that are safe to retry. run_job only *enqueues* an execution, so a one-off 5xx/429 from
# the API control plane should be retried rather than hard-failing a real job's trigger.
# (2026-08-24: a single 503 from lyrics-transcription-job's trigger failed a real job's
# transcription with no retry — this is the guard.)
_TRANSIENT_RUN_JOB_ERRORS = (
gcp_exceptions.ServiceUnavailable, # 503
gcp_exceptions.InternalServerError, # 500
gcp_exceptions.GatewayTimeout, # 504
gcp_exceptions.TooManyRequests, # 429
)
_RUN_JOB_MAX_ATTEMPTS = 3
_RUN_JOB_BASE_DELAY_SECONDS = 1.0
# Mapping of worker types to their Cloud Tasks queue names
# These queues are created by Pulumi in infrastructure/__main__.py
WORKER_QUEUES = {
@@ -411,7 +428,9 @@ class WorkerService:
]
),
)
operation = client.run_job(request=request)
operation = await self._run_job_with_retry(
client, request, log_prefix=f"[batch:{batch_id}]"
)
logger.info(f"[batch:{batch_id}] Started Cloud Run Job bulk-search-job: {operation.metadata}")
return True
except Exception as e:
@@ -538,6 +557,33 @@ class WorkerService:
worker_module="video_worker",
)
async def _run_job_with_retry(self, client, request, log_prefix: str):
"""Invoke ``JobsClient.run_job`` with a small bounded retry on transient errors.
``run_job`` only enqueues an execution, so a one-off 5xx/429 from the Cloud Run
Jobs Admin control plane is safe to retry rather than hard-failing the trigger.
Non-transient errors (NotFound / PermissionDenied / InvalidArgument) are NOT
caught here — they propagate immediately to the caller's error handling.
Sleeps with ``asyncio.sleep`` so the event loop isn't blocked between attempts.
"""
last_exc: Optional[Exception] = None
for attempt in range(1, _RUN_JOB_MAX_ATTEMPTS + 1):
try:
return client.run_job(request=request)
except _TRANSIENT_RUN_JOB_ERRORS as e:
last_exc = e
if attempt >= _RUN_JOB_MAX_ATTEMPTS:
break
delay = _RUN_JOB_BASE_DELAY_SECONDS * (2 ** (attempt - 1))
logger.warning(
f"{log_prefix} transient error triggering Cloud Run Job "
f"({type(e).__name__}, attempt {attempt}/{_RUN_JOB_MAX_ATTEMPTS}); "
f"retrying in {delay:.0f}s"
)
await asyncio.sleep(delay)
# Exhausted transient retries — re-raise so the caller logs + returns False.
raise last_exc
async def _trigger_worker_cloud_run_job(
self,
job_id: str,
@@ -590,8 +636,10 @@ class WorkerService:
)
)
# Run the job (async operation)
operation = client.run_job(request=request)
# Run the job (async operation), retrying transient control-plane errors.
operation = await self._run_job_with_retry(
client, request, log_prefix=f"[job:{job_id}]"
)
logger.info(
f"[job:{job_id}] Started Cloud Run Job {cloud_run_job_name}: "
f"{operation.metadata}"
+7 -5
View File
@@ -2,13 +2,15 @@
YouTube download service for cloud backend.
This service provides a single entry point for all YouTube downloads in the cloud.
It automatically routes downloads through the remote flacfetch service when configured,
avoiding YouTube bot detection issues on Cloud Run IPs.
flacfetch is the SOLE downloader: downloads are always routed through the remote
flacfetch service, which has YouTube cookies and avoids bot detection on Cloud Run IPs.
The flow is:
1. Check if remote flacfetch is configured (FLACFETCH_API_URL)
2. If yes: Use FlacfetchClient.download_by_id() - downloads on VM, uploads to GCS
3. If no: Use local yt_dlp (with warning about bot detection risk)
3. If no: raise YouTubeDownloadError — there is NO local yt-dlp fallback. We never
run yt-dlp inside the Cloud Run container (it's blocked by bot detection and a
silent fallback previously masked a real download bug — 2026-06-08 incident).
All entry points (audio search selection, direct URL submission) should use this
service for YouTube downloads to ensure consistent behavior.
@@ -34,8 +36,8 @@ class YouTubeDownloadService:
When remote flacfetch is configured (FLACFETCH_API_URL), downloads happen
on the flacfetch VM which has YouTube cookies and avoids bot detection.
When remote is not configured, falls back to local yt_dlp with a warning
that downloads may be blocked on Cloud Run IPs.
When remote is not configured, this raises YouTubeDownloadError. There is no
local yt-dlp fallback — flacfetch is the sole downloader.
Usage:
service = get_youtube_download_service()
@@ -502,8 +502,12 @@ class TestMadeForYouYouTubeErrorHandling:
youtube_order_metadata
):
"""
Test that exceptions during processing send failure notification to admin.
Test that a job-creation failure sends a failure notification to admin AND
re-raises so the Stripe webhook returns non-2xx and Stripe retries the (likely
transient) failure — a paid order must not be silently dropped when no job was
ever created.
"""
import pytest
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
# Make job creation fail
@@ -516,15 +520,16 @@ class TestMadeForYouYouTubeErrorHandling:
patch('backend.api.routes.users.get_effective_distribution_settings', return_value=mock_distribution_settings), \
patch('backend.api.routes.users.resolve_cdg_txt_defaults', return_value=(False, False)):
# Should not raise - error is handled internally
await _handle_made_for_you_order(
session_id="sess_test_error",
metadata=youtube_order_metadata,
user_service=mock_user_service_for_webhook,
email_service=mock_email_service,
)
# Re-raises (job never created) so the webhook returns non-2xx -> Stripe retries
with pytest.raises(Exception, match="Database error"):
await _handle_made_for_you_order(
session_id="sess_test_error",
metadata=youtube_order_metadata,
user_service=mock_user_service_for_webhook,
email_service=mock_email_service,
)
# Verify failure email was sent to admin
# Verify failure email was sent to admin before re-raising
mock_email_service.send_email.assert_called()
call_args = mock_email_service.send_email.call_args
assert call_args.kwargs['to_email'] == ADMIN_EMAIL
@@ -231,7 +231,7 @@ def test_stale_48h_expiry_sends_email_with_timeout_reason():
sent = {}
class _CapturingProvider:
def send_email(self, to_email, subject, html_content, text_content):
def send_email(self, to_email, subject, html_content, text_content=None, **kwargs):
sent['subject'] = subject
sent['text'] = text_content
return True
@@ -258,3 +258,58 @@ def test_stale_48h_expiry_sends_email_with_timeout_reason():
assert "48" not in sent['subject'] and "not confirmed" not in sent['subject'], (
f"over_limit email should not say '48 hours'. subject={sent.get('subject')!r}"
)
# ---------------------------------------------------------------------------
# Regression (job a453d1d5): a failing email-service construction must NOT
# crash an otherwise-successful audio download. reconcile_and_maybe_pause runs
# in the audio-download-job Cloud Run Job; EmailService() raises in production
# when POSTMARK_SERVER_TOKEN is unset. Reconcile must degrade to no-email.
# ---------------------------------------------------------------------------
def _patch_reconcile_singletons(monkeypatch, jm, us, actual_seconds):
"""Patch the function-scoped imports reconcile_and_maybe_pause pulls in.
These are imported inside the function (to avoid circular imports), so they
must be patched at their source modules, not on duration_reconciliation.
"""
from backend.services import duration_reconciliation as dr
monkeypatch.setattr("backend.services.job_manager.JobManager", lambda: jm)
monkeypatch.setattr("backend.services.user_service.get_user_service", lambda: us)
monkeypatch.setattr("backend.services.storage_service.StorageService", lambda: MagicMock())
monkeypatch.setattr(
"backend.services.email_service.get_email_service",
MagicMock(side_effect=RuntimeError("POSTMARK_SERVER_TOKEN is not set in production")),
)
monkeypatch.setattr(dr, "_ffprobe_seconds", lambda job, storage: actual_seconds)
@pytest.mark.asyncio
async def test_reconcile_and_maybe_pause_survives_email_service_failure(monkeypatch):
from backend.services import duration_reconciliation as dr
jm = MagicMock()
jm.get_job.return_value = _job(credits_charged=2)
# Duration matches estimate → proceed, no email needed anyway.
_patch_reconcile_singletons(monkeypatch, jm, MagicMock(), actual_seconds=900.0) # 15min -> 2 credits
# Must not raise despite email service construction failing.
blocked = await dr.reconcile_and_maybe_pause("job1")
assert blocked is False # proceeds normally
@pytest.mark.asyncio
async def test_reconcile_and_maybe_pause_over_limit_still_cancels_without_email(monkeypatch):
"""Over-limit cancel must still refund+cancel even if email can't be built."""
from backend.services import duration_reconciliation as dr
jm = MagicMock()
jm.get_job.return_value = _job(credits_charged=2)
us = MagicMock()
us.add_credits.return_value = (True, 99, "ok")
_patch_reconcile_singletons(monkeypatch, jm, us, actual_seconds=4000.0) # >60min
blocked = await dr.reconcile_and_maybe_pause("job1")
assert blocked is True # cancelled
jm.cancel_job.assert_called_once()
us.add_credits.assert_called_once() # full refund still happens
+187
View File
@@ -0,0 +1,187 @@
"""
Unit tests for the admin create-user endpoint.
Tests POST /api/users/admin/users, which lets admins create a user account
directly (e.g. to grant credits, submit jobs on behalf of, or impersonate
someone who has never logged in).
"""
import pytest
from unittest.mock import Mock
from fastapi.testclient import TestClient
from fastapi import FastAPI
from backend.api.routes.users import router
from backend.api.dependencies import require_admin
from backend.services.user_service import get_user_service
from backend.services.auth_service import AuthResult, UserType
from backend.models.user import User
app = FastAPI()
app.include_router(router, prefix="/api")
def get_mock_admin():
"""Override for require_admin dependency."""
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=-1,
message="Admin session valid",
user_email="admin@nomadkaraoke.com",
is_admin=True,
)
@pytest.fixture
def mock_user_service():
service = Mock()
service.get_user.return_value = None # default: user doesn't exist
new_user = Mock(spec=User)
new_user.email = "new@example.com"
new_user.credits = 0
service.get_or_create_user.return_value = new_user
service.add_credits.return_value = (True, 3, "Added 3 credits")
return service
@pytest.fixture
def client(mock_user_service):
app.dependency_overrides[require_admin] = get_mock_admin
app.dependency_overrides[get_user_service] = lambda: mock_user_service
yield TestClient(app)
app.dependency_overrides.clear()
class TestAdminCreateUser:
"""Tests for POST /api/users/admin/users."""
def test_create_user_minimal(self, client, mock_user_service):
"""Creating with just an email creates the account with zero credits."""
response = client.post(
"/api/users/admin/users",
json={"email": "new@example.com"},
)
assert response.status_code == 201
data = response.json()
assert data["status"] == "success"
assert data["email"] == "new@example.com"
assert data["credits"] == 0
mock_user_service.get_or_create_user.assert_called_once_with("new@example.com")
mock_user_service.add_credits.assert_not_called()
mock_user_service.update_user.assert_not_called()
def test_create_user_with_credits_and_display_name(self, client, mock_user_service):
"""Initial credits are granted and the welcome-credit flag is set."""
response = client.post(
"/api/users/admin/users",
json={
"email": "new@example.com",
"display_name": "Jane Singer",
"initial_credits": 3,
"credit_reason": "made-for-you order",
},
)
assert response.status_code == 201
data = response.json()
assert data["credits"] == 3
assert "3 credit(s)" in data["message"]
mock_user_service.add_credits.assert_called_once_with(
email="new@example.com",
amount=3,
reason="made-for-you order",
admin_email="admin@nomadkaraoke.com",
)
# display_name saved + welcome credit suppressed (admin credits replace it)
update_kwargs = mock_user_service.update_user.call_args.kwargs
assert update_kwargs["display_name"] == "Jane Singer"
assert update_kwargs["welcome_credits_granted"] is True
def test_create_without_credits_leaves_welcome_credit_eligible(self, client, mock_user_service):
"""No initial credits → welcome_credits_granted is left untouched."""
response = client.post(
"/api/users/admin/users",
json={"email": "new@example.com", "display_name": "Somebody"},
)
assert response.status_code == 201
update_kwargs = mock_user_service.update_user.call_args.kwargs
assert "welcome_credits_granted" not in update_kwargs
def test_email_normalized_to_lowercase(self, client, mock_user_service):
"""Mixed-case emails are lowercased before lookup and creation."""
response = client.post(
"/api/users/admin/users",
json={"email": "Mixed.Case@Example.COM"},
)
assert response.status_code == 201
assert response.json()["email"] == "mixed.case@example.com"
mock_user_service.get_user.assert_called_once_with("mixed.case@example.com")
mock_user_service.get_or_create_user.assert_called_once_with("mixed.case@example.com")
def test_duplicate_user_returns_409(self, client, mock_user_service):
"""Creating a user that already exists returns 409."""
mock_user_service.get_user.return_value = Mock(spec=User)
response = client.post(
"/api/users/admin/users",
json={"email": "existing@example.com"},
)
assert response.status_code == 409
assert "already exists" in response.json()["detail"]
mock_user_service.get_or_create_user.assert_not_called()
def test_invalid_email_rejected(self, client, mock_user_service):
"""A malformed email fails validation with 422."""
response = client.post(
"/api/users/admin/users",
json={"email": "not-an-email"},
)
assert response.status_code == 422
mock_user_service.get_or_create_user.assert_not_called()
def test_credits_out_of_range_rejected(self, client, mock_user_service):
"""initial_credits outside 0-1000 is rejected."""
for bad_amount in (-1, 1001):
response = client.post(
"/api/users/admin/users",
json={"email": "new@example.com", "initial_credits": bad_amount},
)
assert response.status_code == 400
mock_user_service.get_or_create_user.assert_not_called()
def test_add_credits_failure_returns_500(self, client, mock_user_service):
"""If granting credits fails after creation, the endpoint reports it."""
mock_user_service.add_credits.return_value = (False, 0, "Firestore unavailable")
response = client.post(
"/api/users/admin/users",
json={"email": "new@example.com", "initial_credits": 2},
)
assert response.status_code == 500
assert "adding credits failed" in response.json()["detail"]
def test_requires_admin(self, mock_user_service):
"""Non-admin requests are rejected."""
def deny_admin():
from fastapi import HTTPException
raise HTTPException(status_code=403, detail="Admin access required")
app.dependency_overrides[require_admin] = deny_admin
app.dependency_overrides[get_user_service] = lambda: mock_user_service
try:
client = TestClient(app)
response = client.post(
"/api/users/admin/users",
json={"email": "new@example.com"},
)
assert response.status_code == 403
finally:
app.dependency_overrides.clear()
+116 -1
View File
@@ -127,11 +127,13 @@ class TestUpdateJob:
def test_update_user_email(self, client, mock_job):
"""Test updating user_email field."""
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
patch('backend.api.routes.admin.get_user_service') as mock_get_us:
mock_jm = Mock()
mock_jm.get_job.return_value = mock_job
mock_jm.update_job.return_value = True
mock_jm_class.return_value = mock_jm
mock_get_us.return_value.get_user.return_value = Mock() # user exists
response = client.patch(
"/api/admin/jobs/test-job-123",
@@ -324,3 +326,116 @@ class TestUpdateJobAuthorization:
app.dependency_overrides[require_admin] = original_override
else:
app.dependency_overrides[require_admin] = get_mock_admin
class TestUpdateJobUserEmailAutoCreate:
"""Tests for auto-creating a user account when user_email is reassigned."""
def _patch(self, mock_job, existing_user):
"""Return patched JobManager + user_service context managers."""
jm_patch = patch('backend.api.routes.admin.JobManager')
us_patch = patch('backend.api.routes.admin.get_user_service')
return jm_patch, us_patch
def test_creates_user_when_email_unknown(self, client, mock_job):
"""Reassigning to an email with no account auto-creates the account."""
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
patch('backend.api.routes.admin.get_user_service') as mock_get_us:
mock_jm = Mock()
mock_jm.get_job.return_value = mock_job
mock_jm.update_job.return_value = True
mock_jm_class.return_value = mock_jm
mock_us = Mock()
mock_us.get_user.return_value = None # no account exists
mock_get_us.return_value = mock_us
response = client.patch(
"/api/admin/jobs/test-job-123",
json={"user_email": "brandnew@example.com"},
)
assert response.status_code == 200
mock_us.get_or_create_user.assert_called_once_with("brandnew@example.com")
assert "Created new user account for brandnew@example.com" in response.json()["message"]
def test_does_not_create_when_user_exists(self, client, mock_job):
"""Reassigning to an existing user's email does not create anything."""
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
patch('backend.api.routes.admin.get_user_service') as mock_get_us:
mock_jm = Mock()
mock_jm.get_job.return_value = mock_job
mock_jm.update_job.return_value = True
mock_jm_class.return_value = mock_jm
mock_us = Mock()
mock_us.get_user.return_value = Mock() # account exists
mock_get_us.return_value = mock_us
response = client.patch(
"/api/admin/jobs/test-job-123",
json={"user_email": "existing@example.com"},
)
assert response.status_code == 200
mock_us.get_or_create_user.assert_not_called()
assert "Created new user account" not in response.json()["message"]
def test_email_is_normalized_to_lowercase(self, client, mock_job):
"""Mixed-case emails are lowercased before saving to the job."""
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
patch('backend.api.routes.admin.get_user_service') as mock_get_us:
mock_jm = Mock()
mock_jm.get_job.return_value = mock_job
mock_jm.update_job.return_value = True
mock_jm_class.return_value = mock_jm
mock_us = Mock()
mock_us.get_user.return_value = None
mock_get_us.return_value = mock_us
response = client.patch(
"/api/admin/jobs/test-job-123",
json={"user_email": " Mixed.Case@Example.COM "},
)
assert response.status_code == 200
call_args = mock_jm.update_job.call_args
assert call_args[0][1]["user_email"] == "mixed.case@example.com"
mock_us.get_user.assert_called_once_with("mixed.case@example.com")
mock_us.get_or_create_user.assert_called_once_with("mixed.case@example.com")
def test_other_field_updates_skip_user_lookup(self, client, mock_job):
"""Updating non-email fields never touches the user service."""
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
patch('backend.api.routes.admin.get_user_service') as mock_get_us:
mock_jm = Mock()
mock_jm.get_job.return_value = mock_job
mock_jm.update_job.return_value = True
mock_jm_class.return_value = mock_jm
response = client.patch(
"/api/admin/jobs/test-job-123",
json={"artist": "Someone Else"},
)
assert response.status_code == 200
mock_get_us.assert_not_called()
def test_blank_user_email_rejected(self, client, mock_job):
"""Whitespace-only or non-email values for user_email return 400."""
for bad_value in (" ", "not-an-email"):
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
patch('backend.api.routes.admin.get_user_service') as mock_get_us:
mock_jm = Mock()
mock_jm.get_job.return_value = mock_job
mock_jm_class.return_value = mock_jm
response = client.patch(
"/api/admin/jobs/test-job-123",
json={"user_email": bad_value},
)
assert response.status_code == 400
assert "valid email" in response.json()["detail"]
mock_jm.update_job.assert_not_called()
+149
View File
@@ -0,0 +1,149 @@
"""
Unit tests for the admin stats overview endpoint.
Covers the exclude_test=True path (the admin dashboard default), which streams
users and jobs with Firestore field masks. The field masks are load-bearing:
without them the endpoint streams full job documents (~100MB collection-wide)
and takes 15-20s, blocking the event loop for every other request.
"""
from datetime import datetime, timedelta
from unittest.mock import Mock
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from backend.api.routes.admin import (
router,
_compute_admin_stats_overview,
_OVERVIEW_USER_FIELDS,
_OVERVIEW_JOB_FIELDS,
)
from backend.api.dependencies import require_admin
from backend.services.user_service import get_user_service, USERS_COLLECTION
app = FastAPI()
app.include_router(router, prefix="/api")
def get_mock_admin():
from backend.api.dependencies import AuthResult, UserType
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=999,
message="Admin authenticated",
user_email="admin@example.com",
is_admin=True,
)
app.dependency_overrides[require_admin] = get_mock_admin
def make_docs(dicts):
docs = []
for d in dicts:
m = Mock()
m.to_dict.return_value = d
docs.append(m)
return docs
def make_db(user_dicts, job_dicts):
"""Fake Firestore db supporting .collection(...).select(...).limit(...).stream()."""
users_coll = Mock()
users_coll.select.return_value.limit.return_value.stream.return_value = make_docs(user_dicts)
jobs_coll = Mock()
jobs_coll.select.return_value.limit.return_value.stream.return_value = make_docs(job_dicts)
db = Mock()
db.collection.side_effect = lambda name: users_coll if name == USERS_COLLECTION else jobs_coll
return db, users_coll, jobs_coll
@pytest.fixture
def now():
return datetime.utcnow()
@pytest.fixture
def sample_data(now):
users = [
{"email": "real1@example.com", "last_login_at": now - timedelta(days=1),
"credit_transactions": [{"amount": 5, "created_at": now - timedelta(days=2)}]},
{"email": "real2@example.com", "last_login_at": now - timedelta(days=20),
"credit_transactions": [{"amount": -1, "created_at": now - timedelta(days=2)},
{"amount": 3, "created_at": now - timedelta(days=45)}]},
# Test user — must be excluded from all counts
{"email": "abc@inbox.testmail.app", "last_login_at": now - timedelta(days=1),
"credit_transactions": [{"amount": 100, "created_at": now - timedelta(days=1)}]},
]
jobs = [
{"user_email": "real1@example.com", "created_at": now - timedelta(days=1), "status": "complete"},
{"user_email": "real1@example.com", "created_at": now - timedelta(days=10), "status": "failed"},
{"user_email": "real2@example.com", "created_at": now - timedelta(days=40), "status": "transcribing"},
{"user_email": "real2@example.com", "created_at": now - timedelta(days=1), "status": "awaiting_review"},
# Test-user job — must be excluded
{"user_email": "abc@inbox.testmail.app", "created_at": now - timedelta(days=1), "status": "complete"},
]
return users, jobs
def test_compute_overview_counts_and_filters_test_data(sample_data):
users, jobs = sample_data
db, _, _ = make_db(users, jobs)
result = _compute_admin_stats_overview(db, exclude_test=True)
assert result.total_users == 2
assert result.active_users_7d == 1
assert result.active_users_30d == 2
assert result.total_jobs == 4
assert result.jobs_last_7d == 2
assert result.jobs_last_30d == 3
assert result.jobs_by_status.complete == 1
assert result.jobs_by_status.failed == 1
assert result.jobs_by_status.processing == 1 # transcribing
assert result.jobs_by_status.awaiting_review == 1
# 5 (recent) — excludes the 3 older than 30d, the negative txn, and the test user's 100
assert result.total_credits_issued_30d == 5
def test_compute_overview_uses_field_masks(sample_data):
"""The .select() field masks are a performance guarantee — full job docs are huge."""
users, jobs = sample_data
db, users_coll, jobs_coll = make_db(users, jobs)
_compute_admin_stats_overview(db, exclude_test=True)
users_coll.select.assert_called_once_with(_OVERVIEW_USER_FIELDS)
jobs_coll.select.assert_called_once_with(_OVERVIEW_JOB_FIELDS)
def test_overview_endpoint_returns_stats(sample_data):
users, jobs = sample_data
db, _, _ = make_db(users, jobs)
mock_service = Mock()
mock_service.db = db
app.dependency_overrides[get_user_service] = lambda: mock_service
try:
client = TestClient(app)
resp = client.get("/api/admin/stats/overview?exclude_test=true")
assert resp.status_code == 200
body = resp.json()
assert body["total_users"] == 2
assert body["total_jobs"] == 4
assert body["jobs_by_status"]["failed"] == 1
finally:
app.dependency_overrides.pop(get_user_service, None)
def test_overview_handles_empty_collections():
db, _, _ = make_db([], [])
result = _compute_admin_stats_overview(db, exclude_test=True)
assert result.total_users == 0
assert result.total_jobs == 0
assert result.total_credits_issued_30d == 0
+16
View File
@@ -321,6 +321,22 @@ class TestAudioSearchServiceSearch:
assert "No results found" in str(exc_info.value)
def test_remote_search_failure_does_not_fall_back_to_local(self):
"""A remote flacfetch error must fail loudly, not silently downgrade to local YouTube."""
from backend.services.flacfetch_client import FlacfetchServiceError
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
mock_remote = Mock()
mock_remote.search = AsyncMock(side_effect=FlacfetchServiceError("remote service down"))
service._remote_client = mock_remote
service._fetcher = Mock() # local fetcher — must NOT be used as a silent fallback
with pytest.raises(AudioSearchError, match="Remote flacfetch search failed"):
service.search("ABBA", "Waterloo")
# Critical: we did NOT silently fall back to the local YouTube-only fetcher.
service._fetcher.search.assert_not_called()
def test_search_multiple_results(self):
"""Test search returns multiple results with correct indices."""
mock_results = []
@@ -394,3 +394,52 @@ class TestGetReviewAudioUrlAsync:
result = await service.get_review_audio_url_async("jobs/abc/input/song.flac")
assert result == "https://signed/url"
class TestGetReviewAudioBytes:
"""get_review_audio_bytes() proxies the audio through the API (CORS-safe)."""
def test_returns_ogg_bytes_on_success(self):
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
mock_storage.file_exists.return_value = True # cache hit
mock_storage.download_bytes.return_value = b"OggS-transcoded-bytes"
service = AudioTranscodingService(storage_service=mock_storage)
data, content_type = service.get_review_audio_bytes("jobs/abc/stems/vocals_clean.flac")
assert data == b"OggS-transcoded-bytes"
assert content_type == "audio/ogg"
mock_storage.download_bytes.assert_called_once_with("jobs/abc/review-audio/vocals_clean.ogg")
def test_falls_back_to_source_bytes_on_transcode_error(self):
"""A transient transcode failure serves the original source, not a 500."""
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
mock_storage.file_exists.return_value = False # cache miss → transcode path
mock_storage.download_file.side_effect = Exception("ffmpeg input download failed")
mock_storage.download_bytes.return_value = b"fLaC-source-bytes"
service = AudioTranscodingService(storage_service=mock_storage)
data, content_type = service.get_review_audio_bytes("jobs/abc/stems/vocals_clean.flac")
assert data == b"fLaC-source-bytes"
assert content_type == "audio/flac"
# Fell back to proxying the original source object.
mock_storage.download_bytes.assert_called_once_with("jobs/abc/stems/vocals_clean.flac")
@pytest.mark.asyncio
async def test_async_wrapper_delegates(self):
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
mock_storage.file_exists.return_value = True
mock_storage.download_bytes.return_value = b"OggS"
service = AudioTranscodingService(storage_service=mock_storage)
data, content_type = await service.get_review_audio_bytes_async("jobs/abc/stems/vocals_clean.flac")
assert data == b"OggS"
assert content_type == "audio/ogg"
+42
View File
@@ -0,0 +1,42 @@
"""
Tests for admin-token initialization in AuthService.
An empty ADMIN_TOKENS configuration silently breaks every admin/internal-worker
endpoint (they fail closed with 403). That's safe but looks like an auth bug
rather than a config error, so it must be a LOUD signal: an ERROR log (picked up
by the error monitor → Discord alert), not a quiet warning.
"""
from unittest.mock import patch, MagicMock
from backend.services.auth_service import AuthService
def _make_service(admin_tokens_value):
"""Construct AuthService with a controlled settings.admin_tokens value."""
with patch("backend.services.auth_service.FirestoreService"), \
patch("backend.services.auth_service.get_settings") as mock_get_settings, \
patch("backend.services.auth_service.logger") as mock_logger:
mock_settings = MagicMock()
mock_settings.admin_tokens = admin_tokens_value
mock_settings.scheduler_service_account = "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
mock_get_settings.return_value = mock_settings
service = AuthService()
return service, mock_logger
def test_no_admin_tokens_logs_error_not_warning():
"""Empty ADMIN_TOKENS → ERROR-level loud signal, not a quiet warning."""
service, mock_logger = _make_service("")
assert service.admin_tokens == []
mock_logger.error.assert_called_once()
# It used to be a quiet warning — make sure it isn't anymore.
mock_logger.warning.assert_not_called()
def test_admin_tokens_present_no_error():
"""Configured admin tokens → no error, tokens parsed."""
service, mock_logger = _make_service("tok1, tok2 ,tok3")
assert service.admin_tokens == ["tok1", "tok2", "tok3"]
mock_logger.error.assert_not_called()
+93 -10
View File
@@ -101,7 +101,9 @@ class TestChangeToPrivate:
"""Test public -> private visibility change."""
@pytest.mark.asyncio
async def test_calls_redistribute(self):
async def test_redistributes_then_deletes_public(self):
"""Distribute-then-delete: redistribute runs, then public outputs are deleted
with the references captured before redistribution overwrote state."""
mock_job_manager = MagicMock()
mock_job_ref = MagicMock()
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
@@ -110,18 +112,29 @@ class TestChangeToPrivate:
job = _make_job(is_private=False, state_data={
"youtube_url": "https://youtube.com/watch?v=abc",
"brand_code": "NOMAD-0001",
"gdrive_files": {"mp4": "id1"},
"dropbox_link": "https://dropbox.com/test",
})
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock) as mock_delete, \
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=True) as mock_redist:
call_order = []
mock_redist = AsyncMock(return_value=True, side_effect=lambda *a, **k: call_order.append("redist") or True)
mock_delete = AsyncMock(side_effect=lambda *a, **k: call_order.append("delete"))
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_public_outputs", mock_delete), \
patch("backend.workers.video_worker.redistribute_video", mock_redist):
result = await service.change_to_private("test-123", job, "user@example.com")
assert result["status"] == "success"
assert result["reprocessing_required"] is False
mock_delete.assert_called_once_with("test-123", job, keep_gcs_finals=True)
mock_redist.assert_called_once_with("test-123")
# Redistribution must happen BEFORE any public deletion.
assert call_order == ["redist", "delete"]
# Public deletion receives the references captured before redistribution.
captured = mock_delete.call_args.args[1]
assert captured["youtube_url"] == "https://youtube.com/watch?v=abc"
assert captured["brand_code"] == "NOMAD-0001"
assert captured["gdrive_files"] == {"mp4": "id1"}
@pytest.mark.asyncio
async def test_sets_is_private_true(self):
@@ -132,7 +145,7 @@ class TestChangeToPrivate:
service = VisibilityChangeService(job_manager=mock_job_manager)
job = _make_job(is_private=False, state_data={})
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_public_outputs", new_callable=AsyncMock), \
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=True):
await service.change_to_private("test-123", job, "user@example.com")
@@ -283,22 +296,33 @@ class TestChangeToPrivateErrors:
@pytest.mark.asyncio
async def test_rollback_on_redistribute_failure(self):
"""On redistribution failure NOTHING public is deleted and the job is
reverted to public — a failed going-private is a no-op, not a partial."""
mock_job_manager = MagicMock()
mock_job_ref = MagicMock()
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
service = VisibilityChangeService(job_manager=mock_job_manager)
job = _make_job(is_private=False, state_data={})
job = _make_job(is_private=False, state_data={
"youtube_url": "https://youtube.com/watch?v=abc",
"brand_code": "NOMAD-0001",
"gdrive_files": {"mp4": "id1"},
})
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
mock_delete = AsyncMock()
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_public_outputs", mock_delete), \
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=False):
with pytest.raises(RuntimeError, match="Redistribution failed"):
await service.change_to_private("test-123", job, "user@example.com")
# Guard flag should be cleared on failure (DELETE_FIELD sentinel)
last_update = mock_job_ref.update.call_args_list[-1]
val = last_update.args[0].get("state_data.visibility_change_in_progress")
# Public outputs must NOT be deleted when redistribution fails.
mock_delete.assert_not_called()
# Job reverted to public + guard flag cleared (DELETE_FIELD sentinel).
last_update = mock_job_ref.update.call_args_list[-1].args[0]
assert last_update.get("is_private") is False
val = last_update.get("state_data.visibility_change_in_progress")
assert "delete" in str(type(val)).lower() or "sentinel" in str(val).lower()
@@ -323,6 +347,65 @@ class TestDeleteDistributedOutputs:
mock_brand_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
@pytest.mark.asyncio
async def test_delete_public_outputs_recycles_public_code(self):
"""_delete_public_outputs recycles the captured public NOMAD number."""
mock_job_manager = MagicMock()
service = VisibilityChangeService(job_manager=mock_job_manager)
public_outputs = {
"youtube_url": None,
"brand_code": "NOMAD-0042",
"gdrive_files": None,
"dropbox_path": None,
"artist": "A",
"title": "T",
}
with patch("backend.services.brand_code_service.get_brand_code_service") as mock_bcs, \
patch("backend.services.brand_code_service.BrandCodeService.parse_brand_code", return_value=("NOMAD", 42)), \
patch("backend.services.nomad_master_mirror.cleanup_nomad_masters") as mock_mirror:
mock_brand_svc = MagicMock()
mock_bcs.return_value = mock_brand_svc
await service._delete_public_outputs("test-123", public_outputs)
# No public YouTube/Dropbox/GDrive present → all deletions "succeed" →
# the public number is recycled and the mirror is cleaned.
mock_mirror.assert_called_once_with("NOMAD-0042")
mock_brand_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
@pytest.mark.asyncio
async def test_delete_public_outputs_skips_recycle_on_incomplete_cleanup(self):
"""If a public deletion fails, the number is NOT recycled (avoids a future
duplicate against lingering public files)."""
mock_job_manager = MagicMock()
service = VisibilityChangeService(job_manager=mock_job_manager)
public_outputs = {
"youtube_url": None,
"brand_code": "NOMAD-0042",
"gdrive_files": {"mp4": "id1"},
"dropbox_path": None,
"artist": "A",
"title": "T",
}
with patch("backend.services.gdrive_service.get_gdrive_service") as mock_gd, \
patch("backend.services.nomad_master_mirror.cleanup_nomad_masters"), \
patch("backend.services.brand_code_service.get_brand_code_service") as mock_bcs, \
patch("backend.services.brand_code_service.BrandCodeService.parse_brand_code", return_value=("NOMAD", 42)):
gd = MagicMock()
gd.is_configured = True
gd.delete_files.side_effect = RuntimeError("gdrive boom")
mock_gd.return_value = gd
mock_brand_svc = MagicMock()
mock_bcs.return_value = mock_brand_svc
await service._delete_public_outputs("test-123", public_outputs)
mock_brand_svc.recycle_brand_code.assert_not_called()
@pytest.mark.asyncio
async def test_clears_distribution_state_keys(self):
mock_job_manager = MagicMock()
+102
View File
@@ -0,0 +1,102 @@
"""
Fallback audit (Theme 7): production must fail loudly on missing required config
rather than silently running on dev defaults (wrong GCP project / GCS bucket /
localhost worker URL / console-only email), and the tenant query-param override
must be production-safe by default.
"""
import importlib
import pytest
from backend.config import is_production, validate_production_config
from backend.services.email_service import EmailService
# ---- is_production() ----
def test_is_production_via_environment(monkeypatch):
monkeypatch.setenv("ENVIRONMENT", "production")
monkeypatch.delenv("K_SERVICE", raising=False)
assert is_production() is True
def test_is_production_via_k_service(monkeypatch):
"""Cloud Run sets K_SERVICE automatically — production-safe even if ENVIRONMENT is unset."""
monkeypatch.delenv("ENVIRONMENT", raising=False)
monkeypatch.delenv("ENV", raising=False)
monkeypatch.setenv("K_SERVICE", "karaoke-api")
assert is_production() is True
def test_is_production_false_in_dev(monkeypatch):
monkeypatch.delenv("ENVIRONMENT", raising=False)
monkeypatch.delenv("ENV", raising=False)
monkeypatch.delenv("K_SERVICE", raising=False)
assert is_production() is False
# ---- validate_production_config() ----
def test_validate_raises_when_required_var_missing_in_prod(monkeypatch):
monkeypatch.setenv("ENVIRONMENT", "production")
monkeypatch.delenv("K_SERVICE", raising=False)
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "nomadkaraoke")
monkeypatch.setenv("GCS_BUCKET_NAME", "karaoke-gen-storage-nomadkaraoke")
monkeypatch.delenv("CLOUD_RUN_SERVICE_URL", raising=False) # missing!
with pytest.raises(RuntimeError, match="CLOUD_RUN_SERVICE_URL"):
validate_production_config()
def test_validate_passes_when_all_required_set_in_prod(monkeypatch):
monkeypatch.setenv("ENVIRONMENT", "production")
monkeypatch.delenv("K_SERVICE", raising=False)
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "nomadkaraoke")
monkeypatch.setenv("GCS_BUCKET_NAME", "karaoke-gen-storage-nomadkaraoke")
monkeypatch.setenv("CLOUD_RUN_SERVICE_URL", "https://api.nomadkaraoke.com")
validate_production_config() # must not raise
def test_validate_noop_in_dev(monkeypatch):
monkeypatch.delenv("ENVIRONMENT", raising=False)
monkeypatch.delenv("ENV", raising=False)
monkeypatch.delenv("K_SERVICE", raising=False)
monkeypatch.delenv("CLOUD_RUN_SERVICE_URL", raising=False)
validate_production_config() # no-op, must not raise
# ---- email provider (7.5) ----
def test_email_provider_raises_in_prod_without_postmark(monkeypatch):
monkeypatch.setenv("ENVIRONMENT", "production")
monkeypatch.delenv("K_SERVICE", raising=False)
monkeypatch.delenv("POSTMARK_SERVER_TOKEN", raising=False)
with pytest.raises(RuntimeError, match="POSTMARK_SERVER_TOKEN"):
EmailService()
def test_email_provider_console_in_dev_without_postmark(monkeypatch):
monkeypatch.delenv("ENVIRONMENT", raising=False)
monkeypatch.delenv("ENV", raising=False)
monkeypatch.delenv("K_SERVICE", raising=False)
monkeypatch.delenv("POSTMARK_SERVER_TOKEN", raising=False)
svc = EmailService() # must not raise — console fallback is fine in dev
assert svc.is_configured() is False
# ---- tenant gate (7.4) ----
def test_tenant_gate_production_safe_with_k_service(monkeypatch):
"""K_SERVICE present (Cloud Run) → IS_PRODUCTION True → query-param override disabled."""
monkeypatch.delenv("ENVIRONMENT", raising=False)
monkeypatch.delenv("ENV", raising=False)
monkeypatch.setenv("K_SERVICE", "karaoke-api")
import backend.middleware.tenant as tenant_mod
try:
importlib.reload(tenant_mod)
assert tenant_mod.IS_PRODUCTION is True
finally:
# Restore module to a clean (dev) state so other tests aren't affected.
monkeypatch.delenv("K_SERVICE", raising=False)
importlib.reload(tenant_mod)
+204
View File
@@ -266,6 +266,37 @@ class TestMadeForYouOrderConfirmationEmail:
assert call_kwargs.get('cc_emails') is None
class TestEmailServiceSendEmailPassthrough:
"""Tests for the generic EmailService.send_email passthrough.
Regression (2026-08-22): the made-for-you failure handler called
``email_service.send_email(...)`` but EmailService had no such method (only the
provider did), so the failure alert itself crashed with
``'EmailService' object has no attribute 'send_email'`` — masking the original
error and losing the admin alert entirely.
"""
def test_send_email_delegates_to_provider(self):
service = EmailService()
service.provider = Mock()
service.provider.send_email.return_value = True
result = service.send_email(
to_email="admin@example.com",
subject="[FAILED] Test",
html_content="<p>oops</p>",
text_content="oops",
)
assert result is True
service.provider.send_email.assert_called_once()
call_kwargs = service.provider.send_email.call_args.kwargs
assert call_kwargs["to_email"] == "admin@example.com"
assert call_kwargs["subject"] == "[FAILED] Test"
assert call_kwargs["html_content"] == "<p>oops</p>"
assert call_kwargs["text_content"] == "oops"
class TestMadeForYouAdminNotificationEmail:
"""Tests for send_made_for_you_admin_notification method."""
@@ -1757,6 +1788,179 @@ class TestMadeForYouYouTubeDownloadContract:
assert "[FAILED]" in email_call.kwargs.get('subject', ''), \
"Error notification email should have [FAILED] in subject"
@pytest.mark.asyncio
async def test_youtube_download_failure_still_sends_customer_confirmation(
self, mock_job_manager, mock_email_service, mock_user_service,
mock_theme_service, youtube_order_metadata
):
"""
Regression: a YouTube download failure must NOT prevent the paid customer
from receiving their order-confirmation email, nor prevent the admin from
being alerted.
Bug context (2026-08-22): Job 17dc6f48 failed on a YouTube bot-check
download error. Because the confirmation + admin emails were only sent
*after* audio acquisition, the download failure skipped both — Andrew never
received the "New Made-For-You Order Received!" notification and there was no
guarantee the customer got their confirmation. The confirmation email is now
sent up-front, independently of the (fallible) audio acquisition step.
"""
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
from backend.services.youtube_download_service import YouTubeDownloadError
mock_youtube_service = MagicMock()
mock_youtube_service.download = AsyncMock(
side_effect=YouTubeDownloadError(
"Sign in to confirm you're not a bot"
)
)
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
patch('backend.services.worker_service.get_worker_service', return_value=MagicMock()), \
patch('backend.services.storage_service.StorageService'), \
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_service):
# Must not raise - order intake is resilient to audio-acquisition failures
await _handle_made_for_you_order(
session_id="sess_123",
metadata=youtube_order_metadata,
user_service=mock_user_service,
email_service=mock_email_service,
)
# CRITICAL: customer still receives their order confirmation despite the failure
mock_email_service.send_made_for_you_order_confirmation.assert_called_once()
confirm_kwargs = mock_email_service.send_made_for_you_order_confirmation.call_args.kwargs
assert confirm_kwargs['to_email'] == youtube_order_metadata['customer_email']
assert confirm_kwargs['job_id'] == "test-job-123"
# CRITICAL: admin is alerted to the failure so they can intervene manually
mock_email_service.send_email.assert_called_once()
failure_kwargs = mock_email_service.send_email.call_args.kwargs
assert failure_kwargs['to_email'] == ADMIN_EMAIL
assert "[FAILED]" in failure_kwargs['subject']
@pytest.mark.asyncio
async def test_customer_confirmation_email_failure_does_not_abort_order(
self, mock_job_manager, mock_email_service, mock_user_service,
mock_theme_service, youtube_order_metadata
):
"""
Resilience: if the customer confirmation email itself fails to send, order
processing (audio acquisition + admin notification) must still proceed, and the
failed confirmation must be escalated to the admin (never silently lost). An
email-provider hiccup should never block the actual work.
"""
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
# Confirmation email raises, but the order must still be processed
mock_email_service.send_made_for_you_order_confirmation.side_effect = \
RuntimeError("Postmark timeout")
# start_job_processing is async - mock it so the success path completes
mock_job_manager.start_job_processing = AsyncMock()
mock_youtube_service = MagicMock()
mock_youtube_service.download = AsyncMock(
return_value="uploads/test-job-123/audio/test.webm"
)
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
patch('backend.services.worker_service.get_worker_service', return_value=MagicMock()), \
patch('backend.services.storage_service.StorageService'), \
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_service):
# Must not raise despite the confirmation email failure
await _handle_made_for_you_order(
session_id="sess_123",
metadata=youtube_order_metadata,
user_service=mock_user_service,
email_service=mock_email_service,
)
# Download still happened and admin notification still sent
mock_youtube_service.download.assert_called_once()
mock_email_service.send_made_for_you_admin_notification.assert_called_once()
# The failed customer confirmation is escalated to the admin so it can be
# resent manually — a paid confirmation must never be silently lost.
mock_email_service.send_email.assert_called_once()
alert_kwargs = mock_email_service.send_email.call_args.kwargs
assert alert_kwargs['to_email'] == ADMIN_EMAIL
assert "[FAILED]" in alert_kwargs['subject']
@pytest.mark.asyncio
async def test_confirmation_provider_rejection_is_escalated(
self, mock_job_manager, mock_email_service, mock_user_service,
mock_theme_service, youtube_order_metadata
):
"""
Providers return False (not an exception) when a send is rejected. A rejected
customer confirmation must be escalated to the admin, not silently logged as
sent. Regression guard for the "log success even on False" bug.
"""
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
# Provider rejects the confirmation (returns False, does not raise)
mock_email_service.send_made_for_you_order_confirmation.return_value = False
mock_job_manager.start_job_processing = AsyncMock()
mock_youtube_service = MagicMock()
mock_youtube_service.download = AsyncMock(
return_value="uploads/test-job-123/audio/test.webm"
)
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
patch('backend.services.worker_service.get_worker_service', return_value=MagicMock()), \
patch('backend.services.storage_service.StorageService'), \
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_service):
await _handle_made_for_you_order(
session_id="sess_123",
metadata=youtube_order_metadata,
user_service=mock_user_service,
email_service=mock_email_service,
)
# Rejected confirmation escalated to admin; order still processed
mock_email_service.send_email.assert_called_once()
assert mock_email_service.send_email.call_args.kwargs['to_email'] == ADMIN_EMAIL
mock_email_service.send_made_for_you_admin_notification.assert_called_once()
@pytest.mark.asyncio
async def test_job_creation_failure_reraises_for_stripe_retry(
self, mock_email_service, mock_user_service, mock_theme_service,
youtube_order_metadata
):
"""
If job creation fails (no job_id, session never marked processed), the handler
must re-raise so the Stripe webhook returns non-2xx and Stripe retries — a paid
order must not be silently dropped. The admin is still alerted first.
"""
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
mock_job_manager = MagicMock()
mock_job_manager.create_job.side_effect = RuntimeError("Firestore unavailable")
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
patch('backend.services.storage_service.StorageService'), \
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service):
with pytest.raises(RuntimeError, match="Firestore unavailable"):
await _handle_made_for_you_order(
session_id="sess_123",
metadata=youtube_order_metadata,
user_service=mock_user_service,
email_service=mock_email_service,
)
# Admin alerted before the re-raise; no confirmation (job never created)
mock_email_service.send_email.assert_called_once()
assert mock_email_service.send_email.call_args.kwargs['to_email'] == ADMIN_EMAIL
mock_email_service.send_made_for_you_order_confirmation.assert_not_called()
class TestMadeForYouYouTubeImports:
"""
+7
View File
@@ -76,6 +76,13 @@ class TestSummaryFieldPathsIncludesRetryPending:
from backend.api.routes.jobs import _SUMMARY_STATE_DATA_KEYS
assert 'cloud_run_retry_pending' in _SUMMARY_STATE_DATA_KEYS
def test_firestore_projection_includes_existing_instrumental_path(self):
# Top-level field (not state_data), so only SUMMARY_FIELD_PATHS is needed —
# the frontend job list uses it to relabel the "downloading" step as
# "Preparing your audio" for tenant / upload-based jobs.
from backend.services.firestore_service import FirestoreService
assert 'existing_instrumental_gcs_path' in FirestoreService.SUMMARY_FIELD_PATHS
class TestSummaryFieldPathsIncludesDurationPricing:
"""Regression: duration-pricing fields must be in both SUMMARY_FIELD_PATHS
+195 -2
View File
@@ -209,10 +209,10 @@ class TestAddLyricsEndpoint:
def test_add_lyrics_uses_correction_operations(self):
"""Verify CorrectionOperations.add_lyrics_source is available."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
# The method should exist
assert hasattr(CorrectionOperations, 'add_lyrics_source')
# It should be a static method
import inspect
# Get the method and check it's callable
@@ -220,6 +220,99 @@ class TestAddLyricsEndpoint:
assert callable(method)
class TestAddLyricsRejectionHandling:
"""Endpoint tests for the relevance-filter rejection flow of add-lyrics.
The relevance filter can silently drop a pasted lyrics source during the
correction rerun. The endpoint must report that as status="rejected" (with
the relevance details) instead of a misleading generic success, and must
not persist the no-op rerun to GCS.
"""
REJECTION = {"relevance": 0.013, "matched_words": 3, "total_words": 230}
@pytest.fixture(autouse=True)
def auth_overrides(self):
from backend.main import app
from backend.api.dependencies import require_review_auth
async def mock_require_review_auth(job_id: str = "test123"):
return (job_id, "full")
app.dependency_overrides[require_review_auth] = mock_require_review_auth
yield
app.dependency_overrides.pop(require_review_auth, None)
def _make_updated_result(self, source_kept: bool, source: str = "manual"):
result = MagicMock()
if source_kept:
result.reference_lyrics = {source: MagicMock()}
result.metadata = {}
else:
result.reference_lyrics = {}
result.metadata = {"rejected_sources": {source: dict(self.REJECTION)}}
result.to_dict.return_value = {"reference_lyrics": {}, "metadata": result.metadata}
return result
def _post_add_lyrics(self, test_client, updated_result, payload):
from backend.models.job import JobStatus
mock_job = MagicMock()
mock_job.status = JobStatus.IN_REVIEW
mock_job.artist = "Test Artist"
mock_job.title = "Test Song"
def fake_download(gcs_path, local_path):
with open(local_path, "w") as f:
json.dump({}, f)
with patch("backend.api.routes.review.JobManager") as mock_jm, \
patch("backend.api.routes.review.StorageService") as mock_storage_cls, \
patch("backend.api.routes.review.CorrectionResult") as mock_cr, \
patch("backend.api.routes.review.CorrectionOperations") as mock_ops, \
patch("backend.api.routes.review._get_audio_hash", return_value="hash123"):
mock_jm.return_value.get_job.return_value = mock_job
mock_storage = mock_storage_cls.return_value
mock_storage.download_file.side_effect = fake_download
mock_cr.from_dict.return_value = MagicMock()
mock_ops.add_lyrics_source.return_value = updated_result
response = test_client.post("/api/review/job1/add-lyrics", json=payload)
return response, mock_ops, mock_storage
def test_kept_source_returns_success_and_uploads(self, test_client):
updated = self._make_updated_result(source_kept=True)
response, _, mock_storage = self._post_add_lyrics(
test_client, updated, {"source": "manual", "lyrics": "la la la"}
)
assert response.status_code == 200
body = response.json()
assert body["status"] == "success"
mock_storage.upload_json.assert_called_once()
def test_rejected_source_returns_rejected_without_upload(self, test_client):
updated = self._make_updated_result(source_kept=False)
response, _, mock_storage = self._post_add_lyrics(
test_client, updated, {"source": "manual", "lyrics": "wrong song lyrics"}
)
assert response.status_code == 200
body = response.json()
assert body["status"] == "rejected"
assert body["rejection"] == self.REJECTION
# The no-op rerun must not overwrite corrections.json
mock_storage.upload_json.assert_not_called()
def test_force_flag_is_passed_through(self, test_client):
updated = self._make_updated_result(source_kept=True)
_, mock_ops, _ = self._post_add_lyrics(
test_client, updated, {"source": "manual", "lyrics": "la la la", "force": "true"}
)
assert mock_ops.add_lyrics_source.call_args.kwargs["force"] is True
class TestReviewResubmissionClearsWorkerProgress:
"""Tests for ensuring review submission clears worker progress keys.
@@ -1132,3 +1225,103 @@ class TestGetPreviewVideoRedirect:
self._call(mock_storage)
assert exc_info.value.status_code == 404
mock_storage.generate_signed_url.assert_not_called()
class TestGetVocalsAudio:
"""The vocals waveform endpoint proxies the full vocal stem for the timeline.
Two behaviours: (1) select the fullest vocal mix (vocals_clean) — real jobs
never store a plain 'vocals' key, they store vocals_clean / lead_vocals /
backing_vocals. (2) Return the bytes directly (not a 302 to GCS): the
waveform fetch()es + decodeAudioData()s the audio, and a cross-origin
redirect makes the browser send `Origin: null` which the bucket CORS rejects,
so the waveform never loads.
"""
def _call(self, stems, audio_complete=True):
import asyncio
from backend.api.routes.review import _stream_audio
job = MagicMock()
job.input_media_gcs_path = "jobs/j/input.flac"
job.file_urls = {"stems": stems}
job.state_data = {"audio_complete": audio_complete}
job_manager = MagicMock()
job_manager.get_job.return_value = job
transcoding = MagicMock()
transcoding.get_review_audio_bytes_async = AsyncMock(
return_value=(b"OggS-fake-vocals-bytes", "audio/ogg")
)
with patch("backend.api.routes.review.JobManager", return_value=job_manager), patch(
"backend.services.audio_transcoding_service.AudioTranscodingService",
return_value=transcoding,
):
resp = asyncio.run(
_stream_audio(job_id="j", stem="vocals")
)
return resp, transcoding
def test_proxies_bytes_not_redirect(self):
from starlette.responses import RedirectResponse, Response
resp, _ = self._call({"vocals_clean": "jobs/j/stems/vocals_clean.flac"})
# Must serve the bytes from the API (CORS-friendly), never 302 to GCS.
assert not isinstance(resp, RedirectResponse)
assert isinstance(resp, Response)
assert resp.status_code == 200
assert resp.media_type == "audio/ogg"
assert resp.body == b"OggS-fake-vocals-bytes"
def test_selects_vocals_clean_when_no_plain_vocals_key(self):
# The shape produced by real cloud jobs (no plain "vocals").
_, transcoding = self._call(
{
"instrumental_clean": "jobs/j/stems/instrumental_clean.flac",
"vocals_clean": "jobs/j/stems/vocals_clean.flac",
"lead_vocals": "jobs/j/stems/lead_vocals.flac",
"backing_vocals": "jobs/j/stems/backing_vocals.flac",
}
)
# Must pick the full vocal mix (vocals_clean), not lead_vocals or KeyError.
assert transcoding.get_review_audio_bytes_async.call_args[0][0] == "jobs/j/stems/vocals_clean.flac"
def test_prefers_plain_vocals_then_falls_back_to_lead(self):
# 2-stem split exposes a plain "vocals" — preferred.
_, transcoding = self._call({"vocals": "jobs/j/stems/vocals.flac"})
assert transcoding.get_review_audio_bytes_async.call_args[0][0] == "jobs/j/stems/vocals.flac"
# Only lead_vocals available — last-resort fallback.
_, transcoding = self._call({"lead_vocals": "jobs/j/stems/lead_vocals.flac"})
assert transcoding.get_review_audio_bytes_async.call_args[0][0] == "jobs/j/stems/lead_vocals.flac"
def test_404_when_no_vocal_stem_present(self):
"""audio_complete=True + no vocal stem = the stem will never exist -> 404."""
from fastapi import HTTPException
with pytest.raises(HTTPException) as exc_info:
self._call({"instrumental_clean": "jobs/j/stems/instrumental_clean.flac"})
assert exc_info.value.status_code == 404
def test_202_when_separation_still_in_progress(self):
"""Users can open lyrics review before audio separation finishes (it's
decoupled from the critical path), so a missing vocal stem while
audio_complete=False means "not yet" — return 202 so the frontend polls
instead of permanently hiding the waveform on a terminal 404."""
resp, transcoding = self._call({}, audio_complete=False)
assert resp.status_code == 202
assert resp.headers.get("Retry-After") == "15"
transcoding.get_review_audio_bytes_async.assert_not_called()
def test_404_when_separation_skipped_and_no_vocal_stem(self):
"""Existing-instrumental jobs set audio_complete=True without ever
producing vocal stems — must 404 (terminal), not 202 (retry forever)."""
from fastapi import HTTPException
with pytest.raises(HTTPException) as exc_info:
self._call({}, audio_complete=True)
assert exc_info.value.status_code == 404
+106 -1
View File
@@ -244,7 +244,112 @@ class TestWorkerService:
call_args = mock_run_v2.RunJobRequest.call_args
assert call_args is not None
assert "lyrics-transcription-job" in str(call_args)
def _mock_run_v2(self, run_job_side_effect):
"""Build a mocked run_v2 module whose JobsClient.run_job uses side_effect."""
mock_jobs_client = MagicMock()
mock_jobs_client.run_job.side_effect = run_job_side_effect
mock_run_v2 = MagicMock()
mock_run_v2.JobsClient.return_value = mock_jobs_client
mock_run_v2.RunJobRequest = MagicMock()
mock_run_v2.RunJobRequest.Overrides = MagicMock()
mock_run_v2.RunJobRequest.Overrides.ContainerOverride = MagicMock()
return mock_run_v2, mock_jobs_client
@pytest.mark.asyncio
async def test_trigger_worker_retries_transient_503_then_succeeds(self):
"""A one-off transient 503 from the Jobs Admin API is retried, not fatal."""
from google.api_core import exceptions as gcp_exceptions
from backend.services.worker_service import (
WorkerService, reset_worker_service, _RUN_JOB_MAX_ATTEMPTS,
)
reset_worker_service()
with patch('backend.services.worker_service.get_settings') as mock_settings, \
patch('backend.services.worker_service.asyncio.sleep', new=AsyncMock()) as mock_sleep:
mock_settings.return_value.admin_tokens = "test-token"
mock_settings.return_value.google_cloud_project = "test-project"
mock_settings.return_value.enable_cloud_tasks = False
mock_settings.return_value.gcp_region = "us-central1"
mock_settings.return_value.use_cloud_run_jobs_for_video = False
mock_operation = MagicMock()
mock_operation.metadata = "test-metadata"
# Fail once with a transient 503, then succeed on retry.
mock_run_v2, mock_jobs_client = self._mock_run_v2(
[gcp_exceptions.ServiceUnavailable("503 unavailable"), mock_operation]
)
import google.cloud
with patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}), \
patch.object(google.cloud, 'run_v2', mock_run_v2, create=True):
service = WorkerService()
result = await service.trigger_lyrics_worker("test123")
assert result is True
assert mock_jobs_client.run_job.call_count == 2 # first fails, retry succeeds
assert mock_sleep.await_count == 1 # backed off once between attempts
assert _RUN_JOB_MAX_ATTEMPTS >= 2
@pytest.mark.asyncio
async def test_trigger_worker_gives_up_after_max_attempts(self):
"""Persistent transient errors exhaust retries and return False (not a raise)."""
from google.api_core import exceptions as gcp_exceptions
from backend.services.worker_service import (
WorkerService, reset_worker_service, _RUN_JOB_MAX_ATTEMPTS,
)
reset_worker_service()
with patch('backend.services.worker_service.get_settings') as mock_settings, \
patch('backend.services.worker_service.asyncio.sleep', new=AsyncMock()):
mock_settings.return_value.admin_tokens = "test-token"
mock_settings.return_value.google_cloud_project = "test-project"
mock_settings.return_value.enable_cloud_tasks = False
mock_settings.return_value.gcp_region = "us-central1"
mock_settings.return_value.use_cloud_run_jobs_for_video = False
mock_run_v2, mock_jobs_client = self._mock_run_v2(
gcp_exceptions.ServiceUnavailable("503 unavailable")
)
import google.cloud
with patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}), \
patch.object(google.cloud, 'run_v2', mock_run_v2, create=True):
service = WorkerService()
result = await service.trigger_lyrics_worker("test123")
assert result is False
assert mock_jobs_client.run_job.call_count == _RUN_JOB_MAX_ATTEMPTS
@pytest.mark.asyncio
async def test_trigger_worker_does_not_retry_permanent_error(self):
"""Non-transient errors (e.g. PermissionDenied) fail fast without retry."""
from google.api_core import exceptions as gcp_exceptions
from backend.services.worker_service import WorkerService, reset_worker_service
reset_worker_service()
with patch('backend.services.worker_service.get_settings') as mock_settings, \
patch('backend.services.worker_service.asyncio.sleep', new=AsyncMock()) as mock_sleep:
mock_settings.return_value.admin_tokens = "test-token"
mock_settings.return_value.google_cloud_project = "test-project"
mock_settings.return_value.enable_cloud_tasks = False
mock_settings.return_value.gcp_region = "us-central1"
mock_settings.return_value.use_cloud_run_jobs_for_video = False
mock_run_v2, mock_jobs_client = self._mock_run_v2(
gcp_exceptions.PermissionDenied("permission denied")
)
import google.cloud
with patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}), \
patch.object(google.cloud, 'run_v2', mock_run_v2, create=True):
service = WorkerService()
result = await service.trigger_lyrics_worker("test123")
assert result is False
assert mock_jobs_client.run_job.call_count == 1 # no retry on permanent error
assert mock_sleep.await_count == 0
@pytest.mark.asyncio
async def test_trigger_screens_worker(self):
"""Test triggering screens worker via internal HTTP."""
@@ -51,6 +51,12 @@ def mock_encoding_worker_config():
config.deploy_in_progress = False
config.deploy_in_progress_since = None
config.last_activity_at = None
# No capacity fallback active by default → serving the c4d primary.
config.active_override_vm = None
config.active_override_ip = None
config.active_override_zone = None
config.active_override_set_at = None
config.primary_machine_type = None
return config
@@ -134,6 +140,7 @@ class TestSystemStatusAdmin:
mock_auth = ("token123", UserType.ADMIN, -1)
mock_manager = MagicMock()
mock_manager._zone = "us-central1-c"
mock_manager.get_config.return_value = mock_encoding_worker_config
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
@@ -155,3 +162,46 @@ class TestSystemStatusAdmin:
assert admin["secondary_vm"] == "encoding-worker-a"
assert admin["last_swap_at"] == "2026-03-31T18:10:00Z"
assert admin["deploy_in_progress"] is False
# No fallback active → serving the c4d primary VM.
assert admin["on_fallback"] is False
assert admin["active_vm"] == "encoding-worker-b"
assert admin["active_zone"] == "us-central1-c"
assert admin["active_machine_type"] == "c4d-highcpu-32"
@pytest.mark.asyncio
async def test_admin_sees_capacity_fallback_worker(
self, mock_encoding_status, mock_flacfetch_status, mock_separator_status, mock_encoding_worker_config
):
"""When a stockout routes off the primary, the live worker reflects the fallback."""
from backend.api.routes.health import system_status
from backend.services.auth_service import UserType
# Capacity fallback active: serving an n2-family VM in an alternate zone.
mock_encoding_worker_config.active_override_vm = "encoding-worker-fallback-n2c"
mock_encoding_worker_config.active_override_ip = "34.9.9.9"
mock_encoding_worker_config.active_override_zone = "us-central1-a"
mock_auth = ("token123", UserType.ADMIN, -1)
mock_manager = MagicMock()
mock_manager._zone = "us-central1-c"
mock_manager.get_config.return_value = mock_encoding_worker_config
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
patch("backend.api.routes.health.VERSION", "0.155.3"), \
patch("backend.api.routes.health.COMMIT_SHA", ""), \
patch("backend.api.routes.health.PR_NUMBER", ""), \
patch("backend.api.routes.health.PR_TITLE", ""), \
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"), \
patch("backend.api.routes.health._get_encoding_worker_manager", return_value=mock_manager):
result = await system_status(auth=mock_auth)
admin = result["services"]["encoder"]["admin_details"]
assert admin["on_fallback"] is True
assert admin["active_vm"] == "encoding-worker-fallback-n2c"
assert admin["active_zone"] == "us-central1-a"
# "n2c" family token → n2-highcpu-32 (inferred from the VM name).
assert admin["active_machine_type"] == "n2-highcpu-32"
+38 -17
View File
@@ -11,6 +11,28 @@ from backend.models.user import VerifyMagicLinkResponse, UserPublic
from backend.services.auth_service import AuthResult, AuthService, UserType
def _sent_fields(call_args):
"""Extract the sent email's fields regardless of positional/keyword call style.
Sends now flow through EmailService._log_and_send, which invokes the provider
with keyword args; older direct calls used positionals. Read both.
"""
args, kwargs = call_args.args, call_args.kwargs
def pick(name, idx):
if name in kwargs:
return kwargs[name]
return args[idx] if len(args) > idx else None
return {
"to_email": pick("to_email", 0),
"subject": pick("subject", 1),
"html_content": pick("html_content", 2),
"text_content": pick("text_content", 3),
"from_email_override": kwargs.get("from_email_override"),
}
class TestTenantConfigGetFrontendUrl:
"""Tests for TenantConfig.get_frontend_url()."""
@@ -47,10 +69,10 @@ class TestSendMagicLinkTenantParams:
"""Without tenant params, email uses default Nomad Karaoke branding."""
email_service.send_magic_link("user@test.com", "abc123")
call_args = email_service.provider.send_email.call_args
subject = call_args[0][1]
html_content = call_args[0][2]
text_content = call_args[0][3]
f = _sent_fields(email_service.provider.send_email.call_args)
subject = f["subject"]
html_content = f["html_content"]
text_content = f["text_content"]
assert subject == "Sign in to Nomad Karaoke"
assert "Nomad Karaoke" in html_content
@@ -66,9 +88,9 @@ class TestSendMagicLinkTenantParams:
tenant_frontend_url="https://vocalstar.nomadkaraoke.com",
)
call_args = email_service.provider.send_email.call_args
html_content = call_args[0][2]
text_content = call_args[0][3]
f = _sent_fields(email_service.provider.send_email.call_args)
html_content = f["html_content"]
text_content = f["text_content"]
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=abc123" in html_content
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=abc123" in text_content
@@ -83,10 +105,10 @@ class TestSendMagicLinkTenantParams:
tenant_name="Vocal Star",
)
call_args = email_service.provider.send_email.call_args
subject = call_args[0][1]
html_content = call_args[0][2]
text_content = call_args[0][3]
f = _sent_fields(email_service.provider.send_email.call_args)
subject = f["subject"]
html_content = f["html_content"]
text_content = f["text_content"]
assert subject == "Sign in to Vocal Star"
assert "Vocal Star" in html_content
@@ -100,8 +122,7 @@ class TestSendMagicLinkTenantParams:
tenant_name='<script>alert("xss")</script>',
)
call_args = email_service.provider.send_email.call_args
html_content = call_args[0][2]
html_content = _sent_fields(email_service.provider.send_email.call_args)["html_content"]
# Should be escaped in HTML
assert "<script>" not in html_content
@@ -119,14 +140,14 @@ class TestSendMagicLinkTenantParams:
assert result is True
call_args = email_service.provider.send_email.call_args
subject = call_args[0][1]
html_content = call_args[0][2]
f = _sent_fields(email_service.provider.send_email.call_args)
subject = f["subject"]
html_content = f["html_content"]
assert subject == "Sign in to Vocal Star"
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=token123" in html_content
# Check sender email override was passed through
assert call_args[1]["from_email_override"] == "vocalstar@nomadkaraoke.com"
assert f["from_email_override"] == "vocalstar@nomadkaraoke.com"
class TestVerifyMagicLinkResponseTenantSubdomain:
@@ -21,6 +21,7 @@ from backend.workers.video_worker_orchestrator import (
VideoWorkerOrchestrator,
create_orchestrator_config_from_job,
)
from backend.models.job import JobStatus
class TestOrchestratorConfig:
@@ -2132,3 +2133,52 @@ class TestOriginalVocalsGuideEmit:
with patch("backend.workers.style_helper.load_style_config", side_effect=fake_load):
assert await orch._resolve_intro_seconds() == 8.0
class TestRedistributeModeProgress:
"""redistribute_mode must not attempt job status transitions.
Regression for the public->private data-loss bug: redistributing an already
`complete` job drove `_update_progress(PACKAGING)`, which raised
InvalidStateTransitionError (`complete -> packaging`) and aborted the
redistribution after the public outputs had already been deleted.
"""
def _config(self, redistribute_mode):
return OrchestratorConfig(
job_id="job-1",
artist="A",
title="T",
title_video_path="",
karaoke_video_path="",
instrumental_audio_path="",
redistribute_mode=redistribute_mode,
)
def test_redistribute_mode_skips_status_transition(self):
jm = MagicMock()
orch = VideoWorkerOrchestrator(
config=self._config(redistribute_mode=True),
job_manager=jm,
storage=MagicMock(),
job_logger=MagicMock(),
)
orch._update_progress(JobStatus.PACKAGING, 90, "Uploading files")
jm.transition_to_state.assert_not_called()
jm.update_job.assert_called_once_with("job-1", {"progress": 90})
def test_normal_mode_drives_status_transition(self):
jm = MagicMock()
orch = VideoWorkerOrchestrator(
config=self._config(redistribute_mode=False),
job_manager=jm,
storage=MagicMock(),
job_logger=MagicMock(),
)
orch._update_progress(JobStatus.PACKAGING, 90, "Uploading files")
jm.transition_to_state.assert_called_once()
jm.update_job.assert_not_called()
+36 -10
View File
@@ -816,20 +816,46 @@ class TestDownloadAudioWithUrl:
@pytest.mark.asyncio
async def test_download_audio_url_without_gcs_path_refuses(self, mock_job_with_url, mock_job_manager, mock_storage):
"""A URL job with no GCS file must fail (no local yt-dlp fallback)."""
"""A URL job with no GCS file must fail loudly (no local yt-dlp fallback)."""
from backend.workers.audio_worker import download_audio
from backend.services.audio_search_service import DownloadError
with tempfile.TemporaryDirectory() as temp_dir:
result = await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_with_url,
job_manager_instance=mock_job_manager
)
# Fails loudly with a specific DownloadError rather than returning
# None (which used to surface a generic "Failed to download audio file").
with pytest.raises(DownloadError, match="flacfetch service"):
await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_with_url,
job_manager_instance=mock_job_manager
)
# Refuses to download locally → returns None, never touches storage
assert result is None
# Refuses to download locally → never touches storage
mock_storage.download_file.assert_not_called()
@pytest.mark.asyncio
async def test_download_audio_no_source_raises(self, mock_job_manager, mock_storage):
"""A job with no GCS path, no file_urls and no URL must fail loudly."""
from backend.workers.audio_worker import download_audio
from backend.services.audio_search_service import DownloadError
no_source_job = Job(
job_id="test123",
status=JobStatus.PROCESSING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
)
with tempfile.TemporaryDirectory() as temp_dir:
with pytest.raises(DownloadError, match="No input audio source"):
await download_audio(
"test123", temp_dir, mock_storage, no_source_job,
job_manager_instance=mock_job_manager,
)
mock_storage.download_file.assert_not_called()
@pytest.mark.asyncio
+22
View File
@@ -176,3 +176,25 @@ class TestWorkerFileOperations:
result = await download_audio("test123", temp_dir, mock_storage, mock_job, mock_job_manager)
mock_storage.download_file.assert_called()
@pytest.mark.asyncio
async def test_lyrics_download_audio_no_source_raises(self):
"""Lyrics worker download_audio must fail loudly when there's no source."""
from backend.workers.lyrics_worker import download_audio
from backend.services.audio_search_service import DownloadError
mock_storage = MagicMock()
mock_job_manager = MagicMock()
mock_job = Job(
job_id="test123",
status=JobStatus.TRANSCRIBING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
# No input_media_gcs_path and no url → nothing to download
)
mock_job_manager.get_job.return_value = mock_job
with tempfile.TemporaryDirectory() as temp_dir:
with pytest.raises(DownloadError, match="No input audio available"):
await download_audio("test123", temp_dir, mock_storage, mock_job, mock_job_manager)
mock_storage.download_file.assert_not_called()
+33 -9
View File
@@ -24,6 +24,7 @@ from typing import Optional, Dict, Any
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.audio_search_service import DownloadError
from backend.services.job_health_service import validate_worker_can_run
from backend.config import get_settings
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
@@ -213,9 +214,9 @@ async def process_audio_separation(job_id: str) -> bool:
# Download audio file from GCS or URL
with job_span("download-audio", job_id) as download_span:
job_log.info("Downloading audio file...")
# download_audio raises DownloadError with a specific reason
# on failure (no silent None → generic-error fallback).
audio_path = await download_audio(job_id, temp_dir, storage, job, job_manager_instance=job_manager)
if not audio_path:
raise Exception("Failed to download audio file")
job_log.info(f"Audio downloaded: {os.path.basename(audio_path)}")
download_span.set_attribute("audio_file", os.path.basename(audio_path))
download_span.set_attribute("source", "url" if job.url else "gcs")
@@ -363,6 +364,16 @@ async def process_audio_separation(job_id: str) -> bool:
logger.info(f"[job:{job_id}] WORKER_END worker=audio status=success duration={duration:.1f}s")
return True
except DownloadError as e:
duration = time.time() - start_time
logger.error(f"[job:{job_id}] WORKER_END worker=audio status=error duration={duration:.1f}s error={e}", exc_info=True)
job_manager.mark_job_failed(
job_id=job_id,
error_message=f"Audio download failed: {str(e)}",
error_details={"stage": "download_audio", "error": str(e)}
)
return False
except Exception as e:
duration = time.time() - start_time
logger.error(f"[job:{job_id}] WORKER_END worker=audio status=error duration={duration:.1f}s error={e}", exc_info=True)
@@ -396,7 +407,7 @@ async def download_audio(
storage: StorageService,
job,
job_manager_instance: JobManager = None
) -> Optional[str]:
) -> str:
"""
Fetch the job's audio file from GCS to a local temp directory.
@@ -414,9 +425,14 @@ async def download_audio(
storage: StorageService instance
job: Job object with URL or GCS path
job_manager_instance: Optional JobManager instance for updating job metadata
Returns:
Path to downloaded audio file, or None if failed
Path to the downloaded audio file.
Raises:
DownloadError: with a specific reason if the audio can't be obtained.
We fail loudly with the real cause rather than returning None and
surfacing a generic "Failed to download audio file" to the user.
"""
try:
from karaoke_gen.utils import sanitize_filename
@@ -464,14 +480,22 @@ async def download_audio(
"fetched via the flacfetch service before processing; refusing to "
"download locally."
)
return None
raise DownloadError(
"URL job reached the audio worker without a downloaded input file. "
"URLs must be fetched via the flacfetch service before processing; "
"we never download locally on Cloud Run."
)
logger.error(f"Job {job_id}: No input source found (no GCS path or file_urls)")
return None
raise DownloadError(
"No input audio source found for this job (no GCS path and no file_urls)."
)
except DownloadError:
raise
except Exception as e:
logger.error(f"Job {job_id}: Failed to download audio: {e}", exc_info=True)
return None
raise DownloadError(f"Failed to download audio from storage: {e}") from e
async def upload_separation_results(
+45 -17
View File
@@ -31,6 +31,7 @@ from pathlib import Path
from backend.models.job import JobStatus
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.audio_search_service import DownloadError
from backend.services.job_health_service import validate_worker_can_run
from backend.services.lyrics_cache_service import LyricsCacheService
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
@@ -302,9 +303,9 @@ async def process_lyrics_transcription(job_id: str) -> bool:
# Download audio file from GCS (waits for audio worker if URL job)
with job_span("download-audio", job_id) as download_span:
job_log.info("Downloading audio file from GCS...")
# download_audio raises DownloadError with a specific reason
# on failure (no silent None → generic-error fallback).
audio_path = await download_audio(job_id, temp_dir, storage, job, job_manager)
if not audio_path:
raise Exception("Failed to download audio file")
job_log.info(f"Audio downloaded: {os.path.basename(audio_path)}")
download_span.set_attribute("audio_file", os.path.basename(audio_path))
@@ -552,6 +553,17 @@ async def process_lyrics_transcription(job_id: str) -> bool:
logger.info(f"[job:{job_id}] WORKER_END worker=lyrics status=success duration={duration:.1f}s")
return True
except DownloadError as e:
duration = time.time() - start_time
job_log.error(f"Audio download failed: {str(e)}", exc_info=True)
logger.error(f"[job:{job_id}] WORKER_END worker=lyrics status=error duration={duration:.1f}s error={e}")
job_manager.mark_job_failed(
job_id=job_id,
error_message=f"Audio download failed: {str(e)}",
error_details={"stage": "download_audio", "error": str(e)}
)
return False
except Exception as e:
duration = time.time() - start_time
job_log.error(f"Lyrics transcription failed: {str(e)}", exc_info=True)
@@ -587,13 +599,14 @@ async def download_audio(
job,
job_manager: JobManager,
max_wait_seconds: int = 300
) -> Optional[str]:
) -> str:
"""
Download audio file from GCS to local temp directory.
For URL jobs, the audio worker downloads from YouTube first and uploads to GCS.
We wait for the input_media_gcs_path to be set by the audio worker.
For URL jobs, the audio worker fetches the source via the flacfetch service
first and uploads it to GCS. We wait for the input_media_gcs_path to be set
by the audio worker.
Args:
job_id: Job ID
temp_dir: Temporary directory for download
@@ -601,9 +614,14 @@ async def download_audio(
job: Job object
job_manager: JobManager instance
max_wait_seconds: Maximum time to wait for audio worker to download
Returns:
Path to downloaded audio file, or None if failed
Path to the downloaded audio file.
Raises:
DownloadError: with a specific reason if the audio can't be obtained
(fail loudly with the real cause instead of returning None and
surfacing a generic "Failed to download audio file").
"""
import time
@@ -636,20 +654,30 @@ async def download_audio(
# Check if audio worker failed
if updated_job and updated_job.status == JobStatus.FAILED:
logger.error(f"Job {job_id}: Audio worker failed, cannot proceed with lyrics")
return None
raise DownloadError(
"Audio worker failed before lyrics could run; cannot "
"proceed without the downloaded/separated audio."
)
# Wait before next poll - use asyncio.sleep to not block event loop
await asyncio.sleep(poll_interval)
logger.error(f"Job {job_id}: Timed out waiting for audio download (waited {max_wait_seconds}s)")
return None
raise DownloadError(
f"Timed out after {max_wait_seconds}s waiting for the audio worker "
"to download the input audio."
)
logger.error(f"Job {job_id}: No input_media_gcs_path found and no URL")
return None
raise DownloadError(
"No input audio available (no input_media_gcs_path and no URL)."
)
except DownloadError:
raise
except Exception as e:
logger.error(f"Job {job_id}: Failed to download audio: {e}", exc_info=True)
return None
raise DownloadError(f"Failed to download audio for lyrics: {e}") from e
async def upload_lyrics_results(
+44
View File
@@ -505,6 +505,7 @@ async def redistribute_video(job_id: str) -> bool:
return False
temp_dir = tempfile.mkdtemp(prefix=f"karaoke_redist_{job_id}_")
orchestrator = None
try:
# Download existing finals from GCS by listing the finals folder
@@ -574,6 +575,10 @@ async def redistribute_video(job_id: str) -> bool:
gdrive_folder_id=dist.gdrive_folder_id,
enable_cdg=getattr(job, 'enable_cdg', False),
enable_txt=getattr(job, 'enable_txt', False),
# Redistributing an already-`complete` job: progress updates must not
# attempt status transitions (complete -> packaging is illegal and
# would abort the redistribution).
redistribute_mode=True,
)
orchestrator = VideoWorkerOrchestrator(
@@ -604,6 +609,24 @@ async def redistribute_video(job_id: str) -> bool:
await orchestrator._run_distribution()
await orchestrator._run_notifications()
# Verify the redistribution actually produced the archive before reporting
# success. The orchestrator swallows brand-code and Dropbox failures as
# non-fatal warnings, so an apparent "success" can hide a missing archive.
# Reporting success in that case would let the caller (public->private
# visibility change) delete the still-live public outputs against a
# non-existent private archive — the exact data-loss bug this path fixes.
if config.brand_prefix and not orchestrator.result.brand_code:
raise RuntimeError(
"Redistribution produced no brand code — archive identity is missing"
)
if config.dropbox_path:
dropbox_failed = any(
"Dropbox upload failed" in w
for w in (orchestrator.result.distribution_warnings or [])
)
if dropbox_failed:
raise RuntimeError("Redistribution failed to upload the Dropbox archive")
# Update job state_data with new distribution results
state_update = dict(job.state_data or {})
state_update['brand_code'] = orchestrator.result.brand_code
@@ -623,6 +646,27 @@ async def redistribute_video(job_id: str) -> bool:
except Exception as e:
logger.error(f"[job:{job_id}] WORKER_END worker=video-redistribute status=error error={e}")
# A brand code may have been allocated during _run_organization before the
# failure. It was never persisted to the job, so return it to the pool to
# avoid leaking a number (and, for a public->private change, so the caller's
# rollback leaves no orphaned NOMADNP code).
allocated = getattr(getattr(orchestrator, "result", None), "brand_code", None)
if allocated:
try:
from backend.services.brand_code_service import (
BrandCodeService,
get_brand_code_service,
)
prefix, number = BrandCodeService.parse_brand_code(allocated)
get_brand_code_service().recycle_brand_code(prefix, number)
logger.info(
f"[job:{job_id}] Recycled brand code {allocated} after failed redistribution"
)
except Exception as recycle_err:
logger.warning(
f"[job:{job_id}] Failed to recycle brand code {allocated} "
f"after failed redistribution: {recycle_err}"
)
return False
finally:
+29 -7
View File
@@ -105,6 +105,14 @@ class OrchestratorConfig:
dry_run: bool = False
non_interactive: bool = True
# Redistribution mode: when True, this orchestrator run is redistributing the
# finals of an already-`complete` job (e.g. a public->private visibility change)
# rather than driving a fresh job through its lifecycle. In this mode
# _update_progress must NOT attempt job status transitions — the job is (and
# stays) `complete`, and `complete -> packaging`/`encoding` are illegal
# transitions that would otherwise abort the redistribution.
redistribute_mode: bool = False
@dataclass
class OrchestratorResult:
@@ -234,14 +242,28 @@ class VideoWorkerOrchestrator:
return self._discord_service
def _update_progress(self, status: JobStatus, progress: int, message: str):
"""Update job progress if job_manager is available."""
if self.job_manager:
self.job_manager.transition_to_state(
job_id=self.config.job_id,
new_status=status,
progress=progress,
message=message
"""Update job progress if job_manager is available.
In redistribute_mode the job is already `complete` and must stay that way,
so we update only the progress percentage/message and skip the (illegal)
status transition. Outside redistribute_mode this drives the normal
lifecycle transition with validation.
"""
if not self.job_manager:
return
if self.config.redistribute_mode:
# Progress-only update; do not transition status (job stays `complete`).
self.job_manager.update_job(
self.config.job_id,
{"progress": progress},
)
return
self.job_manager.transition_to_state(
job_id=self.config.job_id,
new_status=status,
progress=progress,
message=message
)
async def run(self) -> OrchestratorResult:
"""
+81 -4
View File
@@ -544,13 +544,25 @@ Content-Type: application/json
{
"source": "manual",
"lyrics": "Full lyrics text...",
"force": false
"force": "false"
}
```
Adds user-pasted lyrics as a new reference source, re-runs the correction pipeline with all sources, and uploads updated corrections to GCS. The `force` flag (default `false`) bypasses the relevance threshold — use when the transcription is poor and a low match % doesn't mean wrong song.
Adds user-pasted lyrics as a new reference source, re-runs the correction pipeline with all sources, and uploads updated corrections to GCS. The `force` flag (default `false`, sent as a string because the body is typed `Dict[str, str]`) bypasses the relevance threshold — use when the transcription is poor and a low match % doesn't mean wrong song.
Returns `{ "status": "success", "data": <CorrectionData> }`.
Returns `{ "status": "success", "data": <CorrectionData> }` when the source is kept.
If the relevance filter drops the source (below the 30% anchor-match threshold), the corrections are **not** persisted and the response is instead:
```json
{
"status": "rejected",
"rejection": { "relevance": 0.013, "matched_words": 3, "total_words": 230 },
"data": { "...": "CorrectionData from the discarded rerun" }
}
```
The frontend paste tab shows the match % and offers "Add Anyway", which retries with `force: "true"`.
#### AI Auto-Correct Suggestions
@@ -1504,10 +1516,70 @@ Authorization: Bearer ADMIN_TOKEN
Returns full user profile including:
- User info and stats
- `locale` (email locale: en/es/de) and `ui_locale` (full UI language, any of 33)
- Recent credit transactions (last 20)
- Recent jobs (last 10)
- Recent jobs (last 10, each with its `locale`)
- Active sessions count
### Email History (Admin)
List every email ever sent to a user, then fetch one for full-fidelity preview.
Merges the Postmark Messages API (last ~45 days, with delivery metadata) with a
persisted Firestore `email_log` (permanent), de-duplicated by message id.
```http
GET /api/admin/users/{email}/emails
Authorization: Bearer ADMIN_TOKEN
```
Response: `{ email, count, postmark_available, emails: [{ message_id, source,
subject, to, from_email, sent_at, status, email_type, has_stored_html }] }`.
```http
GET /api/admin/emails/{message_id}?source=postmark
Authorization: Bearer ADMIN_TOKEN
```
`source` is `postmark` (default; falls back to the stored log on 404/expiry) or
`log` (read the persisted copy directly). Returns the full rendered `html_body`,
`text_body`, addressing, `status`, `delivered_at`, `open_count`, `click_count`,
`bounce`, and the raw `events`.
### Create User (Admin)
Create a user account directly — e.g. to grant credits, submit jobs on behalf of,
or impersonate someone who has never logged in. The user can later log in normally
via magic link with the same email.
```http
POST /api/users/admin/users
Authorization: Bearer ADMIN_TOKEN
Content-Type: application/json
{
"email": "user@example.com",
"display_name": "Optional Name",
"initial_credits": 3,
"credit_reason": "made-for-you order"
}
```
Response (201):
```json
{
"status": "success",
"email": "user@example.com",
"credits": 3,
"message": "Created user user@example.com with 3 credit(s)"
}
```
Notes:
- `display_name`, `initial_credits` (0-1000), and `credit_reason` are optional
- If `initial_credits` > 0, `welcome_credits_granted` is set so the user does NOT
also receive the automatic welcome credit on first login
- Returns 409 if the user already exists
### Add Credits (Admin)
```http
@@ -1783,6 +1855,11 @@ Updates editable job fields. Allowed fields: `artist`, `title`, `user_email`, `t
**Note:** Setting `is_private=true` on a completed job with existing outputs triggers automatic output deletion.
**Note:** `user_email` is trimmed and lowercased before saving. If no account exists
for that email, one is auto-created (so the recipient can log in and see the job,
and the admin can impersonate them immediately). The response message notes when
an account was created.
Response:
```json
{
+110 -2
View File
@@ -14,6 +14,7 @@
| BigQuery (monthly) | S3 `bigquery/musicbrainz/` | Load Parquet files | 30 days |
| BigQuery (Spotify) | S3 `bigquery/spotify/` | Load from Glacier Deep Archive | N/A (static) |
| GCS job files | S3 `gcs/job-files/` | Sync to new bucket | 24h |
| Git repos (code) | S3 `git-repos/{owner}/{repo}.bundle` (+ `manifest.json`) | `git clone <bundle>` then push to a new remote | 24h |
| Secret Manager | S3 `secrets/YYYY-MM-DD.bin` (sealed-box encrypted) | Decrypt with private key from KeepassXC | 24h |
| AWS credentials (function) | GCP Secret Manager `aws-backup-credentials` | Read directly | On-change |
| AWS credentials (offline) | KeepassXC — "Nomad Karaoke — DR backup AWS access" | Manual lookup | On-change |
@@ -24,6 +25,7 @@
- [ ] KeepassXC contains "Nomad Karaoke — DR backup AWS access" (access key, secret key, region, S3 bucket name)
- [ ] KeepassXC contains "Nomad Karaoke — DR backup decryption key" (Curve25519 private key, 64 hex chars)
- [ ] GitHub repo `nomadkaraoke/karaoke-gen` has the secrets `AWS_BACKUP_READONLY_ACCESS_KEY_ID`, `AWS_BACKUP_READONLY_SECRET_ACCESS_KEY`, `DR_MONITOR_DISCORD_WEBHOOK` configured (powers the freshness monitor)
- [ ] GCP Secret Manager `github-backup-token` holds a valid GitHub PAT (`repo` + `read:org`) so the nightly job can bundle every repo — without it the git-repo backup silently skips (see § "Git repo backup setup")
- [ ] You can decrypt yesterday's secrets backup locally (run the drill in § "Quarterly restore drill")
- [ ] Your KeepassXC database itself is backed up off-machine (cloud sync, second device, or printed paper recovery)
@@ -301,6 +303,112 @@ Some external services lock to redirect URIs or treat the old GCP project ID as
- Discord webhook URLs (re-issue if old GCP exposure could have leaked them)
- Cloudflare API tokens (rotate)
## Scenario 3: Loss of GitHub access (account ban / repo takedown)
If the GitHub account is suspended (e.g. an automated copyright false-positive)
or repos are taken down, **the code and its full history are still in S3**. The
nightly backup bundles every repo under `github.com/nomadkaraoke` and
`github.com/beveradb` into a single `git bundle` per repo — a self-contained
file you can clone from directly, no GitHub required. GCP is unaffected, so
production keeps running; this is purely about recovering the source of truth to
a new home.
### What's backed up
- `s3://nomadkaraoke-backup/git-repos/{owner}/{repo}.bundle` — one bundle per
repo, containing **all branches and tags** (entire reachable history).
- `s3://nomadkaraoke-backup/git-repos/manifest.json` — inventory of every repo
at backup time: visibility, default branch, description, size, fork/archived
flags, and per-repo backup status. Use it to know exactly what existed and to
recreate repo settings on the new host.
Forks are excluded by default (recoverable from upstream). Repos are only as
fresh as the last nightly run (24h RPO).
### Restore
```bash
# 1. Set AWS creds (see § "Setting AWS creds locally") and pull the bundles.
aws s3 sync s3://nomadkaraoke-backup/git-repos/ /tmp/git-repos/
# 2. Review the inventory — what existed, and did every repo back up cleanly?
jq '{total, bundled, errors, skipped, repos: [.repos[] | {full_name, status, default_branch, private}]}' \
/tmp/git-repos/manifest.json
# 3. Reconstruct the repo from any bundle. Use --mirror so EVERY branch and tag
# is restored as a real ref — a plain `git clone` keeps non-default branches
# only as remote-tracking refs, and `git push --all` would then omit them.
cd /tmp/git-repos/nomadkaraoke
git clone --mirror karaoke-gen.bundle karaoke-gen.git
cd karaoke-gen.git
git show-ref # every branch + tag is present as a real ref
# 4. Point it at a new remote and push everything (--mirror pushes all refs).
# New home options: a fresh GitHub org/account, GitLab, Codeberg, or a
# self-hosted Gitea. Create the empty repo there first, then:
git remote set-url origin <NEW_REMOTE_URL> # bare mirror already has 'origin'
git push --mirror origin
# (For a normal working clone afterwards: `git clone <NEW_REMOTE_URL>`.)
```
To restore *all* repos in one pass:
```bash
cd /tmp/git-repos
for owner in */; do
for bundle in "$owner"*.bundle; do
name=$(basename "$bundle" .bundle)
# --mirror preserves all branches/tags; `git clone` creates leading dirs.
git clone --mirror "$bundle" "restored/${owner}${name}.git"
# then: cd in, `git remote set-url origin <NEW_URL>`, `git push --mirror origin`
done
done
```
**Verify a bundle without cloning:** `git bundle verify /tmp/git-repos/nomadkaraoke/karaoke-gen.bundle`.
### After restore — repoint tooling
The DR runbook, CI, `poetry`/`pip` VCS deps, and cross-repo scripts reference
`github.com/nomadkaraoke/...` URLs. Once repos live at a new host, update:
- Git remotes in every local clone / worktree
- CI/CD config that clones sibling repos (e.g. `flacfetch` in `karaoke-gen`)
- Any `poetry`/`pip` dependency pinned to a GitHub URL
- Webhooks / deploy keys / Actions secrets on the new host
- `GIT_BACKUP_OWNERS` + the `github-backup-token` PAT so the nightly backup keeps
bundling from the new location
## Git repo backup setup
One-time setup so the nightly job can bundle private repos:
1. Create a GitHub PAT owned by **beveradb** (a member of the `nomadkaraoke` org):
- **Classic PAT:** scopes `repo` (full, to read private repos) + `read:org`
(to enumerate org repos). Simplest.
- **Fine-grained PAT:** resource owner = beveradb *and* a second token for the
nomadkaraoke org (fine-grained tokens are single-owner); grant
`Contents: Read-only` + `Metadata: Read-only`. Classic is easier here.
2. Store it in Secret Manager (value added manually — Pulumi only creates the
empty secret resource):
```bash
printf %s '<PAT>' | gcloud secrets versions add github-backup-token \
--data-file=- --project=nomadkaraoke
```
Also keep a copy in KeepassXC as "Nomad Karaoke — DR GitHub backup PAT".
3. The owners backed up are set by the `GIT_BACKUP_OWNERS` env var on the
`backup-to-aws` function (default `nomadkaraoke,beveradb`), wired in
`infrastructure/modules/backup.py`.
4. Trigger a run and confirm bundles appear:
```bash
curl -X POST -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
https://us-central1-nomadkaraoke.cloudfunctions.net/backup-to-aws
aws s3 ls s3://nomadkaraoke-backup/git-repos/ --recursive | head
```
If the PAT is missing/expired the git-repo step logs a warning and skips; the
freshness monitor then flags `git-repos/` as stale within ~36h.
## Decrypting the secrets backup
```bash
@@ -341,13 +449,13 @@ export AWS_DEFAULT_REGION=us-east-1
## Backup freshness monitor
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `gcs/job-files/`, `secrets/`, and `bigquery/daily-refresh/` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `gcs/job-files/`, `secrets/`, `bigquery/daily-refresh/`, and `git-repos/` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
Per-prefix limits reflect each prefix's **S3 (off-site)** cadence, which is not the same as its GCS-staging cadence:
| Prefix | S3 upload cadence | Monitor limit |
|--------|-------------------|---------------|
| `gcs/job-files/`, `secrets/` | nightly | 36h |
| `gcs/job-files/`, `secrets/`, `git-repos/` | nightly | 36h |
| `firestore/`, `bigquery/daily-refresh/` | weekly (Sundays) | 192h (≈8 days) |
Firestore exports to GCS staging nightly (24h local restore point) but only ships to S3 weekly to cut cross-cloud egress (see `backup_to_aws/main.py` → `firestore_to_s3_today`). The monitor only sees the S3 copy, so its Firestore limit must allow a full week — using the 36h nightly figure caused a false "DR backup is stale" alert every Tue–Sat (fixed 2026-06-18).
+1
View File
@@ -274,3 +274,4 @@ The cloud function does metadata-only checks via the GDrive API (fast, cheap, ca
- **2026-02-28**: Added SendGrid email (primary), kept Pushbullet (fallback). Added post-job trigger from backend. Added `scripts/check_public_share.py` for manual invocation. Motivated by NOMAD-1271 duplicate brand code incident where daily-only checks left a duplicate undetected for ~24 hours.
- **2026-03-02**: NOMAD-1276 incident fix. Post-job trigger now uses 5-minute Cloud Tasks delay instead of immediate invocation, preventing false "all clear" when E2E test files are still in GDrive during cleanup. Also fixed cross-folder gap detection (uses global max across all folders) and added 28 unit tests for the Cloud Function.
- **2026-03-06**: NOMAD-1295 gap. Stale GCE encoding cache (#499) caused job `f4a552bf` to produce bad output on first run (allocated NOMAD-1295, only CDG uploaded). Admin re-triggered the job, which allocated a new brand code (NOMAD-1297) without recycling 1295. Fix: recycled 1295 back to the pool. Updated docs to clarify that new gaps must always be investigated and fixed, never added to KNOWN_GAPS.
- **2026-08-18**: NOMAD-1537 gap. A **public→private visibility change** on job `25d076e5` (`Alma Nocturna – Mejor Cállate`) deleted the public GDrive/YouTube/Dropbox outputs and recycled 1537, then the private redistribution crashed (`redistribute_video` drove an illegal `complete → packaging` transition), so the change failed *after* the public files were already gone — a delete-first, no-rollback flow. The daily validator caught the hole; it self-closed when an unrelated public job reused the recycled 1537. **Going-private is a legitimate cause of a transient gap** (the number is recycled and refilled by the next public track) — the alert is expected and desired, not suppressed. Fixes (v0.196.1): `redistribute_video` runs in `redistribute_mode` (no status transition, stays `complete`); `change_to_private` is now **distribute-then-delete** (public outputs removed only after the private archive succeeds; on failure the job stays fully public); failed redistributions recycle any allocated `NOMADNP` code. Validator intentionally left unchanged.
+80
View File
@@ -6,6 +6,51 @@ Key insights for future AI agents working on this codebase.
---
## Don't Invent Silent Fallbacks — Ask or Fail Loud (Jun 2026)
When the desired behaviour for an edge case is unclear, **do not** invent a quiet
fallback that lets the system keep going while doing the wrong thing. Either ask
the human, or fail loudly with a clear, specific error. Silent fallbacks hide
bugs: the system "works" while producing wrong output, and the real failure
surfaces much later (or never).
**Motivating incident (2026-06-08):** a Facebook-URL job failed with a generic
"Failed to download audio file". A non-YouTube path had silently fallen back to
running yt-dlp *inside the Cloud Run container* (flacfetch was supposed to be the
sole downloader), which then died in a broken `convert_to_wav`. The download had
actually succeeded — the fallback was both unintended and broken. The fix
**deleted** the fallback rather than patching it.
A full audit of the codebase's fallback paths followed — see
`docs/archive/2026-06-09-fallback-audit-plan.md` for the catalogue and the
per-item decisions.
**Rules of thumb:**
- A function that can't produce its result should **raise a specific exception**,
not `return None` and let a caller surface a generic message. (See
`download_audio()` in `backend/workers/audio_worker.py` / `lyrics_worker.py`:
each failure mode now raises `DownloadError` with the real reason.)
- "If X isn't configured, silently do Y instead" is the most dangerous shape —
especially around download, payment, job-state, and worker-triggering. Prefer
failing closed and visibly. (See `YouTubeDownloadService.download` — no
flacfetch → raises, no local yt-dlp.)
- Don't trust a comment that *says* a path is a safe fallback — verify what the
user actually observes when it triggers.
- Comments/docstrings must not lie about fail-open vs fail-closed. The credit
evaluation service is **fail-closed** (`pending_review` on error); its
docstrings used to claim fail-open, which would have tempted a future
maintainer to "fix" the code into a free-credit-abuse hole.
- A safe-but-silent fallback (e.g. empty `ADMIN_TOKENS` → everything 403s) should
still log at ERROR so the error monitor alerts — a quiet warning reads as an
auth bug, not a config error.
Good loud-failure models already in the tree to copy:
`lyrics_transcriber/output/video.py` (raises on a missing background image) and
`backend/services/visibility_change_service.py` (checks the trigger result,
restores state, and raises rather than silently dropping a worker trigger).
---
## Multi-instance-type encode pool: one shared speed-rank, availability-aware (Aug 2026, v0.195.0)
"c4d primary + a single n2 fallback family" is not resilient — a stockout is per
@@ -980,6 +1025,41 @@ All status transitions after workers complete fail silently because they're inva
- `test_youtube_url_calls_start_job_processing_after_download` - verifies proper sequence
- `TestInvalidStateTransitionError`, `TestValidateStateTransitionRaisesBehavior`, `TestStartJobProcessing` in `test_job_manager.py`
### Made-For-You Order Emails Must Be Isolated From Audio Acquisition (Aug 2026)
**Problem**: Job 17dc6f48 (made_for_you order) failed on a YouTube "confirm you're
not a bot" download error, and the admin never received the "New Made-For-You Order
Received!" email. The error-fallback then crashed with
`'EmailService' object has no attribute 'send_email'`, so even the failure alert was lost.
**Root cause**: In `_handle_made_for_you_order`, both the customer order-confirmation
and the admin notification were sent *after* the fallible audio-acquisition step
(YouTube download / audio search). When acquisition raised, execution jumped straight
to the outer `except`, skipping BOTH emails. Separately, the fallback called
`email_service.send_email(...)` — a method that only existed on the *provider*
(`self.provider.send_email`), never on `EmailService` itself.
**Fix**:
1. Send the customer order-confirmation email **up-front**, right after job creation and
*before* audio acquisition — the order is paid/confirmed regardless of whether the
download or search succeeds. Wrapped so an email error is logged, not fatal.
2. Wrap the admin notification so an email hiccup on a successful order can't fake a
`[FAILED]` alert.
3. Route the outer failure handler through `_send_mfy_failure_alert()` (never raises,
HTML-escapes user input, tolerates `job_id=None`): success → normal admin
notification; acquisition failure → `[FAILED]` admin alert while the customer is
still confirmed.
4. Add a thin `EmailService.send_email()` passthrough to the provider so ad-hoc/plain
emails (like the failure alert) work.
**Why tests didn't catch it**: `email_service` was a `MagicMock` in the handler tests,
so `mock.send_email(...)` auto-created the attribute and never surfaced the real
`AttributeError`. **Pattern**: for critical fallbacks, add at least one test that
exercises the real `EmailService` (only mocking `.provider`), and assert that a failure
in a *later* step (audio) does not suppress *earlier* side effects (the confirmation
email). Idempotency note: mark the Stripe session processed *before* sending the
confirmation so a webhook retry can't double-send.
### Use data-testid for E2E
Prefer `data-testid` over label/text selectors. They're immune to label changes and won't break when similar fields are added.
+4
View File
@@ -55,6 +55,10 @@
## Recent Changes
- **Admin Dashboard Stats 18s → ~1s** (2026-08-23): `GET /api/admin/stats/overview?exclude_test=true` streamed every user and job document **in full** to filter test data in Python — ~110 MB across 658 jobs (job docs carry `state_data`/timeline payloads), ~18s per dashboard load. Worse, the sync streaming ran inside an async route, blocking the event loop so every other request on the instance (`/me`, `/config`, payments summary) stalled behind it. **Fix**: Firestore `.select()` field masks on all three streams (jobs need only `user_email`/`created_at`/`status`; measured 15.0s → 1.1s for the jobs stream) and the whole computation now runs via `asyncio.to_thread()` so it can't stall other requests. Unit tests assert the field masks stay in place. Same sync-over-async trap as the Feb 2026 audio-search fix — see [LESSONS-LEARNED.md](LESSONS-LEARNED.md#never-call-sync-over-async-from-fastapi-async-routes-feb-2026).
- **Admin UI/UX Overhaul** (2026-08-22): Made the admin pages usable on mobile and fixed the long-standing overflow problems on the job detail page (v0.197.0). Long status timelines (retried/edited jobs) now collapse to the last 6 stages behind a "+N earlier (M failed)" expander; the Source field no longer bleeds across the info grid (CSS grid `min-w-0`); the Audio Source Details modal got wrap-safe stacked rows plus an "Open in YouTube/Spotify" link built from provider + source ID; Configuration fields are click-to-edit with always-visible pencils. The jobs list search box jumps straight to a job when given a job ID, and the status filter is URL-synced (`/admin/jobs?status=failed`), which the dashboard's now-clickable stat cards and status-breakdown rows link into. Also fixed a real crash: the "Trigger Now" button in the reset-result dialog referenced a deleted handler. Users list/detail, breadcrumbs, and the admin header are all responsive down to phone widths. 4 new e2e tests.
- **Portrait (9:16) Karaoke Video Output** (2026-07-13): When enabled (`PORTRAIT_RENDER_ENABLED`, default on), every finalised job also gets a portrait 1080×1920 karaoke video for phone viewing / social sharing, distributed to **GCS + the Dropbox brand-code folder only** (never Drive/YouTube). It is a genuine **re-render** at portrait resolution with re-wrapped lyrics — not a transform of the finished landscape video (letterbox = tiny lyrics, crop = cuts the ends off every line; proven in the design experiments). The new `karaoke_gen/portrait/` module reuses the same `SubtitlesGenerator` engine + corrected-lyrics data, so word-by-word timing is identical; it adds an orphan-merging wrapper, a branded portrait background (wordmark/header + song/artist + footer), and title/end cards. Rendered on the GCE encoder inside `run_encoding` (best-effort + `PORTRAIT_RENDER_ENABLED` flag; a failure never fails the job) and carried to Dropbox via the existing `finals/` upload path. ~15–30s + ~10 MB per job. See [archive/2026-06-14-portrait-video-design.md](archive/2026-06-14-portrait-video-design.md) and [archive/2026-07-13-portrait-video-plan.md](archive/2026-07-13-portrait-video-plan.md).
- **Cloudflare Edge Security for the Backend API** (2026-07-20): `api.nomadkaraoke.com` is now proxied through Cloudflare (WAF + rate limiting + origin lock), after a vuln-scanner hammered the previously directly-exposed Cloud Run origin. WAF blocks exploit/secret-exposure paths (`contains` operator — regex needs a Business plan); per-IP rate limiting excludes `/api/internal/*`; a Transform Rule injects a secret `X-Edge-Auth` header that the backend's `EdgeAuthMiddleware` (`EDGE_AUTH_MODE=enforce`) requires, blocking direct-to-`*.run.app` bypass (health/root exempt). Key finding: the Cloud Run managed cert can't provision behind Cloudflare, but zone SSL mode "full" (not strict) doesn't validate the origin cert, so it works and is renewal-safe — **never switch the zone to "full (strict)".** Managed as IaC in `infrastructure/modules/edge_security.py`. Also retuned the "High Error Rate" alert to 5xx-only (scanner 404s no longer page). See [ARCHITECTURE.md § Edge Security](ARCHITECTURE.md#edge-security-cloudflare), [LESSONS-LEARNED.md](LESSONS-LEARNED.md#cloudflare-edge-in-front-of-cloud-run--the-ssl-dragon-jul-2026), and [archive/2026-07-20-edge-security-cutover-runbook.md](archive/2026-07-20-edge-security-cutover-runbook.md).
@@ -0,0 +1,237 @@
# Fallback Logic Audit — karaoke-gen (2026-06-09)
**Driver prompt:** `docs/archive/2026-06-08-fallback-logic-audit-prompt.md`
**Motivating incident:** 2026-06-08 Facebook-URL job → generic "Failed to download
audio file". A non-YouTube path silently fell back to running yt-dlp *inside the
Cloud Run container*, which died in a broken `convert_to_wav`. flacfetch was
supposed to be the sole downloader. The fix **deleted** the fallback rather than
patching it. See `docs/archive/2026-06-08-flacfetch-sole-downloader-plan.md` and
memory `project_flacfetch_sole_downloader`.
**Goal of this audit:** make every silent fallback an *explicit, intentional*
decision — fail loudly with a clear error, OR keep + log/alert, OR something
else. Do **not** change behaviour without Andrew's answer. Some fallbacks are
load-bearing graceful degradation and should stay.
**Classification:**
- **A** = legitimate graceful degradation (intended, fails safe + visible). Keep.
- **B** = silent fallback masking a bug/misconfig (like the yt-dlp case). Delete or fail-fast.
- **C** = ambiguous — needs Andrew's intent.
**Method:** 5 parallel read-only triage agents over (1) audio/lyrics acquisition,
(2) job-state & worker triggering, (3) payment/credits/referral/auth, (4)
karaoke_gen core render, (5) backend routes/services/config. Findings below are
verified against actual behaviour, not comments.
> **DECISION fields capture Andrew's answers verbatim** (interview held 2026-06-09).
---
## THEME 1 — Source downgrade: flacfetch → YouTube-only (the motivating class)
These reconstruct the exact "silently use a worse source" pattern that caused the
incident. flacfetch is supposed to be the sole/lossless downloader.
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 1.1 | `backend/services/audio_search_service.py:224-230` | **B** | Remote flacfetch search error → silently re-runs **local** flacfetch (YouTube-only on Cloud Run). Transient remote outage silently downgrades a RED/OPS lossless job to a YouTube rip; user sees only a `logger.warning`. |
| 1.2 | `karaoke_gen/audio_fetcher.py:405-433` | **B** | If `TorrentDownloader` import fails / Transmission down / tracker `*_API_URL` unset → RED/OPS skipped, only `YoutubeProvider` registered. The concrete mechanism behind 1.1. |
| 1.3 | `karaoke_gen/audio_fetcher.py:1818-1823` | **C** | If exactly one of `FLACFETCH_API_URL` / `FLACFETCH_API_KEY` is set → logs "falling back to local mode". A typo'd secret silently disables the remote service. |
| 1.4 | `karaoke_gen/audio_fetcher.py:558-577` | **C** | `select_best` returns result[0] on any ranking failure → may silently auto-pick a lower-quality source. |
**DECISION (Theme 1):** Andrew — **"Fail loudly, no YouTube fallback."** flacfetch
is the sole/lossless downloader; if it can't serve (remote error, RED/OPS
unavailable, half-configured), fail the job with a clear error rather than
silently ripping YouTube. Applies to 1.1–1.4.
---
## THEME 2 — Silent worker-trigger drops → jobs stall forever
A recurring pattern: a downstream worker is triggered fire-and-forget and the
boolean/return is discarded. If the enqueue fails, the job sits in an intermediate
state with **no error and nothing to recover it**. The user is often told "success".
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 2.1 | `backend/services/job_manager.py:1126-1137` | **B** | `_trigger_screens_worker` catches `RuntimeError` (no event loop) and just logs `# TODO: use message queue`. Called from `mark_lyrics_complete` in the **lyrics_worker Cloud Run Job** (sync). If it no-ops, `lyrics_complete=True` is written but screens worker never fires → job stalls before AWAITING_REVIEW; `recover_stuck_jobs` doesn't cover this. *(Verify: does a loop exist in that Job?)* |
| 2.2 | `backend/api/routes/review.py:504` | **B** | After REVIEW_COMPLETE, `asyncio.create_task(trigger_render_video_worker)` result discarded; endpoint returns `{"status":"success"}`. Failed enqueue → stuck at REVIEW_COMPLETE, no error, no auto-recovery. |
| 2.3 | `backend/workers/render_video_worker.py:281,546` | **B** | `await trigger_video_worker(job_id)` bool ignored. Failed trigger → job stuck at INSTRUMENTAL_SELECTED with render done but final encode never started. |
| 2.4 | `backend/api/routes/internal.py:725-728` | **C** | Retry scheduler resets parked job to REVIEW_COMPLETE then triggers; on raise the comment assumes it'll be re-picked as RENDER_PENDING_CAPACITY, but the next tick queries `status==RENDER_PENDING_CAPACITY` and won't see it. Escapes both retry query and 24h timeout sweep → stuck indefinitely. |
| 2.5 | `backend/services/encoding_service.py:1018-1020` | **B** | `get_encoding_service()` does `try: set_worker_manager(manager) except Exception: pass`. Any client-init failure → service silently runs with **no worker manager**, falls back to static URL, loses multi-zone capacity failover, no signal. |
| 2.6 | `audio_download_worker.py:291-294`, `job_manager.py:1078-1081`, `jobs.py:70-71`, `review.py:2208-2209` | **B** | `asyncio.gather(trigger_audio, trigger_lyrics)` results discarded across these sites. One failed enqueue → that pipeline branch silently never starts while the other proceeds; job hangs. |
**Model to emulate:** `backend/services/visibility_change_service.py:194-205` does it
right — checks `triggered`, logs error, restores state, raises.
**DECISION (Theme 2):** Andrew — **"Fail loud / re-park & retry."** Check every
trigger result; on failure mark the job failed or re-queue (the
`visibility_change_service` pattern) so a job can never silently stall. Applies
to 2.1–2.6. _(Still verify reachability of 2.1's no-event-loop path during impl,
but the directional call is fail-loud/retry.)_
---
## THEME 3 — Lyrics/transcription silently degraded or missing
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 3.1 | `karaoke_gen/lyrics_transcriber/core/controller.py:487-491` | **B** | If every transcriber returns empty (no exception, e.g. AudioShake 200 with no words), code logs a warning and proceeds; `process()` skips output but job is still reported "completed successfully". → karaoke video with **no synced lyrics**, no error. |
| 3.2 | `karaoke_gen/lyrics_processor.py:372-373` + `core/config.py:16` | **B/C** | `enable_local_whisper=True` hardcoded as priority-3 fallback. On a host with `whisper_timestamped` installed, AudioShake failure silently yields much lower-quality Whisper timing with no signal. (No-op on Cloud Run where pkg absent — env-dependent.) |
| 3.3 | `core/controller.py:396-398` | **C** | Failure loading existing corrections JSON is swallowed → silently re-transcribes from scratch, discarding prior **human review** work. |
| 3.4 | `core/controller.py:442-454` | **C** | Per-provider reference-lyric fetch errors (Genius/Spotify/LRCLIB/Musixmatch) swallowed; all-fail → "No lyrics found", correction runs transcription-only (lower accuracy). Masks systemic outages (e.g. expired Spotify cookie). |
**DECISION (Theme 3):** Andrew — **"Fail the job loudly."** No transcription
results = fail with a clear error; lyrics are the core deliverable and a
lyric-less "success" must never ship. Treat 3.1 as a hard fail. _(Apply the same
fail-loud principle to 3.2–3.4 during impl — silent low-quality Whisper and
silently discarding human-review corrections both violate the principle; flag if
any needs a different call.)_
---
## THEME 4 — Wrong font / asset / color on a paid deliverable
Silent substitution of a missing branded asset → a wrong-looking video/CDG the
customer paid for. Note the karaoke-render path at
`lyrics_transcriber/output/video.py:43-44` already **raises** on a missing
background — a good loud-failure model the others diverge from.
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 4.1 | `lyrics_transcriber/output/video.py:417-423` | **B** | Final karaoke MP4: if theme font file missing, `:fontsdir` is silently dropped → libass resolves via system fontconfig → whole song in a substitute font, no log above debug. |
| 4.2 | `video_generator.py:120-132,153,174,191` | **B** | Title/end screens: missing font → `ImageFont.load_default()` (~10px bitmap). 4K title/end card renders artist/title in a near-invisible default font. |
| 4.3 | `video_generator.py:368-377` | **B/C** | Title/end screen: missing `background_image` → silently uses flat `background_color` (karaoke path raises instead — inconsistent). |
| 4.4 | `lyrics_transcriber/output/cdg.py:294-306` | **B/C** | CDG: unresolved theme font → bundled `arial.ttf` (warning only). Hardware disc renders all lyrics in Arial. |
| 4.5 | `karaoke_finalise.py:1132-1159` | **B/C** | Duet job: missing/malformed `duet_corrections_json` → renders CDG via LRC path = **solo colors**, loses singer-color distinction (warning only). |
| 4.6 | `lyrics_transcriber/output/cdg.py:551-561` | **B/C** | Duet CDG: lost/length-mismatched line→singer map → defaults every line to singer 1 "to keep the file valid". Silently wrong color attribution. |
| 4.7 | `lyrics_transcriber/output/ass/config.py:115-117,149-151` | **B/C** | Malformed theme color → hardcoded default blue/black. A typo'd theme color renders lyrics in the wrong brand color. |
| 4.8 | `lyrics_transcriber/output/ass/lyrics_line.py:39-45` | **B/C** | Text-measurement font → `load_default()` (different metrics) while libass renders a different font → line-wrap decisions desync from the actual video. Pairs with 4.1. |
**A (keep, verified intended + logged):** GPU→CPU encode fallback
(`karaoke_finalise.py:1803-1881`, visually equivalent libx264, warned);
`style_loader.py:164-192` documented default duet palette;
`subtitles.py:100-107` audio-duration estimate (logged).
**DECISION (Theme 4):** Andrew — **"Fail loudly on missing branded asset."** Match
`video.py:43-44` which already raises. A paid deliverable shouldn't silently
substitute fonts/backgrounds/colors — fail with a clear error so it's caught
before delivery. Applies to 4.1–4.8. _(Keep the confirmed-A items: GPU→CPU
encode, documented duet palette, audio-duration estimate.)_
---
## THEME 5 — Pricing undercharge / ceiling bypass
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 5.1 | `backend/api/routes/jobs.py:128-134` + `services/pricing.py:13-22` | **B** | Client-supplied `duration_seconds`; if `None`, `duration_to_credits(None)=1` and `is_blocked(None)=False`. Omitting duration → any-length job for 1 credit **and** skips the 60-min hard ceiling. `acknowledged_credits` guard only fires if client *sends* a mismatch. |
| 5.2 | `backend/api/routes/jobs.py:2446-2466` (`create_job_from_search`) | **B** | Guided/search flow never passes `credits=` → always `JobCreate.credits=1` regardless of length. Inconsistent with URL path; long-input undercharge. |
| 5.3 | `backend/api/routes/users.py:97` | **B** | Referral discount: `except Exception: discount_percent = 10` on Firestore read failure. A 20% link charged at 10% on a transient error. |
**DECISION (Theme 5):** Andrew — **"Keep defaults but always enforce ceiling +
alert."** Keep the 1-credit default, but the 60-min hard ceiling must always be
enforced (never silently bypassed when duration is omitted), and any
undercharge / discount-guess must raise a Discord alert so it's visible.
_Impl note:_ when duration is unknown we still alert + apply the ceiling rather
than reject; charge-by-duration consistency between URL and search flows to be
handled under this (alert if they diverge). Applies to 5.1–5.3.
---
## THEME 6 — Lost paid orders / "Unknown" customer data
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 6.1 | `backend/api/routes/users.py:1105-1135` (`_handle_made_for_you_order`) | **B** | Broad `except Exception` swallows fulfilment failure *after Stripe charged*; emails admin "[FAILED]" but does **not** re-raise → webhook returns 200 (no Stripe retry). If the email also fails (line 1134 logs only), a paid $50 order silently vanishes. |
| 6.2 | `backend/api/routes/users.py:858-859` | **B** | Made-for-you order: `metadata.get("artist","Unknown Artist")`/`("title","Unknown Title")` → a paid video titled "Unknown Artist - Unknown Title" instead of rejecting the order. |
**DECISION (Theme 6):** Andrew — **"Re-raise + durable failed-order record."** On
made-for-you fulfilment failure, re-raise so Stripe retries AND/OR write a
durable `needs_manual_fulfilment` record (don't rely on an email an admin might
miss); reject orders missing artist/title rather than shipping "Unknown Artist -
Unknown Title". Applies to 6.1–6.2.
---
## THEME 7 — Env-var / config defaults masking prod misconfiguration
A single unset/rotated env var silently produces wrong behaviour with only a
warning. Env vars are set in Cloud Run today, but the defaults are landmines.
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 7.1 | `backend/services/dropbox_service.py:34` | **B** | `GOOGLE_CLOUD_PROJECT` default `"karaoke-gen"` (real project is `nomadkaraoke`). If unset → secret lookup targets a non-existent project; bare `except` swallows → Dropbox distribution silently disabled. |
| 7.2 | `backend/config.py:19-21` | **B** | GCS bucket defaults `karaoke-gen-storage[/-temp/-outputs]` ≠ real `karaoke-gen-storage-nomadkaraoke`. If `GCS_BUCKET_NAME` unset → reads/writes a non-existent bucket, runtime 500s deep in processing instead of boot failure. |
| 7.3 | `backend/services/worker_service.py:160-166` | **B** | If `CLOUD_RUN_SERVICE_URL` unset → worker base URL = `http://localhost:{PORT}` with no env guard. Workers invoked against localhost → jobs created but silently never run. |
| 7.4 | `backend/middleware/tenant.py:30-31,102-105` | **B (security)** | `IS_PRODUCTION` from `ENV/ENVIRONMENT=="production"`, but app default is `"development"`. If prod doesn't explicitly set it → `?tenant=<id>` query override active → **tenant spoofing** (impersonate white-label portal). *(Verify prod sets ENVIRONMENT=production.)* |
| 7.5 | `backend/services/email_service.py:230-245` | **B** | No `POSTMARK_SERVER_TOKEN` → silent `ConsoleEmailProvider`; all sends "succeed". In prod with token unset/rotated, magic-link/completion/receipt emails silently vanish → users can't log in or get downloads. |
**DECISION (Theme 7):** Andrew — **"Fail-fast at startup in prod."** When
`ENVIRONMENT=production`, require these vars and refuse to boot (or go
health-check red) if missing; make the tenant-detection gate production-safe by
default (disable `?tenant=` override unless explicitly development). No silent
wrong-resource defaults. Applies to 7.1–7.5. _Impl note:_ first confirm prod
actually sets `ENVIRONMENT=production` (Pulumi `cloud_run.py`) — the security
gate 7.4 depends on it.
---
## THEME 8 — Lower-risk cleanups (docs lie, opaque errors, auth layers)
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 8.1 | `backend/config.py:77-78` & `credit_evaluation_service.py` module/`grant_welcome_credits` docstrings | **C/doc** | Docstrings say "Fail-open: credits granted on error" but code is **fail-CLOSED** (`pending_review`, no grant) — the *safe* behaviour. The lie risks a future maintainer "fixing code to match docs" and re-introducing free-credit abuse. Fix the docs, confirm policy. |
| 8.2 | `youtube_download_service.py:11,37-38`; `lyrics_worker.py:566` | **doc** | Stale docstrings still describe the deleted yt-dlp fallback ("falls back to local yt_dlp"). Misleading post-incident. |
| 8.3 | `backend/workers/audio_worker.py:467-473`, `lyrics_worker.py:611-623` → `audio_worker.py:217-218` | **C** | Distinct download failure causes all collapse to `return None` → generic user-facing "Failed to download audio file" (the opaque message from the incident). Surface specific reasons to the user? |
| 8.4 | `backend/api/routes/users.py:734-762` (`create_checkout`) | **C** | Unauthenticated; email + referral-discount taken from request body. Anyone can compute a discount against an arbitrary email. Direct money risk low (webhook keys off session metadata). Intended pre-login flow? |
| 8.5 | `backend/services/auth_service.py:107-111` | **C** | OIDC verified with `audience=None` (audience check skipped); mitigated by strict `token_email == scheduler SA`. Acceptable or tighten to URL allowlist? |
| 8.6 | `backend/services/auth_service.py:81-90` | **C** | Empty `ADMIN_TOKENS` → warning only; all admin endpoints 403 (fails closed = safe, but looks like an auth bug not a config bug). Louder signal in prod? |
| 8.7 | `backend/services/email_validation_service.py:226` | **C** | Missing Firestore blocklist doc → `DEFAULT_DISPOSABLE_DOMAINS` (the Firestore `.get` itself is unwrapped, so hard failures propagate — good). Acceptable degradation? |
**DECISION (Theme 8):** Andrew — **"Fix docs + specific errors + admin-token
signal."** Correct the lying/stale docstrings (8.1 fail-open→fail-closed, 8.2
yt-dlp), surface specific download-failure reasons to the user instead of the
generic "Failed to download audio file" (8.3), and add a loud prod signal when
`ADMIN_TOKENS` is empty (8.6). Leave 8.4 (unauth checkout), 8.5 (OIDC
audience=None), 8.7 (blocklist default) as acceptable fail-safe.
---
## A — Legitimate graceful degradation confirmed (no change; listed for the record)
- `audio_transcoding_service.py:113-130,171-175` — review-audio transcode fail → serve original FLAC (logged).
- `backend/workers/audio_worker.py:207-211` — audio separation not configured → **raises** (good model).
- `youtube_download_service.py:118-126` — flacfetch unconfigured → **raises** (the post-incident fix).
- `audio_download_worker.py:341-342` — unsupported source → raises `DownloadError` (post-fix state of the incident).
- `video_worker.py:182-185` — `_encode_via_gce` re-raises on GCE failure (no silent local fallback).
- `local_encoding_service.py:241-264` — GPU→CPU encode, warned. Visible perf degradation.
- `stripe_service.py` (multiple) — unconfigured/invalid → fail closed + visible.
- `user_service.py:1003-1017` — `add_credits` idempotent via `PROCESSED_STRIPE_SESSIONS`.
- `job_manager.py:146-164` — credit-deduction failure deletes job + raises `InsufficientCreditsError`.
- `referral_service.py:283-305` — `record_earning` returns None only for invalid/expired referral; wrapped so it never blocks the buyer's credits.
- `catalog_proxy_service.py:71,103` — autocomplete `[]` on karaoke-decide outage (cosmetic).
- `credential_manager` distribution checks — distinct NOT_CONFIGURED/INVALID/ERROR/VALID, blocking 400 on create-from-url.
- `file_upload.py:1827-1833` (create-from-url) — re-raises, calls `fail_job`, 500 with real detail.
---
## Execution roadmap (Phase 4) — one PR per theme, with tests
Ordered safest/clearest → most delicate. Each PR updates `docs/LESSONS-LEARNED.md`
with the principle ("don't invent silent fallbacks — ask or fail loud") + the
notable example(s) it fixes.
| PR | Theme | Decision in one line | Risk |
|----|-------|----------------------|------|
| 1 | **T8** docs/errors | Fix lying fail-open docstrings + stale yt-dlp docstrings; surface specific download-failure reasons; loud prod signal on empty ADMIN_TOKENS | Low |
| 2 | **T1** sourcing | flacfetch sole downloader → fail loud (no silent YouTube downgrade) across 1.1–1.4 | Low/Med |
| 3 | **T4** render assets | Missing branded font/bg/duet-color → raise (match video.py:43-44) across 4.1–4.8 | Med |
| 4 | **T7** env config | Prod fail-fast on missing required vars; tenant gate production-safe by default | Med (verify Pulumi env first) |
| 5 | **T3** lyrics | Empty transcription = fail loud; same principle to whisper/corrections/reference | Med |
| 6 | **T2** worker triggers | Check every trigger result → fail/re-park; never silently stall (2.1–2.6) | High (job state machine) |
| 7 | **T5** pricing | Keep 1-credit default but always enforce 60-min ceiling + alert on undercharge/discount-guess | High (money) |
| 8 | **T6** paid orders | Re-raise + durable needs_manual_fulfilment record; reject missing artist/title | High (money/webhook) |
**Status:** Phases 1–3 complete (discover + triage + interview; all 8 decisions
captured above). Phase 4 (execute) — pending sequencing go-ahead from Andrew.
@@ -0,0 +1,204 @@
# Plan: Fix visibility-change redistribution + make sequence-gap alerts recycle-aware
**Created:** 2026-08-18
**Branch:** feat/sess-20260818-1124-visibility-recycle-dataloss
**Status:** Draft
## Overview
Investigation of a "GDrive Validation: missing 1537" alert traced to a **public→private
visibility change** on NOMAD-1537 (`Alma Nocturna – Mejor Cállate`, job `25d076e5`),
not a brand-code allocation race. Two real defects and one policy gap were found:
1. **`redistribute_video` always crashes** on `complete → packaging`
(`video_worker_orchestrator.py:661`), so **every** public→private conversion silently
fails its private-side redistribution — the track is never archived to the
`Tracks-NonPublished` Dropbox and never gets a `NOMADNP` code. It looks fine to the
customer because downloads serve from GCS finals.
2. **`change_to_private` deletes first, rebuilds second, with no rollback**
(`visibility_change_service.py:74-114`): it deletes YouTube/Dropbox/GDrive + recycles
the public number, *then* calls the (always-failing) redistribution. Each failure also
**leaks a `NOMADNP` code** (allocated, never saved, never recycled — e.g. `NOMADNP-0214`).
3. **The gdrive-validator has no awareness of intentionally-vacated numbers.** Going-private
recycles the public number (kept behaviour — see Decisions). Between recycle and the next
public job reusing it, the number is legitimately absent from the public share, so the
daily validator fires a false "missing" alert. (Here, `e921ab26 / Luvcat – Spider` later
reused 1537, closing the gap ~5h after the alert.)
### Root-cause timeline (UTC 2026-08-18, confirmed from logs)
- `00:05:54–58` — public→private on `25d076e5`: deleted YouTube `TJUKJRyb5MQ`, Dropbox folder,
GDrive public-share files for 1537; recycled `NOMAD-1537`; cleared distribution state.
- `00:06:07` — allocated `NOMADNP-0214`, started distribution, crashed
`Invalid state transition … complete -> packaging`; redistribution aborted, **no rollback**.
- `01:00:11` — gdrive-validator daily run reports `CDG/MP4/MP4-720p: missing 1537` → the alert.
- `05:5x` — unrelated public job `e921ab26` (Luvcat – Spider) allocated the recycled `1537`
and published under it.
- `07:0x` — GCS/divebar mirror pulled `NOMAD-1537 - Luvcat - Spider.*` → gap closed.
Customer impact: **none** — `25d076e5` is a healthy private track (GCS-backed downloads work).
Internal impact: no `Tracks-NonPublished` archive / `NOMADNP` code for it; one leaked private
code; spurious operator alert.
## Decisions (from product owner, 2026-08-18)
- **Number policy: recycle & reuse (keep current).** A vacated public number returns to the
pool and the next public job fills it.
- **Validator: leave as-is — the transient gap warning is DESIRED.** Going-private is rare, the
gap fills naturally on the next public track, and the owner explicitly wants the alert even
in that case. → **Part E is dropped**; no change to `gdrive_validator/main.py` or
`check_public_share.py`. Do not add anything to static `KNOWN_GAPS` either.
- **Private archive: yes — fix redistribution.** Going-private must archive to
`Tracks-NonPublished` with a `NOMADNP` code, consistent with native-private jobs, and must
be atomic (public outputs removed only after the private archive succeeds).
Scope is therefore **A–D only** (fix + harden the redistribution path and recover the one
affected job); the alerting pipeline is intentionally untouched.
## Requirements
- [ ] **A.** `redistribute_video` runs org+distribution+notifications on a `complete` job
without an illegal status transition; job remains `complete` throughout.
- [ ] **B.** `change_to_private` is **distribute-then-delete**: private redistribution +
`NOMADNP` allocation succeed *before* public YouTube/Dropbox/GDrive deletion + public
number recycle. On any failure: no public deletion, no leaked private code, job stays
fully public and `complete`.
- [ ] **C.** No leaked `NOMADNP` codes: a private code allocated during a redistribution that
later fails is recycled (or not allocated until the success path).
- [ ] **D.** Recover `25d076e5` (create its NonPublished archive + `NOMADNP` code) and recycle
the leaked `NOMADNP-0214`.
- [ ] Regression tests for A, B, C. All existing `test_change_visibility.py` tests still pass.
- [ ] Validator and `KNOWN_GAPS` unchanged (transient going-private alert is desired).
**Out of scope (explicitly not doing):** ~~E — recycle-aware validator~~. The owner wants to keep
receiving the gap warning for going-private events; it self-resolves on the next public track.
## Technical Approach
### A. Fix the `complete → packaging` crash (proximate bug)
`redistribute_video` (`backend/workers/video_worker.py:481`) reuses
`VideoWorkerOrchestrator._run_organization/_run_distribution/_run_notifications`;
`_run_distribution` calls `self._update_progress(JobStatus.PACKAGING, 90, …)`
(`video_worker_orchestrator.py:661`), which invokes `JobManager.transition_status(...,
raise_on_invalid=True)`. From `complete` that's illegal (`models/job.py:193`:
`COMPLETE → [AWAITING_REVIEW, LYRICS_COMPLETE]`).
**Chosen fix:** add a `redistribute_mode: bool = False` flag to `OrchestratorConfig`
(or an `update_status: bool` param threaded to `_update_progress`). When set, `_update_progress`
updates the progress **percentage/message only** and **skips the status write**, leaving the job
`complete`. Rationale: a redistribution is not a lifecycle change; the job is and remains
complete. Avoids polluting `STATE_TRANSITIONS` with a `COMPLETE↔PACKAGING` round-trip that other
call sites could misuse.
- Guard: keep `raise_on_invalid=True` for the normal pipeline; the flag only bypasses the write.
- Verify no other stage in the redistribute-only path (`_run_organization`, `_run_distribution`,
`_run_notifications`) performs a status transition that assumes a fresh pipeline.
### B. Distribute-then-delete + rollback (`change_to_private`) — as implemented
1. **Capture the public output references** (`youtube_url`, `brand_code`, `gdrive_files`,
`dropbox_path`, artist/title) from the job snapshot *before* anything mutates state —
redistribution overwrites `state_data` with the new private values.
2. Set the guard flag **and** `is_private=True` up front (a *temporary* flag) so
`get_effective_distribution_for_job()` selects the private destination during redistribution.
No "changed to private" timeline event yet.
3. **Redistribute to the private destination** (`redistribute_video`): reuse GCS finals
(`keep_gcs_finals` stays true — never deleted for this path), upload to `Tracks-NonPublished`,
allocate `NOMADNP` code. Public outputs are still live at this point.
4. **If redistribution fails** (raises or returns False): revert `is_private=False`, clear the
guard flag, re-raise `RuntimeError("Redistribution failed …")`. No public output was touched,
and `redistribute_video` already recycled any `NOMADNP` code it allocated (C) — a failed
going-private is a clean no-op.
5. **On success**, the private archive exists and the move has committed — from here we do
**not** revert to public. Delete the *public* outputs (YouTube, public Dropbox folder, public
GDrive files) via `_delete_public_outputs` (best-effort, never raises) and **recycle the public
`NOMAD` number** — but only if every public deletion succeeded (else keep the number reserved
to avoid a future duplicate). Then record the "changed to private" timeline event and clear the
guard flag.
Note the YouTube deletion is irreversible, which is *why* it must be last — the old delete-first
order could never be safely rolled back. `redistribute_video` additionally verifies the archive
actually materialized (brand code allocated + Dropbox upload not failed) before returning success,
because the orchestrator swallows brand-code/Dropbox failures as warnings; without this a false
"success" would delete the public outputs against a non-existent private archive.
### C. No leaked private codes
Two options; prefer (i):
- (i) Allocate the `NOMADNP` code inside the redistribution success path only; if redistribution
fails before it is persisted, nothing to recycle. Where allocation already happens early
(orchestrator `_run_organization`), wrap the redistribute call so a failure recycles
`orchestrator.result.brand_code` if one was allocated.
- (ii) Always recycle `orchestrator.result.brand_code` in the `except` path of `change_to_private`.
### D. Recovery (operational, after A–C deployed)
- **`25d076e5`:** re-run the fixed private redistribution (finals + packages confirmed present in
`gs://…/jobs/25d076e5/{finals,packages}/`). Produces the NonPublished archive + `NOMADNP` code.
Use the admin re-distribute path or a one-off `redistribute_video('25d076e5')` invocation.
- **Leaked `NOMADNP-0214`:** recycle into `brand_code_counters/NOMADNP.recycled` (currently
`next_number=216, recycled=[215]`), or leave — private prefixes aren't validated. Recycle for
hygiene.
- No action needed on `NOMAD-1537` (already correctly reused by Luvcat, gap closed).
### E. (dropped)
Recycle-aware validator suppression is intentionally **not** implemented — see Decisions. The
transient going-private gap warning is desired and self-resolves on the next public track. The
post-job re-validation trigger (`video_worker_orchestrator.py:305`, gated on `gdrive_folder_id`)
is correct as-is for private conversions (no public folder to re-check).
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `backend/workers/video_worker_orchestrator.py` | Modify | `redistribute_mode`/`update_status` flag; `_update_progress` skips status write when set |
| `backend/workers/video_worker.py` | Modify | `redistribute_video` passes the flag; recycle allocated code on failure |
| `backend/services/visibility_change_service.py` | Modify | Reorder `change_to_private` to distribute-then-delete; split `_delete_distributed_outputs`; recycle-on-failure |
| `backend/models/job.py` | Review | Confirm no `STATE_TRANSITIONS` change needed (preferred: none) |
| `backend/tests/test_change_visibility.py` | Modify | Real distribute-then-delete + rollback assertions (not just guard-flag) |
| `backend/tests/test_video_worker_redistribute.py` | Create | `redistribute_video` on `complete` job succeeds, no illegal transition |
| `docs/GDRIVE-VALIDATOR.md` | Modify | Add incident to History; note going-private is a legitimate (alerting) cause of gaps |
| `pyproject.toml` | Modify | Version bump |
## Testing Strategy
Follow `docs/TESTING.md`; backend unit/integration in `backend/tests/` (mock GCP), validator
unit in `infrastructure/functions/gdrive_validator/test_main.py`.
- **A:** `redistribute_video` on a `complete` job runs all three stages and does **not** raise
`InvalidStateTransitionError`; job status stays `complete`; brand_code/dropbox_link written.
- **B:** `change_to_private` — (a) success path: private redistribute called *before* any public
delete; public delete + public-code recycle happen only after; (b) failure path: redistribution
raises → **assert public YouTube/Dropbox/GDrive delete were NOT called**, `is_private` stays
False, guard flag cleared, exception re-raised. Strengthen the existing
`test_rollback_on_redistribute_failure` (today only checks the guard flag).
- **C:** redistribution failure → allocated `NOMADNP` code is recycled exactly once.
- **Regression:** full `test_change_visibility.py` + `test_brand_code_service.py` green.
- **Post-deploy (once):** re-run `python scripts/check_public_share.py` → clean; recover
`25d076e5` and confirm NonPublished archive + `NOMADNP` code appear.
## Recovery Runbook (D)
```python
# After A–C deployed. Recover the private archive for 25d076e5 (finals present in GCS).
from backend.workers.video_worker import redistribute_video
await redistribute_video("25d076e5") # job already is_private=True → NonPublished + NOMADNP
# Recycle the leaked private code
from backend.services.brand_code_service import get_brand_code_service
get_brand_code_service().recycle_brand_code("NOMADNP", 214)
```
## Open Questions
- [ ] Preferred A mechanism: config `redistribute_mode` flag vs. threading `update_status=False`
through `_update_progress`? (Leaning: config flag — single choke point.)
- [ ] For B, is it acceptable for the private `Tracks-NonPublished` archive to exist *simultaneously*
with the still-live public outputs for the few seconds before public deletion? (Expected: yes.)
## Rollback Plan
- Pure backend code; no schema changes, no infra/validator changes. Revert the PR to restore prior
behaviour.
- `redistribute_mode` is opt-in (only the redistribute path sets it); the normal pipeline is
unaffected, so A/B cannot regress fresh-job distribution.
- Recovery step (D) is idempotent-ish: re-running `redistribute_video` re-uploads from GCS finals;
safe to retry.
```
@@ -0,0 +1,106 @@
# Health-check alert noise + frontend graceful degradation (2026-08-22)
## Trigger
A "Karaoke Backend - Service Unavailable" uptime alert fired at 06:06 UTC on
2026-08-22 and auto-recovered ~1m41s later. Investigation of the noise, plus a
follow-on request to make the frontend degrade gracefully during such blips.
## Root cause of the alert
**A routine, platform-initiated Cloud Run instance recycle — not a crash.**
- The backend runs on `--min-instances 1` (a deliberate cost choice).
- At 06:01:53 UTC Cloud Run reaped the single warm instance (which had run ~9.6h
since the previous evening's deploy) and started a replacement
(`Reason: MANUAL_OR_CUSTOMER_MIN_INSTANCE`, then `AUTOSCALING`). The new
container's STARTUP probe passed ~06:03:13.
- During the ~80s gap (06:02:30–06:03:50) there was **no warm origin**, so
Cloudflare failed the health check from **all 6** uptime checker regions
simultaneously. Zero `/api/health` requests reached the origin in that window;
no `SIGTERM`/OOM/error was logged (platform reaps leave no teardown log).
- The uptime alert (reworked 2026-08-19 to page only when >1 checker location
fails) did its job — it caught a genuine, if brief, hard-down.
- A second, related failure mode was also observed (00:11–00:12 UTC): the single
instance's event loop stalled (orchestrating an encoding-worker fallback
cold-start with blocking timeouts), so health probes queued past the 10s
uptime timeout across regions, then flushed at once.
Blast radius of such a blip: ~80s of API unavailability. The **frontend still
loads** (static Cloudflare Pages export), **Cloud Run Jobs** (video renders) and
**GCE encoding-worker** executions already in flight **keep running**; only
backend-side orchestration is briefly paused and self-heals via Cloud
Tasks/Scheduler retries + the recover-stuck-jobs / retry-pending-render crons.
## Change 1 — soften the alert (server-side)
`infrastructure/modules/monitoring.py`: the "Service Unavailable" condition
`duration` 60s → **300s**. A sub-5-min self-healing recycle/stall no longer
pages; a sustained hard-down still fires (~5–6 min). The read-retry budget in the
frontend (`lib/backend-status.ts`) is aligned to the same ~10s escalation.
We deliberately did **not** raise `--min-instances` to 2 (cost choice). If real
outages ever slip through undetected, that is the cheaper-detection lever and it
removes both failure modes at the source.
## Change 2 — graceful degradation (frontend)
Goal: during a blip, retry transparently and show one reassuring app-wide message
instead of every screen throwing a generic error.
- **`lib/backend-status.ts`** — framework-agnostic connectivity store
(`online | reconnecting | unavailable`) + `useBackendStatus()`. **Status is
derived purely from how long the OLDEST in-flight tracked read has been
outstanding** (`beginRequest`/`endRequest`): `reconnecting` at
`STALL_RECONNECTING_MS` (10s), `unavailable` at `STALL_UNAVAILABLE_MS` (20s),
back to `online` the instant the stalled read settles.
**Addendum (2026-08-23, v0.198.3): stall + health-probe confirmation.** A stall
alone turned out not to be proof of an outage either — first-time
instrumental-analysis / lyrics-review loads transcode audio server-side and can
legitimately run 20–60s, false-firing the banner. Now, once a stall crosses the
threshold, the store confirms with a cheap `GET /api/health` probe (registered by
`lib/api.ts` via `configureHealthProbe`; 4s timeout, `Promise.race`d so a hung
origin can't wedge it). While the probe answers OK — or has no verdict yet — the
banner stays hidden; only a failed/timed-out probe (as during a real recycle,
when the origin hangs) lets it surface (~4s later than before). The probe
re-fires every `PROBE_FRESH_MS` (10s) while the stall persists, so recovery
clears the banner even if the original read is still hung.
- **`lib/api.ts` — `apiFetch`** wraps every backend call (drop-in for `fetch`;
internals use `globalThis.fetch`). Design decisions:
- **The banner keys on a genuine STALL, not slowness.** A read that completes —
even a normal-slow 3–5s one — surfaces nothing; only a read still outstanding
past 10s shows the hint. (The original 2.5s "slow-request" hint was too
trigger-happy — it fired during normal lyrics-review loads.)
- **Only GETs are tracked, and only GETs get a hard-timeout (45s) backstop.**
Long-running POSTs (preview video, generate, search, auto-correct) are
legitimately slow: they must never trip the banner nor be aborted mid-encode.
Callers can opt a slow read out with `opts.trackConnectivity: false`, or
time-box any request with `opts.timeoutMs`.
- **Retries GET only** (idempotent); **never auto-retries non-GET** (a replayed
create/submit/payment could double-charge). GETs retry within a ~2s budget,
then throw `BackendUnavailableError`.
- Transient = 502/503/504 + Cloudflare 520–524. Third-party hosts (GCS
signed-URL uploads) pass straight through untouched.
- **`components/backend-status-banner.tsx`** — the two UX states; mounted in
`app/[locale]/layout.tsx` so it covers all customer-facing surfaces (landing,
logged-in dashboard, review screens) with full i18n. `/admin/*` is intentionally
not covered (internal, English-only).
- **i18n** — `backendStatus` namespace added to `messages/en.json` and translated
to all 32 other locales.
### Copy (en)
> **We're having trouble reaching our servers**
> This is usually temporary — please try again in a couple of minutes.
> Any karaoke videos currently being created are unaffected and will keep processing.
## Tests
- `__tests__/backend-status.test.ts` — store transitions + timer escalation.
- `__tests__/api-fetch.test.ts` — GET retry→unavailable, transient-503 retry,
transparent recovery, non-GET no-retry, GCS passthrough, caller-abort passthrough.
- `lib/__tests__/api.test.ts` — updated `completeJobUpload` assertion (network
failure now maps to `BackendUnavailableError` preserving `.cause`).
- Banner verified visually (reconnecting + unavailable, en + es) via local dev.
- Full suite: 1129 passing.
@@ -0,0 +1,146 @@
# Admin: Locale/Language/Country Visibility + Email History
**Branch:** `feat/sess-20260822-2340-admin-locale-emails`
**Date:** 2026-08-23
Two independent admin-facing features so support/intervention work can (a) know what
language/country a user is using the product in, and (b) see the exact emails ever sent
to a user, rendered as they appeared in the inbox with full delivery metadata.
Decisions (confirmed with user):
- **Email history:** Postmark live query (rich metadata, ~45d retention) **+** persist every
future send to Firestore for permanent history beyond 45 days. Merge both sources.
- **Locale:** Full capture — add a real per-job `locale` (any of 33 langs from the actual
`Accept-Language` header), surface the user's UI language, and derive country from IP.
---
## Feature A — Locale / language / country
### Backend
1. **New helper** `get_full_locale_from_request(request)` in `backend/i18n.py`
- Returns the first language tag from `Accept-Language` **without** narrowing to en/es/de
(e.g. `pt`, `ja`, `zh`). Keep the existing `get_locale_from_request` untouched (emails
still need en/es/de).
2. **Job model** `backend/models/job.py`
- Add `locale: Optional[str] = None` to `Job` (~L239-531) and `JobCreate` (~L534-655).
3. **Capture on job creation** (populate `locale` from `get_full_locale_from_request`):
- URL jobs: `backend/api/routes/jobs.py` (~L79-197)
- File upload: `backend/api/routes/file_upload.py`
- Audio search: `backend/api/routes/audio_search.py`
- Made-for-you: capture at checkout (`backend/api/routes/users.py` create_made_for_you_checkout,
~L801) → put `locale` in Stripe session metadata → read in the `checkout.session.completed`
webhook (~L1313) when the job is created.
4. **Dashboard summary projection**: add `'locale'` to `SUMMARY_FIELD_PATHS`
(`backend/services/firestore_service.py` ~L200-220) so it appears in `list_jobs_summary`.
(Top-level field → only this constant, not `_SUMMARY_STATE_DATA_KEYS`.)
5. **User UI locale (full value)** `backend/models/user.py`
- Add `ui_locale: Optional[str] = None` (keep existing `locale` en/es/de for email rendering).
- Populate in `verify_magic_link` (`users.py` ~L441-446) from the full Accept-Language, and
update it opportunistically on job creation (cheap `update_user` when it changes).
6. **Surface in admin responses**
- `UserDetailResponse` (`users.py` ~L1753-1780): add `locale`, `ui_locale`.
- `get_user_detail` return (~L1954): include them; add `locale` to each `recent_jobs` entry (~L1919-1925).
### Frontend
7. **`LocaleBadge` component** `frontend/components/admin/locale-badge.tsx`
- Input: a locale string. Renders a small pill: flag emoji + human language name.
- Language name via `Intl.DisplayNames(['en'], { type: 'language' })`; flag via a
locale→region map (reuse `countryCodeToFlag` from `frontend/lib/ip-geolocation.ts:78`).
- Graceful fallback for unknown/empty locale (`🌐 —`).
8. **Types**: add `locale` to `Job` (`frontend/lib/api.ts` ~L105-152) and `locale`/`ui_locale`
to `AdminUserDetail` (~L2256-2301) + the recent-jobs entry type.
9. **Placements**
- Jobs table (`frontend/app/admin/jobs/page.tsx` ~L2142-2211): `LocaleBadge` in the row
(language only — cheap, no IP lookup per row).
- Job detail info grid (`jobs/page.tsx` ~L1113-1179): Language cell (`LocaleBadge`) +
Country via existing `<IpInfo ip={creation_ip} />`.
- User detail (`frontend/app/admin/users/detail/page.tsx`): `LocaleBadge` in the header
(~L342-348) / Account Info card. Country already shown via `<IpInfo>`.
Note: keep IP→country lookups to the single-record detail views (cached in the
`ip_geolocation` Firestore collection). The jobs *list* shows language only, to avoid N
geolocation calls per page.
---
## Feature B — Email history ("emails sent to this user")
### Backend
10. **Persist every send** — single chokepoint in `EmailService`
(`backend/services/email_service.py`). Route all sends through one private
`_log_and_send(...)` that calls `self.provider.send_email(...)`, captures the Postmark
`MessageID` from the response, then best-effort writes a Firestore `email_log` doc:
`{ recipient, cc, bcc, from, subject, html_content, text_content, email_type,
message_stream, postmark_message_id, created_at }`.
- Mechanical: replace the ~15 `self.provider.send_email(` call sites with `self._log_and_send(`.
- Add optional `email_type` kwarg to each `send_*` for categorization (default inferred/None).
- Wrap the Firestore write in try/except — **logging must never break a send**.
- Capture `MessageID`: `PostmarkEmailProvider.send_email` must return it (change return to
include message id, or add an out-param) — currently it discards the response body.
11. **`PostmarkAdminService`** `backend/services/postmark_admin_service.py`
(model on `stripe_admin_service.py`):
- `get_user_email_history(email)` → `GET https://api.postmarkapp.com/messages/outbound?recipient=<email>&count=...`
using `X-Postmark-Server-Token` (env `POSTMARK_SERVER_TOKEN`). Merge with Firestore
`email_log` docs for that recipient; dedupe by `postmark_message_id`; sort by sent-at desc.
- `get_email_detail(message_id)` → `GET /messages/outbound/{id}/details` (full `HtmlBody`,
subject, status, opens/clicks, bounce). Fallback to the Firestore `email_log` doc for
messages older than Postmark's 45-day retention.
12. **Admin endpoints** `backend/api/routes/admin.py` (pattern: `get_user_payments` ~L2969,
guarded by `Depends(require_admin)`):
- `GET /admin/users/{email}/emails` → summary list.
- `GET /admin/emails/{message_id}` → full detail (HTML + metadata); `?source=log` for
Firestore-only records.
### Frontend
13. **API client** `frontend/lib/api.ts`: `adminApi.getUserEmails(email)` +
`adminApi.getEmailDetail(id, source?)`, plus `UserEmailSummary` / `EmailDetail` interfaces.
14. **User detail page**: new **"Emails sent to this user"** `<Card>` (rows: subject,
type badge, sent-at, delivery-status badge). Row click → **`EmailPreviewDialog`**:
- Left/main: `<iframe srcDoc={html} sandbox>` so the email renders exactly as in the inbox
(isolated styles), inside `<DialogContent>` + `<ScrollArea>`.
- Side panel: To / From / CC / BCC / Subject / sent-at / status / open & click counts /
bounce reason.
---
## Testing
- **Backend unit**: `get_full_locale_from_request` parsing; job `locale` persisted on each
creation path; `_log_and_send` writes an `email_log` doc (Postmark mocked) and never raises
when Firestore fails; `PostmarkAdminService` list/detail with `requests` mocked incl. the
45-day fallback; admin endpoints with the service mocked + `require_admin` auth.
- **Frontend unit (jest)**: `LocaleBadge` rendering (known/unknown locale); email list + modal
render; iframe `srcDoc` wiring.
- **Prod E2E (Playwright)**: optional — user-detail page shows the emails card + opens a
preview for a known recipient.
## Infra / ops
- No new secrets (`postmark-server-token` already wired into the API service).
- New Firestore collection `email_log`. Add a composite index (recipient asc, created_at desc)
if the merge query needs it — note in PR; Firestore will surface the index hint on first query.
- Bump `tool.poetry.version` in `pyproject.toml`.
## Risks / notes
- Postmark `MessageID` isn't captured today — must thread it through the provider return.
- Not all `send_*` funnel through `send_email` today (e.g. `send_magic_link` calls
`self.provider.send_email` directly), which is exactly why the `_log_and_send` chokepoint
replaces the provider call sites rather than wrapping `send_email`.
- `User.locale` stays en/es/de (emails depend on it); the true UI language lives in the new
`ui_locale`.
@@ -0,0 +1,70 @@
# Admin Create Users + Auto-Create on Job Reassignment (2026-08-24)
## Task (Andrew's prompt, verbatim)
> I'd like to be able to create users from the gen admin users page, so I can submit jobs
> on their behalf (while logged in as admin, after impersonating the new user account) and
> assign free credits to users who have never logged in before. I've actually just edited
> an admin-created job to change the user email address to this:
> "[customer email redacted — public repo]" but that user didn't exist yet, so i'm not sure
> what happens in this case. Ideally in this scenario that user account would get created
> on the fly and the job would be assigned to the new user account
## What happened with the reassigned job (investigation)
The reassigned job had `user_email` set to the customer's email, but
`PATCH /api/admin/jobs/{id}` only wrote the string to
the job doc — no `gen_users` account was created. Consequences: notification emails still
send (notifier uses the raw email, falls back to `en` locale), and the job would appear in
the user's list if they ever logged in (jobs are associated purely by the `user_email`
string; magic-link login lazily creates the account). But until then: no account, no
credits, impersonation 404s.
## Changes (v0.199.0)
1. **`POST /api/users/admin/users`** (`backend/api/routes/users.py`) — admin creates a
user account directly: `email` (required), `display_name`, `initial_credits` (0-1000),
`credit_reason`. 409 if exists. If initial credits are granted,
`welcome_credits_granted` is set so the user doesn't also get the automatic welcome
credit on first login. Models in `backend/models/user.py`
(`AdminCreateUserRequest/Response`).
2. **Auto-create on job reassignment** (`backend/api/routes/admin.py` `update_job`) —
when an admin PATCHes `user_email`, the email is trimmed + lowercased before saving,
and if no `gen_users` account exists one is created via `get_or_create_user`. The
response message notes the creation, and the admin jobs page toast surfaces it.
3. **Admin users page** (`frontend/app/admin/users/page.tsx`) — "Create User" button +
dialog (email, optional display name, optional initial credits). On success the list
is filtered to the new user, so the existing Impersonate / Add Credits buttons work
immediately (impersonation only requires the account doc to exist).
4. `adminApi.createUser` in `frontend/lib/api.ts`; docs in `docs/API.md`.
## Tests
- New `backend/tests/test_admin_create_user.py` (9 tests: minimal create, credits +
display name + welcome-flag suppression, lowercase normalization, 409 duplicate,
422 invalid email, 400 out-of-range credits, 500 add-credits failure, 403 non-admin).
- `backend/tests/test_admin_job_update.py`: new `TestUpdateJobUserEmailAutoCreate` class
(creates when unknown, skips when existing, lowercases, non-email edits never touch
user service).
- Full backend suite: 3917 passed. Frontend: 1151 Jest tests passed; eslint + tsc clean
on touched files.
## Post-deploy TODO
- Backfill the account for the customer whose job was reassigned before this shipped
(details in agent memory, kept out of this public repo): either re-save the
`user_email` field on the job in the admin UI (now auto-creates), or call the new
create endpoint — then grant credits/impersonate as desired.
## Design decisions
- Admin-granted initial credits suppress the automatic welcome credit (set
`welcome_credits_granted=True`) to avoid double-granting.
- `email_verified` stays false on admin-created accounts — verification still happens on
first magic-link login.
- Job reassignment now lowercases the email; job→user association is a string match on
`user_email`, and all account doc IDs are lowercased emails, so mixed-case entry would
otherwise silently orphan the job.
+262
View File
@@ -0,0 +1,262 @@
/**
* @jest-environment jsdom
*
* Tests for apiFetch — the timeout + safe-retry wrapper that all backend calls go
* through (lib/api.ts). In jsdom the hostname is "localhost", so API_BASE_URL is ""
* and backend calls are addressed with relative "/api/..." URLs.
*/
import { apiFetch, BackendUnavailableError, __backendHealthProbe } from '@/lib/api'
import {
getBackendStatus,
configureHealthProbe,
STALL_RECONNECTING_MS,
STALL_UNAVAILABLE_MS,
} from '@/lib/backend-status'
function mockResponse(status: number, body: unknown = {}): Response {
return {
ok: status >= 200 && status < 300,
status,
json: async () => body,
} as unknown as Response
}
/** A fetch mock that returns a promise you resolve/reject by hand, so a request can
* be held "in flight" under fake timers and then settled to clean up. */
function deferredFetch() {
let settle!: (r: Response) => void
let fail!: (e: unknown) => void
const fn = jest.fn(
() =>
new Promise<Response>((res, rej) => {
settle = res
fail = rej
}),
)
return { fn, settle: (r: Response) => settle(r), fail: (e: unknown) => fail(e) }
}
describe('apiFetch', () => {
const fetchMock = jest.fn()
beforeEach(() => {
fetchMock.mockReset()
;(globalThis as unknown as { fetch: unknown }).fetch = fetchMock
// Re-register the real probe so its cached verdict resets between tests.
configureHealthProbe(__backendHealthProbe)
})
afterEach(() => {
jest.useRealTimers()
})
it('returns the response and stays online on a fast successful GET', async () => {
fetchMock.mockResolvedValue(mockResponse(200, { ok: true }))
const res = await apiFetch('/api/jobs/abc')
expect(res.status).toBe(200)
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(getBackendStatus()).toBe('online')
})
it('does NOT retry a deterministic 404 and stays online', async () => {
fetchMock.mockResolvedValue(mockResponse(404))
const res = await apiFetch('/api/jobs/missing')
expect(res.status).toBe(404)
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(getBackendStatus()).toBe('online')
})
it('retries a GET on repeated network failure, then throws BackendUnavailableError', async () => {
jest.useFakeTimers()
fetchMock.mockRejectedValue(new TypeError('Failed to fetch'))
const p = apiFetch('/api/jobs/abc')
const assertion = expect(p).rejects.toBeInstanceOf(BackendUnavailableError)
await jest.advanceTimersByTimeAsync(600)
await jest.advanceTimersByTimeAsync(1500)
await assertion
expect(fetchMock).toHaveBeenCalledTimes(3)
// A fast total failure (~2s) is NOT a stall, so the banner never appears.
expect(getBackendStatus()).toBe('online')
})
it('retries a GET that keeps returning a transient 503, then throws', async () => {
jest.useFakeTimers()
fetchMock.mockResolvedValue(mockResponse(503))
const p = apiFetch('/api/jobs/abc')
const assertion = expect(p).rejects.toBeInstanceOf(BackendUnavailableError)
await jest.advanceTimersByTimeAsync(600)
await jest.advanceTimersByTimeAsync(1500)
await assertion
expect(fetchMock).toHaveBeenCalledTimes(3)
expect(getBackendStatus()).toBe('online')
})
it('recovers transparently when a retried GET succeeds on a later attempt', async () => {
jest.useFakeTimers()
fetchMock
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
.mockResolvedValueOnce(mockResponse(200, { ok: true }))
const p = apiFetch('/api/jobs/abc')
await jest.advanceTimersByTimeAsync(600)
const res = await p
expect(res.status).toBe(200)
expect(fetchMock).toHaveBeenCalledTimes(2)
expect(getBackendStatus()).toBe('online')
})
it('surfaces the banner for a stalled GET once the health probe confirms the outage, then clears', async () => {
jest.useFakeTimers()
// Everything hangs — the backend is genuinely unreachable (recycle-style: the
// origin holds requests open, so the probe only fails via its own timeout).
let settleGet!: (r: Response) => void
fetchMock.mockImplementation((url: unknown) => {
if (String(url).includes('/api/health')) return new Promise<Response>(() => {})
return new Promise<Response>((res) => {
settleGet = res
})
})
const p = apiFetch('/api/jobs/abc')
p.catch(() => {}) // avoid unhandled rejection if it ever fails
expect(getBackendStatus()).toBe('online')
// Stall threshold crossed → probe fires, but until it has a verdict the banner
// stays hidden (a slow endpoint must not alarm the user without evidence).
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS)
expect(getBackendStatus()).toBe('online')
// Probe times out (~4s) → outage confirmed → the hint appears.
await jest.advanceTimersByTimeAsync(5_000)
expect(getBackendStatus()).toBe('reconnecting')
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS - STALL_RECONNECTING_MS - 5_000)
expect(getBackendStatus()).toBe('unavailable')
settleGet(mockResponse(200, { ok: true }))
await p
expect(getBackendStatus()).toBe('online')
})
it('never surfaces the banner for a slow GET while the backend is reachable (health probe OK)', async () => {
jest.useFakeTimers()
// The read is legitimately slow (e.g. first-time instrumental-analysis
// transcoding) but /api/health answers instantly — no banner, ever.
let settleGet!: (r: Response) => void
fetchMock.mockImplementation((url: unknown) => {
if (String(url).includes('/api/health')) return Promise.resolve(mockResponse(200))
return new Promise<Response>((res) => {
settleGet = res
})
})
const p = apiFetch('/api/jobs/abc')
p.catch(() => {})
// Well past both stall thresholds (but under the 45s hard timeout).
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS + 15_000)
expect(getBackendStatus()).toBe('online')
settleGet(mockResponse(200, { ok: true }))
await p
expect(getBackendStatus()).toBe('online')
})
it('never surfaces the banner for a slow POST (mutations are not tracked)', async () => {
jest.useFakeTimers()
const d = deferredFetch()
fetchMock.mockImplementation(d.fn)
const p = apiFetch('/api/jobs/create-from-url', { method: 'POST', body: '{}' })
p.catch(() => {})
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS + 5000)
expect(getBackendStatus()).toBe('online')
d.settle(mockResponse(200, { ok: true }))
await p
})
it('does NOT impose a hard timeout on a long-running POST (e.g. preview render)', async () => {
jest.useFakeTimers()
let capturedSignal: AbortSignal | undefined
const d = deferredFetch()
fetchMock.mockImplementation((_url: unknown, init: RequestInit) => {
capturedSignal = init.signal ?? undefined
return d.fn()
})
const p = apiFetch('/api/review/abc/preview-video', { method: 'POST', body: '{}' })
p.catch(() => {})
// Well past the GET hard-timeout (45s): a POST must still be running, unaborted.
await jest.advanceTimersByTimeAsync(60_000)
expect(capturedSignal?.aborted).toBe(false)
d.settle(mockResponse(200, { ok: true }))
await expect(p).resolves.toBeDefined()
})
it('never auto-retries a non-GET, even on network failure', async () => {
fetchMock.mockRejectedValue(new TypeError('Failed to fetch'))
await expect(
apiFetch('/api/jobs/create-from-url', { method: 'POST', body: '{}' }),
).rejects.toBeInstanceOf(BackendUnavailableError)
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(getBackendStatus()).toBe('online')
})
it('reads method + signal from a Request input (a POST Request is not retried)', async () => {
// jsdom has no global Request; provide a minimal stand-in with the fields
// apiFetch reads (url/method/signal) so `input instanceof Request` engages.
class FakeRequest {
url: string
method: string
signal?: AbortSignal
constructor(url: string, init?: { method?: string; signal?: AbortSignal }) {
this.url = url
this.method = init?.method ?? 'GET'
this.signal = init?.signal
}
}
;(globalThis as unknown as { Request: unknown }).Request = FakeRequest
try {
fetchMock.mockRejectedValue(new TypeError('Failed to fetch'))
const req = new FakeRequest('http://localhost/api/jobs/create-from-url', {
method: 'POST',
})
await expect(apiFetch(req as unknown as Request)).rejects.toBeInstanceOf(
BackendUnavailableError,
)
expect(fetchMock).toHaveBeenCalledTimes(1)
} finally {
delete (globalThis as unknown as { Request?: unknown }).Request
}
})
it('passes non-backend URLs (e.g. GCS uploads) straight through with the original error', async () => {
const gcsError = new TypeError('gcs unreachable')
fetchMock.mockRejectedValue(gcsError)
await expect(
apiFetch('https://storage.googleapis.com/bucket/obj', { method: 'PUT', body: 'x' }),
).rejects.toBe(gcsError)
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(getBackendStatus()).toBe('online')
})
it('propagates a caller-initiated abort without surfacing the banner', async () => {
const abortErr = new DOMException('Aborted', 'AbortError')
fetchMock.mockRejectedValue(abortErr)
const controller = new AbortController()
controller.abort()
await expect(
apiFetch('/api/jobs/abc', { signal: controller.signal }),
).rejects.toBe(abortErr)
expect(getBackendStatus()).toBe('online')
})
})
+161
View File
@@ -0,0 +1,161 @@
/**
* @jest-environment jsdom
*
* Tests for the backend-connectivity status store (lib/backend-status.ts).
* Status is derived from how long the OLDEST in-flight tracked read has been
* outstanding — a read that completes promptly never surfaces the banner.
*/
import {
getBackendStatus,
beginRequest,
endRequest,
configureHealthProbe,
STALL_RECONNECTING_MS,
STALL_UNAVAILABLE_MS,
PROBE_FRESH_MS,
} from '@/lib/backend-status'
describe('backend-status store (stall-based)', () => {
let open: number[] = []
beforeEach(() => {
jest.useFakeTimers()
open = []
})
afterEach(() => {
// Settle anything still in flight so the module singleton resets to online.
open.forEach((id) => endRequest(id))
jest.clearAllTimers()
jest.useRealTimers()
})
it('starts online', () => {
expect(getBackendStatus()).toBe('online')
})
it('stays online while a read is young, then escalates as it stalls', async () => {
open.push(beginRequest())
expect(getBackendStatus()).toBe('online')
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS - 1000)
expect(getBackendStatus()).toBe('online')
await jest.advanceTimersByTimeAsync(1000) // cross the reconnecting threshold
expect(getBackendStatus()).toBe('reconnecting')
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS - STALL_RECONNECTING_MS)
expect(getBackendStatus()).toBe('unavailable')
})
it('returns to online the moment the stalled read settles', async () => {
const id = beginRequest()
open.push(id)
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS + 100)
expect(getBackendStatus()).toBe('unavailable')
endRequest(id)
open = []
expect(getBackendStatus()).toBe('online')
})
it('a read that completes quickly never surfaces the banner', async () => {
const id = beginRequest()
await jest.advanceTimersByTimeAsync(3000) // 3s — normal-slow, not a stall
endRequest(id)
expect(getBackendStatus()).toBe('online')
// ...and nothing appears later either (nothing is in flight).
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS)
expect(getBackendStatus()).toBe('online')
})
it('tracks the OLDEST outstanding read, not the newest', async () => {
const a = beginRequest()
open.push(a)
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS)
expect(getBackendStatus()).toBe('reconnecting')
const b = beginRequest() // fresh read starts while `a` is still stalled
open.push(b)
expect(getBackendStatus()).toBe('reconnecting')
endRequest(b) // settling the young one doesn't clear the old stall
open = [a]
expect(getBackendStatus()).toBe('reconnecting')
endRequest(a)
open = []
expect(getBackendStatus()).toBe('online')
})
})
describe('backend-status store (health-probe confirmation)', () => {
let open: number[] = []
beforeEach(() => {
jest.useFakeTimers()
open = []
})
afterEach(() => {
open.forEach((id) => endRequest(id))
// Restore pure stall-based behavior so other suites are unaffected.
configureHealthProbe(null)
jest.clearAllTimers()
jest.useRealTimers()
})
it('suppresses the banner while the probe reports the backend reachable', async () => {
const probe = jest.fn(() => Promise.resolve(true))
configureHealthProbe(probe)
open.push(beginRequest())
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS + 5000)
expect(getBackendStatus()).toBe('online')
expect(probe).toHaveBeenCalled()
})
it('shows the banner once the probe confirms the backend is unreachable', async () => {
configureHealthProbe(() => Promise.resolve(false))
open.push(beginRequest())
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS)
expect(getBackendStatus()).toBe('reconnecting')
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS - STALL_RECONNECTING_MS)
expect(getBackendStatus()).toBe('unavailable')
})
it('re-probes as the verdict goes stale, and clears the banner if the backend recovers', async () => {
let reachable = false
const probe = jest.fn(() => Promise.resolve(reachable))
configureHealthProbe(probe)
open.push(beginRequest())
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS)
expect(getBackendStatus()).toBe('unavailable')
// Backend comes back (even though the old read is still hung) — the next
// re-probe succeeds and the banner clears.
reachable = true
await jest.advanceTimersByTimeAsync(PROBE_FRESH_MS + 2000)
expect(getBackendStatus()).toBe('online')
expect(probe.mock.calls.length).toBeGreaterThan(1)
})
it('holds the banner back while the probe has no verdict yet', async () => {
// A probe that takes 3s to fail (e.g. its own timeout racing a hung origin).
configureHealthProbe(
() => new Promise((res) => setTimeout(() => res(false), 3000)),
)
open.push(beginRequest())
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS)
expect(getBackendStatus()).toBe('online') // stalled, but not yet confirmed
await jest.advanceTimersByTimeAsync(3000) // verdict lands
expect(getBackendStatus()).toBe('reconnecting')
})
})
+63
View File
@@ -139,6 +139,69 @@ describe('getJobStep', () => {
});
});
describe('Upload-based (tenant / existing-instrumental) jobs', () => {
const withInstrumental = (status: string, stateData?: Record<string, any>): Job => ({
...createJob(status, stateData),
existing_instrumental_gcs_path: 'uploads/test-job-123/audio/existing_instrumental.mp3',
});
it('shows "preparingAudio" instead of "downloading" while staging uploads', () => {
const result = getJobStep(withInstrumental('downloading'));
expect(result.step).toBe(3);
expect(result.label).toBe('preparingAudio');
});
it('also relabels the downloading_audio stage for uploaded audio', () => {
const result = getJobStep(withInstrumental('downloading_audio'));
expect(result.step).toBe(3);
expect(result.label).toBe('preparingAudio');
});
it('advances to step 4 (transcribing) once the lyrics worker starts', () => {
const result = getJobStep(withInstrumental('downloading', {
lyrics_progress: { stage: 'transcribing', progress: 10 },
}));
expect(result.step).toBe(4);
expect(result.label).toBe('transcribing');
});
it('does not relabel a normal download job (no uploaded instrumental)', () => {
const result = getJobStep(createJob('downloading'));
expect(result.step).toBe(3);
expect(result.label).toBe('downloading');
});
});
describe('Status labels are always valid i18n keys (no raw "jobStatus.X")', () => {
// Regression: the "downloading + workers" path used to pass the literal
// "Processing" (not a jobStatus key), which rendered as "jobStatus.Processing".
it('returns a valid key (transcribing) for lyrics-only progress, not "Processing"', () => {
const result = getJobStep(createJob('downloading', {
lyrics_progress: { stage: 'transcribing', progress: 5 },
}));
expect(result.step).toBe(4);
expect(result.label).toBe('transcribing');
expect(result.label).not.toBe('Processing');
});
it('every label getJobStep can emit exists in en.json jobStatus', () => {
const en = require('../messages/en.json');
const jobStatusKeys = new Set(Object.keys(en.jobStatus));
// Static labels from STATUS_CONFIG plus keys emitted by the parallel/upload helpers.
const dynamicKeys = [
'processing', 'preparingAudio', 'processingComplete',
'audio1of2', 'audio2of2', 'audioDone', 'audio',
'transcribing', 'correcting', 'lyricsDone', 'lyrics',
];
for (const cfg of Object.values(STATUS_CONFIG)) {
expect(jobStatusKeys.has((cfg as any).label)).toBe(true);
}
for (const k of dynamicKeys) {
expect(jobStatusKeys.has(k)).toBe(true);
}
});
});
describe('Step 4: Parallel Processing', () => {
it('returns step 4 for separating_stage1', () => {
const job = createJob('separating_stage1');
+45
View File
@@ -0,0 +1,45 @@
/**
* @jest-environment jsdom
*
* Tests for LocaleBadge — the admin-only flag + language pill showing what UI
* language a user/job was using.
*/
import React from 'react'
import { render, screen } from '@testing-library/react'
import { LocaleBadge, localeDisplayName } from '@/components/admin/locale-badge'
describe('LocaleBadge', () => {
it('renders the locale code with a flag for a known language', () => {
render(<LocaleBadge locale="pt" />)
// Shows the code by default
expect(screen.getByText(/pt/)).toBeInTheDocument()
// Language name is in the tooltip
expect(screen.getByTitle(/Portuguese/i)).toBeInTheDocument()
})
it('renders the full language name when showName is set', () => {
render(<LocaleBadge locale="ja" showName />)
expect(screen.getByText(/Japanese/i)).toBeInTheDocument()
})
it('normalizes a region-qualified locale to its primary subtag', () => {
render(<LocaleBadge locale="pt-BR" />)
expect(screen.getByTitle(/Portuguese \(pt\)/i)).toBeInTheDocument()
})
it('renders nothing for an empty locale by default', () => {
const { container } = render(<LocaleBadge locale={null} />)
expect(container.firstChild).toBeNull()
})
it('renders a placeholder for an empty locale when showEmpty is set', () => {
render(<LocaleBadge locale={undefined} showEmpty />)
expect(screen.getByText(/—/)).toBeInTheDocument()
})
it('localeDisplayName returns a readable name or null', () => {
expect(localeDisplayName('de')).toMatch(/German/i)
expect(localeDisplayName(null)).toBeNull()
})
})
@@ -0,0 +1,93 @@
import { render, screen, waitFor } from '@testing-library/react'
import { SystemStatusModal } from '@/components/system-status-modal'
import type { SystemStatus } from '@/lib/api'
// Mock the API layer so the modal renders against controlled status payloads.
const getSystemStatus = jest.fn()
jest.mock('@/lib/api', () => ({
api: {
getSystemStatus: () => getSystemStatus(),
},
}))
function baseStatus(overrides: Partial<SystemStatus['services']> = {}): SystemStatus {
return {
services: {
frontend: { status: 'ok', version: '0.196.3' },
backend: { status: 'ok', version: '0.196.3' },
encoder: { status: 'ok', version: '0.196.3' },
flacfetch: { status: 'ok', version: '0.21.1' },
separator: { status: 'offline' },
...overrides,
},
}
}
describe('SystemStatusModal', () => {
beforeEach(() => {
getSystemStatus.mockReset()
})
it('shows the live encoding worker instance type on the primary (no fallback)', async () => {
getSystemStatus.mockResolvedValue(
baseStatus({
encoder: {
status: 'ok',
version: '0.196.3',
admin_details: {
primary_vm: 'encoding-worker-a',
active_vm: 'encoding-worker-a',
active_zone: 'us-central1-c',
active_machine_type: 'c4d-highcpu-32',
on_fallback: false,
},
},
}),
)
render(<SystemStatusModal open onClose={() => {}} />)
// Instance type + serving VM are surfaced for the live worker.
expect(await screen.findByText('c4d-highcpu-32')).toBeInTheDocument()
expect(screen.getByText(/encoding-worker-a · us-central1-c/)).toBeInTheDocument()
// No fallback badge/notice when serving the primary.
expect(screen.queryByText('Fallback')).not.toBeInTheDocument()
})
it('flags a capacity fallback with the fallback badge and notice', async () => {
getSystemStatus.mockResolvedValue(
baseStatus({
encoder: {
status: 'ok',
version: '0.196.3',
admin_details: {
primary_vm: 'encoding-worker-a',
active_vm: 'encoding-worker-fallback-n2c',
active_zone: 'us-central1-a',
active_machine_type: 'n2-highcpu-32',
on_fallback: true,
},
},
}),
)
render(<SystemStatusModal open onClose={() => {}} />)
expect(await screen.findByText('n2-highcpu-32')).toBeInTheDocument()
expect(screen.getByText('Fallback')).toBeInTheDocument()
expect(
screen.getByText(/Primary capacity unavailable/i),
).toBeInTheDocument()
})
it('omits the live-worker section for non-admins (no admin_details)', async () => {
getSystemStatus.mockResolvedValue(baseStatus())
render(<SystemStatusModal open onClose={() => {}} />)
// Encoder card still renders, but there is no live-worker detail.
await waitFor(() => expect(getSystemStatus).toHaveBeenCalled())
expect(screen.queryByText('Live worker:')).not.toBeInTheDocument()
expect(screen.queryByText('Fallback')).not.toBeInTheDocument()
})
})
+34 -7
View File
@@ -131,13 +131,25 @@ describe('TenantJobFlow — error handling', () => {
jest.clearAllMocks()
})
// Mirrors handleSubmit's catch mapping in TenantJobFlow.tsx, using the en
// jobFlow strings that t('submitError') / t('submitNetworkError') resolve to.
const SUBMIT_ERROR = 'Something went wrong. Please try again.'
const SUBMIT_NETWORK_ERROR = 'Network error — please check your connection and try again.'
function mapSubmitError(err: any): string {
const { ApiError } = require('@/lib/api')
if (err instanceof ApiError) return err.message
if (err instanceof TypeError || /network|failed to fetch|load failed/i.test(String(err?.message ?? ''))) {
return SUBMIT_NETWORK_ERROR
}
return SUBMIT_ERROR
}
it('ApiError message is surfaced when createJobWithUploadUrls fails', async () => {
const { ApiError } = require('@/lib/api')
mockApi.createJobWithUploadUrls.mockRejectedValue(
new ApiError('Tenant file upload is not enabled', 403),
)
// Simulate handleSubmit error path
let errorMessage = ''
try {
await api.createJobWithUploadUrls('Artist', 'Title', [], {
@@ -145,16 +157,15 @@ describe('TenantJobFlow — error handling', () => {
existing_instrumental: true,
})
} catch (err: any) {
errorMessage = err instanceof ApiError ? err.message : 'Something went wrong. Please try again.'
errorMessage = mapSubmitError(err)
}
expect(errorMessage).toBe('Tenant file upload is not enabled')
})
it('generic errors get fallback message', async () => {
mockApi.createJobWithUploadUrls.mockRejectedValue(new TypeError('Network error'))
it('network-level failures map to the network error message', async () => {
mockApi.createJobWithUploadUrls.mockRejectedValue(new TypeError('Failed to fetch'))
const { ApiError } = require('@/lib/api')
let errorMessage = ''
try {
await api.createJobWithUploadUrls('Artist', 'Title', [], {
@@ -162,10 +173,26 @@ describe('TenantJobFlow — error handling', () => {
existing_instrumental: true,
})
} catch (err: any) {
errorMessage = err instanceof ApiError ? err.message : 'Something went wrong. Please try again.'
errorMessage = mapSubmitError(err)
}
expect(errorMessage).toBe('Something went wrong. Please try again.')
expect(errorMessage).toBe(SUBMIT_NETWORK_ERROR)
})
it('non-network, non-ApiError failures get the generic fallback message', async () => {
mockApi.createJobWithUploadUrls.mockRejectedValue(new Error('boom'))
let errorMessage = ''
try {
await api.createJobWithUploadUrls('Artist', 'Title', [], {
is_private: true,
existing_instrumental: true,
})
} catch (err: any) {
errorMessage = mapSubmitError(err)
}
expect(errorMessage).toBe(SUBMIT_ERROR)
})
it('missing upload URL throws ApiError', async () => {
@@ -0,0 +1,79 @@
/**
* @jest-environment jsdom
*
* Tests for UserEmailsCard — the admin "Emails sent to this user" section and
* its inbox-fidelity preview modal.
*/
import React from 'react'
import { render, screen, waitFor, fireEvent } from '@testing-library/react'
import { UserEmailsCard } from '@/components/admin/user-emails-card'
jest.mock('@/lib/api', () => ({
adminApi: {
getUserEmails: jest.fn(),
getEmailDetail: jest.fn(),
},
}))
import { adminApi } from '@/lib/api'
const getUserEmails = adminApi.getUserEmails as jest.Mock
const getEmailDetail = adminApi.getEmailDetail as jest.Mock
describe('UserEmailsCard', () => {
beforeEach(() => {
jest.clearAllMocks()
})
it('lists emails returned for the user', async () => {
getUserEmails.mockResolvedValue({
email: 'u@x.com', count: 2, postmark_available: true,
emails: [
{ message_id: 'm1', source: 'postmark', subject: 'Welcome to Nomad', sent_at: '2026-08-20T10:00:00Z', status: 'Delivered', email_type: 'welcome' },
{ message_id: 'm2', source: 'log', subject: 'Your receipt', sent_at: '2026-08-19T10:00:00Z', email_type: 'credits_added' },
],
})
render(<UserEmailsCard email="u@x.com" />)
await waitFor(() => expect(screen.getByText('Welcome to Nomad')).toBeInTheDocument())
expect(screen.getByText('Your receipt')).toBeInTheDocument()
expect(getUserEmails).toHaveBeenCalledWith('u@x.com')
})
it('shows an empty state when there are no emails', async () => {
getUserEmails.mockResolvedValue({ email: 'u@x.com', count: 0, postmark_available: true, emails: [] })
render(<UserEmailsCard email="u@x.com" />)
await waitFor(() => expect(screen.getByText(/No emails found/i)).toBeInTheDocument())
})
it('opens the preview modal and renders the email HTML in an iframe', async () => {
getUserEmails.mockResolvedValue({
email: 'u@x.com', count: 1, postmark_available: true,
emails: [{ message_id: 'm1', source: 'postmark', subject: 'Welcome', sent_at: '2026-08-20T10:00:00Z', status: 'Delivered' }],
})
getEmailDetail.mockResolvedValue({
message_id: 'm1', source: 'postmark', subject: 'Welcome', from_email: 'gen@x.com',
to: 'u@x.com', sent_at: '2026-08-20T10:00:00Z', status: 'Delivered',
html_body: '<h1>Hello there</h1>', open_count: 2,
})
render(<UserEmailsCard email="u@x.com" />)
await waitFor(() => expect(screen.getByText('Welcome')).toBeInTheDocument())
fireEvent.click(screen.getByText('Welcome'))
await waitFor(() => expect(getEmailDetail).toHaveBeenCalledWith('m1', 'postmark'))
// Metadata + iframe with the exact HTML the user received.
await waitFor(() => {
const iframe = document.querySelector('iframe[title="Email preview"]') as HTMLIFrameElement
expect(iframe).toBeTruthy()
expect(iframe.getAttribute('srcDoc') ?? iframe.getAttribute('srcdoc')).toContain('Hello there')
})
})
it('shows an error when loading fails', async () => {
getUserEmails.mockRejectedValue(new Error('nope'))
render(<UserEmailsCard email="u@x.com" />)
await waitFor(() => expect(screen.getByText('nope')).toBeInTheDocument())
})
})
+2
View File
@@ -5,6 +5,7 @@ import { hasLocale } from 'next-intl';
import { notFound } from 'next/navigation';
import { routing } from '@/i18n/routing';
import { ReferralCapture } from '@/components/ReferralCapture';
import { BackendStatusBanner } from '@/components/backend-status-banner';
export function generateStaticParams() {
return routing.locales.map((locale) => ({ locale }));
@@ -37,6 +38,7 @@ export default async function LocaleLayout({
<Suspense fallback={null}>
<ReferralCapture />
</Suspense>
<BackendStatusBanner />
{children}
</NextIntlClientProvider>
);
+234 -105
View File
@@ -55,6 +55,8 @@ import {
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Separator } from "@/components/ui/separator"
import { LocaleBadge } from "@/components/admin/locale-badge"
import { IpInfo } from "@/components/admin/ip-info"
import {
Search,
RefreshCw,
@@ -101,6 +103,7 @@ const statusOptions = [
{ value: "in_review", label: "In Review" },
{ value: "rendering_video", label: "Rendering Video" },
{ value: "awaiting_instrumental_selection", label: "Awaiting Instrumental" },
{ value: "generating_screens", label: "Generating Screens" },
{ value: "generating_video", label: "Generating Video" },
{ value: "encoding", label: "Encoding" },
{ value: "complete", label: "Complete" },
@@ -123,6 +126,7 @@ const statusLabels: Record<string, string> = {
in_review: "In Review",
rendering_video: "Rendering",
awaiting_instrumental_selection: "Awaiting Inst.",
generating_screens: "Gen. Screens",
generating_video: "Generating",
encoding: "Encoding",
complete: "Complete",
@@ -143,7 +147,7 @@ function AdminJobsPageContent() {
const [jobs, setJobs] = useState<Job[]>([])
const [loading, setLoading] = useState(true)
const [statusFilter, setStatusFilter] = useState("all")
const [statusFilter, setStatusFilter] = useState(() => searchParams.get("status") || "all")
const [userEmailFilter, setUserEmailFilter] = useState("")
const [searchInput, setSearchInput] = useState("")
@@ -202,6 +206,9 @@ function AdminJobsPageContent() {
const [overrideAudioDialogOpen, setOverrideAudioDialogOpen] = useState(false)
const [overridingAudio, setOverridingAudio] = useState(false)
// Timeline expand state (long timelines are collapsed by default)
const [timelineExpanded, setTimelineExpanded] = useState(false)
const loadJobs = useCallback(async () => {
try {
setLoading(true)
@@ -231,11 +238,14 @@ function AdminJobsPageContent() {
setSelectedJob(data)
} catch (err: any) {
console.error("Failed to load job:", err)
toast({
title: "Error",
description: err.message || "Failed to load job",
variant: "destructive",
})
// A 404 is fully communicated by the "Job not found" view — no toast needed
if (err?.status !== 404) {
toast({
title: "Error",
description: err.message || "Failed to load job",
variant: "destructive",
})
}
setSelectedJob(null)
} finally {
setDetailLoading(false)
@@ -268,10 +278,14 @@ function AdminJobsPageContent() {
}, [])
useEffect(() => {
loadJobs()
}, [loadJobs])
// Skip the (expensive) list load while a single job is being viewed
if (!selectedJobId) {
loadJobs()
}
}, [loadJobs, selectedJobId])
useEffect(() => {
setTimelineExpanded(false)
if (selectedJobId) {
loadJobDetail(selectedJobId)
loadLogs(selectedJobId)
@@ -284,7 +298,19 @@ function AdminJobsPageContent() {
}, [selectedJobId, loadJobDetail, loadLogs, loadFiles])
const handleSearch = () => {
setUserEmailFilter(searchInput)
const query = searchInput.trim()
// A bare hex string is a job ID — jump straight to its detail page
if (/^[0-9a-f]{8}(-[0-9a-f-]{4,})?$/i.test(query)) {
router.push(`/admin/jobs?id=${query}`)
return
}
setUserEmailFilter(query)
}
// Keep the status filter in the URL so dashboard links and reloads work
const handleStatusChange = (value: string) => {
setStatusFilter(value)
router.replace(value !== "all" ? `/admin/jobs?status=${value}` : "/admin/jobs")
}
const handleKeyPress = (e: React.KeyboardEvent) => {
@@ -311,15 +337,21 @@ function AdminJobsPageContent() {
try {
setSaving(true)
const updates: JobUpdateRequest = { [field]: editValue }
await adminApi.updateJob(selectedJobId, updates)
// The backend trims + lowercases user_email; mirror that locally so the
// displayed value matches what was saved
const savedValue = field === "user_email" ? editValue.trim().toLowerCase() : editValue
const updates: JobUpdateRequest = { [field]: savedValue }
const result = await adminApi.updateJob(selectedJobId, updates)
// Update local state
setSelectedJob({ ...selectedJob, [field]: editValue })
setSelectedJob({ ...selectedJob, [field]: savedValue })
// Surface anything beyond the generic success message (e.g. "Created new
// user account for x@y.com" when reassigning user_email)
const extra = result?.message?.replace(/^Successfully updated \d+ field\(s\)\.?\s*/, "")
toast({
title: "Updated",
description: `${field} has been updated`,
description: extra ? `${field} has been updated. ${extra}` : `${field} has been updated`,
})
setEditingField(null)
@@ -434,8 +466,34 @@ function AdminJobsPageContent() {
}
}
// Note: handleClearWorkers and handleTriggerWorker removed
// These low-level escape hatches are replaced by Full Restart and Regen Screens
// Trigger a worker manually (used from the reset-result dialog when
// resetting to instrumental_selected didn't auto-trigger the video worker)
const handleTriggerWorker = async (workerType: string) => {
if (!selectedJobId) return
try {
const result = await adminApi.triggerWorker(selectedJobId, workerType)
if (result.triggered) {
toast({
title: "Worker Triggered",
description: result.message || `${workerType} worker is starting`,
})
} else {
toast({
title: "Worker Not Triggered",
description: result.error || result.message,
variant: "destructive",
})
}
loadJobDetail(selectedJobId)
loadLogs(selectedJobId)
} catch (err: any) {
toast({
title: "Error",
description: err.message || `Failed to trigger ${workerType} worker`,
variant: "destructive",
})
}
}
// Handle regenerate screens - regenerates title/end screens with current metadata
const handleRegenerateScreens = async () => {
@@ -643,6 +701,16 @@ function AdminJobsPageContent() {
return { type: "unknown" as const, icon: FileText, label: "Unknown", detail: undefined }
}
// Build a clickable external URL for the job's audio source, when one exists
const getExternalSourceUrl = (job: Job): string | null => {
if (job.url) return job.url
if (!job.source_id) return null
const provider = (job.source_name || "").toLowerCase()
if (provider.includes("youtube")) return `https://www.youtube.com/watch?v=${job.source_id}`
if (provider.includes("spotify")) return `https://open.spotify.com/track/${job.source_id}`
return null
}
// Calculate stage durations from timeline
const getStageDurations = (job: Job) => {
if (!job?.timeline || job.timeline.length < 2) return []
@@ -823,6 +891,15 @@ function AdminJobsPageContent() {
const SourceIcon = jobSource.icon
const canDeleteOutputs = ["complete", "prep_complete", "failed", "cancelled"].includes(selectedJob.status)
// Collapse long timelines (retries/edits create many entries) to the most recent stages
const TIMELINE_TAIL = 6
const timelineCollapsible = stageDurations.length > TIMELINE_TAIL + 2
const visibleStages = timelineCollapsible && !timelineExpanded
? stageDurations.slice(stageDurations.length - TIMELINE_TAIL)
: stageDurations
const hiddenStages = stageDurations.slice(0, stageDurations.length - visibleStages.length)
const hiddenFailures = hiddenStages.filter((s) => s.status === "failed").length
return (
<TooltipProvider>
<div className="space-y-4">
@@ -873,7 +950,7 @@ function AdminJobsPageContent() {
</div>
{/* ===== STICKY ACTION TOOLBAR ===== */}
<div className="sticky top-0 z-10 -mx-4 px-4 py-2 bg-background/95 backdrop-blur border-b">
<div className="sticky top-0 z-10 -mx-4 px-4 md:-mx-6 md:px-6 py-2 bg-background/95 backdrop-blur border-b">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide mr-1">Reset to:</span>
{[
@@ -1051,8 +1128,40 @@ function AdminJobsPageContent() {
{/* ===== HORIZONTAL TIMELINE ===== */}
<div className="py-3 border-b">
<div className="flex flex-wrap items-start gap-y-2">
{stageDurations.map((stage, i) => {
const isLast = i === stageDurations.length - 1
{timelineCollapsible && !timelineExpanded && (
<div className="flex items-start">
<button
className="flex flex-col items-center px-2 py-1 rounded-md border border-dashed text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors"
onClick={() => setTimelineExpanded(true)}
title="Show all timeline entries"
>
<span className="text-xs font-medium whitespace-nowrap">
+{hiddenStages.length} earlier
{hiddenFailures > 0 && (
<span className="text-red-500"> ({hiddenFailures} failed)</span>
)}
</span>
<span className="text-[10px] font-mono mt-0.5">
{formatTimeOnly(hiddenStages[0]?.startTime)}
</span>
</button>
<ChevronRight className="w-3 h-3 text-muted-foreground/40 mx-0.5 mt-2" />
</div>
)}
{timelineCollapsible && timelineExpanded && (
<div className="flex items-start">
<button
className="flex items-center px-2 py-2 rounded-md border border-dashed text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors"
onClick={() => setTimelineExpanded(false)}
title="Collapse older timeline entries"
>
<span className="text-xs font-medium whitespace-nowrap">Collapse</span>
</button>
<ChevronRight className="w-3 h-3 text-muted-foreground/40 mx-0.5 mt-2" />
</div>
)}
{visibleStages.map((stage, i) => {
const isLast = i === visibleStages.length - 1
const isCurrent = isLast
const bgColor = getTimelineStageColor(stage.status, isCurrent)
const textColor = getTimelineTextColor(stage.status)
@@ -1112,7 +1221,7 @@ function AdminJobsPageContent() {
{/* ===== JOB INFO GRID ===== */}
<div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-8 gap-4 py-3">
<div className="space-y-1">
<div className="space-y-1 min-w-0">
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">User</p>
{selectedJob.user_email ? (
<p
@@ -1126,28 +1235,44 @@ function AdminJobsPageContent() {
<p className="text-sm truncate text-muted-foreground">Unknown</p>
)}
</div>
<div className="space-y-1">
<div className="space-y-1 min-w-0">
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Language</p>
{selectedJob.locale ? (
<LocaleBadge locale={selectedJob.locale} showName />
) : (
<p className="text-sm text-muted-foreground">—</p>
)}
</div>
<div className="space-y-1 min-w-0">
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Country</p>
{selectedJob.creation_ip ? (
<div className="text-sm"><IpInfo ip={selectedJob.creation_ip} compact /></div>
) : (
<p className="text-sm text-muted-foreground">—</p>
)}
</div>
<div className="space-y-1 min-w-0">
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Source</p>
<button
className="text-sm flex items-center gap-1.5 text-primary hover:underline cursor-pointer truncate text-left"
className="w-full max-w-full min-w-0 text-sm flex items-center gap-1.5 text-primary hover:underline cursor-pointer text-left"
title="Click for source details"
onClick={() => setSourceModalOpen(true)}
>
<SourceIcon className="w-3.5 h-3.5 shrink-0" />
<span className="truncate">
<span className="truncate min-w-0">
{jobSource.type === "url" && jobSource.detail
? jobSource.detail.replace(/^https?:\/\/(www\.)?/, "").slice(0, 40)
? jobSource.detail.replace(/^https?:\/\/(www\.)?/, "")
: jobSource.detail || "Unknown"}
</span>
</button>
</div>
<div className="space-y-1">
<div className="space-y-1 min-w-0">
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Created</p>
<p className="text-sm" title={formatDate(selectedJob.created_at)}>
{formatDateCompact(selectedJob.created_at)}
</p>
</div>
<div className="space-y-1">
<div className="space-y-1 min-w-0">
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Progress</p>
<div className="flex items-center gap-2">
<div className="flex-1 h-1.5 bg-muted rounded-full overflow-hidden max-w-[60px]">
@@ -1160,19 +1285,19 @@ function AdminJobsPageContent() {
</div>
</div>
{/* Timing stats */}
<div className="space-y-1">
<div className="space-y-1 min-w-0">
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Total Time</p>
<p className="text-sm font-mono">{formatDurationLong(timingStats.total) || "—"}</p>
</div>
<div className="space-y-1">
<div className="space-y-1 min-w-0">
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Processing</p>
<p className="text-sm font-mono text-blue-600 dark:text-blue-400">{formatDurationLong(timingStats.processing) || "—"}</p>
</div>
<div className="space-y-1">
<div className="space-y-1 min-w-0">
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Waiting</p>
<p className="text-sm font-mono text-amber-600 dark:text-amber-400">{formatDurationLong(timingStats.waiting) || "—"}</p>
</div>
<div className="space-y-1">
<div className="space-y-1 min-w-0">
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Theme</p>
<p className="text-sm truncate">{selectedJob.theme_id || "default"}</p>
</div>
@@ -1232,15 +1357,21 @@ function AdminJobsPageContent() {
</div>
) : (
<div className="flex items-center gap-1 flex-1 min-w-0">
<span className="text-xs truncate flex-1">{value || "—"}</span>
<button
className="text-xs truncate flex-1 text-left rounded px-1 py-0.5 -mx-1 hover:bg-muted/70 cursor-text decoration-dotted underline-offset-2 group-hover:underline min-w-0"
onClick={() => startEditing(key, value || "")}
title={`Click to edit ${label.toLowerCase()}`}
>
{value || <span className="text-muted-foreground">— click to set</span>}
</button>
<Button
variant="ghost"
size="icon"
className="h-5 w-5 opacity-0 group-hover:opacity-100"
className="h-5 w-5 shrink-0 text-muted-foreground/60 hover:text-foreground"
onClick={() => startEditing(key, value || "")}
title={`Edit ${label}`}
>
<Pencil className="w-2.5 h-2.5" />
<Pencil className="w-3 h-3" />
</Button>
</div>
)}
@@ -1250,7 +1381,7 @@ function AdminJobsPageContent() {
{/* Private (non-published) toggle */}
<div className="flex items-center gap-2 pt-2 border-t">
<span className="text-[10px] font-medium text-muted-foreground uppercase w-20 shrink-0">Private</span>
<div className="flex items-center gap-2 flex-1">
<div className="flex items-center gap-2 flex-1 min-w-0">
<input
type="checkbox"
id="admin-is-private"
@@ -1430,7 +1561,7 @@ function AdminJobsPageContent() {
{/* ===== SOURCE INFO MODAL ===== */}
<Dialog open={sourceModalOpen} onOpenChange={setSourceModalOpen}>
<DialogContent className="max-w-md">
<DialogContent className="max-w-lg max-h-[85vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<SourceIcon className="w-4 h-4" />
@@ -1441,69 +1572,62 @@ function AdminJobsPageContent() {
</DialogDescription>
</DialogHeader>
<div className="space-y-3 text-sm">
{selectedJob.audio_source_type && (
<div className="flex justify-between">
<span className="text-muted-foreground">Source Type</span>
<span className="font-medium">{selectedJob.audio_source_type.replace(/_/g, " ")}</span>
</div>
)}
{selectedJob.source_name && (
<div className="flex justify-between">
<span className="text-muted-foreground">Provider</span>
<span className="font-medium">{selectedJob.source_name}</span>
</div>
)}
{selectedJob.source_id && (
<div className="flex justify-between">
<span className="text-muted-foreground">Source ID</span>
<span className="font-mono text-xs">{selectedJob.source_id}</span>
</div>
{(() => {
const externalUrl = getExternalSourceUrl(selectedJob)
return externalUrl ? (
<a
href={externalUrl}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-2 p-2.5 rounded-md border bg-muted/40 text-primary hover:bg-muted transition-colors"
>
<ExternalLink className="w-4 h-4 shrink-0" />
<span className="font-medium">
Open in {selectedJob.source_name || (selectedJob.url ? "YouTube" : "provider")}
</span>
<span className="ml-auto font-mono text-xs text-muted-foreground truncate max-w-[50%]">
{externalUrl.replace(/^https?:\/\/(www\.)?/, "")}
</span>
</a>
) : null
})()}
{[
{ label: "Source Type", value: selectedJob.audio_source_type?.replace(/_/g, " "), mono: false },
{ label: "Provider", value: selectedJob.source_name, mono: false },
{ label: "Source ID", value: selectedJob.source_id, mono: true },
{ label: "Search Artist", value: selectedJob.audio_search_artist, mono: false },
{ label: "Search Title", value: selectedJob.audio_search_title, mono: false },
{ label: "Filename", value: selectedJob.filename, mono: true },
{
label: "Target File",
value: selectedJob.target_file !== selectedJob.filename ? selectedJob.target_file : undefined,
mono: true,
},
].map(({ label, value, mono }) =>
value ? (
<div key={label} className="space-y-0.5">
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">{label}</p>
<p className={`break-all ${mono ? "font-mono text-xs" : "font-medium"}`}>{value}</p>
</div>
) : null
)}
{selectedJob.url && (
<div className="flex justify-between gap-2">
<span className="text-muted-foreground shrink-0">URL</span>
<div className="space-y-0.5">
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">URL</p>
<a
href={selectedJob.url}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline truncate font-mono text-xs"
className="block text-primary hover:underline break-all font-mono text-xs"
>
{selectedJob.url}
</a>
</div>
)}
{selectedJob.filename && (
<div className="flex justify-between gap-2">
<span className="text-muted-foreground shrink-0">Filename</span>
<span className="truncate font-mono text-xs">{selectedJob.filename}</span>
</div>
)}
{selectedJob.target_file && selectedJob.target_file !== selectedJob.filename && (
<div className="flex justify-between gap-2">
<span className="text-muted-foreground shrink-0">Target File</span>
<span className="truncate font-mono text-xs">{selectedJob.target_file}</span>
</div>
)}
{(selectedJob.audio_search_artist || selectedJob.audio_search_title) && (
<>
{selectedJob.audio_search_artist && (
<div className="flex justify-between">
<span className="text-muted-foreground">Search Artist</span>
<span>{selectedJob.audio_search_artist}</span>
</div>
)}
{selectedJob.audio_search_title && (
<div className="flex justify-between">
<span className="text-muted-foreground">Search Title</span>
<span>{selectedJob.audio_search_title}</span>
</div>
)}
</>
)}
{selectedJob.download_url && (
<div className="flex justify-between gap-2">
<span className="text-muted-foreground shrink-0">Download URL</span>
<span className="truncate font-mono text-xs">{selectedJob.download_url}</span>
<div className="space-y-0.5">
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Download URL</p>
<p className="break-all font-mono text-xs">{selectedJob.download_url}</p>
</div>
)}
{!selectedJob.audio_source_type && !selectedJob.url && !selectedJob.filename && (
@@ -2087,7 +2211,7 @@ function AdminJobsPageContent() {
<div className="flex flex-col sm:flex-row gap-4">
<div className="flex-1 flex gap-2">
<Input
placeholder="Filter by user email..."
placeholder="Filter by email, or paste a job ID..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
onKeyDown={handleKeyPress}
@@ -2097,7 +2221,7 @@ function AdminJobsPageContent() {
<Search className="w-4 h-4" />
</Button>
</div>
<Select value={statusFilter} onValueChange={setStatusFilter}>
<Select value={statusFilter} onValueChange={handleStatusChange}>
<SelectTrigger className="w-[200px]">
<SelectValue placeholder="Filter by status" />
</SelectTrigger>
@@ -2117,11 +2241,11 @@ function AdminJobsPageContent() {
<TableHeader>
<TableRow>
<TableHead>Job ID</TableHead>
<TableHead>User</TableHead>
<TableHead className="hidden md:table-cell">User</TableHead>
<TableHead>Artist / Title</TableHead>
<TableHead>Status</TableHead>
<TableHead>Progress</TableHead>
<TableHead>Created</TableHead>
<TableHead className="hidden sm:table-cell">Progress</TableHead>
<TableHead className="hidden lg:table-cell">Created</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
@@ -2146,28 +2270,33 @@ function AdminJobsPageContent() {
onClick={() => router.push(`/admin/jobs?id=${job.job_id}`)}
>
<TableCell className="font-mono text-sm">{job.job_id}</TableCell>
<TableCell className="text-sm text-muted-foreground max-w-[150px] truncate">
<TableCell className="hidden md:table-cell text-sm text-muted-foreground max-w-[150px] truncate">
{job.user_email || "—"}
</TableCell>
<TableCell>
{job.artist && job.title ? (
<span className="max-w-[200px] truncate block">
{job.artist} - {job.title}
</span>
) : job.filename ? (
<span className="max-w-[200px] truncate block text-muted-foreground">
{job.filename}
</span>
) : (
"—"
)}
<div className="flex items-center gap-2 min-w-0">
{job.artist && job.title ? (
<span className="max-w-[200px] truncate block">
{job.artist} - {job.title}
</span>
) : job.filename ? (
<span className="max-w-[200px] truncate block text-muted-foreground">
{job.filename}
</span>
) : (
"—"
)}
{job.locale && (
<LocaleBadge locale={job.locale} className="shrink-0 text-[10px] py-0 px-1.5 h-auto" />
)}
</div>
</TableCell>
<TableCell>
<Badge variant={getStatusVariant(job.status)}>
{job.status.replace(/_/g, " ")}
</Badge>
</TableCell>
<TableCell>
<TableCell className="hidden sm:table-cell">
<div className="flex items-center gap-2">
<div className="w-16 h-2 bg-muted rounded-full overflow-hidden">
<div
@@ -2180,8 +2309,8 @@ function AdminJobsPageContent() {
</span>
</div>
</TableCell>
<TableCell className="text-sm">
{formatDate(job.created_at)}
<TableCell className="hidden lg:table-cell text-sm whitespace-nowrap" title={formatDate(job.created_at)}>
{formatDateCompact(job.created_at)}
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-1" onClick={(e) => e.stopPropagation()}>
+18 -13
View File
@@ -40,7 +40,9 @@ function AdminBreadcrumb() {
breadcrumbs.push({ label: "Users" })
} else {
breadcrumbs.push({ label: "Users", href: "/admin/users" })
breadcrumbs.push({ label: decodeURIComponent(segments[2]) })
breadcrumbs.push({
label: segments[2] === "detail" ? "User Detail" : decodeURIComponent(segments[2]),
})
}
} else if (segments[1] === "jobs") {
if (segments.length === 2) {
@@ -49,18 +51,18 @@ function AdminBreadcrumb() {
breadcrumbs.push({ label: "Jobs", href: "/admin/jobs" })
breadcrumbs.push({ label: decodeURIComponent(segments[2]) })
}
} else if (segments[1] === "payments") {
breadcrumbs.push({ label: "Payments" })
} else if (segments[1] === "referrals") {
breadcrumbs.push({ label: "Referrals" })
} else if (segments[1] === "searches") {
breadcrumbs.push({ label: "Audio Searches" })
} else if (segments[1] === "payments") {
breadcrumbs.push({ label: "Payments" })
} else if (segments[1] === "rate-limits") {
breadcrumbs.push({ label: "Rate Limits" })
} else if (segments[1] === "abuse") {
breadcrumbs.push({ label: "Abuse Investigation" })
} else {
// Fallback: prettify the URL segment (payments, referrals, rate-limits, ...)
breadcrumbs.push({
label: segments[1]
.split("-")
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
.join(" "),
})
}
}
}
@@ -145,15 +147,18 @@ export default function AdminLayout({
<header className="flex h-16 shrink-0 items-center gap-2 border-b px-4">
<SidebarTrigger className="-ml-1" />
<Separator orientation="vertical" className="mr-2 h-4" />
<AdminBreadcrumb />
<div className="ml-auto flex items-center gap-2">
<div className="min-w-0 overflow-hidden">
<AdminBreadcrumb />
</div>
<div className="ml-auto flex items-center gap-2 shrink-0">
<Switch
id="show-test-data"
checked={showTestData}
onCheckedChange={setShowTestData}
/>
<Label htmlFor="show-test-data" className="text-sm text-muted-foreground cursor-pointer">
Show test data
<Label htmlFor="show-test-data" className="text-sm text-muted-foreground cursor-pointer whitespace-nowrap">
<span className="hidden sm:inline">Show test data</span>
<span className="sm:hidden">Test data</span>
</Label>
</div>
</header>
+28 -50
View File
@@ -1,6 +1,7 @@
"use client"
import { useEffect, useState } from "react"
import Link from "next/link"
import { adminApi, AdminStatsOverview, RevenueSummary } from "@/lib/api"
import { useAdminSettings } from "@/lib/admin-settings"
import { StatsCard, StatsGrid } from "@/components/admin/stats-card"
@@ -88,6 +89,7 @@ export default function AdminDashboardPage() {
description={`${stats?.active_users_7d ?? 0} active in last 7 days`}
icon={Users}
loading={loading}
href="/admin/users"
/>
<StatsCard
title="Total Jobs"
@@ -95,6 +97,7 @@ export default function AdminDashboardPage() {
description={`${stats?.jobs_last_7d ?? 0} in last 7 days`}
icon={Briefcase}
loading={loading}
href="/admin/jobs"
/>
<StatsCard
title="Revenue (30d)"
@@ -103,6 +106,7 @@ export default function AdminDashboardPage() {
icon={DollarSign}
loading={loading}
valueClassName="text-green-600 dark:text-green-400"
href="/admin/payments"
/>
<StatsCard
title="Credits Issued (30d)"
@@ -110,6 +114,7 @@ export default function AdminDashboardPage() {
description="Credits added to accounts"
icon={CreditCard}
loading={loading}
href="/admin/payments"
/>
</StatsGrid>
@@ -127,56 +132,29 @@ export default function AdminDashboardPage() {
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : (
<div className="space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Clock className="w-4 h-4 text-yellow-500" />
<span className="text-sm">Pending</span>
</div>
<Badge variant="secondary">{stats?.jobs_by_status?.pending ?? 0}</Badge>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Loader2 className="w-4 h-4 text-blue-500" />
<span className="text-sm">Processing</span>
</div>
<Badge variant="secondary">{stats?.jobs_by_status?.processing ?? 0}</Badge>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<AlertCircle className="w-4 h-4 text-orange-500" />
<span className="text-sm">Awaiting Review</span>
</div>
<Badge variant="secondary">{stats?.jobs_by_status?.awaiting_review ?? 0}</Badge>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<AlertCircle className="w-4 h-4 text-purple-500" />
<span className="text-sm">Awaiting Instrumental</span>
</div>
<Badge variant="secondary">{stats?.jobs_by_status?.awaiting_instrumental ?? 0}</Badge>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<CheckCircle className="w-4 h-4 text-green-500" />
<span className="text-sm">Complete</span>
</div>
<Badge variant="secondary">{stats?.jobs_by_status?.complete ?? 0}</Badge>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<XCircle className="w-4 h-4 text-red-500" />
<span className="text-sm">Failed</span>
</div>
<Badge variant="destructive">{stats?.jobs_by_status?.failed ?? 0}</Badge>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<XCircle className="w-4 h-4 text-muted-foreground" />
<span className="text-sm">Cancelled</span>
</div>
<Badge variant="outline">{stats?.jobs_by_status?.cancelled ?? 0}</Badge>
</div>
<div className="space-y-1">
{[
{ label: "Pending", icon: Clock, iconClass: "text-yellow-500", count: stats?.jobs_by_status?.pending ?? 0, href: "/admin/jobs?status=pending", badge: "secondary" as const },
{ label: "Processing", icon: Loader2, iconClass: "text-blue-500", count: stats?.jobs_by_status?.processing ?? 0, href: "/admin/jobs", badge: "secondary" as const },
{ label: "Awaiting Review", icon: AlertCircle, iconClass: "text-orange-500", count: stats?.jobs_by_status?.awaiting_review ?? 0, href: "/admin/jobs?status=awaiting_review", badge: "secondary" as const },
{ label: "Awaiting Instrumental", icon: AlertCircle, iconClass: "text-purple-500", count: stats?.jobs_by_status?.awaiting_instrumental ?? 0, href: "/admin/jobs?status=awaiting_instrumental_selection", badge: "secondary" as const },
{ label: "Complete", icon: CheckCircle, iconClass: "text-green-500", count: stats?.jobs_by_status?.complete ?? 0, href: "/admin/jobs?status=complete", badge: "secondary" as const },
{ label: "Failed", icon: XCircle, iconClass: "text-red-500", count: stats?.jobs_by_status?.failed ?? 0, href: "/admin/jobs?status=failed", badge: "destructive" as const },
{ label: "Cancelled", icon: XCircle, iconClass: "text-muted-foreground", count: stats?.jobs_by_status?.cancelled ?? 0, href: "/admin/jobs?status=cancelled", badge: "outline" as const },
].map(({ label, icon: RowIcon, iconClass, count, href, badge }) => (
<Link
key={label}
href={href}
className="flex items-center justify-between rounded-md px-2 py-1.5 -mx-2 hover:bg-muted/60 transition-colors"
title={`View ${label.toLowerCase()} jobs`}
>
<div className="flex items-center gap-2">
<RowIcon className={`w-4 h-4 ${iconClass}`} />
<span className="text-sm">{label}</span>
</div>
<Badge variant={badge}>{count}</Badge>
</Link>
))}
</div>
)}
</CardContent>
+26 -13
View File
@@ -70,6 +70,8 @@ import { cn } from "@/lib/utils"
import { useToast } from "@/hooks/use-toast"
import { useAuth } from "@/lib/auth"
import { IpInfo } from "@/components/admin/ip-info"
import { LocaleBadge } from "@/components/admin/locale-badge"
import { UserEmailsCard } from "@/components/admin/user-emails-card"
export default function AdminUserDetailPage() {
const searchParams = useSearchParams()
@@ -333,23 +335,26 @@ export default function AdminUserDetailPage() {
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<Button variant="ghost" size="icon" onClick={() => router.push("/admin/users")} title="Back to users list">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
<div className="flex items-start gap-2 sm:gap-4 min-w-0">
<Button variant="ghost" size="icon" className="shrink-0" onClick={() => router.push("/admin/users")} title="Back to users list">
<ArrowLeft className="w-4 h-4" />
</Button>
<div>
<h1 className="text-2xl font-bold tracking-tight flex items-center gap-2">
{user.display_name || user.email}
<div className="min-w-0">
<h1 className="text-xl sm:text-2xl font-bold tracking-tight flex items-center gap-2 flex-wrap">
<span className="break-all">{user.display_name || user.email}</span>
<Badge variant={user.role === "admin" ? "default" : "secondary"}>
{user.role}
</Badge>
{!user.is_active && <Badge variant="destructive">Disabled</Badge>}
{/* UI language the user browses in — so support communicates in the
right language. Falls back to the email locale if unknown. */}
<LocaleBadge locale={user.ui_locale || user.locale} showName />
</h1>
<p className="text-muted-foreground">{user.email}</p>
<p className="text-muted-foreground break-all">{user.email}</p>
</div>
</div>
<div className="flex gap-2">
<div className="flex gap-2 shrink-0">
<Button variant="outline" size="sm" onClick={loadUser} disabled={loading}>
<RefreshCw className={`w-4 h-4 mr-2 ${loading ? "animate-spin" : ""}`} />
Refresh
@@ -422,7 +427,7 @@ export default function AdminUserDetailPage() {
</div>
{/* Stats Grid */}
<div className="grid gap-4 md:grid-cols-4">
<div className="grid grid-cols-2 gap-3 sm:gap-4 md:grid-cols-4">
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium flex items-center gap-2">
@@ -527,9 +532,9 @@ export default function AdminUserDetailPage() {
<span className="text-muted-foreground">Signup IP</span>
<IpInfo ip={user.signup_ip} />
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Device Fingerprint</span>
<code className="text-xs bg-muted px-1.5 py-0.5 rounded">{user.device_fingerprint || "unknown"}</code>
<div className="flex justify-between gap-4">
<span className="text-muted-foreground shrink-0">Device Fingerprint</span>
<code className="text-xs bg-muted px-1.5 py-0.5 rounded break-all text-right">{user.device_fingerprint || "unknown"}</code>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Welcome Credits</span>
@@ -696,7 +701,12 @@ export default function AdminUserDetailPage() {
>
<TableCell className="font-mono text-sm">{job.job_id}</TableCell>
<TableCell>
{job.artist && job.title ? `${job.artist} - ${job.title}` : "—"}
<span className="inline-flex items-center gap-2">
{job.artist && job.title ? `${job.artist} - ${job.title}` : "—"}
{job.locale && (
<LocaleBadge locale={job.locale} className="text-[10px] py-0 px-1.5 h-auto" />
)}
</span>
</TableCell>
<TableCell>
<Badge variant={
@@ -718,6 +728,9 @@ export default function AdminUserDetailPage() {
</CardContent>
</Card>
{/* Emails sent to this user */}
<UserEmailsCard email={email} />
{/* Add Credits Dialog */}
<Dialog open={creditDialogOpen} onOpenChange={setCreditDialogOpen}>
<DialogContent>
+145 -18
View File
@@ -38,6 +38,7 @@ import {
ChevronLeft,
ChevronRight,
Plus,
UserPlus,
Loader2,
CreditCard,
LogIn,
@@ -101,6 +102,13 @@ export default function AdminUsersPage() {
// Impersonation state - tracks which user is being impersonated (for loading indicator)
const [impersonatingEmail, setImpersonatingEmail] = useState<string | null>(null)
// Create user dialog state
const [createDialogOpen, setCreateDialogOpen] = useState(false)
const [newUserEmail, setNewUserEmail] = useState("")
const [newUserDisplayName, setNewUserDisplayName] = useState("")
const [newUserCredits, setNewUserCredits] = useState("")
const [creatingUser, setCreatingUser] = useState(false)
const loadUsers = useCallback(async () => {
try {
setLoading(true)
@@ -178,6 +186,60 @@ export default function AdminUsersPage() {
}
}
const handleCreateUser = async () => {
const email = newUserEmail.trim().toLowerCase()
if (!email || !email.includes("@")) {
toast({
title: "Invalid Email",
description: "Please enter a valid email address",
variant: "destructive",
})
return
}
let credits = 0
if (newUserCredits.trim()) {
credits = parseInt(newUserCredits.trim(), 10)
if (!Number.isInteger(credits) || credits < 0 || credits > 1000) {
toast({
title: "Invalid Credits",
description: "Initial credits must be between 0 and 1,000",
variant: "destructive",
})
return
}
}
try {
setCreatingUser(true)
const result = await adminApi.createUser({
email,
display_name: newUserDisplayName.trim() || undefined,
initial_credits: credits,
})
toast({
title: "User Created",
description: result.message,
})
setCreateDialogOpen(false)
setNewUserEmail("")
setNewUserDisplayName("")
setNewUserCredits("")
// Surface the new user in the list
setSearchInput(email)
setSearch(email)
setOffset(0)
} catch (err: any) {
toast({
title: "Error",
description: err.message || "Failed to create user",
variant: "destructive",
})
} finally {
setCreatingUser(false)
}
}
const handleImpersonate = async (user: AdminUser) => {
// Don't allow impersonating yourself
if (user.email === currentUser?.email) {
@@ -229,10 +291,16 @@ export default function AdminUsersPage() {
Manage user accounts and credits
</p>
</div>
<Button variant="outline" size="sm" onClick={loadUsers} disabled={loading}>
<RefreshCw className={`w-4 h-4 mr-2 ${loading ? "animate-spin" : ""}`} />
Refresh
</Button>
<div className="flex gap-2">
<Button size="sm" onClick={() => setCreateDialogOpen(true)}>
<UserPlus className="w-4 h-4 mr-2" />
Create User
</Button>
<Button variant="outline" size="sm" onClick={loadUsers} disabled={loading}>
<RefreshCw className={`w-4 h-4 mr-2 ${loading ? "animate-spin" : ""}`} />
Refresh
</Button>
</div>
</div>
{/* Filters */}
@@ -242,7 +310,7 @@ export default function AdminUsersPage() {
placeholder="Search by email..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
onKeyPress={handleKeyPress}
onKeyDown={handleKeyPress}
className="max-w-sm"
/>
<Button variant="secondary" onClick={handleSearch}>
@@ -288,7 +356,7 @@ export default function AdminUsersPage() {
{sortBy === "email" ? (sortOrder === "asc" ? <ArrowUp className="w-3 h-3" /> : <ArrowDown className="w-3 h-3" />) : <ArrowUpDown className="w-3 h-3 text-muted-foreground/50" />}
</span>
</TableHead>
<TableHead>Role</TableHead>
<TableHead className="hidden sm:table-cell">Role</TableHead>
<TableHead
className="text-right cursor-pointer select-none"
onClick={() => { setSortBy("credits"); setSortOrder(sortBy === "credits" && sortOrder === "desc" ? "asc" : "desc"); setOffset(0) }}
@@ -299,10 +367,10 @@ export default function AdminUsersPage() {
{sortBy === "credits" ? (sortOrder === "asc" ? <ArrowUp className="w-3 h-3" /> : <ArrowDown className="w-3 h-3" />) : <ArrowUpDown className="w-3 h-3 text-muted-foreground/50" />}
</span>
</TableHead>
<TableHead className="text-right">Spent</TableHead>
<TableHead className="text-right">Jobs</TableHead>
<TableHead className="hidden lg:table-cell text-right">Spent</TableHead>
<TableHead className="hidden md:table-cell text-right">Jobs</TableHead>
<TableHead
className="cursor-pointer select-none"
className="hidden lg:table-cell cursor-pointer select-none"
onClick={() => { setSortBy("created_at"); setSortOrder(sortBy === "created_at" && sortOrder === "desc" ? "asc" : "desc"); setOffset(0) }}
title="Sort by creation date"
>
@@ -312,7 +380,7 @@ export default function AdminUsersPage() {
</span>
</TableHead>
<TableHead
className="cursor-pointer select-none"
className="hidden md:table-cell cursor-pointer select-none"
onClick={() => { setSortBy("last_login_at"); setSortOrder(sortBy === "last_login_at" && sortOrder === "desc" ? "asc" : "desc"); setOffset(0) }}
title="Sort by last login"
>
@@ -345,30 +413,30 @@ export default function AdminUsersPage() {
onClick={() => router.push(`/admin/users/detail?email=${encodeURIComponent(user.email)}`)}
title="View user details"
>
<TableCell className="font-medium">
{user.display_name || user.email}
<TableCell className="font-medium max-w-[180px] sm:max-w-[260px]">
<span className="block truncate">{user.display_name || user.email}</span>
{user.display_name && (
<span className="text-muted-foreground text-sm block">
<span className="text-muted-foreground text-sm block truncate">
{user.email}
</span>
)}
</TableCell>
<TableCell>
<TableCell className="hidden sm:table-cell">
<Badge variant={user.role === "admin" ? "default" : "secondary"}>
{user.role}
</Badge>
</TableCell>
<TableCell className="text-right">{user.credits}</TableCell>
<TableCell className="text-right text-sm text-muted-foreground">
<TableCell className="hidden lg:table-cell text-right text-sm text-muted-foreground">
{(user.total_spent ?? 0) > 0 ? `$${((user.total_spent ?? 0) / 100).toFixed(2)}` : "—"}
</TableCell>
<TableCell className="text-right">
<TableCell className="hidden md:table-cell text-right">
{user.total_jobs_created ?? 0} / {user.total_jobs_completed ?? 0}
</TableCell>
<TableCell className="text-sm text-muted-foreground" title={formatFullDate(user.created_at)}>
<TableCell className="hidden lg:table-cell text-sm text-muted-foreground" title={formatFullDate(user.created_at)}>
{formatRelativeTime(user.created_at)}
</TableCell>
<TableCell className="text-sm text-muted-foreground" title={formatFullDate(user.last_login_at)}>
<TableCell className="hidden md:table-cell text-sm text-muted-foreground" title={formatFullDate(user.last_login_at)}>
{formatRelativeTime(user.last_login_at)}
</TableCell>
<TableCell className="text-right">
@@ -478,6 +546,65 @@ export default function AdminUsersPage() {
</DialogFooter>
</DialogContent>
</Dialog>
{/* Create User Dialog */}
<Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Create User</DialogTitle>
<DialogDescription>
Create an account for someone who hasn&apos;t logged in yet, so you can
grant credits, submit jobs on their behalf, or impersonate them. They
can log in later via magic link with the same email.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="new-user-email">Email</Label>
<Input
id="new-user-email"
type="email"
placeholder="user@example.com"
value={newUserEmail}
onChange={(e) => setNewUserEmail(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="new-user-display-name">Display Name (optional)</Label>
<Input
id="new-user-display-name"
placeholder="e.g., Jane Singer"
value={newUserDisplayName}
onChange={(e) => setNewUserDisplayName(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="new-user-credits">Initial Credits (optional)</Label>
<Input
id="new-user-credits"
type="number"
min="0"
max="1000"
placeholder="0"
value={newUserCredits}
onChange={(e) => setNewUserCredits(e.target.value)}
/>
<p className="text-sm text-muted-foreground">
If set, these replace the automatic welcome credit on first login.
</p>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setCreateDialogOpen(false)}>
Cancel
</Button>
<Button onClick={handleCreateUser} disabled={!newUserEmail.trim() || creatingUser}>
{creatingUser && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
Create User
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}
@@ -0,0 +1,69 @@
"use client"
/**
* LocaleBadge — small flag + language pill for admin views.
*
* Shows the UI language a user/job was using the product in, so support/intervention
* can communicate in the right language. Admin-only: never rendered in the customer UI.
*
* `locale` is a primary language subtag (any of the 33 supported UI locales, e.g.
* "pt", "ja", "zh"). The flag is a representative country for that language (decorative);
* the language name comes from Intl.DisplayNames.
*/
import { Badge } from "@/components/ui/badge"
import { countryCodeToFlag } from "@/lib/ip-geolocation"
// Representative country flag per supported language subtag (decorative only).
const LOCALE_TO_COUNTRY: Record<string, string> = {
en: "GB", es: "ES", de: "DE", pt: "PT", fr: "FR", ja: "JP", ko: "KR",
zh: "CN", it: "IT", nl: "NL", pl: "PL", tr: "TR", ru: "RU", th: "TH",
id: "ID", vi: "VN", tl: "PH", hi: "IN", ar: "SA", sv: "SE", nb: "NO",
da: "DK", fi: "FI", cs: "CZ", ro: "RO", hu: "HU", el: "GR", he: "IL",
ms: "MY", uk: "UA", hr: "HR", sk: "SK", ca: "ES",
}
function languageName(locale: string): string {
try {
const dn = new Intl.DisplayNames(["en"], { type: "language" })
return dn.of(locale) || locale
} catch {
return locale
}
}
export function localeDisplayName(locale?: string | null): string | null {
if (!locale) return null
return languageName(locale.toLowerCase())
}
interface LocaleBadgeProps {
locale?: string | null
/** Show the full language name instead of just the code (for detail views). */
showName?: boolean
/** Render a muted placeholder when no locale is known (default: render nothing). */
showEmpty?: boolean
className?: string
}
export function LocaleBadge({ locale, showName = false, showEmpty = false, className }: LocaleBadgeProps) {
const normalized = locale ? locale.toLowerCase().split("-")[0] : ""
if (!normalized) {
if (!showEmpty) return null
return (
<Badge variant="outline" className={className} title="Unknown language">
🌐 —
</Badge>
)
}
const flag = countryCodeToFlag(LOCALE_TO_COUNTRY[normalized] || "")
const name = languageName(normalized)
const label = showName ? name : normalized
return (
<Badge variant="secondary" className={className} title={`Language: ${name} (${normalized})`}>
{flag ? `${flag} ` : ""}{label}
</Badge>
)
}
+11 -2
View File
@@ -1,5 +1,6 @@
"use client"
import Link from "next/link"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { cn } from "@/lib/utils"
@@ -18,6 +19,8 @@ interface StatsCardProps {
loading?: boolean
className?: string
valueClassName?: string
/** When set, the whole card becomes a link to this page */
href?: string
}
export function StatsCard({
@@ -29,6 +32,7 @@ export function StatsCard({
loading,
className,
valueClassName,
href,
}: StatsCardProps) {
if (loading) {
return (
@@ -46,8 +50,8 @@ export function StatsCard({
)
}
return (
<Card className={cn("", className)}>
const card = (
<Card className={cn(href && "transition-colors hover:bg-muted/50 hover:border-primary/30", className)}>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
{title}
@@ -70,6 +74,11 @@ export function StatsCard({
</CardContent>
</Card>
)
if (href) {
return <Link href={href} className="block">{card}</Link>
}
return card
}
interface StatsGridProps {
@@ -0,0 +1,252 @@
"use client"
/**
* UserEmailsCard — "Emails sent to this user" section for the admin user-detail page.
*
* Lists every email ever sent to the user (Postmark Messages API for the last ~45 days,
* merged with our persisted email_log for older mail). Clicking a row opens a modal that
* renders the email exactly as it appeared in the inbox (sandboxed iframe) alongside its
* delivery metadata.
*/
import { useEffect, useState } from "react"
import { adminApi, UserEmailSummary, EmailDetail } from "@/lib/api"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Mail, RefreshCw, Loader2 } from "lucide-react"
function formatDate(value?: string | null): string {
if (!value) return "—"
const d = new Date(value)
return isNaN(d.getTime()) ? String(value) : d.toLocaleString()
}
function statusVariant(status?: string | null): "default" | "secondary" | "destructive" | "outline" {
const s = (status || "").toLowerCase()
if (s.includes("bounce") || s.includes("fail")) return "destructive"
if (s.includes("delivered") || s.includes("sent") || s.includes("opened")) return "default"
return "secondary"
}
function joinAddrs(value?: string | string[] | null): string {
if (!value) return ""
return Array.isArray(value) ? value.join(", ") : value
}
export function UserEmailsCard({ email }: { email: string }) {
const [emails, setEmails] = useState<UserEmailSummary[]>([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [postmarkAvailable, setPostmarkAvailable] = useState(true)
const [selected, setSelected] = useState<UserEmailSummary | null>(null)
const [detail, setDetail] = useState<EmailDetail | null>(null)
const [detailLoading, setDetailLoading] = useState(false)
const [detailError, setDetailError] = useState<string | null>(null)
const load = async () => {
if (!email) return
try {
setLoading(true)
setError(null)
const data = await adminApi.getUserEmails(email)
setEmails(data.emails || [])
setPostmarkAvailable(data.postmark_available)
} catch (err: any) {
setError(err?.message || "Failed to load emails")
} finally {
setLoading(false)
}
}
useEffect(() => {
load()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [email])
const openEmail = async (item: UserEmailSummary) => {
setSelected(item)
setDetail(null)
setDetailError(null)
setDetailLoading(true)
try {
// Prefer the Postmark record for rich metadata; fall back to our stored
// copy for messages older than Postmark's retention window.
const source = item.source === "log" ? "log" : "postmark"
const id = item.message_id || item.doc_id || ""
const data = await adminApi.getEmailDetail(id, source)
setDetail(data)
} catch (err: any) {
setDetailError(err?.message || "Failed to load email")
} finally {
setDetailLoading(false)
}
}
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0">
<div>
<CardTitle className="flex items-center gap-2">
<Mail className="w-4 h-4" /> Emails Sent
{emails.length > 0 && <Badge variant="secondary">{emails.length}</Badge>}
</CardTitle>
<CardDescription>
Every email sent to this user — click to view it exactly as they received it.
{!postmarkAvailable && " (Postmark unavailable — showing stored log only.)"}
</CardDescription>
</div>
<Button variant="ghost" size="icon" onClick={load} disabled={loading} title="Refresh">
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
</Button>
</CardHeader>
<CardContent>
{error ? (
<p className="text-sm text-destructive">{error}</p>
) : loading && emails.length === 0 ? (
<p className="text-sm text-muted-foreground">Loading emails…</p>
) : emails.length === 0 ? (
<p className="text-sm text-muted-foreground">No emails found for this user.</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Sent</TableHead>
<TableHead>Subject</TableHead>
<TableHead>Type</TableHead>
<TableHead>Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{emails.map((item, i) => (
<TableRow
key={item.message_id || item.doc_id || i}
className="cursor-pointer hover:bg-muted/50 focus-visible:bg-muted/50 focus-visible:outline-none"
role="button"
tabIndex={0}
aria-label={`Open email: ${item.subject || "(no subject)"}`}
onClick={() => openEmail(item)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault()
openEmail(item)
}
}}
>
<TableCell className="text-sm whitespace-nowrap">{formatDate(item.sent_at)}</TableCell>
<TableCell className="text-sm max-w-[280px] truncate">{item.subject || "(no subject)"}</TableCell>
<TableCell>
{item.email_type ? (
<Badge variant="outline" className="text-[10px]">{item.email_type}</Badge>
) : (
<span className="text-muted-foreground text-xs">—</span>
)}
</TableCell>
<TableCell>
{item.status ? (
<Badge variant={statusVariant(item.status)}>{item.status}</Badge>
) : (
<span className="text-muted-foreground text-xs">
{item.source === "log" ? "logged" : "—"}
</span>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
<Dialog open={!!selected} onOpenChange={(open) => !open && setSelected(null)}>
<DialogContent className="max-w-4xl max-h-[90vh] overflow-hidden flex flex-col">
<DialogHeader>
<DialogTitle className="truncate">{selected?.subject || "Email"}</DialogTitle>
<DialogDescription>
Rendered exactly as it appeared in the recipient&apos;s inbox.
</DialogDescription>
</DialogHeader>
{detailLoading ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground py-8 justify-center">
<Loader2 className="w-4 h-4 animate-spin" /> Loading email…
</div>
) : detailError ? (
<p className="text-sm text-destructive py-4">{detailError}</p>
) : detail ? (
<div className="flex-1 min-h-0 grid grid-cols-1 md:grid-cols-[220px_1fr] gap-4 overflow-hidden">
{/* Metadata side panel */}
<div className="text-xs space-y-2 overflow-y-auto pr-1">
<MetaRow label="To" value={joinAddrs(detail.to)} />
<MetaRow label="From" value={detail.from_email} />
{joinAddrs(detail.cc) && <MetaRow label="Cc" value={joinAddrs(detail.cc)} />}
{joinAddrs(detail.bcc) && <MetaRow label="Bcc" value={joinAddrs(detail.bcc)} />}
<MetaRow label="Sent" value={formatDate(detail.sent_at)} />
{detail.status && (
<div className="flex flex-col gap-0.5">
<span className="text-muted-foreground">Status</span>
<Badge variant={statusVariant(detail.status)} className="w-fit">{detail.status}</Badge>
</div>
)}
{detail.delivered_at && <MetaRow label="Delivered" value={formatDate(detail.delivered_at)} />}
{typeof detail.open_count === "number" && <MetaRow label="Opens" value={String(detail.open_count)} />}
{typeof detail.click_count === "number" && <MetaRow label="Clicks" value={String(detail.click_count)} />}
{detail.email_type && <MetaRow label="Type" value={detail.email_type} />}
{detail.bounce && Object.keys(detail.bounce).length > 0 && (
<MetaRow label="Bounce" value={detail.bounce.Type || detail.bounce.Description || JSON.stringify(detail.bounce)} />
)}
{detail.source === "log" && (
<p className="text-muted-foreground italic pt-1">
From our stored copy (older than Postmark&apos;s 45-day retention).
</p>
)}
</div>
{/* Email body rendered in an isolated sandboxed iframe */}
<div className="min-h-0 overflow-hidden border rounded-md bg-white">
{detail.html_body ? (
<iframe
title="Email preview"
sandbox=""
srcDoc={detail.html_body}
className="w-full h-[60vh]"
/>
) : detail.text_body ? (
<pre className="w-full h-[60vh] overflow-auto p-4 text-xs whitespace-pre-wrap text-black">
{detail.text_body}
</pre>
) : (
<p className="p-4 text-sm text-muted-foreground">No body content available.</p>
)}
</div>
</div>
) : null}
</DialogContent>
</Dialog>
</Card>
)
}
function MetaRow({ label, value }: { label: string; value?: string | null }) {
return (
<div className="flex flex-col gap-0.5">
<span className="text-muted-foreground">{label}</span>
<span className="break-words">{value || "—"}</span>
</div>
)
}
@@ -0,0 +1,88 @@
"use client"
import { useEffect, useState } from "react"
import { useTranslations } from "next-intl"
import { Loader2, CloudOff, X } from "lucide-react"
import {
useBackendStatus,
__installBackendStatusDevHook,
} from "@/lib/backend-status"
/**
* App-wide, non-blocking banner that reacts to backend connectivity (see
* lib/backend-status.ts). During a brief origin blip — e.g. Cloud Run recycling its
* single min-instance — the API is momentarily unreachable even though nothing is
* broken and any in-flight karaoke renders keep running. Rather than every screen
* showing its own scary error, this shows a single reassuring message:
*
* - "reconnecting": a subtle pill with a spinner while we transparently retry.
* - "unavailable": a gentle card explaining it's temporary and that ongoing jobs
* are unaffected, once trouble persists past the threshold.
*
* It floats over content (no layout shift) and disappears the instant connectivity
* is restored.
*/
export function BackendStatusBanner() {
const status = useBackendStatus()
const t = useTranslations("backendStatus")
const [dismissed, setDismissed] = useState(false)
// Expose the dev/preview trigger (window.__nkBackendStatus) for manual UX review.
useEffect(() => {
__installBackendStatusDevHook()
}, [])
// Re-arm the dismiss so a *later* outage episode shows again.
useEffect(() => {
if (status === "online") setDismissed(false)
}, [status])
if (status === "online") return null
if (status === "reconnecting") {
return (
<div
className="fixed top-3 left-1/2 z-[60] -translate-x-1/2 pointer-events-none"
role="status"
aria-live="polite"
>
<div className="flex items-center gap-2 rounded-full border border-amber-500/30 bg-amber-950/80 px-3.5 py-1.5 text-xs text-amber-200 shadow-lg backdrop-blur">
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin" />
<span>{t("reconnecting")}</span>
</div>
</div>
)
}
// status === "unavailable"
if (dismissed) return null
return (
<div
className="fixed top-3 left-1/2 z-[60] w-[calc(100%-1.5rem)] max-w-md -translate-x-1/2"
role="alert"
aria-live="assertive"
>
<div className="relative rounded-xl border border-amber-500/40 bg-amber-950/90 px-4 py-3 pr-9 text-amber-100 shadow-2xl backdrop-blur">
<button
type="button"
onClick={() => setDismissed(true)}
aria-label={t("dismiss")}
className="absolute right-2 top-2 rounded-md p-1 text-amber-300/70 transition-colors hover:bg-amber-800/50 hover:text-amber-100"
>
<X className="h-4 w-4" />
</button>
<div className="flex items-start gap-3">
<CloudOff className="mt-0.5 h-5 w-5 shrink-0 text-amber-300" />
<div className="space-y-1">
<p className="text-sm font-semibold text-amber-50">{t("unavailable.title")}</p>
<p className="text-xs leading-relaxed text-amber-200/90">{t("unavailable.body")}</p>
<p className="text-xs leading-relaxed text-amber-200/70">
{t("unavailable.reassurance")}
</p>
</div>
</div>
</div>
</div>
)
}
+6
View File
@@ -13,6 +13,7 @@ import { DurationCostConfirm } from "./DurationCostConfirm"
import { BuyCreditsDialog } from "@/components/credits/BuyCreditsDialog"
import { getJobStep, formatStepIndicator, getJobProgressPercent, isWaitingForEncodingCapacity, isVisibilityChangeInProgress } from "@/lib/job-status"
import { useAuth } from "@/lib/auth"
import { LocaleBadge } from "@/components/admin/locale-badge"
import { useDurationConfirm } from "@/hooks/use-duration-confirm"
import { parseServerDate } from "@/lib/utils"
@@ -231,6 +232,11 @@ export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
<span>{createdAt}</span>
<span style={{ opacity: 0.7 }}>•</span>
<StatusIndicator job={job} />
{/* Admin-only: what UI language the job was submitted in. Hidden from
regular users (redundant — it's always their own language). */}
{isAdmin && job.locale && (
<LocaleBadge locale={job.locale} className="text-[10px] py-0 px-1.5 h-auto" />
)}
</p>
{/* Progress bar for active jobs */}
+15 -3
View File
@@ -119,9 +119,21 @@ export function TenantJobFlow({ onJobCreated }: TenantJobFlowProps) {
setPhase("done")
onJobCreated()
} catch (err: any) {
const message = err instanceof ApiError
? err.message
: "Something went wrong. Please try again."
// Surface the real cause for debugging — the generic user-facing string
// below hides which step failed (create / upload / complete).
console.error("[TenantJobFlow] submit failed:", err)
let message: string
if (err instanceof ApiError) {
message = err.message
} else if (
err instanceof TypeError ||
/network|failed to fetch|load failed/i.test(String(err?.message ?? ""))
) {
// fetch()/XHR network-level failure (offline, connection reset, CORS).
message = t('submitNetworkError')
} else {
message = t('submitError')
}
setError(message)
setPhase("idle")
setUploadProgress(0)
@@ -1,8 +1,9 @@
'use client'
import { memo, useRef, useCallback } from 'react'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { Play, XCircle, Hand } from 'lucide-react'
import { Hand } from 'lucide-react'
import { Word } from '@/lib/lyrics-review/types'
import TimelineEditor from './TimelineEditor'
import { cn } from '@/lib/utils'
@@ -17,6 +18,7 @@ const TapButton = memo(function TapButton({
onTapStart: () => void
onTapEnd: () => void
}) {
const t = useTranslations('lyricsReview.editTimeline')
const isPressedRef = useRef(false)
const handleTapStart = useCallback(() => {
@@ -51,7 +53,7 @@ const TapButton = memo(function TapButton({
)}
>
<Hand className="h-5 w-5 mr-2" />
{isSpacebarPressed ? 'HOLD...' : 'TAP'}
{isSpacebarPressed ? t('hold') : t('tap')}
</Button>
)
})
@@ -60,17 +62,12 @@ interface EditTimelineSectionProps {
words: Word[]
startTime: number
endTime: number
originalStartTime: number | null
originalEndTime: number | null
currentStartTime: number | null
currentEndTime: number | null
currentTime?: number
isManualSyncing: boolean
syncWordIndex: number
isSpacebarPressed: boolean
onWordUpdate: (index: number, updates: Partial<Word>) => void
onPlaySegment?: (time: number) => void
startManualSync: () => void
isGlobal?: boolean
onTapStart?: () => void
onTapEnd?: () => void
@@ -80,21 +77,17 @@ export default function EditTimelineSection({
words,
startTime,
endTime,
originalStartTime,
originalEndTime,
currentStartTime,
currentEndTime,
currentTime,
isManualSyncing,
syncWordIndex,
isSpacebarPressed,
onWordUpdate,
onPlaySegment,
startManualSync,
isGlobal = false,
onTapStart,
onTapEnd,
}: EditTimelineSectionProps) {
const t = useTranslations('lyricsReview.editTimeline')
// Simple mobile detection
const isMobile = typeof window !== 'undefined' && window.innerWidth < 640
@@ -110,8 +103,9 @@ export default function EditTimelineSection({
return (
<>
{/* Timeline Editor */}
<div className={cn('mb-0', isMobile ? 'h-20' : 'h-[120px]')}>
{/* Timeline Editor — height hugs its content (ruler + word bars + waveform)
instead of a fixed min-height, to avoid dead vertical space. */}
<div>
<TimelineEditor
words={words}
startTime={startTime}
@@ -122,70 +116,32 @@ export default function EditTimelineSection({
/>
</div>
{/* Time range info and controls */}
<div
className={cn(
'flex items-center justify-between gap-2',
isMobile ? 'flex-col items-stretch mt-2 mb-3' : 'flex-row mt-0 mb-0'
)}
>
{/* Time range info - hidden on mobile to save space */}
{!isMobile && (
<div className="text-xs text-muted-foreground">
<div>
Original Time Range: {originalStartTime?.toFixed(2) ?? 'N/A'} -{' '}
{originalEndTime?.toFixed(2) ?? 'N/A'}
</div>
<div>
Current Time Range: {currentStartTime?.toFixed(2) ?? 'N/A'} -{' '}
{currentEndTime?.toFixed(2) ?? 'N/A'}
</div>
</div>
)}
{/* Controls */}
{/* Sync helper — only visible while manually syncing. The Tap To Sync
toggle and the time-range readout now live in the modal header to
reclaim the vertical space above the word list. */}
{(currentWordInfo || (isMobile && isManualSyncing)) && (
<div
className={cn(
'flex items-center gap-2',
isMobile ? 'flex-col items-stretch' : 'flex-row'
isMobile ? 'flex-col items-stretch mt-2 mb-3' : 'flex-row mt-0 mb-0'
)}
>
{/* Tap To Sync button */}
<Button
variant={isManualSyncing ? 'outline' : 'default'}
onClick={startManualSync}
className={cn(
isManualSyncing
? 'border-destructive text-destructive hover:bg-destructive/10'
: 'bg-primary'
)}
>
{isManualSyncing ? (
<>
<XCircle className="h-4 w-4 mr-1" />
Cancel
</>
) : (
<>
<Play className="h-4 w-4 mr-1" />
Tap To Sync
</>
)}
</Button>
{/* Current word info during sync */}
{currentWordInfo && (
<div className={cn('text-center', isMobile ? '' : 'text-left')}>
<div className="text-sm">
Word {currentWordInfo.index} of {currentWordInfo.total}:{' '}
{t('wordProgress', {
index: currentWordInfo.index,
total: currentWordInfo.total,
})}{' '}
<strong>{currentWordInfo.text}</strong>
</div>
<div className="text-xs text-muted-foreground">
{isSpacebarPressed
? 'Holding... Release when word ends'
? t('holdingRelease')
: isMobile
? 'Tap the button when word starts'
: 'Press spacebar when word starts (tap for short words, hold for long words)'}
? t('tapWhenStarts')
: t('pressSpacebarHint')}
</div>
</div>
)}
@@ -199,7 +155,7 @@ export default function EditTimelineSection({
/>
)}
</div>
</div>
)}
</>
)
}
@@ -20,6 +20,7 @@ import {
WordClickInfo,
ModalContent,
SearchLyricsResponse,
AddLyricsResult,
} from '@/lib/lyrics-review/types'
import type { EditLog, EditLogEntry, EditFeedbackReason } from '@/lib/lyrics-review/types'
import type { InstrumentalSelectionType, LyricsReviewApiClient } from '@/lib/api'
@@ -62,6 +63,7 @@ import AutoCorrectPanel from './AutoCorrectPanel'
import { useAutoCorrect } from '@/hooks/useAutoCorrect'
import { getWordsFromIds } from '@/lib/lyrics-review/utils/wordUtils'
import { applyOffsetToCorrectionData, applyOffsetToSegment } from '@/lib/lyrics-review/utils/timingUtils'
import { VocalsAudioDataLoader } from './VocalsAudioDataLoader'
// Add type for window augmentation
declare global {
@@ -78,9 +80,10 @@ interface ApiClient {
submitAnnotations: (annotations: never[]) => Promise<void>
submitEditLog: (editLog: EditLog) => Promise<void>
updateHandlers: (handlers: string[]) => Promise<CorrectionData>
addLyrics: (source: string, lyrics: string) => Promise<CorrectionData>
addLyrics: (source: string, lyrics: string, force?: boolean) => Promise<AddLyricsResult>
searchLyrics?: (artist: string, title: string, forceSources?: string[]) => Promise<SearchLyricsResponse>
getAudioUrl: (hash: string) => string
getVocalsAudioUrl: () => string
generatePreviewVideo: (data: CorrectionData, isDuet?: boolean) => Promise<{
status: string
message?: string
@@ -154,6 +157,8 @@ export default function LyricsAnalyzer({
const [reviewMode, setReviewMode] = useState(false)
const [isSubmitting, setIsSubmitting] = useState(false)
const [vocalsAudioUrl, setVocalsAudioUrl] = useState<string | null>(null)
// Success screen state (for auto-close after submission)
const [showSuccess, setShowSuccess] = useState(false)
const [countdown, setCountdown] = useState(2)
@@ -570,6 +575,12 @@ export default function LyricsAnalyzer({
}
}, [showInstrumentalReview, isLocalMode])
useEffect(() => {
if (!apiClient) return
setVocalsAudioUrl(apiClient.getVocalsAudioUrl())
}, [apiClient])
// Countdown effect for success screen (auto-close/redirect after submission)
useEffect(() => {
if (!showSuccess) return
@@ -1174,13 +1185,19 @@ export default function LyricsAnalyzer({
// Add lyrics
const handleAddLyrics = useCallback(
async (source: string, lyrics: string) => {
async (source: string, lyrics: string, force?: boolean): Promise<AddLyricsResult | void> => {
if (!apiClient) return
try {
setIsAddingLyrics(true)
const newData = await apiClient.addLyrics(source, lyrics)
updateDataWithHistory(newData, 'add lyrics')
const result = await apiClient.addLyrics(source, lyrics, force)
// The relevance filter can reject the pasted lyrics — only apply the
// returned data when the source was actually kept; the caller shows
// the rejection and can retry with force=true.
if (result.status === 'success') {
updateDataWithHistory(result.data, 'add lyrics')
}
return result
} finally {
setIsAddingLyrics(false)
}
@@ -1352,330 +1369,332 @@ export default function LyricsAnalyzer({
}
return (
<div className="max-w-full overflow-x-hidden">
<Header
isReadOnly={isReadOnly}
onFileLoad={onFileLoad}
data={data}
onMetricClick={metricClickHandlers}
effectiveMode={effectiveMode}
onModeChange={setInteractionMode}
apiClient={apiClient}
audioHash={audioHash}
onTimeUpdate={setCurrentAudioTime}
onHandlerToggle={handleHandlerToggle}
isUpdatingHandlers={isUpdatingHandlers}
onHandlerClick={handleHandlerClick}
onFindReplace={() => setIsFindReplaceModalOpen(true)}
onEditAll={handleReplaceAllLyrics}
onTimingOffset={handleOpenTimingOffsetModal}
timingOffsetMs={timingOffsetMs}
onUndo={handleUndo}
onRedo={handleRedo}
canUndo={canUndo}
canRedo={canRedo}
onResetCorrections={handleResetCorrections}
statsVisible={statsVisible}
onStatsToggle={() => setStatsVisible((v) => !v)}
reviewMode={reviewMode}
onReviewModeToggle={setReviewMode}
onAcceptAllCorrections={handleAcceptAllCorrections}
onAcceptHighConfidenceCorrections={handleAcceptHighConfidenceCorrections}
onRevertAllCorrections={handleRevertAllCorrections}
isDuet={isDuet}
onToggleDuet={() => setIsDuet(d => !d)}
onAutoCorrect={
!isLocalMode && jobId
? () =>
autoCorrect.acceptedCount > 0
? setAutoCorrectDetailsOpen((o) => !o)
: setIsAutoCorrectModalOpen(true)
: undefined
}
autoCorrectedCount={autoCorrect.acceptedCount}
/>
<AutoCorrectPanel
controller={autoCorrect}
isReadOnly={isReadOnly}
open={autoCorrectDetailsOpen}
onClose={() => setAutoCorrectDetailsOpen(false)}
onRerun={() => {
setAutoCorrectDetailsOpen(false)
setIsAutoCorrectModalOpen(true)
}}
/>
<div className={cn('grid gap-2', isMobile ? 'grid-cols-1' : 'grid-cols-2')}>
<TranscriptionView
data={displayData}
mode={effectiveMode}
onElementClick={setModalContent}
onWordClick={handleWordClick}
flashingType={flashingType}
flashingHandler={flashingHandler}
highlightInfo={highlightInfo}
onPlaySegment={handlePlaySegment}
currentTime={isAnyModalOpen ? undefined : currentAudioTime}
anchors={data.anchor_sequences}
onDataChange={(updatedData) => {
updateDataWithHistory(updatedData, 'direct data change')
}}
<VocalsAudioDataLoader audioUrl={vocalsAudioUrl}>
<div className="max-w-full overflow-x-hidden">
<Header
isReadOnly={isReadOnly}
onFileLoad={onFileLoad}
data={data}
onMetricClick={metricClickHandlers}
effectiveMode={effectiveMode}
onModeChange={setInteractionMode}
apiClient={apiClient}
audioHash={audioHash}
onTimeUpdate={setCurrentAudioTime}
onHandlerToggle={handleHandlerToggle}
isUpdatingHandlers={isUpdatingHandlers}
onHandlerClick={handleHandlerClick}
onFindReplace={() => setIsFindReplaceModalOpen(true)}
onEditAll={handleReplaceAllLyrics}
onTimingOffset={handleOpenTimingOffsetModal}
timingOffsetMs={timingOffsetMs}
onUndo={handleUndo}
onRedo={handleRedo}
canUndo={canUndo}
canRedo={canRedo}
onResetCorrections={handleResetCorrections}
statsVisible={statsVisible}
onStatsToggle={() => setStatsVisible((v) => !v)}
reviewMode={reviewMode}
onRevertCorrection={handleRevertCorrection}
onEditCorrection={handleEditCorrection}
onAcceptCorrection={handleAcceptCorrection}
onShowCorrectionDetail={handleShowCorrectionDetail}
activeGapWordIds={activeGapWordIds}
advancedMode={advancedMode}
onAdvancedModeToggle={handleAdvancedModeToggle}
editedWordIds={editedWordIds}
aiCorrectedWordIds={aiCorrectedWordIds}
aiOriginalTextByWordId={aiOriginalTextByWordId}
aiEstimatedWordIds={aiEstimatedWordIds}
onReviewModeToggle={setReviewMode}
onAcceptAllCorrections={handleAcceptAllCorrections}
onAcceptHighConfidenceCorrections={handleAcceptHighConfidenceCorrections}
onRevertAllCorrections={handleRevertAllCorrections}
isDuet={isDuet}
onSegmentSingerChange={(segmentIdx, next) => {
const segments = [...data.corrected_segments]
segments[segmentIdx] = { ...segments[segmentIdx], singer: next }
updateDataWithHistory({ ...data, corrected_segments: segments }, 'singer change')
}}
onSegmentFocus={setFocusedSegmentIndex}
onToggleDuet={() => setIsDuet(d => !d)}
onAutoCorrect={
!isLocalMode && jobId
? () =>
autoCorrect.acceptedCount > 0
? setAutoCorrectDetailsOpen((o) => !o)
: setIsAutoCorrectModalOpen(true)
: undefined
}
autoCorrectedCount={autoCorrect.acceptedCount}
/>
<ReferenceView
referenceSources={data.reference_lyrics}
anchors={data.anchor_sequences}
gaps={data.gap_sequences}
mode={effectiveMode}
onElementClick={setModalContent}
onWordClick={handleWordClick}
flashingType={flashingType}
highlightInfo={highlightInfo}
currentSource={currentSource}
onSourceChange={setCurrentSource}
corrected_segments={data.corrected_segments}
corrections={data.corrections}
onAddLyrics={() => setIsAddLyricsModalOpen(true)}
onAddLyricsInline={handleAddLyrics}
onSearchLyrics={handleSearchLyrics}
<AutoCorrectPanel
controller={autoCorrect}
isReadOnly={isReadOnly}
open={autoCorrectDetailsOpen}
onClose={() => setAutoCorrectDetailsOpen(false)}
onRerun={() => {
setAutoCorrectDetailsOpen(false)
setIsAutoCorrectModalOpen(true)
}}
/>
<div className={cn('grid gap-2', isMobile ? 'grid-cols-1' : 'grid-cols-2')}>
<TranscriptionView
data={displayData}
mode={effectiveMode}
onElementClick={setModalContent}
onWordClick={handleWordClick}
flashingType={flashingType}
flashingHandler={flashingHandler}
highlightInfo={highlightInfo}
onPlaySegment={handlePlaySegment}
currentTime={isAnyModalOpen ? undefined : currentAudioTime}
anchors={data.anchor_sequences}
onDataChange={(updatedData) => {
updateDataWithHistory(updatedData, 'direct data change')
}}
reviewMode={reviewMode}
onRevertCorrection={handleRevertCorrection}
onEditCorrection={handleEditCorrection}
onAcceptCorrection={handleAcceptCorrection}
onShowCorrectionDetail={handleShowCorrectionDetail}
activeGapWordIds={activeGapWordIds}
advancedMode={advancedMode}
onAdvancedModeToggle={handleAdvancedModeToggle}
editedWordIds={editedWordIds}
aiCorrectedWordIds={aiCorrectedWordIds}
aiOriginalTextByWordId={aiOriginalTextByWordId}
aiEstimatedWordIds={aiEstimatedWordIds}
isDuet={isDuet}
onSegmentSingerChange={(segmentIdx, next) => {
const segments = [...data.corrected_segments]
segments[segmentIdx] = { ...segments[segmentIdx], singer: next }
updateDataWithHistory({ ...data, corrected_segments: segments }, 'singer change')
}}
onSegmentFocus={setFocusedSegmentIndex}
/>
<ReferenceView
referenceSources={data.reference_lyrics}
anchors={data.anchor_sequences}
gaps={data.gap_sequences}
mode={effectiveMode}
onElementClick={setModalContent}
onWordClick={handleWordClick}
flashingType={flashingType}
highlightInfo={highlightInfo}
currentSource={currentSource}
onSourceChange={setCurrentSource}
corrected_segments={data.corrected_segments}
corrections={data.corrections}
onAddLyrics={() => setIsAddLyricsModalOpen(true)}
onAddLyricsInline={handleAddLyrics}
onSearchLyrics={handleSearchLyrics}
defaultArtist={data.metadata?.artist || ''}
defaultTitle={data.metadata?.title || ''}
/>
</div>
{/* Spacer for sticky footer */}
{!isReadOnly && apiClient && <div className="h-16" />}
{/* Sticky footer bar */}
{!isReadOnly && apiClient && (
<div className="fixed bottom-0 left-0 right-0 bg-background border-t shadow-lg py-3 px-4 z-50 flex justify-center items-center gap-4 flex-wrap">
<GapNavigator
currentGapIndex={currentGapIndex}
totalGaps={uncorrectedGaps.length}
onPrevGap={handlePrevGap}
onNextGap={handleNextGap}
/>
{data.gap_sequences.length > 0 && (
<div className="flex items-center gap-1.5">
<div className="w-16 h-1.5 bg-muted rounded-full overflow-hidden">
<div
className="h-full bg-green-500 rounded-full transition-all"
style={{
width: `${data.gap_sequences.length > 0 ? ((data.gap_sequences.length - uncorrectedGaps.length) / data.gap_sequences.length) * 100 : 0}%`,
}}
/>
</div>
{uncorrectedGaps.length === 0 ? (
<span className="text-xs text-green-500 flex items-center gap-0.5">
<CheckCircle2 className="h-3.5 w-3.5" />
All gaps reviewed
</span>
) : (
<span className="text-xs text-muted-foreground whitespace-nowrap">
{data.gap_sequences.length - uncorrectedGaps.length}/{data.gap_sequences.length} gaps reviewed
</span>
)}
</div>
)}
{apiClient?.saveReviewSession && (
<>
<Button
variant="outline"
size="sm"
onClick={() => saveSession('manual')}
disabled={history.length <= 1}
>
Save Progress
</Button>
<Button
variant="outline"
size="sm"
onClick={handleOpenSessionBrowser}
>
Session History
</Button>
</>
)}
<span className="text-sm text-muted-foreground">Lyrics look good?</span>
<Button onClick={handleFinishReview} disabled={isReviewComplete}>
{isReviewComplete ? 'Review Complete' : 'Preview Video'}
<Video className="ml-2 h-4 w-4" />
</Button>
</div>
)}
{/* Modals */}
<EditModal
open={Boolean(editModalSegment)}
onClose={() => {
setEditModalSegment(null)
handleSetModalSpacebarHandler(undefined)
}}
segment={
editModalSegment?.segment
? timingOffsetMs !== 0
? applyOffsetToSegment(editModalSegment.segment, timingOffsetMs)
: editModalSegment.segment
: null
}
segmentIndex={editModalSegment?.index ?? null}
originalSegment={
editModalSegment?.originalSegment
? timingOffsetMs !== 0
? applyOffsetToSegment(editModalSegment.originalSegment, timingOffsetMs)
: editModalSegment.originalSegment
: null
}
onSave={handleUpdateSegment}
onDelete={handleDeleteSegment}
onAddSegment={handleAddSegment}
onSplitSegment={handleSplitSegment}
onMergeSegment={handleMergeSegment}
onPlaySegment={handlePlaySegment}
currentTime={currentAudioTime}
originalTranscribedSegment={
editModalSegment?.segment &&
editModalSegment?.index !== null &&
originalData.original_segments
? (() => {
const origSegment =
originalData.original_segments.find(
(s: LyricsSegment) => s.id === editModalSegment.segment.id
) || null
return origSegment && timingOffsetMs !== 0
? applyOffsetToSegment(origSegment, timingOffsetMs)
: origSegment
})()
: null
}
/>
<ReviewChangesModal
open={isReviewModalOpen}
onClose={() => setIsReviewModalOpen(false)}
data={data}
onSubmit={handleSubmitToServer}
isSubmitting={isSubmitting}
apiClient={apiClient}
timingOffsetMs={timingOffsetMs}
isDuet={isDuet}
/>
<AddLyricsModal
open={isAddLyricsModalOpen}
onClose={() => setIsAddLyricsModalOpen(false)}
onAdd={handleAddLyrics}
onSearch={handleSearchLyrics}
defaultArtist={data.metadata?.artist || ''}
defaultTitle={data.metadata?.title || ''}
/>
</div>
{/* Spacer for sticky footer */}
{!isReadOnly && apiClient && <div className="h-16" />}
<FindReplaceModal
open={isFindReplaceModalOpen}
onClose={() => setIsFindReplaceModalOpen(false)}
onReplace={handleFindReplace}
data={data}
/>
{/* Sticky footer bar */}
{!isReadOnly && apiClient && (
<div className="fixed bottom-0 left-0 right-0 bg-background border-t shadow-lg py-3 px-4 z-50 flex justify-center items-center gap-4 flex-wrap">
<GapNavigator
currentGapIndex={currentGapIndex}
totalGaps={uncorrectedGaps.length}
onPrevGap={handlePrevGap}
onNextGap={handleNextGap}
<TimingOffsetModal
open={isTimingOffsetModalOpen}
onClose={() => setIsTimingOffsetModalOpen(false)}
currentOffset={timingOffsetMs}
onApply={handleApplyTimingOffset}
/>
<ReplaceAllLyricsModal
open={isReplaceAllLyricsModalOpen}
onClose={() => setIsReplaceAllLyricsModalOpen(false)}
onSave={handleSaveReplaceAllLyrics}
onPlaySegment={handlePlaySegment}
currentTime={currentAudioTime}
setModalSpacebarHandler={handleSetModalSpacebarHandler}
existingSegments={data.corrected_segments}
jobId={jobId ?? ''}
artist={data.metadata?.artist}
title={data.metadata?.title}
authToken={getAccessToken() ?? undefined}
/>
<AutoCorrectModal
open={isAutoCorrectModalOpen}
onClose={() => setIsAutoCorrectModalOpen(false)}
onRun={(settings) => void autoCorrect.run(settings)}
onCancelRun={autoCorrect.cancel}
status={autoCorrect.status}
error={autoCorrect.error}
hasReferences={autoCorrect.hasReferences}
/>
<EditFeedbackBar
entry={lastEditEntry}
visible={showFeedbackBar}
onFeedback={handleEditFeedback}
onDismiss={() => setShowFeedbackBar(false)}
/>
{selectedCorrection && (
<CorrectionDetailCard
open={correctionDetailOpen}
onClose={() => {
setCorrectionDetailOpen(false)
setSelectedCorrection(null)
}}
originalWord={selectedCorrection.originalWord}
correctedWord={selectedCorrection.correctedWord}
category={selectedCorrection.category}
confidence={selectedCorrection.confidence}
reason={selectedCorrection.reason}
handler={selectedCorrection.handler}
source={selectedCorrection.source}
onRevert={() => {
handleRevertCorrection(selectedCorrection.wordId)
setCorrectionDetailOpen(false)
setSelectedCorrection(null)
}}
onEdit={() => {
handleEditCorrection(selectedCorrection.wordId)
setCorrectionDetailOpen(false)
setSelectedCorrection(null)
}}
onAccept={() => {
handleAcceptCorrection(selectedCorrection.wordId)
setCorrectionDetailOpen(false)
setSelectedCorrection(null)
}}
/>
{data.gap_sequences.length > 0 && (
<div className="flex items-center gap-1.5">
<div className="w-16 h-1.5 bg-muted rounded-full overflow-hidden">
<div
className="h-full bg-green-500 rounded-full transition-all"
style={{
width: `${data.gap_sequences.length > 0 ? ((data.gap_sequences.length - uncorrectedGaps.length) / data.gap_sequences.length) * 100 : 0}%`,
}}
/>
</div>
{uncorrectedGaps.length === 0 ? (
<span className="text-xs text-green-500 flex items-center gap-0.5">
<CheckCircle2 className="h-3.5 w-3.5" />
All gaps reviewed
</span>
) : (
<span className="text-xs text-muted-foreground whitespace-nowrap">
{data.gap_sequences.length - uncorrectedGaps.length}/{data.gap_sequences.length} gaps reviewed
</span>
)}
</div>
)}
{apiClient?.saveReviewSession && (
<>
<Button
variant="outline"
size="sm"
onClick={() => saveSession('manual')}
disabled={history.length <= 1}
>
Save Progress
</Button>
<Button
variant="outline"
size="sm"
onClick={handleOpenSessionBrowser}
>
Session History
</Button>
</>
)}
<span className="text-sm text-muted-foreground">Lyrics look good?</span>
<Button onClick={handleFinishReview} disabled={isReviewComplete}>
{isReviewComplete ? 'Review Complete' : 'Preview Video'}
<Video className="ml-2 h-4 w-4" />
</Button>
</div>
)}
)}
{/* Modals */}
<EditModal
open={Boolean(editModalSegment)}
onClose={() => {
setEditModalSegment(null)
handleSetModalSpacebarHandler(undefined)
}}
segment={
editModalSegment?.segment
? timingOffsetMs !== 0
? applyOffsetToSegment(editModalSegment.segment, timingOffsetMs)
: editModalSegment.segment
: null
}
segmentIndex={editModalSegment?.index ?? null}
originalSegment={
editModalSegment?.originalSegment
? timingOffsetMs !== 0
? applyOffsetToSegment(editModalSegment.originalSegment, timingOffsetMs)
: editModalSegment.originalSegment
: null
}
onSave={handleUpdateSegment}
onDelete={handleDeleteSegment}
onAddSegment={handleAddSegment}
onSplitSegment={handleSplitSegment}
onMergeSegment={handleMergeSegment}
onPlaySegment={handlePlaySegment}
currentTime={currentAudioTime}
originalTranscribedSegment={
editModalSegment?.segment &&
editModalSegment?.index !== null &&
originalData.original_segments
? (() => {
const origSegment =
originalData.original_segments.find(
(s: LyricsSegment) => s.id === editModalSegment.segment.id
) || null
return origSegment && timingOffsetMs !== 0
? applyOffsetToSegment(origSegment, timingOffsetMs)
: origSegment
})()
: null
}
/>
<ReviewChangesModal
open={isReviewModalOpen}
onClose={() => setIsReviewModalOpen(false)}
data={data}
onSubmit={handleSubmitToServer}
isSubmitting={isSubmitting}
apiClient={apiClient}
timingOffsetMs={timingOffsetMs}
isDuet={isDuet}
/>
<AddLyricsModal
open={isAddLyricsModalOpen}
onClose={() => setIsAddLyricsModalOpen(false)}
onAdd={handleAddLyrics}
onSearch={handleSearchLyrics}
defaultArtist={data.metadata?.artist || ''}
defaultTitle={data.metadata?.title || ''}
/>
<FindReplaceModal
open={isFindReplaceModalOpen}
onClose={() => setIsFindReplaceModalOpen(false)}
onReplace={handleFindReplace}
data={data}
/>
<TimingOffsetModal
open={isTimingOffsetModalOpen}
onClose={() => setIsTimingOffsetModalOpen(false)}
currentOffset={timingOffsetMs}
onApply={handleApplyTimingOffset}
/>
<ReplaceAllLyricsModal
open={isReplaceAllLyricsModalOpen}
onClose={() => setIsReplaceAllLyricsModalOpen(false)}
onSave={handleSaveReplaceAllLyrics}
onPlaySegment={handlePlaySegment}
currentTime={currentAudioTime}
setModalSpacebarHandler={handleSetModalSpacebarHandler}
existingSegments={data.corrected_segments}
jobId={jobId ?? ''}
artist={data.metadata?.artist}
title={data.metadata?.title}
authToken={getAccessToken() ?? undefined}
/>
<AutoCorrectModal
open={isAutoCorrectModalOpen}
onClose={() => setIsAutoCorrectModalOpen(false)}
onRun={(settings) => void autoCorrect.run(settings)}
onCancelRun={autoCorrect.cancel}
status={autoCorrect.status}
error={autoCorrect.error}
hasReferences={autoCorrect.hasReferences}
/>
<EditFeedbackBar
entry={lastEditEntry}
visible={showFeedbackBar}
onFeedback={handleEditFeedback}
onDismiss={() => setShowFeedbackBar(false)}
/>
{selectedCorrection && (
<CorrectionDetailCard
open={correctionDetailOpen}
onClose={() => {
setCorrectionDetailOpen(false)
setSelectedCorrection(null)
}}
originalWord={selectedCorrection.originalWord}
correctedWord={selectedCorrection.correctedWord}
category={selectedCorrection.category}
confidence={selectedCorrection.confidence}
reason={selectedCorrection.reason}
handler={selectedCorrection.handler}
source={selectedCorrection.source}
onRevert={() => {
handleRevertCorrection(selectedCorrection.wordId)
setCorrectionDetailOpen(false)
setSelectedCorrection(null)
}}
onEdit={() => {
handleEditCorrection(selectedCorrection.wordId)
setCorrectionDetailOpen(false)
setSelectedCorrection(null)
}}
onAccept={() => {
handleAcceptCorrection(selectedCorrection.wordId)
setCorrectionDetailOpen(false)
setSelectedCorrection(null)
}}
/>
)}
{!isReadOnly && (
<SessionRestoreDialog
open={sessionRestoreOpen}
onClose={() => setSessionRestoreOpen(false)}
onRestore={handleSessionRestore}
sessions={savedSessions}
apiClient={sessionClient as LyricsReviewApiClient}
isLoading={sessionsLoading}
/>
)}
</div>
{!isReadOnly && (
<SessionRestoreDialog
open={sessionRestoreOpen}
onClose={() => setSessionRestoreOpen(false)}
onRestore={handleSessionRestore}
sessions={savedSessions}
apiClient={sessionClient as LyricsReviewApiClient}
isLoading={sessionsLoading}
/>
)}
</div>
</VocalsAudioDataLoader>
)
}
@@ -4,14 +4,14 @@ import { useTranslations } from 'next-intl'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { Info } from 'lucide-react'
import { SearchLyricsResponse } from '@/lib/lyrics-review/types'
import { AddLyricsResult, SearchLyricsResponse } from '@/lib/lyrics-review/types'
import SearchLyricsTab from './modals/SearchLyricsTab'
import PasteLyricsTab from './modals/PasteLyricsTab'
interface ReferenceEmptyStateProps {
defaultArtist: string
defaultTitle: string
onAdd: (source: string, lyrics: string) => Promise<void>
onAdd: (source: string, lyrics: string, force?: boolean) => Promise<AddLyricsResult | void>
onSearch: (artist: string, title: string, forceSources: string[]) => Promise<SearchLyricsResponse>
}
@@ -3,6 +3,8 @@
import { useRef, useState } from 'react'
import { Word } from '@/lib/lyrics-review/types'
import { cn } from '@/lib/utils'
import { WaveformVisualizer } from './WaveformVisualizer'
import { VocalsAudioDataLoaderContext } from './VocalsAudioDataLoader'
interface TimelineEditorProps {
words: Word[]
@@ -43,11 +45,25 @@ export default function TimelineEditor({
isResize: boolean
): boolean => {
if (isResize) {
if (currentIndex === words.length - 1) return false
// Compare against the nearest *timed* neighbours, not just array neighbours:
// unsynchronized words (null timestamps) aren't drawn on the timeline, so an
// adjacent null-timed word must be skipped to reach the real neighbour bar.
const nextWord = words
.slice(currentIndex + 1)
.find((word) => word.start_time !== null && word.end_time !== null)
if (nextWord && nextWord.start_time !== null && proposedEnd > nextWord.start_time) {
return true
}
const nextWord = words[currentIndex + 1]
if (!nextWord || nextWord.start_time === null) return false
return proposedEnd > nextWord.start_time
const previousWord = words
.slice(0, currentIndex)
.reverse()
.find((word) => word.start_time !== null && word.end_time !== null)
if (previousWord && previousWord.end_time !== null && proposedStart < previousWord.end_time) {
return true
}
return false
}
return words.some((word, index) => {
@@ -227,14 +243,14 @@ export default function TimelineEditor({
return (
<div
ref={containerRef}
className="relative h-[75px] bg-card rounded my-2 px-2 border border-border"
className="relative bg-card rounded border border-border"
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
onMouseLeave={handleMouseUp}
>
{/* Timeline ruler */}
<div
className="absolute top-0 left-0 right-0 h-10 border-b border-border cursor-pointer"
className="h-10 border-b border-border cursor-pointer"
onClick={handleTimelineClick}
>
{generateTimelineMarks()}
@@ -249,52 +265,65 @@ export default function TimelineEditor({
)}
{/* Word blocks */}
{words.map((word, index) => {
if (word.start_time === null || word.end_time === null) return null
<div className="relative h-[30px]">
{words.map((word, index) => {
if (word.start_time === null || word.end_time === null) return null
const leftPosition = timeToPosition(word.start_time)
const rightPosition = timeToPosition(word.end_time)
const width = rightPosition - leftPosition
const leftPosition = timeToPosition(word.start_time)
const rightPosition = timeToPosition(word.end_time)
const width = rightPosition - leftPosition
return (
<div
key={index}
className={cn(
'absolute h-[30px] top-10 bg-primary rounded text-primary-foreground px-2 py-1',
'cursor-move select-none flex items-center text-sm font-sans transition-colors',
isWordHighlighted(word) && 'bg-purple-500 dark:bg-purple-600'
)}
style={{
left: `${leftPosition}%`,
width: `${width}%`,
maxWidth: `calc(${100 - leftPosition}%)`,
}}
onMouseDown={(e) => {
e.stopPropagation()
handleMouseDown(e, index, 'move')
}}
onContextMenu={(e) => handleContextMenu(e, index)}
>
{/* Left resize handle */}
return (
<div
className="absolute top-0 left-0 w-2.5 h-full cursor-col-resize hover:bg-primary-foreground/20 rounded-l"
key={index}
className={cn(
'absolute bg-primary rounded text-primary-foreground px-2 py-1',
'cursor-move select-none flex items-center text-sm font-sans transition-colors',
isWordHighlighted(word) && 'bg-purple-500 dark:bg-purple-600'
)}
style={{
left: `${leftPosition}%`,
width: `${width}%`,
maxWidth: `calc(${100 - leftPosition}%)`,
}}
onMouseDown={(e) => {
e.stopPropagation()
handleMouseDown(e, index, 'resize-left')
handleMouseDown(e, index, 'move')
}}
/>
{word.text}
{/* Right resize handle */}
<div
className="absolute top-0 right-0 w-2.5 h-full cursor-col-resize hover:bg-primary-foreground/20 rounded-r"
onMouseDown={(e) => {
e.stopPropagation()
handleMouseDown(e, index, 'resize-right')
}}
/>
</div>
)
})}
onContextMenu={(e) => handleContextMenu(e, index)}
>
{/* Left resize handle */}
<div
className="absolute top-0 left-0 w-2.5 h-full cursor-col-resize hover:bg-primary-foreground/20 rounded-l"
onMouseDown={(e) => {
e.stopPropagation()
handleMouseDown(e, index, 'resize-left')
}}
/>
{word.text}
{/* Right resize handle */}
<div
className="absolute top-0 right-0 w-2.5 h-full cursor-col-resize hover:bg-primary-foreground/20 rounded-r"
onMouseDown={(e) => {
e.stopPropagation()
handleMouseDown(e, index, 'resize-right')
}}
/>
</div>
)
})}
</div>
<VocalsAudioDataLoaderContext.Consumer>
{({ audioData: vocalsAudioData }) => (
vocalsAudioData && <WaveformVisualizer
startTime={startTime}
endTime={endTime}
audioData={vocalsAudioData}
className="w-[100%] h-[35px]"
/>
)}
</VocalsAudioDataLoaderContext.Consumer>
</div>
)
}
@@ -0,0 +1,59 @@
import { AudioData, AudioNotReadyError, fetchAudioData } from '@/lib/audio-data'
import { createContext, PropsWithChildren, useEffect, useState } from 'react'
export const VocalsAudioDataLoaderContext = createContext<{ audioData: AudioData | null }>({ audioData: null })
export interface AudioDataLoaderProps extends PropsWithChildren {
audioUrl: string | null
}
// Audio separation runs in the background while the user reviews lyrics, so the
// vocal stem often doesn't exist yet on first page load (endpoint returns 202).
// Poll until it appears; separation takes a few minutes at most, so cap the
// polling rather than retrying forever if something upstream is wedged.
const NOT_READY_RETRY_MS = 15_000
const NOT_READY_MAX_RETRIES = 40 // 40 × 15s = 10 minutes
export const VocalsAudioDataLoader = ({ audioUrl, children }: AudioDataLoaderProps) => {
const [audioData, setAudioData] = useState<AudioData | null>(null)
useEffect(() => {
if (!audioUrl) return
// Guard against (a) an unhandled rejection when the endpoint 404s (no vocal
// stem for this job) and (b) a stale in-flight fetch resolving after a newer
// audioUrl has already been set.
let cancelled = false
let retryTimer: ReturnType<typeof setTimeout> | undefined
const load = (attempt: number) => {
fetchAudioData(audioUrl)
.then((audioData) => {
if (!cancelled) setAudioData(audioData)
})
.catch((error) => {
if (cancelled) return
if (error instanceof AudioNotReadyError && attempt < NOT_READY_MAX_RETRIES) {
retryTimer = setTimeout(() => load(attempt + 1), NOT_READY_RETRY_MS)
return
}
console.error('Failed to load vocals audio data', error)
setAudioData(null)
})
}
load(0)
return () => {
cancelled = true
if (retryTimer) clearTimeout(retryTimer)
setAudioData(null)
}
}, [audioUrl])
return (
<VocalsAudioDataLoaderContext.Provider value={{ audioData }}>
{children}
</VocalsAudioDataLoaderContext.Provider>
)
}
@@ -0,0 +1,113 @@
import { HTMLProps, useCallback, useEffect, useRef, useState } from 'react'
import colors from 'tailwindcss/colors'
import { AudioData } from '@/lib/audio-data'
import { useAudioReady } from '@/lib/lyrics-review/hooks/useAudioReady'
export interface WaveformVisualizerProps extends Omit<HTMLProps<HTMLCanvasElement>, 'width' | 'height'> {
startTime: number
endTime: number
audioData: AudioData | null
barColor?: string
}
export const WaveformVisualizer = ({
startTime,
endTime,
audioData,
className,
barColor = colors.yellow['500'],
... canvasProps
}: WaveformVisualizerProps) => {
const containerRef = useRef<HTMLDivElement | null>(null)
const canvasCtxRef = useRef<CanvasRenderingContext2D | null>(null)
const audioReady = useAudioReady()
const [canvasSize, setCanvasSize] = useState<{ width: number; height: number; }>({ width: 0, height: 0 })
useEffect(() => {
if (!containerRef.current) return
const resizeObserver = new ResizeObserver((entries) => {
const size = entries.at(-1)!.contentBoxSize[0]
setCanvasSize({
width: size.inlineSize,
height: size.blockSize
})
})
resizeObserver.observe(containerRef.current, {
box: 'content-box'
})
return () => {
resizeObserver.disconnect()
}
}, [containerRef.current])
const readAudioData = useCallback((startTime: number, endTime: number) => {
if (audioData == null) return null
// Index directly into the time-based peak envelope (peaksPerSecond buckets
// per second) so we only ever touch the window being drawn, never the whole
// track.
const startIndex = Math.max(0, Math.floor(startTime * audioData.peaksPerSecond))
const endIndex = Math.min(audioData.peaks.length, Math.ceil(endTime * audioData.peaksPerSecond))
return audioData.peaks.slice(startIndex, endIndex)
}, [audioData])
const render = useCallback((startTime: number, endTime: number) => {
const ctx = canvasCtxRef.current
if (!ctx) return
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.fillStyle = barColor
const audioData = readAudioData(startTime, endTime)
if (!audioData) return
for (let x = 0; x < ctx.canvas.width; x++) {
// Clamp the first pixel: (x - 0.5) is negative at x=0, and a negative
// slice start would sample peaks from the end of the window instead.
const dataPointIndex = Math.max(0, Math.floor((x - 0.5) / ctx.canvas.width * audioData.length))
// When fewer peaks than pixels are visible (zoomed in), adjacent columns
// floor to the same index; force at least one peak per column so the
// waveform doesn't render zero-height gaps.
const nextDataPointIndex = Math.max(
dataPointIndex + 1,
Math.floor((x + 0.5) / ctx.canvas.width * audioData.length)
)
const amplitude = audioData
.slice(dataPointIndex, nextDataPointIndex)
.reduce((maxAmplitude, point) => Math.max(maxAmplitude, Math.abs(point)), 0)
const barHeight = amplitude * ctx.canvas.height
ctx.fillRect(x, (ctx.canvas.height - barHeight) / 2, 1, barHeight)
}
}, [readAudioData, barColor])
// Re-render when the data (readAudioData is memoized on audioData), the window,
// the canvas size, or the colour changes. audioData arrives asynchronously, so
// omitting `render` here would leave the canvas blank until an unrelated prop
// changed.
useEffect(() => {
render(startTime, endTime)
}, [render, startTime, endTime, canvasSize, audioReady.ready])
return (
<div
ref={containerRef}
className={className}
>
<canvas
ref={(el) => {
canvasCtxRef.current = el?.getContext('2d') ?? null
}}
className={"w-[100%] h-[100%]"}
width={canvasSize.width}
height={canvasSize.height}
{... canvasProps}
></canvas>
</div>
)
}
@@ -0,0 +1,116 @@
import { act, render, screen } from '@testing-library/react'
import { useContext } from 'react'
import { AudioData, AudioNotReadyError, fetchAudioData as fetchAudioDataImport } from '@/lib/audio-data'
import { VocalsAudioDataLoader, VocalsAudioDataLoaderContext } from '../VocalsAudioDataLoader'
jest.mock('@/lib/audio-data', () => {
const actual = jest.requireActual('@/lib/audio-data')
return { ...actual, fetchAudioData: jest.fn() }
})
const fetchAudioData = fetchAudioDataImport as jest.Mock
const AUDIO_DATA: AudioData = {
duration: 120,
peaks: new Float32Array([0.5]),
peaksPerSecond: 400,
}
const Probe = () => {
const { audioData } = useContext(VocalsAudioDataLoaderContext)
return <div data-testid="probe">{audioData ? 'loaded' : 'empty'}</div>
}
// Flush the pending promise chain inside the loader's .then/.catch handlers.
const flushPromises = () => act(async () => {})
describe('VocalsAudioDataLoader', () => {
beforeEach(() => {
jest.clearAllMocks()
jest.useFakeTimers()
})
afterEach(() => {
jest.useRealTimers()
})
it('provides audio data when the fetch succeeds', async () => {
fetchAudioData.mockResolvedValue(AUDIO_DATA)
render(
<VocalsAudioDataLoader audioUrl="https://api/audio/vocals">
<Probe />
</VocalsAudioDataLoader>
)
await flushPromises()
expect(screen.getByTestId('probe')).toHaveTextContent('loaded')
expect(fetchAudioData).toHaveBeenCalledTimes(1)
})
it('retries while separation is in progress (202), then loads', async () => {
// Separation runs in the background during lyrics review — the stem often
// doesn't exist on first load. The loader must poll, not give up.
fetchAudioData
.mockRejectedValueOnce(new AudioNotReadyError())
.mockRejectedValueOnce(new AudioNotReadyError())
.mockResolvedValue(AUDIO_DATA)
render(
<VocalsAudioDataLoader audioUrl="https://api/audio/vocals">
<Probe />
</VocalsAudioDataLoader>
)
await flushPromises()
expect(screen.getByTestId('probe')).toHaveTextContent('empty')
await act(async () => {
jest.advanceTimersByTime(15_000)
})
expect(screen.getByTestId('probe')).toHaveTextContent('empty')
await act(async () => {
jest.advanceTimersByTime(15_000)
})
expect(fetchAudioData).toHaveBeenCalledTimes(3)
expect(screen.getByTestId('probe')).toHaveTextContent('loaded')
})
it('does not retry on a terminal error (e.g. 404: job has no vocal stem)', async () => {
fetchAudioData.mockRejectedValue(new Error('Failed to fetch vocals audio: 404'))
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {})
render(
<VocalsAudioDataLoader audioUrl="https://api/audio/vocals">
<Probe />
</VocalsAudioDataLoader>
)
await flushPromises()
await act(async () => {
jest.advanceTimersByTime(60_000)
})
expect(fetchAudioData).toHaveBeenCalledTimes(1)
expect(screen.getByTestId('probe')).toHaveTextContent('empty')
expect(consoleError).toHaveBeenCalled()
consoleError.mockRestore()
})
it('stops polling on unmount', async () => {
fetchAudioData.mockRejectedValue(new AudioNotReadyError())
const { unmount } = render(
<VocalsAudioDataLoader audioUrl="https://api/audio/vocals">
<Probe />
</VocalsAudioDataLoader>
)
await flushPromises()
unmount()
await act(async () => {
jest.advanceTimersByTime(120_000)
})
expect(fetchAudioData).toHaveBeenCalledTimes(1)
})
})
@@ -4,14 +4,14 @@ import { useTranslations } from 'next-intl'
import { useState } from 'react'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { SearchLyricsResponse } from '@/lib/lyrics-review/types'
import { AddLyricsResult, SearchLyricsResponse } from '@/lib/lyrics-review/types'
import SearchLyricsTab from './SearchLyricsTab'
import PasteLyricsTab from './PasteLyricsTab'
interface AddLyricsModalProps {
open: boolean
onClose: () => void
onAdd: (source: string, lyrics: string) => Promise<void>
onAdd: (source: string, lyrics: string, force?: boolean) => Promise<AddLyricsResult | void>
onSearch: (artist: string, title: string, forceSources: string[]) => Promise<SearchLyricsResponse>
defaultArtist: string
defaultTitle: string
@@ -5,7 +5,8 @@ import { useState, useEffect, useCallback, useRef } from 'react'
import { toast } from 'sonner'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Loader2, Play, Square, RotateCcw, Trash2, History } from 'lucide-react'
import { Loader2, Play, Square, RotateCcw, Trash2, History, XCircle } from 'lucide-react'
import { cn } from '@/lib/utils'
import { LyricsSegment, Word } from '@/lib/lyrics-review/types'
import { nanoid } from 'nanoid'
import EditWordList from '../EditWordList'
@@ -56,6 +57,7 @@ export default function EditModal({
const t = useTranslations('lyricsReview.modals.editAll')
const tActions = useTranslations('lyricsReview.editActionBar')
const tHeader = useTranslations('lyricsReview.header')
const tTimeline = useTranslations('lyricsReview.editTimeline')
const { ready: audioReady } = useAudioReady()
const [editedSegment, setEditedSegment] = useState<LyricsSegment | null>(segment)
const [timingFixCount, setTimingFixCount] = useState(0)
@@ -383,23 +385,65 @@ export default function EditModal({
return (
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && handleClose()}>
<DialogContent className="max-w-[960px] max-h-[90vh] overflow-hidden flex flex-col" onKeyDown={handleKeyDown}>
<DialogContent className="max-w-[960px] max-h-[90vh] overflow-hidden flex flex-col gap-2" onKeyDown={handleKeyDown}>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
{isGlobal ? t('title') : t('editSegment', { index: segmentIndex ?? 0 })}
{segment && segment.start_time !== null && onPlaySegment && (
{/* Left: title (with the segment's time range folded into the heading)
+ play. Right: Tap To Sync, moved up here to reclaim vertical space
above the word list. pr-10 keeps it clear of the dialog close button. */}
<div className="flex items-center justify-between gap-4 pr-10">
<DialogTitle className="flex items-center gap-2">
<span>
{isGlobal ? t('title') : t('editSegment', { index: segmentIndex ?? 0 })}
{!isGlobal &&
editedSegment &&
editedSegment.start_time !== null &&
editedSegment.end_time !== null && (
<span className="font-normal text-muted-foreground">
{' '}
({editedSegment.start_time.toFixed(2)} - {editedSegment.end_time.toFixed(2)})
</span>
)}
</span>
{segment && segment.start_time !== null && onPlaySegment && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={handlePlayToggle}
disabled={!audioReady}
title={audioReady ? undefined : tHeader('audioStillLoading')}
>
{isPlaying ? <Square className="h-4 w-4" /> : <Play className="h-4 w-4" />}
</Button>
)}
</DialogTitle>
{/* Tap To Sync toggle (relocated from EditTimelineSection) */}
{editedSegment && editedSegment.words.some((w) => w.start_time !== null) && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={handlePlayToggle}
disabled={!audioReady}
title={audioReady ? undefined : tHeader('audioStillLoading')}
variant={isManualSyncing ? 'outline' : 'default'}
onClick={startManualSync}
className={cn(
'shrink-0',
isManualSyncing
? 'border-destructive text-destructive hover:bg-destructive/10'
: 'bg-primary'
)}
>
{isPlaying ? <Square className="h-4 w-4" /> : <Play className="h-4 w-4" />}
{isManualSyncing ? (
<>
<XCircle className="h-4 w-4 mr-1" />
{tTimeline('cancelSync')}
</>
) : (
<>
<Play className="h-4 w-4 mr-1" />
{tTimeline('tapToSync')}
</>
)}
</Button>
)}
</DialogTitle>
</div>
</DialogHeader>
{isLoading ? (
@@ -410,7 +454,7 @@ export default function EditModal({
</p>
</div>
) : editedSegment ? (
<div className="flex-1 overflow-auto space-y-4">
<div className="flex flex-col flex-1 space-y-2 overflow-hidden">
{timingFixCount > 0 && (
<div
role="status"
@@ -424,41 +468,40 @@ export default function EditModal({
{/* Timeline editor with Tap To Sync */}
{editedSegment.words.some((w) => w.start_time !== null) && (
<EditTimelineSection
words={editedSegment.words}
startTime={startTime}
endTime={endTime}
originalStartTime={originalSegment?.start_time ?? null}
originalEndTime={originalSegment?.end_time ?? null}
currentStartTime={editedSegment.start_time}
currentEndTime={editedSegment.end_time}
currentTime={currentTime}
isManualSyncing={isManualSyncing}
syncWordIndex={syncWordIndex}
isSpacebarPressed={isSpacebarPressed}
onWordUpdate={handleWordChange}
onPlaySegment={onPlaySegment}
startManualSync={startManualSync}
isGlobal={isGlobal}
onTapStart={handleTapStart}
onTapEnd={handleTapEnd}
/>
<div className="flex-grow">
<EditTimelineSection
words={editedSegment.words}
startTime={startTime}
endTime={endTime}
currentTime={currentTime}
isManualSyncing={isManualSyncing}
syncWordIndex={syncWordIndex}
isSpacebarPressed={isSpacebarPressed}
onWordUpdate={handleWordChange}
onPlaySegment={onPlaySegment}
isGlobal={isGlobal}
onTapStart={handleTapStart}
onTapEnd={handleTapEnd}
/>
</div>
)}
{/* Word list */}
<EditWordList
words={editedSegment.words}
onWordUpdate={handleWordChange}
onSplitWord={handleSplitWord}
onMergeWords={handleMergeWords}
onAddWord={handleAddWord}
onRemoveWord={handleRemoveWord}
onReplaceAllWords={handleReplaceAllWords}
onSplitSegment={handleSplitSegment}
onAddSegment={handleAddSegmentAt}
onMergeSegment={handleMergeSegment}
isGlobal={isGlobal}
/>
<div className="overflow-auto px-[12px]">
{/* Word list */}
<EditWordList
words={editedSegment.words}
onWordUpdate={handleWordChange}
onSplitWord={handleSplitWord}
onMergeWords={handleMergeWords}
onAddWord={handleAddWord}
onRemoveWord={handleRemoveWord}
onReplaceAllWords={handleReplaceAllWords}
onSplitSegment={handleSplitSegment}
onAddSegment={handleAddSegmentAt}
onMergeSegment={handleMergeSegment}
isGlobal={isGlobal}
/>
</div>
</div>
) : (
<div className="flex items-center justify-center flex-1">
@@ -6,10 +6,12 @@ import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Loader2 } from 'lucide-react'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Loader2, AlertTriangle } from 'lucide-react'
import { AddLyricsResult, RejectedSource } from '@/lib/lyrics-review/types'
interface PasteLyricsTabProps {
onAdd: (source: string, lyrics: string) => Promise<void>
onAdd: (source: string, lyrics: string, force?: boolean) => Promise<AddLyricsResult | void>
onClose: () => void
disabled?: boolean
}
@@ -24,15 +26,22 @@ export default function PasteLyricsTab({
const [lyrics, setLyrics] = useState('')
const [isAdding, setIsAdding] = useState(false)
const [error, setError] = useState<string | null>(null)
const [rejection, setRejection] = useState<Partial<RejectedSource> | null>(null)
const handleAdd = async () => {
const handleAdd = async (force = false) => {
if (!source.trim() || !lyrics.trim()) return
setIsAdding(true)
setError(null)
try {
await onAdd(source.trim(), lyrics.trim())
const result = await onAdd(source.trim(), lyrics.trim(), force)
if (result && result.status === 'rejected') {
// Keep the pasted text so the user can force-add or fix it
setRejection(result.rejection ?? {})
return
}
setRejection(null)
setSource('')
setLyrics('')
onClose()
@@ -48,10 +57,16 @@ export default function PasteLyricsTab({
setSource('')
setLyrics('')
setError(null)
setRejection(null)
onClose()
}
}
const rejectionPercent =
rejection && typeof rejection.relevance === 'number'
? Math.round(rejection.relevance * 100)
: 0
return (
<div className="space-y-4">
<div className="space-y-2">
@@ -59,7 +74,10 @@ export default function PasteLyricsTab({
<Input
id="paste-source"
value={source}
onChange={(e) => setSource(e.target.value)}
onChange={(e) => {
setSource(e.target.value)
setRejection(null)
}}
placeholder={t('sourceNamePlaceholder')}
disabled={isAdding || disabled}
/>
@@ -70,7 +88,10 @@ export default function PasteLyricsTab({
<Textarea
id="paste-lyrics"
value={lyrics}
onChange={(e) => setLyrics(e.target.value)}
onChange={(e) => {
setLyrics(e.target.value)
setRejection(null)
}}
placeholder={t('lyricsPlaceholder')}
rows={10}
disabled={isAdding || disabled}
@@ -80,12 +101,37 @@ export default function PasteLyricsTab({
{error && <p className="text-sm text-destructive">{error}</p>}
{rejection && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
{t('rejectedWarning', { percent: rejectionPercent })}
</AlertDescription>
</Alert>
)}
<div className="flex justify-end gap-2 pt-2">
<Button variant="outline" onClick={handleCancel} disabled={isAdding || disabled}>
Cancel
</Button>
{rejection && (
<Button
variant="destructive"
onClick={() => handleAdd(true)}
disabled={isAdding || disabled || !source.trim() || !lyrics.trim()}
>
{isAdding ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
{t('adding')}
</>
) : (
t('addAnyway')
)}
</Button>
)}
<Button
onClick={handleAdd}
onClick={() => handleAdd()}
disabled={isAdding || disabled || !source.trim() || !lyrics.trim()}
>
{isAdding ? (
@@ -0,0 +1,91 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import PasteLyricsTab from '../PasteLyricsTab'
import type { AddLyricsResult } from '@/lib/lyrics-review/types'
describe('PasteLyricsTab', () => {
const successResult: AddLyricsResult = {
status: 'success',
data: {} as AddLyricsResult['data'],
}
const rejectedResult: AddLyricsResult = {
status: 'rejected',
rejection: { relevance: 0.013, matched_words: 3, total_words: 230 },
data: {} as AddLyricsResult['data'],
}
async function fillAndSubmit(onAdd: jest.Mock, onClose: jest.Mock) {
const user = userEvent.setup()
render(<PasteLyricsTab onAdd={onAdd} onClose={onClose} />)
await user.type(screen.getByLabelText('Source Name'), 'manual')
await user.type(screen.getByLabelText('Lyrics'), 'Some lyrics text')
await user.click(screen.getByRole('button', { name: 'Add Lyrics' }))
return user
}
it('clears fields and closes on success', async () => {
const onAdd = jest.fn().mockResolvedValue(successResult)
const onClose = jest.fn()
await fillAndSubmit(onAdd, onClose)
expect(onAdd).toHaveBeenCalledWith('manual', 'Some lyrics text', false)
expect(onClose).toHaveBeenCalled()
expect(screen.getByLabelText('Lyrics')).toHaveValue('')
})
it('keeps fields, shows warning, and offers Add Anyway when rejected', async () => {
const onAdd = jest.fn().mockResolvedValue(rejectedResult)
const onClose = jest.fn()
await fillAndSubmit(onAdd, onClose)
// Lyrics preserved, modal stays open
expect(onClose).not.toHaveBeenCalled()
expect(screen.getByLabelText('Lyrics')).toHaveValue('Some lyrics text')
// Warning mentions the match percentage (1.3% → 1%)
expect(screen.getByText(/only matched 1%/)).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Add Anyway' })).toBeInTheDocument()
})
it('retries with force=true via Add Anyway and closes on success', async () => {
const onAdd = jest
.fn()
.mockResolvedValueOnce(rejectedResult)
.mockResolvedValueOnce(successResult)
const onClose = jest.fn()
const user = await fillAndSubmit(onAdd, onClose)
await user.click(screen.getByRole('button', { name: 'Add Anyway' }))
expect(onAdd).toHaveBeenLastCalledWith('manual', 'Some lyrics text', true)
expect(onClose).toHaveBeenCalled()
})
it('clears the rejection warning when the lyrics are edited', async () => {
const onAdd = jest.fn().mockResolvedValue(rejectedResult)
const onClose = jest.fn()
const user = await fillAndSubmit(onAdd, onClose)
expect(screen.getByText(/only matched/)).toBeInTheDocument()
await user.type(screen.getByLabelText('Lyrics'), ' more words')
expect(screen.queryByText(/only matched/)).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Add Anyway' })).not.toBeInTheDocument()
})
it('handles legacy void result as success', async () => {
// Local-mode/legacy onAdd may resolve with no result — treat as success
const onAdd = jest.fn().mockResolvedValue(undefined)
const onClose = jest.fn()
await fillAndSubmit(onAdd, onClose)
expect(onClose).toHaveBeenCalled()
})
})
+40 -6
View File
@@ -59,7 +59,7 @@ function ServiceCard({
className="rounded-lg border p-4"
style={{
borderColor: "var(--card-border)",
backgroundColor: "var(--card-bg)",
backgroundColor: "var(--card)",
}}
>
<div className="flex items-center justify-between mb-1">
@@ -106,6 +106,38 @@ function ServiceCard({
);
}
function LiveWorkerSection({ details }: { details: NonNullable<ServiceStatus["admin_details"]> }) {
const t = useTranslations('status');
return (
<div className="mt-2 text-xs">
<div className="flex items-center gap-1.5 flex-wrap">
<span className="opacity-60">{t('liveWorker')}:</span>
<span className="font-mono font-medium">{details.active_machine_type}</span>
{details.on_fallback && (
<span
className="rounded px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-amber-400"
style={{ backgroundColor: "rgba(251,191,36,0.12)" }}
>
{t('fallbackBadge')}
</span>
)}
</div>
{details.active_vm && (
<div className="mt-0.5 font-mono opacity-50">
{details.active_vm}
{details.active_zone ? ` · ${details.active_zone}` : ""}
</div>
)}
{details.on_fallback && (
<div className="mt-1 opacity-50 text-[10px] leading-snug">
{t('fallbackNote')}
</div>
)}
</div>
);
}
function BlueGreenSection({ details }: { details: NonNullable<ServiceStatus["admin_details"]> }) {
const t = useTranslations('status');
const [expanded, setExpanded] = useState(false);
@@ -216,7 +248,7 @@ export function SystemStatusModal({ open, onClose }: SystemStatusModalProps) {
return (
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
<DialogContent className="sm:max-w-lg" style={{ backgroundColor: "var(--card-bg)", borderColor: "var(--card-border)" }}>
<DialogContent className="sm:max-w-lg" style={{ backgroundColor: "var(--bg)", borderColor: "var(--card-border)" }}>
<DialogHeader>
<DialogTitle className="text-foreground">{t('systemStatus')}</DialogTitle>
</DialogHeader>
@@ -234,10 +266,12 @@ export function SystemStatusModal({ open, onClose }: SystemStatusModalProps) {
<ServiceCard name={t('frontend')} service={frontendService} />
<ServiceCard name={t('backend')} service={services.backend} />
<ServiceCard name={t('encoder')} service={services.encoder}>
{services.encoder.admin_details &&
services.encoder.admin_details.primary_vm && (
<BlueGreenSection details={services.encoder.admin_details} />
)}
{services.encoder.admin_details?.active_machine_type && (
<LiveWorkerSection details={services.encoder.admin_details} />
)}
{services.encoder.admin_details?.primary_vm && (
<BlueGreenSection details={services.encoder.admin_details} />
)}
</ServiceCard>
<ServiceCard name={t('flacfetch')} service={services.flacfetch} />
<ServiceCard name={t('separator')} service={services.separator} />
+175 -81
View File
@@ -1,15 +1,28 @@
// frontend/e2e/helpers/stripe-checkout.ts
import { Page } from '@playwright/test';
import { Page, Frame, Locator } from '@playwright/test';
/**
* Automate Stripe's hosted checkout page (checkout.stripe.com).
*
* Stripe Checkout (as of April 2026) shows:
* - "Pay with Link" / "Pay with Klarna" buttons at top
* - Payment method radio buttons: Card, Cash App Pay, Klarna, Bank
* - Clicking "Card" reveals card input fields (number, expiry, CVC)
* - Card fields are inside iframes within the page
* - A "Pay" button at the bottom
* ⚠️ Stripe changes this page's structure without notice — likely A/B testing
* or staged rollouts, so BOTH the old and new layouts can appear on any given
* day (and can flip back). We have observed at least three variants:
* 1. Multi-method accordion of *radios* (Card / Cash App / Klarna / Bank),
* card fields inside iframes, Pay button in the top frame. (Apr 2026)
* 2. Single method (Card only): card fields render as *direct* textboxes in
* the top document, no chooser at all. (#916, Aug 17)
* 3. Multi-method Payment Element where the chooser is *buttons* (not radios)
* and the whole element — chooser, card fields AND the "Pay" button — is
* rendered inside a nested same-origin iframe. (Aug 19-20)
*
* DO NOT narrow this helper to a single layout — it must tolerate all of the
* above. It does so by being layout-agnostic:
* - `page.getByRole(...)` only sees the top frame, so we search EVERY frame
* (top + nested iframes) for each element via `locateVisibleInFrames`.
* - The "Card" chooser is matched as a radio OR a button.
* - Card fields are matched whether direct inputs or iframe-nested.
* If Stripe introduces yet another layout, extend the locators here rather than
* assuming a single shape.
*
* Environment variables:
* E2E_STRIPE_CARD_NUMBER, E2E_STRIPE_CARD_EXPIRY,
@@ -38,6 +51,32 @@ function getCardDetailsFromEnv(): CardDetails {
return { number, expiry, cvc, name };
}
/**
* Poll every frame (top document + nested iframes) for the first locator that
* is visible, returning it (or null on timeout). Playwright's Page-level
* locators only see the top frame; Stripe's Payment Element lives in a nested
* iframe, so we must look frame-by-frame.
*/
async function locateVisibleInFrames(
page: Page,
make: (frame: Frame) => Locator,
timeout = 30_000
): Promise<Locator | null> {
const deadline = Date.now() + timeout;
do {
for (const frame of page.frames()) {
if (frame.isDetached()) continue;
const loc = make(frame).first();
// isVisible() rejects if the frame detaches mid-check — treat as "not here".
if (await loc.isVisible({ timeout: 1_000 }).catch(() => false)) {
return loc;
}
}
await page.waitForTimeout(300);
} while (Date.now() < deadline);
return null;
}
/**
* Complete the Stripe Checkout page with card details from environment.
*
@@ -50,75 +89,128 @@ export async function completeStripeCheckout(page: Page): Promise<void> {
// Step 1: Wait for Stripe Checkout page to fully load
console.log(' Waiting for Stripe Checkout page...');
await page.waitForURL(/checkout\.stripe\.com/, { timeout: 30_000 });
// Wait for the page to be fully interactive — look for the "Pay" button
// which is one of the last elements to render
await page.getByRole('button', { name: /^Pay$/i }).waitFor({
state: 'visible',
timeout: 30_000,
});
// The "Pay" button is one of the last elements to render and confirms the
// Payment Element is interactive. It may be in the top frame (single-method
// layout) or a nested iframe (multi-method layout). Match it exactly so the
// "Pay with Link" / "Pay with Klarna" express buttons don't shadow it.
const payButton = await locateVisibleInFrames(
page,
(f) => f.getByRole('button', { name: /^Pay$/i }),
30_000
);
if (!payButton) {
await page.screenshot({ path: 'test-results/stripe-no-pay-button.png' });
throw new Error('Stripe "Pay" button not visible in any frame after 30s');
}
await page.screenshot({ path: 'test-results/stripe-checkout-loaded.png' });
console.log(' Stripe Checkout loaded');
// Step 2: Select "Card" payment method
// Stripe uses an accordion with radio buttons overlaid by buttons.
// Use force:true to bypass the overlay interception.
// Step 2: Ensure the card fields are shown. In the single-method layout they
// are already visible; in the multi-method accordion we must expand "Card"
// (rendered as a button or radio depending on Stripe's variant).
console.log(' Selecting Card payment method...');
const cardRadio = page.getByRole('radio', { name: 'Card' });
await cardRadio.check({ force: true, timeout: 10_000 });
console.log(' Card payment method selected');
let cardNumberField = await locateVisibleInFrames(
page,
(f) => cardFieldLocator(f, 'cardNumber'),
5_000
);
// Wait for card input fields to appear after selecting Card
// Stripe renders card fields inside iframes after the radio is clicked
await page.waitForTimeout(2000);
if (cardNumberField) {
console.log(' Card fields already visible — no chooser to expand');
} else {
const cardChoice = await locateVisibleInFrames(
page,
(f) =>
f
.getByRole('radio', { name: /^Card$/i })
.or(f.getByRole('button', { name: /^Card$/i })),
5_000
);
if (cardChoice) {
// force:true bypasses any overlay/accordion animation intercepting clicks.
await cardChoice.click({ force: true }).catch(() => {});
console.log(' Card payment method selected');
} else {
console.log(' No Card chooser found — waiting for card fields to render...');
}
cardNumberField = await locateVisibleInFrames(
page,
(f) => cardFieldLocator(f, 'cardNumber'),
15_000
);
if (!cardNumberField) {
console.log(' WARNING: card number field not visible after selecting Card');
}
}
await page.waitForTimeout(1000);
await page.screenshot({ path: 'test-results/stripe-card-selected.png' });
// Step 3: Fill card number
// After clicking "Card", Stripe shows card input fields.
// These may be direct inputs (#cardNumber) or inside iframes.
// Step 3-5: Fill card number, expiry, CVC
console.log(' Filling card number...');
await fillCardField(page, 'cardNumber', card.number);
// Step 4: Fill expiry
console.log(' Filling card expiry...');
await fillCardField(page, 'cardExpiry', card.expiry);
// Step 5: Fill CVC
console.log(' Filling CVC...');
await fillCardField(page, 'cardCvc', card.cvc);
// Step 6: Fill cardholder name if field exists
// Step 6: Fill cardholder name if the field exists (any frame)
if (card.name) {
const nameInput = page.locator('#billingName, input[name="billingName"]');
if (await nameInput.isVisible({ timeout: 2000 }).catch(() => false)) {
const nameInput = await locateVisibleInFrames(
page,
(f) =>
f
.locator('#billingName, input[name="billingName"], input[placeholder="Full name on card"]')
.or(f.getByRole('textbox', { name: /cardholder name/i })),
2_000
);
if (nameInput) {
console.log(' Filling cardholder name...');
await nameInput.fill(card.name);
}
}
// Step 6b: Fill ZIP code (required for US cards)
const zipInput = page.locator('#billingPostalCode, input[name="billingPostalCode"], input[placeholder="ZIP"]');
if (await zipInput.isVisible({ timeout: 2000 }).catch(() => false)) {
// Step 6b: Fill ZIP code (required for US cards) — search any frame
const zipInput = await locateVisibleInFrames(
page,
(f) =>
f
.locator('#billingPostalCode, input[name="billingPostalCode"], input[placeholder="ZIP"]')
.or(f.getByRole('textbox', { name: /^zip$|postal code/i })),
2_000
);
if (zipInput) {
console.log(' Filling ZIP code...');
await zipInput.fill(process.env.E2E_STRIPE_ZIP || '10001');
}
// Step 6c: Uncheck "Save my information" to avoid phone number requirement
const saveCheckbox = page.getByRole('checkbox', { name: /save my information/i });
if (await saveCheckbox.isVisible({ timeout: 2000 }).catch(() => false)) {
if (await saveCheckbox.isChecked()) {
console.log(' Unchecking "Save my information"...');
await saveCheckbox.uncheck({ force: true });
}
// Step 6c: Uncheck "Save my information" to avoid a phone-number requirement
const saveCheckbox = await locateVisibleInFrames(
page,
(f) => f.getByRole('checkbox', { name: /save my information/i }),
2_000
);
if (saveCheckbox && (await saveCheckbox.isChecked().catch(() => false))) {
console.log(' Unchecking "Save my information"...');
await saveCheckbox.uncheck({ force: true }).catch(() => {});
}
await page.screenshot({ path: 'test-results/stripe-checkout-filled.png' });
console.log(' Card details filled');
// Step 7: Click "Pay" button
// Step 7: Click "Pay" button (re-locate in case the frame re-rendered)
console.log(' Clicking Pay button...');
const payButton = page.getByRole('button', { name: /^Pay$/i });
await payButton.waitFor({ state: 'visible', timeout: 10_000 });
await payButton.click();
const finalPay = await locateVisibleInFrames(
page,
(f) => f.getByRole('button', { name: /^Pay$/i }),
10_000
);
if (!finalPay) {
await page.screenshot({ path: 'test-results/stripe-no-pay-button-final.png' });
throw new Error('Stripe "Pay" button not visible when ready to submit');
}
await finalPay.click();
console.log(' Payment submitted, waiting for redirect...');
// Wait for redirect back to our site
@@ -130,42 +222,44 @@ export async function completeStripeCheckout(page: Page): Promise<void> {
}
/**
* Fill a card field by name. Tries direct input first, then iframe-based.
*
* Stripe Checkout card fields use IDs like #cardNumber, #cardExpiry, #cardCvc
* when rendered as direct inputs, or are inside iframes when using Elements.
* Accessible-name and placeholder metadata for each Stripe card field, used to
* build robust locators that work whether Stripe renders the field as a direct
* input (single-payment-method layout) or inside an iframe.
*/
const CARD_FIELD_META: Record<string, { name: RegExp; placeholder?: string }> = {
cardNumber: { name: /card number/i, placeholder: '1234 1234 1234 1234' },
cardExpiry: { name: /expiration|expiry/i, placeholder: 'MM / YY' },
cardCvc: { name: /^cvc$|security code/i },
};
/**
* Locator for a Stripe card field within a given frame. Matches by Stripe's
* stable field-name attribute, element id, input name, placeholder, or
* accessible name — whichever the current Checkout layout uses.
*/
function cardFieldLocator(frame: Frame, fieldName: string): Locator {
const meta = CARD_FIELD_META[fieldName];
const selectors = [
`[data-elements-stable-field-name="${fieldName}"]`,
`#${fieldName}`,
`input[name="${fieldName}"]`,
];
if (meta?.placeholder) selectors.push(`input[placeholder="${meta.placeholder}"]`);
let loc = frame.locator(selectors.join(', '));
if (meta) loc = loc.or(frame.getByRole('textbox', { name: meta.name }));
return loc.first();
}
/**
* Fill a card field by name, searching every frame (top document + nested
* iframes). Stripe renders card fields either as direct inputs (single-payment-
* method layout) or inside the Payment Element iframe (multi-method layout).
*/
async function fillCardField(page: Page, fieldName: string, value: string): Promise<void> {
// Try 1: Direct input by ID
const directInput = page.locator(`#${fieldName}`);
if (await directInput.isVisible({ timeout: 3000 }).catch(() => false)) {
await directInput.click();
await directInput.type(value, { delay: 50 });
return;
const input = await locateVisibleInFrames(page, (f) => cardFieldLocator(f, fieldName), 15_000);
if (!input) {
throw new Error(`Could not find card field: ${fieldName} in any frame`);
}
// Try 2: Direct input by data attribute
const dataInput = page.locator(`[data-elements-stable-field-name="${fieldName}"]`);
if (await dataInput.isVisible({ timeout: 2000 }).catch(() => false)) {
await dataInput.click();
await dataInput.type(value, { delay: 50 });
return;
}
// Try 3: Input inside an iframe (Stripe Elements)
// Find all iframes and try each one for the card input
const iframes = page.locator('iframe');
const iframeCount = await iframes.count();
for (let i = 0; i < iframeCount; i++) {
const frame = iframes.nth(i).contentFrame();
// Look for inputs inside this iframe
const input = frame.locator(`input[name="${fieldName}"], input[autocomplete*="cc"]`).first();
if (await input.isVisible({ timeout: 1000 }).catch(() => false)) {
await input.type(value, { delay: 50 });
console.log(` Found ${fieldName} in iframe ${i}`);
return;
}
}
throw new Error(`Could not find card field: ${fieldName} (tried direct input, data attribute, and ${iframeCount} iframes)`);
await input.click();
await input.type(value, { delay: 50 });
}
@@ -217,24 +217,22 @@ test.describe(`Tenant Portal Happy Path — ${TENANT_ID}`, () => {
return r.json();
};
// For a pre-supplied (tenant) instrumental there is nothing to pick, so
// "Proceed to Instrumental Review" completes the review directly and the
// instrumental route redirects to /app. For a selectable instrumental an
// InstrumentalSelector (#submit-btn) renders instead. Handle both.
// Core tenant invariant: the operator ALWAYS uploads their own instrumental, so
// there is no audio separation and therefore NO instrumental-selection step —
// "Proceed to Instrumental Review" must complete the review directly (redirect to
// /app). If the InstrumentalSelector (#submit-btn) ever renders, the tenant flow
// has regressed (separation ran / the operator is being asked to pick a stem),
// which is exactly the real-world scenario this test exists to protect.
const submitBtn = page.locator('#submit-btn');
let hasInstrumentalStep = false;
try {
// waitFor actually blocks up to the timeout (isVisible would not); if the
// selector never appears the review already completed on "Proceed".
await submitBtn.waitFor({ state: 'visible', timeout: 15_000 });
hasInstrumentalStep = true;
} catch { /* pre-supplied tenant instrumental: review completed directly */ }
if (hasInstrumentalStep) {
const opt = page.locator('.selection-option').first();
if (await opt.isVisible().catch(() => false)) await opt.click();
await submitBtn.click();
console.log(`[${TENANT_ID}] Instrumental confirmed`);
}
const instrumentalStepAppeared = await submitBtn
.waitFor({ state: 'visible', timeout: 15_000 })
.then(() => true)
.catch(() => false);
expect(
instrumentalStepAppeared,
'tenant with a pre-supplied instrumental must NOT be shown an instrumental-selection step (no audio separation)',
).toBe(false);
console.log(`[${TENANT_ID}] No instrumental-selection step (as expected for pre-supplied instrumental)`);
// Confirm the review actually advanced (left awaiting_review) before waiting
// on the render — otherwise a silent no-op would masquerade as a render hang.
@@ -275,6 +273,14 @@ test.describe(`Tenant Portal Happy Path — ${TENANT_ID}`, () => {
for (const f of ['lossy_4k_mp4', 'lossy_720p_mp4', 'with_vocals_mp4']) expect(finals).toContain(f);
for (const p of ['cdg_zip', 'txt_zip']) expect(packages).toContain(p);
expect(job.is_private, 'tenant job is private').toBeTruthy();
console.log(`[${TENANT_ID}] PASSED — complete, Dropbox present, no YouTube, downloads available`);
// Real-world tenant-scenario invariants (beyond "it completed"): these guard the
// exact flow tenant operators rely on — they upload their own audio + instrumental,
// so audio search / separation / instrumental review must all be bypassed.
// 1. The operator's uploaded instrumental is what's used, not a separated stem.
expect(sd.instrumental_selection, 'uploaded instrumental used (custom), not a separated stem').toBe('custom');
// 2. Lyrics were transcribed + corrected — the job did real work, not a short-circuit.
expect(sd.lyrics_complete, 'lyrics transcription completed').toBeTruthy();
console.log(`[${TENANT_ID}] PASSED — complete, private, Dropbox present, no YouTube, uploaded instrumental used, downloads available`);
});
});
@@ -490,10 +490,11 @@ test.describe('Admin Job Detail Page', () => {
await expect(sourceButton).toBeVisible();
// Click to open modal, which should contain the clickable YouTube link
// (both the "Open in ..." banner and the raw URL row link to YouTube)
await sourceButton.click();
const modal = page.getByLabel('Audio Source Details');
await expect(modal).toBeVisible();
const sourceLink = modal.locator('a[href*="youtube.com"]');
const sourceLink = modal.locator('a[href*="youtube.com"]').first();
await expect(sourceLink).toBeVisible();
await expect(sourceLink).toHaveAttribute('target', '_blank');
});
@@ -820,4 +821,123 @@ test.describe('Admin Job Detail Page', () => {
await expect(modal.getByText('file upload')).toBeVisible();
await expect(modal.getByText('my-song.mp3')).toBeVisible();
});
test('long timeline collapses to recent stages with expander', async ({ page }) => {
const longTimelineJob = {
...mockJob,
status: 'awaiting_review',
timeline: [
{ status: 'pending', timestamp: '2026-01-09T10:00:00Z', progress: 0 },
{ status: 'downloading', timestamp: '2026-01-09T10:01:00Z', progress: 10 },
{ status: 'failed', timestamp: '2026-01-09T10:02:00Z', progress: 10 },
{ status: 'downloading', timestamp: '2026-01-09T10:03:00Z', progress: 10 },
{ status: 'failed', timestamp: '2026-01-09T10:04:00Z', progress: 10 },
{ status: 'downloading', timestamp: '2026-01-09T10:05:00Z', progress: 12 },
{ status: 'separating_stage1', timestamp: '2026-01-09T10:06:00Z', progress: 30 },
{ status: 'separating_stage2', timestamp: '2026-01-09T10:10:00Z', progress: 45 },
{ status: 'transcribing', timestamp: '2026-01-09T10:15:00Z', progress: 50 },
{ status: 'correcting', timestamp: '2026-01-09T10:20:00Z', progress: 52 },
{ status: 'awaiting_review', timestamp: '2026-01-09T10:25:00Z', progress: 55 },
],
};
await setupApiFixtures(page, {
mocks: [
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: longTimelineJob } },
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
],
});
await page.goto('/admin/jobs?id=test-job-123');
await page.waitForLoadState('networkidle');
// 11 stages > threshold: collapsed chip shows hidden count and failure count
const expander = page.locator('button[title="Show all timeline entries"]');
await expect(expander).toBeVisible();
await expect(expander).toContainText('+5 earlier');
await expect(expander).toContainText('(2 failed)');
// Early stages hidden, recent stages visible
await expect(page.getByText('Pending', { exact: true })).toHaveCount(0);
await expect(page.getByText('Transcribing', { exact: true })).toBeVisible();
// Expand shows everything and offers Collapse
await expander.click();
await expect(page.getByText('Pending', { exact: true })).toBeVisible();
const collapse = page.locator('button[title="Collapse older timeline entries"]');
await expect(collapse).toBeVisible();
await collapse.click();
await expect(page.getByText('Pending', { exact: true })).toHaveCount(0);
});
test('short timeline is not collapsed', async ({ page }) => {
await setupApiFixtures(page, {
mocks: [
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: mockJob } },
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
],
});
await page.goto('/admin/jobs?id=test-job-123');
await page.waitForLoadState('networkidle');
await expect(page.locator('button[title="Show all timeline entries"]')).toHaveCount(0);
await expect(page.getByText('Pending', { exact: true })).toBeVisible();
});
test('source modal builds provider link from source ID for search jobs', async ({ page }) => {
const youtubeSearchJob = {
...mockJob,
url: undefined,
audio_source_type: 'audio_search',
source_name: 'YouTube',
source_id: 'dQw4w9WgXcQ',
filename: 'some-file.webm',
};
await setupApiFixtures(page, {
mocks: [
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: youtubeSearchJob } },
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
],
});
await page.goto('/admin/jobs?id=test-job-123');
await page.waitForLoadState('networkidle');
await page.locator('button[title="Click for source details"]').click();
const modal = page.getByLabel('Audio Source Details');
await expect(modal).toBeVisible();
// "Open in YouTube" link built from provider + source ID
const openLink = modal.locator('a[href="https://www.youtube.com/watch?v=dQw4w9WgXcQ"]');
await expect(openLink).toBeVisible();
await expect(openLink).toContainText('Open in YouTube');
await expect(openLink).toHaveAttribute('target', '_blank');
});
test('jobs list search jumps to detail page when given a job ID', async ({ page }) => {
await setupApiFixtures(page, {
mocks: [
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
{ method: 'GET', path: '/api/jobs', response: { body: mockJobsList } },
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: mockJob } },
{ method: 'GET', path: '/api/jobs/abc12345', response: { status: 404, body: { detail: 'Job not found' } } },
{ method: 'GET', path: '/api/jobs/abc12345/logs', response: { body: { logs: [] } } },
],
});
await page.goto('/admin/jobs');
await page.waitForLoadState('networkidle');
await page.getByPlaceholder('Filter by email, or paste a job ID...').fill('abc12345');
await page.keyboard.press('Enter');
await expect(page).toHaveURL(/\/admin\/jobs\/?\?id=abc12345/);
});
});
+75 -5
View File
@@ -2,7 +2,7 @@
* Tests for API client
*/
import { api, ApiError, extractErrorMessage } from "../api"
import { api, ApiError, BackendUnavailableError, extractErrorMessage } from "../api"
// Mock fetch globally
global.fetch = jest.fn()
@@ -293,6 +293,48 @@ describe("API Client", () => {
const body = JSON.parse(call[1].body)
expect(body.uploaded_files).toEqual(["audio"])
})
it("retries on a transient network failure and then succeeds", async () => {
const mockResponse = { status: "success", message: "Processing started" }
;(global.fetch as jest.Mock)
.mockRejectedValueOnce(new TypeError("Failed to fetch"))
.mockResolvedValueOnce({ ok: true, json: async () => mockResponse })
const result = await api.completeJobUpload("job-789", ["audio"])
expect(result).toEqual(mockResponse)
expect(global.fetch).toHaveBeenCalledTimes(2)
})
it("gives up after 3 network failures with BackendUnavailableError (preserving the cause)", async () => {
const networkError = new TypeError("Failed to fetch")
;(global.fetch as jest.Mock).mockRejectedValue(networkError)
// apiFetch maps a network-level failure to a typed BackendUnavailableError
// (which drives the app-wide connectivity banner) while keeping the original
// error as `.cause`, so nothing is silently swallowed.
const err = await api
.completeJobUpload("job-789", ["audio"])
.catch((e) => e)
expect(err).toBeInstanceOf(BackendUnavailableError)
expect(err.cause).toBe(networkError)
expect(global.fetch).toHaveBeenCalledTimes(3)
})
it("does NOT retry on an HTTP error response (deterministic)", async () => {
;(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: false,
status: 400,
json: async () => ({ detail: "Job is not in pending state" }),
})
await expect(api.completeJobUpload("job-789", ["audio"])).rejects.toBeInstanceOf(
ApiError
)
// A 4xx is not a transient failure — it must not be retried.
expect(global.fetch).toHaveBeenCalledTimes(1)
})
})
describe("uploadJobSmart", () => {
@@ -634,13 +676,41 @@ describe("createLyricsReviewApiClient", () => {
})
)
// Verify request body
// Verify request body (force is sent as a string — the endpoint body is Dict[str, str])
const call = (global.fetch as jest.Mock).mock.calls[0]
const body = JSON.parse(call[1].body)
expect(body).toEqual({ source: "genius", lyrics: "Some lyrics text" })
expect(body).toEqual({ source: "genius", lyrics: "Some lyrics text", force: "false" })
// Verify the client extracts the data field from the response
expect(result).toEqual(mockCorrectionData)
// Verify the client returns the full result envelope
expect(result).toEqual({ status: "success", data: mockCorrectionData })
})
it("should send force='true' when force-adding", async () => {
;(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => ({ status: "success", data: {} }),
})
const client = createLyricsReviewApiClient("job123")
await client.addLyrics("manual", "Some lyrics text", true)
const call = (global.fetch as jest.Mock).mock.calls[0]
const body = JSON.parse(call[1].body)
expect(body).toEqual({ source: "manual", lyrics: "Some lyrics text", force: "true" })
})
it("should surface rejected status and rejection details", async () => {
const rejection = { relevance: 0.013, matched_words: 3, total_words: 230 }
;(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => ({ status: "rejected", rejection, data: { reference_lyrics: {} } }),
})
const client = createLyricsReviewApiClient("job123")
const result = await client.addLyrics("manual", "Wrong song lyrics")
expect(result.status).toBe("rejected")
expect(result.rejection).toEqual(rejection)
})
})
Loaded 100 of 3740 files, more files were not shown because too many files have changed in this diff. Show more