Compare commits

...
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.6 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>
2026-03-02 11:25:04 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 89c37a37f3 Reduce idle reminder delay from 5 to 2 minutes (#435)
## Summary
- Reduce the `IDLE_REMINDER_DELAY_SECONDS` from 5 minutes to 2 minutes
so users get their review prompt email sooner after a job reaches
ready-for-review status

## Test plan
- [ ] CI passes
- [ ] Deploy and verify next job that hits AWAITING_REVIEW sends email
after ~2 minutes

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 00:42:40 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 d415c3b2f5 Update homepage demo video (#436)
## Summary
- Update the YouTube demo video on the landing page from `uvKtLOUiqz8`
to `GJY60IfIHOQ`

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 05:41:08 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 a8ea9e6d38 feat: in-app Buy Credits dialog and pricing updates (#434)
## Summary
- Fix broken "Buy More Credits" flow for logged-in users — replaces
redirect (which bounced back to `/app`) with an in-app dialog
- Add `BuyCreditsDialog` component following the existing
`FeedbackDialog` pattern
- Make credits count in header clickable to open the buy dialog
- Update "Made For You" pricing from $15 to $50 (frontend labels +
Stripe backend)
- Update hero section: "Create It Yourself ($5)", green "2 free credits"
message, remove redundant line, tighten spacing

## Test plan
- [ ] Log in, click "Buy More Credits" in dropdown — dialog opens with
package grid
- [ ] Click credits count in header — same dialog opens
- [ ] Select package, click "Continue to Payment" — redirects to Stripe
checkout
- [ ] Landing page pricing still works for unauthenticated users
- [ ] Made For You order form shows $50 pricing
- [ ] Hero section shows updated copy and tighter spacing

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 05:04:22 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 9511d03912 Add delete user to admin dashboard (#433)
## Summary
- Adds backend `delete_user` method to UserService that deletes user
document, sessions, and magic links (prevents deleting admins)
- Adds `DELETE /admin/users/{email}` endpoint with admin auth
- Adds `deleteUser` to frontend API client
- Adds Delete User button + AlertDialog confirmation on admin user
detail page

Jobs are preserved as historical records — only user auth data is
removed.

## Test plan
- [ ] Navigate to admin user detail page for a non-admin test user
- [ ] Verify "Delete User" button appears (should not appear for admin
users)
- [ ] Click delete, verify confirmation dialog appears
- [ ] Confirm deletion, verify success toast and redirect to user list
- [ ] Verify user no longer appears in the list

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 04:41:13 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 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>
2026-03-01 23:35:54 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 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>
2026-03-01 23:05:45 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 61e4cec189 Remove beta program, promote free credits on homepage (#430)
## Summary

- Remove the beta tester program section from the homepage — users
already get 2 free credits on signup, making the beta enrollment form
unnecessary friction
- Update hero CTA to open auth dialog with "Free" badge instead of
linking to pricing with "$5"
- Add prominent free credits callout card in the pricing section with
"Sign Up Free" button
- Remove 5 beta enrollment E2E tests, update landing page and smoke
tests for new free credits UI
- Update product communication guide to reflect free credits instead of
beta program

This is PR 1 of 2. Backend beta endpoints and admin pages are unchanged.
PR 2 will add the feedback-for-credits mechanism.

## Test plan

- [x] `npm run build` passes with no errors from removed imports/state
- [x] 4 auth regression tests pass (magic link + token persistence)
- [x] Landing page and smoke tests updated and passing for free credits
UI
- [x] All 161 passing regression tests still pass (21 pre-existing
failures unrelated to this change)

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 21:06:56 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 30105b1ad1 Update homepage screenshots and add demo recording tooling (#429)
## Summary
- Replace all 4 homepage AVIF screenshots with fresh captures from
production E2E test reflecting recent UX improvements
- Update screenshot labels and descriptions in landing page (page.tsx)
- Add demo video recording infrastructure: Playwright config, E2E spec,
and ffmpeg post-processing script
- Refresh all 16 docs/images screenshots from latest E2E happy path run

## Changes
- **Homepage screenshots**: Replaced job-dashboard, lyrics-review,
instrumental-review, and example-output AVIF/PNG files
- **Landing page copy**: Updated alt text, titles, descriptions to match
new UX (e.g., "Create Your Video", "Review Lyrics", "Choose Your
Instrumental", "Download & Share")
- **Demo tooling**: `playwright.demo.config.ts` (1280x720 recording),
`demo-recording.spec.ts` (paced walkthrough), `create-demo-video.mjs`
(ffmpeg post-processor)
- **npm scripts**: Added `test:e2e:demo`, `test:e2e:demo:headed`,
`demo:create-video`

## Test plan
- [x] All 483 unit tests pass
- [x] Next.js build succeeds
- [x] Screenshots verified from production E2E run
- [x] Demo recording spec tested against production (18.8 min run, all
10 scenes captured)

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 18:59:25 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 5bfefd2df9 Improve E2E test robustness and add production screenshots (#428)
## Summary
- Add `gotoWithRetry()` helper for resilient navigation (retries up to
3x with backoff)
- Apply to all production page navigations (landing, /app, review page)
- Construct absolute URL for review page instead of relying on relative
href
- Add content verification after review page load with automatic reload
fallback
- Add 16 production screenshots documenting the complete happy path
journey

## Root Cause
The previous test run failed with `net::ERR_INTERNET_DISCONNECTED` when
opening the review page in a new tab — a transient network error during
the long-running test. The retry logic handles this gracefully.

## Verified
Full end-to-end test passed against production (17.8 minutes, all 12
steps).

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 14:43:46 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 6248b2c50d Fix title card preview font loading race condition (#427)
<!-- @coderabbitai ignore -->

## Summary
- Fix canvas title card preview rendering with serif fallback font on
initial page load
- Canvas API doesn't participate in CSS font swap, so it was drawing
text before the custom font (AvenirNext-Bold) finished loading
- Now explicitly checks `document.fonts.check()` and awaits
`document.fonts.load()` before rendering text on the canvas
- Removed the unreliable `document.fonts.ready` effect (resolves
immediately when no fonts are actively loading)

## Test plan
- [x] Added 5 unit tests for TitleCardPreview font loading behavior
- [x] All 483 frontend unit tests pass
- [x] All 1086 backend tests pass
- [x] CodeRabbit review: no findings
- [ ] Verify in production that title card preview renders with correct
font on first load

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 14:40:59 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 4fe0a8f7c8 Improve E2E screenshot quality and timing (#426)
## Summary
- Remove redundant/duplicate screenshots (05b, 07b, 07e/07f/07g, 08d
duplicate, 10)
- Add render waits before screenshots that were capturing too early
(customize step, preview modal, instrumental page)
- Consolidate the preview video screenshot group into a single
meaningful capture

Reduces total screenshots from 23 to ~17 while improving quality of each
capture.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 14:05:28 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 4bf70138b5 Fix notification chime behavior for audio selection and completion (#425)
## Summary
- Stop playing the action-needed chime when a job enters
`awaiting_audio_selection` — the user is already engaged with the inline
audio picker, so the notification is unnecessary
- Add a distinct success chime (rising C major arpeggio: C6→E6→G6) for
job completion, so users can tell "done" apart from "attention needed"
by sound alone
- Keep existing alert chime for `awaiting_review`, `in_review`,
`awaiting_instrumental_selection`, and `failed`

## Changes
- **`frontend/lib/job-status.ts`**: Add `isNotifiableBlockingStatus()` —
delegates to `isBlockingStatus()` but excludes
`awaiting_audio_selection`. UI sorting/badges/cards unchanged.
- **`frontend/hooks/use-notifications.ts`**: Refactor sound system into
`playAlertChime()` and `playSuccessChime()`, route by
`NotificationReason`. Switch notification filtering to
`isNotifiableBlockingStatus()`.
- **`frontend/__tests__/job-status.test.ts`**: 7 new tests for
`isNotifiableBlockingStatus` (true/false cases, case insensitivity,
null/undefined).

## Test plan
- [x] All 478 Jest tests pass (including 7 new tests)
- [x] CodeRabbit review: no findings
- [ ] Manual: create a job via audio search — confirm no chime during
audio selection
- [ ] Manual: let a job reach review — confirm alert chime plays
- [ ] Manual: let a job complete — confirm distinct success chime plays

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 13:50:13 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 e3645b54d4 Fix happy path E2E test for guided job creation flow (#424)
## Summary
- Update Steps 4-5 of the happy path E2E test to use the new 3-step
guided flow
- Old flow: Search tab → dialog → select → job card
- New flow: Song Info → Choose Audio (inline search) → Customize &
Create → Job Created

## Test plan
- [x] Run happy path test against production
- [ ] All CI checks pass

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 13:16:45 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 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>
2026-03-01 02:58:50 -05:00
Andrew Beveridge ☄️ ef4439b6cc Added docs/archive/2026-02-28-gdrive-validator-email-alerts-plan.md (#423) 2026-02-28 21:43:18 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 e102a2bf36 Fix event loop blocking in audio search endpoints (#422)
@coderabbitai ignore

## Summary
- Fix `/api/audio-search/{job_id}/select` taking 20-36s to respond
(should be <1s) and `/api/audio-search/search` sometimes taking 25-47s
- Root cause: async endpoints called sync methods that create new event
loops via `loop.run_until_complete()`, blocking the FastAPI event loop
- RED/OPS and Spotify download paths now call FlacfetchClient async
methods directly (matching YouTubeDownloadService pattern)
- Generic downloads use `asyncio.to_thread()` as safe fallback
- Search endpoint uses `search_async()` instead of sync `search()`
- Fixed `InsufficientCreditsError` occasionally returning 500 instead of
402
- Added fail-fast guard for missing `remote_search_id` in torrent
download fallback

## Test plan
- [x] 14 new tests covering async download paths, error handling, and
exception propagation
- [x] All 2099 tests pass (1 pre-existing unrelated failure in test
ordering)
- [x] CodeRabbit review: 1 finding fixed (missing remote_search_id
guard)
- [ ] Deploy to prod and verify `/select` latency drops from 20-36s to
<1s
- [ ] Verify InsufficientCreditsError returns 402 not 500

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 16:41:59 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 18fa1aa03f Fix gdrive-validator scheduler IAM + API key whitespace (#420)
@coderabbitai ignore

## Summary

- Add `roles/run.invoker` for the validator's own service account on the
Cloud Run service — Gen2 functions need this for Cloud Scheduler's OIDC
token to be accepted
- Strip whitespace from Pushbullet and SendGrid API key env vars
(handles trailing newlines in Secret Manager values)

This codifies the manual gcloud fix from #412 into Pulumi IaC and closes
that PR.

## Already deployed

- Pulumi applied: IAM binding created
- Cloud function redeployed with `.strip()` fix

## Test plan

- [x] `pulumi preview` — clean, 1 create
- [x] `pulumi up` — applied successfully
- [x] Cloud function redeployed

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 01:14:23 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 e0c8645fea Add email alerts, manual trigger, and post-job check to GDrive validator (#419)
@coderabbitai ignore

## Summary

- **Email notifications via SendGrid** — replaces Pushbullet as the
primary notification channel for the GDrive validator cloud function.
Pushbullet kept as secondary fallback.
- **Post-job trigger** — the backend orchestrator now triggers GDrive
validation after each job that uploads to the public share, catching
duplicates within minutes instead of up to 24 hours.
- **Manual CLI** — `python scripts/check_public_share.py` for on-demand
validation checks with formatted output and `--json` flag.
- **Comprehensive docs** — `docs/GDRIVE-VALIDATOR.md` with architecture,
configuration, troubleshooting, and operational reference.

Motivated by the NOMAD-1271 duplicate brand code incident where
daily-only checks left a duplicate undetected for ~24 hours.

## Changes

| File | Change |
|------|--------|
| `infrastructure/functions/gdrive_validator/main.py` | Add
`send_email_notification()` via SendGrid, unified `send_notification()`
sends both email + Pushbullet |
| `infrastructure/functions/gdrive_validator/requirements.txt` | Add
`sendgrid>=6.0.0` |
| `infrastructure/functions/gdrive_validator/deploy.sh` | Add SendGrid
secret + email env vars |
| `infrastructure/__main__.py` | Add SendGrid secret to function,
backend SA invoker IAM (Cloud Functions + Cloud Run) |
| `infrastructure/modules/secrets.py` | Add `gdrive-validator-url`
secret |
| `.github/workflows/ci.yml` | Add `GDRIVE_VALIDATOR_URL` to Cloud Run
deploy secrets |
| `backend/services/gdrive_validator_client.py` | **New**: HTTP client
with OIDC auth, fire-and-forget pattern |
| `backend/workers/video_worker_orchestrator.py` | Add Stage 6:
post-distribution GDrive validation (only when `gdrive_folder_id` set) |
| `scripts/check_public_share.py` | **New**: CLI tool for manual
validation checks |
| `docs/GDRIVE-VALIDATOR.md` | **New**: Comprehensive validator
documentation |
| `pyproject.toml` | Version bump to 0.119.9 |

## Already deployed

- Pulumi infrastructure applied (IAM bindings, secrets, function config)
- Cloud Function redeployed with SendGrid support
- `gdrive-validator-url` secret set in Secret Manager
- Tested via `check_public_share.py` — validated 3,608 files, email sent
successfully

## Test plan

- [x] `make test` — 170 passed, 3 skipped (1 pre-existing failure in
credit-enforcement unrelated to this PR)
- [x] `pulumi preview` — clean, 3 creates + 1 update
- [x] `pulumi up` — applied successfully
- [x] Cloud Function deployed and tested end-to-end
- [x] `python scripts/check_public_share.py` — formatted output works
- [x] `python scripts/check_public_share.py --json` — JSON output works
- [x] Email received at gen@nomadkaraoke.com (notification_sent: true)
- [ ] Post-job trigger: will verify on next job completion (backend
needs redeploy via CI merge)

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 01:05:16 -05:00
Andrew Beveridge ☄️andClaude c7b7f4bee5 fix: gate brand code recycling on full GDrive cleanup confirmation (#418)
## Summary

- Brand code `NOMAD-1271` was reused for a real song (Hot Mulligan - Pop
Shuvit) while old E2E test job files still existed in Google Drive,
creating a duplicate in the public share
- Root cause: `cleanup-distribution` endpoint had two bugs that allowed
brand codes to be recycled before GDrive was confirmed clean

## Root Causes

1. **Empty dict was falsy**: `if gdrive_files:` skips cleanup when
`gdrive_files = {}` (empty dict). This happened when GDrive uploads
silently failed (pre-PR #417), so test job files accumulated in GDrive
without ever being cleaned
2. **Brand code recycled too early**: Brand code was recycled
immediately after Dropbox cleanup succeeded, *without* confirming GDrive
was also clean — a new job could claim the recycled code while old
GDrive files still existed

## Changes

- **`gdrive_service.py`**: Added `find_files_by_brand_code()` — searches
CDG/, MP4/, MP4-720p/ subfolders by brand code prefix as a fallback when
tracked file IDs aren't available (old jobs, or jobs where upload failed
silently). Raises `RuntimeError` if any subfolder search fails so
callers can't misread an incomplete search as "GDrive is clean"
- **`jobs.py` (`cleanup-distribution`)**: Now uses tracked file IDs
(fast path) OR falls back to brand_code search; brand code is only
recycled after **both** Dropbox AND GDrive are confirmed clean. Fixed
`method` key being lost when results dict was replaced (use local
variable instead of interim mutation)
- **`scripts/cleanup_test_job_gdrive.py`**: Remediation script to delete
existing stranded test job files from GDrive

## Testing

- 41 tests passing, 94% coverage on `gdrive_service.py`
- New `TestDeleteFile` class (5 tests for `delete_file`/`delete_files` —
previously uncovered)
- New `test_cleanup_distribution.py` (9 tests covering fast path,
fallback, and brand code gating logic)
- Updated error handling test to verify `RuntimeError` is raised (not
swallowed) on subfolder search failure
- [x] CodeRabbit CLI review completed, 2 findings fixed

@coderabbitai ignore

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

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-27 17:35:50 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 0f5ddb0092 Fix silent Google Drive upload failures with retry + alerting (#417)
## Summary
- Added tenacity retry with connection reset to Google Drive API calls
(`get_or_create_folder`, `upload_file`, `delete_file`) to handle stale
HTTP connections on idle Cloud Run containers
- Added `distribution_warnings` field to `OrchestratorResult` and
`_handle_native_distribution()` to track non-fatal upload failures
(YouTube, Dropbox, GDrive)
- Added Pushbullet notification when distribution uploads fail, so
operator is alerted immediately
- Added backfill script (`scripts/backfill_gdrive_uploads.py`) for
affected jobs - already run successfully for 12 affected jobs
- Updated docs: LESSONS-LEARNED.md and TROUBLESHOOTING.md with GDrive
stale connection pattern

## Context
Every GDrive upload silently failed for ~1 month (64 errors, 12+
affected jobs). The root cause was the singleton `GoogleDriveService`
caching its HTTP connection, which went stale when Cloud Run containers
sat idle between jobs. The orchestrator caught all exceptions and
continued, so jobs completed with `gdrive_files: {}` and no alert was
sent.

## Test plan
- [x] 5 new retry behavior tests in `test_gdrive_service.py`
(BrokenPipeError, SSLError, give up after 3, service reset, no retry on
non-transient)
- [x] 3 new distribution warnings tests in
`test_video_worker_orchestrator.py`
- [x] All 76 affected tests pass
- [x] Full backend test suite passes
- [x] Backfill script already run successfully for all 12 affected jobs

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 19:47:30 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 23a8b0fb98 Fix missing CDG ZIP packages: fail-fast validation + remediation (#416)
## Summary

- **Systemic fix**: Orchestrator now validates CDG/TXT outputs after
packaging, before encoding. If `enable_cdg=True` but no CDG ZIP was
produced, the job fails immediately with a clear error instead of
silently completing without the package.
- **Remediation**: Created `scripts/regenerate_cdg.py` to regenerate and
distribute CDG/TXT packages for affected jobs (5b6aba25, 5161b069).
Packages uploaded to GCS, GDrive, and Dropbox.
- **Root cause**: Before b671b83f, `instrumental_selection: custom` had
no case in the orchestrator config builder — fell through to "Backing"
suffix, CDG generator looked for wrong filename, `FileNotFoundError` was
silently caught.

## Changes

| File | Change |
|------|--------|
| `backend/workers/video_worker_orchestrator.py` | Post-packaging
validation + LRC-missing check update |
| `backend/tests/test_video_worker_orchestrator.py` | 8 new tests in
`TestPackagingValidation` |
| `scripts/regenerate_cdg.py` | One-time remediation script (GCS +
Firestore + GDrive + Dropbox) |
| `docs/LESSONS-LEARNED.md` | Pipeline stage validation pattern |
| `docs/TROUBLESHOOTING.md` | CDG missing recovery runbook |
| `docs/README.md` | Updated recent changes |
| `pyproject.toml` | Version 0.119.6 → 0.119.7 |

## Test plan

- [x] 8 new tests in `TestPackagingValidation` (CDG fails, TXT fails,
combined CDG+TXT fails, CDG succeeds, CDG disabled, LRC missing raises
with CDG, LRC missing raises with TXT, LRC missing skips without CDG)
- [x] All 2062+ backend tests pass
- [x] Remediation script run successfully for both affected jobs
- [x] Verified CDG/TXT ZIPs in GCS, Firestore, GDrive, and Dropbox

> **CodeRabbit note**: 1 finding (unreachable `else` branch in
`_run_packaging` LRC check) — kept as defensive code since the test
`test_lrc_missing_skips_when_cdg_disabled` exercises this path directly.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 19:13:22 +00:00
Andrew Beveridge ☄️ 028e9f40d4 docs: add TROUBLESHOOTING.md with encoding recovery runbook (#415)
Follows up on #414 — that PR got merged before the force-push landed, so
TROUBLESHOOTING.md was missing.

- Creates `docs/TROUBLESHOOTING.md` with the encoding recovery runbook
- Trims the verbose block from CLAUDE.md down to a one-line pointer
- Adds TROUBLESHOOTING.md to the quick reference table in CLAUDE.md

Docs-only, no code changes.

<!-- @coderabbitai ignore -->
2026-02-27 12:53:45 -05:00
162 changed files with 15543 additions and 1888 deletions

No files matched your search

+1 -1
View File
@@ -1243,7 +1243,7 @@ jobs:
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
--vpc-egress private-ranges-only \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,AUDIO_SEPARATOR_API_URL=https://nomadkaraoke--audio-separator-api.modal.run,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true" \
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest"
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
- name: Verify deployment and version
run: |
+2 -22
View File
@@ -19,6 +19,7 @@
| **Testing & code quality** | `docs/TESTING.md` |
| API reference | `docs/API.md` |
| Past learnings | `docs/LESSONS-LEARNED.md` |
| **Operational runbooks** | `docs/TROUBLESHOOTING.md` |
| **Product communication** | `docs/PRODUCT-COMMUNICATION-GUIDE.md` |
| Brand style guide | `docs/BRAND-STYLE-GUIDE.md` |
@@ -137,28 +138,7 @@ gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
--command="sudo systemctl restart encoding-worker"
```
**Job stuck at `encoding` status?** This happens when a Cloud Run deployment kills the poller mid-encoding. The GCE worker finishes but nobody receives the result. Recovery steps:
```bash
# 1. Check if the job is flagged by health monitoring
curl -s "https://api.nomadkaraoke.com/api/health/job-consistency" \
-H "X-Admin-Token: $(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke)" \
| python3 -m json.tool | grep -A3 "encoding_stuck"
# 2. Check GCE worker status for the specific job
WORKER_URL=$(gcloud secrets versions access latest --secret=encoding-worker-url --project=nomadkaraoke)
WORKER_KEY=$(gcloud secrets versions access latest --secret=encoding-worker-api-key --project=nomadkaraoke)
curl -s "$WORKER_URL/status/YOUR_JOB_ID" -H "X-API-Key: $WORKER_KEY" | python3 -m json.tool
# 3. Re-trigger the video worker — it will rejoin the GCE poll if still running,
# or pick up the cached result if already complete
curl -X POST "https://api.nomadkaraoke.com/api/internal/workers/video" \
-H "X-Admin-Token: $(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke)" \
-H "Content-Type: application/json" \
-d '{"job_id": "YOUR_JOB_ID"}'
```
Note: **SSH restart is not needed** for stuck encoding jobs since PR #413 (v0.119.6). The `/encode` endpoint is now idempotent — re-triggering the video worker is sufficient.
For job stuck at `encoding` status, see [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md).
### What Doesn't Work
- `gcloud auth print-identity-token` - Wrong token type for internal endpoints
+22 -2
View File
@@ -1551,8 +1551,9 @@ async def delete_job_outputs(
This endpoint deletes:
1. YouTube video (if uploaded)
2. Dropbox folder (if uploaded) - frees brand code for reuse
2. Dropbox folder (if uploaded)
3. Google Drive files (if uploaded)
4. Recycles brand code for reuse (if Dropbox + GDrive cleanup succeeded)
The job record is preserved with outputs_deleted_at timestamp set.
State data related to distribution is cleared.
@@ -1688,6 +1689,23 @@ async def delete_job_outputs(
logger.error(f"Error deleting GCS finals folder for job {job_id}: {e}", exc_info=True)
results["gcs_finals"] = {"status": "error", "error": str(e)}
# Recycle brand code if Dropbox and GDrive cleanup both succeeded
dropbox_success = results["dropbox"]["status"] in ("success", "skipped")
gdrive_success = results["gdrive"]["status"] in ("success", "skipped")
if brand_code and dropbox_success and gdrive_success:
try:
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
prefix, number = BrandCodeService.parse_brand_code(brand_code)
get_brand_code_service().recycle_brand_code(prefix, number)
results["brand_code"] = {"status": "recycled", "code": brand_code}
logger.info(f"Recycled brand code {brand_code} during delete-outputs for job {job_id}")
except (ValueError, Exception) as e:
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
results["brand_code"] = {"status": "failed", "error": str(e)}
elif brand_code:
logger.warning(f"Brand code {brand_code} NOT recycled: cleanup incomplete (dropbox={results['dropbox']['status']}, gdrive={results['gdrive']['status']})")
results["brand_code"] = {"status": "skipped", "reason": "Dropbox/GDrive cleanup incomplete"}
# Update job record
deletion_timestamp = datetime.now(timezone.utc)
user_service = get_user_service()
@@ -1735,12 +1753,14 @@ async def delete_job_outputs(
overall_status = "success"
message = "Outputs deleted successfully"
brand_code_status = results.get('brand_code', {}).get('status', 'n/a')
logger.info(
f"Admin {admin_email} deleted outputs for job {job_id}. "
f"YouTube: {results['youtube']['status']}, "
f"Dropbox: {results['dropbox']['status']}, "
f"GDrive: {results['gdrive']['status']}, "
f"GCS Finals: {results['gcs_finals']['status']}. "
f"GCS Finals: {results['gcs_finals']['status']}, "
f"Brand Code: {brand_code_status}. "
f"Cleared state_data keys: {cleared_keys}"
)
+56 -22
View File
@@ -35,6 +35,7 @@ from backend.services.audio_search_service import (
NoResultsError,
DownloadError,
)
from backend.services.flacfetch_client import get_flacfetch_client, FlacfetchServiceError
from backend.services.youtube_download_service import (
get_youtube_download_service,
YouTubeDownloadError,
@@ -382,8 +383,9 @@ async def _download_audio_and_trigger_workers(
raise DownloadError(f"YouTube download failed: {e}")
elif source_name in ['RED', 'OPS']:
# Torrent sources - must use remote flacfetch
if not audio_search_service.is_remote_enabled():
# Torrent sources - must use remote flacfetch (async, no event loop blocking)
flacfetch_client = get_flacfetch_client()
if not flacfetch_client:
raise DownloadError(
f"Cannot download from {source_name} without remote flacfetch service. "
"Configure FLACFETCH_API_URL."
@@ -393,31 +395,48 @@ async def _download_audio_and_trigger_workers(
if source_id:
logger.info(f"Torrent download via download_by_id: {source_name} ID={source_id}")
result = audio_search_service.download_by_id(
download_id = await flacfetch_client.download_by_id(
source_name=source_name,
source_id=source_id,
output_dir="",
target_file=target_file,
download_url=download_url,
gcs_path=gcs_destination,
)
else:
if not remote_search_id:
raise DownloadError(
f"No source_id or remote_search_id available for {source_name} download"
)
logger.info(f"Torrent download via search-based download")
result = audio_search_service.download(
download_id = await flacfetch_client.download(
search_id=remote_search_id,
result_index=selection_index,
output_dir="",
gcs_path=gcs_destination,
remote_search_id=remote_search_id,
)
# Extract GCS path from result
audio_gcs_path = _extract_gcs_path(result.filepath)
filename = os.path.basename(result.filepath)
def log_progress(status):
progress = status.get("progress", 0)
speed = status.get("download_speed_kbps", 0)
logger.debug(f"Download progress: {progress:.1f}% ({speed:.1f} KB/s)")
final_status = await flacfetch_client.wait_for_download(
download_id,
timeout=600,
progress_callback=log_progress,
)
filepath = final_status.get("gcs_path") or final_status.get("output_path")
if not filepath:
raise DownloadError("Remote download completed but no file path returned")
audio_gcs_path = _extract_gcs_path(filepath)
filename = os.path.basename(filepath)
logger.info(f"Torrent download complete: {audio_gcs_path}")
elif source_name == 'Spotify':
# Spotify downloads - use audio_search_service
if not audio_search_service.is_remote_enabled():
# Spotify downloads - use async FlacfetchClient directly (no event loop blocking)
flacfetch_client = get_flacfetch_client()
if not flacfetch_client:
raise DownloadError(
f"Cannot download from Spotify without remote flacfetch service. "
"Configure FLACFETCH_API_URL."
@@ -426,25 +445,40 @@ async def _download_audio_and_trigger_workers(
gcs_destination = f"uploads/{job_id}/audio/"
logger.info(f"Spotify download: source_id={source_id}")
result = audio_search_service.download_by_id(
download_id = await flacfetch_client.download_by_id(
source_name=source_name,
source_id=source_id,
output_dir="",
download_url=download_url,
gcs_path=gcs_destination,
)
audio_gcs_path = _extract_gcs_path(result.filepath)
filename = os.path.basename(result.filepath)
def log_progress(status):
progress = status.get("progress", 0)
speed = status.get("download_speed_kbps", 0)
logger.debug(f"Download progress: {progress:.1f}% ({speed:.1f} KB/s)")
final_status = await flacfetch_client.wait_for_download(
download_id,
timeout=600,
progress_callback=log_progress,
)
filepath = final_status.get("gcs_path") or final_status.get("output_path")
if not filepath:
raise DownloadError("Remote download completed but no file path returned")
audio_gcs_path = _extract_gcs_path(filepath)
filename = os.path.basename(filepath)
logger.info(f"Spotify download complete: {audio_gcs_path}")
else:
# Unknown source - try generic download
# Unknown source - try generic download (run sync code in thread to avoid blocking)
logger.warning(f"Unknown source type: {source_name}, attempting generic download")
temp_dir = tempfile.mkdtemp(prefix=f"audio_download_{job_id}_")
try:
result = audio_search_service.download(
result = await asyncio.to_thread(
audio_search_service.download,
result_index=selection_index,
output_dir=temp_dir,
remote_search_id=remote_search_id,
@@ -494,7 +528,7 @@ async def _download_audio_and_trigger_workers(
worker_service.trigger_lyrics_worker(job_id)
)
except DownloadError as e:
except (DownloadError, FlacfetchServiceError) as e:
logger.error(f"Download failed for job {job_id}: {e}")
job_manager.fail_job(job_id, f"Audio download failed: {e}")
except Exception as e:
@@ -734,7 +768,7 @@ async def search_audio(
audio_search_service = get_audio_search_service()
try:
search_results = audio_search_service.search(body.artist, body.title)
search_results = await audio_search_service.search_async(body.artist, body.title)
except NoResultsError as e:
job_manager.fail_job(job_id, f"No audio sources found for: {body.artist} - {body.title}")
raise HTTPException(
@@ -867,9 +901,9 @@ async def search_audio(
except HTTPException:
raise
except (InsufficientCreditsError, RateLimitExceededError):
raise
except Exception as e:
if isinstance(e, (InsufficientCreditsError, RateLimitExceededError)):
raise
logger.error(f"Error in audio search: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
+147 -23
View File
@@ -361,6 +361,24 @@ async def delete_job(
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to delete this job")
# Recycle any unreturned brand code before deleting the job record
state_data = job.state_data or {}
brand_code = state_data.get('brand_code')
if brand_code:
if not job.outputs_deleted_at:
logger.warning(
f"Deleting job {job_id} with brand_code {brand_code} whose outputs "
f"were not cleaned up first. Brand code will be recycled but "
f"distributed files (GDrive/Dropbox/YouTube) may be orphaned."
)
try:
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
prefix, number = BrandCodeService.parse_brand_code(brand_code)
get_brand_code_service().recycle_brand_code(prefix, number)
logger.info(f"Recycled brand code {brand_code} before deleting job {job_id}")
except (ValueError, Exception) as e:
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
job_manager.delete_job(job_id, delete_files=delete_files)
return {"status": "success", "message": f"Job {job_id} deleted"}
@@ -644,6 +662,55 @@ async def submit_corrections(
raise HTTPException(status_code=500, detail=str(e))
@router.post("/{job_id}/edit-log")
async def submit_edit_log(
job_id: str,
edit_log: Dict[str, Any],
auth_result: AuthResult = Depends(require_auth)
) -> dict:
"""
Store an edit log from a lyrics review session.
Edit logs capture what edits users made and optional feedback on why,
for use as training data to improve transcription models.
Stored to GCS as jobs/{job_id}/lyrics/edit_log_{session_id}.json.
"""
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
session_id = edit_log.get("session_id", "unknown")
entries = edit_log.get("entries", [])
feedback_count = sum(1 for e in entries if e.get("feedback") and e["feedback"].get("reason") != "no_response")
try:
storage = StorageService()
gcs_path = f"jobs/{job_id}/lyrics/edit_log_{session_id}.json"
storage.upload_json(gcs_path, edit_log)
job_manager.update_state_data(job_id, 'last_edit_log_path', gcs_path)
job_manager.update_state_data(job_id, 'last_edit_log_session', session_id)
logger.info(
f"Job {job_id}: Edit log saved — {len(entries)} entries, "
f"{feedback_count} with feedback, session {session_id}"
)
return {
"status": "success",
"entries_count": len(entries),
"feedback_count": feedback_count,
}
except Exception as e:
logger.error(f"Error saving edit log for job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
@router.post("/{job_id}/create-custom-instrumental")
async def create_custom_instrumental(
job_id: str,
@@ -1655,6 +1722,7 @@ async def cleanup_distribution(
# Clean up Dropbox
brand_code = state_data.get('brand_code')
dropbox_path = getattr(job, 'dropbox_path', None)
dropbox_cleaned = False
if brand_code and dropbox_path:
try:
from backend.services.dropbox_service import get_dropbox_service
@@ -1664,22 +1732,11 @@ async def cleanup_distribution(
folder_name = f"{brand_code} - {base_name}"
full_path = f"{dropbox_path}/{folder_name}"
success = dropbox.delete_folder(full_path)
dropbox_cleaned = success
results["dropbox"] = {
"status": "success" if success else "failed",
"path": full_path
}
# Recycle the brand code number so it can be reused
if success:
try:
from backend.services.brand_code_service import (
BrandCodeService, get_brand_code_service
)
prefix, number = BrandCodeService.parse_brand_code(brand_code)
get_brand_code_service().recycle_brand_code(prefix, number)
results["dropbox"]["recycled_brand_code"] = True
except (ValueError, Exception) as e:
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
results["dropbox"]["recycled_brand_code"] = False
else:
results["dropbox"] = {"status": "failed", "reason": "Dropbox credentials not configured"}
except Exception as e:
@@ -1687,25 +1744,92 @@ async def cleanup_distribution(
results["dropbox"] = {"status": "error", "error": str(e)}
# Clean up Google Drive
# Use tracked file IDs if available; otherwise fall back to searching by brand code.
# This handles old jobs where gdrive_files was not persisted (e.g., uploaded before
# file ID tracking was implemented, or when GDrive upload silently failed and a
# previous test run left files behind).
gdrive_files = state_data.get('gdrive_files')
if gdrive_files:
gdrive_folder_id = getattr(job, 'gdrive_folder_id', None)
gdrive_cleaned = False
if gdrive_files or (gdrive_folder_id and brand_code):
try:
from backend.services.gdrive_service import get_gdrive_service
gdrive = get_gdrive_service()
if gdrive.is_configured:
# gdrive_files is a dict like {"mp4": "file_id", "mp4_720p": "file_id", "cdg": "file_id"}
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
delete_results = gdrive.delete_files(file_ids)
all_success = all(delete_results.values())
results["gdrive"] = {
"status": "success" if all_success else "partial",
"files": delete_results
}
file_ids: list = []
gdrive_method = None # track how files were located for response
if gdrive_files and isinstance(gdrive_files, dict):
# Fast path: delete using tracked file IDs from state_data
file_ids = [v for v in gdrive_files.values() if v]
logger.info(
f"GDrive cleanup for job {job_id}: "
f"using {len(file_ids)} tracked file IDs"
)
if not file_ids and gdrive_folder_id and brand_code:
# Fallback: search by brand code prefix in CDG/, MP4/, MP4-720p/ subfolders.
# Handles jobs where gdrive_files was not tracked (old jobs, or jobs where
# GDrive upload succeeded but file IDs were lost).
logger.info(
f"GDrive cleanup for job {job_id}: "
f"no tracked file IDs, searching by brand_code '{brand_code}'"
)
file_ids = gdrive.find_files_by_brand_code(gdrive_folder_id, brand_code)
gdrive_method = "brand_code_search"
if file_ids:
delete_results = gdrive.delete_files(file_ids)
all_success = all(delete_results.values())
gdrive_cleaned = all_success
results["gdrive"] = {
"status": "success" if all_success else "partial",
"files": delete_results,
}
if gdrive_method:
results["gdrive"]["method"] = gdrive_method
else:
gdrive_cleaned = True # Nothing to delete
results["gdrive"] = {
"status": "skipped",
"reason": "no files found to delete",
}
else:
results["gdrive"] = {"status": "failed", "reason": "Google Drive credentials not configured"}
results["gdrive"] = {
"status": "failed",
"reason": "Google Drive credentials not configured",
}
except Exception as e:
logger.error(f"Error cleaning up Google Drive for job {job_id}: {e}", exc_info=True)
logger.error(
f"Error cleaning up Google Drive for job {job_id}: {e}", exc_info=True
)
results["gdrive"] = {"status": "error", "error": str(e)}
else:
if not gdrive_folder_id:
results["gdrive"]["reason"] = "no gdrive_folder_id on job and no tracked file IDs"
# Recycle the brand code so it can be reused — but only after GDrive is confirmed clean.
# If we recycle before GDrive cleanup, a new job could claim the same brand code and
# collide with leftover files on GDrive (duplicate brand code in public share).
if dropbox_cleaned and brand_code and gdrive_cleaned:
try:
from backend.services.brand_code_service import (
BrandCodeService, get_brand_code_service
)
prefix, number = BrandCodeService.parse_brand_code(brand_code)
get_brand_code_service().recycle_brand_code(prefix, number)
results["dropbox"]["recycled_brand_code"] = True
logger.info(f"Recycled brand code {brand_code} after full distribution cleanup")
except (ValueError, Exception) as e:
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
results["dropbox"]["recycled_brand_code"] = False
elif dropbox_cleaned and brand_code:
logger.warning(
f"Brand code {brand_code} NOT recycled: GDrive cleanup did not confirm success "
f"(gdrive_cleaned={gdrive_cleaned}). Brand code will remain reserved to prevent "
f"collisions with leftover GDrive files."
)
# Delete the job if requested
if delete_job:
+43 -12
View File
@@ -732,17 +732,41 @@ async def get_preview_video(
@router.post("/{job_id}/v1/annotations")
async def submit_annotation(
job_id: str,
annotation: Dict[str, Any],
payload: Dict[str, Any],
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""
Submit a correction annotation for ML training data.
For now, just log and acknowledge - full annotation support
would require a database.
Submit correction annotations for ML training data.
Accepts either a single annotation dict or {"annotations": [...]} batch.
Stores to GCS at jobs/{job_id}/lyrics/annotations.json.
"""
logger.info(f"Job {job_id}: Annotation submitted (logged but not stored)")
return {"status": "success", "annotation_id": "stub"}
annotations = payload.get("annotations", [payload]) if isinstance(payload, dict) else [payload]
try:
storage = StorageService()
gcs_path = f"jobs/{job_id}/lyrics/annotations.json"
# Merge with any existing annotations
existing: list = []
try:
existing_data = storage.download_json(gcs_path)
if isinstance(existing_data, list):
existing = existing_data
elif isinstance(existing_data, dict) and "annotations" in existing_data:
existing = existing_data["annotations"]
except Exception:
pass # No existing file, start fresh
merged = existing + annotations
storage.upload_json(gcs_path, {"annotations": merged})
logger.info(f"Job {job_id}: {len(annotations)} annotation(s) saved ({len(merged)} total)")
return {"status": "success", "saved_count": len(annotations), "total_count": len(merged)}
except Exception as e:
logger.error(f"Job {job_id}: Error saving annotations: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
@router.get("/{job_id}/v1/annotations/stats")
@@ -751,11 +775,18 @@ async def get_annotation_stats(
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""Get annotation statistics."""
return {
"total_annotations": 0,
"by_type": {},
"message": "Annotation stats not yet implemented"
}
try:
storage = StorageService()
gcs_path = f"jobs/{job_id}/lyrics/annotations.json"
data = storage.download_json(gcs_path)
annotations = data.get("annotations", []) if isinstance(data, dict) else data
by_type: Dict[str, int] = {}
for a in annotations:
atype = a.get("annotation_type", "unknown")
by_type[atype] = by_type.get(atype, 0) + 1
return {"total_annotations": len(annotations), "by_type": by_type}
except Exception:
return {"total_annotations": 0, "by_type": {}}
@router.get("/{job_id}/instrumental-analysis")
+186
View File
@@ -48,6 +48,10 @@ from backend.models.user import (
BetaFeedbackRequest,
BetaFeedbackResponse,
BetaTesterFeedback,
UserFeedback,
UserFeedbackRequest,
UserFeedbackResponse,
FeedbackEligibilityResponse,
)
from backend.services.user_service import get_user_service, UserService, USERS_COLLECTION
from backend.services.email_service import get_email_service, EmailService
@@ -321,6 +325,10 @@ async def get_current_user(
if auth_result.is_valid and auth_result.user_email:
# Get or create user record for the authenticated email
user = user_service.get_or_create_user(auth_result.user_email)
feedback_eligible = (
user.total_jobs_completed >= 2
and not user.has_submitted_feedback
)
user_public = UserPublic(
email=user.email,
role=user.role if not auth_result.is_admin else UserRole.ADMIN,
@@ -328,6 +336,7 @@ async def get_current_user(
display_name=user.display_name,
total_jobs_created=user.total_jobs_created,
total_jobs_completed=user.total_jobs_completed,
feedback_eligible=feedback_eligible,
)
return UserProfileResponse(user=user_public, has_session=True)
@@ -337,6 +346,10 @@ async def get_current_user(
if not valid or not user:
raise HTTPException(status_code=401, detail=message)
feedback_eligible = (
user.total_jobs_completed >= 2
and not user.has_submitted_feedback
)
user_public = UserPublic(
email=user.email,
role=user.role,
@@ -344,6 +357,7 @@ async def get_current_user(
display_name=user.display_name,
total_jobs_created=user.total_jobs_created,
total_jobs_completed=user.total_jobs_completed,
feedback_eligible=feedback_eligible,
)
return UserProfileResponse(user=user_public, has_session=True)
@@ -1130,6 +1144,153 @@ async def get_feedback_form_data(
}
# =============================================================================
# User Feedback-for-Credits Endpoints
# =============================================================================
@router.get("/feedback/eligibility", response_model=FeedbackEligibilityResponse)
async def check_feedback_eligibility(
authorization: Optional[str] = Header(None),
user_service: UserService = Depends(get_user_service),
):
"""
Check if the current user is eligible to submit feedback for credits.
Eligible if: total_jobs_completed >= 2 AND has not already submitted feedback.
"""
if not authorization:
raise HTTPException(status_code=401, detail="Authentication required")
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
# Try auth service first (admin tokens, auth_tokens)
from backend.services.auth_service import get_auth_service
auth_service = get_auth_service()
auth_result = auth_service.validate_token_full(token)
user = None
if auth_result.is_valid and auth_result.user_email:
user = user_service.get_or_create_user(auth_result.user_email)
else:
valid, user, message = user_service.validate_session(token)
if not valid or not user:
raise HTTPException(status_code=401, detail=message)
eligible = user.total_jobs_completed >= 2 and not user.has_submitted_feedback
return FeedbackEligibilityResponse(
eligible=eligible,
has_submitted=user.has_submitted_feedback,
jobs_completed=user.total_jobs_completed,
credits_reward=2,
)
@router.post("/feedback", response_model=UserFeedbackResponse)
async def submit_user_feedback(
request: UserFeedbackRequest,
authorization: Optional[str] = Header(None),
user_service: UserService = Depends(get_user_service),
):
"""
Submit product feedback to earn 2 free credits.
Requires authentication. Users must have completed 2+ jobs and
not have already submitted feedback. At least one text field
must have >50 characters.
"""
if not authorization:
raise HTTPException(status_code=401, detail="Authentication required")
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
# Try auth service first (admin tokens, auth_tokens)
from backend.services.auth_service import get_auth_service
auth_service = get_auth_service()
auth_result = auth_service.validate_token_full(token)
user = None
if auth_result.is_valid and auth_result.user_email:
user = user_service.get_or_create_user(auth_result.user_email)
else:
valid, user, message = user_service.validate_session(token)
if not valid or not user:
raise HTTPException(status_code=401, detail=message)
# Check eligibility: must have completed 2+ jobs
if user.total_jobs_completed < 2:
raise HTTPException(
status_code=400,
detail="You need to complete at least 2 karaoke videos before submitting feedback."
)
# Check if already submitted
if user.has_submitted_feedback:
raise HTTPException(
status_code=400,
detail="You have already submitted feedback. Thank you!"
)
# Validate: at least one text field has >50 characters
has_detailed_feedback = (
(request.what_went_well and len(request.what_went_well) > 50) or
(request.what_could_improve and len(request.what_could_improve) > 50) or
(request.additional_comments and len(request.additional_comments) > 50)
)
if not has_detailed_feedback:
raise HTTPException(
status_code=400,
detail="Please provide detailed feedback in at least one text field (more than 50 characters)."
)
# Save feedback to Firestore
import uuid
feedback = UserFeedback(
id=str(uuid.uuid4()),
user_email=user.email,
overall_rating=request.overall_rating,
ease_of_use_rating=request.ease_of_use_rating,
lyrics_accuracy_rating=request.lyrics_accuracy_rating,
correction_experience_rating=request.correction_experience_rating,
what_went_well=request.what_went_well,
what_could_improve=request.what_could_improve,
additional_comments=request.additional_comments,
would_recommend=request.would_recommend,
would_use_again=request.would_use_again,
submitted_via="web",
)
user_service.db.collection("user_feedback").document(feedback.id).set(
feedback.model_dump(mode='json')
)
# Mark user as having submitted feedback
user_service.update_user(
user.email,
has_submitted_feedback=True,
)
# Grant 2 credits
credits_granted = 2
user_service.add_credits(
email=user.email,
amount=credits_granted,
reason="feedback_bonus",
)
logger.info(
f"User feedback received from {_mask_email(user.email)}, "
f"credits granted: {credits_granted}"
)
return UserFeedbackResponse(
status="success",
message=f"Thank you for your feedback! You earned {credits_granted} free credits.",
credits_granted=credits_granted,
)
# =============================================================================
# Admin Endpoints
# =============================================================================
@@ -1410,6 +1571,31 @@ async def enable_user(
return {"status": "success", "message": f"User {email} has been enabled"}
@router.delete("/admin/users/{email}")
async def delete_user(
email: str,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""
Permanently delete a user and all associated data (admin only).
Jobs are NOT deleted - they remain as historical records.
"""
admin_token, _, _ = auth_data
admin_id = f"admin:{admin_token[:8]}..." if admin_token else "admin:unknown"
try:
success = user_service.delete_user(email, admin_email=admin_id)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
if not success:
raise HTTPException(status_code=404, detail="User not found")
return {"status": "success", "message": f"User {email} has been deleted"}
@router.post("/admin/users/{email}/role")
async def set_user_role(
email: str,
+71
View File
@@ -104,6 +104,9 @@ class User(BaseModel):
# Users can subscribe from multiple devices/browsers
push_subscriptions: List[PushSubscription] = Field(default_factory=list)
# Feedback-for-credits program
has_submitted_feedback: bool = False
class MagicLinkToken(BaseModel):
"""
@@ -185,6 +188,7 @@ class UserPublic(BaseModel):
total_jobs_created: int = 0
total_jobs_completed: int = 0
tenant_id: Optional[str] = None
feedback_eligible: bool = False
class AddCreditsRequest(BaseModel):
@@ -288,3 +292,70 @@ class BetaFeedbackResponse(BaseModel):
status: str
message: str
bonus_credits: int = 0 # Bonus credits for great feedback
# ============================================================================
# User Feedback-for-Credits Models
# ============================================================================
class UserFeedback(BaseModel):
"""
Feedback from any user (not just beta testers).
Stored in Firestore 'user_feedback' collection.
Users earn 2 free credits for submitting detailed feedback.
"""
id: str
user_email: str
# Ratings (1-5 scale)
overall_rating: int = Field(ge=1, le=5)
ease_of_use_rating: int = Field(ge=1, le=5)
lyrics_accuracy_rating: int = Field(ge=1, le=5)
correction_experience_rating: int = Field(ge=1, le=5)
# Open-ended feedback
what_went_well: Optional[str] = None
what_could_improve: Optional[str] = None
additional_comments: Optional[str] = None
# Would they recommend / use again?
would_recommend: bool = True
would_use_again: bool = True
# Metadata
created_at: datetime = Field(default_factory=datetime.utcnow)
submitted_via: str = "web"
class UserFeedbackRequest(BaseModel):
"""Request to submit user feedback for credits."""
# Ratings (1-5 scale)
overall_rating: int = Field(ge=1, le=5)
ease_of_use_rating: int = Field(ge=1, le=5)
lyrics_accuracy_rating: int = Field(ge=1, le=5)
correction_experience_rating: int = Field(ge=1, le=5)
# Open-ended feedback
what_went_well: Optional[str] = None
what_could_improve: Optional[str] = None
additional_comments: Optional[str] = None
# Would they recommend / use again?
would_recommend: bool = True
would_use_again: bool = True
class UserFeedbackResponse(BaseModel):
"""Response after submitting user feedback."""
status: str
message: str
credits_granted: int = 0
class FeedbackEligibilityResponse(BaseModel):
"""Response for feedback eligibility check."""
eligible: bool
has_submitted: bool
jobs_completed: int
credits_reward: int = 2
+12 -9
View File
@@ -612,13 +612,13 @@ class AudioSearchService:
async def search_async(self, artist: str, title: str) -> List[AudioSearchResult]:
"""
Async version of search for use in async routes.
Note: Currently wraps sync search in executor. Future optimization
could make this fully async.
Runs the sync search in a thread executor to avoid blocking
the event loop.
"""
loop = asyncio.get_event_loop()
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, self.search, artist, title)
async def download_async(
self,
result_index: int,
@@ -630,10 +630,10 @@ class AudioSearchService:
"""
Async version of download for use in async routes.
Note: Currently wraps sync download in executor. Future optimization
could make this fully async.
Runs the sync download in a thread executor to avoid blocking
the event loop.
"""
loop = asyncio.get_event_loop()
loop = asyncio.get_running_loop()
return await loop.run_in_executor(
None,
lambda: self.download(result_index, output_dir, output_filename, gcs_path, remote_search_id)
@@ -651,8 +651,11 @@ class AudioSearchService:
) -> AudioDownloadResult:
"""
Async version of download_by_id for use in async routes.
Runs the sync download_by_id in a thread executor to avoid blocking
the event loop.
"""
loop = asyncio.get_event_loop()
loop = asyncio.get_running_loop()
return await loop.run_in_executor(
None,
lambda: self.download_by_id(
+46 -4
View File
@@ -400,9 +400,31 @@ Start creating: {self.frontend_url}
"""
subject = "Welcome to Nomad Karaoke! 🎤"
credits_text = f"You have <strong>{credits} credits</strong> to get started!" if credits > 0 else ""
extra_styles = """
.credits-box {
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
border: 2px solid #e2b714;
border-radius: 12px;
padding: 24px;
text-align: center;
margin: 24px 0;
}
.credits-box .credits-number {
font-size: 48px;
font-weight: bold;
color: #e2b714;
line-height: 1;
}
.credits-box .credits-label {
font-size: 16px;
color: #ccc;
margin-top: 4px;
}
.credits-box .credits-note {
font-size: 13px;
color: #999;
margin-top: 12px;
}
.feature {
display: flex;
align-items: flex-start;
@@ -414,10 +436,22 @@ Start creating: {self.frontend_url}
}
"""
credits_box = ""
if credits > 0:
credits_box = f"""
<div class="credits-box">
<div class="credits-number">{credits}</div>
<div class="credits-label">Free Credits</div>
<div class="credits-note">Each credit creates one professional karaoke video</div>
</div>
"""
content = f"""
<p>Welcome to Nomad Karaoke!</p>
<p>Turn any song into a professional karaoke video in minutes. {credits_text}</p>
<p>Turn any song into a professional karaoke video in minutes.</p>
{credits_box}
<p><strong>Here's how it works:</strong></p>
@@ -453,6 +487,10 @@ Start creating: {self.frontend_url}
</div>
</div>
<p style="text-align: center; font-size: 14px; color: #999; margin-top: 20px;">
Complete 2 videos and earn 2 more free credits by sharing your feedback!
</p>
<p style="text-align: center;">
<a href="{self.frontend_url}" class="button">Get Started</a>
</p>
@@ -460,11 +498,13 @@ Start creating: {self.frontend_url}
html_content = self._build_email_html(content, extra_styles)
credits_text = f"\nYou have {credits} free credits to get started!\nEach credit creates one professional karaoke video.\n" if credits > 0 else ""
text_content = f"""
Welcome to Nomad Karaoke!
Turn any song into a professional karaoke video in minutes.
{credits_text}
Here's how it works:
1. Search for a song
@@ -479,6 +519,8 @@ Here's how it works:
4. Get your video
Download your 4K karaoke video or upload directly to YouTube.
Complete 2 videos and earn 2 more free credits by sharing your feedback!
Get started: {self.frontend_url}
---
+189 -66
View File
@@ -12,13 +12,19 @@ shared with YouTube credentials if scopes include drive.file.
import json
import logging
import os
import ssl
from typing import Any, Dict, Optional
from tenacity import Retrying, stop_after_attempt, wait_exponential, retry_if_exception_type
from backend.config import get_settings
from karaoke_gen.utils import sanitize_filename
logger = logging.getLogger(__name__)
# Transient errors that indicate a stale HTTP connection (Cloud Run idle containers)
TRANSIENT_ERRORS = (BrokenPipeError, ConnectionResetError, ConnectionError, ssl.SSLError)
class GoogleDriveService:
"""Google Drive operations using native API."""
@@ -33,6 +39,11 @@ class GoogleDriveService:
self._credentials_data: Optional[Dict[str, Any]] = None
self._loaded = False
def _reset_service(self):
"""Reset the cached Drive service to force a fresh connection on next use."""
logger.info("Resetting Google Drive service connection")
self._service = None
def _load_credentials(self) -> Optional[Dict[str, Any]]:
"""Load OAuth credentials from Secret Manager."""
if self._loaded:
@@ -127,6 +138,9 @@ class GoogleDriveService:
"""
Get existing folder or create new one, return folder ID.
Retries on transient connection errors (BrokenPipeError, SSLError)
that occur when Cloud Run containers sit idle between jobs.
Args:
parent_id: Parent folder ID
folder_name: Name of folder to find or create
@@ -134,33 +148,41 @@ class GoogleDriveService:
Returns:
Folder ID
"""
logger.info(f"Looking for folder '{folder_name}' in parent {parent_id}")
for attempt in Retrying(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=8),
retry=retry_if_exception_type(TRANSIENT_ERRORS),
before_sleep=lambda retry_state: self._reset_service(),
reraise=True,
):
with attempt:
logger.info(f"Looking for folder '{folder_name}' in parent {parent_id}")
# Search for existing folder
# Escape single quotes in folder name for Google Drive API query syntax
escaped_folder_name = folder_name.replace("'", "\\'")
query = (
f"name='{escaped_folder_name}' and '{parent_id}' in parents "
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
)
results = self.service.files().list(q=query, fields="files(id, name)").execute()
# Search for existing folder
# Escape single quotes in folder name for Google Drive API query syntax
escaped_folder_name = folder_name.replace("'", "\\'")
query = (
f"name='{escaped_folder_name}' and '{parent_id}' in parents "
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
)
results = self.service.files().list(q=query, fields="files(id, name)").execute()
if results.get("files"):
folder_id = results["files"][0]["id"]
logger.info(f"Found existing folder '{folder_name}': {folder_id}")
return folder_id
if results.get("files"):
folder_id = results["files"][0]["id"]
logger.info(f"Found existing folder '{folder_name}': {folder_id}")
return folder_id
# Create folder
logger.info(f"Creating new folder '{folder_name}'")
metadata = {
"name": folder_name,
"mimeType": "application/vnd.google-apps.folder",
"parents": [parent_id],
}
folder = self.service.files().create(body=metadata, fields="id").execute()
folder_id = folder["id"]
logger.info(f"Created folder '{folder_name}': {folder_id}")
return folder_id
# Create folder
logger.info(f"Creating new folder '{folder_name}'")
metadata = {
"name": folder_name,
"mimeType": "application/vnd.google-apps.folder",
"parents": [parent_id],
}
folder = self.service.files().create(body=metadata, fields="id").execute()
folder_id = folder["id"]
logger.info(f"Created folder '{folder_name}': {folder_id}")
return folder_id
def upload_file(
self,
@@ -172,6 +194,9 @@ class GoogleDriveService:
"""
Upload a file to a specific Drive folder.
Retries on transient connection errors (BrokenPipeError, SSLError)
that occur when Cloud Run containers sit idle between jobs.
Args:
local_path: Local file path
parent_id: Parent folder ID in Google Drive
@@ -183,49 +208,57 @@ class GoogleDriveService:
"""
from googleapiclient.http import MediaFileUpload
file_size = os.path.getsize(local_path)
logger.info(
f"Uploading {local_path} ({file_size / 1024 / 1024:.1f} MB) "
f"as '{filename}' to folder {parent_id}"
)
for attempt in Retrying(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=8),
retry=retry_if_exception_type(TRANSIENT_ERRORS),
before_sleep=lambda retry_state: self._reset_service(),
reraise=True,
):
with attempt:
file_size = os.path.getsize(local_path)
logger.info(
f"Uploading {local_path} ({file_size / 1024 / 1024:.1f} MB) "
f"as '{filename}' to folder {parent_id}"
)
# Determine MIME type
ext = os.path.splitext(local_path)[1].lower()
mime_types = {
".mp4": "video/mp4",
".mkv": "video/x-matroska",
".zip": "application/zip",
".flac": "audio/flac",
".mp3": "audio/mpeg",
".wav": "audio/wav",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
}
mime_type = mime_types.get(ext, "application/octet-stream")
# Determine MIME type
ext = os.path.splitext(local_path)[1].lower()
mime_types = {
".mp4": "video/mp4",
".mkv": "video/x-matroska",
".zip": "application/zip",
".flac": "audio/flac",
".mp3": "audio/mpeg",
".wav": "audio/wav",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
}
mime_type = mime_types.get(ext, "application/octet-stream")
# Check for existing file with same name
if replace_existing:
# Escape single quotes in filename for Google Drive API query syntax
escaped_filename = filename.replace("'", "\\'")
query = (
f"name='{escaped_filename}' and '{parent_id}' in parents and trashed=false"
)
results = self.service.files().list(q=query, fields="files(id)").execute()
for existing_file in results.get("files", []):
logger.info(f"Deleting existing file: {existing_file['id']}")
self.service.files().delete(fileId=existing_file["id"]).execute()
# Check for existing file with same name
if replace_existing:
# Escape single quotes in filename for Google Drive API query syntax
escaped_filename = filename.replace("'", "\\'")
query = (
f"name='{escaped_filename}' and '{parent_id}' in parents and trashed=false"
)
results = self.service.files().list(q=query, fields="files(id)").execute()
for existing_file in results.get("files", []):
logger.info(f"Deleting existing file: {existing_file['id']}")
self.service.files().delete(fileId=existing_file["id"]).execute()
# Upload file
metadata = {"name": filename, "parents": [parent_id]}
media = MediaFileUpload(local_path, mimetype=mime_type, resumable=True)
# Upload file
metadata = {"name": filename, "parents": [parent_id]}
media = MediaFileUpload(local_path, mimetype=mime_type, resumable=True)
file_result = (
self.service.files().create(body=metadata, media_body=media, fields="id").execute()
)
file_id = file_result["id"]
logger.info(f"Successfully uploaded '{filename}': {file_id}")
return file_id
file_result = (
self.service.files().create(body=metadata, media_body=media, fields="id").execute()
)
file_id = file_result["id"]
logger.info(f"Successfully uploaded '{filename}': {file_id}")
return file_id
def upload_to_public_share(
self,
@@ -308,6 +341,9 @@ class GoogleDriveService:
"""
Delete a file from Google Drive.
Retries on transient connection errors (BrokenPipeError, SSLError)
that occur when Cloud Run containers sit idle between jobs.
Args:
file_id: Google Drive file ID to delete
@@ -317,9 +353,17 @@ class GoogleDriveService:
logger.info(f"Deleting Google Drive file: {file_id}")
try:
self.service.files().delete(fileId=file_id).execute()
logger.info(f"Successfully deleted file: {file_id}")
return True
for attempt in Retrying(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=8),
retry=retry_if_exception_type(TRANSIENT_ERRORS),
before_sleep=lambda retry_state: self._reset_service(),
reraise=True,
):
with attempt:
self.service.files().delete(fileId=file_id).execute()
logger.info(f"Successfully deleted file: {file_id}")
return True
except Exception as e:
# Check if it's a 404 (already deleted)
if hasattr(e, 'resp') and e.resp.status == 404:
@@ -343,6 +387,85 @@ class GoogleDriveService:
results[file_id] = self.delete_file(file_id)
return results
def find_files_by_brand_code(self, root_folder_id: str, brand_code: str) -> list[str]:
"""
Search for files in public share subfolders matching a brand code prefix.
Used as a fallback when gdrive_files is not tracked in state_data (e.g., old
jobs uploaded before file ID tracking was implemented, or jobs where GDrive
upload succeeded but file IDs were not saved due to a bug).
Searches CDG/, MP4/, MP4-720p/ subfolders for files whose name starts with
'{brand_code} - '.
Args:
root_folder_id: Root Google Drive folder ID for the public share
brand_code: Brand code prefix to search for (e.g., "NOMAD-1271")
Returns:
List of file IDs found matching the brand code
"""
found_ids = []
subfolders = ["CDG", "MP4", "MP4-720p"]
search_errors: list[Exception] = []
for subfolder in subfolders:
try:
# Find the subfolder
escaped_subfolder = subfolder.replace("'", "\\'")
query = (
f"name='{escaped_subfolder}' and '{root_folder_id}' in parents "
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
)
results = self.service.files().list(
q=query, fields="files(id, name)", supportsAllDrives=True,
includeItemsFromAllDrives=True
).execute()
if not results.get("files"):
logger.debug(f"Subfolder '{subfolder}' not found in {root_folder_id}")
continue
subfolder_id = results["files"][0]["id"]
# Search for files whose name starts with the brand code
# Use contains for efficiency, then filter by exact prefix
escaped_brand = brand_code.replace("'", "\\'")
file_query = (
f"name contains '{escaped_brand}' and '{subfolder_id}' in parents "
f"and trashed=false"
)
file_results = self.service.files().list(
q=file_query, fields="files(id, name)", supportsAllDrives=True,
includeItemsFromAllDrives=True
).execute()
for f in file_results.get("files", []):
if f["name"].startswith(f"{brand_code} - "):
found_ids.append(f["id"])
logger.info(
f"Found GDrive file to clean up in {subfolder}/: "
f"{f['name']} ({f['id']})"
)
except Exception as e:
logger.error(
f"Error searching for brand_code '{brand_code}' in '{subfolder}': {e}",
exc_info=True,
)
search_errors.append(e)
if search_errors:
# Raise so the caller knows the search was incomplete.
# This prevents the cleanup endpoint from treating an uncertain result
# as "GDrive is clean" and incorrectly recycling the brand code.
raise RuntimeError(
f"GDrive brand_code search incomplete: "
f"{len(search_errors)}/{len(subfolders)} subfolder(s) failed"
)
return found_ids
# Singleton instance
_gdrive_service: Optional[GoogleDriveService] = None
@@ -0,0 +1,62 @@
"""
GDrive Validator Cloud Function client.
Lightweight HTTP client for invoking the gdrive-validator Cloud Function
from the backend (e.g., after job completion). Uses OIDC authentication
via the backend's service account.
Fire-and-forget pattern: never blocks or fails the caller.
"""
import logging
import os
import requests
import google.auth.transport.requests
import google.oauth2.id_token
logger = logging.getLogger(__name__)
# Cloud Function URL - set via environment variable
GDRIVE_VALIDATOR_URL = os.environ.get("GDRIVE_VALIDATOR_URL", "")
def trigger_gdrive_validation() -> dict | None:
"""
Invoke the GDrive validator Cloud Function.
Uses the backend service account's OIDC token for authentication.
Returns:
Parsed JSON response from the function, or None on error.
"""
if not GDRIVE_VALIDATOR_URL:
logger.debug("GDRIVE_VALIDATOR_URL not set, skipping GDrive validation trigger")
return None
try:
# Get OIDC token for the Cloud Function URL
auth_request = google.auth.transport.requests.Request()
token = google.oauth2.id_token.fetch_id_token(auth_request, GDRIVE_VALIDATOR_URL)
response = requests.post(
GDRIVE_VALIDATOR_URL,
headers={"Authorization": f"Bearer {token}"},
timeout=60,
)
response.raise_for_status()
result = response.json()
status = result.get("status", "unknown")
if status == "issues_found":
logger.warning("GDrive validation found issues (notification sent)")
elif status == "ok":
logger.info("GDrive validation: all clear")
else:
logger.info(f"GDrive validation returned status: {status}")
return result
except Exception:
logger.exception("Failed to trigger GDrive validation (non-fatal)")
return None
+1 -1
View File
@@ -48,7 +48,7 @@ CREDIT_PACKAGES = {
# Made-for-you service package (not a credit package - creates a job directly)
MADE_FOR_YOU_PACKAGE = {
"price_cents": 1500, # $15.00
"price_cents": 5000, # $50.00
"name": "Made For You Karaoke Video",
"description": "Professional 4K karaoke video with perfectly synced lyrics, delivered to your email within 24 hours",
"images": ["https://gen.nomadkaraoke.com/nomad-logo.png"],
+49
View File
@@ -768,6 +768,55 @@ class UserService:
logger.exception("Error enabling user")
return False
def delete_user(self, email: str, admin_email: str) -> bool:
"""
Permanently delete a user and all their associated data.
Deletes: user document, sessions, magic links.
Does NOT delete jobs (they remain as historical records).
Args:
email: Email of the user to delete
admin_email: Email/ID of the admin performing the action
Returns:
True if user was deleted, False if user not found
Raises:
ValueError: If trying to delete an admin user
"""
try:
email = email.lower()
user = self.get_user(email)
if not user:
return False
if user.role == UserRole.ADMIN:
raise ValueError("Cannot delete admin users")
# Revoke all active sessions
self.revoke_all_sessions(email)
# Delete magic links for the user
magic_links = self.db.collection(MAGIC_LINKS_COLLECTION).where(
filter=FieldFilter('email', '==', email)
).stream()
for doc in magic_links:
doc.reference.delete()
# Delete the user document
self.db.collection(USERS_COLLECTION).document(email).delete()
logger.info(f"Admin {admin_email} permanently deleted user {email}")
return True
except ValueError:
raise
except Exception:
logger.exception(f"Error deleting user {email}")
return False
def increment_jobs_completed(self, email: str) -> bool:
"""Increment the completed jobs counter for a user using atomic increment."""
try:
+1 -1
View File
@@ -54,7 +54,7 @@ WORKER_DISPATCH_DEADLINES = {
}
# Default delay for idle reminders (seconds)
IDLE_REMINDER_DELAY_SECONDS = 5 * 60 # 5 minutes
IDLE_REMINDER_DELAY_SECONDS = 2 * 60 # 2 minutes
class WorkerService:
+14 -8
View File
@@ -115,6 +115,7 @@ class TestAudioSearchYouTubeFlow:
async def test_torrent_download_does_not_use_youtube_service(self, mock_youtube_service, mock_services):
"""
When selecting a torrent result (RED/OPS), should NOT use YouTubeDownloadService.
Should use FlacfetchClient directly instead.
"""
mock_job = mock_services['job_manager'].get_job.return_value
mock_job.status = "awaiting_audio_selection"
@@ -132,16 +133,22 @@ class TestAudioSearchYouTubeFlow:
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
# Mock audio_search_service for torrent download
mock_audio_search_service = MagicMock()
mock_audio_search_service.is_remote_enabled = MagicMock(return_value=True)
mock_result = MagicMock()
mock_result.filepath = "gs://bucket/uploads/test/audio/test.flac"
mock_audio_search_service.download_by_id = MagicMock(return_value=mock_result)
# Mock FlacfetchClient for direct async download
mock_flacfetch = MagicMock()
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-test-123")
mock_flacfetch.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://bucket/uploads/test/audio/test.flac",
})
with patch(
'backend.api.routes.audio_search.get_youtube_download_service',
return_value=mock_youtube_service
), patch(
'backend.api.routes.audio_search.get_flacfetch_client',
return_value=mock_flacfetch
), patch(
'backend.api.routes.audio_search.job_manager',
mock_services['job_manager']
@@ -152,7 +159,6 @@ class TestAudioSearchYouTubeFlow:
'backend.api.routes.audio_search.worker_service',
mock_services['worker_service']
):
# Call the download function (now runs as background task, returns None)
await _download_audio_and_trigger_workers(
job_id="test_job_123",
selection_index=0,
@@ -162,8 +168,8 @@ class TestAudioSearchYouTubeFlow:
# YouTubeDownloadService should NOT be called for torrent
mock_youtube_service.download_by_id.assert_not_called()
# audio_search_service.download_by_id should be called instead
mock_audio_search_service.download_by_id.assert_called_once()
# FlacfetchClient.download_by_id should be called directly
mock_flacfetch.download_by_id.assert_called_once()
class TestDirectUrlSubmissionFlow:
+104
View File
@@ -470,3 +470,107 @@ class TestDeleteOutputsGCSFinals:
assert response.status_code == 200
# Verify path format is jobs/{job_id}/finals/
mock_storage.delete_folder.assert_called_once_with("jobs/abc-123-xyz/finals/")
class TestDeleteOutputsBrandCodeRecycling:
"""Tests for brand code recycling during output deletion."""
def test_brand_code_recycled_on_success(self, client, mock_complete_job):
"""Test that brand code is recycled when Dropbox and GDrive cleanup succeed."""
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code') as mock_parse, \
patch('backend.services.brand_code_service.get_brand_code_service') as mock_get_svc:
mock_jm = Mock()
mock_jm.get_job.return_value = mock_complete_job
mock_jm_class.return_value = mock_jm
mock_db = Mock()
mock_job_ref = Mock()
mock_db.collection.return_value.document.return_value = mock_job_ref
mock_user_service.return_value.db = mock_db
mock_parse.return_value = ("NOMAD", 1234)
mock_svc = Mock()
mock_get_svc.return_value = mock_svc
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
assert response.status_code == 200
data = response.json()
# Brand code should be recycled (all services skip = success condition)
assert "brand_code" in data["deleted_services"]
assert data["deleted_services"]["brand_code"]["status"] == "recycled"
assert data["deleted_services"]["brand_code"]["code"] == "NOMAD-1234"
mock_svc.recycle_brand_code.assert_called_once_with("NOMAD", 1234)
def test_brand_code_not_recycled_without_brand_code(self, client, mock_job_no_outputs):
"""Test that no recycling happens when job has no brand code."""
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
patch('backend.api.routes.admin.get_user_service') as mock_user_service:
mock_jm = Mock()
mock_jm.get_job.return_value = mock_job_no_outputs
mock_jm_class.return_value = mock_jm
mock_db = Mock()
mock_job_ref = Mock()
mock_db.collection.return_value.document.return_value = mock_job_ref
mock_user_service.return_value.db = mock_db
response = client.post("/api/admin/jobs/test-job-456/delete-outputs")
assert response.status_code == 200
data = response.json()
# No brand_code key in response since there's nothing to recycle
assert "brand_code" not in data["deleted_services"]
def test_brand_code_skipped_when_dropbox_fails(self, client, mock_complete_job):
"""Test that brand code is NOT recycled when Dropbox cleanup fails."""
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
patch('backend.services.dropbox_service.get_dropbox_service') as mock_dropbox_svc:
mock_jm = Mock()
mock_jm.get_job.return_value = mock_complete_job
mock_jm_class.return_value = mock_jm
mock_db = Mock()
mock_job_ref = Mock()
mock_db.collection.return_value.document.return_value = mock_job_ref
mock_user_service.return_value.db = mock_db
# Make Dropbox fail
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.side_effect = Exception("Dropbox error")
mock_dropbox_svc.return_value = mock_dropbox
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
assert response.status_code == 200
data = response.json()
assert data["deleted_services"]["brand_code"]["status"] == "skipped"
assert "incomplete" in data["deleted_services"]["brand_code"]["reason"].lower()
def test_brand_code_recycle_error_handled_gracefully(self, client, mock_complete_job):
"""Test that brand code recycling errors don't crash the endpoint."""
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code') as mock_parse:
mock_jm = Mock()
mock_jm.get_job.return_value = mock_complete_job
mock_jm_class.return_value = mock_jm
mock_db = Mock()
mock_job_ref = Mock()
mock_db.collection.return_value.document.return_value = mock_job_ref
mock_user_service.return_value.db = mock_db
# Make parse_brand_code raise an error
mock_parse.side_effect = ValueError("Invalid brand code format")
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
assert response.status_code == 200
data = response.json()
assert data["deleted_services"]["brand_code"]["status"] == "failed"
assert "Invalid brand code format" in data["deleted_services"]["brand_code"]["error"]
+607 -89
View File
@@ -1173,58 +1173,60 @@ class TestAudioSearchApiRouteDownload:
def test_remote_download_passes_gcs_path(self, mock_job_manager, mock_storage_service, mock_worker_service):
"""
Test that remote torrent downloads include GCS path for direct upload.
Test that remote torrent downloads use FlacfetchClient directly with GCS path.
This was the bug: we were calling download() without gcs_path for
torrent sources, causing flacfetch VM to return a local path that
Cloud Run couldn't access.
The route bypasses audio_search_service and calls flacfetch_client.download_by_id()
directly to avoid event loop blocking.
"""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
# Setup mock job with RED search result
# Setup mock job with RED search result (includes source_id for download_by_id path)
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Unwanted',
'artist': 'Avril Lavigne',
'provider': 'RED', # Torrent source
'provider': 'RED',
'quality': 'FLAC 16bit CD',
'source_id': 'torrent123',
'target_file': 'Unwanted.flac',
'url': '',
}]
}
mock_job.audio_search_artist = 'Avril Lavigne'
mock_job.audio_search_title = 'Unwanted'
mock_job_manager.get_job.return_value = mock_job
# Create mock audio search service with remote client
mock_audio_service = Mock()
mock_audio_service.is_remote_enabled.return_value = True
# Mock download to return GCS path
mock_download_result = Mock()
mock_download_result.filepath = "gs://bucket/uploads/job123/audio/Avril Lavigne - Unwanted.flac"
mock_audio_service.download.return_value = mock_download_result
# Mock FlacfetchClient
mock_flacfetch = Mock()
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-123")
mock_flacfetch.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://bucket/uploads/job123/audio/Avril Lavigne - Unwanted.flac",
})
# Run the async function
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job123",
selection_index=0,
audio_search_service=mock_audio_service,
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job123",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
)
finally:
loop.close()
finally:
loop.close()
# CRITICAL: Verify download was called with gcs_path for remote torrent source
mock_audio_service.download.assert_called_once()
call_kwargs = mock_audio_service.download.call_args.kwargs
# The gcs_path should be set for remote torrent downloads
assert 'gcs_path' in call_kwargs
# CRITICAL: Verify FlacfetchClient.download_by_id was called with gcs_path
mock_flacfetch.download_by_id.assert_called_once()
call_kwargs = mock_flacfetch.download_by_id.call_args.kwargs
assert call_kwargs['gcs_path'] == "uploads/job123/audio/"
assert call_kwargs['source_name'] == 'RED'
assert call_kwargs['source_id'] == 'torrent123'
def test_youtube_remote_download_uses_youtube_service(self, mock_job_manager, mock_storage_service, mock_worker_service):
"""
@@ -1343,7 +1345,7 @@ class TestAudioSearchApiRouteDownload:
mock_youtube_service.download_by_id.assert_called_once()
def test_handles_gcs_path_response_correctly(self, mock_job_manager, mock_storage_service, mock_worker_service):
"""Test that GCS path responses are parsed correctly."""
"""Test that GCS path responses from FlacfetchClient are parsed correctly."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
@@ -1355,31 +1357,35 @@ class TestAudioSearchApiRouteDownload:
'artist': 'Test Artist',
'provider': 'RED',
'quality': 'FLAC',
'source_id': 'torrent789',
'target_file': 'test.flac',
'url': '',
}]
}
mock_job_manager.get_job.return_value = mock_job
# Create mock audio search service
mock_audio_service = Mock()
mock_audio_service.is_remote_enabled.return_value = True
# Mock download to return full GCS path
mock_download_result = Mock()
mock_download_result.filepath = "gs://karaoke-gen-bucket/uploads/job789/audio/test.flac"
mock_audio_service.download.return_value = mock_download_result
# Mock FlacfetchClient returning full GCS path
mock_flacfetch = Mock()
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-789")
mock_flacfetch.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://karaoke-gen-bucket/uploads/job789/audio/test.flac",
})
# Run the async function
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job789",
selection_index=0,
audio_search_service=mock_audio_service,
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job789",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
)
finally:
loop.close()
finally:
loop.close()
# Verify job was updated with correct GCS path (without gs://bucket/ prefix)
update_calls = mock_job_manager.update_job.call_args_list
@@ -1398,9 +1404,9 @@ class TestAudioSearchApiRouteDownload:
def test_torrent_download_requires_remote(self, mock_job_manager, mock_storage_service):
"""
Test that torrent sources (RED/OPS) require remote flacfetch.
Test that torrent sources (RED/OPS) require remote flacfetch client.
When running as a background task, the error is caught and the job is failed.
When get_flacfetch_client() returns None, the job should be failed.
"""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
@@ -1417,22 +1423,21 @@ class TestAudioSearchApiRouteDownload:
}
mock_job_manager.get_job.return_value = mock_job
# Create mock audio search service WITHOUT remote client
mock_audio_service = Mock()
mock_audio_service.is_remote_enabled.return_value = False
loop = asyncio.new_event_loop()
try:
# The background task catches exceptions and fails the job
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_no_remote",
selection_index=0,
audio_search_service=mock_audio_service,
# No flacfetch client configured
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=None):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_no_remote",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
)
finally:
loop.close()
finally:
loop.close()
# Verify the job was failed with an appropriate error message
mock_job_manager.fail_job.assert_called_once()
@@ -1564,27 +1569,35 @@ class TestAudioSearchApiRouteDownload:
'artist': 'Artist',
'provider': 'RED',
'quality': 'FLAC',
'source_id': 'torrent_w',
'target_file': 'test.flac',
'url': '',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
mock_audio_service.is_remote_enabled.return_value = True
mock_download_result = Mock()
mock_download_result.filepath = "gs://bucket/uploads/job_w/audio/test.flac"
mock_audio_service.download.return_value = mock_download_result
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_w",
selection_index=0,
audio_search_service=mock_audio_service,
# Mock FlacfetchClient
mock_flacfetch = Mock()
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-w")
mock_flacfetch.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://bucket/uploads/job_w/audio/test.flac",
})
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_w",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
)
finally:
loop.close()
finally:
loop.close()
# Both workers should be triggered
mock_worker_service.trigger_audio_worker.assert_called_once_with("job_w")
@@ -1609,26 +1622,32 @@ class TestAudioSearchApiRouteDownload:
'artist': 'Artist',
'provider': 'RED',
'quality': 'FLAC',
'source_id': 'torrent_err',
'target_file': 'test.flac',
'url': '',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
mock_audio_service.is_remote_enabled.return_value = True
mock_audio_service.download.side_effect = RuntimeError("Unexpected connection error")
loop = asyncio.new_event_loop()
try:
# Should not raise - background tasks catch all exceptions
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_err",
selection_index=0,
audio_search_service=mock_audio_service,
# Mock FlacfetchClient that raises an error
mock_flacfetch = Mock()
mock_flacfetch.download_by_id = AsyncMock(side_effect=RuntimeError("Unexpected connection error"))
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
# Should not raise - background tasks catch all exceptions
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_err",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
)
finally:
loop.close()
finally:
loop.close()
# Job should be failed with error message
mock_job_manager.fail_job.assert_called_once()
@@ -1636,3 +1655,502 @@ class TestAudioSearchApiRouteDownload:
assert fail_args.args[0] == "job_err"
assert "Unexpected connection error" in fail_args.args[1]
class TestAsyncEventLoopFixes:
"""
Tests for the async event loop blocking fixes.
Verifies that:
- Background tasks use FlacfetchClient async methods directly (RED/OPS/Spotify)
- Background tasks use asyncio.to_thread for generic downloads
- Search endpoint uses search_async instead of sync search
- InsufficientCreditsError propagates as 402, not 500
- FlacfetchServiceError is handled in background tasks
"""
@pytest.fixture
def mock_job_manager(self):
with patch('backend.api.routes.audio_search.job_manager') as mock:
yield mock
@pytest.fixture
def mock_storage_service(self):
with patch('backend.api.routes.audio_search.storage_service') as mock:
yield mock
@pytest.fixture
def mock_worker_service(self):
with patch('backend.api.routes.audio_search.get_worker_service') as mock:
worker = Mock()
worker.trigger_audio_worker = AsyncMock()
worker.trigger_lyrics_worker = AsyncMock()
mock.return_value = worker
yield worker
def test_spotify_download_uses_flacfetch_client_directly(
self, mock_job_manager, mock_storage_service, mock_worker_service
):
"""Spotify downloads should use FlacfetchClient.download_by_id() directly."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Blinding Lights',
'artist': 'The Weeknd',
'provider': 'Spotify',
'quality': 'OGG 320kbps',
'source_id': 'spotify:track:0VjIjW4GlUZAMYd2vXMi3b',
'url': 'https://open.spotify.com/track/0VjIjW4GlUZAMYd2vXMi3b',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
mock_flacfetch = Mock()
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-spotify-1")
mock_flacfetch.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://bucket/uploads/job_sp/audio/The Weeknd - Blinding Lights.ogg",
})
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_sp",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
# Verify FlacfetchClient was used directly (not audio_search_service)
mock_flacfetch.download_by_id.assert_called_once()
call_kwargs = mock_flacfetch.download_by_id.call_args.kwargs
assert call_kwargs['source_name'] == 'Spotify'
assert call_kwargs['source_id'] == 'spotify:track:0VjIjW4GlUZAMYd2vXMi3b'
assert call_kwargs['gcs_path'] == 'uploads/job_sp/audio/'
mock_flacfetch.wait_for_download.assert_called_once()
# audio_search_service.download_by_id should NOT be called
mock_audio_service.download_by_id.assert_not_called()
def test_spotify_download_requires_flacfetch_client(self, mock_job_manager, mock_storage_service):
"""Spotify download should fail job when FlacfetchClient is not configured."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Test',
'artist': 'Test',
'provider': 'Spotify',
'quality': 'OGG',
'source_id': 'spotify:track:abc',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=None):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_sp_err",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
mock_job_manager.fail_job.assert_called_once()
assert "flacfetch" in mock_job_manager.fail_job.call_args.args[1].lower()
def test_generic_download_uses_asyncio_to_thread(self, mock_job_manager, mock_storage_service, mock_worker_service):
"""Generic/unknown source downloads should use asyncio.to_thread to avoid blocking."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
import tempfile
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Test Song',
'artist': 'Unknown Artist',
'provider': 'SomeNewSource',
'quality': 'MP3',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
# Create a temporary file to simulate a downloaded file
tmp = tempfile.NamedTemporaryFile(suffix='.mp3', delete=False)
tmp.write(b'fake audio data')
tmp.close()
mock_download_result = Mock()
mock_download_result.filepath = tmp.name
mock_audio_service.download.return_value = mock_download_result
with patch('backend.api.routes.audio_search.asyncio') as mock_asyncio:
# Make to_thread return a coroutine that returns the mock result
mock_asyncio.to_thread = AsyncMock(return_value=mock_download_result)
mock_asyncio.gather = AsyncMock()
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_generic",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
# Verify asyncio.to_thread was called (not direct sync call)
mock_asyncio.to_thread.assert_called_once()
# Cleanup
import os
try:
os.unlink(tmp.name)
except OSError:
pass
def test_red_download_without_source_id_uses_search_download(
self, mock_job_manager, mock_storage_service, mock_worker_service
):
"""RED download without source_id should use flacfetch_client.download() with search_id."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Test',
'artist': 'Artist',
'provider': 'RED',
'quality': 'FLAC',
# No source_id — triggers the search-based download path
}],
'remote_search_id': 'search-abc-123',
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
mock_flacfetch = Mock()
mock_flacfetch.download = AsyncMock(return_value="dl-search-1")
mock_flacfetch.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://bucket/uploads/job_nosrc/audio/test.flac",
})
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_nosrc",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
# Should use flacfetch_client.download() (not download_by_id)
mock_flacfetch.download.assert_called_once()
call_kwargs = mock_flacfetch.download.call_args.kwargs
assert call_kwargs['search_id'] == 'search-abc-123'
assert call_kwargs['result_index'] == 0
assert call_kwargs['gcs_path'] == 'uploads/job_nosrc/audio/'
def test_flacfetch_service_error_handled_in_background_task(
self, mock_job_manager, mock_storage_service
):
"""FlacfetchServiceError should be caught and job should be failed."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
from backend.services.flacfetch_client import FlacfetchServiceError
import asyncio
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Test',
'artist': 'Artist',
'provider': 'OPS',
'quality': 'FLAC',
'source_id': 'ops123',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
mock_flacfetch = Mock()
mock_flacfetch.download_by_id = AsyncMock(
side_effect=FlacfetchServiceError("Connection refused")
)
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_fserr",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
mock_job_manager.fail_job.assert_called_once()
assert "Connection refused" in mock_job_manager.fail_job.call_args.args[1]
def test_wait_for_download_no_filepath_fails_job(
self, mock_job_manager, mock_storage_service
):
"""If wait_for_download returns no filepath, job should be failed."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Test',
'artist': 'Artist',
'provider': 'RED',
'quality': 'FLAC',
'source_id': 'torrent_nofp',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
# wait_for_download returns status without gcs_path or output_path
mock_flacfetch = Mock()
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-nofp")
mock_flacfetch.wait_for_download = AsyncMock(return_value={
"status": "complete",
# No gcs_path or output_path
})
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_nofp",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
mock_job_manager.fail_job.assert_called_once()
assert "no file path" in mock_job_manager.fail_job.call_args.args[1].lower()
def test_spotify_wait_for_download_no_filepath_fails_job(
self, mock_job_manager, mock_storage_service
):
"""Spotify: if wait_for_download returns no filepath, job should be failed."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Test',
'artist': 'Artist',
'provider': 'Spotify',
'quality': 'OGG',
'source_id': 'spotify:track:nofp',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
mock_flacfetch = Mock()
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-sp-nofp")
mock_flacfetch.wait_for_download = AsyncMock(return_value={
"status": "complete",
})
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_sp_nofp",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
mock_job_manager.fail_job.assert_called_once()
assert "no file path" in mock_job_manager.fail_job.call_args.args[1].lower()
def test_youtube_download_error_fails_job(
self, mock_job_manager, mock_storage_service
):
"""YouTubeDownloadError should be caught and job failed."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
from backend.services.youtube_download_service import YouTubeDownloadError
import asyncio
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Deleted Video',
'artist': 'Unknown',
'provider': 'YouTube',
'quality': 'Opus',
'source_id': 'deleted123',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
mock_youtube_service = Mock()
mock_youtube_service.download_by_id = AsyncMock(
side_effect=YouTubeDownloadError("Video unavailable")
)
with patch('backend.api.routes.audio_search.get_youtube_download_service', return_value=mock_youtube_service):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_yt_err",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
mock_job_manager.fail_job.assert_called_once()
assert "Video unavailable" in mock_job_manager.fail_job.call_args.args[1]
def test_youtube_no_video_id_fails_job(
self, mock_job_manager, mock_storage_service
):
"""YouTube download with no source_id and no extractable video ID should fail."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Bad Link',
'artist': 'Unknown',
'provider': 'YouTube',
'quality': 'Opus',
# No source_id
'url': 'https://example.com/not-youtube',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
mock_youtube_service = Mock()
mock_youtube_service._extract_video_id = Mock(return_value=None)
with patch('backend.api.routes.audio_search.get_youtube_download_service', return_value=mock_youtube_service):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_yt_noid",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
mock_job_manager.fail_job.assert_called_once()
assert "video ID" in mock_job_manager.fail_job.call_args.args[1] or \
"No video" in mock_job_manager.fail_job.call_args.args[1]
class TestSearchAsyncUsage:
"""Tests that the search endpoint uses search_async instead of sync search."""
def test_search_async_uses_get_running_loop(self):
"""search_async should use asyncio.get_running_loop() (not deprecated get_event_loop)."""
import asyncio
import inspect
source = inspect.getsource(AudioSearchService.search_async)
assert 'get_running_loop' in source
assert 'get_event_loop' not in source
def test_download_async_uses_get_running_loop(self):
"""download_async should use asyncio.get_running_loop()."""
import inspect
source = inspect.getsource(AudioSearchService.download_async)
assert 'get_running_loop' in source
assert 'get_event_loop' not in source
def test_download_by_id_async_uses_get_running_loop(self):
"""download_by_id_async should use asyncio.get_running_loop()."""
import inspect
source = inspect.getsource(AudioSearchService.download_by_id_async)
assert 'get_running_loop' in source
assert 'get_event_loop' not in source
def test_search_endpoint_calls_search_async(self):
"""Verify the search endpoint source calls search_async, not sync search."""
import inspect
from backend.api.routes.audio_search import search_audio
source = inspect.getsource(search_audio)
assert 'search_async' in source
# Should NOT have a bare .search( call (which is sync)
# But it may have search_async( which contains "search" — so check specifically
# that search_async is used and not audio_search_service.search(
assert 'await audio_search_service.search_async(' in source
class TestInsufficientCreditsErrorPropagation:
"""Test that InsufficientCreditsError propagates correctly as 402."""
def test_exception_handler_uses_isinstance(self):
"""
Verify the exception handler uses isinstance() for InsufficientCreditsError.
This is robust against class identity issues from module reloading.
"""
import inspect
from backend.api.routes.audio_search import search_audio
source = inspect.getsource(search_audio)
assert 'isinstance(e, (InsufficientCreditsError, RateLimitExceededError))' in source
+381
View File
@@ -0,0 +1,381 @@
"""
Tests for the cleanup-distribution endpoint in jobs.py.
Verifies:
- GDrive cleanup uses tracked file IDs from state_data when available (fast path)
- GDrive cleanup falls back to brand_code search when gdrive_files is empty (fallback path)
- Brand code is recycled ONLY after both Dropbox AND GDrive are confirmed clean
- Brand code is NOT recycled when GDrive cleanup fails or is skipped
- Endpoint returns correct status for each distribution service
The cleanup-distribution endpoint is used by the E2E happy-path test (Step 12)
to remove test job files from YouTube, Dropbox, and Google Drive after the test.
"""
import pytest
from unittest.mock import Mock, patch, MagicMock
from fastapi.testclient import TestClient
from fastapi import FastAPI
from datetime import datetime, UTC
from backend.api.routes.jobs import router
from backend.api.dependencies import require_admin, require_auth, AuthResult, UserType
from backend.models.job import Job, JobStatus
# ─── Test App ────────────────────────────────────────────────────────────────
def get_mock_admin():
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=999,
message="Admin authenticated",
user_email="admin@example.com",
is_admin=True,
)
app = FastAPI()
app.include_router(router, prefix="/api")
app.dependency_overrides[require_admin] = get_mock_admin
app.dependency_overrides[require_auth] = get_mock_admin
@pytest.fixture
def client():
return TestClient(app)
# ─── Fixtures ────────────────────────────────────────────────────────────────
def _make_job(
*,
brand_code="NOMAD-1271",
gdrive_files=None,
gdrive_folder_id="root-folder-id",
dropbox_path="/Tracks-PublicShare",
artist="piri",
title="dog",
):
"""Make a mock Job in COMPLETE state with the given distribution data."""
job = Mock(spec=Job)
job.job_id = "test-job-id"
job.status = JobStatus.COMPLETE
job.artist = artist
job.title = title
job.dropbox_path = dropbox_path
job.gdrive_folder_id = gdrive_folder_id
job.state_data = {
"brand_code": brand_code,
"gdrive_files": gdrive_files if gdrive_files is not None else {},
}
return job
# ─── GDrive Cleanup — Fast Path (tracked file IDs) ───────────────────────────
class TestCleanupDistributionGDriveTrackedFileIDs:
"""GDrive cleanup uses tracked file IDs from state_data when available."""
def test_gdrive_cleanup_uses_tracked_file_ids(self, client):
"""When gdrive_files has file IDs, delete_files is called with those IDs."""
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True
mock_gdrive = Mock()
mock_gdrive.is_configured = True
mock_gdrive.delete_files.return_value = {"file-id-mp4": True, "file-id-cdg": True}
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
data = response.json()
# Should have used the tracked file IDs (fast path)
mock_gdrive.delete_files.assert_called_once_with(["file-id-mp4", "file-id-cdg"])
# Should NOT have searched by brand code
mock_gdrive.find_files_by_brand_code.assert_not_called()
assert data["gdrive"]["status"] == "success"
def test_gdrive_cleanup_reports_partial_when_some_deletes_fail(self, client):
"""When some file deletes fail, status is 'partial'."""
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True
mock_gdrive = Mock()
mock_gdrive.is_configured = True
mock_gdrive.delete_files.return_value = {
"file-id-mp4": True,
"file-id-cdg": False, # This one failed
}
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
data = response.json()
assert data["gdrive"]["status"] == "partial"
# ─── GDrive Cleanup — Fallback Path (brand_code search) ──────────────────────
class TestCleanupDistributionGDriveFallback:
"""GDrive cleanup searches by brand_code when gdrive_files is empty."""
def test_falls_back_to_brand_code_search_when_gdrive_files_empty(self, client):
"""When gdrive_files={}, search GDrive by brand_code and delete found files."""
job = _make_job(gdrive_files={}) # Empty — simulates old jobs / silently-failed uploads
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True
mock_gdrive = Mock()
mock_gdrive.is_configured = True
# find_files_by_brand_code returns file IDs found by searching GDrive
mock_gdrive.find_files_by_brand_code.return_value = ["old-file-id-cdg", "old-file-id-mp4"]
mock_gdrive.delete_files.return_value = {
"old-file-id-cdg": True,
"old-file-id-mp4": True,
}
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
data = response.json()
# Should have searched by brand code (fallback path)
mock_gdrive.find_files_by_brand_code.assert_called_once_with(
"root-folder-id", "NOMAD-1271"
)
# Should have deleted the found files
mock_gdrive.delete_files.assert_called_once()
assert data["gdrive"]["status"] == "success"
def test_falls_back_to_brand_code_search_when_gdrive_files_none(self, client):
"""When gdrive_files not in state_data (old job), search by brand_code."""
job = _make_job(gdrive_files=None)
job.state_data = {"brand_code": "NOMAD-1271"} # No gdrive_files key at all
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True
mock_gdrive = Mock()
mock_gdrive.is_configured = True
mock_gdrive.find_files_by_brand_code.return_value = ["legacy-file-id"]
mock_gdrive.delete_files.return_value = {"legacy-file-id": True}
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
mock_gdrive.find_files_by_brand_code.assert_called_once()
def test_reports_skipped_when_no_files_found_by_brand_code(self, client):
"""When brand_code search finds nothing, GDrive status is 'skipped'."""
job = _make_job(gdrive_files={})
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True
mock_gdrive = Mock()
mock_gdrive.is_configured = True
mock_gdrive.find_files_by_brand_code.return_value = [] # Nothing found
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
data = response.json()
assert data["gdrive"]["status"] == "skipped"
assert "no files found" in data["gdrive"]["reason"]
# ─── Brand Code Recycling — Gated on GDrive Success ──────────────────────────
class TestCleanupDistributionBrandCodeRecycling:
"""Brand code is recycled only after BOTH Dropbox AND GDrive are confirmed clean."""
def test_brand_code_recycled_when_both_dropbox_and_gdrive_cleaned(self, client):
"""Brand code is recycled when Dropbox delete succeeds and GDrive cleanup succeeds."""
job = _make_job(gdrive_files={"cdg": "file-id"})
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True # Dropbox success
mock_gdrive = Mock()
mock_gdrive.is_configured = True
mock_gdrive.delete_files.return_value = {"file-id": True} # GDrive success
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.BrandCodeService") as mock_bcs_class, \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
mock_bcs_class.parse_brand_code.return_value = ("NOMAD", 1271)
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
data = response.json()
# Brand code should be recycled
mock_brand_service.recycle_brand_code.assert_called_once()
assert data["dropbox"].get("recycled_brand_code") is True
def test_brand_code_not_recycled_when_gdrive_cleanup_partial(self, client):
"""Brand code is NOT recycled when GDrive delete only partially succeeded.
If GDrive still has files with this brand code, recycling would allow a new
job to get the same brand code, creating a duplicate in the public share.
"""
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True # Dropbox success
mock_gdrive = Mock()
mock_gdrive.is_configured = True
mock_gdrive.delete_files.return_value = {
"file-id-mp4": True,
"file-id-cdg": False, # CDG file still on GDrive
}
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
data = response.json()
# Brand code should NOT be recycled because GDrive still has a file
mock_brand_service.recycle_brand_code.assert_not_called()
# recycled_brand_code key should be absent (recycling never attempted)
assert "recycled_brand_code" not in data.get("dropbox", {})
def test_brand_code_not_recycled_when_gdrive_not_configured(self, client):
"""Brand code is NOT recycled when GDrive is not configured.
Without GDrive credentials, we cannot confirm that GDrive was cleaned.
A previous upload may have succeeded (e.g., different credentials rotation).
"""
job = _make_job(gdrive_files={"cdg": "file-id"})
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True
mock_gdrive = Mock()
mock_gdrive.is_configured = False # GDrive not configured
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
# Brand code NOT recycled — GDrive might still have files
mock_brand_service.recycle_brand_code.assert_not_called()
def test_brand_code_recycled_when_gdrive_finds_nothing_to_delete(self, client):
"""Brand code IS recycled when GDrive search finds nothing (already clean)."""
job = _make_job(gdrive_files={}) # Empty — no tracked IDs
mock_dropbox = Mock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True
mock_gdrive = Mock()
mock_gdrive.is_configured = True
mock_gdrive.find_files_by_brand_code.return_value = [] # GDrive already clean
mock_brand_service = Mock()
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.brand_code_service.BrandCodeService") as mock_bcs_class, \
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
mock_jm.get_job.return_value = job
mock_jm.delete_job.return_value = None
mock_bcs_class.parse_brand_code.return_value = ("NOMAD", 1271)
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
assert response.status_code == 200
data = response.json()
# GDrive was confirmed clean (nothing found), so brand code IS recycled
mock_brand_service.recycle_brand_code.assert_called_once()
assert data["dropbox"].get("recycled_brand_code") is True
+433 -5
View File
@@ -9,6 +9,7 @@ These tests mock the Google API client and Secret Manager to verify:
"""
import json
import os
import ssl
import pytest
from unittest.mock import Mock, MagicMock, patch
@@ -501,24 +502,451 @@ class TestUploadToPublicShare:
assert len(result) == 1
class TestRetryBehavior:
"""Test retry behavior for transient connection errors."""
@patch("backend.services.gdrive_service.get_settings")
def test_retries_on_broken_pipe(self, mock_get_settings):
"""Test that BrokenPipeError triggers retry and succeeds on second attempt."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
mock_files_api = Mock()
mock_list_result = Mock()
# First call raises BrokenPipeError, second succeeds
mock_list_result.execute.side_effect = [
BrokenPipeError("[Errno 32] Broken pipe"),
{"files": [{"id": "folder-123", "name": "MP4"}]},
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
# Patch _reset_service to clear but re-set the mock (avoid real OAuth)
def mock_reset():
service._service = mock_drive
service._reset_service = mock_reset
folder_id = service.get_or_create_folder("parent-123", "MP4")
assert folder_id == "folder-123"
assert mock_list_result.execute.call_count == 2
@patch("backend.services.gdrive_service.get_settings")
def test_gives_up_after_3_attempts(self, mock_get_settings):
"""Test that 3 consecutive failures raises the exception."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = BrokenPipeError("[Errno 32] Broken pipe")
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
# Patch _reset_service to re-set the mock (avoid real OAuth)
service._reset_service = lambda: setattr(service, '_service', mock_drive)
with pytest.raises(BrokenPipeError):
service.get_or_create_folder("parent-123", "MP4")
assert mock_list_result.execute.call_count == 3
@patch("backend.services.gdrive_service.get_settings")
def test_service_reset_on_retry(self, mock_get_settings):
"""Test that _service is reset to None between retry attempts."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = [
BrokenPipeError("[Errno 32] Broken pipe"),
{"files": [{"id": "folder-123", "name": "MP4"}]},
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
# Patch _reset_service to track calls but still do the reset
original_reset = service._reset_service
reset_calls = []
def tracked_reset():
reset_calls.append(True)
original_reset()
# Re-set mock service so the retry works
service._service = mock_drive
service._reset_service = tracked_reset
folder_id = service.get_or_create_folder("parent-123", "MP4")
assert folder_id == "folder-123"
assert len(reset_calls) == 1 # Reset called once between attempt 1 and 2
@patch("backend.services.gdrive_service.get_settings")
def test_retries_on_ssl_error(self, mock_get_settings):
"""Test that SSLError triggers retry."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = [
ssl.SSLError("SSL: UNEXPECTED_EOF_WHILE_READING"),
{"files": [{"id": "folder-123", "name": "MP4"}]},
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
# Patch _reset_service to re-set the mock (avoid real OAuth)
service._reset_service = lambda: setattr(service, '_service', mock_drive)
folder_id = service.get_or_create_folder("parent-123", "MP4")
assert folder_id == "folder-123"
assert mock_list_result.execute.call_count == 2
@patch("backend.services.gdrive_service.get_settings")
def test_no_retry_on_non_transient_error(self, mock_get_settings):
"""Test that non-transient errors are not retried."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = ValueError("bad value")
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
with pytest.raises(ValueError):
service.get_or_create_folder("parent-123", "MP4")
assert mock_list_result.execute.call_count == 1
class TestDeleteFile:
"""Test delete_file and delete_files methods."""
def _make_service(self, mock_get_settings):
"""Helper: make a GoogleDriveService with fake credentials pre-loaded."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
return service
@patch("backend.services.gdrive_service.get_settings")
def test_delete_file_success(self, mock_get_settings):
"""Successful delete returns True."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_delete = Mock()
mock_delete.execute.return_value = None
mock_files_api.delete.return_value = mock_delete
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.delete_file("file-id-123")
assert result is True
mock_files_api.delete.assert_called_once_with(fileId="file-id-123")
@patch("backend.services.gdrive_service.get_settings")
def test_delete_file_returns_true_on_404(self, mock_get_settings):
"""404 (already deleted) returns True — idempotent cleanup."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_delete = Mock()
not_found = Exception("File not found")
not_found.resp = Mock()
not_found.resp.status = 404
mock_delete.execute.side_effect = not_found
mock_files_api.delete.return_value = mock_delete
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.delete_file("already-gone-id")
assert result is True
@patch("backend.services.gdrive_service.get_settings")
def test_delete_file_returns_false_on_error(self, mock_get_settings):
"""Non-404 errors return False."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_delete = Mock()
mock_delete.execute.side_effect = Exception("Permission denied")
mock_files_api.delete.return_value = mock_delete
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.delete_file("restricted-file")
assert result is False
@patch("backend.services.gdrive_service.get_settings")
def test_delete_files_calls_delete_file_for_each_id(self, mock_get_settings):
"""delete_files returns a per-ID success dict."""
service = self._make_service(mock_get_settings)
# Stub delete_file: first ID succeeds, second fails
results_by_id = {"id-1": True, "id-2": False}
service.delete_file = lambda fid: results_by_id[fid]
result = service.delete_files(["id-1", "id-2"])
assert result == {"id-1": True, "id-2": False}
@patch("backend.services.gdrive_service.get_settings")
def test_delete_files_empty_list(self, mock_get_settings):
"""delete_files with empty list returns empty dict."""
service = self._make_service(mock_get_settings)
result = service.delete_files([])
assert result == {}
class TestFindFilesByBrandCode:
"""Test find_files_by_brand_code method — used as fallback in cleanup-distribution."""
def _make_service(self, mock_get_settings):
"""Helper: make a GoogleDriveService with fake credentials pre-loaded."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
service._loaded = True
service._credentials_data = {
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
}
return service
def _attach_mock_drive(self, service, list_side_effects):
"""Attach a mock Drive client whose files().list().execute() returns given values."""
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = list_side_effects
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
return mock_files_api
@patch("backend.services.gdrive_service.get_settings")
def test_finds_files_in_all_subfolders(self, mock_get_settings):
"""Test finds matching files across CDG/, MP4/, MP4-720p/ subfolders."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_list_result = Mock()
# Responses: for each subfolder: (1) find subfolder, (2) search for files
mock_list_result.execute.side_effect = [
{"files": [{"id": "cdg-folder"}]}, # CDG subfolder found
{"files": [{"id": "cdg-file-1", "name": "NOMAD-1271 - piri - dog.zip"}]},
{"files": [{"id": "mp4-folder"}]}, # MP4 subfolder found
{"files": [{"id": "mp4-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
{"files": [{"id": "mp4720-folder"}]}, # MP4-720p subfolder found
{"files": [{"id": "mp4720-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
assert len(result) == 3
assert "cdg-file-1" in result
assert "mp4-file-1" in result
assert "mp4720-file-1" in result
@patch("backend.services.gdrive_service.get_settings")
def test_returns_empty_when_subfolder_not_found(self, mock_get_settings):
"""Test returns empty list when public share subfolders don't exist."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_list_result = Mock()
# All subfolder lookups return empty
mock_list_result.execute.return_value = {"files": []}
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
assert result == []
@patch("backend.services.gdrive_service.get_settings")
def test_filters_by_exact_brand_code_prefix(self, mock_get_settings):
"""Test only returns files whose name starts with '{brand_code} - '."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = [
{"files": [{"id": "cdg-folder"}]},
{
"files": [
{"id": "match-id", "name": "NOMAD-1271 - piri - dog.zip"},
# This one contains NOMAD-1271 but doesn't START with it — should be excluded
{"id": "no-match-id", "name": "BONUS-NOMAD-1271 - other.zip"},
]
},
{"files": []}, # MP4 subfolder not found
{"files": []}, # MP4-720p subfolder not found
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
assert result == ["match-id"]
@patch("backend.services.gdrive_service.get_settings")
def test_returns_empty_when_no_files_match_brand_code(self, mock_get_settings):
"""Test returns empty list when subfolder exists but has no matching files."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = [
{"files": [{"id": "cdg-folder"}]},
{"files": [{"id": "other-id", "name": "NOMAD-1300 - someone else.zip"}]},
{"files": []}, # MP4 not found
{"files": []}, # MP4-720p not found
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
assert result == []
@patch("backend.services.gdrive_service.get_settings")
def test_raises_after_all_subfolders_when_any_error(self, mock_get_settings):
"""When any subfolder search errors, raises RuntimeError after processing all subfolders.
This prevents the cleanup endpoint from treating an incomplete search result
as "GDrive is clean" and incorrectly recycling the brand code.
"""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = [
{"files": [{"id": "cdg-folder"}]},
Exception("API error"), # CDG file search fails
{"files": [{"id": "mp4-folder"}]},
{"files": [{"id": "mp4-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
{"files": [{"id": "mp4720-folder"}]},
{"files": []},
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
# Should raise after processing all subfolders — an incomplete search must not
# be silently treated as "nothing found" by the caller
with pytest.raises(RuntimeError, match="search incomplete"):
service.find_files_by_brand_code("root-folder", "NOMAD-1271")
class TestGetGdriveService:
"""Test get_gdrive_service singleton."""
@patch("backend.services.gdrive_service.get_settings")
def test_get_gdrive_service_singleton(self, mock_get_settings):
"""Test get_gdrive_service returns singleton instance."""
from backend.services.gdrive_service import get_gdrive_service
import backend.services.gdrive_service as gdrive_module
# Reset singleton
gdrive_module._gdrive_service = None
mock_settings = Mock()
mock_settings.get_secret.return_value = None
mock_get_settings.return_value = mock_settings
service1 = get_gdrive_service()
service2 = get_gdrive_service()
assert service1 is service2
@@ -196,7 +196,7 @@ class TestUserEmailExtraction:
mock_jm.create_job.return_value = mock_job
mock_jm.get_job.return_value = mock_job
mock_cred.return_value.check_youtube_credentials.return_value = Mock(status=Mock(value="valid"))
mock_search.return_value.search.return_value = []
mock_search.return_value.search_async = AsyncMock(return_value=[])
await search_audio(
request=mock_request,
+205 -1
View File
@@ -214,6 +214,91 @@ class TestDeleteJob:
assert response.status_code in [200, 404]
class TestDeleteJobBrandCodeRecycling:
"""Tests for brand code recycling in DELETE /api/jobs/{job_id}."""
def test_brand_code_recycled_before_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
"""Test that brand code is recycled before the job is deleted."""
mock_job_manager = MagicMock()
job_with_brand = Job(
job_id="test-bc-123",
status=JobStatus.COMPLETE,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Test",
state_data={"brand_code": "NOMAD-0042"},
outputs_deleted_at=datetime.now(UTC),
)
mock_job_manager.get_job.return_value = job_with_brand
mock_job_manager.delete_job.return_value = True
mock_creds = MagicMock()
mock_creds.universe_domain = 'googleapis.com'
with patch('backend.api.routes.jobs.job_manager', mock_job_manager), \
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
patch('backend.api.routes.jobs.get_theme_service', return_value=mock_theme_service), \
patch('backend.services.job_manager.JobManager', lambda *a, **k: mock_job_manager), \
patch('backend.services.firestore_service.firestore'), \
patch('backend.services.storage_service.storage'), \
patch('google.auth.default', return_value=(mock_creds, 'test-project')), \
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code', return_value=("NOMAD", 42)) as mock_parse, \
patch('backend.services.brand_code_service.get_brand_code_service') as mock_get_svc:
mock_svc = MagicMock()
mock_get_svc.return_value = mock_svc
from backend.main import app
client = TestClient(app)
response = client.delete("/api/jobs/test-bc-123", headers=auth_headers)
assert response.status_code == 200
mock_parse.assert_called_once_with("NOMAD-0042")
mock_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
mock_job_manager.delete_job.assert_called_once()
def test_recycling_failure_does_not_prevent_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
"""Test that job deletion proceeds even if brand code recycling fails."""
mock_job_manager = MagicMock()
job_with_brand = Job(
job_id="test-bc-456",
status=JobStatus.COMPLETE,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Test",
state_data={"brand_code": "NOMAD-0099"},
outputs_deleted_at=datetime.now(UTC),
)
mock_job_manager.get_job.return_value = job_with_brand
mock_job_manager.delete_job.return_value = True
mock_creds = MagicMock()
mock_creds.universe_domain = 'googleapis.com'
with patch('backend.api.routes.jobs.job_manager', mock_job_manager), \
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
patch('backend.api.routes.jobs.get_theme_service', return_value=mock_theme_service), \
patch('backend.services.job_manager.JobManager', lambda *a, **k: mock_job_manager), \
patch('backend.services.firestore_service.firestore'), \
patch('backend.services.storage_service.storage'), \
patch('google.auth.default', return_value=(mock_creds, 'test-project')), \
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code', side_effect=ValueError("Bad format")):
from backend.main import app
client = TestClient(app)
response = client.delete("/api/jobs/test-bc-456", headers=auth_headers)
assert response.status_code == 200
# Job should still be deleted despite recycling failure
mock_job_manager.delete_job.assert_called_once()
def test_no_brand_code_skips_recycling(self, client, mock_job_manager, auth_headers):
"""Test that deletion without brand code doesn't attempt recycling."""
with patch('backend.services.brand_code_service.get_brand_code_service') as mock_get_svc:
response = client.delete("/api/jobs/test123", headers=auth_headers)
assert response.status_code == 200
mock_get_svc.assert_not_called()
class TestCancelJob:
"""Tests for POST /api/jobs/{job_id}/cancel."""
@@ -274,10 +359,129 @@ class TestSelectInstrumental:
class TestStartReview:
"""Tests for POST /api/jobs/{job_id}/start-review."""
def test_start_review_endpoint_exists(self, client, mock_job_manager, mock_job, auth_headers):
"""Test start review endpoint exists."""
response = client.post("/api/jobs/test123/start-review", headers=auth_headers)
# Should not be 404 or 405
assert response.status_code not in [404, 405]
class TestSubmitEditLog:
"""Tests for POST /api/jobs/{job_id}/edit-log."""
def test_submit_edit_log_returns_200(self, client, mock_job_manager, mock_job, auth_headers):
"""Test submitting a valid edit log returns 200."""
edit_log = {
"session_id": "sess-abc",
"job_id": "test123",
"audio_hash": "hash123",
"started_at": "2026-03-01T00:00:00.000Z",
"entries": [
{
"id": "e1",
"timestamp": "2026-03-01T00:01:00.000Z",
"operation": "word_change",
"segment_id": "s1",
"segment_index": 0,
"word_ids_before": ["w1"],
"word_ids_after": ["w1"],
"text_before": "helo",
"text_after": "hello",
"feedback": {"reason": "misheard_word", "timestamp": "2026-03-01T00:01:05.000Z"}
}
]
}
with patch('backend.api.routes.jobs.StorageService') as mock_storage_cls:
mock_storage = MagicMock()
mock_storage_cls.return_value = mock_storage
response = client.post("/api/jobs/test123/edit-log", json=edit_log, headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert data["status"] == "success"
assert data["entries_count"] == 1
assert data["feedback_count"] == 1
def test_submit_edit_log_stores_to_gcs(self, client, mock_job_manager, mock_job, auth_headers):
"""Test edit log is stored to GCS with correct path."""
edit_log = {
"session_id": "sess-xyz",
"job_id": "test123",
"audio_hash": "hash123",
"started_at": "2026-03-01T00:00:00.000Z",
"entries": []
}
with patch('backend.api.routes.jobs.StorageService') as mock_storage_cls:
mock_storage = MagicMock()
mock_storage_cls.return_value = mock_storage
client.post("/api/jobs/test123/edit-log", json=edit_log, headers=auth_headers)
mock_storage.upload_json.assert_called_once_with(
"jobs/test123/lyrics/edit_log_sess-xyz.json",
edit_log
)
def test_submit_edit_log_updates_firestore(self, client, mock_job_manager, mock_job, auth_headers):
"""Test edit log updates Firestore state_data."""
edit_log = {
"session_id": "sess-123",
"job_id": "test123",
"audio_hash": "h",
"started_at": "2026-03-01T00:00:00.000Z",
"entries": []
}
with patch('backend.api.routes.jobs.StorageService') as mock_storage_cls:
mock_storage_cls.return_value = MagicMock()
client.post("/api/jobs/test123/edit-log", json=edit_log, headers=auth_headers)
mock_job_manager.update_state_data.assert_any_call(
"test123", "last_edit_log_path", "jobs/test123/lyrics/edit_log_sess-123.json"
)
mock_job_manager.update_state_data.assert_any_call(
"test123", "last_edit_log_session", "sess-123"
)
def test_submit_edit_log_nonexistent_job_returns_404(self, mock_worker_service, auth_headers):
"""Test submitting to nonexistent job returns 404."""
mock_jm = MagicMock()
mock_jm.get_job.return_value = None
mock_creds = MagicMock()
mock_creds.universe_domain = 'googleapis.com'
def mock_jm_factory(*args, **kwargs):
return mock_jm
with patch('backend.api.routes.jobs.job_manager', mock_jm), \
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
patch('backend.services.job_manager.JobManager', mock_jm_factory), \
patch('backend.services.firestore_service.firestore'), \
patch('backend.services.storage_service.storage'), \
patch('google.auth.default', return_value=(mock_creds, 'test-project')):
from backend.main import app
test_client = TestClient(app)
response = test_client.post(
"/api/jobs/nonexistent/edit-log",
json={"session_id": "s", "entries": []},
headers=auth_headers
)
assert response.status_code == 404
def test_submit_edit_log_counts_feedback_correctly(self, client, mock_job_manager, mock_job, auth_headers):
"""Test feedback count excludes no_response entries."""
edit_log = {
"session_id": "sess-1",
"job_id": "test123",
"audio_hash": "h",
"started_at": "2026-03-01T00:00:00.000Z",
"entries": [
{"id": "e1", "feedback": {"reason": "misheard_word"}},
{"id": "e2", "feedback": {"reason": "no_response"}},
{"id": "e3", "feedback": None},
{"id": "e4", "feedback": {"reason": "wrong_lyrics"}},
]
}
with patch('backend.api.routes.jobs.StorageService') as mock_storage_cls:
mock_storage_cls.return_value = MagicMock()
response = client.post("/api/jobs/test123/edit-log", json=edit_log, headers=auth_headers)
data = response.json()
assert data["entries_count"] == 4
assert data["feedback_count"] == 2 # misheard_word + wrong_lyrics
+119
View File
@@ -0,0 +1,119 @@
"""
Unit tests for the annotations endpoint in review.py.
Tests the actual storage logic (not the stub version).
"""
import pytest
from unittest.mock import MagicMock, patch
from fastapi.testclient import TestClient
@pytest.fixture
def mock_storage():
"""Create a mock StorageService that tracks calls."""
storage = MagicMock()
storage.upload_json = MagicMock()
# Default: no existing annotations
storage.download_json = MagicMock(side_effect=Exception("Not found"))
return storage
@pytest.fixture
def client(mock_storage):
"""Create TestClient with mocked dependencies for review routes."""
mock_creds = MagicMock()
mock_creds.universe_domain = 'googleapis.com'
mock_jm = MagicMock()
mock_jm.get_job.return_value = MagicMock(
job_id="test-job",
status="in_review",
review_token="test-review-token"
)
def mock_jm_factory(*args, **kwargs):
return mock_jm
# Override review auth to bypass complex auth chain
async def fake_review_auth():
return ("test-job", "full")
with patch('backend.api.routes.jobs.job_manager', mock_jm), \
patch('backend.services.job_manager.JobManager', mock_jm_factory), \
patch('backend.services.firestore_service.firestore'), \
patch('backend.services.storage_service.storage'), \
patch('google.auth.default', return_value=(mock_creds, 'test-project')):
from backend.main import app
from backend.api.dependencies import require_review_auth
# Override review auth dependency (must use the same function object used by routes)
app.dependency_overrides[require_review_auth] = fake_review_auth
# Patch StorageService inside the review module
with patch('backend.api.routes.review.StorageService', return_value=mock_storage):
yield TestClient(app)
app.dependency_overrides.clear()
class TestSubmitAnnotations:
"""Tests for POST /api/review/{job_id}/v1/annotations."""
def test_submit_single_annotation(self, client, mock_storage):
"""Test submitting a single annotation stores to GCS."""
annotation = {"annotation_type": "SOUND_ALIKE", "original_text": "helo", "corrected_text": "hello"}
response = client.post("/api/review/test-job/v1/annotations", json=annotation)
assert response.status_code == 200
data = response.json()
assert data["status"] == "success"
assert data["saved_count"] == 1
def test_submit_batch_annotations(self, client, mock_storage):
"""Test submitting a batch of annotations."""
payload = {
"annotations": [
{"annotation_type": "SOUND_ALIKE", "original_text": "a"},
{"annotation_type": "EXTRA_WORDS", "original_text": "b"},
]
}
response = client.post("/api/review/test-job/v1/annotations", json=payload)
assert response.status_code == 200
data = response.json()
assert data["saved_count"] == 2
assert data["total_count"] == 2
def test_annotations_stored_to_correct_gcs_path(self, client, mock_storage):
"""Test annotations are stored at jobs/{job_id}/lyrics/annotations.json."""
client.post(
"/api/review/test-job/v1/annotations",
json={"annotation_type": "MANUAL_EDIT"}
)
mock_storage.upload_json.assert_called_once()
gcs_path = mock_storage.upload_json.call_args[0][0]
assert gcs_path == "jobs/test-job/lyrics/annotations.json"
def test_annotations_merged_with_existing(self, client, mock_storage):
"""Test new annotations are merged with existing ones."""
# Set up existing annotations
mock_storage.download_json.side_effect = None
mock_storage.download_json.return_value = {
"annotations": [{"annotation_type": "SOUND_ALIKE", "original_text": "existing"}]
}
payload = {"annotations": [{"annotation_type": "EXTRA_WORDS", "original_text": "new"}]}
response = client.post("/api/review/test-job/v1/annotations", json=payload)
data = response.json()
assert data["saved_count"] == 1
assert data["total_count"] == 2 # 1 existing + 1 new
# Verify merged data was uploaded
uploaded_data = mock_storage.upload_json.call_args[0][1]
assert len(uploaded_data["annotations"]) == 2
def test_annotations_fresh_when_no_existing(self, client, mock_storage):
"""Test annotations start fresh when no existing file."""
payload = {"annotations": [{"annotation_type": "NO_ERROR"}]}
response = client.post("/api/review/test-job/v1/annotations", json=payload)
assert response.json()["total_count"] == 1
+293 -7
View File
@@ -250,8 +250,28 @@ class TestVideoWorkerOrchestratorPackaging:
"""Test packaging stage."""
@pytest.mark.asyncio
async def test_run_packaging_no_lrc(self):
"""Test packaging stage with no LRC file."""
async def test_run_packaging_no_lrc_cdg_disabled(self):
"""Test packaging stage with no LRC file and CDG disabled skips silently."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=False,
lrc_file_path=None,
)
orchestrator = VideoWorkerOrchestrator(config)
# Should not raise, just skip
await orchestrator._run_packaging()
assert orchestrator.result.final_karaoke_cdg_zip is None
@pytest.mark.asyncio
async def test_run_packaging_no_lrc_cdg_enabled_raises(self):
"""Test packaging stage raises when CDG enabled but no LRC file."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
@@ -264,10 +284,8 @@ class TestVideoWorkerOrchestratorPackaging:
)
orchestrator = VideoWorkerOrchestrator(config)
# Should not raise, just skip
await orchestrator._run_packaging()
assert orchestrator.result.final_karaoke_cdg_zip is None
with pytest.raises(RuntimeError, match="LRC file not available"):
await orchestrator._run_packaging()
@pytest.mark.asyncio
async def test_run_packaging_cdg(self):
@@ -368,6 +386,209 @@ class TestVideoWorkerOrchestratorPackaging:
"countdown_padding_seconds must be passed for CDG timestamp adjustment"
class TestPackagingValidation:
"""Test CDG/TXT packaging validation checks.
These tests verify that the orchestrator fails fast when CDG/TXT
generation is enabled but fails, rather than silently proceeding
to expensive encoding. This prevents jobs from completing without
their requested CDG/TXT packages.
Added after jobs 5b6aba25 and 5161b069 completed with enable_cdg=True
but no CDG ZIP was produced due to a FileNotFoundError being silently caught.
"""
@pytest.mark.asyncio
async def test_cdg_validation_fails_when_enabled_but_not_produced(self):
"""Test that orchestrator raises when CDG enabled but not produced."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=True,
)
orchestrator = VideoWorkerOrchestrator(config)
# Mock _run_packaging to NOT set result.final_karaoke_cdg_zip (simulates failure)
async def mock_packaging():
pass # CDG generation "failed" silently
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
result = await orchestrator.run()
assert result.success is False
assert "CDG generation was enabled but failed" in result.error_message
mock_encoding.assert_not_called() # Should not reach encoding
@pytest.mark.asyncio
async def test_txt_validation_fails_when_enabled_but_not_produced(self):
"""Test that orchestrator raises when TXT enabled but not produced."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_txt=True,
)
orchestrator = VideoWorkerOrchestrator(config)
async def mock_packaging():
pass # TXT generation "failed" silently
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
result = await orchestrator.run()
assert result.success is False
assert "TXT generation was enabled but failed" in result.error_message
mock_encoding.assert_not_called()
@pytest.mark.asyncio
async def test_pipeline_succeeds_when_cdg_disabled(self):
"""Test that pipeline succeeds normally when CDG is not enabled."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=False,
enable_txt=False,
)
orchestrator = VideoWorkerOrchestrator(config)
with patch.object(orchestrator, "_run_packaging", new_callable=AsyncMock) as mock_pkg, \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_notifications", new_callable=AsyncMock):
result = await orchestrator.run()
assert result.success is True
mock_pkg.assert_not_called() # Packaging skipped entirely
@pytest.mark.asyncio
async def test_cdg_validation_passes_when_cdg_produced(self):
"""Test that validation passes when CDG is successfully produced."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=True,
)
orchestrator = VideoWorkerOrchestrator(config)
async def mock_packaging_success():
orchestrator.result.final_karaoke_cdg_zip = "/output/cdg.zip"
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging_success), \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_notifications", new_callable=AsyncMock):
result = await orchestrator.run()
assert result.success is True
@pytest.mark.asyncio
async def test_both_cdg_and_txt_validation_fail_together(self):
"""Test that orchestrator catches CDG failure when both CDG and TXT enabled."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=True,
enable_txt=True,
)
orchestrator = VideoWorkerOrchestrator(config)
async def mock_packaging():
pass # Both CDG and TXT "failed" silently
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
result = await orchestrator.run()
assert result.success is False
# CDG validation is checked first
assert "CDG generation was enabled but failed" in result.error_message
mock_encoding.assert_not_called()
@pytest.mark.asyncio
async def test_lrc_missing_raises_when_cdg_enabled(self):
"""Test that missing LRC file raises when CDG is enabled."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=True,
lrc_file_path="/nonexistent/path.lrc",
)
orchestrator = VideoWorkerOrchestrator(config)
with pytest.raises(RuntimeError, match="LRC file not available"):
await orchestrator._run_packaging()
@pytest.mark.asyncio
async def test_lrc_missing_raises_when_txt_enabled(self):
"""Test that missing LRC file raises when TXT is enabled."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_txt=True,
lrc_file_path=None,
)
orchestrator = VideoWorkerOrchestrator(config)
with pytest.raises(RuntimeError, match="LRC file not available"):
await orchestrator._run_packaging()
@pytest.mark.asyncio
async def test_lrc_missing_skips_when_cdg_disabled(self):
"""Test that missing LRC file just skips packaging when CDG/TXT disabled."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=False,
enable_txt=False,
lrc_file_path=None,
)
orchestrator = VideoWorkerOrchestrator(config)
# Should not raise, just skip
await orchestrator._run_packaging()
assert orchestrator.result.final_karaoke_cdg_zip is None
class TestVideoWorkerOrchestratorEncoding:
"""Test encoding stage."""
@@ -772,8 +993,12 @@ class TestVideoWorkerOrchestratorFullPipeline:
)
orchestrator = VideoWorkerOrchestrator(config)
# Mock packaging to set CDG result (validation requires it when enable_cdg=True)
async def mock_packaging_with_result():
orchestrator.result.final_karaoke_cdg_zip = "/output/cdg.zip"
# Mock all stages
with patch.object(orchestrator, "_run_packaging", new_callable=AsyncMock) as mock_packaging, \
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging_with_result) as mock_packaging, \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding, \
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock) as mock_org, \
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock) as mock_dist, \
@@ -1287,3 +1512,64 @@ class TestOrchestratorCountdownPadding:
assert captured_input is not None, "encode() should have been called"
assert captured_input.options.get("countdown_padding_seconds") == 3.0, \
"Orchestrator must pass countdown_padding_seconds in EncodingInput.options"
class TestDistributionWarnings:
"""Test distribution_warnings tracking in OrchestratorResult."""
def test_result_has_distribution_warnings_field(self):
"""Test that OrchestratorResult has distribution_warnings as empty list by default."""
result = OrchestratorResult(success=True)
assert result.distribution_warnings == []
@pytest.mark.asyncio
async def test_gdrive_failure_populates_warnings(self):
"""Test that Google Drive upload failure populates distribution_warnings."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
gdrive_folder_id="folder-123",
)
orchestrator = VideoWorkerOrchestrator(config)
orchestrator.result.brand_code = "NOMAD-0001"
with patch("backend.services.gdrive_service.get_gdrive_service") as mock_get:
mock_gdrive = MagicMock()
mock_gdrive.is_configured = True
mock_gdrive.upload_to_public_share.side_effect = Exception("Connection refused")
mock_get.return_value = mock_gdrive
await orchestrator._upload_to_gdrive()
assert len(orchestrator.result.distribution_warnings) == 1
assert "Google Drive upload failed" in orchestrator.result.distribution_warnings[0]
@pytest.mark.asyncio
async def test_dropbox_failure_populates_warnings(self):
"""Test that Dropbox upload failure populates distribution_warnings."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
dropbox_path="/Public Share",
)
orchestrator = VideoWorkerOrchestrator(config)
orchestrator.result.brand_code = "NOMAD-0001"
with patch("backend.services.dropbox_service.get_dropbox_service") as mock_get:
mock_dropbox = MagicMock()
mock_dropbox.is_configured = True
mock_dropbox.upload_folder.side_effect = Exception("Auth expired")
mock_get.return_value = mock_dropbox
await orchestrator._upload_to_dropbox()
assert len(orchestrator.result.distribution_warnings) == 1
assert "Dropbox upload failed" in orchestrator.result.distribution_warnings[0]
+77 -17
View File
@@ -339,15 +339,26 @@ async def generate_video_orchestrated(job_id: str) -> bool:
# Store result metadata in job BEFORE transitioning to COMPLETE
# This ensures youtube_url is available when completion email is sent
logger.info(f"[job:{job_id}] Video generation complete")
job_manager.update_job(job_id, {
'state_data': {
**job.state_data,
'brand_code': result.brand_code,
'youtube_url': result.youtube_url,
'dropbox_link': result.dropbox_link,
'gdrive_files': result.gdrive_files,
}
})
state_update = {
**job.state_data,
'brand_code': result.brand_code,
'youtube_url': result.youtube_url,
'dropbox_link': result.dropbox_link,
'gdrive_files': result.gdrive_files,
}
if result.distribution_warnings:
state_update['distribution_warnings'] = result.distribution_warnings
job_manager.update_job(job_id, {'state_data': state_update})
# Send Pushbullet alert if any distribution uploads failed
if result.distribution_warnings:
_send_distribution_warning_notification(
job_id=job_id,
artist=job.artist,
title=job.title,
warnings=result.distribution_warnings,
settings=settings,
)
# Mark job as complete (triggers completion email with youtube_url now available)
job_manager.transition_to_state(
@@ -841,6 +852,7 @@ async def _handle_native_distribution(
job_log.warning(f"Dropbox SDK not installed: {e}")
except Exception as e:
job_log.error(f"Native Dropbox upload failed: {e}", exc_info=True)
result.setdefault('distribution_warnings', []).append(f"Dropbox upload failed: {e}")
# Don't fail the job - distribution is optional
# Upload to Google Drive using native API
@@ -884,6 +896,7 @@ async def _handle_native_distribution(
job_log.warning(f"Google API packages not installed: {e}")
except Exception as e:
job_log.error(f"Native Google Drive upload failed: {e}", exc_info=True)
result.setdefault('distribution_warnings', []).append(f"Google Drive upload failed: {e}")
# Don't fail the job - distribution is optional
elif existing_gdrive_files:
job_log.info(f"Skipping Google Drive upload - orchestrator already uploaded {len(existing_gdrive_files)} files")
@@ -891,17 +904,64 @@ async def _handle_native_distribution(
# Update job state_data with brand code and links
if brand_code or result.get('dropbox_link') or result.get('gdrive_files'):
try:
job_manager.update_job(job_id, {
'state_data': {
**job.state_data,
'brand_code': brand_code,
'dropbox_link': result.get('dropbox_link'),
'gdrive_files': result.get('gdrive_files'),
}
})
state_update = {
**job.state_data,
'brand_code': brand_code,
'dropbox_link': result.get('dropbox_link'),
'gdrive_files': result.get('gdrive_files'),
}
if result.get('distribution_warnings'):
state_update['distribution_warnings'] = result['distribution_warnings']
job_manager.update_job(job_id, {'state_data': state_update})
except Exception as e:
job_log.warning(f"Failed to update job state_data: {e}")
# Send Pushbullet alert if any distribution uploads failed
if result.get('distribution_warnings'):
_send_distribution_warning_notification(
job_id=job_id,
artist=job.artist,
title=job.title,
warnings=result['distribution_warnings'],
settings=settings,
)
def _send_distribution_warning_notification(
job_id: str,
artist: str,
title: str,
warnings: list[str],
settings=None,
) -> None:
"""Send Pushbullet notification when distribution uploads fail."""
try:
if settings is None:
settings = get_settings()
api_key = settings.get_secret("pushbullet-api-key")
if not api_key:
logger.warning("Pushbullet API key not found, skipping distribution warning notification")
return
import requests as req
push_title = f"Distribution Warning: {artist} - {title}"
body = f"Job {job_id} completed but {len(warnings)} upload(s) failed:\n\n"
body += "\n".join(f" - {w}" for w in warnings)
resp = req.post(
"https://api.pushbullet.com/v2/pushes",
headers={"Access-Token": api_key, "Content-Type": "application/json"},
json={"type": "note", "title": push_title, "body": body},
timeout=10,
)
if resp.ok:
logger.info(f"[job:{job_id}] Distribution warning notification sent via Pushbullet")
else:
logger.warning(f"[job:{job_id}] Pushbullet notification failed: {resp.status_code} {resp.text}")
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to send Pushbullet notification: {e}")
def _validate_prerequisites(job) -> bool:
"""Validate that all prerequisites are met for video generation."""
@@ -109,6 +109,9 @@ class OrchestratorResult:
dropbox_link: Optional[str] = None
gdrive_files: Optional[Dict[str, str]] = field(default_factory=dict)
# Distribution warnings (non-fatal upload failures)
distribution_warnings: List[str] = field(default_factory=list)
# Timing
encoding_time_seconds: Optional[float] = None
total_time_seconds: Optional[float] = None
@@ -228,6 +231,18 @@ class VideoWorkerOrchestrator:
if self.config.enable_cdg or self.config.enable_txt:
await self._run_packaging()
# Validate required packaging outputs before expensive encoding
if self.config.enable_cdg and not self.result.final_karaoke_cdg_zip:
raise RuntimeError(
"CDG generation was enabled but failed. "
"Check worker logs for CDG-related errors."
)
if self.config.enable_txt and not self.result.final_karaoke_txt_zip:
raise RuntimeError(
"TXT generation was enabled but failed. "
"Check worker logs for TXT-related errors."
)
# Stage 2: Encoding
await self._run_encoding()
@@ -240,6 +255,11 @@ class VideoWorkerOrchestrator:
# Stage 5: Notifications (Discord)
await self._run_notifications()
# Stage 6: Post-distribution GDrive validation
# Only for jobs that uploaded to the public share (non-private)
if self.config.gdrive_folder_id:
await self._trigger_gdrive_validation()
self.result.success = True
self.result.total_time_seconds = time.time() - start_time
@@ -259,6 +279,10 @@ class VideoWorkerOrchestrator:
self.job_log.info("Starting packaging stage (CDG/TXT)")
if not self.config.lrc_file_path or not os.path.isfile(self.config.lrc_file_path):
if self.config.enable_cdg or self.config.enable_txt:
raise RuntimeError(
f"CDG/TXT generation enabled but LRC file not available: {self.config.lrc_file_path}"
)
self.job_log.warning("No LRC file available, skipping CDG/TXT packaging")
return
@@ -587,6 +611,7 @@ class VideoWorkerOrchestrator:
except Exception as e:
self.job_log.error(f"YouTube upload failed: {e}")
self.result.distribution_warnings.append(f"YouTube upload failed: {e}")
# Don't fail the pipeline - YouTube is optional
async def _upload_to_dropbox(self):
@@ -623,6 +648,7 @@ class VideoWorkerOrchestrator:
except Exception as e:
self.job_log.error(f"Dropbox upload failed: {e}")
self.result.distribution_warnings.append(f"Dropbox upload failed: {e}")
# Don't fail the pipeline - Dropbox is optional
async def _upload_to_gdrive(self):
@@ -659,6 +685,7 @@ class VideoWorkerOrchestrator:
except Exception as e:
self.job_log.error(f"Google Drive upload failed: {e}")
self.result.distribution_warnings.append(f"Google Drive upload failed: {e}")
# Don't fail the pipeline - GDrive is optional
async def _run_notifications(self):
@@ -681,6 +708,16 @@ class VideoWorkerOrchestrator:
self.job_log.error(f"Discord notification failed: {e}")
# Don't fail the pipeline - notifications are optional
async def _trigger_gdrive_validation(self):
"""Trigger GDrive validation after uploading to the public share."""
try:
from backend.services.gdrive_validator_client import trigger_gdrive_validation
self.job_log.info("Triggering post-job GDrive validation")
trigger_gdrive_validation()
except Exception as e:
self.job_log.warning(f"GDrive validation trigger failed (non-fatal): {e}")
# Never fail the pipeline for validation
def create_orchestrator_config_from_job(
job,
+107 -7
View File
@@ -225,6 +225,51 @@ Error (duration mismatch):
}
```
#### Submit Edit Log
```http
POST /api/jobs/{job_id}/edit-log
Content-Type: application/json
{
"session_id": "abc123",
"job_id": "test-job",
"audio_hash": "hash",
"started_at": "2026-03-01T00:00:00.000Z",
"entries": [
{
"id": "entry-1",
"timestamp": "2026-03-01T00:01:00.000Z",
"operation": "word_change",
"segment_id": "seg-0",
"segment_index": 0,
"word_ids_before": ["w1"],
"word_ids_after": ["w1"],
"text_before": "helo",
"text_after": "hello",
"feedback": { "reason": "misheard_word", "timestamp": "..." }
}
]
}
```
Stores a session edit log to GCS at `jobs/{job_id}/lyrics/edit_log_{session_id}.json`. Tracks all user edits and optional feedback reasons for transcription improvement. Called automatically on review submission.
#### Submit Annotations
```http
POST /api/review/{job_id}/v1/annotations
Content-Type: application/json
{
"annotations": [
{ "annotation_type": "SOUND_ALIKE", "original_text": "helo" }
]
}
```
Stores annotations to `jobs/{job_id}/lyrics/annotations.json`. Merges with existing annotations if present.
### Instrumental Selection (Finalise-Only Jobs)
For finalise-only jobs (where audio prep was done externally), instrumental selection is handled separately:
@@ -438,6 +483,8 @@ GET /api/users/me
Authorization: Bearer SESSION_TOKEN
```
Response includes `feedback_eligible: bool` indicating whether the user can earn credits by submitting feedback (requires 2+ completed jobs and no prior feedback submission).
### Logout
```http
@@ -516,7 +563,7 @@ Credits are checked and deducted at job creation time. The flow:
3. **Deduct** - `user_service.deduct_credit()` atomically deducts 1 credit (with job_id for audit trail)
4. **Refund on failure** - If the job fails, 1 credit is automatically refunded
Admin users bypass credit checks entirely. New users receive 2 welcome credits.
Admin users bypass credit checks entirely. New users receive 2 welcome credits. Users can earn 2 additional free credits by submitting product feedback after completing 2+ jobs (see [User Feedback for Credits](#user-feedback-for-credits)).
#### 402 Response
@@ -539,7 +586,9 @@ POST /api/users/webhooks/stripe
Handles `checkout.session.completed` events.
## Beta Tester Program (PR #90)
## Beta Tester Program (Deprecated)
> **Note**: The beta program was removed from the homepage in PR #430. These endpoints are preserved for backward compatibility but are no longer actively promoted. New users receive 2 welcome credits instead. See [User Feedback for Credits](#user-feedback-for-credits) for the current feedback-for-credits mechanism.
### Enroll as Beta Tester
@@ -556,7 +605,7 @@ Content-Type: application/json
Returns 1 free credit and session token.
### Submit Feedback
### Submit Beta Feedback
```http
POST /api/users/beta/feedback
@@ -575,6 +624,56 @@ Content-Type: application/json
Bonus credit for detailed feedback (50+ chars).
### User Feedback for Credits
Available to all users (not just beta testers). Users who have completed 2+ jobs can submit feedback to earn 2 free credits.
#### Check Eligibility
```http
GET /api/users/feedback/eligibility
Authorization: Bearer SESSION_TOKEN
```
Response:
```json
{
"eligible": true,
"has_submitted": false,
"jobs_completed": 3,
"credits_reward": 2
}
```
#### Submit Feedback
```http
POST /api/users/feedback
Authorization: Bearer SESSION_TOKEN
Content-Type: application/json
{
"overall_rating": 4,
"ease_of_use_rating": 5,
"lyrics_accuracy_rating": 4,
"correction_experience_rating": 3,
"what_went_well": "The lyrics sync was really accurate...",
"what_could_improve": "Would love more theme options...",
"additional_comments": "",
"would_recommend": true,
"would_use_again": true
}
```
Requirements:
- User must have completed 2+ jobs
- At least one text field must have >50 characters
- User can only submit once (duplicate prevention)
Grants 2 credits on success. Feedback stored in `user_feedback` Firestore collection.
The `/api/users/me` response includes `feedback_eligible: bool` so the frontend can show/hide feedback prompts without an extra API call.
## Admin Endpoints
All admin endpoints require an admin-role session token.
@@ -980,7 +1079,7 @@ Allowed target states:
**Note**: With the combined review flow, `awaiting_instrumental_selection` is no longer a valid reset target for new jobs. Use `awaiting_review` instead to re-select the instrumental.
The `instrumental_selected` state is useful for re-encoding and re-distributing a job after using "Delete Outputs":
1. Delete outputs → Removes YouTube/Dropbox/GDrive files, frees brand code
1. Delete outputs → Removes YouTube/Dropbox/GDrive files, recycles brand code
2. Reset to `instrumental_selected` → Clears video state, keeps settings, auto-triggers video worker
3. Job re-processes with same instrumental, lyrics, and distribution settings
@@ -1205,7 +1304,7 @@ POST /api/admin/jobs/{job_id}/delete-outputs
Authorization: Bearer ADMIN_TOKEN
```
Deletes all distributed outputs (YouTube, Dropbox, Google Drive) for a job while preserving the job record. Use this to fix quality issues: delete outputs, reset to `awaiting_review`, correct lyrics, and re-process.
Deletes all distributed outputs (YouTube, Dropbox, Google Drive) for a job and recycles the brand code. The job record is preserved. Use this to fix quality issues: delete outputs, reset to `awaiting_review`, correct lyrics, and re-process.
Requirements:
- Job must be in terminal state (`complete`, `prep_complete`, `failed`, or `cancelled`)
@@ -1220,7 +1319,8 @@ Response:
"deleted_services": {
"youtube": {"status": "success", "video_id": "dQw4w9WgXcQ"},
"dropbox": {"status": "success", "path": "/Karaoke/NOMAD-1234 - Artist - Title"},
"gdrive": {"status": "success", "files": {"mp4": true, "mp4_720p": true}}
"gdrive": {"status": "success", "files": {"mp4": true, "mp4_720p": true}},
"brand_code": {"status": "recycled", "code": "NOMAD-1234"}
},
"cleared_state_data": ["youtube_url", "brand_code", "dropbox_link", "gdrive_files"],
"outputs_deleted_at": "2026-01-10T12:00:00Z"
@@ -1229,7 +1329,7 @@ Response:
Service statuses: `success`, `failed`, `skipped` (not configured or no data), `partial` (some files failed), `error` (exception).
The brand code is freed for reuse when the Dropbox folder is deleted. When the job is re-processed and outputs are re-uploaded, the `outputs_deleted_at` flag is automatically cleared.
The brand code is automatically recycled after both Dropbox and GDrive cleanup succeed. If either cleanup fails, the brand code is preserved to prevent collisions. Brand code recycling status is returned in `deleted_services.brand_code`. The `DELETE /api/jobs/{id}` endpoint also recycles brand codes before deletion. When the job is re-processed and outputs are re-uploaded, the `outputs_deleted_at` flag is automatically cleared.
#### Clear Worker Progress
+4 -1
View File
@@ -119,6 +119,8 @@ jobs/{job_id}/
├── lyrics/
│ ├── corrections.json # Auto-corrected
│ ├── corrections_updated.json # After human review
│ ├── edit_log_{session}.json # User edit log with feedback
│ ├── annotations.json # Correction annotations
│ └── karaoke.ass
├── screens/
│ ├── title.mov
@@ -180,7 +182,8 @@ karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses
| `jobs/{job_id}/logs` | Worker log entries (subcollection) | timestamp, level, worker, message, ttl_expiry |
| `sessions` | Magic link auth sessions | user_email, token, expires_at |
| `magic_links` | Passwordless auth tokens | email, token, expires_at, used |
| `beta_feedback` | Beta program feedback | user_email, ratings, comments |
| `user_feedback` | User feedback for credits (all users) | user_email, ratings, comments, created_at |
| `beta_feedback` | Beta program feedback (deprecated) | user_email, ratings, comments |
**Note**: The `users` collection in the same Firestore instance belongs to karaoke-decide (different schema: user_id, is_guest, quiz_* fields). Don't use it for karaoke-gen.
+7 -8
View File
@@ -36,12 +36,13 @@
- [ ] Click "Search" or equivalent button
- [ ] Wait for search results to appear in the UI
### 3. Audio Selection (UI Only)
### 3. Audio Selection & Customization (UI Only)
- [ ] Audio selection dialog/panel should appear
- [ ] View available audio options in the UI
- [ ] Click to select the first/best audio option
- [ ] Confirm the selection via UI button
- [ ] **Enable private mode** (check the `#guided-private` checkbox) — test jobs use `NOMADNP` prefix to avoid consuming public `NOMAD` brand codes and skip GDrive/YouTube uploads
- [ ] Wait for job to transition to processing state
### 4. Wait for Lyrics Transcription
@@ -93,14 +94,12 @@
> **CRITICAL**: Test MUST clean up after itself to avoid polluting production distribution channels
- [ ] Verify job.state_data contains distribution results:
- [ ] `brand_code` - The generated brand code (e.g., "NOMAD-1234")
- [ ] `youtube_url` - YouTube video URL (if YouTube enabled)
- [ ] `brand_code` - The generated brand code (e.g., `NOMADNP-0042` for private mode)
- [ ] `dropbox_link` - Dropbox shared link (if Dropbox enabled)
- [ ] `gdrive_files` - Google Drive file IDs (if GDrive enabled)
- [ ] **CLEANUP** - After verification, delete all distributed content:
- [ ] Delete YouTube video via API (using stored youtube_url)
- [ ] Delete Dropbox folder via API (using brand_code + dropbox_path)
- [ ] Delete Google Drive files via API (using gdrive_files IDs)
- [ ] YouTube and GDrive should NOT be present (private mode skips them)
- [ ] **CLEANUP** - After verification, clean up via `cleanup-distribution` endpoint:
- [ ] Deletes Dropbox folder and recycles brand code
- [ ] YouTube/GDrive cleanup skipped for private jobs
- [ ] Delete the test job from the system (GCS + Firestore)
## Technical Requirements
+212
View File
@@ -0,0 +1,212 @@
# Google Drive Validator
Automated validation of the Nomad Karaoke public Google Drive share folder. Detects duplicate brand codes, invalid filenames, and sequence gaps.
## Overview
The public share folder (`1laRKAyxo0v817SstfM5XkpbWiNKNAMSX`) contains all published karaoke tracks organized into subfolders:
```
Public Share/
CDG/ # .zip files (MP3 + CDG for KJ players)
MP4/ # .mp4 files (4K lossless)
MP4-720p/ # .mp4 files (720p lossy)
```
Each file follows the naming convention: `NOMAD-XXXX - Artist - Title.(mp4|zip)`
The validator checks:
- **Duplicate sequence numbers** - e.g., two files both named `NOMAD-1271`
- **Invalid filenames** - files that don't match the expected pattern
- **Sequence gaps** - missing numbers in the NOMAD-XXXX sequence (with known exclusions)
## Architecture
```
┌────────────────────────┐
│ Cloud Scheduler │
│ (9 PM ET daily) │
└──────────┬─────────────┘
│ OIDC auth
▼
┌──────────────────┐ ┌────────────────────────┐ ┌──────────────┐
│ Backend (post- │ OIDC │ gdrive-validator │ API │ Google Drive │
│ job completion) │─────────→│ Cloud Function (Gen2) │─────────→│ API v3 │
└──────────────────┘ └──────────┬─────────────┘ └──────────────┘
│
┌──────────────────┐ ┌──────┴──────┐
│ gcloud functions │ │ │
│ call (manual) │─────────→ ▼ ▼
└──────────────────┘ ┌───────────┐ ┌────────────┐
│ SendGrid │ │ Pushbullet │
│ (primary) │ │ (fallback) │
└───────────┘ └────────────┘
```
### Trigger Points
| Trigger | When | How |
|---------|------|-----|
| **Daily schedule** | 9:00 PM ET every day | Cloud Scheduler → HTTP POST with OIDC token |
| **Post-job** | After each job uploads to public share | Backend orchestrator → HTTP POST with OIDC token |
| **Manual** | On demand | `python scripts/check_public_share.py` via gcloud CLI |
### Notifications
Notifications are sent via **both** channels (belt + suspenders):
1. **SendGrid email** (primary) - Sent to `gen@nomadkaraoke.com`. Provides a persistent, searchable record.
2. **Pushbullet** (fallback) - Push notification for immediate visibility.
Notifications are sent when:
- Issues are found (always)
- No issues found and `NOTIFY_ON_SUCCESS=true` (daily summary)
- Errors occur during validation
## Files
| File | Purpose |
|------|---------|
| `infrastructure/functions/gdrive_validator/main.py` | Cloud Function source code |
| `infrastructure/functions/gdrive_validator/requirements.txt` | Python dependencies |
| `infrastructure/functions/gdrive_validator/deploy.sh` | Manual deployment script |
| `infrastructure/__main__.py` | Pulumi config (env vars, secrets, IAM) |
| `infrastructure/modules/iam/worker_sas.py` | Service account definition |
| `backend/services/gdrive_validator_client.py` | Backend HTTP client (OIDC auth) |
| `backend/workers/video_worker_orchestrator.py` | Post-job trigger integration |
| `scripts/check_public_share.py` | Local CLI for manual checks |
## Configuration
### Environment Variables (Cloud Function)
| Variable | Value | Description |
|----------|-------|-------------|
| `GDRIVE_FOLDER_ID` | `1laRKAyxo0v817SstfM5XkpbWiNKNAMSX` | Root folder of public share |
| `NOTIFY_ON_SUCCESS` | `true` | Send daily "all clear" summary |
| `EMAIL_TO` | `gen@nomadkaraoke.com` | Email recipient |
| `EMAIL_FROM` | `gen@nomadkaraoke.com` | Email sender |
### Secrets (Cloud Function)
| Secret | Source | Description |
|--------|--------|-------------|
| `SENDGRID_API_KEY` | `sendgrid-api-key:latest` | SendGrid API key for email |
| `PUSHBULLET_API_KEY` | `pushbullet-api-key:latest` | Pushbullet API key for push notifications |
### Secrets (Backend / Cloud Run)
| Secret | Source | Description |
|--------|--------|-------------|
| `GDRIVE_VALIDATOR_URL` | `gdrive-validator-url:latest` | Cloud Function URL for post-job trigger |
### IAM
| Principal | Role | Resource | Purpose |
|-----------|------|----------|---------|
| `gdrive-validator@` SA | `roles/cloudfunctions.invoker` | gdrive-validator function | Self-invoke (Cloud Scheduler) |
| Cloud Scheduler agent | `roles/cloudfunctions.invoker` | gdrive-validator function | Daily trigger |
| `karaoke-backend@` SA | `roles/cloudfunctions.invoker` | gdrive-validator function | Post-job trigger |
| `karaoke-backend@` SA | `roles/run.invoker` | gdrive-validator Cloud Run service | Gen2 function HTTP access |
### Known Gaps
The validator knows about expected sequence gaps (historical missing numbers). These are configured identically in both:
- `infrastructure/functions/gdrive_validator/main.py` (Cloud Function)
- `scripts/validate_and_sync.py` (local script)
When a new gap is discovered intentionally (e.g., a track was removed), update the `KNOWN_GAPS` dict in **both** files.
## Usage
### Manual Check
```bash
# Formatted output
python scripts/check_public_share.py
# Raw JSON
python scripts/check_public_share.py --json
```
Exit codes: `0` = all clear, `1` = issues found, `2` = error.
### Checking Cloud Function Logs
```bash
gcloud functions logs read gdrive-validator --region=us-central1 --project=nomadkaraoke --limit=50
```
### Redeploying the Cloud Function
The Cloud Function source is not deployed via CI — it's deployed either:
1. **Via Pulumi** (infrastructure changes like env vars, secrets, IAM)
2. **Via `deploy.sh`** (code changes to `main.py`)
```bash
cd infrastructure/functions/gdrive_validator
./deploy.sh
```
Note: `deploy.sh` deploys the source code. Pulumi manages the infrastructure (env vars, secrets, IAM, scheduler). After running `deploy.sh`, the Pulumi-managed config is overwritten by the gcloud deploy — run `pulumi up` afterward if you need to restore Pulumi-managed settings.
## Troubleshooting
### Email Not Received
1. Check Cloud Function logs for SendGrid errors:
```bash
gcloud functions logs read gdrive-validator --region=us-central1 --limit=20
```
2. Verify the SendGrid API key is set:
```bash
gcloud secrets versions access latest --secret=sendgrid-api-key --project=nomadkaraoke | head -c 10
```
3. Check SendGrid dashboard for delivery status
4. Pushbullet should still work as fallback
### Post-Job Trigger Not Firing
1. Check that `GDRIVE_VALIDATOR_URL` secret is set:
```bash
gcloud secrets versions access latest --secret=gdrive-validator-url --project=nomadkaraoke
```
2. Check backend logs for the job — look for "Triggering post-job GDrive validation" or "GDrive validation trigger failed"
3. Verify the backend SA has invoker permissions:
```bash
gcloud functions get-iam-policy gdrive-validator --region=us-central1 --project=nomadkaraoke
```
4. The trigger only fires for non-private jobs (jobs with `gdrive_folder_id` set)
### False Positive Gaps
If the validator reports gaps that are intentional:
1. Add the gap number(s) to `KNOWN_GAPS` in both `main.py` and `scripts/validate_and_sync.py`
2. Redeploy the cloud function with `./deploy.sh`
### Duplicate Brand Code Detected
This is the most critical alert. Steps:
1. Check which files have the duplicate: the notification lists them
2. Determine which is correct (check Firestore job records)
3. Remove or rename the incorrect file in Google Drive
4. Re-trigger validation to confirm the fix
## Cloud Function vs Local Script
| Check | Cloud Function | Local Script (`validate_and_sync.py`) |
|-------|---------------|--------------------------------------|
| Duplicate sequence numbers | Yes | Yes |
| Invalid filenames | Yes | Yes |
| Sequence gaps | Yes | Yes |
| ZIP contents (MP3+CDG) | No (expensive) | Yes |
| Video resolution | No (expensive) | Yes |
| Render quality | No (expensive) | Yes |
| Bidirectional sync | No (read-only) | Yes (rclone) |
The cloud function does metadata-only checks via the GDrive API (fast, cheap, can run frequently). The local script does deep content validation that requires downloading files (slow, run manually).
## History
- **2025-12-24**: Initial cloud function deployed with Pushbullet notifications and daily Cloud Scheduler trigger
- **2026-02-28**: Added SendGrid email (primary), kept Pushbullet (fallback). Added post-job trigger from backend. Added `scripts/check_public_share.py` for manual invocation. Motivated by NOMAD-1271 duplicate brand code incident where daily-only checks left a duplicate undetected for ~24 hours.
+45
View File
@@ -6,6 +6,16 @@ Key insights for future AI agents working on this codebase.
---
## UX Patterns
### Fixture-Driven UI Verification
For UI that renders differently based on data (e.g., audio search result tiers), fetch real production data as fixtures and build a Playwright review tool. The `npm run fixtures:review-ui` pattern (41 fixtures, console-based `next()` advancement) was far more effective than manual testing or screenshots — caught edge cases with non-Latin filenames, single-character filenames, and underscore-separated names that unit tests alone would have missed.
### Filename Matching Normalization
When comparing filenames to search titles, treat underscores/hyphens/dots as word separators BEFORE stripping non-alphanumeric chars. Also require a minimum substring length (3 chars) to prevent false matches like filename "K" matching title "KoREH". For non-Latin scripts (Hebrew, etc.), return an indeterminate result rather than a false match or false mismatch.
---
## Architecture Decisions
### Separate Collections for Multi-App Projects
@@ -30,6 +40,17 @@ When two sequential human review steps can be combined into one, do it. We origi
## Common Gotchas
### Gate Resource Recycling on Full Cleanup Confirmation (Feb 2026)
**What happened**: Brand code NOMAD-1271 was recycled and reused for a real song while old E2E test job files still existed in Google Drive, creating a duplicate in the public share.
**Root causes**:
1. `if gdrive_files:` skips cleanup when `gdrive_files = {}` (empty dict is falsy) — any falsy check on a collection will silently skip work
2. Brand code recycled after Dropbox cleanup success, *before* confirming GDrive was clean — partial cleanup allowed resource reuse with orphaned files
**Fix**: Use `if gdrive_files is not None` (or check explicitly). Gate resource recycling on **all** cleanup steps succeeding, not just the first one. When a resource has been distributed to N places, it's only safe to recycle when all N locations are confirmed clean.
**Pattern**: Treat resource IDs (brand codes, sequential IDs) like distributed transactions — either all distribution points are cleaned, or the ID stays reserved.
### Fail Fast, Don't Fall Back
Silent fallbacks hide configuration errors. When critical configuration is missing (themes, credentials, etc.), raise clear errors instead of falling back to defaults. Better to fail loudly during testing than silently produce incorrect output in production. Example: Theme validation (v0.109.0) now raises `ValueError` on incomplete themes instead of merging with defaults. This ensures all cloud jobs use complete, explicit themes with no silent degradation.
@@ -58,6 +79,15 @@ When multiple code paths create jobs (file upload, audio search, webhooks), use
**Pattern**: When a function can fail, prefer exceptions over boolean returns. Silent failures accumulate into production bugs. Use centralized helpers for multi-step operations (state change + side effects) to prevent divergent implementations.
### Validate Pipeline Stage Outputs Before Proceeding (Feb 2026)
**What happened**: Jobs 5b6aba25 and 5161b069 completed with `enable_cdg=True` but no CDG ZIP was produced. The orchestrator silently caught a `FileNotFoundError` during CDG generation and proceeded to 11+ minutes of GPU encoding, distribution, and notifications — all for an incomplete output.
**Root cause**: CDG generation failed because `instrumental_selection: custom` had no case in the filename construction (fell through to "Backing" suffix). The `FileNotFoundError` was caught by a broad `except Exception` that just logged and continued, since "CDG is optional."
**Fix**: Add validation gates between pipeline stages. After packaging completes but before expensive encoding begins, verify that all enabled outputs were actually produced. If `enable_cdg=True` but no CDG ZIP exists, raise `RuntimeError` immediately. This fails fast, saves encoding costs, and makes the error visible.
**Pattern**: When a pipeline stage produces optional outputs that were explicitly requested, validate their existence before proceeding to the next stage. "Optional" means "can be disabled," not "can silently fail when enabled."
### Fix Both Sides of Dual Code Paths
When fixing a bug in a system with multiple code paths (e.g., legacy vs orchestrator, local vs cloud), verify ALL paths are fixed. PR #271 fixed the GCE worker to READ `instrumental_selection` but only checked the legacy path which was already SENDING it. The orchestrator path (production default) wasn't sending it. **Pattern**: If a component receives config from multiple callers, check ALL callers when fixing the receiving side. Write integration tests that cover each path.
@@ -213,6 +243,18 @@ When deferring processing from one worker to another, you MUST update the job st
### Google Drive Query Escaping
Escape special chars in Google Drive API queries: `'` → `\'`, `\` → `\\\\`.
### Google Drive Stale Connection on Cloud Run (Feb 2026)
**What happened**: Every GDrive upload silently failed for ~1 month (64 errors, 12+ jobs). Errors: `[Errno 32] Broken pipe` or `[SSL: UNEXPECTED_EOF_WHILE_READING]`. Jobs completed with `gdrive_files: {}` and no alert was sent.
**Root cause**: The singleton `GoogleDriveService` caches its HTTP connection. When Cloud Run containers sit idle between jobs, the underlying TCP connection goes stale. The next API call hits a dead socket. The orchestrator catches all exceptions in distribution and continues silently.
**Fix** (v0.119.7):
1. Added tenacity retry with `_reset_service()` (sets `self._service = None` to force fresh connection) on transient errors (`BrokenPipeError`, `ConnectionResetError`, `ssl.SSLError`)
2. Added `distribution_warnings` field to `OrchestratorResult` to track non-fatal upload failures
3. Added Pushbullet notification when distribution uploads fail, so operator is alerted immediately
**Pattern**: Any singleton service that caches HTTP connections should have retry logic with connection reset for stale connection errors. Cloud Run containers can idle for minutes between requests, killing keep-alive connections. Also, never silently swallow distribution failures - always track and alert on them.
### FFmpeg Path Escaping
For subprocess without shell, FFmpeg filter paths need: apostrophes escaped as `'\\''`, special chars as `\\[char]`.
@@ -637,6 +679,9 @@ Langfuse v3 is built on OpenTelemetry. If `CallbackHandler()` is created without
### Cold Start Mitigation
Set `min-instances > 0` for Cloud Run services with heavy initialization.
### Never Call sync-over-async from FastAPI async Routes (Feb 2026)
Sync methods that internally create new event loops (`asyncio.new_event_loop()` + `loop.run_until_complete()`) will **block the FastAPI event loop** when called from `async def` routes or background tasks. The response body gets queued but never flushed because the blocked loop can't process I/O — causing 20-36s endpoint latency instead of <1s. **Fix**: Either (a) call the underlying async client directly with `await` (preferred — e.g., `await flacfetch_client.download_by_id()`), or (b) wrap sync calls in `await asyncio.to_thread()` / `loop.run_in_executor()` to run them in a thread pool. The `nest_asyncio` library is NOT a reliable workaround — it patches CPython internals and can cause deadlocks. See `audio_search.py` and `youtube_download_service.py` for the correct async patterns.
---
## Data & Storage
+5 -5
View File
@@ -59,12 +59,12 @@ Guidelines for how to communicate about Nomad Karaoke to users, in marketing mat
---
## Beta Tester Program
## Free Credits
- Beta testers get up to 5 free karaoke video generations
- Mandatory feedback required after each video
- Must acknowledge they'll review/correct lyrics transcription
- Helps improve the system through real-world testing
- All new accounts receive 2 free credits to try the service
- No payment required to get started
- Credits never expire
- Additional credits available for purchase ($5/credit, bulk discounts available)
---
+14 -4
View File
@@ -5,9 +5,9 @@
## What Works
- **Web App**: https://gen.nomadkaraoke.com
- `/` - Landing page with pricing and beta enrollment
- `/` - Landing page with pricing
- `/app` - Main app (upload audio, review lyrics, download videos)
- `/admin` - Admin dashboard (user management, job monitoring, beta program)
- `/admin` - Admin dashboard (user management, job monitoring)
- **Backend API**: https://api.nomadkaraoke.com - FastAPI on Cloud Run
- **CLI Tools**: `karaoke-gen` (local), `karaoke-gen-remote` (cloud)
@@ -24,7 +24,7 @@
| Token-based auth | Working |
| Magic link auth | Working |
| Payment flow (Stripe) | Working |
| Beta tester program | Working |
| Feedback-for-credits | Working (2+ jobs → 2 free credits) |
| Admin dashboard | Working |
| Rate limiting & abuse prevention | Working |
| CI/CD self-hosted runner | Working (GCP) |
@@ -34,7 +34,7 @@
## Known Issues
- CDG format generation requires additional style configuration
(No known issues)
## Pending Work
@@ -42,6 +42,16 @@
## Recent Changes
- **Feedback-for-Credits** (2026-03-01): Added a feedback-for-credits mechanism available to all users (replaces the old beta-only feedback flow). Users who complete 2+ karaoke videos can submit product feedback (star ratings + text) to earn 2 free credits (total possible free credits: 4 — 2 welcome + 2 feedback). New endpoints: `GET /api/users/feedback/eligibility`, `POST /api/users/feedback`. The `/api/users/me` response includes `feedback_eligible: bool` so the frontend can show/hide prompts without an extra API call. Frontend shows a dismissible banner on the dashboard and a "Earn 2 Free Credits" menu item in the user dropdown when eligible. Feedback stored in `user_feedback` Firestore collection with duplicate prevention via `has_submitted_feedback` flag on user model. Welcome email updated with credit-focused messaging and feedback teaser. See [API.md](API.md#user-feedback-for-credits).
- **Remove Beta Program from Homepage** (2026-03-01): Removed beta enrollment from landing page and replaced with prominent "2 Free Credits" messaging. Beta enrollment endpoint preserved for backward compatibility but no longer actively promoted. See PR #430.
- **Fix Event Loop Blocking in Audio Search Endpoints** (2026-02-28): Fixed `/api/audio-search/{job_id}/select` taking 20-36s to respond (should be <1s) and `/api/audio-search/search` sometimes taking 25-47s. **Root cause**: Async endpoints called sync methods that create new event loops via `loop.run_until_complete()`, blocking the FastAPI event loop — response body was queued but never flushed. **Fix**: RED/OPS and Spotify download paths now call `FlacfetchClient` async methods directly (matching `YouTubeDownloadService` pattern), generic downloads use `asyncio.to_thread()`, search endpoint uses `search_async()`. Also fixed `InsufficientCreditsError` occasionally returning 500 instead of 402 by using `isinstance()` check. Added 14 new tests. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#never-call-sync-over-async-from-fastapi-async-routes-feb-2026).
- **GDrive Cleanup Robustness + Brand Code Race Fix** (2026-02-27): Fixed duplicate brand codes appearing in the public Google Drive share after the daily E2E test (NOMAD-1271 appearing for both the test job "piri - dog" and real song "Hot Mulligan - Pop Shuvit"). **Root causes**: (1) `if gdrive_files:` was falsy for empty dict `{}` — when GDrive upload silently failed (pre-PR #417), the entire GDrive cleanup block was skipped, (2) Brand code was recycled immediately after Dropbox cleanup succeeded, without confirming GDrive was also clean — a new job could claim the recycled code while old GDrive files still existed. **Fixes**: Added `find_files_by_brand_code()` fallback to `GoogleDriveService` that searches CDG/MP4/MP4-720p subfolders by brand code prefix when tracked file IDs aren't available. `cleanup-distribution` endpoint now: (a) uses tracked file IDs (fast path) or falls back to brand_code search, (b) only recycles the brand code after **both** Dropbox AND GDrive are confirmed clean. Added `scripts/cleanup_test_job_gdrive.py` remediation script. Added 14 new tests (94% coverage on gdrive_service.py).
- **CDG Packaging Fail-Fast Validation** (2026-02-27): Fixed silent CDG generation failures where jobs completed with `enable_cdg=True` but no CDG ZIP was produced. **Root cause**: Jobs 5b6aba25 and 5161b069 had `instrumental_selection: custom` but before commit b671b83f, the orchestrator had no `custom` case — it fell through to `"Backing"` suffix. The CDG generator then hit a `FileNotFoundError` looking for the wrong filename, which was silently caught. **Fix**: (1) Orchestrator now validates CDG/TXT outputs after packaging stage and before encoding — if `enable_cdg=True` but no CDG ZIP was produced, the pipeline fails fast instead of silently continuing to expensive encoding, (2) Missing LRC file now raises when CDG/TXT is enabled instead of silently skipping, (3) Added `scripts/regenerate_cdg.py` remediation script for affected jobs. Removed "CDG requires additional style configuration" known issue (the nomad theme has complete CDG styles). Added 7 new tests for validation logic.
- **GCE Encoding Pipeline Resilience** (2026-02-26): Made encoding pipeline resilient to Cloud Run deployment interruptions. A deployment killed a poller mid-encoding, leaving job a03ad39c permanently stuck at `encoding` status. Three fixes: (1) GCE worker `/encode` endpoint now idempotent — returns cached results for completed jobs, allows retry on failure, returns status for in-progress (previously hard 409 reject), (2) `encoding_service.py` handles cached/in_progress responses and falls back to status check on 409, (3) Health service detects jobs stuck in `encoding` >50 min. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#resilient-remote-worker-interactions-feb-2026).
- **Private (Non-Published) Tracks** (2026-02-24): Added `is_private` flag on jobs for private/non-published track production. Private jobs upload to Dropbox `Tracks-NonPublished` folder with `NOMADNP` brand prefix, skip YouTube and Google Drive entirely, and send completion emails without the YouTube section. Available as a checkbox on all job creation tabs and as an admin toggle (auto-deletes outputs when toggling a completed job to private). See [archive/2026-02-24-private-tracks-plan.md](archive/2026-02-24-private-tracks-plan.md).
+94
View File
@@ -0,0 +1,94 @@
# Troubleshooting
Operational runbooks for known production issues.
---
## Job stuck at `encoding` status
**Cause:** A Cloud Run deployment killed the poller mid-encoding. The GCE worker finished but nobody received the result. The health service will flag this as `encoding_stuck` after 50 minutes.
**Recovery:**
```bash
# 1. Confirm the job is flagged
curl -s "https://api.nomadkaraoke.com/api/health/job-consistency" \
-H "X-Admin-Token: $(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke)" \
| python3 -m json.tool | grep -A3 "encoding_stuck"
# 2. Check what the GCE worker knows about the job
WORKER_URL=$(gcloud secrets versions access latest --secret=encoding-worker-url --project=nomadkaraoke)
WORKER_KEY=$(gcloud secrets versions access latest --secret=encoding-worker-api-key --project=nomadkaraoke)
curl -s "$WORKER_URL/status/YOUR_JOB_ID" -H "X-API-Key: $WORKER_KEY" | python3 -m json.tool
# 3. Re-trigger the video worker — it will pick up the cached GCE result if encoding
# already finished, or rejoin the poll if it's still running
curl -X POST "https://api.nomadkaraoke.com/api/internal/workers/video" \
-H "X-Admin-Token: $(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke)" \
-H "Content-Type: application/json" \
-d '{"job_id": "YOUR_JOB_ID"}'
```
**Note:** SSH-restarting the encoding worker is **not needed** since v0.119.6 (PR #413). The `/encode` endpoint is now idempotent — re-triggering the video worker is sufficient.
---
## CDG/TXT packages missing from completed job
**Cause:** Before v0.119.7, CDG/TXT generation failures were silently caught. Jobs would complete with `enable_cdg=True` but no CDG ZIP in outputs. Fixed in v0.119.7 with fail-fast validation — new jobs will now fail loudly if CDG/TXT generation fails.
**Recovery** (for jobs that already completed without CDG/TXT):
```bash
# Regenerate and distribute CDG/TXT packages for specific jobs
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
python -m scripts.regenerate_cdg JOB_ID [JOB_ID ...]
# Example:
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
python -m scripts.regenerate_cdg 5b6aba25 5161b069
```
The script is idempotent — re-running it skips regeneration if the CDG ZIP already exists in GCS and proceeds to any missing distribution steps (GDrive, Dropbox).
---
## GCE encoding worker on wrong wheel version
**Cause:** Worker picks up a new deploy but doesn't restart automatically.
```bash
# Check current wheel version
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
--command="curl -s http://localhost:8080/health | python3 -m json.tool"
# Restart to pick up latest wheel
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
--command="sudo systemctl restart encoding-worker"
```
---
## Google Drive uploads missing (gdrive_files empty)
**Symptoms:** Jobs complete successfully but `state_data.gdrive_files` is empty `{}`. Cloud Run logs show `BrokenPipeError` or `SSL: UNEXPECTED_EOF_WHILE_READING`.
**Cause:** Stale HTTP connections in the singleton `GoogleDriveService`. Since v0.119.7, this is handled automatically with retry + connection reset.
**Backfill affected jobs:**
```bash
# Dry run - list affected jobs
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
python scripts/backfill_gdrive_uploads.py --all-missing --dry-run
# Run for real
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
python scripts/backfill_gdrive_uploads.py --all-missing
# Specific jobs
python scripts/backfill_gdrive_uploads.py --job-ids JOB1,JOB2
```
@@ -0,0 +1,109 @@
# GDrive Validator: Email Alerts, Manual Trigger, Post-Job Check
## Context
The GDrive validator cloud function checks the public Google Drive share for duplicate brand codes, invalid filenames, and sequence gaps. Currently it:
- Runs once daily at 9 PM Eastern via Cloud Scheduler
- Sends results via Pushbullet (easy to miss, no persistent record)
- Cannot be easily triggered manually
- Doesn't run after each job, so issues can persist for up to 24 hours before detection
The recent NOMAD-1271 duplicate brand code incident showed that daily checks aren't frequent enough — the duplicate existed for at least a day before manual discovery.
## Changes
### 1. Cloud Function: Replace Pushbullet with Email (SendGrid)
**File:** `infrastructure/functions/gdrive_validator/main.py`
- Replace `send_pushbullet_notification()` with `send_email_notification()` using SendGrid API
- SendGrid API key already in Secret Manager as `sendgrid-api-key`
- Send from `gen@nomadkaraoke.com` to `gen@nomadkaraoke.com`
- Keep Pushbullet as a secondary fallback (both are cheap; belt + suspenders)
- Add `SENDGRID_API_KEY` env var to the function
**File:** `infrastructure/functions/gdrive_validator/requirements.txt`
- Add `sendgrid>=6.0.0`
**File:** `infrastructure/__main__.py`
- Add `sendgrid-api-key` secret to the function's `secret_environment_variables`
- Add `EMAIL_TO` env var = `gen@nomadkaraoke.com`
**File:** `infrastructure/functions/gdrive_validator/deploy.sh`
- Add `--set-secrets` entry for `SENDGRID_API_KEY=sendgrid-api-key:latest`
- Add `--set-env-vars` entry for `EMAIL_TO=gen@nomadkaraoke.com`
### 2. Local Command: `check_public_share`
**File:** `scripts/check_public_share.py`
- Calls the Cloud Function via `gcloud functions call gdrive-validator --region=us-central1`
- Parses the JSON response and prints formatted results to terminal
- Exit code 0 = all clear, 1 = issues found, 2 = error
- Supports `--json` flag for raw JSON output
### 3. Post-Job Trigger from Backend
**File:** `backend/services/gdrive_validator_client.py` (new)
- Lightweight client that calls the Cloud Function via HTTP with OIDC token
- Uses `google.oauth2.id_token.fetch_id_token()` for authentication
- Fire-and-forget pattern (never blocks or fails the job)
- Logs the response but does not raise on validation issues (just notifies)
**File:** `backend/workers/video_worker_orchestrator.py`
- After `_run_notifications()` (line ~253), add a new call: `await self._trigger_gdrive_validation()`
- Only triggers for non-private, non-test jobs (private jobs don't upload to public share)
- Wrapped in try/except so validation failure never blocks job completion
**File:** `infrastructure/__main__.py`
- Add IAM binding: grant `karaoke-backend` service account `roles/cloudfunctions.invoker` on the gdrive-validator function
- For Gen2 functions also need `roles/run.invoker` on the underlying Cloud Run service
**File:** `infrastructure/modules/iam/backend_sa.py`
- Add the Cloud Functions invoker permission
### 4. Pulumi Infrastructure Updates
All IAM and secret changes go through `infrastructure/__main__.py` — deployed automatically on merge to main.
## Comparison: Local Script vs Cloud Function
| Check | Local Script | Cloud Function |
|-------|-------------|----------------|
| Duplicate sequence numbers | ✅ | ✅ |
| Invalid filenames | ✅ | ✅ |
| Sequence gaps (with known gaps) | ✅ | ✅ |
| Known gaps config | ✅ (identical) | ✅ (identical) |
| ZIP contents (MP3+CDG) | ✅ | ❌ (expensive, needs file download) |
| Video resolution (4K/720p) | ✅ | ❌ (expensive, needs file download) |
| Render quality (pixel check) | ✅ | ❌ (expensive, needs ffmpeg) |
| Bidirectional sync | ✅ (rclone) | ❌ (read-only) |
The cloud function correctly implements the "quick/cheap" checks (metadata-only via GDrive API). The expensive content checks (ZIP, resolution, pixel) belong in the local script since they require downloading files. No changes needed to align them.
## Files Modified
| File | Change |
|------|--------|
| `infrastructure/functions/gdrive_validator/main.py` | Add SendGrid email, keep Pushbullet as fallback |
| `infrastructure/functions/gdrive_validator/requirements.txt` | Add `sendgrid` |
| `infrastructure/functions/gdrive_validator/deploy.sh` | Add SendGrid secret + EMAIL_TO env var |
| `infrastructure/__main__.py` | Add SendGrid secret to function, add backend invoker IAM |
| `backend/services/gdrive_validator_client.py` | New: HTTP client to invoke cloud function |
| `backend/workers/video_worker_orchestrator.py` | Add post-distribution GDrive validation trigger |
| `scripts/check_public_share.py` | New: local command to trigger cloud function |
## Verification
1. Deploy cloud function with `./deploy.sh`
2. Run `python scripts/check_public_share.py` — should print formatted results and receive email at gen@nomadkaraoke.com
3. Trigger a test job or wait for the daily E2E test — after job completes, check Cloud Function logs to confirm it was invoked
4. Check gen@nomadkaraoke.com inbox for the validation email
5. Run `make test` to verify no regressions
@@ -0,0 +1,75 @@
# UX Overhaul - Master Plan
> **Status**: Phases 1-3 complete, Phase 4 remaining
> **Created**: 2026-02-28
> **Branch**: feat/sess-20260227-1637-ux-overhaul
> **Worktree**: /Users/andrew/Projects/nomadkaraoke/karaoke-gen-ux-overhaul
## Overview
The karaoke generation platform was built for personal/power-user use. New users lack guidance at each stage of the multi-step process. This UX overhaul will improve guidance, simplify choices, and steer users toward the best outcomes.
## Phased Approach
The system has several distinct stages of human interaction, each requiring dedicated UX thought. We're breaking this into phases, with a detailed plan for each phase created through live UI walkthrough with screenshots and user feedback.
### Phase 1: Job Creation & Audio Input ✅
**Plan**: [2026-02-28-ux-phase1-job-creation.md](2026-02-28-ux-phase1-job-creation.md)
**Implementation**: [2026-02-28-ux-phase1-implementation.md](2026-02-28-ux-phase1-implementation.md)
**Scope**: Restructure the job creation form as a guided flow. Steer users toward Search as the default path, with Upload/URL as fallbacks.
**Done**: Removed "Skip lyrics review" checkbox, renamed Private label, built 3-step GuidedJobFlow wizard, title card preview, production E2E tests. Renamed "Find Audio" → "Choose Audio".
### Phase 2: Audio Source Selection ✅
**Plan**: [2026-02-28-ux-phase2-audio-selection.md](2026-02-28-ux-phase2-audio-selection.md)
**Scope**: Auto-select audio for simple cases, improve guidance for complex cases, build heuristics from real usage data.
**Done**: 3-tier confidence system (perfect match / recommended / limited sources), guidance-first layout for Tier 3, validated against 41 production fixtures with unit tests.
### Phase 3: Lyrics Review ✅
**Plan**: [2026-02-28-ux-phase3-lyrics-review.md](2026-02-28-ux-phase3-lyrics-review.md)
**Scope**: Add onboarding, explain color coding, guide users through the correction workflow. This is the most complex screen.
**Done**: Guidance panel replacing stats bar (collapsible, color coding legend, workflow tips), gap navigator with keyboard shortcuts (J/K), simplified toolbar with Advanced Mode toggle, hidden line numbers/delete icons by default, edit tracking system with low-friction feedback bar for transcription improvement data collection. 40 tests.
### Phase 4: Instrumental Review ← REMAINING
**Plan**: [2026-02-28-ux-phase4-instrumental-review.md](2026-02-28-ux-phase4-instrumental-review.md)
**Scope**: Explain what backing vocals are, guide the listen/decide flow, simplify the default case.
## Cross-Cutting Concerns
- **Remove "Skip lyrics review" checkbox** from UI (keep backend field for API/admin use)
- **Rename "Private (non-published)"** to something clearer like "Private (no YouTube upload)"
- **Auto-select heuristics training** - Pull last ~50 jobs, capture what audio the user would choose and why, codify into algorithm (may be a separate workstream touching flacfetch)
## Screenshots Captured
All screenshots saved in the worktree root during the walkthrough session:
### Phase 1: Job Creation
- `phase1-job-creation-current.png` - Current job creation form
- `phase1-filled-form.png` - Form filled with Coldplay - Parachutes
- `phase1-job-created-awaiting-audio.png` - Job created, awaiting audio selection
### Phase 2: Audio Source Selection
- `phase2-audio-search-results.png` - Audio search results dialog (Coldplay, top)
- `phase2-audio-search-bottom.png` - Audio search results dialog (Coldplay, bottom)
- `phase2-pony-bradshaw-results.png` - Audio search results for obscure track (Pony Bradshaw)
### Phase 3: Lyrics Review (Difficulty Spectrum)
- `phase3-lyrics-review.png` / `phase3-lyrics-review-top.png` - Bon Jovi lyrics review (easy-medium, 94% anchored)
- `phase3-lyrics-review-bottom.png` - Bon Jovi lyrics review (bottom/end of lyrics)
- `phase3-bon-jovi-review.png` - Bon Jovi "It's My Life" (easy-medium: 94% anchored, 9 gaps, 18 words)
- `phase3-silversun-pickups-review.png` - Silversun Pickups (medium: 84% anchored, 8 gaps, 32 words)
- `phase3-steve-taylor-review.png` - Steve Taylor live (hard: 42% anchored, 20 gaps, 194 words, wrong reference lyrics)
- `phase3-preview-dialog.png` - Preview Video dialog (transition from lyrics to instrumental review)
### Phase 4: Instrumental Review
- `phase4-instrumental-review.png` - Instrumental review page (Coldplay - Parachutes, 4% backing vocals, Clean recommended)
## Test Jobs Used
| Track | ID | Difficulty | Stage |
|-------|-----|-----------|-------|
| Coldplay - Parachutes | a95023e8 | Easy | Progressed to instrumental review |
| Bon Jovi - It's My Life | c235f6bd | Easy-Medium | At lyrics review |
| Silversun Pickups - Well Thought Out Twinkles | 41026cfe | Medium | At lyrics review |
| Pony Bradshaw - Jehovah | 3552d63d | Medium | At lyrics review |
| Steve Taylor - Jim Morrisons Grave - Live | ce8f2901 | Hard | At lyrics review |
@@ -0,0 +1,58 @@
# Phase 1: Job Creation UX Overhaul - Implementation Record
Date: 2026-02-28
## What Was Done
### Increment 1: Quick Wins
- Removed "Skip lyrics review (non-interactive)" checkbox from all 3 tabs in `JobSubmission.tsx`
- Renamed "Private (non-published)" to "Private (no YouTube upload)" across all 3 tabs
- Removed `nonInteractive` state variable and `non_interactive` from all submit handler payloads
- Backend `non_interactive` field preserved for CLI/admin API use
### Increment 2: Guided Step Flow
Replaced the tab-based `JobSubmission` with a new `GuidedJobFlow` wizard component.
#### New Files Created
| File | Purpose |
|------|---------|
| `lib/audio-search-utils.ts` | Extracted categorization logic shared between AudioSearchDialog and new flow |
| `components/job/GuidedJobFlow.tsx` | Main orchestrator with step state management |
| `components/job/steps/SongInfoStep.tsx` | Step 1: Artist & Title input |
| `components/job/steps/AudioSourceStep.tsx` | Step 2: Auto-search + fallback upload/URL |
| `components/job/steps/CustomizeStep.tsx` | Step 3: Title card preview + options |
| `components/job/steps/ConfirmStep.tsx` | Step 4: Review & confirm |
| `components/job/TitleCardPreview.tsx` | CSS mockup of title/end screens |
#### Modified Files
| File | Change |
|------|--------|
| `components/job/JobSubmission.tsx` | Quick wins only (kept as reference) |
| `components/audio-search/AudioSearchDialog.tsx` | Refactored to import from shared utils |
| `app/app/page.tsx` | Swapped JobSubmission for GuidedJobFlow |
### Architecture Decisions
1. **Display overrides in Step 1**: The `searchAudio` API sets display_artist/display_title at creation time (not updateable after). So the display override toggle stays in Step 1 as a collapsible section, before the search is triggered.
2. **Privacy setting timing**: For search path, `is_private` is set during the `searchAudio` call in Step 2. Step 3 (Customize) shows the current value but changes there would need a backend `updateJob` call (which supports `is_private`). For upload/URL fallback paths, `is_private` is set at creation time.
3. **Upload/URL skip customize**: When users choose upload or URL fallback in Step 2, they skip directly to Step 4 (Confirm) since the title card preview is less relevant for these paths.
4. **Search polling**: AudioSourceStep polls `getAudioSearchResults` every 2 seconds (max 30 attempts = 60s) while waiting for the backend search to complete.
5. **Error handling**: Backend errors during search show the error message and immediately offer fallback options (Upload file / YouTube URL).
## Visual Testing Results
Screenshots saved in `docs/images/`:
- `phase1-step1-initial.png` - Empty step 1 form
- `phase1-step1-filled.png` - Form with "Queen - Bohemian Rhapsody"
- `phase1-step1-display-override.png` - Display override section expanded
- `phase1-step2-searching.png` - Search loading state with spinner
- `phase1-step2-error-with-fallbacks.png` - Error handling with fallback options
## Test Results
- All 323 Jest tests pass
- Next.js build succeeds with no errors
- Visual testing confirms all Step 1 and Step 2 UI renders correctly
@@ -0,0 +1,93 @@
# Phase 1: Job Creation & Audio Input - UX Plan
> **Status**: Feedback captured, ready for detailed design
> **Screenshots**: `phase1-job-creation-current.png`, `phase1-filled-form.png`
## Current State
The job creation form at `/app` has:
- **Three equal tabs**: Search / Upload / URL - no indication which is preferred or when to use each
- **"Search For Audio Online"** heading with Artist/Title fields
- **Note**: "Format these exactly as you want them on the title card and video filename" - confusing for users who don't know what "title card" means
- **"Use different artist/title for title screen"** - collapsible, but unclear what it does
- **"Skip lyrics review (non-interactive)"** - admin-only but visible, confusing
- **"Private (non-published)"** - useful but wording is unclear
- **"Search & Create Job"** button - creates job AND searches, then user must find the job in Recent Jobs and click "Select Audio" separately (split interaction)
## User Feedback
### Search should be strongly preferred
> "We need to strongly steer users towards trying Search first as it provides high quality lossless audio which makes for a better karaoke track. Ideally they should only use Upload for tracks which aren't commercially/generally available online, and they should only use YouTube if the specific version they want a karaoke track for doesn't come up in the Search results (e.g. if it's a bootleg or specific live version or something indie which is only on YouTube)"
### Title card note is confusing
> "Honestly I'd imagine this is kinda confusing to new users who may not even know what 'title screen' means."
### Restructure as guided flow
> "I'm now wondering if it would be better to restructure it as a series of questions which leads the user to the job creation. That way we could give the user clearer guidance for each step and make the order make sense (e.g. do the audio search first, only fall back to youtube/upload if they couldn't find the exact version in the search results). If we did that the question about whether there should be a different artist/title for the title card could be answered as a separate question in this flow, with a dynamically generated preview image showing roughly what the title card would look like to help the user understand what it is."
### Remove "Skip lyrics review"
> "Honestly I can't even remember why I added 'Skip lyrics review' as an option, we should probably remove that as I don't really think there's ever a legit reason for anyone to use that."
**Investigation result**: Added Dec 25, 2025 as CLI `-y` equivalent, refined to admin-only per-job option Jan 3, 2026 (PR #162). It's an admin/testing power tool that auto-completes review stages. The backend `non_interactive` field should stay for API/admin use, but the checkbox should be removed from the job creation form.
### Rename "Private" option
> "The 'Private' option is definitely useful and important, we can probably make it even easier to understand by changing '(non-published)' to '(no public upload on YouTube)' or something"
## Proposed Design: Guided Step Flow
Replace the current tab-based form with a step-by-step guided flow:
### Step 1: "What song do you want to make a karaoke track for?"
- Artist & Title fields (simple, friendly)
- This is the same regardless of input method
### Step 2: "Find the audio"
- Auto-search runs immediately with the artist/title from Step 1
- Results appear inline (not in a separate modal after job creation)
- "Best Choice" is prominently recommended (or auto-selected - see Phase 2)
- If nothing found or wrong version: "Can't find it? Try a YouTube URL or upload your own audio file"
- Upload and URL become **fallback options**, not equal peers
### Step 3: "How should it look?"
- Title card preview (dynamically rendered) showing roughly what the title/end screens will look like
- Option to override artist/title for display
- Private toggle with clearer label: "Private (no YouTube upload)"
- This step gives context for what "title card" actually means
### Step 4: Confirm & Create
## Key Technical Considerations
### Current flow (split interaction):
```
Form → "Search & Create Job" → Job created in backend → Job appears in Recent Jobs list
→ User clicks "Select Audio" on job card → Modal dialog opens → User picks result → Job progresses
```
### Proposed flow (unified):
```
Step 1 (artist/title) → Step 2 (search results inline, or fallback to upload/URL)
→ Step 3 (title card preview, private toggle) → Step 4 (confirm) → Job created & processing
```
The key complexity: currently the backend creates the job when the search is initiated. The guided flow might need to either:
1. Still create the job early but hide that from the user (keep current backend flow, change frontend presentation)
2. Defer job creation until the user confirms everything (would require backend changes)
Option 1 is probably simpler and lower-risk.
### Components affected:
- `frontend/components/job/JobSubmission.tsx` - Main form (3 tab state objects, submit handlers)
- `frontend/components/audio-search/AudioSearchDialog.tsx` - Currently a modal, would become inline
- `frontend/components/job/JobCard.tsx` - Currently shows "Select Audio" button for awaiting jobs
- `frontend/app/app/page.tsx` - Main dashboard layout (2-column: form + recent jobs)
- `frontend/lib/api.ts` - `searchAudio()`, `getAudioSearchResults()`, `selectAudioResult()`
## Changes to Ship
1. **Remove "Skip lyrics review" checkbox** from all 3 tabs in JobSubmission.tsx (lines 325-348, 447-470, 607-630). Keep backend `non_interactive` field.
2. **Rename "Private (non-published)"** to "Private (no YouTube upload)" or similar
3. **Restructure form** as guided step flow (major change - needs detailed component design)
4. **Title card preview** - dynamically generated preview showing what title screen looks like
5. **Inline audio search results** - move from modal dialog to inline step in guided flow
6. **Fallback positioning** - Upload/URL presented as fallbacks when Search doesn't find the right track
@@ -0,0 +1,136 @@
# Phase 2: Audio Source Selection - UX Plan
> **Status**: Implemented and verified with 41 production fixtures
> **Screenshots**: `phase2-audio-search-results.png`, `phase2-audio-search-bottom.png`, `phase2-pony-bradshaw-results.png`
## Implementation Summary (2026-02-28)
### 3-Tier Confidence System
Built in `frontend/lib/audio-search-utils.ts` and `frontend/components/job/steps/AudioSourceStep.tsx`:
- **Tier 1 ("Perfect match found")**: Green card, best result is lossless with 50+ seeders and no filename mismatch
- **Tier 2 ("Recommended")**: Amber card with reasoning — has lossless options but not clearly ideal
- **Tier 3 ("Limited sources found")**: Guidance-first layout — upload/URL fallback shown above search results
### Key Features
- **Filename mismatch detection**: Compares search title against `target_file` (torrent/Spotify) or `title` (YouTube). Handles underscores as word separators, skips non-Latin scripts gracefully. Shows "Title match" / "Wrong track?" badges.
- **Spotify separated from YouTube**: Own category with green styling, higher priority than YouTube in best-result selection
- **Dynamic guidance tips**: The "Limited sources found" box only shows tips relevant to the actual result types found
- **Color-coded view counts**: Green (1M+), amber (100K+), neutral for YouTube/Spotify results
- **Availability tooltips**: User-friendly language ("may take a bit more time to prepare")
### Testing
- 75 unit tests for `audio-search-utils.ts` (96%+ coverage)
- 47 fixture confidence tests against 41 production search results
- Fixture review tooling: `npm run fixtures:review-ui` for visual verification
- E2E regression tests (25 tests) and production E2E tests (7 tests)
## Current State
The "Select Audio Source" modal dialog shows:
- **Title**: "Select Audio Source v0.119.8 (N results across M categories)"
- **Categories** (up to 9): BEST CHOICE, HI-RES 24-BIT, STUDIO ALBUMS, SINGLES, LIVE VERSIONS, COMPILATIONS, VINYL RIPS, YOUTUBE/LOSSY, OTHER
- Each result shows: index number, quality badges (LOSSLESS, VINYL, YouTube), artist, title, format details, file size, availability badge (High/Medium/Low color-coded), album metadata, target filename
- Each category shows 2-3 results by default with "+N more" expand button
- Each result has a "Select" button
## Problems Identified
### Too much information / too much choice
> "It's just too much information and probably too much choice for most users who just know what song they want a karaoke version of."
### Wrong songs appear in results
- Coldplay "Parachutes" search returned "Everything's Not Lost", "High Speed", "Spies" (other songs from the same album or artist)
- Pony Bradshaw "Jehovah" search returned "Van Gogh", "Josephine" (other songs by same artist)
- The compilation results (#27, #28 for Coldplay) showed filename "Parachutes/03 - Spies.flac" - a different track entirely
- Users need domain knowledge to evaluate these
### Availability badges unexplained
- High (green), Medium (yellow/orange), Low (red) availability badges are shown but never explained
- Users don't know that availability directly affects download success rate
### No guidance on what matters for karaoke
- 24-bit vs 16-bit doesn't matter much for karaoke (vocals get removed anyway)
- Vinyl rips may have surface noise that affects separation quality
- Availability matters more than bit depth for reliability
- Live versions will sound different from studio versions
## User Feedback
### Auto-select for simple cases
> "For those simple/standard users who are making karaoke tracks which have commercially available releases which are easy to download (like this Coldplay example), we should probably just make the choice for the user and only show them this more complex set of alternate options if they explicitly click something to show more advanced options."
### Better guidance for advanced view
> "There's also several gotchas which aren't communicated on this view at all, e.g. the fact that vinyl versions, live versions, or other songs entirely may show up (you have to check the filename makes sense for the song you wanted) so even if we keep this view as an 'advanced' or 'show more options' view in the UX rework, we should add better guidance to it to help users know what to look for."
### Obscure tracks are trickier
For Pony Bradshaw - Jehovah (less popular track):
- No "BEST CHOICE" section appeared
- Only 3 categories: HI-RES 24-BIT (1, Low availability), STUDIO ALBUMS (4, Medium/Low), YOUTUBE/LOSSY (5)
- User's choice: Studio Album #1 (Medium availability, 16bit CD) because "it's the most available (and thus will download the fastest) and 24bit input audio is overkill for karaoke"
### Build auto-select heuristics from real data
> "In order to make the system reliably make a good default choice for the user, we probably ought to run searches for a bunch of input tracks with a variety of popularities (we could just look at the last 50 tracks I've actually made through this karaoke generator as they're already a pretty diverse mix) and for every track, capture what audio I would choose in this 'Select Audio Source' modal AND WHY, then use that reasoning information to build a system which auto-chooses for the user."
## Proposed Design
### Tier 1: Auto-Select (Simple Cases)
When there's a clear winner (BEST CHOICE category with High availability):
- **Auto-select it** and show the user a simple confirmation:
- "We found a high-quality lossless version of this track from [Album / Year / Label]"
- Small "See all options" or "Choose a different version" link for power users
- This covers the majority of popular/commercially available tracks
### Tier 2: Recommended Pick (Medium Confidence)
When there's no BEST CHOICE but there are reasonable lossless options:
- **Highlight the recommended pick** with clear reasoning: "Recommended: Studio album version with reliable availability"
- Show the recommendation prominently, with other options below in a collapsed "Other options" section
- Add brief explanation of why this was chosen
### Tier 3: Manual Selection Required (Low Confidence)
When results are very limited, all low availability, or no lossless options:
- Show all results with guidance
- Add contextual tips at the top:
- "Check the filename matches your song title"
- "Higher availability = more reliable download"
- "Studio album versions typically produce the best karaoke results"
- "Vinyl rips may have surface noise"
- "YouTube is lower quality but works for rare/live tracks"
### Advanced View (Always Accessible)
Keep the current full category view as an "Advanced options" panel:
- Add guidance header explaining the gotchas
- Add tooltips on availability badges explaining what they mean
- Flag potentially wrong tracks (filename doesn't match search title)
- Consider dimming or warning on results where the filename suggests a different song
## Auto-Select Heuristics Training Plan
### Data Collection
1. Pull the last ~50 completed jobs from Firestore
2. For each job that went through audio search:
- Retrieve the cached search results (what options were available)
- Record which result index was selected
- Have the user annotate WHY that choice was made
3. Categorize by popularity/availability patterns
### Heuristic Rules to Codify
Based on walkthrough observations:
1. **Availability > bit depth** for karaoke (failed download = start over, 24-bit is wasted)
2. **Filename must match song title** (compilation results often have wrong tracks)
3. **Prefer studio albums** over compilations, vinyl rips, live versions
4. **Avoid vinyl rips** for karaoke (surface noise affects vocal separation)
5. **YouTube/lossy is last resort** (lower quality, may be different arrangements)
6. **When in doubt, pick highest availability** among lossless results
### Implementation
- Could live in flacfetch's ranking logic (already has some of this)
- Or as a frontend/backend layer that post-processes flacfetch results
- Should be testable: given a set of search results, predict the correct selection
## Components Affected
- `frontend/components/audio-search/AudioSearchDialog.tsx` - Major refactor to add tiers
- `frontend/lib/api.ts` - May need new endpoint or parameter for auto-select
- Possibly `flacfetch` ranking algorithm (separate repo/workstream)
- Backend may need a "confidence score" or "recommended index" in search results response
@@ -0,0 +1,185 @@
# Phase 3: Lyrics Review - UX Plan
> **Status**: Implemented
> **Screenshots**: `phase3-lyrics-review-top.png`, `phase3-lyrics-review-bottom.png`
## Implementation Summary (2026-03-01)
### Guidance Panel (replaces stats bar)
- `GuidancePanel.tsx` — collapsible panel with color coding legend, workflow tips
- Stats hidden behind toggle (previously always visible, overwhelming for new users)
- Contextual tips for common correction types (phantom words, mis-heard words, etc.)
### Gap Navigator
- `GapNavigator.tsx` — "Gap 3 of 9" with prev/next buttons
- Keyboard shortcuts: J (next gap), K (previous gap)
- Auto-scrolls to gap and flashes the relevant words
- Scoped to uncorrected gaps only
### Simplified Toolbar
- Advanced Mode toggle (persisted in localStorage)
- Default: hides line numbers, delete icons, power-user tools
- Advanced: shows Find/Replace, Edit All, Undo Auto Corrections, Timing Offset
### Edit Tracking & Feedback System
- `editLog.ts` — session-based edit log capturing all user edits (word changes, deletions, additions, find/replace, segment operations, reverts)
- `EditFeedbackBar.tsx` — slim feedback bar above sticky footer, appears after single-word edits with contextual "why?" buttons (Mis-heard word, Wrong lyrics, Spelling/punctuation, etc.)
- Auto-dismisses after 10 seconds, pauses timer while hovered
- Edit logs submitted to backend on review completion for transcription model improvement
- Replaces the old high-friction `CorrectionAnnotationModal` (9 categories, confidence slider — nobody used it)
- Backend endpoints: `POST /api/jobs/{job_id}/edit-log` (GCS storage), `POST /api/review/{job_id}/v1/annotations` (fixed from stub)
- 40 tests across frontend and backend
### Word Component Improvements
- Active gap ring indicator (persistent highlight for currently navigated gap)
- Color coding preserved: blue = matched/confident, orange = needs review
## Current State
The lyrics review page at `/app/jobs#/{jobId}/review` is the most complex screen in the app. It's a combined review flow (lyrics + instrumental selection in one session).
### Top Stats Bar
Four cards showing:
- **Correction Handlers** - collapsed section (unclear what this means)
- **Anchor Sequences: 19 (94%)** - "Matched sections between transcription and reference", sub-stats: "Words in Anchors: 266", "Multi-source Matches: 19"
- **Corrected Gaps: 0 (0%)** - "Successfully corrected sections", sub-stats: "Words Replaced: 0", "Words Added/Deleted: +0/-0"
- **Uncorrected Gaps: 9 (6%)** - "Sections that may need manual review", sub-stats: "Words Uncorrected: 18", "Number of Gaps: 9"
### Toolbar
- **Mode buttons**: Edit (selected), Highlight, Delete
- **Actions**: Undo All, undo/redo arrows, Find/Replace, Edit All
- **Secondary row**: Undo Auto Corrections, Timing Offset, Feedback On
- **Playback**: Play button with timeline slider (0:00 to 3:44)
### Left Panel: Corrected Transcription
- Numbered lines (0-49 for Bon Jovi example)
- Each line has: line number, delete icon, play icon, lyrics text
- **Text/Timeline toggle** at top
- Words are color-coded (see Color Coding section below)
### Right Panel: Reference Lyrics
- **Source tabs**: Lrclib (selected), Genius, Spotify, + New
- Copy button next to "Reference Lyrics" heading
- Reference text with color-coded highlights matching the left panel
### Bottom Bar (Sticky)
- "Lyrics look good?" text
- **"Preview Video"** pink button
- After preview, user clicks "Proceed to Instrumental Review" (green button) to move to Phase 4
### Flow: Lyrics → Preview → Instrumental
The combined review flow is:
1. User reviews/corrects lyrics on this page
2. User clicks "Preview Video" to generate a preview with their corrections
3. User watches preview to verify sync
4. User clicks "Proceed to Instrumental Review" to move to instrumental selection (Phase 4)
## User Feedback
### Stats Bar
> "This whole section could probably be removed or hidden behind a 'Stats' toggle button or something. Maybe we could use the space in this section to give the user guidance on how to use the tool instead?"
### Toolbar
> "Agreed re. 'no guidance on when to use which' but I'm not really sure how best to resolve that without making the UI even more cluttered/overwhelming. Maybe the section above could be sufficient to give the user guidance on these buttons too, if we can make smart/efficient use of the space. We should also ensure all buttons have really rich, helpful tooltips (but also consider mobile users who may not have access to tooltips)."
### Left Panel
> "All users definitely need the play button beside lines, but the line numbers and delete icons should probably be hidden unless the user enables 'Advanced Mode' or something"
### Color Coding (User's Explanation)
> "Blue means 'matched with reference lyrics, so most likely correct'. Orange means 'unable to match with reference lyrics, so needs to be reviewed and either edited or deleted'."
>
> "Generally the user should be focusing on the Corrected Transcription panel. Words which are highlighted in blue are highly likely to be correct, so the user should focus on the words which are highlighted in orange (the 'gaps')."
### Correction Workflow
> "I immediately focus on the gaps (highlighted in orange), typically I click the play icon beside those lines to listen to what the singer actually sings in each segment, while visually trying to find the relevant part of the reference lyrics to advise me on what action to take. Then I'll click on the segment and either edit, merge, delete words as necessary, adjust word timings etc. till the lyrics in that segment are correct and well synced, then press enter/click save. I'll repeat that for every gap until I'm confident I've reviewed and corrected (where necessary) all gaps, then I'll hit preview and listen to the whole track once to ensure the sync is fine before proceeding to instrumental review."
### Common Types of Corrections Needed
**1. Phantom words (delete)**
> "The transcription very commonly puts 'And' at the start of lines during an instrumental section, in which case that word just needs to be deleted by clicking on the segment and clicking the delete icon beside the word."
**2. Mis-heard words (edit)**
> "In many cases, the transcription just has some mistakes where it mis-heard things."
**3. Stylistic differences (no action needed)**
> "In some cases, they may notice it's just a stylistic difference (e.g. the transcription writes '22' whereas reference lyrics write 'twenty two') and there's no action required."
**4. Reference lyrics are imperfect too**
> "Lyrics fetched from the internet are also not 100% accurate, and in some cases are not available at all, so the user should use their best judgement when making these corrections."
### Difficulty Varies Hugely by Track
**Easy tracks** (acoustic, country, clear vocals):
> "Acoustic or country tracks or pretty much anything with simple clear vocals tend to be transcribed really well and there may be no gaps / corrections to be made at all, or only a couple."
**Hard tracks** (rock, screamo, unclear vocals):
> "Hard rock, screamo, or anything where the vocals aren't super clear can be a challenge - in some bad cases the transcription may be more than 50% incorrect and there can be quite a lot of work to do to get it corrected."
### Concrete Examples from Walkthrough
5 tracks at lyrics review stage, showing the full difficulty spectrum:
| Track | ID | Difficulty | Notes |
|-------|-----|-----------|-------|
| Coldplay - Parachutes | a95023e8 | Easy | Short song, only 2 mistakes: phantom "And" to delete, "I" → "I'll" |
| Bon Jovi - It's My Life | c235f6bd | Easy-Medium | Few gaps, some need no action ("wanna", "calling"), but "Love can't even look, you gotta" is clearly mis-heard |
| Silversun Pickups - Well Thought Out Twinkles | 41026cfe | Medium | Several clear transcription errors, e.g. "Share about elliptic views" → "We share apocalyptic views" |
| Pony Bradshaw - Jehovah | 3552d63d | Medium | Several clear errors, e.g. "In Dilla, town on fire" → "A dilettante on fire" |
| Steve Taylor - Jim Morrisons Grave - Live | ce8f2901 | Hard | Live version from YouTube, whole spoken section at start before singing begins (needs bulk deletion), plus many transcription mistakes e.g. "Jim Morrison, cryin'" → "Jim Morrison's Grave" |
## Proposed Design
### Replace Stats Bar with Guidance Panel
Use the stats bar space for user guidance instead:
- Brief explanation of what this page is for
- Color coding legend (blue = matched/confident, orange = needs review)
- Quick workflow tip: "Focus on the orange highlighted words. Click the play button to listen, then click the word to edit."
- Collapsible "Stats" section for power users who want the numbers
- Consider making this dismissible after first visit (remember in localStorage)
### Toolbar Improvements
- Rich, helpful tooltips on all buttons (important: also consider mobile users who can't hover)
- Consider "Advanced Mode" toggle that shows/hides power-user tools
- Default view: Edit mode, play button, undo/redo, Preview Video
- Advanced view: adds Highlight, Delete, Find/Replace, Timing Offset, Edit All
### Left Panel Simplification
- **Hide by default**: Line numbers, delete icons
- **Show by default**: Play button, lyrics text with color coding
- **Advanced Mode**: Shows line numbers, delete icons, and other power tools
- Play button is essential for all users (core to the correction workflow)
### Guided Gap Review Mode
Based on the user's workflow of stepping through gaps:
- "Jump to next gap" button/shortcut
- Auto-scroll to the next uncorrected gap
- Highlight the corresponding section in reference lyrics
- Show a count: "Gap 3 of 9" with prev/next navigation
### Color Coding Legend
Persistent but minimal:
- Small bar or badge near the top: "🔵 Matched with reference lyrics" | "🟠 Needs your review"
- Or integrated into the guidance panel
### Contextual Tips for Common Corrections
Based on the user's experience, show tips like:
- "Phantom words: If you see an extra word like 'And' at the start of a line during music, delete it"
- "Listen first: Click the play button to hear what's actually sung before editing"
- "Reference lyrics aren't perfect either - use your best judgement"
- "Stylistic differences (e.g. '22' vs 'twenty two') don't need correcting"
### Preview & Submit Flow
- After correcting gaps, user clicks "Preview Video"
- Preview plays; user verifies sync
- "Proceed to Instrumental Review" button moves to Phase 4
- This flow is already in place - just needs clearer labeling/guidance
## Components Affected
- `frontend/components/` - Need to explore the review components in detail
- The review UI was originally a separate React+Vite+MUI app (~14k lines) consolidated into the main Next.js frontend in Jan 2026
- Key route: `/app/jobs#/{jobId}/review` (hash-based routing)
- Stats panel component (replace with guidance panel)
- Toolbar component (add tooltips, advanced mode toggle)
- Transcription line component (hide line numbers/delete by default)
- Need to identify the "gap navigation" mechanism if one exists
@@ -0,0 +1,147 @@
# Phase 4: Instrumental Review - UX Plan
> **Status**: User feedback captured, ready for detailed design
> **Screenshots**: `phase4-instrumental-review.png`
## Current State
The instrumental review page at `/app/jobs#/{jobId}/instrumental` is the final human review stage before the video is generated. It's a significantly simpler interface than the lyrics review.
### Header Bar
- Track name (e.g., "Coldplay - Parachutes")
- Three stat badges:
- **Segments count** (e.g., "1 segments")
- **Backing vocals percentage** (e.g., "4% backing vocals")
- **Recommendation badge** (e.g., "Clean recommended" in pink)
### Audio Player Controls
- Play button with current time / total duration
- **4 audio toggle buttons**: Original, Backing Vocals Only, Pure Instrumental, Instrumental + Backing
- Upload button (for uploading a custom instrumental)
- Zoom levels: 1x, 2x, 4x
- Keyboard shortcuts: Shift+drag (select region), Space (play/pause)
### Waveform Visualization
- Two waveform tracks displayed with timeline markers
- Shows the audio waveform across the full track duration
- Interactive - users can click/drag to select regions
### Mute Regions Panel (Bottom Left)
- "Click segments below or Shift + drag on waveform"
- Shows detected backing vocal segments as clickable buttons (e.g., "0:38 - 0:40")
- Users can add custom mute regions by shift+dragging on the waveform
### Final Selection Panel (Bottom Right)
Three options:
1. **Clean Instrumental** - "No backing vocals" - shown with "Recommended" badge when backing vocals % is low
2. **With Backing Vocals** - "All backing vocals included"
3. **Original Audio** - "Full original with lead vocals"
- **"Confirm & Continue"** button to finalize and proceed to video generation
## User Feedback
### No explanation of what this page is or how to use it
> "The page doesn't explain to the user what it is and how to use it."
The page drops users in with no context about what they're looking at or what they should do.
### The Primary Workflow Users Should Follow
> "The primary thing they should start with is clicking on any pink sections in the waveform to listen to how the backing vocals sound, decide if the backing vocals should be kept or if we should use the clean instrumental, and if they want the backing vocals but they're mixed in with lead vocals for some sections of the song, they need to create a custom instrumental by shift-dragging on the waveform to mark sections for muting, clicking 'Create Custom', then selecting that."
The intended workflow is:
1. **Listen to pink sections** - Click on any pink (backing vocal) segments in the waveform to hear what they sound like
2. **Decide: keep or remove?** - Do the backing vocals add to the karaoke experience, or should they be removed?
3. **If keeping backing vocals but some sections have lead vocal bleed**: Create a custom instrumental by shift+dragging on the waveform to mark problem sections for muting, click "Create Custom", then select that custom version
4. **Confirm selection** and proceed to video generation
### Three Possible Outcomes
**Simple case (clean)**: Backing vocals are minimal or unwanted → select "Clean Instrumental" → Confirm
**Simple case (keep backing vocals)**: Backing vocals sound good throughout → select "With Backing Vocals" → Confirm
**Complex case (custom)**: Want backing vocals but some sections have lead vocal bleed → mute problem sections → "Create Custom" → select custom version → Confirm
## Observations
### What's Working Well
- The page is much simpler than lyrics review - clear, focused decision
- The recommendation badge ("Clean recommended") is helpful
- Audio toggle buttons let users A/B test between instrumental options
- Waveform visualization with pink backing vocal highlights is intuitive once you know what to do
### Potential Issues for New Users
#### 1. No onboarding or explanation
- Users don't know what "backing vocals" are or why this review exists
- No guidance on what to do first (click pink sections to listen)
- The whole purpose of the page needs a brief introduction
#### 2. The workflow isn't communicated
- Users should start by listening to backing vocal segments, but nothing tells them this
- The decision tree (clean vs backing vocals vs custom) isn't explained
- "Create Custom" workflow (shift+drag → mute → create) is completely hidden
#### 3. Mute Regions / Custom Instrumental flow is opaque
- "Click segments below or Shift + drag on waveform" is the only guidance
- Users don't know WHEN they'd want to mute regions (answer: when backing vocals are mixed with lead vocal bleed in specific sections)
- The connection between muting sections and creating a "Custom" instrumental option isn't clear
#### 4. What does "Upload" do?
- The Upload button near the audio toggles isn't explained
- Needs a tooltip or brief explanation
#### 5. Stats badges are jargon-heavy
- "1 segments" and "4% backing vocals" - what do these mean to a new user?
- The recommendation badge is good, but the numbers without context may confuse
## Proposed Design
### Replace Stats Bar with Guided Onboarding (Consistent with Phase 3 Approach)
Replace the stats badges area with a guidance panel that explains:
- **What this page is**: "This is where you choose your karaoke backing track. The AI has separated the vocals from the music - now you decide which version sounds best."
- **What backing vocals are**: "Backing vocals are the harmony/chorus voices that sing along with the lead singer. Some karaoke singers prefer to keep them for guidance, others prefer a pure instrumental."
- **What to do first**: "Start by clicking the pink highlighted sections in the waveform to listen to the backing vocals. Then decide if you want to keep them or use a clean instrumental."
- Collapsible/dismissible for returning users (localStorage)
### Guided Workflow Steps
Present the decision as a clear flow:
**Step 1: Listen** - "Click the pink sections in the waveform to hear the backing vocals"
**Step 2: Decide** - "Do you want to keep the backing vocals?"
- If no → "Select Clean Instrumental and confirm"
- If yes → "Select With Backing Vocals. If some sections have unwanted lead vocal bleed, continue to Step 3"
**Step 3 (if needed): Customize** - "Shift+drag on the waveform to mark sections where lead vocals bleed through, then click Create Custom to generate a custom instrumental with those sections muted"
### Contextual Recommendations
The system already recommends "Clean" when backing vocals are low (4%). Enhance this with:
- Clear reasoning: "We recommend Clean Instrumental because this track has very few backing vocals (4%)"
- For tracks with high backing vocal %, recommend "With Backing Vocals" and explain why
### Simplify for Default Users
- For tracks where the recommendation is clear, the guidance could suggest just confirming
- "This track has very little backing vocal content. We recommend the Clean Instrumental - confirm below to proceed!"
- The "Confirm & Continue" button could be more prominent
### Improve Mute Regions / Custom Instrumental UX
- Explain WHEN users need this: "If you want backing vocals but notice lead vocal bleed in certain sections, you can mute those sections to create a custom mix"
- Make the shift+drag → Create Custom flow more discoverable
- Consider a more guided approach: "Hear something that shouldn't be there? Shift+drag over that section to mark it for muting"
## Flow After Confirmation
After clicking "Confirm & Continue":
- The job progresses to video generation
- This is the final human review step
- User then waits for the video to be rendered and can download it
## Components Affected
- Need to explore the instrumental review components in detail
- Key route: `/app/jobs#/{jobId}/instrumental` (hash-based routing)
- The audio player with waveform visualization
- The backing vocal detection/mute regions system
- The final selection radio group
@@ -0,0 +1,43 @@
# Feedback-for-Credits Mechanism — 2026-03-01
## Summary
Replaced the beta-only feedback flow with a general feedback-for-credits mechanism available to all users. Users who complete 2+ karaoke videos can submit product feedback to earn 2 free credits, bringing total possible free credits to 4 (2 welcome + 2 feedback).
This was PR 2 of 2 in the beta→credits transition:
- PR #430: Removed beta program from homepage, promoted 2 free welcome credits
- PR #431: Added feedback-for-credits for all users
## Key Changes
### Backend
- **New models** in `backend/models/user.py`: `UserFeedback`, `UserFeedbackRequest`, `UserFeedbackResponse`, `FeedbackEligibilityResponse`
- **New field** on `User` model: `has_submitted_feedback: bool` (for duplicate prevention)
- **New field** on `UserPublic` model: `feedback_eligible: bool` (computed in `/me` endpoint)
- **New endpoints** in `backend/api/routes/users.py`:
- `GET /api/users/feedback/eligibility` — returns eligibility details
- `POST /api/users/feedback` — submits feedback, grants 2 credits
- **Updated `/me` endpoint** — computes `feedback_eligible` inline (no extra API call needed)
- **New Firestore collection**: `user_feedback` (separate from `beta_feedback`)
- **Updated welcome email** — credit-focused styling with feedback teaser
### Frontend
- **FeedbackDialog component** (`frontend/components/feedback/FeedbackDialog.tsx`) — 4 star ratings, 3 text fields, 2 checkboxes, loading/success states
- **Dashboard banner** — dismissible green banner when `user.feedback_eligible === true`
- **User dropdown** — "Earn 2 Free Credits" menu item with Gift icon
- **Types/API** — `feedback_eligible` on User type, `submitFeedback()` API method
## Decisions Made
- **Eligibility threshold**: 2 completed jobs. Low enough to be achievable, high enough that users have meaningful experience to share.
- **Credit reward**: 2 credits (same as welcome credits). Enough to be compelling, not so much it undermines paid packages.
- **One-time only**: `has_submitted_feedback` flag prevents duplicate submissions.
- **Inline eligibility**: `feedback_eligible` computed in `/me` response avoids an extra API roundtrip.
- **Separate collection**: `user_feedback` kept separate from `beta_feedback` to preserve historical beta data.
- **Text validation**: At least one text field must have >50 characters to ensure substantive feedback.
## Future Considerations
- Analytics: Track feedback submission rates and banner click-through rates
- Admin view: Consider adding an admin page to view user feedback submissions
- Follow-up: Could send email prompts to eligible users who haven't submitted yet
Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 161 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 155 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 155 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 167 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

+13
View File
@@ -1,6 +1,19 @@
playwright-report-prod/
playwright-report-demo/
# Demo video output and raw recordings (large files, not for git)
demo-output/
docs/images/e2e-happy-path/video/
# Local debug scripts (may contain tokens - never commit)
# Use this pattern for ad-hoc testing: test-*.local.{js,cjs,mjs,ts}
test-*.local.*
debug-*.local.*
# Search result fixtures (large raw data, regenerate with fetch-search-fixtures.mjs)
# The index.json is tracked for reference; individual result files are gitignored
e2e/fixtures/data/search-results/*.json
!e2e/fixtures/data/search-results/index.json
# Chrome profile for interactive fixture review (auto-created by playwright.review.config.ts)
.review-profile/
+36 -1
View File
@@ -2,7 +2,7 @@
* Unit tests for job-status.ts utility functions
*/
import { getJobStep, formatStepIndicator, isBlockingStatus, getJobProgressPercent, getJobPriority, sortJobsByPriority, getDisplayJobs, JobStep } from '../lib/job-status';
import { getJobStep, formatStepIndicator, isBlockingStatus, isNotifiableBlockingStatus, getJobProgressPercent, getJobPriority, sortJobsByPriority, getDisplayJobs, JobStep } from '../lib/job-status';
import type { Job } from '../lib/api';
// Helper to create a minimal Job object for testing
@@ -426,6 +426,41 @@ describe('isBlockingStatus', () => {
});
});
describe('isNotifiableBlockingStatus', () => {
it('returns true for awaiting_review', () => {
expect(isNotifiableBlockingStatus('awaiting_review')).toBe(true);
});
it('returns true for in_review', () => {
expect(isNotifiableBlockingStatus('in_review')).toBe(true);
});
it('returns true for awaiting_instrumental_selection', () => {
expect(isNotifiableBlockingStatus('awaiting_instrumental_selection')).toBe(true);
});
it('returns false for awaiting_audio_selection (user already engaged)', () => {
expect(isNotifiableBlockingStatus('awaiting_audio_selection')).toBe(false);
});
it('returns false for non-blocking statuses', () => {
expect(isNotifiableBlockingStatus('pending')).toBe(false);
expect(isNotifiableBlockingStatus('downloading')).toBe(false);
expect(isNotifiableBlockingStatus('complete')).toBe(false);
expect(isNotifiableBlockingStatus('failed')).toBe(false);
});
it('handles case insensitivity', () => {
expect(isNotifiableBlockingStatus('AWAITING_REVIEW')).toBe(true);
expect(isNotifiableBlockingStatus('AWAITING_AUDIO_SELECTION')).toBe(false);
});
it('handles null/undefined gracefully', () => {
expect(isNotifiableBlockingStatus(null as unknown as string)).toBe(false);
expect(isNotifiableBlockingStatus(undefined as unknown as string)).toBe(false);
});
});
describe('getJobProgressPercent', () => {
it('returns 0 for terminal states (step 0)', () => {
const job = createJob('failed');
+29 -1
View File
@@ -1534,8 +1534,9 @@ function AdminJobsPageContent() {
This will permanently delete:
<ul className="list-disc list-inside mt-2 space-y-1">
<li>YouTube video (if uploaded)</li>
<li>Dropbox folder (frees brand code for reuse)</li>
<li>Dropbox folder (if uploaded)</li>
<li>Google Drive files (if uploaded)</li>
<li>Brand code (recycled for reuse if cleanup succeeds)</li>
</ul>
<br />
The job record will be preserved with a timestamp marking when outputs were deleted.
@@ -1653,6 +1654,33 @@ function AdminJobsPageContent() {
</div>
</div>
</div>
{/* Brand Code */}
{deleteOutputsResult.deleted_services.brand_code && (
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className={`w-2 h-2 rounded-full mt-1.5 ${
deleteOutputsResult.deleted_services.brand_code.status === "recycled"
? "bg-green-500"
: deleteOutputsResult.deleted_services.brand_code.status === "skipped"
? "bg-gray-400"
: "bg-red-500"
}`} />
<div className="flex-1 min-w-0">
<div className="font-medium text-sm">Brand Code</div>
<div className="text-xs text-muted-foreground">
{deleteOutputsResult.deleted_services.brand_code.status === "recycled" && (
<>Recycled <code className="text-xs bg-muted px-1 rounded">{deleteOutputsResult.deleted_services.brand_code.code}</code> for reuse</>
)}
{deleteOutputsResult.deleted_services.brand_code.status === "skipped" && (
<>{deleteOutputsResult.deleted_services.brand_code.reason}</>
)}
{deleteOutputsResult.deleted_services.brand_code.status === "failed" && (
<span className="text-red-500">{deleteOutputsResult.deleted_services.brand_code.error}</span>
)}
</div>
</div>
</div>
)}
</div>
{deleteOutputsResult.cleared_state_data.length > 0 && (
+71
View File
@@ -22,6 +22,16 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
@@ -34,6 +44,7 @@ import {
CreditCard,
Briefcase,
Clock,
Trash2,
} from "lucide-react"
import { useToast } from "@/hooks/use-toast"
@@ -47,6 +58,9 @@ export default function AdminUserDetailPage() {
const [loading, setLoading] = useState(true)
const [actionLoading, setActionLoading] = useState(false)
// Delete dialog
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
// Credit dialog
const [creditDialogOpen, setCreditDialogOpen] = useState(false)
const [creditAmount, setCreditAmount] = useState("")
@@ -142,6 +156,28 @@ export default function AdminUserDetailPage() {
}
}
const handleDeleteUser = async () => {
if (!user) return
try {
setActionLoading(true)
await adminApi.deleteUser(email)
toast({
title: "User Deleted",
description: `User ${email} has been permanently deleted`,
})
router.push("/admin/users")
} catch (err: any) {
toast({
title: "Error",
description: err.message || "Failed to delete user",
variant: "destructive",
})
} finally {
setActionLoading(false)
}
}
const formatDate = (dateStr?: string) => {
if (!dateStr) return "Never"
return new Date(dateStr).toLocaleString()
@@ -229,6 +265,16 @@ export default function AdminUserDetailPage() {
</>
)}
</Button>
{user.role !== "admin" && (
<Button
variant="destructive"
onClick={() => setDeleteDialogOpen(true)}
disabled={actionLoading}
>
<Trash2 className="w-4 h-4 mr-2" />
Delete User
</Button>
)}
</div>
{/* Stats Grid */}
@@ -438,6 +484,31 @@ export default function AdminUserDetailPage() {
</DialogFooter>
</DialogContent>
</Dialog>
{/* Delete User Confirmation Dialog */}
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete User</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to permanently delete user {email}? This action
cannot be undone. All sessions and authentication data will be removed.
Jobs will be preserved as historical records.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleDeleteUser}
disabled={actionLoading}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{actionLoading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
Delete User
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
+59 -7
View File
@@ -15,15 +15,16 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Music2, RefreshCw, Loader2, Moon, Sun, Eye, EyeOff } from "lucide-react"
import { Music2, RefreshCw, Loader2, Moon, Sun, Eye, EyeOff, Gift, X } from "lucide-react"
import { sortJobsByPriority, getDisplayJobs } from "@/lib/job-status"
import { WarmingUpLoader } from "@/components/WarmingUpLoader"
import { JobCard } from "@/components/job"
import { JobSubmission } from "@/components/job/JobSubmission"
import { GuidedJobFlow } from "@/components/job/GuidedJobFlow"
import { AuthStatus } from "@/components/auth"
import { AutoProcessor } from "@/components/AutoProcessor"
import { VersionFooter } from "@/components/version-footer"
import { PushNotificationPrompt } from "@/components/push-notification-prompt"
import { FeedbackDialog } from "@/components/feedback/FeedbackDialog"
import { useTheme } from "@/lib/theme"
import {
Tooltip,
@@ -53,14 +54,22 @@ function AppPageContent() {
if (typeof window === "undefined") return false
return localStorage.getItem("nomad-karaoke-hide-completed") === "true"
})
const [feedbackBannerDismissed, setFeedbackBannerDismissed] = useState(false)
const [showFeedbackDialog, setShowFeedbackDialog] = useState(false)
// Check if user is admin (for exclude_test parameter)
const isAdmin = user?.role === "admin" || user?.email?.endsWith("@nomadkaraoke.com")
// Derive displayed jobs from allJobs + display limit + filter (instant, no re-fetch)
// Filter out in-progress search jobs (managed by the guided flow, not standalone cards)
const visibleJobs = useMemo(
() => allJobs.filter(job => job.status !== 'awaiting_audio_selection'),
[allJobs]
)
// Derive displayed jobs from visibleJobs + display limit + filter (instant, no re-fetch)
const { displayedJobs: jobs, totalFetched } = useMemo(
() => getDisplayJobs(allJobs, jobLimit, hideCompleted),
[allJobs, jobLimit, hideCompleted]
() => getDisplayJobs(visibleJobs, jobLimit, hideCompleted),
[visibleJobs, jobLimit, hideCompleted]
)
// Memoize loadJobs for use with visibility refresh
@@ -226,21 +235,64 @@ function AppPageContent() {
</div>
</header>
{/* Feedback dialog */}
<FeedbackDialog
open={showFeedbackDialog}
onClose={() => setShowFeedbackDialog(false)}
/>
<main className="px-4 pt-24 pb-8 space-y-6">
{/* Push notification prompt - shows once when appropriate */}
<PushNotificationPrompt />
{/* Feedback-for-credits banner */}
{user?.feedback_eligible && !feedbackBannerDismissed && (
<div className="flex items-center justify-between gap-3 rounded-lg border px-4 py-3"
style={{
borderColor: 'var(--accent)',
backgroundColor: 'rgba(34, 197, 94, 0.05)',
}}
>
<div className="flex items-center gap-3 min-w-0">
<Gift className="w-5 h-5 text-green-500 shrink-0" />
<p className="text-sm" style={{ color: 'var(--text)' }}>
<strong>Earn 2 free credits!</strong>{' '}
<span style={{ color: 'var(--text-muted)' }}>
Share your feedback on the karaoke creation experience.
</span>
</p>
</div>
<div className="flex items-center gap-2 shrink-0">
<Button
size="sm"
variant="outline"
onClick={() => setShowFeedbackDialog(true)}
className="text-green-500 border-green-500/30 hover:bg-green-500/10"
>
Give Feedback
</Button>
<button
onClick={() => setFeedbackBannerDismissed(true)}
className="p-1 rounded hover:bg-secondary transition-colors"
style={{ color: 'var(--text-muted)' }}
>
<X className="w-4 h-4" />
</button>
</div>
</div>
)}
<div className="grid lg:grid-cols-2 gap-8">
{/* Submit Job Card */}
<Card className="backdrop-blur min-w-0" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}>
<CardHeader>
<CardTitle style={{ color: 'var(--text)' }}>Create Karaoke Video</CardTitle>
<CardDescription style={{ color: 'var(--text-muted)' }}>
Upload an audio file, provide a YouTube URL, or search for audio by artist & title
Turn any song into a karaoke video with synced lyrics
</CardDescription>
</CardHeader>
<CardContent>
<JobSubmission onJobCreated={loadJobs} />
<GuidedJobFlow onJobCreated={loadJobs} />
</CardContent>
</Card>
+10 -1
View File
@@ -1,5 +1,6 @@
import type React from "react"
import type { Metadata } from "next"
import localFont from "next/font/local"
import { ThemeProvider } from "@/components/theme-provider"
import { TenantProvider } from "@/components/tenant-provider"
import { ImpersonationBannerWrapper } from "@/components/impersonation-banner-wrapper"
@@ -7,6 +8,14 @@ import { ServiceWorkerRegistration } from "@/components/service-worker-registrat
import { GoogleAnalytics } from "@/components/google-analytics"
import "./globals.css"
// AvenirNext Bold - matches the font used in actual Nomad theme title card generation
// (karaoke_gen/resources/AvenirNext-Bold.ttf)
const titleCardFont = localFont({
src: "../public/fonts/AvenirNext-Bold.ttf",
display: "swap",
variable: "--font-title-card",
})
export const metadata: Metadata = {
title: "Nomad Karaoke: Generator",
description: "Generate professional karaoke videos with AI-powered vocal separation and synchronized lyrics",
@@ -28,7 +37,7 @@ export default function RootLayout({
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body className="font-sans antialiased" style={{ background: 'var(--bg)', color: 'var(--text)' }}>
<body className={`font-sans antialiased ${titleCardFont.variable}`} style={{ background: 'var(--bg)', color: 'var(--text)' }}>
<GoogleAnalytics />
<ServiceWorkerRegistration />
<ThemeProvider
+41 -207
View File
@@ -1,6 +1,6 @@
'use client';
import { useState, useEffect, useRef } from 'react';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import {
@@ -8,10 +8,8 @@ import {
Sparkles,
Video,
Youtube,
ChevronDown,
Check,
Gift,
MessageSquare,
Mail,
Loader2,
Search,
@@ -21,7 +19,7 @@ import {
FileVideo,
CreditCard,
} from 'lucide-react';
import { api, setAccessToken, getAccessToken, CreditPackage, BetaEnrollResponse } from '@/lib/api';
import { api, setAccessToken, getAccessToken, CreditPackage } from '@/lib/api';
import { AuthDialog } from '@/components/auth/AuthDialog';
import { WarmingUpLoader } from '@/components/WarmingUpLoader';
import { ThemeToggle } from '@/components/ThemeToggle';
@@ -66,16 +64,6 @@ export default function LandingPage() {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Beta form state
const [showBetaForm, setShowBetaForm] = useState(false);
const [betaEmail, setBetaEmail] = useState('');
const [betaPromise, setBetaPromise] = useState('');
const [betaAccept, setBetaAccept] = useState(false);
const [betaLoading, setBetaLoading] = useState(false);
const [betaError, setBetaError] = useState<string | null>(null);
const [betaSuccess, setBetaSuccess] = useState(false);
const [betaWillRedirect, setBetaWillRedirect] = useState(false);
// Made For You form state
const [mfyArtist, setMfyArtist] = useState('');
const [mfyTitle, setMfyTitle] = useState('');
@@ -89,18 +77,6 @@ export default function LandingPage() {
// Auth dialog state
const [showAuthDialog, setShowAuthDialog] = useState(false);
// Ref for redirect timeout cleanup
const redirectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
// Cleanup timeout on unmount
useEffect(() => {
return () => {
if (redirectTimeoutRef.current) {
clearTimeout(redirectTimeoutRef.current);
}
};
}, []);
// Check if already logged in and redirect to app
useEffect(() => {
const token = getAccessToken();
@@ -159,55 +135,6 @@ export default function LandingPage() {
}
};
// Handle beta enrollment
const handleBetaEnroll = async (e: React.FormEvent) => {
e.preventDefault();
setBetaError(null);
// Validation
if (!betaEmail) {
setBetaError('Please enter your email address');
return;
}
if (!betaAccept) {
setBetaError('Please accept the corrections work agreement');
return;
}
if (!betaPromise || betaPromise.length < 10) {
setBetaError('Please write a sentence about a song you want to make into karaoke');
return;
}
setBetaLoading(true);
try {
const response: BetaEnrollResponse = await api.enrollBetaTester(
betaEmail,
betaPromise,
betaAccept
);
// If we got a session token, store it and redirect to main app
if (response.session_token) {
setAccessToken(response.session_token);
setBetaSuccess(true);
setBetaWillRedirect(true);
// Redirect to main app after showing success message
redirectTimeoutRef.current = setTimeout(() => {
router.push('/app');
}, 2000);
} else {
// No token means email verification needed
setBetaSuccess(true);
setBetaWillRedirect(false);
}
} catch (err) {
setBetaError(err instanceof Error ? err.message : 'Failed to enroll in beta program');
} finally {
setBetaLoading(false);
}
};
// Handle Made For You checkout
const handleMadeForYouSubmit = async (e: React.FormEvent) => {
e.preventDefault();
@@ -285,7 +212,7 @@ export default function LandingPage() {
</nav>
{/* Hero Section */}
<section className="pt-32 pb-16 px-4">
<section className="pt-32 pb-6 px-4">
<div className="max-w-4xl mx-auto text-center">
<h1 className="text-4xl sm:text-5xl md:text-6xl font-extrabold mb-6 leading-tight">
Create a <span className="gradient-text">Karaoke Video</span> for Any Song
@@ -298,15 +225,15 @@ export default function LandingPage() {
{/* Two pricing options */}
<div className="flex flex-col sm:flex-row items-center justify-center gap-6 mb-6">
<div className="flex flex-col items-center gap-2">
<a
href="#pricing"
<button
onClick={() => setShowAuthDialog(true)}
className="inline-flex items-center gap-2 bg-primary-500 hover:bg-primary-600 text-white font-semibold px-8 py-4 rounded-xl transition-all btn-glow"
>
<Video className="w-5 h-5" />
Create It Yourself
<span className="ml-1 px-2 py-0.5 bg-white/20 rounded-full text-sm">$5</span>
</a>
<span className="text-dark-400 text-sm">Review lyrics yourself in ~10 min</span>
</button>
<span className="text-green-400 text-sm">2 free credits included - no payment required</span>
</div>
<div className="flex flex-col items-center gap-2">
<a
@@ -315,19 +242,12 @@ export default function LandingPage() {
>
<Gift className="w-5 h-5" />
We&apos;ll Make It For You
<span className="ml-1 px-2 py-0.5 bg-yellow-500/20 rounded-full text-sm">$15</span>
<span className="ml-1 px-2 py-0.5 bg-yellow-500/20 rounded-full text-sm">$50</span>
</a>
<span className="text-yellow-400/70 text-sm">We handle everything, delivered in 24h</span>
</div>
</div>
<a
href="#beta"
className="inline-flex items-center gap-1 text-primary-400 hover:text-primary-300 text-sm font-medium transition-colors"
>
Or try it free as a beta tester
<ChevronDown className="w-4 h-4" />
</a>
</div>
</section>
@@ -338,7 +258,7 @@ export default function LandingPage() {
<div className="aspect-video">
<iframe
className="w-full h-full rounded-xl"
src="https://www.youtube.com/embed/uvKtLOUiqz8?si=K06hw2B-QJ81Loeo"
src="https://www.youtube.com/embed/GJY60IfIHOQ"
title="Nomad Karaoke Demo"
frameBorder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
@@ -403,20 +323,20 @@ export default function LandingPage() {
Here&apos;s what the process looks like at each step
</p>
<div className="grid md:grid-cols-2 gap-8">
{/* Job Dashboard Screenshot */}
{/* Job Creation Screenshot */}
<div className="bg-dark-800 border border-dark-700 rounded-xl overflow-hidden">
<div className="aspect-video bg-dark-900 relative">
<Image
src="/screenshots/job-dashboard.avif"
alt="Job Dashboard showing karaoke video projects with status indicators"
alt="Guided job creation flow with artist and title entry"
fill
className="object-cover"
sizes="(max-width: 768px) 100vw, 50vw"
/>
</div>
<div className="p-4">
<h3 className="font-semibold mb-1">Job Dashboard</h3>
<p className="text-dark-400 text-sm">Track progress of all your karaoke video projects</p>
<h3 className="font-semibold mb-1">Create Your Video</h3>
<p className="text-dark-400 text-sm">Enter any song and we find the best audio automatically</p>
</div>
</div>
@@ -425,15 +345,15 @@ export default function LandingPage() {
<div className="aspect-video bg-dark-900 relative">
<Image
src="/screenshots/lyrics-review.avif"
alt="Lyrics Review UI with word-by-word editing and timing controls"
alt="Lyrics review with synced lyrics alongside reference lyrics for correction"
fill
className="object-cover"
className="object-cover object-top"
sizes="(max-width: 768px) 100vw, 50vw"
/>
</div>
<div className="p-4">
<h3 className="font-semibold mb-1">Lyrics Review</h3>
<p className="text-dark-400 text-sm">Correct any transcription errors before generating your video</p>
<h3 className="font-semibold mb-1">Review Lyrics</h3>
<p className="text-dark-400 text-sm">Compare synced lyrics with references and fix any errors</p>
</div>
</div>
@@ -442,15 +362,15 @@ export default function LandingPage() {
<div className="aspect-video bg-dark-900 relative">
<Image
src="/screenshots/instrumental-review.avif"
alt="Instrumental Selection UI with audio player and backing vocals options"
alt="Instrumental review with waveform visualization and backing vocal options"
fill
className="object-cover"
className="object-cover object-top"
sizes="(max-width: 768px) 100vw, 50vw"
/>
</div>
<div className="p-4">
<h3 className="font-semibold mb-1">Instrumental Selection</h3>
<p className="text-dark-400 text-sm">Pick the sound that works best for your karaoke</p>
<h3 className="font-semibold mb-1">Choose Your Instrumental</h3>
<p className="text-dark-400 text-sm">Listen to audio options and pick the best backing track</p>
</div>
</div>
@@ -459,127 +379,41 @@ export default function LandingPage() {
<div className="aspect-video bg-dark-900 relative">
<Image
src="/screenshots/example-output.avif"
alt="Example karaoke video output with synchronized lyrics"
alt="Completed karaoke job with download options for 4K, 720p, CDG, and more"
fill
className="object-cover"
sizes="(max-width: 768px) 100vw, 50vw"
/>
</div>
<div className="p-4">
<h3 className="font-semibold mb-1">Final Video</h3>
<p className="text-dark-400 text-sm">4K karaoke video ready for your next singing session</p>
<h3 className="font-semibold mb-1">Download & Share</h3>
<p className="text-dark-400 text-sm">Get your 4K video, 720p, CDG, and more in minutes</p>
</div>
</div>
</div>
</div>
</section>
{/* Beta Tester Program */}
<section id="beta" className="py-12 px-4">
<div className="max-w-2xl mx-auto">
<div className="bg-gradient-to-r from-pink-500/10 to-purple-500/10 border border-primary/30 rounded-2xl p-8 text-center">
<div className="inline-flex items-center gap-2 bg-primary-500/20 text-primary-400 px-4 py-2 rounded-full text-sm font-medium mb-4">
<Gift className="w-4 h-4" />
Beta Tester Program
</div>
<h3 className="text-2xl font-bold mb-3">Try It Free!</h3>
<p className="text-dark-300 mb-6">
Help us improve by testing the tool and sharing your feedback. Beta testers get{' '}
<span className="text-green-400 font-semibold">up to 5 free karaoke videos</span>{' '}
in exchange for providing feedback on each one.
</p>
{!showBetaForm && !betaSuccess && (
<button
onClick={() => setShowBetaForm(true)}
className="inline-flex items-center gap-2 bg-primary-500 hover:bg-primary-600 text-white font-semibold px-6 py-3 rounded-xl transition-all btn-glow"
>
Join Beta Program
<MessageSquare className="w-5 h-5" />
</button>
)}
{showBetaForm && !betaSuccess && (
<form onSubmit={handleBetaEnroll} className="mt-6 text-left space-y-4">
<div>
<label htmlFor="beta-email" className="block text-sm font-medium text-dark-300 mb-2">
Email address
</label>
<input
type="email"
id="beta-email"
value={betaEmail}
onChange={(e) => setBetaEmail(e.target.value)}
placeholder="you@example.com"
className="w-full px-4 py-3 bg-secondary border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary text-foreground placeholder:text-muted-foreground"
required
/>
</div>
<div>
<label htmlFor="beta-promise" className="block text-sm font-medium text-dark-300 mb-2">
What song do you want to make into karaoke?
</label>
<textarea
id="beta-promise"
value={betaPromise}
onChange={(e) => setBetaPromise(e.target.value)}
placeholder="Tell us about a song you'd love to sing..."
rows={3}
className="w-full px-4 py-3 bg-secondary border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary text-foreground placeholder:text-muted-foreground resize-none"
/>
</div>
<div className="flex items-start gap-3">
<input
type="checkbox"
id="beta-accept"
checked={betaAccept}
onChange={(e) => setBetaAccept(e.target.checked)}
className="mt-1 w-4 h-4 rounded border-border bg-secondary text-primary focus:ring-primary"
/>
<label htmlFor="beta-accept" className="text-sm text-muted-foreground">
I understand that I&apos;ll need to review and correct any lyrics transcription errors, and provide feedback after each video
</label>
</div>
{betaError && (
<p className="text-red-400 text-sm">{betaError}</p>
)}
<button
type="submit"
disabled={betaLoading}
className="w-full bg-primary-500 hover:bg-primary-600 disabled:bg-primary-500/50 text-white font-semibold py-3 rounded-xl transition-all btn-glow flex items-center justify-center gap-2"
>
{betaLoading ? 'Enrolling...' : 'Get My Free Credit'}
{!betaLoading && <Gift className="w-5 h-5" />}
</button>
</form>
)}
{betaSuccess && (
<div className="mt-6 p-4 bg-green-500/20 border border-green-500/30 rounded-xl">
<p className="text-green-400 font-semibold">
Welcome to the beta program!{' '}
{betaWillRedirect
? 'Redirecting to the app...'
: 'Check your email for a sign-in link.'}
</p>
</div>
)}
</div>
</div>
</section>
{/* Pricing */}
<section id="pricing" className="py-20 px-4">
<div className="max-w-4xl mx-auto">
<h2 className="text-3xl font-bold text-center mb-4">Simple Pricing</h2>
<p className="text-dark-400 text-center mb-12 max-w-xl mx-auto">
One credit = one karaoke video. Buy more to save more.
<p className="text-dark-400 text-center mb-4 max-w-xl mx-auto">
Start with 2 free credits, then buy more to save more.
</p>
<div className="bg-green-500/10 border border-green-500/30 rounded-2xl p-6 text-center mb-10 max-w-sm mx-auto">
<div className="text-sm text-green-400 font-medium mb-1">Every new account includes</div>
<div className="text-4xl font-bold text-green-400 mb-1">2 Free Credits</div>
<div className="text-sm text-dark-400 mb-4">No payment required</div>
<button
onClick={() => setShowAuthDialog(true)}
className="inline-flex items-center gap-2 bg-green-500 hover:bg-green-600 text-white font-semibold px-6 py-3 rounded-xl transition-all"
>
Sign Up Free
</button>
</div>
{/* Package Selection */}
{packagesLoading && (
<WarmingUpLoader className="py-8" />
@@ -692,7 +526,7 @@ export default function LandingPage() {
<h2 className="text-3xl font-bold mb-4">We&apos;ll Make It For You</h2>
<p className="text-dark-400 max-w-2xl mx-auto mb-4">
Don&apos;t want to use the Generator and review the lyrics yourself? No problem.
Tell us the song, pay $15, and we&apos;ll deliver your karaoke video within 24 hours.
Tell us the song, pay $50, and we&apos;ll deliver your karaoke video within 24 hours.
</p>
<p className="text-dark-500 text-sm max-w-xl mx-auto">
Don&apos;t want to spend 10 minutes reviewing lyrics? For just $10 more than DIY, we handle everything.
@@ -787,7 +621,7 @@ export default function LandingPage() {
<div className="bg-dark-800 border border-dark-700 rounded-2xl p-6 sm:p-8">
<div className="flex items-center justify-between mb-6">
<h3 className="text-xl font-semibold">Order a Video</h3>
<div className="text-2xl font-bold text-primary-400">$15</div>
<div className="text-2xl font-bold text-primary-400">$50</div>
</div>
<form onSubmit={handleMadeForYouSubmit} className="space-y-5">
@@ -937,7 +771,7 @@ export default function LandingPage() {
) : (
<>
<CreditCard className="w-5 h-5" />
Pay $15 &amp; Order
Pay $50 &amp; Order
</>
)}
</button>
@@ -1,10 +1,20 @@
"use client"
import { useState, useEffect, useMemo } from "react"
import { api, AudioSearchResult } from "@/lib/api"
import { api } from "@/lib/api"
import {
ExtendedAudioSearchResult,
groupResults,
getDisplayName,
formatCount,
formatMetadata,
formatQuality,
getAvailabilityLabel,
checkFilenameMismatch,
} from "@/lib/audio-search-utils"
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"
import { Loader2, Music2, ChevronDown, ChevronUp } from "lucide-react"
import { Loader2, Music2, ChevronDown, ChevronUp, Lightbulb } from "lucide-react"
// Version from pyproject.toml (single source of truth)
const APP_VERSION = process.env.NEXT_PUBLIC_APP_VERSION || "0.0.0"
@@ -14,117 +24,16 @@ interface AudioSearchDialogProps {
open: boolean
onClose: () => void
onSelect: () => void
searchTitle?: string
}
// Extended result type to include all backend fields
interface ExtendedAudioSearchResult extends AudioSearchResult {
channel?: string
view_count?: number
formatted_duration?: string
formatted_size?: string
release_type?: string
label?: string
edition_info?: string
target_file?: string
quality_data?: {
format?: string
bit_depth?: number
sample_rate?: number
bitrate?: number
media?: string
}
}
// Category configuration matching flacfetch
interface CategoryConfig {
name: string
maxDisplay: number
color: string
borderColor: string
}
const CATEGORY_CONFIG: Record<string, CategoryConfig> = {
'BEST CHOICE': { name: 'BEST CHOICE', maxDisplay: 3, color: 'text-amber-400', borderColor: 'border-amber-500/30' },
'HI-RES 24-BIT': { name: 'HI-RES 24-BIT', maxDisplay: 3, color: 'text-purple-400', borderColor: 'border-purple-500/30' },
'STUDIO ALBUMS': { name: 'STUDIO ALBUMS', maxDisplay: 3, color: 'text-blue-400', borderColor: 'border-blue-500/30' },
'SINGLES': { name: 'SINGLES', maxDisplay: 2, color: 'text-cyan-400', borderColor: 'border-cyan-500/30' },
'LIVE VERSIONS': { name: 'LIVE VERSIONS', maxDisplay: 2, color: 'text-pink-400', borderColor: 'border-pink-500/30' },
'COMPILATIONS': { name: 'COMPILATIONS', maxDisplay: 2, color: 'text-teal-400', borderColor: 'border-teal-500/30' },
'VINYL RIPS': { name: 'VINYL RIPS', maxDisplay: 2, color: 'text-orange-400', borderColor: 'border-orange-500/30' },
'YOUTUBE/LOSSY': { name: 'YOUTUBE/LOSSY', maxDisplay: 3, color: 'text-red-400', borderColor: 'border-red-500/30' },
'OTHER': { name: 'OTHER', maxDisplay: 3, color: 'text-muted-foreground', borderColor: 'border-border' },
}
const CATEGORY_ORDER = [
'BEST CHOICE',
'HI-RES 24-BIT',
'STUDIO ALBUMS',
'SINGLES',
'LIVE VERSIONS',
'COMPILATIONS',
'VINYL RIPS',
'YOUTUBE/LOSSY',
'OTHER'
]
// Categorize a single result based on flacfetch logic
function categorizeResult(result: ExtendedAudioSearchResult): string {
const isLossless = result.is_lossless === true
const is24Bit = result.quality_data?.bit_depth === 24
const seeders = result.seeders ?? 0
const provider = result.provider?.toLowerCase() ?? ''
const releaseType = result.release_type?.toLowerCase() ?? ''
const media = result.quality_data?.media?.toLowerCase() ?? ''
// YouTube and lossy sources
if (provider === 'youtube' || !isLossless) {
return 'YOUTUBE/LOSSY'
}
// Best choice (50+ seeders, lossless)
if (isLossless && seeders >= 50) {
return 'BEST CHOICE'
}
// Hi-res 24-bit
if (isLossless && is24Bit) {
return 'HI-RES 24-BIT'
}
// Vinyl rips
if (isLossless && media === 'vinyl') {
return 'VINYL RIPS'
}
// Live versions
if (isLossless && (releaseType === 'live album' || releaseType === 'bootleg' || releaseType.includes('live'))) {
return 'LIVE VERSIONS'
}
// Compilations
if (isLossless && (releaseType === 'compilation' || releaseType === 'soundtrack' || releaseType === 'anthology')) {
return 'COMPILATIONS'
}
// Singles/EPs
if (isLossless && (releaseType === 'single' || releaseType === 'ep')) {
return 'SINGLES'
}
// Studio albums
if (isLossless && (releaseType === 'album' || !releaseType)) {
return 'STUDIO ALBUMS'
}
return 'OTHER'
}
export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearchDialogProps) {
export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle }: AudioSearchDialogProps) {
const [results, setResults] = useState<ExtendedAudioSearchResult[]>([])
const [isLoading, setIsLoading] = useState(true)
const [isSelecting, setIsSelecting] = useState<number | null>(null)
const [error, setError] = useState("")
const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set())
const [showGuidance, setShowGuidance] = useState(false)
// Debug: Log component version on mount
useEffect(() => {
@@ -137,6 +46,7 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearc
console.log(`[AudioSearchDialog v${APP_VERSION}] Dialog opened for job: ${jobId}`)
loadResults()
setExpandedCategories(new Set()) // Reset expanded state
setShowGuidance(false)
}
}, [open, jobId])
@@ -158,31 +68,7 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearc
}
// Group results by category
const groupedResults = useMemo(() => {
const groups: Record<string, ExtendedAudioSearchResult[]> = {}
for (const result of results) {
const category = categorizeResult(result)
if (!groups[category]) {
groups[category] = []
}
groups[category].push(result)
}
// Sort by category order
const sortedGroups: Array<{ category: string; results: ExtendedAudioSearchResult[]; config: CategoryConfig }> = []
for (const cat of CATEGORY_ORDER) {
if (groups[cat] && groups[cat].length > 0) {
sortedGroups.push({
category: cat,
results: groups[cat],
config: CATEGORY_CONFIG[cat]
})
}
}
return sortedGroups
}, [results])
const groupedResults = useMemo(() => groupResults(results), [results])
// Count total categories
const totalCategories = groupedResults.length
@@ -214,51 +100,6 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearc
})
}
// Get display name - use channel for YouTube, artist for others
function getDisplayName(result: ExtendedAudioSearchResult): string {
if (result.provider === "YouTube" && result.channel) {
return result.channel
}
return result.artist || ""
}
// Format views/seeders compactly
function formatCount(count?: number): string {
if (!count && count !== 0) return "-"
if (count >= 1000000) return `${(count / 1000000).toFixed(1)}M`
if (count >= 1000) return `${(count / 1000).toFixed(1)}K`
return count.toString()
}
// Format release metadata line
function formatMetadata(result: ExtendedAudioSearchResult): string {
const parts: string[] = []
if (result.release_type) parts.push(result.release_type)
if (result.year) parts.push(result.year.toString())
if (result.label) parts.push(result.label)
if (result.edition_info) parts.push(result.edition_info)
if (result.quality_data?.media) parts.push(result.quality_data.media)
return parts.length > 0 ? `[${parts.join(' / ')}]` : ''
}
// Get quality display string
function formatQuality(result: ExtendedAudioSearchResult): string {
if (result.quality) return result.quality
const qd = result.quality_data
if (!qd) return '-'
const parts: string[] = []
if (qd.format) parts.push(qd.format)
if (qd.bit_depth) parts.push(`${qd.bit_depth}bit`)
if (qd.bitrate) parts.push(`${qd.bitrate}kbps`)
if (qd.media) parts.push(qd.media)
return parts.join(' ') || '-'
}
return (
<Dialog open={open} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-w-7xl w-[95vw] max-h-[90vh] flex flex-col bg-card border-border !p-0 gap-0 overflow-hidden">
@@ -272,6 +113,29 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearc
</DialogTitle>
</div>
{/* Guidance header (collapsed by default) */}
{!isLoading && results.length > 0 && (
<div className="px-4 py-1.5 border-b border-border bg-secondary/30">
<button
onClick={() => setShowGuidance(!showGuidance)}
className="flex items-center gap-1.5 text-[10px] text-muted-foreground hover:text-foreground transition-colors"
>
<Lightbulb className="w-3 h-3" />
Tips for choosing
{showGuidance ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
</button>
{showGuidance && (
<ul className="text-[10px] text-muted-foreground mt-1.5 ml-5 space-y-0.5 pb-1">
<li>Check the filename matches your song title</li>
<li>Green availability badge = more reliable download</li>
<li>Studio album versions produce the best karaoke results</li>
<li>Avoid vinyl rips (surface noise affects separation)</li>
<li>YouTube is a last resort — lossless sources sound better</li>
</ul>
)}
</div>
)}
{error && (
<div className="px-4 py-2 text-xs text-red-400 bg-red-500/10 border-b border-border">
{error}
@@ -322,89 +186,112 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearc
{/* Results in category */}
<div className="divide-y divide-slate-700/50">
{displayResults.map((result) => (
<div
key={result.index}
className="px-3 py-1.5 hover:bg-secondary/50 flex items-center gap-2 text-xs"
>
{/* Index */}
<span className="w-5 text-muted-foreground font-mono shrink-0 text-[10px]">
{result.index + 1}.
</span>
{displayResults.map((result) => {
const mismatch = searchTitle ? checkFilenameMismatch(searchTitle, result) : null
const hasMismatch = mismatch?.isMismatch ?? false
{/* Main content - 2 lines */}
<div className="flex-1 min-w-0">
{/* Line 1: badges + artist + title + quality + size + availability */}
<div className="flex items-center gap-1 flex-wrap">
{result.is_lossless && (
<span className="text-[8px] px-1 py-0.5 rounded bg-green-600/20 text-green-400 font-medium">
LOSSLESS
return (
<div
key={result.index}
className={`px-3 py-1.5 hover:bg-secondary/50 flex items-center gap-2 text-xs ${
hasMismatch ? 'opacity-60' : ''
}`}
>
{/* Index */}
<span className="w-5 text-muted-foreground font-mono shrink-0 text-[10px]">
{result.index + 1}.
</span>
{/* Main content - 2 lines */}
<div className="flex-1 min-w-0">
{/* Line 1: badges + artist + title + quality + size + availability */}
<div className="flex items-center gap-1 flex-wrap">
{result.is_lossless && (
<span className="text-[8px] px-1 py-0.5 rounded bg-green-600/20 text-green-400 font-medium">
LOSSLESS
</span>
)}
{result.quality_data?.media?.toLowerCase() === 'vinyl' && (
<span className="text-[8px] px-1 py-0.5 rounded bg-red-600/20 text-red-400 font-medium">
VINYL
</span>
)}
{result.provider === "YouTube" && (
<span className="text-[8px] px-1 py-0.5 rounded font-medium bg-red-600/20 text-red-400">
YouTube
</span>
)}
{hasMismatch && (
<span
title={`Expected "${searchTitle}" but filename is "${mismatch!.filename}"${mismatch!.suggestedTrack ? ` (looks like "${mismatch!.suggestedTrack}")` : ''}`}
className="text-[8px] px-1 py-0.5 rounded font-medium bg-yellow-600/20 text-yellow-400 cursor-help"
>
Wrong track?
</span>
)}
<span className="text-green-400 font-medium">{getDisplayName(result)}</span>
<span className="text-muted-foreground">-</span>
<span className="text-foreground">{result.title}</span>
<span className={`text-[10px] ${result.is_lossless ? "text-green-400" : "text-muted-foreground"}`}>
({formatQuality(result)})
</span>
<span className="text-[10px] text-muted-foreground">{result.formatted_size || '-'}</span>
{result.seeders !== undefined && result.seeders !== null ? (
(() => {
const { text, tooltip } = getAvailabilityLabel(result.seeders)
return (
<span
title={tooltip}
className={`text-[8px] px-1 py-0.5 rounded font-medium cursor-help ${
result.seeders >= 50 ? 'bg-green-600/20 text-green-400' :
result.seeders >= 10 ? 'bg-yellow-600/20 text-yellow-400' :
'bg-red-600/20 text-red-400'
}`}
>
{text} availability
</span>
)
})()
) : result.view_count !== undefined ? (
<span className={`text-[8px] px-1 py-0.5 rounded font-medium ${
result.view_count >= 1000000 ? 'bg-green-600/20 text-green-400' :
result.view_count >= 10000 ? 'bg-yellow-600/20 text-yellow-400' :
'bg-muted text-muted-foreground'
}`}>
{formatCount(result.view_count)} views
</span>
) : null}
</div>
{/* Line 2: metadata + filename */}
{(formatMetadata(result) || result.target_file) && (
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
{formatMetadata(result) && (
<span className="truncate">{formatMetadata(result)}</span>
)}
{result.target_file && (
<span className="font-mono truncate">&quot;{result.target_file}&quot;</span>
)}
</div>
)}
{result.quality_data?.media?.toLowerCase() === 'vinyl' && (
<span className="text-[8px] px-1 py-0.5 rounded bg-red-600/20 text-red-400 font-medium">
VINYL
</span>
)}
{result.provider === "YouTube" && (
<span className="text-[8px] px-1 py-0.5 rounded font-medium bg-red-600/20 text-red-400">
YouTube
</span>
)}
<span className="text-green-400 font-medium">{getDisplayName(result)}</span>
<span className="text-muted-foreground">-</span>
<span className="text-foreground">{result.title}</span>
<span className={`text-[10px] ${result.is_lossless ? "text-green-400" : "text-muted-foreground"}`}>
({formatQuality(result)})
</span>
<span className="text-[10px] text-muted-foreground">{result.formatted_size || '-'}</span>
{result.seeders !== undefined && result.seeders !== null ? (
<span className={`text-[8px] px-1 py-0.5 rounded font-medium ${
result.seeders >= 50 ? 'bg-green-600/20 text-green-400' :
result.seeders >= 10 ? 'bg-yellow-600/20 text-yellow-400' :
'bg-red-600/20 text-red-400'
}`}>
{result.seeders >= 50 ? 'High' : result.seeders >= 10 ? 'Medium' : 'Low'} availability
</span>
) : result.view_count !== undefined ? (
<span className={`text-[8px] px-1 py-0.5 rounded font-medium ${
result.view_count >= 1000000 ? 'bg-green-600/20 text-green-400' :
result.view_count >= 10000 ? 'bg-yellow-600/20 text-yellow-400' :
'bg-muted text-muted-foreground'
}`}>
{formatCount(result.view_count)} views
</span>
) : null}
</div>
{/* Line 2: metadata + filename */}
{(formatMetadata(result) || result.target_file) && (
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
{formatMetadata(result) && (
<span className="truncate">{formatMetadata(result)}</span>
)}
{result.target_file && (
<span className="font-mono truncate">&quot;{result.target_file}&quot;</span>
)}
</div>
)}
{/* Select button */}
<Button
size="sm"
onClick={() => handleSelect(result.index)}
disabled={isSelecting !== null}
className="w-14 h-6 text-[9px] bg-amber-600 hover:bg-amber-500 text-foreground px-2 shrink-0"
>
{isSelecting === result.index ? (
<Loader2 className="w-3 h-3 animate-spin" />
) : (
"Select"
)}
</Button>
</div>
{/* Select button */}
<Button
size="sm"
onClick={() => handleSelect(result.index)}
disabled={isSelecting !== null}
className="w-14 h-6 text-[9px] bg-amber-600 hover:bg-amber-500 text-foreground px-2 shrink-0"
>
{isSelecting === result.index ? (
<Loader2 className="w-3 h-3 animate-spin" />
) : (
"Select"
)}
</Button>
</div>
))}
)
})}
</div>
</div>
)
+33 -8
View File
@@ -1,7 +1,7 @@
"use client"
import { useState, useEffect } from "react"
import { User, LogOut, CreditCard, Coins, KeyRound, Shield, FlaskConical } from "lucide-react"
import { User, LogOut, CreditCard, Coins, KeyRound, Shield, FlaskConical, Gift } from "lucide-react"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import {
@@ -16,6 +16,8 @@ import { Switch } from "@/components/ui/switch"
import { useAuth } from "@/lib/auth"
import { useAdminSettings } from "@/lib/admin-settings"
import { AuthDialog } from "./AuthDialog"
import { FeedbackDialog } from "@/components/feedback/FeedbackDialog"
import { BuyCreditsDialog } from "@/components/credits/BuyCreditsDialog"
interface AuthStatusProps {
onAuthChange?: () => void
@@ -25,6 +27,8 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
const { user, logout } = useAuth()
const { showTestData, setShowTestData } = useAdminSettings()
const [showAuthDialog, setShowAuthDialog] = useState(false)
const [showFeedbackDialog, setShowFeedbackDialog] = useState(false)
const [showBuyCreditsDialog, setShowBuyCreditsDialog] = useState(false)
const [mounted, setMounted] = useState(false)
// Avoid hydration mismatch
@@ -45,12 +49,7 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
}
const handleBuyCredits = () => {
// Navigate to landing page pricing section with email prefilled if available
const buyUrl = new URL('/#pricing', window.location.origin)
if (user?.email) {
buyUrl.searchParams.set("email", user.email)
}
window.location.href = buyUrl.toString()
setShowBuyCreditsDialog(true)
}
// Don't render until mounted (avoids hydration issues)
@@ -60,6 +59,7 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
if (user) {
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
@@ -71,7 +71,14 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
<span className="hidden sm:inline max-w-[150px] truncate">
{user.display_name || user.email}
</span>
<span className="flex items-center gap-1 text-warning font-medium">
<span
onClick={(e) => {
e.stopPropagation()
handleBuyCredits()
}}
className="flex items-center gap-1 text-warning font-medium hover:text-warning/80 transition-colors cursor-pointer"
title="Buy more credits"
>
<Coins className="w-3 h-3" />
{user.credits} {user.credits === 1 ? 'credit' : 'credits'}
</span>
@@ -101,6 +108,15 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
<CreditCard className="w-4 h-4 mr-2" />
<span>Buy More Credits</span>
</DropdownMenuItem>
{user.feedback_eligible && (
<DropdownMenuItem
onClick={() => setShowFeedbackDialog(true)}
className="text-green-500 focus:text-green-400 focus:bg-secondary"
>
<Gift className="w-4 h-4 mr-2" />
<span>Earn 2 Free Credits</span>
</DropdownMenuItem>
)}
{(user.role === "admin" || user.email?.endsWith("@nomadkaraoke.com")) && (
<>
<DropdownMenuSeparator className="bg-border" />
@@ -134,6 +150,15 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<FeedbackDialog
open={showFeedbackDialog}
onClose={() => setShowFeedbackDialog(false)}
/>
<BuyCreditsDialog
open={showBuyCreditsDialog}
onClose={() => setShowBuyCreditsDialog(false)}
/>
</>
)
}
@@ -0,0 +1,144 @@
'use client'
import { useState, useEffect } from 'react'
import { CreditCard, Loader2 } from 'lucide-react'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { api, CreditPackage } from '@/lib/api'
import { useAuth } from '@/lib/auth'
interface BuyCreditsDialogProps {
open: boolean
onClose: () => void
}
const formatPrice = (cents: number) => `$${(cents / 100).toFixed(0)}`
const pricePerVideo = (pkg: CreditPackage) =>
`$${(pkg.price_cents / 100 / pkg.credits).toFixed(2)}`
export function BuyCreditsDialog({ open, onClose }: BuyCreditsDialogProps) {
const { user } = useAuth()
const [packages, setPackages] = useState<CreditPackage[]>([])
const [selectedPackage, setSelectedPackage] = useState<CreditPackage | null>(null)
const [loading, setLoading] = useState(false)
const [checkoutLoading, setCheckoutLoading] = useState(false)
const [error, setError] = useState('')
useEffect(() => {
if (!open) return
setError('')
setLoading(true)
api.getCreditPackages()
.then((pkgs) => {
setPackages(pkgs)
// Pre-select best value package (5 credits) or first
const bestValue = pkgs.find((p) => p.credits === 5) || pkgs[0]
setSelectedPackage(bestValue)
})
.catch((err) => {
setError(err instanceof Error ? err.message : 'Failed to load packages')
})
.finally(() => setLoading(false))
}, [open])
const handleCheckout = async () => {
if (!selectedPackage || !user?.email) return
setCheckoutLoading(true)
setError('')
try {
const checkoutUrl = await api.createCheckout(selectedPackage.id, user.email)
window.location.href = checkoutUrl
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create checkout session')
setCheckoutLoading(false)
}
}
return (
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
<DialogContent className="sm:max-w-md bg-card border-border">
<DialogHeader>
<DialogTitle className="text-foreground flex items-center gap-2">
<CreditCard className="w-5 h-5 text-primary" />
Buy More Credits
</DialogTitle>
<DialogDescription className="text-muted-foreground">
Each credit creates one karaoke video. Pick a package below.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 mt-2">
{loading && (
<div className="flex justify-center py-8">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
)}
{error && (
<div className="text-center py-4 text-sm text-destructive">{error}</div>
)}
{!loading && !error && packages.length > 0 && (
<>
<div className="grid grid-cols-2 gap-3">
{packages.map((pkg) => {
const isSelected = selectedPackage?.id === pkg.id
const isBestValue = pkg.credits === 5
const savings = pkg.credits > 1
? Math.round((1 - pkg.price_cents / (pkg.credits * 500)) * 100)
: 0
return (
<button
key={pkg.id}
onClick={() => setSelectedPackage(pkg)}
className={`relative p-4 rounded-xl border-2 transition-all text-left ${
isSelected
? 'border-primary bg-primary/10'
: 'border-border hover:border-muted-foreground/50 bg-secondary/50'
}`}
>
{isBestValue && (
<span className="absolute -top-2.5 left-1/2 -translate-x-1/2 bg-primary text-primary-foreground text-xs font-semibold px-2 py-0.5 rounded-full">
Best Value
</span>
)}
<div className="text-2xl font-bold">{pkg.credits}</div>
<div className="text-sm text-muted-foreground mb-1">
{pkg.credits === 1 ? 'credit' : 'credits'}
</div>
<div className="text-lg font-semibold text-primary">
{formatPrice(pkg.price_cents)}
</div>
<div className="text-xs text-muted-foreground">{pricePerVideo(pkg)}/video</div>
{savings > 0 && (
<div className="text-xs text-green-500 mt-1">Save {savings}%</div>
)}
</button>
)
})}
</div>
<Button
onClick={handleCheckout}
disabled={!selectedPackage || checkoutLoading}
className="w-full"
>
{checkoutLoading ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Redirecting to payment...
</>
) : selectedPackage ? (
`Continue to Payment — ${formatPrice(selectedPackage.price_cents)}`
) : (
'Select a package'
)}
</Button>
</>
)}
</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,280 @@
'use client'
import { useState } from 'react'
import { Star, Loader2, CheckCircle, Gift } from 'lucide-react'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Checkbox } from '@/components/ui/checkbox'
import { api } from '@/lib/api'
import { useAuth } from '@/lib/auth'
interface FeedbackDialogProps {
open: boolean
onClose: () => void
}
function StarRating({ value, onChange, label }: {
value: number
onChange: (v: number) => void
label: string
}) {
return (
<div className="space-y-1">
<Label className="text-sm">{label}</Label>
<div className="flex gap-1">
{[1, 2, 3, 4, 5].map((star) => (
<button
key={star}
type="button"
onClick={() => onChange(star)}
className="p-0.5 transition-colors"
>
<Star
className={`w-5 h-5 ${
star <= value
? 'fill-yellow-400 text-yellow-400'
: 'text-muted-foreground'
}`}
/>
</button>
))}
</div>
</div>
)
}
export function FeedbackDialog({ open, onClose }: FeedbackDialogProps) {
const { fetchUser } = useAuth()
const [isSubmitting, setIsSubmitting] = useState(false)
const [isSuccess, setIsSuccess] = useState(false)
const [error, setError] = useState('')
const [creditsGranted, setCreditsGranted] = useState(0)
// Ratings
const [overallRating, setOverallRating] = useState(0)
const [easeOfUseRating, setEaseOfUseRating] = useState(0)
const [lyricsAccuracyRating, setLyricsAccuracyRating] = useState(0)
const [correctionRating, setCorrectionRating] = useState(0)
// Text fields
const [whatWentWell, setWhatWentWell] = useState('')
const [whatCouldImprove, setWhatCouldImprove] = useState('')
const [additionalComments, setAdditionalComments] = useState('')
// Checkboxes
const [wouldRecommend, setWouldRecommend] = useState(true)
const [wouldUseAgain, setWouldUseAgain] = useState(true)
const hasDetailedFeedback =
whatWentWell.length > 50 ||
whatCouldImprove.length > 50 ||
additionalComments.length > 50
const allRatingsSet =
overallRating > 0 &&
easeOfUseRating > 0 &&
lyricsAccuracyRating > 0 &&
correctionRating > 0
const canSubmit = allRatingsSet && hasDetailedFeedback && !isSubmitting
const longestText = Math.max(
whatWentWell.length,
whatCouldImprove.length,
additionalComments.length
)
const handleSubmit = async () => {
setError('')
setIsSubmitting(true)
try {
const result = await api.submitFeedback({
overall_rating: overallRating,
ease_of_use_rating: easeOfUseRating,
lyrics_accuracy_rating: lyricsAccuracyRating,
correction_experience_rating: correctionRating,
what_went_well: whatWentWell || undefined,
what_could_improve: whatCouldImprove || undefined,
additional_comments: additionalComments || undefined,
would_recommend: wouldRecommend,
would_use_again: wouldUseAgain,
})
setCreditsGranted(result.credits_granted)
setIsSuccess(true)
// Refresh user data to update credits and feedback_eligible
fetchUser()
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to submit feedback')
} finally {
setIsSubmitting(false)
}
}
const handleClose = () => {
if (isSuccess) {
// Reset form state for next time
setOverallRating(0)
setEaseOfUseRating(0)
setLyricsAccuracyRating(0)
setCorrectionRating(0)
setWhatWentWell('')
setWhatCouldImprove('')
setAdditionalComments('')
setWouldRecommend(true)
setWouldUseAgain(true)
setIsSuccess(false)
setCreditsGranted(0)
}
setError('')
onClose()
}
return (
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && handleClose()}>
<DialogContent className="sm:max-w-lg bg-card border-border max-h-[90vh] overflow-y-auto">
{isSuccess ? (
<div className="text-center py-6 space-y-4">
<CheckCircle className="w-16 h-16 text-green-500 mx-auto" />
<DialogHeader>
<DialogTitle className="text-foreground text-xl">Thank You!</DialogTitle>
<DialogDescription className="text-muted-foreground text-base">
Your feedback helps us improve Nomad Karaoke for everyone.
</DialogDescription>
</DialogHeader>
<div className="bg-green-500/10 border border-green-500/30 rounded-lg p-4 mx-auto max-w-xs">
<p className="text-2xl font-bold text-green-500">+{creditsGranted}</p>
<p className="text-sm text-muted-foreground">credits added to your account</p>
</div>
<Button onClick={handleClose} className="mt-4">
Done
</Button>
</div>
) : (
<>
<DialogHeader>
<DialogTitle className="text-foreground flex items-center gap-2">
<Gift className="w-5 h-5 text-green-500" />
Share Your Feedback — Earn 2 Free Credits
</DialogTitle>
<DialogDescription className="text-muted-foreground">
Tell us about your experience creating karaoke videos. Your feedback directly shapes what we build next.
</DialogDescription>
</DialogHeader>
<div className="space-y-5 mt-2">
{/* Star Ratings */}
<div className="grid grid-cols-2 gap-4">
<StarRating
label="Overall Experience"
value={overallRating}
onChange={setOverallRating}
/>
<StarRating
label="Ease of Use"
value={easeOfUseRating}
onChange={setEaseOfUseRating}
/>
<StarRating
label="Lyrics Accuracy"
value={lyricsAccuracyRating}
onChange={setLyricsAccuracyRating}
/>
<StarRating
label="Correction Experience"
value={correctionRating}
onChange={setCorrectionRating}
/>
</div>
{/* Text Fields */}
<div className="space-y-3">
<div className="space-y-1.5">
<Label htmlFor="went-well">What went well?</Label>
<Textarea
id="went-well"
value={whatWentWell}
onChange={(e) => setWhatWentWell(e.target.value)}
placeholder="What did you enjoy about creating karaoke videos?"
rows={2}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="could-improve">What could be better?</Label>
<Textarea
id="could-improve"
value={whatCouldImprove}
onChange={(e) => setWhatCouldImprove(e.target.value)}
placeholder="What would make the experience better?"
rows={2}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="additional">Additional comments</Label>
<Textarea
id="additional"
value={additionalComments}
onChange={(e) => setAdditionalComments(e.target.value)}
placeholder="Anything else you'd like us to know?"
rows={2}
/>
</div>
{!hasDetailedFeedback && (
<p className="text-xs text-muted-foreground">
Please write at least 50 characters in one of the fields above ({longestText}/50)
</p>
)}
</div>
{/* Checkboxes */}
<div className="space-y-3">
<div className="flex items-center gap-2">
<Checkbox
id="would-recommend"
checked={wouldRecommend}
onCheckedChange={(checked) => setWouldRecommend(checked === true)}
/>
<Label htmlFor="would-recommend" className="text-sm font-normal cursor-pointer">
I would recommend Nomad Karaoke to others
</Label>
</div>
<div className="flex items-center gap-2">
<Checkbox
id="would-use-again"
checked={wouldUseAgain}
onCheckedChange={(checked) => setWouldUseAgain(checked === true)}
/>
<Label htmlFor="would-use-again" className="text-sm font-normal cursor-pointer">
I would use Nomad Karaoke again
</Label>
</div>
</div>
{/* Error */}
{error && (
<p className="text-sm text-destructive">{error}</p>
)}
{/* Submit */}
<Button
onClick={handleSubmit}
disabled={!canSubmit}
className="w-full"
>
{isSubmitting ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Submitting...
</>
) : (
'Submit Feedback & Earn 2 Credits'
)}
</Button>
</div>
</>
)}
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,130 @@
"use client"
import { useState } from "react"
import { Lightbulb, X } from "lucide-react"
import type { BackingVocalAnalysis, AudibleSegment } from "@/lib/api"
interface InstrumentalGuidancePanelProps {
analysis: BackingVocalAnalysis
audibleSegments: AudibleSegment[]
}
export function InstrumentalGuidancePanel({
analysis,
audibleSegments,
}: InstrumentalGuidancePanelProps) {
const [guidanceDismissed, setGuidanceDismissed] = useState(() => {
if (typeof window === "undefined") return false
return localStorage.getItem("instrumentalReviewGuidanceDismissed") === "true"
})
const handleDismiss = () => {
setGuidanceDismissed(true)
if (typeof window !== "undefined") {
localStorage.setItem("instrumentalReviewGuidanceDismissed", "true")
}
}
const handleShowTips = () => {
setGuidanceDismissed(false)
if (typeof window !== "undefined") {
localStorage.removeItem("instrumentalReviewGuidanceDismissed")
}
}
const isCleanRecommended = analysis.recommended_selection === "clean"
const percentage = analysis.audible_percentage
const hasSegments = audibleSegments.length > 0
if (guidanceDismissed) {
return (
<div className="flex items-center gap-2 text-xs">
<button
className="text-amber-500 hover:text-amber-400 transition-colors"
onClick={handleShowTips}
>
Show tips
</button>
</div>
)
}
// Simple case: clean recommended with low backing vocals
if (isCleanRecommended && percentage < 10) {
return (
<div className="flex items-start gap-2 p-2.5 rounded-md bg-amber-500/10 border border-amber-500/20">
<Lightbulb className="h-4 w-4 text-amber-500 shrink-0 mt-0.5" />
<div className="text-xs text-muted-foreground flex-1 leading-relaxed space-y-1.5">
<p>
<strong>Choose your karaoke backing track.</strong> The AI separated
the vocals from the music — now pick which version sounds best.
</p>
<p>
This track has very little backing vocal content ({percentage.toFixed(0)}%).
We recommend the <strong>Clean Instrumental</strong> — just confirm
below to proceed.
</p>
<p className="text-muted-foreground/70">
Want to hear the difference? Use the audio buttons above to compare,
or click the{" "}
<span className="inline-block w-2 h-2 rounded-full bg-pink-500/60 align-middle" />{" "}
pink sections in the waveform to listen to the backing vocals.
</p>
</div>
<button
className="text-muted-foreground hover:text-foreground transition-colors shrink-0"
onClick={handleDismiss}
aria-label="Dismiss tip"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
)
}
// Complex case: backing vocals present, needs review
return (
<div className="flex items-start gap-2 p-2.5 rounded-md bg-amber-500/10 border border-amber-500/20">
<Lightbulb className="h-4 w-4 text-amber-500 shrink-0 mt-0.5" />
<div className="text-xs text-muted-foreground flex-1 leading-relaxed space-y-1.5">
<p>
<strong>Choose your karaoke backing track.</strong> The AI separated
the vocals from the music — now pick which version sounds best.
</p>
<p>
<strong>Backing vocals</strong> are the harmony/chorus voices that sing
along with the lead. Some karaoke singers prefer to keep them for guidance,
others prefer a clean instrumental.
</p>
<div className="space-y-1 pl-2 border-l-2 border-amber-500/30">
<p>
<strong>Step 1:</strong> Click the{" "}
<span className="inline-block w-2 h-2 rounded-full bg-pink-500/60 align-middle" />{" "}
pink sections in the waveform to hear the backing vocals
{hasSegments && ` (${audibleSegments.length} detected)`}.
</p>
<p>
<strong>Step 2:</strong> Decide — keep them or use the clean
instrumental? Use the audio toggle buttons above to compare.
</p>
<p>
<strong>Step 3</strong> (if needed): If you want backing vocals but
some sections have unwanted lead vocal bleed,{" "}
<kbd className="px-1 py-0.5 rounded bg-muted text-[0.65rem] font-mono">
Shift
</kbd>
+drag on the waveform to mark those sections, then click{" "}
<strong>Create Custom</strong>.
</p>
</div>
</div>
<button
className="text-muted-foreground hover:text-foreground transition-colors shrink-0"
onClick={handleDismiss}
aria-label="Dismiss tip"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
)
}
@@ -21,6 +21,7 @@ import { WaveformViewer } from "./WaveformViewer"
import { MuteRegionEditor } from "./MuteRegionEditor"
import { SelectionOptions } from "./SelectionOptions"
import { CustomUpload } from "./CustomUpload"
import { InstrumentalGuidancePanel } from "./InstrumentalGuidancePanel"
interface InstrumentalSelectorProps {
job: Job
@@ -78,6 +79,12 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
const [isShiftHeld, setIsShiftHeld] = useState(false)
const [isAudioLoading, setIsAudioLoading] = useState(false)
// Hover highlight state
const [hoveredItem, setHoveredItem] = useState<{
type: "region" | "segment"
index: number
} | null>(null)
// Derived state
const hasOriginal = analysisData?.has_original ?? false
const hasWithBacking = !!analysisData?.audio_urls.with_backing
@@ -86,6 +93,13 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
[analysisData?.analysis.audible_segments]
)
const highlightedTimeRange = useMemo(() => {
if (!hoveredItem) return null
const source = hoveredItem.type === "region" ? muteRegions : audibleSegments
const item = source[hoveredItem.index]
return item ? { start: item.start_seconds, end: item.end_seconds } : null
}, [hoveredItem, muteRegions, audibleSegments])
// Toggle play/pause - defined early so it can be used in keyboard shortcuts
const togglePlayPause = useCallback(() => {
const audio = audioRef.current
@@ -543,36 +557,27 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
const amplitudes = waveformData?.amplitudes ?? []
return (
<div className="flex flex-col h-screen bg-background p-4 gap-3 overflow-hidden">
<div className="flex flex-col min-h-screen bg-background p-2 md:p-4 gap-2 md:gap-3">
{/* Header */}
<header className="flex items-center justify-between flex-shrink-0">
<header className="flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between flex-shrink-0">
<div className="flex items-center gap-3">
<span className="text-lg font-semibold flex items-center gap-2">
<img
src="https://gen.nomadkaraoke.com/nomad-karaoke-logo.svg"
alt="Nomad Karaoke"
className="h-10"
className="h-8 md:h-10"
onError={(e) => {
e.currentTarget.style.display = "none"
}}
/>
Instrumental Review
<span className="sm:hidden">Review</span>
<span className="hidden sm:inline">Instrumental Review</span>
</span>
<span className="text-sm text-muted-foreground">
<span className="text-xs md:text-sm text-muted-foreground truncate">
{job.artist} {job.artist && job.title ? "-" : ""} {job.title}
</span>
</div>
<div className="flex items-center gap-2">
{audibleSegments.length > 0 && (
<>
<span className="px-2.5 py-1 rounded-full text-xs bg-secondary text-muted-foreground">
{audibleSegments.length} segments
</span>
<span className="px-2.5 py-1 rounded-full text-xs bg-secondary text-muted-foreground">
{analysisData?.analysis.audible_percentage.toFixed(0)}% backing vocals
</span>
</>
)}
<span
className={`px-2.5 py-1 rounded-full text-xs ${
analysisData?.analysis.recommended_selection === "clean"
@@ -582,20 +587,28 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
>
{analysisData?.analysis.recommended_selection === "clean"
? "Clean recommended"
: "Review needed"}
: "Review backing vocals"}
</span>
</div>
</header>
{/* Guidance panel */}
{analysisData && (
<InstrumentalGuidancePanel
analysis={analysisData.analysis}
audibleSegments={audibleSegments}
/>
)}
{/* Waveform Player */}
<div className="flex-1 flex flex-col bg-card border border-border rounded-xl overflow-hidden min-h-0">
<div className="min-h-[200px] md:min-h-[250px] lg:flex-1 lg:min-h-0 flex flex-col bg-card border border-border rounded-xl overflow-hidden">
{/* Toolbar */}
<div className="flex items-center justify-between px-4 py-2.5 bg-secondary border-b border-border gap-3 flex-shrink-0 flex-wrap">
<div className="flex items-center justify-between px-2 md:px-4 py-2 md:py-2.5 bg-secondary border-b border-border gap-3 flex-shrink-0 flex-wrap">
<div className="flex items-center gap-2">
<Button
size="icon"
onClick={togglePlayPause}
className="rounded-full w-8 h-8"
className="rounded-full w-9 h-9 md:w-8 md:h-8"
>
{isPlaying ? (
<Pause className="w-4 h-4" />
@@ -620,7 +633,6 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
uploadedFilename={uploadedFilename}
isLoading={isAudioLoading}
/>
<CustomUpload onUpload={handleUpload} isUploading={isUploading} />
</div>
<div className="flex items-center gap-3">
@@ -630,7 +642,7 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
key={level}
type="button"
onClick={() => setZoomLevel(level)}
className={`w-7 h-7 rounded text-xs font-medium transition-colors ${
className={`w-9 h-9 md:w-7 md:h-7 rounded text-xs font-medium transition-colors ${
zoomLevel === level
? "bg-primary text-primary-foreground"
: "text-muted-foreground hover:bg-secondary hover:text-foreground"
@@ -640,13 +652,13 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
</button>
))}
</div>
<span className="text-[10px] text-muted-foreground">
<span className="hidden md:inline text-[10px] text-muted-foreground">
<kbd className="px-1.5 py-0.5 bg-background border border-border rounded text-[10px] font-mono">
Shift
</kbd>
+drag
</span>
<kbd className="px-1.5 py-0.5 bg-background border border-border rounded text-[10px] font-mono">
<kbd className="hidden md:inline px-1.5 py-0.5 bg-background border border-border rounded text-[10px] font-mono">
Space
</kbd>
</div>
@@ -664,6 +676,7 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
onSeek={seekTo}
onRegionCreate={addRegion}
isShiftHeld={isShiftHeld}
highlightedTimeRange={highlightedTimeRange}
/>
{isAudioLoading && (
<div className="absolute inset-0 flex items-center justify-center bg-background/50 backdrop-blur-sm">
@@ -674,37 +687,54 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
</div>
)}
</div>
{/* Time axis */}
<div className="flex justify-between px-3 py-1 text-[10px] text-muted-foreground bg-black/40 flex-shrink-0">
<span>0:00</span>
<span>{formatTime(duration * 0.25)}</span>
<span>{formatTime(duration * 0.5)}</span>
<span>{formatTime(duration * 0.75)}</span>
<span>{formatTime(duration)}</span>
</div>
</div>
{/* Hidden audio element */}
<audio ref={audioRef} src={getAudioUrl()} className="hidden" />
{/* Bottom section */}
<div className="flex gap-3 flex-shrink-0">
{/* Mute regions panel */}
<MuteRegionEditor
regions={muteRegions}
audibleSegments={audibleSegments}
hasCustom={hasCustom}
isCreatingCustom={isCreatingCustom}
onRemoveRegion={removeRegion}
onClearAll={clearAllRegions}
onCreateCustom={handleCreateCustom}
onSeekTo={seekTo}
onAddSegment={addSegmentAsRegion}
/>
<div className="flex flex-col lg:flex-row gap-2 md:gap-3 flex-shrink-0">
{/* Left column: Custom Mix + Alternate Instrumental */}
<div className="flex flex-col gap-2 md:gap-3 lg:flex-1 lg:min-w-0">
<MuteRegionEditor
regions={muteRegions}
audibleSegments={audibleSegments}
hasCustom={hasCustom}
isCreatingCustom={isCreatingCustom}
onRemoveRegion={removeRegion}
onClearAll={clearAllRegions}
onCreateCustom={handleCreateCustom}
onSeekTo={seekTo}
onAddSegment={addSegmentAsRegion}
onHoverRegion={(index) =>
setHoveredItem(index !== null ? { type: "region", index } : null)
}
onHoverSegment={(index) =>
setHoveredItem(index !== null ? { type: "segment", index } : null)
}
/>
{/* Selection panel */}
<div className="w-[340px] bg-card border border-border rounded-lg p-3 flex flex-col gap-2">
{/* Alternate Instrumental section */}
<div className="bg-card border border-border rounded-lg p-3">
<div className="flex items-center justify-between">
<span className="text-sm font-semibold">Alternate Instrumental</span>
<CustomUpload onUpload={handleUpload} isUploading={isUploading} />
</div>
<p className="text-xs text-muted-foreground mt-1.5">
Have your own instrumental track? Upload it here. The file must be the
same duration as the original audio ({formatTime(duration)}) so the
synced lyrics stay aligned.
</p>
{hasUploaded && uploadedFilename && (
<p className="text-xs text-green-500 mt-1">
✓ Using: {uploadedFilename}
</p>
)}
</div>
</div>
{/* Right column: Selection panel */}
<div className="w-full lg:w-[340px] lg:flex-shrink-0 bg-card border border-border rounded-lg p-3 flex flex-col gap-2">
<SelectionOptions
value={selectedOption}
onChange={setSelectedOption}
@@ -720,9 +750,10 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
id="submit-btn"
onClick={handleSubmit}
disabled={isSubmitting}
className="mt-auto w-full"
size="lg"
className="mt-auto w-full min-h-[44px] text-base font-semibold"
>
<Check className="w-4 h-4 mr-2" />
<Check className="w-5 h-5 mr-2" />
{isSubmitting ? "Submitting..." : "Confirm & Continue"}
</Button>
</div>
@@ -14,6 +14,8 @@ interface MuteRegionEditorProps {
onCreateCustom: () => void
onSeekTo: (time: number) => void
onAddSegment: (index: number) => void
onHoverRegion?: (index: number | null) => void
onHoverSegment?: (index: number | null) => void
}
function formatTime(seconds: number): string {
@@ -33,16 +35,18 @@ export function MuteRegionEditor({
onCreateCustom,
onSeekTo,
onAddSegment,
onHoverRegion,
onHoverSegment,
}: MuteRegionEditorProps) {
const hasRegions = regions.length > 0
const hasSegments = audibleSegments.length > 0
return (
<div className="flex-1 bg-card border border-border rounded-lg p-3 flex flex-col gap-2 max-h-[140px]">
<div className="bg-card border border-border rounded-lg p-3 flex flex-col gap-2 max-h-[180px] lg:max-h-[140px]">
{/* Header */}
<div className="flex items-center justify-between">
<span className="text-sm font-semibold">
Mute Regions {hasRegions && `(${regions.length})`}
Custom Mix {hasRegions && `(${regions.length} muted)`}
</span>
{hasRegions && (
<div className="flex gap-1.5">
@@ -75,6 +79,8 @@ export function MuteRegionEditor({
<div
key={index}
className="inline-flex items-center gap-1 px-2 py-1 bg-secondary rounded text-xs"
onMouseEnter={() => onHoverRegion?.(index)}
onMouseLeave={() => onHoverRegion?.(null)}
>
<button
type="button"
@@ -94,10 +100,24 @@ export function MuteRegionEditor({
))}
</div>
) : (
<div className="text-xs text-muted-foreground">
{hasSegments
? "Click segments below or Shift + drag on waveform"
: "No backing vocals detected - clean instrumental recommended"}
<div className="text-xs text-muted-foreground space-y-1">
{hasSegments ? (
<>
<p>
Want backing vocals but hear lead vocal bleed in some sections?
Mute those sections to create a custom mix.
</p>
<p className="text-muted-foreground/70">
Click a segment below to mute it, or{" "}
<kbd className="px-1 py-0.5 rounded bg-muted text-[0.65rem] font-mono">
Shift
</kbd>
+drag on the waveform to mark a custom region.
</p>
</>
) : (
<p>No backing vocals detected — clean instrumental recommended.</p>
)}
</div>
)}
@@ -109,6 +129,8 @@ export function MuteRegionEditor({
key={index}
type="button"
onClick={() => onAddSegment(index)}
onMouseEnter={() => onHoverSegment?.(index)}
onMouseLeave={() => onHoverSegment?.(null)}
title="Add to mute regions"
className="px-1.5 py-0.5 bg-background border border-border rounded text-[10px] text-muted-foreground hover:border-primary hover:text-primary transition-colors"
>
@@ -110,6 +110,13 @@ export function SelectionOptions({
<div className="text-xs text-muted-foreground truncate">
{option.description}
</div>
{backingVocalAnalysis?.recommended_selection === option.value && (
<div className="text-[10px] text-green-500/80 mt-0.5">
{option.value === "clean"
? `Very few backing vocals detected (${backingVocalAnalysis.audible_percentage.toFixed(0)}%)`
: `Significant backing vocals (${backingVocalAnalysis.audible_percentage.toFixed(0)}%) — may enhance the karaoke experience`}
</div>
)}
</div>
</button>
))}
@@ -13,6 +13,42 @@ interface WaveformViewerProps {
onSeek: (time: number) => void
onRegionCreate: (start: number, end: number) => void
isShiftHeld: boolean
highlightedTimeRange?: { start: number; end: number } | null
}
function formatTime(seconds: number): string {
if (!Number.isFinite(seconds)) return "0:00"
const mins = Math.floor(seconds / 60)
const secs = Math.floor(seconds % 60)
return `${mins}:${secs.toString().padStart(2, "0")}`
}
const RULER_HEIGHT = 20
const NICE_INTERVALS = [1, 2, 5, 10, 15, 30, 60]
function getTickInterval(duration: number, canvasWidth: number): { major: number; minor: number } {
const targetPx = 120
const secondsPerPixel = duration / canvasWidth
const targetInterval = secondsPerPixel * targetPx
let major = NICE_INTERVALS[NICE_INTERVALS.length - 1]
for (const interval of NICE_INTERVALS) {
if (interval >= targetInterval) {
major = interval
break
}
}
// Minor ticks: subdivide major interval
let minor = major / 4
if (major >= 60) minor = 15
else if (major >= 30) minor = 10
else if (major >= 10) minor = 5
else if (major >= 5) minor = 1
else if (major >= 2) minor = 0.5
else minor = 0.25
return { major, minor }
}
export function WaveformViewer({
@@ -25,6 +61,7 @@ export function WaveformViewer({
onSeek,
onRegionCreate,
isShiftHeld,
highlightedTimeRange,
}: WaveformViewerProps) {
const canvasRef = useRef<HTMLCanvasElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
@@ -42,7 +79,8 @@ export function WaveformViewer({
const width = canvas.width
const height = canvas.height
const centerY = height / 2
const waveformHeight = height - RULER_HEIGHT
const centerY = waveformHeight / 2
// Clear with dark background
ctx.fillStyle = "#0d1117"
@@ -62,7 +100,7 @@ export function WaveformViewer({
amplitudes.forEach((amp, i) => {
const x = i * barWidth
const barHeight = Math.max(2, amp * height * 0.9)
const barHeight = Math.max(2, amp * waveformHeight * 0.9)
const y = centerY - barHeight / 2
const time = (i / amplitudes.length) * duration
@@ -89,7 +127,79 @@ export function WaveformViewer({
ctx.fillRect(x, y, Math.max(1, barWidth - 0.5), barHeight)
})
}, [amplitudes, duration, muteRegions, audibleSegments])
// Draw highlight overlay
if (highlightedTimeRange && duration > 0) {
const startX = (highlightedTimeRange.start / duration) * width
const endX = (highlightedTimeRange.end / duration) * width
// Semi-transparent white overlay on waveform area
ctx.fillStyle = "rgba(255, 255, 255, 0.12)"
ctx.fillRect(startX, 0, endX - startX, waveformHeight)
// Vertical edge lines
ctx.strokeStyle = "rgba(255, 255, 255, 0.5)"
ctx.lineWidth = 1
ctx.setLineDash([])
ctx.beginPath()
ctx.moveTo(startX, 0)
ctx.lineTo(startX, waveformHeight)
ctx.moveTo(endX, 0)
ctx.lineTo(endX, waveformHeight)
ctx.stroke()
// Pink tint in ruler area for highlighted range
ctx.fillStyle = "rgba(236, 72, 153, 0.3)"
ctx.fillRect(startX, waveformHeight, endX - startX, RULER_HEIGHT)
}
// Draw time ruler
const rulerY = waveformHeight
ctx.fillStyle = "rgba(0, 0, 0, 0.5)"
ctx.fillRect(0, rulerY, width, RULER_HEIGHT)
// Ruler top border
ctx.strokeStyle = "rgba(255, 255, 255, 0.15)"
ctx.lineWidth = 1
ctx.beginPath()
ctx.moveTo(0, rulerY)
ctx.lineTo(width, rulerY)
ctx.stroke()
if (duration > 0) {
const { major, minor } = getTickInterval(duration, width)
// Draw minor ticks
ctx.strokeStyle = "rgba(255, 255, 255, 0.15)"
ctx.lineWidth = 1
for (let t = 0; t <= duration; t += minor) {
const x = (t / duration) * width
ctx.beginPath()
ctx.moveTo(x, rulerY)
ctx.lineTo(x, rulerY + 4)
ctx.stroke()
}
// Draw major ticks with labels
ctx.strokeStyle = "rgba(255, 255, 255, 0.4)"
ctx.fillStyle = "rgba(255, 255, 255, 0.6)"
ctx.font = "10px monospace"
ctx.textBaseline = "bottom"
for (let t = 0; t <= duration; t += major) {
const x = (t / duration) * width
ctx.beginPath()
ctx.moveTo(x, rulerY)
ctx.lineTo(x, rulerY + 8)
ctx.stroke()
const label = formatTime(t)
const textWidth = ctx.measureText(label).width
// Avoid drawing label past right edge
const labelX = Math.min(x + 3, width - textWidth - 2)
ctx.fillText(label, Math.max(2, labelX), rulerY + RULER_HEIGHT - 2)
}
}
}, [amplitudes, duration, muteRegions, audibleSegments, highlightedTimeRange])
// Resize canvas
const resizeCanvas = useCallback(() => {
@@ -118,6 +228,23 @@ export function WaveformViewer({
return () => window.removeEventListener("resize", handleResize)
}, [resizeCanvas, drawWaveform])
// Auto-scroll to show highlighted range when zoomed
useEffect(() => {
const container = containerRef.current
const canvas = canvasRef.current
if (!container || !canvas || !highlightedTimeRange || !duration || zoomLevel <= 1) return
const startFraction = highlightedTimeRange.start / duration
const endFraction = highlightedTimeRange.end / duration
const centerFraction = (startFraction + endFraction) / 2
const targetScrollLeft = centerFraction * canvas.width - container.clientWidth / 2
container.scrollTo({
left: Math.max(0, targetScrollLeft),
behavior: "smooth",
})
}, [highlightedTimeRange, duration, zoomLevel])
// Calculate playhead position
const playheadPosition =
duration > 0 && canvasRef.current
@@ -0,0 +1,196 @@
import { render, screen } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { InstrumentalGuidancePanel } from "../InstrumentalGuidancePanel"
import type { BackingVocalAnalysis, AudibleSegment } from "@/lib/api"
// Mock localStorage
const localStorageMock = (() => {
let store: Record<string, string> = {}
return {
getItem: jest.fn((key: string) => store[key] || null),
setItem: jest.fn((key: string, value: string) => {
store[key] = value
}),
removeItem: jest.fn((key: string) => {
delete store[key]
}),
clear: jest.fn(() => {
store = {}
}),
}
})()
Object.defineProperty(window, "localStorage", { value: localStorageMock })
const makeAnalysis = (
overrides: Partial<BackingVocalAnalysis> = {}
): BackingVocalAnalysis => ({
audible_segments: [],
audible_percentage: 4,
recommended_selection: "clean",
...overrides,
})
const makeSegments = (count: number): AudibleSegment[] =>
Array.from({ length: count }, (_, i) => ({
start_seconds: i * 10,
end_seconds: i * 10 + 2,
}))
describe("InstrumentalGuidancePanel", () => {
beforeEach(() => {
localStorageMock.clear()
jest.clearAllMocks()
})
describe("simple case - clean recommended with low backing vocals", () => {
it("shows simplified guidance when clean recommended and < 10% backing vocals", () => {
render(
<InstrumentalGuidancePanel
analysis={makeAnalysis({ audible_percentage: 4, recommended_selection: "clean" })}
audibleSegments={[]}
/>
)
expect(screen.getByText(/Choose your karaoke backing track/)).toBeInTheDocument()
expect(screen.getByText(/very little backing vocal content/)).toBeInTheDocument()
expect(screen.getByText(/Clean Instrumental/)).toBeInTheDocument()
})
it("shows the backing vocal percentage", () => {
render(
<InstrumentalGuidancePanel
analysis={makeAnalysis({ audible_percentage: 4 })}
audibleSegments={[]}
/>
)
expect(screen.getByText(/4%/)).toBeInTheDocument()
})
})
describe("complex case - backing vocals need review", () => {
it("shows full workflow steps when backing vocals are significant", () => {
render(
<InstrumentalGuidancePanel
analysis={makeAnalysis({
audible_percentage: 25,
recommended_selection: "with_backing",
})}
audibleSegments={makeSegments(5)}
/>
)
expect(screen.getByText(/Step 1:/)).toBeInTheDocument()
expect(screen.getByText(/Step 2:/)).toBeInTheDocument()
expect(screen.getByText(/Step 3/)).toBeInTheDocument()
})
it("shows segment count in step 1", () => {
render(
<InstrumentalGuidancePanel
analysis={makeAnalysis({
audible_percentage: 25,
recommended_selection: "with_backing",
})}
audibleSegments={makeSegments(3)}
/>
)
expect(screen.getByText(/3 detected/)).toBeInTheDocument()
})
it("explains what backing vocals are", () => {
render(
<InstrumentalGuidancePanel
analysis={makeAnalysis({
audible_percentage: 25,
recommended_selection: "with_backing",
})}
audibleSegments={makeSegments(2)}
/>
)
expect(screen.getByText(/harmony\/chorus voices/)).toBeInTheDocument()
})
it("shows full steps when clean recommended but >= 10% backing vocals", () => {
render(
<InstrumentalGuidancePanel
analysis={makeAnalysis({
audible_percentage: 15,
recommended_selection: "clean",
})}
audibleSegments={makeSegments(3)}
/>
)
expect(screen.getByText(/Step 1:/)).toBeInTheDocument()
expect(screen.getByText(/Step 2:/)).toBeInTheDocument()
})
})
describe("dismissal and persistence", () => {
it("dismisses tip and stores in localStorage", async () => {
const user = userEvent.setup()
render(
<InstrumentalGuidancePanel
analysis={makeAnalysis()}
audibleSegments={[]}
/>
)
await user.click(screen.getByLabelText("Dismiss tip"))
expect(localStorageMock.setItem).toHaveBeenCalledWith(
"instrumentalReviewGuidanceDismissed",
"true"
)
expect(screen.queryByText(/Choose your karaoke backing track/)).not.toBeInTheDocument()
})
it('shows "Show tips" link after dismissal', async () => {
const user = userEvent.setup()
render(
<InstrumentalGuidancePanel
analysis={makeAnalysis()}
audibleSegments={[]}
/>
)
await user.click(screen.getByLabelText("Dismiss tip"))
expect(screen.getByText("Show tips")).toBeInTheDocument()
})
it('restores tip when "Show tips" is clicked', async () => {
const user = userEvent.setup()
render(
<InstrumentalGuidancePanel
analysis={makeAnalysis()}
audibleSegments={[]}
/>
)
await user.click(screen.getByLabelText("Dismiss tip"))
await user.click(screen.getByText("Show tips"))
expect(screen.getByText(/Choose your karaoke backing track/)).toBeInTheDocument()
expect(localStorageMock.removeItem).toHaveBeenCalledWith(
"instrumentalReviewGuidanceDismissed"
)
})
it("starts dismissed if localStorage has been set", () => {
localStorageMock.getItem.mockReturnValueOnce("true")
render(
<InstrumentalGuidancePanel
analysis={makeAnalysis()}
audibleSegments={[]}
/>
)
expect(screen.queryByText(/Choose your karaoke backing track/)).not.toBeInTheDocument()
expect(screen.getByText("Show tips")).toBeInTheDocument()
})
})
})
@@ -0,0 +1,118 @@
import { render, screen } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { MuteRegionEditor } from "../MuteRegionEditor"
import type { AudibleSegment } from "@/lib/api"
const defaultProps = {
regions: [],
audibleSegments: [] as AudibleSegment[],
hasCustom: false,
isCreatingCustom: false,
onRemoveRegion: jest.fn(),
onClearAll: jest.fn(),
onCreateCustom: jest.fn(),
onSeekTo: jest.fn(),
onAddSegment: jest.fn(),
onHoverRegion: jest.fn(),
onHoverSegment: jest.fn(),
}
describe("MuteRegionEditor", () => {
it("shows contextual help when segments exist but no regions", () => {
const segments: AudibleSegment[] = [
{ start_seconds: 10, end_seconds: 12 },
{ start_seconds: 30, end_seconds: 35 },
]
render(
<MuteRegionEditor {...defaultProps} audibleSegments={segments} />
)
expect(screen.getByText(/lead vocal bleed/)).toBeInTheDocument()
expect(screen.getByText(/custom mix/)).toBeInTheDocument()
})
it("shows clean recommendation when no segments detected", () => {
render(<MuteRegionEditor {...defaultProps} />)
expect(screen.getByText(/No backing vocals detected/)).toBeInTheDocument()
expect(screen.getByText(/clean instrumental recommended/)).toBeInTheDocument()
})
it("shows shift+drag instruction", () => {
const segments: AudibleSegment[] = [
{ start_seconds: 10, end_seconds: 12 },
]
render(
<MuteRegionEditor {...defaultProps} audibleSegments={segments} />
)
expect(screen.getByText(/drag on the waveform/)).toBeInTheDocument()
})
it('shows header as "Custom Mix" instead of "Mute Regions"', () => {
render(<MuteRegionEditor {...defaultProps} />)
expect(screen.getByText("Custom Mix")).toBeInTheDocument()
})
it("shows region count in header when regions exist", () => {
render(
<MuteRegionEditor
{...defaultProps}
regions={[
{ start_seconds: 10, end_seconds: 12 },
{ start_seconds: 30, end_seconds: 35 },
]}
/>
)
expect(screen.getByText("Custom Mix (2 muted)")).toBeInTheDocument()
})
it("calls onHoverRegion on mouse enter/leave of region tags", async () => {
const onHoverRegion = jest.fn()
const user = userEvent.setup()
render(
<MuteRegionEditor
{...defaultProps}
onHoverRegion={onHoverRegion}
regions={[
{ start_seconds: 10, end_seconds: 12 },
]}
/>
)
const regionTag = screen.getByText("0:10 - 0:12").closest("div")!
await user.hover(regionTag)
expect(onHoverRegion).toHaveBeenCalledWith(0)
await user.unhover(regionTag)
expect(onHoverRegion).toHaveBeenCalledWith(null)
})
it("calls onHoverSegment on mouse enter/leave of segment buttons", async () => {
const onHoverSegment = jest.fn()
const user = userEvent.setup()
const segments: AudibleSegment[] = [
{ start_seconds: 10, end_seconds: 12 },
]
render(
<MuteRegionEditor
{...defaultProps}
onHoverSegment={onHoverSegment}
audibleSegments={segments}
/>
)
const segmentBtn = screen.getByText("0:10 - 0:12")
await user.hover(segmentBtn)
expect(onHoverSegment).toHaveBeenCalledWith(0)
await user.unhover(segmentBtn)
expect(onHoverSegment).toHaveBeenCalledWith(null)
})
})
@@ -0,0 +1,85 @@
import { render, screen } from "@testing-library/react"
import { SelectionOptions } from "../SelectionOptions"
import type { BackingVocalAnalysis } from "@/lib/api"
const defaultProps = {
value: "clean" as const,
onChange: jest.fn(),
hasWithBacking: true,
hasOriginal: false,
hasCustom: false,
hasUploaded: false,
muteRegionsCount: 0,
}
describe("SelectionOptions", () => {
it("shows recommendation reasoning for clean instrumental", () => {
const analysis: BackingVocalAnalysis = {
audible_segments: [],
audible_percentage: 4,
recommended_selection: "clean",
}
render(
<SelectionOptions
{...defaultProps}
backingVocalAnalysis={analysis}
/>
)
expect(screen.getByText("Recommended")).toBeInTheDocument()
expect(screen.getByText(/Very few backing vocals detected \(4%\)/)).toBeInTheDocument()
})
it("shows recommendation reasoning for with_backing", () => {
const analysis: BackingVocalAnalysis = {
audible_segments: [],
audible_percentage: 25,
recommended_selection: "with_backing",
}
render(
<SelectionOptions
{...defaultProps}
value="with_backing"
backingVocalAnalysis={analysis}
/>
)
expect(screen.getByText("Recommended")).toBeInTheDocument()
expect(screen.getByText(/Significant backing vocals \(25%\)/)).toBeInTheDocument()
})
it("does not show reasoning for non-recommended options", () => {
const analysis: BackingVocalAnalysis = {
audible_segments: [],
audible_percentage: 4,
recommended_selection: "clean",
}
render(
<SelectionOptions
{...defaultProps}
backingVocalAnalysis={analysis}
/>
)
// Only one recommendation reasoning text
const reasoningTexts = screen.getAllByText(/backing vocals/)
// "No backing vocals" (description) + "Very few backing vocals detected" (reasoning) + "All backing vocals included" (description)
expect(reasoningTexts.length).toBeGreaterThanOrEqual(1)
})
it("shows custom option with region count when available", () => {
render(
<SelectionOptions
{...defaultProps}
hasCustom={true}
muteRegionsCount={3}
/>
)
expect(screen.getByText("Custom")).toBeInTheDocument()
expect(screen.getByText("3 regions muted")).toBeInTheDocument()
})
})
+359
View File
@@ -0,0 +1,359 @@
"use client"
import { useState } from "react"
import { useAuth } from "@/lib/auth"
import { useTenant } from "@/lib/tenant"
import { api, ApiError } from "@/lib/api"
import { AlertTriangle, CheckCircle2, Music } from "lucide-react"
import { Button } from "@/components/ui/button"
import Link from "next/link"
import { SongInfoStep } from "./steps/SongInfoStep"
import { AudioSourceStep } from "./steps/AudioSourceStep"
import { CustomizeStep } from "./steps/CustomizeStep"
interface GuidedJobFlowProps {
onJobCreated: () => void
}
type Step = 1 | 2 | 3
const STEP_LABELS = ["Song Info", "Choose Audio", "Customize & Create"]
export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
const { user } = useAuth()
const { features } = useTenant()
const isAdmin = user?.role === "admin"
const noCredits = !isAdmin && user?.credits === 0
const [step, setStep] = useState<Step>(1)
const [showSuccess, setShowSuccess] = useState(false)
// Form state (persists across steps)
const [artist, setArtist] = useState("")
const [title, setTitle] = useState("")
const [displayArtist, setDisplayArtist] = useState("")
const [displayTitle, setDisplayTitle] = useState("")
const [isPrivate, setIsPrivate] = useState(false)
// Job tracking
const [jobId, setJobId] = useState<string | null>(null)
const [audioSource, setAudioSource] = useState<"search" | "upload" | "url">("search")
const [selectedResultIndex, setSelectedResultIndex] = useState<number | null>(null)
// Submission state
const [isSubmitting, setIsSubmitting] = useState(false)
const [submitError, setSubmitError] = useState("")
function handleJobCreated(id: string, source: "search" | "upload" | "url") {
setJobId(id)
setAudioSource(source)
}
function handleSearchResultChosen(resultIndex: number) {
// Just store the choice — don't call selectAudioResult yet
// The job stays in awaiting_audio_selection (hidden from Recent Jobs)
setSelectedResultIndex(resultIndex)
setStep(3)
}
function handleFallbackComplete() {
// Upload/URL jobs are already processing — show success directly
onJobCreated()
setShowSuccess(true)
}
async function handleConfirm() {
if (!jobId || selectedResultIndex === null) return
setIsSubmitting(true)
setSubmitError("")
try {
// NOW we trigger the actual audio selection + processing
await api.selectAudioResult(jobId, selectedResultIndex)
onJobCreated()
setShowSuccess(true)
} catch (err) {
if (err instanceof ApiError) {
setSubmitError(err.message)
} else {
setSubmitError("Failed to start processing. Please try again.")
}
} finally {
setIsSubmitting(false)
}
}
async function handleBackFromAudio(jobIdToCleanup: string | null) {
// Clean up the stale job (best-effort, don't block on failure)
if (jobIdToCleanup) {
api.deleteJob(jobIdToCleanup).catch(() => {
// Silently ignore cleanup failures
})
}
setJobId(null)
setAudioSource("search")
setSelectedResultIndex(null)
setStep(1)
}
function resetFlow() {
setStep(1)
setShowSuccess(false)
setArtist("")
setTitle("")
setDisplayArtist("")
setDisplayTitle("")
setIsPrivate(false)
setJobId(null)
setAudioSource("search")
setSelectedResultIndex(null)
setSubmitError("")
}
// Success state
if (showSuccess) {
const effectiveArtist = displayArtist.trim() || artist
const effectiveTitle = displayTitle.trim() || title
return (
<div className="space-y-5">
<div className="flex flex-col items-center text-center py-5 space-y-3">
<div
className="w-12 h-12 rounded-full flex items-center justify-center"
style={{ backgroundColor: 'rgba(34, 197, 94, 0.15)' }}
>
<CheckCircle2 className="w-7 h-7 text-green-500" />
</div>
<div>
<h2 className="text-lg font-semibold" style={{ color: 'var(--text)' }}>
Job Created
</h2>
<p className="text-sm mt-1" style={{ color: 'var(--text-muted)' }}>
<span className="font-medium" style={{ color: 'var(--text)' }}>{effectiveArtist} - {effectiveTitle}</span>
</p>
{jobId && (
<p className="text-xs mt-0.5 font-mono" style={{ color: 'var(--text-muted)' }} data-testid="created-job-id">
ID: {jobId.slice(0, 8)}
</p>
)}
</div>
</div>
{/* Timeline */}
<p className="text-xs font-semibold uppercase tracking-wider" style={{ color: 'var(--text-muted)' }}>What happens next</p>
<div className="space-y-0 mt-3">
{/* Step 1: Automated processing */}
<div className="flex gap-3">
<div className="flex flex-col items-center">
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 bg-blue-500/15">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" className="text-blue-400">
<path d="M8 1.5a1.25 1.25 0 0 1 1.177.825l.573 1.608 1.608.573a1.25 1.25 0 0 1 0 2.354l-1.608.573-.573 1.608a1.25 1.25 0 0 1-2.354 0l-.573-1.608-1.608-.573a1.25 1.25 0 0 1 0-2.354l1.608-.573.573-1.608A1.25 1.25 0 0 1 8 1.5Z" fill="currentColor" opacity="0.85"/>
<path d="M12 9a1 1 0 0 1 .94.66l.36 1.02 1.02.36a1 1 0 0 1 0 1.884l-1.02.36-.36 1.02a1 1 0 0 1-1.88 0l-.36-1.02-1.02-.36a1 1 0 0 1 0-1.884l1.02-.36.36-1.02A1 1 0 0 1 12 9Z" fill="currentColor" opacity="0.55"/>
</svg>
</div>
<div className="w-px flex-1 min-h-[20px]" style={{ backgroundColor: 'var(--card-border)' }} />
</div>
<div className="pb-4 pt-1">
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>Audio processing</p>
<p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>
We download the audio, separate vocals from the instrumental, and transcribe the lyrics. <span className="font-medium" style={{ color: 'var(--text)' }}>~10 minutes</span>
</p>
<span className="inline-block mt-1.5 text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-blue-500/15 text-blue-400">
Automatic
</span>
</div>
</div>
{/* Step 2: User review */}
<div className="flex gap-3">
<div className="flex flex-col items-center">
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0" style={{ backgroundColor: 'rgba(255, 122, 204, 0.15)' }}>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{ color: 'var(--brand-pink)' }}>
<path d="M8 2a3 3 0 1 0 0 6 3 3 0 0 0 0-6ZM3.5 13.5c0-2.485 2.015-4.5 4.5-4.5s4.5 2.015 4.5 4.5a.5.5 0 0 1-.5.5h-8a.5.5 0 0 1-.5-.5Z" fill="currentColor" opacity="0.85"/>
</svg>
</div>
<div className="w-px flex-1 min-h-[20px]" style={{ backgroundColor: 'var(--card-border)' }} />
</div>
<div className="pb-4 pt-1">
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>You review the lyrics & instrumental</p>
<p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>
Check the lyrics and listen to the instrumental. Fix any errors and approve.
</p>
<div className="flex items-center gap-2 mt-1.5 flex-wrap">
<span className="inline-block text-[10px] px-1.5 py-0.5 rounded-full font-medium" style={{ backgroundColor: 'rgba(255, 122, 204, 0.15)', color: 'var(--brand-pink)' }}>
You
</span>
<span className="flex items-center gap-1 text-[10px]" style={{ color: 'var(--text-muted)' }}>
<svg width="12" height="12" viewBox="0 0 16 16" fill="none">
<path d="M2 3.5A1.5 1.5 0 0 1 3.5 2h9A1.5 1.5 0 0 1 14 3.5v.401a1 1 0 0 1-.373.78L8.707 8.79a1 1 0 0 1-1.414 0L2.373 4.68A1 1 0 0 1 2 3.9V3.5Z" fill="currentColor" opacity="0.7"/>
<path d="M2 6.12l4.586 3.59a2 2 0 0 0 2.828 0L14 6.12V12.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 12.5V6.12Z" fill="currentColor" opacity="0.5"/>
</svg>
Email + chime when ready
</span>
</div>
</div>
</div>
{/* Step 3: Final render */}
<div className="flex gap-3">
<div className="flex flex-col items-center">
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 bg-green-500/15">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" className="text-green-400">
<path d="M3 2.5A1.5 1.5 0 0 1 4.5 1h7A1.5 1.5 0 0 1 13 2.5v11a.5.5 0 0 1-.765.424L8 11.28l-4.235 2.644A.5.5 0 0 1 3 13.5v-11Z" fill="currentColor" opacity="0.5"/>
<path d="M6.354 7.854 7.5 9l2.146-2.146a.5.5 0 0 0-.708-.708L7.5 7.586l-.646-.647a.5.5 0 1 0-.708.708l.208.207Z" fill="currentColor"/>
</svg>
</div>
</div>
<div className="pt-1">
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>Video delivered</p>
<p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>
After you approve, your karaoke video is rendered and uploaded. <span className="font-medium" style={{ color: 'var(--text)' }}>~10 minutes</span>
</p>
<div className="flex items-center gap-2 mt-1.5 flex-wrap">
<span className="inline-block text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-green-500/15 text-green-400">
Automatic
</span>
<span className="flex items-center gap-1 text-[10px]" style={{ color: 'var(--text-muted)' }}>
<svg width="12" height="12" viewBox="0 0 16 16" fill="none">
<path d="M2 3.5A1.5 1.5 0 0 1 3.5 2h9A1.5 1.5 0 0 1 14 3.5v.401a1 1 0 0 1-.373.78L8.707 8.79a1 1 0 0 1-1.414 0L2.373 4.68A1 1 0 0 1 2 3.9V3.5Z" fill="currentColor" opacity="0.7"/>
<path d="M2 6.12l4.586 3.59a2 2 0 0 0 2.828 0L14 6.12V12.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 12.5V6.12Z" fill="currentColor" opacity="0.5"/>
</svg>
Email with link to view
</span>
</div>
</div>
</div>
</div>
<p className="text-[10px] text-center" style={{ color: 'var(--text-muted)' }}>
Track progress in the <span className="font-medium" style={{ color: 'var(--text)' }}>Recent Jobs</span> list. Keep this tab open to hear the chime.
</p>
<Button
onClick={resetFlow}
variant="outline"
className="w-full"
style={{ borderColor: 'var(--card-border)', color: 'var(--text)' }}
>
<Music className="w-4 h-4 mr-2" />
Create Another
</Button>
</div>
)
}
return (
<div className="space-y-4">
{/* Zero-credit warning banner */}
{noCredits && (
<div className="flex items-start gap-2 rounded-lg p-3 border border-amber-500/30 bg-amber-500/10">
<AlertTriangle className="w-5 h-5 text-amber-500 shrink-0 mt-0.5" />
<div className="text-sm" style={{ color: 'var(--text)' }}>
<p>You have no credits remaining. Buy credits to create new karaoke videos.</p>
<Link
href="/#pricing"
className="inline-block mt-1 text-sm font-medium underline"
style={{ color: 'var(--brand-pink)' }}
>
Buy Credits
</Link>
</div>
</div>
)}
{/* Step indicator */}
<div className="flex items-center gap-1" role="navigation" aria-label="Progress">
{STEP_LABELS.map((label, i) => {
const stepNum = (i + 1) as Step
const isActive = step === stepNum
const isCompleted = step > stepNum
return (
<div key={label} className="flex items-center gap-1 flex-1">
<div className="flex items-center gap-1.5 shrink-0">
<div
className={`w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-semibold shrink-0 transition-colors ${
isActive
? 'bg-[var(--brand-pink)] text-white'
: isCompleted
? 'bg-[var(--brand-pink)]/20 text-[var(--brand-pink)]'
: 'bg-[var(--secondary)] text-[var(--text-muted)]'
}`}
>
{isCompleted ? "\u2713" : stepNum}
</div>
<span
className={`text-[10px] whitespace-nowrap transition-colors ${
isActive ? 'font-medium' : ''
}`}
style={{ color: isActive ? 'var(--text)' : 'var(--text-muted)' }}
>
{label}
</span>
</div>
{i < STEP_LABELS.length - 1 && (
<div
className="h-px flex-1 mx-1 hidden sm:block"
style={{
backgroundColor: isCompleted ? 'var(--brand-pink)' : 'var(--card-border)',
opacity: isCompleted ? 0.4 : 1,
}}
/>
)}
</div>
)
})}
</div>
{/* Submit error */}
{submitError && (
<div className="text-sm text-red-400 bg-red-500/10 rounded p-3">
<p>{submitError}</p>
</div>
)}
{/* Step content */}
{step === 1 && (
<SongInfoStep
artist={artist}
title={title}
onArtistChange={setArtist}
onTitleChange={setTitle}
onNext={() => setStep(2)}
disabled={noCredits}
/>
)}
{step === 2 && (
<AudioSourceStep
artist={artist}
title={title}
displayArtist={displayArtist}
displayTitle={displayTitle}
isPrivate={isPrivate}
onJobCreated={handleJobCreated}
onSearchResultChosen={handleSearchResultChosen}
onFallbackComplete={handleFallbackComplete}
onBack={handleBackFromAudio}
noCredits={noCredits}
/>
)}
{step === 3 && (
<CustomizeStep
artist={artist}
title={title}
displayArtist={displayArtist}
displayTitle={displayTitle}
onDisplayArtistChange={setDisplayArtist}
onDisplayTitleChange={setDisplayTitle}
isPrivate={isPrivate}
onPrivateChange={setIsPrivate}
onConfirm={handleConfirm}
onBack={() => setStep(2)}
isSubmitting={isSubmitting}
/>
)}
</div>
)
}
+1
View File
@@ -200,6 +200,7 @@ export function JobCard({ job, onRefresh }: JobCardProps) {
open={showAudioSearch}
onClose={() => setShowAudioSearch(false)}
onSelect={onRefresh}
searchTitle={job.title}
/>
</div>
)
+7 -88
View File
@@ -63,10 +63,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
const [displayTitle, setDisplayTitle] = useState("")
const [showDisplayAs, setShowDisplayAs] = useState(false)
// Non-interactive mode (shared across all tabs)
const [nonInteractive, setNonInteractive] = useState(false)
// Private (non-published) mode - Dropbox only, no YouTube/GDrive
// Private (no YouTube upload) mode - Dropbox only, no YouTube/GDrive
const [isPrivate, setIsPrivate] = useState(false)
// Credit enforcement
@@ -89,7 +86,6 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
setIsSubmitting(true)
try {
await api.uploadJob(uploadFile, uploadArtist.trim(), uploadTitle.trim(), {
non_interactive: nonInteractive,
is_private: isPrivate,
})
setUploadFile(null)
@@ -131,7 +127,6 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
youtubeArtist.trim(),
youtubeTitle.trim(),
{
non_interactive: nonInteractive,
is_private: isPrivate,
}
)
@@ -166,7 +161,6 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
setIsSubmitting(true)
try {
await api.searchAudio(searchArtist.trim(), searchTitle.trim(), false, {
non_interactive: nonInteractive,
is_private: isPrivate,
// Display overrides (empty string means use search values)
display_artist: displayArtist.trim() || undefined,
@@ -322,32 +316,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
<span className="text-amber-500 font-medium">Note:</span> Format these exactly as you want them on the title card and video filename.
</p>
{/* Non-interactive mode (admin only) */}
{isAdmin && (
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
<div className="flex items-start gap-3">
<input
type="checkbox"
id="non-interactive-upload"
checked={nonInteractive}
onChange={(e) => setNonInteractive(e.target.checked)}
disabled={isSubmitting}
className="mt-1 w-4 h-4 rounded border-border bg-secondary accent-[var(--brand-pink)] focus:ring-[var(--brand-pink)] focus:ring-offset-background"
/>
<div>
<Label htmlFor="non-interactive-upload" className="cursor-pointer" style={{ color: 'var(--text)' }}>
Skip lyrics review (non-interactive)
</Label>
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
<span className="text-amber-500 font-medium">Warning:</span> auto lyrics correction isn&apos;t perfect.
Skipping review will likely result in incorrect words in your karaoke video.
</p>
</div>
</div>
</div>
)}
{/* Private (non-published) mode */}
{/* Private (no YouTube upload) mode */}
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
<div className="flex items-start gap-3">
<input
@@ -360,7 +329,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
/>
<div>
<Label htmlFor="private-upload" className="cursor-pointer" style={{ color: 'var(--text)' }}>
Private (non-published)
Private (no YouTube upload)
</Label>
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
Files delivered via Dropbox only. No YouTube or Google Drive upload.
@@ -444,32 +413,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
<span className="text-amber-500 font-medium">Note:</span> Format these exactly as you want them on the title card and video filename.
</p>
{/* Non-interactive mode (admin only) */}
{isAdmin && (
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
<div className="flex items-start gap-3">
<input
type="checkbox"
id="non-interactive-url"
checked={nonInteractive}
onChange={(e) => setNonInteractive(e.target.checked)}
disabled={isSubmitting}
className="mt-1 w-4 h-4 rounded border-border bg-secondary accent-[var(--brand-pink)] focus:ring-[var(--brand-pink)] focus:ring-offset-background"
/>
<div>
<Label htmlFor="non-interactive-url" className="cursor-pointer" style={{ color: 'var(--text)' }}>
Skip lyrics review (non-interactive)
</Label>
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
<span className="text-amber-500 font-medium">Warning:</span> auto lyrics correction isn&apos;t perfect.
Skipping review will likely result in incorrect words in your karaoke video.
</p>
</div>
</div>
</div>
)}
{/* Private (non-published) mode */}
{/* Private (no YouTube upload) mode */}
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
<div className="flex items-start gap-3">
<input
@@ -482,7 +426,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
/>
<div>
<Label htmlFor="private-url" className="cursor-pointer" style={{ color: 'var(--text)' }}>
Private (non-published)
Private (no YouTube upload)
</Label>
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
Files delivered via Dropbox only. No YouTube or Google Drive upload.
@@ -604,32 +548,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
)}
</div>
{/* Non-interactive mode (admin only) */}
{isAdmin && (
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
<div className="flex items-start gap-3">
<input
type="checkbox"
id="non-interactive-search"
checked={nonInteractive}
onChange={(e) => setNonInteractive(e.target.checked)}
disabled={isSubmitting}
className="mt-1 w-4 h-4 rounded border-border bg-secondary accent-[var(--brand-pink)] focus:ring-[var(--brand-pink)] focus:ring-offset-background"
/>
<div>
<Label htmlFor="non-interactive-search" className="cursor-pointer" style={{ color: 'var(--text)' }}>
Skip lyrics review (non-interactive)
</Label>
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
<span className="text-amber-500 font-medium">Warning:</span> auto lyrics correction isn&apos;t perfect.
Skipping review will likely result in incorrect words in your karaoke video.
</p>
</div>
</div>
</div>
)}
{/* Private (non-published) mode */}
{/* Private (no YouTube upload) mode */}
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
<div className="flex items-start gap-3">
<input
@@ -642,7 +561,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
/>
<div>
<Label htmlFor="private-search" className="cursor-pointer" style={{ color: 'var(--text)' }}>
Private (non-published)
Private (no YouTube upload)
</Label>
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
Files delivered via Dropbox only. No YouTube or Google Drive upload.
@@ -0,0 +1,193 @@
"use client"
import { useRef, useEffect, useCallback } from "react"
interface TitleCardPreviewProps {
artist: string
title: string
}
// Matches the Nomad theme title card (style_params.json from GCS):
// - 3840x2160 canvas (16:9)
// - Background: karaoke-title-screen-background-nomad-4k.png
// - Font: AvenirNext-Bold.ttf
// - Title: white (#ffffff), uppercase, region 370,980,3100,350
// - Artist: golden yellow (#ffdf6b), uppercase, region 370,1400,3100,450
const CANVAS_W = 3840
const CANVAS_H = 2160
// Title region: x=370, y=980, w=3100, h=350
const TITLE_X = 370
const TITLE_Y = 980
const TITLE_W = 3100
const TITLE_H = 350
// Artist region: x=370, y=1400, w=3100, h=450
const ARTIST_X = 370
const ARTIST_Y = 1400
const ARTIST_W = 3100
const ARTIST_H = 450
const TITLE_COLOR = "#ffffff"
const ARTIST_COLOR = "#ffdf6b"
let bgImageCache: HTMLImageElement | null = null
function loadBgImage(): Promise<HTMLImageElement> {
if (bgImageCache?.complete) return Promise.resolve(bgImageCache)
return new Promise((resolve, reject) => {
const img = new Image()
img.onload = () => {
bgImageCache = img
resolve(img)
}
img.onerror = reject
img.src = "/title-card-bg.png"
})
}
function fitText(
ctx: CanvasRenderingContext2D,
text: string,
maxWidth: number,
maxHeight: number,
fontFamily: string,
): { fontSize: number; lines: string[] } {
for (let size = 500; size >= 40; size -= 10) {
ctx.font = `700 ${size}px ${fontFamily}`
const metrics = ctx.measureText(text)
if (metrics.width <= maxWidth) {
return { fontSize: size, lines: [text] }
}
// Try 2-line split
const words = text.split(" ")
if (words.length >= 2) {
let bestSplit = 1
let bestDiff = Infinity
for (let i = 1; i < words.length; i++) {
const line1 = words.slice(0, i).join(" ")
const line2 = words.slice(i).join(" ")
const diff = Math.abs(ctx.measureText(line1).width - ctx.measureText(line2).width)
if (diff < bestDiff) {
bestDiff = diff
bestSplit = i
}
}
const line1 = words.slice(0, bestSplit).join(" ")
const line2 = words.slice(bestSplit).join(" ")
const w1 = ctx.measureText(line1).width
const w2 = ctx.measureText(line2).width
const lineHeight = size * 1.1
if (Math.max(w1, w2) <= maxWidth && lineHeight * 2 <= maxHeight) {
return { fontSize: size, lines: [line1, line2] }
}
}
}
return { fontSize: 40, lines: [text] }
}
function drawTextBlock(
ctx: CanvasRenderingContext2D,
text: string,
regionX: number,
regionY: number,
regionW: number,
regionH: number,
color: string,
fontFamily: string,
) {
if (!text) return
ctx.fillStyle = color
ctx.textAlign = "center"
ctx.textBaseline = "middle"
const { fontSize, lines } = fitText(ctx, text, regionW, regionH, fontFamily)
ctx.font = `700 ${fontSize}px ${fontFamily}`
const lineHeight = fontSize * 1.1
const totalHeight = lineHeight * lines.length
const startY = regionY + (regionH - totalHeight) / 2 + lineHeight / 2
for (let i = 0; i < lines.length; i++) {
ctx.fillText(lines[i], regionX + regionW / 2, startY + i * lineHeight)
}
}
export function TitleCardPreview({ artist, title }: TitleCardPreviewProps) {
const canvasRef = useRef<HTMLCanvasElement>(null)
const draw = useCallback(async () => {
const canvas = canvasRef.current
if (!canvas) return
const ctx = canvas.getContext("2d")
if (!ctx) return
// Draw background image (or black fallback)
try {
const bgImg = await loadBgImage()
ctx.drawImage(bgImg, 0, 0, CANVAS_W, CANVAS_H)
} catch {
ctx.fillStyle = "#000000"
ctx.fillRect(0, 0, CANVAS_W, CANVAS_H)
}
// Get computed font family from CSS variable
const computedFont = getComputedStyle(canvas).getPropertyValue("--font-title-card").trim()
const fontFamily = computedFont || "'AvenirNext-Bold', 'Avenir Next', sans-serif"
// Ensure font is loaded before rendering — canvas doesn't participate in CSS
// font swap, so we must explicitly wait for the font to be available.
const fontSpec = `700 100px ${fontFamily}`
if (!document.fonts.check(fontSpec)) {
try {
await document.fonts.load(fontSpec)
} catch {
// Font failed to load; will render with fallback
}
}
// Apply uppercase transform (matching style_params.json title_text_transform/artist_text_transform)
const titleText = (title || "Song Title").toUpperCase()
const artistText = (artist || "Artist").toUpperCase()
// Draw title (white)
drawTextBlock(
ctx,
titleText,
TITLE_X, TITLE_Y, TITLE_W, TITLE_H,
title ? TITLE_COLOR : "rgba(255,255,255,0.25)",
fontFamily,
)
// Draw artist (golden yellow)
drawTextBlock(
ctx,
artistText,
ARTIST_X, ARTIST_Y, ARTIST_W, ARTIST_H,
artist ? ARTIST_COLOR : "rgba(255,223,107,0.25)",
fontFamily,
)
}, [artist, title])
useEffect(() => {
draw()
}, [draw])
return (
<canvas
ref={canvasRef}
width={CANVAS_W}
height={CANVAS_H}
className="w-full rounded-lg"
style={{
aspectRatio: "16/9",
border: "1px solid var(--card-border)",
}}
/>
)
}
@@ -0,0 +1,147 @@
import { render, act } from "@testing-library/react"
import { TitleCardPreview } from "../TitleCardPreview"
// Module-level state shared with mock closures via reference
const state = {
fillTextCalls: [] as Array<{ text: string; font: string }>,
currentFont: "",
fontCheckReturn: true,
fontLoadResolve: null as (() => void) | null,
}
// Mock Image globally before any module code runs
global.Image = class MockImage {
onload: (() => void) | null = null
onerror: (() => void) | null = null
_src = ""
complete = true
get src() {
return this._src
}
set src(v: string) {
this._src = v
// Fire synchronously to avoid timing issues in tests
Promise.resolve().then(() => this.onload?.())
}
} as unknown as typeof Image
function setupMocks() {
state.fillTextCalls = []
state.currentFont = ""
state.fontCheckReturn = true
state.fontLoadResolve = null
HTMLCanvasElement.prototype.getContext = jest.fn(() => ({
drawImage: jest.fn(),
fillRect: jest.fn(),
fillText: jest.fn((text: string) => {
state.fillTextCalls.push({ text, font: state.currentFont })
}),
measureText: jest.fn(() => ({ width: 100 })),
get font() {
return state.currentFont
},
set font(v: string) {
state.currentFont = v
},
fillStyle: "",
textAlign: "",
textBaseline: "",
})) as unknown as typeof HTMLCanvasElement.prototype.getContext
window.getComputedStyle = jest.fn(() => ({
getPropertyValue: (prop: string) => {
if (prop === "--font-title-card") return "'__AvenirNext_abc123'"
return ""
},
})) as unknown as typeof window.getComputedStyle
Object.defineProperty(document, "fonts", {
value: {
check: jest.fn(() => state.fontCheckReturn),
load: jest.fn(
() =>
new Promise<void>((resolve) => {
state.fontLoadResolve = resolve
}),
),
ready: Promise.resolve(),
},
writable: true,
configurable: true,
})
}
beforeEach(() => {
setupMocks()
})
describe("TitleCardPreview", () => {
it("renders title and artist text in uppercase", async () => {
await act(async () => {
render(<TitleCardPreview title="My Song" artist="Cool Band" />)
await new Promise((r) => setTimeout(r, 100))
})
const texts = state.fillTextCalls.map((c) => c.text)
expect(texts).toContain("MY SONG")
expect(texts).toContain("COOL BAND")
})
it("uses font from CSS variable for canvas text", async () => {
await act(async () => {
render(<TitleCardPreview title="Test" artist="Artist" />)
await new Promise((r) => setTimeout(r, 100))
})
const fonts = state.fillTextCalls.map((c) => c.font)
expect(fonts.length).toBeGreaterThan(0)
expect(fonts.every((f) => f.includes("'__AvenirNext_abc123'"))).toBe(true)
})
it("skips document.fonts.load when font is already available", async () => {
state.fontCheckReturn = true
await act(async () => {
render(<TitleCardPreview title="Song" artist="Artist" />)
await new Promise((r) => setTimeout(r, 100))
})
expect(document.fonts.check).toHaveBeenCalledWith(
expect.stringContaining("'__AvenirNext_abc123'"),
)
expect(document.fonts.load).not.toHaveBeenCalled()
})
it("calls document.fonts.load when font is not yet available", async () => {
state.fontCheckReturn = false
await act(async () => {
render(<TitleCardPreview title="Song" artist="Artist" />)
await new Promise((r) => setTimeout(r, 100))
// Resolve the pending font load promise
state.fontLoadResolve?.()
await new Promise((r) => setTimeout(r, 100))
})
expect(document.fonts.check).toHaveBeenCalledWith(
expect.stringContaining("'__AvenirNext_abc123'"),
)
expect(document.fonts.load).toHaveBeenCalledWith(
expect.stringContaining("'__AvenirNext_abc123'"),
)
})
it("still renders text if font load fails", async () => {
state.fontCheckReturn = false
;(document.fonts as { load: jest.Mock }).load = jest.fn().mockRejectedValue(new Error("fail"))
await act(async () => {
render(<TitleCardPreview title="Fallback" artist="Test" />)
await new Promise((r) => setTimeout(r, 100))
})
const texts = state.fillTextCalls.map((c) => c.text)
expect(texts).toContain("FALLBACK")
})
})
@@ -0,0 +1,995 @@
"use client"
import { useState, useEffect, useMemo, useCallback, useRef } from "react"
import { api, ApiError } from "@/lib/api"
import {
ExtendedAudioSearchResult,
groupResults,
getSearchConfidence,
getAvailabilityLabel,
checkFilenameMismatch,
getDisplayName,
formatCount,
formatMetadata,
formatQuality,
SearchConfidence,
} from "@/lib/audio-search-utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Loader2, Music2, ChevronDown, ChevronUp, Upload, Youtube, ArrowLeft, Check, AlertTriangle, CheckCircle2, Lightbulb } from "lucide-react"
import Link from "next/link"
interface AudioSourceStepProps {
artist: string
title: string
displayArtist: string
displayTitle: string
isPrivate: boolean
onJobCreated: (jobId: string, source: "search" | "upload" | "url") => void
onSearchResultChosen: (resultIndex: number) => void
onFallbackComplete: () => void
onBack: (jobIdToCleanup: string | null) => void
noCredits: boolean
}
/** Render an availability badge with tooltip */
function AvailabilityBadge({ seeders }: { seeders: number | undefined | null }) {
if (seeders === undefined || seeders === null) return null
const { text, tooltip } = getAvailabilityLabel(seeders)
if (!text) return null
return (
<span
title={tooltip}
className={`text-[8px] px-1 py-0.5 rounded font-medium cursor-help ${
seeders >= 50 ? 'bg-green-600/20 text-green-400' :
seeders >= 10 ? 'bg-yellow-600/20 text-yellow-400' :
'bg-red-600/20 text-red-400'
}`}
>
{text} avail.
</span>
)
}
/** Render a color-coded view count badge */
function ViewCountBadge({ viewCount }: { viewCount: number | undefined | null }) {
if (viewCount === undefined || viewCount === null) return null
const color = viewCount >= 1_000_000 ? 'bg-green-600/20 text-green-400' :
viewCount >= 100_000 ? 'bg-yellow-600/20 text-yellow-400' :
'bg-[var(--secondary)] text-[var(--text-muted)]'
const tooltip = viewCount >= 1_000_000 ? 'Very popular — likely the right track' :
viewCount >= 100_000 ? 'Moderately popular' :
'Low view count — verify this is the right track'
return (
<span
title={tooltip}
className={`text-[8px] px-1 py-0.5 rounded font-medium cursor-help ${color}`}
>
{formatCount(viewCount)} views
</span>
)
}
/** Render a filename mismatch badge */
function MismatchBadge({ searchTitle, result }: { searchTitle: string; result: ExtendedAudioSearchResult }) {
const mismatch = useMemo(() => checkFilenameMismatch(searchTitle, result), [searchTitle, result])
if (!mismatch.isMismatch) return null
return (
<span
title={`Expected "${searchTitle}" but filename is "${mismatch.filename}"${mismatch.suggestedTrack ? ` (looks like "${mismatch.suggestedTrack}")` : ''}`}
className="text-[8px] px-1 py-0.5 rounded font-medium bg-yellow-600/20 text-yellow-400 cursor-help"
>
Wrong track?
</span>
)
}
export function AudioSourceStep({
artist,
title,
displayArtist,
displayTitle,
isPrivate,
onJobCreated,
onSearchResultChosen,
onFallbackComplete,
onBack,
noCredits,
}: AudioSourceStepProps) {
const [results, setResults] = useState<ExtendedAudioSearchResult[]>([])
const [isSearching, setIsSearching] = useState(true)
const [jobId, setJobId] = useState<string | null>(null)
const [error, setError] = useState("")
const [isCreditError, setIsCreditError] = useState(false)
const [showOtherOptions, setShowOtherOptions] = useState(false)
const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set())
const searchTriggered = useRef(false)
// Fallback form state
const [uploadFile, setUploadFile] = useState<File | null>(null)
const [youtubeUrl, setYoutubeUrl] = useState("")
const [isSubmittingFallback, setIsSubmittingFallback] = useState(false)
const [fallbackMode, setFallbackMode] = useState<"upload" | "url" | null>(null)
// Auto-trigger search on mount
const triggerSearch = useCallback(async () => {
if (searchTriggered.current) return
searchTriggered.current = true
setIsSearching(true)
setError("")
setIsCreditError(false)
try {
const response = await api.searchAudio(artist, title, false, {
is_private: isPrivate,
display_artist: displayArtist.trim() || undefined,
display_title: displayTitle.trim() || undefined,
})
setJobId(response.job_id)
onJobCreated(response.job_id, "search")
// Now poll for results
await pollForResults(response.job_id)
} catch (err) {
if (err instanceof ApiError && err.status === 402) {
setIsCreditError(true)
setError("You're out of credits. Buy more to continue creating karaoke videos.")
} else if (err instanceof ApiError) {
setError(err.message)
} else {
setError("Failed to search for audio")
}
setIsSearching(false)
}
}, [artist, title, displayArtist, displayTitle, isPrivate, onJobCreated])
useEffect(() => {
triggerSearch()
}, [triggerSearch])
async function pollForResults(jid: string) {
const maxAttempts = 30
const interval = 2000
for (let i = 0; i < maxAttempts; i++) {
try {
const data = await api.getAudioSearchResults(jid)
if (data.results && data.results.length > 0) {
setResults(data.results as ExtendedAudioSearchResult[])
setIsSearching(false)
return
}
// Check if search is still in progress
if (data.status === "search_complete" || data.status === "audio_search_complete") {
// Search finished but no results
setResults([])
setIsSearching(false)
return
}
} catch {
// Ignore errors during polling - keep trying
}
await new Promise(resolve => setTimeout(resolve, interval))
}
// Timeout
setError("Search is taking longer than expected. You can try the fallback options below.")
setIsSearching(false)
}
const confidence = useMemo(() => getSearchConfidence(results, title), [results, title])
const groupedResults = useMemo(() => groupResults(results), [results])
const otherResultsCount = results.length > 0 && confidence.bestResult ? results.length - 1 : 0
function handleSelect(index: number) {
// Don't call the API here — defer selectAudioResult to the Customize & Create step
// so the job stays in awaiting_audio_selection (hidden from Recent Jobs) until confirmed
onSearchResultChosen(index)
}
function handleBack() {
onBack(jobId)
}
function toggleCategory(category: string) {
setExpandedCategories(prev => {
const next = new Set(prev)
if (next.has(category)) {
next.delete(category)
} else {
next.add(category)
}
return next
})
}
async function handleUploadSubmit(e: React.FormEvent) {
e.preventDefault()
if (!uploadFile) return
setIsSubmittingFallback(true)
setError("")
setIsCreditError(false)
try {
const response = await api.uploadJob(uploadFile, artist.trim(), title.trim(), {
is_private: isPrivate,
})
onJobCreated(response.job_id, "upload")
onFallbackComplete()
} catch (err) {
if (err instanceof ApiError && err.status === 402) {
setIsCreditError(true)
setError("You're out of credits. Buy more to continue creating karaoke videos.")
} else if (err instanceof ApiError) {
setError(err.message)
} else {
setError("Failed to upload file")
}
} finally {
setIsSubmittingFallback(false)
}
}
async function handleUrlSubmit(e: React.FormEvent) {
e.preventDefault()
if (!youtubeUrl.trim()) return
setIsSubmittingFallback(true)
setError("")
setIsCreditError(false)
try {
const response = await api.createJobFromUrl(youtubeUrl.trim(), artist.trim(), title.trim(), {
is_private: isPrivate,
})
onJobCreated(response.job_id, "url")
onFallbackComplete()
} catch (err) {
if (err instanceof ApiError && err.status === 402) {
setIsCreditError(true)
setError("You're out of credits. Buy more to continue creating karaoke videos.")
} else if (err instanceof ApiError) {
setError(err.message)
} else {
setError("Failed to create job from URL")
}
} finally {
setIsSubmittingFallback(false)
}
}
const isLossyBest = confidence.bestCategory === 'YOUTUBE'
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
Searching for <span className="font-medium" style={{ color: 'var(--text)' }}>{artist} - {title}</span>
</p>
</div>
<Button
variant="ghost"
size="sm"
onClick={handleBack}
disabled={isSubmittingFallback}
style={{ color: 'var(--text-muted)' }}
>
<ArrowLeft className="w-4 h-4 mr-1" />
Back
</Button>
</div>
{/* Error display */}
{error && (
<div className="text-sm text-red-400 bg-red-500/10 rounded p-3">
<p>{error}</p>
{isCreditError && (
<Link href="/#pricing" className="inline-block mt-1 font-medium underline" style={{ color: 'var(--brand-pink)' }}>Buy Credits</Link>
)}
</div>
)}
{/* Loading state */}
{isSearching && (
<div className="flex flex-col items-center justify-center py-12 gap-3">
<Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--brand-pink)' }} />
<div className="text-center">
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>Searching for audio sources...</p>
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
This usually takes 15-30 seconds
</p>
</div>
</div>
)}
{/* Tier 1: Perfect match found */}
{!isSearching && confidence.tier === 1 && confidence.bestResult && (
<PickCard
confidence={confidence}
variant="perfect"
searchTitle={title}
onSelect={handleSelect}
noCredits={noCredits}
/>
)}
{/* Tier 2: Recommended with reasoning */}
{!isSearching && confidence.tier === 2 && confidence.bestResult && (
<PickCard
confidence={confidence}
variant="recommended"
searchTitle={title}
onSelect={handleSelect}
noCredits={noCredits}
/>
)}
{/* Tier 3: Guidance banner + fallback FIRST, then search results below */}
{!isSearching && confidence.tier === 3 && results.length > 0 && (
<>
<GuidanceBanner results={results} />
<FallbackSection
tier={confidence.tier}
hasResults={results.length > 0}
fallbackMode={fallbackMode}
setFallbackMode={setFallbackMode}
youtubeUrl={youtubeUrl}
setYoutubeUrl={setYoutubeUrl}
uploadFile={uploadFile}
setUploadFile={setUploadFile}
isSubmittingFallback={isSubmittingFallback}
noCredits={noCredits}
onUrlSubmit={handleUrlSubmit}
onUploadSubmit={handleUploadSubmit}
/>
</>
)}
{/* Other options section — varies by tier */}
{!isSearching && results.length > 0 && (
<OtherOptionsSection
confidence={confidence}
groupedResults={groupedResults}
otherResultsCount={otherResultsCount}
showOtherOptions={showOtherOptions}
setShowOtherOptions={setShowOtherOptions}
expandedCategories={expandedCategories}
toggleCategory={toggleCategory}
searchTitle={title}
onSelect={handleSelect}
noCredits={noCredits}
/>
)}
{/* No results */}
{!isSearching && results.length === 0 && !error && (
<div className="flex flex-col items-center justify-center py-8" style={{ color: 'var(--text-muted)' }}>
<Music2 className="w-8 h-8 mb-2 opacity-50" />
<p className="text-sm">No audio sources found for this song.</p>
<p className="text-xs mt-1">Try the options below instead.</p>
</div>
)}
{/* Fallback section for Tier 1/2 and no-results — at the bottom */}
{!isSearching && confidence.tier !== 3 && (
<FallbackSection
tier={confidence.tier}
hasResults={results.length > 0}
fallbackMode={fallbackMode}
setFallbackMode={setFallbackMode}
youtubeUrl={youtubeUrl}
setYoutubeUrl={setYoutubeUrl}
uploadFile={uploadFile}
setUploadFile={setUploadFile}
isSubmittingFallback={isSubmittingFallback}
noCredits={noCredits}
onUrlSubmit={handleUrlSubmit}
onUploadSubmit={handleUploadSubmit}
/>
)}
</div>
)
}
/** Pick card for Tier 1 and Tier 2 */
function PickCard({
confidence,
variant,
searchTitle,
onSelect,
noCredits,
}: {
confidence: SearchConfidence
variant: "perfect" | "recommended"
searchTitle: string
onSelect: (index: number) => void
noCredits: boolean
}) {
const bestResult = confidence.bestResult!
const isPerfect = variant === "perfect"
const isLossyBest = confidence.bestCategory === 'YOUTUBE'
return (
<div
className={`border rounded-lg overflow-hidden ${
isPerfect
? 'border-green-500/40 bg-green-500/5'
: 'border-amber-500/40 bg-amber-500/5'
}`}
data-testid="pick-card"
data-confidence-tier={confidence.tier}
>
<div className={`px-3 py-2 flex items-center gap-2 ${
isPerfect ? 'bg-green-500/10' : 'bg-amber-500/10'
}`}>
{isPerfect ? (
<CheckCircle2 className="w-3.5 h-3.5 text-green-400" />
) : null}
<span className={`text-xs font-semibold ${isPerfect ? 'text-green-400' : 'text-amber-400'}`}>
{isPerfect ? 'Perfect match found' : 'Recommended'}
</span>
{bestResult.is_lossless && (
<span className="text-[8px] px-1 py-0.5 rounded bg-green-600/20 text-green-400 font-medium">
LOSSLESS
</span>
)}
{bestResult.provider === "YouTube" && (
<span className="text-[8px] px-1 py-0.5 rounded font-medium bg-red-600/20 text-red-400">
YouTube
</span>
)}
</div>
<div className="px-3 py-3 space-y-2">
{/* Confidence reason */}
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
{confidence.reason}
</p>
<div className="flex items-start gap-3">
<div className="flex-1 min-w-0">
<div className="flex items-baseline gap-1.5">
<span className="text-[10px] shrink-0" style={{ color: 'var(--text-muted)' }}>Release:</span>
<span className="font-medium text-sm" style={{ color: 'var(--text)' }}>
{getDisplayName(bestResult)} - {bestResult.title}
</span>
</div>
{bestResult.target_file && (
<div className="flex items-baseline gap-1.5 mt-0.5">
<span className="text-[10px] shrink-0" style={{ color: 'var(--text-muted)' }}>Filename:</span>
<span className="font-medium text-xs font-mono break-all" style={{ color: 'var(--text)' }}>
{bestResult.target_file}
</span>
</div>
)}
<div className="flex items-center gap-1.5 flex-wrap mt-1.5">
<span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
{formatQuality(bestResult)}
</span>
<AvailabilityBadge seeders={bestResult.seeders} />
{!bestResult.seeders && (
<ViewCountBadge viewCount={bestResult.view_count} />
)}
<MismatchBadge searchTitle={searchTitle} result={bestResult} />
</div>
{formatMetadata(bestResult) && (
<div className="text-[10px] mt-1" style={{ color: 'var(--text-muted)' }}>
{formatMetadata(bestResult)}
</div>
)}
</div>
</div>
{/* Warnings */}
{confidence.warnings.length > 0 && (
<div className="space-y-1">
{confidence.warnings.map((warning, i) => (
<div key={i} className="flex items-start gap-2 rounded p-2 text-[10px] bg-yellow-600/10 text-yellow-400">
<AlertTriangle className="w-3.5 h-3.5 shrink-0 mt-0.5" />
<span>{warning}</span>
</div>
))}
</div>
)}
{/* Lossy quality warning (separate from confidence warnings) */}
{isLossyBest && !confidence.warnings.some(w => w.includes('lossless')) && (
<div className="flex items-start gap-2 rounded p-2 text-[10px] bg-yellow-600/10 text-yellow-400">
<AlertTriangle className="w-3.5 h-3.5 shrink-0 mt-0.5" />
<span>This is a YouTube/lossy source. Lossless audio produces better karaoke results when available.</span>
</div>
)}
<Button
onClick={() => onSelect(bestResult.index)}
disabled={noCredits}
className={`w-full text-white ${
isPerfect
? 'bg-green-600 hover:bg-green-500'
: 'bg-amber-600 hover:bg-amber-500'
}`}
>
<Check className="w-4 h-4 mr-1.5" />
Use This Audio
</Button>
</div>
</div>
)
}
/** Guidance banner for Tier 3 */
function GuidanceBanner({ results }: { results: ExtendedAudioSearchResult[] }) {
const tips = useMemo(() => getGuidanceTips(results), [results])
return (
<div
className="border rounded-lg p-3 space-y-2 border-[var(--card-border)] bg-[var(--secondary)]/30"
data-testid="guidance-banner"
data-confidence-tier={3}
>
<div className="flex items-center gap-2">
<Lightbulb className="w-4 h-4 text-amber-400 shrink-0" />
<span className="text-xs font-semibold" style={{ color: 'var(--text)' }}>
Limited sources found
</span>
</div>
<ul className="text-[10px] space-y-1 ml-6" style={{ color: 'var(--text-muted)' }}>
{tips.map((tip, i) => <li key={i}>{tip}</li>)}
</ul>
</div>
)
}
/** Build context-aware guidance tips based on actual result composition */
function getGuidanceTips(results: ExtendedAudioSearchResult[]): string[] {
const hasFiles = results.some(r => r.target_file)
const hasYoutube = results.some(r => r.provider?.toLowerCase() === 'youtube')
const hasSpotify = results.some(r => r.provider?.toLowerCase() === 'spotify')
const hasLossless = results.some(r => r.is_lossless && !['youtube', 'spotify'].includes(r.provider?.toLowerCase() ?? ''))
const hasVinyl = results.some(r => r.quality_data?.media?.toLowerCase() === 'vinyl')
const hasSeeders = results.some(r => r.seeders !== undefined && r.seeders !== null)
const noLossless = !hasLossless
const tips: string[] = []
if (hasFiles) {
tips.push('Check the filename matches your song title')
}
if (hasSeeders) {
tips.push('Green availability badge = more reliable download')
}
if (hasLossless) {
tips.push('Studio album versions produce the best karaoke results')
}
if (hasVinyl) {
tips.push('Avoid vinyl rips (surface noise affects separation)')
}
if (hasYoutube && hasLossless) {
tips.push('YouTube is a last resort — lossless sources sound better')
}
if (noLossless) {
tips.push('No high quality lossless sources were found')
}
if (hasSpotify && hasYoutube) {
tips.push('Spotify results are higher quality than YouTube')
}
if (noLossless && hasYoutube) {
tips.push('If YouTube is the only option, official music videos or audio-only uploads tend to have the best quality')
}
return tips
}
/** Other options section — render differently per tier */
function OtherOptionsSection({
confidence,
groupedResults,
otherResultsCount,
showOtherOptions,
setShowOtherOptions,
expandedCategories,
toggleCategory,
searchTitle,
onSelect,
noCredits,
}: {
confidence: SearchConfidence
groupedResults: ReturnType<typeof groupResults>
otherResultsCount: number
showOtherOptions: boolean
setShowOtherOptions: (show: boolean) => void
expandedCategories: Set<string>
toggleCategory: (category: string) => void
searchTitle: string
onSelect: (index: number) => void
noCredits: boolean
}) {
const isTier3 = confidence.tier === 3
// For Tier 3, always show results expanded (no toggle needed)
// For Tier 1/2, show toggle to expand other options
if (isTier3) {
return (
<div className="border-t pt-4 space-y-2" style={{ borderColor: 'var(--card-border)' }}>
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>
Search results (may not match your song):
</p>
<ResultCategories
groupedResults={groupedResults}
bestResult={null} // Don't filter any result for Tier 3
expandedCategories={expandedCategories}
toggleCategory={toggleCategory}
searchTitle={searchTitle}
onSelect={onSelect}
noCredits={noCredits}
defaultExpanded
alwaysShowMatchBadge
/>
</div>
)
}
if (otherResultsCount <= 0) return null
return (
<div>
<button
onClick={() => setShowOtherOptions(!showOtherOptions)}
className="flex items-center gap-1.5 text-xs hover:opacity-80 transition-opacity"
style={{ color: 'var(--text-muted)' }}
>
{showOtherOptions ? (
<><ChevronUp className="w-3.5 h-3.5" /> Hide other options</>
) : (
<><ChevronDown className="w-3.5 h-3.5" /> See all {otherResultsCount} other option{otherResultsCount !== 1 ? 's' : ''}</>
)}
</button>
{showOtherOptions && (
<div className="mt-2 space-y-2">
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
Check the filename matches your song. Higher availability (green) = more reliable. Studio album versions produce the best results.
</p>
<ResultCategories
groupedResults={groupedResults}
bestResult={confidence.bestResult}
expandedCategories={expandedCategories}
toggleCategory={toggleCategory}
searchTitle={searchTitle}
onSelect={onSelect}
noCredits={noCredits}
/>
</div>
)}
</div>
)
}
/** Render categorized result groups */
function ResultCategories({
groupedResults,
bestResult,
expandedCategories,
toggleCategory,
searchTitle,
onSelect,
noCredits,
defaultExpanded,
alwaysShowMatchBadge,
}: {
groupedResults: ReturnType<typeof groupResults>
bestResult: ExtendedAudioSearchResult | null
expandedCategories: Set<string>
toggleCategory: (category: string) => void
searchTitle: string
onSelect: (index: number) => void
noCredits: boolean
defaultExpanded?: boolean
alwaysShowMatchBadge?: boolean
}) {
return (
<div className="space-y-2 max-h-[350px] overflow-y-auto pr-1">
{groupedResults.map(({ category, results: catResults, config }) => {
const isExpanded = defaultExpanded || expandedCategories.has(category)
// Filter out the best result from "other options" (when best result shown separately)
const filteredResults = bestResult
? catResults.filter(r => r.index !== bestResult.index)
: catResults
if (filteredResults.length === 0) return null
// Check mismatch status for each result
const mismatchFlags = filteredResults.map(r => checkFilenameMismatch(searchTitle, r).isMismatch)
const hasAnyMatch = mismatchFlags.some(m => !m)
const hasAnyMismatch = mismatchFlags.some(m => m)
// Show match/mismatch badges when there's a mix, or always in Tier 3
const showMatchBadges = (hasAnyMatch && hasAnyMismatch) || (alwaysShowMatchBadge && hasAnyMatch)
// Sort matching results to top when there's a mix
const sortedResults = hasAnyMatch && hasAnyMismatch
? [...filteredResults].sort((a, b) => {
const aMismatch = checkFilenameMismatch(searchTitle, a).isMismatch
const bMismatch = checkFilenameMismatch(searchTitle, b).isMismatch
if (aMismatch === bMismatch) return 0
return aMismatch ? 1 : -1
})
: filteredResults
const displayResults = isExpanded
? sortedResults
: sortedResults.slice(0, config.maxDisplay)
const hiddenCount = filteredResults.length - config.maxDisplay
const hasMore = hiddenCount > 0
return (
<div
key={category}
className="border rounded-lg overflow-hidden border-[var(--card-border)] bg-[var(--secondary)]/20"
>
{/* Category Header */}
<div className="px-3 py-1.5 flex items-center justify-between bg-[var(--secondary)]">
<div className="flex items-center gap-2 text-xs font-semibold">
<span className={config.color}>{category}</span>
<span style={{ color: 'var(--text-muted)' }} className="font-normal">({filteredResults.length})</span>
</div>
{hasMore && !defaultExpanded && (
<button
onClick={() => toggleCategory(category)}
className="text-[10px] hover:opacity-80 flex items-center gap-1"
style={{ color: 'var(--text-muted)' }}
>
{isExpanded ? (
<>Show less <ChevronUp className="w-3 h-3" /></>
) : (
<>+{hiddenCount} more <ChevronDown className="w-3 h-3" /></>
)}
</button>
)}
</div>
{/* Results */}
<div className="divide-y" style={{ borderColor: 'var(--card-border)' }}>
{displayResults.map((result) => (
<ResultRow
key={result.index}
result={result}
searchTitle={searchTitle}
showMatchBadges={showMatchBadges}
onSelect={onSelect}
noCredits={noCredits}
/>
))}
</div>
</div>
)
})}
</div>
)
}
/** Single result row in the "other options" list */
function ResultRow({
result,
searchTitle,
showMatchBadges,
onSelect,
noCredits,
}: {
result: ExtendedAudioSearchResult
searchTitle: string
showMatchBadges: boolean
onSelect: (index: number) => void
noCredits: boolean
}) {
const mismatch = useMemo(() => checkFilenameMismatch(searchTitle, result), [searchTitle, result])
// Only show "Title match" when we actually verified a match (filename is non-empty)
const isMatch = showMatchBadges && !mismatch.isMismatch && mismatch.filename !== ''
return (
<div
className={`px-3 py-2 flex items-center gap-3 text-xs transition-colors ${isMatch ? 'bg-green-600/5' : 'hover:bg-[var(--secondary)]/50'}`}
>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5 flex-wrap">
{result.is_lossless && (
<span className="text-[8px] px-1 py-0.5 rounded bg-green-600/20 text-green-400 font-medium">
LOSSLESS
</span>
)}
{result.provider === "Spotify" && (
<span className="text-[8px] px-1 py-0.5 rounded font-medium bg-green-600/20 text-green-400">
Spotify
</span>
)}
{result.provider === "YouTube" && (
<span className="text-[8px] px-1 py-0.5 rounded font-medium bg-red-600/20 text-red-400">
YouTube
</span>
)}
<span className="font-medium" style={{ color: 'var(--text)' }}>
{getDisplayName(result)} - {result.title}
</span>
<span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
({formatQuality(result)})
</span>
<AvailabilityBadge seeders={result.seeders} />
{!result.seeders && (
<ViewCountBadge viewCount={result.view_count} />
)}
{isMatch ? (
<span className="text-[8px] px-1 py-0.5 rounded font-medium bg-green-600/20 text-green-400">
Title match
</span>
) : (
<MismatchBadge searchTitle={searchTitle} result={result} />
)}
</div>
{formatMetadata(result) && (
<div className="text-[10px] mt-0.5" style={{ color: 'var(--text-muted)' }}>
{formatMetadata(result)}
</div>
)}
{result.target_file && (
<div className="text-[10px] mt-0.5 font-mono break-all" style={{ color: 'var(--text-muted)' }}>
<span className="font-sans">Filename: </span>{result.target_file}
</div>
)}
</div>
<Button
size="sm"
onClick={() => onSelect(result.index)}
disabled={noCredits}
className="h-7 px-3 text-xs shrink-0 bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white"
>
<Check className="w-3 h-3 mr-1" />
Select
</Button>
</div>
)
}
/** Fallback section — upload or YouTube URL */
function FallbackSection({
tier,
hasResults,
fallbackMode,
setFallbackMode,
youtubeUrl,
setYoutubeUrl,
uploadFile,
setUploadFile,
isSubmittingFallback,
noCredits,
onUrlSubmit,
onUploadSubmit,
}: {
tier: number
hasResults: boolean
fallbackMode: "upload" | "url" | null
setFallbackMode: (mode: "upload" | "url" | null) => void
youtubeUrl: string
setYoutubeUrl: (url: string) => void
uploadFile: File | null
setUploadFile: (file: File | null) => void
isSubmittingFallback: boolean
noCredits: boolean
onUrlSubmit: (e: React.FormEvent) => void
onUploadSubmit: (e: React.FormEvent) => void
}) {
const isTier3WithResults = tier === 3 && hasResults
return (
<div className={`${isTier3WithResults ? '' : 'border-t pt-4 '}space-y-3`} style={{ borderColor: 'var(--card-border)' }}>
<p className={isTier3WithResults ? 'text-xs font-medium' : 'text-xs'} style={{ color: 'var(--text-muted)' }}>
{isTier3WithResults
? "Have your own audio? Upload it or paste a YouTube URL:"
: 'Not finding what you need? Try simplifying your search, or provide your own audio:'
}
</p>
{/* Two equally prominent buttons */}
<div className="grid grid-cols-2 gap-2">
<Button
variant="outline"
size="sm"
onClick={() => { setFallbackMode(fallbackMode === "url" ? null : "url"); }}
className={`h-9 text-xs ${fallbackMode === "url" ? 'border-[var(--brand-pink)] bg-[var(--brand-pink)]/10' : ''}`}
style={{ borderColor: fallbackMode === "url" ? 'var(--brand-pink)' : 'var(--card-border)', color: 'var(--text)' }}
>
<Youtube className="w-3.5 h-3.5 mr-1.5" />
YouTube URL
</Button>
<Button
variant="outline"
size="sm"
onClick={() => { setFallbackMode(fallbackMode === "upload" ? null : "upload"); }}
className={`h-9 text-xs ${fallbackMode === "upload" ? 'border-[var(--brand-pink)] bg-[var(--brand-pink)]/10' : ''}`}
style={{ borderColor: fallbackMode === "upload" ? 'var(--brand-pink)' : 'var(--card-border)', color: 'var(--text)' }}
>
<Upload className="w-3.5 h-3.5 mr-1.5" />
Upload file
</Button>
</div>
{/* YouTube URL form */}
{fallbackMode === "url" && (
<form onSubmit={onUrlSubmit} className="space-y-2 p-3 rounded-lg" style={{ backgroundColor: 'var(--secondary)' }}>
<div className="relative">
<Youtube className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4" style={{ color: 'var(--text-muted)' }} />
<Input
type="url"
placeholder="https://youtube.com/watch?v=..."
value={youtubeUrl}
onChange={(e) => setYoutubeUrl(e.target.value)}
className="pl-10 text-xs"
style={{ backgroundColor: 'var(--background)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
disabled={isSubmittingFallback}
autoFocus
/>
</div>
<Button
type="submit"
size="sm"
disabled={!youtubeUrl.trim() || isSubmittingFallback || noCredits}
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white"
>
{isSubmittingFallback ? (
<><Loader2 className="w-3 h-3 mr-1 animate-spin" /> Creating...</>
) : (
"Use This URL"
)}
</Button>
</form>
)}
{/* Upload form */}
{fallbackMode === "upload" && (
<form onSubmit={onUploadSubmit} className="space-y-3 p-3 rounded-lg" style={{ backgroundColor: 'var(--secondary)' }}>
<div
className="relative border-2 border-dashed rounded-lg p-4 text-center transition-colors cursor-pointer"
style={{
borderColor: uploadFile ? 'rgba(255, 122, 204, 0.5)' : 'var(--card-border)',
backgroundColor: uploadFile ? 'rgba(255, 122, 204, 0.05)' : 'transparent',
}}
>
<Input
type="file"
accept=".mp3,.wav,.flac,.m4a,.ogg,audio/*"
onChange={(e) => {
const file = e.target.files?.[0]
if (file) setUploadFile(file)
}}
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
disabled={isSubmittingFallback}
/>
{uploadFile ? (
<div>
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>{uploadFile.name}</p>
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>{(uploadFile.size / 1024 / 1024).toFixed(2)} MB</p>
</div>
) : (
<div>
<Upload className="w-6 h-6 mx-auto mb-1" style={{ color: 'var(--text-muted)' }} />
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>MP3, WAV, FLAC, M4A, or OGG</p>
</div>
)}
</div>
<Button
type="submit"
size="sm"
disabled={!uploadFile || isSubmittingFallback || noCredits}
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white"
>
{isSubmittingFallback ? (
<><Loader2 className="w-3 h-3 mr-1 animate-spin" /> Uploading...</>
) : (
"Upload & Create"
)}
</Button>
</form>
)}
</div>
)
}
@@ -0,0 +1,151 @@
"use client"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { ArrowLeft, Loader2 } from "lucide-react"
import { TitleCardPreview } from "../TitleCardPreview"
interface CustomizeStepProps {
artist: string
title: string
displayArtist: string
displayTitle: string
onDisplayArtistChange: (value: string) => void
onDisplayTitleChange: (value: string) => void
isPrivate: boolean
onPrivateChange: (value: boolean) => void
onConfirm: () => void
onBack: () => void
isSubmitting: boolean
disabled?: boolean
}
export function CustomizeStep({
artist,
title,
displayArtist,
displayTitle,
onDisplayArtistChange,
onDisplayTitleChange,
isPrivate,
onPrivateChange,
onConfirm,
onBack,
isSubmitting,
disabled,
}: CustomizeStepProps) {
// The displayed artist/title on the title card
const previewArtist = displayArtist.trim() || artist
const previewTitle = displayTitle.trim() || title
return (
<div className="space-y-5">
<div className="flex items-center justify-between">
<div>
<h2 className="text-lg font-semibold" style={{ color: 'var(--text)' }}>
Customize & Create
</h2>
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
Preview your title card and confirm your settings.
</p>
</div>
<Button
variant="ghost"
size="sm"
onClick={onBack}
disabled={disabled || isSubmitting}
style={{ color: 'var(--text-muted)' }}
>
<ArrowLeft className="w-4 h-4 mr-1" />
Back
</Button>
</div>
{/* Title card preview - half width, centered */}
<div className="space-y-2">
<Label className="text-xs" style={{ color: 'var(--text-muted)' }}>Title Card Preview</Label>
<div className="mx-auto w-full sm:w-1/2">
<TitleCardPreview artist={previewArtist} title={previewTitle} />
</div>
</div>
{/* Display override fields */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-1.5">
<Label htmlFor="guided-display-artist" className="text-xs" style={{ color: 'var(--text-muted)' }}>
Title Card Artist
{!displayArtist.trim() && artist.trim() && (
<span className="ml-1 opacity-50">(same as above)</span>
)}
</Label>
<Input
id="guided-display-artist"
placeholder={artist || "Artist on title card"}
value={displayArtist}
onChange={(e) => onDisplayArtistChange(e.target.value)}
disabled={disabled || isSubmitting}
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="guided-display-title" className="text-xs" style={{ color: 'var(--text-muted)' }}>
Title Card Title
{!displayTitle.trim() && title.trim() && (
<span className="ml-1 opacity-50">(same as above)</span>
)}
</Label>
<Input
id="guided-display-title"
placeholder={title || "Title on title card"}
value={displayTitle}
onChange={(e) => onDisplayTitleChange(e.target.value)}
disabled={disabled || isSubmitting}
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
/>
</div>
</div>
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
These default to your search values. Override for soundtracks, covers, or alternate formatting.
</p>
{/* Privacy toggle */}
<div className="space-y-2 pt-2 border-t" style={{ borderColor: 'var(--card-border)' }}>
<div className="flex items-start gap-3">
<input
type="checkbox"
id="guided-private"
checked={isPrivate}
onChange={(e) => onPrivateChange(e.target.checked)}
disabled={disabled || isSubmitting}
className="mt-1 w-4 h-4 rounded border-border bg-secondary accent-[var(--brand-pink)] focus:ring-[var(--brand-pink)] focus:ring-offset-background"
/>
<div>
<Label htmlFor="guided-private" className="cursor-pointer" style={{ color: 'var(--text)' }}>
Private (no YouTube upload)
</Label>
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
Files delivered via Dropbox only. No YouTube or Google Drive upload.
</p>
</div>
</div>
</div>
{/* Create button */}
<Button
onClick={onConfirm}
disabled={disabled || isSubmitting}
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white shadow-[0_0_15px_rgba(255,122,204,0.3)] hover:shadow-[0_0_20px_rgba(255,122,204,0.5)] h-11 text-base"
>
{isSubmitting ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Creating...
</>
) : (
"Create Karaoke Video"
)}
</Button>
</div>
)
}
@@ -0,0 +1,116 @@
"use client"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import { ArrowRight, Lightbulb, Pencil, Search, Upload, Youtube } from "lucide-react"
interface SongInfoStepProps {
artist: string
title: string
onArtistChange: (value: string) => void
onTitleChange: (value: string) => void
onNext: () => void
disabled?: boolean
}
export function SongInfoStep({
artist,
title,
onArtistChange,
onTitleChange,
onNext,
disabled,
}: SongInfoStepProps) {
const canProceed = artist.trim() && title.trim()
function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (canProceed) onNext()
}
return (
<form onSubmit={handleSubmit} className="space-y-5">
{/* How it works - compact visual */}
<div className="flex items-center gap-3 text-xs flex-wrap" style={{ color: 'var(--text-muted)' }}>
<div className="flex items-center gap-1.5">
<Search className="w-3.5 h-3.5" style={{ color: 'var(--brand-pink)' }} />
<span>We find the best audio</span>
</div>
<span className="opacity-40">or</span>
<div className="flex items-center gap-1.5">
<Upload className="w-3.5 h-3.5 text-amber-400" />
<span>upload a file</span>
</div>
<span className="opacity-40">/</span>
<div className="flex items-center gap-1.5">
<Youtube className="w-3.5 h-3.5 text-red-400" />
<span>YouTube URL</span>
</div>
<span className="opacity-50">(on next page)</span>
</div>
{/* Search artist/title */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="guided-artist" style={{ color: 'var(--text)' }}>Artist</Label>
<Input
id="guided-artist"
data-testid="guided-artist-input"
placeholder="e.g. Queen"
value={artist}
onChange={(e) => onArtistChange(e.target.value)}
disabled={disabled}
autoFocus
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
/>
</div>
<div className="space-y-2">
<Label htmlFor="guided-title" style={{ color: 'var(--text)' }}>Title</Label>
<Input
id="guided-title"
data-testid="guided-title-input"
placeholder="e.g. Bohemian Rhapsody"
value={title}
onChange={(e) => onTitleChange(e.target.value)}
disabled={disabled}
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
/>
</div>
</div>
{/* Tip callout */}
<div
className="flex items-start gap-2.5 rounded-lg p-3 text-xs"
style={{ backgroundColor: 'var(--secondary)', color: 'var(--text-muted)' }}
>
<Lightbulb className="w-4 h-4 shrink-0 mt-0.5 text-amber-400" />
<p>
Looking for a specific version (live, cover, remix)? Include those details in the title - e.g. &quot;Bohemian Rhapsody - Live at Wembley&quot;.
<br className="mt-1" />
If we can&apos;t find the right audio, you can provide a YouTube URL or upload a file on the next page.
</p>
</div>
{/* Custom lyrics note */}
<div
className="flex items-start gap-2.5 rounded-lg p-3 text-xs"
style={{ backgroundColor: 'var(--secondary)', color: 'var(--text-muted)' }}
>
<Pencil className="w-4 h-4 shrink-0 mt-0.5 text-purple-400" />
<p>
Making a video with custom lyrics? Start with the artist/title of the original song here - you can change the title screen and lyrics later.
</p>
</div>
<Button
type="submit"
disabled={!canProceed || disabled}
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white shadow-[0_0_15px_rgba(255,122,204,0.3)] hover:shadow-[0_0_20px_rgba(255,122,204,0.5)]"
>
Choose Audio
<ArrowRight className="w-4 h-4 ml-2" />
</Button>
</form>
)
}
@@ -25,6 +25,7 @@ interface CorrectedWordWithActionsProps {
backgroundColor?: string
shouldFlash?: boolean
showActions?: boolean
id?: string
}
export default function CorrectedWordWithActions({
@@ -37,6 +38,7 @@ export default function CorrectedWordWithActions({
backgroundColor,
shouldFlash,
showActions = true,
id,
}: CorrectedWordWithActionsProps) {
const handleAction = (e: React.MouseEvent, action: () => void) => {
e.stopPropagation()
@@ -45,6 +47,7 @@ export default function CorrectedWordWithActions({
return (
<span
id={id}
className={cn(
'inline-flex items-center gap-0.5 px-[3px] py-[1px] rounded-sm cursor-pointer relative',
'hover:bg-green-500/35',
@@ -0,0 +1,160 @@
'use client'
import { useEffect, useRef, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import { X } from 'lucide-react'
import type { EditLogEntry, EditFeedbackReason } from '@/lib/lyrics-review/types'
const REASONS_BY_OP: Record<string, { label: string; reason: EditFeedbackReason }[]> = {
word_change: [
{ label: 'Mis-heard word', reason: 'misheard_word' },
{ label: 'Wrong lyrics', reason: 'wrong_lyrics' },
{ label: 'Spelling/punctuation', reason: 'spelling_punctuation' },
{ label: 'Other', reason: 'other' },
],
word_delete: [
{ label: 'Phantom word', reason: 'phantom_word' },
{ label: 'Duplicate', reason: 'duplicate_word' },
{ label: 'Mis-heard word', reason: 'misheard_word' },
{ label: 'Other', reason: 'other' },
],
word_add: [
{ label: 'Missing word', reason: 'missing_word' },
{ label: 'Split word', reason: 'split_word' },
{ label: 'Other', reason: 'other' },
],
}
function getQuestionText(entry: EditLogEntry): string {
const before = entry.text_before.trim()
const after = entry.text_after.trim()
switch (entry.operation) {
case 'word_change':
return `Changed "${before}" → "${after}", why?`
case 'word_delete':
return `Removed "${before}", why?`
case 'word_add':
return `Added "${after}", why?`
default:
return `Edit made, why?`
}
}
interface EditFeedbackBarProps {
entry: EditLogEntry | null
visible: boolean
onFeedback: (entryId: string, reason: EditFeedbackReason) => void
onDismiss: () => void
}
export default function EditFeedbackBar({
entry,
visible,
onFeedback,
onDismiss,
}: EditFeedbackBarProps) {
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const entryIdRef = useRef<string | null>(null)
const hoveredRef = useRef(false)
const remainingRef = useRef(10_000)
const startedAtRef = useRef<number | null>(null)
const clearTimer = useCallback(() => {
if (timerRef.current) {
clearTimeout(timerRef.current)
timerRef.current = null
}
}, [])
const startTimer = useCallback((ms: number) => {
clearTimer()
startedAtRef.current = Date.now()
remainingRef.current = ms
timerRef.current = setTimeout(() => {
if (entry) {
onFeedback(entry.id, 'no_response')
onDismiss()
}
}, ms)
}, [clearTimer, entry, onFeedback, onDismiss])
const handleMouseEnter = useCallback(() => {
hoveredRef.current = true
if (timerRef.current && startedAtRef.current !== null) {
const elapsed = Date.now() - startedAtRef.current
remainingRef.current = Math.max(0, remainingRef.current - elapsed)
clearTimer()
}
}, [clearTimer])
const handleMouseLeave = useCallback(() => {
hoveredRef.current = false
if (visible && entry && remainingRef.current > 0) {
startTimer(remainingRef.current)
}
}, [visible, entry, startTimer])
useEffect(() => {
clearTimer()
if (!visible || !entry) return
// If this is a new entry, start the auto-dismiss timer
if (entry.id !== entryIdRef.current) {
entryIdRef.current = entry.id
remainingRef.current = 10_000
if (!hoveredRef.current) {
startTimer(10_000)
}
}
return clearTimer
}, [visible, entry, clearTimer, startTimer])
if (!visible || !entry) return null
const reasons = REASONS_BY_OP[entry.operation] ?? REASONS_BY_OP.word_change
return (
<div
className="fixed bottom-[52px] left-0 right-0 z-40 flex justify-center animate-in slide-in-from-bottom-2 duration-200"
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
<div className="bg-muted/95 backdrop-blur-sm border-t border-b px-4 py-2 flex items-center gap-3 w-full max-w-4xl">
<span className="text-sm text-muted-foreground shrink-0 truncate max-w-[280px]">
{getQuestionText(entry)}
</span>
<div className="flex items-center gap-1.5 flex-wrap">
{reasons.map((r) => (
<Button
key={r.reason}
variant="outline"
size="sm"
className="h-7 text-xs px-2.5"
onClick={() => {
clearTimer()
onFeedback(entry.id, r.reason)
onDismiss()
}}
>
{r.label}
</Button>
))}
</div>
<Button
variant="ghost"
size="sm"
className="h-7 w-7 p-0 ml-auto shrink-0"
onClick={() => {
clearTimer()
onFeedback(entry.id, 'no_response')
onDismiss()
}}
>
<X className="h-3.5 w-3.5" />
</Button>
</div>
</div>
)
}
@@ -0,0 +1,65 @@
'use client'
import { Button } from '@/components/ui/button'
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip'
import { ChevronLeft, ChevronRight } from 'lucide-react'
interface GapNavigatorProps {
currentGapIndex: number | null
totalGaps: number
onPrevGap: () => void
onNextGap: () => void
}
export default function GapNavigator({
currentGapIndex,
totalGaps,
onPrevGap,
onNextGap,
}: GapNavigatorProps) {
if (totalGaps === 0) return null
const displayIndex = currentGapIndex !== null ? currentGapIndex + 1 : 0
return (
<div className="flex items-center gap-1.5">
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="icon"
className="h-7 w-7"
onClick={onPrevGap}
disabled={currentGapIndex === null || currentGapIndex <= 0}
aria-label="Previous gap"
>
<ChevronLeft className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Previous gap (P)</TooltipContent>
</Tooltip>
<span className="text-xs text-muted-foreground whitespace-nowrap">
Gap {displayIndex} of {totalGaps}
</span>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="icon"
className="h-7 w-7"
onClick={onNextGap}
disabled={currentGapIndex !== null && currentGapIndex >= totalGaps - 1}
aria-label="Next gap"
>
<ChevronRight className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Next gap (N)</TooltipContent>
</Tooltip>
</div>
)
}
@@ -0,0 +1,315 @@
'use client'
import { useState } from 'react'
import { Card } from '@/components/ui/card'
import { Switch } from '@/components/ui/switch'
import { Label } from '@/components/ui/label'
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip'
import { Lightbulb, X } from 'lucide-react'
import { CorrectionData } from '@/lib/lyrics-review/types'
import { cn } from '@/lib/utils'
interface GuidancePanelProps {
data: CorrectionData
isReadOnly: boolean
onMetricClick: {
anchor: () => void
corrected: () => void
uncorrected: () => void
}
onHandlerToggle: (handler: string, enabled: boolean) => void
isUpdatingHandlers: boolean
onHandlerClick?: (handler: string) => void
statsVisible: boolean
onStatsToggle: () => void
}
export default function GuidancePanel({
data,
isReadOnly,
onMetricClick,
onHandlerToggle,
isUpdatingHandlers,
onHandlerClick,
statsVisible,
onStatsToggle,
}: GuidancePanelProps) {
const [guidanceDismissed, setGuidanceDismissed] = useState(() => {
if (typeof window === 'undefined') return false
return localStorage.getItem('lyricsReviewGuidanceDismissed') === 'true'
})
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768
// Calculate metrics
const gapCorrections = data.corrections.reduce(
(map: Record<string, number>, correction) => {
const gap = data.gap_sequences.find((g) =>
g.transcribed_word_ids.includes(correction.word_id)
)
if (gap) {
map[gap.id] = (map[gap.id] || 0) + 1
}
return map
},
{} as Record<string, number>
)
const correctedGapCount = Object.keys(gapCorrections).length
const uncorrectedGapCount = data.gap_sequences.length - correctedGapCount
const totalGaps = data.gap_sequences.length
// Handler info
const handlerCounts =
data.corrections?.reduce(
(counts: Record<string, number>, correction) => {
counts[correction.handler] = (counts[correction.handler] || 0) + 1
return counts
},
{} as Record<string, number>
) || {}
const availableHandlers = data.metadata.available_handlers || []
const enabledHandlers = new Set(data.metadata.enabled_handlers || [])
// Detailed metrics
const totalWords = data.metadata.total_words || 0
const anchorWordCount = data.anchor_sequences?.reduce(
(sum, anchor) => sum + (anchor.transcribed_word_ids?.length || 0),
0
) ?? 0
const multiSourceAnchors = data.anchor_sequences?.filter(
(anchor) =>
anchor?.reference_word_ids && Object.keys(anchor.reference_word_ids).length > 1
).length ?? 0
const replacedCount = data.corrections.filter(
(c) => !c.is_deletion && !c.split_total
).length
const addedCount = data.corrections.filter((c) => c.split_total).length
const deletedCount = data.corrections.filter((c) => c.is_deletion).length
const uncorrectedGaps = data.gap_sequences.filter(
(gap) => !gapCorrections[gap.id] && gap.transcribed_word_ids.length > 0
)
const uncorrectedWordCount = uncorrectedGaps.reduce(
(sum, gap) => sum + gap.transcribed_word_ids.length,
0
)
const anchorPercentage = totalWords > 0 ? Math.round((anchorWordCount / totalWords) * 100) : 0
const correctedWordCount = replacedCount + addedCount
const correctedPercentage = totalWords > 0 ? Math.round((correctedWordCount / totalWords) * 100) : 0
const uncorrectedPercentage = totalWords > 0 ? Math.round((uncorrectedWordCount / totalWords) * 100) : 0
const handleDismiss = () => {
setGuidanceDismissed(true)
if (typeof window !== 'undefined') {
localStorage.setItem('lyricsReviewGuidanceDismissed', 'true')
}
}
const handleShowTips = () => {
setGuidanceDismissed(false)
if (typeof window !== 'undefined') {
localStorage.removeItem('lyricsReviewGuidanceDismissed')
}
}
return (
<div className="space-y-2 mb-2">
{/* Color legend row */}
<div className="flex items-center gap-3 text-xs flex-wrap">
<button
className="flex items-center gap-1.5 hover:opacity-80 transition-opacity"
onClick={onMetricClick.anchor}
>
<span className="w-2.5 h-2.5 rounded-full bg-blue-500/60 inline-block" />
<span className="text-muted-foreground">Matched</span>
</button>
<button
className="flex items-center gap-1.5 hover:opacity-80 transition-opacity"
onClick={onMetricClick.uncorrected}
>
<span className="w-2.5 h-2.5 rounded-full bg-orange-500/60 inline-block" />
<span className="text-muted-foreground">Gaps (needs review)</span>
</button>
<button
className="flex items-center gap-1.5 hover:opacity-80 transition-opacity"
onClick={onMetricClick.corrected}
>
<span className="w-2.5 h-2.5 rounded-full bg-green-500/60 inline-block" />
<span className="text-muted-foreground">Corrected</span>
</button>
<div className="flex items-center gap-2 ml-auto">
{guidanceDismissed && !isReadOnly && (
<button
className="text-amber-500 hover:text-amber-400 transition-colors text-xs"
onClick={handleShowTips}
>
Show tips
</button>
)}
<button
className={cn(
'text-xs px-1.5 py-0.5 rounded border transition-colors',
statsVisible
? 'border-primary text-primary'
: 'border-muted text-muted-foreground hover:text-foreground hover:border-foreground/50'
)}
onClick={onStatsToggle}
>
{statsVisible ? 'Hide Stats' : 'Stats'}
</button>
</div>
</div>
{/* Workflow tips (dismissible) */}
{!guidanceDismissed && !isReadOnly && (
<div className="flex items-start gap-2 p-2.5 rounded-md bg-amber-500/10 border border-amber-500/20">
<Lightbulb className="h-4 w-4 text-amber-500 shrink-0 mt-0.5" />
<div className="text-xs text-muted-foreground flex-1 leading-relaxed space-y-1.5">
{totalGaps === 0 ? (
<p>All lyrics matched the reference — no corrections needed. You can still click any word to edit.</p>
) : (
<>
<p>The <strong>Synced Lyrics</strong> on the left are what will appear in the karaoke video.</p>
<p>The orange highlighted words are <strong>gaps</strong> — sections that couldn&apos;t be matched to the reference lyrics and may contain errors (e.g. mis-heard words which sound similar).</p>
<p>Use <kbd className="px-1 py-0.5 rounded bg-muted text-[0.65rem] font-mono">N</kbd> and <kbd className="px-1 py-0.5 rounded bg-muted text-[0.65rem] font-mono">P</kbd> to jump between gaps. For each one, click play beside the line and compare what you hear with the reference lyrics on the right, then click a word to edit or delete it.</p>
<p>Watch out for phantom words like &quot;and&quot; at the start or end of lines — the transcription often adds these.</p>
<p>Try the <strong>Timeline</strong> view to spot any unusually long words (10+ seconds), which usually indicate a timing problem.</p>
</>
)}
</div>
<button
className="text-muted-foreground hover:text-foreground transition-colors shrink-0"
onClick={handleDismiss}
aria-label="Dismiss tip"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
)}
{/* Stats & Handlers (shown when toggled via header button) */}
{statsVisible && (
<div className={cn('flex gap-2 overflow-hidden', isMobile ? 'flex-col' : 'flex-row', isMobile ? 'h-auto' : 'h-[140px]')}>
{/* Handler panel */}
<Card className={cn('p-2', isMobile ? 'w-full' : 'w-[280px] min-w-[280px]')}>
<h4 className="text-xs text-muted-foreground mb-1">Correction Handlers</h4>
<div className="flex-1 overflow-auto flex flex-col">
{availableHandlers.map((handler: { id: string; name: string; description: string }) => (
<div key={handler.id} className="mb-1">
<Tooltip>
<TooltipTrigger asChild>
<div className="flex items-center gap-2">
<Switch
checked={enabledHandlers.has(handler.id)}
onCheckedChange={(checked) => onHandlerToggle(handler.id, checked)}
disabled={isUpdatingHandlers}
className="scale-75"
/>
<Label
className="text-xs cursor-pointer hover:text-foreground hover:underline transition-colors"
onClick={() => onHandlerClick?.(handler.id)}
>
{handler.name} ({handlerCounts[handler.id] || 0})
</Label>
</div>
</TooltipTrigger>
<TooltipContent>
<p>{handler.description}</p>
</TooltipContent>
</Tooltip>
</div>
))}
</div>
</Card>
{/* Metrics panel */}
<div className="flex-1 grid grid-cols-3 gap-2 h-full">
<Card
className="p-2 cursor-pointer hover:bg-muted/30 transition-colors flex flex-col overflow-hidden h-full"
onClick={onMetricClick.anchor}
>
<div className="flex items-center gap-1 mb-0.5">
<div className="w-3 h-3 rounded bg-blue-500/25 shrink-0" />
<span className="text-xs text-muted-foreground truncate">Anchor Sequences</span>
</div>
<span className="text-lg font-semibold leading-tight">
{data.metadata.anchor_sequences_count ?? '-'} ({anchorPercentage}%)
</span>
<span className="text-[10px] text-muted-foreground leading-tight">
Matched sections between transcription and reference
</span>
<div className="mt-auto space-y-0 text-[10px]">
<div className="flex justify-between">
<span className="text-muted-foreground">Words in Anchors</span>
<span>{anchorWordCount}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Multi-source Matches</span>
<span>{multiSourceAnchors}</span>
</div>
</div>
</Card>
<Card
className="p-2 cursor-pointer hover:bg-muted/30 transition-colors flex flex-col overflow-hidden h-full"
onClick={onMetricClick.corrected}
>
<div className="flex items-center gap-1 mb-0.5">
<div className="w-3 h-3 rounded bg-green-500/25 shrink-0" />
<span className="text-xs text-muted-foreground truncate">Corrected Gaps</span>
</div>
<span className="text-lg font-semibold text-green-500 leading-tight">
{correctedGapCount} ({correctedPercentage}%)
</span>
<span className="text-[10px] text-muted-foreground leading-tight">
Successfully corrected sections
</span>
<div className="mt-auto space-y-0 text-[10px]">
<div className="flex justify-between">
<span className="text-muted-foreground">Words Replaced</span>
<span>{replacedCount}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Words Added / Deleted</span>
<span>+{addedCount} / -{deletedCount}</span>
</div>
</div>
</Card>
<Card
className="p-2 cursor-pointer hover:bg-muted/30 transition-colors flex flex-col overflow-hidden h-full"
onClick={onMetricClick.uncorrected}
>
<div className="flex items-center gap-1 mb-0.5">
<div className="w-3 h-3 rounded bg-orange-500/25 shrink-0" />
<span className="text-xs text-muted-foreground truncate">Uncorrected Gaps</span>
</div>
<span className="text-lg font-semibold text-amber-500 leading-tight">
{uncorrectedGapCount} ({uncorrectedPercentage}%)
</span>
<span className="text-[10px] text-muted-foreground leading-tight">
Sections that may need manual review
</span>
<div className="mt-auto space-y-0 text-[10px]">
<div className="flex justify-between">
<span className="text-muted-foreground">Words Uncorrected</span>
<span>{uncorrectedWordCount}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Number of Gaps</span>
<span>{uncorrectedGaps.length}</span>
</div>
</div>
</Card>
</div>
</div>
)}
</div>
)
}
+79 -270
View File
@@ -1,8 +1,6 @@
'use client'
import { Button } from '@/components/ui/button'
import { Switch } from '@/components/ui/switch'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Card } from '@/components/ui/card'
import {
@@ -19,8 +17,6 @@ import {
Undo2,
Redo2,
Timer,
RotateCcw,
MessageSquare,
Eye,
CheckCircle2,
XCircle,
@@ -28,7 +24,7 @@ import {
import { CorrectionData, InteractionMode } from '@/lib/lyrics-review/types'
import ModeSelector from './ModeSelector'
import AudioPlayer from './AudioPlayer'
import { findWordById } from '@/lib/lyrics-review/utils/wordUtils'
import GuidancePanel from './GuidancePanel'
import { cn } from '@/lib/utils'
interface ApiClient {
@@ -54,7 +50,6 @@ interface HeaderProps {
onHandlerClick?: (handler: string) => void
onFindReplace?: () => void
onEditAll?: () => void
onUnCorrectAll?: () => void
onResetCorrections?: () => void
onTimingOffset?: () => void
timingOffsetMs?: number
@@ -62,8 +57,8 @@ interface HeaderProps {
onRedo: () => void
canUndo: boolean
canRedo: boolean
annotationsEnabled?: boolean
onAnnotationsToggle?: (enabled: boolean) => void
statsVisible: boolean
onStatsToggle: () => void
reviewMode?: boolean
onReviewModeToggle?: (enabled: boolean) => void
onAcceptAllCorrections?: () => void
@@ -86,7 +81,6 @@ export default function Header({
onHandlerClick,
onFindReplace,
onEditAll,
onUnCorrectAll,
onResetCorrections,
onTimingOffset,
timingOffsetMs = 0,
@@ -94,8 +88,8 @@ export default function Header({
onRedo,
canUndo,
canRedo,
annotationsEnabled = true,
onAnnotationsToggle,
statsVisible,
onStatsToggle,
reviewMode = false,
onReviewModeToggle,
onAcceptAllCorrections,
@@ -104,75 +98,12 @@ export default function Header({
}: HeaderProps) {
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768
// Get handlers with their correction counts
const handlerCounts =
data.corrections?.reduce(
(counts: Record<string, number>, correction) => {
counts[correction.handler] = (counts[correction.handler] || 0) + 1
return counts
},
{} as Record<string, number>
) || {}
// Get available handlers from metadata
const availableHandlers = data.metadata.available_handlers || []
const enabledHandlers = new Set(data.metadata.enabled_handlers || [])
// Check if agentic mode is active
const availableHandlers = data.metadata.available_handlers || []
const isAgenticMode = availableHandlers.some(
(h: { id: string }) => h.id === 'AgenticCorrector'
)
// Create a map of gap IDs to their corrections
const gapCorrections = data.corrections.reduce(
(map: Record<string, number>, correction) => {
const gap = data.gap_sequences.find((g) =>
g.transcribed_word_ids.includes(correction.word_id)
)
if (gap) {
map[gap.id] = (map[gap.id] || 0) + 1
}
return map
},
{} as Record<string, number>
)
// Calculate metrics
const correctedGapCount = Object.keys(gapCorrections).length
const uncorrectedGapCount = data.gap_sequences.length - correctedGapCount
// Calculate correction type counts
const replacedCount = data.corrections.filter(
(c) => !c.is_deletion && !c.split_total
).length
const addedCount = data.corrections.filter((c) => c.split_total).length
const deletedCount = data.corrections.filter((c) => c.is_deletion).length
// Calculate additional metrics for detailed display (matching old CorrectionMetrics)
const totalWords = data.metadata.total_words || 0
const anchorWordCount = data.anchor_sequences?.reduce(
(sum, anchor) => sum + (anchor.transcribed_word_ids?.length || 0),
0
) ?? 0
const multiSourceAnchors = data.anchor_sequences?.filter(
(anchor) =>
anchor?.reference_word_ids && Object.keys(anchor.reference_word_ids).length > 1
).length ?? 0
// Calculate uncorrected gaps info
const uncorrectedGaps = data.gap_sequences
.filter((gap) => !gapCorrections[gap.id] && gap.transcribed_word_ids.length > 0)
const uncorrectedWordCount = uncorrectedGaps.reduce(
(sum, gap) => sum + gap.transcribed_word_ids.length,
0
)
// Calculate percentages
const anchorPercentage = totalWords > 0 ? Math.round((anchorWordCount / totalWords) * 100) : 0
const correctedWordCount = replacedCount + addedCount
const correctedPercentage = totalWords > 0 ? Math.round((correctedWordCount / totalWords) * 100) : 0
const uncorrectedPercentage = totalWords > 0 ? Math.round((uncorrectedWordCount / totalWords) * 100) : 0
return (
<TooltipProvider>
<div className="space-y-2">
@@ -185,152 +116,47 @@ export default function Header({
)}
{/* Review Mode toggle and Load File button */}
<div className="flex gap-2 justify-end items-center mb-2">
{!isReadOnly && isAgenticMode && onReviewModeToggle && (
<Tooltip>
<TooltipTrigger asChild>
<Badge
variant={reviewMode ? 'default' : 'outline'}
className="cursor-pointer hover:opacity-80 transition-opacity"
onClick={() => onReviewModeToggle(!reviewMode)}
>
<Eye className="h-3 w-3 mr-1" />
{reviewMode ? 'Review Mode' : 'Review Off'}
</Badge>
</TooltipTrigger>
<TooltipContent>
{reviewMode
? 'Hide inline correction actions'
: 'Show inline actions on all corrections for quick review'}
</TooltipContent>
</Tooltip>
)}
{isReadOnly && (
<Button variant="outline" size="sm" onClick={onFileLoad} className={cn(isMobile && 'w-full')}>
<Upload className="h-4 w-4 mr-1" />
Load File
</Button>
)}
</div>
{/* Handler panel and metrics */}
<div className={cn('flex gap-2 mb-2 overflow-hidden', isMobile ? 'flex-col' : 'flex-row', isMobile ? 'h-auto' : 'h-[140px]')}>
{/* Handler panel */}
<Card className={cn('p-2', isMobile ? 'w-full' : 'w-[280px] min-w-[280px]')}>
<h4 className="text-xs text-muted-foreground mb-1">Correction Handlers</h4>
<div className="flex-1 overflow-auto flex flex-col">
{availableHandlers.map((handler: { id: string; name: string; description: string }) => (
<div key={handler.id} className="mb-1">
<Tooltip>
<TooltipTrigger asChild>
<div className="flex items-center gap-2">
<Switch
checked={enabledHandlers.has(handler.id)}
onCheckedChange={(checked) => onHandlerToggle(handler.id, checked)}
disabled={isUpdatingHandlers}
className="scale-75"
/>
<Label
className="text-xs cursor-pointer hover:text-foreground hover:underline transition-colors"
onClick={() => onHandlerClick?.(handler.id)}
>
{handler.name} ({handlerCounts[handler.id] || 0})
</Label>
</div>
</TooltipTrigger>
<TooltipContent>
<p>{handler.description}</p>
</TooltipContent>
</Tooltip>
</div>
))}
</div>
</Card>
{/* Metrics panel - matches old CorrectionMetrics component */}
<div className="flex-1 grid grid-cols-3 gap-2 h-full">
{/* Anchor Sequences */}
<Card
className="p-2 cursor-pointer hover:bg-muted/30 transition-colors flex flex-col overflow-hidden h-full"
onClick={onMetricClick.anchor}
>
<div className="flex items-center gap-1 mb-0.5">
<div className="w-3 h-3 rounded bg-blue-500/25 shrink-0" />
<span className="text-xs text-muted-foreground truncate">Anchor Sequences</span>
</div>
<span className="text-lg font-semibold leading-tight">
{data.metadata.anchor_sequences_count ?? '-'} ({anchorPercentage}%)
</span>
<span className="text-[10px] text-muted-foreground leading-tight">
Matched sections between transcription and reference
</span>
<div className="mt-auto space-y-0 text-[10px]">
<div className="flex justify-between">
<span className="text-muted-foreground">Words in Anchors</span>
<span>{anchorWordCount}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Multi-source Matches</span>
<span>{multiSourceAnchors}</span>
</div>
</div>
</Card>
{/* Corrected Gaps */}
<Card
className="p-2 cursor-pointer hover:bg-muted/30 transition-colors flex flex-col overflow-hidden h-full"
onClick={onMetricClick.corrected}
>
<div className="flex items-center gap-1 mb-0.5">
<div className="w-3 h-3 rounded bg-green-500/25 shrink-0" />
<span className="text-xs text-muted-foreground truncate">Corrected Gaps</span>
</div>
<span className="text-lg font-semibold text-green-500 leading-tight">
{correctedGapCount} ({correctedPercentage}%)
</span>
<span className="text-[10px] text-muted-foreground leading-tight">
Successfully corrected sections
</span>
<div className="mt-auto space-y-0 text-[10px]">
<div className="flex justify-between">
<span className="text-muted-foreground">Words Replaced</span>
<span>{replacedCount}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Words Added / Deleted</span>
<span>+{addedCount} / -{deletedCount}</span>
</div>
</div>
</Card>
{/* Uncorrected Gaps */}
<Card
className="p-2 cursor-pointer hover:bg-muted/30 transition-colors flex flex-col overflow-hidden h-full"
onClick={onMetricClick.uncorrected}
>
<div className="flex items-center gap-1 mb-0.5">
<div className="w-3 h-3 rounded bg-orange-500/25 shrink-0" />
<span className="text-xs text-muted-foreground truncate">Uncorrected Gaps</span>
</div>
<span className="text-lg font-semibold text-amber-500 leading-tight">
{uncorrectedGapCount} ({uncorrectedPercentage}%)
</span>
<span className="text-[10px] text-muted-foreground leading-tight">
Sections that may need manual review
</span>
<div className="mt-auto space-y-0 text-[10px]">
<div className="flex justify-between">
<span className="text-muted-foreground">Words Uncorrected</span>
<span>{uncorrectedWordCount}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Number of Gaps</span>
<span>{uncorrectedGaps.length}</span>
</div>
</div>
</Card>
{(!isReadOnly && isAgenticMode && onReviewModeToggle) || isReadOnly ? (
<div className="flex gap-2 justify-end items-center mb-2">
{!isReadOnly && isAgenticMode && onReviewModeToggle && (
<Tooltip>
<TooltipTrigger asChild>
<Badge
variant={reviewMode ? 'default' : 'outline'}
className="cursor-pointer hover:opacity-80 transition-opacity"
onClick={() => onReviewModeToggle(!reviewMode)}
>
<Eye className="h-3 w-3 mr-1" />
{reviewMode ? 'Review Mode' : 'Review Off'}
</Badge>
</TooltipTrigger>
<TooltipContent>
{reviewMode
? 'Hide inline correction actions'
: 'Show inline actions on all corrections for quick review'}
</TooltipContent>
</Tooltip>
)}
{isReadOnly && (
<Button variant="outline" size="sm" onClick={onFileLoad} className={cn(isMobile && 'w-full')}>
<Upload className="h-4 w-4 mr-1" />
Load File
</Button>
)}
</div>
</div>
) : null}
{/* Guidance panel with color legend, tips, and conditionally visible stats */}
<GuidancePanel
data={data}
isReadOnly={isReadOnly}
onMetricClick={onMetricClick}
onHandlerToggle={onHandlerToggle}
isUpdatingHandlers={isUpdatingHandlers}
onHandlerClick={onHandlerClick}
statsVisible={statsVisible}
onStatsToggle={onStatsToggle}
/>
{/* Batch Actions Panel */}
{!isReadOnly && reviewMode && isAgenticMode && data.corrections?.length > 0 && (
@@ -396,7 +222,7 @@ export default function Header({
Undo All
</Button>
</TooltipTrigger>
<TooltipContent>Undo all your changes</TooltipContent>
<TooltipContent className="max-w-xs">Reset all changes back to the original AI-corrected lyrics</TooltipContent>
</Tooltip>
)}
@@ -434,71 +260,54 @@ export default function Header({
)}
{!isReadOnly && (
<Button variant="outline" size="sm" onClick={onFindReplace} className="h-8 text-xs">
<Search className="h-3.5 w-3.5 mr-1" />
Find/Replace
</Button>
<Tooltip>
<TooltipTrigger asChild>
<Button variant="outline" size="sm" onClick={onFindReplace} className="h-8 text-xs">
<Search className="h-3.5 w-3.5 mr-1" />
Find/Replace
</Button>
</TooltipTrigger>
<TooltipContent className="max-w-xs">Search for text across all lyrics and replace it. Useful for a word that appears multiple times.</TooltipContent>
</Tooltip>
)}
{!isReadOnly && onEditAll && (
<Button variant="outline" size="sm" onClick={onEditAll} className="h-8 text-xs">
<Edit className="h-3.5 w-3.5 mr-1" />
Edit All
</Button>
)}
{!isReadOnly && onUnCorrectAll && (
<Tooltip>
<TooltipTrigger asChild>
<Button variant="outline" size="sm" onClick={onUnCorrectAll} className="h-8 text-xs">
<RotateCcw className="h-3.5 w-3.5 mr-1" />
Undo Auto Corrections
<Button variant="outline" size="sm" onClick={onEditAll} className="h-8 text-xs">
<Edit className="h-3.5 w-3.5 mr-1" />
Edit All
</Button>
</TooltipTrigger>
<TooltipContent>Revert only automatic AI corrections (keeps your manual edits)</TooltipContent>
<TooltipContent className="max-w-xs">View and edit all lyrics as plain text. Useful when many lines need changing.</TooltipContent>
</Tooltip>
)}
{!isReadOnly && onTimingOffset && (
<div className="flex items-center">
<Button
variant="outline"
size="sm"
onClick={onTimingOffset}
className={cn('h-8 text-xs', timingOffsetMs !== 0 && 'border-purple-500 text-purple-500')}
>
<Timer className="h-3.5 w-3.5 mr-1" />
Timing Offset
</Button>
{timingOffsetMs !== 0 && (
<span className="ml-1 text-xs font-bold text-purple-500">
{timingOffsetMs > 0 ? '+' : ''}
{timingOffsetMs}ms
</span>
)}
</div>
)}
{!isReadOnly && onAnnotationsToggle && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="sm"
onClick={() => onAnnotationsToggle(!annotationsEnabled)}
className={cn('h-8 text-xs', annotationsEnabled && 'border-primary')}
>
<MessageSquare className="h-3.5 w-3.5 mr-1" />
{annotationsEnabled ? 'Feedback On' : 'Feedback Off'}
</Button>
<div className="flex items-center">
<Button
variant="outline"
size="sm"
onClick={onTimingOffset}
className={cn('h-8 text-xs', timingOffsetMs !== 0 && 'border-purple-500 text-purple-500')}
>
<Timer className="h-3.5 w-3.5 mr-1" />
Timing Offset
</Button>
{timingOffsetMs !== 0 && (
<span className="ml-1 text-xs font-bold text-purple-500">
{timingOffsetMs > 0 ? '+' : ''}
{timingOffsetMs}ms
</span>
)}
</div>
</TooltipTrigger>
<TooltipContent>
{annotationsEnabled
? 'Click to disable annotation prompts when editing'
: 'Click to enable annotation prompts when editing'}
</TooltipContent>
<TooltipContent className="max-w-xs">Shift all word timings forward or backward. Use if lyrics appear slightly early or late in the preview.</TooltipContent>
</Tooltip>
)}
</div>
<AudioPlayer
@@ -3,7 +3,7 @@
import { useState, useEffect, useCallback, useMemo, memo } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Video, Check } from 'lucide-react'
import { Video, Check, CheckCircle2 } from 'lucide-react'
import { toast } from 'sonner'
import {
AnchorSequence,
@@ -14,11 +14,12 @@ import {
LyricsSegment,
ReferenceSource,
WordCorrection,
CorrectionAnnotation,
FlashType,
Word,
WordClickInfo,
ModalContent,
} from '@/lib/lyrics-review/types'
import type { EditLog, EditLogEntry, EditFeedbackReason } from '@/lib/lyrics-review/types'
import type { InstrumentalSelectionType } from '@/lib/api'
import { cn } from '@/lib/utils'
import ReferenceView from './ReferenceView'
@@ -26,11 +27,11 @@ import TranscriptionView from './TranscriptionView'
import { EditModal } from './modals'
import { ReviewChangesModal } from './modals'
import { ReplaceAllLyricsModal } from './modals'
import { CorrectionAnnotationModal } from './modals'
import { AddLyricsModal } from './modals'
import { FindReplaceModal } from './modals'
import { TimingOffsetModal } from './modals'
import CorrectionDetailCard from './CorrectionDetailCard'
import EditFeedbackBar from './EditFeedbackBar'
import {
addSegmentBefore,
splitSegment,
@@ -45,7 +46,9 @@ import {
setModalHandler,
getModalState,
} from '@/lib/lyrics-review/utils/keyboardHandlers'
import { createEditLog, addEditEntry, attachFeedback } from '@/lib/lyrics-review/utils/editLog'
import Header from './Header'
import GapNavigator from './GapNavigator'
import { getWordsFromIds } from '@/lib/lyrics-review/utils/wordUtils'
import { applyOffsetToCorrectionData, applyOffsetToSegment } from '@/lib/lyrics-review/utils/timingUtils'
@@ -61,7 +64,8 @@ declare global {
interface ApiClient {
submitCorrections: (data: CorrectionData) => Promise<void>
submitAnnotations: (annotations: Omit<CorrectionAnnotation, 'annotation_id' | 'timestamp'>[]) => Promise<void>
submitAnnotations: (annotations: never[]) => Promise<void>
submitEditLog: (editLog: EditLog) => Promise<void>
updateHandlers: (handlers: string[]) => Promise<CorrectionData>
addLyrics: (source: string, lyrics: string) => Promise<CorrectionData>
getAudioUrl: (hash: string) => string
@@ -135,21 +139,23 @@ export default function LyricsAnalyzer({
const [countdown, setCountdown] = useState(2)
const [showInstrumentalReview, setShowInstrumentalReview] = useState(false)
// Annotation state
const [annotations, setAnnotations] = useState<Omit<CorrectionAnnotation, 'annotation_id' | 'timestamp'>[]>([])
const [isAnnotationModalOpen, setIsAnnotationModalOpen] = useState(false)
const [pendingAnnotation, setPendingAnnotation] = useState<{
originalText: string
correctedText: string
wordIdsAffected: string[]
gapId?: string
} | null>(null)
const [annotationsEnabled, setAnnotationsEnabled] = useState(() => {
if (typeof window === 'undefined') return true
const saved = localStorage.getItem('annotationsEnabled')
return saved !== null ? saved === 'true' : true
// Edit log state
const [editLog] = useState<EditLog>(() => createEditLog(jobId ?? 'unknown', audioHash))
const [lastEditEntry, setLastEditEntry] = useState<EditLogEntry | null>(null)
const [showFeedbackBar, setShowFeedbackBar] = useState(false)
// Stats panel visibility
const [statsVisible, setStatsVisible] = useState(false)
// Advanced mode for transcription view (Simple/Advanced toggle)
const [advancedMode, setAdvancedMode] = useState(() => {
if (typeof window === 'undefined') return false
return localStorage.getItem('lyricsReviewAdvancedMode') === 'true'
})
// Gap navigation state
const [currentGapIndex, setCurrentGapIndex] = useState<number | null>(null)
// Correction detail card state
const [correctionDetailOpen, setCorrectionDetailOpen] = useState(false)
const [selectedCorrection, setSelectedCorrection] = useState<{
@@ -204,11 +210,97 @@ export default function LyricsAnalyzer({
}
}, [data, isReadOnly, initialData])
// Flash handler (defined early so gap navigation can use it)
const handleFlash = useCallback((type: FlashType, info?: HighlightInfo) => {
setFlashingType(null)
setHighlightInfo(null)
requestAnimationFrame(() => {
requestAnimationFrame(() => {
setFlashingType(type)
if (info) {
setHighlightInfo(info)
}
setTimeout(() => {
setFlashingType(null)
setHighlightInfo(null)
}, 1200)
})
})
}, [])
// Compute uncorrected gaps for navigation
const uncorrectedGaps = useMemo(() => {
const gapCorrections = data.corrections.reduce(
(map: Record<string, boolean>, correction) => {
const gap = data.gap_sequences.find((g) =>
g.transcribed_word_ids.includes(correction.word_id)
)
if (gap) map[gap.id] = true
return map
},
{} as Record<string, boolean>
)
return data.gap_sequences.filter(
(gap) => !gapCorrections[gap.id] && gap.transcribed_word_ids.length > 0
)
}, [data.gap_sequences, data.corrections])
// Navigate to a specific gap
const navigateToGap = useCallback(
(index: number) => {
if (index < 0 || index >= uncorrectedGaps.length) return
setCurrentGapIndex(index)
const gap = uncorrectedGaps[index]
const firstWordId = gap.transcribed_word_ids[0]
if (firstWordId) {
const el = document.getElementById(`word-${firstWordId}`)
if (el) {
el.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
}
// Flash only the specific gap's words (not all uncorrected gaps)
const gapWords = gap.transcribed_word_ids
.map((id) => {
for (const seg of data.corrected_segments) {
const w = seg.words.find((w) => w.id === id)
if (w) return w
}
return null
})
.filter((w): w is Word => w !== null)
handleFlash('uncorrected', {
type: 'gap',
sequence: gap,
transcribed_words: gapWords,
})
},
[uncorrectedGaps, handleFlash, data.corrected_segments]
)
const handlePrevGap = useCallback(() => {
const newIndex = currentGapIndex !== null ? currentGapIndex - 1 : 0
navigateToGap(Math.max(0, newIndex))
}, [currentGapIndex, navigateToGap])
const handleNextGap = useCallback(() => {
const newIndex = currentGapIndex !== null ? currentGapIndex + 1 : 0
navigateToGap(Math.min(uncorrectedGaps.length - 1, newIndex))
}, [currentGapIndex, uncorrectedGaps.length, navigateToGap])
// Word IDs for the currently active gap (persistent ring indicator)
const activeGapWordIds = useMemo(() => {
if (currentGapIndex === null || currentGapIndex >= uncorrectedGaps.length) return undefined
return new Set(uncorrectedGaps[currentGapIndex].transcribed_word_ids)
}, [currentGapIndex, uncorrectedGaps])
// Keyboard handlers
useEffect(() => {
const { handleKeyDown, handleKeyUp, cleanup } = setupKeyboardHandlers({
setIsShiftPressed,
setIsCtrlPressed,
onNextGap: handleNextGap,
onPrevGap: handlePrevGap,
})
window.addEventListener('keydown', handleKeyDown)
@@ -225,7 +317,7 @@ export default function LyricsAnalyzer({
document.body.style.userSelect = ''
cleanup()
}
}, [isAnyModalOpen])
}, [isAnyModalOpen, handleNextGap, handlePrevGap])
// Update modal state tracking
useEffect(() => {
@@ -284,51 +376,33 @@ export default function LyricsAnalyzer({
// Calculate effective mode based on modifier key states
const effectiveMode = isCtrlPressed ? 'delete_word' : isShiftPressed ? 'highlight' : interactionMode
// Flash handler
const handleFlash = useCallback((type: FlashType, info?: HighlightInfo) => {
setFlashingType(null)
setHighlightInfo(null)
requestAnimationFrame(() => {
requestAnimationFrame(() => {
setFlashingType(type)
if (info) {
setHighlightInfo(info)
}
setTimeout(() => {
setFlashingType(null)
setHighlightInfo(null)
}, 1200)
})
})
}, [])
// Annotation handlers
const handleSaveAnnotation = useCallback(
(annotation: Omit<CorrectionAnnotation, 'annotation_id' | 'timestamp'>) => {
setAnnotations((prev) => [...prev, annotation])
// Edit feedback handler
const handleEditFeedback = useCallback(
(entryId: string, reason: EditFeedbackReason) => {
attachFeedback(editLog, entryId, reason)
},
[]
[editLog]
)
const handleSkipAnnotation = useCallback(() => {
// No-op for now
}, [])
const handleAnnotationsToggle = useCallback((enabled: boolean) => {
setAnnotationsEnabled(enabled)
const handleAdvancedModeToggle = useCallback((enabled: boolean) => {
setAdvancedMode(enabled)
if (typeof window !== 'undefined') {
localStorage.setItem('annotationsEnabled', String(enabled))
localStorage.setItem('lyricsReviewAdvancedMode', String(enabled))
}
}, [])
const triggerAnnotationModal = useCallback(
(originalText: string, correctedText: string, wordIdsAffected: string[], gapId?: string) => {
if (!annotationsEnabled || isReadOnly) return
setPendingAnnotation({ originalText, correctedText, wordIdsAffected, gapId })
setIsAnnotationModalOpen(true)
const showFeedbackForEntry = useCallback(
(entry: EditLogEntry) => {
// Only show for single-word edits
if (!['word_change', 'word_delete', 'word_add'].includes(entry.operation)) return
// Dismiss previous entry with no_response if still showing
if (lastEditEntry && lastEditEntry.id !== entry.id) {
attachFeedback(editLog, lastEditEntry.id, 'no_response')
}
setLastEditEntry(entry)
setShowFeedbackBar(true)
},
[annotationsEnabled, isReadOnly]
[editLog, lastEditEntry]
)
// Show correction detail
@@ -364,9 +438,18 @@ export default function LyricsAnalyzer({
const handleWordClick = useCallback(
(info: WordClickInfo) => {
if (effectiveMode === 'delete_word') {
const deletedWord = data.corrected_segments.flatMap((s) => s.words).find((w) => w.id === info.word_id)
const segment = data.corrected_segments.find((s) => s.words.some((w) => w.id === info.word_id))
const entry = addEditEntry(editLog, 'word_delete', {
segment_id: segment?.id,
segment_index: segment ? data.corrected_segments.indexOf(segment) : null,
word_ids_before: [info.word_id],
text_before: deletedWord?.text ?? '',
})
const newData = deleteWord(data, info.word_id)
updateDataWithHistory(newData, 'delete word')
handleFlash('word')
showFeedbackForEntry(entry)
return
}
@@ -463,26 +546,75 @@ export default function LyricsAnalyzer({
corrected_segments: newSegments,
}
updateDataWithHistory(newData, 'update segment')
// Diff original vs updated words to create edit log entries
const originalSegment = editModalSegment.originalSegment || editModalSegment.segment
const entries: EditLogEntry[] = []
if (originalSegment && originalSegment.text !== updatedSegment.text) {
const wordIds = updatedSegment.words.map((w) => w.id)
triggerAnnotationModal(originalSegment.text, updatedSegment.text, wordIds)
const origWordMap = new Map(originalSegment.words.map((w) => [w.id, w]))
const updatedWordMap = new Map(updatedSegment.words.map((w) => [w.id, w]))
// Changed or deleted words
for (const origWord of originalSegment.words) {
const updatedWord = updatedWordMap.get(origWord.id)
if (!updatedWord) {
entries.push(addEditEntry(editLog, 'word_delete', {
segment_id: originalSegment.id,
segment_index: editModalSegment.index,
word_ids_before: [origWord.id],
text_before: origWord.text,
}))
} else if (updatedWord.text !== origWord.text) {
entries.push(addEditEntry(editLog, 'word_change', {
segment_id: originalSegment.id,
segment_index: editModalSegment.index,
word_ids_before: [origWord.id],
word_ids_after: [updatedWord.id],
text_before: origWord.text,
text_after: updatedWord.text,
}))
}
}
// Added words
for (const updatedWord of updatedSegment.words) {
if (!origWordMap.has(updatedWord.id)) {
entries.push(addEditEntry(editLog, 'word_add', {
segment_id: originalSegment.id,
segment_index: editModalSegment.index,
word_ids_after: [updatedWord.id],
text_after: updatedWord.text,
}))
}
}
// Show feedback bar only for single-word edits
if (entries.length === 1) {
showFeedbackForEntry(entries[0])
}
}
updateDataWithHistory(newData, 'update segment')
setEditModalSegment(null)
},
[history, historyIndex, editModalSegment, updateDataWithHistory, triggerAnnotationModal]
[history, historyIndex, editModalSegment, updateDataWithHistory, editLog, showFeedbackForEntry]
)
// Delete segment handler
const handleDeleteSegment = useCallback(
(segmentIndex: number) => {
const segment = data.corrected_segments[segmentIndex]
if (segment) {
addEditEntry(editLog, 'segment_delete', {
segment_id: segment.id,
segment_index: segmentIndex,
word_ids_before: segment.words.map((w) => w.id),
text_before: segment.text,
})
}
const newData = deleteSegment(data, segmentIndex)
updateDataWithHistory(newData, 'delete segment')
},
[data, updateDataWithHistory]
[data, updateDataWithHistory, editLog]
)
// Correction action handlers
@@ -525,9 +657,18 @@ export default function LyricsAnalyzer({
corrections: newCorrections,
}
addEditEntry(editLog, 'revert_correction', {
segment_id: segment.id,
segment_index: segmentIndex,
word_ids_before: [wordId],
word_ids_after: [correction.word_id],
text_before: correction.corrected_word,
text_after: correction.original_word,
})
updateDataWithHistory(newData, 'revert correction')
},
[data, updateDataWithHistory]
[data, updateDataWithHistory, editLog]
)
const handleEditCorrection = useCallback(
@@ -575,6 +716,10 @@ export default function LyricsAnalyzer({
return
}
addEditEntry(editLog, 'revert_all', {
details: { count: data.corrections?.length ?? 0 },
})
const corrections = [...(data.corrections || [])].reverse()
let newData = data
@@ -610,7 +755,7 @@ export default function LyricsAnalyzer({
}
updateDataWithHistory(newData, 'revert all corrections')
}, [data, updateDataWithHistory])
}, [data, updateDataWithHistory, editLog])
// Finish review - opens preview modal
const handleFinishReview = useCallback(() => {
@@ -633,12 +778,12 @@ export default function LyricsAnalyzer({
// 1. Save corrections (not final submission yet)
await apiClient.submitCorrections(dataToSubmit)
// 2. Save annotations
if (annotations.length > 0) {
// 2. Save edit log (non-blocking)
if (editLog.entries.length > 0) {
try {
await apiClient.submitAnnotations(annotations)
await apiClient.submitEditLog(editLog)
} catch (error) {
console.error('Failed to submit annotations:', error)
console.error('Failed to submit edit log:', error)
}
}
@@ -666,7 +811,7 @@ export default function LyricsAnalyzer({
toast.error('Failed to submit corrections. Please try again.')
setIsSubmitting(false) // Reset on error so user can retry
}
}, [apiClient, data, timingOffsetMs, annotations, isLocalMode, jobId])
}, [apiClient, data, timingOffsetMs, editLog, isLocalMode, jobId])
// Play segment handler
const handlePlaySegment = useCallback(
@@ -798,9 +943,23 @@ export default function LyricsAnalyzer({
options: { caseSensitive: boolean; useRegex: boolean; fullTextMode: boolean }
) => {
const newData = findAndReplace(data, findText, replaceText, options)
// Count how many segments changed
const changedSegments = newData.corrected_segments.filter(
(seg, i) => seg.text !== data.corrected_segments[i]?.text
)
addEditEntry(editLog, 'find_replace', {
text_before: findText,
text_after: replaceText,
details: {
pattern: findText,
replacement: replaceText,
segments_affected: changedSegments.length,
...options,
},
})
updateDataWithHistory(newData, 'find/replace')
},
[data, updateDataWithHistory]
[data, updateDataWithHistory, editLog]
)
// Un-correct all
@@ -826,11 +985,17 @@ export default function LyricsAnalyzer({
const handleSaveReplaceAllLyrics = useCallback(
(newSegments: LyricsSegment[]) => {
addEditEntry(editLog, 'replace_all_lyrics', {
details: {
segments_before: data.corrected_segments.length,
segments_after: newSegments.length,
},
})
const newData = { ...data, corrected_segments: newSegments }
updateDataWithHistory(newData, 'replace all lyrics')
setIsReplaceAllLyricsModalOpen(false)
},
[data, updateDataWithHistory]
[data, updateDataWithHistory, editLog]
)
// Undo/Redo
@@ -925,10 +1090,9 @@ export default function LyricsAnalyzer({
onRedo={handleRedo}
canUndo={canUndo}
canRedo={canRedo}
onUnCorrectAll={handleUnCorrectAll}
onResetCorrections={handleResetCorrections}
annotationsEnabled={annotationsEnabled}
onAnnotationsToggle={handleAnnotationsToggle}
statsVisible={statsVisible}
onStatsToggle={() => setStatsVisible((v) => !v)}
reviewMode={reviewMode}
onReviewModeToggle={setReviewMode}
onAcceptAllCorrections={handleAcceptAllCorrections}
@@ -956,6 +1120,9 @@ export default function LyricsAnalyzer({
onEditCorrection={handleEditCorrection}
onAcceptCorrection={handleAcceptCorrection}
onShowCorrectionDetail={handleShowCorrectionDetail}
activeGapWordIds={activeGapWordIds}
advancedMode={advancedMode}
onAdvancedModeToggle={handleAdvancedModeToggle}
/>
<ReferenceView
referenceSources={data.reference_lyrics}
@@ -979,7 +1146,35 @@ export default function LyricsAnalyzer({
{/* Sticky footer bar */}
{!isReadOnly && apiClient && (
<div className="fixed bottom-0 left-0 right-0 bg-background border-t shadow-lg py-3 px-4 z-50 flex justify-center items-center gap-4">
<div className="fixed bottom-0 left-0 right-0 bg-background border-t shadow-lg py-3 px-4 z-50 flex justify-center items-center gap-4 flex-wrap">
<GapNavigator
currentGapIndex={currentGapIndex}
totalGaps={uncorrectedGaps.length}
onPrevGap={handlePrevGap}
onNextGap={handleNextGap}
/>
{data.gap_sequences.length > 0 && (
<div className="flex items-center gap-1.5">
<div className="w-16 h-1.5 bg-muted rounded-full overflow-hidden">
<div
className="h-full bg-green-500 rounded-full transition-all"
style={{
width: `${data.gap_sequences.length > 0 ? ((data.gap_sequences.length - uncorrectedGaps.length) / data.gap_sequences.length) * 100 : 0}%`,
}}
/>
</div>
{uncorrectedGaps.length === 0 ? (
<span className="text-xs text-green-500 flex items-center gap-0.5">
<CheckCircle2 className="h-3.5 w-3.5" />
All gaps reviewed
</span>
) : (
<span className="text-xs text-muted-foreground whitespace-nowrap">
{data.gap_sequences.length - uncorrectedGaps.length}/{data.gap_sequences.length} gaps reviewed
</span>
)}
</div>
)}
<span className="text-sm text-muted-foreground">Lyrics look good?</span>
<Button onClick={handleFinishReview} disabled={isReviewComplete}>
{isReviewComplete ? 'Review Complete' : 'Preview Video'}
@@ -1074,26 +1269,12 @@ export default function LyricsAnalyzer({
existingSegments={data.corrected_segments}
/>
{pendingAnnotation && (
<CorrectionAnnotationModal
open={isAnnotationModalOpen}
onClose={() => {
setIsAnnotationModalOpen(false)
setPendingAnnotation(null)
}}
onSave={handleSaveAnnotation}
onSkip={handleSkipAnnotation}
originalText={pendingAnnotation.originalText}
correctedText={pendingAnnotation.correctedText}
wordIdsAffected={pendingAnnotation.wordIdsAffected}
referenceSources={Object.keys(data.reference_lyrics || {})}
audioHash={audioHash}
artist={data.metadata?.audio_filepath?.split('/').pop()?.split('.')[0] || 'Unknown'}
title={data.metadata?.audio_filepath?.split('/').pop()?.split('.')[0] || 'Unknown'}
sessionId={audioHash}
gapId={pendingAnnotation.gapId}
/>
)}
<EditFeedbackBar
entry={lastEditEntry}
visible={showFeedbackBar}
onFeedback={handleEditFeedback}
onDismiss={() => setShowFeedbackBar(false)}
/>
{selectedCorrection && (
<CorrectionDetailCard
@@ -36,8 +36,8 @@ export default function ModeSelector({ effectiveMode, onChange }: ModeSelectorPr
Edit
</ToggleGroupItem>
</TooltipTrigger>
<TooltipContent>
<p>Default mode; click words to edit that lyrics segment</p>
<TooltipContent className="max-w-xs">
<p>Click any word to edit that lyrics line. Default mode for correcting misheard words.</p>
</TooltipContent>
</Tooltip>
@@ -51,8 +51,8 @@ export default function ModeSelector({ effectiveMode, onChange }: ModeSelectorPr
Highlight
</ToggleGroupItem>
</TooltipTrigger>
<TooltipContent>
<p>Hold SHIFT and click words to highlight the matching anchor sequence</p>
<TooltipContent className="max-w-xs">
<p>Click any word to see where it matches in the reference lyrics. Shortcut: hold SHIFT.</p>
</TooltipContent>
</Tooltip>
@@ -66,8 +66,8 @@ export default function ModeSelector({ effectiveMode, onChange }: ModeSelectorPr
Delete
</ToggleGroupItem>
</TooltipTrigger>
<TooltipContent>
<p>Hold CTRL and click words to delete them</p>
<TooltipContent className="max-w-xs">
<p>Click any word to instantly delete it. Great for removing phantom words like &quot;And&quot; during instrumental sections. Shortcut: hold CTRL.</p>
</TooltipContent>
</Tooltip>
</ToggleGroup>
@@ -4,6 +4,7 @@ import { useState } from 'react'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
import { Badge } from '@/components/ui/badge'
import { Play, Trash2, Type, Clock } from 'lucide-react'
import { HighlightedText } from './shared/HighlightedText'
import { TranscriptionViewProps, TranscriptionWordPosition } from '@/lib/lyrics-review/types'
@@ -28,6 +29,9 @@ export default function TranscriptionView({
onEditCorrection,
onAcceptCorrection,
onShowCorrectionDetail,
activeGapWordIds,
advancedMode = false,
onAdvancedModeToggle,
}: TranscriptionViewProps) {
const [selectedSegmentIndex, setSelectedSegmentIndex] = useState<number | null>(null)
const [viewMode, setViewMode] = useState<'text' | 'duration'>('text')
@@ -43,7 +47,16 @@ export default function TranscriptionView({
<Card className="p-2">
<CardContent className="p-0">
<div className="flex justify-between items-center mb-1">
<h3 className="text-sm font-semibold">Corrected Transcription</h3>
<div className="flex items-center gap-2">
<h3 className="text-sm font-semibold">Synced Lyrics</h3>
<Badge
variant={advancedMode ? 'default' : 'outline'}
className="cursor-pointer hover:opacity-80 transition-opacity text-[0.65rem] h-5 px-1.5"
onClick={() => onAdvancedModeToggle?.(!advancedMode)}
>
{advancedMode ? 'Advanced' : 'Simple'}
</Badge>
</div>
<ToggleGroup
type="single"
value={viewMode}
@@ -132,22 +145,26 @@ export default function TranscriptionView({
className="flex items-start w-full hover:bg-muted/50 transition-colors"
>
{/* Segment controls */}
<div className="flex items-center gap-0.5 min-w-[2.5em] pr-1">
<span
className="text-muted-foreground w-[1.8em] text-right mr-1 select-none font-mono text-[0.8rem] leading-tight cursor-pointer hover:underline"
onClick={() => setSelectedSegmentIndex(segmentIndex)}
>
{segmentIndex}
</span>
<Button
variant="ghost"
size="icon"
className="h-[18px] w-[18px] min-h-0 min-w-0 p-[1px] text-destructive hover:text-destructive"
onClick={() => handleDeleteSegment(segmentIndex)}
title="Delete segment"
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
<div className="flex items-center gap-0.5 pr-1" style={{ minWidth: advancedMode ? '2.5em' : undefined }}>
{advancedMode && (
<span
className="text-muted-foreground w-[1.8em] text-right mr-1 select-none font-mono text-[0.8rem] leading-tight cursor-pointer hover:underline"
onClick={() => setSelectedSegmentIndex(segmentIndex)}
>
{segmentIndex}
</span>
)}
{advancedMode && (
<Button
variant="ghost"
size="icon"
className="h-[18px] w-[18px] min-h-0 min-w-0 p-[1px] text-destructive hover:text-destructive"
onClick={() => handleDeleteSegment(segmentIndex)}
title="Delete segment"
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
)}
{segment.start_time !== null && (
<Button
variant="ghost"
@@ -176,6 +193,7 @@ export default function TranscriptionView({
currentTime={currentTime}
gaps={data.gap_sequences}
corrections={data.corrections}
activeGapWordIds={activeGapWordIds}
reviewMode={reviewMode}
onRevertCorrection={onRevertCorrection}
onEditCorrection={onEditCorrection}
@@ -0,0 +1,230 @@
import { render, screen, act } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import EditFeedbackBar from '../EditFeedbackBar'
import type { EditLogEntry } from '@/lib/lyrics-review/types'
function makeEntry(overrides: Partial<EditLogEntry> = {}): EditLogEntry {
return {
id: 'entry-1',
timestamp: new Date().toISOString(),
operation: 'word_change',
segment_id: 's1',
segment_index: 0,
word_ids_before: ['w1'],
word_ids_after: ['w1'],
text_before: 'helo',
text_after: 'hello',
feedback: null,
...overrides,
}
}
describe('EditFeedbackBar', () => {
beforeEach(() => {
jest.useFakeTimers()
})
afterEach(() => {
jest.useRealTimers()
})
it('renders nothing when not visible', () => {
const { container } = render(
<EditFeedbackBar entry={makeEntry()} visible={false} onFeedback={jest.fn()} onDismiss={jest.fn()} />
)
expect(container.firstChild).toBeNull()
})
it('renders nothing when entry is null', () => {
const { container } = render(
<EditFeedbackBar entry={null} visible={true} onFeedback={jest.fn()} onDismiss={jest.fn()} />
)
expect(container.firstChild).toBeNull()
})
it('shows question text for word_change', () => {
render(
<EditFeedbackBar entry={makeEntry()} visible={true} onFeedback={jest.fn()} onDismiss={jest.fn()} />
)
expect(screen.getByText(/Changed "helo" → "hello", why\?/)).toBeInTheDocument()
})
it('shows question text for word_delete', () => {
render(
<EditFeedbackBar
entry={makeEntry({ operation: 'word_delete', text_before: 'ghost', text_after: '' })}
visible={true}
onFeedback={jest.fn()}
onDismiss={jest.fn()}
/>
)
expect(screen.getByText(/Removed "ghost", why\?/)).toBeInTheDocument()
})
it('shows question text for word_add', () => {
render(
<EditFeedbackBar
entry={makeEntry({ operation: 'word_add', text_before: '', text_after: 'world' })}
visible={true}
onFeedback={jest.fn()}
onDismiss={jest.fn()}
/>
)
expect(screen.getByText(/Added "world", why\?/)).toBeInTheDocument()
})
it('shows correct reason buttons for word_change', () => {
render(
<EditFeedbackBar entry={makeEntry()} visible={true} onFeedback={jest.fn()} onDismiss={jest.fn()} />
)
expect(screen.getByText('Mis-heard word')).toBeInTheDocument()
expect(screen.getByText('Wrong lyrics')).toBeInTheDocument()
expect(screen.getByText('Spelling/punctuation')).toBeInTheDocument()
expect(screen.getByText('Other')).toBeInTheDocument()
})
it('shows correct reason buttons for word_delete', () => {
render(
<EditFeedbackBar
entry={makeEntry({ operation: 'word_delete' })}
visible={true}
onFeedback={jest.fn()}
onDismiss={jest.fn()}
/>
)
expect(screen.getByText('Phantom word')).toBeInTheDocument()
expect(screen.getByText('Duplicate')).toBeInTheDocument()
})
it('shows correct reason buttons for word_add', () => {
render(
<EditFeedbackBar
entry={makeEntry({ operation: 'word_add' })}
visible={true}
onFeedback={jest.fn()}
onDismiss={jest.fn()}
/>
)
expect(screen.getByText('Missing word')).toBeInTheDocument()
expect(screen.getByText('Split word')).toBeInTheDocument()
})
it('calls onFeedback with correct reason when button clicked', async () => {
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime })
const onFeedback = jest.fn()
const onDismiss = jest.fn()
render(
<EditFeedbackBar entry={makeEntry()} visible={true} onFeedback={onFeedback} onDismiss={onDismiss} />
)
await user.click(screen.getByText('Mis-heard word'))
expect(onFeedback).toHaveBeenCalledWith('entry-1', 'misheard_word')
expect(onDismiss).toHaveBeenCalled()
})
it('calls onFeedback with no_response and onDismiss when X clicked', async () => {
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime })
const onFeedback = jest.fn()
const onDismiss = jest.fn()
render(
<EditFeedbackBar entry={makeEntry()} visible={true} onFeedback={onFeedback} onDismiss={onDismiss} />
)
// Click the X button (last button)
const buttons = screen.getAllByRole('button')
const closeButton = buttons[buttons.length - 1]
await user.click(closeButton)
expect(onFeedback).toHaveBeenCalledWith('entry-1', 'no_response')
expect(onDismiss).toHaveBeenCalled()
})
it('auto-dismisses after 10 seconds with no_response', () => {
const onFeedback = jest.fn()
const onDismiss = jest.fn()
render(
<EditFeedbackBar entry={makeEntry()} visible={true} onFeedback={onFeedback} onDismiss={onDismiss} />
)
expect(onFeedback).not.toHaveBeenCalled()
act(() => {
jest.advanceTimersByTime(10_000)
})
expect(onFeedback).toHaveBeenCalledWith('entry-1', 'no_response')
expect(onDismiss).toHaveBeenCalled()
})
it('pauses auto-dismiss while hovered', async () => {
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime })
const onFeedback = jest.fn()
const onDismiss = jest.fn()
const { container } = render(
<EditFeedbackBar entry={makeEntry()} visible={true} onFeedback={onFeedback} onDismiss={onDismiss} />
)
const bar = container.firstChild as HTMLElement
// Advance 6 seconds, then hover
act(() => {
jest.advanceTimersByTime(6_000)
})
expect(onFeedback).not.toHaveBeenCalled()
await user.hover(bar)
// Advance well past 10s total — should NOT dismiss while hovered
act(() => {
jest.advanceTimersByTime(10_000)
})
expect(onFeedback).not.toHaveBeenCalled()
// Unhover — timer resumes with remaining ~4s
await user.unhover(bar)
// 3s after unhover — still not dismissed
act(() => {
jest.advanceTimersByTime(3_000)
})
expect(onFeedback).not.toHaveBeenCalled()
// 2 more seconds (past the remaining ~4s) — should dismiss
act(() => {
jest.advanceTimersByTime(2_000)
})
expect(onFeedback).toHaveBeenCalledWith('entry-1', 'no_response')
expect(onDismiss).toHaveBeenCalled()
})
it('does not auto-dismiss if user clicks a reason while hovered', async () => {
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime })
const onFeedback = jest.fn()
const onDismiss = jest.fn()
const { container } = render(
<EditFeedbackBar entry={makeEntry()} visible={true} onFeedback={onFeedback} onDismiss={onDismiss} />
)
const bar = container.firstChild as HTMLElement
await user.hover(bar)
await user.click(screen.getByText('Mis-heard word'))
expect(onFeedback).toHaveBeenCalledWith('entry-1', 'misheard_word')
expect(onDismiss).toHaveBeenCalled()
// Advancing time should not trigger a second no_response call
onFeedback.mockClear()
onDismiss.mockClear()
act(() => {
jest.advanceTimersByTime(15_000)
})
expect(onFeedback).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,79 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import GapNavigator from '../GapNavigator'
describe('GapNavigator', () => {
const defaultProps = {
currentGapIndex: null as number | null,
totalGaps: 5,
onPrevGap: jest.fn(),
onNextGap: jest.fn(),
}
beforeEach(() => {
jest.clearAllMocks()
})
it('renders gap counter', () => {
render(<GapNavigator {...defaultProps} currentGapIndex={2} />)
expect(screen.getByText('Gap 3 of 5')).toBeInTheDocument()
})
it('shows "Gap 0 of N" when no gap selected', () => {
render(<GapNavigator {...defaultProps} currentGapIndex={null} />)
expect(screen.getByText('Gap 0 of 5')).toBeInTheDocument()
})
it('renders nothing when totalGaps is 0', () => {
const { container } = render(<GapNavigator {...defaultProps} totalGaps={0} />)
expect(container.firstChild).toBeNull()
})
it('disables prev button at first gap', () => {
render(<GapNavigator {...defaultProps} currentGapIndex={0} />)
expect(screen.getByLabelText('Previous gap')).toBeDisabled()
expect(screen.getByLabelText('Next gap')).not.toBeDisabled()
})
it('disables next button at last gap', () => {
render(<GapNavigator {...defaultProps} currentGapIndex={4} />)
expect(screen.getByLabelText('Previous gap')).not.toBeDisabled()
expect(screen.getByLabelText('Next gap')).toBeDisabled()
})
it('disables prev button when no gap selected', () => {
render(<GapNavigator {...defaultProps} currentGapIndex={null} />)
expect(screen.getByLabelText('Previous gap')).toBeDisabled()
})
it('calls onNextGap when next button clicked', async () => {
const user = userEvent.setup()
render(<GapNavigator {...defaultProps} currentGapIndex={1} />)
await user.click(screen.getByLabelText('Next gap'))
expect(defaultProps.onNextGap).toHaveBeenCalled()
})
it('calls onPrevGap when prev button clicked', async () => {
const user = userEvent.setup()
render(<GapNavigator {...defaultProps} currentGapIndex={2} />)
await user.click(screen.getByLabelText('Previous gap'))
expect(defaultProps.onPrevGap).toHaveBeenCalled()
})
it('shows keyboard shortcut hints in tooltips', () => {
render(<GapNavigator {...defaultProps} currentGapIndex={0} />)
expect(screen.getByLabelText('Previous gap')).toBeInTheDocument()
expect(screen.getByLabelText('Next gap')).toBeInTheDocument()
})
})
@@ -0,0 +1,176 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import GuidancePanel from '../GuidancePanel'
import { CorrectionData } from '@/lib/lyrics-review/types'
// Mock localStorage
const localStorageMock = (() => {
let store: Record<string, string> = {}
return {
getItem: jest.fn((key: string) => store[key] || null),
setItem: jest.fn((key: string, value: string) => { store[key] = value }),
removeItem: jest.fn((key: string) => { delete store[key] }),
clear: jest.fn(() => { store = {} }),
}
})()
Object.defineProperty(window, 'localStorage', { value: localStorageMock })
const makeMockData = (overrides: Partial<CorrectionData> = {}): CorrectionData => ({
corrected_segments: [],
original_segments: [],
anchor_sequences: [
{
id: 'a1',
transcribed_word_ids: ['w1', 'w2'],
reference_word_ids: { source1: ['r1', 'r2'] },
confidence: 0.9,
},
],
gap_sequences: [
{
id: 'g1',
transcribed_word_ids: ['w3'],
reference_word_ids: { source1: ['r3'] },
},
{
id: 'g2',
transcribed_word_ids: ['w4', 'w5'],
reference_word_ids: { source1: ['r4'] },
},
],
corrections: [
{
word_id: 'w3',
corrected_word_id: 'w3c',
original_word: 'orig',
corrected_word: 'fixed',
handler: 'TestHandler',
confidence: 0.8,
source: 'source1',
reason: 'test',
is_deletion: false,
},
],
reference_lyrics: {},
metadata: {
total_words: 10,
anchor_sequences_count: 1,
available_handlers: [],
enabled_handlers: [],
},
...overrides,
} as unknown as CorrectionData)
describe('GuidancePanel', () => {
const defaultProps = {
isReadOnly: false,
onMetricClick: { anchor: jest.fn(), corrected: jest.fn(), uncorrected: jest.fn() },
onHandlerToggle: jest.fn(),
isUpdatingHandlers: false,
onHandlerClick: jest.fn(),
statsVisible: false,
onStatsToggle: jest.fn(),
}
beforeEach(() => {
localStorageMock.clear()
jest.clearAllMocks()
})
it('renders color legend with all three dot labels', () => {
render(<GuidancePanel data={makeMockData()} {...defaultProps} />)
expect(screen.getByText('Matched')).toBeInTheDocument()
expect(screen.getByText('Gaps (needs review)')).toBeInTheDocument()
expect(screen.getByText('Corrected')).toBeInTheDocument()
})
it('renders workflow tip by default', () => {
render(<GuidancePanel data={makeMockData()} {...defaultProps} />)
expect(screen.getByText(/Synced Lyrics/)).toBeInTheDocument()
})
it('shows zero-gap message when no gaps exist', () => {
const data = makeMockData({ gap_sequences: [], corrections: [] })
render(<GuidancePanel data={data} {...defaultProps} />)
expect(screen.getByText(/All lyrics matched the reference/)).toBeInTheDocument()
})
it('dismisses tip and stores in localStorage', async () => {
const user = userEvent.setup()
render(<GuidancePanel data={makeMockData()} {...defaultProps} />)
const dismissButton = screen.getByLabelText('Dismiss tip')
await user.click(dismissButton)
expect(localStorageMock.setItem).toHaveBeenCalledWith('lyricsReviewGuidanceDismissed', 'true')
expect(screen.queryByText(/Synced Lyrics/)).not.toBeInTheDocument()
})
it('shows "Show tips" link after dismissal', async () => {
const user = userEvent.setup()
render(<GuidancePanel data={makeMockData()} {...defaultProps} />)
await user.click(screen.getByLabelText('Dismiss tip'))
expect(screen.getByText('Show tips')).toBeInTheDocument()
})
it('restores tip when "Show tips" is clicked', async () => {
const user = userEvent.setup()
render(<GuidancePanel data={makeMockData()} {...defaultProps} />)
await user.click(screen.getByLabelText('Dismiss tip'))
await user.click(screen.getByText('Show tips'))
expect(screen.getByText(/Synced Lyrics/)).toBeInTheDocument()
expect(localStorageMock.removeItem).toHaveBeenCalledWith('lyricsReviewGuidanceDismissed')
})
it('hides workflow tip in read-only mode', () => {
render(<GuidancePanel data={makeMockData()} {...defaultProps} isReadOnly={true} />)
expect(screen.queryByText(/Synced Lyrics/)).not.toBeInTheDocument()
})
it('stats are collapsed by default', () => {
render(<GuidancePanel data={makeMockData()} {...defaultProps} />)
expect(screen.getByText('Stats')).toBeInTheDocument()
// Stats content should not be visible
expect(screen.queryByText('Anchor Sequences')).not.toBeInTheDocument()
})
it('calls onStatsToggle when Stats button clicked', async () => {
const user = userEvent.setup()
render(<GuidancePanel data={makeMockData()} {...defaultProps} />)
await user.click(screen.getByText('Stats'))
expect(defaultProps.onStatsToggle).toHaveBeenCalled()
})
it('shows stats content when statsVisible is true', () => {
render(<GuidancePanel data={makeMockData()} {...defaultProps} statsVisible={true} />)
expect(screen.getByText('Anchor Sequences')).toBeInTheDocument()
expect(screen.getByText('Corrected Gaps')).toBeInTheDocument()
expect(screen.getByText('Uncorrected Gaps')).toBeInTheDocument()
})
it('calls metric click handler when color legend dot clicked', async () => {
const user = userEvent.setup()
render(<GuidancePanel data={makeMockData()} {...defaultProps} />)
await user.click(screen.getByText('Matched'))
expect(defaultProps.onMetricClick.anchor).toHaveBeenCalled()
await user.click(screen.getByText('Gaps (needs review)'))
expect(defaultProps.onMetricClick.uncorrected).toHaveBeenCalled()
await user.click(screen.getByText('Corrected'))
expect(defaultProps.onMetricClick.corrected).toHaveBeenCalled()
})
})
@@ -41,6 +41,8 @@ export interface HighlightedTextProps {
gaps?: GapSequence[]
flashingHandler?: string | null
corrections?: WordCorrection[]
// Gap navigation
activeGapWordIds?: Set<string>
// Review mode props for agentic corrections
reviewMode?: boolean
onRevertCorrection?: (wordId: string) => void
@@ -68,6 +70,7 @@ export function HighlightedText({
gaps = [],
flashingHandler,
corrections = [],
activeGapWordIds,
reviewMode = false,
onRevertCorrection,
onEditCorrection,
@@ -116,7 +119,14 @@ export function HighlightedText({
return Boolean(
(flashingType === 'anchor' && wordPos.type === 'anchor') ||
(flashingType === 'corrected' && isCorrected) ||
(flashingType === 'uncorrected' && wordPos.type === 'gap' && !isCorrected) ||
(flashingType === 'uncorrected' &&
wordPos.type === 'gap' &&
!isCorrected &&
// If highlightInfo specifies a gap, only flash that gap's words
(!highlightInfo?.sequence ||
(highlightInfo.sequence as GapSequence).transcribed_word_ids?.includes(
wordPos.word.id
))) ||
(flashingType === 'word' &&
((highlightInfo?.type === 'anchor' &&
wordPos.type === 'anchor' &&
@@ -202,6 +212,7 @@ export function HighlightedText({
onRevert={() => onRevertCorrection?.(wordPos.word.id)}
onEdit={() => onEditCorrection?.(wordPos.word.id)}
onAccept={() => onAcceptCorrection?.(wordPos.word.id)}
id={`word-${wordPos.word.id}`}
onClick={() => {
if (isMobile) {
onShowCorrectionDetail?.(wordPos.word.id)
@@ -230,6 +241,8 @@ export function HighlightedText({
isCorrectedGap={wordPos.isCorrected}
isUncorrectedGap={wordPos.type === 'gap' && !wordPos.isCorrected}
isCurrentlyPlaying={shouldHighlightWord(wordPos)}
isActiveGap={activeGapWordIds?.has(wordPos.word.id)}
id={`word-${wordPos.word.id}`}
onClick={() =>
handleWordClick(
wordPos.word.text,
@@ -299,6 +312,7 @@ export function HighlightedText({
onRevert={() => onRevertCorrection?.(word.id)}
onEdit={() => onEditCorrection?.(word.id)}
onAccept={() => onAcceptCorrection?.(word.id)}
id={`word-${word.id}`}
onClick={() => {
if (isMobile) {
onShowCorrectionDetail?.(word.id)
@@ -333,6 +347,8 @@ export function HighlightedText({
isCurrentlyPlaying={shouldHighlightWord(
wordPos || { word: word.text, id: word.id }
)}
isActiveGap={activeGapWordIds?.has(word.id)}
id={`word-${word.id}`}
onClick={() => handleWordClick(word.text, word.id, anchor, sequence)}
correction={correctionInfo}
/>
@@ -13,8 +13,10 @@ export const WordComponent = React.memo(function Word({
isCorrectedGap,
isUncorrectedGap,
isCurrentlyPlaying,
isActiveGap,
padding = 'px-[3px] py-[1px]',
onClick,
id,
correction,
}: WordProps) {
if (/^\s+$/.test(word)) {
@@ -34,11 +36,13 @@ export const WordComponent = React.memo(function Word({
const wordElement = (
<span
id={id}
className={cn(
'inline-block mr-[0.25em] transition-colors duration-200 cursor-pointer rounded-sm text-[0.85rem] leading-[1.2]',
padding,
bgColorClass,
shouldFlash && 'animate-lyrics-flash',
isActiveGap && 'ring-1 ring-yellow-400 dark:ring-yellow-300',
correction && 'underline decoration-dotted underline-offset-2 decoration-muted-foreground',
'hover:bg-foreground/[0.08]'
)}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff. Show more