mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-04 17:16:04 +09:00
36b331f3d7411ecf97c05bf15146e83161ab94de
179
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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> |
||
|
|
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> |
||
|
|
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>
|
||
|
|
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>
|
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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>
|
||
|
|
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>
|
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
b389927351 |
fix: surface made-for-you orders on dashboard + deep-link admin email (#900)
## Problem A paid **"Made for you"** Stripe order *does* auto-create a job — the `checkout.session.completed` webhook runs `_handle_made_for_you_order`, which builds the job with the customer email, artist, and title, searches audio, and parks it at `awaiting_audio_selection` for an admin to pick the source. Verified in prod: order for *Kenny Chesney – Burn my Boat* correctly created job `b092648c` within seconds and emailed `madeforyou@nomadkaraoke.com`. But the job was **invisible in practice**, so the operator re-created it by hand (duplicate): 1. **Dashboard hid it.** `/app` filtered out *all* `awaiting_audio_selection` jobs — a filter meant to hide self-service jobs mid-wizard. Made-for-you jobs are created server-side by the webhook with no active wizard session, so they got silently dropped. 2. **Email link went to the page that hides it.** The admin notification's "Open Job" button linked to bare `/app/`. ## Changes - **`firestore_service.py`** — add `made_for_you` + `customer_email` to `SUMMARY_FIELD_PATHS` so the dashboard summary payload carries them. - **`job-status.ts`** — new `shouldShowJobOnDashboard()` helper: hide self-service `awaiting_audio_selection` jobs, but keep `made_for_you` ones visible (their `JobCard` already has an "Open Audio Selection" button). - **`app/[locale]/app/page.tsx`** — use the helper; honor a `?status=` URL param so email links can deep-link to the awaiting-audio-selection queue. - **`email_service.py`** — made-for-you admin "Open Job" link now points to `/app/?admin_token=…&status=awaiting_audio_selection` (HTML + text). - **Docs** — LESSONS-LEARNED entry: server-created jobs must fit dashboard UI assumptions. ## Testing - Backend: `test_routes_jobs.py` summary-projection assertion for `made_for_you`; `test_email_service.py` asserts the deep-link carries both `admin_token` and `status=awaiting_audio_selection` (HTML + text). Affected files: **194 passed, 5 skipped**. - Frontend: `job-status.test.ts` unit tests for `shouldShowJobOnDashboard` (**79 passed**). ESLint clean on changed files. - CodeRabbit local review: **No findings** across all 9 files. ## Notes - No new user-facing strings (email is backend English-only), so no i18n changes needed. - Version bumped `0.192.4 → 0.192.5`. @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
d84a827be3 |
feat(auth): show already-used/expired message upfront on verify page (#871)
@coderabbitai ignore Follow-up to #870. That PR added the "Complete Sign-In" gate so email link-scanners can't burn a magic link before the user clicks. This PR improves the case where the link is **genuinely already used or expired**: instead of showing a "Complete Sign-In" button that only fails when clicked, the verify page now shows the "link expired or already used" message (with one-click resend) **upfront**. ### How it stays scanner-safe The decision uses a **read-only** status probe that does **not** consume the token: - New `GET /api/users/auth/link-status` + `UserService.get_magic_link_status()` return `valid` / `used` / `expired` / `invalid` without mutating the doc (verified by a unit test asserting `update`/`set` are never called). - The verify page calls it on mount: - `valid` → show the **Complete Sign-In** gate (token still spent only on the explicit click). - `used`/`expired`/`invalid` → show the failure UI + resend immediately. - probe **errors** → fall back to the gate, so a transient status-endpoint failure never blocks a user holding a valid link. Because the probe is non-mutating, a scanner rendering the page still can't burn a valid token — consumption remains gated behind the click, exactly as in #870. ### Notes - Reuses existing i18n strings (`pleaseWait`, `verifyingWait`, `linkExpiredOrUsed`) — no new translation keys. - The status endpoint is an unauthenticated read, same trust model as `/auth/verify` (the 256-bit token is the only credential); it reveals only valid/used/expired for a token the caller already holds. ### Testing - **Backend (9):** service returns correct status for valid/used/expired/missing/empty **and does not consume** a valid token; endpoint returns the status and short-circuits empty tokens without hitting Firestore. - **Frontend (8):** valid → gate, no verify on mount; dead link → failure UI upfront with no gate and no verify call; probe-error → gate fallback; resend recovery intact. - Full frontend suite green (1072); backend auth suite green (75); `tsc` + `eslint` clean; CodeRabbit local: 0 findings. - Version `0.190.1 → 0.190.2`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) |
||
|
|
2b258cd8f0 |
fix(auth): gate magic-link verify behind explicit click to survive email scanners (#870)
@coderabbitai ignore ## Problem Magic-link sign-in could fail with **"This link has already been used"** even on a fresh link. Root cause: the verify page (`/auth/verify`) auto-consumed the single-use token on mount via a `useEffect` — **no user gesture** — against the state-mutating `GET /api/users/auth/verify`. Anything that *renders the page and runs its JS* (Gmail/Safe-Browsing link scanners, corporate security proxies) therefore burned the token and created a throwaway session before the real user could click. ### Evidence (user `valhalla.gansett@gmail.com`, 2026-07-03, UTC) Two of his login links were consumed within ~60s of delivery by **Google LLC** IPs (`2607:f8b0…`, Chrome/149 headless). Cloud Run logs show his own click losing an 82ms race for token `_VBC4O…`: | Time | Result | IP | Owner | Browser | |------|--------|----|-------|---------| | 00:56:00.176 | **200 (burned it)** | `2607:f8b0…::12` | Google LLC | Chrome/149 | | 00:56:00.223 | 401 already-used | `2607:f8b0…::7` | Google (2nd edge) | Chrome/149 | | 00:56:00.258 | 401 already-used | `173.245.209.177` | Jacob's VPN | Chrome/148 | He got in only via a third link the scanner happened not to prefetch. Scope check: last 30d, only 2/115 login sessions were consumed from Google IPs, all his — so it's his specific mail/security setup tripping a latent design weakness, not a mass outage. ## Fix The verify page now opens on a **"Complete Sign-In" confirm gate** and spends the token only on an explicit click. Scanners render the page but don't click, so the token survives for the real user (standard magic-link mitigation). - Mount-time effect is now side-effect-free (stores referral code, remembers the token) and does **not** verify. - Verification moved into a `handleConfirm` click handler with a re-entrancy guard against double-clicks. - New i18n strings (`confirmTitle`, `confirmBody`, `confirmButton`) translated to all 33 locales. Note: switching GET→POST alone would **not** help — a JS-executing scanner runs the fetch regardless of method. The user-gesture gate is the robust fix. ## Not in scope The admin one-click login path (`/app?admin_token=…`) auto-verifies the same way and has the same latent exposure, but it's admin-only and low-volume. Flagged in `LESSONS-LEARNED.md` for a follow-up rather than changing that flow's UX here. ## Testing - New unit tests: verify page does **not** call `verifyMagicLink` on mount; verifies only after the "Complete Sign-In" click. Existing resend-recovery tests updated to click through the gate. - Full frontend unit suite green (1070 tests); `tsc` + `eslint` clean; CodeRabbit local review: 0 findings. - Version bumped `0.190.0 → 0.190.1`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) |
||
|
|
d5edaab7d2 |
feat(bulk): compact Single/Bulk toggle in card header (#848)
Moves the Single/Bulk switch from a full-width two-button tab (which wasted vertical space for the ~majority who never bulk-submit) into a subtle segmented control in the top-right of the Create Karaoke Video card header. Content switches via state. Frontend-only. 🤖 Generated with [Claude Code](https://claude.com/claude-code) @coderabbitai ignore Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
feca70674b |
feat: Bulk Mode — submit up to 100 karaoke jobs at once (album or text) (#845)
## Bulk Mode — submit up to 100 karaoke jobs at once
Adds a **Bulk Mode** tab to the job-submission flow so users can make
karaoke versions of a whole album (or a typed list) in one go.
### Two ways in
- **By album** — MusicBrainz artist → album → tracklist.
Live/remix/bonus tracks and songs that already have a community version
on KaraokeNerds start **unticked** (re-tick anything). Auto-picks the
canonical edition, with an edition switcher.
- **By text** — up to 100 artist/title rows, each with a
community-version availability badge.
### Auto + review-queue model
Batch settings (auto-pick lossless / public-private / skip audio edit /
skip customization) drive auto-completion. The server runs each audio
search and **auto-selects only a confident lossless ("tier 1") match**;
everything else is parked in the existing `AWAITING_AUDIO_SELECTION`
state and surfaced as a review queue (reusing the existing
`AudioSearchDialog`). A popular full-FLAC album with all toggles on =
zero further prompts; the tab can be closed (searches run as a Cloud Run
Job).
### Credits
Gated upfront: requires `credits >= number_of_songs` (1/song minimum)
before any job is created; admins bypass. Duration deltas for long
tracks are charged per-song during processing as today.
### Backend
- `POST /api/bulk/submit`, `GET /api/bulk/{batch_id}`, `GET
/api/bulk/album/{artists,albums,tracklist}`, `POST
/api/bulk/availability`
- `bulk_search_worker` Cloud Run Job (`infrastructure/`:
`bulk-search-job`) — search → tier-1 auto-select (with duration-delta
charge) or park; per-job crash isolation; idempotent on retry
(charge_pending guard prevents double-charge)
- New `musicbrainz_service` (release lookup + extras detection); reuses
existing `karaokenerds_service` scraper (batch helper) for availability
— **no karaoke-decide change** (it has the `is_community` flag matching
"community-created"; see design doc)
- `pick_auto_selection` ports the frontend tier-1 confidence rule to the
backend (parity test)
### Frontend
- `components/job/bulk/*` (album/text modes, batch settings, submit bar,
batch progress + review queue); api client + types; 33-locale i18n
### Testing
- 40 new backend tests (foundations, MusicBrainz, lookup routes, submit
credit gate, search worker auto/park + credit math, progress) + frontend
Jest for the default-selection and credit-gate helpers
- Safe production E2E smoke
(`frontend/e2e/production/bulk-mode.spec.ts`) — read-only lookups + gate
rejection, does not spawn real jobs
- Full backend suite green (3588 passed); frontend typechecks clean (no
new errors)
### Deploy notes
- **Requires `pulumi up`** to create the `bulk-search-job` Cloud Run Job
before submit works in prod.
- Design + plan: `docs/archive/2026-06-18-bulk-mode-design.md`,
`-plan.md`
Docs: `docs/API.md` § Bulk Mode, `docs/LESSONS-LEARNED.md`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
@coderabbitai ignore
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
||
|
|
a319bf206a |
feat(lyrics-review): show song artist + title in header (#801)
## Summary
The Lyrics Transcription Review header showed only the static title
"Lyrics Transcription Review". The Instrumental Review header already
displays the song (artist + title). This adds the same song display to
the lyrics review header so reviewers can see which song they're working
on at a glance.
## Changes
- `frontend/app/[locale]/app/jobs/[[...slug]]/client.tsx`: render
`artist - title` (from the existing `job` prop) next to the header
title, mirroring the Instrumental Review pattern
(`InstrumentalSelector.tsx`). Uses `[job.artist,
job.title].filter(Boolean).join(" - ")` so it degrades cleanly when a
field is missing, with `truncate` to protect the layout.
- `pyproject.toml`: version bump 0.175.1 → 0.175.2.
## Testing
- ESLint clean on the changed file.
- `tsc` reports no new errors (the 39 pre-existing errors are all in
unrelated files).
- No new user-facing strings — only renders existing `job` data — so no
i18n/translation changes (won't trip CI's locale-completeness check).
- CodeRabbit reviewed locally (1 minor finding, fixed: cleaner
artist/title join).
## Notes
Display-only, low-risk change. No existing test covers either review
header's artist/title display (the instrumental review precedent has
none either); a meaningful test would require mocking the full lyrics
data-loading lifecycle, so none was added.
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
||
|
|
e806616408 |
fix: idempotent session revoke, error-pattern script crash, mobile header overlap (#798)
## Summary Three independent fixes bundled together: 1. **`revoke_session` idempotency** — stops the recurring `Error revoking session` prod error on `karaoke-backend`. Firestore `document.update()` raises `NotFound` (404) when a session doc is already gone (logged out / expired / cleaned up); logout against an already-absent session now succeeds instead of erroring. 2. **`query-error-patterns.py` crash** — `last_seen`/`first_seen` are stored as ISO-8601 strings in Firestore, but the sort key and `--hours` filter did `float(value)`, raising `ValueError` and breaking the `--json` path that `/prod-investigate` relies on. Added a `_to_epoch()` helper handling datetime objects, ISO strings, and numeric epochs. 3. **Mobile header overlap** — `AppHeader` was `position: fixed` and each consumer cleared it with a hardcoded top padding. On narrow viewports the header wraps to 3 rows (149px on a 412px Pixel), exceeding the 112px offset, hiding the "Create Karaoke Video" heading and the top of the form behind it (worse across locales with longer button labels). Switched `AppHeader` to `position: sticky` (matching the already-working jobs-page header) so content always clears it at any height, and removed the now-redundant magic-number offsets. ## Changes - `backend/services/user_service.py` — catch `google_exceptions.NotFound` in `revoke_session`, return `True` - `backend/tests/test_revoke_session.py` — new unit tests (existing / missing / unexpected-error paths) - `scripts/query-error-patterns.py` — `_to_epoch()` helper for sort + `--hours` filter - `frontend/components/app-header.tsx` — `fixed` → `sticky` - `frontend/app/[locale]/app/page.tsx`, `frontend/app/[locale]/app/referrals/page.tsx` — drop hardcoded top padding - `pyproject.toml` — bump to 0.174.17 ## Testing - [x] Backend tests pass locally (47 passed incl. 3 new `revoke_session` tests) - [x] `query-error-patterns.py --json` and `--hours` verified against live Firestore - [x] Mobile header fix verified in Playwright at 412px (Pixel) and 1280px — overlap eliminated (title moves from 12px behind the header to a clear gap below it) - [x] CodeRabbit CLI review: 0 findings ## Review - [x] Local CodeRabbit review completed - [x] Review feedback addressed (none) @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
fe8430d990 |
fix(admin): allow regen-screens from in_review state + surface errors via toast (#793)
## Summary - Fixes a 400 when regenerating title/end screens for a job the user has opened in the review UI (`in_review` state). - Fixes the root cause behind "click Regenerate Screens → modal just closes, no error": `<Toaster />` was never mounted, so **all** `toast()` calls (success and error) silently no-op'd. ## Changes - **Backend:** add `in_review` to `REGENERATE_SCREENS_ALLOWED_STATES` in `backend/api/routes/admin.py`. The sibling `/restart` endpoint already allows `in_review`; this restores parity. Updated `docs/API.md`. - **Frontend:** mount the shadcn `<Toaster />` (same `@/hooks/use-toast` store) in the root `app/layout.tsx` so admin toasts render app-wide. - **Frontend:** give the regen-screens handlers specific, human-readable failure titles/messages (admin dashboard + compact `AdminJobActions` toolbar). - Version bump `0.174.12` → `0.174.13`. ## Testing - [x] Backend: `tests/unit/test_regenerate_screens.py` — allow-list membership, `in_review` → 200, invalid state → 400, missing job → 404 (4 pass). - [x] Frontend: `AdminJobActions.test.tsx` — error-toast path now covered (5 pass). - [x] CodeRabbit CLI review: 0 findings. - [x] Typecheck: no new errors from these changes (pre-existing errors unrelated). ## Review - [x] CodeRabbit CLI review completed locally - [x] Issues addressed @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
6d52503126 |
fix(auth): one-click magic-link resend on verify failure (#739)
## Summary When a magic-link verify fails (expired or already used), the verify page now shows a one-click button that emails a fresh sign-in link to the address the original token was issued to. Complements the 24h TTL bump from #734 and gives Yahoo recipients (and anyone with deferred mail) a recovery path that doesn't require re-entering their email. ## Why Customer `hojob2002@yahoo.com` is back today reporting "Sign-in failed" despite #734 having extended TTL to 24h two days ago. Investigation showed her job had auto-cancelled at the 48h review timeout while she was burning through expired magic links during Yahoo's deferral window — and the verify failure UX gave her nothing actionable beyond "Go to App". With Postmark approval still pending, this is the cheapest recovery improvement we can ship to help users in the same situation. ## Changes - **Backend** — `POST /api/users/auth/resend-from-token` - Looks up the original token in Firestore, mints a fresh magic link for the same email, and sends it - Carries forward `tenant_id`, `referral_code`, and `device_fingerprint` from the original token - 60-second per-token cooldown stamps `last_resend_at` on the doc; repeat clicks (and email-scanner pre-fetches) within the window report `sent` to the UI without re-emailing - Returns `{status: "sent" | "no_token", masked_email, message}` — `no_token` lets the UI degrade gracefully - **Frontend** — verify page error UI - "Email me a new link" button (with sending spinner) - Success state shows masked destination email - Distinct fallback when backend reports `no_token` - Inline error message on network failure - **Translations** — 33 frontend locales, 33 backend locales (auto-translated, French verb form fixed manually) - **Docs** — `docs/API.md` documents the new endpoint with concrete request/response examples - **Version** — 0.172.5 → 0.172.6 ## Security note The token in the URL is a 32-byte cryptographic secret — only the original email recipient could possess it. Resending to the email already recorded in the magic-link doc (rather than accepting an email from the request body) avoids enumeration and adds no new attack surface; the worst case if a token leaked is inbox spam to the verified address, which is bounded by the 60s cooldown. ## Testing - [x] 9 backend tests in `test_resend_magic_link.py` (token exists / missing / empty / used / no-email / no-email-svc / tenant-context / cooldown-suppresses / cooldown-expires) - [x] 4 frontend Jest tests in `verify-page-resend.test.tsx` (button visible on failure, happy path, no_token fallback, network error) - [x] All 173 existing auth/anti-abuse tests still pass - [x] Type-check clean for the modified frontend files ## Review - [x] Local CodeRabbit review completed; relevant findings (cooldown, French grammar, JSON example validity) addressed in fixup commit - [x] Final CodeRabbit pass returns no findings on this branch's code @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
01010c16d3 |
feat(landing): showcase duet/multi-singer mode on homepage (#731)
## Summary - Adds a full-width **Duet & Multi-Singer Mode** feature card to the landing page features section, with a preview still from the rendered karaoke output showing the colour-coded lyrics (blue Singer 1, pink Singer 2, yellow Both). - Adds a matching full-width card in the "See It In Action" screenshots grid. - Copy + all 32 locale translations generated via `frontend/scripts/translate.py`. - Rebuilds the CLI-shipped bundle in `karaoke_gen/nextjs_frontend/out/` so the local `karaoke-gen` launcher also gets the updated landing page. Follow-up to #730 (multi-singer/duet support shipped in 0.172.1). ## Test plan - [ ] `make test` (frontend unit tests pick up the new strings) - [ ] Frontend E2E smoke still passes - [ ] Visual check on deploy preview: feature card + screenshot render correctly, NEW badge shows, image loads - [ ] Confirm locale fallback still works (no missing translation keys) @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
7268dfd830 |
feat(duet): multi-singer karaoke support + local CLI review fixes (#730)
## Summary
- **New feature:** Multi-singer / duet support. Review UI gains a "Duet
Mode" toggle and a per-segment chip to assign Singer 1 / Singer 2 /
Both. Rendered MP4 shows each singer in their signature color (blue /
pink / yellow), sweeping to a near-white tint of the same hue as each
word is sung.
- **Unplanned but necessary:** ~15 local CLI regression fixes that
landed alongside. The i18n work on `main` (LocaleRedirect, static-export
locale prefixes) silently broke the local `karaoke-gen` CLI review flow;
shipped-with-package `ReviewServer` was also missing several
`/api/review/{jobId}/*` endpoint aliases that the unified frontend
expects. This branch closes all of that so the local flow works
end-to-end again.
Full design spec:
[`docs/archive/2026-04-21-multi-singer-duets-design.md`](./docs/archive/2026-04-21-multi-singer-duets-design.md).
Implementation plan:
[`docs/archive/2026-04-21-multi-singer-duets-plan.md`](./docs/archive/2026-04-21-multi-singer-duets-plan.md).
## Changes — Duet Feature
**Backend**
- `Word.singer` / `LyricsSegment.singer` optional fields (`SingerId =
Literal[0,1,2]`, 0=Both)
- `DEFAULT_KARAOKE_STYLE` gains a `singers` block with per-singer colors
(unhighlighted = signature color, highlighted = near-white hue tint)
- `CDG_DUET_SINGERS` palette constant (+ `build_cdg_lyrics` helper —
wired into the render flow but not yet fed into `CDGGenerator`'s TOML
builder; follow-up tracked in `docs/LESSONS-LEARNED.md`)
- `ass/style.py` gains `build_karaoke_styles` factory that emits one ASS
style per singer in use
- `LyricsLine` / `LyricsScreen` / `SubtitlesGenerator` /
`SegmentResizer` all forward segment + word singer fields through the
render chain (several bugs where rebuilds silently dropped the field
were fixed)
- `is_duet` flag persisted in review-session `state_data` (cloud) and
captured by the local `ReviewServer` with a latch-up-only semantic on
`complete_review` so InstrumentalSelector can't accidentally downgrade
it
- `CorrectionOperations.generate_preview_video` threads `is_duet` into
the inner `preview_config`
- `render_video_worker` reads `is_duet` from state_data and propagates
through `OutputGenerator` → `SubtitlesGenerator` (both local + GCE
paths)
**Frontend (`frontend/`, sources only — bundle at
`karaoke_gen/nextjs_frontend/out/` also rebuilt)**
- `SingerId` type + optional `singer` on `Word` / `LyricsSegment` /
`CorrectionData.is_duet`
- `duet.ts` helpers: `cycleSinger`, `resolveSegmentSinger`,
`collectSingersInUse`, `hasMultipleSingers`, `hasWordOverrides`
- `SingerChip` component (click to cycle 1 → 2 → Both, shows `*` when
words have overrides)
- `Header` "Duet Mode" toggle (opt-in, hides chip column when off)
- `TranscriptionView` renders chip + subtle row-tint gradient when duet
is on
- `LyricsAnalyzer` manages `isDuet` state, includes it in save payloads
- `segmentOperations.ts` extends split/merge/addBefore/delete with
singer-inheritance rules (including the tricky implicit-vs-explicit
singer case)
- Keyboard shortcuts `1` / `2` / `B` on a focused segment
- `InstrumentalSelector` falls back to `hasMultipleSingers(segments)`
when `correctionData.is_duet` is missing
- Auto-enable duet on session-restore when restored data shows
multi-singer evidence
- `lyricsReview.duet.*` namespace added to `frontend/messages/en.json`
and auto-translated to all 32 other locales
**i18n**
- Every new user-visible string goes through `next-intl`; the
translation pipeline ran for each en.json change
- Backend new error strings added to
`backend/translations/{en,es,de}.json` and tracked via
`.en-snapshot.json`
## Changes — Local CLI Review Regression Fixes
These were uncovered while trying to manually validate the duet feature
end-to-end. They land in this PR because blocking validation would have
blocked the feature.
- `ReviewServer` now serves the `/{locale}/app/jobs/local/review` (and
broader `/{locale}/app/...`) paths that `LocaleRedirect` unconditionally
bounces to — discovers valid locales from the frontend build
- Added missing `/api/review/{jobId}/...` aliases: `search-lyrics` (new
handler using `CorrectionOperations.search_lyrics_sources`),
`add-lyrics`, `handlers` (POST, matching cloud), `audio/{stem-or-hash}`
(dispatches stems vs audio-by-hash), `instrumental-analysis`,
`waveform-data`, `v1/annotations`, `sessions` stubs
- Review-session history persistence added (external session)
- `job-router-routes.ts` now parses locale-prefixed pathnames so
`/en/app/jobs/local/instrumental` renders the InstrumentalSelector
instead of the lyrics review fallback
- Test-mock signatures updated for the `run_combined_review` 3-tuple
return
## Testing
- [x] Unit tests pass: **1606 package tests + 3002 backend tests + 848
frontend tests**, all green. Coverage: 69.29% (≥69% gate)
- [x] Integration tests pass (including new end-to-end multi-singer
fixture tests)
- [x] Playwright production E2E spec compiles
(`frontend/e2e/production/duet-review.spec.ts`)
- [x] Manual validation done end-to-end on Lady Gaga × Bradley Cooper —
"Shallow (145s duet clip)" — full pipeline produces a proper
duet-rendered MP4 with three per-singer ASS styles tagged correctly
against dialogue lines (6 Singer 1, 16 Singer 2, 4 Both across this
clip). Checked-in fixture at `tests/data/Shallow-Duet-145.ogg`.
- [ ] Manual validation against a second track with dense
call-and-response (spec listed Eminem × Rihanna "Love the Way You Lie")
— not done this PR; can follow up after merge if anything surprising
surfaces
- [ ] End-to-end CDG duet output — still deferred (see Known Follow-Ups)
## Review
- [x] Local code-review done via `feature-dev:code-reviewer` agent
(CodeRabbit CLI fell over on the 3605-file bundle rebuild commit)
- [x] Two findings addressed in commit `da3004ea`: handlers HTTP method,
mergeSegment implicit-singer case
@coderabbitai ignore
## Known Follow-Ups
- `build_cdg_lyrics` helper is implemented and unit-tested but
`CDGGenerator` still constructs its TOML config directly rather than via
`SettingsLyric`. CDG output from duet jobs renders in solo colors today.
Documented in `docs/LESSONS-LEARNED.md`; not required for the MP4/ASS
path which is the feature's primary surface.
- Cloud `complete_review` overwrites `is_duet` in state_data
unconditionally (local server has latch-only semantics). In practice the
frontend's `hasMultipleSingers` fallback in `InstrumentalSelector` keeps
this consistent, but the cloud could gain the same latch for parity.
## Version
Bumped `pyproject.toml` from `0.171.0` → `0.171.1`.
---
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
4b1fd68b14 |
fix(frontend): crash reporting covers admin routes (move to root layout) (#728)
@coderabbitai ignore Follow-up to #725 / #726 — found during post-deploy verification. Test-throwing from \`/admin/crash-test\` showed the default Next.js "Application error" screen instead of the CrashReport card, and no pattern landed in Firestore. Root cause: the error-handling infrastructure was scoped to \`app/[locale]/\`, so routes outside that tree (\`/admin/*\`) had no coverage. ## Fix - Move \`ClientErrorInit\` mount from \`app/[locale]/layout.tsx\` to \`app/layout.tsx\` (root). \`DefaultIntlProvider\` at root already provides \`crashReport\` translations for admin pages. - Drop the \`locale\` prop from \`ClientErrorInit\`; \`client-error-setup\` now auto-detects locale from \`window.location.pathname\` (first segment, whitelisted against known locales, falls back to \`"en"\`). - Add \`app/error.tsx\` and \`app/global-error.tsx\` at root — any uncaught React error anywhere in the app now renders the CrashReport card. - Remove the redundant \`app/[locale]/error.tsx\` and \`global-error.tsx\` (root covers them; Next.js picks the closest boundary, so removing avoids duplication). ## Tests 20/20 frontend unit tests pass. Build emits \`out/admin/crash-test/\` correctly. ## Test plan - [ ] Deploy, visit \`https://gen.nomadkaraoke.com/admin/crash-test/\` as admin. - [ ] Click "Render-time throw" → expect the CrashReport card (not the default Next.js screen). - [ ] Click "Async throw" + "Unhandled rejection" → expect two new \`service=frontend\` patterns in Firestore. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
983c5eb4c0 |
fix(admin): rename crash-test folder (underscore was blocking route) (#726)
@coderabbitai ignore Follow-up to #725. Verified in prod that \`/admin/_crash-test/\` returns 404 because Next.js excludes underscore-prefixed folders from routing (they're treated as private/internal, alongside \`_app\`, \`_document\`, etc.). Confirmed by inspecting \`frontend/out/admin/\` locally: the \`_crash-test\` directory is not emitted by the static export. Rename fixes it — route is now \`/admin/crash-test/\`. ## Test plan - [ ] Deploy, visit \`https://gen.nomadkaraoke.com/admin/crash-test/\` as admin — expect the three-button page. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
6445864534 |
feat: frontend crash reporting → Discord alerts + auto cache bust (#725)
@coderabbitai ignore ## Summary Gives us long-term peace of mind that frontend errors never reach users silently. Every client-side crash is captured, shown to the user with useful debug info, reported to the backend, alerted via the existing Discord error channel, and — critically — after a fix ships, affected users pick it up automatically. ## What this does - **Backend endpoint** `POST /api/client-errors` — normalises inbound reports and upserts into the same `error_patterns` Firestore collection the backend already uses. No new Discord wiring needed: `service="frontend"` patterns flow through the existing error-monitor Cloud Run Job → Discord pipeline. - **Three capture layers on the frontend**: - Global `window.onerror` + `unhandledrejection` listeners (mounted once per tab via `ClientErrorInit` in the locale layout) - Next.js App Router `error.tsx` (per-locale) + `global-error.tsx` (last-resort root) - React `CrashReportBoundary` wrapping `LyricsReviewWrapper` + `InstrumentalReviewWrapper` so a crash there renders in place rather than white-screening the route - **User-facing `CrashReport` card** — shows error name/message + collapsible stack + debug info + build SHA; auto-sends on mount (catches bugs in the wild without user action); has Copy / Send again / Try again / Back buttons. - **Version-aware cache busting** so the next bug I fix actually reaches affected users: - `public/version.json` emitted at build time via a new `prebuild` hook. - `isStale()` compares the compiled `NEXT_PUBLIC_COMMIT_SHA` against the live `/version.json`. - `ChunkLoadError` in the global handlers triggers a hard reload (unregisters SWs, clears caches, navigates with `?_v=<sha>` query-string) behind a 60 s circuit breaker to prevent reload loops. - `CrashReport` shows a prominent "A newer version is available — Update now" banner when stale; demotes "Try again" to secondary in that case. - Ambient 10-minute poll dispatches a `karaoke:stale-version` CustomEvent (no auto-reload ambient — only on crash). - **Admin `/admin/_crash-test` page** — three buttons that fire async throw / unhandled rejection / render-time throw, for post-deploy pipeline verification. - **Rate limiting** on the endpoint: 60/min per IP sliding window, plus pattern-hash dedup collapsing viral bugs to a single pattern. - **Privacy**: URL query strings + fragments stripped; user email only sent if authenticated; no cookies / localStorage / form-value capture. - **i18n**: `crashReport` namespace in `en.json` translated into all 32 locales. Reuses existing env var `NEXT_PUBLIC_COMMIT_SHA` — no new build config. ## Review & verification - 49 Jest suites / 800 tests pass (`make test`). - New unit tests: `crash-reporter.test.ts`, `CrashReport.test.tsx`, `CrashReportBoundary.test.tsx`, `version-check.test.ts`, `test_frontend_ingestion.py`, `test_client_errors.py` — all green. - Implemented task-by-task via subagent-driven workflow with spec + code quality review per task (see `docs/archive/2026-04-19-frontend-crash-reporting-plan.md`). - E2E Playwright test deferred — the admin crash-test page covers manual post-deploy verification. ## Test plan - [ ] Deploy to prod. - [ ] Visit `https://gen.nomadkaraoke.com/admin/_crash-test` as admin; click each of the three buttons. - [ ] Confirm a Discord alert arrives in the error channel (may take up to ~15 min per the monitor Cloud Run schedule). - [ ] Verify Firestore `error_patterns` contains 3 new docs with `service="frontend"`. - [ ] In a separate browser session already open to the app, simulate a stale-bundle scenario (edit `public/version.json` on the CDN, or use an older tab after a new deploy) — confirm `CrashReport` shows the "Update now" banner if an error is thrown. - [ ] Test the original Firefox Android bug (if it reproduces) and verify the crash now lands in Discord with a usable stack trace. ## Follow-ups - Source-map upload for readable production stacks (`Task 15` in the plan). - Consider forwarding the `source` payload field into `PatternData.sample_message` if finer-grained Discord triage (`window.onerror` vs `unhandledrejection` vs boundary) becomes valuable. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
3fac565c76 |
feat: referral flyer customisation with tabbed QR/flyer dialog (#708)
## Summary - Expand the QR Code Generator dialog into a tabbed **Referral Tools** dialog with **QR Code** and **Printable Flyer** tabs - Add a live flyer preview with extensive customisation: colors, text overrides, section visibility, custom branding, and print layout (1/2/4 per page) - Client-side export to PDF, HTML, and PNG (replaces server-side flyer generation) - Preset themes (Light/Dark) with save/load custom presets via localStorage ## Changes - **New components:** `ReferralToolsDialog`, `QRCodeTab`, `FlyerTab`, `FlyerPreview`, `FlyerControls`, `FlyerExport`, `flyer-presets` - **Removed:** `QRCodeDialog` (replaced by `ReferralToolsDialog`) - **Modified:** `ReferralDashboard.tsx`, `admin/referrals/page.tsx` (import updates) - **Dependencies:** Added `html2canvas`, `jspdf` for client-side export - **i18n:** 30+ new translation keys across all 33 locales ## Testing - [x] 32 referral-specific tests pass (presets, export, dialog interaction) - [x] 743/743 total frontend tests pass - [x] TypeScript compilation clean (no new errors) - [x] CodeRabbit CLI review completed locally, feedback addressed ## Review - [x] Local CodeRabbit review completed (10 findings, 6 fixed, 4 skipped as nitpicks) - [x] Review feedback addressed in dedicated commit @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
43900921a5 |
fix: validate auth token on referral interstitial (#707)
## Summary - Users with stale/expired tokens in localStorage were shown "Go to App" instead of the magic link email form on referral interstitial pages (`/r/<code>`) - Now validates the token against `/api/users/me` before deciding which UI to show - Clears stale tokens so future visits work correctly ## Root cause The interstitial checked `getAccessToken()` (localStorage only) which returns non-null even for expired tokens. A user who had previously visited the app would always see "Go to App" even if their session was long expired. ## Test plan - [x] Frontend build passes - [x] All 722 tests pass - [ ] Manual: visit `/r/<code>` with a stale token in localStorage → should see email form - [ ] Manual: visit `/r/<code>` while genuinely logged in → should see "Go to App" @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
77f64a52d7 |
feat: mobile-friendly two-row header (#704)
## Summary - Adds a second row to the app header on mobile (< 640px) so action buttons show text labels instead of cryptic icons - Row 1: logo + title + auth/login status - Row 2: refresh, referrals, help, language switcher, theme toggle — all with visible text labels - Desktop layout (≥ 640px) is completely unchanged - Extracted HelpDropdown and ThemeToggle into small sub-components to avoid JSX duplication ## Test plan - [x] All 721 existing tests pass - [ ] Visual check on mobile viewport (375px, 390px) — two rows visible with text labels - [ ] Visual check on desktop — single row, unchanged from before - [ ] Check dashboard page (with Refresh/Admin children) and referrals page (no children) - [ ] Check logged-in vs logged-out states - [ ] Verify language switcher dropdown positions correctly from row 2 @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
1c1c17f9ab |
fix: Stripe Connect redirect and referral payout management (#702)
## Summary - **Fix broken Stripe Connect return URL** — was redirecting to `/app?tab=referrals` (the dashboard, which ignores that param) instead of `/app/referrals`. Users were ending up logged out at `/en/` after completing Stripe onboarding. - **Add locale redirect fallback** for `/app/referrals` route so Stripe can redirect without locale prefix - **Add Connect account status and management** — new backend endpoints for account status, Express dashboard login, and re-onboarding. Frontend shows payouts enabled/pending status, "Manage Payouts" and "Update Bank Account" buttons. - **Improve Connect button UX** — loading spinner + note that user will be redirected to Stripe, error feedback for all actions ## Test plan - [x] Backend: 48 referral tests + 7 Stripe tests pass - [x] Frontend: 721 tests pass - [x] CodeRabbit review: 3 issues found and fixed - [ ] Manual: verify Connect flow with test account after deploy - [ ] Manual: verify return redirect lands on referrals page with success banner @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
3a1fd08c96 |
fix: apply discount dropdown, credit pricing, checkout state (#700)
## Summary - **Apply Discount modal**: referral code dropdown was empty — `loadReferralLinks()` was in `onOpenChange` which doesn't fire for controlled Dialog open prop changes. Moved to button onClick. Also replaced `Select` with searchable `Combobox` (Popover+Command) to scale with many referral codes. - **Buy Credits dialog**: discounted prices showed contradictory values (e.g. "$9" and "$8.50/video") because `formatPrice` used `toFixed(0)` rounding. Now shows cents when price isn't a whole dollar. - **Buy Credits dialog**: "Redirecting to payment..." persisted after closing/reopening because `checkoutLoading` wasn't reset on dialog open. ## Test plan - [x] Build passes - [x] 721 tests pass - [x] CodeRabbit: no findings - [ ] Manually verify Apply Discount modal loads and filters referral codes - [ ] Manually verify Buy Credits shows correct discounted prices (e.g. $8.50 not $9) - [ ] Manually verify closing/reopening Buy Credits resets checkout button state @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
8ef587e7e3 |
feat(referral): fix discount checkout bug, show discounted prices, admin UX (#699)
## Summary - **Fix**: Referral discount silently dropped at Stripe checkout due to timezone-aware vs naive datetime comparison (same bug previously fixed in `_build_user_public` but missed in `should_apply_discount`) - **Admin UX**: Replace free-text referral code input in Apply Discount dialog with dropdown of active codes (prevents typos/nonexistent codes) - **Buy Credits modal**: Show discounted prices with strikethrough originals when user has active referral discount - **Dashboard banner**: Make referral discount banner dismissable (X button, localStorage) - **User menu**: Show "X% discount active" in the dropdown so discount info persists after banner dismissal ## Test plan - [ ] Verify referred user sees discounted prices in Buy Credits modal - [ ] Verify Stripe checkout session includes the coupon (discount actually applied) - [ ] Verify discount banner can be dismissed and stays dismissed on reload - [ ] Verify user menu shows discount status - [ ] Verify admin Apply Discount dialog shows dropdown of active referral codes @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
3a9438f3e4 |
fix(referrals): use nomadkaraoke.com/r/ for QR codes and referral URLs (#698)
## Summary
QR codes and referral link displays were using
`gen.nomadkaraoke.com/r/{code}` which 404s. The `/r/` short URLs live on
`nomadkaraoke.com` (which redirects to gen). Fixes all referral URL
generation in both user dashboard and admin QR dialog.
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
||
|
|
404caa624a |
feat(admin): full QR/flyer dialog on admin referrals page (#697)
## Summary Replace the simple flyer download button on the admin referrals page with the full QRCodeDialog modal — same one users see on their referrals page. Supports customizable QR styles, colors, center logos, and light/dark flyer themes. - Add `onGenerateFlyer` and `flyerFilename` props to `QRCodeDialog` so admin can use the admin flyer endpoint - Wrap dialog in `NextIntlClientProvider` since admin pages don't have the i18n provider ## Test plan - [x] Build passes - [ ] Click QR icon on any referral row → full dialog opens - [ ] Customize QR, generate flyer → downloads PDF for that code @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
19c85ca5b2 |
fix(referrals): DRY shared AppHeader matching dashboard style (#692)
## Summary Follow-up to #691. Fixes issues found in production: - Rewrites `AppHeader` to match the dashboard header style (local SVG logo, fixed position, dark theme, consistent controls) - Dashboard now uses the shared `AppHeader` with page-specific buttons (refresh, admin toggle) passed as children - Removes broken `Logo` component (external PNG URL) and dead `/jobs` link that 404'd - Adds proper top padding on referrals page for the fixed header ## Test plan - [x] Build passes (`next build`) - [x] All 721 tests pass (`make test`) - [ ] Visual check: dashboard header unchanged after refactor - [ ] Visual check: referrals page header now matches dashboard - [ ] Logo loads correctly (local SVG) @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
60c893391e |
feat(referrals): improve UX with header, explainer, vanity URL request, and i18n (#691)
## Summary - Add AppHeader + "Back to Dashboard" nav to referrals page (matches the rest of the app) - Add friendly "How It Works" section explaining the 3-step referral process with dynamic terms - Add vanity URL request flow (opens pre-filled mailto to admin) - Translate entire referrals section to all 32 non-English locales via Gemini pipeline ## Test plan - [x] Build passes (`next build`) - [x] All 721 tests pass (`make test`) - [x] Translation validation — no missing keys across 32 locales - [ ] Visual check: referrals page has consistent header - [ ] Visual check: "How It Works" section shows correct terms - [ ] Visual check: vanity URL request form works (opens email) - [ ] Visual check: non-English locale loads referrals translations @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
e441b854c6 |
feat(referral): marketing flyer PDF generator (#688)
@coderabbitai ignore
## Summary
- **Marketing Flyer Generator**: Print-ready PDF flyers (light + dark
themes) with personalized referral code, discount, and styled QR code
- Server-side rendering via headless Chromium (added to Dockerfile)
- Available from QR Code dialog (user) and admin referrals table (admin)
## Changes
### Backend
- **New:** `flyer_service.py` — Template rendering + headless Chromium
PDF generation
- **New:** `POST /api/referrals/me/flyer` — User flyer endpoint
- **New:** `POST /api/referrals/admin/links/{code}/flyer` — Admin flyer
endpoint
- **New:** Light + dark HTML flyer templates (from kjbox printables)
- **Modified:** `Dockerfile.base` — Added `chromium` package
### Frontend
- **Modified:** `QRCodeDialog.tsx` — Theme picker + Generate Flyer
button, error handling
- **Modified:** Admin referrals page — Flyer button per row
- **New:** `generateFlyer()` API client function (user + admin)
- **i18n:** 5 new flyer-related strings
### Infrastructure
- **Dockerfile.base change** — Adds Chromium (~200MB). Base image
rebuild required.
## Test plan
- [x] 8 backend unit tests (template substitution, validation, Chromium
flags)
- [x] 11 frontend tests (QR dialog + flyer controls)
- [x] 721 total frontend tests passing
- [x] Local Chrome PDF verification (user confirmed)
- [x] Docker container PDF verification (Chromium 146, fonts + gradients
correct)
- [x] End-to-end test with real styled QR code (user confirmed
scannable)
- [ ] Manual: QR dialog → pick theme → Generate Flyer → verify PDF
- [ ] Manual: Admin referrals → flyer button → verify PDF
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
||
|
|
7bf000eb81 |
feat(referral): add duration fields to admin and user referral UIs (#684)
## Summary - Admin edit/create dialogs: now include discount duration and earning duration fields - Admin table: shows durations below rates (e.g. "10% / 20%" with "30d / 365d" below) - User dashboard: new "Link Terms" section showing discount %, discount window, kickback %, earning window @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
817f2aa1bd |
feat(admin): add Apply Discount to user detail page (#681)
## Summary Admins can apply a referral discount to any user from the user detail page — useful for grandfathering existing users when raising prices. ## Changes ### Backend - New endpoint: `POST /api/referrals/admin/apply-discount` — sets discount %, duration, and referral code on any user - `UserDetailResponse` now includes `referred_by_code`, `referral_discount_expires_at`, `referral_code` ### Frontend - "Apply Discount" button on user detail page (next to Add Credits) - Dialog with discount %, duration (days), and referral code inputs - Current discount status shown on user detail page if active ## Usage - Go to Admin → Users → click a user → "Apply Discount" - Set 50% off for 3650 days with code "loyalty" to grandfather a user @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
607c52bed3 |
feat(referral): embed referral code in magic link for cross-device attribution (#680)
## Summary Referral attribution was failing because it relied solely on a browser cookie. If the user opened the magic link email on a different device or browser, the cookie wasn't there and attribution was lost. ## Fix: Triple-redundant referral code delivery The referral code now travels through three independent paths: 1. **Cookie** (`x-referral-code` header) — same device, same browser 2. **Firestore** (magic link token doc) — stored server-side when magic link is sent 3. **URL param** (`&ref=CODE` on the magic link) — travels with the email itself On verification, the backend checks all three and uses the first one found. ## Changes ### Backend - `SendMagicLinkRequest` + `MagicLinkToken` models: added `referral_code` field - `user_service.create_magic_link()`: accepts and stores referral_code - `email_service.send_magic_link()`: appends `&ref=CODE` to URL, adds discount banner to email - `verify_magic_link`: reads referral code from header OR token doc OR URL param ### Frontend - `api.sendMagicLink()`: passes referral_code in request body - Auth store `sendMagicLink`: reads referral cookie and passes it - Verify page: reads `?ref=CODE` from magic link URL and stores cookie before verification ## Testing - 2952 backend tests pass - Frontend build passes @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
3f00b08fb7 |
fix(referral): show display name on interstitial page (#679)
## Summary The interstitial page wasn't showing the affiliate's display name because of a field name mismatch — frontend type had `display_name` but the API returns `referrer_display_name`. ## Changes - `frontend/lib/types.ts` — `ReferralInterstitial.display_name` → `referrer_display_name`, `code` → `referral_code` - `frontend/app/[locale]/r/client.tsx` — Updated references to use `data.referrer_display_name` @coderabbitai ignore Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
af50b53cd8 |
feat(admin): add edit dialog for referral links (#678)
## Summary Adds a pencil icon button on each row in the admin referrals table that opens an edit dialog to modify display name, custom message, discount %, and kickback %. ## Changes - `frontend/app/admin/referrals/page.tsx` — Edit button + dialog with form fields, uses existing `adminApi.updateReferralLink` endpoint @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
1cd747f170 |
fix(referral): compute and display referral discount status for users (#677)
## Summary Three referral UX fixes: 1. **Discount visibility** — Backend now computes `has_active_referral_discount` and returns discount details (percent, expiry, referral code) in all UserPublic responses. Dashboard shows a purple banner with discount info. Buy Credits dialog shows actual percent + expiry. 2. **Existing user attribution** — Removed the `is_first_login` gate. Any user who logs in with a referral code cookie and hasn't been referred yet gets the referral attributed. This means existing users who click a referral link will get the discount. 3. **Interstitial email signup** — Replaced the "Get Started" redirect with an inline email input form. Users enter their email directly on the interstitial page to receive a magic link. Shows "Check your email" confirmation after sending. Already-logged-in users see a "Go to App" CTA instead. ## Changes ### Backend - `backend/api/routes/users.py` — New `_build_user_public()` helper computes discount status. Attribution gate changed from `is_first_login` to `not user.referred_by_code`. - `backend/models/user.py` — Added `referral_discount_percent`, `referral_discount_expires_at`, `referred_by_code` to UserPublic ### Frontend - `frontend/app/[locale]/r/client.tsx` — Full rewrite: email signup form with magic link, three states (form/sent/logged-in) - `frontend/app/[locale]/app/page.tsx` — Referral discount banner on dashboard - `frontend/components/credits/BuyCreditsDialog.tsx` — Actual discount percent + expiry date - `frontend/lib/auth.ts` — Pass through referral fields - `frontend/lib/types.ts` — New referral type fields @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
bb86722008 |
fix(referral): dedicated interstitial page instead of banner overlay (#675)
## Summary Replace the banner overlay (which looked terrible floating over the landing page) with a proper full-screen interstitial page. ## Flow 1. `nomadkaraoke.com/r/bevvy` → Worker redirects to `gen.nomadkaraoke.com/en/r?code=bevvy` 2. Static `/en/r` page loads, reads `?code=` param, fetches referral data from API 3. Full-screen interstitial: gift icon, referrer name, custom message, discount details, "Get Started" CTA 4. User clicks "Get Started" → landing page (referral code already stored in cookie) ## Changes - New: `frontend/app/[locale]/r/page.tsx` + `client.tsx` — dedicated interstitial page - Reverted: `frontend/components/ReferralCapture.tsx` — back to silent cookie-setter (no banner) - Cleaned: `frontend/public/_redirects` — removed broken `:splat` rules Also pushed: `public-website/worker.js` updated to redirect to `/en/r?code=` instead of `/en/?ref=` @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
0353f5890d |
fix: use redirect for /r/CODE referral links instead of dynamic route (#672)
## Summary The previous approach (catch-all `[[...code]]` route) doesn't work with Next.js static export on Cloudflare Pages — dynamic paths 404 because no HTML file exists for them. ## Fix Replace the dynamic route with a simple Cloudflare Pages `_redirects` rule: - `/r/CODE` → `/en/?ref=CODE` (302 redirect) - The `ReferralCapture` component on the landing page already captures `?ref=CODE` and stores it in a cookie This means referral links redirect to the landing page with the code as a query param, which is simpler and fully compatible with static export. ## Tradeoff The custom interstitial page (with referrer name/message) is removed for now. The referral still works — the code gets stored and applied at checkout. The interstitial can be added back later as a component on the landing page that detects `?ref=` and shows the referral info. @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
1154adc150 |
feat(admin): add referral links management page (#670)
## Summary - Add Referrals page to admin dashboard for managing referral links - Stats overview: total links, clicks, signups, earnings - Links table with enable/disable toggle and copy-to-clipboard - Create Vanity Link dialog with custom discount/kickback rates ## Changes - `frontend/app/admin/referrals/page.tsx` — New admin referrals page - `frontend/components/admin/admin-sidebar.tsx` — Added Referrals nav item - `frontend/app/admin/layout.tsx` — Added breadcrumb support - `frontend/lib/api.ts` — Added 3 admin referral API methods ## Testing - [x] Frontend build passes - [x] 710 frontend unit tests pass - [x] No backend changes @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
80cb53f3a2 |
feat: referral link system with discounts and Stripe Connect payouts (#669)
## Summary - Add a referral system where any user gets a shareable link (`/r/CODE`) with a personalized interstitial page - Referred users get a configurable discount (default 10%) on credit purchases for 30 days - Referrers earn a cash kickback (default 20% of revenue) paid out via Stripe Connect at $20 threshold - Admin can create vanity links with custom rates and manage all referral links ## Changes ### Backend - **New models** (`backend/models/referral.py`): ReferralLink, ReferralEarning, ReferralPayout + API request/response models - **New service** (`backend/services/referral_service.py`): Link CRUD, attribution, discount detection, earnings recording, Stripe Connect onboarding, auto-payout - **New routes** (`backend/api/routes/referrals.py`): 7 endpoints — public interstitial, user dashboard, link updates, Connect onboarding, admin vanity/list/update - **Stripe integration**: Coupon creation/lookup, Connect Express accounts, transfers - **Webhook hook**: Referral earnings recorded on credit purchases - **Auth hook**: Referral attribution on first magic link verification via `x-referral-code` header - **User model**: Added referral fields (referral_code, referred_by_code, referred_at, discount_expires_at, stripe_connect_account_id) ### Frontend - **Interstitial page** (`/r/CODE`): Shows referrer's name, custom message, discount details - **Referral dashboard** (`/app/referrals`): Link sharing, stats, earnings, payout history, Stripe Connect CTA - **Discount badge**: Shown in Buy Credits dialog during active referral window - **Referral capture**: Cookie + localStorage via `/r/CODE` route and `?ref=CODE` query param - **Auth integration**: Passes referral code on magic link verification, clears after use - **i18n**: 33 new translation keys in `referrals` namespace ### Documentation - Design spec: `docs/archive/2026-04-04-referral-system-design.md` - Implementation plan: `docs/archive/2026-04-04-referral-system-plan.md` - Updated `docs/README.md` status table and `docs/API.md` with referral endpoints ## Testing - 68 referral-specific tests (models, service, routes) — all passing - 2935 total backend tests — zero regressions - 710 frontend tests — all passing - Covers: link management, attribution, self-referral blocking, discount detection, earnings calculation, payout threshold, edge cases (rounding, zero amounts), all API endpoints ## Review - [x] CodeRabbit CLI review completed locally (11 findings, 7 fixed) - [x] Test review completed (P0/P1 gaps identified and filled) - [x] Docs reviewed and updated @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
ab330a3ed6 |
feat(i18n): scale to 33 languages with RTL support (#666)
## Summary - Scale i18n from 3 languages (en/es/de) to 33 languages - Upgrade translation pipeline: async parallel execution (5 concurrent) + incremental delta detection - Add RTL support (`dir="rtl"`) for Arabic and Hebrew - Replace LanguageSwitcher `<select>` with grouped scrollable dropdown (flags + native names) - RTL CSS audit: convert directional properties to logical equivalents - 30 new frontend translation files (1062 keys each) + 30 backend files (274 keys each) ### New languages Portuguese, French, Japanese, Korean, Chinese, Italian, Dutch, Polish, Turkish, Russian, Thai, Indonesian, Vietnamese, Filipino, Hindi, Arabic, Swedish, Norwegian, Danish, Finnish, Czech, Romanian, Hungarian, Greek, Hebrew, Malay, Ukrainian, Croatian, Slovak, Catalan ## Test plan - [x] `next build` — 285 static pages generated (11 pages x 33 locales - some deduped) - [x] All translation files have 100% key parity - [ ] Post-deploy: verify Japanese, Arabic (RTL), Portuguese render correctly - [ ] Post-deploy: verify LanguageSwitcher shows all 33 options <!-- @coderabbitai ignore --> 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |