mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-02 01:48:08 +09:00
ca5b294cfd73dca7447012e19d1fa2dde7bc014c
74
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
ad3c0bffc0 |
fix: harden 4 prod error paths (seek non-finite, auto-correct 429, download race + timeout) (#877)
## Summary Investigated and fixed four production error patterns flagged by the error monitor, each with tests. ## Changes **Frontend — `TypeError: currentTime non-finite`** (`/en/app/jobs` review UI) - Guard lyrics-review/audio-editor seek sinks (`AudioPlayer.seekAndPlay`/`handleSeek`, `AudioEditor.seekTo`) and the `handlePlaySegment` dispatcher with `Number.isFinite`; harden `TimelineEditor.handleTimelineClick` against a zero-width container. Restores parity with instrumental-review, which already had these guards. **Backend — auto-correct Vertex `429 RESOURCE_EXHAUSTED` surfaced as generic 502** - Retry model calls with exponential backoff on transient (rate-limit/overload) errors via `_is_transient_model_error`; surface a distinct **retryable 429** instead of 502. Retry env knobs parsed defensively (clamp + warn, never crash at import). **Backend — `audio-download-job` `InvalidStateTransitionError: downloading -> downloading`** - Root cause: a manual `/retry` raced the Cloud Run auto-retry; the losing run's post-download transition raised and the generic `except` `fail_job`'d a job the winner had already advanced. Fix: idempotent transition — re-read status first, treat an already-advanced job as success, and use `raise_on_invalid=False` so a race never fails a live job. **Backend/infra — `audio-download-job` 600s task-timeout SIGKILL** - Internal `wait_for_download` timeout equalled the Cloud Run task timeout, so slow torrents were SIGKILLed before failing gracefully (leaving the orphaned retry that fed the race above). New `DOWNLOAD_WAIT_TIMEOUT_SECONDS=1080` kept strictly below the task timeout, raised `600s → 1200s`. **Infra already applied to prod via `pulumi up` (targeted); stack is clean.** ## Testing - [x] Backend: 122 tests across touched suites pass (auto_correct incl. 10 retry/env, audio_download_worker incl. 3 race/timeout, review API, proactive) - [x] Frontend: full jest suite 1073/1073 pass (incl. new AudioPlayer non-finite guard test); `tsc` clean for changed files - [x] Infra: `pulumi preview` clean (273 unchanged) after applying timeout + reconciling pre-existing divebar drift ## Review - [x] Local CodeRabbit review completed (1 major finding — retry env validation — fixed + tested) - [x] Version bumped 0.190.5 → 0.191.0 @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) 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>
|
||
|
|
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> |
||
|
|
39fb93653f |
fix(auto-correct): switch active model from Fable 5 to Opus 4.8 (#822)
## Summary Claude **Fable 5** (`claude-fable-5`) is no longer available on the Anthropic API. Verified live against `api.anthropic.com`: ``` 404 not_found_error: "Claude Fable 5 is not available. Please use Opus 4.8. Learn more: https://www.anthropic.com/news/fable-mythos-access" ``` `claude-opus-4-8` responds normally and is the API's own prescribed replacement. Opus 4.8 was also ≈ Gemini 3.1 Pro in our 30-job offline eval, so switching to it preserves the two-model compare quality. ## Changes - **`.github/workflows/ci.yml`** (load-bearing): `AUTO_CORRECT_MODEL=claude-opus-4-8` and `AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview`. Compare mode now runs **Opus 4.8 + Gemini 3.1 Pro** instead of Fable + Gemini. - **`scripts/measure_autocorrect_cost.py`**: default models + docstring example → Opus, so the cost tool measures what prod runs. - **`docs/API.md`**: example auto-correct response reflects Opus. - **`pyproject.toml`**: `0.182.1` → `0.182.2`. ## Re-enable path Fable is **disabled, not deleted** — its pricing entry in `pricing.py` and all Fable unit tests are intentionally left intact. If access returns, flip it back by reverting the two env-var values in `ci.yml`. ## Testing - Auto-correct suite: 73 passed (`backend/tests/services/auto_correct/` + `test_proactive_auto_correct.py`). - Live API probe confirmed Fable 404s and Opus 4.8 works. - CodeRabbit (uncommitted): 0 findings. @coderabbitai ignore Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
a7bb338703 |
feat(auto-correct): enable proactive pre-generation (runs on API service) (#818)
## Summary Enables the proactive pre-generation that PR #816 intended but couldn't deploy (the lyrics-job `--update-secrets` crashed on Cloud Run secret aliases). Per the chosen approach, the work now runs **on the API service** — which already has a working `ANTHROPIC_API_KEY` + `AUTO_CORRECT_COMPARE_MODELS` — instead of the lyrics job, sidestepping the secret-alias problem entirely. ## How it works 1. Lyrics worker finishes transcription → after `mark_lyrics_complete`, fires `WorkerService.trigger_auto_correct(job_id)` — a direct, awaited HTTP call (no Cloud Tasks / new queue). Best-effort: never blocks or fails the job. 2. New internal endpoint `POST /api/internal/workers/auto-correct` (admin auth) runs `process_proactive_auto_correct(job_id)` synchronously on the service: loads `corrections.json`, runs the multi-model `suggest()` with default settings (cache-aligned with the UI), caches it. Gated by `AUTO_CORRECT_PROACTIVE_ENABLED`, 180s timeout, swallows all errors. 3. `ci.yml`: `AUTO_CORRECT_PROACTIVE_ENABLED=true` added to the **service** env (deploys cleanly — the broken lyrics-job secret path is gone). Result: when a reviewer opens the lyrics UI, the auto-run-on-load request is an instant cache hit. ## Testing - Backend: **3462 passing** (emulator excluded), incl. rewritten `test_proactive_auto_correct.py` covering the service worker (flag gating, no-references skip, happy path multi-model, error-swallow) and the lyrics-worker trigger (fires / swallows errors). - CodeRabbit: trace-context propagation + defensive endpoint guard applied. ## Notes - Failure modes unchanged & graceful: flaky AI / out of credits / timeout → endpoint returns a status, job proceeds; UI falls back to on-demand generation. - Version bumped 0.180.0 → 0.181.0. @coderabbitai ignore --------- 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> |
||
|
|
7cf42c8983 |
feat(pricing): duration-based credit pricing + long-duration input handling (#799)
@coderabbitai ignore
## Summary
Implements **duration-based credit pricing** for karaoke jobs, replacing
the flat 1-credit/job model. Credits now scale with input audio length
(`ceil(min/10)`, hard-block >60 min), with cost confirmed before heavy
processing and reconciled against the actual measured audio. Closes out
the planned fix from the 2026-06-04 long-duration mashup incident.
- Design:
`docs/archive/2026-06-04-long-duration-input-handling-design.md`
- Plan: `docs/archive/2026-06-04-long-duration-input-handling-plan.md`
## Pricing model
`credits = max(1, ceil(minutes / 10))` — 1 credit ≤10 min, 2 ≤20 min … 6
≤60 min. Inputs over 60 min are blocked. Single source of truth in
`backend/services/pricing.py`, mirrored in `frontend/lib/pricing.ts`.
## How it works
- **`state_data.credits_charged`** is the authoritative running total.
`create_job` charges the base (URL = full N via `acknowledged_credits`;
search/upload = 1); top-ups deduct only the **delta**
(`count_as_job_creation=False`).
- **Reconciliation engine** (`duration_reconciliation.py`) runs at the
single convergence point before separation+transcription in all three
processing paths (download / post-edit / `start_job_processing`),
exactly once each. It measures the audio actually sent to AudioShake
(post-edit if trimmed):
- actual < estimate → auto-refund the difference
- actual > estimate → pause at new **`AWAITING_DURATION_CONFIRM`**
state, user re-confirms (inline Buy Credits)
- actual > 60 min → refund everything + cancel
- **`POST /api/jobs/{id}/confirm-duration`** (+ `POST
/api/jobs/estimate`) reuse the review-stage pause/resume.
- **Notifications**: in-browser + push, 15-min idle email, 24h reminder,
**48h auto-cancel + full refund** — via the existing idle-reminder /
stale-job machinery.
- **Admin / made-for-you jobs bypass charging entirely**
(`payment_bypassed` → reconcile short-circuits).
## Endpoints
| Method | Path | Purpose |
|---|---|---|
| `POST` | `/api/jobs/estimate` | URL duration probe →
`{duration_seconds, credits, blocked, source}` |
| `POST` | `/api/jobs/{id}/confirm-duration` | confirm cost / resume
(402 insufficient, 409 mismatch) |
| `POST` | `/api/jobs` | URL create gains optional `duration_seconds`,
`acknowledged_credits` |
| `POST` | `/api/audio-search/{id}/select` | gains optional
`acknowledged_credits` |
## Frontend
`DurationCostConfirm` modal (Radix Dialog) surfaced via a "Confirm Cost"
action on `awaiting_duration_confirm` jobs (`useDurationConfirm` hook),
per-result cost chips on audio search, `pricing` i18n namespace in all
33 locales.
## Testing
- Backend: **3358 passing** (incl. boundary tables, money-math
conservation, reconcile up/down/over-limit, confirm 402/409, idempotency
guards, stale-expiry refund, an end-to-end integration test). Frontend:
**960 passing**. i18n completeness clean.
- Reviewed locally: per-task spec + quality review, a holistic
cross-cutting review, `/test-review`, and two CodeRabbit fix cycles.
## Notable bugs caught & fixed during review
- **Multi-credit under-refund**: `_refund_credit_for_job` refunded a
flat 1 — now refunds `credits_charged` (user-cancel of a long job).
- **Admin-bypass trap**: admin jobs would pause at the confirm gate and
be charged real credits — now short-circuited.
- Over-limit double-refund (suppress `cancel_job`'s built-in 1-credit
refund); over-limit email used the wrong "48h" message;
double-confirm/double-select idempotency guards.
- Hit the summary-projection gotcha (added fields to both projection
lists + regression test).
## Known residuals / follow-ups (non-blocking)
- **URL pre-flight cost-confirm is inert** until flacfetch's
`/check-youtube` returns a `duration` key — currently falls back to a
1-credit hold + post-download reconcile (functionally correct). Separate
flacfetch change.
- Duration-confirm email **bodies** are English (URLs are
locale-prefixed; backend i18n covers en/es/de) — `# TODO(i18n)` left.
- Concurrent confirm/select **double-charge TOCTOU** is an accepted
low-probability residual (atomic claim would need a Firestore
transaction); the status-transition guard handles the realistic
double-click case.
## Deploy note
Reuses the existing Cloud Tasks idle-reminder queue and the hourly
stale-review Cloud Scheduler (status-list / action-type expansions only)
— no new infra expected, but worth confirming `pulumi up` is a no-op on
deploy.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
||
|
|
fe8430d990 |
fix(admin): allow regen-screens from in_review state + surface errors via toast (#793)
## Summary - Fixes a 400 when regenerating title/end screens for a job the user has opened in the review UI (`in_review` state). - Fixes the root cause behind "click Regenerate Screens → modal just closes, no error": `<Toaster />` was never mounted, so **all** `toast()` calls (success and error) silently no-op'd. ## Changes - **Backend:** add `in_review` to `REGENERATE_SCREENS_ALLOWED_STATES` in `backend/api/routes/admin.py`. The sibling `/restart` endpoint already allows `in_review`; this restores parity. Updated `docs/API.md`. - **Frontend:** mount the shadcn `<Toaster />` (same `@/hooks/use-toast` store) in the root `app/layout.tsx` so admin toasts render app-wide. - **Frontend:** give the regen-screens handlers specific, human-readable failure titles/messages (admin dashboard + compact `AdminJobActions` toolbar). - Version bump `0.174.12` → `0.174.13`. ## Testing - [x] Backend: `tests/unit/test_regenerate_screens.py` — allow-list membership, `in_review` → 200, invalid state → 400, missing job → 404 (4 pass). - [x] Frontend: `AdminJobActions.test.tsx` — error-toast path now covered (5 pass). - [x] CodeRabbit CLI review: 0 findings. - [x] Typecheck: no new errors from these changes (pre-existing errors unrelated). ## Review - [x] CodeRabbit CLI review completed locally - [x] Issues addressed @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
6d52503126 |
fix(auth): one-click magic-link resend on verify failure (#739)
## Summary When a magic-link verify fails (expired or already used), the verify page now shows a one-click button that emails a fresh sign-in link to the address the original token was issued to. Complements the 24h TTL bump from #734 and gives Yahoo recipients (and anyone with deferred mail) a recovery path that doesn't require re-entering their email. ## Why Customer `hojob2002@yahoo.com` is back today reporting "Sign-in failed" despite #734 having extended TTL to 24h two days ago. Investigation showed her job had auto-cancelled at the 48h review timeout while she was burning through expired magic links during Yahoo's deferral window — and the verify failure UX gave her nothing actionable beyond "Go to App". With Postmark approval still pending, this is the cheapest recovery improvement we can ship to help users in the same situation. ## Changes - **Backend** — `POST /api/users/auth/resend-from-token` - Looks up the original token in Firestore, mints a fresh magic link for the same email, and sends it - Carries forward `tenant_id`, `referral_code`, and `device_fingerprint` from the original token - 60-second per-token cooldown stamps `last_resend_at` on the doc; repeat clicks (and email-scanner pre-fetches) within the window report `sent` to the UI without re-emailing - Returns `{status: "sent" | "no_token", masked_email, message}` — `no_token` lets the UI degrade gracefully - **Frontend** — verify page error UI - "Email me a new link" button (with sending spinner) - Success state shows masked destination email - Distinct fallback when backend reports `no_token` - Inline error message on network failure - **Translations** — 33 frontend locales, 33 backend locales (auto-translated, French verb form fixed manually) - **Docs** — `docs/API.md` documents the new endpoint with concrete request/response examples - **Version** — 0.172.5 → 0.172.6 ## Security note The token in the URL is a 32-byte cryptographic secret — only the original email recipient could possess it. Resending to the email already recorded in the magic-link doc (rather than accepting an email from the request body) avoids enumeration and adds no new attack surface; the worst case if a token leaked is inbox spam to the verified address, which is bounded by the 60s cooldown. ## Testing - [x] 9 backend tests in `test_resend_magic_link.py` (token exists / missing / empty / used / no-email / no-email-svc / tenant-context / cooldown-suppresses / cooldown-expires) - [x] 4 frontend Jest tests in `verify-page-resend.test.tsx` (button visible on failure, happy path, no_token fallback, network error) - [x] All 173 existing auth/anti-abuse tests still pass - [x] Type-check clean for the modified frontend files ## Review - [x] Local CodeRabbit review completed; relevant findings (cooldown, French grammar, JSON example validity) addressed in fixup commit - [x] Final CodeRabbit pass returns no findings on this branch's code @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
1c1c17f9ab |
fix: Stripe Connect redirect and referral payout management (#702)
## Summary - **Fix broken Stripe Connect return URL** — was redirecting to `/app?tab=referrals` (the dashboard, which ignores that param) instead of `/app/referrals`. Users were ending up logged out at `/en/` after completing Stripe onboarding. - **Add locale redirect fallback** for `/app/referrals` route so Stripe can redirect without locale prefix - **Add Connect account status and management** — new backend endpoints for account status, Express dashboard login, and re-onboarding. Frontend shows payouts enabled/pending status, "Manage Payouts" and "Update Bank Account" buttons. - **Improve Connect button UX** — loading spinner + note that user will be redirected to Stripe, error feedback for all actions ## Test plan - [x] Backend: 48 referral tests + 7 Stripe tests pass - [x] Frontend: 721 tests pass - [x] CodeRabbit review: 3 issues found and fixed - [ ] Manual: verify Connect flow with test account after deploy - [ ] Manual: verify return redirect lands on referrals page with success banner @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
80cb53f3a2 |
feat: referral link system with discounts and Stripe Connect payouts (#669)
## Summary - Add a referral system where any user gets a shareable link (`/r/CODE`) with a personalized interstitial page - Referred users get a configurable discount (default 10%) on credit purchases for 30 days - Referrers earn a cash kickback (default 20% of revenue) paid out via Stripe Connect at $20 threshold - Admin can create vanity links with custom rates and manage all referral links ## Changes ### Backend - **New models** (`backend/models/referral.py`): ReferralLink, ReferralEarning, ReferralPayout + API request/response models - **New service** (`backend/services/referral_service.py`): Link CRUD, attribution, discount detection, earnings recording, Stripe Connect onboarding, auto-payout - **New routes** (`backend/api/routes/referrals.py`): 7 endpoints — public interstitial, user dashboard, link updates, Connect onboarding, admin vanity/list/update - **Stripe integration**: Coupon creation/lookup, Connect Express accounts, transfers - **Webhook hook**: Referral earnings recorded on credit purchases - **Auth hook**: Referral attribution on first magic link verification via `x-referral-code` header - **User model**: Added referral fields (referral_code, referred_by_code, referred_at, discount_expires_at, stripe_connect_account_id) ### Frontend - **Interstitial page** (`/r/CODE`): Shows referrer's name, custom message, discount details - **Referral dashboard** (`/app/referrals`): Link sharing, stats, earnings, payout history, Stripe Connect CTA - **Discount badge**: Shown in Buy Credits dialog during active referral window - **Referral capture**: Cookie + localStorage via `/r/CODE` route and `?ref=CODE` query param - **Auth integration**: Passes referral code on magic link verification, clears after use - **i18n**: 33 new translation keys in `referrals` namespace ### Documentation - Design spec: `docs/archive/2026-04-04-referral-system-design.md` - Implementation plan: `docs/archive/2026-04-04-referral-system-plan.md` - Updated `docs/README.md` status table and `docs/API.md` with referral endpoints ## Testing - 68 referral-specific tests (models, service, routes) — all passing - 2935 total backend tests — zero regressions - 710 frontend tests — all passing - Covers: link management, attribution, self-referral blocking, discount detection, earnings calculation, payout threshold, edge cases (rounding, zero amounts), all API endpoints ## Review - [x] CodeRabbit CLI review completed locally (11 findings, 7 fixed) - [x] Test review completed (P0/P1 gaps identified and filled) - [x] Docs reviewed and updated @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
c98da49da9 |
feat: add jobs search, status filter, and fix loading states (#637)
## Summary - Add server-side text search to jobs list API (case-insensitive substring match across artist, title, job_id) - Replace eye icon toggle with status filter dropdown (All statuses, Active, Failed, Completed, Cancelled, Awaiting review, Processing) - Add debounced search input to Recent Jobs header - Expand limit dropdown options (5, 10, 20, 50, 100, 1000) - Fix loading state showing "No jobs yet" during cold starts (now shows spinner) - Fix API always fetching limit=100 regardless of dropdown selection ## Test plan - [x] 8 unit tests for `_search_filter_jobs` (artist, title, job_id, audio search fields, case insensitivity, None handling, empty string, limit interaction) - [x] Full backend test suite passes (2870 passed) - [x] Frontend builds cleanly - [ ] Manual: verify search filters jobs in real-time on dashboard - [ ] Manual: verify status dropdown filters correctly - [ ] Manual: verify loading spinner shows during cold starts instead of "No jobs yet" <!-- @coderabbitai ignore --> 🤖 Generated with [Claude Code](https://claude.com/claude-code) |
||
|
|
591c050545 |
feat: Reference lyrics search with relevance filtering (#632)
## Summary
- Add relevance filtering to the correction pipeline — automatically
rejects wrong-song reference lyrics (below 30% word match threshold,
validated against 168 prod source pairs)
- New `POST /api/review/{job_id}/search-lyrics` endpoint lets users
search with alternate artist/title from the review UI, with force-add
override for edge cases
- Redesigned Add Reference Lyrics modal with Search (default) and Paste
tabs, plus inline empty state when no valid sources exist
## Changes
### Backend
- **Relevance filtering** (`correction/relevance.py`): Per-source
scoring based on anchor sequence word coverage. Integrated into
`LyricsCorrector.run()` after anchor finding — sources below threshold
removed before corrections computed
- **Search endpoint** (`routes/review.py`): Queries all providers
(Genius, Spotify, Musixmatch, LRCLIB) with user-supplied artist/title,
auto-filters results, returns added/rejected/not-found breakdown
- **Provider factory** (`operations.py`): `create_lyrics_providers()`
reads env vars, `search_lyrics_sources()` orchestrates
fetch+filter+correct
- **Force override**: `add-lyrics` and `search-lyrics` support `force`
flag to bypass threshold
### Frontend
- **Tabbed modal**: `AddLyricsModal` rewritten with Search (default) and
Paste tabs
- **SearchLyricsTab**: Artist/title inputs, provider search, rejected
source cards with force-add checkboxes
- **ReferenceEmptyState**: Inline search/paste UI when no valid
reference sources exist
- **API client**: New `searchLyrics()` method with
`SearchLyricsResponse` types
### Analysis
- Empirical threshold analysis script
(`scripts/analyze_reference_relevance.py`) + visual review tool
- 168 source pairs from 81 prod jobs: wrong-song max 3.5%, correct-song
min 26.8% → 30% threshold
## Testing
- 35 new backend tests (relevance scoring, filtering, corrector
integration, search operation, API endpoint)
- 717 existing frontend tests passing (no regressions)
- Edge case: all sources filtered out handled gracefully
## Review
- [x] Local CodeRabbit review completed (3 issues fixed: response
contract, force param coercion, null checks)
@coderabbitai ignore
---
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
||
|
|
6577babfea |
Reduce free credits from 2 to 1 per grant (#592)
## Summary - Welcome credits: 2 → 1 (granted on first email verification) - Feedback credits: 2 → 1 (granted for submitting product feedback) - Total possible free credits per account: 4 → 2 ## Changes **Backend:** `NEW_USER_FREE_CREDITS` constant, feedback credit grant, AI evaluation prompt, model defaults **Frontend:** Landing page, dashboard banner, feedback dialog, auth dropdown menu text **Tests:** Updated all assertions and mock values (115 backend + 712 frontend tests pass) **Docs:** AI-CREDIT-GATING.md, API.md, README.md, PRODUCT-COMMUNICATION-GUIDE.md ## Test plan - [x] Backend tests pass (115 passed) - [x] Frontend Jest tests pass (712 passed) - [ ] CI pipeline passes - [ ] Verify landing page shows "1 Free Credit" after deploy - [ ] Verify new user signup grants 1 credit (not 2) @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
c9e434037b |
feat: admin feedback visibility — page + email notification (#581)
<!-- @coderabbitai ignore --> ## Summary - **Admin feedback page** at `/admin/feedback` — browse all user feedback submissions with star ratings, text fields, search, pagination, and aggregate stats - **Email notification** to admin@nomadkaraoke.com whenever a user submits new feedback (configurable via `ADMIN_NOTIFICATION_EMAIL` env var) - **Admin API endpoint** `GET /api/admin/feedback` with pagination, search, test-data filtering, and average ratings ## Context User feedback was stored in Firestore (`user_feedback` collection) but completely invisible to the admin — the admin panel only showed a boolean "Feedback Submitted: Yes/No" badge per user. This PR closes that gap. ## Changes **Backend:** - `GET /api/admin/feedback` endpoint with pagination, search, `exclude_test` filter, aggregate rating averages - `send_feedback_notification()` method on `EmailService` — sends HTML email with star ratings, all text fields, link to admin page - Wired into `submit_user_feedback` as fire-and-forget (won't block user response) **Frontend:** - New admin page with aggregate stat cards, searchable/paginated table, visual star ratings, expandable rows for text detail - "Feedback" sidebar nav item with MessageSquare icon - `adminApi.listFeedback()` client method + TypeScript types **Tests:** 14 tests covering endpoint (pagination, search, filtering, aggregates, empty state, datetime edge cases), email (content, subject, custom admin, failure), and caller-callee contract integration ## Test plan - [x] `make test` — 712 tests pass (39 suites) - [x] 14 new tests in `test_admin_feedback.py` - [ ] Manual: verify admin page renders at `/admin/feedback` after deploy - [ ] Manual: submit feedback → verify email arrives at admin@nomadkaraoke.com 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
376008fc8f |
Anti-abuse: credits on verification, IP + fingerprint rate limiting (#552)
## Summary Three-layer defense against free credit abuse (disposable email bypass): - **Credits on verification**: Welcome credits granted on first magic link verification, not account creation. Unverified accounts get 0 credits. - **Per-IP rate limiting**: Max 2 new accounts per IP per 24 hours. Silent reject (anti-enumeration). - **Device fingerprinting**: FingerprintJS (open source) sends browser fingerprint with magic link request. Combined with IP — either signal hitting 2/day triggers block. Graceful degradation if fingerprinting fails. ## Changes ### Backend - `get_or_create_user()` creates users with 0 credits, stores `signup_ip` and `device_fingerprint` - New `grant_welcome_credits_if_eligible()` with `welcome_credits_granted` flag for idempotency - Verify endpoint grants credits and returns `credits_granted` in response - `count_recent_signups_from_ip()` and `count_recent_signups_from_fingerprint()` query Firestore - `is_signup_rate_limited()` combines IP + fingerprint signals - `send_magic_link` endpoint checks rate limit before creating magic link (new users only) - New fields: `User.signup_ip`, `User.device_fingerprint`, `User.welcome_credits_granted`, `MagicLinkToken.device_fingerprint`, `SendMagicLinkRequest.device_fingerprint`, `VerifyMagicLinkResponse.credits_granted` ### Frontend - New `fingerprint.ts` lib (lazy-loaded FingerprintJS) - `sendMagicLink` sends `device_fingerprint` with request - Verify page shows "You received N free credits to get started!" on first login - `VerifyMagicLinkResponse` type updated with `credits_granted` ### Tests - 33 unit + integration tests in `test_anti_abuse.py` - Covers: credit granting, idempotency, rate limiting (IP + fingerprint), error paths, caller-callee contracts, model fields, endpoint integration ## Testing - [x] All backend tests pass (33 new + existing) - [x] All frontend tests pass (707 tests) - [x] `make test` passes ## Review - [x] CodeRabbit CLI review completed locally - [x] Review feedback addressed (added `welcome_credits_granted` flag for idempotency) @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
05cb7a9bec |
feat: auto-sync disposable email blocklist from community repo (#546)
## Summary - Add daily auto-sync of disposable email domains from the [disposable-email-domains](https://github.com/disposable-email-domains/disposable-email-domains) community repo (~4,800 domains vs previous 160 hardcoded) - Restructure Firestore blocklist into three layers: external (auto-synced), manual (admin-added), allowlisted (admin overrides) - Admin UI updated with separate sections for each domain source + "Sync Now" button ## Changes ### Backend - New `disposable_domain_sync_service.py` — fetch, parse, and sync external blocklist with migration support - Updated `email_validation_service.py` — effective set = (external + manual) - allowlisted, new allowlist CRUD, backward-compatible `get_blocklist_config()` - New API endpoints: `POST /blocklists/sync`, `POST/DELETE /blocklists/allowlisted-domains`, `POST /internal/sync-disposable-domains` - Updated `GET /blocklists` response with `external_domains`, `manual_domains`, `allowlisted_domains`, `last_sync_at`, `last_sync_count` ### Frontend - Admin rate-limits page: three sub-sections (external/manual/allowlist) with sync status bar - Updated API client types and methods ### Infrastructure - Cloud Scheduler job for daily sync at 3:00 AM UTC (Pulumi) ### Migration - First sync automatically migrates from old `disposable_domains` field - Hardcoded `DEFAULT_DISPOSABLE_DOMAINS` replaced with empty set (external sync takes over) ## Testing - 47 new/updated tests across 3 test files (54 total for email validation + sync) - 2584 tests pass in full suite - CodeRabbit CLI: no findings @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
6b17a1c748 |
feat: review reminder emails and auto-expiry for stale jobs (#544)
## Summary - Hourly cron detects jobs stuck in review (`awaiting_review` / `in_review`) and takes action - **24h**: sends gentle reminder email with review link, help offer, and expiry warning - **48h**: auto-cancels job, refunds credit, sends expiry notification with balance ## Changes - **New:** `backend/workers/stale_review_processor.py` — core processor logic - **New:** `EmailService.send_review_reminder()` and `send_review_expired()` email methods - **New:** `POST /api/internal/process-stale-reviews` endpoint (Cloud Scheduler target) - **New:** Cloud Scheduler job `stale-review-hourly` (hourly, Pulumi) - **New:** 24 unit tests (14 processor + 10 email) - **Fix:** `make test` no longer hangs on frontend Playwright E2E tests - Excludes made-for-you and tenant jobs - Uses separate `expiry_reminder_sent` flag (independent of existing idle reminder) - Version bump: 0.142.4 → 0.143.0 ## Testing - [x] 24 new unit tests, all passing - [x] Full backend test suite: 2578 passed - [x] Full frontend unit tests: 704 passed - [x] `make test` completes without hanging ## Review - [x] Local CodeRabbit review completed (5 findings, 4 fixed, 1 correctly skipped) - [x] Spec review completed (critical `reminder_sent` flag collision caught and fixed) ## Design See `docs/archive/2026-03-19-review-reminder-autoexpiry.plan.md` for full spec. @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
51cd0eadc5 |
Extend search session TTL to 7 days and handle expiry gracefully (#510)
## Summary - Extended search session TTL from 30 minutes to 7 days so users who leave a tab open mid-flow don't hit "Search expired" - Added graceful frontend handling when sessions do expire — redirects to re-search with a friendly message instead of raw error - Updated API docs and tests to match ## Changes - `backend/api/routes/audio_search.py`: TTL `timedelta(minutes=30)` → `timedelta(days=7)` - `frontend/components/job/GuidedJobFlow.tsx`: Catch 404/"Search expired" errors, clear stale session, redirect to Step 2 with friendly message preserving song info - `backend/tests/test_standalone_search.py`: Updated test helper TTL to match - `docs/API.md`: Updated TTL reference from "30-min" to "7-day" ## Testing - [x] All 31 search-specific tests pass - [x] Full backend suite passes (2212 passed) ## Review - [x] Local CodeRabbit review completed (no issues with these changes) @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
f1ec70924e |
Add lyrics review session backup/restore system (#509)
## Summary
- Server-side auto-save of lyrics review sessions (every 60s if dirty,
on preview, on page hide) with SHA-256 deduplication
- Split-pane restore UI with session browser, edit diff preview, and
cross-job search
- Auto-prompts on load if saved sessions exist; falls back to
localStorage for local mode
## Changes
### Backend
- **New model**: `ReviewSession` + `ReviewSessionSummary` dataclasses
with Firestore serialization
- **5 new API endpoints** under `/api/review/`: save, list, get, delete
sessions + cross-job search
- **Firestore**: 8 new methods for review session CRUD using
subcollection pattern (`jobs/{jobId}/review_sessions/{sessionId}`)
- **GCS storage**: Correction data stored in GCS (can exceed Firestore's
1MB doc limit); metadata in Firestore
- **Deduplication**: SHA-256 hash comparison skips saving identical data
### Frontend
- **`useReviewSessionAutoSave` hook**: 60s interval auto-save,
visibilitychange save, exposed `saveSession()` for manual/preview
triggers
- **`SessionRestoreDialog`**: Split-pane modal with session list + edit
diff preview, "This Job"/"All Jobs" tabs, cross-job search, duration
mismatch warning
- **`LyricsAnalyzer` integration**: Auto-checks for saved sessions on
load, "Save Progress" and "Session History" toolbar buttons, triggers
save on preview
### Docs
- API.md: 5 new review session endpoints documented
- README.md: Feature added to Current State table + Recent Changes
- LESSONS-LEARNED.md: GCS + Firestore metadata pattern
### Also included (from #508)
- Job observability improvements: timeline metadata, `log_to_job()`
helper
## Testing
- [x] 18 backend unit tests (model serialization, all API endpoints,
deduplication, auth, 404s)
- [x] 10 auto-save hook tests (triggers, deduplication tracking,
interval, read-only, error handling, summary computation)
- [x] 16 SessionRestoreDialog tests (rendering, restore flow, tab
switching, cross-job search, empty states)
- [x] All 607 frontend tests pass
- [x] All 2409 backend tests pass
## Review
- [x] CodeRabbit CLI review completed locally (1 fix applied:
beforeunload → visibilitychange)
- [x] Test review completed (26 new frontend tests added)
- [x] Docs review completed
@coderabbitai ignore
---
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
|
||
|
|
e04337fa5d |
Fix broken notification and CLI review URLs (#507)
## Summary
- Push notifications were sending users to `/review/{id}` and
`/instrumental/{id}` which 404 on Cloudflare Pages static hosting
- Remote CLI was opening browser to path-based URLs missing the `#/`
hash fragment
- Documentation referenced incorrect URL formats
All URLs now correctly use hash-based routing: `/app/jobs#/{id}/review`
and `/app/jobs#/{id}/instrumental`
## Changes
- **backend/services/push_notification_service.py** — Fixed notification
click URLs
- **backend/api/routes/jobs.py** — Fixed edit track response
`review_url`
- **karaoke_gen/utils/remote_cli.py** — Fixed CLI browser open URLs
- **karaoke_gen/utils/cli_args.py** — Fixed help text
- **Tests** — Updated assertions in push notification and remote CLI
tests
- **Docs** — Fixed URL examples in API.md, README.md, TESTING.md
- **pyproject.toml** — Bump version 0.137.0 → 0.137.1
## Test plan
- [x] Backend push notification tests pass (35 tests)
- [x] Remote CLI tests pass (174 tests)
- [x] Full backend test suite passes (103 tests)
- [x] Frontend unit tests pass (581 tests)
<!-- @coderabbitai ignore -->
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
|
||
|
|
3f568373fd |
Add edit completed tracks feature (#506)
## Summary
- Add ability to edit completed karaoke tracks: cleans up existing
outputs (YouTube, Dropbox, GDrive, GCS), recycles brand code, resets
state to AWAITING_REVIEW
- Support optional artist/title metadata updates during edit (triggers
screens regeneration)
- New `POST /api/jobs/{job_id}/edit` endpoint with cleanup tracking and
review URL response
- Edit button in OutputLinks for completed jobs with confirmation modal
explaining implications
## Changes
### Backend
- `backend/api/routes/jobs.py` - New edit endpoint with full output
cleanup (YouTube, Dropbox, GDrive, GCS finals), brand code recycling,
state transition, and optional metadata update
- `backend/models/job.py` - Added COMPLETE → AWAITING_REVIEW state
transition and `edit_count` field
- `backend/tests/test_edit_completed_track.py` - 14 unit tests covering
success, metadata updates, validation, and cleanup
### Frontend
- `frontend/components/job/EditTrackModal.tsx` - Confirmation modal with
optional artist/title editing
- `frontend/components/job/OutputLinks.tsx` - Edit button (amber) for
completed jobs with outputs
- `frontend/lib/api.ts` - `editCompletedTrack()` API method and
`EditTrackResponse` type
- `frontend/components/__tests__/OutputLinks.test.tsx` - 3 new tests for
Edit button visibility
### Docs
- `docs/API.md` - Documented new endpoint
- `docs/README.md` - Added recent changes entry
- `docs/archive/2026-03-06-edit-completed-tracks-plan.md` -
Implementation plan
## Test plan
- [x] 14 backend unit tests for edit endpoint (success, metadata,
validation, cleanup)
- [x] 3 frontend tests for Edit button visibility (complete job, deleted
outputs, non-complete)
- [x] All 576 frontend unit tests passing
- [ ] Manual: Edit a completed track, verify outputs are cleaned up and
review reopens
- [ ] Manual: Edit with metadata change, verify screens regenerate
<!-- @coderabbitai ignore -->
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
|
||
|
|
c2b2aec5fe |
feat: add Change Visibility button for completed jobs (#501)
## Summary
- Add "Make Public" / "Make Private" button on completed job cards
allowing users to toggle visibility
- Two distinct backend flows: Public→Private (fast redistribution ~1-2
min) and Private→Public (full re-processing ~15-30 min)
- Confirmation modal with direction-specific explanations of what will
happen
## Changes
### Backend
- **New service:** `visibility_change_service.py` — validation, two
change flows, distributed output cleanup (YouTube/Dropbox/GDrive/GCS),
brand code recycling
- **New endpoint:** `POST /api/jobs/{job_id}/change-visibility` with
proper 404/403/400 status codes
- **Video worker:** Added `redistribute_video()` for fast public→private
path (reuses existing finals)
- **Screens worker:** Added render worker trigger after screen regen for
private→public pipeline
- **State machine:** Added `COMPLETE → LYRICS_COMPLETE` transition for
re-processing flow
- **Version:** 0.135.2 → 0.136.0
### Frontend
- **OutputLinks:** "Make Public"/"Make Private" button with Lock/Globe
icons
- **AlertDialog:** Confirmation modal with direction-specific content
explaining consequences
- **API client:** `changeVisibility()` method and response type
### Tests
- 22 backend tests: validation (11), change_to_private (3),
change_to_public (3), output cleanup (4), state transitions (1)
- Frontend OutputLinks test updated for new visibility button
## Testing
- [x] All 22 new backend tests pass
- [x] 2164/2165 backend tests pass (1 pre-existing failure unrelated)
- [x] 573/573 frontend tests pass (30 suites)
## Review
- [x] CodeRabbit CLI review completed locally
- [x] Fixed: Dropbox folder name sanitization mismatch
- [x] Fixed: HTTP status codes (404 for missing job, 403 for ownership)
- [x] Skipped: Screens worker direct DB update (acceptable for simple
restore)
@coderabbitai ignore
---
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
|
||
|
|
04950345bc |
Remove legacy per-user job rate limiting (#475)
@coderabbitai ignore ## Summary - Remove the "5 jobs per day" per-user rate limiting system, which is no longer needed since credits now control usage - Delete `rate_limit_service.py` and all associated tests - Remove `RateLimitExceededError` exception and all references across backend routes - Remove rate limit config fields (`enable_rate_limiting`, `rate_limit_jobs_per_day`) - Clean up frontend admin page: remove Overview tab (rate limit stats) and User Overrides tab - Keep all blocklist management (domain/email/IP blocking) and YouTube queue features intact - Update API and README docs to reflect the change ## Changes - **3 files deleted**: `rate_limit_service.py`, `test_rate_limit_service.py`, `test_rate_limits_api.py` - **13 files edited** across backend and frontend - **Net**: ~56 insertions, ~2,465 deletions ## Test plan - [x] All backend tests pass (1086 core + unit tests) - [x] All frontend tests pass (176 tests) - [x] Verified no remaining references to `RateLimitExceededError` or `rate_limit_service` - [x] Blocklist endpoints preserved and tested - [x] YouTube queue endpoints preserved and tested - [x] Credit enforcement tests updated (removed rate limit fixtures) 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
33667a6852 |
feat: custom video styling for private delivery jobs (#471)
@coderabbitai ignore ## Summary - Private-delivery users can now customize their karaoke video styling: upload custom background images (karaoke + title card) and change artist/title text colors via color pickers with live canvas previews - Backend: 2 new endpoints (`style-upload-urls`, `style-uploads-complete`) that validate ownership, cutoff status, and merge custom assets into the theme's `style_params.json` - Frontend: `ImageUploadField` component, `KaraokeBackgroundPreview` canvas, extended `TitleCardPreview` with custom bg/colors, `CustomizeStep` styling section (visible when private), `GuidedJobFlow` upload orchestration - Also: skip `take-screenshots` spec by default (manual helper, not a real test) ## Test plan - [x] 15 backend tests covering both new endpoints (auth, validation, cutoff, asset merging, color overrides) - [x] 14 CustomizeStep tests (conditional visibility, color pickers, previews, form interactions) - [x] 9 ImageUploadField tests (drag-and-drop, validation, file type/size rejection) - [x] 2 TitleCardPreview tests (custom colors, custom background URL) - [x] 6 guided-flow API contract tests (style upload methods) - [x] All 181 existing Playwright E2E tests pass - [ ] Manual: create a private job, upload custom backgrounds, verify colors render in video 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
937f8f7ec1 |
feat: YouTube quota GCP monitoring + legacy beta cleanup (#460)
## Summary - Remove the deprecated beta enrollment system (endpoints, models, email templates, admin UI, rate limits) — ~20 files cleaned - Remove legacy count-based YouTube upload tracking from rate_limit_service and dead blocklist methods - Add GCP Cloud Monitoring integration to cross-reference YouTube API quota usage with Firestore tracking - Add drift detection (alerts when GCP reported vs Firestore tracked differs >10%) - Display GCP quota data in admin rate-limits dashboard ## Changes ### Backend (15 files) - **Removed:** 5 beta endpoints, `BetaTesterStatus` enum, beta User fields, beta email templates, `validate_email_for_beta()`, deprecated YouTube/beta rate limit methods, dead blocklist CRUD methods - **Added:** `get_gcp_quota_usage()` to `YouTubeQuotaService` with Cloud Monitoring API query, 5-min cache, and drift detection - **Updated:** Rate limits API response model with GCP quota fields (`gcp_quota_available`, `gcp_quota_units_consumed`, `quota_drift`, `quota_drift_alert`) ### Frontend (11 files) - **Deleted:** `frontend/app/admin/beta/page.tsx` (entire beta admin page) - **Removed:** Beta sidebar nav, layout breadcrumb, admin stats card, beta types/API methods, legacy YouTube stats cards - **Added:** GCP Cloud Monitoring section in rate-limits page showing reported usage, delay, and drift alerts ### Tests (4 files) - Removed 8 obsolete tests for deprecated methods - Created `test_gcp_quota_monitor.py` with 10 tests covering GCP quota querying, caching, fallbacks, and drift detection - Updated mock data and assertions across test files ### Docs (3 files) - Removed beta endpoint docs from API.md, added GCP quota fields - Updated ARCHITECTURE.md with Cloud Monitoring integration - Removed beta program section from PRODUCT-VISION.md ## Test plan - [x] All 2265 backend tests pass (1 pre-existing failure unrelated) - [x] All 516 frontend Jest tests pass - [x] New GCP quota monitor tests cover success, caching, fallbacks, drift alerts - [ ] Verify admin rate-limits page no longer shows beta/legacy cards - [ ] Verify GCP quota section shows "unavailable" gracefully when monitoring data not yet populated @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
98b6590658 |
feat: YouTube quota-aware upload system with deferred queue (#456)
## Summary - Replace hard-coded 10 uploads/day limit with YouTube API quota unit tracking (10,000 units/day, ~33 uploads) - Queue uploads when quota is exhausted instead of silently skipping them - Process queued uploads hourly via Cloud Scheduler, notify users via email when complete - Add admin dashboard for quota monitoring and queue management ## Changes ### Backend - New Services - `youtube_quota_service.py` — Tracks YouTube API quota units per day in Firestore (`youtube_quota` collection, date-keyed by Pacific Time) - `youtube_upload_queue_service.py` — Manages deferred upload queue in Firestore (`youtube_upload_queue` collection) with atomic claiming, retry logic, and failure handling - `youtube_queue_processor.py` — Worker that processes queued uploads when quota available (downloads from GCS, uploads to YouTube, sends notification) ### Backend - Modified - `video_worker_orchestrator.py` — Queue on quota exhaustion instead of skip; record quota units after each API call - `rate_limit_service.py` — Deprecated YouTube methods delegate to new quota service with legacy fallback - `job_notification_service.py` + `template_service.py` + `email_service.py` — Follow-up email when deferred upload completes - `rate_limits.py` — 3 new admin endpoints: GET queue, POST retry, POST process - `internal.py` — Internal endpoint for Cloud Scheduler to trigger queue processing - `config.py` — New settings: `youtube_quota_daily_limit`, `youtube_quota_upload_cost`, `youtube_quota_safety_margin` ### Frontend - `rate-limits/page.tsx` — YouTube Queue tab with quota progress bar, queued uploads table, retry/process buttons - `api.ts` — Types and API methods for queue management ### Infrastructure (Pulumi) - Cloud Tasks queue `youtube-upload-queue` - Cloud Scheduler job: hourly, Pacific Time, calls internal process endpoint ### Tests (90 passing) - `test_youtube_quota_service.py` — 16 tests - `test_youtube_upload_queue_service.py` — 15 tests - `test_youtube_queue_processor.py` — 14 tests (async) - `test_rate_limits_api.py` — 4 new endpoint tests - `test_rate_limit_service.py` — 5 updated/new delegation tests ### Docs - Updated ARCHITECTURE.md, API.md, README.md, LESSONS-LEARNED.md ## Motivation 4 jobs on 2026-03-03 had YouTube uploads silently skipped because the hard-coded rate limit of 10 uploads/day was reached. Users expected uploads but got none with no notification. The actual YouTube API quota (10,000 units/day) supports ~33 uploads — the rate limit was overly conservative. ## Testing - [x] 90 targeted backend tests pass (4.03s) - [x] Frontend Jest tests pass (503 tests) - [x] CodeRabbit CLI review completed, feedback addressed @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
a75384fb6f |
docs: complete Singa tenant documentation (#455)
Follow-up docs for PR #453 (Singa tenant). Adds React hydration lesson, tenant asset endpoint docs, local tenant testing guide, and archive entry. <!-- @coderabbitai ignore --> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
e788187351 |
docs: catalog API, community detection, and autocomplete (#452)
## Summary - Documentation for the song lookup autocomplete and community version detection feature shipped in PR #451 ## Changes - **docs/README.md**: Added feature status rows (song lookup autocomplete, community version detection) and recent changes entry - **docs/API.md**: New "Catalog (Song Lookup)" section documenting all 3 endpoints (`/api/catalog/artists`, `/api/catalog/tracks`, `/api/catalog/community-check`) with request/response examples - **docs/ARCHITECTURE.md**: Added karaoke-decide and KaraokeNerds to external services table, added `catalog_proxy_service.py` and `karaokenerds_service.py` to service modules table - **docs/LESSONS-LEARNED.md**: Added "Autocomplete UX: Less Is More" pattern (single autocomplete that overwrites both fields > dual autocompletes) ## Test plan - Docs-only change, no code modifications @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
e44b5f6543 |
fix: recent jobs UX - cancel→delete, date sort, hide-completed fix, admin controls (#447)
@coderabbitai ignore
## Summary
- **Cancel → Delete**: The Cancel button now permanently deletes jobs
(Firestore doc + GCS files) via the existing `DELETE /api/jobs/{job_id}`
endpoint. Cancelled jobs no longer exist as a concept in the user-facing
flow.
- **Hide completed fix**: The "Hide completed" toggle now only hides
successful completions (`complete`, `prep_complete`). Failed jobs remain
visible so users always see jobs that need attention.
- **Date-only sorting**: Removed priority-based sorting that buried
failed jobs below completed ones. Jobs now sort purely by `created_at`
descending — newest first, always.
- **Admin controls toggle**: Admins see a Shield toggle in the header
that reveals inline admin action buttons (reset, restart, delete, regen
screens, etc.) on each job card — no need to switch to the admin
dashboard.
## Test plan
- [x] Frontend tests pass (496 tests)
- [x] Backend route tests pass (8 tests)
- [x] `next build` succeeds
- [x] New AdminJobActions component has unit tests
- [x] JobCard admin controls rendering tested
- [x] JobActions cancel→delete behavior tested
- [x] E2E regression test updated for delete flow
- [ ] Visual verification: failed job appears at top of Recent Jobs
- [ ] Visual verification: "Hide completed" keeps failed jobs visible
- [ ] Visual verification: Admin shield toggle shows/hides admin actions
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
|
||
|
|
f17bc931d0 |
feat: decouple audio search from job creation (search sessions) (#444)
## Summary - Fixes 4 UX problems caused by the guided wizard creating a backend job at Step 2 (audio search), before the user has set `is_private`, display overrides, or confirmed they want a job at all - Adds `POST /api/audio-search/search-standalone` — runs search synchronously, stores results in a 30-minute Firestore session, returns `search_session_id + results` (no job created) - Adds `POST /api/jobs/create-from-search` — creates job at Step 3 with all correct values from the start; atomically consumes the session to prevent duplicate job creation ## Problems Solved **A) Orphan job records** — abandoned searches left job records in Firestore; back button `deleteJob` cleanup was best-effort **B) Wrong field values at creation** — job existed briefly with `is_private: false` and no display overrides **C) Jobs in Recent Jobs list** — `AWAITING_AUDIO_SELECTION` jobs appeared in the list before user confirmed **D) Notification chime fired** — state transitions on the temporary job triggered the action-required chime during search ## Changes - `backend/routers/audio_search.py` — new `POST /api/audio-search/search-standalone` endpoint (synchronous, no job) - `backend/routers/jobs.py` — new `POST /api/jobs/create-from-search` endpoint with validate-then-consume session pattern - `backend/services/firestore_service.py` — `create_search_session`, `get_search_session`, `consume_search_session` (atomic transaction), `delete_search_session` - `infrastructure/modules/database.py` — Firestore TTL policy for `search_sessions` collection (30-min auto-expiry) - `frontend/lib/api.ts` — `searchStandalone`, `createJobFromSearch` methods - `frontend/components/job/steps/AudioSourceStep.tsx` — uses standalone search; no polling; no job state - `frontend/components/job/GuidedJobFlow.tsx` — defers job creation to Step 3 confirm; no `deleteJob` on back **Unchanged:** old `POST /api/audio-search/search` (CLI backward compat), upload/URL paths, `AWAITING_AUDIO_SELECTION` status. ## Testing - [x] 26 new backend unit tests (`backend/tests/test_standalone_search.py`) covering session CRUD, both new endpoints, ownership/tenant/TTL/index validation, atomic consumption - [x] 13 new frontend Jest tests (`frontend/__tests__/guided-flow.test.tsx`) covering API contract, component exports, behavioral invariants - [x] Full test suite passes: 2167 backend + 507 frontend ## Review - [x] CodeRabbit CLI review completed (3 cycles, 0 remaining findings) - [x] Atomic session consumption via Firestore transaction (prevents duplicate jobs on concurrent requests) - [x] Validate-before-consume pattern (4xx errors leave session intact for user retry) - [x] Tenant consistency check added @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> |
||
|
|
7e3e247858 |
feat: improve audio upload UX + signed URL flow for large files (#442)
@coderabbitai ignore ## Summary - **Better no-results UX**: Replace bare "No audio sources found" text with a contextual `NoResultsSection` card explaining why results might be missing (unreleased tracks, independent music, unusual characters) and what to try - **Softer timeout styling**: Timeout errors now show amber (`text-amber-400 bg-amber-500/10`) instead of red — it's a delay, not a failure. Credit/API errors remain red - **Larger fallback buttons** when no results: `h-12` height and `w-4 h-4` icons (vs `h-9`/`w-3.5 h-3.5`) since upload/URL are the primary actions - **Fix file input text overlap**: Replace `opacity-0` absolute `<Input>` with `<label>` + `<input className="sr-only">` — eliminates browser "Browse..." bleed-through, adds "Click to browse or drag a file" helper text - **Signed URL upload flow** for large files (≥25MB): Bypasses Cloud Run's 32MB body limit; files <25MB still use the existing direct upload - **Upload progress bar**: Phase labels (Preparing / Uploading X/Y MB / Finalizing) + animated progress bar during signed URL uploads - **Large file warning** (>100MB): Amber amber notice about expected upload time - **GCS CORS config**: Add Pulumi CORS rule for `PUT` from `gen.nomadkaraoke.com` and `localhost:3000` — required for browser-to-GCS signed URL uploads to work ⚠️ **Deploy order matters**: The GCS CORS config (infrastructure change) must be deployed before the signed URL upload path will work in production. Both changes are in this PR so they deploy together on merge. ## Test plan - [x] 492 Jest tests passing (9 new tests for `createJobWithUploadUrls`, `uploadToSignedUrl`, `completeJobUpload`, `uploadJobSmart`) - [x] `npx next build` succeeds - [x] CodeRabbit CLI: no findings - [ ] **Manual**: Search for a nonexistent track → verify `NoResultsSection` appears with guidance text and larger buttons - [ ] **Manual**: Trigger a timeout (slow network) → verify amber banner (not red) - [ ] **Manual**: Open upload form → verify no "Browse..." text bleed-through, see "Click to browse or drag a file" - [ ] **Manual** (post-deploy): Upload a file ≥25MB → verify progress bar appears and upload completes 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
0ba5193601 |
fix: recycle brand codes on delete-outputs and job deletion (#437)
## Summary
- E2E happy path test now uses **private mode** (NOMADNP prefix) so test
jobs never consume public NOMAD brand codes or upload to GDrive/YouTube
- `delete-outputs` admin endpoint now **recycles brand codes** after
successful Dropbox + GDrive cleanup
- `DELETE /api/jobs/{id}` endpoint now **recycles brand codes** before
deleting the job record
- Frontend delete-outputs dialog accurately shows brand code recycling
status (recycled/skipped/failed)
## Context
Test jobs ("piri - dog") consumed NOMAD-1275 and NOMAD-1276 brand codes.
When manually deleted via `delete-outputs`, the brand codes were not
recycled back to the counter. This caused the GDrive validator to detect
sequence gaps at 1275/1276 when NOMAD-1277 was later uploaded.
## Test plan
- [x] 7 new unit tests for brand code recycling in both endpoints
- [x] All 490 existing tests pass (483 frontend + backend)
- [x] Frontend builds successfully (TypeScript types updated)
- [ ] Manual: run E2E test, verify job uses NOMADNP prefix
- [ ] Manual: delete-outputs on a test job, verify brand code recycled
in response
<!-- @coderabbitai ignore -->
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
|
||
|
|
e11a5976e3 |
docs: update for feedback-for-credits and beta deprecation (#432)
## Summary - Update docs to reflect feedback-for-credits feature (PR #431) and beta program removal (PR #430) - Add `user_feedback` Firestore collection to architecture docs - Mark beta program section as deprecated in API reference - Add archive entry for the feedback-for-credits feature ## Changes | File | Update | |------|--------| | `docs/README.md` | Replace beta with feedback-for-credits in status table, add recent changes entries | | `docs/API.md` | Mark beta section deprecated, document `feedback_eligible` in `/me`, link from credit enforcement | | `docs/ARCHITECTURE.md` | Add `user_feedback` collection, mark `beta_feedback` as deprecated | | `docs/archive/2026-03-01-feedback-for-credits.md` | New archive entry | ## Test plan - [x] Docs-only change, no code modified - [x] Verified all internal doc links are valid @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
fc659d0357 |
feat: feedback-for-credits mechanism for all users (#431)
## Summary - Users who complete 2+ karaoke videos can submit product feedback to earn 2 free credits - Replaces beta-only feedback flow — available to ALL users - PR 2 of 2: follows #430 which removed the beta program from homepage ## Changes **Backend:** - New `POST /api/users/feedback` endpoint with eligibility checks, validation (>50 char text), credit granting - New `GET /api/users/feedback/eligibility` endpoint - `feedback_eligible` field added to `/api/users/me` response - `UserFeedback` model + `user_feedback` Firestore collection - Welcome email updated with prominent credit display and feedback teaser **Frontend:** - `FeedbackDialog` component: 4 star ratings, 3 text fields, 2 checkboxes, submit/success states - Dismissible banner on dashboard when user is eligible - "Earn 2 Free Credits" menu item in user dropdown (green Gift icon) - Auto-refreshes user data after submission to hide prompts **Docs:** - API.md updated with new endpoints ## Test plan - [ ] Backend Python syntax verified (ast.parse) - [ ] Frontend builds successfully (`npx next build`) - [ ] Version bumped to 0.121.0 - [ ] Manual flow: sign up → create 2 jobs → see banner → submit feedback → credits granted → banner disappears - [ ] Edge cases: duplicate submission blocked, ineligible users don't see prompts <!-- @coderabbitai ignore --> 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
221f26b0d8 |
UX overhaul: guidance & simplification across all 4 review stages (#421)
## Summary Complete UX overhaul of the karaoke video generation review flow, spanning 4 phases: - **Phase 1 - Job Creation**: Guided audio source selection with 3-tier confidence system, responsive stepper, renamed "Find Audio" to "Choose Audio" - **Phase 2 - Audio Selection**: Production E2E tests for guided job creation flow - **Phase 3 - Lyrics Review**: Guidance panel with workflow steps, gap navigation scoped to visible lines, simplified review UI with edit tracking and low-friction feedback - **Phase 4 - Instrumental Review**: Responsive layout (waveform no longer disappears on short viewports), canvas-rendered time ruler, hover-to-highlight waveform regions, dedicated Alternate Instrumental upload section with duration explanation, dismissable guidance panel ### Key changes - Root layout switches from viewport-locked (`h-screen overflow-hidden`) to scrollable (`min-h-screen`) — fixes waveform disappearing on short viewports - Bottom section stacks vertically on mobile/tablet, side-by-side on desktop - Time ruler rendered directly on canvas with auto-scaling tick intervals - Hovering mute region or segment buttons highlights the corresponding waveform range - Upload button moved from toolbar to dedicated section with context and duration requirement - 21 unit tests added for instrumental review components - Guidance panels with dismissable tips across lyrics and instrumental review ## Test plan - [x] `npx next build` — no errors - [x] `npx jest --testPathPattern="instrumental-review/__tests__"` — 21/21 pass - [x] Visual testing at 4 viewports: desktop (1280x800), tablet (768x1024), mobile (375x667), short (1280x400) - [x] Hover highlight verified with Playwright MCP - [x] Time ruler scales correctly at 1x and 2x zoom @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
d7e12e3443 |
Add custom instrumental upload endpoint with duration validation (#409)
## Summary
- Add missing `POST /api/jobs/{job_id}/upload-instrumental` endpoint
(was returning 404 in production)
- Validate uploaded audio duration matches original ±0.5s using ffprobe
on GCS signed URLs
- Fix frontend bug: map "uploaded" → "custom" selection type at submit
time (API only accepts "custom")
## Changes
- **backend/api/routes/jobs.py**: New upload endpoint +
`_get_audio_duration_ffprobe_signed` helper
- **frontend/components/instrumental-review/InstrumentalSelector.tsx**:
Selection type mapping fix
- **backend/tests/test_custom_instrumental_route.py**: 22 new tests
(upload endpoint, ffprobe helper, contract)
- **docs/API.md**: Document new endpoint
- **docs/README.md**: Add to recent changes
- **pyproject.toml**: Bump version 0.119.2 → 0.119.3
## Test plan
- [x] 22 new tests covering success, auth, state validation, duration
mismatch, boundary cases
- [x] All 33 existing tests continue to pass
- [ ] Manual verification: upload custom instrumental in review UI
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
|
||
|
|
20453a877c |
Enforce credit system for karaoke video generation (#404)
## Summary - Wire up the existing credits system to actually gate job creation - previously, credits were tracked but never enforced - Add credit check before job creation, atomic deduction after, and auto-refund on job failure - New users now receive 2 welcome credits (was 1) - Frontend shows zero-credit warning banner, disables submit, and handles 402 errors with "Buy Credits" link - Clean up dead credit deduction code from auth_service ## Changes **Backend:** - `InsufficientCreditsError` exception with 402 handler - Credit check + deduction in `JobManager.create_job()` (admin bypass, atomic deduction, rollback on failure) - Auto-refund in `JobManager.fail_job()` (skipped for admins, error-isolated) - Welcome credits bumped 1 → 2 - Removed dead credit deduction path from `auth_service.increment_token_usage()` **Frontend:** - Zero-credit warning banner at top of job submission form - Submit buttons disabled when credits = 0 - 402 error handling with "Buy Credits" link - Boolean state `isCreditError` (not string matching) for credit error display **Tests:** - 13 new backend unit tests covering enforcement, refunds, admin bypass, atomicity - 3 new Playwright E2E tests for frontend credit UX - Tests for 402 exception handler and auth_service cleanup ## Test plan - [x] Backend unit tests: `pytest tests/test_credit_enforcement.py -v` (13 tests) - [x] 402 handler test in `test_main.py` - [x] Auth service test in `test_auth_firestore.py` - [x] Frontend E2E tests: `npx playwright test e2e/regression/credit-enforcement.spec.ts` - [x] Full suite: `make test` (1928 tests passed) - [ ] Manual: Create test user with 0 credits → verify 402 - [ ] Manual: Create test user with 1 credit → verify deduction - [ ] Manual: Fail a job → verify credit refund <!-- @coderabbitai ignore --> 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
fa9bc8eeeb |
Add private (non-published) tracks option (#403)
@coderabbitai ignore ## Summary - Add `is_private` flag to jobs that changes distribution behavior for non-published tracks - Private jobs upload to Dropbox `Tracks-NonPublished` folder with `NOMADNP` brand prefix - Private jobs skip YouTube and Google Drive uploads entirely - Completion emails omit YouTube section for private jobs - Available to all users at job creation; admin can toggle on existing jobs - When admin toggles completed job to private, existing outputs are auto-deleted ## Changes ### Backend - **Job model**: Added `is_private: bool = False` to `Job` and `JobCreate` - **Config**: Added `DEFAULT_PRIVATE_DROPBOX_PATH` and `DEFAULT_PRIVATE_BRAND_PREFIX` settings - **Distribution helper**: New `get_effective_distribution_for_job()` in `job_defaults_service.py` applies private overrides at runtime - **Orchestrator + native paths**: Both distribution code paths use the helper (per "Fix Both Sides" lesson) - **Email template**: YouTube section conditionally removed when `is_private=True` - **Credential pre-validation**: Skip YouTube/GDrive credential checks for private jobs - **API endpoints**: All 4 job creation endpoints accept `is_private`; admin can PATCH it - **Admin auto-delete**: Toggling completed job to private triggers output deletion ### Frontend - **Job creation form**: "Private (Non-Published)" checkbox on all 3 tabs (upload, URL, search) - **Admin dashboard**: Private toggle in job configuration section - **API interfaces**: Updated TypeScript interfaces and API methods ### Tests - 23 unit tests covering model, distribution overrides, email template, notification service, request models, admin toggle, and orchestrator config - Fixed MagicMock truthiness issue in existing tests ## Test plan - [x] All 23 private tracks tests pass - [x] All 1794 existing backend tests pass (1 flaky unrelated test) - [x] CodeRabbit review: credential pre-validation issue found and fixed - [ ] Manual: Create private job end-to-end, verify Dropbox folder - [ ] Manual: Verify completion email has Dropbox link but no YouTube section - [ ] Manual: Admin toggle on completed job deletes outputs 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
d22f1893f8 |
fix: add missing create-custom-instrumental endpoint and prevent oversized Firestore docs (#400)
## Summary
- Add missing `POST /api/jobs/{id}/create-custom-instrumental` endpoint
that was lost during the unified review UI migration. The endpoint
creates a custom instrumental by muting selected backing vocal regions
and returns a signed audio URL for playback.
- Strip `reference_lyrics` from corrections data before saving to
Firestore `state_data`, preventing 1MB document size limit errors when
Genius fetches non-lyrics content (e.g. screenplays). Full data is
preserved in GCS.
- Update frontend `InstrumentalSelector` to use the signed audio URL
returned from the create endpoint instead of a non-existent stream
endpoint.
## Test plan
- [x] 11 new backend tests covering both fixes (happy path, auth,
validation, error handling, Firestore stripping, GCS preservation)
- [x] Full test suite passes (1912 backend, 168 frontend)
- [ ] Manual test: create custom instrumental on a job in review
- [ ] Manual test: submit corrections for a job with oversized Genius
lyrics
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
|
||
|
|
3ea48e487f |
feat: server-side jobs filtering with field projection (#397)
## Summary - Add `fields=summary` query param to `GET /api/jobs` — uses Firestore `select()` to return only ~12 dashboard-required fields instead of 50+ full Job fields, reducing payload from ~16MB to <500KB - Add `hide_completed=true` query param for server-side filtering of terminal statuses (complete, prep_complete, failed, cancelled) - Safety-net prune helpers strip extra keys from `state_data` and `file_urls` nested dicts - Backward compatible: without `fields=summary`, endpoint returns full `List[Job]` as before (admin pages unaffected) ## Test plan - [x] 8 backend unit tests covering prune helpers, hide_completed, exclude_test with dicts, backward compatibility - [x] 5 frontend Jest tests covering query param serialization and partial summary response handling - [x] All 2412 existing tests pass (`make test`) - [ ] Deploy to staging, verify network tab shows reduced payload size - [ ] Verify JobCard renders correctly with summary data (title, status, progress, download links, error) - [ ] Toggle hide-completed — verify server re-fetch with `hide_completed=true` - [ ] Verify admin jobs page (`/admin/jobs`) still works (doesn't send `fields=summary`) @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
0cecc86b79 |
feat: eager audio transcoding for review UI (#395)
## Summary
- Add `AudioTranscodingService` that transcodes FLAC audio to OGG Opus
128kbps (~3 MB vs 35+ MB), cached in GCS at `review-audio/*.ogg`
- Eager transcoding in `screens_worker` before `AWAITING_REVIEW` so
files are cached before the user opens the review UI
- All 3 review audio paths (`_stream_audio`, `get_correction_data`,
`get_instrumental_analysis`) now serve transcoded OGG URLs with FLAC
fallback
- Admin endpoint `POST /admin/jobs/{job_id}/prepare-review-audio` for
backfilling existing jobs
## Test plan
- [x] 21 unit tests at 100% coverage on `AudioTranscodingService`
- [x] 229 existing review tests pass with 0 regressions
- [ ] Deploy and use admin endpoint to backfill job `4bed6f80`
- [ ] Open review UI — verify audio loads fast, Network tab shows ~3 MB
OGG
- [ ] Check GCS for cached files at `jobs/4bed6f80/review-audio/*.ogg`
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
|
||
|
|
2b1e4ead00 |
fix(admin): perform audio search in override-audio-source endpoint (#374)
## Summary Fixes the override-audio-source endpoint which was transitioning jobs to `awaiting_audio_selection` without actually performing the search, leaving jobs stuck with no results to select from. ## Changes - Now performs actual audio search after clearing state - Stores search results in state_data before transitioning - Updated response model to include `search_results_count` and `error` fields - Updated API docs to reflect new behavior ## Test plan - [x] Ran test_admin_job_reset.py - all 39 tests pass - [x] Manually tested on job 284ed6a6 (populated search results) @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com> |
||
|
|
b7b5d5c814 |
feat(admin): add MFY restart and override admin tools (#373)
## Summary
Add three new admin endpoints for better Made-For-You order management,
plus clean up the admin toolbar to remove confusing low-level buttons.
### New Endpoints
1. **`POST /api/admin/jobs/{job_id}/regenerate-screens`**
- Regenerates title/end screens with current artist/title metadata
- Use after editing artist/title to update screens without full
reprocessing
2. **`POST /api/admin/jobs/{job_id}/restart`**
- Full restart that actually triggers workers (fixes the "stuck in
pending" issue)
- Option to preserve audio stems for faster restart
- Handles YouTube, audio search, and file upload jobs appropriately
3. **`POST /api/admin/jobs/{job_id}/override-audio-source`**
- Switch from YouTube URL to audio search mode
- Allows finding higher quality audio for MFY orders
### Frontend Changes
- Add new toolbar buttons: **Regen Screens**, **Full Restart**, **Audio
Search**
- Remove confusing low-level buttons that could leave jobs in broken
states:
- "Reset to Start" (replaced by "Full Restart")
- "Clear Workers" (low-level escape hatch)
- "Trigger" (low-level escape hatch)
- Add confirmation dialogs with clear explanations
### Use Case
When a customer submits a Made-For-You order with:
- Wrong artist/title → Edit fields, click "Regen Screens"
- Low-quality YouTube URL → Click "Audio Search" to switch to audio
search mode
- Job stuck after reset → Click "Full Restart" to actually trigger
workers
## Test plan
- [ ] Verify new endpoints return proper responses
- [ ] Verify "Regen Screens" regenerates screens with updated metadata
- [ ] Verify "Full Restart" with preserve_audio_stems=true triggers
screens worker
- [ ] Verify "Full Restart" with preserve_audio_stems=false re-downloads
YouTube audio
- [ ] Verify "Audio Search" transitions job to awaiting_audio_selection
- [ ] Verify old confusing buttons are removed from toolbar
🤖 Generated with [Claude Code](https://claude.ai/claude-code)
@coderabbitai ignore
---------
Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
|
||
|
|
20b75dcdf5 |
feat: add flacfetch version and health indicator to frontend footer (#353)
## Summary Add flacfetch service health monitoring to the frontend footer, displaying version and status alongside the existing encoding worker indicator. ## Changes - **Backend**: Added `/api/health/flacfetch` endpoint for lightweight health checks - **Frontend**: Added flacfetch health display in version footer with green/red status indicator - **Tests**: Added 6 comprehensive unit tests for health endpoints (flacfetch + encoding worker) - **Docs**: Updated API.md with new endpoint documentation ## Implementation Details The footer now displays: ``` Frontend: v0.114.8 | Backend: v0.114.8 | ● Encoder: v0.95.1 | ● Flacfetch: v1.2.3 ``` Health indicators: - Green dot (●) = service healthy - Red dot (○) = service offline - Hidden if service not configured ## Testing - [x] All 1749 tests pass (including 6 new health endpoint tests) - [x] Manual code review completed (CodeRabbit CLI couldn't handle large diff) - [x] API endpoint tested for all states (not_configured, offline, ok) ## Review - [x] Code quality verified - follows existing patterns - [x] Tests comprehensive - all response states covered - [x] Documentation updated - API.md includes new endpoint @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com> |