mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-28 01:49:00 +09:00
36b331f3d7411ecf97c05bf15146e83161ab94de
190
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
36b331f3d7 |
feat(requests-board): admin history view + fix community publish transition (#1008)
## Why Andrew asked whether we can see past community-requests-board submissions and whether our first real user got a video. Investigation surfaced: - **First real user was fully served.** `tas041964@gmail.com` requested *Sam Cooke and the Soul Stirrers – Wonderful* (Sep 15); it was auto-picked, generated, published to YouTube (NOMAD-1650), and he got the completion email + emailed thanks. ✅ - **No admin view existed** to see this — you had to query Firestore directly. - **A real bug:** the community publish fan-out (`mark_published` + voter emails) fired **only** on the `youtube_upload_queue` path. Jobs published via the direct video-worker distribution path (like Sam Cooke's) bypassed it, so the request stayed `in_progress`, never lit up the board's public "Recently made" list, and other up-voters would silently miss their "track is live" email. ## What 1. **Fix the publish transition** — extract the fan-out into `backend/services/community_publish.py` and call it from **both** publish paths (`youtube_queue_processor` + `video_worker`). Also fixes a latent `len(int)` crash in the log line. 2. **Backfill / safety net** — `POST /api/internal/community-requests/reconcile`: idempotent, publishes any `in_progress` pick whose job is already live on YouTube. (Will be run in prod post-deploy to fix the Sam Cooke request.) 3. **Admin history view** — `GET /api/admin/community-requests` + a `/admin/community-requests` page: every request, all statuses, with requester, votes, and job + YouTube links. The public board's "Recently made" section already existed in the UI — it was empty only because of bug #1; fixing the transition (+ reconcile backfill) lights it up. ## Testing - `backend/tests/test_community_voter_notify.py` — fan-out from the shared module, both-path idempotency, voter dedupe/retry, YouTube-url resolution, and the reconcile scan. - `backend/tests/test_community_review_admin.py` — the new admin history endpoint maps all statuses. - All 31 requests-board + 158 worker tests pass. The one unrelated failure in `test_audio_processor_local_gpu.py` is pre-existing (confirmed with changes stashed). ## Notes - Admin surface is English-only (no i18n changes); no `en.json` strings added. - Local CodeRabbit review couldn't run (CLI requires life360-org SSO; no seat on this repo) — leaving to the GitHub bot. Plan: `docs/archive/2026-09-17-requests-board-history-and-publish-transition-plan.md` 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added an admin Community Requests history page covering all statuses, votes, submitters, review details, linked jobs, and YouTube videos. - Added admin reconciliation for eligible requests with live videos. - Added automatic voter email notifications after community-request publication. - **Bug Fixes** - Improved publication handling across direct and queued video workflows. - Added recovery for incomplete voter notifications and missed publication transitions. - **Documentation** - Documented the community-request history and reconciliation API endpoints. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
2867c22f68 |
fix(review): restore per-suggestion undo for server-pre-applied AI corrections (#981)
## Summary - The server-side pre-apply feature (#957) bakes AI lyric corrections into the review data before the page loads, but the review UI's per-item Undo and "Revert all" controls in the "N auto-corrections applied" panel relied on client-side-only undo bookkeeping that was never populated for pre-applied jobs — so both were silently hidden. Reported by Andrew: `Undo All` did nothing and the auto-corrections panel offered no way to revert individual corrections (e.g. https://gen.nomadkaraoke.com/en/app/jobs/#/8a94db60/review). - `apply.py` now records per-suggestion undo info (removed words, new word ids, segment) at apply time; `pre_apply.py` persists it in `metadata.auto_approval.undo_info`; `useAutoCorrect` seeds its undo map from that on load so per-item Undo / Revert All work the same for pre-applied jobs as for client-applied ones. - Jobs pre-applied *before* this fix ships simply have no undo info (same as a stale suggestion), so the buttons correctly stay hidden only for those older jobs. - The Header "Undo All" button is unchanged — it correctly resets in-session manual edits back to page-load state and was never meant to revert AI corrections baked in before load. - Added a Lessons Learned entry on the underlying pattern (server-applied state needs its own undo data, not just client undo state). ## Test plan - [x] `python -m pytest backend/tests/services/auto_approval/` — 163 passed (18 in `test_apply.py`, including 5 new tests covering `undo_out`/`undo_info` for replace/delete/insert_after) - [x] `npx jest hooks/__tests__/useAutoCorrect.preapplied.test.ts` — 5 passed (3 new, covering undo seeding, `canUndo`, `undoAccept`, and `revertAll` against server-provided undo info) - [x] `npx jest --testPathPattern lyrics-review` — 357 passed, no regressions - [x] `tsc --noEmit` and `eslint` clean on all touched files - [ ] Local CodeRabbit CLI review — could not run (`coderabbit auth status` is tied to a different org's SSO session); opening without `@coderabbitai ignore` so the GitHub bot reviews instead 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> |
||
|
|
bedbcdc3bd |
Requests board: skip songs with existing community karaoke versions (submit + pick time) (#979)
## Summary Stops the requests board from spending a free track — or wasting voters' time — on a song that **already has a good community karaoke version online**, reusing the same KaraokeNerds check the normal job-submission flow uses, at two points. Follow-up to the requests-board Phase 2 automation (#977). Addresses Andrew's two asks: **A) Submission time (soft, non-blocking).** As a signed-in user types an artist/title on the board, we debounce-check KaraokeNerds and surface any existing community versions in a dismissible banner with YouTube links. They can still request it — but many will just watch the existing one. Reuses the existing `POST /api/catalog/community-check` endpoint + `CommunityVersionBanner` component (added an optional board-appropriate subtitle). **B) Pick time (review).** A song may have had no version when requested but gained one by the time it's upvoted to the top. So the daily picker now KaraokeNerds-checks each candidate **in rank order**: - A candidate that already has a community version is **flagged for review** (`review_state=pending`) instead of auto-made, and the picker **skips to the next clean request** — so a fresh, non-duplicate free track still ships that day. - Andrew is emailed a summary and resolves held picks at **`/admin/community-reviews`**: **Make ours anyway** (creates the job like a normal pick), **Reject** (declines and emails every up-voter a link to the existing version), or **Keep on board** (leaves it votable, snoozing re-review for 30 days). - Held requests stay visible/votable on the board; they just aren't auto-made. Flag/email is idempotent (no daily re-nag). ## Andrew's decisions (via AskUserQuestion) Held pick → **skip to next clean request**. Review surface → **admin queue page + email**. "Keep" → **return to board, snooze re-review (30 days)**. ## Changes - **Model:** `SongRequest.review_state` (pending|snoozed), `community_versions`, `community_checked_at`, `review_snoozed_until`. - **Service:** `list_pick_candidates` (skips review-blocked), `set_review_pending` (transactional/idempotent), `snooze_review`, `clear_review`, `reject_request`, `list_pending_reviews`. - **Picker:** candidate loop + community check; extracted `_provision_and_start` shared by the picker and the admin "make" action. - **Admin:** `GET/POST /api/admin/community-reviews`, `/admin/community-reviews` page + sidebar item. New existing-version email to up-voters (33 locales). - **Frontend:** board submit form debounced check + banner. ## Testing - Picker candidate loop (flag dup → make next clean; all-dup → empty + flagged; resume skips re-check), admin actions (make/reject/keep, 404, 500), emulator coverage for the new service methods. 86 passing across touched suites; frontend typechecks clean; 32/32 locale parity. ## Deploy No `infrastructure/` changes — merge deploys it. The daily picker is already enabled in prod, so the pick-time check goes live with the backend deploy; the submission banner ships with the frontend. ## Review CodeRabbit reviewed locally (one minor grammar nit, fixed). @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
d41854f787 |
feat(requests-board): public song-request voting board (Phase 1) (#975)
## What & why
Phase 1 of the **daily-free-community-track** initiative (BACKLOG:
*"Daily free community track via public voting board"*). A public,
Hacker-News-style voting board at **requests.nomadkaraoke.com** where
anyone signs in with an email magic link, submits a song request
(artist/title auto-corrected + deduped), and casts **one vote per
calendar day**. Publicly viewable so it can be linked from YouTube
descriptions to drive top-of-funnel awareness.
Ships the board first (this PR) so the linkable URL exists; the
automation (daily auto-picker, free-credit grant on pick, 24h ownership
handoff, voter publish-emails, and the trending-karaoke agent as a
fallback request source — one free track/day total) is **Phase 2**.
Design doc: `docs/archive/2026-09-02-requests-voting-board-plan.md`.
## Backend
- New `song_request` models + service (Firestore `song_requests` /
`song_request_votes`) with transactional vote arithmetic (create / move
/ flip / toggle-off), dedupe, and ranking. One-vote-per-day is enforced
structurally via the vote doc id (`{email}__{YYYY-MM-DD}`).
- New `/api/requests-board` router: `GET /requests` (public, annotates
the caller's vote), `POST /requests` (submit — auto-corrects via the
existing `match_judge`), `POST /requests/{id}/vote`, `GET /me`.
- Board sign-in (`purpose="requests_board"`): passwordless identity only
— **no welcome credit**, a **higher per-IP signup cap**
(`BOARD_MAX_SIGNUPS_PER_IP`, default 30) so a shared venue WiFi can
register many voters while the per-fingerprint cap stays strict, and
`redirect_path="/requests"`.
- New `POST /users/claim-welcome-credit` powers the "Make it yourself
now" conversion (grants the standard credit the normal way, idempotent).
## Frontend
- `app/[locale]/requests` board: submit form with "we tidied that to…"
feedback, ranked vote list with daily-vote UX, convert-to-gen CTA,
recently-made list with YouTube links.
- API client methods + types; verify page honors `redirect_path`; new
`requests` i18n namespace translated to **all 33 locales**.
- `requests` added to `nonTenantSubdomains`.
## Testing
- 20 backend unit tests (routes + pure logic + sign-in + board signup
limit) and 8 emulator tests exercising **real Firestore transactions**
(vote arithmetic, dedupe, idempotent resubmit, one-vote-per-day). Full
backend unit suite green (4247 passed); frontend typecheck clean.
- Reviewed locally with CodeRabbit CLI (3 cycles); all findings
addressed (auth headers, idempotent resubmit, signup-limit hardening,
blank-input validation, i18n particle, refresh race).
## Deploy note
The board is reachable at `gen.nomadkaraoke.com/en/requests` on deploy.
Wiring the vanity `requests.nomadkaraoke.com` is a **post-deploy
Cloudflare step** — see
`docs/runbooks/requests-subdomain-cloudflare.md`.
@coderabbitai ignore
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
3c58143f75 |
fix(review): re-sign instrumental preview URLs on expiry (refresh-on-error) (#973)
## Problem
Completing a combined review failed to play the instrumental in the
preview modal — toggling to **Instrumental** loaded nothing, with
`NS_ERROR_DOM_NETWORK_ERR` in DevTools (Firefox) on the
`review-audio/instrumental_with_backing.ogg` GCS request.
**Root cause:** the overlaid instrumental `<audio>` uses the signed GCS
URL baked into the review payload at page load, which has a **120-minute
expiry**. A long review session outlives it, so the stem fetch returns
`400 ExpiredToken` and playback silently fails. Confirmed by fetching
the exact URL from the report: `ExpiredToken — Request signature expired
at 2026-09-01T20:16:26Z` (page had been open ~2h11m).
Reloading didn't help because the review UI persists the full
`CorrectionData` — including `instrumental_options[].audio_url` — to
`localStorage` (`lyrics_analyzer_data`) and rehydrates it when the user
has unsaved edits, so the *same* expired URL came back.
The `[SW] Service worker registered` log is a red herring:
`frontend/public/sw.js` has no `fetch` handler.
## Fix (refresh-on-error)
- **Backend:** extract a shared `_build_instrumental_options` helper and
add `GET /api/review/{job_id}/instrumental-urls` returning
freshly-signed stem URLs.
- **Frontend:** on the stem `<audio>` `error` event, re-fetch fresh URLs
via the new endpoint and swap them in. The existing video↔audio sync
effect (keyed on the URL) resumes playback in place. Capped at 3
refreshes per modal open so a genuinely-broken stem (404) can't loop.
No new user-facing strings (the recovery is silent) → no i18n changes.
## Testing
- Backend: 3 new tests for the endpoint (both stems / single stem / 404)
— `TestInstrumentalUrlsRefresh`. Full `test_routes_review.py` +
`test_combined_review_flow.py` + `test_audio_transcoding_service.py` =
111 passed.
- Frontend: 3 new `PreviewVideoSection` tests (swap on error / cap at 3
/ no-op without refresh fn). Full unit suite = 1248 passed.
- CodeRabbit local review: no findings.
@coderabbitai ignore
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
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> |
||
|
|
e58334e461 |
Preview modal UX: audio toggle, backing-vocals waveform, cohesive loading & saving flow (#961)
## Summary
Five UX improvements to the lyrics-review **Preview Video** modal (shown
when the reviewer clicks "Preview Video").
1. **Unified loading** — the `generating` and `encoding` states now
share one centred spinner; only the stage message changes ("Preparing
your preview…" → "Encoding preview video…" → slow-encoder hint). No more
janky layout swap.
2. **Audio toggle (Original ↔ auto-selected Instrumental)** — a hidden
stem `<audio>` element (from `instrumental_options`, already in the
review correction-data) is kept in lock-step with the video
(play/pause/seek/rate/drift ≤0.25s). Switchable mid-playback with
position preserved. Title dropped "(With Vocals)" → just "Preview
Video".
3. **Removed low-value text** — deleted "No manual corrections
detected…" and "Total segments: X". The manual-corrections note now only
shows when the reviewer actually edited.
4. **Backing-vocals waveform** (new `BackingVocalsWaveform`) — only when
the auto-selector kept backing vocals (`with_backing`, confident, and
the stem is playable). Thin 35px canvas of the backing stem (from `GET
/api/review/{jobId}/waveform-data`); clicking seeks the video and
switches audio to the instrumental, for quick sanity-checking of the
automatic pick.
5. **"Complete Track" saving flow** — the modal stays in its "Saving…"
state through the slow `completeReview` call, so it no longer flashes
back to the review screen before the "Review Submitted" view.
Also: `getWaveformData` added to the review API client factory; version
`0.209.2 → 0.210.0`.
## i18n
- Keys added
(`previewVideo.audioLabel/audioOriginal/audioInstrumental/backingVocalsWaveformHint`,
`modals.reviewChanges.previewTitle`) and removed (`previewWithVocals`,
`noManualCorrections`, `totalSegments`); all 33 locales synced via
`translate.py`. Keys-only parity passes.
## Testing
- Frontend jest: **1230 passed / 98 suites** (26 in the two touched
modal/preview suites, incl. audio-toggle mute + backing-waveform
gating).
- Manually verified against **real prod jobs** via local dev (proxying
to prod API):
- `ae225662` (clean pick): audio toggle mutes video + plays clean stem
synced to the same position; waveform correctly hidden.
- `370f7b92` (with_backing pick): 35px backing waveform renders;
clicking it seeks the video (102.5s→138.8s) and the instrumental audio
follows in lock-step.
- Local CodeRabbit review run and its 2 minor findings addressed
(playbackRate sync on audio switch; gate waveform on stem availability).
@coderabbitai ignore
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
3680ed66b3 |
Full-auto review: per-screen skip + server-side pre-apply + submission autonomy UI (workstream C) (#957)
Completes the fully-automated-review initiative (workstream C — the final build item). Three interlocking parts, all shipped in one PR. ## C1 — Per-screen skip Only show the review screen that actually needs a human. - **Confident backing → skip the instrumental screen.** Completing the lyrics review finishes the whole job. The client sends `instrumental_selection="auto"`; the backend resolves it from the stored verdict (`resolve_auto_instrumental`), so CLI/tenant clients get the skip for free. - **Mirror case (only backing gates) → skip the lyrics screen.** The router deep-links straight to `#/instrumental`; the server-pre-applied corrections are the lyrics payload. - **Escape hatch:** a "let me choose the instrumental myself" toggle in the finish modal. - `always_review` jobs never auto-skip (gated server-side in the shared summary). ## C2 — Server-side pre-apply (kills the on-load edit race) Andrew's directive: apply the AI/heuristic corrections *before* the review-ready notification, so the review screen loads one final state. - New `pre_apply.ensure_and_pre_apply` runs in `screens_worker` before the `AWAITING_REVIEW` transition: ensures the suggestion cache (bounded, fail-open), applies with the same machinery the executor uses (`apply.build_applied_segments`), and writes `corrections_updated.json` with a `pre_applied` marker. - `useAutoCorrect` gains a `preApplied` mode: no client-side auto-run/auto-apply, panel seeded read-only from the server's applied/rejected ids. Backward compatible (no marker → today's behavior). ## C3 — Submission autonomy UI - **Review mode** (fully automatic / always let me review) + **backing-vocals preference** (keep-where-possible / clean / let-me-choose) toggles in the guided flow. - Plumbed through every submission route + `JobCreate`; **33 locales** translated. ## Shared source of truth `instrumental.backing_decision` is the one place the executor, the complete-review `"auto"` resolver, and the UI summary all derive the instrumental decision — they can't drift. ## Tests - Backend: `test_instrumental.py` (decision matrix, summary/resolver incl. always_review gating + stem checks, JobCreate coercion), `test_pre_apply.py` (apply/marker/fail-open), executor `backing_preference` cases. Full auto_approval suite: 112 pass. Touched route suites: green. - Frontend: `useAutoCorrect.preapplied` + `ReviewChangesModal` escape-hatch tests. Full Jest suite: 1218 pass. - i18n completeness enforced by CI. Local CodeRabbit review completed and addressed (always_review gating, stem-availability check, out-of-set preference coercion). @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
5d6a6d4f1b |
fix(review): async preview video generation — survive encoder cold-starts (v0.207.0) (#954)
## Summary
Preview videos in the lyrics review UI got stuck on "Generating preview
video..." whenever the GCE encoding worker needed a cold start (job
`326e1aef`, 2026-08-29): the synchronous `POST /preview-video` held the
connection for 2m36s while three zones were stocked out and a fallback
VM booted — Cloudflare cuts browser connections at ~100s, so the UI
never saw the (successful!) response.
### Backend
- `POST /api/review/{job_id}/preview-video` now returns `{"status":
"generating", "preview_hash"}` immediately after the ASS subtitles are
uploaded; encoding runs in a background asyncio task (established
pattern in this file): GCE encode → local render fallback → GCS error
marker (`previews/{hash}.error.json`) if both fail
- Cache short-circuit: the preview hash is deterministic over the
correction data, so an identical retry returns the existing mp4
instantly as `{"status": "success"}`
- New `GET /api/review/{job_id}/preview-video/{hash}/status` poll
endpoint — GCS-backed (mp4/error-marker existence), so polls work across
Cloud Run instances
- Blocking prep work (GCS downloads, ASS generation) moved to
`asyncio.to_thread` so it no longer stalls the event loop
### Frontend
- `PreviewVideoSection` polls the status endpoint (3s interval, 5-min
cap), escalating to a "starting up an encoding server — this can take a
couple of minutes" message after 30s
- Fixed the Retry button: it previously reset state without
re-triggering generation (spun forever) and was hardcoded English; now
works via a retry nonce and is translated
- Removed the dead `worker_starting` branch (a status the backend never
returned)
- New i18n keys (`encoding`, `timedOut`, `retry`) + updated
`startingEncoder` translated for all 33 locales
## Testing
- 9 new backend tests: cache-hit, generating + background spawn +
stale-marker cleanup, status endpoint (ready/error/generating),
background task (GCE success / local fallback / error marker)
- 7 new Jest tests for `PreviewVideoSection`: cache hit,
poll-until-ready, transient poll failure, terminal error stops polling,
timeout, Retry re-runs, missing hash
- Full suites green: backend 4093 ✓, karaoke_gen unit 1779 ✓, frontend
Jest 1203 ✓, `tsc --noEmit` no new errors vs main, translation
`--keys-only` validation ✓
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
|
||
|
|
f01213f5cb |
Fully-auto review for confident jobs: review_mode framework + auto-approval scorer/executor + replay tool (v0.202.0) (#947)
## Summary Ships the **fully-automated review framework**: jobs now default to `review_mode="auto"` — when the auto-approval scorer is fully confident on BOTH axes, the combined review screens are skipped entirely and the job renders straight through. Everything else falls back to human review exactly as before. **The confident class (deliberately narrow to start, ~5% of jobs expected):** - **Lyrics**: synced reference present, ≥90-99% anchor coverage, and every gap word covered by the pre-generated AI auto-correct suggestions (which the executor applies server-side — a faithful port of the review UI's on-load auto-apply, including conflict-group resolution) — OR zero gaps outright. - **Backing vocals**: non-subjective only — no audible backing content → clean instrumental. - **Never-auto gates**: vocalization sections (da-da-dun/woo-woo — P3), phantom/absurd-duration lines (P8), too-few-words, no/unsynced reference, errored backing analysis. **Calibrated against a 20-job human-review corpus** (all recent admin reviews replayed + annotated): safety 100% (every job that truly needed a human stays in review), lyrics-auto 3/20, overall-auto 1/20. ## How it works - `screens_worker` (pre-AWAITING_REVIEW) and `audio_worker` (post-stems, for the audio-lags-lyrics ordering) both call `maybe_auto_complete_review()`. Every job gets a verdict recorded in `processing_metadata.auto_approval` (shadow data keeps accumulating for calibration); enforcement additionally requires: flag on + `review_mode="auto"` + not made-for-you + no existing/custom instrumental + audio complete. - Enforce path mirrors a human "Complete Review": apply cached AI suggestions → sanity checks → `corrections_updated.json` → `instrumental_selection="clean"` → clear progress keys → `GENERATING_SCREENS→REVIEW_COMPLETE` (new legal edge; no review token or "ready for review" notification is ever issued) → trigger render worker. - **Fail-safe everywhere**: stale suggestions, duplicate-word artifacts (P1 self-conflict signature), state changed mid-enforce (human opened editor), any exception → normal human review. Auto-approval can never fail a job. - Kill switch: `AUTO_APPROVAL_ENFORCE_ENABLED=false` (scoring continues). Per-job: `review_mode="always_review"` (admin PATCH, validated). - Excluded from enforcement (still shadow-scored): made-for-you orders (human QC is part of that product), custom-instrumental jobs. ## Also in this PR (sessions 1-3 of the initiative) - **Review replay tool** (admin-only, prod-inert): `?replay=1` reopens the real lyrics/instrumental review UIs read-only for completed jobs — queue nav, Post-AI/Final toggle, edit-log action panel, dev-only audio byte-proxy (env-gated `REVIEW_AUDIO_PROXY`, path-anchored). This is what produced the calibration corpus. - `auto_approval` service package: scorer (anchor/gap/AI-coverage signals + P3/P8 gate detectors), apply engine, executor, lyrics-diff, offline capture script. ## Testing - 100+ new unit tests across scorer/apply/executor/replay routes; full backend suite 4000+ green locally (8 pre-existing emulator failures reproduce identically on pristine `main` — local-env only, green in CI). Frontend: 1196 Jest tests green. - Scorer validated read-only against the 20 real prod jobs in the private calibration corpus. @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
714f3d2ae6 |
fix: append-after-last segment crash + firestore backup same-day retry collision (#944)
Fixes two independent production issues flagged overnight (2026-08-25).
## 1. Lyrics review crash — `TypeError: Cannot read properties of
undefined (reading 'start_time')`
Error-monitor alert: `frontend` / `onAddSegmentAfter`. Clicking **"Add
segment after"** on the *last* segment calls `addSegmentBefore(data,
beforeIndex)` with `beforeIndex === corrected_segments.length`, so
`corrected_segments[beforeIndex]` is `undefined` and reading
`.start_time` throws.
**Fix** (`frontend/lib/lyrics-review/utils/segmentOperations.ts`): when
`beforeIndex` points past the end (append case), anchor the new
segment's timing/singer off the *previous* segment — start at its
`end_time` (or `0` for an empty list) — instead of dereferencing
`undefined`.
## 2. Nightly backup FAILED — `Firestore: 400 Path already exists`
`export_documents` refuses to write into an output prefix that already
contains an export. The backup Cloud Function returns HTTP 500 if *any*
step fails, so Cloud Scheduler retries the whole function — and the
retry collided with the earlier run's already-written
`firestore/{date}/…overall_export_metadata`. The existing
`_clear_prior_exports` runs *after* export and deliberately keeps
today's, so it never resolved a same-day collision.
**Fix** (`infrastructure/functions/backup_to_aws/firestore_export.py`):
new `_clear_target_prefix()` deletes any leftover `firestore/{date}/`
**before** exporting, making the export idempotent across same-day
retries.
## Tests
- `segmentOperations.test.ts`: append-after-last (`beforeIndex ===
length`) + append-into-empty — 13 passed
- `test_firestore_export.py`: asserts the stale same-day export is
deleted before `export_documents` runs — 5 passed
Version bumped `0.199.4 → 0.199.5`.
Reviewed locally with CodeRabbit CLI (no findings).
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
||
|
|
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>
|
||
|
|
e0e5959edc |
fix(review): surface relevance-filter rejection when pasting lyrics + Add Anyway force option (#937)
## Summary
Pasting reference lyrics in the review UI could silently do nothing: if
the relevance filter (30% anchor-match threshold) rejected the pasted
source during the correction rerun, the `add-lyrics` endpoint still
returned a generic success, so the paste tab cleared the box, closed the
modal, and no reference lyrics appeared — with zero feedback.
Observed in prod on job `0eebb248` ("Jonny Hill & Linda Feller –
Darling"): two "successful" add-lyrics calls, both sources rejected at
1.3% relevance (3/230 words), `reference_lyrics` left empty.
## Changes
- **Backend (`/api/review/{job_id}/add-lyrics`)**: when the source is
dropped by the relevance filter, return `{status: "rejected", rejection:
{relevance, matched_words, total_words}}` and skip persisting the no-op
rerun to GCS. Same change in the local `ReviewServer` (wheel/CLI review
mode), including `force` support it previously lacked.
- **Frontend**: `addLyrics` API client sends the `force` flag (as a
string — the endpoint body is `Dict[str, str]`, which also makes it
deploy-skew-safe). `PasteLyricsTab` keeps the pasted text on rejection,
shows a warning with the match %, and offers an **Add Anyway** button
that retries with `force=true`. Covers both the Add Lyrics modal and the
inline empty-state, which share the tab.
- **i18n**: new `pasteLyrics.rejectedWarning` / `addAnyway` strings
translated to all 33 locales.
- **Docs**: `docs/API.md` add-lyrics section documents the rejected
response.
- **Tests**: backend endpoint tests (success/rejected/force passthrough,
no-upload-on-reject), API client tests (force string, rejected
envelope), and `PasteLyricsTab` component tests (rejection UI, Add
Anyway flow, warning cleared on edit, legacy void result).
## Testing
- `make test`: full backend + frontend suite green (92 suites / 1158
frontend tests; backend 56 review-route tests incl. 3 new).
- Local CodeRabbit review completed; single finding was a pre-existing
translation nitpick (skipped).
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
|
||
|
|
1755fa138c |
fix(review): correct vocal waveform time drift on 44.1kHz audio devices (#938)
## Summary Fixes the vocal waveform in the lyrics-review timeline editor appearing shifted ~0.4–0.5s late relative to the audio in some situations (reported on job 0eebb248, segment 25 at ~171s). **Root cause:** the client-side peak envelope in `frontend/lib/audio-data.ts` floored samples-per-bucket to an integer. At a 44.1kHz `AudioContext` (device-dependent — common on Macs and audio interfaces) the exact stride is 110.25 samples but was floored to 110, making the envelope's clock run ~0.23% fast. The waveform drifted late by ~2.3ms per second of song — ~0.4s by the 3-minute mark. 48kHz devices divide evenly (120) and were unaffected, which is why the bug only appeared "in some situations". ## Changes - Bucket boundaries are now computed from the fractional stride (`Math.floor(bucket * samplesPerBucket)`), keeping every bucket within one bucket (2.5ms, non-accumulating, sub-pixel) of its nominal 1/400s position at any sample rate. - Peak computation extracted into an exported pure `computePeaks()` so it's unit-testable without a browser `AudioContext`. - 7 new unit tests in `frontend/lib/__tests__/audio-data.test.ts`, including a 44.1kHz drift regression test that fails against the old floored-stride code (impulse landed 27 buckets / 67ms late at 29.5s). - Version bump 0.198.4. ## Testing - `make test`: all backend tests + 92 frontend suites (1158 tests) pass. - New regression tests verified to fail against the pre-fix implementation. - Local 8-angle code review + CodeRabbit CLI review: no findings. @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
b5461132d0 |
feat(admin): create users from admin UI + auto-create account on job user_email reassignment (#936)
## Summary
Lets admins provision user accounts before the user has ever logged in —
so we can grant free credits, submit jobs on their behalf, and
impersonate them — and fixes the gap where reassigning a job's
`user_email` to an unknown email left the job orphaned (no account, no
credits, impersonation 404s).
### Changes
- **`POST /api/users/admin/users`** — create a user account directly:
`email` (required), `display_name`, `initial_credits` (0-1000),
`credit_reason`. Returns 409 on duplicate. Initial credits set
`welcome_credits_granted` so the user doesn't also get the automatic
welcome credit on first login.
- **`PATCH /api/admin/jobs/{id}`** — `user_email` is now trimmed +
lowercased (account doc IDs are lowercased emails; mixed case would
silently orphan the job), blank/invalid values are rejected with 400,
and a `gen_users` account is auto-created when none exists. Response
message notes the creation.
- **Admin users page** — "Create User" button + dialog; on success the
list filters to the new user so Impersonate / Add Credits work
immediately.
- **Admin jobs page** — field-save toast surfaces the account-created
message; local state mirrors the backend's email normalization.
### Testing
- New `backend/tests/test_admin_create_user.py` (9 tests) +
`TestUpdateJobUserEmailAutoCreate` (5 tests) in
`test_admin_job_update.py`
- Full backend suite: 3917 passed. Frontend: 1151 Jest tests passed;
eslint/tsc clean on touched files
- CodeRabbit local review: 2 cycles, all findings addressed (PII
redaction, blank-email 400, masked audit log, normalized local state)
Version bump: 0.198.3 → 0.199.0
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
|
||
|
|
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> |
||
|
|
41a5ba5dd4 |
fix(review): poll for vocals waveform while audio separation is in progress (#934)
## Summary
Fixes the blank vocals waveform / console error `Failed to fetch vocals
audio: 404` seen on the lyrics review screen (reported on job
`d508adb6`).
**Root cause:** audio separation is intentionally decoupled from the
lyrics-review critical path — a job reaches `awaiting_review` as soon as
lyrics/screens are done, while stems keep uploading in the background.
On job `d508adb6` the user opened review at 06:51:21 but `vocals_clean`
wasn't uploaded until 06:53:40. The `/api/review/{job_id}/audio/vocals`
endpoint correctly found no vocal stem and returned a 404, which the
frontend treated as terminal — the edit-timeline waveform then stayed
blank for the whole session even though the stem arrived two minutes
later.
## Changes
- **Backend** (`review.py`): when no vocal stem exists yet **and**
`state_data.audio_complete` is false (separation still running), return
`202 Accepted` with `Retry-After: 15` instead of 404. A missing stem
with `audio_complete=true` (e.g. existing-instrumental jobs that skip
separation entirely) still 404s, so clients don't poll forever for a
stem that will never exist.
- **Frontend** (`VocalsAudioDataLoader`, `audio-data.ts`): a 202 now
throws a typed `AudioNotReadyError`; the loader retries every 15s
(capped at 10 minutes) and renders the waveform once the stem arrives.
Terminal errors (404/5xx) still fail once without polling, and polling
stops on unmount.
## Testing
- Backend: new tests for 202-while-separating and
404-when-separation-skipped; existing vocals-endpoint tests updated with
explicit `state_data` (91 passed across related review/transcoding test
files).
- Frontend: new `VocalsAudioDataLoader.test.tsx` covering success,
retry-then-load, terminal-error no-retry, and unmount cleanup. Full jest
suite: 1146 passed.
- Verified against prod: reproduced the exact 404 from Cloud Run logs
(trace-level), confirmed the stem-upload race timeline, and confirmed
the endpoint serves the proxied OGG once stems exist.
@coderabbitai ignore
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
|
||
|
|
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>
|
||
|
|
d7482ee85a |
feat(review): vocals waveform in timeline editor — finished + fixed (takes over #895) (#927)
Vocals waveform in the timeline editor (finishes @netux's #895): backend stem-selection fix (vocals_clean), downsampled peak-envelope perf, edit-modal space reclaim, full i18n (33 locales), CodeRabbit fixes, and ReviewServer.vocals_filepath made optional. Reviewed + visually QA'd on a real job. |
||
|
|
9ac53e32b6 |
feat(frontend): read API base url from query parameters in localhost frontend (#894)
Reviewed, verified locally against fixture review data, and merged by maintainer. Thanks @netux! |
||
|
|
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> |
||
|
|
1b6833b182 |
fix(jobs): show job/log timestamps in the viewer's local timezone (#907)
## Problem Job dates on the dashboard displayed the raw UTC wall-clock instead of the viewer's local time. e.g. a job submitted at ~4:10 PM local (viewer at UTC-2) showed as `8/14/2026, 6:10:25 PM`. ## Root cause `created_at` (and timeline/log timestamps) were built from naive `datetime.utcnow()` and serialized via `model_dump(mode='json')` / `.isoformat()`, producing ISO strings with **no timezone offset** (`"2026-08-14T18:10:25.123456"`). Firestore stored them as plain strings and returned them verbatim. The frontend's `new Date(str)` parses an offset-less ISO date-time as **local** time, so the UTC value was shown unconverted — off by the viewer's UTC offset. ## Fix **Frontend (fixes all existing + new data, no migration):** - New `parseServerDate()` util in `frontend/lib/utils.ts` — treats offset-less ISO date-times as UTC (appends `Z`); passes through strings that already carry `Z`/`±HH:MM`, plus `Date`/epoch inputs. - Applied at every customer-facing server-timestamp display: `JobCard` created-at, `JobLogs` timestamps, referral payout dates, and referral-discount expiry (`BuyCreditsDialog` + dashboard). - 8 unit tests covering naive/`Z`/`+00:00`/non-UTC-offset/date-only/epoch/`Date` cases. **Backend (makes stored timestamps unambiguous going forward):** - `create_job` and timeline events now use `datetime.now(timezone.utc)`, so serialized ISO strings carry a `+00:00` offset. Arithmetic consumers (`job_health_service`) already guard for both naive and aware datetimes. ## Testing - Backend: 210 targeted tests pass (job_manager / firestore / timeline / job_health / countdown). - Frontend: full suite 1108 tests pass (85 suites), including the new util tests. ## Notes - `/admin/*` pages (English-only, internal) still use `new Date()` directly; they benefit from the backend change for new jobs but were left otherwise untouched as out of scope. - CodeRabbit local review was rate-limited (free OSS quota), so this PR intentionally omits `@coderabbitai ignore` to let the bot review. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
84b0683cba |
fix(audio-search): recover parked jobs — edit + re-search + own-audio fallback (#906)
## Problem
In Bulk Mode (and single jobs), the "Choose audio" dialog was a **hard
dead-end**. When a search returned nothing usable — 0 results, a
transient flacfetch failure, or an auto-picked source that's unusable —
the bulk worker parks the job in `AWAITING_AUDIO_SELECTION` with
**empty** cached results. The dialog then showed "No audio sources
found" with **no retry, no way to edit the title, and no manual
source**, so the user was trapped.
Real-world trigger (batch `4af58968a64a`): two Arctic Monkeys tracks
parked with 0 results (one a transient miss on a common track, one an
over-long title), and three more stuck downloading the **same dead RED
torrent** — all with no path forward.
## What this does
Adds a full recovery path to the shared `AudioSearchDialog` (used by
bulk **and** single jobs):
- **Edit + Search again** — always-available editable artist/title with
a re-search button. Edits apply to the job's search terms *and* display
metadata.
- **Provide your own audio** — paste a YouTube/yt-dlp URL, or upload a
file.
- **Graceful empty state** — a 400 (no cached results) renders as the
empty state with the refine bar, not a red error; real network/5xx
errors still surface.
### Backend (`audio_search.py`) — all guarded to
`AWAITING_AUDIO_SELECTION`, tenant-gated, no new job, no double-charge
(final duration billing reconciles post-download)
- `POST /{job_id}/research` — retry / edit-and-re-search. Empty results
are a normal `200`.
- `POST /{job_id}/provide-url` — YouTube URLs go through the **async**
audio-download worker; generic yt-dlp URLs download inline, bounded by a
timeout (never strands a job).
- `POST /{job_id}/attach-upload-url` + `/attach-upload-complete` —
signed-URL upload of the user's own file (extension allow-list +
traversal-safe; the complete step pins the exact uploaded object).
- Factored the triplicated result serialization into
`_build_result_response`.
## Testing
- 20 backend endpoint tests + 5 frontend dialog tests (all green);
broader audio/jobs sweeps pass.
- i18n: 15 new `audioSearch` keys across all 33 locales.
## Review
Local CodeRabbit review completed (2 cycles, all 6 findings addressed,
final pass 0 findings).
@coderabbitai ignore
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
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> |
||
|
|
c716c79022 |
feat(resilience): auto-recover stuck renders + transient downloads; retry 503 blips (#898)
## Why
Investigating two stuck real-user jobs (a render frozen at "[7/10]
Rendering video" for ~1.3 days, and a torrent download that gave up
after ~1h) surfaced a common gap: **a job can dead-end when a downstream
resource (encoding VM / torrent seeders / tracker) is briefly
unavailable, with no automatic recovery.** All three fixes apply the
same proven **park + periodic-retry-up-to-24h** pattern, folded into the
**existing** `recover-stuck-jobs` cron (every 5 min) — **no new
infra/Cloud Scheduler**.
## What
**1. Render staleness watchdog** (`job_health_service` +
`recover-stuck-jobs`)
A render worker killed mid-render (instance recycle / SIGKILL / lost VM)
left the job frozen at `RENDERING_VIDEO` forever — invisible to the
capacity-retry cron (which only queries `RENDER_PENDING_CAPACITY`), no
watchdog, and (per the UI) no Retry button. Now: `rendering_video` with
no progress for >45 min → re-park into `RENDER_PENDING_CAPACITY` so the
existing retry cron resets it to `REVIEW_COMPLETE` and re-renders (same
24h ceiling).
**2. Transient torrent-download retry** (new `DOWNLOAD_PENDING_RETRY`
status)
Rare tracks with few/intermittent seeders and brief tracker outages hit
gen's ~1h give-up and failed permanently ("Audio download timed out …
Use retry"). Now a stuck **RED/OPS** download parks into
`DOWNLOAD_PENDING_RETRY` and is auto-retried for up to 24h with a
friendly "we'll keep trying automatically" message; permanent failure
only after 24h. Non-torrent sources (YouTube/Spotify/URL) still fail
fast (deterministic). Per-tick dispatch cap prevents fan-out during an
audio-worker outage.
**3. VM-start 503 whole-set retry**
(`encoding_worker_manager.ensure_any_running`)
A transient `503 SERVICE_UNAVAILABLE` (distinct from a capacity
`STOCKOUT`) that hits all zones at once is retried across the whole
candidate set with backoff before giving up — but **only when every
candidate failure was transient** (a capacity or `PERMISSION_DENIED`
failure raises immediately; the 24h park handles a real shortage).
Per-candidate zone failover is unchanged.
**Frontend:** friendly i18n labels for `download_pending_retry` and
`render_pending_capacity` (the latter previously fell through to a raw
status), translated to all 33 locales.
## Verification
- The two triggering jobs were unstuck live: **`87eb17c3` completed +
published**; `7f457087` is a genuinely seedless release right now (RED
healthy for others) — exactly the case Feature 2 now auto-retries for
24h.
- Tests: render/download watchdog + retry paths, per-tick cap, 503
whole-set retry incl. the mixed non-transient case. Full backend suite
green locally.
Local CodeRabbit review completed; both findings (all-transient retry
guard; per-tick dispatch counting) were addressed with tests.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
- **New Features**
- Added automatic recovery and retries for stalled audio downloads and
video rendering jobs.
- Jobs can wait for processing capacity and resume automatically.
- Downloads now retry for up to 24 hours before permanent failure.
- **Bug Fixes**
- Improved handling of stuck downloads, renders, and transient capacity
errors.
- **Localization**
- Added retry and capacity-waiting status messages in supported
languages.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
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>
|
||
|
|
1578984f5b |
fix: filter benign ResizeObserver-loop noise from client error monitor (#878)
## Summary
The error monitor fired a 🔴 New Error Pattern alert for \`ResizeObserver
loop completed with undelivered notifications\` (on \`singa.\`, build
|
||
|
|
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) |
||
|
|
107542ac39 |
fix(encoding): scope worker warmup/heartbeat to review-auth, not admin (#862)
## Summary The lyrics-review page pre-warms the encoding VM on load (and heartbeats while the reviewer edits) so it's booted by the time they preview a render. Both endpoints — `POST /api/internal/encoding-worker/warmup` and `/heartbeat` — required `require_admin` since they were introduced (Mar 25 2026, #595). So **every non-admin customer got a 403 and the JIT pre-warm silently never fired**. Renders still completed (the encoding flow's own `ensure_any_running()` boots the VM on demand), but customers paid the full cold-boot latency the pre-warm was meant to hide. Reported via 403s in the review-screen devtools console. ## Root cause `require_admin` is an admin-only gate; the callers are ordinary customers on a customer-facing page. Admin was the wrong altitude — the rest of the review surface (`submitCorrections`, `handlers`, annotations, audio-edit…) uses `require_review_auth`, which the review page's token already satisfies. ## Fix Re-scope both endpoints to `require_review_auth` with a `{job_id}` path param: - **Backend** (`encoding_worker.py`): `POST /warmup/{job_id}` and `/heartbeat/{job_id}`, gated on `require_review_auth`. Warming the shared VM now authorizes exactly like the review page's other calls, so warmup/heartbeat succeed **precisely when** the review page works — owners, admins (bypass), and `review_token` users included. Abuse posture is unchanged: you can only warm the VM if you already have review access to a real job. - **Frontend** (`api.ts`, `LyricsAnalyzer.tsx`): thread `jobId` through `warmupEncodingWorker`/`heartbeatEncodingWorker`, only fire in cloud mode (`jobId` present — no cloud VM to warm in local mode). ## Changes - `backend/api/routes/encoding_worker.py` — review-auth + `{job_id}` path - `frontend/lib/api.ts` — job-scoped URLs, `jobId` param + guard - `frontend/components/lyrics-review/LyricsAnalyzer.tsx` — pass `jobId`, gate on it - `backend/tests/test_encoding_worker_routes.py` — review-auth contract + regression guard that these routes are **not** admin-gated - `docs/TROUBLESHOOTING.md` — note the auth change and 403 diagnosis - `pyproject.toml` — 0.188.8 → 0.188.9 ## Testing - Backend: `test_encoding_worker_routes.py` (11) + manager/persistence/system-status/retry (67 total) + `test_api_routes.py` (17) — all green. New regression test asserts the routes depend on `require_review_auth` and **never** `require_admin`, plus 401-on-no-auth and 404-on-jobless-path. - Frontend: `jest` lyrics-review + api (319) green; `tsc` clean on both changed files. - Prod verification to follow after deploy: open a review page as a non-admin customer and confirm warmup/heartbeat return 200 (not 403). @coderabbitai ignore Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
8aa41e960c |
fix(lyrics-review): recompute segment times on Ctrl+click word delete (#861)
## Summary
- Ctrl+click "delete word" mode in the lyrics review Synchronizer
removed the word but left the **segment's** `start_time`/`end_time`
pointing at the deleted word — deleting the first word left the segment
starting too early; the last word left it ending too late.
- This diverged from the Edit-segment modal, which recomputes the
segment bounds on every word change. The two paths now behave
identically.
## Root cause
`deleteWord()` in
`frontend/lib/lyrics-review/utils/segmentOperations.ts` built the
updated segment with `{ ...segment, words, text }`, spreading the stale
`start_time`/`end_time` and never recomputing them from the remaining
words. The correct path (`EditModal.updateSegment`) filters the
remaining timed words and takes `Math.min`/`Math.max` (or `null` when
none remain). `LyricsAnalyzer.tsx:667` is the sole caller of
`deleteWord`.
## Changes
- `deleteWord` now recomputes `start_time`/`end_time` from the remaining
words (null when no timed words remain), mirroring
`EditModal.updateSegment`.
- Added 5 unit tests to `segmentOperations.test.ts`:
first/last/middle-word deletion, all-untimed remainder → null bounds,
and only-word deletion → whole segment removed.
## Testing
- [x] New `deleteWord` tests: red before fix, green after
- [x] Full `segmentOperations` suite: 11/11 pass
- [x] Full frontend jest suite: 82 suites / 1068 tests pass
- [x] `tsc --noEmit`: no new type errors in changed files
## Review
- [x] Local CodeRabbit review completed (0 findings)
- [x] Review feedback addressed
@coderabbitai ignore
---
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
||
|
|
37b405b9c6 |
fix: reject untimed lyrics before render + retry transient GDrive drops (#859)
## Summary
Triage + fix for a batch of Discord prod error alerts. Grouped into 3
root causes; fixed the two actionable ones.
### Group A — render/preview crash on untimed lyrics (PRIMARY,
job-breaking)
All the `unsupported format string passed to NoneType.__format__` and
`'<' not supported between instances of 'NoneType' and 'float'` alerts
were **one root cause**. Job `231806a4` ("Nelly Furtado - Maneater") had
Danish custom parody lyrics with **all 50 segments + 364 words
`start_time`/`end_time` = null** — the user pasted lyrics into the
Synchronizer's *Edit Lyrics* modal (which creates untimed segments as an
intermediate state) but never tap-synced, then triggered preview +
render. The output pipeline crashed cryptically at ~6 None-unsafe timing
sites instead of rejecting cleanly.
**Fix — fail loudly with an actionable message instead of crashing:**
- New shared gate `validate_segment_timing()` (`LyricsTimingError`) at
the top of `OutputGenerator.generate_outputs()` — covers preview + local
render + encoder.
- `render_video_worker` gates right after loading corrections,
**before** any expensive work or encoder dispatch — stops the
GCE-encoder crash *now*, without an encoder-wheel redeploy.
- Preview endpoint maps `LyricsTimingError` → **422** "synchronize
first" (was a cryptic 500).
- Defense-in-depth: `segment_resizer` debug logging is now None-safe (a
log line must never crash the pipeline).
- Frontend: block **Submit** when untimed words remain, pointing the
user to the synchronizer (`countUntimedWords` mirrors the backend gate).
### Group B — GDrive "brand_code search incomplete: N/3 subfolder(s)
failed"
Transient connection drops (`SSL: UNEXPECTED_EOF_WHILE_READING`, `Broken
pipe`) against idle Cloud Run containers. Wrapped the per-subfolder
Drive lookups in the existing retry-with-backoff + service-reset so
single drops self-heal.
### Group C — investigated, transient, no code change
- `request_audit_error` + "Exception in ASGI application" = one
Firestore *transaction-expiry* on
`/api/admin/rate-limits/blocklists/allowlisted-domains` (count 1,
admin-only).
- `Default STARTUP TCP probe failed … DEADLINE_EXCEEDED` = one slow cold
start that **succeeded on retry** at 12:10.
## Testing
- `test_timing_validation.py` (incl. all-null regression fixture
matching job 231806a4)
- None-safe resizer logging test
- GDrive transient-recovery + retry-exhaustion tests
- Frontend `countUntimedWords` Jest tests
- Re-ran output/, gdrive, render-worker, review-custom-lyrics,
generate_outputs-consumer suites — all green. CodeRabbit: 0 findings.
## Notes
- Frontend guard toast uses a plain string to match the existing
hardcoded toasts in `handleSubmitToServer` (no new i18n key → no locale
churn).
- Detail: `docs/archive/2026-07-01-render-untimed-lyrics-crash-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>
|
||
|
|
ef65adedc7 |
feat: richer DRM-URL guidance + validate at 'Use this URL' (follow-up to #855) (#856)
## Summary Follow-up to #855 (the Apple Music DRM-URL fix). Two improvements to how we guide users who paste an undownloadable streaming link: ### 1. More downloader options + Google-search fallback The DRM rejection now offers richer guidance: - **Apple Music** → https://am-dl.pages.dev, https://aplmate.com - **Spotify** → https://spotdown.org, https://spotmate.online - **Everything else** (Tidal, Amazon Music, Deezer, Pandora) → a Google search link for "`<platform> downloader`" `_DRM_DOWNLOADER_SUGGESTIONS` now maps platform → list of URLs, and a new `_drm_unsupported_detail()` helper picks `drmUrlUnsupportedWithLink` (known tools) vs the new `drmUrlUnsupportedSearch` (web-search fallback). `LinkifiedText` already renders multiple URLs as clickable links, so no frontend change was needed for the message itself. ### 2. Validate at "Use this URL", not just final submit Previously the guided flow collected the URL early but only surfaced the DRM rejection at **final submit** — after the user walked the entire flow. Now the "Use this URL" button calls a lightweight **`POST /api/jobs/validate-url`** endpoint (reuses `_unsupported_url_platform` + `_drm_unsupported_detail` — single source of truth, no duplicated list/links/i18n), shows the guidance immediately with a "Checking…" spinner, and blocks advancing. Fails open on network error since the final submit still validates server-side. ## Review notes (CodeRabbit, local) - Generalized Amazon Music host matching; `urlparse().hostname` for robustness; locale-neutral comma join (not English "or"). - **Kept** the third-party downloader links by design — explicit product decision (the third-party/link-rot risk is acknowledged; `_DRM_DOWNLOADER_SUGGESTIONS` makes updates one-line). - Disabled the URL input during validation to avoid a stale-result race. - Skipped a suggested 400-handler in `validateJobUrl`: the endpoint returns **200** with `{supported:false}`, not 400. ## Testing - Backend: `TestUnsupportedDrmUrl`, `TestValidateJobUrlEndpoint` (+ existing) — `test_file_upload.py` 151 passed. - Frontend: new `AudioSourceStep` interaction test (Apple Music URL blocked at "Use this URL" with a clickable downloader link, no advance) + `LinkifiedText` tests — 32 passed; full job/ui suites green. Details: `docs/archive/2026-06-27-apple-music-url-download-errors.md` 🤖 Generated with [Claude Code](https://claude.com/claude-code) @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
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>
|
||
|
|
ec41ad5e5e |
feat: colorize word pills when a song has no reference lyrics (#850)
## Summary
- When a song has **no reference lyrics**, nothing classifies words as
anchor/gap/corrected, so every word pill rendered uncoloured — losing
the colour-scanning the review UI is built around (see attached
screenshot: every line plain grey).
- Adds a lowest-precedence **gap-orange** fallback for plain word pills,
gated on "no reference lyrics" (the same
`Object.keys(reference_lyrics).length === 0` signal `GuidancePanel` uses
for its "No reference lyrics found" panel).
- Works in **both Simple and Advanced** modes — threaded through the
single `wordPositions` render path both modes share.
## Changes
- `lib/lyrics-review/types.ts` — new `fallbackGapColor?: boolean` on
`WordProps`.
- `components/lyrics-review/shared/Word.tsx` — appends the fallback to
the end of the colour chain, so any real classification colour
(playing/AI/anchor/user-edited/corrected/gap) still wins.
- `components/lyrics-review/shared/HighlightedText.tsx` — new
`noReferenceFallback` prop, passed down as `fallbackGapColor` to both
`WordComponent` render paths.
- `components/lyrics-review/TranscriptionView.tsx` — computes
`hasReferenceLyrics` and passes
`noReferenceFallback={!hasReferenceLyrics}`.
- `components/lyrics-review/shared/__tests__/Word.test.tsx` — new
focused test (5 cases) verifying the orange appears only with the
fallback flag and never overrides a real classification colour.
- No new user-facing strings → no i18n changes.
## Testing
- [x] Frontend unit suite: 79 suites / 1049 tests pass (incl. new
`Word.test.tsx`)
- [x] Typecheck clean on all touched files
- [x] CodeRabbit CLI review: 0 findings
## Review
- [x] Local CodeRabbit review completed
- [x] No issues to address
@coderabbitai ignore
---
🤖 Generated with [Claude Code](https://claude.com/claude-code)
https://claude.ai/code/session_01E8pq3aMDRkcPdrsmd1PqHH
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>
|
||
|
|
b6dcf6602d |
feat: match-judge improvements — parallel tidy + hard gate, two-way toggle, weak-tier AI verify, preview perf (#841)
## Summary Four follow-ups to the artist/title **match judge** (shipped in v0.184.1), per `docs/archive/2026-06-16-match-judge-improvements-prompt.md`: ### 1. Race fix — parallel tidy + hard gate The judge previously ran only *after* the audio search resolved, leaving a window where a user could select audio with un-tidied metadata (or have a late verdict clobber their pick). - Split into a **`fast`** catalog-only pass (fired on mount, parallel with the audio search) and a **`full`** pass (with the tier, may use AI). New `stage` field + `needs_ai` marker on `/api/catalog/match-judge`. - **Hard-gate** all audio-selection buttons until the judge settles, with a subtle "Checking song details…" indicator. A 12s safety timeout guarantees release. Impossible to reach Step 3 with un-tidied metadata in the normal flow. ### 2. Two-way tidy/correction toggle The notice now switches **both directions** — canonical ⇄ what-you-typed — instead of a one-way undo. The current value is always clear. ### 3. Title-screen preview performance `TitleCardPreview` + `KaraokeBackgroundPreview` rendered a 3840×2160 (4K) canvas and loaded a 2.7 MB 4K PNG for a small thumbnail. - Render at preview resolution (960×540, dpr-aware) via a scale transform. - Low-res background assets (~540 KB) for the preview; 4K stays for the real render path. - Preload backgrounds at Step 2; show a loading spinner. ### 4. Catalog-match trust — verify weak matches with AI A confident catalog match could land on a junk/misspelled Spotify entry (prod: `Queen / Bohemian Rapsody` → wrongly "already canonical"). Now, when audio results are weak (tier 3), the AI judge verifies the catalog match and can override. Extra cost (~$0.0003/call) only on weak-result cases. ## Testing - **Backend:** new unit tests for `fast`/`full` staging, `needs_ai`, weak-tier AI override + keep-catalog-on-unconfident/failure/disabled; route tests for `stage` forwarding. Full suite green (3510 passed). - **Frontend:** Jest coverage for fast-on-mount, gate disable→enable, 12s timeout release, full-pass-only-when-needed, two-way toggle; `TitleCardPreview` preview-resolution canvas + low-res bg + spinner. Full unit suite green (1024 passed). - `make test` green; `tsc` introduces zero net-new errors; ESLint clean. ## i18n 6 new keys (`matchUsingTyped`, `matchUseTidied`, `matchUseCorrection`, `matchChecking`, `titleCardPreview.loading`, `karaokeBackgroundPreview.loading`) translated to all 32 locales. ## Notes Preserves all "constraints from history": no Step-1 autocomplete, cosmetic never restarts the audio search, deferred job creation, public brand rule, audio-before-customize ordering. 🤖 Generated with [Claude Code](https://claude.com/claude-code) @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
ffa9558db5 |
feat: artist/title match-judge — auto-tidy formatting, replace 'database' panel (#836)
## Summary Reworks the **artist/title matching, suggestions & auto-correction** on Step 2 of the Create Karaoke Video flow. The confusing green **"Song found in our database"** panel is gone; formatting is now tidied intelligently and (mostly) invisibly. Driven by a new backend **match judge**: a deterministic normalizer + the karaoke-decide catalog run first, and a light Vertex Gemini model (`gemini-3.5-flash`) is consulted **only** when those aren't confident. ### Behaviour (Step 2) - **Cosmetic** fix (casing/punctuation/diacritics, same song) → applied **silently**, with a quiet *"Tidied to X · keep what I typed"* line. **Never** re-runs the audio search. - **Confident content** fix (e.g. `Yesteray → Yesterday`) → applied with a *"Corrected to X · Undo"* line, and re-runs the audio search **only when the original results were weak** (tier 3). - **Ambiguous** → ask-first *"Did you mean…?"* prompt before changing anything. - **None** → no change. Resilient by design: the judge never blocks job creation — on timeout/error it returns `none`. Kill switch: `MATCH_JUDGE_ENABLED=false` (deterministic + catalog still run). ## Why The catalog panel existed only to nudge official formatting (quality bar for published tracks), but read like "we already have this karaoke video." User feedback flagged it as confusing. This preserves the formatting-hygiene benefit while removing the friction/confusion. Design + history review in `docs/archive/2026-06-15-artist-title-matching-rework-plan.md`. ## Preserved (hard-won lessons honoured) - No Step-1 autocomplete; suggestions stay on Step 2. - Cosmetic correction never restarts the audio search (existing `onArtistTitleCorrection` no-restart path reused). - Deferred job-creation / search-session pattern untouched. - `stringSimilarity`/`findFuzzyMatches` kept as pure utils (existing tests green). - No changes to step structure, visibility/customize ordering, or the public-style brand rule. ## Changes - **Backend**: `backend/services/match_judge/` (classifier → AI judge → orchestration), `POST /api/catalog/match-judge`, config (`MATCH_JUDGE_ENABLED`/`MATCH_JUDGE_MODEL`/`MATCH_JUDGE_TIMEOUT_MS`). - **Frontend**: `api.matchJudge`, Step 2 rewired, green panel removed, new `MatchNotice` component; 5 `jobFlow` i18n keys across all 33 locales. - **Docs**: API.md endpoint section + design/plan doc. Version → 0.183.0. ## Testing - Full suite green: backend (unit + integration + emulator, coverage gate passed) + **1008 frontend tests** + e2e. - New: 20 backend tests (classifier, AI mapping, orchestration, endpoint) + updated `AudioSourceStep` tests (cosmetic tidy, ambiguous ask, none, failure-silent) + preserved fuzzy-matching tests. - CodeRabbit: 1 finding fixed (Literal types), 1 false positive. ## Follow-ups (separate PRs) - Title-screen preview perf (4K canvas/bg → low-res + preload + spinner). @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- 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> |
||
|
|
364e4ebd5f |
feat(auto-correct): proactive multi-model suggestions + cost logging + de-AI-ified review UI (#816)
## Summary Makes AI lyrics auto-correction run **automatically on every job** (multi-model), so suggestions are cached and ready the moment the reviewer opens the lyrics UI — plus token/cost instrumentation and a UI cleanup that removes all "AI"/"model" wording. Measured cost first (`scripts/measure_autocorrect_cost.py`): **~$0.13/track** multi-model on normal songs — cheap enough to run proactively. ## Changes **Cost instrumentation** - Capture per-model `usage` from Anthropic + Gemini; log greppable `auto-correct usage` / `auto-correct cost … total_est_cost_usd=…` lines from `suggest()`. - `backend/services/auto_correct/pricing.py` (Anthropic rates authoritative; Gemini estimated) + `scripts/measure_autocorrect_cost.py` offline harness. **Proactive generation (every job)** - `lyrics_worker._run_proactive_auto_correct()` runs the multi-model path after `mark_lyrics_complete` (downstream already triggered → non-blocking), gated by `AUTO_CORRECT_PROACTIVE_ENABLED`, bounded by a 180s timeout, and **swallows every error** — it never blocks or fails the karaoke job (flaky AI / out of credits / timeout all degrade gracefully). - Cache-key aligned with the UI request, so the review page's on-load call is an instant cache hit (no double spend). - `ci.yml`: wires `AUTO_CORRECT_*` env + the `anthropic-api-key` secret onto `lyrics-transcription-job` (same SA as the API service — no IAM change). **Review UI** - Always multi-model (removed the model-selection toggle); button renamed **"Auto-correct"**; stripped model/consensus/cached attribution badges; reworded strings to drop "AI"/"model" (translated to all 32 locales). - Auto-runs once on review load so suggestions are ready without a click; the button stays for the paste-references-later flow. ## Testing - Backend: **3460 passed** (`backend/tests/`, emulator excluded) — incl. new `test_pricing.py` + `test_proactive_auto_correct.py` (gating, graceful failure, cache alignment). - Frontend: **1006 jest tests pass**; type-clean; 33-locale key parity verified. ## Notes / follow-ups - Proactive activates on the **next deploy** (the lyrics-job env/secret apply via this PR's ci.yml on merge). - Left "AI" wording in two *separate* features untouched (different subsystems): `lyricsReview.agenticMetrics` and `lyricsReview.modals.correctionAnnotation` — flagged for a separate decision. - The production E2E spec's click-to-open flow may want a tweak now that suggestions auto-run on load. @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
0dd5d404e5 |
feat: cache AI auto-correct suggestions per job (free re-runs on unmodified lyrics) (#815)
@coderabbitai ignore
Per Andrew: clicking AI Suggest twice on the same unmodified lyrics
shouldn't spend AI tokens twice.
Suggestions are now cached per job in GCS
(`jobs/{job_id}/lyrics/auto_correct_cache/{hash}.json`), keyed on the
exact input — word ids + texts, reference lyrics texts, settings knobs,
and the resolved model list. A repeat run on byte-identical input
returns the previous suggestions instantly with `cached: true` (teal
"cached" badge in the panel) and incurs no LLM cost. Any edit to the
lyrics, references, or settings produces a new key and a fresh run; word
ids in the key guarantee cached suggestions always reference words that
still exist.
Cache reads/writes are strictly best-effort — any storage failure
degrades to a normal uncached run (tested). 7 new backend tests (hit
skips model call, miss writes cache, key stability/sensitivity, payload
round-trip, corrupt entry = miss, storage failure never breaks the
request).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
|
||
|
|
e4aad66a06 |
feat: Fable 5 default + multi-model compare for AI auto-correct (v0.178.0) (#811)
@coderabbitai ignore ## Summary Follow-up to #809, per Andrew's direction: switch the auto-correct default to the eval's best model, and add an opt-in **multi-model compare mode** that queries several models in parallel, dedupes identical suggestions with consensus counts, and lets the reviewer pick between conflicting variants. ## Changes **Fable 5 as production default** - New Anthropic provider path in `AutoCorrectService` (structured outputs + adaptive thinking — the exact configuration the 30-job eval used). Eval rationale: strict precision 0.62 vs 0.56, strict recall 0.51 vs 0.46, 27s vs 35s median latency vs Gemini 3.1 Pro. - `anthropic-api-key` secret: container added to Pulumi (`infrastructure/modules/secrets.py`, **already applied** — preview was exactly +1 create after pinning pulumi-gcp to 9.22.0 to avoid provider-upgrade VM replaces), value added and verified against the live API. - Cloud Run deploy: `AUTO_CORRECT_MODEL=claude-fable-5`, `AUTO_CORRECT_COMPARE_MODELS=claude-fable-5;gemini-3.1-pro-preview`, `ANTHROPIC_API_KEY` secret mapping. - No silent provider fallback: missing key → clear 502. - `anthropic >=0.109` added as a direct dependency (lock updated). **Multi-model compare mode** - `compare_models` setting → all configured models queried in parallel; identical suggestions deduped with `consensus`/`total_models` + `models` attribution; overlapping disagreements share a `conflict_group`. - UI: "Compare multiple AI models" toggle in the run modal; consensus badges ("2/2 models") and variant badges in the panel; accepting one variant of a conflict group auto-rejects its siblings; accept-all picks the highest-consensus winner per group. - Partial model failure (call error or malformed output) degrades to a response warning; only all-fail returns 502. - EditLog decisions now record models/consensus/conflict_group — per-model accept-rate data accrues in prod. **Cross-provider bug fixed**: google-genai mutates `response_schema` dicts in place (injects `property_ordering`), which the Anthropic API rejects — found via real-call smoke test of compare mode; schemas now deep-copied per call, with a regression test. ## Testing - 55 backend auto-correct tests (incl. 10 new multi-model merge/conflict/degradation tests + schema-pollution regression) and frontend conflict-util tests; full suite green (3,426 backend unit + 103 emulator + 1,004 frontend) - Real-call smoke tests: single-model Fable (glory→chlorine, 0.98, 5.6s) and compare mode (Fable + Gemini parallel, merged to one 2/2-consensus suggestion, 5.8s) - Secret value verified end-to-end against the Anthropic API - CodeRabbit CLI: 12 findings — 5 fixed, 5 skipped with reasons, 2 in files from another merged PR 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
6f8503a113 |
feat: opt-in AI auto-correct suggestions in lyrics review UI (v0.177.0) (#809)
@coderabbitai ignore ## Summary Third take on lyrics auto-correction, redesigned around the failures that led to disabling it in #321 (Jan 2026): **one whole-song LLM call** instead of per-gap calls, **user-triggered from the review UI** instead of blocking the pipeline, and a **pending-suggestion layer with per-change accept/reject/undo** instead of silent application. Fully opt-in — zero change to the default review journey. ## Changes **Backend** - `POST /api/review/{job_id}/auto-correct` — stateless; client posts its current working segments + reference lyrics, gets back word-id-keyed suggestions (`replace` / `delete` / `insert_after`) with reason, category, confidence - `backend/services/auto_correct/` — prompts (kept in sync with the offline eval harness), settings knobs (adlib removal, insertions, min-confidence), Vertex Gemini call with 120s timeout, strict server-side validation of model output - `AUTO_CORRECT_MODEL` env (default `gemini-3.1-pro-preview`); 422 when no reference sources exist **Frontend** - "AI Suggest" button in the review header → settings modal → suggestions panel: per-row accept/reject/undo, accept-all/reject-all, click-to-scroll-and-flash, stale detection when targeted words were edited since generation - `useAutoCorrect` hook + pure `autoCorrectApply` utils (id-based apply/revert, safe against concurrent edits) - EditLog ops `ai_suggestion_run/accept/reject/undo` — real accept-rate data accrues from day one - i18n strings translated to all 33 locales **Model choice** backed by an offline eval over 30 real production jobs scored against actual human review edits (design doc: `docs/archive/2026-06-10-lyrics-auto-correction-reeval-plan.md`): Fable 5 ≈ Gemini 3.1 Pro at the top; GPT-5.2 actively worsened lyrics (would have repeated the 2025 failure). Gemini chosen for v1 (already on Vertex, no new secret); switching models is one env var. ## Testing - 42 backend unit/route tests (`backend/tests/services/auto_correct/`, `backend/tests/api/test_review_auto_correct.py`) - 15 frontend unit tests (`autoCorrectApply.test.ts`) - Production E2E spec (`frontend/e2e/production/auto-correct-suggestions.spec.ts`) — runs one real suggestion cycle and dismisses without mutating review state - Full `make test` green (unit + backend + emulator + frontend) - CodeRabbit CLI review: 7 findings, 6 fixed, 1 skipped with reason 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
2b7d6bb5f0 |
fix(lyrics-review): validate & sanitize word timings during review (prevent overlap at source) (#810)
## Summary Prevents the invalid-word-timing class that caused job `17f7c313`'s overlapping rendered lyrics (`start=0`, `end=-0.005`) from being **created or persisted** during lyrics review. The render-time net (v0.176.2, #804) stays as the last resort; this fixes the source. Root cause: `useManualSync` ("tap-to-time") assigned `start=0` when the audio playhead sat at 0 and cascaded `end = 0 - 0.005`. Verified against this job's data — not AudioShake; not in the edit log (manual-sync timing edits aren't logged there). ## One shared invariant, four enforcement points Each word stays within its segment's `[start, end]`; `end ≥ start`; repaired words are placed at the previous word's end. All four implementations now produce identical results: 1. **Frontend sanitizer** `frontend/lib/lyrics-review/sanitizeWordTimings.ts` — pure function + change report. 2. **Manual-sync clamp** `frontend/hooks/useManualSync.ts` — tap times clamped to the segment window; `end_time` inversion-guarded (without capping — holding a note still extends the segment); toast on clamp. 3. **Modal** `frontend/components/lyrics-review/modals/EditModal.tsx` — sanitize-on-open + `role="status"` banner; Reset/Un-Correct also sanitize (fixes the buggy 0/null editing surface). 4. **Backend safety net** `backend/services/timing_sanitizer.py` + `submit_corrections` — clamps + logs before persisting `corrections_updated.json`. "Segment follows words" (the modal already derives bounds from word min/max) means dragging a word earlier/later extends the segment — so clamping is operation-specific and never traps the user. ## Changes - 3 new sanitizers (FE lib, FE hook helper, BE service) + modal wiring + route safety net. - New unit tests anchored on the `17f7c313` fixture across all layers (FE Jest + BE pytest). - 2 new i18n strings, auto-translated to all 33 locales. - Version `0.176.2 → 0.176.3`. Design + plan in `docs/archive/2026-06-10-review-timing-validation-{design,plan}.md`. ## Testing - [x] Backend unit (sanitizer + request-level submit test): 14 passed - [x] Frontend lyrics-review/hooks/lib: 301 passed - [x] Two-stage subagent review (spec + quality) per task; final whole-impl review; CodeRabbit (1 doc fix; i18n nitpicks skipped) ## Review - [x] Local CodeRabbit review completed @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |