Compare commits

..
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.6 b8a107228b Fix: persist is_private flag in job creation (#405)
@coderabbitai ignore

## Summary

- Fix bug where `is_private` was accepted by the API but not persisted
to Firestore
- The `job_manager.create_job()` method was missing
`is_private=job_create.is_private` when constructing the `Job` object

## Root cause

The `create_job` method in `job_manager.py` manually maps fields from
`JobCreate` to `Job`. The `is_private` field was added to both models in
PR #403 but was not added to this mapping, so all jobs were created with
`is_private=False` regardless of the request.

## Changes

- `backend/services/job_manager.py`: Add
`is_private=job_create.is_private` to `Job()` constructor
- `backend/tests/test_private_tracks.py`: Add 2 regression tests
verifying `create_job` persists `is_private`
- `pyproject.toml`: Bump version 0.119.0 → 0.119.1

## Test plan

- [x] New unit tests pass: `test_create_job_persists_is_private`,
`test_create_job_defaults_is_private_false`
- [x] All 25 private tracks tests pass
- [ ] After deploy: create private job via API, verify `is_private=True`
in Firestore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 13:51:13 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 374ce78951 Fix 402 error propagation for credit enforcement (#406)
## Summary

- Fix InsufficientCreditsError being swallowed by catch-all `except
Exception` blocks in route handlers
- Routes were converting 402 errors to 500 because the global exception
handler never saw them

## Root Cause

Route handlers like `search_audio()` wrap `create_job()` in `try/except
Exception` blocks that convert all exceptions to HTTP 500. Our
`InsufficientCreditsError` inherits from `Exception`, so it was caught
and converted before reaching the global
`@app.exception_handler(InsufficientCreditsError)`.

## Fix

Add explicit re-raise for `InsufficientCreditsError` and
`RateLimitExceededError` in all route handlers that call `create_job()`:
- `audio_search.py` - audio search endpoint
- `jobs.py` - direct job creation
- `file_upload.py` - file upload, upload URLs, URL import, finalise-only
(4 endpoints)

## Verified in Production

- Created test user → got 2 welcome credits (confirmed)
- Created job → credit deducted (confirmed)
- Zero credits → got 500 instead of 402 (this bug)
- After this fix → should return 402

## Test plan

- [x] All 13 credit enforcement tests pass
- [ ] Full CI suite
- [ ] Retest 402 in production after deploy

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 13:41:04 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 20453a877c Enforce credit system for karaoke video generation (#404)
## Summary

- Wire up the existing credits system to actually gate job creation -
previously, credits were tracked but never enforced
- Add credit check before job creation, atomic deduction after, and
auto-refund on job failure
- New users now receive 2 welcome credits (was 1)
- Frontend shows zero-credit warning banner, disables submit, and
handles 402 errors with "Buy Credits" link
- Clean up dead credit deduction code from auth_service

## Changes

**Backend:**
- `InsufficientCreditsError` exception with 402 handler
- Credit check + deduction in `JobManager.create_job()` (admin bypass,
atomic deduction, rollback on failure)
- Auto-refund in `JobManager.fail_job()` (skipped for admins,
error-isolated)
- Welcome credits bumped 1 → 2
- Removed dead credit deduction path from
`auth_service.increment_token_usage()`

**Frontend:**
- Zero-credit warning banner at top of job submission form
- Submit buttons disabled when credits = 0
- 402 error handling with "Buy Credits" link
- Boolean state `isCreditError` (not string matching) for credit error
display

**Tests:**
- 13 new backend unit tests covering enforcement, refunds, admin bypass,
atomicity
- 3 new Playwright E2E tests for frontend credit UX
- Tests for 402 exception handler and auth_service cleanup

## Test plan

- [x] Backend unit tests: `pytest tests/test_credit_enforcement.py -v`
(13 tests)
- [x] 402 handler test in `test_main.py`
- [x] Auth service test in `test_auth_firestore.py`
- [x] Frontend E2E tests: `npx playwright test
e2e/regression/credit-enforcement.spec.ts`
- [x] Full suite: `make test` (1928 tests passed)
- [ ] Manual: Create test user with 0 credits → verify 402
- [ ] Manual: Create test user with 1 credit → verify deduction
- [ ] Manual: Fail a job → verify credit refund

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 01:00:06 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 fa9bc8eeeb Add private (non-published) tracks option (#403)
@coderabbitai ignore

## Summary

- Add `is_private` flag to jobs that changes distribution behavior for
non-published tracks
- Private jobs upload to Dropbox `Tracks-NonPublished` folder with
`NOMADNP` brand prefix
- Private jobs skip YouTube and Google Drive uploads entirely
- Completion emails omit YouTube section for private jobs
- Available to all users at job creation; admin can toggle on existing
jobs
- When admin toggles completed job to private, existing outputs are
auto-deleted

## Changes

### Backend
- **Job model**: Added `is_private: bool = False` to `Job` and
`JobCreate`
- **Config**: Added `DEFAULT_PRIVATE_DROPBOX_PATH` and
`DEFAULT_PRIVATE_BRAND_PREFIX` settings
- **Distribution helper**: New `get_effective_distribution_for_job()` in
`job_defaults_service.py` applies private overrides at runtime
- **Orchestrator + native paths**: Both distribution code paths use the
helper (per "Fix Both Sides" lesson)
- **Email template**: YouTube section conditionally removed when
`is_private=True`
- **Credential pre-validation**: Skip YouTube/GDrive credential checks
for private jobs
- **API endpoints**: All 4 job creation endpoints accept `is_private`;
admin can PATCH it
- **Admin auto-delete**: Toggling completed job to private triggers
output deletion

### Frontend
- **Job creation form**: "Private (Non-Published)" checkbox on all 3
tabs (upload, URL, search)
- **Admin dashboard**: Private toggle in job configuration section
- **API interfaces**: Updated TypeScript interfaces and API methods

### Tests
- 23 unit tests covering model, distribution overrides, email template,
notification service, request models, admin toggle, and orchestrator
config
- Fixed MagicMock truthiness issue in existing tests

## Test plan

- [x] All 23 private tracks tests pass
- [x] All 1794 existing backend tests pass (1 flaky unrelated test)
- [x] CodeRabbit review: credential pre-validation issue found and fixed
- [ ] Manual: Create private job end-to-end, verify Dropbox folder
- [ ] Manual: Verify completion email has Dropbox link but no YouTube
section
- [ ] Manual: Admin toggle on completed job deletes outputs

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 18:07:57 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 0cee5b8ae3 feat: add beveradb/cryptotrader to WIF and SA IAM binding (#402)
## Summary
- Add `beveradb` org to Workload Identity Federation provider attribute
condition
- Add `beveradb/cryptotrader` repo to the service account IAM binding
for `roles/iam.workloadIdentityUser`
- Syncs Pulumi IaC with GCP drift (changes already applied in GCP)

## Test plan
- [ ] `pulumi preview` shows no drift after merge
- [ ] GitHub Actions from beveradb/cryptotrader can authenticate to GCP

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 19:20:38 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 9726192de0 fix: persist uploaded audio, fix custom instrumental selection (#401)
## Summary
- **Uploaded audio persistence**: Files uploaded to `uploads/` are
auto-deleted by a 7-day GCS lifecycle rule. After processing, copies are
now saved to `jobs/{job_id}/input/` (mirroring URL job behavior) so
review playback works indefinitely.
- **Defensive cache fallback**: When the transcoding service can't find
the source file, it now checks for an existing OGG cache from earlier
eager transcoding before falling back to FLAC.
- **Custom instrumental selection**: The review completion endpoint
rejected `"custom"` instrumental selection for mute-region edits because
it only checked for an uploaded instrumental file. Now also checks for
the `custom_instrumental` stem created by the mute-region editor.
- **Video worker custom stem**: When `"custom"` is selected and there's
no uploaded instrumental, the video worker now downloads the
`custom_instrumental` stem instead of incorrectly falling through to
`instrumental_with_backing`.

## Test plan
- [x] Unit tests for upload persistence (happy path, no-op for jobs/
prefix, JobManager fallback, persistence failure doesn't block download)
- [x] Unit tests for defensive cache fallback (cache exists when source
deleted, file_exists throws in fallback)
- [x] Unit tests for custom instrumental validation (allowed with stem,
allowed with upload, rejected without either)
- [x] Tightened existing test assertions for new code paths
- [x] All 30 new/modified tests passing

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 02:43:11 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 d22f1893f8 fix: add missing create-custom-instrumental endpoint and prevent oversized Firestore docs (#400)
## Summary
- Add missing `POST /api/jobs/{id}/create-custom-instrumental` endpoint
that was lost during the unified review UI migration. The endpoint
creates a custom instrumental by muting selected backing vocal regions
and returns a signed audio URL for playback.
- Strip `reference_lyrics` from corrections data before saving to
Firestore `state_data`, preventing 1MB document size limit errors when
Genius fetches non-lyrics content (e.g. screenplays). Full data is
preserved in GCS.
- Update frontend `InstrumentalSelector` to use the signed audio URL
returned from the create endpoint instead of a non-existent stream
endpoint.

## Test plan
- [x] 11 new backend tests covering both fixes (happy path, auth,
validation, error handling, Firestore stripping, GCS preservation)
- [x] Full test suite passes (1912 backend, 168 frontend)
- [ ] Manual test: create custom instrumental on a job in review
- [ ] Manual test: submit corrections for a job with oversized Genius
lyrics

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 01:25:02 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 1a56ae09c5 feat: change default jobs list filter from 5 to 10 (#399)
## Summary
- Change the default job display limit from 5 to 10 for new users (or
users who haven't customized the setting)
- Users with a saved preference in localStorage are unaffected

## Test plan
- [x] Frontend unit tests pass (323/323)
- [x] Backend unit tests pass (1920/1920)
- [ ] Verify in production: new/incognito browser shows 10 jobs by
default

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 11:19:38 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 f29fa8b5cd fix: filter exclude_statuses in Python for hide_completed (#398)
## Summary
- Fix `hide_completed=true` query param failing with Firestore composite
index error
- Move `exclude_statuses` filtering from Firestore `not-in` to
Python-side filtering
- Documents are tiny after `select()` projection, so Python filtering is
fast

## Context
Follow-up to #397. The `not-in` filter on `status` combined with
`order_by(created_at)` requires a composite index that doesn't exist.
This moves the filtering to Python after the projected query returns.

## Test plan
- [x] All 33 backend route tests pass
- [ ] Verify `hide_completed=true` works in production (no Firestore
index error)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 09:32:34 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 3ea48e487f feat: server-side jobs filtering with field projection (#397)
## Summary
- Add `fields=summary` query param to `GET /api/jobs` — uses Firestore
`select()` to return only ~12 dashboard-required fields instead of 50+
full Job fields, reducing payload from ~16MB to <500KB
- Add `hide_completed=true` query param for server-side filtering of
terminal statuses (complete, prep_complete, failed, cancelled)
- Safety-net prune helpers strip extra keys from `state_data` and
`file_urls` nested dicts
- Backward compatible: without `fields=summary`, endpoint returns full
`List[Job]` as before (admin pages unaffected)

## Test plan
- [x] 8 backend unit tests covering prune helpers, hide_completed,
exclude_test with dicts, backward compatibility
- [x] 5 frontend Jest tests covering query param serialization and
partial summary response handling
- [x] All 2412 existing tests pass (`make test`)
- [ ] Deploy to staging, verify network tab shows reduced payload size
- [ ] Verify JobCard renders correctly with summary data (title, status,
progress, download links, error)
- [ ] Toggle hide-completed — verify server re-fetch with
`hide_completed=true`
- [ ] Verify admin jobs page (`/admin/jobs`) still works (doesn't send
`fields=summary`)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 09:06:23 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 4fe960481b feat: show all incomplete jobs first + hide-completed toggle (#393)
## Summary
- **Priority sorting**: Blocking + processing jobs always appear first
in Recent Jobs, regardless of creation date
- **Hide completed toggle**: Eye/EyeOff button filters out completed and
failed jobs, showing only incomplete ones
- **Persistent preferences**: Both the display limit dropdown and
hide-completed toggle persist in localStorage across page reloads
- **Oversized lyrics truncation fix**: Corrected screen generation for
songs with unusually long lyric lines

## Changes
- `frontend/lib/job-status.ts`: Added `hideCompleted` parameter to
`getDisplayJobs()` — filters by job priority before applying display
limit
- `frontend/app/app/page.tsx`: Added Eye/EyeOff toggle with tooltip,
localStorage persistence for both `jobLimit` and `hideCompleted`
- `frontend/__tests__/job-status.test.ts`: 5 new tests covering
hideCompleted filtering behavior

## Test plan
- [x] All 168 tests pass (`make test`)
- [x] 85 job-status unit tests pass including 5 new hideCompleted tests
- [ ] Visual verification: toggle button appears next to limit dropdown,
state persists on reload

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 16:22:37 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 fe51369d30 Fix test infrastructure: timeouts, IPv6 hang, and 21 stale E2E tests (#396)
## Summary
- Fix `make test` hanging indefinitely by adding Makefile timeouts and
resolving Playwright IPv6 binding issue
- Update 21 stale Playwright E2E regression tests to match current UI
(buttons renamed, auth mock structure, navigation flow changes)
- Remove dead code: unused admin endpoints, audio transcoding service,
screens worker clear functionality

## Changes

### Test Infrastructure
- **Makefile**: Added 10-min timeout for backend tests, 15-min for
frontend, with proper cleanup on failure
- **Playwright config**: Force IPv4 binding (`127.0.0.1:3000`) to
prevent IPv6 connection hang on macOS

### E2E Test Fixes (21 tests across 4 files)
- **admin-job-detail.spec.ts**: Updated toolbar button selectors
(`Start`→`Audio`, `Lyrics`→`Review`), removed 3 obsolete Clear Workers
tests
- **cloud-mode-review.spec.ts**: Fixed auth mock to match
`UserProfileResponse` nested structure (`{user: {...}, has_session:
true}`), added instrumental-analysis and waveform-data mocks
- **combined-review-corrections.spec.ts**: Fixed auth mock structure,
string path for mock routes, missing auth token parameter
- **lyrics-review.spec.ts**: Updated button text (`Complete
Review`→`Proceed to Instrumental Review`), added `.first()` for
multi-element label selectors, rewrote submit tests to verify navigation
behavior

### Component/Library Fixes
- **TimeInput.tsx**: Added `htmlFor`/`id` association for accessibility
and Playwright `getByLabel()` support
- **local-mode.ts**: Broadened hash check (`hash.startsWith('#/')`) so
invalid hash routes correctly detect cloud mode

### Dead Code Removal
- Removed unused `clear_workers` admin endpoint and related worker code
- Removed unused `audio_transcoding_service.py` and its 353-line test
file

## Testing
- [x] All 168 Playwright tests pass (3 intentionally skipped)
- [x] All backend tests pass
- [x] `make test` completes end-to-end without hanging
- [x] CI passed

## Review
- [x] CodeRabbit CLI review completed locally - clean pass

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 15:19:14 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 0cecc86b79 feat: eager audio transcoding for review UI (#395)
## Summary
- Add `AudioTranscodingService` that transcodes FLAC audio to OGG Opus
128kbps (~3 MB vs 35+ MB), cached in GCS at `review-audio/*.ogg`
- Eager transcoding in `screens_worker` before `AWAITING_REVIEW` so
files are cached before the user opens the review UI
- All 3 review audio paths (`_stream_audio`, `get_correction_data`,
`get_instrumental_analysis`) now serve transcoded OGG URLs with FLAC
fallback
- Admin endpoint `POST /admin/jobs/{job_id}/prepare-review-audio` for
backfilling existing jobs

## Test plan
- [x] 21 unit tests at 100% coverage on `AudioTranscodingService`
- [x] 229 existing review tests pass with 0 regressions
- [ ] Deploy and use admin endpoint to backfill job `4bed6f80`
- [ ] Open review UI — verify audio loads fast, Network tab shows ~3 MB
OGG
- [ ] Check GCS for cached files at `jobs/4bed6f80/review-audio/*.ogg`

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 13:24:59 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 87e696556d fix: use signed URL redirect for review audio to bypass 32 MiB limit (#394)
## Summary
- Review audio endpoint was proxying files through Cloud Run via
`FileResponse`, hitting the Google Frontend load balancer's 32 MiB
response body size limit
- Files >32 MiB (like the 35 MiB FLAC for job `4bed6f80`) caused 500
errors — app logged 200 internally but LB rejected the response
- Switched to a 302 redirect to a GCS signed URL, matching the pattern
already used for instrumental stems in the same file

## Test plan
- [x] All 28 review route tests pass
- [ ] Verify audio loads in review UI:
https://gen.nomadkaraoke.com/app/jobs/#/4bed6f80/review

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 22:37:37 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 7ac0e07c95 fix: migrate AudioShake from legacy /upload/ to /assets endpoint (#392)
@coderabbitai ignore

## Summary
- AudioShake removed their legacy `/upload/` endpoint, causing all jobs
to fail with `401 Unauthorized`
- Migrated to the new Assets API (`POST /assets`) which returns an
`assetId`
- Updated task creation to use `assetId` instead of `url` per new API
contract

## Test plan
- [x] Verified new `/assets` endpoint works with existing API token
(returns 200 + asset ID)
- [x] Backend unit tests pass (1081 passed, 8 skipped)
- [ ] CI will run full test suite
- [ ] After merge, verify jobs complete lyrics transcription
successfully in production

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 14:26:56 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 6f08a684d1 fix: close audio search dialog immediately after selection (#390)
## Summary
- The `/api/audio-search/{job_id}/select` endpoint was downloading audio
synchronously before returning, keeping the dialog open for 10-60+
seconds
- Refactored into `_validate_and_prepare_selection()` (returns
instantly) and `_download_audio_and_trigger_workers()` (runs as FastAPI
background task)
- Dialog now closes immediately; download proceeds in background with
job status updates visible in the job card

## Test plan
- [x] All 57 backend tests pass (6 new tests added for the refactored
functions)
- [x] Error paths tested: invalid index, job not found, no results,
download failures
- [x] Background task gracefully handles missing jobs and generic
exceptions
- [x] Worker triggering verified after successful download
- [ ] Manual: select audio in popup, verify it closes immediately and
job transitions to "Downloading audio..."

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 12:00:16 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 2f15cfc985 feat(lyrics-review): Add Replace Segment Lyrics mode (#389)
## Summary

- Adds a third mode ("Replace Segment Lyrics") to the Edit All Lyrics
modal, enabling users to swap custom lyrics line-by-line while
preserving existing segment timing
- Extracts `createWordsWithDistributedTiming` shared utility from
EditModal for reuse
- Fixes Makefile `build-frontend` to clean stale output before copying
(was causing old JS chunks to persist)
- Restores accidentally deleted `nextjs_frontend/__init__.py`

## Test plan

- [x] Unit tests for `createWordsWithDistributedTiming` (8 cases)
- [x] Component tests for Replace Segments mode (17 cases)
- [x] E2E Playwright tests (8 cases) 
- [x] All 306 Jest tests pass
- [x] Manual local testing with real audio file via `karaoke-gen` CLI

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 15:39:22 -05:00
Andrew Beveridge ☄️andClaude Sonnet 4.5 9cca4db147 fix(lyrics-review): Enable and improve mode selector buttons (#388)
## Summary
- Fixed non-functional highlight and delete mode buttons in lyrics
review
- Improved mode selector UX with better spacing, icons, and active state
visibility
- Added test infrastructure support for Radix UI components

## Changes
- **ModeSelector.tsx**: Removed `disabled` attributes and fixed onChange
handler to support all modes
- **ModeSelector.tsx**: Enhanced visual design with proper active states
(blue background on selected mode)
- **ModeSelector.tsx**: Improved spacing consistency and changed Edit
icon to Pencil for better visual balance
- **ModeSelector.test.tsx**: Added comprehensive unit tests (100%
coverage)
- **jest.setup.js**: Added ResizeObserver mock for Radix UI ToggleGroup
component
- **pyproject.toml**: Bumped version to 0.116.3

## Testing
- [x] All tests pass (281 frontend + 103 backend tests)
- [x] Unit test coverage: 100% on ModeSelector component
- [x] Manual testing completed via Chrome DevTools MCP
- [x] E2E regression tests pass (existing lyrics review tests)

## Review
- [x] Manual code review completed (CodeRabbit CLI couldn't run due to
447 built files)
- [x] No security, bug, or quality issues found
- [x] Documentation reviewed (no updates needed)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-11 21:41:49 -05:00
Andrew Beveridge ☄️andClaude Sonnet 4.5 1852df9273 fix(gce-encoding): Fix wheel version sorting regression (0.99.9 > 0.116.1) (#387)
## Summary

Critical regression fix from PR #384: Production encoder was running
v0.99.9 instead of v0.116.1 due to alphabetical sorting instead of
semantic version comparison.

**Impact:** GCE encoding worker was using an extremely old version
(0.99.9 from months ago) instead of the latest release (0.116.1),
potentially causing encoding issues or missing recent bug fixes.

## Root Cause

PR #384 fixed invalid wheel filtering but exposed a latent version
sorting bug:
- `sorted(wheels)[-1]` uses string comparison, not semantic versioning
- String comparison: `"0.99.9"` > `"0.116.1"` (because '9' > '1' in
position 2)
- Result: Old version selected over new version

## Changes

**Code (14 lines):**
- Added imports: `re`, `packaging.version.Version`
- Implemented `extract_version()` helper to parse version from filename
- Changed sorting from `sorted(wheels)[-1]` to semantic version sort
- **File:** `backend/services/gce_encoding/main.py`

**Tests (159 lines, 10 new tests):**
- Test exact regression case (0.99.9 vs 0.116.1)
- Demonstrate alphabetical sorting failure
- Test version extraction and edge cases
- Test complex version comparisons (major/minor/patch)
- **File:** `backend/tests/test_gce_encoding_worker.py`

**Documentation:**
- Updated `docs/README.md` with Recent Changes entry
- Added lesson to `docs/LESSONS-LEARNED.md` about semantic version
sorting
- Pattern documented for future reference

**Version:**
- Bumped to v0.116.2 (patch release for bug fix)

## Testing

- [x] All tests pass (24 total, 10 new)
- [x] Test-to-code ratio: 11.4:1
- [x] Edge cases covered (empty list, invalid filenames, complex
versions)
- [x] CodeRabbit review: 0 issues found

## Review

- [x] Local CodeRabbit CLI review completed
- [x] Documentation updated
- [x] All tests passing

@coderabbitai ignore

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

---------

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-11 12:38:44 -05:00
Andrew Beveridge ☄️ 30e55a0031 docs: Add GCP cost optimization analysis (#386)
Comprehensive cost analysis document covering:

- Current spend breakdown (~k/month) 
- Implemented GitHub runner auto-scaling (,390/month saved)
- Additional optimization opportunities (Cloud Run, encoding worker)
- Actionable next steps

Document URL will be: `docs/GCP-COST-OPTIMIZATION.md`

<!-- @coderabbitai ignore -->
2026-02-11 17:28:55 +00:00
Andrew Beveridge ☄️andClaude Sonnet 4.5 8b88f43a96 fix(gce-encoding): Fix wheel installation crash by filtering invalid filenames (#384)
## Summary

Fixes GCE encoding worker crash caused by attempting to install
`karaoke_gen-current.whl`, which is not a valid PEP 427 wheel filename.

## Problem

Job 749141f8 failed with "Cannot connect to host" errors. Investigation
revealed:
- GCE encoding worker was crashing and restarting
- Root cause: pip rejected `karaoke_gen-current.whl` with "Invalid wheel
filename (wrong number of parts)"
- The `ensure_latest_wheel()` function downloaded ALL wheels including
the `-current` convenience file
- This file lacks required PEP 427 naming (version, python, abi,
platform tags)

## Solution

Filter out wheels containing '-current' before selecting which to
install:
```python
wheels = glob.glob("/tmp/karaoke_gen-*.whl")
# Filter out karaoke_gen-current.whl (not a valid PEP 427 wheel name)
wheels = [w for w in wheels if '-current' not in w]
```

## Changes

- **Fix** (`backend/services/gce_encoding/main.py`): Add 3-line filter
for valid wheel names
- **Tests** (`backend/tests/test_gce_encoding_worker.py`): Add 5
comprehensive unit tests
  - Current wheel exclusion
  - Empty result handling
  - Version sorting after filtering
  - Pass-through when no current wheel
  - Path-agnostic filtering
- **Docs** (`docs/README.md`): Add to Recent Changes
- **Docs** (`docs/LESSONS-LEARNED.md`): Add pip wheel filename
validation lesson
- **Version**: Bump to 0.116.1 (patch release)

## Testing

- ✅ All 14 GCE encoding worker tests pass (9 existing + 5 new)
- ✅ Backend tests pass
- ✅ Test-to-code ratio: 26:1 (78 test lines for 3 code lines)
- ✅ Tests cover all edge cases and are isolated/fast
- ⚠️ Frontend E2E tests have pre-existing failures (unrelated to backend
changes)

## Review

- ✅ CodeRabbit CLI review completed locally (zero issues found)
- ✅ Code follows project conventions
- ✅ Comprehensive test coverage
- ✅ Documentation updated

## Impact

- Fixes job 749141f8 and prevents future encoding failures
- No breaking changes
- No API changes
- Production-critical bug fix

@coderabbitai ignore

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

---------

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 16:48:25 -05:00
Andrew Beveridge ☄️ f313fc4208 fix(infra): Update runner manager memory to 512M in config (#385)
Aligns code with deployed infrastructure. Function was seeing OOM with
256M.

<!-- @coderabbitai ignore -->
2026-02-10 16:41:24 -05:00
Andrew Beveridge ☄️ 15d5ed8db1 chore(infra): Trigger deployment for runner autoscaling (#383)
Trigger infrastructure deployment with Cloud Functions admin permission
fixed.

<!-- @coderabbitai ignore -->
2026-02-10 20:52:58 +00:00
528 changed files with 8446 additions and 1402 deletions

No files matched your search

+279
View File
@@ -0,0 +1,279 @@
# Plan: Private (Non-Published) Tracks
**Created:** 2026-02-24
**Branch:** feat/sess-20260224-1149-private-tracks
**Status:** Implemented
## Overview
Add a `is_private` flag to jobs that changes distribution behavior:
- **Dropbox**: Uses `Tracks-NonPublished` folder (not `Tracks-Organized`) with brand code `NOMADNP` (not `NOMAD`)
- **YouTube**: Skipped entirely
- **Google Drive**: Skipped entirely
- **Email**: Completion email includes Dropbox link but no YouTube section
- **Discord**: Still notified (for internal tracking)
Available to all users at job creation and toggleable by admin on existing jobs.
## Requirements
- [ ] All users can mark a job as "Private (Non-Published)" when creating it
- [ ] Admin can toggle `is_private` on any existing job via admin dashboard
- [ ] Private jobs upload to Dropbox at `Tracks-NonPublished` with `NOMADNP-XXXX` brand codes
- [ ] Private jobs skip YouTube and Google Drive uploads entirely
- [ ] Completion emails omit YouTube section when no YouTube URL (private jobs + any other edge case)
- [ ] When admin toggles a completed job to private, existing outputs are auto-deleted
- [ ] Discord notifications still fire for private jobs
- [ ] Existing (non-private) jobs are completely unaffected (backward compatible)
## Technical Approach
### Core Design: Single Boolean Flag with Runtime Overrides
Store `is_private: bool = False` on the job model. At distribution time, a helper function returns effective distribution parameters based on this flag. This means:
- **Toggling is_private automatically changes all distribution behavior** - no need to manually update dropbox_path, brand_prefix, enable_youtube_upload, gdrive_folder_id
- **Job fields still store the "normal" defaults** - the override happens at the config-to-orchestrator boundary
- **Admin can flip one field** and everything adapts
### Key Helper Function
```python
# In job_defaults_service.py
def get_effective_distribution_for_job(job) -> EffectiveDistributionSettings:
"""Return distribution settings, applying private overrides if is_private=True."""
if getattr(job, 'is_private', False):
settings = get_settings()
return EffectiveDistributionSettings(
dropbox_path=settings.default_private_dropbox_path,
brand_prefix=settings.default_private_brand_prefix,
enable_youtube_upload=False,
gdrive_folder_id=None,
# Keep other settings from job (discord, youtube_description, etc.)
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
youtube_description=None,
)
# Non-private: return job's own settings
return EffectiveDistributionSettings(
dropbox_path=getattr(job, 'dropbox_path', None),
brand_prefix=getattr(job, 'brand_prefix', None),
enable_youtube_upload=getattr(job, 'enable_youtube_upload', False),
gdrive_folder_id=getattr(job, 'gdrive_folder_id', None),
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
youtube_description=getattr(job, 'youtube_description_template', None),
)
```
This helper is used in both distribution paths (orchestrator and native fallback).
### Distribution Paths That Need Changes
Two code paths handle distribution (see LESSONS-LEARNED: "Fix Both Sides of Dual Code Paths"):
1. **Orchestrator path** (`video_worker_orchestrator.py`): Primary path. `create_orchestrator_config_from_job()` uses the helper to build config.
2. **Native distribution path** (`video_worker.py` → `_handle_native_distribution()`): Fallback path. Also uses the helper instead of reading job fields directly.
### Email Template Change
Add conditional YouTube section removal in `render_template()`, matching the existing pattern for `feedback_url`:
```python
# Remove YouTube section if no URL provided
if not variables.get("youtube_url"):
result = re.sub(
r"\n*Here's the link for the karaoke video published to YouTube:\n\{youtube_url\}\n*",
'\n',
result,
flags=re.DOTALL
)
variables["youtube_url"] = ""
```
And change `render_job_completion()` to pass `None` instead of `"[YouTube URL not available]"` when youtube_url is empty.
### Admin Toggle Auto-Delete
When admin PATCH updates `is_private` from False to True on a job that has existing outputs, reuse the existing delete-outputs logic to remove YouTube + GDrive + Dropbox outputs. Admin can then "Reprocess" to re-distribute to the private Dropbox path.
## Implementation Steps
### Phase 1: Backend Model & Config (foundation)
1. [ ] **Add `is_private` to Job model** (`backend/models/job.py`)
- Add `is_private: bool = False` field after `made_for_you` field
- Add to `JobCreate` model as well
2. [ ] **Add private distribution config** (`backend/config.py`)
- Add `default_private_dropbox_path: Optional[str] = os.getenv("DEFAULT_PRIVATE_DROPBOX_PATH")`
- Add `default_private_brand_prefix: Optional[str] = os.getenv("DEFAULT_PRIVATE_BRAND_PREFIX", "NOMADNP")`
3. [ ] **Add helper function** (`backend/services/job_defaults_service.py`)
- Add `get_effective_distribution_for_job(job)` function that returns distribution settings with private overrides applied
### Phase 2: Backend API (job creation + admin)
4. [ ] **Add `is_private` to request models** (`backend/models/requests.py`)
- Add `is_private: Optional[bool] = None` to `URLSubmissionRequest`
- Add `is_private: Optional[bool] = None` to `AudioSearchRequest`
5. [ ] **Update URL creation endpoint** (`backend/api/routes/jobs.py`)
- Accept and pass through `is_private` field to `JobCreate`
6. [ ] **Update file upload endpoint** (`backend/api/routes/file_upload.py`)
- Accept `is_private` Form parameter
- Pass through to `JobCreate`
7. [ ] **Update audio search endpoint** (`backend/api/routes/audio_search.py`)
- Accept `is_private` in `AudioSearchRequest`
- Pass through to `JobCreate`
8. [ ] **Update admin endpoints** (`backend/api/routes/admin.py`)
- Add `is_private: Optional[bool] = None` to `JobUpdateRequest`
- Add `"is_private"` to `EDITABLE_JOB_FIELDS`
- In the PATCH handler: detect when `is_private` changes from False→True on a completed job, auto-delete existing outputs (call existing delete-outputs service logic)
### Phase 3: Distribution Pipeline
9. [ ] **Update orchestrator config creation** (`backend/workers/video_worker_orchestrator.py`)
- In `create_orchestrator_config_from_job()`: Use `get_effective_distribution_for_job()` helper to determine dropbox_path, brand_prefix, enable_youtube_upload, gdrive_folder_id instead of reading directly from job
10. [ ] **Update native distribution fallback** (`backend/workers/video_worker.py`)
- In `_handle_native_distribution()`: Use `get_effective_distribution_for_job()` helper instead of reading directly from job fields
### Phase 4: Email Template
11. [ ] **Add YouTube section conditional removal** (`backend/services/template_service.py`)
- In `render_template()`: Add regex to remove YouTube paragraph when `youtube_url` is empty (matching existing `feedback_url` pattern)
- In `render_job_completion()`: Pass `None` for youtube_url when empty (instead of `"[YouTube URL not available]"`)
### Phase 5: Frontend
12. [ ] **Add private checkbox to job creation form** (`frontend/components/job/JobSubmission.tsx`)
- Add "Private (Non-Published)" checkbox below the existing "Skip lyrics review" checkbox
- Show for all users (not just admin)
- Include brief description text: "Private tracks go to Dropbox only, not YouTube or Google Drive"
13. [ ] **Update API interfaces** (`frontend/lib/api.ts`)
- Add `is_private?: boolean` to all job creation option interfaces
- Add `is_private` to `JobUpdateRequest` interface
- Pass through in `uploadJob()`, `createJobFromUrl()`, `searchAudio()` methods
14. [ ] **Add private toggle to admin job detail** (`frontend/app/admin/jobs/page.tsx`)
- Add `is_private` as an inline-editable field in the job overview section (use Switch component)
- Show current state with visual indicator (e.g., lock icon for private jobs)
- When toggling to private on a completed job, show confirmation dialog about auto-deleting outputs
### Phase 6: Environment Configuration
15. [ ] **Update CI/deployment config** (`.github/workflows/ci.yml` or Cloud Run env)
- Add `DEFAULT_PRIVATE_DROPBOX_PATH` environment variable (e.g., `/Karaoke/Tracks-NonPublished`)
- Add `DEFAULT_PRIVATE_BRAND_PREFIX` environment variable (e.g., `NOMADNP`)
- These should be configured in Cloud Run service and CI test environment
### Phase 7: Testing
16. [ ] **Unit tests for private distribution logic** (`backend/tests/test_private_tracks.py`)
- Test `get_effective_distribution_for_job()` with private and non-private jobs
- Test `create_orchestrator_config_from_job()` applies private overrides correctly
- Test `_run_distribution()` skips YouTube and GDrive when private config applied
- Test `_upload_to_dropbox()` uses private path and brand prefix
- Test brand code generation with NOMADNP prefix in Tracks-NonPublished
- Test `_handle_native_distribution()` respects private overrides
- Test non-private jobs are completely unaffected (regression tests)
17. [ ] **Unit tests for email changes** (add to `backend/tests/test_email_service.py` or `test_template_service.py`)
- Test YouTube section removed from email when youtube_url is None
- Test YouTube section present when youtube_url is provided
- Test Dropbox section still present for private jobs
- Test full email rendering for private job scenario
18. [ ] **Unit tests for admin toggle** (add to `backend/tests/test_admin.py` or new file)
- Test admin can update is_private field
- Test toggling is_private to True on completed job triggers output deletion
- Test toggling is_private to True on non-completed job does NOT delete outputs
- Test toggling is_private to False does nothing special
19. [ ] **Integration test** (`backend/tests/emulator/` or `test_distribution_services.py`)
- Test full distribution pipeline with is_private=True: verify Dropbox path, brand prefix, YouTube skip, GDrive skip
20. [ ] **Frontend E2E regression test** (`frontend/e2e/regression/`)
- Test private checkbox appears in job creation form
- Test private toggle in admin dashboard
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `backend/models/job.py` | Modify | Add `is_private: bool = False` to Job and JobCreate |
| `backend/config.py` | Modify | Add `default_private_dropbox_path` and `default_private_brand_prefix` |
| `backend/services/job_defaults_service.py` | Modify | Add `get_effective_distribution_for_job()` helper |
| `backend/models/requests.py` | Modify | Add `is_private` to URL and AudioSearch request models |
| `backend/api/routes/jobs.py` | Modify | Accept and pass `is_private` |
| `backend/api/routes/file_upload.py` | Modify | Accept and pass `is_private` |
| `backend/api/routes/audio_search.py` | Modify | Accept and pass `is_private` |
| `backend/api/routes/admin.py` | Modify | Add `is_private` to editable fields + auto-delete logic |
| `backend/workers/video_worker_orchestrator.py` | Modify | Use helper in `create_orchestrator_config_from_job()` |
| `backend/workers/video_worker.py` | Modify | Use helper in `_handle_native_distribution()` |
| `backend/services/template_service.py` | Modify | Conditional YouTube section removal |
| `frontend/components/job/JobSubmission.tsx` | Modify | Add private checkbox |
| `frontend/lib/api.ts` | Modify | Add `is_private` to interfaces and API calls |
| `frontend/app/admin/jobs/page.tsx` | Modify | Add private toggle to admin detail |
| `backend/tests/test_private_tracks.py` | Create | Comprehensive unit tests for private track logic |
## Testing Strategy
### Unit Tests (~25-30 tests in `test_private_tracks.py`)
- `get_effective_distribution_for_job()` with private=True and False
- `create_orchestrator_config_from_job()` private overrides (YouTube=False, GDrive=None, private Dropbox path, NOMADNP brand)
- Distribution stage skips: YouTube not called, GDrive not called, Dropbox IS called with correct path
- Brand code generation uses NOMADNP prefix and Tracks-NonPublished path
- Native distribution fallback applies same overrides
- **Regression tests**: Non-private jobs have unchanged behavior (same paths, same brand code, YouTube+GDrive+Dropbox all fire)
### Email Template Tests (~5 tests)
- YouTube section stripped when youtube_url is None
- YouTube section preserved when youtube_url has value
- Dropbox section always present
- Full private job email rendering (Dropbox + no YouTube)
- Full non-private job email rendering (both present) - regression
### Admin Toggle Tests (~5 tests)
- is_private editable via PATCH
- Toggle to private on completed job deletes outputs
- Toggle to private on pending/in-progress job does NOT delete
- Toggle to non-private does nothing special
### Frontend Tests
- E2E: Private checkbox visible and functional in job creation
- E2E: Admin toggle visible and includes confirmation dialog
### Manual Verification
- Create a private job end-to-end, verify Dropbox folder in Tracks-NonPublished with NOMADNP code
- Verify completion email has Dropbox link but no YouTube section
- Toggle existing completed job to private, verify outputs deleted
## Regression Risk Analysis
| Risk | Mitigation |
|------|-----------|
| Non-private jobs affected | `is_private` defaults to `False`; helper returns unchanged values for non-private. Explicit regression tests. |
| Dual code paths (orchestrator vs native) | Both paths use same helper function. Tests cover both paths. (Lesson: "Fix Both Sides of Dual Code Paths") |
| Email template regex breaks other content | Regex targets specific YouTube paragraph text. Tests verify non-YouTube content untouched. |
| Brand code namespace collision | NOMADNP codes are in a completely separate Dropbox folder (Tracks-NonPublished), no overlap with NOMAD codes in Tracks-Organized |
| Admin auto-delete on wrong job | Only triggers when `is_private` changes from False→True AND job has terminal status (complete). Confirmation dialog in frontend. |
| Made-for-you orders | MFY webhook doesn't set is_private (defaults False). Admin can toggle after. No change to MFY flow. |
| Existing Firestore documents | Missing `is_private` field defaults to `False` via model default. No migration needed. |
## Open Questions
- [x] Who sees private toggle? → **Everyone** (all users at creation, admin on existing)
- [x] Auto-delete on toggle? → **Yes**, auto-delete all outputs when toggling to private on completed job
- [x] Email format? → **Remove YouTube section** when no YouTube URL (improves all edge cases)
- [x] Discord? → **Still notify** (useful for internal tracking)
## Rollback Plan
1. **Feature flag**: The `is_private` field defaults to `False`, so setting `DEFAULT_PRIVATE_DROPBOX_PATH` to empty/None effectively disables private distribution
2. **No schema migration needed**: Missing `is_private` field on existing Firestore documents defaults to `False`
3. **Email change is backward-compatible**: The YouTube section removal only happens when youtube_url is None, which is already an edge case showing "[YouTube URL not available]"
4. **Frontend**: Private checkbox is additive UI, removing it just means users can't create new private jobs
+1 -1
View File
@@ -1242,7 +1242,7 @@ jobs:
--min-instances 4 \
--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,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true" \
--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"
- name: Verify deployment and version
+25 -8
View File
@@ -1,7 +1,12 @@
# Makefile for karaoke-gen project
# Run `make help` to see available commands
.PHONY: help install install-backend install-frontend build-frontend test test-unit test-backend test-e2e test-frontend test-all lint clean emulators-start emulators-stop
.PHONY: help install install-backend install-frontend build-frontend dev-install test test-unit test-backend test-e2e test-frontend test-all lint clean emulators-start emulators-stop
# Per-stage timeout in seconds (default: 10 minutes)
# Prevents hangs from stale dev servers, broken emulators, etc.
# Override with: make test TEST_TIMEOUT=300
TEST_TIMEOUT ?= 600
# Default target
help:
@@ -12,7 +17,8 @@ help:
@echo " make test-unit - Run unit tests only (karaoke_gen package)"
@echo " make test-e2e - Run emulator tests with auto-start/stop"
@echo " make install - Install all dependencies (backend + frontend)"
@echo " make build-frontend - Build frontend and copy to Python package (for local testing)"
@echo " make build-frontend - Build frontend and copy to Python package"
@echo " make dev-install - Build frontend + pip install -e . (for local CLI testing)"
@echo " make lint - Run linter checks"
@echo " make emulators-start - Start GCP emulators for local development"
@echo " make emulators-stop - Stop GCP emulators"
@@ -34,23 +40,34 @@ install-frontend:
install: install-backend install-frontend
# Build frontend and copy to Python package (for local CLI testing)
# Build frontend and copy to Python package
build-frontend: install-frontend
@echo "=== Building frontend ==="
cd frontend && npm run build
@echo "=== Copying build to Python package ==="
rm -rf karaoke_gen/nextjs_frontend/out
mkdir -p karaoke_gen/nextjs_frontend/out
cp -r frontend/out/* karaoke_gen/nextjs_frontend/out/
@echo "✅ Frontend built and ready for local testing"
@echo "✅ Frontend built and copied to karaoke_gen/nextjs_frontend/out/"
# Build frontend + install package in editable mode for local CLI testing
# After running this, `karaoke-gen` CLI will use the freshly built frontend.
dev-install: build-frontend
@echo "=== Installing package in editable mode ==="
pip install -e .
@echo ""
@echo "✅ Ready! You can now run karaoke-gen with the updated frontend."
@echo " Example: karaoke-gen input.flac \"Artist\" \"Title\""
# Run unit tests for karaoke_gen package
test-unit: install-backend
@echo "=== Running karaoke_gen unit tests ==="
poetry run pytest tests/unit/ -v --cov=karaoke_gen --cov-report=term-missing --cov-fail-under=69
timeout $(TEST_TIMEOUT) poetry run pytest tests/unit/ -v --cov=karaoke_gen --cov-report=term-missing --cov-fail-under=69
# Run backend unit tests (excludes emulator tests)
test-backend-unit: install-backend
@echo "=== Running backend unit tests ==="
poetry run pytest backend/tests/ --ignore=backend/tests/emulator -v
timeout $(TEST_TIMEOUT) poetry run pytest backend/tests/ --ignore=backend/tests/emulator -v
# Run E2E integration tests with emulators
test-e2e: install-backend
@@ -62,7 +79,7 @@ test-e2e: install-backend
export GCS_BUCKET_NAME=test-bucket && \
export ADMIN_TOKENS=test-admin-token && \
export ENVIRONMENT=test && \
poetry run pytest backend/tests/emulator/ -v; \
timeout $(TEST_TIMEOUT) poetry run pytest backend/tests/emulator/ -v; \
TEST_RESULT=$$?; \
./scripts/stop-emulators.sh; \
exit $$TEST_RESULT
@@ -75,7 +92,7 @@ test-backend: test-unit test-backend-unit test-e2e
# Run frontend tests (unit + E2E)
test-frontend: install-frontend
@echo "=== Running frontend tests ==="
cd frontend && npm run test:all
cd frontend && timeout $(TEST_TIMEOUT) npm run test:all
# Run ALL tests (backend + frontend) - use this before committing!
test: test-backend test-frontend
-1
View File
@@ -240,4 +240,3 @@ python3 backend/validate.py
4. **Deploy:** Use `./scripts/deploy.sh`
**The import error would have been caught if you ran validation in a venv!** ✅
# Test comment for CI
+106 -1
View File
@@ -96,6 +96,7 @@ class JobUpdateRequest(BaseModel):
enable_youtube_upload: Optional[bool] = None
non_interactive: Optional[bool] = None
prep_only: Optional[bool] = None
is_private: Optional[bool] = None
class JobUpdateResponse(BaseModel):
@@ -123,6 +124,7 @@ EDITABLE_JOB_FIELDS = {
"enable_youtube_upload",
"non_interactive",
"prep_only",
"is_private",
}
@@ -912,6 +914,7 @@ async def update_job(
- customer_email, customer_notes: Made-for-you order info
- brand_prefix: Brand code prefix
- non_interactive, prep_only: Workflow options
- is_private: Private (non-published) track mode
- discord_webhook_url: Notification URL
- youtube_description, youtube_description_template: YouTube settings
@@ -950,6 +953,14 @@ async def update_job(
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
# Check if we're toggling is_private from False to True on a completed job
# If so, auto-delete existing outputs (YouTube, Dropbox, GDrive)
toggling_to_private = (
"is_private" in updates
and updates["is_private"] is True
and not getattr(job, 'is_private', False)
)
# Perform the update
success = job_manager.update_job(job_id, updates)
@@ -959,17 +970,46 @@ async def update_job(
detail="Failed to update job. Please try again."
)
# Auto-delete outputs when toggling to private on a job with existing outputs
auto_deleted = False
if toggling_to_private and job.status in TERMINAL_STATES and not job.outputs_deleted_at:
state_data = job.state_data or {}
has_outputs = (
state_data.get('youtube_url')
or state_data.get('dropbox_link')
or state_data.get('gdrive_files')
)
if has_outputs:
try:
logger.info(
f"Auto-deleting outputs for job {job_id} (toggled to private by {admin_email})"
)
# Call the delete-outputs endpoint directly (same module)
await delete_job_outputs(job_id, auth_data)
auto_deleted = True
except HTTPException:
# delete_job_outputs raises HTTPException on validation failures,
# but we've already validated terminal state + not-already-deleted
logger.warning(f"Auto-delete outputs skipped for job {job_id} (validation)")
except Exception as e:
logger.warning(f"Auto-delete outputs failed for job {job_id}: {e}")
# Log the admin action
logger.info(
f"Admin {admin_email} updated job {job_id}. "
f"Updated fields: {list(updates.keys())}"
f"{' (outputs auto-deleted)' if auto_deleted else ''}"
)
message = f"Successfully updated {len(updates)} field(s)"
if auto_deleted:
message += ". Existing outputs were auto-deleted (job set to private)."
return JobUpdateResponse(
status="success",
job_id=job_id,
updated_fields=list(updates.keys()),
message=f"Successfully updated {len(updates)} field(s)",
message=message,
)
@@ -1327,6 +1367,69 @@ async def trigger_worker(
)
# =============================================================================
# Prepare Review Audio Endpoint
# =============================================================================
class PrepareReviewAudioResponse(BaseModel):
"""Response from prepare-review-audio endpoint."""
status: str
job_id: str
transcoded_files: List[str]
message: str
@router.post("/jobs/{job_id}/prepare-review-audio", response_model=PrepareReviewAudioResponse)
async def prepare_review_audio(
job_id: str,
auth_data: AuthResult = Depends(require_admin),
):
"""
Transcode review audio to OGG Opus for a job (admin only).
Use this to backfill transcoded audio for existing jobs that were
created before eager transcoding was deployed. Transcodes the main
input audio and all stem files to OGG Opus 128kbps.
Idempotent: skips files that are already transcoded.
"""
admin_email = auth_data.user_email or "unknown"
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
try:
import asyncio
from backend.services.audio_transcoding_service import AudioTranscodingService
transcoding = AudioTranscodingService()
transcoded = await asyncio.to_thread(transcoding.prepare_review_audio_for_job, job)
logger.info(
f"Admin {admin_email} prepared review audio for job {job_id}: "
f"{len(transcoded)} files transcoded"
)
return PrepareReviewAudioResponse(
status="success",
job_id=job_id,
transcoded_files=transcoded,
message=f"Transcoded {len(transcoded)} files to OGG Opus",
)
except Exception as e:
logger.error(
f"Admin {admin_email} failed to prepare review audio for job {job_id}: {e}",
exc_info=True,
)
raise HTTPException(
status_code=500,
detail=f"Failed to prepare review audio: {str(e)}",
)
# =============================================================================
# Clear Worker State Endpoint
# =============================================================================
@@ -1691,6 +1794,7 @@ async def get_job_completion_message(
title=job.title,
youtube_url=youtube_url,
dropbox_url=dropbox_url,
is_private=getattr(job, 'is_private', False),
)
# Build subject: "NOMAD-1178: Artist - Title (Your karaoke video is ready!)"
@@ -1755,6 +1859,7 @@ async def send_job_completion_email(
title=job.title,
youtube_url=youtube_url,
dropbox_url=dropbox_url,
is_private=getattr(job, 'is_private', False),
)
# Send the email
+106 -70
View File
@@ -46,6 +46,7 @@ from backend.version import VERSION
from backend.api.dependencies import require_auth
from backend.services.auth_service import UserType, AuthResult
from backend.middleware.tenant import get_tenant_config_from_request
from backend.exceptions import InsufficientCreditsError, RateLimitExceededError
from pathlib import Path
logger = logging.getLogger(__name__)
@@ -134,6 +135,9 @@ class AudioSearchRequest(BaseModel):
# Non-interactive mode
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
# Private (non-published) track mode
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
@validator('artist', 'title', 'lyrics_artist', 'lyrics_title', 'display_artist', 'display_title')
def normalize_text_fields(cls, v):
"""Normalize text fields to standardize Unicode characters."""
@@ -254,27 +258,20 @@ def _extract_gcs_path(filepath: str) -> str:
return filepath
async def _download_and_start_processing(
def _validate_and_prepare_selection(
job_id: str,
selection_index: int,
audio_search_service,
background_tasks: BackgroundTasks,
) -> Dict[str, Any]:
"""
Download selected audio and start job processing.
This is called either:
- Immediately after search if auto_download=True
- When user calls the select endpoint
For remote flacfetch downloads (torrent sources), the file is downloaded
on the flacfetch VM and uploaded directly to GCS. For local downloads
(YouTube), the file is downloaded locally and then uploaded to GCS.
Validate selection and transition job to DOWNLOADING_AUDIO state.
Returns selection info dict with the selected result details.
Raises HTTPException on validation errors.
"""
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
# Get search results from state_data
search_results = job.state_data.get('audio_search_results', [])
if not search_results:
@@ -288,9 +285,6 @@ async def _download_and_start_processing(
selected = search_results[selection_index]
# Get remote_search_id from state_data (stored during initial search)
remote_search_id = job.state_data.get('remote_search_id')
# Transition to downloading state
job_manager.transition_to_state(
job_id=job_id,
@@ -302,28 +296,65 @@ async def _download_and_start_processing(
'selected_audio_provider': selected['provider'],
}
)
# Save download params to job BEFORE attempting download
# This enables retry even if download fails
source_name = selected.get('provider')
source_id = selected.get('source_id')
target_file = selected.get('target_file')
download_url = selected.get('url')
job_manager.update_job(job_id, {
'audio_source_type': 'audio_search',
'source_name': source_name,
'source_id': source_id,
'target_file': target_file,
'download_url': download_url,
})
logger.info(
f"Job {job_id}: Saved download params before attempt: "
f"source_name={source_name}, source_id={source_id}"
)
return {
'selected_index': selection_index,
'selected_title': selected['title'],
'selected_artist': selected['artist'],
'selected_provider': selected['provider'],
}
async def _download_audio_and_trigger_workers(
job_id: str,
selection_index: int,
audio_search_service,
) -> None:
"""
Download audio and trigger processing workers.
This runs as a background task after the select endpoint returns.
Also called synchronously from the auto_download path during search.
For remote flacfetch downloads (torrent sources), the file is downloaded
on the flacfetch VM and uploaded directly to GCS. For local downloads
(YouTube), the file is downloaded locally and then uploaded to GCS.
"""
try:
job = job_manager.get_job(job_id)
if not job:
logger.error(f"Job {job_id} not found during background download")
return
search_results = job.state_data.get('audio_search_results', [])
selected = search_results[selection_index]
remote_search_id = job.state_data.get('remote_search_id')
# Get source info from selected result
source_name = selected.get('provider')
source_id = selected.get('source_id')
target_file = selected.get('target_file')
download_url = selected.get('url')
# Save download params to job BEFORE attempting download
# This enables retry even if download fails
job_manager.update_job(job_id, {
'audio_source_type': 'audio_search',
'source_name': source_name,
'source_id': source_id,
'target_file': target_file,
'download_url': download_url,
})
logger.info(
f"Job {job_id}: Saved download params before attempt: "
f"source_name={source_name}, source_id={source_id}"
)
# Route to appropriate download handler based on source type
if source_name == 'YouTube':
# Use YouTubeDownloadService for all YouTube downloads
@@ -439,7 +470,7 @@ async def _download_and_start_processing(
shutil.rmtree(temp_dir)
except Exception as e:
logger.warning(f"Failed to clean up temp files: {e}")
# Update job with GCS path
job_manager.update_job(job_id, {
'input_media_gcs_path': audio_gcs_path,
@@ -456,29 +487,19 @@ async def _download_and_start_processing(
message="Audio downloaded, starting processing"
)
# Trigger workers in background
async def trigger_workers():
worker_service = get_worker_service()
await asyncio.gather(
worker_service.trigger_audio_worker(job_id),
worker_service.trigger_lyrics_worker(job_id)
)
# Trigger workers directly
worker_service = get_worker_service()
await asyncio.gather(
worker_service.trigger_audio_worker(job_id),
worker_service.trigger_lyrics_worker(job_id)
)
background_tasks.add_task(trigger_workers)
return {
'selected_index': selection_index,
'selected_title': selected['title'],
'selected_artist': selected['artist'],
'selected_provider': selected['provider'],
}
except DownloadError as e:
logger.error(f"Download failed for job {job_id}: {e}")
job_manager.fail_job(job_id, f"Audio download failed: {e}")
raise HTTPException(status_code=500, detail=f"Download failed: {e}")
except Exception as e:
logger.error(f"Download failed for job {job_id}: {e}", exc_info=True)
job_manager.fail_job(job_id, f"Audio download failed: {e}")
raise HTTPException(status_code=500, detail=f"Download failed: {e}")
@router.post("/audio-search/search", response_model=AudioSearchResponse)
@@ -604,6 +625,7 @@ async def search_audio(
auto_download=body.auto_download,
request_metadata=request_metadata,
non_interactive=body.non_interactive,
is_private=body.is_private,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else None,
)
@@ -743,16 +765,22 @@ async def search_audio(
# If auto_download, select best and start processing
if body.auto_download:
best_index = audio_search_service.select_best(search_results)
logger.info(f"Auto-download enabled, selecting result {best_index}")
selection_info = await _download_and_start_processing(
selection_info = _validate_and_prepare_selection(
job_id=job_id,
selection_index=best_index,
audio_search_service=audio_search_service,
background_tasks=background_tasks,
)
# For auto_download, run download in background so this endpoint returns quickly
background_tasks.add_task(
_download_audio_and_trigger_workers,
job_id,
best_index,
audio_search_service,
)
return AudioSearchResponse(
status="success",
job_id=job_id,
@@ -839,6 +867,8 @@ async def search_audio(
except HTTPException:
raise
except (InsufficientCreditsError, RateLimitExceededError):
raise
except Exception as e:
logger.error(f"Error in audio search: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
@@ -886,24 +916,23 @@ async def select_audio_source(
):
"""
Select an audio source and start job processing.
This endpoint:
1. Validates the job is awaiting selection
2. Downloads the selected audio
3. Uploads to GCS
4. Triggers audio and lyrics workers
This endpoint returns immediately after validating the selection and
transitioning the job to DOWNLOADING_AUDIO state. The actual download
runs as a background task so the UI can close the selection dialog
without waiting for the download to complete.
"""
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
# Verify job is awaiting selection
if job.status != JobStatus.AWAITING_AUDIO_SELECTION:
raise HTTPException(
status_code=400,
detail=f"Job is not awaiting audio selection (status: {job.status})"
)
# Get search service instance
# Note: With download_by_id, we no longer need to re-search to populate the cache.
# The source_id stored in job.state_data['audio_search_results'] is sufficient.
@@ -913,18 +942,25 @@ async def select_audio_source(
search_results = job.state_data.get('audio_search_results', [])
if not search_results:
raise HTTPException(status_code=400, detail="No search results cached for this job")
selection_info = await _download_and_start_processing(
# Validate selection and transition to DOWNLOADING_AUDIO (returns immediately)
selection_info = _validate_and_prepare_selection(
job_id=job_id,
selection_index=body.selection_index,
audio_search_service=audio_search_service,
background_tasks=background_tasks,
)
# Schedule the actual download as a background task
background_tasks.add_task(
_download_audio_and_trigger_workers,
job_id,
body.selection_index,
audio_search_service,
)
return AudioSelectResponse(
status="success",
job_id=job_id,
message="Audio selected and download started",
message="Audio selected, download starting",
selected_index=selection_info['selected_index'],
selected_title=selection_info['selected_title'],
selected_artist=selection_info['selected_artist'],
+36 -8
View File
@@ -39,6 +39,7 @@ from backend.services.metrics import metrics
from backend.api.dependencies import require_auth
from backend.services.auth_service import UserType, AuthResult
from backend.middleware.tenant import get_tenant_config_from_request
from backend.exceptions import InsufficientCreditsError, RateLimitExceededError
from backend.services.youtube_download_service import (
get_youtube_download_service,
YouTubeDownloadError,
@@ -111,6 +112,9 @@ class CreateJobFromUrlRequest(BaseModel):
# Non-interactive mode
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
# Private (non-published) track mode
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
class CreateJobFromUrlResponse(BaseModel):
"""Response from creating a job from URL."""
@@ -172,6 +176,9 @@ class CreateJobWithUploadUrlsRequest(BaseModel):
# Non-interactive mode
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
# Private (non-published) track mode
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
class SignedUploadUrl(BaseModel):
"""Signed URL for uploading a file."""
@@ -361,6 +368,8 @@ async def upload_and_create_job(
other_stems_models: Optional[str] = Form(None, description="Comma-separated list of models for other stems (bass, drums, guitar, etc.)"),
# Non-interactive mode
non_interactive: bool = Form(False, description="Skip interactive steps (lyrics review, instrumental selection)"),
# Private (non-published) track mode
is_private: bool = Form(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive"),
):
"""
Upload an audio file and create a karaoke generation job with full style configuration.
@@ -461,10 +470,11 @@ async def upload_and_create_job(
# Validate credentials for requested distribution services (including defaults)
# This prevents accepting jobs that will fail later due to missing credentials
# Skip YouTube/GDrive checks for private jobs (they won't use those services)
invalid_services = []
credential_manager = get_credential_manager()
if effective_enable_youtube_upload:
if effective_enable_youtube_upload and not is_private:
result = credential_manager.check_youtube_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"youtube ({result.message})")
@@ -474,7 +484,7 @@ async def upload_and_create_job(
if result.status != CredentialStatus.VALID:
invalid_services.append(f"dropbox ({result.message})")
if dist.gdrive_folder_id:
if dist.gdrive_folder_id and not is_private:
result = credential_manager.check_gdrive_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"gdrive ({result.message})")
@@ -574,6 +584,8 @@ async def upload_and_create_job(
request_metadata=request_metadata,
# Non-interactive mode
non_interactive=non_interactive,
# Private (non-published) track mode
is_private=is_private,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else None,
)
@@ -800,6 +812,8 @@ async def upload_and_create_job(
except HTTPException:
raise
except (InsufficientCreditsError, RateLimitExceededError):
raise
except Exception as e:
logger.error(f"Error uploading files: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e)) from e
@@ -876,6 +890,8 @@ class CreateFinaliseOnlyJobRequest(BaseModel):
dropbox_path: Optional[str] = Field(None, description="Dropbox folder path for organized output")
gdrive_folder_id: Optional[str] = Field(None, description="Google Drive folder ID for public share uploads")
# Private (non-published) track mode
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
@@ -1022,10 +1038,11 @@ async def create_job_with_upload_urls(
effective_enable_youtube_upload = body.enable_youtube_upload if body.enable_youtube_upload is not None else settings.default_enable_youtube_upload
# Validate credentials for requested distribution services
# Skip YouTube/GDrive checks for private jobs (they won't use those services)
invalid_services = []
credential_manager = get_credential_manager()
if effective_enable_youtube_upload:
if effective_enable_youtube_upload and not body.is_private:
result = credential_manager.check_youtube_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"youtube ({result.message})")
@@ -1035,7 +1052,7 @@ async def create_job_with_upload_urls(
if result.status != CredentialStatus.VALID:
invalid_services.append(f"dropbox ({result.message})")
if dist.gdrive_folder_id:
if dist.gdrive_folder_id and not body.is_private:
result = credential_manager.check_gdrive_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"gdrive ({result.message})")
@@ -1104,6 +1121,7 @@ async def create_job_with_upload_urls(
other_stems_models=body.other_stems_models,
request_metadata=request_metadata,
non_interactive=body.non_interactive,
is_private=body.is_private,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else None,
)
@@ -1161,6 +1179,8 @@ async def create_job_with_upload_urls(
except HTTPException:
raise
except (InsufficientCreditsError, RateLimitExceededError):
raise
except Exception as e:
logger.error(f"Error creating job with upload URLs: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e)) from e
@@ -1464,10 +1484,11 @@ async def create_job_from_url(
effective_enable_youtube_upload = body.enable_youtube_upload if body.enable_youtube_upload is not None else settings.default_enable_youtube_upload
# Validate credentials for requested distribution services
# Skip YouTube/GDrive checks for private jobs (they won't use those services)
invalid_services = []
credential_manager = get_credential_manager()
if effective_enable_youtube_upload:
if effective_enable_youtube_upload and not body.is_private:
result = credential_manager.check_youtube_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"youtube ({result.message})")
@@ -1477,7 +1498,7 @@ async def create_job_from_url(
if result.status != CredentialStatus.VALID:
invalid_services.append(f"dropbox ({result.message})")
if dist.gdrive_folder_id:
if dist.gdrive_folder_id and not body.is_private:
result = credential_manager.check_gdrive_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"gdrive ({result.message})")
@@ -1544,6 +1565,7 @@ async def create_job_from_url(
other_stems_models=body.other_stems_models,
request_metadata=request_metadata,
non_interactive=body.non_interactive,
is_private=body.is_private,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else None,
)
@@ -1635,6 +1657,8 @@ async def create_job_from_url(
except HTTPException:
raise
except (InsufficientCreditsError, RateLimitExceededError):
raise
except Exception as e:
logger.error(f"Error creating job from URL: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e)) from e
@@ -1771,10 +1795,11 @@ async def create_finalise_only_job(
effective_enable_youtube_upload = body.enable_youtube_upload if body.enable_youtube_upload is not None else settings.default_enable_youtube_upload
# Validate distribution credentials if services are requested
# Skip YouTube/GDrive checks for private jobs (they won't use those services)
invalid_services = []
credential_manager = get_credential_manager()
if effective_enable_youtube_upload:
if effective_enable_youtube_upload and not body.is_private:
result = credential_manager.check_youtube_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"youtube ({result.message})")
@@ -1784,7 +1809,7 @@ async def create_finalise_only_job(
if result.status != CredentialStatus.VALID:
invalid_services.append(f"dropbox ({result.message})")
if dist.gdrive_folder_id:
if dist.gdrive_folder_id and not body.is_private:
result = credential_manager.check_gdrive_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"gdrive ({result.message})")
@@ -1842,6 +1867,7 @@ async def create_finalise_only_job(
finalise_only=True,
keep_brand_code=body.keep_brand_code,
request_metadata=request_metadata,
is_private=body.is_private,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else None,
)
@@ -1899,6 +1925,8 @@ async def create_finalise_only_job(
except HTTPException:
raise
except (InsufficientCreditsError, RateLimitExceededError):
raise
except Exception as e:
logger.error(f"Error creating finalise-only job: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e)) from e
+159 -6
View File
@@ -20,6 +20,7 @@ from backend.models.requests import (
CancelJobRequest,
InstrumentalSelection,
CompleteReviewRequest,
CreateCustomInstrumentalRequest,
)
from backend.services.job_manager import JobManager
from backend.services.worker_service import get_worker_service
@@ -31,6 +32,7 @@ from backend.services.auth_service import AuthResult
from backend.services.metrics import metrics
from backend.middleware.tenant import get_tenant_from_request
from backend.utils.test_data import is_test_email
from backend.exceptions import InsufficientCreditsError, RateLimitExceededError
logger = logging.getLogger(__name__)
@@ -115,7 +117,8 @@ async def create_job(
enable_youtube_upload=effective_enable_youtube_upload,
youtube_description=request.youtube_description,
webhook_url=request.webhook_url,
user_email=user_email
user_email=user_email,
is_private=request.is_private or False,
)
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
@@ -133,6 +136,8 @@ async def create_job(
job_id=job.job_id,
message="Job created successfully. Processing started."
)
except (InsufficientCreditsError, RateLimitExceededError):
raise
except Exception as e:
logger.error(f"Error creating job: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
@@ -188,7 +193,33 @@ def _check_job_ownership(job: Job, auth_result: AuthResult) -> bool:
return True
@router.get("", response_model=List[Job])
_SUMMARY_STATE_DATA_KEYS = {
'brand_code', 'youtube_url', 'dropbox_link',
'audio_progress', 'lyrics_progress',
'audio_complete', 'lyrics_complete',
'backing_vocals_analysis',
}
_SUMMARY_FILE_URLS_KEYS = {'finals', 'videos', 'packages'}
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete', 'failed', 'cancelled']
def _prune_state_data(data: Dict[str, Any]) -> Dict[str, Any]:
"""Strip state_data down to dashboard-required keys."""
sd = data.get('state_data')
if isinstance(sd, dict):
data['state_data'] = {k: v for k, v in sd.items() if k in _SUMMARY_STATE_DATA_KEYS}
return data
def _prune_file_urls(data: Dict[str, Any]) -> Dict[str, Any]:
"""Strip file_urls down to dashboard-required keys."""
fu = data.get('file_urls')
if isinstance(fu, dict):
data['file_urls'] = {k: v for k, v in fu.items() if k in _SUMMARY_FILE_URLS_KEYS}
return data
@router.get("", response_model=None)
async def list_jobs(
request: Request,
status: Optional[JobStatus] = None,
@@ -198,8 +229,10 @@ async def list_jobs(
created_before: Optional[str] = None,
exclude_test: bool = True,
limit: int = 100,
fields: Optional[str] = None,
hide_completed: bool = False,
auth_result: AuthResult = Depends(require_auth)
) -> List[Job]:
):
"""
List jobs with optional filters.
@@ -214,9 +247,13 @@ async def list_jobs(
created_before: Filter jobs created before this ISO datetime
exclude_test: If True (default), exclude jobs from test users (admin only)
limit: Maximum number of jobs to return (default 100)
fields: Set to "summary" for reduced payload with only dashboard-required fields
hide_completed: If True, exclude terminal-status jobs (complete, prep_complete, failed, cancelled)
Returns:
List of jobs matching filters, ordered by created_at descending
List of jobs matching filters, ordered by created_at descending.
When fields=summary, returns List[dict] (pruned).
Otherwise returns List[Job] (full model).
"""
from datetime import datetime
@@ -253,6 +290,32 @@ async def list_jobs(
# Tenant users only see jobs from their tenant
tenant_id = get_tenant_from_request(request)
# --- Summary mode: field-projected query returning dicts ---
if fields == "summary":
exclude_statuses = _HIDE_COMPLETED_STATUSES if hide_completed else None
jobs_dicts = job_manager.list_jobs_summary(
status=status,
exclude_statuses=exclude_statuses,
environment=environment,
client_id=client_id,
created_after=created_after_dt,
created_before=created_before_dt,
user_email=user_email_filter,
tenant_id=tenant_id,
limit=limit,
)
# Exclude test user jobs (Python-side, same as full mode)
if exclude_test and auth_result.is_admin:
jobs_dicts = [j for j in jobs_dicts if not is_test_email(j.get('user_email') or "")]
# Safety-net pruning (in case Firestore returned extra nested keys)
jobs_dicts = [_prune_file_urls(_prune_state_data(j)) for j in jobs_dicts]
logger.debug(f"Listed {len(jobs_dicts)} summary jobs for user={auth_result.user_email}")
return jobs_dicts
# --- Full mode: existing behaviour (List[Job]) ---
jobs = job_manager.list_jobs(
status=status,
environment=environment,
@@ -536,8 +599,14 @@ async def submit_corrections(
)
try:
# Store corrected lyrics in state_data
job_manager.update_state_data(job_id, 'corrected_lyrics', submission.corrections)
# Strip reference_lyrics from Firestore save to avoid exceeding 1MB document
# limit. reference_lyrics can be very large (e.g. Genius fetching non-lyrics
# content like screenplays). The full data is preserved in the GCS upload below.
corrections_for_firestore = {
k: v for k, v in submission.corrections.items()
if k != 'reference_lyrics'
}
job_manager.update_state_data(job_id, 'corrected_lyrics', corrections_for_firestore)
if submission.user_notes:
job_manager.update_state_data(job_id, 'review_notes', submission.user_notes)
@@ -570,6 +639,90 @@ async def submit_corrections(
raise HTTPException(status_code=500, detail=str(e))
@router.post("/{job_id}/create-custom-instrumental")
async def create_custom_instrumental(
job_id: str,
request: CreateCustomInstrumentalRequest,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
"""
Create a custom instrumental by muting regions of backing vocals.
Downloads the clean instrumental and backing vocals stems, applies mute
regions, combines them, uploads to GCS, and returns a signed URL for playback.
"""
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")
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not in review state (current status: {job.status})"
)
# Get stem paths from job
stems = job.file_urls.get('stems', {})
clean_path = stems.get('instrumental_clean')
backing_path = stems.get('backing_vocals')
if not clean_path or not backing_path:
raise HTTPException(
status_code=400,
detail="Job missing required stems (instrumental_clean and/or backing_vocals)"
)
try:
from backend.services.audio_editing_service import AudioEditingService
from karaoke_gen.instrumental_review import MuteRegion
storage = StorageService()
editing_service = AudioEditingService(storage_service=storage)
# Convert request mute regions to domain model
mute_regions = [
MuteRegion(start_seconds=r.start_seconds, end_seconds=r.end_seconds)
for r in request.mute_regions
]
# Create custom instrumental and upload to GCS (offload blocking IO to thread)
output_path = f"jobs/{job_id}/stems/custom_instrumental.flac"
result = await asyncio.get_event_loop().run_in_executor(
None,
lambda: editing_service.create_custom_instrumental(
gcs_clean_instrumental_path=clean_path,
gcs_backing_vocals_path=backing_path,
mute_regions=mute_regions,
gcs_output_path=output_path,
job_id=job_id,
)
)
# Store the custom instrumental path in job file_urls
job_manager.update_file_url(job_id, 'stems', 'custom_instrumental', output_path)
# Generate signed URL for playback
from backend.services.audio_transcoding_service import AudioTranscodingService
transcoding = AudioTranscodingService(storage_service=storage)
audio_url = await transcoding.get_review_audio_url_async(output_path, expiration_minutes=120)
logger.info(f"Job {job_id}: Custom instrumental created with {len(mute_regions)} mute regions")
return {
"status": "success",
"message": f"Custom instrumental created with {len(mute_regions)} mute regions",
"audio_url": audio_url,
"muted_duration_seconds": result.total_muted_duration_seconds,
}
except Exception as e:
logger.error(f"Error creating custom instrumental for job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
@router.post("/{job_id}/complete-review")
async def complete_review(
job_id: str,
+54 -51
View File
@@ -22,7 +22,7 @@ from pathlib import Path
from typing import Dict, Any, Set, Tuple
from fastapi import APIRouter, HTTPException, Request, Depends
from fastapi.responses import FileResponse, StreamingResponse
from fastapi.responses import FileResponse, RedirectResponse, StreamingResponse
from starlette.background import BackgroundTask
from backend.models.job import JobStatus
@@ -138,27 +138,40 @@ async def get_correction_data(
}
# === Add instrumental data for combined review ===
from backend.services.audio_transcoding_service import AudioTranscodingService
transcoding = AudioTranscodingService(storage_service=storage)
# Get instrumental stem URLs
stems = job.file_urls.get('stems', {})
clean_url = stems.get('instrumental_clean')
backing_url = stems.get('instrumental_with_backing')
# Build instrumental options with signed URLs
# Build instrumental options with transcoded signed URLs (OGG Opus)
instrumental_options = []
url_tasks = {}
if clean_url:
url_tasks['clean'] = transcoding.get_review_audio_url_async(clean_url, expiration_minutes=120)
if backing_url:
url_tasks['with_backing'] = transcoding.get_review_audio_url_async(backing_url, expiration_minutes=120)
signed_urls = {}
if url_tasks:
results = await asyncio.gather(*url_tasks.values())
signed_urls = dict(zip(url_tasks.keys(), results))
if clean_url:
instrumental_options.append({
"id": "clean",
"label": "Clean Instrumental",
"description": "No backing vocals - just the music",
"audio_url": storage.generate_signed_url(clean_url, expiration_minutes=120),
"audio_url": signed_urls['clean'],
})
if backing_url:
instrumental_options.append({
"id": "with_backing",
"label": "Instrumental with Backing Vocals",
"description": "Includes harmonies and background vocals",
"audio_url": storage.generate_signed_url(backing_url, expiration_minutes=120),
"audio_url": signed_urls['with_backing'],
})
corrections_data['instrumental_options'] = instrumental_options
@@ -213,49 +226,32 @@ async def get_audio_no_hash(
async def _stream_audio(job_id: str):
"""
Stream the audio file for playback in the review interface.
Redirect to a signed GCS URL for audio playback in the review interface.
Serves transcoded OGG Opus (~3 MB) instead of raw FLAC (~35 MB).
Falls back to FLAC if transcoded version is not available.
"""
from backend.services.audio_transcoding_service import AudioTranscodingService
job_manager = JobManager()
storage = StorageService()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
audio_gcs_path = job.input_media_gcs_path
if not audio_gcs_path:
raise HTTPException(status_code=404, detail="Audio file not found")
# Download to temp file and stream
try:
# Create temp file
with tempfile.NamedTemporaryFile(delete=False, suffix=".flac") as tmp:
tmp_path = tmp.name
storage.download_file(audio_gcs_path, tmp_path)
# Determine content type
if audio_gcs_path.endswith('.flac'):
media_type = "audio/flac"
elif audio_gcs_path.endswith('.wav'):
media_type = "audio/wav"
elif audio_gcs_path.endswith('.mp3'):
media_type = "audio/mpeg"
else:
media_type = "audio/mpeg"
logger.info(f"Job {job_id}: Streaming audio for review")
return FileResponse(
tmp_path,
media_type=media_type,
filename=os.path.basename(audio_gcs_path),
background=BackgroundTask(os.unlink, tmp_path),
)
transcoding = AudioTranscodingService()
signed_url = await transcoding.get_review_audio_url_async(audio_gcs_path, expiration_minutes=120)
logger.info(f"Job {job_id}: Redirecting to signed URL for audio review")
return RedirectResponse(url=signed_url, status_code=302)
except Exception as e:
logger.error(f"Job {job_id}: Error streaming audio: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error streaming audio: {str(e)}")
logger.error(f"Job {job_id}: Error generating audio signed URL: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error serving audio: {str(e)}")
@router.post("/{job_id}/complete")
@@ -296,8 +292,9 @@ async def complete_review(
)
valid_selections = ["clean", "with_backing"]
# Also allow "custom" for user-provided instrumentals
if job.existing_instrumental_gcs_path:
# Allow "custom" for mute-region instrumentals or user-uploaded instrumentals
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
if job.existing_instrumental_gcs_path or stems.get("custom_instrumental"):
valid_selections.append("custom")
if instrumental_selection not in valid_selections:
@@ -785,23 +782,29 @@ async def get_instrumental_analysis(
backing_analysis = job.state_data.get('backing_vocals_analysis', {})
# Get stem URLs
from backend.services.audio_transcoding_service import AudioTranscodingService
transcoding = AudioTranscodingService(storage_service=storage)
stems = job.file_urls.get('stems', {})
clean_url = stems.get('instrumental_clean')
backing_url = stems.get('instrumental_with_backing')
# Build audio URLs with signed access
audio_urls = {}
if clean_url:
audio_urls['clean'] = storage.generate_signed_url(clean_url, expiration_minutes=120)
if backing_url:
audio_urls['with_backing'] = storage.generate_signed_url(backing_url, expiration_minutes=120)
if job.input_media_gcs_path:
audio_urls['original'] = storage.generate_signed_url(job.input_media_gcs_path, expiration_minutes=120)
# Check for backing vocals stem for playback
backing_vocals_path = stems.get('backing_vocals')
# Build audio URLs with transcoded signed access (OGG Opus, parallel)
url_tasks = {}
if clean_url:
url_tasks['clean'] = transcoding.get_review_audio_url_async(clean_url, expiration_minutes=120)
if backing_url:
url_tasks['with_backing'] = transcoding.get_review_audio_url_async(backing_url, expiration_minutes=120)
if job.input_media_gcs_path:
url_tasks['original'] = transcoding.get_review_audio_url_async(job.input_media_gcs_path, expiration_minutes=120)
if backing_vocals_path:
audio_urls['backing_vocals'] = storage.generate_signed_url(backing_vocals_path, expiration_minutes=120)
url_tasks['backing_vocals'] = transcoding.get_review_audio_url_async(backing_vocals_path, expiration_minutes=120)
audio_urls = {}
if url_tasks:
results = await asyncio.gather(*url_tasks.values())
audio_urls = dict(zip(url_tasks.keys(), results))
# Format response to match InstrumentalAnalysis type
return {
+4
View File
@@ -116,6 +116,10 @@ class Settings(BaseSettings):
default_enable_youtube_upload: bool = os.getenv("DEFAULT_ENABLE_YOUTUBE_UPLOAD", "false").lower() in ("true", "1", "yes")
default_brand_prefix: Optional[str] = os.getenv("DEFAULT_BRAND_PREFIX")
# Private (non-published) track distribution settings
default_private_dropbox_path: Optional[str] = os.getenv("DEFAULT_PRIVATE_DROPBOX_PATH")
default_private_brand_prefix: Optional[str] = os.getenv("DEFAULT_PRIVATE_BRAND_PREFIX", "NOMADNP")
# Rate Limiting Configuration
# Enable/disable rate limiting system-wide (useful for development)
enable_rate_limiting: bool = os.getenv("ENABLE_RATE_LIMITING", "true").lower() in ("true", "1", "yes")
+22
View File
@@ -66,6 +66,28 @@ class IPBlockedError(Exception):
super().__init__(message)
class InsufficientCreditsError(Exception):
"""
Raised when a user attempts to create a job without sufficient credits.
Attributes:
message: Human-readable error message
credits_available: Number of credits the user currently has
credits_required: Number of credits required (always 1 for now)
"""
def __init__(
self,
message: str,
credits_available: int = 0,
credits_required: int = 1
):
self.message = message
self.credits_available = credits_available
self.credits_required = credits_required
super().__init__(message)
class InvalidStateTransitionError(Exception):
"""
Raised when an invalid job state transition is attempted.
+15 -1
View File
@@ -167,7 +167,7 @@ app.include_router(tenant.router) # Tenant/white-label configuration (no /api p
# Exception handler for rate limiting
from fastapi import Request
from fastapi.responses import JSONResponse
from backend.exceptions import RateLimitExceededError
from backend.exceptions import RateLimitExceededError, InsufficientCreditsError
@app.exception_handler(RateLimitExceededError)
@@ -187,6 +187,20 @@ async def rate_limit_exception_handler(request: Request, exc: RateLimitExceededE
)
@app.exception_handler(InsufficientCreditsError)
async def insufficient_credits_exception_handler(request: Request, exc: InsufficientCreditsError):
"""Handle insufficient credits errors with 402 Payment Required status."""
return JSONResponse(
status_code=402,
content={
"detail": exc.message,
"credits_available": exc.credits_available,
"credits_required": exc.credits_required,
"buy_url": "/#pricing",
},
)
@app.get("/")
async def root():
"""Root endpoint."""
+6
View File
@@ -299,6 +299,9 @@ class Job(BaseModel):
customer_email: Optional[str] = None # Customer email for final delivery (job owned by admin during processing)
customer_notes: Optional[str] = None # Notes provided by customer with their order
# Private (non-published) track mode
is_private: bool = False # Private tracks: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive
# Output deletion tracking (for admin cleanup without deleting job)
outputs_deleted_at: Optional[datetime] = None # Timestamp when outputs were deleted by admin
outputs_deleted_by: Optional[str] = None # Admin email who deleted outputs
@@ -506,6 +509,9 @@ class JobCreate(BaseModel):
customer_email: Optional[str] = None # Customer email for final delivery (job owned by admin during processing)
customer_notes: Optional[str] = None # Notes provided by customer with their order
# Private (non-published) track mode
is_private: bool = False # Private tracks: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive
# Request metadata (set by API endpoint from request headers)
request_metadata: Dict[str, Any] = Field(default_factory=dict)
"""
+2 -1
View File
@@ -10,7 +10,7 @@ class URLSubmissionRequest(BaseModel):
url: HttpUrl
artist: Optional[str] = None # Auto-detected if not provided
title: Optional[str] = None # Auto-detected if not provided
# Optional preferences
enable_cdg: bool = False # Requires style config
enable_txt: bool = False # Requires style config
@@ -18,6 +18,7 @@ class URLSubmissionRequest(BaseModel):
youtube_description: Optional[str] = None
webhook_url: Optional[str] = None
user_email: Optional[str] = None
is_private: Optional[bool] = None # Private (non-published) track mode
class UploadSubmissionRequest(BaseModel):
@@ -0,0 +1,181 @@
"""
Audio transcoding service for review UI optimization.
Transcodes FLAC audio files to OGG Opus for efficient browser playback.
Original FLAC files are never modified — transcoded versions are cached
in GCS at jobs/{job_id}/review-audio/{filename}.ogg.
Eager transcoding: called from screens_worker before AWAITING_REVIEW
so all files are cached before the user opens the review UI.
Falls back to original FLAC signed URLs if transcoded version is missing.
"""
import asyncio
import hashlib
import logging
import os
import subprocess
import tempfile
from pathlib import Path
from typing import Optional
from backend.services.storage_service import StorageService
logger = logging.getLogger(__name__)
class AudioTranscodingService:
"""
Transcodes audio files to OGG Opus and caches them in GCS.
Used by the review UI to serve ~3 MB OGG files instead of 35+ MB FLACs.
"""
def __init__(self, storage_service: Optional[StorageService] = None):
self.storage = storage_service or StorageService()
def _get_cache_path(self, source_gcs_path: str) -> str:
"""
Derive the cache path for a transcoded file.
Examples:
jobs/abc123/input/song.flac -> jobs/abc123/review-audio/song.ogg
jobs/abc123/stems/instrumental_clean.flac -> jobs/abc123/review-audio/instrumental_clean.ogg
"""
parts = Path(source_gcs_path).parts
# Find "jobs/{job_id}" prefix
try:
jobs_idx = list(parts).index("jobs")
job_id = parts[jobs_idx + 1]
except (ValueError, IndexError):
# Fallback: use a hash of the full path to avoid collisions
job_id = "_" + hashlib.sha256(source_gcs_path.encode()).hexdigest()[:12]
filename = Path(source_gcs_path).stem + ".ogg"
return f"jobs/{job_id}/review-audio/{filename}"
def _transcode_and_upload(self, source_gcs_path: str, cache_path: str) -> str:
"""
Download FLAC from GCS, transcode to OGG Opus, upload to cache path.
Returns the cache GCS path on success.
Raises on failure.
"""
with tempfile.TemporaryDirectory() as temp_dir:
local_input = os.path.join(temp_dir, "input.flac")
local_output = os.path.join(temp_dir, "output.ogg")
# Download source
self.storage.download_file(source_gcs_path, local_input)
# Transcode: FLAC -> OGG Opus 128kbps
cmd = [
"ffmpeg", "-hide_banner", "-loglevel", "error",
"-y",
"-i", local_input,
"-c:a", "libopus",
"-b:a", "128k",
"-vn",
local_output,
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
if result.returncode != 0:
raise RuntimeError(
f"ffmpeg transcoding failed (exit {result.returncode}): {result.stderr}"
)
# Upload transcoded file
self.storage.upload_file(local_output, cache_path)
return cache_path
def transcode_if_needed(self, source_gcs_path: str) -> str:
"""
Return the GCS path of the transcoded OGG file, transcoding if not cached.
Returns the cache path (always an OGG file in review-audio/).
Raises if transcoding fails.
"""
cache_path = self._get_cache_path(source_gcs_path)
if self.storage.file_exists(cache_path):
logger.debug(f"Cache hit: {cache_path}")
return cache_path
logger.info(f"Cache miss, transcoding: {source_gcs_path} -> {cache_path}")
return self._transcode_and_upload(source_gcs_path, cache_path)
def get_review_audio_url(
self, source_gcs_path: str, expiration_minutes: int = 120
) -> str:
"""
Get a signed URL for the transcoded audio, falling back to original FLAC.
"""
try:
cache_path = self.transcode_if_needed(source_gcs_path)
return self.storage.generate_signed_url(cache_path, expiration_minutes)
except Exception as e:
# Source may be deleted but cache from earlier transcode persists
try:
cache_path = self._get_cache_path(source_gcs_path)
if self.storage.file_exists(cache_path):
logger.info(f"Source gone but cache exists, serving: {cache_path}")
return self.storage.generate_signed_url(cache_path, expiration_minutes)
except Exception:
pass # Fall through to FLAC fallback below
logger.warning(
f"Transcoding failed for {source_gcs_path}, falling back to FLAC: {e}"
)
return self.storage.generate_signed_url(source_gcs_path, expiration_minutes)
async def get_review_audio_url_async(
self, source_gcs_path: str, expiration_minutes: int = 120
) -> str:
"""Async wrapper around get_review_audio_url via asyncio.to_thread."""
return await asyncio.to_thread(
self.get_review_audio_url, source_gcs_path, expiration_minutes
)
def prepare_review_audio_for_job(self, job) -> list[str]:
"""
Transcode all review audio files for a job (eager transcoding).
Called from screens_worker before AWAITING_REVIEW transition
and from the admin backfill endpoint.
Returns list of cache paths that were transcoded.
"""
job_id = job.job_id
transcoded = []
# Collect all audio paths to transcode
paths_to_transcode = []
# Main input audio
if job.input_media_gcs_path:
paths_to_transcode.append(("input", job.input_media_gcs_path))
# Stems
stems = job.file_urls.get("stems", {})
for stem_key in ["instrumental_clean", "instrumental_with_backing", "backing_vocals"]:
path = stems.get(stem_key)
if path:
paths_to_transcode.append((stem_key, path))
for label, source_path in paths_to_transcode:
try:
cache_path = self.transcode_if_needed(source_path)
transcoded.append(cache_path)
logger.info(f"[{job_id}] Transcoded {label}: {cache_path}")
except Exception as e:
# Non-fatal: review UI will fall back to FLAC
logger.warning(
f"[{job_id}] Failed to transcode {label} ({source_path}): {e}"
)
logger.info(
f"[{job_id}] Review audio preparation complete: "
f"{len(transcoded)}/{len(paths_to_transcode)} files transcoded"
)
return transcoded
+7 -27
View File
@@ -437,10 +437,11 @@ class AuthService:
def increment_token_usage(self, token: str, job_id: str) -> bool:
"""
Increment usage count for a token and track the job.
Increment usage count for an auth_token and track the job.
For session tokens (magic link auth), this deducts a credit from the user.
For auth_tokens, this increments the usage count.
Note: Credit deduction for session-based users is handled in
JobManager.create_job(), not here. This method only tracks usage
for legacy auth_tokens stored in Firestore.
Args:
token: The access token
@@ -465,32 +466,11 @@ class AuthService:
if token in self.admin_tokens:
return True
# Check if this is a session token (STRIPE type from validate_token means it's a session)
# Session tokens are not in auth_tokens collection
# Only increment usage for auth_tokens in Firestore
# Session tokens (magic link auth) have credits managed by JobManager.create_job()
token_data = self.firestore.get_token(token)
if not token_data:
# This is a session token - deduct credit from user
from backend.services.user_service import get_user_service
user_service = get_user_service()
# Get the user email from the session
is_valid, user, _ = user_service.validate_session(token)
if not is_valid or not user:
logger.error(f"Session token validation failed during usage increment")
return False
# Deduct one credit
success, new_balance, deduct_message = user_service.deduct_credit(
user.email, job_id, reason="job_creation"
)
if success:
logger.info(f"Deducted credit for user {user.email} (remaining: {new_balance})")
return True
else:
logger.error(f"Failed to deduct credit for user {user.email}: {deduct_message}")
return False
return True
# Regular auth_token - increment usage in Firestore
try:
+76
View File
@@ -173,6 +173,82 @@ class FirestoreService:
logger.error(f"Error listing jobs: {e}")
raise
# Fields needed by the dashboard summary view
SUMMARY_FIELD_PATHS = [
'job_id', 'status', 'progress', 'created_at', 'artist', 'title',
'error_message', 'non_interactive', 'outputs_deleted_at', 'user_email',
'state_data.brand_code', 'state_data.youtube_url', 'state_data.dropbox_link',
'state_data.audio_progress', 'state_data.lyrics_progress',
'state_data.audio_complete', 'state_data.lyrics_complete',
'state_data.backing_vocals_analysis',
'file_urls.finals', 'file_urls.videos', 'file_urls.packages',
]
def list_jobs_summary(
self,
status: Optional[JobStatus] = None,
exclude_statuses: Optional[List[str]] = None,
environment: Optional[str] = None,
client_id: Optional[str] = None,
created_after: Optional[datetime] = None,
created_before: Optional[datetime] = None,
user_email: Optional[str] = None,
tenant_id: Optional[str] = None,
limit: int = 100,
) -> List[Dict[str, Any]]:
"""
List jobs with Firestore field projection for reduced payload.
Uses ``query.select()`` so Firestore only reads the requested fields,
drastically cutting bandwidth and deserialization cost.
Returns raw dicts (not Job models) because projected documents would
fail Pydantic validation for missing required fields.
"""
try:
query = self.db.collection(self.collection)
if status:
query = query.where(filter=FieldFilter('status', '==', status.value))
# NOTE: exclude_statuses is filtered in Python after the query
# because Firestore's not-in filter combined with order_by(created_at)
# requires a composite index. Since documents are tiny after select(),
# Python filtering is fast and avoids the index requirement.
if environment:
query = query.where(filter=FieldFilter('request_metadata.environment', '==', environment))
if client_id:
query = query.where(filter=FieldFilter('request_metadata.client_id', '==', client_id))
if user_email:
query = query.where(filter=FieldFilter('user_email', '==', user_email.lower()))
if tenant_id:
query = query.where(filter=FieldFilter('tenant_id', '==', tenant_id))
if created_after:
query = query.where(filter=FieldFilter('created_at', '>=', created_after))
if created_before:
query = query.where(filter=FieldFilter('created_at', '<=', created_before))
query = query.order_by('created_at', direction=firestore.Query.DESCENDING).limit(limit)
query = query.select(self.SUMMARY_FIELD_PATHS)
docs = query.stream()
results = [doc.to_dict() for doc in docs]
# Apply exclude_statuses filter in Python (see note above)
if exclude_statuses:
results = [r for r in results if r.get('status') not in exclude_statuses]
return results
except Exception as e:
logger.error(f"Error listing jobs summary: {e}")
raise
def delete_jobs_by_filter(
self,
environment: Optional[str] = None,
+15 -2
View File
@@ -3,6 +3,7 @@ import glob as glob_module
import json
import logging
import os
import re
import subprocess
import sys
import tempfile
@@ -13,6 +14,7 @@ from typing import Optional
from fastapi import FastAPI, BackgroundTasks, HTTPException, Header, Depends
from google.cloud import storage
from packaging.version import Version
from pydantic import BaseModel
logging.basicConfig(level=logging.INFO)
@@ -254,12 +256,23 @@ def ensure_latest_wheel():
# Find the downloaded wheel (get the latest by version sorting)
wheels = glob_module.glob("/tmp/karaoke_gen-*.whl")
# Filter out karaoke_gen-current.whl (not a valid PEP 427 wheel name)
wheels = [w for w in wheels if '-current' not in w]
if not wheels:
logger.warning("No wheel found in GCS, using fallback encoding logic")
return False
# Sort to get latest version
wheel_path = sorted(wheels)[-1]
# Sort to get latest version (by semantic version, not alphabetically)
def extract_version(wheel_path):
"""Extract version from wheel filename like karaoke_gen-0.116.1-py3-none-any.whl"""
match = re.search(r'karaoke_gen-([0-9.]+)-', wheel_path)
if match:
return Version(match.group(1))
return Version("0.0.0") # Fallback for unparseable filenames
wheels.sort(key=extract_version, reverse=True)
wheel_path = wheels[0]
logger.info(f"Installing wheel: {wheel_path}")
# Install (or upgrade) the wheel
+39
View File
@@ -61,6 +61,45 @@ def get_effective_distribution_settings(
)
def get_effective_distribution_for_job(job) -> EffectiveDistributionSettings:
"""
Get effective distribution settings for a job, applying private overrides if is_private=True.
For private (non-published) jobs, this overrides:
- dropbox_path → private Dropbox path (Tracks-NonPublished)
- brand_prefix → private brand prefix (NOMADNP)
- enable_youtube_upload → False (no YouTube for private)
- gdrive_folder_id → None (no Google Drive for private)
For non-private jobs, returns the job's own distribution settings unchanged.
Args:
job: Job object (or any object with distribution fields)
Returns:
EffectiveDistributionSettings with private overrides applied if needed
"""
if getattr(job, 'is_private', False):
settings = get_settings()
return EffectiveDistributionSettings(
dropbox_path=settings.default_private_dropbox_path,
brand_prefix=settings.default_private_brand_prefix,
enable_youtube_upload=False,
gdrive_folder_id=None,
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
youtube_description=None,
)
# Non-private: return job's own settings
return EffectiveDistributionSettings(
dropbox_path=getattr(job, 'dropbox_path', None),
brand_prefix=getattr(job, 'brand_prefix', None),
enable_youtube_upload=getattr(job, 'enable_youtube_upload', False),
gdrive_folder_id=getattr(job, 'gdrive_folder_id', None),
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
youtube_description=getattr(job, 'youtube_description_template', None),
)
def resolve_cdg_txt_defaults(
theme_id: Optional[str],
enable_cdg: Optional[bool] = None,
+83 -2
View File
@@ -14,7 +14,7 @@ from datetime import datetime
from typing import Optional, Dict, Any, List
from backend.config import settings
from backend.exceptions import RateLimitExceededError, InvalidStateTransitionError
from backend.exceptions import RateLimitExceededError, InvalidStateTransitionError, InsufficientCreditsError
from backend.models.job import Job, JobStatus, JobCreate, STATE_TRANSITIONS
from backend.models.worker_log import WorkerLogEntry
from backend.services.firestore_service import FirestoreService
@@ -80,6 +80,18 @@ class JobManager:
limit_value=settings.rate_limit_jobs_per_day
)
# Check credits (skip for admins)
if job_create.user_email and not is_admin:
from backend.services.user_service import get_user_service
user_service = get_user_service()
if not user_service.has_credits(job_create.user_email):
credits_available = user_service.check_credits(job_create.user_email)
raise InsufficientCreditsError(
message="You're out of credits. Buy more to continue creating karaoke videos.",
credits_available=credits_available,
credits_required=1,
)
# Enforce theme requirement - all jobs must have a theme
# This prevents unstyled videos from ever being generated
if not job_create.theme_id:
@@ -130,11 +142,33 @@ class JobManager:
made_for_you=job_create.made_for_you,
customer_email=job_create.customer_email,
customer_notes=job_create.customer_notes,
# Private (non-published) track mode
is_private=job_create.is_private,
)
self.firestore.create_job(job)
logger.info(f"Created new job {job_id} with status PENDING")
# Deduct credit atomically (after job is persisted so we have job_id for transaction record)
if job_create.user_email and not is_admin:
from backend.services.user_service import get_user_service
user_service = get_user_service()
success, _remaining, deduct_msg = user_service.deduct_credit(
job_create.user_email, job_id, reason="job_creation"
)
if not success:
# Deduction failed (e.g., race condition) - delete the job and raise error
logger.error(f"Credit deduction failed for job {job_id}: {deduct_msg}")
try:
self.firestore.delete_job(job_id)
except Exception:
logger.exception(f"Failed to delete job {job_id} after credit deduction failure")
raise InsufficientCreditsError(
message="Failed to deduct credit. Please try again.",
credits_available=0,
credits_required=1,
)
# Record job creation for rate limiting (after successful persistence)
if job_create.user_email:
try:
@@ -210,6 +244,31 @@ class JobManager:
limit=limit
)
def list_jobs_summary(
self,
status: Optional[JobStatus] = None,
exclude_statuses: Optional[List[str]] = None,
environment: Optional[str] = None,
client_id: Optional[str] = None,
created_after: Optional[datetime] = None,
created_before: Optional[datetime] = None,
user_email: Optional[str] = None,
tenant_id: Optional[str] = None,
limit: int = 100,
) -> List[Dict[str, Any]]:
"""List jobs with field projection (summary mode)."""
return self.firestore.list_jobs_summary(
status=status,
exclude_statuses=exclude_statuses,
environment=environment,
client_id=client_id,
created_after=created_after,
created_before=created_before,
user_email=user_email,
tenant_id=tenant_id,
limit=limit,
)
def delete_jobs_by_filter(
self,
environment: Optional[str] = None,
@@ -532,6 +591,7 @@ class JobManager:
youtube_url=youtube_url,
dropbox_url=dropbox_url,
brand_code=brand_code,
is_private=getattr(job, 'is_private', False),
)
# Try to get existing event loop, create new one if none exists
@@ -755,11 +815,32 @@ class JobManager:
)
logger.error(f"Job {job_id} failed: {error_message}")
# Auto-refund credit on failure (skip for admin-owned jobs)
try:
job = self.get_job(job_id)
if job and job.user_email:
from backend.services.auth_service import is_admin_email
from backend.services.user_service import get_user_service
if not is_admin_email(job.user_email):
user_service = get_user_service()
refund_ok, new_balance, refund_msg = user_service.refund_credit(
job.user_email, job_id, reason="job_failed"
)
if refund_ok:
logger.info(f"Refunded credit for failed job {job_id} to {_mask_email(job.user_email)} (balance: {new_balance})")
else:
logger.warning(f"Credit refund failed for job {job_id}: {refund_msg}")
except Exception as refund_err:
# Don't fail the fail_job call if refund fails
logger.warning(f"Error refunding credit for job {job_id}: {refund_err}")
return True
except Exception as e:
logger.error(f"Error marking job {job_id} as failed: {e}")
return False
def update_file_url(self, job_id: str, category: str, file_type: str, url: str) -> None:
"""
Update a file URL in the job's file_urls structure.
@@ -71,6 +71,7 @@ class JobNotificationService:
youtube_url: Optional[str] = None,
dropbox_url: Optional[str] = None,
brand_code: Optional[str] = None,
is_private: bool = False,
) -> bool:
"""
Send job completion email to user.
@@ -84,6 +85,7 @@ class JobNotificationService:
youtube_url: YouTube video URL
dropbox_url: Dropbox folder URL
brand_code: Release ID (e.g., "NOMAD-1178")
is_private: If True, omit YouTube section (private/non-published tracks)
Returns:
True if email was sent successfully
@@ -106,6 +108,7 @@ class JobNotificationService:
title=title,
job_id=job_id,
feedback_url=FEEDBACK_FORM_URL,
is_private=is_private,
)
# Send the email with CC to admin
@@ -218,6 +221,7 @@ class JobNotificationService:
title: Optional[str] = None,
youtube_url: Optional[str] = None,
dropbox_url: Optional[str] = None,
is_private: bool = False,
) -> str:
"""
Get the rendered completion message for a job (for admin copy functionality).
@@ -229,6 +233,7 @@ class JobNotificationService:
title: Song title
youtube_url: YouTube video URL
dropbox_url: Dropbox folder URL
is_private: If True, omit YouTube section (private/non-published tracks)
Returns:
Rendered message content as plain text
@@ -241,6 +246,7 @@ class JobNotificationService:
title=title,
job_id=job_id,
feedback_url=FEEDBACK_FORM_URL,
is_private=is_private,
)
+11
View File
@@ -212,6 +212,7 @@ class TemplateService:
title: Optional[str] = None,
job_id: Optional[str] = None,
feedback_url: Optional[str] = None,
is_private: bool = False,
) -> str:
"""
Render the job completion email template.
@@ -224,11 +225,21 @@ class TemplateService:
title: Song title
job_id: Job ID
feedback_url: Feedback form URL (optional)
is_private: If True, remove YouTube section entirely (private/non-published tracks)
Returns:
Rendered email content
"""
template = self.get_job_completion_template()
# For private tracks, remove the YouTube section entirely
if is_private:
template = re.sub(
r"\n*Here's the link for the karaoke video published to YouTube:\n\{youtube_url\}\n*",
'\n',
template,
)
variables = {
"name": name or "there",
"youtube_url": youtube_url or "[YouTube URL not available]",
+1 -1
View File
@@ -48,7 +48,7 @@ class UserService:
"""Service for user management and authentication."""
# Number of free credits granted to new users
NEW_USER_FREE_CREDITS = 1
NEW_USER_FREE_CREDITS = 2
def __init__(self):
"""Initialize user service with Firestore client."""
+12 -12
View File
@@ -75,7 +75,7 @@ class TestAudioSearchYouTubeFlow:
}
# Import the route function
from backend.api.routes.audio_search import _download_and_start_processing
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
# Patch dependencies
with patch(
@@ -87,20 +87,19 @@ class TestAudioSearchYouTubeFlow:
), patch(
'backend.api.routes.audio_search.storage_service',
mock_services['storage_service']
), patch(
'backend.api.routes.audio_search.worker_service',
mock_services['worker_service']
):
# Create a mock audio_search_service
mock_audio_search_service = MagicMock()
mock_audio_search_service.is_remote_enabled = MagicMock(return_value=True)
# Create a mock background_tasks
mock_background_tasks = MagicMock()
# Call the download function
result = await _download_and_start_processing(
# 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,
audio_search_service=mock_audio_search_service,
background_tasks=mock_background_tasks,
)
# Verify YouTubeDownloadService was used
@@ -131,7 +130,7 @@ class TestAudioSearchYouTubeFlow:
'audio_search_count': 1,
}
from backend.api.routes.audio_search import _download_and_start_processing
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
# Mock audio_search_service for torrent download
mock_audio_search_service = MagicMock()
@@ -149,14 +148,15 @@ class TestAudioSearchYouTubeFlow:
), patch(
'backend.api.routes.audio_search.storage_service',
mock_services['storage_service']
), patch(
'backend.api.routes.audio_search.worker_service',
mock_services['worker_service']
):
mock_background_tasks = MagicMock()
result = await _download_and_start_processing(
# 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,
audio_search_service=mock_audio_search_service,
background_tasks=mock_background_tasks,
)
# YouTubeDownloadService should NOT be called for torrent
+265 -77
View File
@@ -1140,37 +1140,48 @@ class TestFlacfetchIntegration:
class TestAudioSearchApiRouteDownload:
"""
Tests for _download_and_start_processing function in audio_search routes.
Tests for audio search download functions in audio_search routes.
This tests the API layer's handling of the download flow, including:
- Correct routing between local and remote downloads
- GCS path handling for remote downloads
- Error handling
- Background task scheduling (select endpoint returns immediately)
"""
@pytest.fixture
def mock_job_manager(self):
"""Mock the job manager singleton."""
with patch('backend.api.routes.audio_search.job_manager') as mock:
yield mock
@pytest.fixture
def mock_storage_service(self):
"""Mock the storage service singleton."""
with patch('backend.api.routes.audio_search.storage_service') as mock:
yield mock
def test_remote_download_passes_gcs_path(self, mock_job_manager, mock_storage_service):
@pytest.fixture
def mock_worker_service(self):
"""Mock the worker service."""
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_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.
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.
"""
from backend.api.routes.audio_search import _download_and_start_processing
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
# Setup mock job with RED search result
mock_job = Mock()
mock_job.state_data = {
@@ -1184,49 +1195,45 @@ class TestAudioSearchApiRouteDownload:
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
# Create mock background tasks
mock_bg_tasks = Mock()
# Run the async function
loop = asyncio.new_event_loop()
try:
result = loop.run_until_complete(
_download_and_start_processing(
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job123",
selection_index=0,
audio_search_service=mock_audio_service,
background_tasks=mock_bg_tasks,
)
)
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
assert call_kwargs['gcs_path'] == "uploads/job123/audio/"
def test_youtube_remote_download_uses_youtube_service(self, mock_job_manager, mock_storage_service):
def test_youtube_remote_download_uses_youtube_service(self, mock_job_manager, mock_storage_service, mock_worker_service):
"""
Test that YouTube downloads use YouTubeDownloadService.
After the consolidation refactor, all YouTube downloads go through
YouTubeDownloadService instead of audio_search_service.download_by_id().
"""
from backend.api.routes.audio_search import _download_and_start_processing
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
# Setup mock job with YouTube search result that has source_id
@@ -1237,7 +1244,7 @@ class TestAudioSearchApiRouteDownload:
'artist': 'Kenny Chesney',
'provider': 'YouTube',
'quality': 'Opus 128kbps',
'source_id': 'qmTjyGH9ro4', # YouTube video ID (11 chars)
'source_id': 'qmTjyGH9ro4',
'url': 'https://www.youtube.com/watch?v=qmTjyGH9ro4',
}]
}
@@ -1256,20 +1263,15 @@ class TestAudioSearchApiRouteDownload:
)
mock_youtube_service._extract_video_id = Mock(return_value="qmTjyGH9ro4")
# Create mock background tasks
mock_bg_tasks = Mock()
# Patch get_youtube_download_service to return our mock
with patch('backend.api.routes.audio_search.get_youtube_download_service', return_value=mock_youtube_service):
# Run the async function
loop = asyncio.new_event_loop()
try:
result = loop.run_until_complete(
_download_and_start_processing(
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job456",
selection_index=0,
audio_search_service=mock_audio_service,
background_tasks=mock_bg_tasks,
)
)
finally:
@@ -1288,12 +1290,12 @@ class TestAudioSearchApiRouteDownload:
# audio_search_service.download_by_id should NOT be called for YouTube
mock_audio_service.download_by_id.assert_not_called()
def test_youtube_download_always_uses_youtube_service(self, mock_job_manager, mock_storage_service):
def test_youtube_download_always_uses_youtube_service(self, mock_job_manager, mock_storage_service, mock_worker_service):
"""
Test that YouTube downloads always use YouTubeDownloadService,
regardless of remote enabled status. The service handles fallback internally.
"""
from backend.api.routes.audio_search import _download_and_start_processing
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
# Setup mock job with YouTube search result (use valid 11-char video ID)
@@ -1304,7 +1306,7 @@ class TestAudioSearchApiRouteDownload:
'artist': 'Avril Lavigne',
'provider': 'YouTube',
'quality': 'Opus 128kbps',
'source_id': 'abc123xyz45', # Valid 11-char ID
'source_id': 'abc123xyz45',
'url': 'https://www.youtube.com/watch?v=abc123xyz45',
}]
}
@@ -1323,20 +1325,15 @@ class TestAudioSearchApiRouteDownload:
)
mock_youtube_service._extract_video_id = Mock(return_value="abc123xyz45")
# Create mock background tasks
mock_bg_tasks = Mock()
# Patch get_youtube_download_service to return our mock
with patch('backend.api.routes.audio_search.get_youtube_download_service', return_value=mock_youtube_service):
# Run the async function
loop = asyncio.new_event_loop()
try:
result = loop.run_until_complete(
_download_and_start_processing(
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job789",
selection_index=0,
audio_search_service=mock_audio_service,
background_tasks=mock_bg_tasks,
)
)
finally:
@@ -1344,12 +1341,12 @@ class TestAudioSearchApiRouteDownload:
# YouTubeDownloadService.download_by_id should always be called for YouTube
mock_youtube_service.download_by_id.assert_called_once()
def test_handles_gcs_path_response_correctly(self, mock_job_manager, mock_storage_service):
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."""
from backend.api.routes.audio_search import _download_and_start_processing
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
# Setup mock job with RED search result
mock_job = Mock()
mock_job.state_data = {
@@ -1361,33 +1358,32 @@ class TestAudioSearchApiRouteDownload:
}]
}
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
# Run the async function
loop = asyncio.new_event_loop()
try:
result = loop.run_until_complete(
_download_and_start_processing(
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job789",
selection_index=0,
audio_search_service=mock_audio_service,
background_tasks=Mock(),
)
)
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
# Find the call that sets input_media_gcs_path
gcs_path_set = False
for call in update_calls:
@@ -1397,24 +1393,17 @@ class TestAudioSearchApiRouteDownload:
assert gcs_path == "uploads/job789/audio/test.flac"
gcs_path_set = True
break
assert gcs_path_set, "input_media_gcs_path was not set in job update"
def test_torrent_download_requires_remote(self, mock_job_manager, mock_storage_service):
"""
Test that torrent sources (RED/OPS) require remote flacfetch.
Torrent downloads can only happen on the flacfetch VM which has:
- BitTorrent peer connectivity
- Private tracker credentials
- Long-running seeding capability
Cloud Run cannot download torrents, so remote must be enabled.
When running as a background task, the error is caught and the job is failed.
"""
from backend.api.routes.audio_search import _download_and_start_processing
from backend.services.audio_search_service import DownloadError
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
import pytest
# Setup mock job with RED search result
mock_job = Mock()
@@ -1422,7 +1411,7 @@ class TestAudioSearchApiRouteDownload:
'audio_search_results': [{
'title': 'Test',
'artist': 'Test',
'provider': 'RED', # Torrent source requires remote
'provider': 'RED',
'quality': 'FLAC',
}]
}
@@ -1430,21 +1419,220 @@ class TestAudioSearchApiRouteDownload:
# Create mock audio search service WITHOUT remote client
mock_audio_service = Mock()
mock_audio_service.is_remote_enabled.return_value = False # REMOTE DISABLED
mock_audio_service.is_remote_enabled.return_value = False
loop = asyncio.new_event_loop()
try:
# Should raise an error because RED requires remote
with pytest.raises(Exception) as exc_info:
loop.run_until_complete(
_download_and_start_processing(
job_id="job_no_remote",
selection_index=0,
audio_search_service=mock_audio_service,
background_tasks=Mock(),
)
# 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,
)
# Verify the error message mentions remote flacfetch
assert "remote flacfetch" in str(exc_info.value).lower() or "flacfetch" in str(exc_info.value).lower()
)
finally:
loop.close()
# Verify the job was failed with an appropriate error message
mock_job_manager.fail_job.assert_called_once()
fail_args = mock_job_manager.fail_job.call_args
assert fail_args.args[0] == "job_no_remote"
assert "remote flacfetch" in fail_args.args[1].lower() or "flacfetch" in fail_args.args[1].lower()
def test_validate_and_prepare_selection(self, mock_job_manager, mock_storage_service):
"""
Test that _validate_and_prepare_selection transitions job state and returns
selection info without performing the download.
"""
from backend.api.routes.audio_search import _validate_and_prepare_selection
# Setup mock job
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Waterloo',
'artist': 'ABBA',
'provider': 'RED',
'quality': 'FLAC',
'source_id': 'abc123',
'target_file': 'Waterloo.flac',
'url': '',
}]
}
mock_job_manager.get_job.return_value = mock_job
result = _validate_and_prepare_selection(
job_id="job_test",
selection_index=0,
)
# Should return selection info
assert result['selected_index'] == 0
assert result['selected_title'] == 'Waterloo'
assert result['selected_artist'] == 'ABBA'
assert result['selected_provider'] == 'RED'
# Should transition to DOWNLOADING_AUDIO
mock_job_manager.transition_to_state.assert_called_once()
call_kwargs = mock_job_manager.transition_to_state.call_args.kwargs
assert call_kwargs['new_status'] == JobStatus.DOWNLOADING_AUDIO
# Should save download params
mock_job_manager.update_job.assert_called_once()
update_data = mock_job_manager.update_job.call_args.args[1]
assert update_data['audio_source_type'] == 'audio_search'
assert update_data['source_name'] == 'RED'
def test_validate_and_prepare_selection_invalid_index(self, mock_job_manager, mock_storage_service):
"""Test _validate_and_prepare_selection raises HTTPException for invalid index."""
from backend.api.routes.audio_search import _validate_and_prepare_selection
from fastapi import HTTPException
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{'title': 'Song', 'artist': 'Artist', 'provider': 'RED'}]
}
mock_job_manager.get_job.return_value = mock_job
with pytest.raises(HTTPException) as exc_info:
_validate_and_prepare_selection(job_id="job_test", selection_index=99)
assert exc_info.value.status_code == 400
assert "Invalid selection index" in exc_info.value.detail
def test_validate_and_prepare_selection_job_not_found(self, mock_job_manager, mock_storage_service):
"""Test _validate_and_prepare_selection raises HTTPException when job not found."""
from backend.api.routes.audio_search import _validate_and_prepare_selection
from fastapi import HTTPException
mock_job_manager.get_job.return_value = None
with pytest.raises(HTTPException) as exc_info:
_validate_and_prepare_selection(job_id="nonexistent", selection_index=0)
assert exc_info.value.status_code == 404
def test_validate_and_prepare_selection_no_results(self, mock_job_manager, mock_storage_service):
"""Test _validate_and_prepare_selection raises HTTPException when no search results."""
from backend.api.routes.audio_search import _validate_and_prepare_selection
from fastapi import HTTPException
mock_job = Mock()
mock_job.state_data = {'audio_search_results': []}
mock_job_manager.get_job.return_value = mock_job
with pytest.raises(HTTPException) as exc_info:
_validate_and_prepare_selection(job_id="job_test", selection_index=0)
assert exc_info.value.status_code == 400
assert "No search results" in exc_info.value.detail
def test_download_background_job_not_found(self, mock_job_manager, mock_storage_service):
"""Test _download_audio_and_trigger_workers handles missing job gracefully."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
mock_job_manager.get_job.return_value = None
mock_audio_service = Mock()
loop = asyncio.new_event_loop()
try:
# Should not raise - background tasks must handle errors gracefully
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="gone",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
# Should not try to fail a non-existent job
mock_job_manager.fail_job.assert_not_called()
def test_download_triggers_workers_on_success(self, mock_job_manager, mock_storage_service, mock_worker_service):
"""Test that _download_audio_and_trigger_workers triggers both workers after download."""
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',
}]
}
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,
)
)
finally:
loop.close()
# Both workers should be triggered
mock_worker_service.trigger_audio_worker.assert_called_once_with("job_w")
mock_worker_service.trigger_lyrics_worker.assert_called_once_with("job_w")
# Job should transition to DOWNLOADING
transition_calls = mock_job_manager.transition_to_state.call_args_list
assert any(
c.kwargs.get('new_status') == JobStatus.DOWNLOADING
for c in transition_calls
), "Job should transition to DOWNLOADING status"
def test_download_generic_exception_fails_job(self, mock_job_manager, mock_storage_service):
"""Test that generic exceptions in background download fail the job gracefully."""
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',
}]
}
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,
)
)
finally:
loop.close()
# Job should be failed with error message
mock_job_manager.fail_job.assert_called_once()
fail_args = mock_job_manager.fail_job.call_args
assert fail_args.args[0] == "job_err"
assert "Unexpected connection error" in fail_args.args[1]
@@ -0,0 +1,396 @@
"""
Tests for audio_transcoding_service.py - Review audio transcoding to OGG Opus.
These tests mock StorageService and subprocess to verify:
- Cache path derivation for various GCS paths
- Cache hit path (no ffmpeg call)
- Cache miss with successful transcode
- Fallback to FLAC on transcoding failure
- Bulk prepare_review_audio_for_job transcodes all expected files
"""
import pytest
from unittest.mock import Mock, patch, call, ANY
class TestGetCachePath:
"""Test _get_cache_path() derivation logic."""
def _make_service(self):
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
return AudioTranscodingService(storage_service=mock_storage)
def test_input_audio_path(self):
service = self._make_service()
result = service._get_cache_path("jobs/abc123/input/song.flac")
assert result == "jobs/abc123/review-audio/song.ogg"
def test_stem_path(self):
service = self._make_service()
result = service._get_cache_path("jobs/abc123/stems/instrumental_clean.flac")
assert result == "jobs/abc123/review-audio/instrumental_clean.ogg"
def test_backing_vocals_path(self):
service = self._make_service()
result = service._get_cache_path("jobs/abc123/stems/backing_vocals.flac")
assert result == "jobs/abc123/review-audio/backing_vocals.ogg"
def test_nested_job_path(self):
service = self._make_service()
result = service._get_cache_path("jobs/4bed6f80/stems/instrumental_with_backing.flac")
assert result == "jobs/4bed6f80/review-audio/instrumental_with_backing.ogg"
def test_wav_extension(self):
service = self._make_service()
result = service._get_cache_path("jobs/abc123/input/song.wav")
assert result == "jobs/abc123/review-audio/song.ogg"
def test_no_jobs_prefix_fallback_uses_hash(self):
service = self._make_service()
result = service._get_cache_path("other/path/audio.flac")
# Should use a hash-based fallback, not a literal "_unknown"
assert result.startswith("jobs/_")
assert result.endswith("/review-audio/audio.ogg")
assert len(result.split("/")[1]) == 13 # "_" + 12-char hash
def test_no_jobs_prefix_different_paths_different_hashes(self):
service = self._make_service()
result1 = service._get_cache_path("other/path/audio.flac")
result2 = service._get_cache_path("another/path/audio.flac")
# Different source paths should produce different cache paths
assert result1 != result2
class TestTranscodeIfNeeded:
"""Test transcode_if_needed() cache hit/miss logic."""
@patch("backend.services.audio_transcoding_service.subprocess")
def test_cache_hit_skips_transcode(self, mock_subprocess):
"""When cached file exists, return it without transcoding."""
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
mock_storage.file_exists.return_value = True
service = AudioTranscodingService(storage_service=mock_storage)
result = service.transcode_if_needed("jobs/abc/input/song.flac")
assert result == "jobs/abc/review-audio/song.ogg"
mock_storage.file_exists.assert_called_once_with("jobs/abc/review-audio/song.ogg")
mock_subprocess.run.assert_not_called()
mock_storage.download_file.assert_not_called()
@patch("backend.services.audio_transcoding_service.subprocess")
def test_cache_miss_transcodes_and_uploads(self, mock_subprocess):
"""When cached file is missing, download + transcode + upload."""
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
mock_storage.file_exists.return_value = False
mock_subprocess.run.return_value = Mock(returncode=0, stderr="")
service = AudioTranscodingService(storage_service=mock_storage)
result = service.transcode_if_needed("jobs/abc/input/song.flac")
assert result == "jobs/abc/review-audio/song.ogg"
# Verify download from correct source path
download_args = mock_storage.download_file.call_args[0]
assert download_args[0] == "jobs/abc/input/song.flac"
# Verify ffmpeg command
mock_subprocess.run.assert_called_once()
ffmpeg_call = mock_subprocess.run.call_args
ffmpeg_cmd = ffmpeg_call[0][0]
assert "ffmpeg" in ffmpeg_cmd[0]
assert "libopus" in ffmpeg_cmd
assert "128k" in ffmpeg_cmd
assert "-vn" in ffmpeg_cmd
# Verify timeout is set
assert ffmpeg_call[1]["timeout"] == 120
# Verify upload to correct cache path
upload_args = mock_storage.upload_file.call_args[0]
assert upload_args[1] == "jobs/abc/review-audio/song.ogg"
class TestGetReviewAudioUrl:
"""Test get_review_audio_url() with fallback behavior."""
@patch("backend.services.audio_transcoding_service.subprocess")
def test_returns_transcoded_url_on_success(self, mock_subprocess):
"""On success, return signed URL for transcoded file."""
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
mock_storage.file_exists.return_value = True
mock_storage.generate_signed_url.return_value = "https://signed-url/song.ogg"
service = AudioTranscodingService(storage_service=mock_storage)
result = service.get_review_audio_url("jobs/abc/input/song.flac")
assert result == "https://signed-url/song.ogg"
mock_storage.generate_signed_url.assert_called_once_with(
"jobs/abc/review-audio/song.ogg", 120
)
def test_falls_back_to_flac_on_error(self):
"""On transcoding error with no cache, fall back to original FLAC signed URL."""
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
mock_storage.file_exists.return_value = False
mock_storage.download_file.side_effect = Exception("GCS download failed")
mock_storage.generate_signed_url.return_value = "https://signed-url/song.flac"
service = AudioTranscodingService(storage_service=mock_storage)
result = service.get_review_audio_url("jobs/abc/input/song.flac")
assert result == "https://signed-url/song.flac"
mock_storage.generate_signed_url.assert_called_once_with(
"jobs/abc/input/song.flac", 120
)
# file_exists called twice: once in transcode_if_needed (cache miss),
# once in fallback (cache still missing → fall through to FLAC)
assert mock_storage.file_exists.call_count == 2
def test_serves_cache_when_source_deleted(self):
"""When source is deleted but OGG cache exists, serve the cache."""
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
# First file_exists (in transcode_if_needed): cache miss
# download_file fails: source deleted
# Second file_exists (in fallback): cache found
mock_storage.file_exists.side_effect = [False, True]
mock_storage.download_file.side_effect = Exception("blob not found")
mock_storage.generate_signed_url.return_value = "https://signed-url/song.ogg"
service = AudioTranscodingService(storage_service=mock_storage)
result = service.get_review_audio_url("jobs/abc/input/song.flac")
assert result == "https://signed-url/song.ogg"
mock_storage.generate_signed_url.assert_called_once_with(
"jobs/abc/review-audio/song.ogg", 120
)
def test_falls_back_to_flac_when_cache_check_also_fails(self):
"""When source is deleted and file_exists() also throws, fall back to FLAC."""
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
# First file_exists (in transcode_if_needed): cache miss
# download_file fails: source deleted
# Second file_exists (in fallback): also throws
mock_storage.file_exists.side_effect = [False, Exception("GCS unavailable")]
mock_storage.download_file.side_effect = Exception("blob not found")
mock_storage.generate_signed_url.return_value = "https://signed-url/song.flac"
service = AudioTranscodingService(storage_service=mock_storage)
result = service.get_review_audio_url("jobs/abc/input/song.flac")
assert result == "https://signed-url/song.flac"
mock_storage.generate_signed_url.assert_called_once_with(
"jobs/abc/input/song.flac", 120
)
@patch("backend.services.audio_transcoding_service.subprocess")
def test_custom_expiration_minutes(self, mock_subprocess):
"""Custom expiration_minutes is passed through to generate_signed_url."""
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
mock_storage.file_exists.return_value = True
mock_storage.generate_signed_url.return_value = "https://signed-url/song.ogg"
service = AudioTranscodingService(storage_service=mock_storage)
service.get_review_audio_url("jobs/abc/input/song.flac", expiration_minutes=60)
mock_storage.generate_signed_url.assert_called_once_with(
"jobs/abc/review-audio/song.ogg", 60
)
@patch("backend.services.audio_transcoding_service.subprocess")
def test_falls_back_on_ffmpeg_failure(self, mock_subprocess):
"""On ffmpeg failure, fall back to original FLAC signed URL."""
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
mock_storage.file_exists.return_value = False
mock_subprocess.run.return_value = Mock(returncode=1, stderr="codec error")
service = AudioTranscodingService(storage_service=mock_storage)
result = service.get_review_audio_url("jobs/abc/input/song.flac")
# Should fall back to FLAC URL
mock_storage.generate_signed_url.assert_called_once_with(
"jobs/abc/input/song.flac", 120
)
class TestPrepareReviewAudioForJob:
"""Test prepare_review_audio_for_job() bulk transcoding."""
@patch("backend.services.audio_transcoding_service.subprocess")
def test_transcodes_all_expected_files(self, mock_subprocess):
"""Should transcode input + all stems and return correct cache paths."""
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
mock_storage.file_exists.return_value = True # All cache hits
service = AudioTranscodingService(storage_service=mock_storage)
mock_job = Mock()
mock_job.job_id = "abc123"
mock_job.input_media_gcs_path = "jobs/abc123/input/song.flac"
mock_job.file_urls = {
"stems": {
"instrumental_clean": "jobs/abc123/stems/instrumental_clean.flac",
"instrumental_with_backing": "jobs/abc123/stems/instrumental_with_backing.flac",
"backing_vocals": "jobs/abc123/stems/backing_vocals.flac",
}
}
result = service.prepare_review_audio_for_job(mock_job)
assert len(result) == 4
assert "jobs/abc123/review-audio/song.ogg" in result
assert "jobs/abc123/review-audio/instrumental_clean.ogg" in result
assert "jobs/abc123/review-audio/instrumental_with_backing.ogg" in result
assert "jobs/abc123/review-audio/backing_vocals.ogg" in result
assert mock_storage.file_exists.call_count == 4
# No ffmpeg calls since all are cache hits
mock_subprocess.run.assert_not_called()
@patch("backend.services.audio_transcoding_service.subprocess")
def test_continues_on_individual_failure(self, mock_subprocess):
"""If one file fails to transcode, others should still succeed."""
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
# First call (input): cache miss + download fails
# Subsequent calls: cache hits
mock_storage.file_exists.side_effect = [False, True, True, True]
mock_storage.download_file.side_effect = Exception("download failed")
service = AudioTranscodingService(storage_service=mock_storage)
mock_job = Mock()
mock_job.job_id = "abc123"
mock_job.input_media_gcs_path = "jobs/abc123/input/song.flac"
mock_job.file_urls = {
"stems": {
"instrumental_clean": "jobs/abc123/stems/instrumental_clean.flac",
"instrumental_with_backing": "jobs/abc123/stems/instrumental_with_backing.flac",
"backing_vocals": "jobs/abc123/stems/backing_vocals.flac",
}
}
result = service.prepare_review_audio_for_job(mock_job)
# 3 out of 4 succeeded (the 3 cache hits)
assert len(result) == 3
@patch("backend.services.audio_transcoding_service.subprocess")
def test_handles_missing_stems(self, mock_subprocess):
"""Should handle jobs with missing stem paths gracefully."""
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
mock_storage.file_exists.return_value = True
service = AudioTranscodingService(storage_service=mock_storage)
mock_job = Mock()
mock_job.job_id = "abc123"
mock_job.input_media_gcs_path = "jobs/abc123/input/song.flac"
mock_job.file_urls = {"stems": {}} # No stems
result = service.prepare_review_audio_for_job(mock_job)
# Only the input audio
assert len(result) == 1
@patch("backend.services.audio_transcoding_service.subprocess")
def test_handles_no_input_audio(self, mock_subprocess):
"""Should handle jobs with no input_media_gcs_path."""
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
mock_storage.file_exists.return_value = True
service = AudioTranscodingService(storage_service=mock_storage)
mock_job = Mock()
mock_job.job_id = "abc123"
mock_job.input_media_gcs_path = None
mock_job.file_urls = {
"stems": {
"instrumental_clean": "jobs/abc123/stems/instrumental_clean.flac",
}
}
result = service.prepare_review_audio_for_job(mock_job)
assert len(result) == 1
@patch("backend.services.audio_transcoding_service.subprocess")
def test_handles_no_stems_key(self, mock_subprocess):
"""Should handle jobs where file_urls has no stems key at all."""
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
mock_storage.file_exists.return_value = True
service = AudioTranscodingService(storage_service=mock_storage)
mock_job = Mock()
mock_job.job_id = "abc123"
mock_job.input_media_gcs_path = "jobs/abc123/input/song.flac"
mock_job.file_urls = {} # No stems key
result = service.prepare_review_audio_for_job(mock_job)
assert len(result) == 1
assert result[0] == "jobs/abc123/review-audio/song.ogg"
class TestInit:
"""Test AudioTranscodingService initialization."""
@patch("backend.services.audio_transcoding_service.StorageService")
def test_creates_default_storage_service(self, mock_storage_class):
"""Creates a StorageService when none is provided."""
from backend.services.audio_transcoding_service import AudioTranscodingService
service = AudioTranscodingService()
mock_storage_class.assert_called_once()
assert service.storage is mock_storage_class.return_value
def test_uses_provided_storage_service(self):
"""Uses the provided storage service instead of creating one."""
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
service = AudioTranscodingService(storage_service=mock_storage)
assert service.storage is mock_storage
class TestGetReviewAudioUrlAsync:
"""Test async wrapper."""
@pytest.mark.asyncio
@patch("backend.services.audio_transcoding_service.subprocess")
async def test_async_wrapper_delegates(self, mock_subprocess):
"""Async wrapper should call sync method via to_thread."""
from backend.services.audio_transcoding_service import AudioTranscodingService
mock_storage = Mock()
mock_storage.file_exists.return_value = True
mock_storage.generate_signed_url.return_value = "https://signed/url"
service = AudioTranscodingService(storage_service=mock_storage)
result = await service.get_review_audio_url_async("jobs/abc/input/song.flac")
assert result == "https://signed/url"
+148
View File
@@ -0,0 +1,148 @@
"""
Tests for download_audio() upload persistence in audio_worker.py.
Verifies that uploaded files (uploads/ prefix) are copied to jobs/ prefix
so they survive the 7-day GCS lifecycle rule on uploads/.
"""
import os
import pytest
from unittest.mock import Mock, patch, AsyncMock
@pytest.mark.asyncio
@patch("backend.workers.audio_worker.JobManager")
async def test_upload_persisted_to_jobs_prefix(MockJobManager):
"""Uploaded audio (uploads/ prefix) should be copied to jobs/{id}/input/."""
from backend.workers.audio_worker import download_audio
mock_storage = Mock()
mock_jm = Mock()
mock_job = Mock()
mock_job.input_media_gcs_path = "uploads/abc123/audio/My Song.flac"
mock_job.filename = "My Song.flac"
mock_job.url = None
mock_job.file_urls = {}
result = await download_audio(
job_id="abc123",
temp_dir="/tmp/test",
storage=mock_storage,
job=mock_job,
job_manager_instance=mock_jm,
)
# Should download from original upload path
mock_storage.download_file.assert_called_once_with(
"uploads/abc123/audio/My Song.flac", os.path.join("/tmp/test", "My Song.flac")
)
# Should re-upload to persistent jobs/ path
mock_storage.upload_file.assert_called_once_with(
os.path.join("/tmp/test", "My Song.flac"),
"jobs/abc123/input/My Song.flac",
)
# Should update job metadata
mock_jm.update_job.assert_called_once_with(
"abc123", {"input_media_gcs_path": "jobs/abc123/input/My Song.flac"}
)
mock_jm.update_file_url.assert_called_once_with(
"abc123", "input", "audio", "jobs/abc123/input/My Song.flac"
)
assert result == os.path.join("/tmp/test", "My Song.flac")
@pytest.mark.asyncio
@patch("backend.workers.audio_worker.JobManager")
async def test_jobs_prefix_not_re_persisted(MockJobManager):
"""Files already in jobs/ prefix should NOT be re-uploaded."""
from backend.workers.audio_worker import download_audio
mock_storage = Mock()
mock_jm = Mock()
mock_job = Mock()
mock_job.input_media_gcs_path = "jobs/abc123/input/song.flac"
mock_job.filename = "song.flac"
mock_job.url = None
mock_job.file_urls = {}
result = await download_audio(
job_id="abc123",
temp_dir="/tmp/test",
storage=mock_storage,
job=mock_job,
job_manager_instance=mock_jm,
)
# Should download but NOT re-upload
mock_storage.download_file.assert_called_once()
mock_storage.upload_file.assert_not_called()
mock_jm.update_job.assert_not_called()
@pytest.mark.asyncio
@patch("backend.workers.audio_worker.JobManager")
async def test_upload_persistence_creates_job_manager_if_none(MockJobManager):
"""If no job_manager_instance provided, creates one for persistence."""
from backend.workers.audio_worker import download_audio
mock_storage = Mock()
mock_jm_instance = Mock()
MockJobManager.return_value = mock_jm_instance
mock_job = Mock()
mock_job.input_media_gcs_path = "uploads/def456/audio/track.flac"
mock_job.filename = "track.flac"
mock_job.url = None
mock_job.file_urls = {}
await download_audio(
job_id="def456",
temp_dir="/tmp/test",
storage=mock_storage,
job=mock_job,
job_manager_instance=None,
)
# Should have created a JobManager
MockJobManager.assert_called_once()
# Should use the created instance
mock_jm_instance.update_job.assert_called_once()
mock_jm_instance.update_file_url.assert_called_once()
@pytest.mark.asyncio
@patch("backend.workers.audio_worker.JobManager")
async def test_persistence_failure_does_not_block_download(MockJobManager):
"""If upload_file fails during persistence, download still succeeds."""
from backend.workers.audio_worker import download_audio
mock_storage = Mock()
mock_storage.upload_file.side_effect = Exception("GCS upload failed")
mock_jm = Mock()
mock_job = Mock()
mock_job.input_media_gcs_path = "uploads/abc123/audio/song.flac"
mock_job.filename = "song.flac"
mock_job.url = None
mock_job.file_urls = {}
result = await download_audio(
job_id="abc123",
temp_dir="/tmp/test",
storage=mock_storage,
job=mock_job,
job_manager_instance=mock_jm,
)
# Download succeeded despite persistence failure
assert result == os.path.join("/tmp/test", "song.flac")
mock_storage.download_file.assert_called_once()
# upload_file was attempted but failed
mock_storage.upload_file.assert_called_once()
# Metadata update should NOT have been called (upload failed first)
mock_jm.update_job.assert_not_called()
+29
View File
@@ -32,6 +32,35 @@ class TestAuthServiceBasics:
assert hasattr(AuthService, 'validate_token') or hasattr(AuthService, 'verify_token')
class TestIncrementTokenUsage:
"""Tests for increment_token_usage after credit deduction cleanup."""
def test_session_token_does_not_deduct_credits(self):
"""
Verify that increment_token_usage does NOT deduct credits for session tokens.
Credit deduction is handled by JobManager.create_job(), not here.
This test ensures the dead code removal didn't break the method.
"""
mock_firestore = MagicMock()
# Session token: not in admin_tokens, not in Firestore auth_tokens
mock_firestore.get_token.return_value = None
with patch('backend.services.auth_service.FirestoreService', return_value=mock_firestore), \
patch.dict('os.environ', {'ADMIN_TOKENS': 'admin-token'}):
from backend.services.auth_service import AuthService
service = AuthService()
# Mock validate_token to return valid session user
with patch.object(service, 'validate_token', return_value=(True, 'stripe', 5, 'OK')):
result = service.increment_token_usage("session-token-123", "job-abc")
# Should return True (no-op for session tokens)
assert result is True
# Should NOT try to deduct credits via user_service
# (If it did, it would fail since user_service is not mocked)
class TestFirestoreServiceBasics:
"""Basic tests for FirestoreService."""
+262
View File
@@ -0,0 +1,262 @@
"""
Tests for credit enforcement in job creation and failure flows.
Verifies that:
- Job creation requires credits (unless admin)
- Credits are deducted on job creation
- Credits are refunded on job failure
- New users get 2 welcome credits
"""
import pytest
from unittest.mock import Mock, MagicMock, patch
from datetime import datetime
# Mock Firestore before importing modules that use it
import sys
sys.modules.setdefault('google.cloud.firestore', MagicMock())
from backend.services.job_manager import JobManager
from backend.models.job import Job, JobCreate, JobStatus
from backend.exceptions import InsufficientCreditsError
@pytest.fixture
def mock_firestore_service():
"""Mock FirestoreService."""
with patch('backend.services.job_manager.FirestoreService') as mock:
service = Mock()
mock.return_value = service
yield service
@pytest.fixture
def mock_storage_service():
"""Mock StorageService."""
with patch('backend.services.job_manager.StorageService') as mock:
service = Mock()
mock.return_value = service
yield service
@pytest.fixture
def job_manager(mock_firestore_service, mock_storage_service):
"""Create JobManager with mocked dependencies."""
return JobManager()
@pytest.fixture
def mock_user_service():
"""Mock UserService via get_user_service (patched at source module)."""
service = Mock()
with patch('backend.services.user_service.get_user_service', return_value=service):
yield service
@pytest.fixture
def mock_rate_limit_service():
"""Mock rate limit service to always allow."""
service = Mock()
service.check_user_job_limit.return_value = (True, 5, "OK")
service.record_job_creation.return_value = None
with patch('backend.services.rate_limit_service.get_rate_limit_service', return_value=service):
yield service
class TestCreditCheckOnJobCreation:
"""Test credit checks during job creation."""
def test_job_creation_succeeds_with_credits(
self, job_manager, mock_firestore_service, mock_user_service, mock_rate_limit_service
):
"""Job creation succeeds when user has credits, and credit is deducted."""
mock_user_service.has_credits.return_value = True
mock_user_service.deduct_credit.return_value = (True, 4, "Credit deducted. 4 remaining")
job = job_manager.create_job(
JobCreate(artist="Test", title="Song", theme_id="nomad", user_email="user@test.com"),
is_admin=False,
)
assert job.status == JobStatus.PENDING
mock_user_service.has_credits.assert_called_once_with("user@test.com")
mock_user_service.deduct_credit.assert_called_once()
# Verify deduct_credit was called with user email, job_id, and reason
call_args = mock_user_service.deduct_credit.call_args
assert call_args[0][0] == "user@test.com"
def test_job_creation_fails_without_credits(
self, job_manager, mock_firestore_service, mock_user_service, mock_rate_limit_service
):
"""Job creation raises InsufficientCreditsError when user has no credits."""
mock_user_service.has_credits.return_value = False
mock_user_service.check_credits.return_value = 0
with pytest.raises(InsufficientCreditsError) as exc_info:
job_manager.create_job(
JobCreate(artist="Test", title="Song", theme_id="nomad", user_email="broke@test.com"),
is_admin=False,
)
assert exc_info.value.credits_available == 0
assert exc_info.value.credits_required == 1
# Verify Firestore create_job was NOT called (fail-fast before job creation)
mock_firestore_service.create_job.assert_not_called()
def test_admin_bypasses_credit_check(
self, job_manager, mock_firestore_service, mock_user_service, mock_rate_limit_service
):
"""Admin users bypass credit check entirely."""
job = job_manager.create_job(
JobCreate(artist="Test", title="Song", theme_id="nomad", user_email="admin@nomadkaraoke.com"),
is_admin=True,
)
assert job.status == JobStatus.PENDING
mock_user_service.has_credits.assert_not_called()
mock_user_service.deduct_credit.assert_not_called()
def test_job_without_user_email_skips_credit_check(
self, job_manager, mock_firestore_service, mock_user_service, mock_rate_limit_service
):
"""Jobs without user_email (e.g., API token auth) skip credit check."""
job = job_manager.create_job(
JobCreate(artist="Test", title="Song", theme_id="nomad"),
is_admin=False,
)
assert job.status == JobStatus.PENDING
mock_user_service.has_credits.assert_not_called()
def test_deduction_failure_deletes_job_and_raises(
self, job_manager, mock_firestore_service, mock_user_service, mock_rate_limit_service
):
"""If credit deduction fails after job creation, the job is deleted."""
mock_user_service.has_credits.return_value = True
mock_user_service.deduct_credit.return_value = (False, 0, "Insufficient credits")
with pytest.raises(InsufficientCreditsError):
job_manager.create_job(
JobCreate(artist="Test", title="Song", theme_id="nomad", user_email="user@test.com"),
is_admin=False,
)
# Job was created then deleted
mock_firestore_service.create_job.assert_called_once()
mock_firestore_service.delete_job.assert_called_once()
class TestCreditRefundOnJobFailure:
"""Test credit refund when jobs fail."""
def test_credit_refunded_on_job_failure(
self, job_manager, mock_firestore_service, mock_user_service
):
"""Credit is refunded when a non-admin job fails."""
mock_job = Mock(spec=Job)
mock_job.user_email = "user@test.com"
mock_firestore_service.get_job.return_value = mock_job
mock_user_service.refund_credit.return_value = (True, 1, "Refunded")
with patch('backend.services.auth_service.is_admin_email', return_value=False):
result = job_manager.fail_job("job123", "Processing error")
assert result is True
mock_user_service.refund_credit.assert_called_once_with(
"user@test.com", "job123", reason="job_failed"
)
def test_credit_refund_skipped_for_admin_jobs(
self, job_manager, mock_firestore_service, mock_user_service
):
"""Credit refund is skipped for admin-owned jobs."""
mock_job = Mock(spec=Job)
mock_job.user_email = "admin@nomadkaraoke.com"
mock_firestore_service.get_job.return_value = mock_job
with patch('backend.services.auth_service.is_admin_email', return_value=True):
result = job_manager.fail_job("job123", "Processing error")
assert result is True
mock_user_service.refund_credit.assert_not_called()
def test_refund_failure_does_not_fail_job_marking(
self, job_manager, mock_firestore_service, mock_user_service
):
"""If refund fails, the job is still marked as failed."""
mock_job = Mock(spec=Job)
mock_job.user_email = "user@test.com"
mock_firestore_service.get_job.return_value = mock_job
mock_user_service.refund_credit.side_effect = Exception("Firestore error")
with patch('backend.services.auth_service.is_admin_email', return_value=False):
result = job_manager.fail_job("job123", "Processing error")
assert result is True # Job still marked as failed
def test_no_refund_when_job_has_no_user_email(
self, job_manager, mock_firestore_service, mock_user_service
):
"""No refund attempted when job has no user_email."""
mock_job = Mock(spec=Job)
mock_job.user_email = None
mock_firestore_service.get_job.return_value = mock_job
result = job_manager.fail_job("job123", "Processing error")
assert result is True
mock_user_service.refund_credit.assert_not_called()
class TestCreditAndRateLimitOrdering:
"""Test interaction between rate limit and credit checks."""
def test_rate_limited_user_not_charged_credit(
self, job_manager, mock_firestore_service, mock_user_service
):
"""User who is rate limited should NOT have a credit deducted."""
mock_rate_limit_service = Mock()
mock_rate_limit_service.check_user_job_limit.return_value = (False, 0, "Rate limit exceeded")
mock_rate_limit_service.get_user_job_count_today.return_value = 5
with patch('backend.services.rate_limit_service.get_rate_limit_service', return_value=mock_rate_limit_service):
from backend.exceptions import RateLimitExceededError
with pytest.raises(RateLimitExceededError):
job_manager.create_job(
JobCreate(artist="Test", title="Song", theme_id="nomad", user_email="user@test.com"),
is_admin=False,
)
# Credit check should never be called because rate limit fails first
mock_user_service.has_credits.assert_not_called()
mock_user_service.deduct_credit.assert_not_called()
class TestWelcomeCredits:
"""Test new user welcome credits."""
def test_new_user_gets_2_welcome_credits(self):
"""Verify NEW_USER_FREE_CREDITS is set to 2."""
from backend.services.user_service import UserService
assert UserService.NEW_USER_FREE_CREDITS == 2
class TestInsufficientCreditsError:
"""Test the InsufficientCreditsError exception."""
def test_exception_attributes(self):
"""Verify exception stores all attributes."""
err = InsufficientCreditsError(
message="No credits",
credits_available=0,
credits_required=1,
)
assert err.message == "No credits"
assert err.credits_available == 0
assert err.credits_required == 1
assert str(err) == "No credits"
def test_exception_defaults(self):
"""Verify default values."""
err = InsufficientCreditsError(message="Out of credits")
assert err.credits_available == 0
assert err.credits_required == 1
@@ -0,0 +1,450 @@
"""
Unit tests for the create-custom-instrumental endpoint and
reference_lyrics stripping in submit_corrections.
Tests the route logic in backend/api/routes/jobs.py by mocking
the service layer (JobManager, AudioEditingService, StorageService).
"""
import pytest
from datetime import datetime, UTC
from unittest.mock import MagicMock, AsyncMock, patch
from contextlib import ExitStack
from fastapi.testclient import TestClient
from backend.models.job import Job, JobStatus
# --- Fixtures ---
@pytest.fixture
def review_job():
"""Create a job in AWAITING_REVIEW status with stems."""
return Job(
job_id="job-abc",
status=JobStatus.AWAITING_REVIEW,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
user_email="owner@example.com",
file_urls={
"stems": {
"instrumental_clean": "jobs/job-abc/stems/instrumental_clean.flac",
"backing_vocals": "jobs/job-abc/stems/backing_vocals.flac",
}
},
)
@pytest.fixture
def in_review_job():
"""Create a job in IN_REVIEW status with stems."""
return Job(
job_id="job-abc",
status=JobStatus.IN_REVIEW,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
user_email="owner@example.com",
file_urls={
"stems": {
"instrumental_clean": "jobs/job-abc/stems/instrumental_clean.flac",
"backing_vocals": "jobs/job-abc/stems/backing_vocals.flac",
}
},
)
@pytest.fixture
def job_no_stems():
"""Create a job in review state missing stems."""
return Job(
job_id="job-abc",
status=JobStatus.AWAITING_REVIEW,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
file_urls={},
)
@pytest.fixture
def completed_job():
"""Create a job in COMPLETE status."""
return Job(
job_id="job-abc",
status=JobStatus.COMPLETE,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
file_urls={
"stems": {
"instrumental_clean": "jobs/job-abc/stems/clean.flac",
"backing_vocals": "jobs/job-abc/stems/backing.flac",
}
},
)
@pytest.fixture
def mock_job_manager():
"""Create a mock JobManager."""
manager = MagicMock()
manager.update_state_data.return_value = None
manager.update_file_url.return_value = None
manager.transition_to_state.return_value = True
return manager
@pytest.fixture
def mock_worker_service():
"""Create a mock WorkerService."""
service = MagicMock()
service.trigger_audio_worker = AsyncMock(return_value=True)
service.trigger_lyrics_worker = AsyncMock(return_value=True)
return service
@pytest.fixture
def patched_client(mock_job_manager, mock_worker_service):
"""Create TestClient with all core patches active for the test duration."""
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.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
yield TestClient(app)
# --- Tests: create-custom-instrumental endpoint ---
class TestCreateCustomInstrumentalEndpoint:
"""Tests for POST /api/jobs/{job_id}/create-custom-instrumental."""
def test_success_returns_audio_url(
self, review_job, mock_job_manager, mock_worker_service, patched_client, auth_headers
):
"""Happy path: creates custom instrumental and returns signed audio URL."""
mock_job_manager.get_job.return_value = review_job
mock_result = MagicMock()
mock_result.total_muted_duration_seconds = 5.0
mock_editing_service = MagicMock()
mock_editing_service.create_custom_instrumental.return_value = mock_result
mock_transcoding = MagicMock()
mock_transcoding.get_review_audio_url_async = AsyncMock(
return_value="https://storage.googleapis.com/signed-url"
)
with patch(
"backend.services.audio_editing_service.AudioEditingService",
return_value=mock_editing_service,
), patch(
"backend.services.audio_transcoding_service.AudioTranscodingService",
return_value=mock_transcoding,
), patch(
"backend.api.routes.jobs.StorageService",
return_value=MagicMock(),
):
response = patched_client.post(
"/api/jobs/job-abc/create-custom-instrumental",
json={
"mute_regions": [
{"start_seconds": 10.0, "end_seconds": 20.0},
{"start_seconds": 60.0, "end_seconds": 65.0},
]
},
headers=auth_headers,
)
assert response.status_code == 200
data = response.json()
assert data["status"] == "success"
assert data["audio_url"] == "https://storage.googleapis.com/signed-url"
assert data["muted_duration_seconds"] == 5.0
assert "2 mute regions" in data["message"]
def test_success_in_review_status(
self, in_review_job, mock_job_manager, mock_worker_service, patched_client, auth_headers
):
"""Endpoint works when job is IN_REVIEW (not just AWAITING_REVIEW)."""
mock_job_manager.get_job.return_value = in_review_job
mock_result = MagicMock()
mock_result.total_muted_duration_seconds = 3.0
mock_editing_service = MagicMock()
mock_editing_service.create_custom_instrumental.return_value = mock_result
mock_transcoding = MagicMock()
mock_transcoding.get_review_audio_url_async = AsyncMock(
return_value="https://example.com/signed"
)
with patch(
"backend.services.audio_editing_service.AudioEditingService",
return_value=mock_editing_service,
), patch(
"backend.services.audio_transcoding_service.AudioTranscodingService",
return_value=mock_transcoding,
), patch(
"backend.api.routes.jobs.StorageService",
return_value=MagicMock(),
):
response = patched_client.post(
"/api/jobs/job-abc/create-custom-instrumental",
json={"mute_regions": [{"start_seconds": 1.0, "end_seconds": 2.0}]},
headers=auth_headers,
)
assert response.status_code == 200
def test_job_not_found_returns_404(
self, mock_job_manager, mock_worker_service, patched_client, auth_headers
):
"""Returns 404 when job does not exist."""
mock_job_manager.get_job.return_value = None
response = patched_client.post(
"/api/jobs/nonexistent/create-custom-instrumental",
json={"mute_regions": [{"start_seconds": 1.0, "end_seconds": 2.0}]},
headers=auth_headers,
)
assert response.status_code == 404
assert "not found" in response.json()["detail"].lower()
def test_wrong_status_returns_400(
self, completed_job, mock_job_manager, mock_worker_service, patched_client, auth_headers
):
"""Returns 400 when job is not in a review state."""
mock_job_manager.get_job.return_value = completed_job
response = patched_client.post(
"/api/jobs/job-abc/create-custom-instrumental",
json={"mute_regions": [{"start_seconds": 1.0, "end_seconds": 2.0}]},
headers=auth_headers,
)
assert response.status_code == 400
assert "not in review state" in response.json()["detail"].lower()
def test_missing_stems_returns_400(
self, job_no_stems, mock_job_manager, mock_worker_service, patched_client, auth_headers
):
"""Returns 400 when job does not have required stem files."""
mock_job_manager.get_job.return_value = job_no_stems
response = patched_client.post(
"/api/jobs/job-abc/create-custom-instrumental",
json={"mute_regions": [{"start_seconds": 1.0, "end_seconds": 2.0}]},
headers=auth_headers,
)
assert response.status_code == 400
assert "missing required stems" in response.json()["detail"].lower()
def test_empty_mute_regions_returns_422(
self, review_job, mock_job_manager, mock_worker_service, patched_client, auth_headers
):
"""Returns 422 when mute_regions is empty (Pydantic validation)."""
mock_job_manager.get_job.return_value = review_job
response = patched_client.post(
"/api/jobs/job-abc/create-custom-instrumental",
json={"mute_regions": []},
headers=auth_headers,
)
assert response.status_code == 422
def test_stores_custom_instrumental_path(
self, review_job, mock_job_manager, mock_worker_service, patched_client, auth_headers
):
"""Verifies update_file_url is called to persist the custom instrumental path."""
mock_job_manager.get_job.return_value = review_job
mock_result = MagicMock()
mock_result.total_muted_duration_seconds = 2.0
mock_editing_service = MagicMock()
mock_editing_service.create_custom_instrumental.return_value = mock_result
mock_transcoding = MagicMock()
mock_transcoding.get_review_audio_url_async = AsyncMock(
return_value="https://example.com/signed"
)
with patch(
"backend.services.audio_editing_service.AudioEditingService",
return_value=mock_editing_service,
), patch(
"backend.services.audio_transcoding_service.AudioTranscodingService",
return_value=mock_transcoding,
), patch(
"backend.api.routes.jobs.StorageService",
return_value=MagicMock(),
):
patched_client.post(
"/api/jobs/job-abc/create-custom-instrumental",
json={"mute_regions": [{"start_seconds": 5.0, "end_seconds": 10.0}]},
headers=auth_headers,
)
# Verify file URL was stored
mock_job_manager.update_file_url.assert_called_once_with(
"job-abc", "stems", "custom_instrumental",
"jobs/job-abc/stems/custom_instrumental.flac",
)
def test_service_error_returns_500(
self, review_job, mock_job_manager, mock_worker_service, patched_client, auth_headers
):
"""Returns 500 when the editing service raises an exception."""
mock_job_manager.get_job.return_value = review_job
mock_editing_service = MagicMock()
mock_editing_service.create_custom_instrumental.side_effect = RuntimeError(
"FFmpeg failed"
)
with patch(
"backend.services.audio_editing_service.AudioEditingService",
return_value=mock_editing_service,
), patch(
"backend.api.routes.jobs.StorageService",
return_value=MagicMock(),
):
response = patched_client.post(
"/api/jobs/job-abc/create-custom-instrumental",
json={"mute_regions": [{"start_seconds": 1.0, "end_seconds": 2.0}]},
headers=auth_headers,
)
assert response.status_code == 500
assert "FFmpeg failed" in response.json()["detail"]
# --- Tests: reference_lyrics stripping in submit_corrections ---
class TestSubmitCorrectionsReferenceLyricsStripping:
"""Tests for reference_lyrics being stripped from Firestore save in submit_corrections."""
def _make_corrections_payload(self, extra_keys=None):
"""Build a valid corrections payload that passes CorrectionsSubmission validation.
The CorrectionsSubmission model requires 'lines' and 'metadata' in corrections.
"""
data = {
"lines": [{"text": "Hello world", "start": 0.0, "end": 1.0}],
"metadata": {"source": "test", "version": "1.0"},
}
if extra_keys:
data.update(extra_keys)
return data
def test_reference_lyrics_stripped_from_firestore_save(
self, review_job, mock_job_manager, mock_worker_service, patched_client, auth_headers
):
"""Verify reference_lyrics is excluded from Firestore state_data update."""
mock_job_manager.get_job.return_value = review_job
mock_storage = MagicMock()
corrections_data = self._make_corrections_payload(extra_keys={
"corrected_segments": [{"text": "hello"}],
"reference_lyrics": {
"genius": "Very long lyrics content..." * 1000,
},
})
with patch("backend.services.storage_service.StorageService", return_value=mock_storage), \
patch("backend.api.routes.jobs.StorageService", return_value=mock_storage):
response = patched_client.post(
"/api/jobs/job-abc/corrections",
json={"corrections": corrections_data},
headers=auth_headers,
)
assert response.status_code == 200
# Check update_state_data was called with data that does NOT contain reference_lyrics
state_data_call = mock_job_manager.update_state_data.call_args_list[0]
saved_data = state_data_call[0][2] # Third positional arg is the data dict
assert "reference_lyrics" not in saved_data
# Check preserved keys are still present
assert "lines" in saved_data
assert "metadata" in saved_data
assert "corrected_segments" in saved_data
def test_full_corrections_saved_to_gcs(
self, review_job, mock_job_manager, mock_worker_service, patched_client, auth_headers
):
"""Verify the full corrections data (including reference_lyrics) goes to GCS."""
mock_job_manager.get_job.return_value = review_job
mock_storage = MagicMock()
corrections_data = self._make_corrections_payload(extra_keys={
"reference_lyrics": {
"genius": "Full lyrics text",
},
})
with patch("backend.services.storage_service.StorageService", return_value=mock_storage), \
patch("backend.api.routes.jobs.StorageService", return_value=mock_storage):
response = patched_client.post(
"/api/jobs/job-abc/corrections",
json={"corrections": corrections_data},
headers=auth_headers,
)
assert response.status_code == 200
# Check upload_json was called with the FULL data including reference_lyrics
mock_storage.upload_json.assert_called_once()
gcs_path, gcs_data = mock_storage.upload_json.call_args[0]
assert "corrections_updated.json" in gcs_path
assert "reference_lyrics" in gcs_data
def test_corrections_without_reference_lyrics_still_works(
self, review_job, mock_job_manager, mock_worker_service, patched_client, auth_headers
):
"""Verify submit_corrections works fine when reference_lyrics is not present."""
mock_job_manager.get_job.return_value = review_job
mock_storage = MagicMock()
corrections_data = self._make_corrections_payload(extra_keys={
"corrected_segments": [{"text": "hello world"}],
})
with patch("backend.services.storage_service.StorageService", return_value=mock_storage), \
patch("backend.api.routes.jobs.StorageService", return_value=mock_storage):
response = patched_client.post(
"/api/jobs/job-abc/corrections",
json={"corrections": corrections_data},
headers=auth_headers,
)
assert response.status_code == 200
# State data should have all keys (no reference_lyrics to strip)
state_data_call = mock_job_manager.update_state_data.call_args_list[0]
saved_data = state_data_call[0][2]
assert "lines" in saved_data
assert "metadata" in saved_data
assert "reference_lyrics" not in saved_data
+17 -14
View File
@@ -777,21 +777,22 @@ class TestVideoWorkerDistribution:
async def test_handle_native_distribution_dropbox_not_configured(self):
"""Test Dropbox upload skipped when service not configured."""
from backend.workers.video_worker import _handle_native_distribution
mock_job = MagicMock()
mock_job.dropbox_path = "/test/path"
mock_job.brand_prefix = "TEST"
mock_job.gdrive_folder_id = None
mock_job.is_private = False
mock_job.artist = "Test"
mock_job.title = "Song"
mock_job.state_data = {}
mock_job_log = MagicMock()
mock_job_manager = MagicMock()
mock_dropbox = MagicMock()
mock_dropbox.is_configured = False
with patch('backend.services.dropbox_service.get_dropbox_service', return_value=mock_dropbox):
await _handle_native_distribution(
job_id="test-123",
@@ -801,7 +802,7 @@ class TestVideoWorkerDistribution:
temp_dir="/tmp/test",
result={},
)
# Should log warning about not configured
mock_job_log.warning.assert_called()
@@ -809,21 +810,22 @@ class TestVideoWorkerDistribution:
async def test_handle_native_distribution_gdrive_not_configured(self):
"""Test Google Drive upload skipped when service not configured."""
from backend.workers.video_worker import _handle_native_distribution
mock_job = MagicMock()
mock_job.dropbox_path = None
mock_job.brand_prefix = None
mock_job.gdrive_folder_id = "test_folder_id"
mock_job.is_private = False
mock_job.artist = "Test"
mock_job.title = "Song"
mock_job.state_data = {}
mock_job_log = MagicMock()
mock_job_manager = MagicMock()
mock_gdrive = MagicMock()
mock_gdrive.is_configured = False
with patch('backend.services.gdrive_service.get_gdrive_service', return_value=mock_gdrive):
await _handle_native_distribution(
job_id="test-123",
@@ -833,7 +835,7 @@ class TestVideoWorkerDistribution:
temp_dir="/tmp/test",
result={},
)
# Should log warning about not configured
mock_job_log.warning.assert_called()
@@ -841,18 +843,19 @@ class TestVideoWorkerDistribution:
async def test_handle_native_distribution_handles_import_error(self):
"""Test that import errors for services are handled gracefully."""
from backend.workers.video_worker import _handle_native_distribution
mock_job = MagicMock()
mock_job.dropbox_path = "/test/path"
mock_job.brand_prefix = "TEST"
mock_job.gdrive_folder_id = None
mock_job.is_private = False
mock_job.artist = "Test"
mock_job.title = "Song"
mock_job.state_data = {}
mock_job_log = MagicMock()
mock_job_manager = MagicMock()
# Simulate import error
with patch('backend.services.dropbox_service.get_dropbox_service', side_effect=ImportError("No module")):
await _handle_native_distribution(
@@ -863,6 +866,6 @@ class TestVideoWorkerDistribution:
temp_dir="/tmp/test",
result={},
)
# Should log warning about import error
mock_job_log.warning.assert_called()
+229
View File
@@ -9,7 +9,9 @@ to avoid dependency issues in CI/CD environments.
"""
import pytest
import re
from pathlib import Path
from packaging.version import Version
# Copy the find_file function here to test it in isolation
@@ -227,3 +229,230 @@ class TestInstrumentalSelectionRegression:
assert result is not None
name = result.name.lower()
assert "clean" in name, f"Expected clean instrumental but found: {result.name}"
class TestWheelFilenameFiltering:
"""Test wheel filename filtering to prevent installation of invalid wheels.
Bug: The ensure_latest_wheel() function downloads all wheels including
karaoke_gen-current.whl, which is not a valid PEP 427 wheel filename
(missing version and platform tags). When pip tries to install it,
it fails with: "Invalid wheel filename (wrong number of parts)"
Fix: Filter out wheels containing '-current' before selecting which to install.
"""
def filter_wheels(self, wheels):
"""Replicate the filtering logic from ensure_latest_wheel()."""
return [w for w in wheels if '-current' not in w]
def test_filters_out_current_wheel(self):
"""Test that karaoke_gen-current.whl is filtered out."""
wheels = [
"/tmp/karaoke_gen-0.116.0-py3-none-any.whl",
"/tmp/karaoke_gen-current.whl",
"/tmp/karaoke_gen-0.115.0-py3-none-any.whl",
]
filtered = self.filter_wheels(wheels)
assert len(filtered) == 2
assert "/tmp/karaoke_gen-current.whl" not in filtered
assert "/tmp/karaoke_gen-0.116.0-py3-none-any.whl" in filtered
assert "/tmp/karaoke_gen-0.115.0-py3-none-any.whl" in filtered
def test_returns_empty_when_only_current_wheel(self):
"""Test that filtering returns empty list when only current wheel exists."""
wheels = ["/tmp/karaoke_gen-current.whl"]
filtered = self.filter_wheels(wheels)
assert filtered == []
def test_selects_latest_version_after_filtering(self):
"""Test that the latest version is selected after filtering out current.
Note: This test verifies filtering but uses simple sorting.
See TestWheelVersionSorting for comprehensive semantic version sorting tests.
"""
wheels = [
"/tmp/karaoke_gen-0.114.0-py3-none-any.whl",
"/tmp/karaoke_gen-current.whl",
"/tmp/karaoke_gen-0.116.0-py3-none-any.whl",
"/tmp/karaoke_gen-0.115.0-py3-none-any.whl",
]
filtered = self.filter_wheels(wheels)
# Verify current wheel was filtered out
assert len(filtered) == 3
assert all("-current" not in w for w in filtered)
def test_no_filtering_when_no_current_wheel(self):
"""Test that valid wheels pass through when no current wheel exists."""
wheels = [
"/tmp/karaoke_gen-0.116.0-py3-none-any.whl",
"/tmp/karaoke_gen-0.115.0-py3-none-any.whl",
]
filtered = self.filter_wheels(wheels)
assert len(filtered) == 2
assert filtered == wheels
def test_filters_current_in_different_paths(self):
"""Test that current wheel is filtered regardless of path."""
wheels = [
"/different/path/karaoke_gen-current.whl",
"/tmp/karaoke_gen-0.116.0-py3-none-any.whl",
]
filtered = self.filter_wheels(wheels)
assert len(filtered) == 1
assert "/tmp/karaoke_gen-0.116.0-py3-none-any.whl" in filtered
class TestWheelVersionSorting:
"""Test semantic version sorting for wheel selection.
Bug: The ensure_latest_wheel() function uses sorted(wheels)[-1] which does
alphabetical sorting, not semantic version sorting. This causes version 0.99.9
to be selected over 0.116.1 because string comparison puts '9' > '1'.
Fix: Extract version from filename using regex and sort by packaging.version.Version
"""
def extract_version(self, wheel_path):
"""Replicate the version extraction logic from ensure_latest_wheel()."""
match = re.search(r'karaoke_gen-([0-9.]+)-', wheel_path)
if match:
return Version(match.group(1))
return Version("0.0.0") # Fallback for unparseable filenames
def select_latest_wheel(self, wheels):
"""Replicate the full selection logic from ensure_latest_wheel()."""
# Filter out -current wheels
filtered = [w for w in wheels if '-current' not in w]
if not filtered:
return None
# Sort by semantic version
filtered.sort(key=self.extract_version, reverse=True)
return filtered[0]
def test_semantic_version_sorting_regression(self):
"""Test the exact bug: 0.99.9 should NOT be selected over 0.116.1"""
wheels = [
"/tmp/karaoke_gen-0.99.9-py3-none-any.whl",
"/tmp/karaoke_gen-0.116.1-py3-none-any.whl",
]
latest = self.select_latest_wheel(wheels)
# Semantic version: 0.116.1 > 0.99.9
assert "0.116.1" in latest
assert "0.99.9" not in latest
def test_alphabetical_would_fail(self):
"""Demonstrate that alphabetical sorting gives wrong result."""
wheels = [
"/tmp/karaoke_gen-0.99.9-py3-none-any.whl",
"/tmp/karaoke_gen-0.116.1-py3-none-any.whl",
]
# This is the OLD buggy behavior (alphabetical)
alphabetical_latest = sorted(wheels)[-1]
# Alphabetical puts 0.99.9 last (WRONG!)
assert "0.99.9" in alphabetical_latest
def test_version_extraction(self):
"""Test that version is correctly extracted from wheel filename."""
test_cases = [
("/tmp/karaoke_gen-0.116.1-py3-none-any.whl", "0.116.1"),
("/tmp/karaoke_gen-0.99.9-py3-none-any.whl", "0.99.9"),
("/tmp/karaoke_gen-1.0.0-py3-none-any.whl", "1.0.0"),
("/tmp/karaoke_gen-0.1.2-py3-none-any.whl", "0.1.2"),
]
for wheel_path, expected_version in test_cases:
version = self.extract_version(wheel_path)
assert str(version) == expected_version
def test_version_extraction_fallback(self):
"""Test that unparseable filenames get fallback version."""
invalid_wheels = [
"/tmp/karaoke_gen-current.whl",
"/tmp/karaoke_gen-latest.whl",
"/tmp/invalid-filename.whl",
]
for wheel in invalid_wheels:
version = self.extract_version(wheel)
assert version == Version("0.0.0")
def test_complex_version_sorting(self):
"""Test sorting with multiple versions including patch, minor, major."""
wheels = [
"/tmp/karaoke_gen-0.99.9-py3-none-any.whl",
"/tmp/karaoke_gen-0.116.0-py3-none-any.whl",
"/tmp/karaoke_gen-0.116.1-py3-none-any.whl",
"/tmp/karaoke_gen-1.0.0-py3-none-any.whl",
"/tmp/karaoke_gen-0.115.0-py3-none-any.whl",
"/tmp/karaoke_gen-0.1.0-py3-none-any.whl",
]
latest = self.select_latest_wheel(wheels)
# 1.0.0 is the highest version
assert "1.0.0" in latest
def test_version_sorting_with_current_wheel(self):
"""Test that current wheel is filtered before version sorting."""
wheels = [
"/tmp/karaoke_gen-0.99.9-py3-none-any.whl",
"/tmp/karaoke_gen-current.whl",
"/tmp/karaoke_gen-0.116.1-py3-none-any.whl",
]
latest = self.select_latest_wheel(wheels)
# Current is filtered out, 0.116.1 is selected
assert "0.116.1" in latest
assert "current" not in latest
def test_patch_version_comparison(self):
"""Test that patch versions are compared correctly."""
wheels = [
"/tmp/karaoke_gen-0.116.0-py3-none-any.whl",
"/tmp/karaoke_gen-0.116.1-py3-none-any.whl",
"/tmp/karaoke_gen-0.116.2-py3-none-any.whl",
]
latest = self.select_latest_wheel(wheels)
assert "0.116.2" in latest
def test_minor_version_comparison(self):
"""Test that minor versions are compared correctly."""
wheels = [
"/tmp/karaoke_gen-0.115.0-py3-none-any.whl",
"/tmp/karaoke_gen-0.116.0-py3-none-any.whl",
"/tmp/karaoke_gen-0.200.0-py3-none-any.whl",
]
latest = self.select_latest_wheel(wheels)
assert "0.200.0" in latest
def test_empty_wheels_list(self):
"""Test that empty list returns None."""
wheels = []
latest = self.select_latest_wheel(wheels)
assert latest is None
def test_only_current_wheel_returns_none(self):
"""Test that list with only current wheel returns None."""
wheels = ["/tmp/karaoke_gen-current.whl"]
latest = self.select_latest_wheel(wheels)
assert latest is None
@@ -381,7 +381,7 @@ class TestAudioSearchCacheIndependence:
def test_download_code_uses_youtube_download_service(self):
"""
Verify that _download_and_start_processing uses YouTubeDownloadService.
Verify that _download_audio_and_trigger_workers uses YouTubeDownloadService.
After the consolidation refactor (2025-01), all YouTube downloads go through
YouTubeDownloadService instead of using download_from_url directly. This
@@ -390,14 +390,14 @@ class TestAudioSearchCacheIndependence:
from backend.api.routes import audio_search
import inspect
# Get the source of _download_and_start_processing
source = inspect.getsource(audio_search._download_and_start_processing)
# Get the source of _download_audio_and_trigger_workers
source = inspect.getsource(audio_search._download_audio_and_trigger_workers)
# Verify YouTubeDownloadService is used for YouTube
assert "source_name == 'YouTube'" in source, \
"_download_and_start_processing must check for YouTube source"
"_download_audio_and_trigger_workers must check for YouTube source"
assert 'youtube_service' in source or 'get_youtube_download_service' in source, \
"_download_and_start_processing must use YouTubeDownloadService for YouTube"
"_download_audio_and_trigger_workers must use YouTubeDownloadService for YouTube"
def test_youtube_download_service_import_exists(self):
"""
+1 -1
View File
@@ -428,7 +428,7 @@ class TestMadeForYouFieldMapping:
brand_prefix="NOMAD",
)
job = job_manager.create_job(job_create)
job = job_manager.create_job(job_create, is_admin=True)
# Verify all made-for-you fields
assert job.made_for_you is True
+26
View File
@@ -75,6 +75,32 @@ class TestMain:
assert 'karaoke' in app.title.lower() or app.title
class TestExceptionHandlers:
"""Tests for global exception handlers in main.py."""
@pytest.mark.asyncio
async def test_insufficient_credits_handler_returns_402_response(self):
"""Test that the insufficient credits handler returns HTTP 402 with correct body."""
from backend.main import insufficient_credits_exception_handler
from backend.exceptions import InsufficientCreditsError
exc = InsufficientCreditsError(
message="No credits remaining",
credits_available=0,
credits_required=1,
)
response = await insufficient_credits_exception_handler(request=None, exc=exc)
assert response.status_code == 402
import json
body = json.loads(response.body)
assert body["detail"] == "No credits remaining"
assert body["credits_available"] == 0
assert body["credits_required"] == 1
assert body["buy_url"] == "/#pricing"
class TestDependencies:
"""Tests for dependencies.py."""
+419
View File
@@ -0,0 +1,419 @@
"""
Tests for private (non-published) tracks feature.
Tests cover:
- Job model is_private field
- Distribution settings overrides for private jobs
- Email template YouTube section removal
- Admin toggle with auto-delete behavior
"""
import pytest
from datetime import datetime
from unittest.mock import Mock, patch, MagicMock
from types import SimpleNamespace
from backend.models.job import Job, JobCreate
from backend.services.job_defaults_service import (
get_effective_distribution_for_job,
EffectiveDistributionSettings,
)
from backend.services.template_service import TemplateService
class TestJobModelIsPrivate:
"""Tests for is_private field on Job and JobCreate models."""
def test_job_defaults_to_not_private(self):
"""Job.is_private defaults to False."""
now = datetime.utcnow().isoformat()
job = Job(job_id="test-123", status="pending", created_at=now, updated_at=now)
assert job.is_private is False
def test_job_can_be_created_as_private(self):
"""Job can be explicitly set as private."""
now = datetime.utcnow().isoformat()
job = Job(job_id="test-123", status="pending", is_private=True, created_at=now, updated_at=now)
assert job.is_private is True
def test_job_create_defaults_to_not_private(self):
"""JobCreate.is_private defaults to False."""
job_create = JobCreate(artist="Test", title="Song")
assert job_create.is_private is False
def test_job_create_can_be_private(self):
"""JobCreate can be explicitly set as private."""
job_create = JobCreate(artist="Test", title="Song", is_private=True)
assert job_create.is_private is True
def test_create_job_persists_is_private(self):
"""JobManager.create_job should persist is_private from JobCreate to Job."""
from backend.services.job_manager import JobManager
manager = JobManager()
manager.firestore = Mock()
manager.firestore.create_job = Mock()
job_create = JobCreate(
artist="Test",
title="Song",
is_private=True,
theme_id="nomad",
)
job = manager.create_job(job_create, is_admin=True)
assert job.is_private is True
manager.firestore.create_job.assert_called_once()
saved_job = manager.firestore.create_job.call_args[0][0]
assert saved_job.is_private is True
def test_create_job_defaults_is_private_false(self):
"""JobManager.create_job should default is_private to False."""
from backend.services.job_manager import JobManager
manager = JobManager()
manager.firestore = Mock()
manager.firestore.create_job = Mock()
job_create = JobCreate(
artist="Test",
title="Song",
theme_id="nomad",
)
job = manager.create_job(job_create, is_admin=True)
assert job.is_private is False
class TestGetEffectiveDistributionForJob:
"""Tests for get_effective_distribution_for_job() helper."""
@patch('backend.services.job_defaults_service.get_settings')
def test_private_job_uses_private_dropbox_path(self, mock_settings):
"""Private job should use the private Dropbox path."""
mock_settings.return_value = SimpleNamespace(
default_private_dropbox_path="/Tracks-NonPublished",
default_private_brand_prefix="NOMADNP",
)
job = SimpleNamespace(
is_private=True,
dropbox_path="/Tracks-Organized",
brand_prefix="NOMAD",
enable_youtube_upload=True,
gdrive_folder_id="some-folder-id",
discord_webhook_url="https://discord.com/hook",
youtube_description_template="template",
)
dist = get_effective_distribution_for_job(job)
assert dist.dropbox_path == "/Tracks-NonPublished"
assert dist.brand_prefix == "NOMADNP"
@patch('backend.services.job_defaults_service.get_settings')
def test_private_job_disables_youtube(self, mock_settings):
"""Private job should have YouTube upload disabled."""
mock_settings.return_value = SimpleNamespace(
default_private_dropbox_path="/Tracks-NonPublished",
default_private_brand_prefix="NOMADNP",
)
job = SimpleNamespace(
is_private=True,
enable_youtube_upload=True,
discord_webhook_url=None,
)
dist = get_effective_distribution_for_job(job)
assert dist.enable_youtube_upload is False
assert dist.youtube_description is None
@patch('backend.services.job_defaults_service.get_settings')
def test_private_job_disables_gdrive(self, mock_settings):
"""Private job should have Google Drive folder ID set to None."""
mock_settings.return_value = SimpleNamespace(
default_private_dropbox_path="/Tracks-NonPublished",
default_private_brand_prefix="NOMADNP",
)
job = SimpleNamespace(
is_private=True,
gdrive_folder_id="some-folder-id",
discord_webhook_url=None,
)
dist = get_effective_distribution_for_job(job)
assert dist.gdrive_folder_id is None
@patch('backend.services.job_defaults_service.get_settings')
def test_private_job_preserves_discord(self, mock_settings):
"""Private job should still have Discord webhook preserved."""
mock_settings.return_value = SimpleNamespace(
default_private_dropbox_path="/Tracks-NonPublished",
default_private_brand_prefix="NOMADNP",
)
job = SimpleNamespace(
is_private=True,
discord_webhook_url="https://discord.com/webhook/123",
)
dist = get_effective_distribution_for_job(job)
assert dist.discord_webhook_url == "https://discord.com/webhook/123"
def test_non_private_job_uses_job_settings(self):
"""Non-private job should use its own distribution settings."""
job = SimpleNamespace(
is_private=False,
dropbox_path="/Tracks-Organized",
brand_prefix="NOMAD",
enable_youtube_upload=True,
gdrive_folder_id="folder-id",
discord_webhook_url="https://discord.com/hook",
youtube_description_template="description",
)
dist = get_effective_distribution_for_job(job)
assert dist.dropbox_path == "/Tracks-Organized"
assert dist.brand_prefix == "NOMAD"
assert dist.enable_youtube_upload is True
assert dist.gdrive_folder_id == "folder-id"
assert dist.discord_webhook_url == "https://discord.com/hook"
assert dist.youtube_description == "description"
def test_job_without_is_private_treated_as_non_private(self):
"""Job object without is_private attribute should be treated as non-private."""
job = SimpleNamespace(
dropbox_path="/Tracks-Organized",
brand_prefix="NOMAD",
enable_youtube_upload=False,
gdrive_folder_id=None,
discord_webhook_url=None,
youtube_description_template=None,
)
dist = get_effective_distribution_for_job(job)
assert dist.dropbox_path == "/Tracks-Organized"
assert dist.brand_prefix == "NOMAD"
assert dist.enable_youtube_upload is False
class TestTemplateServicePrivate:
"""Tests for email template rendering with is_private flag."""
def test_private_job_removes_youtube_section(self):
"""Private job completion email should not contain YouTube section."""
service = TemplateService()
service._storage_client = Mock()
service._bucket = Mock()
# Force use of default template
service._bucket.blob.return_value.exists.return_value = False
result = service.render_job_completion(
name="Test User",
youtube_url=None,
dropbox_url="https://dropbox.com/link",
artist="Artist",
title="Song",
job_id="job-123",
is_private=True,
)
assert "YouTube" not in result
assert "youtube_url" not in result
assert "https://dropbox.com/link" in result
def test_non_private_job_includes_youtube_section(self):
"""Non-private job completion email should include YouTube section."""
service = TemplateService()
service._storage_client = Mock()
service._bucket = Mock()
service._bucket.blob.return_value.exists.return_value = False
result = service.render_job_completion(
name="Test User",
youtube_url="https://youtube.com/watch?v=123",
dropbox_url="https://dropbox.com/link",
artist="Artist",
title="Song",
job_id="job-123",
is_private=False,
)
assert "https://youtube.com/watch?v=123" in result
assert "YouTube" in result
def test_private_job_still_has_dropbox_link(self):
"""Private job email should still contain the Dropbox link."""
service = TemplateService()
service._storage_client = Mock()
service._bucket = Mock()
service._bucket.blob.return_value.exists.return_value = False
result = service.render_job_completion(
name="Test User",
dropbox_url="https://dropbox.com/sh/abc123",
artist="Artist",
title="Song",
job_id="job-123",
is_private=True,
)
assert "https://dropbox.com/sh/abc123" in result
assert "dropbox" in result.lower()
def test_private_job_still_has_greeting(self):
"""Private job email should still contain the greeting."""
service = TemplateService()
service._storage_client = Mock()
service._bucket = Mock()
service._bucket.blob.return_value.exists.return_value = False
result = service.render_job_completion(
name="Jane",
dropbox_url="https://dropbox.com/link",
is_private=True,
)
assert "Hi Jane" in result
class TestNotificationServicePrivate:
"""Tests for notification service passing is_private to template."""
@pytest.mark.asyncio
async def test_send_completion_email_passes_is_private(self):
"""send_job_completion_email should pass is_private to template renderer."""
from backend.services.job_notification_service import JobNotificationService
service = JobNotificationService()
service.email_service = Mock()
service.email_service.send_job_completion.return_value = True
service.template_service = Mock()
service.template_service.render_job_completion.return_value = "Test message"
with patch('backend.services.job_notification_service.ENABLE_AUTO_EMAILS', True):
await service.send_job_completion_email(
job_id="job-123",
user_email="user@example.com",
is_private=True,
)
# Verify is_private=True was passed to template renderer
call_kwargs = service.template_service.render_job_completion.call_args
assert call_kwargs[1].get('is_private') is True or \
(call_kwargs[0] and True in call_kwargs[0]) # positional or keyword
@pytest.mark.asyncio
async def test_send_completion_email_defaults_is_private_false(self):
"""send_job_completion_email should default is_private to False."""
from backend.services.job_notification_service import JobNotificationService
service = JobNotificationService()
service.email_service = Mock()
service.email_service.send_job_completion.return_value = True
service.template_service = Mock()
service.template_service.render_job_completion.return_value = "Test message"
with patch('backend.services.job_notification_service.ENABLE_AUTO_EMAILS', True):
await service.send_job_completion_email(
job_id="job-123",
user_email="user@example.com",
)
call_kwargs = service.template_service.render_job_completion.call_args
assert call_kwargs[1].get('is_private') is False
def test_get_completion_message_passes_is_private(self):
"""get_completion_message should pass is_private to template renderer."""
from backend.services.job_notification_service import JobNotificationService
service = JobNotificationService()
service.template_service = Mock()
service.template_service.render_job_completion.return_value = "Test message"
service.get_completion_message(job_id="job-123", is_private=True)
call_kwargs = service.template_service.render_job_completion.call_args
assert call_kwargs[1].get('is_private') is True
class TestRequestModelIsPrivate:
"""Tests for is_private on API request models."""
def test_url_submission_request_has_is_private(self):
"""URLSubmissionRequest should accept is_private field."""
from backend.models.requests import URLSubmissionRequest
req = URLSubmissionRequest(url="https://youtube.com/watch?v=123", is_private=True)
assert req.is_private is True
def test_url_submission_request_is_private_defaults_none(self):
"""URLSubmissionRequest.is_private should default to None."""
from backend.models.requests import URLSubmissionRequest
req = URLSubmissionRequest(url="https://youtube.com/watch?v=123")
assert req.is_private is None
class TestAdminPrivateToggle:
"""Tests for admin API handling of is_private toggle."""
def test_is_private_in_editable_fields(self):
"""is_private should be in the EDITABLE_JOB_FIELDS set."""
from backend.api.routes.admin import EDITABLE_JOB_FIELDS
assert "is_private" in EDITABLE_JOB_FIELDS
def test_job_update_request_has_is_private(self):
"""JobUpdateRequest model should accept is_private field."""
from backend.api.routes.admin import JobUpdateRequest
req = JobUpdateRequest(is_private=True)
assert req.is_private is True
def test_job_update_request_is_private_optional(self):
"""JobUpdateRequest.is_private should be optional."""
from backend.api.routes.admin import JobUpdateRequest
req = JobUpdateRequest()
assert req.is_private is None
class TestOrchestratorConfigPrivate:
"""Tests for orchestrator config with private jobs."""
@patch('backend.services.job_defaults_service.get_settings')
def test_private_job_config_disables_youtube_and_gdrive(self, mock_settings):
"""Private job should produce config with no YouTube and no GDrive."""
mock_settings.return_value = SimpleNamespace(
default_private_dropbox_path="/Tracks-NonPublished",
default_private_brand_prefix="NOMADNP",
)
from backend.workers.video_worker_orchestrator import create_orchestrator_config_from_job
job = MagicMock()
job.job_id = "test-private"
job.artist = "Artist"
job.title = "Title"
job.state_data = {"instrumental_selection": "clean"}
job.enable_cdg = False
job.enable_txt = False
job.enable_youtube_upload = True # Would normally enable YouTube
job.is_private = True # But private overrides it
job.brand_prefix = "NOMAD"
job.discord_webhook_url = None
job.youtube_description_template = "desc"
job.dropbox_path = "/Tracks-Organized"
job.gdrive_folder_id = "folder-123"
job.keep_brand_code = None
job.existing_instrumental_gcs_path = None
config = create_orchestrator_config_from_job(
job=job,
temp_dir="/tmp/test",
youtube_credentials={"token": "test"},
)
assert config.enable_youtube_upload is False
assert config.gdrive_folder_id is None
assert config.brand_prefix == "NOMADNP"
assert config.youtube_description_template is None
+162
View File
@@ -374,6 +374,168 @@ class TestCompleteReviewWithInstrumentalSelection:
assert selection in ['clean', 'with_backing', 'custom']
class TestSummaryEndpoint:
"""Tests for the fields=summary query parameter on list_jobs.
When fields=summary, the endpoint uses Firestore field projection and
returns pruned dicts instead of full Job models. This dramatically
reduces payload size for the dashboard polling use case.
"""
def test_prune_state_data_keeps_allowed_keys(self):
"""Verify _prune_state_data keeps only dashboard-required keys."""
from backend.api.routes.jobs import _prune_state_data
data = {
'state_data': {
'brand_code': 'NKP',
'youtube_url': 'https://youtu.be/abc',
'audio_progress': {'stage': 'separating'},
'lyrics_progress': {'stage': 'transcribing'},
'audio_complete': True,
'lyrics_complete': True,
'backing_vocals_analysis': {'recommended_selection': 'clean'},
'dropbox_link': 'https://dropbox.com/s/...',
# These should be stripped
'corrected_lyrics': {'lines': [1, 2, 3]},
'render_progress': {'stage': 'done'},
'blocking_state_entered_at': '2026-01-01',
}
}
result = _prune_state_data(data)
sd = result['state_data']
assert 'brand_code' in sd
assert 'youtube_url' in sd
assert 'audio_progress' in sd
assert 'lyrics_progress' in sd
assert 'audio_complete' in sd
assert 'lyrics_complete' in sd
assert 'backing_vocals_analysis' in sd
assert 'dropbox_link' in sd
# Stripped keys
assert 'corrected_lyrics' not in sd
assert 'render_progress' not in sd
assert 'blocking_state_entered_at' not in sd
def test_prune_state_data_handles_missing(self):
"""Verify _prune_state_data is safe when state_data is absent."""
from backend.api.routes.jobs import _prune_state_data
assert _prune_state_data({}) == {}
assert _prune_state_data({'state_data': None}) == {'state_data': None}
def test_prune_file_urls_keeps_allowed_keys(self):
"""Verify _prune_file_urls keeps only dashboard-required keys."""
from backend.api.routes.jobs import _prune_file_urls
data = {
'file_urls': {
'finals': {'lossless_4k_mp4': 'gs://bucket/finals/4k.mp4'},
'videos': {'with_vocals': 'gs://bucket/videos/wv.mkv'},
'packages': {'cdg_zip': 'gs://bucket/packages/cdg.zip'},
# These should be stripped
'stems': {'clean': 'gs://bucket/stems/clean.flac'},
'lyrics': {'corrections': 'gs://bucket/lyrics/c.json'},
'screens': {'title': 'gs://bucket/screens/title.mov'},
}
}
result = _prune_file_urls(data)
fu = result['file_urls']
assert 'finals' in fu
assert 'videos' in fu
assert 'packages' in fu
assert 'stems' not in fu
assert 'lyrics' not in fu
assert 'screens' not in fu
def test_prune_file_urls_handles_missing(self):
"""Verify _prune_file_urls is safe when file_urls is absent."""
from backend.api.routes.jobs import _prune_file_urls
assert _prune_file_urls({}) == {}
assert _prune_file_urls({'file_urls': None}) == {'file_urls': None}
def test_summary_returns_only_expected_fields(self):
"""Verify a pruned summary dict only contains dashboard fields."""
from backend.api.routes.jobs import _prune_state_data, _prune_file_urls
raw = {
'job_id': 'abc123',
'status': 'pending',
'progress': 0,
'created_at': '2026-01-01T00:00:00',
'artist': 'Test',
'title': 'Song',
'error_message': None,
'non_interactive': False,
'outputs_deleted_at': None,
'user_email': 'test@example.com',
'state_data': {
'brand_code': 'NKP',
'corrected_lyrics': 'should be removed',
},
'file_urls': {
'finals': {'lossless_4k_mp4': 'gs://...'},
'stems': {'clean': 'gs://...'},
},
}
result = _prune_file_urls(_prune_state_data(raw))
# state_data should only have brand_code
assert list(result['state_data'].keys()) == ['brand_code']
# file_urls should only have finals
assert list(result['file_urls'].keys()) == ['finals']
def test_hide_completed_statuses(self):
"""Verify _HIDE_COMPLETED_STATUSES includes the expected terminal statuses."""
from backend.api.routes.jobs import _HIDE_COMPLETED_STATUSES
assert 'complete' in _HIDE_COMPLETED_STATUSES
assert 'prep_complete' in _HIDE_COMPLETED_STATUSES
assert 'failed' in _HIDE_COMPLETED_STATUSES
assert 'cancelled' in _HIDE_COMPLETED_STATUSES
# Active statuses should NOT be in the list
assert 'pending' not in _HIDE_COMPLETED_STATUSES
assert 'downloading' not in _HIDE_COMPLETED_STATUSES
def test_exclude_test_works_with_summary_dicts(self):
"""Verify test email filtering works on raw dicts (not Job models)."""
from backend.utils.test_data import is_test_email
# Summary mode returns dicts, so exclude_test filters using dict access
job_dicts = [
{'job_id': '1', 'user_email': 'real@example.com'},
{'job_id': '2', 'user_email': 'test@inbox.testmail.app'},
{'job_id': '3', 'user_email': None},
]
filtered = [j for j in job_dicts if not is_test_email(j.get('user_email') or "")]
assert len(filtered) == 2
assert filtered[0]['job_id'] == '1'
assert filtered[1]['job_id'] == '3'
def test_full_response_unchanged_without_fields_param(self):
"""Verify the endpoint returns full Job models when fields is not set.
This is a backward-compatibility test: the admin jobs page (adminApi.listAllJobs)
does NOT send fields=summary, so it must continue receiving full Job objects.
"""
# When fields is None, the route falls through to the full Job path.
# We verify this by checking that the route accepts fields=None gracefully.
# (The actual HTTP test would require a TestClient, so here we verify
# the route function signature accepts None.)
import inspect
from backend.api.routes.jobs import list_jobs
sig = inspect.signature(list_jobs)
fields_param = sig.parameters.get('fields')
assert fields_param is not None
assert fields_param.default is None # Default should be None (full mode)
class TestScreensWorkerBackingVocalsAnalysis:
"""Tests documenting that backing vocals analysis now runs in screens_worker.
+37
View File
@@ -613,3 +613,40 @@ class TestCorrectionFlowIntegration:
# The corrections_updated key should be added
assert "corrections_updated" not in file_urls_before["lyrics"]
assert "corrections_updated" in file_urls_after["lyrics"]
class TestInstrumentalSelectionValidation:
"""Tests for instrumental_selection validation in complete_review."""
def test_custom_allowed_with_custom_instrumental_stem(self):
"""'custom' should be valid when custom_instrumental stem exists (mute-region editing)."""
from unittest.mock import Mock, patch, AsyncMock
valid_selections = ["clean", "with_backing"]
# Simulate the validation logic from review.py
stems = {"custom_instrumental": "jobs/test/stems/custom_instrumental.flac"}
existing_instrumental_gcs_path = None
if existing_instrumental_gcs_path or stems.get("custom_instrumental"):
valid_selections.append("custom")
assert "custom" in valid_selections
def test_custom_allowed_with_uploaded_instrumental(self):
"""'custom' should be valid when existing_instrumental_gcs_path is set."""
valid_selections = ["clean", "with_backing"]
stems = {}
existing_instrumental_gcs_path = "uploads/test/audio/instrumental.flac"
if existing_instrumental_gcs_path or stems.get("custom_instrumental"):
valid_selections.append("custom")
assert "custom" in valid_selections
def test_custom_rejected_without_custom_stem_or_upload(self):
"""'custom' should NOT be valid when neither custom stem nor upload exists."""
valid_selections = ["clean", "with_backing"]
stems = {"instrumental_clean": "jobs/test/stems/clean.flac"}
existing_instrumental_gcs_path = None
if existing_instrumental_gcs_path or stems.get("custom_instrumental"):
valid_selections.append("custom")
assert "custom" not in valid_selections
+12 -2
View File
@@ -184,7 +184,12 @@ class TestWorkerService:
mock_run_v2.RunJobRequest.Overrides = MagicMock()
mock_run_v2.RunJobRequest.Overrides.ContainerOverride = MagicMock()
with patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}):
# Patch both sys.modules and the parent package attribute to ensure
# 'from google.cloud import run_v2' resolves to our mock regardless
# of whether the real package is installed (namespace package resolution)
import google.cloud
with patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}), \
patch.object(google.cloud, 'run_v2', mock_run_v2, create=True):
service = WorkerService()
result = await service.trigger_audio_worker("test123")
@@ -222,7 +227,12 @@ class TestWorkerService:
mock_run_v2.RunJobRequest.Overrides = MagicMock()
mock_run_v2.RunJobRequest.Overrides.ContainerOverride = MagicMock()
with patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}):
# Patch both sys.modules and the parent package attribute to ensure
# 'from google.cloud import run_v2' resolves to our mock regardless
# of whether the real package is installed (namespace package resolution)
import google.cloud
with patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}), \
patch.object(google.cloud, 'run_v2', mock_run_v2, create=True):
service = WorkerService()
result = await service.trigger_lyrics_worker("test123")
@@ -855,6 +855,7 @@ class TestCreateOrchestratorConfigFromJob:
job.enable_cdg = True
job.enable_txt = False
job.enable_youtube_upload = True
job.is_private = False
job.brand_prefix = "NOMAD"
job.discord_webhook_url = "https://discord.com/api/webhooks/123/abc"
job.youtube_description_template = "Test description"
@@ -888,6 +889,7 @@ class TestCreateOrchestratorConfigFromJob:
job.enable_cdg = False
job.enable_txt = False
job.enable_youtube_upload = False
job.is_private = False
job.brand_prefix = None
job.discord_webhook_url = None
job.youtube_description_template = None
@@ -926,6 +928,7 @@ class TestCreateOrchestratorConfigFromJob:
job.enable_cdg = False
job.enable_txt = False
job.enable_youtube_upload = False
job.is_private = False
job.brand_prefix = None
job.discord_webhook_url = None
job.youtube_description_template = None
+13
View File
@@ -485,6 +485,19 @@ async def download_audio(
local_path = os.path.join(temp_dir, safe_filename)
storage.download_file(job.input_media_gcs_path, local_path)
logger.info(f"Job {job_id}: Downloaded uploaded file to {local_path}")
# Persist uploaded audio to jobs/ prefix (uploads/ has 7-day lifecycle)
if job.input_media_gcs_path.startswith("uploads/"):
try:
persistent_path = f"jobs/{job_id}/input/{safe_filename}"
storage.upload_file(local_path, persistent_path)
jm = job_manager_instance or JobManager()
jm.update_job(job_id, {'input_media_gcs_path': persistent_path})
jm.update_file_url(job_id, 'input', 'audio', persistent_path)
logger.info(f"Job {job_id}: Persisted upload to {persistent_path}")
except Exception as e:
logger.warning(f"Job {job_id}: Failed to persist upload to jobs/ prefix: {e}")
return local_path
# Case 2: URL download (from file_urls if already downloaded, or from job.url)
+37
View File
@@ -184,6 +184,12 @@ async def generate_screens(job_id: str) -> bool:
job_log.info("Analyzing backing vocals for instrumental selection...")
await _analyze_backing_vocals(job_id, job_manager, storage, job_log)
# Transcode review audio to OGG Opus for fast browser playback
# This runs BEFORE review so all files are cached when the user opens the UI
with job_span("transcode-review-audio", job_id):
job_log.info("Transcoding review audio to OGG Opus...")
await _transcode_review_audio(job_id, job_manager, job_log)
# Transition to AWAITING_REVIEW (combined lyrics + instrumental review)
# Human must review lyrics AND select instrumental before video can be rendered
logger.info(f"[job:{job_id}] Screens generated, awaiting combined review")
@@ -615,6 +621,37 @@ async def _analyze_backing_vocals(
})
async def _transcode_review_audio(
job_id: str,
job_manager: JobManager,
job_log: logging.Logger,
) -> None:
"""
Transcode all review audio files to OGG Opus for fast browser playback.
This eagerly transcodes input audio + stems so the review UI serves
~3 MB OGG files instead of 35+ MB FLACs. Non-fatal: if transcoding
fails, the review UI falls back to original FLAC signed URLs.
"""
from backend.services.audio_transcoding_service import AudioTranscodingService
try:
job = job_manager.get_job(job_id)
if not job:
job_log.warning(f"Could not get job {job_id} for review audio transcoding")
return
transcoding = AudioTranscodingService()
transcoded = transcoding.prepare_review_audio_for_job(job)
job_log.info(f"Review audio transcoding complete: {len(transcoded)} files")
except Exception as e:
# Non-fatal: review UI will fall back to FLAC signed URLs
job_log.warning(f"Review audio transcoding failed (non-fatal): {e}")
logger.warning(f"Job {job_id}: Review audio transcoding failed: {e}")
async def _apply_countdown_padding_if_needed(
job_id: str,
job_manager: JobManager,
+28 -12
View File
@@ -237,15 +237,17 @@ async def generate_video_orchestrated(job_id: str) -> bool:
if rclone_service.setup_rclone_config():
job_log.info("Rclone config loaded for Dropbox upload")
# Load YouTube credentials if needed
# Load YouTube credentials if needed (skip for private/non-published tracks)
youtube_credentials = None
if getattr(job, 'enable_youtube_upload', False):
if getattr(job, 'enable_youtube_upload', False) and not getattr(job, 'is_private', False):
youtube_service = get_youtube_service()
if youtube_service.is_configured:
youtube_credentials = youtube_service.get_credentials_dict()
job_log.info("YouTube credentials loaded for video upload")
else:
job_log.warning("YouTube credentials not available - upload will be skipped")
elif getattr(job, 'is_private', False):
job_log.info("Private track - skipping YouTube upload")
try:
# Wrap entire worker in a tracing span
@@ -467,16 +469,18 @@ async def generate_video_legacy(job_id: str) -> bool:
else:
job_log.warning("Rclone config not available - Dropbox upload will be skipped")
# Load YouTube credentials if needed
# Load YouTube credentials if needed (skip for private/non-published tracks)
youtube_credentials = None
if getattr(job, 'enable_youtube_upload', False):
if getattr(job, 'enable_youtube_upload', False) and not getattr(job, 'is_private', False):
youtube_service = get_youtube_service()
if youtube_service.is_configured:
youtube_credentials = youtube_service.get_credentials_dict()
job_log.info("YouTube credentials loaded for video upload")
else:
job_log.warning("YouTube credentials not available - upload will be skipped")
elif getattr(job, 'is_private', False):
job_log.info("Private track - skipping YouTube upload")
try:
# Wrap entire worker in a tracing span
with job_span("video-worker", job_id, {"artist": job.artist, "title": job.title}) as root_span:
@@ -776,10 +780,14 @@ async def _handle_native_distribution(
brand_code = keep_brand_code
result['brand_code'] = brand_code
job_log.info(f"Using preserved brand code: {brand_code}")
# Get effective distribution settings (applies private track overrides if is_private=True)
from backend.services.job_defaults_service import get_effective_distribution_for_job
dist = get_effective_distribution_for_job(job)
# Upload to Dropbox using native SDK
dropbox_path = getattr(job, 'dropbox_path', None)
brand_prefix = getattr(job, 'brand_prefix', None)
dropbox_path = dist.dropbox_path
brand_prefix = dist.brand_prefix
if dropbox_path and brand_prefix:
try:
@@ -836,7 +844,7 @@ async def _handle_native_distribution(
# Upload to Google Drive using native API
# Skip if orchestrator already uploaded (gdrive_files already populated)
# This prevents duplicate uploads when using the orchestrator path
gdrive_folder_id = getattr(job, 'gdrive_folder_id', None)
gdrive_folder_id = dist.gdrive_folder_id
existing_gdrive_files = result.get('gdrive_files')
if gdrive_folder_id and not existing_gdrive_files:
@@ -925,11 +933,12 @@ def _validate_prerequisites(job) -> bool:
logger.error(f"Job {job.job_id}: Missing lyrics video")
return False
# Check instrumental exists - for 'custom', check existing_instrumental_gcs_path instead of stems
# Check instrumental exists - for 'custom', check uploaded file or mute-region stem
if instrumental_selection == 'custom':
existing_instrumental_path = getattr(job, 'existing_instrumental_gcs_path', None)
if not existing_instrumental_path:
logger.error(f"Job {job.job_id}: Custom instrumental selected but no existing_instrumental_gcs_path")
stems = job.file_urls.get('stems', {})
if not existing_instrumental_path and not stems.get('custom_instrumental'):
logger.error(f"Job {job.job_id}: Custom instrumental selected but no existing_instrumental_gcs_path or custom_instrumental stem")
return False
return True # Other stem checks not needed for custom instrumental
@@ -1000,6 +1009,13 @@ async def _setup_working_directory(
log_progress(f"Downloading user-provided existing instrumental...")
storage.download_file(existing_instrumental_path, instrumental_path)
log_progress("Downloaded user-provided instrumental")
elif instrumental_selection == 'custom':
# Custom instrumental from mute-region editing
custom_url = job.file_urls['stems']['custom_instrumental']
instrumental_path = os.path.join(temp_dir, f"{base_name} (Instrumental Custom).flac")
log_progress("Downloading custom (mute-region) instrumental...")
storage.download_file(custom_url, instrumental_path)
log_progress("Downloaded custom instrumental")
else:
# Use AI-separated instrumental based on selection
instrumental_key = 'instrumental_clean' if instrumental_selection == 'clean' else 'instrumental_with_backing'
+12 -8
View File
@@ -731,6 +731,10 @@ def create_orchestrator_config_from_job(
instrumental_suffix = "Clean" if instrumental_selection == 'clean' else "Backing"
instrumental_path = os.path.join(temp_dir, f"{base_name} (Instrumental {instrumental_suffix}).flac")
# Get effective distribution settings (applies private track overrides if is_private=True)
from backend.services.job_defaults_service import get_effective_distribution_for_job
dist = get_effective_distribution_for_job(job)
return OrchestratorConfig(
job_id=job.job_id,
artist=job.artist,
@@ -750,18 +754,18 @@ def create_orchestrator_config_from_job(
# Feature flags
enable_cdg=getattr(job, 'enable_cdg', False),
enable_txt=getattr(job, 'enable_txt', False),
enable_youtube_upload=getattr(job, 'enable_youtube_upload', False),
enable_youtube_upload=dist.enable_youtube_upload,
# Service configurations
brand_prefix=getattr(job, 'brand_prefix', None),
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
# Service configurations (distribution settings from helper, respects is_private)
brand_prefix=dist.brand_prefix,
discord_webhook_url=dist.discord_webhook_url,
youtube_credentials=youtube_credentials,
youtube_description_template=getattr(job, 'youtube_description_template', None),
youtube_description_template=dist.youtube_description,
cdg_styles=cdg_styles,
# Dropbox/GDrive
dropbox_path=getattr(job, 'dropbox_path', None),
gdrive_folder_id=getattr(job, 'gdrive_folder_id', None),
# Dropbox/GDrive (overridden for private tracks)
dropbox_path=dist.dropbox_path,
gdrive_folder_id=dist.gdrive_folder_id,
# Keep existing brand code
keep_brand_code=getattr(job, 'keep_brand_code', None),
+84 -2
View File
@@ -77,6 +77,7 @@ Content-Type: multipart/form-data
file: <audio file>
artist: "Artist Name"
title: "Song Title"
is_private: false # Optional. If true, Dropbox uses Tracks-NonPublished/NOMADNP, no YouTube/GDrive
```
Returns job ID. Triggers async processing.
@@ -100,12 +101,15 @@ GET /api/jobs
GET /api/jobs?status=complete
GET /api/jobs?limit=10&offset=0
GET /api/jobs?exclude_test=false
GET /api/jobs?fields=summary&hide_completed=true
```
Query parameters:
- `exclude_test` (bool, default: true) - Admin only: filter out jobs from test users
- `status` - Filter by job status
- `limit` / `offset` - Pagination
- `fields` (string, optional) - Set to `summary` to return only dashboard-required fields using Firestore field projection. Reduces payload from ~16MB to <500KB for large job lists.
- `hide_completed` (bool, default: false) - Exclude terminal statuses (complete, prep_complete, failed, cancelled) server-side
#### Delete Job
@@ -166,7 +170,33 @@ Generates preview video during review. The `use_background_image` option control
GET /api/review/{job_id}/audio/{stem_type}
```
Streams audio for review playback.
Redirects to a signed GCS URL for review playback. Audio is served as OGG Opus (~3 MB) transcoded from the original FLAC (~35 MB). Transcoding happens eagerly during screen generation; if the transcoded file is missing, falls back to the original FLAC.
#### Create Custom Instrumental
```http
POST /api/jobs/{job_id}/create-custom-instrumental
Content-Type: application/json
{
"mute_regions": [
{"start_seconds": 17.0, "end_seconds": 42.0},
{"start_seconds": 53.8, "end_seconds": 71.4}
]
}
```
Creates a custom instrumental by muting selected regions of backing vocals, combining with the clean instrumental, and uploading to GCS. Returns a signed audio URL for immediate playback.
Response:
```json
{
"status": "success",
"message": "Custom instrumental created with 2 mute regions",
"audio_url": "https://storage.googleapis.com/...",
"muted_duration_seconds": 42.6
}
```
### Instrumental Selection (Finalise-Only Jobs)
@@ -348,7 +378,9 @@ POST /api/internal/jobs/{job_id}/trigger-video
Common status codes:
- `400` - Bad request
- `401` - Unauthorized
- `402` - Insufficient credits (see [Credit Enforcement](#credit-enforcement))
- `404` - Job not found
- `429` - Rate limit exceeded
- `500` - Server error
## User Authentication
@@ -448,6 +480,30 @@ After payment completes via Stripe webhook:
**Email suppression**: Intermediate reminder emails (lyrics review, instrumental selection) are suppressed for made-for-you jobs since admin handles these directly. Only order confirmation and final delivery emails go to customer
### Credit Enforcement
Credits are checked and deducted at job creation time. The flow:
1. **Check** - `user_service.has_credits()` verifies the user has >= 1 credit
2. **Create job** - Job is persisted to Firestore
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.
#### 402 Response
When a user has no credits, job creation returns HTTP 402:
```json
{
"detail": "You're out of credits. Buy more to continue creating karaoke videos.",
"credits_available": 0,
"credits_required": 1,
"buy_url": "/#pricing"
}
```
### Stripe Webhook
```http
@@ -858,7 +914,9 @@ Content-Type: application/json
}
```
Updates editable job fields. Allowed fields: `artist`, `title`, `user_email`, `theme_id`, `brand_prefix`, `discord_webhook_url`, `youtube_description`, `youtube_description_template`, `customer_email`, `customer_notes`, `enable_cdg`, `enable_txt`, `enable_youtube_upload`, `non_interactive`, `prep_only`.
Updates editable job fields. Allowed fields: `artist`, `title`, `user_email`, `theme_id`, `brand_prefix`, `discord_webhook_url`, `youtube_description`, `youtube_description_template`, `customer_email`, `customer_notes`, `enable_cdg`, `enable_txt`, `enable_youtube_upload`, `non_interactive`, `prep_only`, `is_private`.
**Note:** Setting `is_private=true` on a completed job with existing outputs triggers automatic output deletion.
Response:
```json
@@ -990,6 +1048,30 @@ Response:
Screen generation takes 30-60 seconds. Monitor progress via job timeline or logs.
#### Prepare Review Audio
```http
POST /api/admin/jobs/{job_id}/prepare-review-audio
Authorization: Bearer ADMIN_TOKEN
```
Transcodes all review audio files (input + stems) to OGG Opus 128kbps for fast browser playback. Idempotent — skips files already transcoded.
Use this to backfill existing jobs created before eager transcoding was deployed, or to re-transcode after stems are regenerated.
Response:
```json
{
"status": "success",
"job_id": "abc123",
"transcoded_files": [
"jobs/abc123/review-audio/song.ogg",
"jobs/abc123/review-audio/instrumental_clean.ogg"
],
"message": "Transcoded 2 files to OGG Opus"
}
```
#### Restart Job
```http
+3 -1
View File
@@ -55,10 +55,11 @@
└────────┬────────┘ └────────┬────────┘
└──────────┬───────────┘
▼
3. SCREENS GENERATION + BACKING VOCALS ANALYSIS
3. SCREENS GENERATION + BACKING VOCALS ANALYSIS + AUDIO TRANSCODING
• Title screen (5s video)
• End screen (5s video)
• Analyze backing vocals track (for instrumental selection)
• Transcode audio to OGG Opus for review UI (~3 MB vs 35 MB FLAC)
▼
4. COMBINED HUMAN REVIEW (AWAITING_REVIEW)
• React UI for lyrics correction
@@ -228,6 +229,7 @@ The Video Worker uses an orchestrator pattern to ensure all features work regard
| `email_service.py` | SendGrid email delivery with CC support |
| `template_service.py` | GCS-backed email templates |
| `job_notification_service.py` | Email orchestration (completion, reminders) |
| `audio_transcoding_service.py` | Transcode FLAC → OGG Opus for review UI playback |
## Audio Source Download Flow
+162
View File
@@ -0,0 +1,162 @@
# GCP Cost Optimization Analysis
**Date:** February 10, 2026
**Current Spend:** ~$6,000/month (~$200/day)
**Target:** Sustainable burn rate
## Executive Summary
Analyzed GCP billing data and identified $1,440+/month in immediate savings through GitHub runner auto-scaling (implemented). Additional opportunities identified for Cloud Run optimization (~$3,200/month potential savings).
## Cost Breakdown (Before Optimization)
| Service | Monthly Cost | % of Total | Notes |
|---------|--------------|------------|-------|
| **Cloud Run (karaoke-backend)** | ~$3,200 | 53% | concurrency=1, 4 min instances, 8 CPU, 16GB RAM |
| **GitHub Actions Runners** | ~$1,440 | 24% | 20 VMs running 24/7 |
| **GCE Encoding Worker** | ~$700 | 12% | c4d-highcpu-32 running 24/7 |
| **Cloud Storage** | ~$400 | 7% | 2.3TB storage |
| **Artifact Registry** | ~$78 | 1% | 390GB Docker images |
| **Other Services** | ~$182 | 3% | NAT, Load Balancers, etc. |
| **Total** | **~$6,000** | 100% | |
## Implemented Optimizations
### ✅ GitHub Actions Runners Auto-Scaling
**Status:** Deployed and operational (February 10, 2026)
**Changes Made:**
- Reduced from 20 VMs to 3 Spot/Preemptible instances
- Implemented auto-start on CI job queue (via GitHub webhook)
- Implemented auto-stop after 1 hour idle (via Cloud Scheduler)
- Removed external IPs (using Cloud NAT instead)
**Cost Impact:**
- **Before:** 20 VMs × $72/month = $1,440/month
- **After:** 3 Spot VMs × $25/month × ~20% utilization = $50-100/month
- **Savings:** ~$1,340-1,390/month (93% reduction)
**Implementation:**
- PRs: [#376](https://github.com/nomadkaraoke/karaoke-gen/pull/376), [#383](https://github.com/nomadkaraoke/karaoke-gen/pull/383), [#385](https://github.com/nomadkaraoke/karaoke-gen/pull/385)
- Infrastructure: `infrastructure/modules/runner_manager.py`, `infrastructure/compute/github_runners.py`
- Webhook: Configured at org level for all repos
- Monitoring: Cloud Function logs, Cloud Scheduler jobs
**Technical Details:**
```
Function: github-runner-manager
Memory: 512M
Idle Timeout: 1 hour
Check Frequency: Every 15 minutes
Webhook URL: https://us-central1-nomadkaraoke.cloudfunctions.net/github-runner-manager
```
## Pending Optimization Opportunities
### 🔍 Cloud Run Configuration (High Priority)
**Current Issue:**
- `concurrency=1` forces one request per instance
- `min-instances=4` keeps 4 instances always running
- High CPU/RAM allocation (8 CPU, 16GB) per instance
**Analysis Required:**
The `concurrency=1` setting may have been added deliberately for performance reasons. Investigation needed to determine:
1. Why was `concurrency=1` set? (performance issue, or unnecessary?)
2. Does `render_video_worker` run FFmpeg locally in Cloud Run? (CPU-intensive)
3. Can we increase concurrency without causing OOM or CPU contention?
**Potential Savings:** ~$2,400-3,000/month (if we can increase concurrency and reduce min-instances)
**Next Steps:**
1. Review git history for when `concurrency=1` was added and why
2. Profile render_video_worker memory/CPU usage during FFmpeg operations
3. Test with `concurrency=2-4` in staging environment
4. Monitor for OOM errors or performance degradation
### 🔍 GCE Encoding Worker
**Current State:**
- c4d-highcpu-32 VM running 24/7
- Cost: ~$700/month
**Opportunities:**
1. **Spot Instance:** Could save 60-91% (~$420-630/month savings)
- Risk: May be preempted during video encoding jobs
- Mitigation: Implement job restart logic
2. **Auto-scaling:** Start/stop based on video queue depth
- Could scale to zero when no jobs queued
- Startup time: ~2-3 minutes (acceptable for async processing)
**Recommendation:** Test Spot instance first (lower risk), then consider auto-scaling
### 🔧 Artifact Registry Cleanup (Quick Win)
**Current State:**
- 390GB of Docker images
- Cost: ~$78/month
- Many old images likely unused
**Action Items:**
```bash
# List images and their sizes
gcloud artifacts docker images list \
us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend \
--include-tags --format="table(package,version,create_time,size)"
# Set lifecycle policy to delete images older than 30 days (keep 10 most recent)
gcloud artifacts repositories update karaoke-repo \
--location=us-central1 \
--cleanup-policy-dry-run \
--cleanup-policies='tagState=tagged,olderThan=30d,keep=10'
```
**Potential Savings:** ~$40-60/month
### 🔧 Billing Alerts (Risk Management)
**Status:** No billing alerts configured
**Recommendation:** Set up budget alerts
```bash
# Alert at 50%, 80%, 100% of $5,000/month budget
gcloud billing budgets create \
--billing-account=BILLING_ACCOUNT_ID \
--display-name="Monthly Budget Alert" \
--budget-amount=5000 \
--threshold-rule=percent=50 \
--threshold-rule=percent=80 \
--threshold-rule=percent=100
```
## Summary
### Immediate Results (Implemented)
- **$1,390/month saved** through GitHub runner auto-scaling
- **New monthly spend:** ~$4,600/month (24% reduction)
### Potential Additional Savings
- Cloud Run optimization: $2,400-3,000/month (requires investigation)
- Encoding Worker Spot: $420-630/month (moderate risk)
- Artifact Registry cleanup: $40-60/month (quick win)
- **Total potential:** $2,860-3,690/month additional savings
### Target State
If all optimizations implemented:
- **Current:** $6,000/month
- **After runner optimization:** $4,600/month
- **After all optimizations:** $1,200-1,800/month
- **Total reduction:** 70-80%
## References
- [GCP Pricing Calculator](https://cloud.google.com/products/calculator)
- [Cloud Run Pricing](https://cloud.google.com/run/pricing)
- [Spot VM Pricing](https://cloud.google.com/compute/docs/instances/spot)
- [GitHub Self-Hosted Runners](https://docs.github.com/en/actions/hosting-your-own-runners)
## Change Log
- **2026-02-10:** Initial analysis and GitHub runner optimization implemented
- **2026-02-10:** Runners reduced from 20 → 3 with auto-scaling, saving $1,390/month
+42 -1
View File
@@ -98,6 +98,47 @@ await run_video_worker(job_id, job_manager, storage)
### Worker Idempotency Must Complete the Lifecycle
When implementing idempotency checks that set `stage='running'` at start, workers MUST also set `stage='complete'` on success. Without the completion update, retries or reprocessing attempts will be blocked because the stage is permanently stuck at `'running'`. The fix in v0.108.14 added completion markers to render_video, video, and screens workers.
### pip Wheel Filename Validation (Feb 2026)
**What happened**: Job 749141f8 failed with "Cannot connect to host 136.119.50.148:8080" during encoding. Investigation revealed the GCE encoding worker service had crashed and was restarting. The crash was caused by pip rejecting `karaoke_gen-current.whl` with "Invalid wheel filename (wrong number of parts)".
**Root cause**: The `ensure_latest_wheel()` function in `backend/services/gce_encoding/main.py` downloaded all wheels from GCS using a wildcard pattern (`karaoke_gen-*.whl`), which included `karaoke_gen-current.whl`. This file is a convenience symlink/copy for CI deployment but lacks the version and platform tags required by PEP 427 wheel naming standard (`{distribution}-{version}-{python}-{abi}-{platform}.whl`). When pip tried to install it, it failed, causing the worker to crash.
**Why it was confusing**: The actual error ("Cannot connect") masked the real problem (wheel installation failure). The service was healthy but kept restarting due to the pip error, making it temporarily unavailable when Cloud Run tried to connect.
**Fix**: Filter out wheels containing '-current' before selecting which to install:
```python
wheels = glob.glob("/tmp/karaoke_gen-*.whl")
# Filter out karaoke_gen-current.whl (not a valid PEP 427 wheel name)
wheels = [w for w in wheels if '-current' not in w]
```
**Pattern**: When downloading artifacts with wildcards, filter results to exclude non-standard naming patterns before processing. CI convenience files (symlinks, "latest", "current") often don't follow the same naming conventions as versioned releases. Always validate artifact names match expected patterns before attempting to use them.
### Semantic Version Sorting (Feb 2026)
**What happened**: PR #384 fixed the invalid wheel filename crash but exposed a version sorting bug. Production encoder started showing "Encoder: v0.99.9" instead of the latest v0.116.1. The GCE encoding worker was running an extremely old version from months ago.
**Root cause**: After filtering out invalid wheels, the code used `sorted(wheels)[-1]` to select the "latest" wheel. This does **alphabetical sorting**, not semantic version sorting. String comparison puts "karaoke_gen-0.99.9-..." AFTER "karaoke_gen-0.116.1-..." because '9' > '1' in the second character position.
**Why it's tricky**: For some version ranges, alphabetical sorting happens to work correctly (0.100.0 > 0.99.0), but fails for others (0.99.9 > 0.116.1). This makes the bug intermittent and hard to notice until a specific version combination triggers it.
**Fix**: Extract version numbers from filenames and sort using `packaging.version.Version`:
```python
from packaging.version import Version
import re
def extract_version(wheel_path):
"""Extract version from wheel filename like karaoke_gen-0.116.1-py3-none-any.whl"""
match = re.search(r'karaoke_gen-([0-9.]+)-', wheel_path)
if match:
return Version(match.group(1))
return Version("0.0.0") # Fallback for unparseable filenames
wheels.sort(key=extract_version, reverse=True)
latest_wheel = wheels[0]
```
**Pattern**: When selecting "latest" from a list of versioned artifacts (wheels, releases, tags), always use semantic version comparison, not string/alphabetical sorting. The `packaging` library is part of Python's standard packaging infrastructure and handles all semantic versioning edge cases (major.minor.patch, pre-releases, etc.). String sorting only works accidentally for some version ranges.
### Clear Worker Progress Keys When Reprocessing
When resetting a job or re-reviewing a completed job, all worker progress keys (`*_progress`) must be cleared from `state_data`. Workers check `state_data.{worker}_progress.stage == 'complete'` for idempotency - if stale keys exist from a previous run, workers will skip execution even though the job needs reprocessing. **Pattern**: Any operation that intends to re-run workers (admin reset, review resubmission) must explicitly clear progress keys using `job_manager.delete_state_data_keys()`. See `backend/api/routes/review.py:complete_review()` and `backend/api/routes/admin.py:clear_worker_state()`.
@@ -569,7 +610,7 @@ Set `min-instances > 0` for Cloud Run services with heavy initialization.
## Data & Storage
### Firestore 1MB Limit
Use subcollections for unbounded data (logs, events). Embedded arrays hit 1MB limit.
Use subcollections for unbounded data (logs, events). Embedded arrays hit 1MB limit. When saving large objects to Firestore `state_data`, strip fields not needed for Firestore queries (e.g. `reference_lyrics`) and store full data in GCS instead. The Genius API occasionally returns non-lyrics content (screenplays, articles) that can bloat documents past 1MB.
### Firestore Timezone-Aware
Firestore returns timezone-aware datetimes. Compare with `datetime.now(timezone.utc)`, not naive `datetime.now()`.
+7
View File
@@ -30,6 +30,7 @@
| CI/CD self-hosted runner | Working (GCP) |
| E2E happy path test | Working (~20-25 min full pipeline) |
| **White-label B2B portals** | Working (Vocal Star first tenant) |
| **Private (non-published) tracks** | Working |
## Known Issues
@@ -41,6 +42,12 @@
## Recent Changes
- **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).
- **GCE Encoding Worker Version Sorting Fix** (2026-02-11): Fixed critical regression from PR #384 where alphabetical sorting caused encoder to use v0.99.9 instead of v0.116.1. **Root cause**: `sorted(wheels)[-1]` uses string comparison, not semantic versioning. String comparison puts "0.99.9" > "0.116.1" (because '9' > '1' in second position). **Impact**: Production encoder was running an extremely old version (v0.99.9 from months ago) instead of the latest (v0.116.1). **Fix**: Extract version from wheel filename using regex, sort by `packaging.version.Version` objects instead of strings. Added 10 comprehensive unit tests covering the exact regression case (0.99.9 vs 0.116.1), edge cases (empty list, invalid filenames), and complex version comparisons (major/minor/patch). Production now correctly selects the latest semantic version. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#semantic-version-sorting-feb-2026).
- **GCE Encoding Worker Wheel Fix** (2026-02-10): Fixed encoding worker crash caused by attempting to install `karaoke_gen-current.whl`, which is not a valid PEP 427 wheel filename (missing version and platform tags). **Root cause**: The `ensure_latest_wheel()` function downloaded all wheels including `karaoke_gen-current.whl`, then tried to install it. pip rejected it with "Invalid wheel filename (wrong number of parts)", causing encoding to fail and the service to restart, resulting in "Cannot connect" errors from Cloud Run. **Fix**: Filter out wheels containing '-current' before selecting which wheel to install. Only properly versioned wheels (e.g., `karaoke_gen-0.116.0-py3-none-any.whl`) are now considered. Added 5 comprehensive unit tests covering current wheel exclusion, empty results, version sorting, and path-agnostic filtering. Fixes job 749141f8 and prevents future encoding failures. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#pip-wheel-filename-validation-feb-2026).
- **Flacfetch Retry Logic & Audio Search Recovery** (2026-02-10): Added comprehensive retry logic for flacfetch download failures to handle transient network issues and service restarts. Jobs now retry downloads up to 9 times over ~6 minutes with exponential backoff (10s → 20s → 40s → 60s capped), significantly reducing failures from temporary network hiccups. **Key improvements**: (1) Retry logic with selective error handling (retries on connection errors and 5xx, immediate fail on 4xx), (2) State persistence - download parameters (source_name, source_id, target_file, download_url) now saved BEFORE download attempt, enabling retry even if download fails, (3) Enhanced retry endpoint - `/api/jobs/{id}/retry` now handles audio search jobs by re-downloading using saved params, (4) User feedback - retry button now shows error toast with actual API error message instead of silent failures. Added 5 comprehensive retry tests covering network errors, 4xx/5xx responses, max retries, and exponential backoff timing. Job 749141f8 investigation revealed the root cause: no source info was saved when flacfetch calls failed, making retry impossible. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#retry-transient-failures-feb-2026) for retry implementation patterns.
- **CDG Sync Fix for Countdown-Padded Songs** (2026-02-05): Fixed CDG files being 3 seconds out of sync with audio when songs have countdown padding applied. **Root cause**: Video rendering adds 3s countdown padding to audio AND shifts LRC timestamps by +3s. CDG generation was using these countdown-shifted LRC timestamps but with instrumental audio (which has no countdown padding), causing lyrics to appear 3s late. **Fix**: CDG generator now receives `lrc_has_countdown_padding` flag; when True, it strips the countdown segment and shifts timestamps back before generating the CDG. Added 11 unit tests and updated orchestrator/packaging pipeline. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#fix-both-sides-of-dual-code-paths).
@@ -0,0 +1,279 @@
# Plan: Private (Non-Published) Tracks
**Created:** 2026-02-24
**Branch:** feat/sess-20260224-1149-private-tracks
**Status:** Draft
## Overview
Add a `is_private` flag to jobs that changes distribution behavior:
- **Dropbox**: Uses `Tracks-NonPublished` folder (not `Tracks-Organized`) with brand code `NOMADNP` (not `NOMAD`)
- **YouTube**: Skipped entirely
- **Google Drive**: Skipped entirely
- **Email**: Completion email includes Dropbox link but no YouTube section
- **Discord**: Still notified (for internal tracking)
Available to all users at job creation and toggleable by admin on existing jobs.
## Requirements
- [ ] All users can mark a job as "Private (Non-Published)" when creating it
- [ ] Admin can toggle `is_private` on any existing job via admin dashboard
- [ ] Private jobs upload to Dropbox at `Tracks-NonPublished` with `NOMADNP-XXXX` brand codes
- [ ] Private jobs skip YouTube and Google Drive uploads entirely
- [ ] Completion emails omit YouTube section when no YouTube URL (private jobs + any other edge case)
- [ ] When admin toggles a completed job to private, existing outputs are auto-deleted
- [ ] Discord notifications still fire for private jobs
- [ ] Existing (non-private) jobs are completely unaffected (backward compatible)
## Technical Approach
### Core Design: Single Boolean Flag with Runtime Overrides
Store `is_private: bool = False` on the job model. At distribution time, a helper function returns effective distribution parameters based on this flag. This means:
- **Toggling is_private automatically changes all distribution behavior** - no need to manually update dropbox_path, brand_prefix, enable_youtube_upload, gdrive_folder_id
- **Job fields still store the "normal" defaults** - the override happens at the config-to-orchestrator boundary
- **Admin can flip one field** and everything adapts
### Key Helper Function
```python
# In job_defaults_service.py
def get_effective_distribution_for_job(job) -> EffectiveDistributionSettings:
"""Return distribution settings, applying private overrides if is_private=True."""
if getattr(job, 'is_private', False):
settings = get_settings()
return EffectiveDistributionSettings(
dropbox_path=settings.default_private_dropbox_path,
brand_prefix=settings.default_private_brand_prefix,
enable_youtube_upload=False,
gdrive_folder_id=None,
# Keep other settings from job (discord, youtube_description, etc.)
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
youtube_description=None,
)
# Non-private: return job's own settings
return EffectiveDistributionSettings(
dropbox_path=getattr(job, 'dropbox_path', None),
brand_prefix=getattr(job, 'brand_prefix', None),
enable_youtube_upload=getattr(job, 'enable_youtube_upload', False),
gdrive_folder_id=getattr(job, 'gdrive_folder_id', None),
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
youtube_description=getattr(job, 'youtube_description_template', None),
)
```
This helper is used in both distribution paths (orchestrator and native fallback).
### Distribution Paths That Need Changes
Two code paths handle distribution (see LESSONS-LEARNED: "Fix Both Sides of Dual Code Paths"):
1. **Orchestrator path** (`video_worker_orchestrator.py`): Primary path. `create_orchestrator_config_from_job()` uses the helper to build config.
2. **Native distribution path** (`video_worker.py` → `_handle_native_distribution()`): Fallback path. Also uses the helper instead of reading job fields directly.
### Email Template Change
Add conditional YouTube section removal in `render_template()`, matching the existing pattern for `feedback_url`:
```python
# Remove YouTube section if no URL provided
if not variables.get("youtube_url"):
result = re.sub(
r"\n*Here's the link for the karaoke video published to YouTube:\n\{youtube_url\}\n*",
'\n',
result,
flags=re.DOTALL
)
variables["youtube_url"] = ""
```
And change `render_job_completion()` to pass `None` instead of `"[YouTube URL not available]"` when youtube_url is empty.
### Admin Toggle Auto-Delete
When admin PATCH updates `is_private` from False to True on a job that has existing outputs, reuse the existing delete-outputs logic to remove YouTube + GDrive + Dropbox outputs. Admin can then "Reprocess" to re-distribute to the private Dropbox path.
## Implementation Steps
### Phase 1: Backend Model & Config (foundation)
1. [ ] **Add `is_private` to Job model** (`backend/models/job.py`)
- Add `is_private: bool = False` field after `made_for_you` field
- Add to `JobCreate` model as well
2. [ ] **Add private distribution config** (`backend/config.py`)
- Add `default_private_dropbox_path: Optional[str] = os.getenv("DEFAULT_PRIVATE_DROPBOX_PATH")`
- Add `default_private_brand_prefix: Optional[str] = os.getenv("DEFAULT_PRIVATE_BRAND_PREFIX", "NOMADNP")`
3. [ ] **Add helper function** (`backend/services/job_defaults_service.py`)
- Add `get_effective_distribution_for_job(job)` function that returns distribution settings with private overrides applied
### Phase 2: Backend API (job creation + admin)
4. [ ] **Add `is_private` to request models** (`backend/models/requests.py`)
- Add `is_private: Optional[bool] = None` to `URLSubmissionRequest`
- Add `is_private: Optional[bool] = None` to `AudioSearchRequest`
5. [ ] **Update URL creation endpoint** (`backend/api/routes/jobs.py`)
- Accept and pass through `is_private` field to `JobCreate`
6. [ ] **Update file upload endpoint** (`backend/api/routes/file_upload.py`)
- Accept `is_private` Form parameter
- Pass through to `JobCreate`
7. [ ] **Update audio search endpoint** (`backend/api/routes/audio_search.py`)
- Accept `is_private` in `AudioSearchRequest`
- Pass through to `JobCreate`
8. [ ] **Update admin endpoints** (`backend/api/routes/admin.py`)
- Add `is_private: Optional[bool] = None` to `JobUpdateRequest`
- Add `"is_private"` to `EDITABLE_JOB_FIELDS`
- In the PATCH handler: detect when `is_private` changes from False→True on a completed job, auto-delete existing outputs (call existing delete-outputs service logic)
### Phase 3: Distribution Pipeline
9. [ ] **Update orchestrator config creation** (`backend/workers/video_worker_orchestrator.py`)
- In `create_orchestrator_config_from_job()`: Use `get_effective_distribution_for_job()` helper to determine dropbox_path, brand_prefix, enable_youtube_upload, gdrive_folder_id instead of reading directly from job
10. [ ] **Update native distribution fallback** (`backend/workers/video_worker.py`)
- In `_handle_native_distribution()`: Use `get_effective_distribution_for_job()` helper instead of reading directly from job fields
### Phase 4: Email Template
11. [ ] **Add YouTube section conditional removal** (`backend/services/template_service.py`)
- In `render_template()`: Add regex to remove YouTube paragraph when `youtube_url` is empty (matching existing `feedback_url` pattern)
- In `render_job_completion()`: Pass `None` for youtube_url when empty (instead of `"[YouTube URL not available]"`)
### Phase 5: Frontend
12. [ ] **Add private checkbox to job creation form** (`frontend/components/job/JobSubmission.tsx`)
- Add "Private (Non-Published)" checkbox below the existing "Skip lyrics review" checkbox
- Show for all users (not just admin)
- Include brief description text: "Private tracks go to Dropbox only, not YouTube or Google Drive"
13. [ ] **Update API interfaces** (`frontend/lib/api.ts`)
- Add `is_private?: boolean` to all job creation option interfaces
- Add `is_private` to `JobUpdateRequest` interface
- Pass through in `uploadJob()`, `createJobFromUrl()`, `searchAudio()` methods
14. [ ] **Add private toggle to admin job detail** (`frontend/app/admin/jobs/page.tsx`)
- Add `is_private` as an inline-editable field in the job overview section (use Switch component)
- Show current state with visual indicator (e.g., lock icon for private jobs)
- When toggling to private on a completed job, show confirmation dialog about auto-deleting outputs
### Phase 6: Environment Configuration
15. [ ] **Update CI/deployment config** (`.github/workflows/ci.yml` or Cloud Run env)
- Add `DEFAULT_PRIVATE_DROPBOX_PATH` environment variable (e.g., `/Karaoke/Tracks-NonPublished`)
- Add `DEFAULT_PRIVATE_BRAND_PREFIX` environment variable (e.g., `NOMADNP`)
- These should be configured in Cloud Run service and CI test environment
### Phase 7: Testing
16. [ ] **Unit tests for private distribution logic** (`backend/tests/test_private_tracks.py`)
- Test `get_effective_distribution_for_job()` with private and non-private jobs
- Test `create_orchestrator_config_from_job()` applies private overrides correctly
- Test `_run_distribution()` skips YouTube and GDrive when private config applied
- Test `_upload_to_dropbox()` uses private path and brand prefix
- Test brand code generation with NOMADNP prefix in Tracks-NonPublished
- Test `_handle_native_distribution()` respects private overrides
- Test non-private jobs are completely unaffected (regression tests)
17. [ ] **Unit tests for email changes** (add to `backend/tests/test_email_service.py` or `test_template_service.py`)
- Test YouTube section removed from email when youtube_url is None
- Test YouTube section present when youtube_url is provided
- Test Dropbox section still present for private jobs
- Test full email rendering for private job scenario
18. [ ] **Unit tests for admin toggle** (add to `backend/tests/test_admin.py` or new file)
- Test admin can update is_private field
- Test toggling is_private to True on completed job triggers output deletion
- Test toggling is_private to True on non-completed job does NOT delete outputs
- Test toggling is_private to False does nothing special
19. [ ] **Integration test** (`backend/tests/emulator/` or `test_distribution_services.py`)
- Test full distribution pipeline with is_private=True: verify Dropbox path, brand prefix, YouTube skip, GDrive skip
20. [ ] **Frontend E2E regression test** (`frontend/e2e/regression/`)
- Test private checkbox appears in job creation form
- Test private toggle in admin dashboard
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `backend/models/job.py` | Modify | Add `is_private: bool = False` to Job and JobCreate |
| `backend/config.py` | Modify | Add `default_private_dropbox_path` and `default_private_brand_prefix` |
| `backend/services/job_defaults_service.py` | Modify | Add `get_effective_distribution_for_job()` helper |
| `backend/models/requests.py` | Modify | Add `is_private` to URL and AudioSearch request models |
| `backend/api/routes/jobs.py` | Modify | Accept and pass `is_private` |
| `backend/api/routes/file_upload.py` | Modify | Accept and pass `is_private` |
| `backend/api/routes/audio_search.py` | Modify | Accept and pass `is_private` |
| `backend/api/routes/admin.py` | Modify | Add `is_private` to editable fields + auto-delete logic |
| `backend/workers/video_worker_orchestrator.py` | Modify | Use helper in `create_orchestrator_config_from_job()` |
| `backend/workers/video_worker.py` | Modify | Use helper in `_handle_native_distribution()` |
| `backend/services/template_service.py` | Modify | Conditional YouTube section removal |
| `frontend/components/job/JobSubmission.tsx` | Modify | Add private checkbox |
| `frontend/lib/api.ts` | Modify | Add `is_private` to interfaces and API calls |
| `frontend/app/admin/jobs/page.tsx` | Modify | Add private toggle to admin detail |
| `backend/tests/test_private_tracks.py` | Create | Comprehensive unit tests for private track logic |
## Testing Strategy
### Unit Tests (~25-30 tests in `test_private_tracks.py`)
- `get_effective_distribution_for_job()` with private=True and False
- `create_orchestrator_config_from_job()` private overrides (YouTube=False, GDrive=None, private Dropbox path, NOMADNP brand)
- Distribution stage skips: YouTube not called, GDrive not called, Dropbox IS called with correct path
- Brand code generation uses NOMADNP prefix and Tracks-NonPublished path
- Native distribution fallback applies same overrides
- **Regression tests**: Non-private jobs have unchanged behavior (same paths, same brand code, YouTube+GDrive+Dropbox all fire)
### Email Template Tests (~5 tests)
- YouTube section stripped when youtube_url is None
- YouTube section preserved when youtube_url has value
- Dropbox section always present
- Full private job email rendering (Dropbox + no YouTube)
- Full non-private job email rendering (both present) - regression
### Admin Toggle Tests (~5 tests)
- is_private editable via PATCH
- Toggle to private on completed job deletes outputs
- Toggle to private on pending/in-progress job does NOT delete
- Toggle to non-private does nothing special
### Frontend Tests
- E2E: Private checkbox visible and functional in job creation
- E2E: Admin toggle visible and includes confirmation dialog
### Manual Verification
- Create a private job end-to-end, verify Dropbox folder in Tracks-NonPublished with NOMADNP code
- Verify completion email has Dropbox link but no YouTube section
- Toggle existing completed job to private, verify outputs deleted
## Regression Risk Analysis
| Risk | Mitigation |
|------|-----------|
| Non-private jobs affected | `is_private` defaults to `False`; helper returns unchanged values for non-private. Explicit regression tests. |
| Dual code paths (orchestrator vs native) | Both paths use same helper function. Tests cover both paths. (Lesson: "Fix Both Sides of Dual Code Paths") |
| Email template regex breaks other content | Regex targets specific YouTube paragraph text. Tests verify non-YouTube content untouched. |
| Brand code namespace collision | NOMADNP codes are in a completely separate Dropbox folder (Tracks-NonPublished), no overlap with NOMAD codes in Tracks-Organized |
| Admin auto-delete on wrong job | Only triggers when `is_private` changes from False→True AND job has terminal status (complete). Confirmation dialog in frontend. |
| Made-for-you orders | MFY webhook doesn't set is_private (defaults False). Admin can toggle after. No change to MFY flow. |
| Existing Firestore documents | Missing `is_private` field defaults to `False` via model default. No migration needed. |
## Open Questions
- [x] Who sees private toggle? → **Everyone** (all users at creation, admin on existing)
- [x] Auto-delete on toggle? → **Yes**, auto-delete all outputs when toggling to private on completed job
- [x] Email format? → **Remove YouTube section** when no YouTube URL (improves all edge cases)
- [x] Discord? → **Still notify** (useful for internal tracking)
## Rollback Plan
1. **Feature flag**: The `is_private` field defaults to `False`, so setting `DEFAULT_PRIVATE_DROPBOX_PATH` to empty/None effectively disables private distribution
2. **No schema migration needed**: Missing `is_private` field on existing Firestore documents defaults to `False`
3. **Email change is backward-compatible**: The YouTube section removal only happens when youtube_url is None, which is already an edge case showing "[YouTube URL not available]"
4. **Frontend**: Private checkbox is additive UI, removing it just means users can't create new private jobs
+136 -1
View File
@@ -2,7 +2,7 @@
* Unit tests for job-status.ts utility functions
*/
import { getJobStep, formatStepIndicator, isBlockingStatus, getJobProgressPercent, getJobPriority, sortJobsByPriority, JobStep } from '../lib/job-status';
import { getJobStep, formatStepIndicator, isBlockingStatus, getJobProgressPercent, getJobPriority, sortJobsByPriority, getDisplayJobs, JobStep } from '../lib/job-status';
import type { Job } from '../lib/api';
// Helper to create a minimal Job object for testing
@@ -595,3 +595,138 @@ describe('sortJobsByPriority', () => {
expect(sorted[4].status).toBe('failed'); // failed
});
});
describe('getDisplayJobs', () => {
// Helper: pre-sorted jobs (blocking, processing, complete, failed)
function createSortedJobs(counts: { blocking?: number; processing?: number; complete?: number; failed?: number }): Job[] {
const jobs: Job[] = [];
let t = 20; // descending timestamp within each priority group
for (let i = 0; i < (counts.blocking ?? 0); i++) {
jobs.push({ job_id: `blocking-${i}`, status: 'awaiting_review', progress: 0, created_at: `2024-01-01T${t--}:00:00Z`, updated_at: '2024-01-01T00:00:00Z' });
}
for (let i = 0; i < (counts.processing ?? 0); i++) {
jobs.push({ job_id: `processing-${i}`, status: 'rendering_video', progress: 0, created_at: `2024-01-01T${t--}:00:00Z`, updated_at: '2024-01-01T00:00:00Z' });
}
for (let i = 0; i < (counts.complete ?? 0); i++) {
jobs.push({ job_id: `complete-${i}`, status: 'complete', progress: 100, created_at: `2024-01-01T${t--}:00:00Z`, updated_at: '2024-01-01T00:00:00Z' });
}
for (let i = 0; i < (counts.failed ?? 0); i++) {
jobs.push({ job_id: `failed-${i}`, status: 'failed', progress: 0, created_at: `2024-01-01T${t--}:00:00Z`, updated_at: '2024-01-01T00:00:00Z' });
}
return jobs;
}
it('returns all jobs when fewer than display limit', () => {
const jobs = createSortedJobs({ complete: 3 });
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5);
expect(displayedJobs).toHaveLength(3);
expect(totalFetched).toBe(3);
});
it('returns empty array for empty input', () => {
const { displayedJobs, totalFetched } = getDisplayJobs([], 5);
expect(displayedJobs).toHaveLength(0);
expect(totalFetched).toBe(0);
});
it('limits to displayLimit when no incomplete jobs', () => {
const jobs = createSortedJobs({ complete: 10 });
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5);
expect(displayedJobs).toHaveLength(5);
expect(totalFetched).toBe(10);
});
it('expands beyond limit when more incomplete than limit', () => {
const jobs = createSortedJobs({ blocking: 3, processing: 4, complete: 5 });
const { displayedJobs } = getDisplayJobs(jobs, 5);
// 7 incomplete > limit of 5, so show all 7
expect(displayedJobs).toHaveLength(7);
expect(displayedJobs.filter(j => j.status === 'awaiting_review')).toHaveLength(3);
expect(displayedJobs.filter(j => j.status === 'rendering_video')).toHaveLength(4);
});
it('fills remaining slots with completed when fewer incomplete than limit', () => {
const jobs = createSortedJobs({ blocking: 1, processing: 1, complete: 10 });
const { displayedJobs } = getDisplayJobs(jobs, 5);
// 2 incomplete < 5 limit, so show 5 total (2 incomplete + 3 completed)
expect(displayedJobs).toHaveLength(5);
expect(displayedJobs[0].status).toBe('awaiting_review');
expect(displayedJobs[1].status).toBe('rendering_video');
expect(displayedJobs[2].status).toBe('complete');
});
it('returns all jobs when displayLimit is -1 (All mode)', () => {
const jobs = createSortedJobs({ blocking: 2, complete: 20 });
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, -1);
expect(displayedJobs).toHaveLength(22);
expect(totalFetched).toBe(22);
});
it('preserves sort order from input', () => {
const jobs = createSortedJobs({ blocking: 1, processing: 1, complete: 3 });
const { displayedJobs } = getDisplayJobs(jobs, 5);
expect(displayedJobs[0].status).toBe('awaiting_review');
expect(displayedJobs[1].status).toBe('rendering_video');
expect(displayedJobs[2].status).toBe('complete');
expect(displayedJobs[3].status).toBe('complete');
expect(displayedJobs[4].status).toBe('complete');
});
describe('hideCompleted filter', () => {
it('filters out complete and failed jobs when hideCompleted is true', () => {
const jobs = createSortedJobs({ blocking: 1, processing: 2, complete: 5, failed: 3 });
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, -1, true);
expect(totalFetched).toBe(11);
expect(displayedJobs).toHaveLength(3);
expect(displayedJobs.every(j => j.status === 'awaiting_review' || j.status === 'rendering_video')).toBe(true);
});
it('respects display limit after filtering', () => {
const jobs = createSortedJobs({ blocking: 2, processing: 5, complete: 10 });
const { displayedJobs } = getDisplayJobs(jobs, 5, true);
// 7 incomplete jobs, all visible since incomplete count (7) > limit (5)
expect(displayedJobs).toHaveLength(7);
});
it('returns empty when all jobs are complete and hideCompleted is true', () => {
const jobs = createSortedJobs({ complete: 10 });
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5, true);
expect(displayedJobs).toHaveLength(0);
expect(totalFetched).toBe(10);
});
it('does not filter when hideCompleted is false', () => {
const jobs = createSortedJobs({ blocking: 1, complete: 5, failed: 2 });
const { displayedJobs } = getDisplayJobs(jobs, -1, false);
expect(displayedJobs).toHaveLength(8);
});
it('defaults to showing all when hideCompleted is omitted', () => {
const jobs = createSortedJobs({ complete: 5, failed: 2 });
const { displayedJobs } = getDisplayJobs(jobs, -1);
expect(displayedJobs).toHaveLength(7);
});
});
it('core bug: old incomplete job visible even when recent jobs are all completed', () => {
// Simulate the bug scenario: 5 recent completed jobs + 1 older blocking job
// With old behavior (LIMIT 5 at query), the blocking job would never be fetched.
// With new behavior, all 6 are fetched and display limit of 5 expands to show blocking.
const jobs = sortJobsByPriority([
{ job_id: 'old-blocking', status: 'awaiting_review', progress: 0, created_at: '2024-01-01T01:00:00Z', updated_at: '2024-01-01T01:00:00Z' },
{ job_id: 'new-1', status: 'complete', progress: 100, created_at: '2024-01-10T01:00:00Z', updated_at: '2024-01-10T01:00:00Z' },
{ job_id: 'new-2', status: 'complete', progress: 100, created_at: '2024-01-09T01:00:00Z', updated_at: '2024-01-09T01:00:00Z' },
{ job_id: 'new-3', status: 'complete', progress: 100, created_at: '2024-01-08T01:00:00Z', updated_at: '2024-01-08T01:00:00Z' },
{ job_id: 'new-4', status: 'complete', progress: 100, created_at: '2024-01-07T01:00:00Z', updated_at: '2024-01-07T01:00:00Z' },
{ job_id: 'new-5', status: 'complete', progress: 100, created_at: '2024-01-06T01:00:00Z', updated_at: '2024-01-06T01:00:00Z' },
]);
const { displayedJobs } = getDisplayJobs(jobs, 5);
// The blocking job must be visible
const blockingJobs = displayedJobs.filter(j => j.status === 'awaiting_review');
expect(blockingJobs).toHaveLength(1);
expect(blockingJobs[0].job_id).toBe('old-blocking');
// Should show 5 total (1 incomplete + 4 completed, since limit is 5 and max(5, 1) = 5)
expect(displayedJobs).toHaveLength(5);
});
});
+35
View File
@@ -1210,6 +1210,41 @@ function AdminJobsPageContent() {
)}
</div>
))}
{/* Private (non-published) toggle */}
<div className="flex items-center gap-2 pt-2 border-t">
<span className="text-[10px] font-medium text-muted-foreground uppercase w-20 shrink-0">Private</span>
<div className="flex items-center gap-2 flex-1">
<input
type="checkbox"
id="admin-is-private"
checked={selectedJob.is_private || false}
onChange={async (e) => {
const newValue = e.target.checked
try {
await adminApi.updateJob(selectedJobId!, { is_private: newValue })
setSelectedJob({ ...selectedJob, is_private: newValue })
toast({
title: "Updated",
description: newValue
? "Job set to private (outputs will be auto-deleted if completed)"
: "Job set to public",
})
} catch (err: any) {
toast({
title: "Error",
description: err.message || "Failed to update private flag",
variant: "destructive",
})
}
}}
className="w-3.5 h-3.5 rounded border-border accent-orange-500"
/>
<label htmlFor="admin-is-private" className="text-xs cursor-pointer">
Non-published (Dropbox only, no YouTube/GDrive)
</label>
</div>
</div>
</CardContent>
</Card>
+60 -14
View File
@@ -1,6 +1,6 @@
"use client"
import { useState, useEffect, useCallback, Suspense, useRef } from "react"
import { useState, useEffect, useCallback, useMemo, Suspense, useRef } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { api, Job, getAccessToken } from "@/lib/api"
import { useAuth } from "@/lib/auth"
@@ -15,8 +15,8 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Music2, RefreshCw, Loader2, Moon, Sun } from "lucide-react"
import { sortJobsByPriority } from "@/lib/job-status"
import { Music2, RefreshCw, Loader2, Moon, Sun, Eye, EyeOff } 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"
@@ -35,7 +35,7 @@ import {
function AppPageContent() {
const router = useRouter()
const searchParams = useSearchParams()
const [jobs, setJobs] = useState<Job[]>([])
const [allJobs, setAllJobs] = useState<Job[]>([])
const [isLoadingJobs, setIsLoadingJobs] = useState(true)
const [isInitialLoad, setIsInitialLoad] = useState(true)
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null)
@@ -44,11 +44,25 @@ function AppPageContent() {
const { isDarkMode, toggleTheme, mounted } = useTheme()
const { user, fetchUser, verifyMagicLink } = useAuth()
const { showTestData } = useAdminSettings()
const [jobLimit, setJobLimit] = useState<number>(5)
const [jobLimit, setJobLimit] = useState<number>(() => {
if (typeof window === "undefined") return 10
const saved = localStorage.getItem("nomad-karaoke-job-limit")
return saved ? Number(saved) : 10
})
const [hideCompleted, setHideCompleted] = useState<boolean>(() => {
if (typeof window === "undefined") return false
return localStorage.getItem("nomad-karaoke-hide-completed") === "true"
})
// 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)
const { displayedJobs: jobs, totalFetched } = useMemo(
() => getDisplayJobs(allJobs, jobLimit, hideCompleted),
[allJobs, jobLimit, hideCompleted]
)
// Memoize loadJobs for use with visibility refresh
const loadJobs = useCallback(async () => {
if (!getAccessToken()) {
@@ -57,13 +71,15 @@ function AppPageContent() {
return
}
try {
// Only admins can filter test jobs, and by default we hide them
// Use summary mode for reduced payload (~12 fields instead of 50+)
const data = await api.listJobs({
limit: jobLimit === -1 ? 100 : jobLimit,
exclude_test: isAdmin ? !showTestData : undefined
limit: 100,
exclude_test: isAdmin ? !showTestData : undefined,
fields: 'summary',
hide_completed: hideCompleted,
})
// Sort: blocking jobs first, then processing, then completed
setJobs(sortJobsByPriority(data))
setAllJobs(sortJobsByPriority(data))
} catch (err: any) {
// Don't log auth errors - user just needs to authenticate
if (err?.status !== 401) {
@@ -73,10 +89,10 @@ function AppPageContent() {
setIsLoadingJobs(false)
setIsInitialLoad(false)
}
}, [isAdmin, showTestData, jobLimit])
}, [isAdmin, showTestData, hideCompleted])
// Enable notifications for job status changes (sound + title animation)
useJobNotifications(jobs)
useJobNotifications(allJobs)
// Refresh jobs immediately when tab becomes visible (after returning from review UIs)
useVisibilityRefresh(loadJobs, isAuthenticated === true)
@@ -158,7 +174,7 @@ function AppPageContent() {
return (
<div className="min-h-screen animated-gradient">
{/* AutoProcessor - handles non-interactive mode for jobs with that flag */}
<AutoProcessor jobs={jobs} onJobsChanged={loadJobs} />
<AutoProcessor jobs={allJobs} onJobsChanged={loadJobs} />
{/* Header */}
<header className="fixed top-0 left-0 right-0 z-50 bg-dark-900/80 backdrop-blur-md border-b border-dark-700">
@@ -235,7 +251,33 @@ function AppPageContent() {
<CardTitle style={{ color: 'var(--text)' }}>Recent Jobs</CardTitle>
<div className="flex items-center gap-2">
{isLoadingJobs && <Loader2 className="w-4 h-4 animate-spin" style={{ color: 'var(--text-muted)' }} />}
<Select value={String(jobLimit)} onValueChange={(v) => setJobLimit(Number(v))}>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-7 w-7 p-0"
style={{ color: 'var(--text-muted)' }}
onClick={() => {
const next = !hideCompleted
setHideCompleted(next)
localStorage.setItem("nomad-karaoke-hide-completed", String(next))
}}
>
{hideCompleted ? <EyeOff className="w-3.5 h-3.5" /> : <Eye className="w-3.5 h-3.5" />}
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">
<p>{hideCompleted ? "Show all jobs" : "Hide completed jobs"}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
<Select value={String(jobLimit)} onValueChange={(v) => {
const val = Number(v)
setJobLimit(val)
localStorage.setItem("nomad-karaoke-job-limit", String(val))
}}>
<SelectTrigger className="h-7 w-[80px] text-xs">
<SelectValue />
</SelectTrigger>
@@ -249,7 +291,11 @@ function AppPageContent() {
</div>
</div>
<CardDescription style={{ color: 'var(--text-muted)' }}>
{jobs.length} job{jobs.length !== 1 ? 's' : ''} shown
{hideCompleted
? `${jobs.length} incomplete of ${totalFetched} total`
: jobs.length < totalFetched
? `Showing ${jobs.length} of ${totalFetched} jobs`
: `${jobs.length} job${jobs.length !== 1 ? 's' : ''}`}
</CardDescription>
</CardHeader>
<CardContent className="px-3 sm:px-6">
@@ -71,6 +71,7 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
// UI state
const [zoomLevel, setZoomLevel] = useState<ZoomLevel>(1)
const [customAudioUrl, setCustomAudioUrl] = useState<string | null>(null)
const [isCreatingCustom, setIsCreatingCustom] = useState(false)
const [isUploading, setIsUploading] = useState(false)
const [isSubmitting, setIsSubmitting] = useState(false)
@@ -222,6 +223,10 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
// Get audio URL for current selection
const getAudioUrl = useCallback(() => {
// Custom instrumental uses the signed URL from creation response
if (activeAudio === "custom" && customAudioUrl) {
return customAudioUrl
}
// For cloud mode, use signed URLs from analysis data
// For local mode, use the API stream endpoint
if (!isLocalMode && analysisData?.audio_urls) {
@@ -237,7 +242,7 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
// Local mode: use API stream endpoint
const stemType = STEM_TYPE_MAP[activeAudio]
return api.getAudioStreamUrl(job.job_id, stemType)
}, [job.job_id, activeAudio, isLocalMode, analysisData])
}, [job.job_id, activeAudio, isLocalMode, analysisData, customAudioUrl])
// Handle audio type change
const handleAudioChange = useCallback(
@@ -253,9 +258,12 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
setIsAudioLoading(true)
// Update audio source
// For cloud mode, use signed URLs from analysis data
let audioUrl: string
if (!isLocalMode && analysisData?.audio_urls) {
// Custom instrumental uses the signed URL from creation response
if (type === "custom" && customAudioUrl) {
audioUrl = customAudioUrl
} else if (!isLocalMode && analysisData?.audio_urls) {
// Cloud mode: use signed URLs from analysis data
const urls = analysisData.audio_urls
switch (type) {
case "clean": audioUrl = urls.clean || ""; break
@@ -290,7 +298,7 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
audio.addEventListener("loadeddata", handleLoaded, { once: true })
audio.addEventListener("error", handleError, { once: true })
},
[job.job_id, isLocalMode, analysisData]
[job.job_id, isLocalMode, analysisData, customAudioUrl]
)
// Seek to time
@@ -351,14 +359,16 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
setIsCreatingCustom(true)
try {
await api.createCustomInstrumental(job.job_id, muteRegions)
const result = await api.createCustomInstrumental(job.job_id, muteRegions)
const audioUrl = result.audio_url || api.getAudioStreamUrl(job.job_id, "custom_instrumental")
setCustomAudioUrl(audioUrl)
setHasCustom(true)
setSelectedOption("custom")
setActiveAudio("custom")
// Update audio source
// Update audio source with signed URL from response
if (audio) {
audio.src = api.getAudioStreamUrl(job.job_id, "custom_instrumental")
audio.src = audioUrl
audio.addEventListener(
"loadeddata",
() => {
+131 -10
View File
@@ -8,7 +8,8 @@ import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Upload, Youtube, Music, Loader2, ChevronDown, ChevronRight } from "lucide-react"
import { Upload, Youtube, Music, Loader2, ChevronDown, ChevronRight, AlertTriangle } from "lucide-react"
import Link from "next/link"
interface JobSubmissionProps {
onJobCreated: () => void
@@ -41,6 +42,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
}, [availableTabs, activeTab])
const [error, setError] = useState("")
const [isCreditError, setIsCreditError] = useState(false)
const [isSubmitting, setIsSubmitting] = useState(false)
// Upload form
@@ -64,9 +66,16 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
// Non-interactive mode (shared across all tabs)
const [nonInteractive, setNonInteractive] = useState(false)
// Private (non-published) mode - Dropbox only, no YouTube/GDrive
const [isPrivate, setIsPrivate] = useState(false)
// Credit enforcement
const noCredits = !isAdmin && user?.credits === 0
async function handleUploadSubmit(e: React.FormEvent) {
e.preventDefault()
setError("")
setIsCreditError(false)
if (!uploadFile) {
setError("Please select an audio file")
@@ -81,13 +90,17 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
try {
await api.uploadJob(uploadFile, uploadArtist.trim(), uploadTitle.trim(), {
non_interactive: nonInteractive,
is_private: isPrivate,
})
setUploadFile(null)
setUploadArtist("")
setUploadTitle("")
onJobCreated()
} catch (err) {
if (err instanceof ApiError) {
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")
@@ -100,6 +113,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
async function handleUrlSubmit(e: React.FormEvent) {
e.preventDefault()
setError("")
setIsCreditError(false)
if (!youtubeUrl.trim()) {
setError("Please enter a URL")
@@ -118,6 +132,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
youtubeTitle.trim(),
{
non_interactive: nonInteractive,
is_private: isPrivate,
}
)
setYoutubeUrl("")
@@ -125,7 +140,10 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
setYoutubeTitle("")
onJobCreated()
} catch (err) {
if (err instanceof ApiError) {
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")
@@ -138,6 +156,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
async function handleSearchSubmit(e: React.FormEvent) {
e.preventDefault()
setError("")
setIsCreditError(false)
if (!searchArtist.trim() || !searchTitle.trim()) {
setError("Please enter both artist and title")
@@ -148,6 +167,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
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,
display_title: displayTitle.trim() || undefined,
@@ -158,7 +178,10 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
setDisplayTitle("")
onJobCreated()
} catch (err) {
if (err instanceof ApiError) {
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")
@@ -178,6 +201,23 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
return (
<Tabs value={activeTab} onValueChange={setActiveTab}>
{/* Zero-credit warning banner */}
{noCredits && (
<div className="flex items-start gap-2 rounded-lg p-3 mb-4 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>
)}
{/* Only show tabs bar when there are multiple options */}
{availableTabs.length > 1 && (
<TabsList
@@ -307,14 +347,41 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
</div>
)}
{/* Private (non-published) mode */}
<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="private-upload"
checked={isPrivate}
onChange={(e) => setIsPrivate(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="private-upload" className="cursor-pointer" style={{ color: 'var(--text)' }}>
Private (non-published)
</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>
{error && activeTab === "upload" && (
<p className="text-sm text-red-400 bg-red-500/10 rounded p-2">{error}</p>
<div className="text-sm text-red-400 bg-red-500/10 rounded p-2">
<p>{error}</p>
{isCreditError && (
<Link href="/#pricing" className="inline-block mt-1 font-medium underline" style={{ color: 'var(--brand-pink)' }}>Buy Credits</Link>
)}
</div>
)}
<Button
type="submit"
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)]"
disabled={isSubmitting}
disabled={isSubmitting || noCredits}
>
{isSubmitting ? (
<>
@@ -402,14 +469,41 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
</div>
)}
{/* Private (non-published) mode */}
<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="private-url"
checked={isPrivate}
onChange={(e) => setIsPrivate(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="private-url" className="cursor-pointer" style={{ color: 'var(--text)' }}>
Private (non-published)
</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>
{error && activeTab === "url" && (
<p className="text-sm text-red-400 bg-red-500/10 rounded p-2">{error}</p>
<div className="text-sm text-red-400 bg-red-500/10 rounded p-2">
<p>{error}</p>
{isCreditError && (
<Link href="/#pricing" className="inline-block mt-1 font-medium underline" style={{ color: 'var(--brand-pink)' }}>Buy Credits</Link>
)}
</div>
)}
<Button
type="submit"
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)]"
disabled={isSubmitting}
disabled={isSubmitting || noCredits}
>
{isSubmitting ? (
<>
@@ -535,14 +629,41 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
</div>
)}
{/* Private (non-published) mode */}
<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="private-search"
checked={isPrivate}
onChange={(e) => setIsPrivate(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="private-search" className="cursor-pointer" style={{ color: 'var(--text)' }}>
Private (non-published)
</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>
{error && activeTab === "search" && (
<p className="text-sm text-red-400 bg-red-500/10 rounded p-2">{error}</p>
<div className="text-sm text-red-400 bg-red-500/10 rounded p-2">
<p>{error}</p>
{isCreditError && (
<Link href="/#pricing" className="inline-block mt-1 font-medium underline" style={{ color: 'var(--brand-pink)' }}>Buy Credits</Link>
)}
</div>
)}
<Button
type="submit"
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)]"
disabled={isSubmitting}
disabled={isSubmitting || noCredits}
>
{isSubmitting ? (
<>
@@ -7,7 +7,7 @@ import {
TooltipProvider,
TooltipTrigger,
} from '@/components/ui/tooltip'
import { Highlighter, Edit, Trash2 } from 'lucide-react'
import { Highlighter, Pencil, Trash2 } from 'lucide-react'
import { InteractionMode } from '@/lib/lyrics-review/types'
interface ModeSelectorProps {
@@ -23,13 +23,16 @@ export default function ModeSelector({ effectiveMode, onChange }: ModeSelectorPr
<ToggleGroup
type="single"
value={effectiveMode}
onValueChange={(value) => value === 'edit' && onChange(value as InteractionMode)}
onValueChange={(value) => value && onChange(value as InteractionMode)}
className="h-8"
>
<Tooltip>
<TooltipTrigger asChild>
<ToggleGroupItem value="edit" className="h-8 px-2 text-[0.75rem]">
<Edit className="h-3.5 w-3.5 mr-1" />
<ToggleGroupItem
value="edit"
className="h-8 px-2.5 text-[0.75rem] !flex-none aria-checked:font-semibold aria-checked:bg-blue-600 aria-checked:text-white dark:aria-checked:bg-blue-500"
>
<Pencil className="h-3.5 w-3.5 mr-1" />
Edit
</ToggleGroupItem>
</TooltipTrigger>
@@ -40,7 +43,10 @@ export default function ModeSelector({ effectiveMode, onChange }: ModeSelectorPr
<Tooltip>
<TooltipTrigger asChild>
<ToggleGroupItem value="highlight" className="h-8 px-2 text-[0.75rem]" disabled>
<ToggleGroupItem
value="highlight"
className="h-8 px-2.5 text-[0.75rem] !flex-none aria-checked:font-semibold aria-checked:bg-blue-600 aria-checked:text-white dark:aria-checked:bg-blue-500"
>
<Highlighter className="h-3.5 w-3.5 mr-1" />
Highlight
</ToggleGroupItem>
@@ -52,7 +58,10 @@ export default function ModeSelector({ effectiveMode, onChange }: ModeSelectorPr
<Tooltip>
<TooltipTrigger asChild>
<ToggleGroupItem value="delete_word" className="h-8 px-2 text-[0.75rem]" disabled>
<ToggleGroupItem
value="delete_word"
className="h-8 px-2.5 text-[0.75rem] !flex-none aria-checked:font-semibold aria-checked:bg-blue-600 aria-checked:text-white dark:aria-checked:bg-blue-500"
>
<Trash2 className="h-3.5 w-3.5 mr-1" />
Delete
</ToggleGroupItem>
@@ -1,6 +1,6 @@
'use client'
import { useState, useRef, useEffect, useCallback, memo } from 'react'
import { useState, useRef, useEffect, useCallback, useId, memo } from 'react'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
@@ -19,6 +19,7 @@ const TimeInput = memo(function TimeInput({
widthClass = 'w-24',
debounceMs = 300
}: TimeInputProps) {
const inputId = useId()
const [localValue, setLocalValue] = useState<string>('')
const [isFocused, setIsFocused] = useState(false)
const debounceRef = useRef<NodeJS.Timeout | null>(null)
@@ -65,8 +66,9 @@ const TimeInput = memo(function TimeInput({
return (
<div className={widthClass}>
<Label className="text-xs text-muted-foreground mb-1">{label}</Label>
<Label htmlFor={inputId} className="text-xs text-muted-foreground mb-1">{label}</Label>
<Input
id={inputId}
type="number"
value={isFocused ? localValue : (value?.toFixed(2) ?? '')}
onFocus={handleFocus}
@@ -0,0 +1,63 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import ModeSelector from '../ModeSelector'
import { InteractionMode } from '@/lib/lyrics-review/types'
describe('ModeSelector', () => {
it('renders all three mode buttons', () => {
const mockOnChange = jest.fn()
render(<ModeSelector effectiveMode="edit" onChange={mockOnChange} />)
expect(screen.getByRole('radio', { name: /edit/i })).toBeInTheDocument()
expect(screen.getByRole('radio', { name: /highlight/i })).toBeInTheDocument()
expect(screen.getByRole('radio', { name: /delete/i })).toBeInTheDocument()
})
it('all mode buttons are enabled (not disabled)', () => {
const mockOnChange = jest.fn()
render(<ModeSelector effectiveMode="edit" onChange={mockOnChange} />)
const editBtn = screen.getByRole('radio', { name: /edit/i })
const highlightBtn = screen.getByRole('radio', { name: /highlight/i })
const deleteBtn = screen.getByRole('radio', { name: /delete/i })
// Verify buttons are not disabled
expect(editBtn).not.toBeDisabled()
expect(highlightBtn).not.toBeDisabled()
expect(deleteBtn).not.toBeDisabled()
})
it('calls onChange when clicking highlight button', async () => {
const user = userEvent.setup()
const mockOnChange = jest.fn()
render(<ModeSelector effectiveMode="edit" onChange={mockOnChange} />)
const highlightBtn = screen.getByRole('radio', { name: /highlight/i })
await user.click(highlightBtn)
expect(mockOnChange).toHaveBeenCalledWith('highlight')
})
it('calls onChange when clicking delete button', async () => {
const user = userEvent.setup()
const mockOnChange = jest.fn()
render(<ModeSelector effectiveMode="edit" onChange={mockOnChange} />)
const deleteBtn = screen.getByRole('radio', { name: /delete/i })
await user.click(deleteBtn)
expect(mockOnChange).toHaveBeenCalledWith('delete_word')
})
it('shows correct active state for current mode', () => {
const mockOnChange = jest.fn()
const { rerender } = render(<ModeSelector effectiveMode="highlight" onChange={mockOnChange} />)
const highlightBtn = screen.getByRole('radio', { name: /highlight/i })
expect(highlightBtn).toHaveAttribute('aria-checked', 'true')
rerender(<ModeSelector effectiveMode="delete_word" onChange={mockOnChange} />)
const deleteBtn = screen.getByRole('radio', { name: /delete/i })
expect(deleteBtn).toHaveAttribute('aria-checked', 'true')
})
})
@@ -0,0 +1,313 @@
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import ReplaceAllLyricsModal from '../modals/ReplaceAllLyricsModal'
import { LyricsSegment } from '@/lib/lyrics-review/types'
// Mock the LyricsSynchronizer to avoid complex dependencies
jest.mock('../synchronizer/LyricsSynchronizer', () => {
return function MockLyricsSynchronizer() {
return <div data-testid="lyrics-synchronizer">Synchronizer</div>
}
})
const mockSegments: LyricsSegment[] = [
{
id: 'seg1',
text: 'Hello world',
start_time: 0,
end_time: 2,
words: [
{ id: 'w1', text: 'Hello', start_time: 0, end_time: 1, confidence: 0.9 },
{ id: 'w2', text: 'world', start_time: 1, end_time: 2, confidence: 0.95 },
],
},
{
id: 'seg2',
text: 'Goodbye moon',
start_time: 3,
end_time: 5,
words: [
{ id: 'w3', text: 'Goodbye', start_time: 3, end_time: 4, confidence: 0.88 },
{ id: 'w4', text: 'moon', start_time: 4, end_time: 5, confidence: 0.92 },
],
},
{
id: 'seg3',
text: 'Third line here',
start_time: 6,
end_time: 9,
words: [
{ id: 'w5', text: 'Third', start_time: 6, end_time: 7, confidence: 0.9 },
{ id: 'w6', text: 'line', start_time: 7, end_time: 8, confidence: 0.9 },
{ id: 'w7', text: 'here', start_time: 8, end_time: 9, confidence: 0.9 },
],
},
]
const defaultProps = {
open: true,
onClose: jest.fn(),
onSave: jest.fn(),
setModalSpacebarHandler: jest.fn(),
existingSegments: mockSegments,
}
async function openReplaceSegmentsMode() {
const user = userEvent.setup()
render(<ReplaceAllLyricsModal {...defaultProps} />)
// Click "Replace Segment Lyrics" in mode selection
const replaceSegmentsCard = screen.getByText('Replace Segment Lyrics')
await user.click(replaceSegmentsCard)
}
describe('Replace Segments Mode', () => {
beforeEach(() => {
jest.clearAllMocks()
})
it('shows Replace Segment Lyrics option in mode selection when existing lyrics exist', () => {
render(<ReplaceAllLyricsModal {...defaultProps} />)
expect(screen.getByText('Replace Segment Lyrics')).toBeInTheDocument()
expect(screen.getByText('Recommended for custom lyrics')).toBeInTheDocument()
})
it('does not show Replace Segment Lyrics when no existing lyrics', () => {
render(<ReplaceAllLyricsModal {...defaultProps} existingSegments={[]} />)
expect(screen.queryByText('Replace Segment Lyrics')).not.toBeInTheDocument()
})
it('renders textarea pre-filled with existing segment text', async () => {
await openReplaceSegmentsMode()
const textarea = screen.getByRole('textbox')
expect(textarea).toHaveValue('Hello world\nGoodbye moon\nThird line here')
})
it('shows correct matching line count', async () => {
await openReplaceSegmentsMode()
expect(screen.getByText('3/3 lines')).toBeInTheDocument()
})
it('Apply button is enabled when line count matches', async () => {
await openReplaceSegmentsMode()
const applyButton = screen.getByRole('button', { name: 'Apply' })
expect(applyButton).not.toBeDisabled()
})
it('disables Apply when line count differs (too many)', async () => {
const user = userEvent.setup()
await openReplaceSegmentsMode()
const textarea = screen.getByRole('textbox')
await user.clear(textarea)
await user.type(textarea, 'line 1\nline 2\nline 3\nline 4')
const applyButton = screen.getByRole('button', { name: 'Apply' })
expect(applyButton).toBeDisabled()
expect(screen.getByText(/1 too many/)).toBeInTheDocument()
})
it('disables Apply when line count differs (too few)', async () => {
const user = userEvent.setup()
await openReplaceSegmentsMode()
const textarea = screen.getByRole('textbox')
await user.clear(textarea)
await user.type(textarea, 'line 1\nline 2')
const applyButton = screen.getByRole('button', { name: 'Apply' })
expect(applyButton).toBeDisabled()
expect(screen.getByText(/1 too few/)).toBeInTheDocument()
})
it('shows mismatch error message with correct counts', async () => {
const user = userEvent.setup()
await openReplaceSegmentsMode()
const textarea = screen.getByRole('textbox')
await user.clear(textarea)
await user.type(textarea, 'only one line')
expect(screen.getByText(/expected 3, got 1/)).toBeInTheDocument()
})
it('calls onSave with unchanged segments when no text is modified', async () => {
const user = userEvent.setup()
await openReplaceSegmentsMode()
const applyButton = screen.getByRole('button', { name: 'Apply' })
await user.click(applyButton)
expect(defaultProps.onSave).toHaveBeenCalledTimes(1)
const savedSegments = defaultProps.onSave.mock.calls[0][0]
expect(savedSegments).toHaveLength(3)
// Unchanged segments should have same words (deep copy)
expect(savedSegments[0].text).toBe('Hello world')
expect(savedSegments[0].words).toHaveLength(2)
expect(savedSegments[0].words[0].text).toBe('Hello')
expect(savedSegments[0].words[1].text).toBe('world')
// Preserved original timing
expect(savedSegments[0].words[0].start_time).toBe(0)
expect(savedSegments[0].words[0].end_time).toBe(1)
})
it('creates new words with distributed timing for changed lines', async () => {
const user = userEvent.setup()
await openReplaceSegmentsMode()
const textarea = screen.getByRole('textbox')
await user.clear(textarea)
await user.type(textarea, 'Hello world\nNew custom lyrics here\nThird line here')
const applyButton = screen.getByRole('button', { name: 'Apply' })
await user.click(applyButton)
expect(defaultProps.onSave).toHaveBeenCalledTimes(1)
const savedSegments = defaultProps.onSave.mock.calls[0][0]
// First segment unchanged
expect(savedSegments[0].words[0].text).toBe('Hello')
expect(savedSegments[0].words[0].start_time).toBe(0)
// Second segment changed — new words with distributed timing over 3-5s
expect(savedSegments[1].text).toBe('New custom lyrics here')
expect(savedSegments[1].words).toHaveLength(4)
expect(savedSegments[1].words[0].text).toBe('New')
expect(savedSegments[1].words[0].start_time).toBe(3)
expect(savedSegments[1].words[3].text).toBe('here')
expect(savedSegments[1].words[3].end_time).toBe(5)
// Third segment unchanged
expect(savedSegments[2].words[0].text).toBe('Third')
})
it('preserves segment id and timing for changed lines', async () => {
const user = userEvent.setup()
await openReplaceSegmentsMode()
const textarea = screen.getByRole('textbox')
await user.clear(textarea)
await user.type(textarea, 'Hello world\nCompletely different\nThird line here')
const applyButton = screen.getByRole('button', { name: 'Apply' })
await user.click(applyButton)
const savedSegments = defaultProps.onSave.mock.calls[0][0]
// Changed segment keeps original id and timing boundaries
expect(savedSegments[1].id).toBe('seg2')
expect(savedSegments[1].start_time).toBe(3)
expect(savedSegments[1].end_time).toBe(5)
})
it('calls onClose after applying', async () => {
const user = userEvent.setup()
await openReplaceSegmentsMode()
const applyButton = screen.getByRole('button', { name: 'Apply' })
await user.click(applyButton)
expect(defaultProps.onClose).toHaveBeenCalled()
})
it('back button returns to mode selection', async () => {
const user = userEvent.setup()
await openReplaceSegmentsMode()
// Should be in replace segments mode
expect(screen.getByText('Edit lyrics line by line', { exact: false })).toBeInTheDocument()
// Click back arrow
const backButton = screen.getAllByRole('button').find(
(btn) => btn.querySelector('svg.lucide-arrow-left')
)
expect(backButton).toBeTruthy()
await user.click(backButton!)
// Should be back in mode selection
expect(screen.getByText('Edit All Lyrics')).toBeInTheDocument()
expect(screen.getByText('Re-sync Existing Lyrics')).toBeInTheDocument()
expect(screen.getByText('Replace Segment Lyrics')).toBeInTheDocument()
})
it('cancel button closes the modal', async () => {
const user = userEvent.setup()
await openReplaceSegmentsMode()
const cancelButton = screen.getByRole('button', { name: 'Cancel' })
await user.click(cancelButton)
expect(defaultProps.onClose).toHaveBeenCalled()
})
it('does not show Replace Segment Lyrics when segments have no words', () => {
const emptyWordSegments: LyricsSegment[] = [
{ id: 's1', text: 'test', start_time: 0, end_time: 1, words: [] },
]
render(<ReplaceAllLyricsModal {...defaultProps} existingSegments={emptyWordSegments} />)
expect(screen.queryByText('Replace Segment Lyrics')).not.toBeInTheDocument()
})
it('handles changing empty segment text to non-empty', async () => {
const user = userEvent.setup()
const segmentsWithEmpty: LyricsSegment[] = [
{
id: 'seg1',
text: '',
start_time: 0,
end_time: 2,
words: [{ id: 'w1', text: '', start_time: 0, end_time: 2, confidence: 1 }],
},
{
id: 'seg2',
text: 'Hello world',
start_time: 3,
end_time: 5,
words: [
{ id: 'w2', text: 'Hello', start_time: 3, end_time: 4, confidence: 1 },
{ id: 'w3', text: 'world', start_time: 4, end_time: 5, confidence: 1 },
],
},
]
render(<ReplaceAllLyricsModal {...defaultProps} existingSegments={segmentsWithEmpty} />)
const replaceSegmentsCard = screen.getByText('Replace Segment Lyrics')
await user.click(replaceSegmentsCard)
const textarea = screen.getByRole('textbox')
await user.clear(textarea)
await user.type(textarea, 'New first line\nHello world')
const applyButton = screen.getByRole('button', { name: 'Apply' })
await user.click(applyButton)
const savedSegments = defaultProps.onSave.mock.calls[0][0]
expect(savedSegments[0].text).toBe('New first line')
expect(savedSegments[0].words).toHaveLength(3)
expect(savedSegments[0].words[0].start_time).toBe(0)
expect(savedSegments[0].words[2].end_time).toBeCloseTo(2)
})
it('deep copies unchanged segments (no mutation)', async () => {
const user = userEvent.setup()
await openReplaceSegmentsMode()
const applyButton = screen.getByRole('button', { name: 'Apply' })
await user.click(applyButton)
const savedSegments = defaultProps.onSave.mock.calls[0][0]
// Verify deep copy — different object references
expect(savedSegments[0]).not.toBe(mockSegments[0])
expect(savedSegments[0].words).not.toBe(mockSegments[0].words)
expect(savedSegments[0].words[0]).not.toBe(mockSegments[0].words[0])
})
})
@@ -10,7 +10,7 @@ import EditWordList from '../EditWordList'
import EditTimelineSection from '../EditTimelineSection'
import useManualSync from '@/hooks/useManualSync'
import { setModalHandler } from '@/lib/lyrics-review/utils/keyboardHandlers'
import { splitWordWithTiming } from '@/lib/lyrics-review/utils/wordUtils'
import { splitWordWithTiming, createWordsWithDistributedTiming } from '@/lib/lyrics-review/utils/wordUtils'
interface EditModalProps {
open: boolean
@@ -248,22 +248,12 @@ export default function EditModal({
const handleReplaceAllWords = useCallback(
(replacementText: string) => {
if (!editedSegment) return
const wordTexts = replacementText.trim().split(/\s+/).filter((w) => w.length > 0)
if (wordTexts.length === 0) return
const segStart = editedSegment.start_time ?? 0
const segEnd = editedSegment.end_time ?? segStart + 1
const totalDuration = segEnd - segStart
const wordDuration = totalDuration / wordTexts.length
const newWords: Word[] = wordTexts.map((text, index) => ({
id: nanoid(),
text,
start_time: segStart + index * wordDuration,
end_time: segStart + (index + 1) * wordDuration,
confidence: 1.0,
}))
const newWords = createWordsWithDistributedTiming(
replacementText,
editedSegment.start_time,
editedSegment.end_time
)
if (newWords.length === 0) return
updateSegment(newWords)
},
[editedSegment, updateSegment]
@@ -2,7 +2,7 @@
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { RefreshCw, ClipboardPaste, X } from 'lucide-react'
import { RefreshCw, ClipboardPaste, TextCursorInput, X } from 'lucide-react'
import { cn } from '@/lib/utils'
interface ModeSelectionModalProps {
@@ -10,6 +10,7 @@ interface ModeSelectionModalProps {
onClose: () => void
onSelectReplace: () => void
onSelectResync: () => void
onSelectReplaceSegments: () => void
hasExistingLyrics: boolean
}
@@ -18,6 +19,7 @@ export default function ModeSelectionModal({
onClose,
onSelectReplace,
onSelectResync,
onSelectReplaceSegments,
hasExistingLyrics,
}: ModeSelectionModalProps) {
return (
@@ -59,6 +61,29 @@ export default function ModeSelectionModal({
</div>
)}
{/* Replace Segment Lyrics option - only show if there are existing lyrics */}
{hasExistingLyrics && (
<div
className={cn(
'p-4 border rounded-lg cursor-pointer',
'hover:bg-muted/30 hover:border-muted-foreground transition-colors'
)}
onClick={onSelectReplaceSegments}
>
<div className="flex items-start gap-3">
<TextCursorInput className="h-10 w-10 text-muted-foreground mt-0.5" />
<div className="flex-1">
<h3 className="text-lg font-semibold">Replace Segment Lyrics</h3>
<p className="text-sm text-muted-foreground mt-1">
Edit or paste new lyrics for each line. Timing is preserved — only the words
change. Best for custom lyrics, translations, or fixing multiple lines at once.
</p>
<p className="text-xs text-green-500 mt-2">Recommended for custom lyrics</p>
</div>
</div>
</div>
)}
{/* Replace All option */}
<div
className={cn(
@@ -4,9 +4,10 @@ import { useState, useEffect, useCallback, useMemo } from 'react'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { X, ArrowLeft, ClipboardPaste, Sparkles } from 'lucide-react'
import { X, ArrowLeft, ClipboardPaste, Sparkles, Info, Check, AlertTriangle } from 'lucide-react'
import { nanoid } from 'nanoid'
import { LyricsSegment, Word } from '@/lib/lyrics-review/types'
import { createWordsWithDistributedTiming } from '@/lib/lyrics-review/utils/wordUtils'
import ModeSelectionModal from './ModeSelectionModal'
import LyricsSynchronizer from '../synchronizer/LyricsSynchronizer'
@@ -18,7 +19,7 @@ declare global {
}
}
type ModalMode = 'selection' | 'replace' | 'resync'
type ModalMode = 'selection' | 'replace' | 'resync' | 'replaceSegments'
interface ReplaceAllLyricsModalProps {
open: boolean
@@ -67,6 +68,15 @@ export default function ReplaceAllLyricsModal({
return { lines: lines.length, words: totalWords }
}, [inputText])
// Line count validation for replaceSegments mode
const replaceSegmentsInfo = useMemo(() => {
const expectedLineCount = existingSegments.length
const lines = inputText.split('\n')
const currentLineCount = lines.length
const lineDiff = currentLineCount - expectedLineCount
return { expectedLineCount, currentLineCount, lineDiff }
}, [inputText, existingSegments])
// Process the input text into segments and words
const processLyrics = useCallback(() => {
if (!inputText.trim()) return
@@ -123,6 +133,36 @@ export default function ReplaceAllLyricsModal({
onClose()
}, [onClose])
// Apply replace segments: build updated segments with new words for changed lines
const handleApplyReplaceSegments = useCallback(() => {
const newLines = inputText.split('\n')
const updatedSegments: LyricsSegment[] = existingSegments.map((segment, i) => {
const newLineText = newLines[i]?.trim() ?? ''
const originalText = segment.text.trim()
if (newLineText === originalText) {
// Unchanged — deep copy to avoid mutation
return JSON.parse(JSON.stringify(segment))
}
// Changed — create new words with distributed timing
const newWords = createWordsWithDistributedTiming(
newLineText,
segment.start_time,
segment.end_time
)
return {
...segment,
text: newLineText,
words: newWords,
}
})
onSave(updatedSegments)
handleClose()
}, [inputText, existingSegments, onSave, handleClose])
// Handle save from synchronizer
const handleSave = useCallback(
(segments: LyricsSegment[]) => {
@@ -141,6 +181,11 @@ export default function ReplaceAllLyricsModal({
setMode('resync')
}, [])
const handleSelectReplaceSegments = useCallback(() => {
setInputText(existingSegments.map((s) => s.text.trim()).join('\n'))
setMode('replaceSegments')
}, [existingSegments])
// Handle back to selection
const handleBackToSelection = useCallback(() => {
setMode('selection')
@@ -163,6 +208,7 @@ export default function ReplaceAllLyricsModal({
onClose={handleClose}
onSelectReplace={handleSelectReplace}
onSelectResync={handleSelectResync}
onSelectReplaceSegments={handleSelectReplaceSegments}
hasExistingLyrics={hasExistingLyrics}
/>
@@ -219,6 +265,86 @@ export default function ReplaceAllLyricsModal({
</DialogContent>
</Dialog>
{/* Replace Segment Lyrics Modal */}
<Dialog open={open && mode === 'replaceSegments'} onOpenChange={(isOpen) => !isOpen && handleClose()}>
<DialogContent className="max-w-2xl h-[80vh] max-h-[80vh] flex flex-col">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Button variant="ghost" size="icon" onClick={handleBackToSelection} className="h-8 w-8">
<ArrowLeft className="h-4 w-4" />
</Button>
<span className="flex-1">Replace Segment Lyrics</span>
<Button variant="ghost" size="icon" onClick={handleClose} className="h-8 w-8">
<X className="h-4 w-4" />
</Button>
</DialogTitle>
</DialogHeader>
<div className="flex-1 overflow-hidden flex flex-col gap-4">
<div className="flex items-start gap-2 p-3 rounded-md bg-muted/50 text-sm text-muted-foreground">
<Info className="h-4 w-4 mt-0.5 shrink-0" />
<p>
Edit lyrics line by line. Each line corresponds to a timed segment.
The number of lines must stay the same (currently: {replaceSegmentsInfo.expectedLineCount} lines).
Changed lines will get new word timing estimated from the segment duration.
Unchanged lines are left as-is.
</p>
</div>
<div className="flex items-center gap-4">
<Button variant="outline" size="sm" onClick={handlePasteFromClipboard}>
<ClipboardPaste className="h-4 w-4 mr-2" />
Paste from Clipboard
</Button>
<span className={`text-sm font-medium ${replaceSegmentsInfo.lineDiff === 0 ? 'text-green-500' : 'text-destructive'}`}>
{replaceSegmentsInfo.lineDiff === 0 ? (
<span className="flex items-center gap-1">
<Check className="h-4 w-4" />
{replaceSegmentsInfo.currentLineCount}/{replaceSegmentsInfo.expectedLineCount} lines
</span>
) : (
<span className="flex items-center gap-1">
<AlertTriangle className="h-4 w-4" />
{replaceSegmentsInfo.currentLineCount}/{replaceSegmentsInfo.expectedLineCount} lines
</span>
)}
</span>
</div>
<Textarea
value={inputText}
onChange={(e) => setInputText(e.target.value)}
placeholder="Edit lyrics line by line..."
className="flex-1 resize-none font-mono text-sm min-h-[300px]"
/>
{replaceSegmentsInfo.lineDiff !== 0 && (
<div className="flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-sm text-destructive">
<AlertTriangle className="h-4 w-4 mt-0.5 shrink-0" />
<p>
You have {Math.abs(replaceSegmentsInfo.lineDiff)} too{' '}
{replaceSegmentsInfo.lineDiff > 0 ? 'many' : 'few'} lines (expected{' '}
{replaceSegmentsInfo.expectedLineCount}, got {replaceSegmentsInfo.currentLineCount}).
Each line maps to a timed segment, so the count must match exactly.
</p>
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={handleClose}>
Cancel
</Button>
<Button
onClick={handleApplyReplaceSegments}
disabled={replaceSegmentsInfo.lineDiff !== 0}
>
Apply
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Synchronizer Modal */}
<Dialog open={open && mode === 'resync'} onOpenChange={(isOpen) => !isOpen && handleClose()}>
<DialogContent className="max-w-[calc(100vw-4vw)] w-[calc(100vw-4vw)] h-[90vh] max-h-[90vh] flex flex-col">
@@ -418,10 +418,9 @@ test.describe('Admin Job Detail Page', () => {
// Reset buttons are now in a toolbar (not accordion) labeled "Reset to:"
await expect(page.getByText('Reset to:')).toBeVisible();
// Check the reset buttons are visible in the toolbar
await expect(page.locator('button:has-text("Start")').first()).toBeVisible();
// Note: "Start" and "Inst." were removed; "Lyrics" renamed to "Review"
await expect(page.locator('button:has-text("Audio")').first()).toBeVisible();
await expect(page.locator('button:has-text("Lyrics")').first()).toBeVisible();
await expect(page.locator('button:has-text("Inst.")').first()).toBeVisible();
await expect(page.locator('button:has-text("Review")').first()).toBeVisible();
await expect(page.locator('button:has-text("Reprocess")').first()).toBeVisible();
});
@@ -438,8 +437,8 @@ test.describe('Admin Job Detail Page', () => {
await page.goto('/admin/jobs?id=test-job-123');
await page.waitForLoadState('networkidle');
// Click a reset button (Start = reset to pending)
await page.locator('button:has-text("Start")').first().click();
// Click a reset button (Audio = reset to awaiting_audio_selection)
await page.locator('button:has-text("Audio")').first().click();
// Should show confirmation dialog
await expect(page.getByRole('alertdialog')).toBeVisible();
@@ -448,121 +447,7 @@ test.describe('Admin Job Detail Page', () => {
await expect(page.getByRole('button', { name: 'Reset' })).toBeVisible();
});
test('clear workers button is visible in toolbar', async ({ page }) => {
// Mock job with complete worker progress (typical state when workers need clearing)
const jobWithWorkerProgress = {
...mockJob,
state_data: {
...mockJob.state_data,
render_progress: { stage: 'complete' },
video_progress: { stage: 'complete' },
encoding_progress: { stage: 'complete' },
},
};
await setupApiFixtures(page, {
mocks: [
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: jobWithWorkerProgress } },
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
],
});
await page.goto('/admin/jobs?id=test-job-123');
await page.waitForLoadState('networkidle');
// Clear Workers button should be visible in the toolbar (near Del Outputs, Delete Job)
await expect(page.locator('button:has-text("Clear Workers")')).toBeVisible();
});
test('clear workers button calls API endpoint', async ({ page }) => {
// Mock successful clear workers response
const clearWorkersResponse = {
status: 'success',
job_id: 'test-job-123',
message: 'Cleared 3 worker progress keys',
cleared_keys: ['render_progress', 'video_progress', 'encoding_progress'],
};
// Track API calls
let clearWorkersApiCalled = false;
await setupApiFixtures(page, {
mocks: [
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: mockJob } },
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
{ method: 'POST', path: '/api/admin/jobs/test-job-123/clear-workers', response: { body: clearWorkersResponse } },
],
});
// Also track when the clear-workers endpoint is called
await page.route('**/api/admin/jobs/*/clear-workers', async (route) => {
clearWorkersApiCalled = true;
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(clearWorkersResponse),
});
});
await page.goto('/admin/jobs?id=test-job-123');
await page.waitForLoadState('networkidle');
// Click Clear Workers button in toolbar
await page.locator('button:has-text("Clear Workers")').click();
// Wait a bit for the API call to complete
await page.waitForTimeout(1000);
// Verify the API was called
expect(clearWorkersApiCalled).toBe(true);
});
test('clear workers button shows loading state while processing', async ({ page }) => {
// Mock slow clear workers response
const clearWorkersResponse = {
status: 'success',
job_id: 'test-job-123',
message: 'Cleared 3 worker progress keys',
cleared_keys: ['render_progress', 'video_progress', 'encoding_progress'],
};
await setupApiFixtures(page, {
mocks: [
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: mockJob } },
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
],
});
// Add delayed response for clear-workers
await page.route('**/api/admin/jobs/*/clear-workers', async (route) => {
// Delay response to test loading state
await new Promise(resolve => setTimeout(resolve, 500));
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(clearWorkersResponse),
});
});
await page.goto('/admin/jobs?id=test-job-123');
await page.waitForLoadState('networkidle');
// Get the Clear Workers button
const clearWorkersButton = page.locator('button:has-text("Clear Workers")');
// Click it and immediately check for disabled state
await clearWorkersButton.click();
// Button should be disabled during processing (has spinning icon)
// The button contains a RefreshCw icon that animates when clearingWorkers is true
await expect(clearWorkersButton).toBeDisabled({ timeout: 500 });
});
// Note: "Clear Workers" tests removed - feature replaced by Full Restart + Regen Screens
test('delete outputs button shows confirmation dialog', async ({ page }) => {
await setupApiFixtures(page, {
@@ -103,9 +103,16 @@ const mockJobData = {
};
const mockUserData = {
email: 'test@example.com',
name: 'Test User',
role: 'user',
user: {
email: 'test@example.com',
name: 'Test User',
role: 'user',
credits: 10,
display_name: 'Test User',
total_jobs_created: 5,
total_jobs_completed: 3,
},
has_session: true,
};
// Setup function to configure mocks for cloud mode
@@ -147,6 +154,45 @@ async function setupCloudModeMocks(page: Page) {
path: `/api/review/${TEST_JOB_ID}/audio/test_audio_hash_cloud`,
response: { status: 200, body: '' },
},
// Instrumental analysis endpoint (for instrumental route)
{
method: 'GET',
path: `/api/review/${TEST_JOB_ID}/instrumental-analysis`,
response: {
body: {
job_id: TEST_JOB_ID,
artist: 'Test Artist',
title: 'Test Song',
duration_seconds: 180,
analysis: {
has_audible_content: false,
total_duration_seconds: 180,
audible_segments: [],
recommended_selection: 'clean',
total_audible_duration_seconds: 0,
audible_percentage: 0,
silence_threshold_db: -40,
},
audio_urls: {
clean: 'https://storage.example.com/clean.flac',
with_backing: 'https://storage.example.com/with_backing.flac',
},
has_original: true,
has_uploaded_instrumental: false,
},
},
},
// Waveform data endpoint (for instrumental route)
{
method: 'GET',
path: `/api/review/${TEST_JOB_ID}/waveform-data`,
response: {
body: {
amplitudes: Array(100).fill(0.5),
duration_seconds: 180,
},
},
},
// User endpoint (for auth)
{
method: 'GET',
@@ -179,7 +225,7 @@ test.describe('Cloud Mode - Hash Route Parsing', () => {
});
test('parses hash-based instrumental route correctly', async ({ page }) => {
// Update mock to include instrumental options for the job in instrumental state
// Update mock to include instrumental analysis endpoints
await setupApiFixtures(page, {
mocks: [
{
@@ -192,6 +238,43 @@ test.describe('Cloud Mode - Hash Route Parsing', () => {
path: `/api/review/${TEST_JOB_ID}/correction-data`,
response: { body: mockCorrectionData },
},
{
method: 'GET',
path: `/api/review/${TEST_JOB_ID}/instrumental-analysis`,
response: {
body: {
job_id: TEST_JOB_ID,
artist: 'Test Artist',
title: 'Test Song',
duration_seconds: 180,
analysis: {
has_audible_content: false,
total_duration_seconds: 180,
audible_segments: [],
recommended_selection: 'clean',
total_audible_duration_seconds: 0,
audible_percentage: 0,
silence_threshold_db: -40,
},
audio_urls: {
clean: 'https://storage.example.com/clean.flac',
with_backing: 'https://storage.example.com/with_backing.flac',
},
has_original: true,
has_uploaded_instrumental: false,
},
},
},
{
method: 'GET',
path: `/api/review/${TEST_JOB_ID}/waveform-data`,
response: {
body: {
amplitudes: Array(100).fill(0.5),
duration_seconds: 180,
},
},
},
{
method: 'GET',
path: '/api/users/me',
@@ -210,7 +293,7 @@ test.describe('Cloud Mode - Hash Route Parsing', () => {
await page.waitForLoadState('networkidle');
// Should show the instrumental selection UI (not "Page not found")
await expect(page.locator('h1')).toContainText('Instrumental Selection', { timeout: 10000 });
await expect(page.getByText('Instrumental Review')).toBeVisible({ timeout: 10000 });
});
test('invalid hash route shows page not found', async ({ page }) => {
@@ -297,7 +380,7 @@ test.describe('Cloud Mode - Navigation Flow', () => {
await page.waitForTimeout(500);
// Should now show instrumental UI
await expect(page.locator('h1')).toContainText('Instrumental Selection', { timeout: 10000 });
await expect(page.getByText('Instrumental Review')).toBeVisible({ timeout: 10000 });
});
});
@@ -416,7 +499,7 @@ test.describe('Cloud Mode - Instrumental Audio Loading', () => {
await page.waitForLoadState('networkidle');
// Should show the instrumental selection UI
await expect(page.locator('h1')).toContainText('Instrumental Selection', { timeout: 10000 });
await expect(page.getByText('Instrumental Review')).toBeVisible({ timeout: 10000 });
// Wait for UI to fully load
await page.waitForTimeout(1000);
@@ -507,7 +590,7 @@ test.describe('Cloud Mode - Instrumental Audio Loading', () => {
await page.waitForLoadState('networkidle');
// Should show the instrumental selection UI
await expect(page.locator('h1')).toContainText('Instrumental Selection', { timeout: 10000 });
await expect(page.getByText('Instrumental Review')).toBeVisible({ timeout: 10000 });
// Find audio tabs
const originalTab = page.getByRole('button', { name: /^original$/i });
@@ -102,9 +102,16 @@ const mockJobData = {
};
const mockUserData = {
email: 'test@example.com',
name: 'Test User',
role: 'user',
user: {
email: 'test@example.com',
name: 'Test User',
role: 'user',
credits: 10,
display_name: 'Test User',
total_jobs_created: 5,
total_jobs_completed: 3,
},
has_session: true,
};
const mockInstrumentalAnalysis = {
@@ -166,7 +173,7 @@ test.describe('Combined Review Corrections Preservation', () => {
}
});
await setAuthToken(page);
await setAuthToken(page, 'test-token-123');
});
test.afterEach(async ({ page }) => {
@@ -289,7 +296,7 @@ test.describe('Combined Review Corrections Preservation', () => {
// Audio endpoint
{
method: 'GET',
path: new RegExp(`/api/review/${TEST_JOB_ID}/audio`),
path: `/api/review/${TEST_JOB_ID}/audio/:audioHash`,
response: { status: 200, body: '' },
},
],
@@ -381,7 +388,7 @@ test.describe('Combined Review Corrections Preservation', () => {
test.describe('Regression Prevention', () => {
test.beforeEach(async ({ page }) => {
await setAuthToken(page);
await setAuthToken(page, 'test-token-123');
});
test.afterEach(async ({ page }) => {
@@ -0,0 +1,135 @@
import { test, expect } from '@playwright/test';
import { setupApiFixtures, setAuthToken } from '../fixtures/test-helper';
/**
* Regression Tests - Credit Enforcement
*
* Tests that the credit system properly gates job creation:
* - Zero-credit users see warning and disabled submit
* - 402 errors display "out of credits" message with buy link
* - Users with credits can submit normally
*/
const BASE_MOCKS = [
{
method: 'GET',
path: '/api/themes',
response: { body: { themes: [] } },
},
{
method: 'GET',
path: '/api/users/credits/packages',
response: { body: { packages: [] } },
},
];
function userMeMock(credits: number, role: string = 'user') {
return {
method: 'GET',
path: '/api/users/me',
response: {
body: {
user: { email: 'test@example.com', credits, role },
has_session: true,
},
},
};
}
test.describe('Credit Enforcement', () => {
test.beforeEach(async ({ page }) => {
await setAuthToken(page, 'test-token');
});
test('zero-credit user sees warning banner and disabled submit', async ({ page }) => {
await setupApiFixtures(page, {
mocks: [
userMeMock(0),
...BASE_MOCKS,
{
method: 'GET',
path: '/api/jobs',
response: { body: [] },
},
],
});
await page.goto('/app');
await page.waitForLoadState('networkidle');
// Warning banner should be visible
await expect(page.getByText('You have no credits remaining')).toBeVisible();
await expect(page.getByRole('link', { name: 'Buy Credits' })).toBeVisible();
// Submit button should be disabled
const submitButton = page.getByRole('button', { name: /Create Karaoke Video|Search & Create Job/i });
await expect(submitButton).toBeDisabled();
});
test('402 error displays out of credits message with buy link', async ({ page }) => {
await setupApiFixtures(page, {
mocks: [
userMeMock(1), // Has credits initially (form enabled)
...BASE_MOCKS,
{
method: 'GET',
path: '/api/jobs',
response: { body: [] },
},
{
method: 'POST',
path: '/api/audio-search',
response: {
status: 402,
body: {
detail: "You're out of credits. Buy more to continue creating karaoke videos.",
credits_available: 0,
credits_required: 1,
buy_url: '/#pricing',
},
},
},
],
});
await page.goto('/app');
await page.waitForLoadState('networkidle');
// Fill in the search form
await page.getByTestId('search-artist-input').fill('Test Artist');
await page.getByTestId('search-title-input').fill('Test Song');
// Submit
await page.getByRole('button', { name: /Search & Create Job/i }).click();
// Should show credit error message
await expect(page.getByText(/out of credits/i)).toBeVisible();
// Should show buy credits link
await expect(page.getByRole('link', { name: 'Buy Credits' })).toBeVisible();
});
test('user with credits can submit normally', async ({ page }) => {
await setupApiFixtures(page, {
mocks: [
userMeMock(5),
...BASE_MOCKS,
{
method: 'GET',
path: '/api/jobs',
response: { body: [] },
},
],
});
await page.goto('/app');
await page.waitForLoadState('networkidle');
// No warning banner
await expect(page.getByText('You have no credits remaining')).not.toBeVisible();
// Submit button should be enabled
const submitButton = page.getByRole('button', { name: /Create Karaoke Video|Search & Create Job/i });
await expect(submitButton).toBeEnabled();
});
});
+32 -34
View File
@@ -463,8 +463,8 @@ test.describe('Lyrics Review - Edit Operations', () => {
const dialog = page.locator('[role="dialog"]');
await expect(dialog).toBeVisible({ timeout: 5000 });
// Find the start time input (labeled "Start")
const startInput = dialog.getByLabel('Start');
// Find the first start time input (labeled "Start") - multiple segments may have one
const startInput = dialog.getByLabel('Start').first();
await expect(startInput).toBeVisible();
// Click into the input to focus it
@@ -477,7 +477,7 @@ test.describe('Lyrics Review - Edit Operations', () => {
await expect(startInput).toHaveValue('12.34');
// Test end time input as well
const endInput = dialog.getByLabel('End');
const endInput = dialog.getByLabel('End').first();
await expect(endInput).toBeVisible();
await endInput.click();
@@ -566,7 +566,7 @@ test.describe('Lyrics Review - Complete Review Flow', () => {
await expect(dialog).toBeVisible({ timeout: 10000 });
// Look for Complete Review button in modal
const completeBtn = dialog.getByRole('button', { name: /complete review/i });
const completeBtn = dialog.getByRole('button', { name: /proceed to instrumental review/i });
if (await completeBtn.isVisible({ timeout: 5000 }).catch(() => false)) {
await completeBtn.click();
// Should submit and close
@@ -655,27 +655,7 @@ test.describe('Lyrics Review - Submit UX', () => {
await setupSubmitFlowMocks(page);
});
test('success screen shows after submission in local mode', async ({ page }) => {
await page.goto('/app/jobs/local/review');
await page.waitForLoadState('networkidle');
// Open preview modal and submit
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
const previewBtn = page.getByRole('button', { name: /preview video/i });
await expect(previewBtn).toBeVisible({ timeout: 10000 });
await previewBtn.click();
const dialog = page.locator('[role="dialog"]');
await expect(dialog).toBeVisible({ timeout: 10000 });
await dialog.getByRole('button', { name: /complete review/i }).click();
// Wait for success screen
await expect(page.getByText('Review Submitted')).toBeVisible({ timeout: 10000 });
await expect(page.getByText(/Closing in \d+s/)).toBeVisible();
});
test('submit button becomes disabled when clicked', async ({ page }) => {
test('proceed button navigates to instrumental review in local mode', async ({ page }) => {
await page.goto('/app/jobs/local/review');
await page.waitForLoadState('networkidle');
@@ -688,18 +668,36 @@ test.describe('Lyrics Review - Submit UX', () => {
const dialog = page.locator('[role="dialog"]');
await expect(dialog).toBeVisible({ timeout: 10000 });
const completeBtn = dialog.getByRole('button', { name: /complete review/i });
await expect(completeBtn).toBeVisible({ timeout: 5000 });
await dialog.getByRole('button', { name: /proceed to instrumental review/i }).click();
// Should navigate to instrumental review page
await page.waitForURL('**/instrumental**', { timeout: 10000 });
expect(page.url()).toContain('/instrumental');
});
test('proceed button is enabled and clickable in preview modal', async ({ page }) => {
await page.goto('/app/jobs/local/review');
await page.waitForLoadState('networkidle');
// Open preview modal
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
const previewBtn = page.getByRole('button', { name: /preview video/i });
await expect(previewBtn).toBeVisible({ timeout: 10000 });
await previewBtn.click();
const dialog = page.locator('[role="dialog"]');
await expect(dialog).toBeVisible({ timeout: 10000 });
const proceedBtn = dialog.getByRole('button', { name: /proceed to instrumental review/i });
await expect(proceedBtn).toBeVisible({ timeout: 5000 });
// Verify button is enabled before click
await expect(completeBtn).toBeEnabled();
await expect(proceedBtn).toBeEnabled();
// Click the button
await completeBtn.click();
// Transition should occur - either loading state or success screen
// We can verify we reach the success screen
await expect(page.getByText('Review Submitted')).toBeVisible({ timeout: 10000 });
// Click navigates to instrumental review
await proceedBtn.click();
await page.waitForURL('**/instrumental**', { timeout: 10000 });
expect(page.url()).toContain('/instrumental');
});
});
@@ -0,0 +1,270 @@
import { test, expect, Page } from '@playwright/test';
import { setupApiFixtures, clearAuthToken } from '../fixtures/test-helper';
/**
* Replace Segment Lyrics E2E Tests
*
* Tests the "Replace Segment Lyrics" mode in Edit All Lyrics, which lets users
* swap in custom lyrics line-by-line while preserving existing segment timing.
*
* To run these tests:
* npx playwright test e2e/regression/replace-segments.spec.ts
*/
const mockCorrectionData = {
original_segments: [
{
id: 'seg_1',
text: 'Hello world from the test',
start_time: 0.0,
end_time: 2.5,
words: [
{ id: 'word_1', text: 'Hello', start_time: 0.0, end_time: 0.5, confidence: 0.95 },
{ id: 'word_2', text: 'world', start_time: 0.5, end_time: 1.0, confidence: 0.92 },
{ id: 'word_3', text: 'from', start_time: 1.0, end_time: 1.5, confidence: 0.88 },
{ id: 'word_4', text: 'the', start_time: 1.5, end_time: 2.0, confidence: 0.90 },
{ id: 'word_5', text: 'test', start_time: 2.0, end_time: 2.5, confidence: 0.94 },
],
},
{
id: 'seg_2',
text: 'This is another line',
start_time: 3.0,
end_time: 5.0,
words: [
{ id: 'word_6', text: 'This', start_time: 3.0, end_time: 3.5, confidence: 0.96 },
{ id: 'word_7', text: 'is', start_time: 3.5, end_time: 4.0, confidence: 0.97 },
{ id: 'word_8', text: 'another', start_time: 4.0, end_time: 4.5, confidence: 0.93 },
{ id: 'word_9', text: 'line', start_time: 4.5, end_time: 5.0, confidence: 0.91 },
],
},
{
id: 'seg_3',
text: 'Final segment here',
start_time: 6.0,
end_time: 8.0,
words: [
{ id: 'word_10', text: 'Final', start_time: 6.0, end_time: 6.7, confidence: 0.90 },
{ id: 'word_11', text: 'segment', start_time: 6.7, end_time: 7.4, confidence: 0.91 },
{ id: 'word_12', text: 'here', start_time: 7.4, end_time: 8.0, confidence: 0.92 },
],
},
],
corrected_segments: [
{
id: 'seg_1',
text: 'Hello world from the test',
start_time: 0.0,
end_time: 2.5,
words: [
{ id: 'word_1', text: 'Hello', start_time: 0.0, end_time: 0.5, confidence: 0.95 },
{ id: 'word_2', text: 'world', start_time: 0.5, end_time: 1.0, confidence: 0.92 },
{ id: 'word_3', text: 'from', start_time: 1.0, end_time: 1.5, confidence: 0.88 },
{ id: 'word_4', text: 'the', start_time: 1.5, end_time: 2.0, confidence: 0.90 },
{ id: 'word_5', text: 'test', start_time: 2.0, end_time: 2.5, confidence: 0.94 },
],
},
{
id: 'seg_2',
text: 'This is another line',
start_time: 3.0,
end_time: 5.0,
words: [
{ id: 'word_6', text: 'This', start_time: 3.0, end_time: 3.5, confidence: 0.96 },
{ id: 'word_7', text: 'is', start_time: 3.5, end_time: 4.0, confidence: 0.97 },
{ id: 'word_8', text: 'another', start_time: 4.0, end_time: 4.5, confidence: 0.93 },
{ id: 'word_9', text: 'line', start_time: 4.5, end_time: 5.0, confidence: 0.91 },
],
},
{
id: 'seg_3',
text: 'Final segment here',
start_time: 6.0,
end_time: 8.0,
words: [
{ id: 'word_10', text: 'Final', start_time: 6.0, end_time: 6.7, confidence: 0.90 },
{ id: 'word_11', text: 'segment', start_time: 6.7, end_time: 7.4, confidence: 0.91 },
{ id: 'word_12', text: 'here', start_time: 7.4, end_time: 8.0, confidence: 0.92 },
],
},
],
reference_lyrics: {},
anchor_sequences: [],
gap_sequences: [],
corrections: [],
corrections_made: 0,
confidence: 0.9,
metadata: {
anchor_sequences_count: 0,
gap_sequences_count: 0,
total_words: 12,
correction_ratio: 0,
audio_hash: 'test_audio_hash_123',
artist: 'Test Artist',
title: 'Test Song',
available_handlers: [],
enabled_handlers: [],
},
correction_steps: [],
word_id_map: {},
segment_id_map: {},
resized_segments: [],
};
const mockJobData = {
job_id: 'local',
status: 'awaiting_review',
progress: 50,
created_at: null,
updated_at: null,
artist: 'Test Artist',
title: 'Test Song',
user_email: 'local@localhost',
audio_hash: 'test_audio_hash_123',
};
async function setupLocalModeMocks(page: Page) {
return setupApiFixtures(page, {
mocks: [
{ method: 'GET', path: '/api/jobs/local', response: { body: mockJobData } },
{ method: 'GET', path: '/api/jobs/local/corrections', response: { body: mockCorrectionData } },
{ method: 'GET', path: '/api/review/local/correction-data', response: { body: mockCorrectionData } },
{ method: 'POST', path: '/api/jobs/local/corrections', response: { body: { status: 'success' } } },
{ method: 'GET', path: '/api/audio/test_audio_hash_123', response: { status: 200, body: '' } },
{ method: 'GET', path: '/api/review/local/audio/test_audio_hash_123', response: { status: 200, body: '' } },
{ method: 'GET', path: '/api/tenant/config', response: { body: { tenant: null, is_default: true } } },
],
});
}
async function openReplaceSegmentsMode(page: Page) {
await page.goto('/app/jobs/local/review');
await page.waitForLoadState('networkidle');
// Click "Edit All" button
const editAllBtn = page.getByRole('button', { name: /edit all/i });
await expect(editAllBtn).toBeVisible({ timeout: 10000 });
await editAllBtn.click();
// Mode selection should appear
await expect(page.getByText('Edit All Lyrics')).toBeVisible({ timeout: 5000 });
// Click "Replace Segment Lyrics"
const replaceSegmentsCard = page.getByText('Replace Segment Lyrics');
await expect(replaceSegmentsCard).toBeVisible();
await replaceSegmentsCard.click();
// Wait for replace segments dialog
await expect(page.getByText('Edit lyrics line by line')).toBeVisible({ timeout: 5000 });
}
test.describe('Replace Segment Lyrics', () => {
test.beforeEach(async ({ page }) => {
await clearAuthToken(page);
await setupLocalModeMocks(page);
});
test('shows Replace Segment Lyrics option in mode selection', async ({ page }) => {
await page.goto('/app/jobs/local/review');
await page.waitForLoadState('networkidle');
const editAllBtn = page.getByRole('button', { name: /edit all/i });
await expect(editAllBtn).toBeVisible({ timeout: 10000 });
await editAllBtn.click();
// Should see all three options
await expect(page.getByText('Re-sync Existing Lyrics')).toBeVisible();
await expect(page.getByText('Replace Segment Lyrics')).toBeVisible();
await expect(page.getByText('Replace All Lyrics')).toBeVisible();
await expect(page.getByText('Recommended for custom lyrics')).toBeVisible();
});
test('textarea shows existing lyrics pre-filled', async ({ page }) => {
await openReplaceSegmentsMode(page);
const textarea = page.getByRole('textbox');
await expect(textarea).toHaveValue(
'Hello world from the test\nThis is another line\nFinal segment here'
);
});
test('shows matching line count when correct', async ({ page }) => {
await openReplaceSegmentsMode(page);
await expect(page.getByText('3/3 lines')).toBeVisible();
});
test('Apply is enabled when line count matches', async ({ page }) => {
await openReplaceSegmentsMode(page);
const applyBtn = page.getByRole('button', { name: 'Apply' });
await expect(applyBtn).toBeEnabled();
});
test('disables Apply and shows error when extra line added', async ({ page }) => {
await openReplaceSegmentsMode(page);
const textarea = page.getByRole('textbox');
// Add an extra line
await textarea.fill(
'Hello world from the test\nThis is another line\nFinal segment here\nExtra line'
);
const applyBtn = page.getByRole('button', { name: 'Apply' });
await expect(applyBtn).toBeDisabled();
await expect(page.getByText(/1 too many/)).toBeVisible();
await expect(page.getByText('4/3 lines')).toBeVisible();
});
test('disables Apply and shows error when line removed', async ({ page }) => {
await openReplaceSegmentsMode(page);
const textarea = page.getByRole('textbox');
await textarea.fill('Hello world from the test\nThis is another line');
const applyBtn = page.getByRole('button', { name: 'Apply' });
await expect(applyBtn).toBeDisabled();
await expect(page.getByText(/1 too few/)).toBeVisible();
});
test('Apply updates modified segment lyrics in the UI', async ({ page }) => {
await openReplaceSegmentsMode(page);
const textarea = page.getByRole('textbox');
await textarea.fill(
'Hello world from the test\nCustom parody lyrics now\nFinal segment here'
);
const applyBtn = page.getByRole('button', { name: 'Apply' });
await expect(applyBtn).toBeEnabled();
await applyBtn.click();
// Dialog should close
await expect(page.getByText('Edit lyrics line by line')).not.toBeVisible();
// The modified line should appear in the lyrics view
await expect(page.getByText('Custom')).toBeVisible({ timeout: 5000 });
await expect(page.getByText('parody')).toBeVisible();
// Unchanged lines should still be there
await expect(page.getByText('Hello')).toBeVisible();
await expect(page.getByText('Final')).toBeVisible();
});
test('re-enables Apply after fixing line count mismatch', async ({ page }) => {
await openReplaceSegmentsMode(page);
const textarea = page.getByRole('textbox');
// Add extra line
await textarea.fill(
'Hello world from the test\nThis is another line\nFinal segment here\nExtra'
);
await expect(page.getByRole('button', { name: 'Apply' })).toBeDisabled();
// Fix it back to 3 lines
await textarea.fill(
'Hello world from the test\nThis is another line\nFinal segment here'
);
await expect(page.getByRole('button', { name: 'Apply' })).toBeEnabled();
});
});
+1
View File
@@ -11,6 +11,7 @@ const customJestConfig = {
testEnvironment: 'jest-environment-jsdom',
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/$1',
'^nanoid$': '<rootDir>/node_modules/nanoid/index.cjs',
},
testMatch: [
'**/__tests__/**/*.test.[jt]s?(x)',
+8
View File
@@ -27,3 +27,11 @@ global.IntersectionObserver = class IntersectionObserver {
unobserve() {}
}
// Mock ResizeObserver
global.ResizeObserver = class ResizeObserver {
constructor() {}
disconnect() {}
observe() {}
unobserve() {}
}
+60
View File
@@ -52,6 +52,66 @@ describe("API Client", () => {
expect(callArgs).toContain("status=complete")
expect(callArgs).toContain("limit=10")
})
it("should send fields=summary query param", async () => {
;(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => [],
})
await api.listJobs({ fields: "summary", limit: 100 })
const callArgs = (global.fetch as jest.Mock).mock.calls[0][0]
expect(callArgs).toContain("fields=summary")
})
it("should send hide_completed=true query param", async () => {
;(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => [],
})
await api.listJobs({ fields: "summary", hide_completed: true })
const callArgs = (global.fetch as jest.Mock).mock.calls[0][0]
expect(callArgs).toContain("hide_completed=true")
})
it("should not send hide_completed when undefined", async () => {
;(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => [],
})
await api.listJobs({ fields: "summary" })
const callArgs = (global.fetch as jest.Mock).mock.calls[0][0]
expect(callArgs).not.toContain("hide_completed")
})
it("should handle summary response with partial job data", async () => {
const summaryJobs = [
{
job_id: "abc",
status: "pending",
progress: 0,
created_at: "2026-01-01T00:00:00",
artist: "Test",
title: "Song",
state_data: { brand_code: "NKP" },
file_urls: { finals: {} },
},
]
;(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => summaryJobs,
})
const result = await api.listJobs({ fields: "summary" })
expect(result).toHaveLength(1)
expect(result[0].job_id).toBe("abc")
// Summary jobs may have missing optional fields
expect(result[0].timeline).toBeUndefined()
expect(result[0].review_token).toBeUndefined()
})
})
describe("getJob", () => {
+20 -2
View File
@@ -71,6 +71,7 @@ export interface Job {
instrumental_token?: string;
audio_hash?: string;
non_interactive?: boolean;
is_private?: boolean;
user_email?: string;
outputs_deleted_at?: string;
outputs_deleted_by?: string;
@@ -269,11 +270,19 @@ export const api = {
/**
* List all jobs
*/
async listJobs(params?: { status?: string; limit?: number; exclude_test?: boolean }): Promise<Job[]> {
async listJobs(params?: {
status?: string;
limit?: number;
exclude_test?: boolean;
fields?: 'summary';
hide_completed?: boolean;
}): Promise<Job[]> {
const searchParams = new URLSearchParams();
if (params?.status) searchParams.set('status', params.status);
if (params?.limit) searchParams.set('limit', String(params.limit));
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
if (params?.fields) searchParams.set('fields', params.fields);
if (params?.hide_completed !== undefined) searchParams.set('hide_completed', String(params.hide_completed));
const url = `${API_BASE_URL}/api/jobs${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await fetch(url, {
@@ -307,6 +316,7 @@ export const api = {
theme_id?: string;
color_overrides?: ColorOverrides;
non_interactive?: boolean;
is_private?: boolean;
}
): Promise<UploadJobResponse> {
const formData = new FormData();
@@ -335,6 +345,9 @@ export const api = {
if (options?.non_interactive !== undefined) {
formData.append('non_interactive', String(options.non_interactive));
}
if (options?.is_private !== undefined) {
formData.append('is_private', String(options.is_private));
}
const response = await fetch(`${API_BASE_URL}/api/jobs/upload`, {
method: 'POST',
@@ -360,6 +373,7 @@ export const api = {
theme_id?: string;
color_overrides?: ColorOverrides;
non_interactive?: boolean;
is_private?: boolean;
}
): Promise<{ status: string; job_id: string; message: string }> {
const body: Record<string, any> = { url };
@@ -372,6 +386,7 @@ export const api = {
if (options?.theme_id) body.theme_id = options.theme_id;
if (options?.color_overrides) body.color_overrides = options.color_overrides;
if (options?.non_interactive !== undefined) body.non_interactive = options.non_interactive;
if (options?.is_private !== undefined) body.is_private = options.is_private;
const response = await fetch(`${API_BASE_URL}/api/jobs/create-from-url`, {
method: 'POST',
@@ -478,7 +493,7 @@ export const api = {
/**
* Create a custom instrumental with mute regions
*/
async createCustomInstrumental(jobId: string, muteRegions: MuteRegion[]): Promise<{ status: string; message: string }> {
async createCustomInstrumental(jobId: string, muteRegions: MuteRegion[]): Promise<{ status: string; message: string; audio_url?: string }> {
const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/create-custom-instrumental`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
@@ -556,6 +571,7 @@ export const api = {
theme_id?: string;
color_overrides?: ColorOverrides;
non_interactive?: boolean;
is_private?: boolean;
// Display overrides - if provided, these appear on title screens/filenames instead of search values
display_artist?: string;
display_title?: string;
@@ -569,6 +585,7 @@ export const api = {
if (options?.theme_id) body.theme_id = options.theme_id;
if (options?.color_overrides) body.color_overrides = options.color_overrides;
if (options?.non_interactive !== undefined) body.non_interactive = options.non_interactive;
if (options?.is_private !== undefined) body.is_private = options.is_private;
// Display overrides
if (options?.display_artist) body.display_artist = options.display_artist;
if (options?.display_title) body.display_title = options.display_title;
@@ -1709,6 +1726,7 @@ export interface JobUpdateRequest {
enable_youtube_upload?: boolean;
non_interactive?: boolean;
prep_only?: boolean;
is_private?: boolean;
}
export interface JobUpdateResponse {
+39
View File
@@ -292,3 +292,42 @@ export function sortJobsByPriority(jobs: Job[]): Job[] {
return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
});
}
/**
* Select which jobs to display from a sorted list, ensuring all incomplete
* jobs (blocking + processing) are always visible even if they exceed the
* display limit. Completed/failed jobs fill remaining slots.
*
* @param sortedJobs - Jobs already sorted by sortJobsByPriority
* @param displayLimit - Max jobs to show (-1 = show all)
* @returns Object with displayedJobs array and totalFetched count
*/
export function getDisplayJobs(
sortedJobs: Job[],
displayLimit: number,
hideCompleted: boolean = false
): { displayedJobs: Job[]; totalFetched: number } {
const totalFetched = sortedJobs.length;
// Filter out completed/failed jobs when toggle is on
const filteredJobs = hideCompleted
? sortedJobs.filter((job) => getJobPriority(job) <= 1)
: sortedJobs;
// Show all: -1 or fewer jobs than limit
if (displayLimit === -1 || filteredJobs.length <= displayLimit) {
return { displayedJobs: filteredJobs, totalFetched };
}
// Count incomplete jobs (priority 0 = blocking, 1 = processing)
const incompleteCount = filteredJobs.filter(
(job) => getJobPriority(job) <= 1
).length;
// Show at least displayLimit jobs, but expand if there are more incomplete
const showCount = Math.max(displayLimit, incompleteCount);
return {
displayedJobs: filteredJobs.slice(0, showCount),
totalFetched,
};
}
+2 -1
View File
@@ -42,7 +42,8 @@ export function isLocalMode(): boolean {
// If using hash-based routing (cloud mode pattern), it's NOT local mode
// Cloud mode uses: /app/jobs/#/{jobId}/review or /app/jobs/#/{jobId}/instrumental
if (hash && hash.match(/^#\/?[^/]+\/(review|instrumental)/)) {
// Any hash starting with #/ indicates cloud mode routing (even for invalid routes)
if (hash && hash.startsWith('#/')) {
return false
}
@@ -1,4 +1,4 @@
import { splitWordWithTiming, findWordById, getWordsFromIds } from '../wordUtils'
import { splitWordWithTiming, createWordsWithDistributedTiming, findWordById, getWordsFromIds } from '../wordUtils'
import { LyricsSegment } from '../../types'
describe('splitWordWithTiming', () => {
@@ -162,6 +162,63 @@ describe('splitWordWithTiming', () => {
})
})
describe('createWordsWithDistributedTiming', () => {
it('distributes timing equally for 3 words across 0-3s', () => {
const result = createWordsWithDistributedTiming('one two three', 0, 3)
expect(result).toHaveLength(3)
expect(result[0]).toMatchObject({ text: 'one', start_time: 0, end_time: 1, confidence: 1.0 })
expect(result[1]).toMatchObject({ text: 'two', start_time: 1, end_time: 2, confidence: 1.0 })
expect(result[2]).toMatchObject({ text: 'three', start_time: 2, end_time: 3, confidence: 1.0 })
})
it('single word fills entire segment', () => {
const result = createWordsWithDistributedTiming('hello', 5, 8)
expect(result).toHaveLength(1)
expect(result[0]).toMatchObject({ text: 'hello', start_time: 5, end_time: 8 })
})
it('returns empty array for empty text', () => {
const result = createWordsWithDistributedTiming('', 0, 3)
expect(result).toHaveLength(0)
})
it('returns empty array for whitespace-only text', () => {
const result = createWordsWithDistributedTiming(' \t ', 0, 3)
expect(result).toHaveLength(0)
})
it('defaults to 0-1s when timing is null', () => {
const result = createWordsWithDistributedTiming('hello world', null, null)
expect(result).toHaveLength(2)
expect(result[0]).toMatchObject({ text: 'hello', start_time: 0, end_time: 0.5 })
expect(result[1]).toMatchObject({ text: 'world', start_time: 0.5, end_time: 1 })
})
it('defaults start to 0 and end to 1 when only start is null', () => {
const result = createWordsWithDistributedTiming('a b', null, null)
expect(result[0].start_time).toBe(0)
expect(result[1].end_time).toBe(1)
})
it('generates unique IDs for each word', () => {
const result = createWordsWithDistributedTiming('a b c', 0, 3)
const ids = result.map((w) => w.id)
expect(new Set(ids).size).toBe(3)
})
it('handles extra whitespace between words', () => {
const result = createWordsWithDistributedTiming(' hello world ', 0, 2)
expect(result).toHaveLength(2)
expect(result[0].text).toBe('hello')
expect(result[1].text).toBe('world')
})
})
describe('findWordById', () => {
const mockSegments: LyricsSegment[] = [
{
@@ -1,3 +1,4 @@
import { nanoid } from 'nanoid'
import { Word, LyricsSegment } from '../types'
/**
@@ -50,6 +51,32 @@ export function splitWordWithTiming(
}))
}
/**
* Create Word objects with evenly distributed timing across a segment's duration.
* Used when replacing segment text while preserving the segment's time range.
*/
export function createWordsWithDistributedTiming(
text: string,
segStart: number | null,
segEnd: number | null
): Word[] {
const wordTexts = text.trim().split(/\s+/).filter((w) => w.length > 0)
if (wordTexts.length === 0) return []
const start = segStart ?? 0
const end = segEnd ?? start + 1
const totalDuration = end - start
const wordDuration = totalDuration / wordTexts.length
return wordTexts.map((text, index) => ({
id: nanoid(),
text,
start_time: start + index * wordDuration,
end_time: start + (index + 1) * wordDuration,
confidence: 1.0,
}))
}
/**
* Convert an array of word IDs to their corresponding Word objects
* Filters out any IDs that don't match to valid words
+4 -1
View File
@@ -21,7 +21,10 @@ if (fs.existsSync(envLocalPath)) {
// Configurable port for dev server (default: 3000)
// Use E2E_PORT env var to change, e.g.: E2E_PORT=3001 npx playwright test
const PORT = process.env.E2E_PORT || '3000';
const BASE_URL = `http://localhost:${PORT}`;
// Use 127.0.0.1 instead of localhost to avoid IPv6 resolution issues on macOS.
// localhost resolves to ::1 (IPv6) first, but Next.js dev server may not accept
// IPv6 connections, causing Playwright's webServer health check to hang.
const BASE_URL = `http://127.0.0.1:${PORT}`;
/**
* Playwright configuration for karaoke-gen frontend E2E tests.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 463 KiB

After

Width:  |  Height:  |  Size: 463 KiB

@@ -66,7 +66,7 @@ def create_workload_identity_provider(
"attribute.repository": "assertion.repository",
"attribute.repository_owner": "assertion.repository_owner",
},
attribute_condition="assertion.repository_owner == 'nomadkaraoke'",
attribute_condition="assertion.repository_owner == 'nomadkaraoke' || assertion.repository_owner == 'beveradb'",
oidc=iam.WorkloadIdentityPoolProviderOidcArgs(
issuer_uri="https://token.actions.githubusercontent.com",
),
@@ -170,7 +170,7 @@ def grant_github_actions_permissions(
)
# Allow GitHub Actions to impersonate the service account
# All nomadkaraoke repos that deploy to GCP need access
# All repos that deploy to GCP need access (nomadkaraoke org + beveradb personal)
bindings["wif_binding"] = serviceaccount.IAMBinding(
"github-actions-wif-binding",
service_account_id=service_account.name,
@@ -185,6 +185,9 @@ def grant_github_actions_permissions(
pool.name.apply(
lambda pool_name: f"principalSet://iam.googleapis.com/{pool_name}/attribute.repository/nomadkaraoke/karaoke-decide"
),
pool.name.apply(
lambda pool_name: f"principalSet://iam.googleapis.com/{pool_name}/attribute.repository/beveradb/cryptotrader"
),
],
)
@@ -27,6 +27,11 @@ class LyricsProviderConfig:
class BaseLyricsProvider(ABC):
"""Base class for lyrics providers."""
# Lyrics text beyond this length are almost certainly not real song lyrics
# (e.g. screenplays, articles, or other non-lyrics content from web scraping).
# Typical songs are 1000-4000 chars; 3000 is a safe truncation point.
MAX_LYRICS_LENGTH = 3000
def __init__(self, config: LyricsProviderConfig, logger: Optional[logging.Logger] = None):
self.logger = logger or logging.getLogger(__name__)
self.cache_dir = Path(config.cache_dir) if config.cache_dir else None
@@ -123,6 +128,20 @@ class BaseLyricsProvider(ABC):
Returns:
List of LyricsSegment objects with unique IDs and Word objects
"""
# Guard against abnormally long text (screenplays, articles, etc.)
if len(text) > self.MAX_LYRICS_LENGTH:
self.logger.warning(
f"{self.get_name()}: Lyrics text is {len(text):,} chars, truncating to ~{self.MAX_LYRICS_LENGTH:,} "
f"(likely non-lyrics content)"
)
# Truncate at the last complete line before the limit
truncated = text[: self.MAX_LYRICS_LENGTH]
last_newline = truncated.rfind("\n")
if last_newline > 0:
text = truncated[:last_newline]
else:
text = truncated
segments = []
lines = text.strip().split("\n")
@@ -125,26 +125,26 @@ class AudioShakeAPI:
return {"x-api-key": self.config.api_token, "Content-Type": "application/json"}
def upload_file(self, filepath: str) -> str:
"""Upload audio file and return file URL."""
"""Upload audio file via Assets API and return asset ID."""
self.logger.info(f"Uploading {filepath} to AudioShake")
self._validate_config() # Validate before making API call
url = f"{self.config.base_url}/upload/"
url = f"{self.config.base_url}/assets"
with open(filepath, "rb") as file:
files = {"file": (os.path.basename(filepath), file)}
response = requests.post(url, headers={"x-api-key": self.config.api_token}, files=files)
self.logger.debug(f"Upload response: {response.status_code} - {response.text}")
response.raise_for_status()
return response.json()["link"]
return response.json()["id"]
def create_task(self, file_url: str) -> str:
def create_task(self, asset_id: str) -> str:
"""Create transcription task and return task ID."""
self.logger.info(f"Creating task for file {file_url}")
self.logger.info(f"Creating task for asset {asset_id}")
url = f"{self.config.base_url}/tasks"
data = {
"url": file_url,
"assetId": asset_id,
"targets": [
{
"model": "alignment",
@@ -290,10 +290,10 @@ class AudioShakeTranscriber(BaseTranscriber):
try:
# Upload file and create task
file_url = self.api.upload_file(upload_filepath)
self.logger.debug(f"File uploaded successfully. File URL: {file_url}")
asset_id = self.api.upload_file(upload_filepath)
self.logger.debug(f"File uploaded successfully. Asset ID: {asset_id}")
task_id = self.api.create_task(file_url)
task_id = self.api.create_task(asset_id)
self.logger.debug(f"Task created successfully. Task ID: {task_id}")
return task_id
+1
View File
@@ -0,0 +1 @@
<!DOCTYPE html><!--tSn8ObPJyQkdGHYgdwN6Y--><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/chunks/981a3bf030d34e95.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/56df4d5ab85b6adb.js"/><script src="/_next/static/chunks/248cba0fcb3874ed.js" async=""></script><script src="/_next/static/chunks/a9ed54eed3e14c92.js" async=""></script><script src="/_next/static/chunks/94bde6376cf279be.js" async=""></script><script src="/_next/static/chunks/5997132b61dec430.js" async=""></script><script src="/_next/static/chunks/turbopack-7ce6493647b9aa23.js" async=""></script><script src="/_next/static/chunks/4dc7efe58b813844.js" async=""></script><script src="/_next/static/chunks/d668512033b1256e.js" async=""></script><script src="/_next/static/chunks/247eb132b7f7b574.js" async=""></script><script src="/_next/static/chunks/d235c7efc1a1df60.js" async=""></script><link rel="preload" href="https://www.googletagmanager.com/gtag/js?id=G-D0E63LB9FY" as="script"/><meta name="robots" content="noindex"/><title>404: This page could not be found.</title><title>Nomad Karaoke: Generator</title><meta name="description" content="Generate professional karaoke videos with AI-powered vocal separation and synchronized lyrics"/><link rel="manifest" href="/manifest.webmanifest"/><link rel="icon" href="/favicon.ico" sizes="any"/><link rel="icon" href="/favicon-16x16.png" sizes="16x16" type="image/png"/><link rel="icon" href="/favicon-32x32.png" sizes="32x32" type="image/png"/><link rel="apple-touch-icon" href="/apple-touch-icon.png"/><script src="/_next/static/chunks/a6dad97d9634a72d.js" noModule=""></script></head><body class="font-sans antialiased" style="background:var(--bg);color:var(--text)"><div hidden=""><!--$--><!--/$--></div><script>((a,b,c,d,e,f,g,h)=>{let i=document.documentElement,j=["light","dark"];function k(b){var c;(Array.isArray(a)?a:[a]).forEach(a=>{let c="class"===a,d=c&&f?e.map(a=>f[a]||a):e;c?(i.classList.remove(...d),i.classList.add(f&&f[b]?f[b]:b)):i.setAttribute(a,b)}),c=b,h&&j.includes(c)&&(i.style.colorScheme=c)}if(d)k(d);else try{let a=localStorage.getItem(b)||c,d=g&&"system"===a?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":a;k(d)}catch(a){}})("class","theme","dark",null,["light","dark"],null,true,true)</script><div style="font-family:system-ui,&quot;Segoe UI&quot;,Roboto,Helvetica,Arial,sans-serif,&quot;Apple Color Emoji&quot;,&quot;Segoe UI Emoji&quot;;height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/56df4d5ab85b6adb.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[43316,[\"/_next/static/chunks/4dc7efe58b813844.js\",\"/_next/static/chunks/d668512033b1256e.js\",\"/_next/static/chunks/247eb132b7f7b574.js\",\"/_next/static/chunks/d235c7efc1a1df60.js\"],\"GoogleAnalytics\"]\n3:I[72285,[\"/_next/static/chunks/4dc7efe58b813844.js\",\"/_next/static/chunks/d668512033b1256e.js\",\"/_next/static/chunks/247eb132b7f7b574.js\",\"/_next/static/chunks/d235c7efc1a1df60.js\"],\"ServiceWorkerRegistration\"]\n4:I[89554,[\"/_next/static/chunks/4dc7efe58b813844.js\",\"/_next/static/chunks/d668512033b1256e.js\",\"/_next/static/chunks/247eb132b7f7b574.js\",\"/_next/static/chunks/d235c7efc1a1df60.js\"],\"ThemeProvider\"]\n5:I[57091,[\"/_next/static/chunks/4dc7efe58b813844.js\",\"/_next/static/chunks/d668512033b1256e.js\",\"/_next/static/chunks/247eb132b7f7b574.js\",\"/_next/static/chunks/d235c7efc1a1df60.js\"],\"TenantProvider\"]\n6:I[48030,[\"/_next/static/chunks/4dc7efe58b813844.js\",\"/_next/static/chunks/d668512033b1256e.js\",\"/_next/static/chunks/247eb132b7f7b574.js\",\"/_next/static/chunks/d235c7efc1a1df60.js\"],\"ImpersonationBannerWrapper\"]\n7:I[39756,[\"/_next/static/chunks/4dc7efe58b813844.js\",\"/_next/static/chunks/d668512033b1256e.js\",\"/_next/static/chunks/247eb132b7f7b574.js\",\"/_next/static/chunks/d235c7efc1a1df60.js\"],\"default\"]\n8:I[37457,[\"/_next/static/chunks/4dc7efe58b813844.js\",\"/_next/static/chunks/d668512033b1256e.js\",\"/_next/static/chunks/247eb132b7f7b574.js\",\"/_next/static/chunks/d235c7efc1a1df60.js\"],\"default\"]\n9:I[97367,[\"/_next/static/chunks/4dLine truncated
@@ -0,0 +1 @@
<!DOCTYPE html><!--tSn8ObPJyQkdGHYgdwN6Y--><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/chunks/981a3bf030d34e95.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/56df4d5ab85b6adb.js"/><script src="/_next/static/chunks/248cba0fcb3874ed.js" async=""></script><script src="/_next/static/chunks/a9ed54eed3e14c92.js" async=""></script><script src="/_next/static/chunks/94bde6376cf279be.js" async=""></script><script src="/_next/static/chunks/5997132b61dec430.js" async=""></script><script src="/_next/static/chunks/turbopack-7ce6493647b9aa23.js" async=""></script><script src="/_next/static/chunks/4dc7efe58b813844.js" async=""></script><script src="/_next/static/chunks/d668512033b1256e.js" async=""></script><script src="/_next/static/chunks/247eb132b7f7b574.js" async=""></script><script src="/_next/static/chunks/d235c7efc1a1df60.js" async=""></script><link rel="preload" href="https://www.googletagmanager.com/gtag/js?id=G-D0E63LB9FY" as="script"/><meta name="robots" content="noindex"/><title>404: This page could not be found.</title><title>Nomad Karaoke: Generator</title><meta name="description" content="Generate professional karaoke videos with AI-powered vocal separation and synchronized lyrics"/><link rel="manifest" href="/manifest.webmanifest"/><link rel="icon" href="/favicon.ico" sizes="any"/><link rel="icon" href="/favicon-16x16.png" sizes="16x16" type="image/png"/><link rel="icon" href="/favicon-32x32.png" sizes="32x32" type="image/png"/><link rel="apple-touch-icon" href="/apple-touch-icon.png"/><script src="/_next/static/chunks/a6dad97d9634a72d.js" noModule=""></script></head><body class="font-sans antialiased" style="background:var(--bg);color:var(--text)"><div hidden=""><!--$--><!--/$--></div><script>((a,b,c,d,e,f,g,h)=>{let i=document.documentElement,j=["light","dark"];function k(b){var c;(Array.isArray(a)?a:[a]).forEach(a=>{let c="class"===a,d=c&&f?e.map(a=>f[a]||a):e;c?(i.classList.remove(...d),i.classList.add(f&&f[b]?f[b]:b)):i.setAttribute(a,b)}),c=b,h&&j.includes(c)&&(i.style.colorScheme=c)}if(d)k(d);else try{let a=localStorage.getItem(b)||c,d=g&&"system"===a?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":a;k(d)}catch(a){}})("class","theme","dark",null,["light","dark"],null,true,true)</script><div style="font-family:system-ui,&quot;Segoe UI&quot;,Roboto,Helvetica,Arial,sans-serif,&quot;Apple Color Emoji&quot;,&quot;Segoe UI Emoji&quot;;height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/56df4d5ab85b6adb.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[43316,[\"/_next/static/chunks/4dc7efe58b813844.js\",\"/_next/static/chunks/d668512033b1256e.js\",\"/_next/static/chunks/247eb132b7f7b574.js\",\"/_next/static/chunks/d235c7efc1a1df60.js\"],\"GoogleAnalytics\"]\n3:I[72285,[\"/_next/static/chunks/4dc7efe58b813844.js\",\"/_next/static/chunks/d668512033b1256e.js\",\"/_next/static/chunks/247eb132b7f7b574.js\",\"/_next/static/chunks/d235c7efc1a1df60.js\"],\"ServiceWorkerRegistration\"]\n4:I[89554,[\"/_next/static/chunks/4dc7efe58b813844.js\",\"/_next/static/chunks/d668512033b1256e.js\",\"/_next/static/chunks/247eb132b7f7b574.js\",\"/_next/static/chunks/d235c7efc1a1df60.js\"],\"ThemeProvider\"]\n5:I[57091,[\"/_next/static/chunks/4dc7efe58b813844.js\",\"/_next/static/chunks/d668512033b1256e.js\",\"/_next/static/chunks/247eb132b7f7b574.js\",\"/_next/static/chunks/d235c7efc1a1df60.js\"],\"TenantProvider\"]\n6:I[48030,[\"/_next/static/chunks/4dc7efe58b813844.js\",\"/_next/static/chunks/d668512033b1256e.js\",\"/_next/static/chunks/247eb132b7f7b574.js\",\"/_next/static/chunks/d235c7efc1a1df60.js\"],\"ImpersonationBannerWrapper\"]\n7:I[39756,[\"/_next/static/chunks/4dc7efe58b813844.js\",\"/_next/static/chunks/d668512033b1256e.js\",\"/_next/static/chunks/247eb132b7f7b574.js\",\"/_next/static/chunks/d235c7efc1a1df60.js\"],\"default\"]\n8:I[37457,[\"/_next/static/chunks/4dc7efe58b813844.js\",\"/_next/static/chunks/d668512033b1256e.js\",\"/_next/static/chunks/247eb132b7f7b574.js\",\"/_next/static/chunks/d235c7efc1a1df60.js\"],\"default\"]\n9:I[97367,[\"/_next/static/chunks/4dLine truncated
@@ -0,0 +1,9 @@
1:"$Sreact.fragment"
2:I[47257,["/_next/static/chunks/ff1a16fafef87110.js","/_next/static/chunks/247eb132b7f7b574.js"],"ClientPageRoot"]
3:I[31713,["/_next/static/chunks/7a7cb38b07cc9f82.js","/_next/static/chunks/d235c7efc1a1df60.js","/_next/static/chunks/d668512033b1256e.js","/_next/static/chunks/3fba0305955d13e6.js","/_next/static/chunks/692f5d9e0d700c76.js","/_next/static/chunks/dcde6ed684dacd0e.js"],"default"]
6:I[97367,["/_next/static/chunks/ff1a16fafef87110.js","/_next/static/chunks/247eb132b7f7b574.js"],"OutletBoundary"]
7:"$Sreact.suspense"
0:{"buildId":"tSn8ObPJyQkdGHYgdwN6Y","rsc":["$","$1","c",{"children":[["$","$L2",null,{"Component":"$3","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@4","$@5"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/3fba0305955d13e6.js","async":true}],["$","script","script-1",{"src":"/_next/static/chunks/692f5d9e0d700c76.js","async":true}],["$","script","script-2",{"src":"/_next/static/chunks/dcde6ed684dacd0e.js","async":true}]],["$","$L6",null,{"children":["$","$7",null,{"name":"Next.MetadataOutlet","children":"$@8"}]}]]}],"loading":null,"isPartial":false}
4:{}
5:"$0:rsc:props:children:0:props:serverProvidedParams:params"
8:null
@@ -0,0 +1,23 @@
1:"$Sreact.fragment"
2:I[43316,["/_next/static/chunks/7a7cb38b07cc9f82.js","/_next/static/chunks/d235c7efc1a1df60.js","/_next/static/chunks/d668512033b1256e.js"],"GoogleAnalytics"]
3:I[72285,["/_next/static/chunks/7a7cb38b07cc9f82.js","/_next/static/chunks/d235c7efc1a1df60.js","/_next/static/chunks/d668512033b1256e.js"],"ServiceWorkerRegistration"]
4:I[89554,["/_next/static/chunks/7a7cb38b07cc9f82.js","/_next/static/chunks/d235c7efc1a1df60.js","/_next/static/chunks/d668512033b1256e.js"],"ThemeProvider"]
5:I[57091,["/_next/static/chunks/7a7cb38b07cc9f82.js","/_next/static/chunks/d235c7efc1a1df60.js","/_next/static/chunks/d668512033b1256e.js"],"TenantProvider"]
6:I[48030,["/_next/static/chunks/7a7cb38b07cc9f82.js","/_next/static/chunks/d235c7efc1a1df60.js","/_next/static/chunks/d668512033b1256e.js"],"ImpersonationBannerWrapper"]
7:I[39756,["/_next/static/chunks/ff1a16fafef87110.js","/_next/static/chunks/247eb132b7f7b574.js"],"default"]
8:I[37457,["/_next/static/chunks/ff1a16fafef87110.js","/_next/static/chunks/247eb132b7f7b574.js"],"default"]
9:I[47257,["/_next/static/chunks/ff1a16fafef87110.js","/_next/static/chunks/247eb132b7f7b574.js"],"ClientPageRoot"]
a:I[31713,["/_next/static/chunks/7a7cb38b07cc9f82.js","/_next/static/chunks/d235c7efc1a1df60.js","/_next/static/chunks/d668512033b1256e.js","/_next/static/chunks/3fba0305955d13e6.js","/_next/static/chunks/692f5d9e0d700c76.js","/_next/static/chunks/dcde6ed684dacd0e.js"],"default"]
d:I[97367,["/_next/static/chunks/ff1a16fafef87110.js","/_next/static/chunks/247eb132b7f7b574.js"],"OutletBoundary"]
e:"$Sreact.suspense"
10:I[97367,["/_next/static/chunks/ff1a16fafef87110.js","/_next/static/chunks/247eb132b7f7b574.js"],"ViewportBoundary"]
12:I[97367,["/_next/static/chunks/ff1a16fafef87110.js","/_next/static/chunks/247eb132b7f7b574.js"],"MetadataBoundary"]
14:I[68027,["/_next/static/chunks/ff1a16fafef87110.js","/_next/static/chunks/247eb132b7f7b574.js"],"default"]
:HL["/_next/static/chunks/981a3bf030d34e95.css","style"]
0:{"P":null,"b":"tSn8ObPJyQkdGHYgdwN6Y","c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/981a3bf030d34e95.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/7a7cb38b07cc9f82.js","async":true,"nonce":"$undefined"}],["$","script","script-1",{"src":"/_next/static/chunks/d235c7efc1a1df60.js","async":true,"nonce":"$undefined"}],["$","script","script-2",{"src":"/_next/static/chunks/d668512033b1256e.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":["$","body",null,{"className":"font-sans antialiased","style":{"background":"var(--bg)","color":"var(--text)"},"children":[["$","$L2",null,{}],["$","$L3",null,{}],["$","$L4",null,{"attribute":"class","defaultTheme":"dark","enableSystem":true,"disableTransitionOnChange":true,"children":["$","$L5",null,{"children":[["$","$L6",null,{}],["$","$L7",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L8",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]]}]}]]}]}]]}],{"children":[["$","$1","c",{"children":[["$","$L9",null,{"Component":"$a","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@b","$@c"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/3fba0305955d13e6.js","async":true,"nonce":"$undefined"}],["$","script","script-1",{"src":"/_next/static/chunks/692f5d9e0d700c76.js","async":true,"nonce":"$undefined"}],["$","script","script-2",{"src":"/_next/static/chunks/dcde6ed684dacd0e.js","async":true,"nonce":"$undefined"}]],["$","$Ld",null,{"children":["$","$e",null,{"name":"Next.MetadataOutlet","children":"$@f"}]}]]}],{},null,false,false]},null,false,false],["$","$1","h",{"children":[null,["$","$L10",null,{"children":"$@11"}],["$","div",null,{"hidden":true,"children":["$","$L12",null,{"children":["$","$e",null,{"name":"Next.Metadata","children":"$@13"}]}]}],null]}],false]],"m":"$undefined","G":["$14",[]],"S":true}
b:{}
c:"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params"
11:[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]
15:I[27201,["/_next/static/chunks/ff1a16fafef87110.js","/_next/static/chunks/247eb132b7f7b574.js"],"IconMark"]
13:[["$","title","0",{"children":"Nomad Karaoke: Generator"}],["$","meta","1",{"name":"description","content":"Generate professional karaoke videos with AI-powered vocal separation and synchronized lyrics"}],["$","link","2",{"rel":"manifest","href":"/manifest.webmanifest","crossOrigin":"$undefined"}],["$","link","3",{"rel":"icon","href":"/favicon.ico","sizes":"any"}],["$","link","4",{"rel":"icon","href":"/favicon-16x16.png","sizes":"16x16","type":"image/png"}],["$","link","5",{"rel":"icon","href":"/favicon-32x32.png","sizes":"32x32","type":"image/png"}],["$","link","6",{"rel":"apple-touch-icon","href":"/apple-touch-icon.png"}],["$","$L15","7",{}]]
f:null
@@ -0,0 +1,8 @@
1:"$Sreact.fragment"
2:I[97367,["/_next/static/chunks/ff1a16fafef87110.js","/_next/static/chunks/247eb132b7f7b574.js"],"ViewportBoundary"]
4:I[97367,["/_next/static/chunks/ff1a16fafef87110.js","/_next/static/chunks/247eb132b7f7b574.js"],"MetadataBoundary"]
5:"$Sreact.suspense"
7:I[27201,["/_next/static/chunks/ff1a16fafef87110.js","/_next/static/chunks/247eb132b7f7b574.js"],"IconMark"]
0:{"buildId":"tSn8ObPJyQkdGHYgdwN6Y","rsc":["$","$1","h",{"children":[null,["$","$L2",null,{"children":"$@3"}],["$","div",null,{"hidden":true,"children":["$","$L4",null,{"children":["$","$5",null,{"name":"Next.Metadata","children":"$@6"}]}]}],null]}],"loading":null,"isPartial":false}
3:[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]
6:[["$","title","0",{"children":"Nomad Karaoke: Generator"}],["$","meta","1",{"name":"description","content":"Generate professional karaoke videos with AI-powered vocal separation and synchronized lyrics"}],["$","link","2",{"rel":"manifest","href":"/manifest.webmanifest"}],["$","link","3",{"rel":"icon","href":"/favicon.ico","sizes":"any"}],["$","link","4",{"rel":"icon","href":"/favicon-16x16.png","sizes":"16x16","type":"image/png"}],["$","link","5",{"rel":"icon","href":"/favicon-32x32.png","sizes":"32x32","type":"image/png"}],["$","link","6",{"rel":"apple-touch-icon","href":"/apple-touch-icon.png"}],["$","$L7","7",{}]]
@@ -0,0 +1,10 @@
1:"$Sreact.fragment"
2:I[43316,["/_next/static/chunks/7a7cb38b07cc9f82.js","/_next/static/chunks/d235c7efc1a1df60.js","/_next/static/chunks/d668512033b1256e.js"],"GoogleAnalytics"]
3:I[72285,["/_next/static/chunks/7a7cb38b07cc9f82.js","/_next/static/chunks/d235c7efc1a1df60.js","/_next/static/chunks/d668512033b1256e.js"],"ServiceWorkerRegistration"]
4:I[89554,["/_next/static/chunks/7a7cb38b07cc9f82.js","/_next/static/chunks/d235c7efc1a1df60.js","/_next/static/chunks/d668512033b1256e.js"],"ThemeProvider"]
5:I[57091,["/_next/static/chunks/7a7cb38b07cc9f82.js","/_next/static/chunks/d235c7efc1a1df60.js","/_next/static/chunks/d668512033b1256e.js"],"TenantProvider"]
6:I[48030,["/_next/static/chunks/7a7cb38b07cc9f82.js","/_next/static/chunks/d235c7efc1a1df60.js","/_next/static/chunks/d668512033b1256e.js"],"ImpersonationBannerWrapper"]
7:I[39756,["/_next/static/chunks/ff1a16fafef87110.js","/_next/static/chunks/247eb132b7f7b574.js"],"default"]
8:I[37457,["/_next/static/chunks/ff1a16fafef87110.js","/_next/static/chunks/247eb132b7f7b574.js"],"default"]
:HL["/_next/static/chunks/981a3bf030d34e95.css","style"]
0:{"buildId":"tSn8ObPJyQkdGHYgdwN6Y","rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/981a3bf030d34e95.css","precedence":"next"}],["$","script","script-0",{"src":"/_next/static/chunks/7a7cb38b07cc9f82.js","async":true}],["$","script","script-1",{"src":"/_next/static/chunks/d235c7efc1a1df60.js","async":true}],["$","script","script-2",{"src":"/_next/static/chunks/d668512033b1256e.js","async":true}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":["$","body",null,{"className":"font-sans antialiased","style":{"background":"var(--bg)","color":"var(--text)"},"children":[["$","$L2",null,{}],["$","$L3",null,{}],["$","$L4",null,{"attribute":"class","defaultTheme":"dark","enableSystem":true,"disableTransitionOnChange":true,"children":["$","$L5",null,{"children":[["$","$L6",null,{}],["$","$L7",null,{"parallelRouterKey":"children","template":["$","$L8",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]]}]}]]}]}]]}],"loading":null,"isPartial":false}
@@ -0,0 +1,2 @@
:HL["/_next/static/chunks/981a3bf030d34e95.css","style"]
0:{"buildId":"tSn8ObPJyQkdGHYgdwN6Y","tree":{"name":"","paramType":null,"paramKey":"","hasRuntimePrefetch":false,"slots":{"children":{"name":"__PAGE__","paramType":null,"paramKey":"__PAGE__","hasRuntimePrefetch":false,"slots":null,"isRootLayout":false}},"isRootLayout":true},"staleTime":300}
@@ -0,0 +1 @@
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,3116,e=>{"use strict";let s=(0,e.i(75254).default)("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);e.s(["Clock",()=>s],3116)},61659,e=>{"use strict";let s=(0,e.i(75254).default)("CreditCard",[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]]);e.s(["CreditCard",()=>s],61659)},69638,e=>{"use strict";let s=(0,e.i(75254).default)("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);e.s(["CheckCircle",()=>s],69638)},73884,e=>{"use strict";let s=(0,e.i(75254).default)("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);e.s(["XCircle",()=>s],73884)},63209,e=>{"use strict";let s=(0,e.i(75254).default)("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);e.s(["AlertCircle",()=>s],63209)},16715,e=>{"use strict";let s=(0,e.i(75254).default)("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);e.s(["RefreshCw",()=>s],16715)},94179,e=>{"use strict";var s=e.i(43476),t=e.i(91918),a=e.i(25913),r=e.i(47163);let i=(0,a.cva)("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function d({className:e,variant:a,asChild:d=!1,...l}){let c=d?t.Slot:"span";return(0,s.jsx)(c,{"data-slot":"badge",className:(0,r.cn)(i({variant:a}),e),...l})}e.s(["Badge",()=>d])},70065,e=>{"use strict";var s=e.i(43476),t=e.i(47163);function a({className:e,...a}){return(0,s.jsx)("div",{"data-slot":"card",className:(0,t.cn)("bg-card text-card-foreground flex flex-col gap-1 rounded-lg border py-6 shadow-sm",e),...a})}function r({className:e,...a}){return(0,s.jsx)("div",{"data-slot":"card-header",className:(0,t.cn)("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...a})}function i({className:e,...a}){return(0,s.jsx)("div",{"data-slot":"card-title",className:(0,t.cn)("leading-none font-semibold",e),...a})}function d({className:e,...a}){return(0,s.jsx)("div",{"data-slot":"card-description",className:(0,t.cn)("text-muted-foreground text-sm",e),...a})}function l({className:e,...a}){return(0,s.jsx)("div",{"data-slot":"card-content",className:(0,t.cn)("px-6",e),...a})}e.s(["Card",()=>a,"CardContent",()=>l,"CardDescription",()=>d,"CardHeader",()=>r,"CardTitle",()=>i])},59276,e=>{"use strict";var s=e.i(43476),t=e.i(70065),a=e.i(71428),r=e.i(47163);function i({title:e,value:i,description:d,icon:l,trend:c,loading:n,className:o,valueClassName:x}){return n?(0,s.jsxs)(t.Card,{className:(0,r.cn)("",o),children:[(0,s.jsx)(t.CardHeader,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:(0,s.jsx)(t.CardTitle,{className:"text-sm font-medium",children:(0,s.jsx)(a.Skeleton,{className:"h-4 w-24"})})}),(0,s.jsxs)(t.CardContent,{children:[(0,s.jsx)(a.Skeleton,{className:"h-8 w-16"}),(0,s.jsx)(a.Skeleton,{className:"h-3 w-32 mt-2"})]})]}):(0,s.jsxs)(t.Card,{className:(0,r.cn)("",o),children:[(0,s.jsxs)(t.CardHeader,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[(0,s.jsx)(t.CardTitle,{className:"text-sm font-medium text-muted-foreground",children:e}),l&&(0,s.jsx)(l,{className:"h-4 w-4 text-muted-foreground"})]}),(0,s.jsxs)(t.CardContent,{children:[(0,s.jsx)("div",{className:(0,r.cn)("text-2xl font-bold",x),children:i}),d&&(0,s.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:d}),c&&(0,s.jsxs)("p",{className:(0,r.cn)("text-xs mt-1",!0===c.positive?"text-green-500":!1===c.positive?"text-red-500":"text-muted-foreground"),children:[!0===c.Line truncated
@@ -0,0 +1 @@
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,31278,17521,e=>{"use strict";let s=(0,e.i(75254).default)("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);e.s(["default",()=>s],17521),e.s(["Loader2",()=>s],31278)},18566,(e,s,r)=>{s.exports=e.r(76562)},69638,e=>{"use strict";let s=(0,e.i(75254).default)("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);e.s(["CheckCircle",()=>s],69638)},3116,e=>{"use strict";let s=(0,e.i(75254).default)("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);e.s(["Clock",()=>s],3116)},63488,e=>{"use strict";let s=(0,e.i(75254).default)("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);e.s(["Mail",()=>s],63488)},31897,e=>{"use strict";var s=e.i(43476),r=e.i(71645),t=e.i(18566),a=e.i(69638),l=e.i(31278),d=e.i(63488),i=e.i(3116),c=e.i(67881);function o(){return(0,t.useSearchParams)().get("session_id"),(0,s.jsxs)("div",{className:"max-w-md w-full bg-card border border-border rounded-xl p-8 text-center",children:[(0,s.jsx)(a.CheckCircle,{className:"w-16 h-16 text-success mx-auto mb-4"}),(0,s.jsx)("h1",{className:"text-2xl font-bold text-foreground mb-2",children:"Order Confirmed!"}),(0,s.jsx)("p",{className:"text-muted-foreground mb-6",children:"Thank you for your order. We're creating your custom karaoke video now."}),(0,s.jsxs)("div",{className:"space-y-4 mb-6",children:[(0,s.jsxs)("div",{className:"flex items-center gap-3 text-left p-3 bg-secondary rounded-lg",children:[(0,s.jsx)(i.Clock,{className:"w-5 h-5 text-primary flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium text-foreground",children:"Delivery within 24 hours"}),(0,s.jsx)("p",{className:"text-sm text-muted-foreground",children:"Most orders are completed in just a few hours"})]})]}),(0,s.jsxs)("div",{className:"flex items-center gap-3 text-left p-3 bg-secondary rounded-lg",children:[(0,s.jsx)(d.Mail,{className:"w-5 h-5 text-primary flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium text-foreground",children:"Check your email"}),(0,s.jsx)("p",{className:"text-sm text-muted-foreground",children:"We'll send your video when it's ready"})]})]})]}),(0,s.jsxs)("div",{className:"space-y-3",children:[(0,s.jsx)(c.Button,{asChild:!0,className:"w-full bg-primary hover:bg-primary/90",children:(0,s.jsx)("a",{href:"https://nomadkaraoke.com",children:"Back to Nomad Karaoke"})}),(0,s.jsx)("p",{className:"text-xs text-muted-foreground",children:"Questions? Email us at help@nomadkaraoke.com"})]})]})}function n(){return(0,s.jsx)("div",{className:"min-h-screen bg-background flex items-center justify-center p-4",children:(0,s.jsx)(r.Suspense,{fallback:(0,s.jsxs)("div",{className:"max-w-md w-full bg-card border border-border rounded-xl p-8 text-center",children:[(0,s.jsx)(l.Loader2,{className:"w-16 h-16 text-primary mx-auto mb-4 animate-spin"}),(0,s.jsx)("p",{className:"text-muted-foreground",children:"Loading..."})]}),children:(0,s.jsx)(o,{})})})}e.s(["default",()=>n])}]);
@@ -0,0 +1,7 @@
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,16715,e=>{"use strict";let t=(0,e.i(75254).default)("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);e.s(["RefreshCw",()=>t],16715)},94179,e=>{"use strict";var t=e.i(43476),r=e.i(91918),a=e.i(25913),o=e.i(47163);let n=(0,a.cva)("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function i({className:e,variant:a,asChild:i=!1,...l}){let s=i?r.Slot:"span";return(0,t.jsx)(s,{"data-slot":"badge",className:(0,o.cn)(n({variant:a}),e),...l})}e.s(["Badge",()=>i])},70065,e=>{"use strict";var t=e.i(43476),r=e.i(47163);function a({className:e,...a}){return(0,t.jsx)("div",{"data-slot":"card",className:(0,r.cn)("bg-card text-card-foreground flex flex-col gap-1 rounded-lg border py-6 shadow-sm",e),...a})}function o({className:e,...a}){return(0,t.jsx)("div",{"data-slot":"card-header",className:(0,r.cn)("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...a})}function n({className:e,...a}){return(0,t.jsx)("div",{"data-slot":"card-title",className:(0,r.cn)("leading-none font-semibold",e),...a})}function i({className:e,...a}){return(0,t.jsx)("div",{"data-slot":"card-description",className:(0,r.cn)("text-muted-foreground text-sm",e),...a})}function l({className:e,...a}){return(0,t.jsx)("div",{"data-slot":"card-content",className:(0,r.cn)("px-6",e),...a})}e.s(["Card",()=>a,"CardContent",()=>l,"CardDescription",()=>i,"CardHeader",()=>o,"CardTitle",()=>n])},47627,e=>{"use strict";var t=e.i(43476),r=e.i(47163);function a({className:e,...a}){return(0,t.jsx)("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:(0,t.jsx)("table",{"data-slot":"table",className:(0,r.cn)("w-full caption-bottom text-sm",e),...a})})}function o({className:e,...a}){return(0,t.jsx)("thead",{"data-slot":"table-header",className:(0,r.cn)("[&_tr]:border-b",e),...a})}function n({className:e,...a}){return(0,t.jsx)("tbody",{"data-slot":"table-body",className:(0,r.cn)("[&_tr:last-child]:border-0",e),...a})}function i({className:e,...a}){return(0,t.jsx)("tr",{"data-slot":"table-row",className:(0,r.cn)("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",e),...a})}function l({className:e,...a}){return(0,t.jsx)("th",{"data-slot":"table-head",className:(0,r.cn)("text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...a})}function s({className:e,...a}){return(0,t.jsx)("td",{"data-slot":"table-cell",className:(0,r.cn)("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...a})}e.s(["Table",()=>a,"TableBody",()=>n,"TableCell",()=>s,"TableHead",()=>l,"TableHeader",()=>o,"TableRow",()=>i])},20682,e=>{"use strict";var t=e.i(71645);let r=0,a=new Map,o=e=>{if(a.has(e))return;let t=setTimeout(()=>{a.delete(e),l({type:"REMOVE_TOAST",toastId:e})},1e6);a.set(e,t)},n=[],i={toasts:[]};function l(e){i=((e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,1)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(e=>e.id===t.toast.id?{...e,...t.toast}:e)};case"DISMISS_TOAST":{let{toastId:r}=t;return r?o(r):e.toasts.forEach(e=>{o(e.id)}),{...e,toasts:e.toasts.map(e=>e.id===r||void 0===r?{...e,open:!1}:e)}}case"REMOVE_TOAST":if(void 0===t.toastId)return{...e,toasts:[]};return{...e,toasts:e.toasts.filter(e=>e.id!==t.toastId)}}})(i,e),n.forEach(e=>{e(i)})}function s({...e}){let t=(r=(r+1)%Number.MAX_SAFE_INTEGER).toString(),a=()=>l({type:"DISMISS_TOAST",toastId:t});return l({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:e=>{e||a()}}}),{id:t,dismiss:a,update:e=>l({type:"UPDATE_TOAST",toast:{...e,id:t}})}}function c(){let[e,r]=t.useState(i);return t.useEffect(()=>(n.push(r),()=>{leLine truncated
You can add a description to the \`${h}\` by passing a \`${C}\` component as a child, which also benefits sighted users by adding visible context to the dialog.
Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${h}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component.
For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return r.useEffect(()=>{document.getElementById(e.current?.getAttribute("aria-describedby"))||console.warn(t)},[t,e]),null},E=e.i(47163),A=e.i(67881);function N({...e}){return(0,t.jsx)(f,{"data-slot":"alert-dialog",...e})}function k({...e}){return(0,t.jsx)(p,{"data-slot":"alert-dialog-trigger",...e})}function P({...e}){return(0,t.jsx)(v,{"data-slot":"alert-dialog-portal",...e})}function I({className:e,...r}){return(0,t.jsx)(m,{"data-slot":"alert-dialog-overlay",className:(0,E.cn)("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...r})}function L({className:e,...r}){return(0,t.jsxs)(P,{children:[(0,t.jsx)(I,{}),(0,t.jsx)(x,{"data-slot":"alert-dialog-content",className:(0,E.cn)("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...r})]})}function _({className:e,...r}){return(0,t.jsx)("div",{"data-slot":"alert-dialog-header",className:(0,E.cn)("flex flex-col gap-2 text-center sm:text-left",e),...r})}function H({className:e,...r}){return(0,t.jsx)("div",{"data-slot":"alert-dialog-footer",className:(0,E.cn)("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...r})}function M({className:e,...r}){return(0,t.jsx)(y,{"data-slot":"alert-dialog-title",className:(0,E.cn)("text-lg font-semibold",e),...r})}function O({className:e,...r}){return(0,t.jsx)(S,{"data-slot":"alert-dialog-description",className:(0,E.cn)("text-muted-foreground text-sm",e),...r})}function F({className:e,...r}){return(0,t.jsx)(T,{className:(0,E.cn)((0,A.buttonVariants)(),e),...r})}function z({className:e,...r}){return(0,t.jsx)(R,{className:(0,E.cn)((0,A.buttonVariants)({variant:"outline"}),e),...r})}e.s(["AlertDialog",()=>N,"AlertDialogAction",()=>F,"AlertDialogCancel",()=>z,"AlertDialogContent",()=>L,"AlertDialogDescription",()=>O,"AlertDialogFooter",()=>H,"AlertDialogHeader",()=>_,"AlertDialogTitle",()=>M,"AlertDialogTrigger",()=>k],30009)},48256,e=>{"use strict";let t=(0,e.i(75254).default)("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);e.s(["Globe",()=>t],48256)},67240,e=>{"use strict";let t=(0,e.i(75254).default)("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);e.s(["RotateCcw",()=>t],67240)},74886,e=>{"use strict";let t=(0,e.i(75254).default)("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);e.s(["Copy",()=>t],74886)},69074,e=>{"use strict";let t=(0,e.i(75254).default)("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);e.s(["Upload",()=>t],69074)},42727,e=>{"use strict";var t=e.i(71645),r=e.i(81140),a=e.i(75830),o=e.i(20783),n=e.i(30030),i=e.i(10772),l=e.i(48425),s=e.i(30207),c=e.i(69340),d=e.i(86318),u=e.i(43476),f="rovingFocusGroup.onEntryFocus",p={bubbles:!1,cancelable:!0},v="RovingFocusGroup",[m,h,g]=(0,a.createCollection)(v),[b,x]=(0,n.createContextScope)(v,[g]),[w,y]=b(v),C=t.forwardRef((e,t)=>(0,u.jsx)(m.Provider,{scope:e.__scopeRovingFocusGroup,children:(0,u.jsx)(m.Slot,{scope:e.__scopeRovingFocusGroup,children:(0,u.jsx)(S,{...e,ref:t})})}));C.displayName=v;var S=t.forwardRef((e,a)=>{let{__scopeRovingFocusGroup:n,orientation:i,loop:v=!1,dir:m,currentTabStopId:g,defaultCurrentTabStopId:b,onCurrentTabStopIdChange:x,onEntryFocus:y,preventScrollOnEntryFocus:C=!1,...S}=e,T=t.useRef(null),j=(0,o.useComposedRefs)(a,T),R=(0,d.useDirection)(m),[E=null,A]=(0,c.useControllableState)({prop:g,defaultProp:b,onChange:x}),[N,k]=t.useState(!1),P=(0,s.useCallbackRef)(y),I=h(n),L=t.useRef(!1),[_,H]=t.useState(0);return t.useEffect(()=>{let e=T.current;if(e)return e.addEventListener(f,P),()=>e.removeEventListener(f,P)},[P]),(0,u.jsx)(w,{scope:n,orientation:i,dir:R,loop:v,currentTabStopId:E,onItemFocus:t.useCallback(e=>A(e),[A]),onItemShiftTab:t.useCallback(()=>k(!0),[]),onFocusableItemAdd:t.useCallback(()=>H(e=>e+1),[]),onFocusableItemRemove:t.useCallback(()=>H(e=>e-1),[]),children:(0,u.jsx)(l.Primitive.div,{tabIndex:N||0===_?-1:0,"data-orientation":i,...S,ref:j,style:{outline:"none",...e.style},onMouseDown:(0,r.composeEventHandlers)(e.onMouseDown,()=>{L.current=!0}),onFocus:(0,r.composeEventHandlers)(e.onFocus,e=>{let t=!L.current;if(e.target===e.currentTarget&&t&&!N){let t=new CustomEvent Line truncated
@@ -0,0 +1 @@
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,91915,(e,r,t)=>{"use strict";function n(e,r={}){if(r.onlyHashChange)return void e();let t=document.documentElement;if("smooth"!==t.dataset.scrollBehavior)return void e();let a=t.style.scrollBehavior;t.style.scrollBehavior="auto",r.dontForceLayout||t.getClientRects(),e(),t.style.scrollBehavior=a}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"disableSmoothScrollDuringRouteTransition",{enumerable:!0,get:function(){return n}}),e.r(33525)},68017,(e,r,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"HTTPAccessFallbackBoundary",{enumerable:!0,get:function(){return i}});let n=e.r(90809),a=e.r(43476),o=n._(e.r(71645)),c=e.r(90373),u=e.r(54394);e.r(33525);let l=e.r(8372);class s extends o.default.Component{constructor(e){super(e),this.state={triggeredStatus:void 0,previousPathname:e.pathname}}componentDidCatch(){}static getDerivedStateFromError(e){if((0,u.isHTTPAccessFallbackError)(e))return{triggeredStatus:(0,u.getAccessFallbackHTTPStatus)(e)};throw e}static getDerivedStateFromProps(e,r){return e.pathname!==r.previousPathname&&r.triggeredStatus?{triggeredStatus:void 0,previousPathname:e.pathname}:{triggeredStatus:r.triggeredStatus,previousPathname:e.pathname}}render(){let{notFound:e,forbidden:r,unauthorized:t,children:n}=this.props,{triggeredStatus:o}=this.state,c={[u.HTTPAccessErrorStatus.NOT_FOUND]:e,[u.HTTPAccessErrorStatus.FORBIDDEN]:r,[u.HTTPAccessErrorStatus.UNAUTHORIZED]:t};if(o){let l=o===u.HTTPAccessErrorStatus.NOT_FOUND&&e,s=o===u.HTTPAccessErrorStatus.FORBIDDEN&&r,i=o===u.HTTPAccessErrorStatus.UNAUTHORIZED&&t;return l||s||i?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("meta",{name:"robots",content:"noindex"}),!1,c[o]]}):n}return n}}function i({notFound:e,forbidden:r,unauthorized:t,children:n}){let u=(0,c.useUntrackedPathname)(),i=(0,o.useContext)(l.MissingSlotContext);return e||r||t?(0,a.jsx)(s,{pathname:u,notFound:e,forbidden:r,unauthorized:t,missingSlots:i,children:n}):(0,a.jsx)(a.Fragment,{children:n})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),r.exports=t.default)},91798,(e,r,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"useRouterBFCache",{enumerable:!0,get:function(){return a}});let n=e.r(71645);function a(e,r){let[t,a]=(0,n.useState)(()=>({tree:e,stateKey:r,next:null}));if(t.tree===e)return t;let o={tree:e,stateKey:r,next:null},c=1,u=t,l=o;for(;null!==u&&c<1;){if(u.stateKey===r){l.next=u.next;break}{c++;let e={tree:u.tree,stateKey:u.stateKey,next:null};l.next=e,l=e}u=u.next}return a(o),o}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),r.exports=t.default)},39756,(e,r,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return T}});let n=e.r(55682),a=e.r(90809),o=e.r(43476),c=e.r(88540),u=a._(e.r(71645)),l=n._(e.r(74080)),s=e.r(8372),i=e.r(87288),d=e.r(1244),f=e.r(72383),p=e.r(56019),h=e.r(91915),m=e.r(58442),g=e.r(68017),y=e.r(70725),b=e.r(84356),P=e.r(41538),_=e.r(91798);e.r(74180);let v=e.r(61994),O=e.r(33906),S=l.default.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,E=["bottom","height","left","right","top","width","x","y"];function R(e,r){let t=e.getBoundingClientRect();return t.top>=0&&t.top<=r}class j extends u.default.Component{componentDidMount(){this.handlePotentialScroll()}componentDidUpdate(){this.props.focusAndScrollRef.apply&&this.handlePotentialScroll()}render(){return this.props.children}constructor(...e){super(...e),this.handlePotentialScroll=()=>{let{focusAndScrollRef:e,segmentPath:r}=this.props;if(e.apply){if(0!==e.segmentPaths.length&&!e.segmentPaths.some(e=>r.every((r,t)=>(0,p.matchSegment)(r,e[t]))))return;let t=null,n=e.hashFragment;if(n&&(t="top"===n?document.body:document.getElementById(n)??document.getElementsByName(n)[0]),t||(t="undefined"==typeof window?null:(0,S.findDOMNode)(this)),!(t instanceof Element))return;for(;!(t instanceof HTMLElement)||function(e){if(["sticky","fixed"].includes(getComputedStyle(e).position))return!0;let r=e.getBoundingClientRect();return E.every(e=>0===r[e])}(t);){if(null===t.nextElementSibling)return;t=t.nextElementSibling}e.apply=!1,e.hashFragment=null,e.segmentPaths=[],(0,h.disableSmoothScrollDuringRouteTransition)(()=>{if(n)return void t.scrollIntoView();let e=document.documentElement,r=e.clientHeight;!R(t,r)&&(e.scrollTop=0,R(t,r)||t.scrollIntoView())},{dontForceLayout:!0,onlyHashChange:e.onlyHashChange}),e.onlyHashChange=!1,t.focus()}}}}function w({segmentPath:e,children:r}){let t=(0,u.useContext)(s.GlobalLayoutRouterContext);if(!t)thLine truncated
@@ -0,0 +1,4 @@
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,12718,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"InvariantError",{enumerable:!0,get:function(){return n}});class n extends Error{constructor(e,t){super(`Invariant: ${e.endsWith(".")?e:e+"."} This is a bug in Next.js.`,t),this.name="InvariantError"}}},32061,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n={BailoutToCSRError:function(){return u},isBailoutToCSRError:function(){return i}};for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]});let a="BAILOUT_TO_CLIENT_SIDE_RENDERING";class u extends Error{constructor(e){super(`Bail out to client-side rendering: ${e}`),this.reason=e,this.digest=a}}function i(e){return"object"==typeof e&&null!==e&&"digest"in e&&e.digest===a}},54394,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n={HTTPAccessErrorStatus:function(){return a},HTTP_ERROR_FALLBACK_ERROR_CODE:function(){return i},getAccessFallbackErrorTypeByStatus:function(){return l},getAccessFallbackHTTPStatus:function(){return s},isHTTPAccessFallbackError:function(){return c}};for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]});let a={NOT_FOUND:404,FORBIDDEN:403,UNAUTHORIZED:401},u=new Set(Object.values(a)),i="NEXT_HTTP_ERROR_FALLBACK";function c(e){if("object"!=typeof e||null===e||!("digest"in e)||"string"!=typeof e.digest)return!1;let[t,r]=e.digest.split(";");return t===i&&u.has(Number(r))}function s(e){return Number(e.digest.split(";")[1])}function l(e){switch(e){case 401:return"unauthorized";case 403:return"forbidden";case 404:return"not-found";default:return}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},76963,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"RedirectStatusCode",{enumerable:!0,get:function(){return o}});var n,o=((n={})[n.SeeOther=303]="SeeOther",n[n.TemporaryRedirect=307]="TemporaryRedirect",n[n.PermanentRedirect=308]="PermanentRedirect",n);("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},68391,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n,o={REDIRECT_ERROR_CODE:function(){return i},RedirectType:function(){return c},isRedirectError:function(){return s}};for(var a in o)Object.defineProperty(r,a,{enumerable:!0,get:o[a]});let u=e.r(76963),i="NEXT_REDIRECT";var c=((n={}).push="push",n.replace="replace",n);function s(e){if("object"!=typeof e||null===e||!("digest"in e)||"string"!=typeof e.digest)return!1;let t=e.digest.split(";"),[r,n]=t,o=t.slice(2,-2).join(";"),a=Number(t.at(-2));return r===i&&("replace"===n||"push"===n)&&"string"==typeof o&&!isNaN(a)&&a in u.RedirectStatusCode}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},65713,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"isNextRouterError",{enumerable:!0,get:function(){return a}});let n=e.r(54394),o=e.r(68391);function a(e){return(0,o.isRedirectError)(e)||(0,n.isHTTPAccessFallbackError)(e)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},61994,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n={NavigationPromisesContext:function(){return s},PathParamsContext:function(){return c},PathnameContext:function(){return i},SearchParamsContext:function(){return u},createDevToolsInstrumentedPromise:function(){return l}};for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]});let a=e.r(71645),u=(0,a.createContext)(null),i=(0,a.createContext)(null),c=(0,a.createContext)(null),s=(0,a.createContext)(null);function l(e,t){let r=Promise.resolve(t);return r.status="fulfilled",r.value=t,r.displayName=`${e} (SSR)`,r}},45955,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"workUnitAsyncStorageInstance",{enumerable:!0,get:function(){return n}});let n=(0,e.r(90317).createAsyncLocalStorage)()},21768,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n={ACTION_HEADER:function(){return u},FLIGHT_HEADERS:function(){return _},NEXT_ACTION_NOT_FOUND_HEADER:function(){return R},NEXT_DID_POSTPONE_HEADER:function(){return b},NEXT_HMR_REFRESH_HASH_COOKIE:function(){return d},NEXT_HMR_REFRESH_HEADER:function(){return l},NEXT_HTML_REQUELine truncated
${t}`))}function $(){let e=new AbortController;return e.abort(Object.defineProperty(new y.BailoutToCSRError("Render in Browser"),"__NEXT_ERROR_CODE",{value:"E721",enumerable:!1,configurable:!0})),e.signal}function X(e){switch(e.type){case"prerender":case"prerender-runtime":let t=new AbortController;if(e.cacheSignal)e.cacheSignal.inputReady().then(()=>{t.abort()});else{let r=(0,l.getRuntimeStagePromise)(e);r?r.then(()=>(0,_.scheduleOnNextTick)(()=>t.abort())):(0,_.scheduleOnNextTick)(()=>t.abort())}return t.signal;case"prerender-client":case"prerender-ppr":case"prerender-legacy":case"request":case"cache":case"private-cache":case"unstable-cache":return}}function B(e,t){let r=t.dynamicTracking;r&&r.dynamicAccesses.push({stack:r.isDebugDynamicAccesses?Error().stack:void 0,expression:e})}function F(e){let t=d.workAsyncStorage.getStore(),r=l.workUnitAsyncStorage.getStore();if(t&&r)switch(r.type){case"prerender-client":case"prerender":{let n=r.fallbackRouteParams;n&&n.size>0&&i.default.use((0,f.makeHangingPromise)(r.renderSignal,t.route,e));break}case"prerender-ppr":{let n=r.fallbackRouteParams;if(n&&n.size>0)return x(t.route,e,r.dynamicTracking);break}case"prerender-runtime":throw Object.defineProperty(new m.InvariantError(`\`${e}\` was called during a runtime prerender. Next.js should be preventing ${e} from being included in server components statically, but did not in this case.`),"__NEXT_ERROR_CODE",{value:"E771",enumerable:!1,configurable:!0});case"cache":case"private-cache":throw Object.defineProperty(new m.InvariantError(`\`${e}\` was called inside a cache scope. Next.js should be preventing ${e} from being included in server components statically, but did not in this case.`),"__NEXT_ERROR_CODE",{value:"E745",enumerable:!1,configurable:!0})}}function G(e){let t=d.workAsyncStorage.getStore(),r=l.workUnitAsyncStorage.getStore();if(t)switch(!r&&(0,l.throwForMissingRequestStore)(e),r.type){case"prerender-client":i.default.use((0,f.makeHangingPromise)(r.renderSignal,t.route,e));break;case"prerender-legacy":case"prerender-ppr":if(t.forceStatic)return;throw Object.defineProperty(new y.BailoutToCSRError(e),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0});case"prerender":case"prerender-runtime":throw Object.defineProperty(new m.InvariantError(`\`${e}\` was called from a Server Component. Next.js should be preventing ${e} from being included in server components statically, but did not in this case.`),"__NEXT_ERROR_CODE",{value:"E795",enumerable:!1,configurable:!0});case"cache":case"unstable-cache":case"private-cache":throw Object.defineProperty(new m.InvariantError(`\`${e}\` was called inside a cache scope. Next.js should be preventing ${e} from being included in server components statically, but did not in this case.`),"__NEXT_ERROR_CODE",{value:"E745",enumerable:!1,configurable:!0});case"request":return}}let W=/\n\s+at Suspense \(<anonymous>\)/,q=RegExp(`\\n\\s+at Suspense \\(<anonymous>\\)(?:(?!\\n\\s+at (?:body|div|main|section|article|aside|header|footer|nav|form|p|span|h1|h2|h3|h4|h5|h6) \\(<anonymous>\\))[\\s\\S])*?\\n\\s+at ${p.ROOT_LAYOUT_BOUNDARY_NAME} \\([^\\n]*\\)`),z=RegExp(`\\n\\s+at ${p.METADATA_BOUNDARY_NAME}[\\n\\s]`),Y=RegExp(`\\n\\s+at ${p.VIEWPORT_BOUNDARY_NAME}[\\n\\s]`),K=RegExp(`\\n\\s+at ${p.OUTLET_BOUNDARY_NAME}[\\n\\s]`);function V(e,t,r,n){if(!K.test(t)){if(z.test(t)){r.hasDynamicMetadata=!0;return}if(Y.test(t)){r.hasDynamicViewport=!0;return}if(q.test(t)){r.hasAllowedDynamic=!0,r.hasSuspenseAboveBody=!0;return}else if(W.test(t)){r.hasAllowedDynamic=!0;return}else{var o,a;let u;if(n.syncDynamicErrorWithStack)return void r.dynamicErrors.push(n.syncDynamicErrorWithStack);let i=(o=`Route "${e.route}": Uncached data was accessed outside of <Suspense>. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route`,a=t,(u=Object.defineProperty(Error(o),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0})).stack=u.name+": "+o+a,u);return void r.dynamicErrors.push(i)}}}var Q=((o={})[o.Full=0]="Full",o[o.Empty=1]="Empty",o[o.Errored=2]="Errored",o);function J(e,t){console.error(t),e.dev||(e.hasReadableErrorStacks?console.error(`To get a more detailed stack trace and pinpoint the issue, start the app in development mode by running \`next dev\`, then open "${e.route}" in your browser to investigate the error.`):console.error(`To get a more detailed stack trace and pinpoint the issue, try one of the following:
- Start the app in development mode by running \`next dev\`, then open "${e.route}" in your browser to investigate the error.
- Rerun the production build with \`next build --debug-prerender\` to generate better stack traces.`))}function Z(e,t,r,n){if(n.syncDynamicErrorWithStack)throw J(e,n.syncDynamicErrorWithStack),new s.StaticGenBailoutError;if(0!==t){if(r.hasSuspenseAboveBody)return;let n=r.dynamicErrors;if(n.length>0){for(let t=0;t<n.length;t++)J(e,n[t]);throw new s.StaticGenBailoutError}if(r.hasDynamicViewport)throw console.error(`Route "${e.route}" has a \`generateViewport\` that depends on Request data (\`cookies()\`, etc...) or uncached external data (\`fetch(...)\`, etc...) without explicitly allowing fully dynamic rendering. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`),new s.StaticGenBailoutError;if(1===t)throw console.error(`Route "${e.route}" did not produce a static shell and Next.js was unable to determine a reason. This is a bug in Next.js.`),new s.StaticGenBailoutError}else if(!1===r.hasAllowedDynamic&&r.hasDynamicMetadata)throw console.error(`Route "${e.route}" has a \`generateMetadata\` that depends on Request data (\`cookies()\`, etc...) or uncached external data (\`fetch(...)\`, etc...) when the rest of the route does not. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`),new s.StaticGenBailoutError}function ee(e,t){return e.runtimeStagePromise?e.runtimeStagePromise.then(()=>t):t}},91414,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"unstable_rethrow",{enumerable:!0,get:function(){return function e(t){if((0,u.isNextRouterError)(t)||(0,a.isBailoutToCSRError)(t)||(0,c.isDynamicServerError)(t)||(0,i.isDynamicPostpone)(t)||(0,o.isPostpone)(t)||(0,n.isHangingPromiseRejectionError)(t)||(0,i.isPrerenderInterruptedError)(t))throw t;t instanceof Error&&"cause"in t&&e(t.cause)}}});let n=e.r(63138),o=e.r(67287),a=e.r(32061),u=e.r(65713),i=e.r(67673),c=e.r(76353);("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},90508,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"unstable_rethrow",{enumerable:!0,get:function(){return n}});let n="undefined"==typeof window?e.r(91414).unstable_rethrow:e.r(15507).unstable_rethrow;("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},92805,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n={ReadonlyURLSearchParams:function(){return a.ReadonlyURLSearchParams},RedirectType:function(){return i.RedirectType},forbidden:function(){return s.forbidden},notFound:function(){return c.notFound},permanentRedirect:function(){return u.permanentRedirect},redirect:function(){return u.redirect},unauthorized:function(){return l.unauthorized},unstable_isUnrecognizedActionError:function(){return f},unstable_rethrow:function(){return d.unstable_rethrow}};for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]});let a=e.r(3680),u=e.r(24063),i=e.r(68391),c=e.r(22783),s=e.r(79854),l=e.r(22683),d=e.r(90508);function f(){throw Object.defineProperty(Error("`unstable_isUnrecognizedActionError` can only be used on the client."),"__NEXT_ERROR_CODE",{value:"E776",enumerable:!1,configurable:!0})}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},76562,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n={ReadonlyURLSearchParams:function(){return f.ReadonlyURLSearchParams},RedirectType:function(){return f.RedirectType},ServerInsertedHTMLContext:function(){return l.ServerInsertedHTMLContext},forbidden:function(){return f.forbidden},notFound:function(){return f.notFound},permanentRedirect:function(){return f.permanentRedirect},redirect:function(){return f.redirect},unauthorized:function(){return f.unauthorized},unstable_isUnrecognizedActionError:function(){return d.unstable_isUnrecognizedActionError},unstable_rethrow:function(){return f.unstable_rethrow},useParams:function(){return h},usePathname:function(){return m},useRouter:function(){return b},useSearchParams:function(){return y},useSelectedLayoutSegment:function(){return g},useSelectedLayoutSegments:function(){return E},useServerInsertedHTML:function(){return l.useServerInsertedHTML}};for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]});let a=e.r(90809)._(e.r(71645)),u=e.r(8372),i=e.r(61994),c=e.r(13258),s=e.r(3680),l=e.r(13957),d=e.r(92838),f=e.r(92805),p="undefined"==typeof window?e.r(67673).useDynamicRouteParams:void 0,_="undefined"==typeof window?e.r(67673).useDynamicSearchParams:void 0;function y(){_?.("useSearchParams()");let e=(0,Line truncated
@@ -0,0 +1 @@
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,74965,e=>{"use strict";var t=e.i(43476),s=e.i(71645),a=e.i(18566),r=e.i(54858),l=e.i(54458),i=e.i(67881),n=e.i(23750),d=e.i(94179),o=e.i(70065),c=e.i(47627),m=e.i(62870),x=e.i(30030),u=e.i(75830),h=e.i(20783),g=e.i(81140),p=e.i(69340),j=e.i(48425),f=e.i(34620),b=e.i(96626),v=e.i(10772),N="Collapsible",[w,y]=(0,x.createContextScope)(N),[_,C]=w(N),k=s.forwardRef((e,a)=>{let{__scopeCollapsible:r,open:l,defaultOpen:i,disabled:n,onOpenChange:d,...o}=e,[c=!1,m]=(0,p.useControllableState)({prop:l,defaultProp:i,onChange:d});return(0,t.jsx)(_,{scope:r,disabled:n,contentId:(0,v.useId)(),open:c,onOpenToggle:s.useCallback(()=>m(e=>!e),[m]),children:(0,t.jsx)(j.Primitive.div,{"data-state":F(c),"data-disabled":n?"":void 0,...o,ref:a})})});k.displayName=N;var T="CollapsibleTrigger",A=s.forwardRef((e,s)=>{let{__scopeCollapsible:a,...r}=e,l=C(T,a);return(0,t.jsx)(j.Primitive.button,{type:"button","aria-controls":l.contentId,"aria-expanded":l.open||!1,"data-state":F(l.open),"data-disabled":l.disabled?"":void 0,disabled:l.disabled,...r,ref:s,onClick:(0,g.composeEventHandlers)(e.onClick,l.onOpenToggle)})});A.displayName=T;var D="CollapsibleContent",S=s.forwardRef((e,s)=>{let{forceMount:a,...r}=e,l=C(D,e.__scopeCollapsible);return(0,t.jsx)(b.Presence,{present:a||l.open,children:({present:e})=>(0,t.jsx)(R,{...r,ref:s,present:e})})});S.displayName=D;var R=s.forwardRef((e,a)=>{let{__scopeCollapsible:r,present:l,children:i,...n}=e,d=C(D,r),[o,c]=s.useState(l),m=s.useRef(null),x=(0,h.useComposedRefs)(a,m),u=s.useRef(0),g=u.current,p=s.useRef(0),b=p.current,v=d.open||o,N=s.useRef(v),w=s.useRef(void 0);return s.useEffect(()=>{let e=requestAnimationFrame(()=>N.current=!1);return()=>cancelAnimationFrame(e)},[]),(0,f.useLayoutEffect)(()=>{let e=m.current;if(e){w.current=w.current||{transitionDuration:e.style.transitionDuration,animationName:e.style.animationName},e.style.transitionDuration="0s",e.style.animationName="none";let t=e.getBoundingClientRect();u.current=t.height,p.current=t.width,N.current||(e.style.transitionDuration=w.current.transitionDuration,e.style.animationName=w.current.animationName),c(l)}},[d.open,l]),(0,t.jsx)(j.Primitive.div,{"data-state":F(d.open),"data-disabled":d.disabled?"":void 0,id:d.contentId,hidden:!v,...n,ref:x,style:{"--radix-collapsible-content-height":g?`${g}px`:void 0,"--radix-collapsible-content-width":b?`${b}px`:void 0,...e.style},children:v&&i})});function F(e){return e?"open":"closed"}var O=e.i(86318),L="Accordion",$=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[I,P,B]=(0,u.createCollection)(L),[E,J]=(0,x.createContextScope)(L,[B,y]),U=y(),H=s.default.forwardRef((e,s)=>{let{type:a,...r}=e;return(0,t.jsx)(I.Provider,{scope:e.__scopeAccordion,children:"multiple"===a?(0,t.jsx)(G,{...r,ref:s}):(0,t.jsx)(W,{...r,ref:s})})});H.displayName=L;var[z,q]=E(L),[M,V]=E(L,{collapsible:!1}),W=s.default.forwardRef((e,a)=>{let{value:r,defaultValue:l,onValueChange:i=()=>{},collapsible:n=!1,...d}=e,[o,c]=(0,p.useControllableState)({prop:r,defaultProp:l,onChange:i});return(0,t.jsx)(z,{scope:e.__scopeAccordion,value:o?[o]:[],onItemOpen:c,onItemClose:s.default.useCallback(()=>n&&c(""),[n,c]),children:(0,t.jsx)(M,{scope:e.__scopeAccordion,collapsible:n,children:(0,t.jsx)(X,{...d,ref:a})})})}),G=s.default.forwardRef((e,a)=>{let{value:r,defaultValue:l,onValueChange:i=()=>{},...n}=e,[d=[],o]=(0,p.useControllableState)({prop:r,defaultProp:l,onChange:i}),c=s.default.useCallback(e=>o((t=[])=>[...t,e]),[o]),m=s.default.useCallback(e=>o((t=[])=>t.filter(t=>t!==e)),[o]);return(0,t.jsx)(z,{scope:e.__scopeAccordion,value:d,onItemOpen:c,onItemClose:m,children:(0,t.jsx)(M,{scope:e.__scopeAccordion,collapsible:!0,children:(0,t.jsx)(X,{...n,ref:a})})})}),[Y,K]=E(L),X=s.default.forwardRef((e,a)=>{let{__scopeAccordion:r,disabled:l,dir:i,orientation:n="vertical",...d}=e,o=s.default.useRef(null),c=(0,h.useComposedRefs)(o,a),m=P(r),x="ltr"===(0,O.useDirection)(i),u=(0,g.composeEventHandlers)(e.onKeyDown,e=>{if(!$.includes(e.key))return;let t=e.target,s=m().filter(e=>!e.ref.current?.disabled),a=s.findIndex(e=>e.ref.current===t),r=s.length;if(-1===a)return;e.preventDefault();let l=a,i=r-1,d=()=>{(l=a+1)>i&&(l=0)},o=()=>{(l=a-1)<0&&(l=i)};switch(e.key){case"Home":l=0;break;case"End":l=i;break;case"ArrowRight":"horizontal"===n&&(x?d():o());break;case"ArrowDown":"vertical"===n&&d();break;case"ArrowLeft":"horizontal"===n&&(x?o():d());break;case"ArrowUp":"vertical"===n&&o()}let c=l%r;s[c].ref.current?.focus()});return(0,t.jsx)(Y,{scope:r,disabled:l,direction:i,orientation:n,children:(0,t.jsx)(I.Slot,{scope:r,children:(0,t.jsx)(j.Primitive.div,{...d,"data-orientation":n,ref:c,onKeyDown:l?void 0:u})})})}),Z="AccordionItem",[Q,ee]=E(Z),et=s.default.forwardRef((e,s)=>{let{__scopeAccordion:a,value:r,...l}=e,i=K(Z,a),n=q(Z,a),d=U(a),o=(0,v.useId)(),c=r&&n.value.includes(r)||!1,m=i.disabled||e.disabled;return(0,t.jsx)(Q,{scopeLine truncated
@@ -1,7 +1,7 @@
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,69638,e=>{"use strict";let t=(0,e.i(75254).default)("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);e.s(["CheckCircle",()=>t],69638)},73884,e=>{"use strict";let t=(0,e.i(75254).default)("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);e.s(["XCircle",()=>t],73884)},16715,e=>{"use strict";let t=(0,e.i(75254).default)("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);e.s(["RefreshCw",()=>t],16715)},94179,e=>{"use strict";var t=e.i(43476),a=e.i(91918),s=e.i(25913),l=e.i(47163);let r=(0,s.cva)("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function i({className:e,variant:s,asChild:i=!1,...n}){let o=i?a.Slot:"span";return(0,t.jsx)(o,{"data-slot":"badge",className:(0,l.cn)(r({variant:s}),e),...n})}e.s(["Badge",()=>i])},20682,e=>{"use strict";var t=e.i(71645);let a=0,s=new Map,l=e=>{if(s.has(e))return;let t=setTimeout(()=>{s.delete(e),n({type:"REMOVE_TOAST",toastId:e})},1e6);s.set(e,t)},r=[],i={toasts:[]};function n(e){i=((e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,1)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(e=>e.id===t.toast.id?{...e,...t.toast}:e)};case"DISMISS_TOAST":{let{toastId:a}=t;return a?l(a):e.toasts.forEach(e=>{l(e.id)}),{...e,toasts:e.toasts.map(e=>e.id===a||void 0===a?{...e,open:!1}:e)}}case"REMOVE_TOAST":if(void 0===t.toastId)return{...e,toasts:[]};return{...e,toasts:e.toasts.filter(e=>e.id!==t.toastId)}}})(i,e),r.forEach(e=>{e(i)})}function o({...e}){let t=(a=(a+1)%Number.MAX_SAFE_INTEGER).toString(),s=()=>n({type:"DISMISS_TOAST",toastId:t});return n({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:e=>{e||s()}}}),{id:t,dismiss:s,update:e=>n({type:"UPDATE_TOAST",toast:{...e,id:t}})}}function c(){let[e,a]=t.useState(i);return t.useEffect(()=>(r.push(a),()=>{let e=r.indexOf(a);e>-1&&r.splice(e,1)}),[e]),{...e,toast:o,dismiss:e=>n({type:"DISMISS_TOAST",toastId:e})}}e.s(["useToast",()=>c])},47627,e=>{"use strict";var t=e.i(43476),a=e.i(47163);function s({className:e,...s}){return(0,t.jsx)("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:(0,t.jsx)("table",{"data-slot":"table",className:(0,a.cn)("w-full caption-bottom text-sm",e),...s})})}function l({className:e,...s}){return(0,t.jsx)("thead",{"data-slot":"table-header",className:(0,a.cn)("[&_tr]:border-b",e),...s})}function r({className:e,...s}){return(0,t.jsx)("tbody",{"data-slot":"table-body",className:(0,a.cn)("[&_tr:last-child]:border-0",e),...s})}function i({className:e,...s}){return(0,t.jsx)("tr",{"data-slot":"table-row",className:(0,a.cn)("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",e),...s})}function n({className:e,...s}){return(0,t.jsx)("th",{"data-slot":"table-head",className:(0,a.cn)("text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...s})}function o({className:e,...s}){return(0,t.jsx)("td",{"data-slot":"table-cell",className:(0,a.cn)("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...s})}e.s(["Table",()=>s,"TableBody",()=>r,"TableCell",()=>o,"TableHead",()=>n,"TableHeader",()=>l,"TableRow",()=>i])},30009,e=>{"use strict";var t=e.i(43476),a=e.i(71645),s=e.i(30030),l=e.i(20783),r=e.i(26999),i=e.i(81140),n=e.i(91918),o="AlertDialog",[c,d]=(0,s.createContextScope)(o,[r.createDialogScope]),u=(0,r.createDialogScope)(),h=e=>{let{__scopeAlertDialog:a,...s}=e,l=u(a);return(0,t.jsx)(r.Root,{...l,...s,modal:!0})};h.displayName=o;var x=a.forwardRef((e,a)=>{let{__scopeAlertDialog:s,...l}=e,i=u(s);return(0,t.jsx)(r.Trigger,{...i,...l,ref:a})});x.dispLine truncated
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,53339,e=>{"use strict";let t=(0,e.i(75254).default)("Music",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]);e.s(["Music",()=>t],53339)},69638,e=>{"use strict";let t=(0,e.i(75254).default)("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);e.s(["CheckCircle",()=>t],69638)},73884,e=>{"use strict";let t=(0,e.i(75254).default)("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);e.s(["XCircle",()=>t],73884)},16715,e=>{"use strict";let t=(0,e.i(75254).default)("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);e.s(["RefreshCw",()=>t],16715)},94179,e=>{"use strict";var t=e.i(43476),a=e.i(91918),s=e.i(25913),l=e.i(47163);let r=(0,s.cva)("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function i({className:e,variant:s,asChild:i=!1,...n}){let o=i?a.Slot:"span";return(0,t.jsx)(o,{"data-slot":"badge",className:(0,l.cn)(r({variant:s}),e),...n})}e.s(["Badge",()=>i])},20682,e=>{"use strict";var t=e.i(71645);let a=0,s=new Map,l=e=>{if(s.has(e))return;let t=setTimeout(()=>{s.delete(e),n({type:"REMOVE_TOAST",toastId:e})},1e6);s.set(e,t)},r=[],i={toasts:[]};function n(e){i=((e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,1)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(e=>e.id===t.toast.id?{...e,...t.toast}:e)};case"DISMISS_TOAST":{let{toastId:a}=t;return a?l(a):e.toasts.forEach(e=>{l(e.id)}),{...e,toasts:e.toasts.map(e=>e.id===a||void 0===a?{...e,open:!1}:e)}}case"REMOVE_TOAST":if(void 0===t.toastId)return{...e,toasts:[]};return{...e,toasts:e.toasts.filter(e=>e.id!==t.toastId)}}})(i,e),r.forEach(e=>{e(i)})}function o({...e}){let t=(a=(a+1)%Number.MAX_SAFE_INTEGER).toString(),s=()=>n({type:"DISMISS_TOAST",toastId:t});return n({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:e=>{e||s()}}}),{id:t,dismiss:s,update:e=>n({type:"UPDATE_TOAST",toast:{...e,id:t}})}}function c(){let[e,a]=t.useState(i);return t.useEffect(()=>(r.push(a),()=>{let e=r.indexOf(a);e>-1&&r.splice(e,1)}),[e]),{...e,toast:o,dismiss:e=>n({type:"DISMISS_TOAST",toastId:e})}}e.s(["useToast",()=>c])},47627,e=>{"use strict";var t=e.i(43476),a=e.i(47163);function s({className:e,...s}){return(0,t.jsx)("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:(0,t.jsx)("table",{"data-slot":"table",className:(0,a.cn)("w-full caption-bottom text-sm",e),...s})})}function l({className:e,...s}){return(0,t.jsx)("thead",{"data-slot":"table-header",className:(0,a.cn)("[&_tr]:border-b",e),...s})}function r({className:e,...s}){return(0,t.jsx)("tbody",{"data-slot":"table-body",className:(0,a.cn)("[&_tr:last-child]:border-0",e),...s})}function i({className:e,...s}){return(0,t.jsx)("tr",{"data-slot":"table-row",className:(0,a.cn)("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",e),...s})}function n({className:e,...s}){return(0,t.jsx)("th",{"data-slot":"table-head",className:(0,a.cn)("text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...s})}function o({className:e,...s}){return(0,t.jsx)("td",{"data-slot":"table-cell",className:(0,a.cn)("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...s})}e.s(["Table",()=>s,"TableBody",()=>r,"TableCell",()=>o,"TableHead",()=>n,"TableHeader",()=>l,"TableRow",()=>i])},27612,e=>{"use strict";let t=(0,e.i(75254).default)("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:Line truncated
You can add a description to the \`${p}\` by passing a \`${T}\` component as a child, which also benefits sighted users by adding visible context to the dialog.
Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${p}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component.
For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return a.useEffect(()=>{document.getElementById(e.current?.getAttribute("aria-describedby"))||console.warn(t)},[t,e]),null},S=e.i(47163),_=e.i(67881);function k({...e}){return(0,t.jsx)(h,{"data-slot":"alert-dialog",...e})}function R({...e}){return(0,t.jsx)(x,{"data-slot":"alert-dialog-trigger",...e})}function O({...e}){return(0,t.jsx)(m,{"data-slot":"alert-dialog-portal",...e})}function M({className:e,...a}){return(0,t.jsx)(g,{"data-slot":"alert-dialog-overlay",className:(0,S.cn)("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...a})}function E({className:e,...a}){return(0,t.jsxs)(O,{children:[(0,t.jsx)(M,{}),(0,t.jsx)(j,{"data-slot":"alert-dialog-content",className:(0,S.cn)("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...a})]})}function B({className:e,...a}){return(0,t.jsx)("div",{"data-slot":"alert-dialog-header",className:(0,S.cn)("flex flex-col gap-2 text-center sm:text-left",e),...a})}function F({className:e,...a}){return(0,t.jsx)("div",{"data-slot":"alert-dialog-footer",className:(0,S.cn)("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...a})}function H({className:e,...a}){return(0,t.jsx)(y,{"data-slot":"alert-dialog-title",className:(0,S.cn)("text-lg font-semibold",e),...a})}function I({className:e,...a}){return(0,t.jsx)(C,{"data-slot":"alert-dialog-description",className:(0,S.cn)("text-muted-foreground text-sm",e),...a})}function z({className:e,...a}){return(0,t.jsx)(w,{className:(0,S.cn)((0,_.buttonVariants)(),e),...a})}function P({className:e,...a}){return(0,t.jsx)(A,{className:(0,S.cn)((0,_.buttonVariants)({variant:"outline"}),e),...a})}e.s(["AlertDialog",()=>k,"AlertDialogAction",()=>z,"AlertDialogCancel",()=>P,"AlertDialogContent",()=>E,"AlertDialogDescription",()=>I,"AlertDialogFooter",()=>F,"AlertDialogHeader",()=>B,"AlertDialogTitle",()=>H,"AlertDialogTrigger",()=>R],30009)},13314,e=>{"use strict";var t=e.i(43476),a=e.i(71645),s=e.i(54858),l=e.i(54458),r=e.i(67881),i=e.i(94179),n=e.i(47627),o=e.i(62870),c=e.i(30009),d=e.i(28231),u=e.i(16715),h=e.i(31278),x=e.i(27612),m=e.i(53339),g=e.i(69638),p=e.i(73884),f=e.i(75254);let b=(0,f.default)("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]),j=(0,f.default)("HardDrive",[["line",{x1:"22",x2:"2",y1:"12",y2:"12",key:"1y58io"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}],["line",{x1:"6",x2:"6.01",y1:"16",y2:"16",key:"sgf278"}],["line",{x1:"10",x2:"10.01",y1:"16",y2:"16",key:"1l4acy"}]]);var v=e.i(20682);let y=[{value:"all",label:"All Statuses"},{value:"awaiting_audio_selection",label:"Awaiting Selection"},{value:"pending",label:"Pending"},{value:"complete",label:"Complete"},{value:"failed",label:"Failed"}];function T(){let{toast:e}=(0,v.useToast)(),{showTestData:f}=(0,l.useAdminSettings)(),[T,C]=(0,a.useState)([]),[w,N]=(0,a.useState)(!0),[A,D]=(0,a.useState)("all"),[S,_]=(0,a.useState)(!1),[k,R]=(0,a.useState)(null),[O,M]=(0,a.useState)(!1),[E,B]=(0,a.useState)(!1),[F,H]=(0,a.useState)(!1),[I,z]=(0,a.useState)(null),[P,L]=(0,a.useState)(!1),V=(0,a.useCallback)(async()=>{try{N(!0);let e=await s.adminApi.listAudioSearches({limit:100,status_filter:"all"!==A?A:void 0,exclude_test:!f});C(e.jobs)}catch(t){console.error("Failed to load searches:",t),e({title:"Error",description:t.message||"Failed to load audio searches",variant:"destructive"})}finally{N(!1)}},[A,f,e]),$=(0,a.useCallback)(async()=>{try{L(!0);let e=await s.adminApi.getCacheStats();z(e)}catch(e){console.error("Failed to load cache stats:",e),z(null)}finally{L(!1)}},[]);(0,a.useEffect)(()=>{V(),$()},[V,$]);let U=async()=>{if(k)try{M(!0);let t=await s.adminApi.clearAudioSearchCache(k.job_id);e({title:"Cache Cleared",description:t.message}),_(!1),R(null),V(),$()}catch(t){e({title:"Error",description:t.message||"Failed to clear cache",variant:"destructive"})}finally{M(!1)}},q=async()=>{try{H(!0);let t=await s.adminApi.clearAllCache();e({title:"All Cache Cleared",description:t.message}),B(!1),$()}catch(t){e({title:"Error",description:t.message||"Failed to clear all cache",variant:"destructive"})}finally{H(!1)}},X=e=>{if(0===e)return"0 B";let t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(1))+" "+["B","KB","MB","GB"][t]};return(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"flex items-center ju Line truncated
For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return a.useEffect(()=>{document.getElementById(e.current?.getAttribute("aria-describedby"))||console.warn(t)},[t,e]),null},S=e.i(47163),k=e.i(67881);function _({...e}){return(0,t.jsx)(h,{"data-slot":"alert-dialog",...e})}function M({...e}){return(0,t.jsx)(x,{"data-slot":"alert-dialog-trigger",...e})}function R({...e}){return(0,t.jsx)(m,{"data-slot":"alert-dialog-portal",...e})}function O({className:e,...a}){return(0,t.jsx)(g,{"data-slot":"alert-dialog-overlay",className:(0,S.cn)("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...a})}function E({className:e,...a}){return(0,t.jsxs)(R,{children:[(0,t.jsx)(O,{}),(0,t.jsx)(j,{"data-slot":"alert-dialog-content",className:(0,S.cn)("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...a})]})}function H({className:e,...a}){return(0,t.jsx)("div",{"data-slot":"alert-dialog-header",className:(0,S.cn)("flex flex-col gap-2 text-center sm:text-left",e),...a})}function B({className:e,...a}){return(0,t.jsx)("div",{"data-slot":"alert-dialog-footer",className:(0,S.cn)("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...a})}function F({className:e,...a}){return(0,t.jsx)(y,{"data-slot":"alert-dialog-title",className:(0,S.cn)("text-lg font-semibold",e),...a})}function I({className:e,...a}){return(0,t.jsx)(C,{"data-slot":"alert-dialog-description",className:(0,S.cn)("text-muted-foreground text-sm",e),...a})}function z({className:e,...a}){return(0,t.jsx)(w,{className:(0,S.cn)((0,k.buttonVariants)(),e),...a})}function P({className:e,...a}){return(0,t.jsx)(A,{className:(0,S.cn)((0,k.buttonVariants)({variant:"outline"}),e),...a})}e.s(["AlertDialog",()=>_,"AlertDialogAction",()=>z,"AlertDialogCancel",()=>P,"AlertDialogContent",()=>E,"AlertDialogDescription",()=>I,"AlertDialogFooter",()=>B,"AlertDialogHeader",()=>H,"AlertDialogTitle",()=>F,"AlertDialogTrigger",()=>M],30009)},13314,e=>{"use strict";var t=e.i(43476),a=e.i(71645),s=e.i(54858),l=e.i(54458),r=e.i(67881),i=e.i(94179),n=e.i(47627),o=e.i(62870),c=e.i(30009),d=e.i(28231),u=e.i(16715),h=e.i(31278),x=e.i(27612),m=e.i(53339),g=e.i(69638),p=e.i(73884),f=e.i(75254);let b=(0,f.default)("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]),j=(0,f.default)("HardDrive",[["line",{x1:"22",x2:"2",y1:"12",y2:"12",key:"1y58io"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}],["line",{x1:"6",x2:"6.01",y1:"16",y2:"16",key:"sgf278"}],["line",{x1:"10",x2:"10.01",y1:"16",y2:"16",key:"1l4acy"}]]);var v=e.i(20682);let y=[{value:"all",label:"All Statuses"},{value:"awaiting_audio_selection",label:"Awaiting Selection"},{value:"pending",label:"Pending"},{value:"complete",label:"Complete"},{value:"failed",label:"Failed"}];function T(){let{toast:e}=(0,v.useToast)(),{showTestData:f}=(0,l.useAdminSettings)(),[T,C]=(0,a.useState)([]),[w,N]=(0,a.useState)(!0),[A,D]=(0,a.useState)("all"),[S,k]=(0,a.useState)(!1),[_,M]=(0,a.useState)(null),[R,O]=(0,a.useState)(!1),[E,H]=(0,a.useState)(!1),[B,F]=(0,a.useState)(!1),[I,z]=(0,a.useState)(null),[P,V]=(0,a.useState)(!1),L=(0,a.useCallback)(async()=>{try{N(!0);let e=await s.adminApi.listAudioSearches({limit:100,status_filter:"all"!==A?A:void 0,exclude_test:!f});C(e.jobs)}catch(t){console.error("Failed to load searches:",t),e({title:"Error",description:t.message||"Failed to load audio searches",variant:"destructive"})}finally{N(!1)}},[A,f,e]),$=(0,a.useCallback)(async()=>{try{V(!0);let e=await s.adminApi.getCacheStats();z(e)}catch(e){console.error("Failed to load cache stats:",e),z(null)}finally{V(!1)}},[]);(0,a.useEffect)(()=>{L(),$()},[L,$]);let q=async()=>{if(_)try{O(!0);let t=await s.adminApi.clearAudioSearchCache(_.job_id);e({title:"Cache Cleared",description:t.message}),k(!1),M(null),L(),$()}catch(t){e({title:"Error",description:t.message||"Failed to clear cache",variant:"destructive"})}finally{O(!1)}},U=async()=>{try{F(!0);let t=await s.adminApi.clearAllCache();e({title:"All Cache Cleared",description:t.message}),H(!1),$()}catch(t){e({title:"Error",description:t.message||"Failed to clear all cache",variant:"destructive"})}finally{F(!1)}},X=e=>{if(0===e)return"0 B";let t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(1))+" "+["B","KB","MB","GB"][t]};return(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"flex items-center ju Line truncated
@@ -0,0 +1,5 @@
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,81140,30030,e=>{"use strict";function t(e,n,{checkForDefaultPrevented:r=!0}={}){return function(t){if(e?.(t),!1===r||!t.defaultPrevented)return n?.(t)}}e.s(["composeEventHandlers",()=>t],81140);var n=e.i(71645),r=e.i(43476);function o(e,t){let o=n.createContext(t),i=e=>{let{children:t,...i}=e,a=n.useMemo(()=>i,Object.values(i));return(0,r.jsx)(o.Provider,{value:a,children:t})};return i.displayName=e+"Provider",[i,function(r){let i=n.useContext(o);if(i)return i;if(void 0!==t)return t;throw Error(`\`${r}\` must be used within \`${e}\``)}]}function i(e,t=[]){let o=[],a=()=>{let t=o.map(e=>n.createContext(e));return function(r){let o=r?.[e]||t;return n.useMemo(()=>({[`__scope${e}`]:{...r,[e]:o}}),[r,o])}};return a.scopeName=e,[function(t,i){let a=n.createContext(i),u=o.length;o=[...o,i];let c=t=>{let{scope:o,children:i,...c}=t,s=o?.[e]?.[u]||a,l=n.useMemo(()=>c,Object.values(c));return(0,r.jsx)(s.Provider,{value:l,children:i})};return c.displayName=t+"Provider",[c,function(r,o){let c=o?.[e]?.[u]||a,s=n.useContext(c);if(s)return s;if(void 0!==i)return i;throw Error(`\`${r}\` must be used within \`${t}\``)}]},function(...e){let t=e[0];if(1===e.length)return t;let r=()=>{let r=e.map(e=>({useScope:e(),scopeName:e.scopeName}));return function(e){let o=r.reduce((t,{useScope:n,scopeName:r})=>{let o=n(e)[`__scope${r}`];return{...t,...o}},{});return n.useMemo(()=>({[`__scope${t.scopeName}`]:o}),[o])}};return r.scopeName=t.scopeName,r}(a,...t)]}e.s(["createContext",()=>o,"createContextScope",()=>i],30030)},48425,e=>{"use strict";var t=e.i(71645),n=e.i(74080),r=e.i(91918),o=e.i(43476),i=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"].reduce((e,n)=>{let i=t.forwardRef((e,t)=>{let{asChild:i,...a}=e,u=i?r.Slot:n;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),(0,o.jsx)(u,{...a,ref:t})});return i.displayName=`Primitive.${n}`,{...e,[n]:i}},{});function a(e,t){e&&n.flushSync(()=>e.dispatchEvent(t))}e.s(["Primitive",()=>i,"dispatchDiscreteCustomEvent",()=>a])},30207,e=>{"use strict";var t=e.i(71645);function n(e){let n=t.useRef(e);return t.useEffect(()=>{n.current=e}),t.useMemo(()=>(...e)=>n.current?.(...e),[])}e.s(["useCallbackRef",()=>n])},26330,e=>{"use strict";var t,n=e.i(71645),r=e.i(81140),o=e.i(48425),i=e.i(20783),a=e.i(30207),u=e.i(43476),c="dismissableLayer.update",s=n.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),l=n.forwardRef((e,l)=>{let{disableOutsidePointerEvents:p=!1,onEscapeKeyDown:v,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:y,...E}=e,b=n.useContext(s),[w,C]=n.useState(null),R=w?.ownerDocument??globalThis?.document,[,N]=n.useState({}),S=(0,i.useComposedRefs)(l,e=>C(e)),P=Array.from(b.layers),[x]=[...b.layersWithOutsidePointerEventsDisabled].slice(-1),O=P.indexOf(x),D=w?P.indexOf(w):-1,T=b.layersWithOutsidePointerEventsDisabled.size>0,L=D>=O,M=function(e,t=globalThis?.document){let r=(0,a.useCallbackRef)(e),o=n.useRef(!1),i=n.useRef(()=>{});return n.useEffect(()=>{let e=e=>{if(e.target&&!o.current){let n=function(){f("dismissableLayer.pointerDownOutside",r,o,{discrete:!0})},o={originalEvent:e};"touch"===e.pointerType?(t.removeEventListener("click",i.current),i.current=n,t.addEventListener("click",i.current,{once:!0})):n()}else t.removeEventListener("click",i.current);o.current=!1},n=window.setTimeout(()=>{t.addEventListener("pointerdown",e)},0);return()=>{window.clearTimeout(n),t.removeEventListener("pointerdown",e),t.removeEventListener("click",i.current)}},[t,r]),{onPointerDownCapture:()=>o.current=!0}}(e=>{let t=e.target,n=[...b.branches].some(e=>e.contains(t));L&&!n&&(m?.(e),g?.(e),e.defaultPrevented||y?.())},R),k=function(e,t=globalThis?.document){let r=(0,a.useCallbackRef)(e),o=n.useRef(!1);return n.useEffect(()=>{let e=e=>{e.target&&!o.current&&f("dismissableLayer.focusOutside",r,{originalEvent:e},{discrete:!1})};return t.addEventListener("focusin",e),()=>t.removeEventListener("focusin",e)},[t,r]),{onFocusCapture:()=>o.current=!0,onBlurCapture:()=>o.current=!1}}(e=>{let t=e.target;![...b.branches].some(e=>e.contains(t))&&(h?.(e),g?.(e),e.defaultPrevented||y?.())},R);return!function(e,t=globalThis?.document){let r=(0,a.useCallbackRef)(e);n.useEffect(()=>{let e=e=>{"Escape"===e.key&&r(e)};return t.addEventListener("keydown",e,{capture:!0}),()=>t.removeEventListener("keydown",e,{capture:!0})},[r,t])}(e=>{D===b.layers.size-1&&(v?.(e),!e.defaultPrevented&&y&&(e.preventDefault(),y()))},R),n.useEffect(()=>{if(w)return p&&(0===b.layersWithOutsidePointerEventsDisabled.size&&(t=R.body.style.pointerEvents,R.body.style.pointerEvents="none"),b.layersWithOutsidePointerEventsDisabled.add(w)),b.layers.add(w),d(),()=>{p&&1===b.layersWithOutsidePointerEventsDisabled.size&&(R.body.style.pointerEvents=t)}},[w,R,p,b]),n.useEffect(()=>()=>{w&&(b.layers.delete(w),b.layersLine truncated
If you want to hide the \`${n.titleName}\`, you can wrap it with our VisuallyHidden component.
For more information, see https://radix-ui.com/primitives/docs/components/${n.docsSlug}`;return t.useEffect(()=>{e&&(document.getElementById(e)||console.error(r))},[r,e]),null},Z=({contentRef:e,descriptionId:n})=>{let r=Y("DialogDescriptionWarning"),o=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${r.contentName}}.`;return t.useEffect(()=>{let t=e.current?.getAttribute("aria-describedby");n&&t&&(document.getElementById(n)||console.warn(o))},[o,e,n]),null};e.s(["Close",()=>H,"Content",()=>k,"Description",()=>B,"Overlay",()=>T,"Portal",()=>O,"Root",()=>C,"Title",()=>_,"Trigger",()=>N,"WarningProvider",()=>X,"createDialogScope",()=>E])}]);
@@ -0,0 +1 @@
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,33525,(e,t,a)=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0}),Object.defineProperty(a,"warnOnce",{enumerable:!0,get:function(){return s}});let s=e=>{}},69638,e=>{"use strict";let t=(0,e.i(75254).default)("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);e.s(["CheckCircle",()=>t],69638)},3116,e=>{"use strict";let t=(0,e.i(75254).default)("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);e.s(["Clock",()=>t],3116)},61659,e=>{"use strict";let t=(0,e.i(75254).default)("CreditCard",[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]]);e.s(["CreditCard",()=>t],61659)},63488,e=>{"use strict";let t=(0,e.i(75254).default)("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);e.s(["Mail",()=>t],63488)},23616,e=>{"use strict";let t=(0,e.i(75254).default)("Youtube",[["path",{d:"M2.5 17a24.12 24.12 0 0 1 0-10 2 2 0 0 1 1.4-1.4 49.56 49.56 0 0 1 16.2 0A2 2 0 0 1 21.5 7a24.12 24.12 0 0 1 0 10 2 2 0 0 1-1.4 1.4 49.55 49.55 0 0 1-16.2 0A2 2 0 0 1 2.5 17",key:"1q2vi4"}],["path",{d:"m10 15 5-3-5-3z",key:"1jp15x"}]]);e.s(["Youtube",()=>t],23616)},64659,65261,84123,e=>{"use strict";var t=e.i(31171);e.s(["ChevronDown",()=>t.default],64659);var a=e.i(43476),s=e.i(71645),r=e.i(63488);let l=(0,e.i(75254).default)("KeyRound",[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]);e.s(["KeyRound",()=>l],65261);var i=e.i(71689),n=e.i(31278),o=e.i(69638),d=e.i(67881),c=e.i(23750),u=e.i(30374),m=e.i(38036);function x({open:e,onClose:t,onSuccess:x}){let[h,f]=(0,s.useState)("email"),[p,g]=(0,s.useState)(""),[y,k]=(0,s.useState)(""),[j,v]=(0,s.useState)(""),{sendMagicLink:b,loginWithToken:N,isLoading:w,error:C,clearError:M}=(0,m.useAuth)(),D=async e=>{(e.preventDefault(),v(""),p.trim())?p.includes("@")&&p.includes(".")?await b(p.trim().toLowerCase())&&f("sent"):v("Please enter a valid email"):v("Please enter your email")},S=async e=>{(e.preventDefault(),v(""),y.trim())?await N(y.trim())&&(k(""),x()):v("Please enter your access token")},T=()=>{f("email"),g(""),k(""),v(""),M(),t()},A=j||C;return(0,a.jsx)(u.Dialog,{open:e,onOpenChange:e=>!e&&T(),children:(0,a.jsxs)(u.DialogContent,{className:"sm:max-w-md bg-card border-border",children:["email"===h&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(u.DialogHeader,{children:[(0,a.jsxs)(u.DialogTitle,{className:"text-foreground flex items-center gap-2",children:[(0,a.jsx)(r.Mail,{className:"w-5 h-5 text-primary"}),"Sign In"]}),(0,a.jsx)(u.DialogDescription,{className:"text-muted-foreground",children:"Enter your email to receive a sign-in link"})]}),(0,a.jsxs)("form",{onSubmit:D,className:"space-y-4",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)(c.Input,{type:"email",placeholder:"you@example.com",value:p,onChange:e=>{g(e.target.value),v(""),M()},className:"bg-secondary border-border text-foreground",autoFocus:!0,disabled:w}),A&&(0,a.jsx)("p",{className:"text-xs text-destructive mt-1",children:A})]}),(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(d.Button,{type:"submit",disabled:!p.trim()||w,className:"w-full bg-primary hover:bg-primary/90",children:w?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(n.Loader2,{className:"w-4 h-4 mr-2 animate-spin"}),"Sending..."]}):"Send Sign-In Link"}),(0,a.jsxs)(d.Button,{type:"button",variant:"ghost",onClick:()=>f("token"),className:"text-muted-foreground hover:text-foreground",children:[(0,a.jsx)(l,{className:"w-4 h-4 mr-2"}),"Use Access Token Instead"]})]}),(0,a.jsx)("p",{className:"text-xs text-muted-foreground text-center",children:"No account? Just enter your email to get started."})]})]}),"sent"===h&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(u.DialogHeader,{children:(0,a.jsxs)(u.DialogTitle,{className:"text-foreground flex items-center gap-2",children:[(0,a.jsx)(o.CheckCircle,{className:"w-5 h-5 text-success"}),"Check Your Email"]})}),(0,a.jsxs)("div",{className:"space-y-4 py-4",children:[(0,a.jsx)("p",{className:"text-foreground",children:"We sent a sign-in link to:"}),(0,a.jsx)("p",{className:"text-foreground font-medium bg-secondary px-4 py-2 rounded-md",children:p}),(0,a.jsx)("p",{className:"text-sm text-muted-foreground",children:"Click the link in the email to sign in. The link expires in 15 minutes."}),(0,a.jsxs)("div",{className:"pt-4 border-t border-border space-y-2",children:[(0,a.jsxs)(d.Button,{variant:"outline",onClick:()=>f("email"),className:"w-full border-border text-foreground hover:text-forLine truncated
@@ -0,0 +1 @@
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,20682,e=>{"use strict";var s=e.i(71645);let t=0,a=new Map,r=e=>{if(a.has(e))return;let s=setTimeout(()=>{a.delete(e),n({type:"REMOVE_TOAST",toastId:e})},1e6);a.set(e,s)},d=[],i={toasts:[]};function n(e){i=((e,s)=>{switch(s.type){case"ADD_TOAST":return{...e,toasts:[s.toast,...e.toasts].slice(0,1)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(e=>e.id===s.toast.id?{...e,...s.toast}:e)};case"DISMISS_TOAST":{let{toastId:t}=s;return t?r(t):e.toasts.forEach(e=>{r(e.id)}),{...e,toasts:e.toasts.map(e=>e.id===t||void 0===t?{...e,open:!1}:e)}}case"REMOVE_TOAST":if(void 0===s.toastId)return{...e,toasts:[]};return{...e,toasts:e.toasts.filter(e=>e.id!==s.toastId)}}})(i,e),d.forEach(e=>{e(i)})}function l({...e}){let s=(t=(t+1)%Number.MAX_SAFE_INTEGER).toString(),a=()=>n({type:"DISMISS_TOAST",toastId:s});return n({type:"ADD_TOAST",toast:{...e,id:s,open:!0,onOpenChange:e=>{e||a()}}}),{id:s,dismiss:a,update:e=>n({type:"UPDATE_TOAST",toast:{...e,id:s}})}}function c(){let[e,t]=s.useState(i);return s.useEffect(()=>(d.push(t),()=>{let e=d.indexOf(t);e>-1&&d.splice(e,1)}),[e]),{...e,toast:l,dismiss:e=>n({type:"DISMISS_TOAST",toastId:e})}}e.s(["useToast",()=>c])},86311,e=>{"use strict";let s=(0,e.i(75254).default)("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);e.s(["MessageSquare",()=>s],86311)},16715,e=>{"use strict";let s=(0,e.i(75254).default)("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);e.s(["RefreshCw",()=>s],16715)},94179,e=>{"use strict";var s=e.i(43476),t=e.i(91918),a=e.i(25913),r=e.i(47163);let d=(0,a.cva)("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function i({className:e,variant:a,asChild:i=!1,...n}){let l=i?t.Slot:"span";return(0,s.jsx)(l,{"data-slot":"badge",className:(0,r.cn)(d({variant:a}),e),...n})}e.s(["Badge",()=>i])},70065,e=>{"use strict";var s=e.i(43476),t=e.i(47163);function a({className:e,...a}){return(0,s.jsx)("div",{"data-slot":"card",className:(0,t.cn)("bg-card text-card-foreground flex flex-col gap-1 rounded-lg border py-6 shadow-sm",e),...a})}function r({className:e,...a}){return(0,s.jsx)("div",{"data-slot":"card-header",className:(0,t.cn)("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...a})}function d({className:e,...a}){return(0,s.jsx)("div",{"data-slot":"card-title",className:(0,t.cn)("leading-none font-semibold",e),...a})}function i({className:e,...a}){return(0,s.jsx)("div",{"data-slot":"card-description",className:(0,t.cn)("text-muted-foreground text-sm",e),...a})}function n({className:e,...a}){return(0,s.jsx)("div",{"data-slot":"card-content",className:(0,t.cn)("px-6",e),...a})}e.s(["Card",()=>a,"CardContent",()=>n,"CardDescription",()=>i,"CardHeader",()=>r,"CardTitle",()=>d])},59276,e=>{"use strict";var s=e.i(43476),t=e.i(70065),a=e.i(71428),r=e.i(47163);function d({title:e,value:d,description:i,icon:n,trend:l,loading:c,className:o,valueClassName:x}){return c?(0,s.jsxs)(t.Card,{className:(0,r.cn)("",o),children:[(0,s.jsx)(t.CardHeader,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:(0,s.jsx)(t.CardTitle,{className:"text-sm font-medium",children:(0,s.jsx)(a.Skeleton,{className:"h-4 w-24"})})}),(0,s.jsxs)(t.CardContent,{children:[(0,s.jsx)(a.Skeleton,{className:"h-8 w-16"}),(0,s.jsx)(a.Skeleton,{className:"h-3 w-32 mt-2"})]})]}):(0,s.jsxs)(t.Card,{className:(0,r.cn)("",o),children:[(0,s.jsxs)(t.CardHeader,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[(0,s.jsx)(t.CardTitle,{className:"text-sm font-medium text-muted-foreground",children:e}),n&&(0,s.jsx)(n,{className:"h-4 w-4 text-muted-foreground"})]}),(0,s.jsxs)(t.CardContent,{children:[(0,s.jsx)("div",{className:(0,r.cn)("text-2xl font-bold",Line truncated
@@ -0,0 +1,6 @@
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,33525,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"warnOnce",{enumerable:!0,get:function(){return r}});let r=e=>{}},41947,e=>{"use strict";let t=(0,e.i(75254).default)("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);e.s(["default",()=>t])},37727,e=>{"use strict";var t=e.i(41947);e.s(["X",()=>t.default])},86536,e=>{"use strict";let t=(0,e.i(75254).default)("Eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);e.s(["Eye",()=>t],86536)},24672,e=>{"use strict";var t=e.i(68834),n=e.i(54858);let r={logo_url:null,logo_height:40,primary_color:"#ff5bb8",secondary_color:"#8b5cf6",accent_color:"#ffdf6b",background_color:null,favicon_url:null,site_title:"Nomad Karaoke Generator",tagline:null},a={audio_search:!0,file_upload:!0,youtube_url:!0,youtube_upload:!0,dropbox_upload:!0,gdrive_upload:!0,theme_selection:!0,color_overrides:!0,enable_cdg:!0,enable_4k:!0,admin_access:!0},i={theme_id:null,locked_theme:null,distribution_mode:"all"},o=(0,t.create)()((e,t)=>({tenant:null,isDefault:!0,isLoading:!1,error:null,isInitialized:!1,get branding(){let{tenant:e}=t();return e?.branding??r},get features(){let{tenant:e}=t();return e?.features??a},get defaults(){let{tenant:e}=t();return e?.defaults??i},get tenantId(){let{tenant:e}=t();return e?.id??null},fetchTenantConfig:async()=>{if(!t().isLoading){e({isLoading:!0,error:null});try{let t=function(){let e=window.location.hostname.toLowerCase();if("localhost"===e||"127.0.0.1"===e)return new URLSearchParams(window.location.search).get("tenant");if(e.includes("nomadkaraoke.com")){let t=e.split(".");if((3===t.length||4===t.length&&"gen"===t[1])&&!["gen","api","www","buy","admin","app","beta"].includes(t[0]))return t[0]}return null}(),r=`${n.API_BASE_URL}/api/tenant/config`;t&&(r+=`?tenant=${encodeURIComponent(t)}`);let a=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json",...t?{"X-Tenant-ID":t}:{}}});if(!a.ok)throw Error("Failed to fetch tenant configuration");let i=await a.json();e({tenant:i.tenant,isDefault:i.is_default,isLoading:!1,isInitialized:!0}),i.tenant&&l(i.tenant.branding)}catch(t){console.error("Failed to fetch tenant config:",t),e({tenant:null,isDefault:!0,isLoading:!1,error:t instanceof Error?t.message:"Failed to load tenant configuration",isInitialized:!0})}}},setTenant:(t,n)=>{e({tenant:t,isDefault:n,isInitialized:!0}),t&&l(t.branding)},clearError:()=>e({error:null})}));function l(e){if("undefined"==typeof document)return;let t=document.documentElement;if(t.style.setProperty("--tenant-primary",e.primary_color),t.style.setProperty("--tenant-secondary",e.secondary_color),e.accent_color&&t.style.setProperty("--tenant-accent",e.accent_color),e.background_color&&t.style.setProperty("--tenant-background",e.background_color),e.site_title&&(document.title=e.site_title),e.favicon_url){let t=document.querySelector("link[rel~='icon']");t&&(t.href=e.favicon_url)}}e.s(["useTenant",0,o])},89554,e=>{"use strict";var t=e.i(43476),n=e.i(71645),r=(e,t,n,r,a,i,o,l)=>{let s=document.documentElement,c=["light","dark"];function d(t){var n;(Array.isArray(e)?e:[e]).forEach(e=>{let n="class"===e,r=n&&i?a.map(e=>i[e]||e):a;n?(s.classList.remove(...r),s.classList.add(i&&i[t]?i[t]:t)):s.setAttribute(e,t)}),n=t,l&&c.includes(n)&&(s.style.colorScheme=n)}if(r)d(r);else try{let e=localStorage.getItem(t)||n,r=o&&"system"===e?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":e;d(r)}catch(e){}},a=["light","dark"],i="(prefers-color-scheme: dark)",o="undefined"==typeof window,l=n.createContext(void 0),s=e=>n.useContext(l)?n.createElement(n.Fragment,null,e.children):n.createElement(d,{...e}),c=["light","dark"],d=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:r=!0,enableColorScheme:o=!0,storageKey:s="theme",themes:d=c,defaultTheme:h=r?"system":"light",attribute:p="data-theme",value:y,children:b,nonce:v,scriptProps:_})=>{let[w,k]=n.useState(()=>f(s,h)),[S,E]=n.useState(()=>"system"===w?g():w),T=y?Object.values(y):d,x=n.useCallback(e=>{let n=e;if(!n)return;"system"===e&&r&&(n=g());let i=y?y[n]:n,l=t?m(v):null,s=document.documentElement,c=e=>{"class"===e?(s.classList.remove(...T),i&&s.classList.add(i)):e.startsWith("data-")&&(i?s.setAttribute(e,i):s.removeAttribute(e))};if(Array.isArray(p)?p.forEach(c):c(p),o){let e=a.includes(h)?h:null,t=a.includes(n)?n:e;s.style.colorScheme=t}null==l||l()},[v]),I=n.useCallback(e=>{let t="function"==typeof e?e(w):e;k(t);try{localStorage.setItem(s,t)}catch(e){}},[w]),j=n.useCallback(t=>{E(g(t)),"system"===w&&r&&!e&&x("system")},[w,e]);n.useEffect(()=>{let e=window.matchMedia(i);return e.addListener(j),j(e),()=>e.removeListener(j)},[j]),n.useEffect(()=>{let e=e=>{e.key===s&&(e.newValue?k(e.newValue)Line truncated
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${a}');
`})]})}e.s(["GoogleAnalytics",()=>i])}]);
Loaded 100 of 528 files, more files were not shown because too many files have changed in this diff. Show more