Commit Graph
465 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.8 36b331f3d7 feat(requests-board): admin history view + fix community publish transition (#1008)
## Why

Andrew asked whether we can see past community-requests-board
submissions and whether our first real user got a video. Investigation
surfaced:

- **First real user was fully served.** `tas041964@gmail.com` requested
*Sam Cooke and the Soul Stirrers – Wonderful* (Sep 15); it was
auto-picked, generated, published to YouTube (NOMAD-1650), and he got
the completion email + emailed thanks. ✅
- **No admin view existed** to see this — you had to query Firestore
directly.
- **A real bug:** the community publish fan-out (`mark_published` +
voter emails) fired **only** on the `youtube_upload_queue` path. Jobs
published via the direct video-worker distribution path (like Sam
Cooke's) bypassed it, so the request stayed `in_progress`, never lit up
the board's public "Recently made" list, and other up-voters would
silently miss their "track is live" email.

## What

1. **Fix the publish transition** — extract the fan-out into
`backend/services/community_publish.py` and call it from **both**
publish paths (`youtube_queue_processor` + `video_worker`). Also fixes a
latent `len(int)` crash in the log line.
2. **Backfill / safety net** — `POST
/api/internal/community-requests/reconcile`: idempotent, publishes any
`in_progress` pick whose job is already live on YouTube. (Will be run in
prod post-deploy to fix the Sam Cooke request.)
3. **Admin history view** — `GET /api/admin/community-requests` + a
`/admin/community-requests` page: every request, all statuses, with
requester, votes, and job + YouTube links.

The public board's "Recently made" section already existed in the UI —
it was empty only because of bug #1; fixing the transition (+ reconcile
backfill) lights it up.

## Testing

- `backend/tests/test_community_voter_notify.py` — fan-out from the
shared module, both-path idempotency, voter dedupe/retry, YouTube-url
resolution, and the reconcile scan.
- `backend/tests/test_community_review_admin.py` — the new admin history
endpoint maps all statuses.
- All 31 requests-board + 158 worker tests pass. The one unrelated
failure in `test_audio_processor_local_gpu.py` is pre-existing
(confirmed with changes stashed).

## Notes

- Admin surface is English-only (no i18n changes); no `en.json` strings
added.
- Local CodeRabbit review couldn't run (CLI requires life360-org SSO; no
seat on this repo) — leaving to the GitHub bot.

Plan:
`docs/archive/2026-09-17-requests-board-history-and-publish-transition-plan.md`

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

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

- **New Features**
- Added an admin Community Requests history page covering all statuses,
votes, submitters, review details, linked jobs, and YouTube videos.
  - Added admin reconciliation for eligible requests with live videos.
- Added automatic voter email notifications after community-request
publication.

- **Bug Fixes**
- Improved publication handling across direct and queued video
workflows.
- Added recovery for incomplete voter notifications and missed
publication transitions.

- **Documentation**
- Documented the community-request history and reconciliation API
endpoints.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-17 01:07:40 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 083a478aba fix(e2e+email): Stripe redirect not source-of-truth + benign Postmark suppressions (#1009)
## Summary

Fixes the two remaining open threads from the 2026-09-15
E2E/overnight-error triage — both diagnosed as **benign false alarms**,
now hardened so they stop paging.

### 1. Stripe Stage-1 "Credit Purchase" E2E flake (daily #173)
**Root cause:** the test failed when the browser redirect back from
Stripe timed out (`stripe-checkout.ts` `waitForURL` 60s), even though
the charge completed and credits were granted server-side. Prod logs
confirmed the Stripe `checkout.session.completed` webhook fired on the
"failed" runs too, and the next scheduled daily passed identically — a
browser-redirect flake, **not** a credit-delivery outage.

**Fix:** make the **server-side credit grant** the authoritative
pass/fail gate.
- `completeStripeCheckout()` now returns `{ redirected }` instead of
throwing on the redirect wait.
- The spec polls the read-only admin detail endpoint (`GET
/api/users/admin/users/{email}/detail`) for a credit increase above a
pre-purchase baseline — that's the real gate. The browser redirect +
success-page assertions become best-effort UX checks.

### 2. Postmark 422 "Failed to send magic link" ERROR alerts
**Root cause:** junk/placeholder addresses (e.g. `whatever@example.com`)
typed into the sign-in form that Postmark has suppressed (hard bounce /
spam / manual) → `ErrorCode 406 (InactiveRecipient)` → logged at ERROR →
paged. Not the E2E suite (uses testmail.app) and not outreach.

**Fix:** detect `ErrorCode 406`, log it at **INFO** (not ERROR), and
surface a `suppressed` flag (`SendResult.suppressed` →
`provider.last_suppressed` → `EmailService.last_send_suppressed`) so the
magic-link + resend handlers log suppressed recipients at INFO instead
of paging.

## Testing
- 4 new `test_email_service.py` unit tests: suppressed flagging + no
ERROR log, non-406 422 still errors, reset-on-success, end-to-end
`last_send_suppressed` wiring.
- All 47 `test_email_service` + 31 resend/tenant tests pass. Frontend
`tsc` clean on both changed files.
- The E2E robustness change is exercised by the next E2E Daily (Payment
+ Happy Path) run post-deploy.

## Notes
- Local CodeRabbit CLI review was blocked by a workspace-SSO/org
mismatch (CLI is authed to a different org), so this PR is left open for
the GitHub CodeRabbit bot to review.

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

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-17 00:52:22 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 727329d458 fix(e2e): seed test-token via addInitScript — fix canary execution-context race (#1006)
## Problem
Regression from #1003. That PR changed `gotoWithRetry`'s default
`networkidle`→`domcontentloaded` (to fix the #170 goto-timeout), so
`page.goto` now returns before the `/app` SPA settles. The **test-token
auth path** then did:
```ts
await gotoWithRetry(page, `${PROD_URL}/app`);
await page.evaluate((token) => localStorage.setItem('karaoke_access_token', token), accessToken);
```
The `page.evaluate` raced the `/app` client-side redirect → **`Execution
context was destroyed, most likely because of a navigation`**.

This path is used by the **post-deploy canary** (the daily E2E uses
magic-link, which is why the *daily* passed but *every deploy's canary*
failed on v0.225.5+, e.g. run #3410 on v0.225.7).

## Fix
Seed the token with `page.addInitScript` **before** navigating —
`addInitScript` runs before page scripts on every navigation, so the app
is authenticated on first load with no post-navigation `evaluate`. Drops
the racy `evaluate` + `reload` + `networkidle` wait.

Audited the other `gotoWithRetry` sites: the `PROD_URL` goto is followed
by auto-waiting `expect()` asserts; the review-page gotos settle via
`expect().toBeVisible()` / `waitForTimeout` before their `scrollTo`
evaluates — the token path was the only actual race.

## Testing
- Spec typechecks clean.
- Verified by the **post-deploy canary** on this version's deploy (it
runs the token path) — should go green where v0.225.5–.7 failed.

Root-cause detail + triage of the other overnight alerts (Stripe Stage-1
flake, admin `reset-worker-state` 500, Postmark suppressed-recipient) is
in `docs/archive/2026-09-15-e2e-flakiness-error-triage-handoff.md`.

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

## Summary by CodeRabbit

- **Bug Fixes**
- Improved the pre-configured-token sign-in flow to load more reliably
and avoid navigation timing issues in end-to-end testing.

- **Chores**
  - Incremented the project version to 0.225.8.

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-15 18:28:30 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 38350053f6 fix(e2e,review): deterministic review-submit + durable render dispatch (#1003)
## Problem
Mode B of the E2E job-orchestration stalls (plan:
`docs/archive/2026-09-15-e2e-job-orchestration-stalls-plan.md`).
Investigation this session found every `in_review`-stuck job was an
**E2E test job**, and `POST /api/review/{id}/complete` was **never
called** for them (real jobs complete fine — 200s). So the job correctly
waits at `in_review`; the **test's review-completion step is flaky**. It
failed silently: Step 8 clicked submit + `waitForTimeout`, never
verifying the transition — so a dropped click / swallowed
`completeReview` surfaced ~40 min later as a misleading "Timeout waiting
for job completion".

## E2E — fix the flakiness at its source
- **`assertReviewSubmitted()`** polls `/api/jobs/{id}` (as the job
owner, admin-token fallback) and asserts the job left
`awaiting_review`/`in_review` after a submit — fails **loud at the
submit step** with an actionable message instead of a misleading
completion timeout.
- **Step 8** now verifies the instrumental submit landed and **retries
the submit once** before failing; **Step 7 "Complete Track"** confirms
the transition too.
- **`gotoWithRetry` now defaults to `domcontentloaded`** instead of
`networkidle` — this long-polling SPA never reaches network-idle, which
timed out `page.goto` at 60s (the real run #170 retry failure).

## Backend — durability (W1c)
- `complete_review` now **awaits** the render-worker dispatch instead of
a fire-and-forget `asyncio.create_task` (which can be dropped if the
Cloud Run instance is recycled right after the 200, stranding the job at
`review_complete`). A dispatch failure does **not** fail the user's
approval — `recover-stuck-jobs` re-triggers `review_complete` jobs with
no render within ~5 min.

## Testing
- Backend review suite green (298 passed; 2 failures are pre-existing
emulator-dependent `song_request_service` tests, unrelated).
- `happy-path-real-user.spec.ts` typechecks clean (the pre-existing
`next-intl`/`stripe-webhook-security` tsc errors are unrelated).
- The hardened E2E is self-verifying by design — the next scheduled run
exercises it end-to-end in prod.

## Notes / deferred
- Complements PR #1002 (Mode A — durable prep→screens handoff, the
backend root cause). Independent files.
- **Deferred (follow-up):** a speculative frontend change to
`LyricsAnalyzer`/`InstrumentalSelector` error handling — the current
fallback (route to the instrumental screen on error) is reasonable, and
the hardened test will now pinpoint the exact client-side failure if it
recurs, enabling a targeted fix rather than a guess. Also deferred:
broadening the stale-review watchdog to non-cancel alerting for
tenant/test jobs (needs a product call on auto-cancel vs alert).

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-15 01:41:23 -04:00
Andrew Beveridge ☄️andClaude Fable 5 65285f7386 test(e2e): happy-path accepts all review CTA variants (root cause of the Stage-2 flake) (#992)
## Summary

Root-causes and fixes the daily Stage-2 / post-deploy-canary happy-path
"flake" (handoff: `docs/archive/2026-09-12-e2e-reliability-handoff.md`
§3).

**The flake was not a review data-load problem.** Artifacts from failed
run 34729291204 show the review page fully loaded (lyrics visible,
preview video rendered) — the Playwright error was `waiting for
getByRole('button', { name: /proceed to instrumental/i })`: the button
was **absent**, not disabled. The finish modal's CTA is nondeterministic
per job (`ReviewChangesModal` `completesReview`, driven by the
auto-scorer's backing verdict + stem availability, both of which vary
with each fresh transcription/separation):

- scorer **not** confident → **"Proceed to Instrumental Review"**
(two-screen flow) → test passed (e.g. the 22:15 UTC canary)
- backing confident and/or both stems ready → **"Complete Track"**
(inline instrumental chooser; completes the whole review;
`/instrumental` screen never appears) → test timed out (all of last
night's failures, same signature both retry attempts)

Both are correct product flows — this is a test-side fix, as steered by
the handoff's product-vs-test guidance (real users are not affected; the
review loads fine).

## Changes (spec-only, `happy-path-real-user.spec.ts`)

- **Step 7 finish CTA**: accept `Proceed to Instrumental Review` **or**
`Complete Track`. On Complete Track, wait for the success redirect to
`/app` and skip Step 8; also detect the product's `completeReview`
failure fallback (hash → `#/{id}/instrumental`) and fall through to Step
8 instead of timing out.
- **C1 mirror skip**: lyrics-confident jobs hash-redirect straight to
`#/{id}/instrumental` with no lyrics screen — detect via the hash and
jump to Step 8.
- **Real auto-waits**: the surface/readiness gates now use
`locator.waitFor()` / `expect().toBeEnabled()` — `isVisible({timeout})`
/ `isEnabled({timeout})` are instant snapshots (the timeout option is
deprecated/ignored) and gambled the run on render timing.
- **Fixed the always-firing "Review page content not found,
reloading..."**: the `.or()` union matched many elements → strict-mode
violation threw instantly on every run (including passing ones); scoped
with `.first()`.
- **Step 8 redirect check anchored on pathname**: bare `/\/app/` matched
the current `/app/jobs` URL and resolved instantly.

No version bump (test-only, matching #989/#990 precedent).

## Testing

- `eslint` clean; `playwright --list` parses the spec under the
production config.
- Local code review (8-angle finder + verify pass): 5 correctness
findings found and fixed (see commit 2); cycle-2 verification clean.
- Real validation is the next daily E2E runs (~$0.50 each): last night's
runs show the scorer currently hitting the "Complete Track" branch
consistently, so the new branch gets exercised immediately after merge.
Tenant E2E already re-verified green (run 34730560382).

## Success criteria (handoff §5)

This PR addresses criterion 1 (root cause + fix + written explanation).
Criteria 2–4 (≥3 consecutive green dailies, green canary on next version
bump, tenant green) verified post-merge.

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

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

## Summary by CodeRabbit

* **Tests**
* Improved end-to-end coverage for lyric review flows with varying
automated verification outcomes.
* Added validation for both direct completion and instrumental-review
paths.
* Improved navigation checks and review-page readiness handling to
reduce test failures caused by timing or redirect differences.
* Updated test guidance and comments to reflect the supported review
scenarios.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-13 02:12:08 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 0895b142f6 test(e2e): allow one retry on happy-path (stop paging on review-page flake) (#990)
When verifying the payment fix end-to-end, Stage 1 (Credit Purchase)
**passed** (~$0.50 on the Nomad debit card ✅) but Stage 2 (Happy Path)
failed on the intermittent review-page flake:
```
WARNING: Review page content not found, reloading...
WARNING: No video element found, but continuing anyway
WARNING: Proceed button not ready after preview — recovering...
✘ expect(getByRole('button', {name:/proceed to instrumental/i})).toBeEnabled() — Timeout 30000ms
```
The same spec passed on the 0.223.2 canary earlier — it's flaky, not
broken.

**Root cause of the paging:** the spec pinned `retries: 0` (each retry =
a fresh 15-20 min job), which also overrode the canary's `--retries=2`
(spec-level `describe.configure` beats the CLI flag). So any single
flake hard-fails and pages the daily E2E + the post-deploy canary.

**Fix:** `retries: 1` — a genuine flake self-heals on a clean run; a
passing run never retries, so no steady-state cost, capped at one extra
attempt.

Follow-up worth a separate look: *why* the review page / preview video
is intermittently not-ready in prod (the underlying flake this masks).

Frontend/e2e only — no version bump.

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

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

## Summary by CodeRabbit

- **Tests**
- Improved production end-to-end test reliability by allowing one retry
for intermittent preview and review-page readiness issues.
- Preserved fast execution for passing runs while limiting additional
time when a retry is needed.

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

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-13 01:15:03 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 9e4e7f4876 test(e2e): daily credit-purchase ~$0.50 via 95%-off code (off personal card) (#989)
The daily E2E has failed 6 days straight at **Stage 1: Credit Purchase**
— the real Stripe checkout couldn't complete because the personal card
behind `E2E_STRIPE_CARD_*` was frozen (`stripe-checkout.ts:236` timed
out waiting for the success redirect).

Per Andrew's steer, keep real-payment coverage but make it cheap and off
the personal card:
- **Referral code `e2etest70` (70% off, ~$3) → `e2etest95` (95% off,
~$0.50).** $10 base × 5% = **$0.50 = Stripe's USD minimum** (a literal
$0.10 isn't possible — Stripe rejects sub-$0.50 USD charges). The
`e2etest95` vanity link is **already created in prod** (owner
`admin@nomadkaraoke.com`, 95% off, 0% kickback, enabled).
- Updated the discount-badge assertion (70%→95%) and cost comments.

## ⚠️ Action required (Andrew)
Point the **`E2E_STRIPE_CARD_*` GitHub secrets at the Nomad debit card**
(not your personal card). Until then the daily/canary purchase test will
keep failing at checkout — this PR only makes it cheap; the frozen card
is what's blocking completion.

Frontend/e2e only — no backend change, no version bump.

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

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

## Summary by CodeRabbit

- **Tests**
- Updated the production credit-purchase test to use a 95% referral
discount.
- Updated expected discount messaging and pricing to reflect the new
offer and Stripe’s minimum charge.

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

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-13 00:41:55 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 5b5264dc54 Incident hardening: deploy/CI/runner resilience (R1/R2/R3/R4/C1/C2) (#987)
Part 3 of 3 of the **Incident hardening (post-NOMAD-1632)** initiative
(plan: `docs/archive/2026-09-12-incident-hardening-plan.md`). Closes the
deploy/CI/runner gaps: no functional gate, no codified rollback, bad
revision serves 100% immediately, fire-and-forget runner stranding, and
a flaky smoke. **No backend app code changed → no version bump.**

## ⚠️ Reviewer note — read first
**R3/R4 rewrites the live `deploy-backend` step.** It's designed to be
*auto-revert-safe* (a failed candidate smoke means we simply never
migrate traffic, so the prior revision keeps serving 100% — a bad
revision serves **0%**, not an outage). But it changes how **every**
backend deploy works and **can't be fully exercised in CI**. This is the
one to watch on first merge. If you'd rather de-risk, R3/R4 is the only
item here that's safe to split out — the rest (R1/R2/C1/C2) are
independent and lower-risk.

## R2 — codified fast rollback (`scripts/rollback.sh` + runbook)
Dry-run-able, explicit-target-required rollback for the Cloud Run
**service** (traffic-shift to a prior revision — instant, no rebuild)
and the three **jobs** (image re-pin, correct per-job region/repo —
verified against ci.yml). `--list` shows available revisions/tags;
`--dry-run` prints every gcloud command. `docs/TROUBLESHOOTING.md` "Fast
rollback" runbook added as the first section.

## R3/R4 — service traffic-canary
`deploy-backend` now deploys `--no-traffic --tag candidate`, smokes the
tagged candidate URL (health + expected version, with retries), then
`update-traffic --to-latest` **only on pass**. Cloud Run Jobs can't
traffic-split (noted inline) → they rely on R1 + R2.

## R1 — post-deploy functional canary, version-change-gated
New `deploy-verify` job runs the real production happy-path
(`happy-path-real-user.spec.ts`, admin-credit variant — reuses
e2e-daily's impersonate token refresh, secret names verified identical)
after a backend deploy, **only when the backend version actually
changed** (new "Detect backend version change" step compares `poetry
version` to the currently-served `/api/health/detailed`).
Frontend/docs/infra-only merges short-circuit. On failure → Discord
alert + loud fail printing the exact `scripts/rollback.sh` invocation.
Per the plan's caveat, a fresh happy-path won't reproduce every incident
class (e.g. Failure B's stale-cache) — an admin reset+retry variant is a
noted follow-up.

## C1 — ephemeral-runner stranding fix
`infrastructure/functions/runner_manager/ephemeral.py` now confirms the
VM insert **operation** succeeded instead of fire-and-forget: a late
stockout/quota/transient error raises → existing zone-fallback / webhook
redelivery kicks in instead of silently stranding a queued job for ~15
min. An insert-confirm *timeout* is treated as "still provisioning" (not
a failure); guarded for older clients. **+4 tests (46 pass).**

## C2 — de-flake the E2E smoke
`networkidle` → `domcontentloaded` + explicit element waits (the
marketing page's background requests made `networkidle` time out and
redden real deploys).

## Validation (local only — no deploy)
- `ci.yml` + `e2e-daily.yml` parse; **actionlint clean** on new code.
- `rollback.sh`: `bash -n` + `shellcheck` clean; constants cross-checked
against ci.yml.
- `test_ephemeral.py`: **46 passed**.

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

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-12 16:58:12 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 7c03834aaf fix(encoding): map GCE finals by format tag, not whole filename (NOMAD-1632 720p gap) (#982)
## Problem

Validator alert: `MP4-720p: missing 1632`. This was **NOMAD-1632 — Nat
King Cole – "Portrait of Jennie"** (job `21150e73`). Only the **720p**
variant was missing; MP4 and CDG were present and correct (so recycling
the brand code would have been *wrong*).

## Root cause — filename/title substring collision

The encoder produced and uploaded the 720p to GCS correctly (`… (Final
Karaoke Lossy 720p).mp4`), but `GCEEncodingBackend.encode()` mapped the
worker's returned file list to format keys by scanning the **whole
filename**, checking `"portrait"` (to detect the 9:16 portrait video)
**before** `"720p"`. The title contains "Portrait", so the 720p matched
the portrait branch → `mp4_720p` never set → `final_video_720p=None` →
`upload_to_public_share` **silently skips** a `None` path → published to
MP4/ + CDG/ with no MP4-720p/ entry. Deterministic for **any** song
whose artist/title contains a format word ("portrait", "720p", "4k",
"lossless", "vocals", …). Only the daily validator caught it, ~24h
later.

## Fix

- **`classify_encoded_output()`** — a shared, title-collision-proof
classifier that matches the trailing **format parenthetical only** (plus
system short-names), never artist/title text. Used by both
`GCEEncodingBackend.encode()` and `redistribute_video` (same latent
bug).
- **Completeness guard** (defense-in-depth) — `encode()` now returns
`success=False` (orchestrator raises → retry + immediate alert) if the
worker returns fewer formats than requested, so *any* partial-encode
cause fails loud instead of publishing an incomplete release.
- **Portrait Video download button** in `OutputLinks` (shown when the
job has `finals.portrait_1080x1920`) — the feature shipped but had no UI
download. Added the backend download filename suffix and the
`outputLinks.portrait` string translated to all 33 locales.
- Docs: `GDRIVE-VALIDATOR.md` History entry; version bump 0.222.1 →
0.222.2.

## Live gap remediation (already done, outside this PR)

The correct 720p already existed in GCS, so it was uploaded directly to
the `MP4-720p/` public-share folder as `NOMAD-1632 - Nat King Cole -
Portrait of Jennie.mp4` (verified present; mirror backfills nightly). No
re-render, no YouTube disruption. 1632 was **not** recycled.

## Testing

- `test_encoding_interface.py` — 37 pass, incl. a NOMAD-1632
reproduction (`Portrait of Jennie` 720p → `mp4_720p`),
title-with-"720p"/"4k" leakage cases, short-name coverage, and a
completeness-guard failure test.
- `OutputLinks.test.tsx` — portrait button show/hide (frontend unit
suite: 1252 pass).
- Orchestrator (82) + change-visibility (25) suites pass.
- Full backend unit run: 4373 pass (8 failures are pre-existing
`test_emulator_integration` env failures — emulator not running locally;
unrelated to this change).

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

- **New Features**
  - Added downloadable portrait-format video output at 1080×1920.
  - Added localized “Portrait Video” labels across supported languages.

- **Bug Fixes**
- Improved output recognition so video titles containing format terms
are classified correctly.
- Prevented incomplete encoding results from being published when a
requested format is missing.
  - Corrected portrait-format filenames for clearer downloads.

- **Chores**
  - Updated the application version to 0.222.2.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-12 05:58:23 -04:00
Andrew Beveridge ☄️andClaude Sonnet 5 2867c22f68 fix(review): restore per-suggestion undo for server-pre-applied AI corrections (#981)
## Summary
- The server-side pre-apply feature (#957) bakes AI lyric corrections
into the review data before the page loads, but the review UI's per-item
Undo and "Revert all" controls in the "N auto-corrections applied" panel
relied on client-side-only undo bookkeeping that was never populated for
pre-applied jobs — so both were silently hidden. Reported by Andrew:
`Undo All` did nothing and the auto-corrections panel offered no way to
revert individual corrections (e.g.
https://gen.nomadkaraoke.com/en/app/jobs/#/8a94db60/review).
- `apply.py` now records per-suggestion undo info (removed words, new
word ids, segment) at apply time; `pre_apply.py` persists it in
`metadata.auto_approval.undo_info`; `useAutoCorrect` seeds its undo map
from that on load so per-item Undo / Revert All work the same for
pre-applied jobs as for client-applied ones.
- Jobs pre-applied *before* this fix ships simply have no undo info
(same as a stale suggestion), so the buttons correctly stay hidden only
for those older jobs.
- The Header "Undo All" button is unchanged — it correctly resets
in-session manual edits back to page-load state and was never meant to
revert AI corrections baked in before load.
- Added a Lessons Learned entry on the underlying pattern
(server-applied state needs its own undo data, not just client undo
state).

## Test plan
- [x] `python -m pytest backend/tests/services/auto_approval/` — 163
passed (18 in `test_apply.py`, including 5 new tests covering
`undo_out`/`undo_info` for replace/delete/insert_after)
- [x] `npx jest hooks/__tests__/useAutoCorrect.preapplied.test.ts` — 5
passed (3 new, covering undo seeding, `canUndo`, `undoAccept`, and
`revertAll` against server-provided undo info)
- [x] `npx jest --testPathPattern lyrics-review` — 357 passed, no
regressions
- [x] `tsc --noEmit` and `eslint` clean on all touched files
- [ ] Local CodeRabbit CLI review — could not run (`coderabbit auth
status` is tied to a different org's SSO session); opening without
`@coderabbitai ignore` so the GitHub bot reviews instead

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

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-09 23:15:51 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 bedbcdc3bd Requests board: skip songs with existing community karaoke versions (submit + pick time) (#979)
## Summary

Stops the requests board from spending a free track — or wasting voters'
time — on a song that **already has a good community karaoke version
online**, reusing the same KaraokeNerds check the normal job-submission
flow uses, at two points.

Follow-up to the requests-board Phase 2 automation (#977). Addresses
Andrew's two asks:

**A) Submission time (soft, non-blocking).** As a signed-in user types
an artist/title on the board, we debounce-check KaraokeNerds and surface
any existing community versions in a dismissible banner with YouTube
links. They can still request it — but many will just watch the existing
one. Reuses the existing `POST /api/catalog/community-check` endpoint +
`CommunityVersionBanner` component (added an optional board-appropriate
subtitle).

**B) Pick time (review).** A song may have had no version when requested
but gained one by the time it's upvoted to the top. So the daily picker
now KaraokeNerds-checks each candidate **in rank order**:
- A candidate that already has a community version is **flagged for
review** (`review_state=pending`) instead of auto-made, and the picker
**skips to the next clean request** — so a fresh, non-duplicate free
track still ships that day.
- Andrew is emailed a summary and resolves held picks at
**`/admin/community-reviews`**: **Make ours anyway** (creates the job
like a normal pick), **Reject** (declines and emails every up-voter a
link to the existing version), or **Keep on board** (leaves it votable,
snoozing re-review for 30 days).
- Held requests stay visible/votable on the board; they just aren't
auto-made. Flag/email is idempotent (no daily re-nag).

## Andrew's decisions (via AskUserQuestion)
Held pick → **skip to next clean request**. Review surface → **admin
queue page + email**. "Keep" → **return to board, snooze re-review (30
days)**.

## Changes
- **Model:** `SongRequest.review_state` (pending|snoozed),
`community_versions`, `community_checked_at`, `review_snoozed_until`.
- **Service:** `list_pick_candidates` (skips review-blocked),
`set_review_pending` (transactional/idempotent), `snooze_review`,
`clear_review`, `reject_request`, `list_pending_reviews`.
- **Picker:** candidate loop + community check; extracted
`_provision_and_start` shared by the picker and the admin "make" action.
- **Admin:** `GET/POST /api/admin/community-reviews`,
`/admin/community-reviews` page + sidebar item. New existing-version
email to up-voters (33 locales).
- **Frontend:** board submit form debounced check + banner.

## Testing
- Picker candidate loop (flag dup → make next clean; all-dup → empty +
flagged; resume skips re-check), admin actions (make/reject/keep, 404,
500), emulator coverage for the new service methods. 86 passing across
touched suites; frontend typechecks clean; 32/32 locale parity.

## Deploy
No `infrastructure/` changes — merge deploys it. The daily picker is
already enabled in prod, so the pick-time check goes live with the
backend deploy; the submission banner ships with the frontend.

## Review
CodeRabbit reviewed locally (one minor grammar nit, fixed).

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-03 16:59:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 d41854f787 feat(requests-board): public song-request voting board (Phase 1) (#975)
## What & why

Phase 1 of the **daily-free-community-track** initiative (BACKLOG:
*"Daily free community track via public voting board"*). A public,
Hacker-News-style voting board at **requests.nomadkaraoke.com** where
anyone signs in with an email magic link, submits a song request
(artist/title auto-corrected + deduped), and casts **one vote per
calendar day**. Publicly viewable so it can be linked from YouTube
descriptions to drive top-of-funnel awareness.

Ships the board first (this PR) so the linkable URL exists; the
automation (daily auto-picker, free-credit grant on pick, 24h ownership
handoff, voter publish-emails, and the trending-karaoke agent as a
fallback request source — one free track/day total) is **Phase 2**.
Design doc: `docs/archive/2026-09-02-requests-voting-board-plan.md`.

## Backend
- New `song_request` models + service (Firestore `song_requests` /
`song_request_votes`) with transactional vote arithmetic (create / move
/ flip / toggle-off), dedupe, and ranking. One-vote-per-day is enforced
structurally via the vote doc id (`{email}__{YYYY-MM-DD}`).
- New `/api/requests-board` router: `GET /requests` (public, annotates
the caller's vote), `POST /requests` (submit — auto-corrects via the
existing `match_judge`), `POST /requests/{id}/vote`, `GET /me`.
- Board sign-in (`purpose="requests_board"`): passwordless identity only
— **no welcome credit**, a **higher per-IP signup cap**
(`BOARD_MAX_SIGNUPS_PER_IP`, default 30) so a shared venue WiFi can
register many voters while the per-fingerprint cap stays strict, and
`redirect_path="/requests"`.
- New `POST /users/claim-welcome-credit` powers the "Make it yourself
now" conversion (grants the standard credit the normal way, idempotent).

## Frontend
- `app/[locale]/requests` board: submit form with "we tidied that to…"
feedback, ranked vote list with daily-vote UX, convert-to-gen CTA,
recently-made list with YouTube links.
- API client methods + types; verify page honors `redirect_path`; new
`requests` i18n namespace translated to **all 33 locales**.
- `requests` added to `nonTenantSubdomains`.

## Testing
- 20 backend unit tests (routes + pure logic + sign-in + board signup
limit) and 8 emulator tests exercising **real Firestore transactions**
(vote arithmetic, dedupe, idempotent resubmit, one-vote-per-day). Full
backend unit suite green (4247 passed); frontend typecheck clean.
- Reviewed locally with CodeRabbit CLI (3 cycles); all findings
addressed (auth headers, idempotent resubmit, signup-limit hardening,
blank-input validation, i18n particle, refresh race).

## Deploy note
The board is reachable at `gen.nomadkaraoke.com/en/requests` on deploy.
Wiring the vanity `requests.nomadkaraoke.com` is a **post-deploy
Cloudflare step** — see
`docs/runbooks/requests-subdomain-cloudflare.md`.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-02 22:02:35 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 3c58143f75 fix(review): re-sign instrumental preview URLs on expiry (refresh-on-error) (#973)
## Problem

Completing a combined review failed to play the instrumental in the
preview modal — toggling to **Instrumental** loaded nothing, with
`NS_ERROR_DOM_NETWORK_ERR` in DevTools (Firefox) on the
`review-audio/instrumental_with_backing.ogg` GCS request.

**Root cause:** the overlaid instrumental `<audio>` uses the signed GCS
URL baked into the review payload at page load, which has a **120-minute
expiry**. A long review session outlives it, so the stem fetch returns
`400 ExpiredToken` and playback silently fails. Confirmed by fetching
the exact URL from the report: `ExpiredToken — Request signature expired
at 2026-09-01T20:16:26Z` (page had been open ~2h11m).

Reloading didn't help because the review UI persists the full
`CorrectionData` — including `instrumental_options[].audio_url` — to
`localStorage` (`lyrics_analyzer_data`) and rehydrates it when the user
has unsaved edits, so the *same* expired URL came back.

The `[SW] Service worker registered` log is a red herring:
`frontend/public/sw.js` has no `fetch` handler.

## Fix (refresh-on-error)

- **Backend:** extract a shared `_build_instrumental_options` helper and
add `GET /api/review/{job_id}/instrumental-urls` returning
freshly-signed stem URLs.
- **Frontend:** on the stem `<audio>` `error` event, re-fetch fresh URLs
via the new endpoint and swap them in. The existing video↔audio sync
effect (keyed on the URL) resumes playback in place. Capped at 3
refreshes per modal open so a genuinely-broken stem (404) can't loop.

No new user-facing strings (the recovery is silent) → no i18n changes.

## Testing

- Backend: 3 new tests for the endpoint (both stems / single stem / 404)
— `TestInstrumentalUrlsRefresh`. Full `test_routes_review.py` +
`test_combined_review_flow.py` + `test_audio_transcoding_service.py` =
111 passed.
- Frontend: 3 new `PreviewVideoSection` tests (swap on error / cap at 3
/ no-op without refresh fn). Full unit suite = 1248 passed.
- CodeRabbit local review: no findings.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-01 17:21:35 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 d39dfd6778 Encoding worker infra/auth failures: retry instead of terminal-failing the job (#972)
## Why

Prod alert burst (2026-08-31): a paying customer's job (`6452888e`) was
**terminally failed** — its render worker error was:

> Encoding job 6452888e failed: Failed to retrieve
`https://metadata.google.internal/.../service-accounts/default/` …
**Compute Engine Metadata server unavailable** …
`SSLCertVerificationError`

Root cause: the c4d primary pair was in a zonal stockout (503 on start),
so the render fell back to `encoding-worker-fallback-c4a`. That fallback
VM **booted and accepted the job** but then couldn't reach the GCE
metadata server to fetch its service-account token, so it couldn't touch
GCS and died mid-encode. This surfaced as a bare `RuntimeError`, hit
`render_video_worker`'s generic `except Exception` → `fail_job`, and
lost the job with **no retry** — even though the exact same work
succeeds on any healthy worker.

The same alert burst also included the daily E2E happy-path failure (the
encoder being offline made the preview step flaky) and a benign
`match-judge AI call failed; returning no-suggestion` red-error page.
All three are addressed here.

## What

**1. Encoding infra/auth failures are now recoverable (primary fix)**
- `encoding_errors.py`: `is_worker_infra_error()` classifier (metadata /
SSL-cert / missing-credentials markers, deliberately specific so a real
ffmpeg/input error never matches) + new `EncodingWorkerInfraError` — a
**subclass of `EncodingWorkerStartError`** so it flows through the
existing park-for-auto-retry path with zero changes to the render
worker's `except` (and the final-encode Cloud Run Job retries too).
- `encoding_service.wait_for_completion()`: on a worker-reported
infra/auth failure, **demote the broken worker + invalidate the URL
cache**, then raise the recoverable typed error instead of
`RuntimeError`.
- `encoding_worker_manager.demote_active_worker()`: records a
capacity-state cooldown for the serving fallback's `machine_type@zone`
and clears `active_override`, so the retry re-selects a *different,
healthy* VM. Scoped to **fallbacks only** — it never family-demotes the
fast c4d primary on a rare blip.

**2. match-judge noise** — the two graceful-degradation
`logger.exception` calls become `logger.warning(exc_info=True)`, so a
transient Vertex/Gemini blip that safely returns no-suggestion stops
paging as a red "new error pattern".

**3. Happy-path E2E robustness** — tolerate slow encoder cold-starts at
the preview step: scope the alert check to the modal (kills the spurious
empty-`[role=alert]` "Preview error:" from run #151) and recover the
"Proceed to Instrumental" button via reload+reopen. The final assertion
stays authoritative, so genuinely broken generation still fails the
smoke test.

## Testing
- New unit coverage: classifier positive/negative + subclass
(`test_encoding_errors.py`), `demote_active_worker` (fallback
demote+clear, primary no-op, never-raises), `wait_for_completion` infra
classification (+ demote/invalidate, and no-manager path), and render
worker **parks** (not fails) on `EncodingWorkerInfraError`.
- `python -m pytest` across the encoding / worker / match-judge suites:
**177 passed** locally.

## Not in this PR (infra, needs Andrew / GCP write)
- **Fault A**: `encoding-worker-a` (c4d, us-central1-c) is chronically
503 on start (zonal stockout) — that's why the "Encoder offline" footer
showed in the E2E. This change makes the fallback path robust to it, but
the underlying c4d capacity/zone choice is an infra decision (secret/VM
change; my GCP access is read-only). Worth deciding whether to repin the
primary family/zone or promote a fallback.

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

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

* **New Features**
* Detects infrastructure and authentication failures on encoding
workers.
* Demotes affected workers and retries jobs using alternate capacity
when available.

* **Bug Fixes**
* Prevents recoverable worker failures from becoming terminal job
errors.
* Reduces misleading error-level logging for gracefully handled
match-judge failures.
* Improves preview-flow recovery by waiting for actions to become
enabled.

* **Documentation**
* Clarified that retries prefer, but do not guarantee, a different
worker.

* **Chores**
  * Updated the application version to 0.217.0.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-31 18:59:59 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 af36975db7 Admin create/manage tenants: album batch via tenant bulk flow + full theme customisation (#971)
## Why

Enables the "album for one client" use case: a batch of tracks with
audio provided up front, a client-supplied instrumental per track, and
one shared theme. That pipeline already exists as the **tenant bulk
flow** (folder pick → LLM pairs mixed↔instrumental → resumable uploads →
skip separation → locked theme on every job) — the only missing piece
was an easy way to **mint a tenant** (previously a hand-run
`scripts/setup-*-tenant.py`). This adds admin create **and** manage, so
a client's feedback can be iterated on (edit theme, re-render).

## What

**Backend** (`backend/services/tenant_admin_service.py` +
`backend/api/routes/tenant_admin.py`):
- `POST /api/admin/tenants` (multipart) — mint a tenant: derives a
**self-contained theme** from the default Nomad theme (copies its assets
so every `background_image` basename resolves), applies colour
overrides, overlays uploaded backgrounds, registers the theme, writes
`tenants/{id}/config.json` with B2B defaults (private, no
YouTube/GDrive, locked theme). Reserves the config **create-only before
any theme write**, with rollback on failure.
- `GET /api/admin/tenants` / `GET /api/admin/tenants/{id}` / `GET
/api/admin/tenants/_template` — list, full detail (config + theme
`style_params` + assets), and the default theme JSON as a template.
- `PUT /api/admin/tenants/{id}` (multipart) — **full theme
customisation**: merge config (one level, `id` immutable), replace the
entire `style_params.json`, upload/replace assets (images **or fonts**),
update logo.
- Full `style_params` override accepted on create too. Theme docs
validated to `intro/karaoke/end/cdg`. Guards against a tenant id
colliding with an existing theme.

**Frontend** (`/admin/tenants`):
- Tenants list + **Create** dialog (name→auto-slug, colours,
backgrounds, Dropbox/delivery, logo, + an "Advanced: full theme JSON"
editor seeded from the Nomad template).
- **Manage** dialog: editable config fields + a validated full **theme
JSON editor** + asset list & upload.
- New tenants are driveable immediately via **`?preview_tenant=<id>`** —
no DNS needed.
- Sidebar "Tenants" entry;
`adminApi.listTenants/createTenant/getTenant/updateTenant/getThemeTemplate`.

## Testing
- 36 backend tests (`test_tenant_admin_service.py`,
`test_tenant_admin_route.py`) + 4 frontend tests
(`admin-tenants-page.test.tsx`), incl. atomic-reservation /
conflict-no-clobber / rollback / theme-collision / full-theme-edit.
- Full `make test` green locally (backend + 1245 frontend); typecheck
clean.
- Reviewed locally with CodeRabbit (2 cycles, all findings addressed).

## Notes
- Admin is English-only → no i18n locale files touched.
- Follow-up (out of scope): saved **user** themes in the Custom Video
Style dialog (reuses this theme-derivation core); and an optional
"re-apply theme + re-render existing job" action.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-31 18:31:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 feb4c86842 gen: vanity referral request approve/deny queue (rename-in-place) (#967)
## Problem

When a user requests a custom vanity referral code, the backend only
emailed the admin — nothing was persisted. To "approve," the admin had
to open **Create Vanity Link** and hand-retype the owner email + desired
code, which created a *second* link alongside the user's auto-generated
one (split stats, two live codes). The **Edit** modal can't change a
link's code. There was no approve/deny concept and no notification to
the requester. Confusing and unintuitive (reported first-hand while
setting up the YouTube referral link).

## Solution

User vanity requests now persist to Firestore and surface as a
**"Pending Vanity Requests"** banner at the top of `/admin/referrals`
with one-click **Approve** / **Deny**.

- **Approve** = renames the user's existing link *in place* (`odu4brd8`
→ `youtube`): stats/earnings preserved, referral attribution
(`referred_by_code` + earnings) migrated, old code disabled as a
breadcrumb (stats zeroed so admin totals don't double-count), and the
requester is **emailed** that their link is live.
- **Deny** = marks the request denied.
- One unified code per user — no more duplicate links or split stats.

## Changes

**Backend**
- `VanityRequestDoc` model (`referral_vanity_requests`, keyed by
owner_email so a re-request overwrites).
- `referral_service`: `create_vanity_request` / `list` / `get` /
`approve` / `deny` + `rename_link` (atomic `create()` to close the
destination-code race; migrates attribution; zeroes old-alias stats).
`get_or_create_link` now prefers enabled links so the renamed alias
never resurfaces.
- 3 admin endpoints: `GET/POST /admin/vanity-requests[...]`.
`request_vanity_url` now validates the code up-front (before link
creation) and persists the request.

**Frontend** (`/admin/referrals` is English-only, no i18n)
- Pending-requests banner card +
`adminApi.listVanityRequests/approveVanityRequest/denyVanityRequest` +
`VanityRequest` type.

## Testing

- Backend unit/route: **21** (approve/deny/list, request validation,
404/400 paths)
- Emulator (real Firestore): **11** (rename preserves stats + migrates
attribution + disables/zeroes old alias; atomic create blocks taken
codes; approve/deny/re-request)
- Frontend: **4** (banner renders, approve/deny wiring, hidden when
empty)
- Version `0.214.0` → `0.215.0`. Local CodeRabbit review completed (2
fix cycles).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-30 21:52:26 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 0bebf5c170 gen: inline instrumental chooser for all jobs + fix backing-scorer race (#966)
Two fixes for jobs where a backing-vocals song showed **no** inline
chooser and was forced to the heavy `/instrumental` screen — diagnosed
on job `be8231fd` ("The Qemists - Take It Back").

## Diagnosis
The auto-approval verdict is scored by `screens_worker` on lyrics
completion. `mark_audio_complete` is decoupled from status, so when
lyrics finish first and audio is still separating, the backing-vocals
analysis isn't available yet → the backing half is scored `review`
(`analysis_present:false`, `audio_incomplete`). The `audio_worker`
re-score meant to fix this is **skipped once a human opens the editor**
(status `IN_REVIEW`, not `AWAITING_REVIEW`), so the stale "no analysis"
verdict persists forever — even though the analysis later lands and
would score a confident `with_backing` keep.

## Fix 1 — backend: read-time self-correction (race-proof)
`auto_approval_summary` now re-derives the backing verdict from the live
`state_data.backing_vocals_analysis` when the stored verdict was scored
*without* it (`backing_analysis_available` falsy). Pure/read-only —
enforcement & auto-complete are untouched. Unit-tested with the real
job's signals (`corr 0.75`, `-28.7 dB`, `64%` audible → confident
`with_backing`), and that it respects the keep flag and doesn't override
a verdict that already had the analysis.

## Fix 2 — frontend: inline chooser for ALL jobs with both stems
The **"🎬 Your karaoke video will use:"** radio group now shows whenever
both a clean and a with-backing stem exist — not only when the scorer
was confident. Confident → green **"✓ recommended"** badge + confident
copy; not confident → the analysis's recommendation is **preselected**
with a neutral *"Have a listen and choose…"* prompt (no badge). Picking
clean/with-backing **completes inline** ("Complete Track"); **Advanced
mode** is the opt-in to `/instrumental`. The backend `complete` endpoint
already accepts explicit `clean`/`with_backing`, so this is
frontend-only.

**Verified live** on `be8231fd` via the dev server: the chooser now
renders (backing preselected, clean + Advanced offered, CTA "Complete
Track") instead of forcing the advanced screen.

## Tests
- Backend: `auto_approval` suite 121 pass (+3 new self-correction
tests); review/correction-data 142 pass.
- Frontend: full suite **1237 pass**; `ReviewChangesModal` rewritten for
the new prop API incl. the non-confident chooser path. ESLint + tsc
clean.
- i18n: 33 locales, full key parity.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-30 16:00:33 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 7abd0a9617 gen: shrink preview video + name the instrumental variant in the preview pill (#965)
Follow-ups to the review-modal audio split (#964), from Andrew's
feedback:

1. **Smaller preview video** — the `<video>` height is now capped
(`max-h-[45vh]`, aspect ratio preserved, works for portrait too) so the
**"🎬 Your karaoke video will use:"** choice is visible without
scrolling. Previously the player filled most of the modal and pushed the
options off-screen.

2. **Preview pill names the variant** — the "Instrumental" preview pill
now reads **"Instrumental (plus backing vocals)"** or **"Instrumental
(clean)"** depending on the current final-output selection below, so
it's clear which stem you're auditioning (it was ambiguous before — you
had to experiment to find out it tracked the radio choice).

## Tests
- `PreviewVideoSection` + `ReviewChangesModal` suites updated (dynamic
pill label asserted, incl. live update when `auditionInstrumental` swaps
the stem). Full frontend suite: **1237/1237 pass**. ESLint clean.

## i18n
- New keys `previewVideo.audioInstrumentalPillBacking` /
`audioInstrumentalPillClean` translated across all 33 locales; full key
parity.

Note: local CodeRabbit CLI hit its free-OSS review cap this cycle, so
this PR is left open for the GitHub bot to review (no `@coderabbitai
ignore`).

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-30 14:58:40 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 b48a721d03 gen: split preview audio from final-instrumental choice in review modal (#964)
## Problem

In the finish/preview modal the single **"Audio:"** segmented control
did two unrelated jobs at once — audition playback (incl. "Original with
vocals", which is never a valid output) *and* the final-output
instrumental selection — with no signal telling the user which
instrumental the produced video would actually use. The prose "switch to
the clean instrumental" had no obvious target, and the escape-hatch
checkbox wording was long/confusing.

## Change

Split the two concerns into distinct, clearly-labelled controls.

**`PreviewVideoSection`** — now a pure preview component:
- Always the simple **`Preview audio: [ Original (with vocals) ] [
Instrumental ]`** toggle (audition only).
- Exposes an imperative `auditionInstrumental(id, seekTime?)` so a
decision made in the modal also plays that stem.

**`ReviewChangesModal`** — owns one unambiguous decision control:

```
🎬 Your karaoke video will use:
   (●) Instrumental + backing vocals    ✓ recommended
   (○) Clean instrumental                     ← only when a clean stem exists
   (○) Advanced mode (edit backing vocals or upload your own instrumental)
```

- Picking **backing/clean** both *selects* (final output) and
*auditions* it.
- **Advanced mode** replaces the old wordy escape-hatch checkbox — it
opts into the full instrumental screen (CTA flips to "Proceed to
Instrumental Review").
- Helper text now uses plain language (no "bleed" jargon): "…if you can
hear the lead singer's voice coming through, switch to Clean
instrumental above."

No backend change — still submits `clean` vs `auto` exactly as before.

## Tests

- Rewrote the obsolete choice-pill tests to cover the new radio group
(recommended badge, Advanced-mode wording per backing/clean case,
clean-radio reports choice + clears review-anyway, hidden when not
confident) and the imperative audition handle.
- Full frontend suite: **1237/1237 pass**. ESLint clean on changed
files.

## i18n

All 33 locales at full key parity. New keys (`finalChoiceLabel`,
`recommended`, `advancedMode`, `advancedModeClean`) translated; reworded
`autoInstrumentalBacking` refreshed; obsolete checkbox keys pruned.
Ambiguous "upload your own" phrasing made explicit ("…your own
instrumental") after a local CodeRabbit pass flagged 6 mistranslations.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-30 14:25:32 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 b464e40d84 Inline clean-instrumental choice via 3-way audio toggle on the finish modal (#962)
## Summary

On the lyrics-review **finish modal**, when the backing instrumental is
confidently auto-selected, reviewers previously had only a heavyweight
escape hatch ("Let me choose the instrumental myself" → the full
instrumental-review screen). The common override — "the backing vocals
sound bad, just give me the clean instrumental" — is now a **single
click**.

The clean instrumental becomes a **third pill in the "Audio:" preview
toggle** so the two instrumentals can be A/B'd and chosen in one place:

- **`PreviewVideoSection`** — when both stems exist and are meaningfully
different (verdict `with_backing` + a clean stem present), the single
"Instrumental" pill splits into **Instrumental + backing vocals** /
**Clean instrumental**. Selecting a variant both auditions and selects
it (last activated wins); the backing-vocals waveform auditions the
with-backing stem. When clean is already the default (or only one stem
exists), the single "Instrumental" pill is kept — nothing to choose.
- **`LyricsAnalyzer`** submits the reviewer's choice (`clean` vs
`auto`). The backend already accepts an explicit `clean` selection at
`POST /api/review/{id}/complete`, so **no backend change**.
- The confident-box note reflects the current choice, and the
escape-hatch checkbox is reworded to the specific, rarely-used action
(keep BV but mute sections / upload custom), with a clean-case variant.
- **i18n:** reworded + new keys across all 33 locales (`translate.py
--target all`; key parity verified).

## Testing

- `PreviewVideoSection.test.tsx` — 3-way toggle: splits pills when
offered, reports choice + swaps stem on clean click, keeps single pill
when only one stem / not offered.
- `ReviewChangesModal.test.tsx` — note reflects the reported choice;
per-case escape-hatch wording.
- Full frontend suite: **98 suites / 1236 tests pass**. Changed source
files typecheck clean.

## Notes

- New completion toasts are kept in English to match the 7 existing
hardcoded toasts in the same submit function (localizing only the new
ones would be inconsistent; localizing all is out of scope).
- **Pending live-verify (Andrew's ear):** an in-review
confident-`with_backing` job — confirm the 3-pill toggle A/Bs cleanly
and that picking "Clean instrumental" ships the clean stem.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-30 02:09:06 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 e58334e461 Preview modal UX: audio toggle, backing-vocals waveform, cohesive loading & saving flow (#961)
## Summary

Five UX improvements to the lyrics-review **Preview Video** modal (shown
when the reviewer clicks "Preview Video").

1. **Unified loading** — the `generating` and `encoding` states now
share one centred spinner; only the stage message changes ("Preparing
your preview…" → "Encoding preview video…" → slow-encoder hint). No more
janky layout swap.
2. **Audio toggle (Original ↔ auto-selected Instrumental)** — a hidden
stem `<audio>` element (from `instrumental_options`, already in the
review correction-data) is kept in lock-step with the video
(play/pause/seek/rate/drift ≤0.25s). Switchable mid-playback with
position preserved. Title dropped "(With Vocals)" → just "Preview
Video".
3. **Removed low-value text** — deleted "No manual corrections
detected…" and "Total segments: X". The manual-corrections note now only
shows when the reviewer actually edited.
4. **Backing-vocals waveform** (new `BackingVocalsWaveform`) — only when
the auto-selector kept backing vocals (`with_backing`, confident, and
the stem is playable). Thin 35px canvas of the backing stem (from `GET
/api/review/{jobId}/waveform-data`); clicking seeks the video and
switches audio to the instrumental, for quick sanity-checking of the
automatic pick.
5. **"Complete Track" saving flow** — the modal stays in its "Saving…"
state through the slow `completeReview` call, so it no longer flashes
back to the review screen before the "Review Submitted" view.

Also: `getWaveformData` added to the review API client factory; version
`0.209.2 → 0.210.0`.

## i18n
- Keys added
(`previewVideo.audioLabel/audioOriginal/audioInstrumental/backingVocalsWaveformHint`,
`modals.reviewChanges.previewTitle`) and removed (`previewWithVocals`,
`noManualCorrections`, `totalSegments`); all 33 locales synced via
`translate.py`. Keys-only parity passes.

## Testing
- Frontend jest: **1230 passed / 98 suites** (26 in the two touched
modal/preview suites, incl. audio-toggle mute + backing-waveform
gating).
- Manually verified against **real prod jobs** via local dev (proxying
to prod API):
- `ae225662` (clean pick): audio toggle mutes video + plays clean stem
synced to the same position; waveform correctly hidden.
- `370f7b92` (with_backing pick): 35px backing waveform renders;
clicking it seeks the video (102.5s→138.8s) and the instrumental audio
follows in lock-step.
- Local CodeRabbit review run and its 2 minor findings addressed
(playbackRate sync on audio switch; gate waveform on stem availability).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-29 22:08:42 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 a4d9303e8d fix(lyrics-review): Tap To Sync — stop stale-start crush + gap-fill tapped words (#958)
## Summary

Fixes the Tap To Sync bug where re-syncing a segment left a word crushed
to a tiny sliver (job `3ecab928` seg 28: **"call" collapsing to ~0.01s**
with a dead gap before "seems"). Verified live against real prod audio
in the replay UI, for both tap and hold.

Two related fixes in `frontend/hooks/useManualSync.ts`:

### 1. Overlap safety-net no longer crushes against a *stale* next-word
start (root cause)
When advancing to the next word, the overlap `useEffect` compared the
just-synced word's end against the **next word's start** — which still
held its **old** timing because it hadn't been re-tapped yet. For an
adjacent old start (e.g. "seems" at 155.50 right after "call"), it
pulled `call.end` back to that stale value (~0.01s). Taps happened to be
rescued by the keydown gap-fill; **holds** took the shorten-only branch
and stayed crushed.

Fix: track which word indices got a fresh `start_time` in the current
pass (`syncedIndicesRef`) and only let the overlap effect act when the
next word has actually been re-synced this pass. The forward correction
is already handled correctly at the next word's keydown.

### 2. Tapped word fills the gap up to the next onset
A *tapped* word only marks its onset, so it should hold until the next
word starts rather than staying a fixed 0.5s block.
`adjustPreviousWordEnd()` now grows a tapped previous word's end to
`nextStart − buffer`, capped at **`MAX_TAP_GAP_FILL_SECONDS = 1.0s`**.
Holds keep their deliberate release (only shortened on overlap). A
shared helper keeps the keyboard and touch paths in sync.

## Testing
- `frontend/hooks/__tests__/useManualSync.tapSync.test.tsx`: added
gap-fill, 1s-cap, and **hold-crush regression** tests (the hold-crush
test fails without the `syncedIndicesRef` guard — verified).
- 17/17 useManualSync tests green; 210/210 across `hooks` +
`components/lyrics-review`.
- Verified live in the replay UI (real prod job `3ecab928` seg 28): tap
→ "call" fills to onset (0.87s); hold → "call" keeps its held 0.82s, no
crush.
- Preserves all v0.208.0 invariants (no negative durations, lead-in/out
on both paths, auto-stop while spacebar held).

## Version
`0.208.0` → `0.208.1`

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-29 19:53:09 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 3680ed66b3 Full-auto review: per-screen skip + server-side pre-apply + submission autonomy UI (workstream C) (#957)
Completes the fully-automated-review initiative (workstream C — the
final build item). Three interlocking parts, all shipped in one PR.

## C1 — Per-screen skip
Only show the review screen that actually needs a human.
- **Confident backing → skip the instrumental screen.** Completing the
lyrics review finishes the whole job. The client sends
`instrumental_selection="auto"`; the backend resolves it from the stored
verdict (`resolve_auto_instrumental`), so CLI/tenant clients get the
skip for free.
- **Mirror case (only backing gates) → skip the lyrics screen.** The
router deep-links straight to `#/instrumental`; the server-pre-applied
corrections are the lyrics payload.
- **Escape hatch:** a "let me choose the instrumental myself" toggle in
the finish modal.
- `always_review` jobs never auto-skip (gated server-side in the shared
summary).

## C2 — Server-side pre-apply (kills the on-load edit race)
Andrew's directive: apply the AI/heuristic corrections *before* the
review-ready notification, so the review screen loads one final state.
- New `pre_apply.ensure_and_pre_apply` runs in `screens_worker` before
the `AWAITING_REVIEW` transition: ensures the suggestion cache (bounded,
fail-open), applies with the same machinery the executor uses
(`apply.build_applied_segments`), and writes `corrections_updated.json`
with a `pre_applied` marker.
- `useAutoCorrect` gains a `preApplied` mode: no client-side
auto-run/auto-apply, panel seeded read-only from the server's
applied/rejected ids. Backward compatible (no marker → today's
behavior).

## C3 — Submission autonomy UI
- **Review mode** (fully automatic / always let me review) +
**backing-vocals preference** (keep-where-possible / clean /
let-me-choose) toggles in the guided flow.
- Plumbed through every submission route + `JobCreate`; **33 locales**
translated.

## Shared source of truth
`instrumental.backing_decision` is the one place the executor, the
complete-review `"auto"` resolver, and the UI summary all derive the
instrumental decision — they can't drift.

## Tests
- Backend: `test_instrumental.py` (decision matrix, summary/resolver
incl. always_review gating + stem checks, JobCreate coercion),
`test_pre_apply.py` (apply/marker/fail-open), executor
`backing_preference` cases. Full auto_approval suite: 112 pass. Touched
route suites: green.
- Frontend: `useAutoCorrect.preapplied` + `ReviewChangesModal`
escape-hatch tests. Full Jest suite: 1218 pass.
- i18n completeness enforced by CI.

Local CodeRabbit review completed and addressed (always_review gating,
stem-availability check, out-of-set preference coercion).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-29 18:58:55 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 8ce0d39faa fix(lyrics-review): Tap To Sync timing corruption + padded edit-segment timeline (#956)
## Summary

Fixes **Tap To Sync timing corruption** in the Edit Segment modal and
reworks the segment timeline for easier re-timing of the first/last
words.

### Tap To Sync fixes (`useManualSync`)
- **Negative durations on re-sync** — the overlap-correction effect
pulled a just-tapped word's end back to the *next* word's **stale**
start (it hadn't been re-tapped yet), producing `end_time < start_time`.
The sanitizer then reported *"Fixed N word timing(s) that fell outside
this segment"* on reopen. Now guarded + clamped so it never inverts.
- **First word squished / segment start ratcheting** — `clampSyncTime`
forced every tap into the tight `[segStart, segEnd]`, so a legit tap in
the 3s playback lead-in got shoved up to `segStart` and the start could
never be re-synced earlier. Now allows taps in `[segStart − leadIn,
segEnd + leadOut]` (floored at 0).
- **Last word cut off** — symmetric lead-out + auto-stop no longer fires
while the spacebar is held, so the last word can extend the segment
(hold past the end / default-duration overshoot) instead of being
truncated.
- Both keyboard **and touch** sync paths use the widened window.

### Edit Segment timeline UX
- ±1s **greyed context padding** on each side (dashed boundary), **faded
waveform** outside the segment, and **neighbouring segments' words** as
read-only context blocks. Word bars, drag, ruler, cursor and
click-to-scrub all map over the padded view; words can be dragged/synced
into the padding to extend the segment.
- Modal widened `960px → 95vw / max 1400px`.
- Header **play button** starts 1s before and auto-stops 1s after the
segment.

### Dev tooling (dev-gated, no prod impact)
- `&edit=1` makes a replay session editable locally (guarded by
`NODE_ENV !== 'production'`) so the real review UI can be exercised
against real job data + audio. Documented in `docs/REPLAY.md`.
- `review_test_fixtures.py` now serves a synthetic **click-track** so
Tap To Sync is exercisable offline.

## Testing
- New/expanded unit tests in `hooks/__tests__/useManualSync*.ts(x)`:
negative-duration regression (fails on old code, passes on fix),
lead-in/lead-out clamp cases, and segment-end extension. All 13 pass;
178 lyrics-review + hook tests green.
- Typecheck clean on touched files.
- Verified end-to-end in the browser against a real completed job
(replay + real vocals): tap-sync produces valid monotonic timings, no
sanitizer banner, first/last words extend correctly, timeline padding +
fade + neighbour words render as intended.

## Notes
- CodeRabbit reviewed locally; its one finding (touch path missing the
lead window) is fixed.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-29 17:17:10 -04:00
Andrew Beveridge ☄️andClaude Fable 5 5d6a6d4f1b fix(review): async preview video generation — survive encoder cold-starts (v0.207.0) (#954)
## Summary

Preview videos in the lyrics review UI got stuck on "Generating preview
video..." whenever the GCE encoding worker needed a cold start (job
`326e1aef`, 2026-08-29): the synchronous `POST /preview-video` held the
connection for 2m36s while three zones were stocked out and a fallback
VM booted — Cloudflare cuts browser connections at ~100s, so the UI
never saw the (successful!) response.

### Backend
- `POST /api/review/{job_id}/preview-video` now returns `{"status":
"generating", "preview_hash"}` immediately after the ASS subtitles are
uploaded; encoding runs in a background asyncio task (established
pattern in this file): GCE encode → local render fallback → GCS error
marker (`previews/{hash}.error.json`) if both fail
- Cache short-circuit: the preview hash is deterministic over the
correction data, so an identical retry returns the existing mp4
instantly as `{"status": "success"}`
- New `GET /api/review/{job_id}/preview-video/{hash}/status` poll
endpoint — GCS-backed (mp4/error-marker existence), so polls work across
Cloud Run instances
- Blocking prep work (GCS downloads, ASS generation) moved to
`asyncio.to_thread` so it no longer stalls the event loop

### Frontend
- `PreviewVideoSection` polls the status endpoint (3s interval, 5-min
cap), escalating to a "starting up an encoding server — this can take a
couple of minutes" message after 30s
- Fixed the Retry button: it previously reset state without
re-triggering generation (spun forever) and was hardcoded English; now
works via a retry nonce and is translated
- Removed the dead `worker_starting` branch (a status the backend never
returned)
- New i18n keys (`encoding`, `timedOut`, `retry`) + updated
`startingEncoder` translated for all 33 locales

## Testing

- 9 new backend tests: cache-hit, generating + background spawn +
stale-marker cleanup, status endpoint (ready/error/generating),
background task (GCE success / local fallback / error marker)
- 7 new Jest tests for `PreviewVideoSection`: cache hit,
poll-until-ready, transient poll failure, terminal error stops polling,
timeout, Retry re-runs, missing hash
- Full suites green: backend 4093 ✓, karaoke_gen unit 1779 ✓, frontend
Jest 1203 ✓, `tsc --noEmit` no new errors vs main, translation
`--keys-only` validation ✓

@coderabbitai ignore

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 02:14:23 -04:00
Andrew Beveridge ☄️andClaude Fable 5 f01213f5cb Fully-auto review for confident jobs: review_mode framework + auto-approval scorer/executor + replay tool (v0.202.0) (#947)
## Summary

Ships the **fully-automated review framework**: jobs now default to
`review_mode="auto"` — when the auto-approval scorer is fully confident
on BOTH axes, the combined review screens are skipped entirely and the
job renders straight through. Everything else falls back to human review
exactly as before.

**The confident class (deliberately narrow to start, ~5% of jobs
expected):**
- **Lyrics**: synced reference present, ≥90-99% anchor coverage, and
every gap word covered by the pre-generated AI auto-correct suggestions
(which the executor applies server-side — a faithful port of the review
UI's on-load auto-apply, including conflict-group resolution) — OR zero
gaps outright.
- **Backing vocals**: non-subjective only — no audible backing content →
clean instrumental.
- **Never-auto gates**: vocalization sections (da-da-dun/woo-woo — P3),
phantom/absurd-duration lines (P8), too-few-words, no/unsynced
reference, errored backing analysis.

**Calibrated against a 20-job human-review corpus** (all recent admin
reviews replayed + annotated): safety 100% (every job that truly needed
a human stays in review), lyrics-auto 3/20, overall-auto 1/20.

## How it works

- `screens_worker` (pre-AWAITING_REVIEW) and `audio_worker` (post-stems,
for the audio-lags-lyrics ordering) both call
`maybe_auto_complete_review()`. Every job gets a verdict recorded in
`processing_metadata.auto_approval` (shadow data keeps accumulating for
calibration); enforcement additionally requires: flag on +
`review_mode="auto"` + not made-for-you + no existing/custom
instrumental + audio complete.
- Enforce path mirrors a human "Complete Review": apply cached AI
suggestions → sanity checks → `corrections_updated.json` →
`instrumental_selection="clean"` → clear progress keys →
`GENERATING_SCREENS→REVIEW_COMPLETE` (new legal edge; no review token or
"ready for review" notification is ever issued) → trigger render worker.
- **Fail-safe everywhere**: stale suggestions, duplicate-word artifacts
(P1 self-conflict signature), state changed mid-enforce (human opened
editor), any exception → normal human review. Auto-approval can never
fail a job.
- Kill switch: `AUTO_APPROVAL_ENFORCE_ENABLED=false` (scoring
continues). Per-job: `review_mode="always_review"` (admin PATCH,
validated).
- Excluded from enforcement (still shadow-scored): made-for-you orders
(human QC is part of that product), custom-instrumental jobs.

## Also in this PR (sessions 1-3 of the initiative)

- **Review replay tool** (admin-only, prod-inert): `?replay=1` reopens
the real lyrics/instrumental review UIs read-only for completed jobs —
queue nav, Post-AI/Final toggle, edit-log action panel, dev-only audio
byte-proxy (env-gated `REVIEW_AUDIO_PROXY`, path-anchored). This is what
produced the calibration corpus.
- `auto_approval` service package: scorer (anchor/gap/AI-coverage
signals + P3/P8 gate detectors), apply engine, executor, lyrics-diff,
offline capture script.

## Testing

- 100+ new unit tests across scorer/apply/executor/replay routes; full
backend suite 4000+ green locally (8 pre-existing emulator failures
reproduce identically on pristine `main` — local-env only, green in CI).
Frontend: 1196 Jest tests green.
- Scorer validated read-only against the 20 real prod jobs in the
private calibration corpus.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-27 03:07:33 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 79b7c80264 fix(e2e): fill Stripe Checkout name + ZIP fields (daily E2E false alarm) (#945)
## Problem

The daily **E2E Daily Test — Stage 1: Credit Purchase** (run #146) fired
the Discord alert *"🚨 Payment flow is broken. Customers may not be
receiving credits."* on all 3 retries.

This was **test drift, not a production outage.** Stripe's hosted
Checkout now renders **required** *Name on card* and *ZIP code* fields,
but the test helper's fill locators no longer matched their current
accessible names, so both were left blank. Stripe blocked the "Pay"
click (`Please provide the name on your card` / `Your ZIP code is
invalid`), the page never redirected, and the 60s `waitForURL` timed
out.

Root cause confirmed from the failed run's `error-context.md` +
`test-failed-1.png` (both validation errors visible on the stuck
Checkout page). Prod `/api/health` was healthy throughout, and real
customers fill these fields themselves — so checkout is unaffected.

## Fix (`frontend/e2e/helpers/stripe-checkout.ts`, test-only)

- **Name** locator now matches `/name on card|cardholder name/i`,
placeholder `First and last name`, and
`[data-elements-stable-field-name="billingName"]`.
- **ZIP** locator drops the broken `^zip$` anchor (the accessible name
is "ZIP code") → `/zip|postal code/i`.
- Bumped the too-short 2s field-search timeouts to 8s; added WARNING
logs when a field isn't found.
- Defaulted the cardholder name so a missing/empty secret can't silently
reblank it.

## Verification

Ran `credit-purchase-real.spec.ts` against **production with a real $3
charge**: checkout completed, redirected to **"Payment Successful · 2
credits available"**, and the *"1 credits added"* confirmation email
arrived. Old locator regexes tested `false` against the real snapshot
strings; new ones test `true`. Typecheck clean. CodeRabbit local review:
no findings.

> Note: a ~600s "Test timeout exceeded" seen locally *after* the body
passes is an environmental macOS teardown quirk (production config uses
`trace:'on'`+`video:'on'`), reproducible with a bare navigate-and-close
test — it does not occur on CI's Ubuntu runners.

@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-26 12:38:31 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 714f3d2ae6 fix: append-after-last segment crash + firestore backup same-day retry collision (#944)
Fixes two independent production issues flagged overnight (2026-08-25).

## 1. Lyrics review crash — `TypeError: Cannot read properties of
undefined (reading 'start_time')`
Error-monitor alert: `frontend` / `onAddSegmentAfter`. Clicking **"Add
segment after"** on the *last* segment calls `addSegmentBefore(data,
beforeIndex)` with `beforeIndex === corrected_segments.length`, so
`corrected_segments[beforeIndex]` is `undefined` and reading
`.start_time` throws.

**Fix** (`frontend/lib/lyrics-review/utils/segmentOperations.ts`): when
`beforeIndex` points past the end (append case), anchor the new
segment's timing/singer off the *previous* segment — start at its
`end_time` (or `0` for an empty list) — instead of dereferencing
`undefined`.

## 2. Nightly backup FAILED — `Firestore: 400 Path already exists`
`export_documents` refuses to write into an output prefix that already
contains an export. The backup Cloud Function returns HTTP 500 if *any*
step fails, so Cloud Scheduler retries the whole function — and the
retry collided with the earlier run's already-written
`firestore/{date}/…overall_export_metadata`. The existing
`_clear_prior_exports` runs *after* export and deliberately keeps
today's, so it never resolved a same-day collision.

**Fix** (`infrastructure/functions/backup_to_aws/firestore_export.py`):
new `_clear_target_prefix()` deletes any leftover `firestore/{date}/`
**before** exporting, making the export idempotent across same-day
retries.

## Tests
- `segmentOperations.test.ts`: append-after-last (`beforeIndex ===
length`) + append-into-empty — 13 passed
- `test_firestore_export.py`: asserts the stale same-day export is
deleted before `export_documents` runs — 5 passed

Version bumped `0.199.4 → 0.199.5`.

Reviewed locally with CodeRabbit CLI (no 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-25 17:47:01 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 156d4369f9 Tenant bulk upload: folder pick + LLM pairing + review table + resumable uploads (v0.200.0) (#943)
## Summary

Adds a **Bulk** mode to tenant portals (frog #3, Vocal Star ask): drop a
folder of tracks, automation pairs Mixed vs Instrumental audio and
extracts Artist/Title from filenames, the operator reviews/fixes an
editable table, then submits all as jobs — with uploads that survive
slow/flaky connections.

### Bulk mode
- `POST /api/tenant/bulk/analyze` — authed, gated on new
`TenantFeatures.bulk_upload` (default on), cap 100 audio files. Regex
fast path for the `S####-1/-2 … Guide/BV/Instru` convention +
Vertex-Gemini pass for leftovers
(`backend/services/tenant_bulk/analyze.py`), regex-only fallback if the
model errors. Pure analysis — filenames only, no state written.
- Label parsing: STRONG labels (guide/instru/bv/backing vocals) override
the `-1`/`-2` slot (surfaces the real-world `S1102-2 … Guide` anomaly as
mixed-only unpaired); WEAK words (Off/Lead/Vocals/Karaoke) stay in the
title unless bracketed.
- `TenantBulkFlow.tsx`: folder/file pick → editable review table
(reassignable Mixed/Instrumental dropdowns, warnings strip,
low-confidence cautions) → bounded-concurrency submit reusing the tenant
single-submit sequence. Mixed-only rows blocked + flagged. Jobs stamped
`state_data.batch_id` + `created_from='tenant-bulk'`.

### Resilient uploads (opt-in `upload_mode: "resumable"`)
- Backend returns **GCS resumable session URIs** (created server-side
with the caller's Origin → GCS answers session CORS itself; **no bucket
CORS changes**). Signed PUT stays the default for all existing clients.
- `frontend/lib/resumable-upload.ts` (dependency-free): 256KiB-aligned
adaptive chunks, always-query-offset resume (no persisted byte ever
re-sent), stall detection instead of hard timeouts, backoff+jitter cut
short by online/visibility events, waiting-offline pause, EWMA
throughput + per-row ETA, non-advancing-308 loop guard.
- `frontend/lib/upload-recovery.ts`: IndexedDB persistence → after a
reload/crash a "Resume unfinished batch?" banner lets the operator
re-pick the folder and every upload resumes from its server-side offset
against the same jobs (never duplicates).

### Tests
- Backend: 26 new (real Bulk-Batch-1 fixture incl. S1102 anomaly,
label-in-title regressions, endpoint auth/feature/cap gates, upload_mode
contract)
- Frontend: 22 new (engine chunk choreography/offset recovery/permanent
errors/retry caps; component resumable routing, re-pick recovery,
retry-no-duplicate)
- Full suite green: backend (incl. emulator) + 1194 frontend
- Prod E2E extension of `tenant-happy-path` is a documented follow-up
(needs this deployed first)

### Docs
- `docs/API.md`: new endpoint + `upload_mode`/`batch_id` fields
- Design + decision record: workspace
`docs/archive/2026-08-25-tenant-bulk-upload-plan.md`

Local CodeRabbit review: 3 completed rounds on this branch, all 9
findings 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-25 17:10:07 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 ed20281ca0 Tenant flow: auto-reset submit form (2s) + "Complete Track" CTA when no instrumental review (#942)
Two tenant-flow streamlining items Andrew raised while validating the
Vocal Star portal (frog #3).

## 1. Auto-reset the Submit form ~2s after success
After a track submits, `TenantJobFlow` shows the confirmation briefly
then auto-returns to a blank form (~2s) so operators can submit one
track after another quickly. The "Submit Another" button stays for
anyone who wants to reset sooner.

## 2. "Complete Track" CTA when there's no instrumental review
Tenant / uploaded-instrumental jobs skip the instrumental-review step,
so the lyrics-review preview modal's CTA "Proceed to Instrumental
Review" was misleading. It now reads **"Complete Track"** whenever the
review completes directly — driven by the existing
`hasExistingInstrumental` signal via a new `completesReview` prop on
`ReviewChangesModal`. Consumer jobs that DO have an instrumental step
are unchanged.

## Details
- Updated the tenant prod E2E to accept either CTA label (`/complete
track|proceed to instrumental/i`) so it's deploy-safe across the
transition.
- Added a `ReviewChangesModal` test for the new label; existing tests
unchanged (default `completesReview=false`).
- New `completeTrack` i18n key translated to all 33 locales.
- Frontend-only. Version 0.199.3 → 0.199.4.
- The larger **bulk-upload mode** Andrew requested is tracked separately
in BACKLOG (not in this PR).
- Merging this to main also re-triggers the backend deploy (now with the
firestore pin from #941), which will ship #939/#940's still-undeployed
backend changes once a self-hosted runner is available (currently
blocked by Spot preemption).

## Testing
- `ReviewChangesModal` tests: 6/6 pass (incl. new "Complete Track"
case).
- `tsc` clean for all changed files; E2E spec compiles.
- CodeRabbit local review: 0 findings.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-25 01:32:14 -04:00
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 ☄️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 ☄️ 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 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 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
Andrew Beveridge ☄️andClaude Opus 4.8 1b6833b182 fix(jobs): show job/log timestamps in the viewer's local timezone (#907)
## Problem

Job dates on the dashboard displayed the raw UTC wall-clock instead of
the viewer's local time. e.g. a job submitted at ~4:10 PM local (viewer
at UTC-2) showed as `8/14/2026, 6:10:25 PM`.

## Root cause

`created_at` (and timeline/log timestamps) were built from naive
`datetime.utcnow()` and serialized via `model_dump(mode='json')` /
`.isoformat()`, producing ISO strings with **no timezone offset**
(`"2026-08-14T18:10:25.123456"`). Firestore stored them as plain strings
and returned them verbatim. The frontend's `new Date(str)` parses an
offset-less ISO date-time as **local** time, so the UTC value was shown
unconverted — off by the viewer's UTC offset.

## Fix

**Frontend (fixes all existing + new data, no migration):**
- New `parseServerDate()` util in `frontend/lib/utils.ts` — treats
offset-less ISO date-times as UTC (appends `Z`); passes through strings
that already carry `Z`/`±HH:MM`, plus `Date`/epoch inputs.
- Applied at every customer-facing server-timestamp display: `JobCard`
created-at, `JobLogs` timestamps, referral payout dates, and
referral-discount expiry (`BuyCreditsDialog` + dashboard).
- 8 unit tests covering
naive/`Z`/`+00:00`/non-UTC-offset/date-only/epoch/`Date` cases.

**Backend (makes stored timestamps unambiguous going forward):**
- `create_job` and timeline events now use `datetime.now(timezone.utc)`,
so serialized ISO strings carry a `+00:00` offset. Arithmetic consumers
(`job_health_service`) already guard for both naive and aware datetimes.

## Testing
- Backend: 210 targeted tests pass (job_manager / firestore / timeline /
job_health / countdown).
- Frontend: full suite 1108 tests pass (85 suites), including the new
util tests.

## Notes
- `/admin/*` pages (English-only, internal) still use `new Date()`
directly; they benefit from the backend change for new jobs but were
left otherwise untouched as out of scope.
- CodeRabbit local review was rate-limited (free OSS quota), so this PR
intentionally omits `@coderabbitai ignore` to let the bot review.

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 17:40:11 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 84b0683cba fix(audio-search): recover parked jobs — edit + re-search + own-audio fallback (#906)
## Problem

In Bulk Mode (and single jobs), the "Choose audio" dialog was a **hard
dead-end**. When a search returned nothing usable — 0 results, a
transient flacfetch failure, or an auto-picked source that's unusable —
the bulk worker parks the job in `AWAITING_AUDIO_SELECTION` with
**empty** cached results. The dialog then showed "No audio sources
found" with **no retry, no way to edit the title, and no manual
source**, so the user was trapped.

Real-world trigger (batch `4af58968a64a`): two Arctic Monkeys tracks
parked with 0 results (one a transient miss on a common track, one an
over-long title), and three more stuck downloading the **same dead RED
torrent** — all with no path forward.

## What this does

Adds a full recovery path to the shared `AudioSearchDialog` (used by
bulk **and** single jobs):

- **Edit + Search again** — always-available editable artist/title with
a re-search button. Edits apply to the job's search terms *and* display
metadata.
- **Provide your own audio** — paste a YouTube/yt-dlp URL, or upload a
file.
- **Graceful empty state** — a 400 (no cached results) renders as the
empty state with the refine bar, not a red error; real network/5xx
errors still surface.

### Backend (`audio_search.py`) — all guarded to
`AWAITING_AUDIO_SELECTION`, tenant-gated, no new job, no double-charge
(final duration billing reconciles post-download)
- `POST /{job_id}/research` — retry / edit-and-re-search. Empty results
are a normal `200`.
- `POST /{job_id}/provide-url` — YouTube URLs go through the **async**
audio-download worker; generic yt-dlp URLs download inline, bounded by a
timeout (never strands a job).
- `POST /{job_id}/attach-upload-url` + `/attach-upload-complete` —
signed-URL upload of the user's own file (extension allow-list +
traversal-safe; the complete step pins the exact uploaded object).
- Factored the triplicated result serialization into
`_build_result_response`.

## Testing
- 20 backend endpoint tests + 5 frontend dialog tests (all green);
broader audio/jobs sweeps pass.
- i18n: 15 new `audioSearch` keys across all 33 locales.

## Review
Local CodeRabbit review completed (2 cycles, all 6 findings addressed,
final pass 0 findings).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 02:50:53 -04:00