mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-05 17:38:25 +09:00
36b331f3d7411ecf97c05bf15146e83161ab94de
39
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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> |
||
|
|
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> |
||
|
|
7a3c1d6683 |
Clearer job status labels: 'Preparing your audio' for uploads + fix raw jobStatus.Processing key (#940)
## Why
Two frontend job-status **label** bugs, both surfaced while manually
driving the Vocal Star tenant flow:
1. **Tenant/upload jobs show "Downloading"** even though the operator
uploaded their own audio — there's nothing to download. (Andrew hit this
on a real job: "it's currently Downloading — what is there to download
though, since I uploaded the files?")
2. **Backlog item — raw i18n key rendered verbatim:** status sometimes
reads `[4/10] jobStatus.Processing`.
Both live in `frontend/lib/job-status.ts`.
## Fixes
**1. "Preparing your audio" for upload-based jobs.** The download stage
reused the consumer "Downloading" label. For jobs with a pre-supplied
instrumental (`existing_instrumental_gcs_path`), the staging stage now
shows **"Preparing your audio"**. Added `existing_instrumental_gcs_path`
to the job-list summary projection (`SUMMARY_FIELD_PATHS`) — it's a
top-level field (no `state_data` prune needed), so the list view can
detect upload jobs.
**2. No more raw `jobStatus.X`.** The "downloading + workers running"
path passed the **literal string `"Processing"`** (not a `jobStatus`
key) as the label, so `t("Processing")` missed and rendered
`jobStatus.Processing`. Now it uses a valid `processing` key, and when
only one parallel worker is reporting (tenant jobs run lyrics only — no
separation), it shows that worker's real status (e.g. "Transcribing
lyrics") instead of a generic label.
## Guardrail
Added a regression test asserting **every label `getJobStep` can emit
exists in `en.json` jobStatus** — so this whole class of raw-key bug
can't recur.
## Testing
- Frontend `job-status.test.ts`: 90/90 pass (new cases: upload-job
relabel, downloading_audio, advance-to-transcribing,
no-relabel-for-normal-jobs, raw-key regression, en.json completeness).
- Backend: new `SUMMARY_FIELD_PATHS` projection guard test.
- New keys `jobStatus.preparingAudio` + `jobStatus.processing`
translated to all 33 locales.
- Version bumped 0.199.2 → 0.199.3.
- CodeRabbit local review: 0 findings.
@coderabbitai ignore
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
||
|
|
0e5a7b60a6 |
fix(frontend): confirm backend unreachable via health probe before showing connectivity banner (#935)
## Summary Slow-but-legitimate page loads (e.g. **first-time instrumental-analysis / lyrics-review loads**, which transcode audio stems server-side via ffmpeg and can run 20–60s) were tripping the stall-based connectivity banner, showing *"We're having trouble reaching our servers"* during a perfectly normal load. **Fix:** a stalled GET now only surfaces the banner once a cheap `GET /api/health` probe confirms the backend is actually unreachable. - When the oldest in-flight GET crosses the 10s stall threshold, `lib/backend-status.ts` fires the probe registered by `lib/api.ts` (`configureHealthProbe`). - Probe answers OK (or no verdict yet) → backend is reachable, the read is just a slow endpoint → **no banner**. - Probe fails or times out (4s, `Promise.race`d so a hung origin can't wedge it — during a Cloud Run recycle the origin *hangs* rather than erroring) → outage confirmed → banner appears (~4s later than before). - Probe re-fires every 10s while a stall persists, so recovery clears the banner even if the original read is still hung. - Dev-override hook and pure stall-based behavior (when no probe is configured) are unchanged. Also bumps version to 0.198.3 and adds an addendum to the 2026-08-22 design doc. ## Testing - Reworked `__tests__/api-fetch.test.ts` stall test for the new confirm-before-banner flow + new test: slow GET with healthy `/api/health` never shows the banner. - New `__tests__/backend-status.test.ts` suite: probe-OK suppression, probe-fail escalation, stale-verdict re-probe + recovery clearing, no-verdict hold-back. - Full `make test` green: 91 suites / 1151 frontend tests + backend suites. @coderabbitai ignore (Local CodeRabbit review completed on this branch — no findings.) 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
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>
|
||
|
|
3d56dd4108 |
fix: connectivity banner only on real read stall (not slowness) (#922)
## Why Follow-up to #921. In prod the connectivity banner was **too sensitive**: 1. It fired during a normal lyrics-review load — the 2.5s "slow request" hint tripped on any request taking >2.5s, even successful ones. 2. The "Preview Video" modal showed **"The server is temporarily unavailable"** — the long-running preview-generation POST (video encode, often >45s) hit apiFetch's blanket 45s hard-timeout and failed, even though the backend was fine. ## What - **`backend-status.ts` — status now derives purely from a real STALL.** It tracks how long the *oldest in-flight tracked read* has been outstanding: `reconnecting` at 10s, `unavailable` at 20s, back to `online` the instant it settles. A read that completes — even a normal-slow 3–5s one — surfaces **nothing**. - **`apiFetch` — GET-only tracking + GET-only hard-timeout.** - Only GETs feed the banner (a page waits on reads during a recycle; long POSTs are legitimately slow). - The 45s hard-timeout backstop applies to **GETs only** — preview/generate/search POSTs run **untimed** to completion, fixing the false "unavailable" error. - New `opts.trackConnectivity: false` lets a known-slow read opt out; `opts.timeoutMs` still time-boxes any call. Retry semantics unchanged (GET-only, never replays a mutation). ## Testing - Rewrote store + apiFetch unit tests for the stall model: POST untracked, POST not hard-timed-out (signal not aborted after 60s), a stalled GET → reconnecting→unavailable→clear, fast failures stay `online`. - Full suite green: **1132 passing**. - Banner rendering re-verified locally. - Local CodeRabbit review: **no findings**. No infra changes in this PR. @coderabbitai ignore Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
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> |
||
|
|
df93eb9f82 |
feat(status): opaque System Status modal + live encoding-worker instance type (#920)
## Summary Two fixes to the **System Status** modal (opened from the version footer): ### 1. Modal was transparent The modal set `backgroundColor: var(--card-bg)` — but `--card-bg` is **defined nowhere** in the codebase (the real vars are `--card` / `--card-border`). An undefined CSS variable makes the property invalid, so the modal fell back to `transparent` and the job list showed through it (see the reported screenshot). Fixed by using defined opaque surfaces: - Dialog shell → `var(--bg)` (`#0f0f0f` dark / `#f8fafc` light) - Service cards → `var(--card)` (`#1a1a1a` dark / `#ffffff` light) This was the only usage of the phantom `var(--card-bg)` anywhere in the frontend. ### 2. Show the currently-live encoding worker Given the recent c4d stockout / multi-instance-family fallback work, admins couldn't see **which** worker was actually serving or its instance type. The live worker is the `active_override` VM when a capacity fallback has routed off the primary, else the c4d blue-green primary. - **Backend** (`/health/system-status`): the admin-only encoder `admin_details` now carries `active_vm`, `active_zone`, `active_machine_type`, and `on_fallback`. The instance type is derived via the existing `infer_machine_type` helper (primary → `c4d-highcpu-32`; fallbacks decoded from the VM-name family token, e.g. `…-fallback-n2c` → `n2-highcpu-32`). - **Frontend**: a new `LiveWorkerSection` on the Encoder card shows the instance type prominently, the serving `VM · zone`, and an amber **"Fallback"** badge + notice when running off the primary due to a stockout. The existing Blue-Green expander is unchanged. ## Changes - `backend/api/routes/health.py` — compute live-worker fields (admin only) - `frontend/components/system-status-modal.tsx` — opaque vars + `LiveWorkerSection` - `frontend/lib/api.ts` — `ServiceStatus.admin_details` new fields - `frontend/messages/*` — 3 new `status` keys translated to all 32 locales ## Testing - `make test` — full suite green (backend 1741+3878+103, frontend 1115 tests / 86 suites) - Added a capacity-fallback path test to `test_system_status_endpoint.py` - Added `frontend/__tests__/system-status-modal.test.tsx` (primary, fallback badge/notice, non-admin omission) - CodeRabbit reviewed locally; addressed 3 minor translation-grammar findings (ja/sk/ro) @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
3e666c28bb |
fix(e2e,submit): tolerate Stripe layout A/B + retry tenant upload-complete (#919)
## Problem Two independent daily-E2E failures fired alerts: - **E2E Daily #138/#139 (Credit Purchase)** — timed out 30s at `stripe-checkout.ts` waiting for a top-frame `Pay` button. - **Tenant E2E #80 (`vocalstar`; `singa` passed)** — timed out 120s waiting for "Track Submitted". ## Root causes (both investigated to ground truth) **1. Stripe Checkout layout flipped again (test-only).** Stripe has now oscillated its hosted Checkout layout **three times**, strongly implying A/B testing / staged rollout: - Apr (#715): multi-method accordion of **radios**, card fields in iframes, Pay in top frame - Aug 17 (#916): **single-method**, direct textbox inputs, no chooser - Now: multi-method **Payment Element** where the chooser is **buttons** and the whole element — chooser, card fields **and the Pay button** — is inside a **nested iframe** `page.getByRole(...)` only searches the top frame, so the Pay button (now nested) was invisible → 30s timeout. The real checkout rendered correctly throughout (right product, referral 70% off, $3.00 total). **2. Tenant submit: network blip on the final completion call (real, transient).** For `vocalstar` the submit **created the job + deducted a credit**, both files reached GCS (verified in the bucket), but the final `completeJobUpload()` `fetch` failed at the network layer — it never reached the server (zero backend logs) — and threw a non-`ApiError`, surfacing the generic "Something went wrong" while stranding the paid-for job at "Setting up". `singa` passed the identical flow seconds earlier. ## Changes (v0.196.2) - **`frontend/e2e/helpers/stripe-checkout.ts`** — rewritten to be **layout-agnostic**: searches **every frame** (top + nested iframes) for the Pay button, the Card chooser (radio **or** button), card fields (direct **or** iframe), ZIP and save-info toggle. Prominent doc-comment cataloguing the three observed variants with a "do not narrow to one layout" warning. - **`frontend/lib/api.ts`** — `completeJobUpload` now retries **network-level** failures (3 attempts, backoff). HTTP errors are never retried (deterministic). Self-heals the exact failure observed. - **`frontend/components/job/TenantJobFlow.tsx`** — logs the real error; shows a network-specific message (`submitNetworkError`, translated to all 33 locales). - Tests: 3 new `completeJobUpload` retry tests; tenant error-mapping tests updated. All pass; tsc/eslint clean on changed files. ## Verification - Dispatched `e2e-daily.yml` on this branch (test code from branch, driving **production**): - **Stage 1: Credit Purchase — ✅ success** (real ~$3 charge through the new nested-iframe Stripe layout — directly exercises the helper fix) - Stage 2: Happy Path — validating (orthogonal to these changes) - Run: https://github.com/nomadkaraoke/karaoke-gen/actions/runs/32394417473 - Local CodeRabbit review completed; one legit finding fixed (Hebrew register), one false positive skipped (`ApiError` is exported at `api.ts:3982`; the new `toBeInstanceOf(ApiError)` test passes). @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
5291d6ca78 |
fix: quiet visibility-change 404 noise + clarify re-render UX (#901)
## Summary A **private→public visibility change** on a completed job re-runs the render pipeline. This tripped three error-monitor alerts and confused users. All fixed here (backend noise + frontend UX), plus the encoding-capacity transparency the delay exposed. Traced from prod alerts on job `25d076e5` (user clicked "Make Public"; the finals were deleted for re-render, and the encoding-worker capacity was exhausted → 503s for ~26 min → looked "stuck"). ## Backend — kill the false-alarm noise - `visibility_change_service`: best-effort intermediate-artifact deletes now pass `ignore_missing=True` (no more spurious `Error deleting file …404` ERRORs). - `storage_service.download_file`: re-raises `NotFound` at `warning`, not `error`. - `jobs` download route: missing object → **HTTP 404** (localized detail), not 500. Temp file is now cleaned up when download fails before streaming starts (no leak). ## Frontend — fix the UX confusion - **JobCard banner** while `visibility_change_in_progress` (and not complete): explains the re-render + republish takes ~15–30 min, so a completed track no longer silently reverts to a generic processing state. - **OutputLinks** hides stale links during a change: GCS finals only during the private→public re-render (status leaves `complete`); YouTube/Dropbox in both directions. The fast public→private path keeps its finals. - **Encoding-capacity transparency**: the `render_pending_capacity` status + its persistent `state_data` breadcrumb drive a `(waiting for encoding server availability)` note next to progress; reworded `jobStatus.waitingForCapacity`. - New i18n strings translated to all 33 locales (frontend + backend). ## Testing - Backend: `test_change_visibility`, `test_storage_service`, `test_routes_jobs` (added: intermediate deletes use `ignore_missing`; `download_file` re-raises `NotFound`). - Frontend: `job-status` helper tests (capacity/visibility, incl. lingering-breadcrumb guard) + `OutputLinks` (both transition directions). - Full frontend jest suite green (1094 tests). ## Reviewed locally with CodeRabbit 2 major + 1 minor findings addressed (temp-file leak, direction-aware download gating, localized 404). @coderabbitai ignore 🤖 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> |
||
|
|
eac3dac910 |
fix: recognize Turbopack chunk-load errors for post-deploy auto-reload (#879)
## Problem
Prod error-monitor alert:
```
Error: Failed to load chunk /_next/static/chunks/<ID>.js from module <NUM>
at https://gen.nomadkaraoke.com/_next/static/chunks/turbopack-*.js
```
The gen frontend is a static export (`output: 'export'`) served from
GitHub Pages with hashed chunk filenames. On deploy, old chunk hashes
vanish, so a user with an already-loaded tab hits a **post-deploy
mismatch** when the app lazy-loads a stale chunk. The frontend is
designed to auto-recover from this via `hardReload()` in
`client-error-setup.ts` — but the recovery wasn't firing.
## Root cause
`isChunkLoadError()` in `frontend/lib/version-check.ts` only recognized
webpack/native-ESM phrasings (`ChunkLoadError`, `Loading chunk <id>
failed`, `Failed to fetch dynamically imported module`, `Importing a
module script failed`).
**Next.js 16 defaults to Turbopack**, whose browser runtime throws a
plain `Error` (name `"Error"`, *not* `ChunkLoadError`) with a different
message: `Failed to load chunk <path> from module <n>` (also `… as a
runtime dependency of chunk <id>` / `… from an HMR update`). Confirmed
by inspecting the built runtime
`out/_next/static/chunks/turbopack-*.js`.
None of the regexes matched → the auto-hard-reload never triggered (user
saw a broken page) **and** the error was reported to the monitor → this
alert.
## Fix
- Add `/Failed to load chunk/i` to `isChunkLoadError()`'s regex list,
documenting all three bundler families.
- Add the first tests for `isChunkLoadError` (webpack, Turbopack ×3
variants, native ESM, negatives).
- Bump `0.191.1` → `0.191.2`.
Left the crash-reporter's `isBenignError` untouched: a chunk error that
survives the 60s reload circuit-breaker *should* still be reported
(persistent = a real problem like missing CDN files, not mere
staleness).
## Notes
- Users who already saw the error recover with a manual reload — this
fix makes future post-deploy mismatches self-heal automatically.
- The error store aggregates by pattern and does not persist
`user_email`, so the affected visitor can't be identified (and this hit
was on the logged-out `/zh/` homepage anyway).
## Testing
- `npx jest __tests__/version-check.test.ts
__tests__/CrashReport.test.tsx` → 20/20 pass
- `npx eslint` on changed files → clean
@coderabbitai ignore
Co-authored-by: Claude Opus 4.8 (1M context) <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) |
||
|
|
2ff5e4b49f |
feat(bulk): collapse editions to tracklist variants + clickable community versions (#852)
## Summary
Improves Bulk Mode's "By album" UX in two ways (live-MusicBrainz, no
mirror dependency):
**1. Edition selection → tracklist variants (A+C).** The release
dropdown was ~17 rows of the same album pressed in different countries.
Since the selection only feeds a list of track *names*, we now collapse
a release-group's editions into a few distinct **tracklist variants**
(Option 1: grouped by track count — zero extra MB calls, dodges the
egress rate-limiter) and show a single confident default — *"Using
Original · 1976 · 10 tracks"* — with a **Change** disclosure (hidden
entirely when there's one variant). **Track numbers** are now rendered.
Representative pressing is locale-biased (`next-intl` locale → country
preference), wiring the hook the future mirror upgrade will lean on.
**2. Community versions → vertical, clickable.** The wide inline
`Community version: A, B, C` is replaced by a vertical list, each row a
**clickable YouTube link** so the user can preview a version and decide
whether to remake it. We simply stopped discarding the `youtube_url` the
scraper already captured. Shared by album and text modes.
## Changes
- **Backend** — `musicbrainz_service.build_variants()` +
`country_prefs_for_locale()`; `karaokenerds_service` batch returns
`versions:[{brand,url}]` (back-compat `brands` kept); `bulk.py`
models/routes gain `variants`, `selected_variant_mbid`, per-track
`versions`, and a `locale` param.
- **Frontend** — new `CommunityVersions` component (replaces
`AvailabilityBadge`); `BulkAlbumMode` C-pattern picker + track numbers;
types updated.
- **i18n** — 6 new `bulk` keys translated to all 32 locales.
- **Docs** — `API.md` bulk endpoints updated.
## Testing
- Backend: new unit tests for variant grouping, locale prefs, versions
dedup, and route plumbing; full bulk/MB/KN/catalog suites green (62
passing across touched + regression files).
- Frontend: `community-versions.test.tsx` (link href/target/rel,
fallback, hidden states); `tsc` clean on all touched files.
- Post-deploy: API-level prod verification of
`/api/bulk/album/tracklist` (variants + versions present).
## Notes
- The larger mirror-backed upgrade (exact tracklist-signature grouping +
popularity ranking) is captured in
`docs/archive/2026-06-18-musicbrainz-mirror-and-album-ux-handoff.md`;
this PR is the cheap live-MB version.
- Design:
`docs/archive/2026-06-22-bulk-edition-collapse-and-community-versions-design.md`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
@coderabbitai ignore
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
||
|
|
4f411c4306 |
feat(lyrics-review): auto-apply corrections + timeline-in-text Advanced view (#846)
## Summary Reworks the lyrics review UX now that AI auto-corrections are reliable, and replaces the separate Timeline view with timing intelligence baked into the lyrics themselves. ### Auto-correct display - **Auto-apply on load** (= the old "Accept all") as the review **baseline** — not an undoable edit — so no save/restore prompt appears unless you make a genuine manual edit. - Corrected words render **purple** with a grey struck-through "original transcription" bubble above; words whose timing was **estimated** (a word split into several, or inserted) get an **amber dashed underline**, while clean 1:1 replacements stay solid. - The standing suggestions row is gone — the toolbar button reads **"Auto-corrected · N"** and opens a details panel on demand (per-item **undo**, **Re-run**, **Revert all auto-corrections**). - Guidance panel: purple/amber legend + a "play each corrected line and re-check timing" tip. Tooltips say "auto-corrected by our system" (no "AI"). ### Timeline rework (replaces the Timeline view) - Single **Simple / Advanced** toggle replaces both the Text/Timeline toggle and the old Simple/Advanced badge; `DurationTimelineView` deleted. - Inline **>2s long-word** (badge inside the pill, right-aligned) and **>2s inter-word gap** warnings, in both modes. - **Advanced** mode stretches each word pill by its duration (flex) so a segment fills the full width as a readable timeline; gap spacers are **click-to-play** (hover shows a play icon). ### Session restore unification - Removed the ad-hoc `window.confirm` localStorage path. The same `SessionRestoreDialog` is now used everywhere — server-backed in cloud mode, and a new **localStorage session store** when running karaoke-gen locally. ### Other - `crash-reporter`: never POST client errors from a localhost origin (was tripping the prod error monitor during local dev). - New `Word` provenance fields + apply-time stamping. ## Testing - Frontend unit suite: **1034/1034 pass** (new tests for apply-time stamping, the local session store, and the localhost-skip guard). - `tsc --noEmit`: no new errors; ESLint: 0 errors. - All **33 locales** translated and verified complete (1415 keys each). - Iterated and verified live in a local frontend against the prod backend across several real jobs (auto-apply, purple/bubbles/markers, Advanced timeline, gap-click-to-play, clean fresh-load with no restore prompt). - Reviewed with CodeRabbit; findings addressed. Design doc: `docs/archive/2026-06-18-autocorrect-applied-ux-design.md` @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>
|
||
|
|
fea6ebec1a |
fix(tenant): make white-label B2B portals attribute jobs to the tenant (Vocal Star + Singa) (#824)
@coderabbitai ignore ## Problem The white-label tenant portals (`vocalstar.nomadkaraoke.com`, `singa.nomadkaraoke.com`) looked "done" but **had never worked end-to-end**: 0 of the last 484 production jobs carried a `tenant_id`. No tenant job had ever run. **Root cause:** the frontend API client never sent the `X-Tenant-ID` header. Tenant portals call the shared `api.nomadkaraoke.com`, whose Host isn't the tenant subdomain, and the `?tenant=` query param is disabled in prod — so the backend could never detect the tenant. Every tenant sign-in and job submission silently fell back to consumer behavior (default theme, no tenant Dropbox, etc.). The `getTenantHeaders()` helper existed and was unit-tested, but was never wired into requests. ## Changes **Frontend** (`lib/api.ts`, `lib/tenant.ts`) - Attach `X-Tenant-ID` on all authenticated requests **and** the magic-link request, sourced from `window.__TENANT_CONFIG__` (edge-injected by the Cloudflare function; mirrored from the tenant store for dev/preview). Consumer build resolves no tenant → no header → **behavior unchanged**. **Backend** (`_apply_tenant_overrides` in `file_upload.py`) - Make tenant config **authoritative** over global distribution defaults. Prod sets `DEFAULT_DROPBOX_PATH` / `DEFAULT_GDRIVE_FOLDER_ID` / `DEFAULT_BRAND_PREFIX` globally; these seed `dist`, and the old "fill only when unset" overlay let them leak — so every tenant job would have landed in the **shared consumer Dropbox folder** and uploaded to the **global Google Drive**. Now Dropbox/GDrive routing is gated by the tenant feature flags and cleared when disabled. **Tenant configs** (GCS + setup scripts, Vocal Star + Singa) - Disable Google Drive (`gdrive_upload=false`, `gdrive_folder_id=null`), keep YouTube off, enable Dropbox to each tenant's own folder. B2B = locked theme, no YouTube/GDrive, Dropbox + portal download only. ## Why it's consumer-safe - Frontend: header only attached when a tenant is resolved (never on `gen.nomadkaraoke.com`). - Backend: `_apply_tenant_overrides` early-returns when `tenant_config is None` (all consumer jobs). ## Testing - New: frontend header-attachment tests (tenant build vs consumer); backend authoritative-override + feature-flag-gating regression guards (incl. the global-default-leak case). - Full suites green: **3466 backend**, **1013 frontend**. - Verified live tenant configs via API after update. Manual prod E2E (real track through each portal) + a daily per-tenant E2E workflow follow in a second PR, once this deploys and is verified in prod. Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
c1837c1086 |
fix(lyrics-review): gate audio playback until loaded + silence benign AbortError noise (#800)
## Summary
- Production error monitor flagged `AbortError: The fetching process for
the media resource was aborted...` from the lyrics-review page. Root
cause: the audio player started fetching a large file on mount but left
playback controls live before the media could play, so early clicks /
spacebar did nothing **and** the rejected `play()` promise was reported
as error noise.
- Fixes both the noise and the janky UX: playback is now gated until the
audio is fully ready, with a clear loading spinner + buffer progress
bar.
## Changes
- **AudioPlayer** is now the single source of truth for readiness:
tracks `canplaythrough` (+ fully-buffered fallback), publishes
`window.isAudioReady` and a `karaoke:audio-ready` event, and **guards
the `seekAndPlayAudio` / `toggleAudioPlayback` globals** so spacebar,
segment buttons, and the edit modal no-op until ready.
- While loading, shows a spinner + `<Progress>` bar ("Loading
audio..."); on failure shows an inline error.
- New `useAudioReady()` hook visually disables the segment play buttons
(`TranscriptionView`) and the edit-modal play button with an "Audio is
still loading..." tooltip.
- Added `.catch(() => {})` to the three bare `play()` calls and filter
benign `AbortError` in `crash-reporter` so this class of noise never
reaches the error monitor again.
- 3 new i18n strings, translated to all 33 locales (ASCII `...` to match
existing loading strings).
## Testing
- [x] Frontend unit suite green: **916 tests / 65 suites** (added
`AudioPlayer` readiness+gating, `useAudioReady`, `crash-reporter`
benign-abort cases)
- [x] Lint clean; typecheck clean on all touched files
- [ ] Manual: throttled-network check of spinner → controls transition
(recommended post-deploy)
## Review
- [x] CodeRabbit CLI review completed locally (1 finding fixed: ASCII
ellipsis; 1 pre-existing tl.json translation gap noted, out of scope)
- [x] Issues addressed
Plan doc: `docs/archive/2026-06-07-lyrics-review-audio-loading-plan.md`
@coderabbitai ignore
---
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
||
|
|
7cf42c8983 |
feat(pricing): duration-based credit pricing + long-duration input handling (#799)
@coderabbitai ignore
## Summary
Implements **duration-based credit pricing** for karaoke jobs, replacing
the flat 1-credit/job model. Credits now scale with input audio length
(`ceil(min/10)`, hard-block >60 min), with cost confirmed before heavy
processing and reconciled against the actual measured audio. Closes out
the planned fix from the 2026-06-04 long-duration mashup incident.
- Design:
`docs/archive/2026-06-04-long-duration-input-handling-design.md`
- Plan: `docs/archive/2026-06-04-long-duration-input-handling-plan.md`
## Pricing model
`credits = max(1, ceil(minutes / 10))` — 1 credit ≤10 min, 2 ≤20 min … 6
≤60 min. Inputs over 60 min are blocked. Single source of truth in
`backend/services/pricing.py`, mirrored in `frontend/lib/pricing.ts`.
## How it works
- **`state_data.credits_charged`** is the authoritative running total.
`create_job` charges the base (URL = full N via `acknowledged_credits`;
search/upload = 1); top-ups deduct only the **delta**
(`count_as_job_creation=False`).
- **Reconciliation engine** (`duration_reconciliation.py`) runs at the
single convergence point before separation+transcription in all three
processing paths (download / post-edit / `start_job_processing`),
exactly once each. It measures the audio actually sent to AudioShake
(post-edit if trimmed):
- actual < estimate → auto-refund the difference
- actual > estimate → pause at new **`AWAITING_DURATION_CONFIRM`**
state, user re-confirms (inline Buy Credits)
- actual > 60 min → refund everything + cancel
- **`POST /api/jobs/{id}/confirm-duration`** (+ `POST
/api/jobs/estimate`) reuse the review-stage pause/resume.
- **Notifications**: in-browser + push, 15-min idle email, 24h reminder,
**48h auto-cancel + full refund** — via the existing idle-reminder /
stale-job machinery.
- **Admin / made-for-you jobs bypass charging entirely**
(`payment_bypassed` → reconcile short-circuits).
## Endpoints
| Method | Path | Purpose |
|---|---|---|
| `POST` | `/api/jobs/estimate` | URL duration probe →
`{duration_seconds, credits, blocked, source}` |
| `POST` | `/api/jobs/{id}/confirm-duration` | confirm cost / resume
(402 insufficient, 409 mismatch) |
| `POST` | `/api/jobs` | URL create gains optional `duration_seconds`,
`acknowledged_credits` |
| `POST` | `/api/audio-search/{id}/select` | gains optional
`acknowledged_credits` |
## Frontend
`DurationCostConfirm` modal (Radix Dialog) surfaced via a "Confirm Cost"
action on `awaiting_duration_confirm` jobs (`useDurationConfirm` hook),
per-result cost chips on audio search, `pricing` i18n namespace in all
33 locales.
## Testing
- Backend: **3358 passing** (incl. boundary tables, money-math
conservation, reconcile up/down/over-limit, confirm 402/409, idempotency
guards, stale-expiry refund, an end-to-end integration test). Frontend:
**960 passing**. i18n completeness clean.
- Reviewed locally: per-task spec + quality review, a holistic
cross-cutting review, `/test-review`, and two CodeRabbit fix cycles.
## Notable bugs caught & fixed during review
- **Multi-credit under-refund**: `_refund_credit_for_job` refunded a
flat 1 — now refunds `credits_charged` (user-cancel of a long job).
- **Admin-bypass trap**: admin jobs would pause at the confirm gate and
be charged real credits — now short-circuited.
- Over-limit double-refund (suppress `cancel_job`'s built-in 1-credit
refund); over-limit email used the wrong "48h" message;
double-confirm/double-select idempotency guards.
- Hit the summary-projection gotcha (added fields to both projection
lists + regression test).
## Known residuals / follow-ups (non-blocking)
- **URL pre-flight cost-confirm is inert** until flacfetch's
`/check-youtube` returns a `duration` key — currently falls back to a
1-credit hold + post-download reconcile (functionally correct). Separate
flacfetch change.
- Duration-confirm email **bodies** are English (URLs are
locale-prefixed; backend i18n covers en/es/de) — `# TODO(i18n)` left.
- Concurrent confirm/select **double-charge TOCTOU** is an accepted
low-probability residual (atomic claim would need a Firestore
transaction); the status-transition guard handles the realistic
double-click case.
## Deploy note
Reuses the existing Cloud Tasks idle-reminder queue and the hourly
stale-review Cloud Scheduler (status-list / action-type expansions only)
— no new infra expected, but worth confirming `pulumi up` is a no-op on
deploy.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
||
|
|
64301db5d2 |
fix(audio-download): make worker idempotent, surface auto-retry to user (#762)
## Summary
Fixes the race condition behind job `8a9c74ff` where a single user Retry
click caused the `audio-download-job` Cloud Run Job to run 3 times,
producing a visible "Audio download failed: Invalid state transition for
job ...: downloading -> JobStatus.DOWNLOADING" error AND
double-triggering downstream L4 GPU separation + lyrics transcription
jobs.
Root cause: the user clicked Retry inside the ~75s window between Cloud
Run's failed task and its automatic task-attempt retry. Two parallel
executions raced on job state.
## Changes
**Backend**
- `audio_download_worker.py`:
- `DOWNLOAD_ALREADY_DONE_STATUSES` idempotency guard — return success
early when status is already past `DOWNLOADING_AUDIO`, instead of
re-downloading and crashing on a redundant state transition.
- `_mark_retry_pending_if_attempts_remain` writes
`state_data.cloud_run_retry_pending = { expires_at }` when
`CLOUD_RUN_TASK_ATTEMPT < CLOUD_RUN_MAX_RETRIES` (2). Final attempt
explicitly clears any stale marker.
- `_clear_retry_pending_and_error` clears the marker and `error_message`
on successful download so the dashboard stops showing a resolved
transient failure.
- `jobs.py` `/retry` endpoint returns **409** when
`cloud_run_retry_pending` is active, preventing duplicate parallel
executions.
- `job_manager.py` error-message rendering fix: f-strings now use
`.value` consistently so we don't get the misleading `downloading ->
JobStatus.DOWNLOADING` artifact.
- `cloud_run_retry_pending` added to `SUMMARY_FIELD_PATHS` and the
dashboard prune allowlist.
**Frontend**
- `isAutoRetryPending(job)` helper in `lib/job-status.ts`.
- `JobActions`: when auto-retry is pending, hide the manual Retry button
and show "Retrying automatically…" with a spinner. Falls back to Retry
once the window expires.
- `JobCard`: don't render the `error_message` banner on completed jobs
(covers legacy data where a transient failure left a stale error
string).
- New i18n keys auto-translated to all 33 locales.
**Docs**
- `LESSONS-LEARNED.md`: Cloud Run Job retry race pattern + idempotency
defenses.
## Testing
- [x] Backend unit tests pass: 3183 passed, 36 skipped (10 new tests for
this work)
- [x] Frontend Jest tests pass: 110 passed in affected suites (8 new
tests)
- [x] TDD throughout — failing test before each implementation change
Tests added cover:
- Worker idempotency across 8 post-download statuses (`DOWNLOADING`,
`AWAITING_AUDIO_EDIT`, `TRANSCRIBING`, ... `COMPLETE`)
- Retry-pending marker: written on non-final attempt, cleared on final
attempt, cleared on success
- `_is_auto_retry_pending` helper edge cases (missing / past / future /
malformed)
- Frontend: indicator shows during window, falls back to Retry after
expiry, JobCard hides stale error on complete
## Review
- [x] Local code review completed (CodeRabbit CLI auth issue →
`feature-dev:code-reviewer` agent fallback)
- [x] Should-fix finding addressed: stale marker after final attempt
blocked manual retry for ~3 min (commit `d87cd86`)
- [ ] Optional finding deferred: frontend doesn't auto-re-render at
exact expiry time (dashboard polls, self-heals)
## Infrastructure
No Pulumi changes. `audio-download-job` `max_retries=2` retained —
automatic recovery from transient Spotify timeouts still works, and the
new idempotency guard makes retries safe.
@coderabbitai ignore
---
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.7 (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> |
||
|
|
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> |
||
|
|
8c1dfe5460 |
feat(i18n): Phase 3 frontend — next-intl infrastructure + 1062 strings (en/es/de) (#656)
@coderabbitai ignore
## Summary
- Phase 3 of the i18n multilingual initiative — makes the karaoke-gen
frontend fully multilingual (English, Spanish, German)
- Installs `next-intl` with `[locale]` path-based routing,
LanguageSwitcher, and `Accept-Language` API header
- Extracts **1,062 strings** from ~70 components into `messages/en.json`
across 31 namespaces
- Wires `useTranslations()` into all user-facing components (landing,
dashboard, auth, job flow, lyrics review, instrumental review, audio
editor, etc.)
- Admin pages (`/admin/*`) stay outside locale routing — intentionally
excluded from i18n scope
- Static export generates `/en/`, `/es/`, `/de/` directories (45 total
pages) for Cloudflare Pages
- `es.json`/`de.json` are English placeholders — translation via Gemini
pipeline pending
- Translation pipeline (`scripts/translate.py`) and glossary (55
karaoke-specific terms) included
## Key architecture decisions
- Root layout keeps ThemeProvider/TenantProvider (needed by admin pages
outside `[locale]`)
- Only NextIntlClientProvider added to `[locale]/layout.tsx`
- `job-status.ts` labels converted to translation keys; consumers
translate via `useTranslations('jobStatus')`
- Jest mock loads actual `en.json` so existing tests validate i18n
wiring without assertion changes
## Test plan
- [x] All 707 frontend tests pass (39 suites)
- [x] Static build generates all 45 pages across 3 locales
- [x] Admin pages render at `/admin/` without locale prefix
- [x] CodeRabbit review: 4 issues fixed, 7 pre-existing noted
- [ ] Post-deploy: verify `/en/` landing page renders correctly
- [ ] Post-deploy: verify LanguageSwitcher redirects to `/es/` and
`/de/`
- [ ] Post-deploy: verify `/admin/` still works without locale context
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
||
|
|
c98da49da9 |
feat: add jobs search, status filter, and fix loading states (#637)
## Summary - Add server-side text search to jobs list API (case-insensitive substring match across artist, title, job_id) - Replace eye icon toggle with status filter dropdown (All statuses, Active, Failed, Completed, Cancelled, Awaiting review, Processing) - Add debounced search input to Recent Jobs header - Expand limit dropdown options (5, 10, 20, 50, 100, 1000) - Fix loading state showing "No jobs yet" during cold starts (now shows spinner) - Fix API always fetching limit=100 regardless of dropdown selection ## Test plan - [x] 8 unit tests for `_search_filter_jobs` (artist, title, job_id, audio search fields, case insensitivity, None handling, empty string, limit interaction) - [x] Full backend test suite passes (2870 passed) - [x] Frontend builds cleanly - [ ] Manual: verify search filters jobs in real-time on dashboard - [ ] Manual: verify status dropdown filters correctly - [ ] Manual: verify loading spinner shows during cold starts instead of "No jobs yet" <!-- @coderabbitai ignore --> 🤖 Generated with [Claude Code](https://claude.com/claude-code) |
||
|
|
14a6b767ce |
fix: improve cancelled job UX and fix /dashboard redirects (#633)
## Summary - Allow downloading files from cancelled jobs (backend no longer requires job to be complete if the file exists in GCS) - Hide cancelled jobs from default recent jobs view alongside completed jobs; visible via "Show all jobs" toggle - Fix stale `/dashboard` routes → `/app` (including impersonation redirect that 404'd) - Show accurate total job count and helpful empty state when jobs are filtered out ## Test plan - [x] Backend unit tests pass (2837 passed) - [x] Frontend unit tests pass (717 passed, 39 suites) - [ ] Verify cancelled job download works in prod after deploy - [ ] Verify impersonation redirects to /app correctly - [ ] Verify "Show all jobs" toggle shows/hides cancelled and completed jobs - [ ] Verify empty state message shows correct total and eye icon hint @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
93823b8a20 |
Move song suggestions to Step 2 with fuzzy typo correction (#512)
@coderabbitai ignore ## Summary - **Simplified Step 1 (Song Info)**: Removed autocomplete — plain text inputs for artist/title so users aren't confused by autocomplete behavior - **Step 2 song suggestions**: Catalog lookup + community version check fire in parallel with audio search. Results appear as a "Song found in our database" panel (exact match) or correction suggestion panel while the user waits - **Fuzzy "Did you mean?" correction**: When audio search returns poor results (Tier 3) and catalog has no exact title match, fetches the artist's discography and fuzzy-matches against the user's title. Shows amber banner with one-click correction + expandable alternatives list. Title-based fallback with artist tiebreaker handles garbled artist fields - **Visibility step reworked**: Action buttons at top for one-click select+continue, "change later" note, removed Recommended badge - **Minor UI polish**: Warning icon on community banner, "Recommended Audio" heading, YouTube icon on community links, filename above release in pick card ## Test plan - [x] 70 new tests added (fuzzy matching, SongInfoStep, AudioSourceStep, VisibilityStep, CommunityVersionBanner) - [x] All 677 tests pass - [x] Manual testing via Playwright: "Fox Stevenson / ruises" typo → Did you mean Bruises; "fox stevenson bruises / bruises" garbled artist → correct Fox Stevenson suggestion - [x] CodeRabbit review completed, issues fixed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
58f1b51244 |
fix: URL/upload fallback paths now respect private/published visibility (#495)
## Summary - **Bug:** When creating a job via YouTube URL or file upload (fallback paths in Step 2), the job was created immediately — skipping the Visibility step (Step 3) entirely. This meant `is_private` was always `false` regardless of user intent. - **Fix:** All three audio source paths (search, URL, upload) now go through Steps 3-4 before job creation, ensuring the user's private/published choice is always respected. - **Tests:** Added 18 unit tests covering all audio source × visibility combinations, display override handling, mutual exclusivity, and error cases. ## Root Cause `AudioSourceStep` had two code paths: 1. **Search result selected** → proceeded to Step 3 (Visibility) → Step 4 (Customize) → job created with correct `is_private` 2. **URL pasted / file uploaded** → job created immediately in Step 2 with `is_private: false` → jumped to success screen The fix makes path 2 behave like path 1: store the URL/file, proceed through Steps 3-4, then create the job in `handleConfirm`. ## Test plan - [x] 37 Jest tests pass (19 existing + 18 new) - [x] 573 total frontend tests pass - [x] CodeRabbit review: no findings - [x] Verified job `5f3f0b88` had `is_private: False` in Firestore (confirming the bug) @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
ca9f3bd5ba |
feat: streamlined tenant portal with 4-field upload form (#481)
@coderabbitai ignore ## Summary - Replace the multi-step consumer wizard with a streamlined 4-field form (Artist, Title, Mixed Audio, Instrumental Audio) for B2B tenant portals - All tenant jobs automatically private with tenant-specific Dropbox/GDrive delivery, locked theme, and brand prefix - Backend: `_apply_tenant_overrides()` helper forces private, applies locked theme, overlays tenant distribution settings; private tenant jobs use their own paths instead of NonPublished override - Frontend: New `TenantJobFlow` component with drag-and-drop file uploads; conditional rendering based on tenant detection ## Test plan - [x] 10 backend unit tests (tenant override logic, distribution routing, partial config edge cases) - [x] 9 frontend unit tests (API contract, error handling, form validation) - [x] 3 E2E production tests (simplified form verification, track submission, consumer portal isolation) - [x] All existing tests pass (2307 backend + 520 frontend Jest + 181 Playwright regression) - [ ] Run production E2E test after deploy: `KARAOKE_ADMIN_TOKEN=xxx npx playwright test e2e/production/tenant-job-submission.spec.ts --config=playwright.production.config.ts` 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
33667a6852 |
feat: custom video styling for private delivery jobs (#471)
@coderabbitai ignore ## Summary - Private-delivery users can now customize their karaoke video styling: upload custom background images (karaoke + title card) and change artist/title text colors via color pickers with live canvas previews - Backend: 2 new endpoints (`style-upload-urls`, `style-uploads-complete`) that validate ownership, cutoff status, and merge custom assets into the theme's `style_params.json` - Frontend: `ImageUploadField` component, `KaraokeBackgroundPreview` canvas, extended `TitleCardPreview` with custom bg/colors, `CustomizeStep` styling section (visible when private), `GuidedJobFlow` upload orchestration - Also: skip `take-screenshots` spec by default (manual helper, not a real test) ## Test plan - [x] 15 backend tests covering both new endpoints (auth, validation, cutoff, asset merging, color overrides) - [x] 14 CustomizeStep tests (conditional visibility, color pickers, previews, form interactions) - [x] 9 ImageUploadField tests (drag-and-drop, validation, file type/size rejection) - [x] 2 TitleCardPreview tests (custom colors, custom background URL) - [x] 6 guided-flow API contract tests (style upload methods) - [x] All 181 existing Playwright E2E tests pass - [ ] Manual: create a private job, upload custom backgrounds, verify colors render in video 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
e44b5f6543 |
fix: recent jobs UX - cancel→delete, date sort, hide-completed fix, admin controls (#447)
@coderabbitai ignore
## Summary
- **Cancel → Delete**: The Cancel button now permanently deletes jobs
(Firestore doc + GCS files) via the existing `DELETE /api/jobs/{job_id}`
endpoint. Cancelled jobs no longer exist as a concept in the user-facing
flow.
- **Hide completed fix**: The "Hide completed" toggle now only hides
successful completions (`complete`, `prep_complete`). Failed jobs remain
visible so users always see jobs that need attention.
- **Date-only sorting**: Removed priority-based sorting that buried
failed jobs below completed ones. Jobs now sort purely by `created_at`
descending — newest first, always.
- **Admin controls toggle**: Admins see a Shield toggle in the header
that reveals inline admin action buttons (reset, restart, delete, regen
screens, etc.) on each job card — no need to switch to the admin
dashboard.
## Test plan
- [x] Frontend tests pass (496 tests)
- [x] Backend route tests pass (8 tests)
- [x] `next build` succeeds
- [x] New AdminJobActions component has unit tests
- [x] JobCard admin controls rendering tested
- [x] JobActions cancel→delete behavior tested
- [x] E2E regression test updated for delete flow
- [ ] Visual verification: failed job appears at top of Recent Jobs
- [ ] Visual verification: "Hide completed" keeps failed jobs visible
- [ ] Visual verification: Admin shield toggle shows/hides admin actions
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
|
||
|
|
f17bc931d0 |
feat: decouple audio search from job creation (search sessions) (#444)
## Summary - Fixes 4 UX problems caused by the guided wizard creating a backend job at Step 2 (audio search), before the user has set `is_private`, display overrides, or confirmed they want a job at all - Adds `POST /api/audio-search/search-standalone` — runs search synchronously, stores results in a 30-minute Firestore session, returns `search_session_id + results` (no job created) - Adds `POST /api/jobs/create-from-search` — creates job at Step 3 with all correct values from the start; atomically consumes the session to prevent duplicate job creation ## Problems Solved **A) Orphan job records** — abandoned searches left job records in Firestore; back button `deleteJob` cleanup was best-effort **B) Wrong field values at creation** — job existed briefly with `is_private: false` and no display overrides **C) Jobs in Recent Jobs list** — `AWAITING_AUDIO_SELECTION` jobs appeared in the list before user confirmed **D) Notification chime fired** — state transitions on the temporary job triggered the action-required chime during search ## Changes - `backend/routers/audio_search.py` — new `POST /api/audio-search/search-standalone` endpoint (synchronous, no job) - `backend/routers/jobs.py` — new `POST /api/jobs/create-from-search` endpoint with validate-then-consume session pattern - `backend/services/firestore_service.py` — `create_search_session`, `get_search_session`, `consume_search_session` (atomic transaction), `delete_search_session` - `infrastructure/modules/database.py` — Firestore TTL policy for `search_sessions` collection (30-min auto-expiry) - `frontend/lib/api.ts` — `searchStandalone`, `createJobFromSearch` methods - `frontend/components/job/steps/AudioSourceStep.tsx` — uses standalone search; no polling; no job state - `frontend/components/job/GuidedJobFlow.tsx` — defers job creation to Step 3 confirm; no `deleteJob` on back **Unchanged:** old `POST /api/audio-search/search` (CLI backward compat), upload/URL paths, `AWAITING_AUDIO_SELECTION` status. ## Testing - [x] 26 new backend unit tests (`backend/tests/test_standalone_search.py`) covering session CRUD, both new endpoints, ownership/tenant/TTL/index validation, atomic consumption - [x] 13 new frontend Jest tests (`frontend/__tests__/guided-flow.test.tsx`) covering API contract, component exports, behavioral invariants - [x] Full test suite passes: 2167 backend + 507 frontend ## Review - [x] CodeRabbit CLI review completed (3 cycles, 0 remaining findings) - [x] Atomic session consumption via Firestore transaction (prevents duplicate jobs on concurrent requests) - [x] Validate-before-consume pattern (4xx errors leave session intact for user retry) - [x] Tenant consistency check added @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> |
||
|
|
4bf70138b5 |
Fix notification chime behavior for audio selection and completion (#425)
## Summary - Stop playing the action-needed chime when a job enters `awaiting_audio_selection` — the user is already engaged with the inline audio picker, so the notification is unnecessary - Add a distinct success chime (rising C major arpeggio: C6→E6→G6) for job completion, so users can tell "done" apart from "attention needed" by sound alone - Keep existing alert chime for `awaiting_review`, `in_review`, `awaiting_instrumental_selection`, and `failed` ## Changes - **`frontend/lib/job-status.ts`**: Add `isNotifiableBlockingStatus()` — delegates to `isBlockingStatus()` but excludes `awaiting_audio_selection`. UI sorting/badges/cards unchanged. - **`frontend/hooks/use-notifications.ts`**: Refactor sound system into `playAlertChime()` and `playSuccessChime()`, route by `NotificationReason`. Switch notification filtering to `isNotifiableBlockingStatus()`. - **`frontend/__tests__/job-status.test.ts`**: 7 new tests for `isNotifiableBlockingStatus` (true/false cases, case insensitivity, null/undefined). ## Test plan - [x] All 478 Jest tests pass (including 7 new tests) - [x] CodeRabbit review: no findings - [ ] Manual: create a job via audio search — confirm no chime during audio selection - [ ] Manual: let a job reach review — confirm alert chime plays - [ ] Manual: let a job complete — confirm distinct success chime plays @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
4fe960481b |
feat: show all incomplete jobs first + hide-completed toggle (#393)
## Summary - **Priority sorting**: Blocking + processing jobs always appear first in Recent Jobs, regardless of creation date - **Hide completed toggle**: Eye/EyeOff button filters out completed and failed jobs, showing only incomplete ones - **Persistent preferences**: Both the display limit dropdown and hide-completed toggle persist in localStorage across page reloads - **Oversized lyrics truncation fix**: Corrected screen generation for songs with unusually long lyric lines ## Changes - `frontend/lib/job-status.ts`: Added `hideCompleted` parameter to `getDisplayJobs()` — filters by job priority before applying display limit - `frontend/app/app/page.tsx`: Added Eye/EyeOff toggle with tooltip, localStorage persistence for both `jobLimit` and `hideCompleted` - `frontend/__tests__/job-status.test.ts`: 5 new tests covering hideCompleted filtering behavior ## Test plan - [x] All 168 tests pass (`make test`) - [x] 85 job-status unit tests pass including 5 new hideCompleted tests - [ ] Visual verification: toggle button appears next to limit dropdown, state persists on reload <!-- @coderabbitai ignore --> 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
fb32a9af9e |
feat: improve dashboard performance and UX (#354)
## Summary - Improved recent jobs list loading performance by reducing default limit - Added user control via job limit dropdown - Implemented smart priority sorting for better UX ## Changes - Reduced default job limit from 20 to 5 for faster initial load - Added job limit dropdown with options: 5, 10, 20, All - Implemented priority sorting: blocking jobs (awaiting user action) appear first, followed by processing, completed, and failed jobs - Made OutputLinks buttons responsive by hiding text labels on mobile (icons-only) to prevent horizontal overflow - Added 14 comprehensive unit tests for `getJobPriority()` and `sortJobsByPriority()` functions - Updated docs/README.md with change summary ## Technical Details **Frontend-only changes:** - `frontend/lib/job-status.ts`: Added priority scoring and sorting utilities - `frontend/app/app/page.tsx`: Added job limit state, dropdown UI, and sorting logic - `frontend/components/job/OutputLinks.tsx`: Made buttons responsive with `hidden sm:inline` pattern - `frontend/__tests__/job-status.test.ts`: Added 14 unit tests covering all priority levels and edge cases **Performance impact:** - Initial API call fetches 5 jobs instead of 20 (60% reduction in payload) - Users can still access more history via dropdown - Priority sorting ensures important jobs are always visible first ## Testing - [x] All 248 tests pass (including 14 new unit tests) - [x] TypeScript compilation successful - [x] Manual testing: dropdown changes job count, priority sorting verified - [x] Mobile testing: no horizontal overflow, buttons show icons-only ## Review - [x] Test coverage excellent (unit tests for all new logic) - [x] Documentation updated (docs/README.md) @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com> |
||
|
|
f661b6a27b |
feat(branding): Implement consistent brand theming across all frontends (#231)
## Summary - Implement unified brand theming with brand pink (#ff7acc) as primary color across all Nomad Karaoke frontends - Create comprehensive brand style guide for human and LLM reference - Add proper light/dark mode support throughout - Update homepage content for transparency and accuracy - Create product communication guide for consistent messaging ## Changes ### Homepage Content Updates - Changed "in minutes" to "in under 30 minutes" for accuracy - Removed AI terminology per user preference (use "our system" instead) - Made review step clearly required, not optional polish - Fixed YouTube claim: videos go to Nomad Karaoke channel, not user's - Added demo video embed - Added placeholder sections for screenshots (job dashboard, lyrics review, etc.) ### Brand Style Guide (`docs/BRAND-STYLE-GUIDE.md`) - Comprehensive guide covering colors, typography, logo usage, UI components, email design - Updated to v1.1: radial background gradients, logo usage (SVG preferred), light/dark theme requirements - Fixed success color consistency (#22c55e) ### Product Communication Guide (`docs/PRODUCT-COMMUNICATION-GUIDE.md`) - Core principles: transparency over hype, avoid AI term, acknowledge user effort - Terminology preferences table - FAQ guidance for consistent answers - Referenced in CLAUDE.md for future agent sessions ### Main Frontend (`frontend/`) - Updated CSS variables in `globals.css` for brand colors and light/dark mode - Added ThemeProvider to layout for proper theme switching - Updated landing page, auth dialog, job cards with brand pink (#ff7acc) - Created Playwright screenshot tests for visual verification ### Lyrics Transcriber Frontend - Updated MUI theme with brand pink primary color - Fixed theme-aware colors in: EditModal, EditWordList, WordDivider, Word, CorrectedWordWithActions, TranscriptionView, ReferenceView, AIFeedbackModal - Fixed TapButton onMouseLeave race condition - Added clarifying tooltip to Undo Auto Corrections button ### Email Templates - Refactored to use reusable helper methods (`_build_email_html`, `_get_email_header`, `_get_email_footer`) - Updated all 7 email templates with brand pink headers, buttons, and accents - Fixed success color to match brand guide (#22c55e) - Updated preview script to use actual email service ### Other - Bumped versions: backend 0.96.0, frontend 0.81.0 - Added archive entry for brand consistency work ## Screenshots ### Homepage | Hero Section | Full Page | |--------------|-----------| |  |  | ### Lyrics Review UI  ### Instrumental Review UI  ### Email Templates | Job Completion | Action Reminder | Beta Welcome | |----------------|-----------------|--------------| |  |  |  | ## Test plan - [x] Playwright screenshots captured - [x] Visual verification of brand consistency - [x] Frontend build passes - [x] CodeRabbit review feedback addressed (3 cycles) @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
5c71d58a8d |
Fix progress display to show step 4 when workers are active during download
When the backend status is "downloading" but parallel workers (audio/lyrics) are actively running, the frontend now correctly displays step 4 progress instead of appearing stuck at step 3 "Downloading". This improves UX by showing detailed worker progress (e.g., "Audio 1/2 + Transcribing") when both workers are active, making the job appear responsive. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> |
||
|
|
7218b4d176 |
feat: Add step-based job status display with progress indicator
- Create job-status.ts utility that maps 28+ backend statuses to a 10-step user-friendly system - Display status as "[X/10] Status..." format for better progress visibility - Add visual progress bar that matches status color - Show "Action needed" badge for blocking states (review, instrumental selection) - Handle parallel processing (audio + lyrics) with combined status display - Add comprehensive unit tests (40+ test cases) for all status mappings - Update JobCard to use new StatusIndicator and ProgressBar components This improves user experience by providing clearer feedback about job progress instead of showing static labels like "Downloading..." for extended periods. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> |