Compare commits

..
14 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.6 010784141c fix: resolve 500 error on admin users search (#526)
## Summary
- Fix 500 error when searching users on admin dashboard caused by
Firestore range filter on `email` conflicting with `order_by` on
`created_at` (requires composite index)
- Move sorting to Python when search is active (docs are already fetched
for in-memory pagination anyway)
- Strip whitespace from search input to handle trailing spaces from URL
encoding (`search=dalton+`)

## Test plan
- [x] All 2489 backend tests pass
- [x] CodeRabbit review: 1 finding fixed (type-safe sort key)
- [ ] Verify search works 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-03-10 00:38:53 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 64a95d79c6 perf: pre-generate audio editor assets for instant loading (#525)
## Summary
- Audio editor UI was taking 10-20 seconds to load because waveform
generation + FLAC→OGG transcoding happened on-demand
- Now pre-generates both assets in the download worker before
`awaiting_audio_edit`, matching the pattern `screens_worker` uses for
lyrics/instrumental review
- Editor should now load in ~1s (just reads cached JSON + serves signed
URL for pre-transcoded OGG)

## Changes
- `AudioAnalysisService`: new `cache_waveform_data()` and
`load_cached_waveform()` methods
- `audio_download_worker`: pre-transcodes OGG + caches waveform JSON
before state transition (non-fatal)
- `input-audio-info` endpoint: checks for cached waveform first, falls
back to on-demand
- 10 new unit tests covering cache hit/miss, pre-generation, and
fallback behavior

## Test plan
- [x] 2512 backend tests pass (1 pre-existing failure unrelated)
- [ ] Create job with audio edit enabled, verify editor loads instantly

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 18:04:13 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 4824743a99 fix: update E2E tests for new Visibility step (#524)
## Summary
- The guided job creation flow was expanded from 3→4 steps (added
Visibility step between audio selection and Customize & Create)
- E2E tests were not updated, causing the daily happy path test to fail
([run
#95](https://github.com/nomadkaraoke/karaoke-gen/actions/runs/22840888562))
- Updated 3 test files to interact with the new Visibility step before
proceeding to Customize & Create

## Changes
- **happy-path-real-user.spec.ts**: Click "Keep Private" in Visibility
step, remove obsolete `#guided-private` checkbox
- **guided-flow.spec.ts**: All 4 job-creation tests updated for
Visibility step (search, private+display names, YouTube URL, file
upload)
- **demo-recording.spec.ts**: Added Visibility scene, renumbered
subsequent scenes

## Test plan
- [x] All 701 frontend unit tests pass
- [ ] CI E2E smoke tests pass
- [ ] `e2e-happy-path` label triggers production happy path test —
should now pass with the Visibility step interaction

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 17:54:14 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 b2b2469f6f ui: improve audio edit opt-in with clearer visual hierarchy (#523)
## Summary
- Redesigned the audio edit opt-in screen shown after selecting audio in
the job creation flow
- "Use as-is" (default) gets a green Zap icon and "Recommended" badge —
visually prominent so most users click through quickly
- "Edit audio first" gets a purple Scissors icon with a gold lightbulb
hint explaining when it's useful (live recordings with intros, tracks
with sections to remove)
- Left-aligned layout with icons for better scannability

## Test plan
- [x] All 701 frontend tests pass
- [ ] Visual check 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-03-09 16:38:17 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 ba265839cf fix: swap upload_json arguments for audio edit endpoints (#522)
## Summary
- Fixed swapped `upload_json(destination_path, data)` arguments in two
audio edit endpoints
- Both `save_audio_edit_session` and `submit_audio_edit` were passing
`(data, path)` instead of `(path, data)`, causing 500 errors

## Test plan
- [x] Verify audio edit session save works (POST
`/api/review/{job_id}/audio-edit-sessions`)
- [x] Verify audio edit submit works (POST
`/api/review/{job_id}/audio-edit/submit`)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 16:27:10 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 6c120b709c feat: audio edits admin dashboard + reset-to-audio-edit button (#521)
## Summary
- New admin page at `/admin/audio-edits` to view and inspect audio
editing sessions
- "Audio Edit" reset button in admin job actions to reset any job back
to audio edit phase
- Backend API endpoints for listing/viewing audio edit reviews

## Changes

### Admin Dashboard (`/admin/audio-edits`)
- List view: jobs with audio edits, searchable by artist/title/email
- Detail dialog with 3 tabs: Edit Stack, Sessions, Audio playback
- Raw data dialog with JSON copy
- Follows existing edit-reviews page pattern

### Reset to Audio Edit
- New "Audio Edit" button in admin job actions (between Audio and
Review)
- **Critical safety**: restores `input_media_gcs_path` to original when
resetting (the submit endpoint overwrites this with edited audio)
- Clears edit stack, redo stack, uploads, and all downstream processing
flags

### Backend
- `GET /api/admin/audio-edit-reviews` - list jobs with audio edits
- `GET /api/admin/audio-edit-reviews/{job_id}` - full detail with
sessions, signed audio URLs

## Test plan
- [x] All 64 backend tests pass (admin reset + audio edit routes)
- [x] All 701 frontend Jest tests pass (38 suites)
- [x] Reset to `awaiting_audio_edit` properly clears state data keys
- [x] `input_media_gcs_path` restored to original on audio edit reset

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 11:59:04 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 483ba9e11b fix: trigger workers in background after audio edit submit (#520)
## Summary
- The audio edit submit endpoint was `await`ing worker triggers (Cloud
Run Job calls) synchronously
- These calls take 30+ seconds, causing the browser `fetch` to time out
- The frontend never received the success response, so the
success/countdown screen never appeared
- Fix: use `asyncio.create_task()` to fire-and-forget the worker
triggers

## Changes
- `backend/api/routes/review.py`: Wrap worker trigger calls in a
background task so the HTTP response returns immediately

## Test plan
- [x] All 25 audio edit route tests pass
- [x] Submit endpoint still returns correct response shape
- [x] Workers still get triggered (just asynchronously)

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 11:09:03 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 7d4a577dcb fix: worker valid statuses for audio_edit_complete + duration display (#519)
## Summary
- Workers (audio_worker, lyrics_worker) were immediately rejecting jobs
in `audio_edit_complete` status because that status wasn't in their
valid status lists
- `formatTimePrecise()` produced garbled output like "-2:-14.5" for
negative durations due to `Math.floor()` on negative numbers

## Changes
- Added `JobStatus.AUDIO_EDIT_COMPLETE` to `audio_worker` and
`lyrics_worker` valid statuses in `job_health_service.py`
- Fixed `formatTimePrecise()` in `AudioEditor.tsx` to use `Math.abs()`
and prepend sign separately

## Test plan
- [x] All 25 audio edit route tests pass
- [x] All 50 job health service tests pass
- [x] Verified negative duration formatting produces correct output

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 23:48:19 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 10ad8b51a7 fix: Align audio edit apply/undo/redo response with frontend (#518)
## Summary
- `_build_audio_edit_response()` returned nested structure
(`edited_audio.*`, `edit_stack_size` integer) but frontend expected flat
fields (`current_audio_url`, `duration_after`, `edit_stack` array)
- This caused "can't access property 'length', t is undefined" when
trying to apply any edit operation (cut, trim, mute)
- Also added `duration_before`/`duration_after` tracking to edit entries

## Test plan
- [x] All 25 audio edit route tests pass
- [x] Full test suite passes (2490 backend + 189 Playwright)
- [ ] Verify edit operations work in production

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 23:13:15 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 7dab28b0ea fix: re-enable Cloud Run Jobs for video encoding to survive deployments (#517)
## Summary

- Re-enable `USE_CLOUD_RUN_JOBS_FOR_VIDEO=true` — this env var was
dropped during the CI migration from cloudbuild.yaml to GitHub Actions,
silently disabling the deployment-safe encoding path
- Add all required env vars and secrets to the `video-encoding-job`
Cloud Run Job in Pulumi (was missing encoding worker credentials,
distribution defaults, Discord, SendGrid, admin tokens)
- Add CI step to update the Cloud Run Job image on each deploy (was
stuck on Dec 2025 image)
- Add unit test verifying video worker routes to Cloud Run Jobs when
flag is enabled

**Incident:** Job `43c0d519` (Westlife - Medley) stuck at `encoding` for
4+ hours on 2026-03-08. A deployment rollout killed the Cloud Run
instance running the encoding orchestrator as a `BackgroundTask`. The
three-layer defense (PRs #413, #473) only protected the GCE encoding
worker, not the Cloud Run orchestrator lifecycle.

**Root cause:** `BackgroundTask` work runs after the HTTP response
returns, so Cloud Run can kill it during deployment drain. Cloud Run
Jobs run to completion and are immune to Service deployments.

See `docs/archive/2026-03-08-fix-encoding-deploy-survival.md` for full
incident analysis.

## Test plan
- [x] Backend tests pass (103 tests)
- [x] New unit test: `test_trigger_video_worker_routes_to_cloud_run_job`
- [x] Job `43c0d519` re-triggered and completed successfully
- [ ] After deploy: verify video worker dispatches Cloud Run Job (check
Cloud Run Jobs console)
- [ ] After deploy: run a test job end-to-end

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 22:57:03 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 2f19921328 fix: Align audio edit API response with frontend interface (#516)
## Summary
- Backend `input-audio-info` endpoint returned nested structure
(`original_audio.playback_url`) but frontend expected flat fields
(`original_audio_url`, `edit_stack`, etc.)
- Caused "can't access property 'length', t.edit_stack is undefined"
error on the audio edit page
- Added defensive `|| []` fallback for `edit_stack` access in frontend

## Test plan
- [x] Backend unit tests updated and passing (25/25)
- [ ] Verify audio edit page loads 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-03-08 22:41:39 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 26297fe7c4 feat: Add Edit Input Audio feature (trim, cut, mute, join) (#514)
## Summary

@coderabbitai ignore

Adds a complete "Edit Input Audio" feature that lets users optionally
trim, cut, mute, or join input audio before processing begins. This is
especially useful for live recordings from YouTube where users need to
skip talking/intros.

**5 phases implemented:**
- **Phase 1 (Backend):** 3 new job states, FFmpeg audio operations
service, 6 API endpoints, edit stack undo/redo
- **Phase 2 (Sessions):** Audio edit session persistence with Firestore
+ GCS, SHA256 deduplication
- **Phase 3 (Creation Flow):** Opt-in toggle in job creation,
requires_audio_edit flag across all 3 creation paths
- **Phase 4 (Editor UI):** Full audio editor with waveform
visualization, selection-based editing, playback controls, submit flow
- **Phase 5 (Restore):** Auto-save hook, session restore dialog, manual
save progress

**Key changes:**
- 3 new job states: `awaiting_audio_edit`, `in_audio_edit`,
`audio_edit_complete`
- Server-side FFmpeg operations (lossless FLAC internally, OGG Opus for
browser)
- Collapsible audio edit toggle in VisibilityStep (defaults to off)
- "Edit Audio" action button in JobCard for awaiting_audio_edit status
- Session auto-save every 3 edits + on page hide + before submit
- Session restore dialog when returning to an interrupted edit

## Test plan

- [x] All 706 frontend tests pass (38 suites)
- [x] All 2491 backend tests pass (1 pre-existing failure in unrelated
test)
- [x] 23 AudioEditor component tests (loading, rendering, undo/redo,
submit, restore, save)
- [x] 25 audio edit route tests
- [x] 18 audio edit service tests
- [x] 13 audio edit session tests
- [x] 5 VisibilityStep toggle tests
- [ ] Manual E2E test with real audio file (user to verify)

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 20:31:13 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 2131342fa1 Deduplicate catalog track suggestions (#513)
@coderabbitai ignore

## Summary
- Deduplicate song suggestions in the CatalogTrackList by artist + track
name before rendering
- Spotify returns the same song from multiple albums (deluxe, singles,
etc.), causing identical rows

## Test plan
- [x] Visual: "Etherwood - Weightless" no longer shows 5 identical rows
- [x] Logic: `findFuzzyMatches` already deduplicates for the Did You
Mean banner; this adds the same to the suggestion panel

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 12:13:11 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 93823b8a20 Move song suggestions to Step 2 with fuzzy typo correction (#512)
@coderabbitai ignore

## Summary

- **Simplified Step 1 (Song Info)**: Removed autocomplete — plain text
inputs for artist/title so users aren't confused by autocomplete
behavior
- **Step 2 song suggestions**: Catalog lookup + community version check
fire in parallel with audio search. Results appear as a "Song found in
our database" panel (exact match) or correction suggestion panel while
the user waits
- **Fuzzy "Did you mean?" correction**: When audio search returns poor
results (Tier 3) and catalog has no exact title match, fetches the
artist's discography and fuzzy-matches against the user's title. Shows
amber banner with one-click correction + expandable alternatives list.
Title-based fallback with artist tiebreaker handles garbled artist
fields
- **Visibility step reworked**: Action buttons at top for one-click
select+continue, "change later" note, removed Recommended badge
- **Minor UI polish**: Warning icon on community banner, "Recommended
Audio" heading, YouTube icon on community links, filename above release
in pick card

## Test plan

- [x] 70 new tests added (fuzzy matching, SongInfoStep, AudioSourceStep,
VisibilityStep, CommunityVersionBanner)
- [x] All 677 tests pass
- [x] Manual testing via Playwright: "Fox Stevenson / ruises" typo → Did
you mean Bruises; "fox stevenson bruises / bruises" garbled artist →
correct Fox Stevenson suggestion
- [x] CodeRabbit review completed, issues fixed

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 04:40:35 -04:00
68 changed files with 10203 additions and 259 deletions

No files matched your search

+16 -1
View File
@@ -1316,9 +1316,24 @@ 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,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-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,USE_CLOUD_RUN_JOBS_FOR_VIDEO=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,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
- name: Update Cloud Run Jobs with new image
run: |
IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}"
echo "📦 Updating Cloud Run Jobs to image: $IMAGE"
# Video encoding job - runs video worker to completion, immune to service deployments
gcloud run jobs update video-encoding-job \
--image "$IMAGE" \
--region us-central1 \
--project ${{ env.PROJECT_ID }} \
--quiet
echo "✅ Cloud Run Jobs updated"
- name: Verify deployment and version
run: |
EXPECTED_VERSION="${{ steps.version_check.outputs.version }}"
+254
View File
@@ -1046,6 +1046,7 @@ class TriggerWorkerResponse(BaseModel):
ALLOWED_RESET_STATES = {
"pending",
"awaiting_audio_selection",
"awaiting_audio_edit", # Re-enter audio editing phase
"awaiting_review", # Combined review (lyrics + instrumental selection)
# Note: awaiting_instrumental_selection removed - deprecated by combined review flow (Jan 2026)
"instrumental_selected", # Re-run video generation with same settings
@@ -1082,6 +1083,22 @@ STATE_DATA_CLEAR_KEYS = {
"screens_progress",
"encoding_progress",
],
"awaiting_audio_edit": [
# Clear edit state so user starts fresh
"audio_edit_stack",
"audio_edit_redo_stack",
"audio_edit_uploads",
# Clear downstream processing flags
"audio_complete",
"lyrics_complete",
"review_complete",
"corrected_lyrics",
"instrumental_selection",
"video_progress",
"render_progress",
"screens_progress",
"encoding_progress",
],
"awaiting_review": [
# Combined review - user reviews lyrics AND selects instrumental in one step
"review_complete",
@@ -1203,6 +1220,18 @@ async def reset_job(
# Add timeline event
clear_updates["timeline"] = ArrayUnion([timeline_event])
# Special handling for awaiting_audio_edit: restore original input audio
# The submit endpoint copies edited audio to input_media_gcs_path,
# so we must restore the original path so the user starts fresh.
if target_state == "awaiting_audio_edit":
original_path = current_state_data.get("original_input_media_gcs_path")
if original_path:
clear_updates["input_media_gcs_path"] = original_path
logger.info(
f"Admin reset job {job_id}: Restoring input_media_gcs_path "
f"to original: {original_path}"
)
# Execute the update
job_ref.update(clear_updates)
@@ -3274,3 +3303,228 @@ async def get_edit_review_detail(
"annotations": annotations,
"audio_url": audio_url,
}
# ─── Audio Edit Reviews ─────────────────────────────────────────────────────
class AudioEditReviewSummary(BaseModel):
job_id: str
artist: str
title: str
user_email: str
status: str
created_at: Optional[str] = None
updated_at: Optional[str] = None
session_count: int = 0
total_edits: int = 0
original_duration: Optional[float] = None
current_duration: Optional[float] = None
latest_trigger: Optional[str] = None
class AudioEditReviewListResponse(BaseModel):
reviews: List[AudioEditReviewSummary]
total: int
has_more: bool
@router.get("/audio-edit-reviews", response_model=AudioEditReviewListResponse)
def list_audio_edit_reviews(
limit: int = 50,
offset: int = 0,
exclude_test: bool = False,
search: Optional[str] = None,
auth_result: AuthResult = Depends(require_admin),
):
"""List jobs that have audio edit sessions."""
from backend.services.firestore_service import FirestoreService
user_service = get_user_service()
db = user_service.db
fs = FirestoreService()
STREAM_LIMIT = 10000
reviews = []
streamed = 0
for doc in db.collection("jobs").limit(STREAM_LIMIT).stream():
streamed += 1
data = doc.to_dict()
state_data = data.get("state_data") or {}
# Only include jobs that have been through audio edit
# (have edit stack or have audio edit sessions)
has_edit_stack = bool(state_data.get("audio_edit_stack"))
status = data.get("status", "")
is_in_audio_edit = status in (
"awaiting_audio_edit", "in_audio_edit", "audio_edit_complete"
)
if not has_edit_stack and not is_in_audio_edit:
# Quick check: does this job have any audio edit sessions subcollection?
sessions_ref = db.collection("jobs").document(doc.id).collection("audio_edit_sessions")
if not next(sessions_ref.limit(1).stream(), None):
continue
email = data.get("user_email", "")
if exclude_test and is_test_email(email):
continue
artist = data.get("artist", "")
title = data.get("title", "")
if search:
search_lower = search.lower()
if (
search_lower not in (artist or "").lower()
and search_lower not in (title or "").lower()
and search_lower not in (email or "").lower()
):
continue
# Get session summary info
sessions = fs.list_audio_edit_sessions(doc.id)
session_count = len(sessions)
total_edits = 0
latest_trigger = None
current_duration = None
original_duration = None
if sessions:
latest = sessions[0] # Already sorted by updated_at DESC
total_edits = latest.edit_count
latest_trigger = latest.trigger
current_duration = latest.audio_duration_seconds
original_duration = latest.original_duration_seconds
created_at = data.get("created_at")
updated_at = data.get("updated_at")
def _to_iso(val) -> Optional[str]:
if val is None:
return None
if hasattr(val, 'isoformat'):
return val.isoformat()
return str(val)
try:
reviews.append(AudioEditReviewSummary(
job_id=doc.id,
artist=artist or "",
title=title or "",
user_email=email or "",
status=status,
created_at=_to_iso(created_at),
updated_at=_to_iso(updated_at),
session_count=session_count,
total_edits=total_edits,
original_duration=original_duration,
current_duration=current_duration,
latest_trigger=latest_trigger,
))
except Exception as e:
logger.warning(f"Job {doc.id}: Error building audio edit review summary: {e}")
continue
if streamed >= STREAM_LIMIT:
logger.warning(f"Audio edit reviews stream hit limit ({STREAM_LIMIT}), results may be incomplete")
reviews.sort(
key=lambda r: r.updated_at or r.created_at or "",
reverse=True,
)
total = len(reviews)
paginated = reviews[offset : offset + limit]
return AudioEditReviewListResponse(
reviews=paginated,
total=total,
has_more=(offset + limit) < total,
)
@router.get("/audio-edit-reviews/{job_id}")
async def get_audio_edit_review_detail(
job_id: str,
auth_result: AuthResult = Depends(require_admin),
):
"""Get full audio edit review detail for one job, including all sessions."""
from backend.services.firestore_service import FirestoreService
from backend.services.audio_transcoding_service import AudioTranscodingService
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
storage = StorageService()
fs = FirestoreService()
job_meta = {
"job_id": job.job_id,
"artist": job.artist,
"title": job.title,
"user_email": job.user_email,
"status": job.status.value if hasattr(job.status, "value") else str(job.status),
"created_at": job.created_at.isoformat() if job.created_at else None,
"updated_at": job.updated_at.isoformat() if job.updated_at else None,
}
# Get all sessions
sessions = fs.list_audio_edit_sessions(job_id)
sessions_data = []
for session in sessions:
session_dict = session.to_dict()
# Convert datetimes to ISO strings
for key in ("created_at", "updated_at"):
val = session_dict.get(key)
if hasattr(val, "isoformat"):
session_dict[key] = val.isoformat()
sessions_data.append(session_dict)
# Get current edit stack from state_data
state_data = job.state_data or {}
edit_stack = state_data.get("audio_edit_stack", [])
# Generate signed URLs for original and current audio
original_audio_url = None
current_audio_url = None
transcoding = AudioTranscodingService(storage_service=storage)
if job.input_media_gcs_path:
try:
current_audio_url = await transcoding.get_review_audio_url_async(
job.input_media_gcs_path, expiration_minutes=120
)
except Exception as e:
logger.warning(f"Job {job_id}: Could not generate current audio URL: {e}")
# Original audio (before edits)
original_path = state_data.get("original_input_media_gcs_path") or job.input_media_gcs_path
if original_path and original_path != job.input_media_gcs_path:
try:
original_audio_url = await transcoding.get_review_audio_url_async(
original_path, expiration_minutes=120
)
except Exception as e:
logger.warning(f"Job {job_id}: Could not generate original audio URL: {e}")
# Load edit log if it exists
edit_log = None
edit_log_path = f"jobs/{job_id}/audio_edit/edit_log.json"
try:
if storage.file_exists(edit_log_path):
edit_log = storage.download_json(edit_log_path)
except Exception as e:
logger.warning(f"Job {job_id}: Could not load audio edit log: {e}")
return {
"job": job_meta,
"sessions": sessions_data,
"edit_stack": edit_stack,
"edit_log": edit_log,
"original_audio_url": original_audio_url,
"current_audio_url": current_audio_url,
}
+13
View File
@@ -162,6 +162,9 @@ class CreateJobFromUrlRequest(BaseModel):
# Private (non-published) track mode
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
# Audio editing
requires_audio_edit: bool = Field(False, description="Pause after download for user to edit input audio")
class CreateJobFromUrlResponse(BaseModel):
"""Response from creating a job from URL."""
@@ -428,6 +431,8 @@ async def upload_and_create_job(
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"),
# Audio editing
requires_audio_edit: bool = Form(False, description="Pause after download for user to edit input audio"),
):
"""
Upload an audio file and create a karaoke generation job with full style configuration.
@@ -668,6 +673,10 @@ async def upload_and_create_job(
logger.info(f"Created job {job_id} for {artist} - {title}")
# Store requires_audio_edit flag in state_data
if requires_audio_edit:
job_manager.update_state_data(job_id, 'requires_audio_edit', True)
# If theme is set and no custom style files are being uploaded, prepare theme style now
# This copies the theme's style_params.json to the job folder so LyricsTranscriber
# can access the style configuration for preview videos
@@ -1734,6 +1743,10 @@ async def create_job_from_url(
job_manager.update_job(job_id, update_data)
logger.info(f"Applied theme '{effective_theme_id}' to job {job_id}")
# Store requires_audio_edit flag in state_data
if body.requires_audio_edit:
job_manager.update_state_data(job_id, 'requires_audio_edit', True)
logger.info(f"Created URL-based job {job_id} for URL: {body.url}")
if artist:
logger.info(f" Artist: {artist}")
+3
View File
@@ -2085,6 +2085,7 @@ class CreateFromSearchRequest(BaseModel):
display_artist: Optional[str] = Field(None, description="Display artist override for title screens/filenames")
display_title: Optional[str] = Field(None, description="Display title override for title screens/filenames")
is_private: bool = Field(False, description="Private track: Dropbox only, no YouTube/GDrive")
requires_audio_edit: bool = Field(False, description="Pause after download for user to edit input audio")
@validator('display_artist', 'display_title')
def strip_whitespace(cls, v):
@@ -2267,6 +2268,8 @@ async def create_job_from_search(
}
if session.get('remote_search_id'):
state_data_update['remote_search_id'] = session['remote_search_id']
if body.requires_audio_edit:
state_data_update['requires_audio_edit'] = True
job_manager.update_job(job_id, {'state_data': state_data_update})
# Transition to DOWNLOADING_AUDIO (skips AWAITING_AUDIO_SELECTION entirely)
+679
View File
@@ -1113,3 +1113,682 @@ async def delete_review_session(
return {"status": "deleted", "session_id": session_id}
# ============================================
# Audio Edit Session Endpoints (backup/restore)
# ============================================
@router.post("/{job_id}/audio-edit-sessions")
async def save_audio_edit_session(
job_id: str,
data: Dict[str, Any],
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""Save an audio edit session snapshot."""
import hashlib
import json as json_mod
from backend.models.audio_edit_session import AudioEditSession, AudioEditSessionSummary
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
user_email = auth_info[0] if isinstance(auth_info, tuple) else ""
edit_data = data.get("edit_data", {})
# Compute hash for deduplication
data_json = json_mod.dumps(edit_data, sort_keys=True, default=str)
data_hash = hashlib.sha256(data_json.encode()).hexdigest()
# Skip if identical to most recent
firestore_svc = FirestoreService()
latest_hash = firestore_svc.get_latest_audio_edit_session_hash(job_id)
if latest_hash == data_hash:
return {"status": "skipped", "reason": "identical_data"}
# Build session
summary_data = data.get("summary", {})
session = AudioEditSession(
job_id=job_id,
user_email=user_email,
edit_count=data.get("edit_count", 0),
trigger=data.get("trigger", "auto"),
audio_duration_seconds=summary_data.get("net_duration_seconds"),
original_duration_seconds=data.get("original_duration_seconds"),
artist=job.artist,
title=job.title,
summary=AudioEditSessionSummary.from_dict(summary_data),
data_hash=data_hash,
)
# Upload edit_data to GCS
storage = StorageService()
gcs_path = f"jobs/{job_id}/audio_edit_sessions/{session.session_id}.json"
storage.upload_json(gcs_path, edit_data)
session.edit_data_gcs_path = gcs_path
# Save metadata to Firestore
firestore_svc.save_audio_edit_session(job_id, session)
return {
"status": "saved",
"session_id": session.session_id,
"created_at": session.created_at.isoformat(),
}
@router.get("/{job_id}/audio-edit-sessions")
async def list_audio_edit_sessions(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""List all audio edit sessions for a job (metadata only)."""
firestore_svc = FirestoreService()
sessions = firestore_svc.list_audio_edit_sessions(job_id)
return {
"sessions": [s.to_dict() for s in sessions]
}
@router.get("/{job_id}/audio-edit-sessions/{session_id}")
async def get_audio_edit_session(
job_id: str,
session_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""Get a single audio edit session with full edit_data loaded from GCS."""
firestore_svc = FirestoreService()
session = firestore_svc.get_audio_edit_session(job_id, session_id)
if not session:
raise HTTPException(status_code=404, detail="Session not found")
result = session.to_dict()
# Load edit data from GCS
if session.edit_data_gcs_path:
try:
storage = StorageService()
result["edit_data"] = storage.download_json(session.edit_data_gcs_path)
except Exception as e:
logger.warning(f"Could not load audio edit data from GCS for session {session_id}: {e}")
result["edit_data"] = None
else:
result["edit_data"] = None
return result
@router.delete("/{job_id}/audio-edit-sessions/{session_id}")
async def delete_audio_edit_session(
job_id: str,
session_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""Delete an audio edit session (metadata + GCS data)."""
firestore_svc = FirestoreService()
session = firestore_svc.get_audio_edit_session(job_id, session_id)
if not session:
raise HTTPException(status_code=404, detail="Session not found")
# Delete GCS data
if session.edit_data_gcs_path:
try:
storage = StorageService()
storage.delete_file(session.edit_data_gcs_path)
except Exception:
logger.warning(f"Could not delete GCS file for audio edit session {session_id}")
# Delete Firestore doc
firestore_svc.delete_audio_edit_session(job_id, session_id)
return {"status": "deleted", "session_id": session_id}
# ============================================
# Audio Edit Endpoints
# ============================================
def _get_current_audio_gcs_path(job) -> str:
"""Get the GCS path of the current audio (latest edit or original)."""
state_data = job.state_data or {}
edit_stack = state_data.get('audio_edit_stack', [])
if edit_stack:
return edit_stack[-1]['gcs_path']
return job.input_media_gcs_path
def _build_audio_edit_response(
job_id: str,
gcs_path: str,
edit_stack: list,
redo_stack: list,
edit_id: str | None = None,
) -> dict:
"""Build a standard response for audio edit operations matching AudioEditResponse interface."""
from backend.services.audio_analysis_service import AudioAnalysisService
from backend.services.audio_transcoding_service import AudioTranscodingService
analysis_service = AudioAnalysisService()
transcoding_service = AudioTranscodingService()
# Get waveform data for current audio
amplitudes, duration = analysis_service.get_waveform_data(
gcs_audio_path=gcs_path,
job_id=job_id,
num_points=1000,
)
# Get playback URL (OGG Opus)
playback_url = transcoding_service.get_review_audio_url(gcs_path)
# Build flat response matching frontend AudioEditResponse interface
response = {
"status": "success",
"duration_after": duration,
"current_audio_url": playback_url,
"waveform_data": {"amplitudes": list(amplitudes)},
"edit_stack": [
{
"edit_id": entry.get("edit_id", ""),
"operation": entry.get("operation", ""),
"params": entry.get("params", {}),
"duration_before": entry.get("duration_before", 0),
"duration_after": entry.get("duration_after", entry.get("duration_seconds", 0)),
"timestamp": entry.get("timestamp", ""),
}
for entry in edit_stack
],
"can_undo": len(edit_stack) > 0,
"can_redo": len(redo_stack) > 0,
}
if edit_id is not None:
response["edit_id"] = edit_id
return response
@router.get("/{job_id}/input-audio-info")
async def get_input_audio_info(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""
Get metadata about the input audio for the audio editor UI.
Returns duration, waveform data, playback URL, and edit state.
"""
from backend.services.audio_analysis_service import AudioAnalysisService
from backend.services.audio_transcoding_service import AudioTranscodingService
from backend.services.audio_edit_service import AudioEditService
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
if not job.input_media_gcs_path:
raise HTTPException(status_code=404, detail="No input audio available")
try:
edit_service = AudioEditService()
analysis_service = AudioAnalysisService()
transcoding_service = AudioTranscodingService()
state_data = job.state_data or {}
edit_stack = state_data.get('audio_edit_stack', [])
# Try cached waveform first (pre-generated by download worker), fall back to on-demand
waveform_cache_path = state_data.get('audio_edit_waveform_cache_path')
cached = None
if waveform_cache_path:
cached = analysis_service.load_cached_waveform(waveform_cache_path)
if cached:
orig_amplitudes, orig_duration = cached
logger.info(f"Job {job_id}: Using cached waveform data")
else:
orig_amplitudes, orig_duration = analysis_service.get_waveform_data(
gcs_audio_path=job.input_media_gcs_path,
job_id=job_id,
num_points=1000,
)
original_playback_url = transcoding_service.get_review_audio_url(job.input_media_gcs_path)
# Determine current audio state
current_duration = orig_duration
current_audio_url = original_playback_url
current_waveform = orig_amplitudes
if edit_stack:
current_gcs_path = edit_stack[-1]['gcs_path']
current_waveform, current_duration = analysis_service.get_waveform_data(
gcs_audio_path=current_gcs_path,
job_id=job_id,
num_points=1000,
)
current_audio_url = transcoding_service.get_review_audio_url(current_gcs_path)
# Return flat structure matching AudioEditInfo frontend interface
result = {
"job_id": job_id,
"artist": job.artist,
"title": job.title,
"original_duration_seconds": orig_duration,
"current_duration_seconds": current_duration,
"original_audio_url": original_playback_url,
"current_audio_url": current_audio_url,
"waveform_data": {"amplitudes": list(current_waveform)},
"original_waveform_data": {"amplitudes": list(orig_amplitudes)},
"edit_stack": [
{
"edit_id": entry.get("edit_id", ""),
"operation": entry.get("operation", ""),
"params": entry.get("params", {}),
"duration_before": entry.get("duration_before", 0),
"duration_after": entry.get("duration_after", 0),
"timestamp": entry.get("timestamp", ""),
}
for entry in edit_stack
],
"can_undo": len(edit_stack) > 0,
"can_redo": len(state_data.get('audio_edit_redo_stack', [])) > 0,
}
return result
except Exception as e:
logger.error(f"Job {job_id}: Error getting input audio info: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error getting audio info: {str(e)}")
@router.post("/{job_id}/audio-edit/apply")
async def apply_audio_edit(
job_id: str,
request: Request,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""
Apply an edit operation to the input audio.
Supported operations: trim_start, trim_end, cut, mute, join_start, join_end.
Returns updated waveform data and playback URL.
"""
import uuid
from backend.services.audio_edit_service import AudioEditService
body = await request.json()
operation = body.get("operation")
params = body.get("params", {})
edit_id = body.get("edit_id") or str(uuid.uuid4())
if not operation:
raise HTTPException(status_code=400, detail="Missing 'operation' field")
valid_operations = {"trim_start", "trim_end", "cut", "mute", "join_start", "join_end"}
if operation not in valid_operations:
raise HTTPException(status_code=400, detail=f"Invalid operation: {operation}. Valid: {valid_operations}")
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
# Transition to IN_AUDIO_EDIT if not already
if job.status == JobStatus.AWAITING_AUDIO_EDIT:
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.IN_AUDIO_EDIT,
progress=15,
message="Audio editing in progress"
)
# Resolve upload_id to GCS path for join operations
if operation in ("join_start", "join_end"):
upload_id = params.get("upload_id")
if not upload_id:
raise HTTPException(status_code=400, detail="Missing 'upload_id' for join operation")
state_data = job.state_data or {}
uploads = state_data.get('audio_edit_uploads', {})
upload_info = uploads.get(upload_id)
if not upload_info:
raise HTTPException(status_code=404, detail=f"Upload {upload_id} not found")
params["upload_gcs_path"] = upload_info["gcs_path"]
try:
edit_service = AudioEditService()
# Get current audio path and duration before edit
state_data = job.state_data or {}
existing_stack = state_data.get('audio_edit_stack', [])
current_gcs_path = _get_current_audio_gcs_path(job)
# Determine duration before this edit
if existing_stack:
duration_before = existing_stack[-1].get('duration_seconds', 0)
else:
before_metadata = edit_service.get_metadata_from_gcs(current_gcs_path)
duration_before = before_metadata.duration_seconds
output_gcs_path = f"jobs/{job_id}/audio_edit/edit_{edit_id}.flac"
# Apply the edit
metadata, result_path = edit_service.apply_edit(
input_gcs_path=current_gcs_path,
operation=operation,
params=params,
output_gcs_path=output_gcs_path,
job_id=job_id,
)
# Update edit stack in state_data
edit_stack = list(existing_stack)
edit_stack.append({
"edit_id": edit_id,
"operation": operation,
"params": {k: v for k, v in params.items() if k != "upload_gcs_path"},
"gcs_path": result_path,
"duration_before": duration_before,
"duration_after": metadata.duration_seconds,
"duration_seconds": metadata.duration_seconds,
"timestamp": __import__("datetime").datetime.utcnow().isoformat(),
})
# Clear redo stack on new edit
updated_state_data = {
**state_data,
'audio_edit_stack': edit_stack,
'audio_edit_redo_stack': [],
}
job_manager.update_job(job_id, {'state_data': updated_state_data})
return _build_audio_edit_response(
job_id=job_id,
gcs_path=result_path,
edit_stack=edit_stack,
redo_stack=[],
edit_id=edit_id,
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Job {job_id}: Error applying audio edit: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error applying edit: {str(e)}")
@router.post("/{job_id}/audio-edit/undo")
async def undo_audio_edit(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""Undo the last audio edit operation."""
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
state_data = job.state_data or {}
edit_stack = list(state_data.get('audio_edit_stack', []))
redo_stack = list(state_data.get('audio_edit_redo_stack', []))
if not edit_stack:
raise HTTPException(status_code=400, detail="Nothing to undo")
# Pop from edit stack, push to redo stack
undone_edit = edit_stack.pop()
redo_stack.append(undone_edit)
updated_state_data = {
**state_data,
'audio_edit_stack': edit_stack,
'audio_edit_redo_stack': redo_stack,
}
job_manager.update_job(job_id, {'state_data': updated_state_data})
# Get the now-current audio (previous edit or original)
current_gcs_path = edit_stack[-1]['gcs_path'] if edit_stack else job.input_media_gcs_path
try:
return _build_audio_edit_response(
job_id=job_id,
gcs_path=current_gcs_path,
edit_stack=edit_stack,
redo_stack=redo_stack,
)
except Exception as e:
logger.error(f"Job {job_id}: Error building undo response: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error during undo: {str(e)}")
@router.post("/{job_id}/audio-edit/redo")
async def redo_audio_edit(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""Redo a previously undone audio edit."""
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
state_data = job.state_data or {}
edit_stack = list(state_data.get('audio_edit_stack', []))
redo_stack = list(state_data.get('audio_edit_redo_stack', []))
if not redo_stack:
raise HTTPException(status_code=400, detail="Nothing to redo")
# Pop from redo stack, push to edit stack
redone_edit = redo_stack.pop()
edit_stack.append(redone_edit)
updated_state_data = {
**state_data,
'audio_edit_stack': edit_stack,
'audio_edit_redo_stack': redo_stack,
}
job_manager.update_job(job_id, {'state_data': updated_state_data})
current_gcs_path = edit_stack[-1]['gcs_path']
try:
return _build_audio_edit_response(
job_id=job_id,
gcs_path=current_gcs_path,
edit_stack=edit_stack,
redo_stack=redo_stack,
)
except Exception as e:
logger.error(f"Job {job_id}: Error building redo response: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error during redo: {str(e)}")
@router.post("/{job_id}/audio-edit/upload")
async def upload_audio_for_join(
job_id: str,
request: Request,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""
Upload additional audio for join operations.
Accepts multipart form upload. Returns upload_id and metadata.
"""
import uuid
from fastapi import UploadFile
from backend.services.audio_edit_service import AudioEditService
from backend.services.audio_analysis_service import AudioAnalysisService
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
# Parse multipart form
form = await request.form()
file = form.get("file")
if not file:
raise HTTPException(status_code=400, detail="Missing 'file' in form data")
# Validate file extension
filename = getattr(file, 'filename', 'unknown')
valid_extensions = {'.flac', '.wav', '.mp3', '.m4a', '.ogg'}
ext = os.path.splitext(filename)[1].lower()
if ext not in valid_extensions:
raise HTTPException(
status_code=400,
detail=f"Invalid file type '{ext}'. Accepted: {', '.join(valid_extensions)}"
)
upload_id = str(uuid.uuid4())
gcs_path = f"jobs/{job_id}/audio_edit/upload_{upload_id}{ext}"
try:
storage = StorageService()
edit_service = AudioEditService()
analysis_service = AudioAnalysisService()
# Save uploaded file to GCS
content = await file.read()
with tempfile.NamedTemporaryFile(suffix=ext, delete=False) as tmp:
tmp.write(content)
tmp_path = tmp.name
try:
storage.upload_file(tmp_path, gcs_path)
# Get metadata
metadata = edit_service.get_metadata(tmp_path)
# Get waveform data
from karaoke_gen.instrumental_review import WaveformGenerator
waveform_gen = WaveformGenerator()
amplitudes, duration = waveform_gen.generate_data_only(
audio_path=tmp_path,
num_points=1000,
)
finally:
os.unlink(tmp_path)
# Store upload info in state_data
state_data = job.state_data or {}
uploads = dict(state_data.get('audio_edit_uploads', {}))
uploads[upload_id] = {
"gcs_path": gcs_path,
"duration_seconds": metadata.duration_seconds,
"filename": filename,
}
updated_state_data = {**state_data, 'audio_edit_uploads': uploads}
job_manager.update_job(job_id, {'state_data': updated_state_data})
return {
"upload_id": upload_id,
"duration_seconds": metadata.duration_seconds,
"waveform_data": {
"amplitudes": amplitudes,
"duration": duration,
},
}
except Exception as e:
logger.error(f"Job {job_id}: Error uploading audio for join: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error uploading audio: {str(e)}")
@router.post("/{job_id}/audio-edit/submit")
async def submit_audio_edit(
job_id: str,
request: Request,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""
Finalize the audio edit and continue processing.
Copies the current edited audio to the job's input path,
then triggers audio separation and lyrics transcription workers.
"""
from backend.services.worker_service import get_worker_service
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
state_data = job.state_data or {}
edit_stack = state_data.get('audio_edit_stack', [])
storage = StorageService()
# Save edit log if provided
body = await request.json() if request.headers.get("content-type", "").startswith("application/json") else {}
edit_log = body.get("edit_log")
if edit_log:
edit_log_path = f"jobs/{job_id}/audio_edit/edit_log.json"
storage.upload_json(edit_log_path, edit_log)
logger.info(f"Job {job_id}: Saved audio edit log to {edit_log_path}")
if edit_stack:
# Copy the latest edited audio to the canonical input path
current_edited_path = edit_stack[-1]['gcs_path']
edited_input_path = f"jobs/{job_id}/input/edited.flac"
# Download and re-upload to canonical path
with tempfile.TemporaryDirectory() as temp_dir:
local_path = os.path.join(temp_dir, "edited.flac")
storage.download_file(current_edited_path, local_path)
storage.upload_file(local_path, edited_input_path)
# Update job to use edited audio as input
job_manager.update_job(job_id, {
'input_media_gcs_path': edited_input_path,
})
logger.info(f"Job {job_id}: Audio edit submitted, using edited audio: {edited_input_path}")
else:
logger.info(f"Job {job_id}: Audio edit submitted with no edits, using original audio")
# Transition state
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AUDIO_EDIT_COMPLETE,
progress=18,
message="Audio edit complete, starting processing"
)
# Trigger parallel workers in background so the HTTP response returns immediately.
# The worker triggers involve Cloud Run Job calls that can take 30+ seconds;
# waiting synchronously causes the browser request to time out.
worker_service = get_worker_service()
async def _trigger_workers():
try:
await asyncio.gather(
worker_service.trigger_audio_worker(job_id),
worker_service.trigger_lyrics_worker(job_id),
)
except Exception as e:
logger.error(f"Job {job_id}: Failed to trigger workers after audio edit: {e}")
asyncio.create_task(_trigger_workers())
return {
"status": "success",
"message": "Audio edit saved. Processing will continue with edited audio.",
"job_id": job_id,
"edits_applied": len(edit_stack),
}
+13 -5
View File
@@ -1244,6 +1244,7 @@ async def list_users(
query = query.where(filter=FieldFilter('is_active', '==', True))
# Search by email prefix (case-insensitive via range query)
search = search.strip() if search else None
if search:
search_lower = search.lower()
# Use range query for prefix matching
@@ -1251,16 +1252,23 @@ async def list_users(
query = query.where(filter=FieldFilter('email', '<', search_lower + '\uffff'))
# Sorting
direction = firestore.Query.DESCENDING if sort_order == "desc" else firestore.Query.ASCENDING
if sort_by in ["created_at", "last_login_at", "credits", "email"]:
query = query.order_by(sort_by, direction=direction)
else:
query = query.order_by("created_at", direction=direction)
# When search is active, Firestore range filters on 'email' conflict with
# order_by on a different field (requires composite index). Since we already
# fetch all docs and paginate in Python, just sort in Python when searching.
sort_field = sort_by if sort_by in ["created_at", "last_login_at", "credits", "email"] else "created_at"
if not search:
direction = firestore.Query.DESCENDING if sort_order == "desc" else firestore.Query.ASCENDING
query = query.order_by(sort_field, direction=direction)
# Get all docs and filter in Python
# Note: This is expensive for large datasets, consider caching
all_docs = list(query.stream())
# Sort in Python when search is active (can't use Firestore order_by with range filter)
if search:
reverse = sort_order == "desc"
all_docs.sort(key=lambda d: (d.to_dict().get(sort_field) is None, d.to_dict().get(sort_field)), reverse=reverse)
# Filter out test users if exclude_test is True
if exclude_test:
all_docs = [d for d in all_docs if not is_test_email(d.to_dict().get('email', ''))]
+110
View File
@@ -0,0 +1,110 @@
"""
Audio edit session model for persisting input audio editing progress.
Stored as a Firestore subcollection: jobs/{job_id}/audio_edit_sessions/{session_id}
Full edit data is stored in GCS to avoid Firestore's 1MB document limit.
"""
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Optional, Dict, Any, List
import uuid
@dataclass
class AudioEditSessionSummary:
"""Compact summary of operations in an audio edit session, for list views."""
total_operations: int = 0
operations_breakdown: Dict[str, int] = field(default_factory=dict)
duration_change_seconds: float = 0.0
net_duration_seconds: float = 0.0
def to_dict(self) -> Dict[str, Any]:
return {
"total_operations": self.total_operations,
"operations_breakdown": self.operations_breakdown,
"duration_change_seconds": self.duration_change_seconds,
"net_duration_seconds": self.net_duration_seconds,
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "AudioEditSessionSummary":
return cls(
total_operations=data.get("total_operations", 0),
operations_breakdown=data.get("operations_breakdown", {}),
duration_change_seconds=data.get("duration_change_seconds", 0.0),
net_duration_seconds=data.get("net_duration_seconds", 0.0),
)
@dataclass
class AudioEditSession:
"""
A saved snapshot of an audio editing session.
Stored at: jobs/{job_id}/audio_edit_sessions/{session_id}
Edit data stored at: jobs/{job_id}/audio_edit_sessions/{session_id}.json (GCS)
"""
session_id: str = field(default_factory=lambda: str(uuid.uuid4()))
job_id: str = ""
user_email: str = ""
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
updated_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
edit_count: int = 0
trigger: str = "auto" # "auto" | "manual" | "submit"
audio_duration_seconds: Optional[float] = None
original_duration_seconds: Optional[float] = None
artist: Optional[str] = None
title: Optional[str] = None
summary: AudioEditSessionSummary = field(default_factory=AudioEditSessionSummary)
edit_data_gcs_path: str = ""
# Hash of the edit data JSON, used to skip duplicate saves
data_hash: str = ""
def to_dict(self) -> Dict[str, Any]:
return {
"session_id": self.session_id,
"job_id": self.job_id,
"user_email": self.user_email,
"created_at": self.created_at,
"updated_at": self.updated_at,
"edit_count": self.edit_count,
"trigger": self.trigger,
"audio_duration_seconds": self.audio_duration_seconds,
"original_duration_seconds": self.original_duration_seconds,
"artist": self.artist,
"title": self.title,
"summary": self.summary.to_dict(),
"edit_data_gcs_path": self.edit_data_gcs_path,
"data_hash": self.data_hash,
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "AudioEditSession":
created_at = data.get("created_at")
if isinstance(created_at, str):
created_at = datetime.fromisoformat(created_at.rstrip("Z")).replace(tzinfo=timezone.utc)
updated_at = data.get("updated_at")
if isinstance(updated_at, str):
updated_at = datetime.fromisoformat(updated_at.rstrip("Z")).replace(tzinfo=timezone.utc)
summary_data = data.get("summary", {})
summary = AudioEditSessionSummary.from_dict(summary_data) if isinstance(summary_data, dict) else AudioEditSessionSummary()
return cls(
session_id=data.get("session_id", str(uuid.uuid4())),
job_id=data.get("job_id", ""),
user_email=data.get("user_email", ""),
created_at=created_at or datetime.now(timezone.utc),
updated_at=updated_at or datetime.now(timezone.utc),
edit_count=data.get("edit_count", 0),
trigger=data.get("trigger", "auto"),
audio_duration_seconds=data.get("audio_duration_seconds"),
original_duration_seconds=data.get("original_duration_seconds"),
artist=data.get("artist"),
title=data.get("title"),
summary=summary,
edit_data_gcs_path=data.get("edit_data_gcs_path", ""),
data_hash=data.get("data_hash", ""),
)
+14 -2
View File
@@ -16,8 +16,9 @@ class JobStatus(str, Enum):
"""
Job status enumeration - Complete state machine.
The workflow has 7 main stages with 2 human interaction points:
The workflow has 8 main stages with up to 3 human interaction points:
1. Input & Setup (may include audio source selection)
1b. Optional Audio Editing (BLOCKING) - trim/cut/mute/join input audio
2. Parallel Processing (audio + lyrics)
3. Title/End Screen Generation + Backing Vocals Analysis
4. Countdown Padding Synchronization
@@ -39,6 +40,11 @@ class JobStatus(str, Enum):
DOWNLOADING = "downloading" # Downloading from URL or processing upload
# Optional: Audio editing (before processing begins)
AWAITING_AUDIO_EDIT = "awaiting_audio_edit" # ⚠️ WAITING FOR USER - edit input audio
IN_AUDIO_EDIT = "in_audio_edit" # User is actively editing audio
AUDIO_EDIT_COMPLETE = "audio_edit_complete" # User submitted edited audio
# Stage 2a: Audio separation (parallel track 1)
SEPARATING_STAGE1 = "separating_stage1" # Clean instrumental separation (Modal API)
SEPARATING_STAGE2 = "separating_stage2" # Backing vocals separation (Modal API)
@@ -103,7 +109,13 @@ STATE_TRANSITIONS = {
JobStatus.DOWNLOADING_AUDIO: [JobStatus.DOWNLOADING, JobStatus.FAILED],
# DOWNLOADING allows parallel processing (audio + lyrics) and then screens when both complete
JobStatus.DOWNLOADING: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
# Can also enter optional audio edit phase if requires_audio_edit flag is set
JobStatus.DOWNLOADING: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_AUDIO_EDIT, JobStatus.FAILED],
# Optional audio edit phase (trim, cut, mute, join input audio before processing)
JobStatus.AWAITING_AUDIO_EDIT: [JobStatus.IN_AUDIO_EDIT, JobStatus.AUDIO_EDIT_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
JobStatus.IN_AUDIO_EDIT: [JobStatus.AWAITING_AUDIO_EDIT, JobStatus.AUDIO_EDIT_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
JobStatus.AUDIO_EDIT_COMPLETE: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
# Audio separation flow
JobStatus.SEPARATING_STAGE1: [JobStatus.SEPARATING_STAGE2, JobStatus.FAILED],
+73 -1
View File
@@ -5,6 +5,7 @@ This service wraps the shared karaoke_gen.instrumental_review module
to provide GCS-integrated audio analysis capabilities.
"""
import json
import logging
import os
import tempfile
@@ -187,7 +188,78 @@ class AudioAnalysisService:
)
return amplitudes, duration
def cache_waveform_data(
self,
gcs_audio_path: str,
job_id: str,
cache_gcs_path: str,
num_points: int = 1000,
) -> tuple[list[float], float]:
"""
Generate waveform data and cache it as JSON in GCS.
Args:
gcs_audio_path: Path to the audio file in GCS
job_id: Job ID for logging
cache_gcs_path: GCS path to store the cached waveform JSON
num_points: Number of data points to generate
Returns:
Tuple of (amplitude_values, duration_seconds)
"""
logger.info(f"[{job_id}] Generating and caching waveform data: {gcs_audio_path}")
amplitudes, duration = self.get_waveform_data(
gcs_audio_path=gcs_audio_path,
job_id=job_id,
num_points=num_points,
)
cache_data = {
"amplitudes": list(amplitudes),
"duration_seconds": duration,
"num_points": num_points,
"source_gcs_path": gcs_audio_path,
}
self.storage_service.upload_json(cache_gcs_path, cache_data)
logger.info(f"[{job_id}] Waveform data cached at {cache_gcs_path}")
return amplitudes, duration
def load_cached_waveform(
self,
cache_gcs_path: str,
) -> Optional[tuple[list[float], float]]:
"""
Load cached waveform data from GCS.
Args:
cache_gcs_path: GCS path to the cached waveform JSON
Returns:
Tuple of (amplitude_values, duration_seconds) or None if not found
"""
try:
if not self.storage_service.file_exists(cache_gcs_path):
return None
with tempfile.TemporaryDirectory() as temp_dir:
local_path = os.path.join(temp_dir, "waveform.json")
self.storage_service.download_file(cache_gcs_path, local_path)
with open(local_path) as f:
data = json.load(f)
amplitudes = data.get("amplitudes", [])
duration = data.get("duration_seconds", 0.0)
if not amplitudes:
return None
return amplitudes, duration
except Exception as e:
logger.warning(f"Failed to load cached waveform from {cache_gcs_path}: {e}")
return None
def generate_waveform_with_mutes(
self,
gcs_audio_path: str,
+180
View File
@@ -0,0 +1,180 @@
"""
Audio editing service — server-side FFmpeg operations for trim, cut, mute, join.
All operations are lossless (FLAC in, FLAC out). Playback URLs use OGG Opus
via the existing AudioTranscodingService.
"""
import logging
import os
import json
import subprocess
import tempfile
from dataclasses import dataclass, asdict
from backend.services.storage_service import StorageService
logger = logging.getLogger(__name__)
@dataclass
class AudioMetadata:
duration_seconds: float
sample_rate: int
channels: int
format: str
file_size_bytes: int
class AudioEditService:
"""Server-side audio editing via FFmpeg."""
def __init__(self, storage_service: StorageService | None = None):
self.storage = storage_service or StorageService()
def get_metadata(self, audio_path: str) -> AudioMetadata:
"""Get audio metadata from a local file using ffprobe."""
cmd = [
"ffprobe", "-v", "quiet", "-print_format", "json",
"-show_format", "-show_streams", audio_path,
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode != 0:
raise RuntimeError(f"ffprobe failed: {result.stderr}")
info = json.loads(result.stdout)
fmt = info.get("format", {})
streams = info.get("streams", [])
audio_stream = next((s for s in streams if s.get("codec_type") == "audio"), {})
return AudioMetadata(
duration_seconds=float(fmt.get("duration", 0)),
sample_rate=int(audio_stream.get("sample_rate", 44100)),
channels=int(audio_stream.get("channels", 2)),
format=fmt.get("format_name", "unknown"),
file_size_bytes=int(fmt.get("size", 0)),
)
def get_metadata_from_gcs(self, gcs_path: str) -> AudioMetadata:
"""Download from GCS and get metadata."""
with tempfile.TemporaryDirectory() as temp_dir:
local_path = os.path.join(temp_dir, "audio")
self.storage.download_file(gcs_path, local_path)
return self.get_metadata(local_path)
def trim_start(self, input_path: str, end_seconds: float, output_path: str) -> AudioMetadata:
"""Remove audio from 0 to end_seconds (skip the first N seconds)."""
self._run_ffmpeg([
"-ss", str(end_seconds),
"-i", input_path,
"-c:a", "flac",
output_path,
])
return self.get_metadata(output_path)
def trim_end(self, input_path: str, start_seconds: float, output_path: str) -> AudioMetadata:
"""Keep audio from 0 to start_seconds (remove from start_seconds to end)."""
self._run_ffmpeg([
"-i", input_path,
"-t", str(start_seconds),
"-c:a", "flac",
output_path,
])
return self.get_metadata(output_path)
def cut_region(self, input_path: str, start: float, end: float, output_path: str) -> AudioMetadata:
"""Remove a region from start to end, joining the remaining parts."""
self._run_ffmpeg([
"-i", input_path,
"-filter_complex",
f"[0]atrim=0:{start},asetpts=PTS-STARTPTS[a];"
f"[0]atrim={end},asetpts=PTS-STARTPTS[b];"
f"[a][b]concat=n=2:v=0:a=1[out]",
"-map", "[out]",
"-c:a", "flac",
output_path,
])
return self.get_metadata(output_path)
def mute_region(self, input_path: str, start: float, end: float, output_path: str) -> AudioMetadata:
"""Silence a region (preserve duration)."""
self._run_ffmpeg([
"-i", input_path,
"-af", f"volume=enable='between(t,{start},{end})':volume=0",
"-c:a", "flac",
output_path,
])
return self.get_metadata(output_path)
def join_audio(self, input_path: str, other_path: str, position: str, output_path: str) -> AudioMetadata:
"""Join two audio files. position: 'start' (prepend other) or 'end' (append other)."""
if position == "start":
first, second = other_path, input_path
else:
first, second = input_path, other_path
self._run_ffmpeg([
"-i", first,
"-i", second,
"-filter_complex", "[0:a][1:a]concat=n=2:v=0:a=1[out]",
"-map", "[out]",
"-c:a", "flac",
output_path,
])
return self.get_metadata(output_path)
def apply_edit(
self,
input_gcs_path: str,
operation: str,
params: dict,
output_gcs_path: str,
job_id: str,
) -> tuple[AudioMetadata, str]:
"""
Apply an edit operation to an audio file in GCS.
Returns (metadata, output_gcs_path).
"""
with tempfile.TemporaryDirectory() as temp_dir:
local_input = os.path.join(temp_dir, "input.flac")
local_output = os.path.join(temp_dir, "output.flac")
# Download current audio
self.storage.download_file(input_gcs_path, local_input)
# Apply the operation
if operation == "trim_start":
metadata = self.trim_start(local_input, params["end_seconds"], local_output)
elif operation == "trim_end":
metadata = self.trim_end(local_input, params["start_seconds"], local_output)
elif operation == "cut":
metadata = self.cut_region(
local_input, params["start_seconds"], params["end_seconds"], local_output
)
elif operation == "mute":
metadata = self.mute_region(
local_input, params["start_seconds"], params["end_seconds"], local_output
)
elif operation in ("join_start", "join_end"):
# Download the upload file
upload_gcs_path = params["upload_gcs_path"]
local_other = os.path.join(temp_dir, "other.flac")
self.storage.download_file(upload_gcs_path, local_other)
position = "start" if operation == "join_start" else "end"
metadata = self.join_audio(local_input, local_other, position, local_output)
else:
raise ValueError(f"Unknown operation: {operation}")
# Upload edited audio
self.storage.upload_file(local_output, output_gcs_path)
logger.info(f"[{job_id}] Applied {operation}, uploaded to {output_gcs_path}")
return metadata, output_gcs_path
def _run_ffmpeg(self, args: list[str]) -> None:
"""Run an ffmpeg command with standard options."""
cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y"] + args
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
if result.returncode != 0:
raise RuntimeError(f"ffmpeg failed (exit {result.returncode}): {result.stderr}")
+110
View File
@@ -11,6 +11,7 @@ from backend.config import settings
from backend.models.job import Job, JobStatus, TimelineEvent
from backend.models.worker_log import WorkerLogEntry
from backend.models.review_session import ReviewSession
from backend.models.audio_edit_session import AudioEditSession
logger = logging.getLogger(__name__)
@@ -887,6 +888,115 @@ class FirestoreService:
logger.error(f"Error searching review sessions: {e}")
return []
# ---- Audio Edit Sessions ----
def save_audio_edit_session(self, job_id: str, session: AudioEditSession) -> str:
"""Save an audio edit session to the subcollection."""
try:
session.job_id = job_id
sessions_ref = self.db.collection(self.collection).document(job_id).collection("audio_edit_sessions")
doc_ref = sessions_ref.document(session.session_id)
doc_ref.set(session.to_dict())
logger.info(f"Saved audio edit session {session.session_id} for job {job_id}")
return session.session_id
except Exception as e:
logger.error(f"Error saving audio edit session for job {job_id}: {e}")
raise
def list_audio_edit_sessions(self, job_id: str) -> List[AudioEditSession]:
"""List all audio edit sessions for a job, ordered by updated_at descending."""
try:
sessions_ref = self.db.collection(self.collection).document(job_id).collection("audio_edit_sessions")
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING)
docs = query.stream()
return [AudioEditSession.from_dict(doc.to_dict()) for doc in docs]
except Exception as e:
logger.error(f"Error listing audio edit sessions for job {job_id}: {e}")
return []
def get_audio_edit_session(self, job_id: str, session_id: str) -> Optional[AudioEditSession]:
"""Get a single audio edit session by ID."""
try:
doc_ref = (
self.db.collection(self.collection)
.document(job_id)
.collection("audio_edit_sessions")
.document(session_id)
)
doc = doc_ref.get()
if not doc.exists:
return None
return AudioEditSession.from_dict(doc.to_dict())
except Exception as e:
logger.error(f"Error getting audio edit session {session_id} for job {job_id}: {e}")
raise
def delete_audio_edit_session(self, job_id: str, session_id: str) -> None:
"""Delete a single audio edit session."""
try:
doc_ref = (
self.db.collection(self.collection)
.document(job_id)
.collection("audio_edit_sessions")
.document(session_id)
)
doc_ref.delete()
logger.info(f"Deleted audio edit session {session_id} for job {job_id}")
except Exception as e:
logger.error(f"Error deleting audio edit session {session_id} for job {job_id}: {e}")
raise
def delete_audio_edit_sessions_subcollection(self, job_id: str, batch_size: int = 500) -> int:
"""Delete all audio edit sessions for a job (used when deleting a job)."""
try:
sessions_ref = self.db.collection(self.collection).document(job_id).collection("audio_edit_sessions")
deleted_count = 0
while True:
docs = sessions_ref.limit(batch_size).stream()
deleted_in_batch = 0
batch = self.db.batch()
for doc in docs:
batch.delete(doc.reference)
deleted_in_batch += 1
if deleted_in_batch == 0:
break
batch.commit()
deleted_count += deleted_in_batch
if deleted_in_batch < batch_size:
break
if deleted_count > 0:
logger.info(f"Deleted {deleted_count} audio edit sessions for job {job_id}")
return deleted_count
except Exception as e:
logger.error(f"Error deleting audio edit sessions subcollection for job {job_id}: {e}")
return 0
def get_latest_audio_edit_session_hash(self, job_id: str) -> Optional[str]:
"""Get the data_hash of the most recent audio edit session for deduplication."""
try:
sessions_ref = self.db.collection(self.collection).document(job_id).collection("audio_edit_sessions")
query = (
sessions_ref
.order_by("updated_at", direction=firestore.Query.DESCENDING)
.limit(1)
.select(["data_hash"])
)
docs = list(query.stream())
if docs:
return docs[0].to_dict().get("data_hash", "")
return None
except Exception as e:
logger.error(f"Error getting latest audio edit session hash for job {job_id}: {e}")
return None
def delete_search_session(self, session_id: str) -> None:
"""Delete a search session after it has been consumed by job creation.
+8
View File
@@ -22,6 +22,9 @@ STATUSES_BEFORE_AUDIO_START = {
JobStatus.PENDING,
JobStatus.SEARCHING_AUDIO,
JobStatus.AWAITING_AUDIO_SELECTION,
JobStatus.AWAITING_AUDIO_EDIT,
JobStatus.IN_AUDIO_EDIT,
JobStatus.AUDIO_EDIT_COMPLETE,
}
# Jobs in these statuses should NOT have lyrics_complete flag set
@@ -29,6 +32,9 @@ STATUSES_BEFORE_LYRICS_START = {
JobStatus.PENDING,
JobStatus.SEARCHING_AUDIO,
JobStatus.AWAITING_AUDIO_SELECTION,
JobStatus.AWAITING_AUDIO_EDIT,
JobStatus.IN_AUDIO_EDIT,
JobStatus.AUDIO_EDIT_COMPLETE,
}
# Statuses where screens_progress.stage='complete' is valid
@@ -185,11 +191,13 @@ def get_worker_valid_statuses() -> Dict[str, List[JobStatus]]:
"audio_worker": [
JobStatus.DOWNLOADING,
JobStatus.DOWNLOADING_AUDIO,
JobStatus.AUDIO_EDIT_COMPLETE,
JobStatus.SEPARATING_STAGE1,
JobStatus.SEPARATING_STAGE2,
],
"lyrics_worker": [
JobStatus.DOWNLOADING,
JobStatus.AUDIO_EDIT_COMPLETE,
JobStatus.TRANSCRIBING,
JobStatus.CORRECTING,
],
+23 -5
View File
@@ -350,6 +350,14 @@ class JobManager:
except Exception as e:
logger.warning(f"Error deleting logs subcollection for job {job_id}: {e}")
# Delete audio edit sessions subcollection
try:
deleted_sessions = self.firestore.delete_audio_edit_sessions_subcollection(job_id)
if deleted_sessions > 0:
logger.info(f"Deleted {deleted_sessions} audio edit sessions for job {job_id}")
except Exception as e:
logger.warning(f"Error deleting audio edit sessions for job {job_id}: {e}")
self.firestore.delete_job(job_id)
logger.info(f"Deleted job {job_id}")
@@ -446,9 +454,9 @@ class JobManager:
if progress is not None:
updates['progress'] = progress
# Generate review token when entering AWAITING_REVIEW state
# Generate review token when entering blocking states that need user action
# Tokens don't expire - they're job-scoped so low risk, and natural expiry happens when job completes
if new_status == JobStatus.AWAITING_REVIEW:
if new_status in (JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_AUDIO_EDIT):
from backend.api.dependencies import generate_review_token
review_token = generate_review_token()
updates['review_token'] = review_token
@@ -531,10 +539,15 @@ class JobManager:
self._send_push_notification(job, "complete")
# Idle reminder scheduling for blocking states
elif new_status in [JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION]:
elif new_status in [JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION, JobStatus.AWAITING_AUDIO_EDIT]:
self._schedule_idle_reminder(job, new_status)
# Send push notification for blocking states
action_type = "lyrics" if new_status == JobStatus.AWAITING_REVIEW else "instrumental"
if new_status == JobStatus.AWAITING_AUDIO_EDIT:
action_type = "audio_edit"
elif new_status == JobStatus.AWAITING_REVIEW:
action_type = "lyrics"
else:
action_type = "instrumental"
self._send_push_notification(job, action_type)
except Exception as e:
@@ -621,7 +634,12 @@ class JobManager:
# Record when we entered blocking state (for idle detection)
blocking_entered_at = datetime.utcnow().isoformat()
action_type = "lyrics" if new_status == JobStatus.AWAITING_REVIEW else "instrumental"
if new_status == JobStatus.AWAITING_AUDIO_EDIT:
action_type = "audio_edit"
elif new_status == JobStatus.AWAITING_REVIEW:
action_type = "lyrics"
else:
action_type = "instrumental"
# Update state_data with blocking state info (handle None state_data)
existing_state_data = job.state_data or {}
@@ -61,6 +61,10 @@ class JobNotificationService:
# Use hash-based routing for static hosting compatibility
return f"{self.frontend_url}/app/jobs#/{job_id}/instrumental"
def _build_audio_edit_url(self, job_id: str) -> str:
"""Build the audio edit URL for a job."""
return f"{self.frontend_url}/app/jobs#/{job_id}/audio-edit"
async def send_job_completion_email(
self,
job_id: str,
@@ -213,6 +217,7 @@ class JobNotificationService:
action_type: Type of action needed:
- "lyrics": Combined review (lyrics + instrumental selection) for normal jobs
- "instrumental": Instrumental-only selection for finalise-only jobs
- "audio_edit": Audio editing before processing begins
user_name: User's display name
artist: Artist name
title: Song title
@@ -249,6 +254,15 @@ class JobNotificationService:
title=title,
instrumental_url=instrumental_url,
)
elif action_type == "audio_edit":
audio_edit_url = self._build_audio_edit_url(job_id)
# Reuse the lyrics template but with the audio edit URL and different subject
message_content = self.template_service.render_action_needed_lyrics(
name=user_name,
artist=artist,
title=title,
review_url=audio_edit_url,
)
else:
logger.error(f"Unknown action type: {action_type}")
return False
@@ -0,0 +1,279 @@
"""
Unit tests for admin audio edit review endpoints.
Tests the GET /api/admin/audio-edit-reviews and
GET /api/admin/audio-edit-reviews/{job_id} endpoints.
"""
import pytest
from unittest.mock import Mock, patch, AsyncMock
from fastapi.testclient import TestClient
from fastapi import FastAPI
from datetime import datetime, timezone
from backend.api.routes.admin import router
from backend.api.dependencies import require_admin
from backend.models.job import Job, JobStatus
from backend.models.audio_edit_session import AudioEditSession, AudioEditSessionSummary
# Create a test app with the admin router
app = FastAPI()
app.include_router(router, prefix="/api")
def get_mock_admin():
"""Override for require_admin dependency."""
from backend.api.dependencies import AuthResult, UserType
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=999,
message="Admin authenticated",
user_email="admin@example.com",
is_admin=True,
)
app.dependency_overrides[require_admin] = get_mock_admin
@pytest.fixture
def client():
return TestClient(app)
def _make_audio_edit_job_doc(job_id, artist="Test Artist", title="Test Song",
user_email="user@example.com", status="complete",
has_edit_stack=True):
"""Create a mock Firestore document for a job with audio edits."""
doc = Mock()
doc.id = job_id
now = datetime.now(timezone.utc)
state_data = {}
if has_edit_stack:
state_data["audio_edit_stack"] = [
{"edit_id": "e1", "operation": "cut", "gcs_path": f"jobs/{job_id}/edits/e1.flac"}
]
doc.to_dict.return_value = {
"artist": artist,
"title": title,
"user_email": user_email,
"status": status,
"state_data": state_data,
"file_urls": {},
"created_at": now,
"updated_at": now,
}
return doc
def _make_session(job_id, trigger="auto", edit_count=3):
"""Create a mock AudioEditSession."""
return AudioEditSession(
session_id="sess-1",
job_id=job_id,
user_email="user@example.com",
edit_count=edit_count,
trigger=trigger,
audio_duration_seconds=150.0,
original_duration_seconds=225.0,
artist="Test Artist",
title="Test Song",
summary=AudioEditSessionSummary(
total_operations=edit_count,
operations_breakdown={"cut": 2, "mute": 1},
duration_change_seconds=-75.0,
net_duration_seconds=150.0,
),
)
class TestListAudioEditReviews:
"""Tests for GET /api/admin/audio-edit-reviews."""
@patch("backend.services.firestore_service.FirestoreService")
@patch("backend.api.routes.admin.get_user_service")
def test_list_returns_jobs_with_edit_stacks(self, mock_get_user_service, MockFS, client):
"""Jobs with audio edit stacks should appear."""
mock_db = Mock()
mock_get_user_service.return_value.db = mock_db
docs = [
_make_audio_edit_job_doc("job-1", has_edit_stack=True),
_make_audio_edit_job_doc("job-2", has_edit_stack=False),
]
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
# job-2 has no edit stack and no sessions subcollection
sessions_ref = Mock()
sessions_ref.limit.return_value.stream.return_value = iter([])
mock_db.collection.return_value.document.return_value.collection.return_value = sessions_ref
# Sessions for job-1
MockFS.return_value.list_audio_edit_sessions.return_value = [
_make_session("job-1")
]
response = client.get("/api/admin/audio-edit-reviews")
assert response.status_code == 200
data = response.json()
assert data["total"] == 1
assert data["reviews"][0]["job_id"] == "job-1"
assert data["reviews"][0]["session_count"] == 1
assert data["reviews"][0]["total_edits"] == 3
@patch("backend.services.firestore_service.FirestoreService")
@patch("backend.api.routes.admin.get_user_service")
def test_list_search_filter(self, mock_get_user_service, MockFS, client):
"""Search should filter by artist, title, and email."""
mock_db = Mock()
mock_get_user_service.return_value.db = mock_db
docs = [
_make_audio_edit_job_doc("job-1", artist="Beatles", title="Hey Jude"),
_make_audio_edit_job_doc("job-2", artist="Queen", title="Bohemian Rhapsody"),
]
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
MockFS.return_value.list_audio_edit_sessions.return_value = [_make_session("job-1")]
response = client.get("/api/admin/audio-edit-reviews?search=beatles")
assert response.status_code == 200
data = response.json()
assert data["total"] == 1
assert data["reviews"][0]["artist"] == "Beatles"
@patch("backend.services.firestore_service.FirestoreService")
@patch("backend.api.routes.admin.get_user_service")
def test_list_pagination(self, mock_get_user_service, MockFS, client):
"""Pagination should work with offset and limit."""
mock_db = Mock()
mock_get_user_service.return_value.db = mock_db
docs = [_make_audio_edit_job_doc(f"job-{i}") for i in range(5)]
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
MockFS.return_value.list_audio_edit_sessions.return_value = []
response = client.get("/api/admin/audio-edit-reviews?limit=2&offset=0")
data = response.json()
assert len(data["reviews"]) == 2
assert data["total"] == 5
assert data["has_more"] is True
@patch("backend.services.firestore_service.FirestoreService")
@patch("backend.api.routes.admin.get_user_service")
def test_list_exclude_test_emails(self, mock_get_user_service, MockFS, client):
"""Test emails should be excluded when exclude_test=true."""
mock_db = Mock()
mock_get_user_service.return_value.db = mock_db
docs = [
_make_audio_edit_job_doc("job-1", user_email="real@example.com"),
_make_audio_edit_job_doc("job-2", user_email="test@inbox.testmail.app"),
]
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
MockFS.return_value.list_audio_edit_sessions.return_value = []
response = client.get("/api/admin/audio-edit-reviews?exclude_test=true")
data = response.json()
assert data["total"] == 1
assert data["reviews"][0]["user_email"] == "real@example.com"
@patch("backend.services.firestore_service.FirestoreService")
@patch("backend.api.routes.admin.get_user_service")
def test_list_includes_in_audio_edit_jobs(self, mock_get_user_service, MockFS, client):
"""Jobs in audio edit statuses should appear even without edit stack."""
mock_db = Mock()
mock_get_user_service.return_value.db = mock_db
docs = [
_make_audio_edit_job_doc("job-1", status="in_audio_edit", has_edit_stack=False),
]
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
MockFS.return_value.list_audio_edit_sessions.return_value = []
response = client.get("/api/admin/audio-edit-reviews")
data = response.json()
assert data["total"] == 1
assert data["reviews"][0]["job_id"] == "job-1"
class TestGetAudioEditReviewDetail:
"""Tests for GET /api/admin/audio-edit-reviews/{job_id}."""
@patch("backend.api.routes.admin.StorageService")
@patch("backend.api.routes.admin.JobManager")
def test_returns_404_for_missing_job(self, MockJobManager, MockStorage, client):
MockJobManager.return_value.get_job.return_value = None
response = client.get("/api/admin/audio-edit-reviews/nonexistent")
assert response.status_code == 404
@patch("backend.services.audio_transcoding_service.AudioTranscodingService")
@patch("backend.services.firestore_service.FirestoreService")
@patch("backend.api.routes.admin.StorageService")
@patch("backend.api.routes.admin.JobManager")
def test_returns_full_detail(self, MockJobManager, MockStorage, MockFS, MockTranscoding, client):
"""Should return job metadata, sessions, edit stack, and audio URLs."""
job = Mock(spec=Job)
job.job_id = "test-job"
job.artist = "Test Artist"
job.title = "Test Song"
job.user_email = "user@example.com"
job.status = JobStatus.COMPLETE
job.created_at = datetime(2026, 3, 1, tzinfo=timezone.utc)
job.updated_at = datetime(2026, 3, 2, tzinfo=timezone.utc)
job.input_media_gcs_path = "jobs/test-job/input/edited.flac"
job.state_data = {
"audio_edit_stack": [
{"edit_id": "e1", "operation": "cut", "gcs_path": "jobs/test-job/edits/e1.flac",
"duration_before": 225, "duration_after": 150, "timestamp": "2026-03-01T10:00:00"},
],
"original_input_media_gcs_path": "jobs/test-job/input/original.flac",
}
MockJobManager.return_value.get_job.return_value = job
storage = MockStorage.return_value
storage.file_exists.return_value = False
session = _make_session("test-job", trigger="submit")
MockFS.return_value.list_audio_edit_sessions.return_value = [session]
response = client.get("/api/admin/audio-edit-reviews/test-job")
assert response.status_code == 200
data = response.json()
assert data["job"]["job_id"] == "test-job"
assert data["job"]["artist"] == "Test Artist"
assert len(data["sessions"]) == 1
assert data["sessions"][0]["trigger"] == "submit"
assert len(data["edit_stack"]) == 1
assert data["edit_stack"][0]["operation"] == "cut"
@patch("backend.services.firestore_service.FirestoreService")
@patch("backend.api.routes.admin.StorageService")
@patch("backend.api.routes.admin.JobManager")
def test_handles_empty_state_gracefully(self, MockJobManager, MockStorage, MockFS, client):
"""Should handle jobs with no edit data gracefully."""
job = Mock(spec=Job)
job.job_id = "test-job"
job.artist = "Test"
job.title = "Song"
job.user_email = "u@e.com"
job.status = JobStatus.AWAITING_AUDIO_EDIT
job.created_at = None
job.updated_at = None
job.input_media_gcs_path = None
job.state_data = {}
MockJobManager.return_value.get_job.return_value = job
storage = MockStorage.return_value
storage.file_exists.return_value = False
MockFS.return_value.list_audio_edit_sessions.return_value = []
response = client.get("/api/admin/audio-edit-reviews/test-job")
assert response.status_code == 200
data = response.json()
assert data["sessions"] == []
assert data["edit_stack"] == []
assert data["edit_log"] is None
+100
View File
@@ -1016,3 +1016,103 @@ class TestResetEndpointWithRealJobData:
assert response.status_code == 200
assert response.json()["status"] == "success"
assert response.json()["new_status"] == "pending"
class TestResetJobToAwaitingAudioEdit:
"""Tests for resetting job to AWAITING_AUDIO_EDIT state."""
def test_reset_to_awaiting_audio_edit_success(self, client, mock_job):
"""Test resetting a job to awaiting_audio_edit."""
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
mock_jm = Mock()
mock_jm.get_job.return_value = mock_job
mock_jm.update_job.return_value = None
mock_jm_class.return_value = mock_jm
response = client.post(
"/api/admin/jobs/test-job-123/reset",
json={"target_state": "awaiting_audio_edit"},
)
assert response.status_code == 200
data = response.json()
assert data["new_status"] == "awaiting_audio_edit"
def test_reset_clears_edit_stack_and_downstream_flags(self, client):
"""Test that resetting clears audio edit state and downstream processing flags."""
from datetime import UTC
job = Job(
job_id="test-job-123",
status=JobStatus.COMPLETE,
artist="Test",
title="Song",
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
state_data={
"audio_edit_stack": [{"edit_id": "e1"}],
"audio_edit_redo_stack": [{"edit_id": "e2"}],
"audio_complete": True,
"lyrics_complete": True,
"review_complete": True,
"screens_progress": {"stage": "complete"},
}
)
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
mock_jm = Mock()
mock_jm.get_job.return_value = job
mock_jm.update_job.return_value = None
mock_jm_class.return_value = mock_jm
response = client.post(
"/api/admin/jobs/test-job-123/reset",
json={"target_state": "awaiting_audio_edit"},
)
assert response.status_code == 200
data = response.json()
cleared = data.get("cleared_data", [])
assert "audio_edit_stack" in cleared
assert "audio_edit_redo_stack" in cleared
assert "audio_complete" in cleared
assert "lyrics_complete" in cleared
assert "review_complete" in cleared
assert "screens_progress" in cleared
def test_reset_restores_original_input_media_path(self, client):
"""Critical test: resetting to audio edit must restore the original
input_media_gcs_path. The submit endpoint overwrites this with edited
audio, so the reset must undo that to let the user start fresh."""
from datetime import UTC
job = Job(
job_id="test-job-123",
status=JobStatus.COMPLETE,
artist="Test",
title="Song",
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
input_media_gcs_path="jobs/test-job-123/input/edited.flac",
state_data={
"original_input_media_gcs_path": "jobs/test-job-123/input/original.flac",
"audio_edit_stack": [{"edit_id": "e1"}],
}
)
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
mock_jm = Mock()
mock_jm.get_job.return_value = job
mock_jm.update_job.return_value = None
mock_jm_class.return_value = mock_jm
response = client.post(
"/api/admin/jobs/test-job-123/reset",
json={"target_state": "awaiting_audio_edit"},
)
assert response.status_code == 200
# Verify the Firestore update included restoring the original path
# The update goes through job_ref.update() which is the mock_db call
# We check the update_job call for status change
update_args = mock_jm.update_job.call_args[0][1]
assert update_args["status"] == "awaiting_audio_edit"
@@ -5,7 +5,9 @@ These tests mock the storage service and shared karaoke_gen modules to verify:
- GCS file download/upload operations
- Audio analysis delegation to shared AudioAnalyzer
- Waveform generation delegation to shared WaveformGenerator
- Waveform data caching (cache_waveform_data / load_cached_waveform)
"""
import json
import pytest
from unittest.mock import Mock, MagicMock, patch, ANY
import tempfile
@@ -292,3 +294,119 @@ class TestGenerateWaveformWithMutes:
# Verify return
assert result_path == "uploads/job123/waveform_muted.png"
class TestCacheWaveformData:
"""Test cache_waveform_data method."""
@patch("backend.services.audio_analysis_service.StorageService")
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
@patch("backend.services.audio_analysis_service.WaveformGenerator")
def test_caches_waveform_to_gcs(
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
):
"""cache_waveform_data should generate waveform and upload JSON to GCS."""
from backend.services.audio_analysis_service import AudioAnalysisService
mock_storage = Mock()
mock_storage_class.return_value = mock_storage
mock_waveform = Mock()
mock_waveform.generate_data_only.return_value = ([0.1, 0.5, 0.3], 200.0)
mock_waveform_class.return_value = mock_waveform
service = AudioAnalysisService()
amplitudes, duration = service.cache_waveform_data(
gcs_audio_path="jobs/j1/input/song.flac",
job_id="j1",
cache_gcs_path="jobs/j1/audio_edit/waveform_original.json",
num_points=1000,
)
assert amplitudes == [0.1, 0.5, 0.3]
assert duration == 200.0
# Verify JSON was uploaded with correct structure
mock_storage.upload_json.assert_called_once()
call_args = mock_storage.upload_json.call_args
assert call_args[0][0] == "jobs/j1/audio_edit/waveform_original.json"
uploaded_data = call_args[0][1]
assert uploaded_data["amplitudes"] == [0.1, 0.5, 0.3]
assert uploaded_data["duration_seconds"] == 200.0
assert uploaded_data["num_points"] == 1000
assert uploaded_data["source_gcs_path"] == "jobs/j1/input/song.flac"
class TestLoadCachedWaveform:
"""Test load_cached_waveform method."""
@patch("backend.services.audio_analysis_service.StorageService")
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
@patch("backend.services.audio_analysis_service.WaveformGenerator")
def test_returns_none_when_cache_missing(
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
):
"""Should return None when cache file doesn't exist."""
from backend.services.audio_analysis_service import AudioAnalysisService
mock_storage = Mock()
mock_storage.file_exists.return_value = False
mock_storage_class.return_value = mock_storage
service = AudioAnalysisService()
result = service.load_cached_waveform("jobs/j1/audio_edit/waveform_original.json")
assert result is None
@patch("backend.services.audio_analysis_service.StorageService")
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
@patch("backend.services.audio_analysis_service.WaveformGenerator")
def test_loads_cached_waveform(
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
):
"""Should load and parse cached waveform JSON from GCS."""
from backend.services.audio_analysis_service import AudioAnalysisService
cache_data = {
"amplitudes": [0.2, 0.6, 0.4],
"duration_seconds": 180.0,
"num_points": 1000,
"source_gcs_path": "jobs/j1/input/song.flac",
}
mock_storage = Mock()
mock_storage.file_exists.return_value = True
# Simulate download_file writing JSON to the local path
def write_json(gcs_path, local_path):
with open(local_path, 'w') as f:
json.dump(cache_data, f)
mock_storage.download_file.side_effect = write_json
mock_storage_class.return_value = mock_storage
service = AudioAnalysisService()
result = service.load_cached_waveform("jobs/j1/audio_edit/waveform_original.json")
assert result is not None
amplitudes, duration = result
assert amplitudes == [0.2, 0.6, 0.4]
assert duration == 180.0
@patch("backend.services.audio_analysis_service.StorageService")
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
@patch("backend.services.audio_analysis_service.WaveformGenerator")
def test_returns_none_on_error(
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
):
"""Should return None gracefully on any error."""
from backend.services.audio_analysis_service import AudioAnalysisService
mock_storage = Mock()
mock_storage.file_exists.return_value = True
mock_storage.download_file.side_effect = Exception("GCS timeout")
mock_storage_class.return_value = mock_storage
service = AudioAnalysisService()
result = service.load_cached_waveform("jobs/j1/audio_edit/waveform_original.json")
assert result is None
@@ -183,6 +183,85 @@ class TestProcessAudioDownload:
assert call_kwargs['source_id'] == 'spotify123'
class TestAudioEditPreGeneration:
"""Tests for pre-generation of editor assets when requires_audio_edit is set."""
@pytest.mark.asyncio
async def test_pregenerates_assets_when_audio_edit_requested(self):
"""Should transcode OGG + cache waveform before transitioning to awaiting_audio_edit."""
job = _make_job(state_data={'requires_audio_edit': True})
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
patch("backend.services.audio_transcoding_service.AudioTranscodingService") as MockTS, \
patch("backend.services.audio_analysis_service.AudioAnalysisService") as MockAS:
mock_jm = MagicMock()
# First get_job returns the initial job, second returns the one with requires_audio_edit
mock_jm.get_job.return_value = job
mock_jm.transition_to_state.return_value = True
mock_jm_cls.return_value = mock_jm
mock_dl.return_value = ("uploads/test-job-123/audio/song.flac", "song.flac")
mock_ts = MagicMock()
MockTS.return_value = mock_ts
mock_as = MagicMock()
mock_as.cache_waveform_data.return_value = ([0.1, 0.5], 200.0)
MockAS.return_value = mock_as
result = await process_audio_download("test-job-123")
assert result is True
# Should have transcoded OGG
mock_ts.transcode_if_needed.assert_called_once_with("uploads/test-job-123/audio/song.flac")
# Should have cached waveform
mock_as.cache_waveform_data.assert_called_once_with(
"uploads/test-job-123/audio/song.flac",
"test-job-123",
"jobs/test-job-123/audio_edit/waveform_original.json",
)
# Should have stored cache path in state_data
mock_jm.update_state_data.assert_any_call(
"test-job-123", "audio_edit_waveform_cache_path",
"jobs/test-job-123/audio_edit/waveform_original.json",
)
# Should have transitioned to awaiting_audio_edit
calls = mock_jm.transition_to_state.call_args_list
assert any(c.kwargs.get('new_status') == JobStatus.AWAITING_AUDIO_EDIT for c in calls)
@pytest.mark.asyncio
async def test_pregeneration_failure_is_nonfatal(self):
"""Pre-generation failure should not prevent the job from reaching awaiting_audio_edit."""
job = _make_job(state_data={'requires_audio_edit': True})
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
patch("backend.services.audio_transcoding_service.AudioTranscodingService") as MockTS:
mock_jm = MagicMock()
mock_jm.get_job.return_value = job
mock_jm.transition_to_state.return_value = True
mock_jm_cls.return_value = mock_jm
mock_dl.return_value = ("uploads/test-job-123/audio/song.flac", "song.flac")
# Transcoding fails
mock_ts = MagicMock()
mock_ts.transcode_if_needed.side_effect = RuntimeError("ffmpeg not found")
MockTS.return_value = mock_ts
result = await process_audio_download("test-job-123")
# Should still succeed and transition to awaiting_audio_edit
assert result is True
calls = mock_jm.transition_to_state.call_args_list
assert any(c.kwargs.get('new_status') == JobStatus.AWAITING_AUDIO_EDIT for c in calls)
class TestDownloadAudio:
"""Tests for _download_audio routing."""
+549
View File
@@ -0,0 +1,549 @@
"""
Tests for audio edit API endpoints in backend/api/routes/review.py.
Tests the 6 new endpoints: input-audio-info, apply, undo, redo, upload, submit.
"""
import pytest
from datetime import datetime, UTC
from unittest.mock import Mock, patch, MagicMock, AsyncMock
from backend.models.job import Job, JobStatus
from backend.services.audio_edit_service import AudioMetadata
NOW = datetime.now(UTC)
# Patch paths - these are imported inside endpoint functions
PATCH_JM = "backend.api.routes.review.JobManager"
PATCH_EDIT_SVC = "backend.services.audio_edit_service.AudioEditService"
PATCH_ANALYSIS_SVC = "backend.services.audio_analysis_service.AudioAnalysisService"
PATCH_TRANSCODE_SVC = "backend.services.audio_transcoding_service.AudioTranscodingService"
PATCH_STORAGE_SVC = "backend.api.routes.review.StorageService"
PATCH_WORKER_SVC = "backend.services.worker_service.get_worker_service"
def _job(**kwargs):
"""Create a Job with required fields filled in."""
defaults = dict(created_at=NOW, updated_at=NOW)
defaults.update(kwargs)
return Job(**defaults)
# --- Fixtures ---
@pytest.fixture(autouse=True)
def _ensure_auth_overrides():
"""Ensure auth overrides are set for every test, even when conftest autouse is fragile."""
from backend.api.dependencies import require_auth, require_admin, require_review_auth
from backend.services.auth_service import UserType, AuthResult
from backend.main import app
async def mock_require_review_auth(job_id: str = "test123"):
return (job_id, "full")
async def mock_require_auth():
return AuthResult(is_valid=True, user_type=UserType.ADMIN, remaining_uses=999,
message="Test", is_admin=True, user_email="test@example.com")
app.dependency_overrides[require_review_auth] = mock_require_review_auth
app.dependency_overrides[require_auth] = mock_require_auth
app.dependency_overrides[require_admin] = mock_require_auth
yield
app.dependency_overrides.pop(require_review_auth, None)
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(require_admin, None)
@pytest.fixture
def mock_job_manager():
with patch(PATCH_JM) as MockJM:
jm = Mock()
MockJM.return_value = jm
yield jm
@pytest.fixture
def mock_services():
"""Mock all service dependencies used by audio edit endpoints."""
with patch(PATCH_EDIT_SVC) as MockES, \
patch(PATCH_ANALYSIS_SVC) as MockAS, \
patch(PATCH_TRANSCODE_SVC) as MockTS:
es = Mock()
MockES.return_value = es
# Default metadata for duration_before lookups
es.get_metadata_from_gcs.return_value = AudioMetadata(
duration_seconds=200.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=30000000,
)
as_inst = Mock()
MockAS.return_value = as_inst
as_inst.get_waveform_data.return_value = ([0.1, 0.5, 0.3], 200.0)
ts = Mock()
MockTS.return_value = ts
ts.get_review_audio_url.return_value = "https://example.com/audio.ogg"
yield {"edit": es, "analysis": as_inst, "transcode": ts}
@pytest.fixture
def audio_edit_job():
"""Job in awaiting_audio_edit state with input media."""
return _job(
job_id="edit-job-1",
status=JobStatus.AWAITING_AUDIO_EDIT,
progress=15,
input_media_gcs_path="jobs/edit-job-1/input/song.flac",
state_data={},
)
@pytest.fixture
def audio_edit_job_with_edits():
"""Job in in_audio_edit state with existing edit stack."""
return _job(
job_id="edit-job-2",
status=JobStatus.IN_AUDIO_EDIT,
progress=15,
input_media_gcs_path="jobs/edit-job-2/input/song.flac",
state_data={
"audio_edit_stack": [
{
"edit_id": "aaa",
"operation": "trim_start",
"params": {"end_seconds": 10.0},
"gcs_path": "jobs/edit-job-2/audio_edit/edit_aaa.flac",
"duration_seconds": 190.0,
"timestamp": "2026-03-08T12:00:00",
}
],
"audio_edit_redo_stack": [],
},
)
# --- GET /input-audio-info ---
class TestGetInputAudioInfo:
def test_returns_audio_info(self, test_client, mock_job_manager, mock_services, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
mock_services["edit"].get_metadata_from_gcs.return_value = AudioMetadata(
duration_seconds=200.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=30000000,
)
resp = test_client.get("/api/review/edit-job-1/input-audio-info")
assert resp.status_code == 200
data = resp.json()
assert data["job_id"] == "edit-job-1"
assert data["original_duration_seconds"] > 0
assert data["current_duration_seconds"] > 0
assert data["original_audio_url"] == "https://example.com/audio.ogg"
assert data["current_audio_url"] == "https://example.com/audio.ogg"
assert data["edit_stack"] == []
assert data["can_undo"] is False
assert "waveform_data" in data
assert "original_waveform_data" in data
def test_returns_edited_audio_when_edits_exist(self, test_client, mock_job_manager, mock_services, audio_edit_job_with_edits):
mock_job_manager.get_job.return_value = audio_edit_job_with_edits
mock_services["edit"].get_metadata_from_gcs.return_value = AudioMetadata(
duration_seconds=200.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=30000000,
)
resp = test_client.get("/api/review/edit-job-2/input-audio-info")
assert resp.status_code == 200
data = resp.json()
assert len(data["edit_stack"]) == 1
assert data["can_undo"] is True
assert data["edit_stack"][0]["edit_id"] == "aaa"
assert data["edit_stack"][0]["operation"] == "trim_start"
def test_404_when_job_not_found(self, test_client, mock_job_manager):
mock_job_manager.get_job.return_value = None
resp = test_client.get("/api/review/nonexistent/input-audio-info")
assert resp.status_code == 404
def test_404_when_no_input_audio(self, test_client, mock_job_manager):
job = _job(job_id="no-audio", status=JobStatus.AWAITING_AUDIO_EDIT,
input_media_gcs_path=None, state_data={})
mock_job_manager.get_job.return_value = job
resp = test_client.get("/api/review/no-audio/input-audio-info")
assert resp.status_code == 404
def test_uses_cached_waveform_when_available(self, test_client, mock_job_manager, mock_services):
"""When waveform cache exists, should use it instead of on-demand generation."""
job = _job(
job_id="cached-job",
status=JobStatus.AWAITING_AUDIO_EDIT,
input_media_gcs_path="jobs/cached-job/input/song.flac",
state_data={"audio_edit_waveform_cache_path": "jobs/cached-job/audio_edit/waveform_original.json"},
)
mock_job_manager.get_job.return_value = job
mock_services["analysis"].load_cached_waveform.return_value = ([0.2, 0.6, 0.4], 180.0)
mock_services["edit"].get_metadata_from_gcs.return_value = AudioMetadata(
duration_seconds=180.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=30000000,
)
resp = test_client.get("/api/review/cached-job/input-audio-info")
assert resp.status_code == 200
data = resp.json()
assert data["original_duration_seconds"] == 180.0
assert data["original_waveform_data"]["amplitudes"] == [0.2, 0.6, 0.4]
# Should have used cache, not on-demand generation
mock_services["analysis"].load_cached_waveform.assert_called_once_with(
"jobs/cached-job/audio_edit/waveform_original.json"
)
mock_services["analysis"].get_waveform_data.assert_not_called()
def test_falls_back_to_on_demand_when_cache_missing(self, test_client, mock_job_manager, mock_services):
"""When waveform cache path is set but cache doesn't exist, should fall back."""
job = _job(
job_id="no-cache-job",
status=JobStatus.AWAITING_AUDIO_EDIT,
input_media_gcs_path="jobs/no-cache-job/input/song.flac",
state_data={"audio_edit_waveform_cache_path": "jobs/no-cache-job/audio_edit/waveform_original.json"},
)
mock_job_manager.get_job.return_value = job
mock_services["analysis"].load_cached_waveform.return_value = None
mock_services["edit"].get_metadata_from_gcs.return_value = AudioMetadata(
duration_seconds=200.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=30000000,
)
resp = test_client.get("/api/review/no-cache-job/input-audio-info")
assert resp.status_code == 200
# Should have fallen back to on-demand
mock_services["analysis"].get_waveform_data.assert_called_once()
def test_on_demand_when_no_cache_path_in_state(self, test_client, mock_job_manager, mock_services, audio_edit_job):
"""Jobs without cache path in state_data should use on-demand generation."""
mock_job_manager.get_job.return_value = audio_edit_job
mock_services["edit"].get_metadata_from_gcs.return_value = AudioMetadata(
duration_seconds=200.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=30000000,
)
resp = test_client.get("/api/review/edit-job-1/input-audio-info")
assert resp.status_code == 200
# No cache path → should not attempt to load cache
mock_services["analysis"].load_cached_waveform.assert_not_called()
mock_services["analysis"].get_waveform_data.assert_called_once()
# --- POST /audio-edit/apply ---
class TestApplyAudioEdit:
def test_apply_trim_start(self, test_client, mock_job_manager, mock_services, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
mock_services["edit"].apply_edit.return_value = (
AudioMetadata(duration_seconds=170.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=25000000),
"jobs/edit-job-1/audio_edit/edit_abc.flac",
)
resp = test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
"operation": "trim_start",
"params": {"end_seconds": 30.0},
"edit_id": "abc",
})
assert resp.status_code == 200
data = resp.json()
assert data["status"] == "success"
assert data["edit_id"] == "abc"
assert data["can_undo"] is True
assert len(data["edit_stack"]) == 1
assert data["edit_stack"][0]["operation"] == "trim_start"
assert "current_audio_url" in data
assert "waveform_data" in data
assert "duration_after" in data
# Should transition to IN_AUDIO_EDIT
mock_job_manager.transition_to_state.assert_called_once()
def test_apply_transitions_to_in_audio_edit(self, test_client, mock_job_manager, mock_services, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
mock_services["edit"].apply_edit.return_value = (
AudioMetadata(duration_seconds=170.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=25000000),
"jobs/edit-job-1/audio_edit/edit_abc.flac",
)
test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
"operation": "trim_start",
"params": {"end_seconds": 30.0},
})
mock_job_manager.transition_to_state.assert_called_once_with(
job_id="edit-job-1",
new_status=JobStatus.IN_AUDIO_EDIT,
progress=15,
message="Audio editing in progress",
)
def test_apply_skips_transition_if_already_in_edit(self, test_client, mock_job_manager, mock_services, audio_edit_job_with_edits):
mock_job_manager.get_job.return_value = audio_edit_job_with_edits
mock_services["edit"].apply_edit.return_value = (
AudioMetadata(duration_seconds=170.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=25000000),
"jobs/edit-job-2/audio_edit/edit_xyz.flac",
)
test_client.post("/api/review/edit-job-2/audio-edit/apply", json={
"operation": "mute",
"params": {"start_seconds": 10.0, "end_seconds": 15.0},
})
mock_job_manager.transition_to_state.assert_not_called()
def test_apply_missing_operation(self, test_client, mock_job_manager, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
resp = test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
"params": {"end_seconds": 30.0},
})
assert resp.status_code == 400
assert "operation" in resp.json()["detail"].lower()
def test_apply_invalid_operation(self, test_client, mock_job_manager, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
resp = test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
"operation": "reverse",
"params": {},
})
assert resp.status_code == 400
assert "Invalid operation" in resp.json()["detail"]
def test_apply_wrong_status(self, test_client, mock_job_manager):
job = _job(job_id="wrong-status", status=JobStatus.COMPLETE,
input_media_gcs_path="jobs/x/input/song.flac", state_data={})
mock_job_manager.get_job.return_value = job
resp = test_client.post("/api/review/wrong-status/audio-edit/apply", json={
"operation": "trim_start",
"params": {"end_seconds": 10.0},
})
assert resp.status_code == 400
assert "not in audio edit state" in resp.json()["detail"]
def test_apply_join_requires_upload_id(self, test_client, mock_job_manager, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
resp = test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
"operation": "join_end",
"params": {},
})
assert resp.status_code == 400
assert "upload_id" in resp.json()["detail"].lower()
def test_apply_join_invalid_upload_id(self, test_client, mock_job_manager, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
resp = test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
"operation": "join_end",
"params": {"upload_id": "nonexistent"},
})
assert resp.status_code == 404
assert "not found" in resp.json()["detail"].lower()
def test_apply_clears_redo_stack(self, test_client, mock_job_manager, mock_services):
"""When applying a new edit, the redo stack should be cleared."""
job = _job(
job_id="redo-clear",
status=JobStatus.IN_AUDIO_EDIT,
input_media_gcs_path="jobs/redo-clear/input/song.flac",
state_data={
"audio_edit_stack": [],
"audio_edit_redo_stack": [{"edit_id": "old", "gcs_path": "old.flac"}],
},
)
mock_job_manager.get_job.return_value = job
mock_services["edit"].apply_edit.return_value = (
AudioMetadata(duration_seconds=180.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=25000000),
"jobs/redo-clear/audio_edit/edit_new.flac",
)
resp = test_client.post("/api/review/redo-clear/audio-edit/apply", json={
"operation": "mute",
"params": {"start_seconds": 5.0, "end_seconds": 10.0},
})
assert resp.status_code == 200
data = resp.json()
assert data["can_redo"] is False
# --- POST /audio-edit/undo ---
class TestUndoAudioEdit:
def test_undo_pops_edit_stack(self, test_client, mock_job_manager, mock_services, audio_edit_job_with_edits):
mock_job_manager.get_job.return_value = audio_edit_job_with_edits
resp = test_client.post("/api/review/edit-job-2/audio-edit/undo")
assert resp.status_code == 200
data = resp.json()
assert len(data["edit_stack"]) == 0
assert data["can_undo"] is False
assert data["can_redo"] is True
# Verify state_data was updated
update_call = mock_job_manager.update_job.call_args[0]
state_data = update_call[1]["state_data"]
assert len(state_data["audio_edit_stack"]) == 0
assert len(state_data["audio_edit_redo_stack"]) == 1
def test_undo_nothing_to_undo(self, test_client, mock_job_manager, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
resp = test_client.post("/api/review/edit-job-1/audio-edit/undo")
assert resp.status_code == 400
assert "Nothing to undo" in resp.json()["detail"]
def test_undo_wrong_status(self, test_client, mock_job_manager):
job = _job(job_id="done", status=JobStatus.COMPLETE, state_data={})
mock_job_manager.get_job.return_value = job
resp = test_client.post("/api/review/done/audio-edit/undo")
assert resp.status_code == 400
# --- POST /audio-edit/redo ---
class TestRedoAudioEdit:
def test_redo_pops_redo_stack(self, test_client, mock_job_manager, mock_services):
job = _job(
job_id="redo-job",
status=JobStatus.IN_AUDIO_EDIT,
input_media_gcs_path="jobs/redo-job/input/song.flac",
state_data={
"audio_edit_stack": [],
"audio_edit_redo_stack": [
{
"edit_id": "bbb",
"operation": "trim_end",
"params": {"end_seconds": 180.0},
"gcs_path": "jobs/redo-job/audio_edit/edit_bbb.flac",
"duration_seconds": 180.0,
}
],
},
)
mock_job_manager.get_job.return_value = job
resp = test_client.post("/api/review/redo-job/audio-edit/redo")
assert resp.status_code == 200
data = resp.json()
assert len(data["edit_stack"]) == 1
assert data["can_undo"] is True
assert data["can_redo"] is False
def test_redo_nothing_to_redo(self, test_client, mock_job_manager, audio_edit_job_with_edits):
mock_job_manager.get_job.return_value = audio_edit_job_with_edits
resp = test_client.post("/api/review/edit-job-2/audio-edit/redo")
assert resp.status_code == 400
assert "Nothing to redo" in resp.json()["detail"]
# --- POST /audio-edit/submit ---
class TestSubmitAudioEdit:
def test_submit_with_edits_copies_audio(self, test_client, mock_job_manager, audio_edit_job_with_edits):
mock_job_manager.get_job.return_value = audio_edit_job_with_edits
with patch(PATCH_STORAGE_SVC) as MockStorage, \
patch(PATCH_WORKER_SVC) as mock_get_ws:
mock_ws = AsyncMock()
mock_get_ws.return_value = mock_ws
resp = test_client.post("/api/review/edit-job-2/audio-edit/submit",
json={})
assert resp.status_code == 200
data = resp.json()
assert data["status"] == "success"
assert data["edits_applied"] == 1
# Should copy edited audio to canonical path
storage_inst = MockStorage.return_value
storage_inst.download_file.assert_called_once()
storage_inst.upload_file.assert_called_once()
# Should update input_media_gcs_path
update_call = mock_job_manager.update_job.call_args[0]
assert update_call[1]["input_media_gcs_path"] == "jobs/edit-job-2/input/edited.flac"
# Should transition to AUDIO_EDIT_COMPLETE
mock_job_manager.transition_to_state.assert_called_once_with(
job_id="edit-job-2",
new_status=JobStatus.AUDIO_EDIT_COMPLETE,
progress=18,
message="Audio edit complete, starting processing",
)
def test_submit_without_edits_uses_original(self, test_client, mock_job_manager, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
with patch(PATCH_STORAGE_SVC) as MockStorage, \
patch(PATCH_WORKER_SVC) as mock_get_ws:
mock_ws = AsyncMock()
mock_get_ws.return_value = mock_ws
resp = test_client.post("/api/review/edit-job-1/audio-edit/submit",
json={})
assert resp.status_code == 200
data = resp.json()
assert data["edits_applied"] == 0
# Should NOT copy any files
MockStorage.return_value.download_file.assert_not_called()
# Should NOT update input_media_gcs_path
mock_job_manager.update_job.assert_not_called()
def test_submit_wrong_status(self, test_client, mock_job_manager):
job = _job(job_id="done", status=JobStatus.COMPLETE, state_data={})
mock_job_manager.get_job.return_value = job
resp = test_client.post("/api/review/done/audio-edit/submit", json={})
assert resp.status_code == 400
def test_submit_job_not_found(self, test_client, mock_job_manager):
mock_job_manager.get_job.return_value = None
resp = test_client.post("/api/review/nonexistent/audio-edit/submit", json={})
assert resp.status_code == 404
# --- Helper function tests ---
class TestHelperFunctions:
def test_get_current_audio_gcs_path_no_edits(self):
from backend.api.routes.review import _get_current_audio_gcs_path
job = _job(
job_id="test",
status=JobStatus.AWAITING_AUDIO_EDIT,
input_media_gcs_path="jobs/test/input/song.flac",
state_data={},
)
assert _get_current_audio_gcs_path(job) == "jobs/test/input/song.flac"
def test_get_current_audio_gcs_path_with_edits(self):
from backend.api.routes.review import _get_current_audio_gcs_path
job = _job(
job_id="test",
status=JobStatus.IN_AUDIO_EDIT,
input_media_gcs_path="jobs/test/input/song.flac",
state_data={
"audio_edit_stack": [
{"gcs_path": "jobs/test/audio_edit/edit_1.flac"},
{"gcs_path": "jobs/test/audio_edit/edit_2.flac"},
],
},
)
assert _get_current_audio_gcs_path(job) == "jobs/test/audio_edit/edit_2.flac"
def test_get_current_audio_gcs_path_empty_state_data(self):
from backend.api.routes.review import _get_current_audio_gcs_path
job = _job(
job_id="test",
status=JobStatus.AWAITING_AUDIO_EDIT,
input_media_gcs_path="jobs/test/input/song.flac",
state_data={},
)
assert _get_current_audio_gcs_path(job) == "jobs/test/input/song.flac"
+320
View File
@@ -0,0 +1,320 @@
"""
Tests for audio_edit_service.py — server-side FFmpeg audio editing.
Tests use mocked subprocess calls since we can't guarantee ffmpeg is
available in CI. Integration tests with real audio files are in a
separate test module.
"""
import json
import os
import pytest
from unittest.mock import Mock, patch, MagicMock, call
from backend.services.audio_edit_service import AudioEditService, AudioMetadata
class TestGetMetadata:
"""Test get_metadata and get_metadata_from_gcs."""
@patch("backend.services.audio_edit_service.subprocess.run")
def test_get_metadata_parses_ffprobe(self, mock_run):
mock_run.return_value = MagicMock(
returncode=0,
stdout=json.dumps({
"format": {
"duration": "245.3",
"format_name": "flac",
"size": "35000000",
},
"streams": [{
"codec_type": "audio",
"sample_rate": "44100",
"channels": 2,
}],
}),
)
service = AudioEditService(storage_service=Mock())
meta = service.get_metadata("/tmp/test.flac")
assert meta.duration_seconds == 245.3
assert meta.sample_rate == 44100
assert meta.channels == 2
assert meta.format == "flac"
assert meta.file_size_bytes == 35000000
@patch("backend.services.audio_edit_service.subprocess.run")
def test_get_metadata_ffprobe_failure(self, mock_run):
mock_run.return_value = MagicMock(
returncode=1,
stderr="ffprobe error",
)
service = AudioEditService(storage_service=Mock())
with pytest.raises(RuntimeError, match="ffprobe failed"):
service.get_metadata("/tmp/test.flac")
@patch("backend.services.audio_edit_service.subprocess.run")
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
def test_get_metadata_from_gcs(self, mock_tmpdir, mock_run):
mock_tmpdir.return_value.__enter__ = Mock(return_value="/tmp/test")
mock_tmpdir.return_value.__exit__ = Mock(return_value=False)
mock_run.return_value = MagicMock(
returncode=0,
stdout=json.dumps({
"format": {"duration": "100.0", "format_name": "flac", "size": "1000"},
"streams": [{"codec_type": "audio", "sample_rate": "44100", "channels": 2}],
}),
)
mock_storage = Mock()
service = AudioEditService(storage_service=mock_storage)
meta = service.get_metadata_from_gcs("jobs/123/input/song.flac")
mock_storage.download_file.assert_called_once()
assert meta.duration_seconds == 100.0
class TestFFmpegOperations:
"""Test trim, cut, mute, join operations via FFmpeg."""
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
def test_trim_start(self, mock_run, mock_meta):
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=200.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=30000000,
)
service = AudioEditService(storage_service=Mock())
result = service.trim_start("/tmp/input.flac", 30.0, "/tmp/output.flac")
# Check ffmpeg was called with -ss
cmd = mock_run.call_args[0][0]
assert "-ss" in cmd
assert "30.0" in cmd
assert result.duration_seconds == 200.0
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
def test_trim_end(self, mock_run, mock_meta):
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=120.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=20000000,
)
service = AudioEditService(storage_service=Mock())
result = service.trim_end("/tmp/input.flac", 120.0, "/tmp/output.flac")
cmd = mock_run.call_args[0][0]
assert "-t" in cmd
assert "120.0" in cmd
assert result.duration_seconds == 120.0
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
def test_cut_region(self, mock_run, mock_meta):
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=180.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=25000000,
)
service = AudioEditService(storage_service=Mock())
result = service.cut_region("/tmp/input.flac", 30.0, 45.0, "/tmp/output.flac")
cmd = mock_run.call_args[0][0]
assert "-filter_complex" in cmd
filter_str = cmd[cmd.index("-filter_complex") + 1]
assert "atrim=0:30.0" in filter_str
assert "atrim=45.0" in filter_str
assert "concat=n=2" in filter_str
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
def test_mute_region(self, mock_run, mock_meta):
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=245.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=35000000,
)
service = AudioEditService(storage_service=Mock())
result = service.mute_region("/tmp/input.flac", 10.0, 15.0, "/tmp/output.flac")
cmd = mock_run.call_args[0][0]
assert "-af" in cmd
af_str = cmd[cmd.index("-af") + 1]
assert "volume=enable='between(t,10.0,15.0)':volume=0" in af_str
assert result.duration_seconds == 245.0 # Duration preserved
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
def test_join_audio_end(self, mock_run, mock_meta):
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=260.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=40000000,
)
service = AudioEditService(storage_service=Mock())
result = service.join_audio("/tmp/main.flac", "/tmp/extra.flac", "end", "/tmp/output.flac")
cmd = mock_run.call_args[0][0]
assert "-filter_complex" in cmd
# For "end", main comes first, extra second
assert cmd[cmd.index("-i") + 1] == "/tmp/main.flac"
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
def test_join_audio_start(self, mock_run, mock_meta):
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=260.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=40000000,
)
service = AudioEditService(storage_service=Mock())
result = service.join_audio("/tmp/main.flac", "/tmp/extra.flac", "start", "/tmp/output.flac")
cmd = mock_run.call_args[0][0]
# For "start", extra comes first, main second
first_input_idx = cmd.index("-i") + 1
assert cmd[first_input_idx] == "/tmp/extra.flac"
@patch("backend.services.audio_edit_service.subprocess.run")
def test_ffmpeg_failure_raises(self, mock_run):
mock_run.return_value = MagicMock(
returncode=1,
stderr="Error: something went wrong",
)
service = AudioEditService(storage_service=Mock())
with pytest.raises(RuntimeError, match="ffmpeg failed"):
service.trim_start("/tmp/input.flac", 30.0, "/tmp/output.flac")
class TestApplyEdit:
"""Test the apply_edit method that orchestrates download/edit/upload."""
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
def test_apply_edit_trim_start(self, mock_tmpdir, mock_run, mock_meta):
mock_tmpdir.return_value.__enter__ = Mock(return_value="/tmp/edit")
mock_tmpdir.return_value.__exit__ = Mock(return_value=False)
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=200.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=30000000,
)
mock_storage = Mock()
service = AudioEditService(storage_service=mock_storage)
metadata, result_path = service.apply_edit(
input_gcs_path="jobs/123/input/song.flac",
operation="trim_start",
params={"end_seconds": 30.0},
output_gcs_path="jobs/123/audio_edit/edit_abc.flac",
job_id="123",
)
mock_storage.download_file.assert_called_once()
mock_storage.upload_file.assert_called_once()
assert result_path == "jobs/123/audio_edit/edit_abc.flac"
assert metadata.duration_seconds == 200.0
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
def test_apply_edit_join_downloads_both_files(self, mock_tmpdir, mock_run, mock_meta):
mock_tmpdir.return_value.__enter__ = Mock(return_value="/tmp/edit")
mock_tmpdir.return_value.__exit__ = Mock(return_value=False)
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=260.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=40000000,
)
mock_storage = Mock()
service = AudioEditService(storage_service=mock_storage)
metadata, result_path = service.apply_edit(
input_gcs_path="jobs/123/input/song.flac",
operation="join_end",
params={"upload_gcs_path": "jobs/123/audio_edit/upload_xyz.flac"},
output_gcs_path="jobs/123/audio_edit/edit_abc.flac",
job_id="123",
)
# Should download both the main audio and the upload
assert mock_storage.download_file.call_count == 2
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
def test_apply_edit_unknown_operation(self, mock_tmpdir):
mock_tmpdir.return_value.__enter__ = Mock(return_value="/tmp/edit")
mock_tmpdir.return_value.__exit__ = Mock(return_value=False)
mock_storage = Mock()
service = AudioEditService(storage_service=mock_storage)
with pytest.raises(ValueError, match="Unknown operation"):
service.apply_edit(
input_gcs_path="jobs/123/input/song.flac",
operation="reverse",
params={},
output_gcs_path="jobs/123/audio_edit/edit_abc.flac",
job_id="123",
)
class TestStateTransitions:
"""Test that new job states and transitions are correctly defined."""
def test_new_states_exist(self):
from backend.models.job import JobStatus
assert hasattr(JobStatus, 'AWAITING_AUDIO_EDIT')
assert hasattr(JobStatus, 'IN_AUDIO_EDIT')
assert hasattr(JobStatus, 'AUDIO_EDIT_COMPLETE')
assert JobStatus.AWAITING_AUDIO_EDIT.value == "awaiting_audio_edit"
assert JobStatus.IN_AUDIO_EDIT.value == "in_audio_edit"
assert JobStatus.AUDIO_EDIT_COMPLETE.value == "audio_edit_complete"
def test_downloading_can_transition_to_awaiting_audio_edit(self):
from backend.models.job import JobStatus, STATE_TRANSITIONS
allowed = STATE_TRANSITIONS[JobStatus.DOWNLOADING]
assert JobStatus.AWAITING_AUDIO_EDIT in allowed
def test_awaiting_audio_edit_transitions(self):
from backend.models.job import JobStatus, STATE_TRANSITIONS
allowed = STATE_TRANSITIONS[JobStatus.AWAITING_AUDIO_EDIT]
assert JobStatus.IN_AUDIO_EDIT in allowed
assert JobStatus.AUDIO_EDIT_COMPLETE in allowed
assert JobStatus.FAILED in allowed
assert JobStatus.CANCELLED in allowed
def test_in_audio_edit_transitions(self):
from backend.models.job import JobStatus, STATE_TRANSITIONS
allowed = STATE_TRANSITIONS[JobStatus.IN_AUDIO_EDIT]
assert JobStatus.AWAITING_AUDIO_EDIT in allowed
assert JobStatus.AUDIO_EDIT_COMPLETE in allowed
assert JobStatus.FAILED in allowed
assert JobStatus.CANCELLED in allowed
def test_audio_edit_complete_continues_to_processing(self):
from backend.models.job import JobStatus, STATE_TRANSITIONS
allowed = STATE_TRANSITIONS[JobStatus.AUDIO_EDIT_COMPLETE]
assert JobStatus.SEPARATING_STAGE1 in allowed
assert JobStatus.TRANSCRIBING in allowed
assert JobStatus.GENERATING_SCREENS in allowed
assert JobStatus.FAILED in allowed
+258
View File
@@ -0,0 +1,258 @@
"""
Tests for audio edit session persistence (Phase 2).
Tests the model, API endpoints, and deduplication logic.
"""
import hashlib
import json
import pytest
from datetime import datetime, UTC, timezone
from unittest.mock import Mock, patch, MagicMock
from backend.models.audio_edit_session import AudioEditSession, AudioEditSessionSummary
from backend.models.job import Job, JobStatus
NOW = datetime.now(UTC)
PATCH_JM = "backend.api.routes.review.JobManager"
PATCH_FS = "backend.api.routes.review.FirestoreService"
PATCH_STORAGE = "backend.api.routes.review.StorageService"
def _job(**kwargs):
defaults = dict(created_at=NOW, updated_at=NOW)
defaults.update(kwargs)
return Job(**defaults)
# --- Model Tests ---
class TestAudioEditSessionModel:
def test_to_dict_and_from_dict_roundtrip(self):
summary = AudioEditSessionSummary(
total_operations=3,
operations_breakdown={"trim_start": 1, "mute": 2},
duration_change_seconds=-15.5,
net_duration_seconds=184.5,
)
session = AudioEditSession(
session_id="test-id",
job_id="job-1",
user_email="user@example.com",
edit_count=3,
trigger="manual",
audio_duration_seconds=184.5,
original_duration_seconds=200.0,
artist="Test Artist",
title="Test Song",
summary=summary,
edit_data_gcs_path="jobs/job-1/audio_edit_sessions/test-id.json",
data_hash="abc123",
)
d = session.to_dict()
restored = AudioEditSession.from_dict(d)
assert restored.session_id == "test-id"
assert restored.job_id == "job-1"
assert restored.edit_count == 3
assert restored.trigger == "manual"
assert restored.audio_duration_seconds == 184.5
assert restored.original_duration_seconds == 200.0
assert restored.artist == "Test Artist"
assert restored.summary.total_operations == 3
assert restored.summary.operations_breakdown == {"trim_start": 1, "mute": 2}
assert restored.data_hash == "abc123"
def test_from_dict_with_string_datetimes(self):
data = {
"session_id": "sid",
"created_at": "2026-03-08T12:00:00",
"updated_at": "2026-03-08T12:30:00",
}
session = AudioEditSession.from_dict(data)
assert session.created_at.year == 2026
assert session.updated_at.minute == 30
def test_from_dict_defaults(self):
session = AudioEditSession.from_dict({})
assert session.edit_count == 0
assert session.trigger == "auto"
assert session.summary.total_operations == 0
def test_summary_to_dict_and_from_dict(self):
s = AudioEditSessionSummary(total_operations=5, operations_breakdown={"cut": 5})
d = s.to_dict()
restored = AudioEditSessionSummary.from_dict(d)
assert restored.total_operations == 5
assert restored.operations_breakdown == {"cut": 5}
# --- API Endpoint Tests ---
@pytest.fixture(autouse=True)
def _ensure_auth_overrides():
"""Ensure auth overrides are set for every test."""
from backend.api.dependencies import require_auth, require_admin, require_review_auth
from backend.services.auth_service import UserType, AuthResult
from backend.main import app
async def mock_require_review_auth(job_id: str = "test123"):
return (job_id, "full")
async def mock_require_auth():
return AuthResult(is_valid=True, user_type=UserType.ADMIN, remaining_uses=999,
message="Test", is_admin=True, user_email="test@example.com")
app.dependency_overrides[require_review_auth] = mock_require_review_auth
app.dependency_overrides[require_auth] = mock_require_auth
app.dependency_overrides[require_admin] = mock_require_auth
yield
app.dependency_overrides.pop(require_review_auth, None)
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(require_admin, None)
@pytest.fixture
def mock_job_manager():
with patch(PATCH_JM) as MockJM:
jm = Mock()
MockJM.return_value = jm
yield jm
@pytest.fixture
def mock_firestore_svc():
with patch(PATCH_FS) as MockFS:
fs = Mock()
MockFS.return_value = fs
yield fs
@pytest.fixture
def mock_storage_svc():
with patch(PATCH_STORAGE) as MockS:
s = Mock()
MockS.return_value = s
yield s
class TestSaveAudioEditSession:
def test_save_new_session(self, test_client, mock_job_manager, mock_firestore_svc, mock_storage_svc):
job = _job(job_id="j1", status=JobStatus.IN_AUDIO_EDIT,
artist="Artist", title="Song", state_data={})
mock_job_manager.get_job.return_value = job
mock_firestore_svc.get_latest_audio_edit_session_hash.return_value = None
edit_data = {"entries": [{"operation": "trim_start", "params": {"end_seconds": 30}}]}
resp = test_client.post("/api/review/j1/audio-edit-sessions", json={
"edit_data": edit_data,
"edit_count": 1,
"trigger": "auto",
"summary": {
"total_operations": 1,
"operations_breakdown": {"trim_start": 1},
"duration_change_seconds": -30.0,
"net_duration_seconds": 170.0,
},
})
assert resp.status_code == 200
data = resp.json()
assert data["status"] == "saved"
assert "session_id" in data
# Should upload to GCS and save to Firestore
mock_storage_svc.upload_json.assert_called_once()
mock_firestore_svc.save_audio_edit_session.assert_called_once()
def test_skip_duplicate_session(self, test_client, mock_job_manager, mock_firestore_svc):
job = _job(job_id="j2", status=JobStatus.IN_AUDIO_EDIT, state_data={})
mock_job_manager.get_job.return_value = job
edit_data = {"entries": []}
data_json = json.dumps(edit_data, sort_keys=True, default=str)
existing_hash = hashlib.sha256(data_json.encode()).hexdigest()
mock_firestore_svc.get_latest_audio_edit_session_hash.return_value = existing_hash
resp = test_client.post("/api/review/j2/audio-edit-sessions", json={
"edit_data": edit_data,
"edit_count": 0,
})
assert resp.status_code == 200
data = resp.json()
assert data["status"] == "skipped"
assert data["reason"] == "identical_data"
def test_save_job_not_found(self, test_client, mock_job_manager):
mock_job_manager.get_job.return_value = None
resp = test_client.post("/api/review/missing/audio-edit-sessions", json={
"edit_data": {},
})
assert resp.status_code == 404
class TestListAudioEditSessions:
def test_list_sessions(self, test_client, mock_firestore_svc):
session = AudioEditSession(
session_id="s1", job_id="j1", edit_count=2,
summary=AudioEditSessionSummary(total_operations=2),
)
mock_firestore_svc.list_audio_edit_sessions.return_value = [session]
resp = test_client.get("/api/review/j1/audio-edit-sessions")
assert resp.status_code == 200
data = resp.json()
assert len(data["sessions"]) == 1
assert data["sessions"][0]["session_id"] == "s1"
def test_list_empty(self, test_client, mock_firestore_svc):
mock_firestore_svc.list_audio_edit_sessions.return_value = []
resp = test_client.get("/api/review/j1/audio-edit-sessions")
assert resp.status_code == 200
assert len(resp.json()["sessions"]) == 0
class TestGetAudioEditSession:
def test_get_with_gcs_data(self, test_client, mock_firestore_svc, mock_storage_svc):
session = AudioEditSession(
session_id="s1", job_id="j1",
edit_data_gcs_path="jobs/j1/audio_edit_sessions/s1.json",
)
mock_firestore_svc.get_audio_edit_session.return_value = session
mock_storage_svc.download_json.return_value = {"entries": [{"op": "trim"}]}
resp = test_client.get("/api/review/j1/audio-edit-sessions/s1")
assert resp.status_code == 200
data = resp.json()
assert data["session_id"] == "s1"
assert data["edit_data"] == {"entries": [{"op": "trim"}]}
def test_get_not_found(self, test_client, mock_firestore_svc):
mock_firestore_svc.get_audio_edit_session.return_value = None
resp = test_client.get("/api/review/j1/audio-edit-sessions/missing")
assert resp.status_code == 404
class TestDeleteAudioEditSession:
def test_delete_session(self, test_client, mock_firestore_svc, mock_storage_svc):
session = AudioEditSession(
session_id="s1", job_id="j1",
edit_data_gcs_path="jobs/j1/audio_edit_sessions/s1.json",
)
mock_firestore_svc.get_audio_edit_session.return_value = session
resp = test_client.delete("/api/review/j1/audio-edit-sessions/s1")
assert resp.status_code == 200
assert resp.json()["status"] == "deleted"
mock_storage_svc.delete_file.assert_called_once_with("jobs/j1/audio_edit_sessions/s1.json")
mock_firestore_svc.delete_audio_edit_session.assert_called_once_with("j1", "s1")
def test_delete_not_found(self, test_client, mock_firestore_svc):
mock_firestore_svc.get_audio_edit_session.return_value = None
resp = test_client.delete("/api/review/j1/audio-edit-sessions/missing")
assert resp.status_code == 404
+54 -4
View File
@@ -271,20 +271,70 @@ class TestWorkerService:
with patch('backend.services.worker_service.httpx.AsyncClient') as mock_client_cls:
mock_client = AsyncMock()
mock_client_cls.return_value.__aenter__.return_value = mock_client
mock_response = Mock()
mock_response.status_code = 200
mock_client.post.return_value = mock_response
worker_service = get_worker_service()
await worker_service.trigger_video_worker("test123")
# Verify HTTP POST was made
mock_client.post.assert_called_once()
call_args = mock_client.post.call_args
assert "/api/internal/workers/video" in str(call_args)
@pytest.mark.asyncio
async def test_trigger_video_worker_routes_to_cloud_run_job(self):
"""Test that video worker routes to Cloud Run Jobs when enabled.
When USE_CLOUD_RUN_JOBS_FOR_VIDEO=true and ENABLE_CLOUD_TASKS=true,
trigger_video_worker should dispatch a Cloud Run Job instead of
posting to the internal HTTP endpoint. This ensures the encoding
orchestrator runs to completion, immune to Cloud Run Service
deployment rollouts (see incident 2026-03-08, job 43c0d519).
"""
from backend.services.worker_service import WorkerService, reset_worker_service
reset_worker_service()
with patch('backend.services.worker_service.get_settings') as mock_settings:
mock_settings.return_value.admin_tokens = "test-token"
mock_settings.return_value.google_cloud_project = "test-project"
mock_settings.return_value.enable_cloud_tasks = True
mock_settings.return_value.gcp_region = "us-central1"
mock_settings.return_value.use_cloud_run_jobs_for_video = True
mock_jobs_client = MagicMock()
mock_operation = MagicMock()
mock_operation.metadata = "test-metadata"
mock_jobs_client.run_job.return_value = mock_operation
mock_run_v2 = MagicMock()
mock_run_v2.JobsClient.return_value = mock_jobs_client
mock_run_v2.RunJobRequest = MagicMock()
mock_run_v2.RunJobRequest.Overrides = MagicMock()
mock_run_v2.RunJobRequest.Overrides.ContainerOverride = MagicMock()
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_video_worker("test123")
assert result is True
mock_jobs_client.run_job.assert_called_once()
# Verify correct Cloud Run Job name
call_args = mock_run_v2.RunJobRequest.call_args
assert call_args is not None
assert "video-encoding-job" in str(call_args)
# Verify job_id is passed via container args override
override_args = mock_run_v2.RunJobRequest.Overrides.ContainerOverride.call_args
assert "--job-id" in str(override_args)
assert "test123" in str(override_args)
class TestWorkerServiceCloudTasks:
"""Test WorkerService Cloud Tasks integration."""
+34
View File
@@ -135,6 +135,40 @@ async def process_audio_download(job_id: str) -> bool:
message="Audio downloaded, starting processing"
)
# Check if audio editing was requested — enter blocking state instead of processing
job = job_manager.get_job(job_id)
if job and job.state_data.get('requires_audio_edit'):
# Preserve the original input path before any edits
job_manager.update_state_data(job_id, 'original_input_media_gcs_path', audio_gcs_path)
# Pre-generate audio editor assets (OGG transcode + waveform data)
# so the editor UI loads instantly. Non-fatal if this fails.
waveform_cache_path = f"jobs/{job_id}/audio_edit/waveform_original.json"
try:
from backend.services.audio_transcoding_service import AudioTranscodingService
from backend.services.audio_analysis_service import AudioAnalysisService
transcoding = AudioTranscodingService()
transcoding.transcode_if_needed(audio_gcs_path)
logger.info(f"[job:{job_id}] Pre-transcoded input audio to OGG for editor")
analysis = AudioAnalysisService()
analysis.cache_waveform_data(audio_gcs_path, job_id, waveform_cache_path)
logger.info(f"[job:{job_id}] Pre-generated waveform data for editor")
job_manager.update_state_data(job_id, 'audio_edit_waveform_cache_path', waveform_cache_path)
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to pre-generate editor assets (non-fatal): {e}")
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_EDIT,
progress=15,
message="Audio downloaded. Please review and edit the audio before processing."
)
logger.info(f"[job:{job_id}] Audio download complete, awaiting audio edit")
return True
# Trigger audio separation and lyrics workers
worker_service = get_worker_service()
await asyncio.gather(
+15 -2
View File
@@ -14,8 +14,11 @@ For UI that renders differently based on data (e.g., audio search result tiers),
### Filename Matching Normalization
When comparing filenames to search titles, treat underscores/hyphens/dots as word separators BEFORE stripping non-alphanumeric chars. Also require a minimum substring length (3 chars) to prevent false matches like filename "K" matching title "KoREH". For non-Latin scripts (Hebrew, etc.), return an indeterminate result rather than a false match or false mismatch.
### Autocomplete UX: Less Is More (Mar 2026)
When adding autocomplete to a multi-field form (artist + title), a single autocomplete on the **primary search field** (title) that overwrites both fields on selection is better than separate autocompletes on each field. Two autocompletes feel "janky" — they compete for attention, spam the backend with double the requests, and confuse users about which one to interact with first. Instead: plain text input for the first field (artist), autocomplete on the second field (title) that only activates when the first field is filled, and selection overwrites both fields with canonical values.
### Song Suggestions: Don't Block Input, Enhance Later (Mar 2026)
Autocomplete on the artist/title input fields confused users — it wasn't clear why they should wait for results or what selecting one would do. Better approach: let users type freely on Step 1, then show catalog suggestions **in parallel with the audio search** on Step 2 (while they're already waiting). This way suggestions feel like a helpful enhancement rather than an obstacle. Two modes work well: (1) exact match → green "Song found" panel for formatting correction, (2) no match + poor audio results → amber "Did you mean?" fuzzy correction banner.
### Fuzzy Search: Artist Tiebreaker for Title-Based Fallback (Mar 2026)
When fuzzy-matching by title returns multiple artists with the same song name (e.g. "Bruises" by Lewis Capaldi vs Fox Stevenson), use the user's garbled artist input as a tiebreaker — `stringSimilarity(userInput, track.artist_name) * 0.2` as a bonus score. Also: Spotify's `q` parameter searches track names, not artist names, so `searchCatalogTracks(artist, artist, 20)` (artist as both query and filter) returns nothing. Use `searchCatalogTracks(artist, undefined, 20)` to get the artist's tracks via general search.
---
@@ -852,6 +855,16 @@ Even with idempotent endpoints (PR #413) and basic retry logic (PR #242), jobs c
**Key insight:** Defense in depth matters. The CI drain prevents *most* conflicts, extended retries handle the *remaining edge cases*, and poll tolerance protects *jobs already in progress*. No single layer is sufficient alone.
### Deployment-Safe Encoding: Cloud Run Jobs (Mar 2026)
The three-layer defense above protects against the **GCE encoding worker** being restarted, but not against the **Cloud Run orchestrator** being killed. Job `43c0d519` (2026-03-08) got stuck because a Cloud Run Service deployment rolled out a new revision while the video worker was running as a `BackgroundTask`. Since the HTTP response had already been sent, Cloud Run treated the request as complete and killed the old instance — terminating the encoding orchestration mid-flight.
**Root cause:** `BackgroundTask` work runs after the HTTP response, so Cloud Run can kill it during deployment drain. The three-layer defense only protects the GCE worker connection, not the orchestrator's lifecycle.
**Fix:** Re-enabled Cloud Run Jobs for video encoding (`USE_CLOUD_RUN_JOBS_FOR_VIDEO=true`). This was built in PR #155 (Dec 2025) but the env var was dropped during the CI migration from `cloudbuild.yaml` to GitHub Actions. Cloud Run Jobs run to completion (up to 24h), immune to Service deployment rollouts.
**Key insight:** When migrating CI systems (cloudbuild.yaml → GitHub Actions), audit env vars carefully. A missing feature flag can silently disable critical protections. The infrastructure (Pulumi) and code existed but were inert without the env var.
---
## What We'd Do Differently
+3 -1
View File
@@ -32,7 +32,7 @@
| **White-label B2B portals** | Working (Vocal Star, Singa) |
| **Private (non-published) tracks** | Working |
| **Custom video styling (private jobs)** | Working |
| **Song lookup autocomplete** | Working (via karaoke-decide catalog) |
| **Song suggestions & fuzzy correction** | Working (catalog lookup on Step 2 + "Did you mean?" typo correction) |
| **Community version detection** | Working (via karaokenerds.com) |
| **Review session backup/restore** | Working (auto-save + restore UI) |
@@ -46,6 +46,8 @@
## Recent Changes
- **Step 2 Song Suggestions & Fuzzy Correction** (2026-03-08): Replaced the Step 1 autocomplete with a simpler approach: plain text inputs on Step 1, then catalog lookup + community version check fire in parallel with the audio search on Step 2. Results appear as a "Song found in our database" panel (exact match) or correction suggestion panel while the user waits. Added fuzzy "Did you mean?" correction — when audio search returns poor results (Tier 3) and catalog has no exact title match, fetches the artist's discography and fuzzy-matches against the user's title using LCS similarity. Shows an amber banner with one-click correction + expandable alternatives list. Handles garbled artist fields via title-based fallback with artist tiebreaker. Visibility step reworked with action buttons at top for one-click select+continue. See [archive/2026-03-08-step2-song-suggestions.plan.md](archive/2026-03-08-step2-song-suggestions.plan.md) and [archive/2026-03-08-fuzzy-did-you-mean.plan.md](archive/2026-03-08-fuzzy-did-you-mean.plan.md).
- **Review Session Backup/Restore** (2026-03-08): Server-side auto-save of lyrics review sessions replaces fragile localStorage-only mechanism. Sessions auto-save every 60s (if dirty), on preview video generation, and on page unload. Deduplication via SHA-256 hash prevents redundant saves. Correction data stored in GCS (can exceed Firestore's 1MB doc limit); metadata in Firestore subcollection (`jobs/{jobId}/review_sessions/{sessionId}`). Restore UI shows split-pane session browser with edit diff preview. Cross-job session search allows reusing edits across different jobs (with duration mismatch warning). On load, automatically prompts to restore if saved sessions exist. See [archive/2026-03-07-lyrics-review-sessions-plan.md](archive/2026-03-07-lyrics-review-sessions-plan.md).
- **Job Observability Improvements** (2026-03-07): Enhanced timeline events with a `metadata` field to capture structured output details (brand codes, YouTube video IDs, Dropbox paths, GDrive file IDs) at key moments — job completion, edit initiation, and admin output deletion. Added `log_to_job()` helper for API endpoints to write to Firestore job log subcollections (previously only workers logged there). Edit and admin-delete endpoints now snapshot previous outputs before cleanup and log each cleanup step. Distribution logging enhanced with video IDs, folder paths, and file IDs. See [plans/improve-job-observability.plan.md](../.claude/plans/improve-job-observability.plan.md).
+1 -1
View File
@@ -56,7 +56,7 @@ curl -X POST "https://api.nomadkaraoke.com/api/internal/workers/video" \
**Note:** SSH-restarting the encoding worker is **not needed** since v0.119.6 (PR #413). The `/encode` endpoint is now idempotent — re-triggering the video worker is sufficient.
**Prevention (since v0.126.2):** CI now performs a graceful drain before restarting the encoding worker — it waits for active jobs to finish (up to 10 min). Additionally, the encoding client retries for ~90s (up from ~14s), and status polling tolerates up to 5 consecutive failures. These three layers together should prevent this issue from recurring.
**Prevention:** The video worker now runs as a **Cloud Run Job** (`USE_CLOUD_RUN_JOBS_FOR_VIDEO=true`), which runs to completion and is immune to Cloud Run Service deployment rollouts. This replaces the `BackgroundTask` pattern that was vulnerable to instance termination during deployments. Additionally, CI performs a graceful drain before restarting the GCE encoding worker, the encoding client retries for ~90s, and status polling tolerates up to 5 consecutive failures.
---
@@ -0,0 +1,95 @@
# Edit Input Audio — Master Plan
**Date:** 2026-03-08
**Branch:** `feat/sess-20260308-1232-edit-input-audio`
**Status:** Complete
## Problem
A common request from clients is to use a live performance from YouTube but skip the first MM:SS of talking/intro before the band starts playing. Currently there's no way to trim, cut, mute, or otherwise edit the input audio before it enters the processing pipeline (separation, transcription, etc.). Users must provide a pre-edited file themselves or accept the full audio as-is.
## Solution Overview
Add an optional **"Edit Input Audio"** phase after audio download completes but before separation/transcription begins. Users opt in during the guided job creation flow. When enabled, the job pauses at a new blocking state (`awaiting_audio_edit`) where users can trim, cut, mute, or join audio using a waveform-based editor UI similar to the existing instrumental review UI. The edited audio replaces the original as input for all subsequent processing stages.
The editor includes full undo/redo support and session persistence (auto-save + restore) following the same pattern built for lyrics review sessions.
## Phases
| Phase | Title | Scope | Dependencies |
|-------|-------|-------|-------------|
| 1 | [State Machine & Backend API](2026-03-08-edit-input-audio-phase1-backend.md) | New job state, audio processing endpoints (trim/cut/mute/join), waveform data generation for input audio | None |
| 2 | [Session Persistence](2026-03-08-edit-input-audio-phase2-sessions.md) | Audio edit session save/restore, Firestore subcollection, GCS storage, deduplication | Phase 1 |
| 3 | [Job Creation Flow Integration](2026-03-08-edit-input-audio-phase3-creation-flow.md) | Opt-in toggle during "Choose Audio" step, job creation with `requires_audio_edit` flag | Phase 1 |
| 4 | [Audio Editor UI](2026-03-08-edit-input-audio-phase4-editor-ui.md) | Waveform viewer, trim/cut/mute/join controls, undo/redo, playback, original vs edited tabs | Phase 1 |
| 5 | [Session Restore & Admin Dashboard](2026-03-08-edit-input-audio-phase5-restore-admin.md) | Auto-save hook, restore dialog on page load, admin dashboard for viewing/replaying audio edit sessions | Phases 2, 4 |
## Key Design Decisions
1. **Opt-in, not default** — Most users don't need audio editing. The option appears as a secondary question after audio selection (for all sources including file uploads), keeping the default flow unchanged.
2. **Server-side audio processing** — Trim, cut, mute, and join operations are performed server-side via FFmpeg. The frontend sends edit descriptors (timestamps, regions) and the backend produces the edited audio file. This avoids loading large audio files into the browser and ensures consistent processing.
3. **Waveform rendered client-side** — Like the instrumental review UI, the frontend renders waveforms on canvas using amplitude data from the backend API. After each edit, the backend returns updated waveform data for the edited audio. All playback uses OGG Opus (not FLAC) to keep streaming fast.
4. **Edit operations are non-destructive** — Each edit creates a new version. The original audio is always preserved. Users can undo/redo freely and always compare original vs edited.
5. **Session persistence follows lyrics review pattern** — Firestore subcollection + GCS for full edit history, deduplication via hash, auto-save every N edits + on page hide.
6. **Blocking state with notifications** — The `awaiting_audio_edit` state follows the same pattern as `awaiting_review`: generates a review token, sends an email notification, and waits for user action.
## Architecture Overview
```
Job Creation (with requires_audio_edit=true)
↓
DOWNLOADING / DOWNLOADING_AUDIO (existing)
↓
Audio download complete
↓
AWAITING_AUDIO_EDIT ← NEW blocking state
↓
[User opens audio editor UI]
↓
IN_AUDIO_EDIT ← NEW (user actively editing)
↓
[User submits edited audio]
↓
AUDIO_EDIT_COMPLETE ← NEW
↓
[Edited audio saved to GCS, replaces input_media_gcs_path]
↓
Trigger workers (separation + transcription) — existing flow continues
```
## Additional Decisions
- **Available for file uploads too** — Users may not be comfortable with external audio editors; our in-app editing makes basic operations accessible.
- **Server-side only processing** — All edit operations use FFmpeg server-side. No client-side Web Audio API. This ensures the preview is perfectly representative of the final result.
- **Admin can reset to audio edit** — Admins can reset a job to `awaiting_audio_edit` via AdminJobActions, useful when a client requests a trim after job creation.
- **Join limited to start/end** — No arbitrary insert. Users can work around by cutting and re-joining.
- **Playback uses OGG Opus** — All preview audio is transcoded to OGG Opus before streaming to the browser. No FLAC streaming.
## Implementation Approach
Implement each phase sequentially on this branch. After each phase:
1. Run `/test-review` and `/docs-review`
2. Commit and push
After all phases complete, test locally with a real audio file (frontend + backend) before `/shipit`.
## GCS File Structure (additions)
```
jobs/{job_id}/
├── input/
│ ├── original.flac # Original downloaded audio (never modified)
│ └── edited.flac # Edited audio (after user submits)
├── audio_edit/
│ ├── waveform_original.json # Cached waveform data for original
│ ├── waveform_edited.json # Cached waveform data for current edit
│ └── preview_{operation_id}.flac # Temporary previews during editing
├── audio_edit_sessions/
│ └── {session_id}.json # Full edit history for session restore
└── ... (existing structure)
```
@@ -0,0 +1,398 @@
# Edit Input Audio — Phase 1: State Machine & Backend API
**Date:** 2026-03-08
**Parent:** [Master Plan](2026-03-08-edit-input-audio-master-plan.md)
**Status:** Planning
## Goal
Add the backend infrastructure for the "edit input audio" feature: new job states, audio processing endpoints (trim, cut, mute, join), waveform data generation for input audio, and the submit/finalize flow.
---
## 1. New Job States
### State Enum Additions
Add to `backend/models/job.py` `JobStatus`:
```python
AWAITING_AUDIO_EDIT = "awaiting_audio_edit" # Blocking: waiting for user to edit audio
IN_AUDIO_EDIT = "in_audio_edit" # User is actively editing
AUDIO_EDIT_COMPLETE = "audio_edit_complete" # User submitted edited audio
```
### State Transitions
Add to `STATE_TRANSITIONS` in `backend/models/job.py`:
```python
# After download, can optionally enter audio edit phase
JobStatus.DOWNLOADING: [
..., # existing transitions
JobStatus.AWAITING_AUDIO_EDIT, # NEW: if requires_audio_edit
],
# Audio edit phase
JobStatus.AWAITING_AUDIO_EDIT: [
JobStatus.IN_AUDIO_EDIT,
JobStatus.FAILED,
JobStatus.CANCELLED,
],
JobStatus.IN_AUDIO_EDIT: [
JobStatus.AWAITING_AUDIO_EDIT, # User leaves without submitting
JobStatus.AUDIO_EDIT_COMPLETE,
JobStatus.FAILED,
JobStatus.CANCELLED,
],
JobStatus.AUDIO_EDIT_COMPLETE: [
JobStatus.SEPARATING_STAGE1, # Continue to normal processing
JobStatus.TRANSCRIBING,
JobStatus.GENERATING_SCREENS,
JobStatus.FAILED,
],
```
### Audio Download Worker Changes
In `backend/workers/audio_download_worker.py`, after audio download completes:
```python
# Check if audio editing was requested
if job.state_data.get('requires_audio_edit'):
# Transition to blocking audio edit state instead of triggering workers
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_EDIT,
progress=15,
message="Audio downloaded. Please review and edit the audio before processing."
)
# Don't trigger workers yet — wait for user to complete audio edit
return True
# Existing flow: trigger workers immediately
await _trigger_workers_parallel(job_id)
```
### Review Token Generation
In `job_manager.py` `transition_to_state()`, add `AWAITING_AUDIO_EDIT` to the review token generation check:
```python
if new_status in (JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_AUDIO_EDIT):
review_token = generate_review_token()
updates['review_token'] = review_token
```
### Notification
In `job_notification_service.py`, add email notification for `AWAITING_AUDIO_EDIT`:
```python
async def send_audio_edit_email(self, job_id, user_email, artist, title):
edit_url = f"{self.frontend_url}/app/jobs#/{job_id}/audio-edit"
# Use existing email template pattern with new template
```
---
## 2. Audio Processing API Endpoints
All endpoints under the existing review router, authenticated via review token.
### `GET /api/review/{job_id}/input-audio-info`
Returns metadata about the input audio for the editor UI.
**Response:**
```json
{
"duration_seconds": 245.3,
"sample_rate": 44100,
"channels": 2,
"format": "flac",
"file_size_bytes": 35000000,
"waveform_data": {
"amplitudes": [0.1, 0.3, 0.8, ...], // 1000 points
"duration": 245.3
},
"playback_url": "https://storage.googleapis.com/...", // Signed URL (OGG Opus)
"has_edits": false,
"edit_count": 0
}
```
**Implementation:**
1. Read audio metadata from GCS (or cache in state_data after download)
2. Generate waveform data using existing `audio_analysis_service.get_waveform_data()`
3. Generate signed URL for playback (transcode to OGG if not already done)
### `POST /api/review/{job_id}/audio-edit/apply`
Apply an edit operation to the current audio. Returns updated metadata + waveform.
**Request body:**
```json
{
"operation": "trim",
"params": {
"start_seconds": 0,
"end_seconds": 32.5
},
"edit_id": "uuid-from-frontend"
}
```
**Supported operations:**
| Operation | Params | Description |
|-----------|--------|-------------|
| `trim_start` | `{ end_seconds: float }` | Remove audio from 0 to end_seconds |
| `trim_end` | `{ start_seconds: float }` | Remove audio from start_seconds to end |
| `cut` | `{ start_seconds: float, end_seconds: float }` | Remove a region, join remaining |
| `mute` | `{ start_seconds: float, end_seconds: float }` | Silence a region (preserve duration) |
| `join_start` | `{ upload_id: string }` | Prepend uploaded audio |
| `join_end` | `{ upload_id: string }` | Append uploaded audio |
**Response:**
```json
{
"status": "success",
"edit_id": "uuid",
"edited_audio": {
"duration_seconds": 212.8,
"waveform_data": {
"amplitudes": [...],
"duration": 212.8
},
"playback_url": "https://...", // Signed URL for edited audio
},
"edit_stack_size": 3,
"can_undo": true,
"can_redo": false
}
```
**Implementation (backend, server-side FFmpeg):**
1. Download current audio from GCS (original or latest edit)
2. Apply operation using FFmpeg:
- `trim_start`: `ffmpeg -ss {end_seconds} -i input.flac output.flac`
- `trim_end`: `ffmpeg -t {start_seconds} -i input.flac output.flac`
- `cut`: `ffmpeg -filter_complex "[0]atrim=0:{start}[a];[0]atrim={end}[b];[a][b]concat=n=2:v=0:a=1"`
- `mute`: `ffmpeg -af "volume=enable='between(t,{start},{end})':volume=0"`
- `join_start/end`: `ffmpeg -filter_complex "[0][1]concat=n=2:v=0:a=1"`
3. Upload edited audio to GCS at `jobs/{job_id}/audio_edit/edit_{edit_id}.flac`
4. Transcode to OGG Opus for playback
5. Generate waveform data for edited audio
6. Update job state_data with edit stack
### `POST /api/review/{job_id}/audio-edit/undo`
Undo the last edit operation.
**Response:** Same as apply — returns the state after undo (previous edit or original).
**Implementation:**
- Maintain an edit stack in job `state_data`:
```python
state_data['audio_edit_stack'] = [
{"edit_id": "uuid1", "gcs_path": "jobs/.../edit_uuid1.flac", "operation": "trim_start", ...},
{"edit_id": "uuid2", "gcs_path": "jobs/.../edit_uuid2.flac", "operation": "mute", ...},
]
state_data['audio_edit_redo_stack'] = []
```
- Undo pops from edit_stack, pushes to redo_stack
- Returns waveform + playback URL for the now-current version
### `POST /api/review/{job_id}/audio-edit/redo`
Redo a previously undone edit.
**Implementation:** Pop from redo_stack, push to edit_stack.
### `POST /api/review/{job_id}/audio-edit/upload`
Upload additional audio for join operations.
**Request:** Multipart file upload (FLAC, WAV, MP3, M4A, OGG)
**Response:**
```json
{
"upload_id": "uuid",
"duration_seconds": 15.2,
"waveform_data": { "amplitudes": [...], "duration": 15.2 }
}
```
**Implementation:**
1. Save to GCS at `jobs/{job_id}/audio_edit/upload_{upload_id}.flac`
2. Transcode to FLAC if not already
3. Return metadata + waveform
### `POST /api/review/{job_id}/audio-edit/submit`
Finalize the audio edit and continue processing.
**Request body:**
```json
{
"edit_log": {
"session_id": "uuid",
"entries": [...],
"started_at": "2026-03-08T12:00:00Z"
}
}
```
**Response:**
```json
{
"status": "success",
"message": "Audio edit saved. Processing will continue with edited audio.",
"job_id": "..."
}
```
**Implementation:**
1. Take the current top-of-stack audio (or original if no edits)
2. Copy to `jobs/{job_id}/input/edited.flac`
3. Update `job.input_media_gcs_path` to point to edited file
4. Save edit log to GCS
5. Transition state: `IN_AUDIO_EDIT` → `AUDIO_EDIT_COMPLETE`
6. Trigger parallel workers (audio separation + lyrics transcription)
7. Clean up intermediate edit files (optional, can defer)
---
## 3. Audio Processing Service
New service: `backend/services/audio_edit_service.py`
Encapsulates all FFmpeg operations for audio editing:
```python
class AudioEditService:
def __init__(self, storage_service: StorageService):
self.storage = storage_service
def trim_start(self, input_path: str, end_seconds: float, output_path: str) -> AudioMetadata:
"""Remove audio from 0 to end_seconds."""
def trim_end(self, input_path: str, start_seconds: float, output_path: str) -> AudioMetadata:
"""Remove audio from start_seconds to end."""
def cut_region(self, input_path: str, start: float, end: float, output_path: str) -> AudioMetadata:
"""Remove a region and join remaining parts."""
def mute_region(self, input_path: str, start: float, end: float, output_path: str) -> AudioMetadata:
"""Silence a region (preserve duration)."""
def join_audio(self, input_path: str, other_path: str, position: str, output_path: str) -> AudioMetadata:
"""Join two audio files (position: 'start' or 'end')."""
def get_metadata(self, audio_path: str) -> AudioMetadata:
"""Get duration, sample rate, channels, format."""
```
Each method returns `AudioMetadata(duration_seconds, sample_rate, channels, format, file_size_bytes)`.
---
## 4. State Data Schema
The job's `state_data` dict gets these new fields:
```python
{
"requires_audio_edit": bool, # Set during job creation
"audio_edit_stack": [ # Edit history for undo/redo
{
"edit_id": str,
"operation": str,
"params": dict,
"gcs_path": str, # Path to audio file after this edit
"duration_seconds": float,
"timestamp": str,
}
],
"audio_edit_redo_stack": [...], # Undone edits available for redo
"audio_edit_uploads": { # Uploaded audio for join operations
"upload_id": { "gcs_path": str, "duration_seconds": float }
},
"original_input_media_gcs_path": str, # Preserved original before edit
}
```
---
## 5. AutoProcessor Integration
Update `frontend/components/AutoProcessor.tsx` to handle `awaiting_audio_edit`:
For `non_interactive=true` jobs, auto-skip the audio edit phase (submit with no edits):
```typescript
case 'awaiting_audio_edit':
processJob(job, 'audio_edit') // Auto-submit with no edits
break
```
---
## 6. Job Status Display
Update `frontend/lib/job-status.ts` to include new states:
```typescript
awaiting_audio_edit: {
label: "Edit Audio",
description: "Review and edit the input audio",
color: "yellow",
actionRequired: true,
},
in_audio_edit: {
label: "Editing Audio",
description: "Audio is being edited",
color: "blue",
},
audio_edit_complete: {
label: "Audio Edited",
description: "Audio edit complete, starting processing",
color: "green",
},
```
---
## Files Changed
| File | Type | Changes |
|------|------|---------|
| `backend/models/job.py` | Edit | Add 3 new states, update STATE_TRANSITIONS |
| `backend/services/job_manager.py` | Edit | Review token for AWAITING_AUDIO_EDIT, notification trigger |
| `backend/services/audio_edit_service.py` | New | FFmpeg audio editing operations |
| `backend/api/routes/review.py` | Edit | Add 6 new endpoints for audio editing |
| `backend/workers/audio_download_worker.py` | Edit | Check requires_audio_edit, conditional state transition |
| `backend/services/job_notification_service.py` | Edit | Email notification for awaiting_audio_edit |
| `frontend/lib/job-status.ts` | Edit | New state display config |
| `frontend/components/AutoProcessor.tsx` | Edit | Handle awaiting_audio_edit for non-interactive |
## Testing Strategy
| Test | Type | What |
|------|------|------|
| `test_audio_edit_service.py` | Unit | FFmpeg operations (trim, cut, mute, join) with real audio files |
| `test_audio_edit_endpoints.py` | Integration | API endpoint tests with auth, state validation |
| `test_audio_edit_state_transitions.py` | Unit | State machine transitions for new states |
| `test_audio_download_edit_flag.py` | Unit | Download worker respects requires_audio_edit flag |
## Open Questions
1. **Edit stack size limit?** — Should we cap the number of edits before requiring the user to submit? Probably not; let them edit freely. But we should clean up intermediate GCS files after submission.
2. **Real-time preview vs apply-then-preview?** — For MVP, each operation applies server-side and returns the result (apply-then-preview). Real-time client-side preview could come later using Web Audio API for simple operations like mute.
3. **Concurrent editing protection?** — Should we prevent multiple browser tabs from editing the same job? The `in_audio_edit` state transition provides some protection, but we should also use optimistic locking on the edit stack.
4. **Audio format for edits?** — Keep everything in FLAC for lossless quality. Transcode to OGG Opus for all playback URLs (same pattern as existing review audio transcoding). Users should never wait for large FLAC files to stream.
@@ -0,0 +1,228 @@
# Edit Input Audio — Phase 2: Session Persistence
**Date:** 2026-03-08
**Parent:** [Master Plan](2026-03-08-edit-input-audio-master-plan.md)
**Status:** Planning
**Depends on:** Phase 1
## Goal
Persist every audio edit operation so users can resume editing after closing their browser, and admins can review/replay audio edit sessions in the dashboard. Follows the same architectural pattern as lyrics review session persistence.
---
## 1. Data Model
### Firestore Subcollection
`jobs/{job_id}/audio_edit_sessions/{session_id}`
Follows the existing `review_sessions` subcollection pattern.
```python
# backend/models/audio_edit_session.py
@dataclass
class AudioEditSession:
session_id: str # UUID
job_id: str # Parent job ID (denormalized)
user_email: str # Who created this session
created_at: datetime # First save timestamp
updated_at: datetime # Last modification
edit_count: int # Number of edit operations
trigger: str # "auto" | "manual" | "submit"
audio_duration_seconds: float | None # Current edited audio duration
original_duration_seconds: float | None # Original audio duration
artist: str | None # Denormalized from job
title: str | None # Denormalized from job
data_hash: str # SHA256 of edit_data for deduplication
# Summary for list views
summary: AudioEditSessionSummary
# Full edit data stored in GCS (NOT in Firestore doc)
edit_data_gcs_path: str # "jobs/{jobId}/audio_edit_sessions/{sessionId}.json"
@dataclass
class AudioEditSessionSummary:
total_operations: int # Number of edit operations
operations_breakdown: dict[str, int] # {"trim_start": 2, "mute": 1, ...}
duration_change_seconds: float # How much duration changed
net_duration_seconds: float # Current audio duration
```
### GCS Edit Data
Stored at `jobs/{job_id}/audio_edit_sessions/{session_id}.json`:
```json
{
"session_id": "uuid",
"job_id": "abc123",
"started_at": "2026-03-08T12:00:00Z",
"entries": [
{
"id": "uuid-entry-1",
"timestamp": "2026-03-08T12:01:30Z",
"operation": "trim_start",
"params": { "end_seconds": 32.5 },
"duration_before": 245.3,
"duration_after": 212.8,
"audio_gcs_path": "jobs/abc123/audio_edit/edit_uuid1.flac"
},
{
"id": "uuid-entry-2",
"timestamp": "2026-03-08T12:03:15Z",
"operation": "mute",
"params": { "start_seconds": 45.0, "end_seconds": 48.2 },
"duration_before": 212.8,
"duration_after": 212.8,
"audio_gcs_path": "jobs/abc123/audio_edit/edit_uuid2.flac"
}
],
"undo_count": 0,
"redo_count": 0
}
```
---
## 2. API Endpoints
### `POST /api/review/{job_id}/audio-edit-sessions`
Save an audio edit session snapshot.
**Request body:**
```json
{
"edit_data": {
"entries": [...],
"started_at": "..."
},
"edit_count": 5,
"trigger": "auto",
"summary": {
"total_operations": 5,
"operations_breakdown": { "trim_start": 1, "mute": 2, "cut": 2 },
"duration_change_seconds": -32.5,
"net_duration_seconds": 212.8
}
}
```
**Response:**
```json
{
"status": "saved" | "skipped",
"session_id": "uuid",
"created_at": "...",
"reason": "identical_data" // Only if skipped
}
```
**Implementation:**
1. Compute SHA256 hash of `edit_data`
2. Compare with latest session's `data_hash` — skip if identical
3. Upload `edit_data` to GCS
4. Save metadata to Firestore subcollection
### `GET /api/review/{job_id}/audio-edit-sessions`
List all audio edit sessions for a job (metadata only).
**Response:**
```json
{
"sessions": [
{
"session_id": "...",
"created_at": "...",
"updated_at": "...",
"edit_count": 5,
"trigger": "auto",
"summary": { ... }
}
]
}
```
Ordered by `updated_at` descending.
### `GET /api/review/{job_id}/audio-edit-sessions/{session_id}`
Get full session with edit_data loaded from GCS.
### `DELETE /api/review/{job_id}/audio-edit-sessions/{session_id}`
Delete a session (admin or session owner).
---
## 3. Firestore Service Methods
Add to `backend/services/firestore_service.py`:
```python
def save_audio_edit_session(self, job_id: str, session: AudioEditSession) -> None
def list_audio_edit_sessions(self, job_id: str) -> list[AudioEditSession]
def get_audio_edit_session(self, job_id: str, session_id: str) -> AudioEditSession | None
def delete_audio_edit_session(self, job_id: str, session_id: str) -> None
def delete_audio_edit_sessions_subcollection(self, job_id: str) -> None
def get_latest_audio_edit_session_hash(self, job_id: str) -> str | None
```
These follow the exact same pattern as the existing `review_sessions` methods.
---
## 4. Deduplication Strategy
Same as lyrics review sessions:
- Compute SHA256 hash of the `edit_data` JSON (sorted keys)
- Skip save if hash matches the most recent session's `data_hash`
- Prevents duplicate saves during rapid edits or undo/redo cycles
---
## 5. Job Deletion Cascade
When a job is deleted, cascade delete:
- `audio_edit_sessions` subcollection (all Firestore docs)
- `jobs/{job_id}/audio_edit_sessions/` GCS prefix (all session files)
- `jobs/{job_id}/audio_edit/` GCS prefix (all intermediate edit files)
Add to existing job deletion logic in `job_manager.py`.
---
## 6. Retention Policy
| Session Type | Retention |
|-------------|-----------|
| Auto-save (`trigger: "auto"`) | 90 days TTL |
| Manual save (`trigger: "manual"`) | Indefinite |
| Submit save (`trigger: "submit"`) | Indefinite |
Follow the same TTL approach as lyrics review sessions.
---
## Files Changed
| File | Type | Changes |
|------|------|---------|
| `backend/models/audio_edit_session.py` | New | AudioEditSession dataclass |
| `backend/services/firestore_service.py` | Edit | Add CRUD methods for audio_edit_sessions subcollection |
| `backend/api/routes/review.py` | Edit | Add session save/list/get/delete endpoints |
| `backend/services/job_manager.py` | Edit | Cascade delete audio_edit_sessions on job deletion |
## Testing Strategy
| Test | Type | What |
|------|------|------|
| `test_audio_edit_session_crud.py` | Unit | Create, list, get, delete sessions |
| `test_audio_edit_session_dedup.py` | Unit | Hash-based deduplication |
| `test_audio_edit_session_endpoints.py` | Integration | API endpoints with auth |
| `test_audio_edit_session_cascade.py` | Unit | Job deletion cleans up sessions |
@@ -0,0 +1,214 @@
# Edit Input Audio — Phase 3: Job Creation Flow Integration
**Date:** 2026-03-08
**Parent:** [Master Plan](2026-03-08-edit-input-audio-master-plan.md)
**Status:** Planning
**Depends on:** Phase 1
## Goal
Add an opt-in toggle during the guided job creation flow so users can indicate they want to edit the input audio before processing begins. This must not add friction for the majority of users who don't need it.
---
## 1. UX Design
### Where the Toggle Appears
After the user selects their audio source in **Step 2: Choose Audio** (in `AudioSourceStep.tsx`), a secondary question appears below their selection:
```
┌─────────────────────────────────────────────────────┐
│ ✓ Selected: "Bohemian Rhapsody - Live at Wembley" │
│ YouTube · 6:03 · HD Audio │
│ │
│ ┌─────────────────────────────────────────────────┐ │
│ │ ✂️ Want to trim or edit this audio first? │ │
│ │ │ │
│ │ If this is a live recording with talking/intro │ │
│ │ you want to skip, or if you need to remove a │ │
│ │ section, you can edit the audio after it's │ │
│ │ downloaded — before lyrics are transcribed. │ │
│ │ │ │
│ │ ( ) No, use as-is (default, selected) │ │
│ │ ( ) Yes, I'll edit it first │ │
│ └─────────────────────────────────────────────────┘ │
│ │
│ [Continue →] │
└─────────────────────────────────────────────────────┘
```
### Design Principles
1. **Default is "No"** — The toggle defaults to "No, use as-is" so the existing flow is unaffected for most users.
2. **Collapsed by default** — The edit option panel is collapsed into a single line link ("Need to trim or edit this audio?") that expands on click. This keeps the UI clean.
3. **Only shown after selection** — The panel only appears after the user has selected/confirmed an audio source.
4. **Shown for all audio sources including file uploads** — Even if users upload their own files, they may not be comfortable with external audio editors. Our in-app editing makes basic operations (trim, cut, mute) accessible to everyone.
### Collapsed State
```
✓ Selected: "Bohemian Rhapsody - Live at Wembley"
YouTube · 6:03 · HD Audio
✂️ Need to trim or edit this audio? ▸
[Continue →]
```
Clicking the link expands the panel with the radio buttons.
---
## 2. Frontend Changes
### `AudioSourceStep.tsx`
Add state:
```typescript
const [wantsAudioEdit, setWantsAudioEdit] = useState(false)
const [showEditOption, setShowEditOption] = useState(false)
```
Pass `wantsAudioEdit` up to parent via callback:
```typescript
onAudioEditToggle?: (wants: boolean) => void
```
New sub-component: `AudioEditToggle.tsx`
```typescript
interface AudioEditToggleProps {
value: boolean
onChange: (wants: boolean) => void
}
```
### `GuidedJobFlow.tsx`
Add state tracking:
```typescript
const [wantsAudioEdit, setWantsAudioEdit] = useState(false)
```
Pass to job creation call:
```typescript
// In handleConfirm(), add to request body:
requires_audio_edit: wantsAudioEdit
```
### Success Screen Update
When `wantsAudioEdit` is true, update the timeline on the success screen:
```
What happens next:
1. Audio downloading (~1 min) — automatic
2. ✂️ You edit audio — trim, cut, or mute sections ← NEW
3. Audio processing (~10 min) — automatic
4. You review — lyrics & instrumental
5. Video delivered (~10 min) — automatic
```
---
## 3. Backend Changes
### Job Creation Endpoints
Both `POST /api/jobs/create-from-search` and `POST /api/jobs/create-from-url` need to accept:
```python
class CreateFromSearchRequest(BaseModel):
# ... existing fields ...
requires_audio_edit: bool = False # NEW
```
Store in job's `state_data`:
```python
if request.requires_audio_edit:
state_data['requires_audio_edit'] = True
```
### File Upload Path
For `POST /api/jobs/upload` (direct file upload), add a query parameter or form field:
```python
requires_audio_edit: bool = Form(False)
```
---
## 4. Tenant Feature Control
Add to `TenantConfig.features`:
```python
audio_editing: bool = True # Enable/disable audio editing for tenant
```
Default: `True` for all tenants. Can be disabled per-tenant if they don't want the extra step.
Frontend check:
```typescript
const { features } = useTenant()
// Only show the edit toggle if tenant allows it
{features.audio_editing && <AudioEditToggle ... />}
```
---
## 5. Job Card Status Display
When a job is in `awaiting_audio_edit` state, the `JobCard` component should show:
```
┌────────────────────────────────────────┐
│ Bohemian Rhapsody - Queen │
│ Status: Edit Audio Required │
│ Your audio is ready for editing. │
│ │
│ [Edit Audio →] │
└────────────────────────────────────────┘
```
The "Edit Audio" button navigates to `/app/jobs#/{jobId}/audio-edit`.
Update `JobCard.tsx`:
```typescript
case 'awaiting_audio_edit':
return (
<ActionButton href={`/app/jobs#/${job.job_id}/audio-edit`}>
Edit Audio
</ActionButton>
)
```
---
## Files Changed
| File | Type | Changes |
|------|------|---------|
| `frontend/components/job/steps/AudioSourceStep.tsx` | Edit | Add AudioEditToggle panel |
| `frontend/components/job/steps/AudioEditToggle.tsx` | New | Collapsed/expanded toggle component |
| `frontend/components/job/GuidedJobFlow.tsx` | Edit | Track wantsAudioEdit state, pass to API, update success screen |
| `frontend/components/job/JobCard.tsx` | Edit | Handle awaiting_audio_edit state with action button |
| `backend/api/routes/jobs.py` | Edit | Accept requires_audio_edit in create endpoints |
| `backend/api/routes/audio_search.py` | Edit | Accept requires_audio_edit in select endpoint |
| `backend/models/tenant.py` | Edit | Add audio_editing feature flag |
## Testing Strategy
| Test | Type | What |
|------|------|------|
| `AudioEditToggle.test.tsx` | Unit | Toggle renders, defaults to off, calls onChange |
| `GuidedJobFlow.test.tsx` | Unit | Toggle state flows through to job creation |
| `test_create_from_search_edit_flag.py` | Integration | API accepts and stores requires_audio_edit |
| `guided-flow-audio-edit.spec.ts` | E2E | Full flow: select audio → enable edit → create job → verify state |
## Resolved Questions
1. **Show for file uploads?** — **Yes.** Users may not be comfortable with external audio editors. Our in-app editing makes basic operations accessible to everyone.
2. **Admin override?** — **Yes.** Admins can reset a job to `awaiting_audio_edit` state via AdminJobActions. Useful when a client requests a trim after job creation.
3. **Remember preference?** — No — it should be a per-job decision.
@@ -0,0 +1,375 @@
# Edit Input Audio — Phase 4: Audio Editor UI
**Date:** 2026-03-08
**Parent:** [Master Plan](2026-03-08-edit-input-audio-master-plan.md)
**Status:** Planning
**Depends on:** Phase 1
## Goal
Build the audio editor UI that lets users trim, cut, mute, and join audio before processing. The UI is modeled on the existing instrumental review UI (waveform viewer, tabs, playback) but adds editing controls and an undo/redo system.
---
## 1. Page Routing
### Hash-based Route
New route: `/app/jobs#/{jobId}/audio-edit`
Add to the existing hash-based router in `frontend/app/app/jobs/[[...slug]]/client.tsx`:
```typescript
function getRouteType(hash: string): RouteType {
if (hash.includes('/audio-edit')) return 'audio-edit'
if (hash.includes('/instrumental')) return 'instrumental'
if (hash.includes('/review')) return 'review'
return 'unknown'
}
function getExpectedStates(routeType: RouteType): string[] {
switch (routeType) {
case 'audio-edit':
return ['awaiting_audio_edit', 'in_audio_edit']
// ... existing cases
}
}
```
### Review Token Auth
The audio edit page uses the same review token auth as lyrics/instrumental review. The token is generated when entering `awaiting_audio_edit` state (Phase 1).
---
## 2. Component Architecture
```
AudioEditor (main container)
├── AudioEditorToolbar
│ ├── UndoRedoControls
│ ├── EditModeSelector (trim/cut/mute)
│ ├── JoinUploadButton
│ └── SubmitButton
├── WaveformEditor (extended WaveformViewer)
│ ├── Canvas (amplitude visualization)
│ ├── TimeRuler
│ ├── SelectionOverlay (for cut/mute regions)
│ ├── TrimHandles (draggable start/end markers)
│ └── Playhead
├── AudioTabSwitcher
│ ├── "Original" tab
│ └── "Edited" tab
├── PlaybackControls
│ ├── Play/Pause
│ ├── Current time / Total duration
│ └── PlaybackSpeed (0.5x, 1x, 1.5x, 2x)
├── EditHistoryPanel (collapsible sidebar)
│ └── List of applied edits with undo points
└── AudioEditorGuidance (help/tips panel)
```
---
## 3. WaveformEditor Component
Extends the existing `WaveformViewer.tsx` pattern but adds interactive editing.
### Canvas Rendering
Same as instrumental review:
- Dark background (#0d1117)
- Blue amplitude bars (#60a5fa)
- Time ruler at bottom
- White playhead line with dot
- 3 zoom levels (1x, 2x, 4x)
### New Interactive Elements
**Trim Handles** (for trim_start / trim_end):
- Draggable vertical lines at the start and end of the waveform
- Drag start handle right → marks region for trimming from start
- Drag end handle left → marks region for trimming from end
- Trimmed region shown with red-tinted overlay and crosshatch pattern
- Snaps to 0.1 second intervals
**Selection Overlay** (for cut / mute):
- Click and drag to select a region
- Selected region highlighted with yellow border and semi-transparent fill
- Context menu or toolbar buttons to apply "Cut" or "Mute" to selection
- Muted regions shown with very dim bars (like instrumental review)
- Cut regions shown with red-tinted overlay
**Interaction Modes:**
| Mode | Click Behavior | Drag Behavior |
|------|---------------|---------------|
| Play | Seek to position | — |
| Trim | — | Drag trim handles |
| Select | Seek to position | Create selection for cut/mute |
### Waveform Data Updates
After each edit operation:
1. Frontend calls `POST /api/review/{job_id}/audio-edit/apply`
2. Backend returns new `waveform_data.amplitudes` for the edited audio
3. Canvas re-renders with new data
4. Duration display updates
### Tab Switching (Original vs Edited)
Two tabs above the waveform:
- **Original**: Shows original audio waveform, plays original audio
- **Edited**: Shows edited audio waveform (after latest edit), plays edited audio
Tab behavior:
- Switching tabs loads the corresponding waveform data and audio URL
- Maintains playback position proportionally (if audio duration changed, map position)
- Shows loading spinner during tab switch (same as instrumental review)
- "Original" tab always shows the unmodified waveform
- "Edited" tab shows the waveform after the most recent edit
---
## 4. Editing Operations UI
### Trim Start
1. User drags the start trim handle to the right
2. Trimmed region turns red with "Remove" label
3. User clicks "Apply Trim" button (or double-clicks the handle)
4. API call to `POST /audio-edit/apply` with `{ operation: "trim_start", params: { end_seconds: X } }`
5. Waveform updates to show trimmed audio
6. "Edited" tab auto-selected
### Trim End
Same as trim start but from the right side.
### Cut Region
1. User switches to "Select" mode
2. Drags to select a region on the waveform
3. Selection highlighted with yellow border
4. User clicks "Cut" in toolbar (or keyboard shortcut: Delete/Backspace)
5. Confirmation tooltip: "Remove 3.2s of audio from 1:23 to 1:26?"
6. API call to `POST /audio-edit/apply` with `{ operation: "cut", params: { start_seconds, end_seconds } }`
7. Waveform updates — region removed, audio joined
### Mute Region
1. Same selection as cut
2. User clicks "Mute" in toolbar (or keyboard shortcut: M)
3. API call with `{ operation: "mute", params: { start_seconds, end_seconds } }`
4. Waveform shows muted region with dim bars
5. Audio duration unchanged
### Join Audio
1. User clicks "Join" button in toolbar
2. File picker opens (accepts FLAC, WAV, MP3, M4A, OGG)
3. File uploaded via `POST /audio-edit/upload`
4. Small dialog appears: "Add to [Start] or [End]?"
5. API call with `{ operation: "join_start" or "join_end", params: { upload_id } }`
6. Waveform expands to include joined audio
**Note:** Join is limited to start/end only (no insert at arbitrary middle position). This is a niche feature that will rarely be used. Users who need to insert in the middle can work around it by cutting and re-joining.
---
## 5. Undo/Redo System
### Frontend State
```typescript
interface EditState {
editStack: EditEntry[] // Applied edits (from backend)
redoStack: EditEntry[] // Undone edits available for redo
canUndo: boolean
canRedo: boolean
}
interface EditEntry {
editId: string
operation: string
params: Record<string, unknown>
durationBefore: number
durationAfter: number
timestamp: string
}
```
### Controls
- Undo button (⟲) — calls `POST /audio-edit/undo`
- Redo button (⟳) — calls `POST /audio-edit/redo`
- Keyboard shortcuts: Ctrl/Cmd+Z (undo), Ctrl/Cmd+Shift+Z (redo)
- Buttons disabled when stack is empty
### Backend Coordination
Each undo/redo returns the same response as apply — updated waveform data and playback URL for the now-current version. The backend maintains the edit/redo stacks in `state_data`.
---
## 6. Playback Controls
### Audio Element
Single hidden `<audio>` element (same pattern as instrumental review):
- Dynamically updates `src` when switching original/edited tabs
- Maintains position across tab switches
### Controls
```
[⏮] [▶/⏸] [⏭] 0:45 / 3:32 Speed: [1x ▾]
```
- Previous: jump 5 seconds back
- Play/Pause: toggle playback
- Next: jump 5 seconds forward
- Time display: current / total
- Speed selector: 0.5x, 1x, 1.5x, 2x
### Click-to-Seek
Click anywhere on the waveform to seek to that position (same as instrumental review).
---
## 7. Edit History Panel
Collapsible sidebar showing the list of applied edits:
```
Edit History
─────────────────
3. Mute 1:45-1:48
(silenced 3.2s)
2. Cut 0:32-0:45
(removed 13s)
1. Trim start → 0:15
(removed 15s intro)
─────────────────
Original: 4:05
Current: 3:34 (-31s)
```
Each entry shows:
- Operation type and parameters
- Duration impact
- Click to preview the state at that point (optional, stretch goal)
---
## 8. Guidance Panel
A collapsible help panel (same pattern as `InstrumentalGuidancePanel`):
```
┌───────────────────────────────────────────────┐
│ ✂️ Audio Editor Tips [×] │
│ │
│ • Trim: Drag the handles at the start/end │
│ to remove intros or outros │
│ • Cut: Select a region and press Delete to │
│ remove it from the middle │
│ • Mute: Select a region and press M to │
│ silence it without changing the duration │
│ • Join: Upload additional audio to add to │
│ the start or end │
│ • Undo/Redo: Ctrl+Z / Ctrl+Shift+Z │
│ • Click anywhere on the waveform to listen │
│ │
│ When you're done, click "Submit" to continue │
│ with processing. │
└───────────────────────────────────────────────┘
```
Dismissible via localStorage (same pattern as instrumental guidance).
---
## 9. Submit Flow
1. User clicks "Submit & Continue" button
2. Confirmation dialog:
```
Submit Edited Audio?
Original duration: 4:05
Edited duration: 3:34
Edits applied: 3
The edited audio will be used for separation and
lyrics transcription. The original is preserved.
[Cancel] [Submit]
```
3. API call to `POST /api/review/{job_id}/audio-edit/submit`
4. Success screen with countdown (same pattern as instrumental review):
```
✓ Audio edit complete!
Processing will continue with your edited audio.
You'll receive an email when lyrics are ready for review.
Redirecting in 3...
```
5. Redirect to `/app` after 3 seconds
### Submit with No Edits
If the user opens the editor but doesn't make any changes:
- "Submit" button text changes to "Continue Without Editing"
- No confirmation dialog needed
- Submits immediately
---
## 10. Mobile Responsiveness
The editor should work on tablet/desktop. Mobile phone support is a stretch goal due to the precision needed for waveform interactions.
- **Desktop (>1024px)**: Full layout with sidebar edit history
- **Tablet (768-1024px)**: Edit history collapsed by default, narrower waveform
- **Mobile (<768px)**: Simplified layout, larger touch targets for trim handles, edit history in a bottom sheet
---
## Files
| File | Type | Description |
|------|------|-------------|
| `frontend/components/audio-editor/AudioEditor.tsx` | New | Main container component |
| `frontend/components/audio-editor/WaveformEditor.tsx` | New | Interactive waveform with trim handles and selection |
| `frontend/components/audio-editor/AudioEditorToolbar.tsx` | New | Undo/redo, mode selector, join, submit |
| `frontend/components/audio-editor/PlaybackControls.tsx` | New | Play/pause, seek, speed |
| `frontend/components/audio-editor/AudioTabSwitcher.tsx` | New | Original vs Edited tabs |
| `frontend/components/audio-editor/EditHistoryPanel.tsx` | New | List of applied edits |
| `frontend/components/audio-editor/AudioEditorGuidance.tsx` | New | Help/tips panel |
| `frontend/components/audio-editor/TrimHandle.tsx` | New | Draggable trim markers |
| `frontend/components/audio-editor/SelectionOverlay.tsx` | New | Cut/mute selection region |
| `frontend/components/audio-editor/index.ts` | New | Exports |
| `frontend/app/app/jobs/[[...slug]]/client.tsx` | Edit | Add audio-edit route |
| `frontend/lib/api.ts` | Edit | Add audio edit API methods |
## Testing Strategy
| Test | Type | What |
|------|------|------|
| `AudioEditor.test.tsx` | Unit | Renders, loads audio info, displays waveform |
| `WaveformEditor.test.tsx` | Unit | Canvas rendering, click-to-seek, selection interactions |
| `AudioEditorToolbar.test.tsx` | Unit | Mode switching, undo/redo state |
| `PlaybackControls.test.tsx` | Unit | Play/pause, speed changes |
| `audio-editor.spec.ts` | E2E | Full flow: open editor → trim → submit → verify job continues |
## Resolved Questions
1. **Client-side preview before apply?** — **No.** All processing is server-side only. This ensures the preview is perfectly representative of the final result. FFmpeg operations should complete in a few seconds.
2. **Keyboard shortcuts scope** — Waveform-focused to avoid conflicts with other page elements.
3. **Max audio duration for editing?** — No limit for MVP. Add one later if performance issues arise.
4. **Zoom-to-selection?** — Defer to post-MVP. Nice UX but adds complexity.
@@ -0,0 +1,302 @@
# Edit Input Audio — Phase 5: Session Restore & Admin Dashboard
**Date:** 2026-03-08
**Parent:** [Master Plan](2026-03-08-edit-input-audio-master-plan.md)
**Status:** Complete
**Depends on:** Phases 2, 4
## Goal
Wire up auto-save during audio editing, provide a restore dialog when users return to an in-progress edit, and give admins the ability to view/replay audio edit sessions in the dashboard.
---
## 1. Auto-Save Hook
### `useAudioEditAutoSave`
New hook following the exact pattern of `useReviewSessionAutoSave`:
```typescript
// frontend/hooks/use-audio-edit-autosave.ts
function useAudioEditAutoSave({
jobId: string,
editStack: EditEntry[],
originalDuration: number,
currentDuration: number,
isReadOnly: boolean,
apiClient: ReviewApiClient,
}) {
const lastBackupStackSize = useRef(0)
const computeSummary = useCallback((): AudioEditSessionSummary => {
const breakdown: Record<string, number> = {}
for (const entry of editStack) {
breakdown[entry.operation] = (breakdown[entry.operation] || 0) + 1
}
return {
total_operations: editStack.length,
operations_breakdown: breakdown,
duration_change_seconds: currentDuration - originalDuration,
net_duration_seconds: currentDuration,
}
}, [editStack, originalDuration, currentDuration])
const saveSession = useCallback(async (trigger: string) => {
if (editStack.length === 0) return
if (editStack.length === lastBackupStackSize.current) return
await apiClient.saveAudioEditSession(jobId, {
edit_data: { entries: editStack, started_at: ... },
edit_count: editStack.length,
trigger,
summary: computeSummary(),
})
lastBackupStackSize.current = editStack.length
}, [editStack, ...])
// Save triggers
// 1. Every 3 edits (same cadence as lyrics review)
useEffect(() => {
if (editStack.length > 0 && editStack.length % 3 === 0) {
saveSession("auto")
}
}, [editStack.length, saveSession])
// 2. On page visibility change
useEffect(() => {
const handler = () => {
if (document.hidden) saveSession("auto")
}
document.addEventListener("visibilitychange", handler)
return () => document.removeEventListener("visibilitychange", handler)
}, [saveSession])
return { saveSession }
}
```
### Save Triggers
| Trigger | Condition | `trigger` field |
|---------|-----------|-----------------|
| Every N edits | Every 3 edits | `"auto"` |
| Page hide | `visibilitychange` when tab loses focus | `"auto"` |
| Before submit | Just before submitting edited audio | `"submit"` |
| Manual | User clicks "Save Progress" button | `"manual"` |
---
## 2. Session Restore Dialog
### When It Appears
When the `AudioEditor` component mounts:
1. Call `GET /api/review/{job_id}/audio-edit-sessions` to check for saved sessions
2. If sessions exist → show `AudioEditRestoreDialog`
3. If no sessions → proceed to fresh editor
### Dialog Design
Same split-pane layout as the lyrics review `SessionRestoreDialog`:
```
┌─────────────────────────────────────────────────────┐
│ Saved Audio Edit Sessions [×] │
├──────────────────────┬──────────────────────────────┤
│ Session List │ Edit Preview │
│ │ │
│ ▸ Mar 8, 2:15 PM │ Operations applied: │
│ 3 edits · auto │ │
│ [Most recent] │ 1. Trim start → 0:15 │
│ │ Removed 15s intro │
│ ▸ Mar 8, 1:45 PM │ │
│ 1 edit · auto │ 2. Cut 0:32-0:45 │
│ │ Removed 13s │
│ │ │
│ │ 3. Mute 1:45-1:48 │
│ │ Silenced 3.2s │
│ │ │
│ │ Duration: 4:05 → 3:34 (-31s) │
│ │ │
├──────────────────────┴──────────────────────────────┤
│ [Start Fresh] [Restore Selected] │
└─────────────────────────────────────────────────────┘
```
### Restore Behavior
When user clicks "Restore Selected":
1. Load full session data: `GET /api/review/{job_id}/audio-edit-sessions/{session_id}`
2. Replay edit entries:
- For each entry in `edit_data.entries`, call `POST /audio-edit/apply` sequentially
- Show progress indicator: "Restoring edit 2 of 3..."
- Each apply returns the updated waveform and audio
3. After all edits replayed, editor is in the same state as when the session was saved
4. User can continue editing from where they left off
### Alternative: Server-side Replay
Instead of replaying edits client-side, the backend could:
1. Accept a session_id in a new endpoint: `POST /audio-edit/restore-session`
2. Backend replays all operations server-side
3. Returns final state (waveform, playback URL, edit stack)
This is faster and more reliable. The frontend just needs to load the final state.
**Recommendation:** Server-side replay for MVP. Client-side replay only needed if we want to show animated step-by-step restoration.
---
## 3. "Save Progress" Button
Add to the `AudioEditorToolbar`:
```
[⟲ Undo] [⟳ Redo] | [✂️ Trim] [✂ Cut] [🔇 Mute] [📎 Join] | [💾 Save] | [Submit & Continue →]
```
- "Save" button triggers `saveSession("manual")`
- Shows toast notification: "Progress saved" / "No new changes"
- Disabled when no edits have been made
---
## 4. Admin Dashboard
### Audio Edit Reviews Page
New admin page: `/admin/audio-edits`
Follows the same pattern as `/admin/edit-reviews` for lyrics.
### List View
```
┌──────────────────────────────────────────────────────────┐
│ Audio Edit Reviews [Search 🔍] │
├──────────────────────────────────────────────────────────┤
│ Job ID │ Artist │ Title │ Edits │ Status │
│──────────────────────────────────────────────────────────│
│ abc12345 │ Queen │ Bohemian... │ 3 │ ✓ Done │
│ def67890 │ Taylor Swift │ Shake It... │ 1 │ ⏳ In Progress │
└──────────────────────────────────────────────────────────┘
```
### Detail View
Click a job to see its audio edit history:
```
┌──────────────────────────────────────────────────────────┐
│ Audio Edit: Queen - Bohemian Rhapsody (abc12345) │
├──────────────────────────────────────────────────────────┤
│ │
│ Original Audio │
│ [▶ Play] Duration: 4:05 │
│ ██████████████████████████████████████████████ (waveform)│
│ │
│ Edited Audio │
│ [▶ Play] Duration: 3:34 │
│ ████████████████████████████████████████ (waveform) │
│ │
│ Edit Log: │
│ ───────── │
│ 1. [12:01:30] trim_start → removed 0:00-0:15 (15s) │
│ 2. [12:03:15] cut → removed 0:17-0:30 (13s) │
│ 3. [12:05:42] mute → silenced 1:30-1:33 (3.2s) │
│ │
│ Sessions: 2 auto-saves, 1 submit │
│ User: andrew@nomadkaraoke.com │
│ Submitted: Mar 8, 2026 12:06 PM │
└──────────────────────────────────────────────────────────┘
```
### Admin API Endpoints
Add to `backend/api/routes/admin.py`:
#### `GET /api/admin/audio-edit-reviews`
List jobs that have audio edit sessions.
**Query params:**
- `q`: Search by artist, title, job_id
- `exclude_test`: Filter test emails
- `limit`: Max results (default 50)
**Implementation:**
- Query jobs where `state_data.requires_audio_edit == true`
- Return summary with job metadata + edit count
#### `GET /api/admin/audio-edit-reviews/{job_id}`
Get full audio edit review for a job.
**Response:**
```json
{
"job_id": "abc123",
"artist": "Queen",
"title": "Bohemian Rhapsody",
"user_email": "andrew@...",
"original_audio_url": "https://...", // Signed URL
"edited_audio_url": "https://...", // Signed URL
"original_waveform": { "amplitudes": [...], "duration": 245.3 },
"edited_waveform": { "amplitudes": [...], "duration": 212.8 },
"edit_sessions": [
{
"session_id": "...",
"trigger": "submit",
"edit_count": 3,
"summary": { ... },
"edit_data": { "entries": [...] }
}
]
}
```
---
## 5. Admin Navigation
Add "Audio Edits" link to admin sidebar, alongside existing "Edit Reviews" link:
```typescript
// In admin layout
{ href: "/admin/audio-edits", label: "Audio Edits", icon: Scissors }
```
---
## Files Changed
| File | Type | Changes |
|------|------|---------|
| `frontend/hooks/use-audio-edit-autosave.ts` | New | Auto-save hook |
| `frontend/components/audio-editor/AudioEditRestoreDialog.tsx` | New | Session restore modal |
| `frontend/components/audio-editor/AudioEditor.tsx` | Edit | Wire up auto-save + restore |
| `frontend/components/audio-editor/AudioEditorToolbar.tsx` | Edit | Add Save button |
| `frontend/app/admin/audio-edits/page.tsx` | New | Admin list view |
| `frontend/app/admin/audio-edits/[jobId]/page.tsx` | New | Admin detail view |
| `frontend/lib/api.ts` | Edit | Add audio edit session API methods + admin endpoints |
| `backend/api/routes/admin.py` | Edit | Add audio edit review endpoints |
## Testing Strategy
| Test | Type | What |
|------|------|------|
| `use-audio-edit-autosave.test.ts` | Unit | Save triggers, dirty tracking, dedup |
| `AudioEditRestoreDialog.test.tsx` | Unit | Session list, selection, restore action |
| `admin-audio-edits.test.tsx` | Unit | Admin list and detail views render |
| `audio-edit-session-restore.spec.ts` | E2E | Full flow: edit → close → reopen → restore → continue |
## Resolved Questions
1. **Cross-job session restore?** — **No.** Audio edits are position-specific and unlikely to transfer across jobs.
2. **Admin replay animation?** — **No for MVP.** Show the edit log as a list + before/after waveforms and audio playback.
3. **Session pruning?** — Cap at 20 sessions per job. Auto-prune oldest auto-saves when limit is reached.
@@ -0,0 +1,200 @@
# Fix: Encoding Orchestration Killed by Cloud Run Deployments
**Date:** 2026-03-08
**Incident:** Job `43c0d519` (Westlife - Medley) stuck at `encoding` status for 4+ hours
**Branch:** `feat/sess-20260308-2013-fix-encoding-deploy-survival`
---
## Incident Analysis
### What Happened
1. **16:18:18** — Video worker HTTP request returned `200` after 80s. The encoding orchestration (submit to GCE, poll, download, upload) continued as a FastAPI `BackgroundTask`.
2. **16:19:19** — GitHub Actions deployed new Cloud Run revision `karaoke-backend-00573-glx`.
3. **16:19:25** — `DEPLOYMENT_ROLLOUT`: new instances started, old instances began draining.
4. **16:19:39** — Old instance (still running background encoding task) submitted encoding to GCE worker.
5. **16:20:10** — GCE worker connection failed (attempt 1/8). Old instance was being terminated.
6. **After 16:20:10** — No more logs. Instance killed. Job stuck permanently at `encoding` status.
### Why Existing Protections Didn't Help
The three-layer defense (PRs #413, #473) protects against the **GCE encoding worker** being restarted:
| Layer | What It Protects | Why It Didn't Help Here |
|-------|-----------------|------------------------|
| CI graceful drain | GCE worker restart waits for active FFmpeg jobs | The GCE worker wasn't restarted — Cloud Run was |
| Extended retries (90s) | Connection failures to GCE worker during restart | Cloud Run killed the instance before retries completed |
| Poll failure tolerance | Transient poll errors during GCE worker restart | The poller itself was killed, not just failing |
**The gap:** All protections assume the Cloud Run orchestrator stays alive. None protect against the orchestrator itself being killed during a deployment.
### Root Cause: `BackgroundTask` Pattern
The video worker endpoint (`internal.py:264`) uses FastAPI's `BackgroundTask`:
```python
background_tasks.add_task(generate_video, job_id) # Fire-and-forget
return WorkerResponse(status="started", ...) # HTTP response returns immediately
```
Cloud Run considers the request "complete" once the response is sent. During a deployment rollout:
- Old instances are **drained** (no new requests routed to them)
- Once no active HTTP requests remain, old instances are **terminated**
- `BackgroundTask` work is silently killed
The encoding orchestration (which takes 2-5+ minutes) runs entirely after the HTTP response, making it vulnerable to termination at any time.
### The Fix Already Exists (But Is Disabled)
**Cloud Run Jobs support was already built** in PR #155 (Dec 2025) for exactly this reason:
- **Infrastructure:** `video-encoding-job` Cloud Run Job provisioned via Pulumi (`infrastructure/modules/cloud_run.py:374`)
- **Code:** `worker_service.py:427` has `_trigger_cloud_run_job()` that dispatches to Cloud Run Jobs
- **Feature flag:** `USE_CLOUD_RUN_JOBS_FOR_VIDEO` env var controls the routing
Cloud Run Jobs run to completion (up to 24h) with no HTTP request lifecycle — they're immune to deployment rollouts.
**Why it's disabled:** The env var `USE_CLOUD_RUN_JOBS_FOR_VIDEO=true` was set in the old `cloudbuild.yaml` (commit `db2c5a03`) but was **dropped when CI migrated to GitHub Actions** (`.github/workflows/ci.yml`). The current CI env vars on line 1319 include `USE_GCE_ENCODING=true` but not `USE_CLOUD_RUN_JOBS_FOR_VIDEO=true`.
---
## Implementation Plan
### Option A: Re-enable Cloud Run Jobs for Video (Recommended)
**Effort:** Small (env var + verification)
**Risk:** Low (infrastructure and code already exist and were previously deployed)
#### Step 1: Add missing env var to CI
In `.github/workflows/ci.yml` line 1319, add `USE_CLOUD_RUN_JOBS_FOR_VIDEO=true` to the `--set-env-vars` string.
#### Step 2: Verify Cloud Run Job infrastructure is current
```bash
# Check the job exists and has the right image
gcloud run jobs describe video-encoding-job --region=us-central1 --project=nomadkaraoke
```
The Cloud Run Job uses the `latest` image tag, so it should already be using the current backend image. Verify:
- Image matches current backend image
- Timeout is 3600s (1 hour)
- Service account has correct permissions
- Environment variables include necessary secrets
#### Step 3: Ensure Cloud Run Job has all required env vars and secrets
The Cloud Run Job defined in Pulumi (`infrastructure/modules/cloud_run.py:407-416`) only has `GOOGLE_CLOUD_PROJECT` and `GCS_BUCKET_NAME`. It's missing critical env vars and secrets that the video worker needs:
- `USE_GCE_ENCODING=true`
- `ENCODING_WORKER_URL` and `ENCODING_WORKER_API_KEY` (secrets)
- `DEFAULT_DROPBOX_PATH`, `DEFAULT_GDRIVE_FOLDER_ID`, etc.
- `DEFAULT_ENABLE_YOUTUBE_UPLOAD`, `DEFAULT_BRAND_PREFIX`
- All the secrets the backend needs (Discord webhook, Stripe, etc.)
**This is likely why it was disabled** — the Cloud Run Job env was incomplete.
Options:
a. **Mirror all env vars/secrets from the Cloud Run Service** to the Job in Pulumi (tedious but correct)
b. **Have the Job fetch config from Secret Manager at runtime** (more elegant but requires code changes)
c. **Use a shared env config module in Pulumi** that both Service and Job reference
#### Step 4: Update the Cloud Run Job image in CI
The CI workflow deploys new images to Cloud Run Service but doesn't update the Cloud Run Job's image. Need to add a step:
```bash
gcloud run jobs update video-encoding-job \
--image="${REGION}-docker.pkg.dev/${PROJECT_ID}/karaoke-repo/karaoke-backend:${VERSION}" \
--region=us-central1 \
--project=${PROJECT_ID}
```
#### Step 5: Test with a real job
1. Deploy the changes
2. Trigger a video worker for a test job
3. Verify it runs as a Cloud Run Job (check Cloud Run Jobs console)
4. Verify encoding completes and all outputs are uploaded
#### Step 6: Add deployment protection test
Create a test that:
- Triggers video encoding via Cloud Run Job
- Simulates a deployment (deploy new Cloud Run Service revision) mid-encoding
- Verifies the Job completes unaffected
### Option B: SIGTERM Handler + Re-enqueue (Alternative)
**Effort:** Medium
**Risk:** Medium (new code path, race conditions)
Add a SIGTERM handler to the Cloud Run Service that:
1. Catches SIGTERM during background task execution
2. Checks if encoding is in-flight
3. Re-triggers the video worker via Cloud Tasks (which will run on a new instance)
This is more complex and has edge cases (what if re-trigger also gets killed?). Option A is simpler.
### Option C: Keep Connection Open (Alternative)
**Effort:** Small
**Risk:** Low but has timeout implications
Instead of `background_tasks.add_task()`, run the video worker inline within the HTTP request handler. This keeps the connection active, preventing Cloud Run from killing the instance during drain.
```python
# Instead of:
background_tasks.add_task(generate_video, job_id)
return WorkerResponse(status="started", ...)
# Do:
success = await generate_video(job_id)
return WorkerResponse(status="completed" if success else "failed", ...)
```
**Pros:** Simple change, no infrastructure needed
**Cons:**
- Cloud Run request timeout is 1800s (30 min) — encoding can exceed this
- Cloud Tasks dispatch deadline might conflict
- The caller must keep the connection open for the full duration
- During drain, Cloud Run waits for active requests but has a grace period limit
---
## Recommendation
**Option A (re-enable Cloud Run Jobs)** is the right fix because:
1. Infrastructure already provisioned and code already written
2. Cloud Run Jobs are purpose-built for long-running batch work
3. Immune to deployment rollouts by design
4. Already used successfully for audio downloads (PR #496)
**However**, Step 3 (env vars/secrets) is the critical blocker — the Job needs the same configuration as the Service. This was likely why it was disabled after the cloudbuild.yaml migration.
**Immediate fix for job `43c0d519`:** Re-trigger the video worker manually:
```bash
curl -X POST "https://api.nomadkaraoke.com/api/internal/workers/video" \
-H "X-Admin-Token: $(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke)" \
-H "Content-Type: application/json" \
-d '{"job_id": "43c0d519"}'
```
---
## Files to Change
| File | Change |
|------|--------|
| `.github/workflows/ci.yml` | Add `USE_CLOUD_RUN_JOBS_FOR_VIDEO=true` to env vars |
| `.github/workflows/ci.yml` | Add step to update Cloud Run Job image on deploy |
| `infrastructure/modules/cloud_run.py` | Add all required env vars and secrets to `video-encoding-job` |
| `docs/LESSONS-LEARNED.md` | Add lesson about env vars dropped during CI migration |
| `docs/TROUBLESHOOTING.md` | Update "stuck at encoding" section with this new failure mode |
## Testing Strategy
- **Unit tests:** Verify `trigger_video_worker` routes to Cloud Run Jobs when `USE_CLOUD_RUN_JOBS_FOR_VIDEO=true`
- **Integration test:** Trigger video worker and verify Cloud Run Job is created
- **Production verification:** Run a test job end-to-end after deployment
@@ -0,0 +1,40 @@
# Plan: Fuzzy "Did you mean?" correction for typos
**Created:** 2026-03-08
**Branch:** feat/sess-20260308-0139-step2-song-suggestions
**Status:** Draft
## Overview
When a user types a misspelled song title (e.g. "ruises" instead of "Bruises"), the audio search returns poor results (Tier 3 / no lossless) and the catalog search returns nothing. The user has no signal they made a typo. We add a second-pass fuzzy search that triggers when results are poor: fetch the artist's discography from the catalog, fuzzy-match against the user's title, and show a "Did you mean X?" banner. Clicking "Yes" corrects the title and restarts the audio search.
## Technical Approach
1. **Trigger condition:** Audio search completes with Tier 3 or no results AND catalog search returned 0 results
2. **Fuzzy search:** Call `api.searchCatalogTracks(artist, artist, 20)` — search the artist's name as the query with artist filter to get their top tracks. This is a broader search that doesn't require matching the title.
3. **Client-side fuzzy match:** Compare each returned track name against the user's title using simple Levenshtein-like similarity (normalized). Pick the best match above a threshold (e.g. 0.6 similarity).
4. **"Did you mean?" banner:** Prominent amber banner with the suggested correction. "Yes, search again" button restarts audio search with corrected artist/title.
5. **Restart flow:** Reset search state, update artist/title via parent callback, re-trigger `doSearch()`.
## Fuzzy Matching Algorithm
Simple approach — no external dependency needed:
- Lowercase both strings
- Calculate longest common subsequence (LCS) ratio: `2 * LCS_length / (len(a) + len(b))`
- Also check if user's title is a substring of the track name or vice versa
- Threshold: 0.6 for LCS ratio, or substring match with length >= 3
- Pick the highest-scoring match
## Files to Modify
| File | Action | Description |
|------|--------|-------------|
| `frontend/components/job/steps/AudioSourceStep.tsx` | Modify | Add fuzzy search trigger, "Did you mean?" banner, restart logic |
## Implementation Steps
1. Add `fuzzyMatch()` utility function (inline in AudioSourceStep)
2. Add state for fuzzy suggestion (`fuzzySuggestion`, `fuzzyDismissed`)
3. Add `useEffect` that triggers fuzzy search when audio search completes with poor results + no catalog results
4. Add `DidYouMeanBanner` component
5. Add restart handler that clears state and re-runs search with corrected name
@@ -0,0 +1,85 @@
# Plan: Move Song DB Suggestions from Step 1 to Step 2
**Created:** 2026-03-08
**Branch:** feat/sess-20260308-0139-step2-song-suggestions
**Status:** Implemented
## Overview
The autocomplete on Step 1's title field is confusing — users don't know why they should wait for it or select a suggestion. Instead, we'll remove autocomplete from Step 1 (making it a simple text entry) and show song DB suggestions in Step 2 while the audio search is loading. This uses the ~15-30s wait time productively and presents suggestions with clear context about what they are and why.
## Requirements
- [x] Remove `AutocompleteInput` from Step 1 title field → plain `<Input>`
- [x] Keep community version check in Step 1 (non-blocking, useful)
- [x] Fire `api.searchCatalogTracks()` in parallel with `api.searchStandalone()` on Step 2 mount
- [x] Show catalog results in Step 2 as a "song name correction" panel
- [x] Clicking a suggestion updates artist/title (the search artist/title used for job creation)
- [x] Panel is dismissible, doesn't appear if no results
- [x] Catalog search failure is silent (doesn't affect audio search)
- [x] Works well on mobile
## Technical Approach
**No new API endpoints needed** — we already have `api.searchCatalogTracks()`.
**Data flow change:** In Step 2, `AudioSourceStep` gets two new props:
- `onArtistTitleCorrection(artist: string, title: string)` — called when user picks a suggestion
- The parent (`GuidedJobFlow`) updates `artist`/`title` state, which re-renders the "Searching for X - Y" header
**Key decision:** When the user corrects artist/title via catalog suggestion, this updates the *search* artist/title (used in `createJobFromSearch`). It does NOT restart the audio search — that would be confusing and waste time. The audio search already happened with the original terms.
## Implementation Steps
### Step 1: Simplify SongInfoStep (remove autocomplete)
1. [x] Replace `AutocompleteInput` with plain `<Input>` for the title field
2. [x] Remove `fetchTrackSuggestions` callback and `AutocompleteInput` import
3. [x] Keep all other functionality (community check, tips, form validation)
### Step 2: Add catalog search to AudioSourceStep
4. [x] Add `onArtistTitleCorrection` prop to `AudioSourceStepProps`
5. [x] Add state: `catalogResults`, `catalogLoading`, `catalogDismissed`
6. [x] Fire `api.searchCatalogTracks(title, artist, 5)` in parallel with `doSearch()` in the mount effect
7. [x] Build `SongSuggestionPanel` inline component showing results
### Step 3: Wire up GuidedJobFlow
8. [x] Add handler in `GuidedJobFlow` that updates `artist`/`title` when catalog suggestion selected
9. [x] Pass handler to `AudioSourceStep` as `onArtistTitleCorrection`
### Step 4: Testing
10. [ ] Run existing E2E tests to verify no regressions
11. [ ] Manual visual check in dev server
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `frontend/components/job/steps/SongInfoStep.tsx` | Modify | Remove AutocompleteInput, use plain Input for title |
| `frontend/components/job/steps/AudioSourceStep.tsx` | Modify | Add parallel catalog search + suggestion panel |
| `frontend/components/job/GuidedJobFlow.tsx` | Modify | Add artist/title correction handler, pass to Step 2 |
## SongSuggestionPanel Design
```
┌─────────────────────────────────────────────┐
│ 🔍 Found matching songs │
│ Click to use the official formatting: │
│ │
│ ┌─ Fox Stevenson - Don't Care Crown ──── ┐ │
│ └──────────────────────────────────────── ┘ │
│ ┌─ Fox Stevenson - Don't Care Crown... ─ ┐ │
│ └──────────────────────────────────────── ┘ │
│ Dismiss ↗ │
└─────────────────────────────────────────────┘
```
- Appears between the "Searching for X - Y" header and the loading spinner
- Uses existing design language (card with border, muted colors)
- Each result is a clickable row showing `Artist - Track` with a subtle "Use" button
- When selected: row highlights briefly, artist/title update, panel auto-dismisses
- "Dismiss" link at bottom to hide permanently
- If already matches exactly, skip showing that result
## Rollback Plan
Revert the branch. No backend changes, no data migrations.
@@ -0,0 +1,159 @@
# Plan: Visibility Step Layout Rework
**Date**: 2026-03-08
**Branch**: `feat/visibility-step-layout`
**Status**: Implemented
## Problem
The Visibility step requires scrolling past two detailed info cards to reach the Continue button. Users who already know what they want (especially repeat users) are forced to scroll every time.
Screenshot shows: header → Published card (large) → Private card (large) → Continue button (below fold).
## Design Decision
**Chosen approach: Action buttons at top, detail cards below as reference.**
Two prominent, descriptive buttons placed immediately after the header let users select-and-continue in one click. The existing detail cards remain below for first-time users who want to understand the implications before choosing.
### Why this over alternatives
| Approach | Pros | Cons |
|----------|------|------|
| **Action buttons at top** (chosen) | Zero scroll for decisive users; details still visible for cautious users; single click to proceed | Two interaction patterns (buttons vs cards) |
| Move Continue to top | Simple change | Still requires scrolling to understand options before clicking |
| Collapsible detail cards | Compact | Hides important info by default; extra click to expand |
| Sticky bottom button | Easy to implement | Overlaps content on small screens; still generic "Continue" |
| Auto-advance on card select | Fewest clicks | No chance to change mind; jarring UX |
## Design Spec
### New Layout (top to bottom)
```
Header: "How should your video be shared?"
Subtitle + Back button (unchanged)
┌─────────────────────────────────────────────────┐
│ [🌐 Publish & Share →] [🔒 Keep Private →] │
│ Recommended │
└─────────────────────────────────────────────────┘
── What's the difference? ──────────────── (divider)
[Published detail card] (informational, still clickable to select)
[Private detail card] (informational, still clickable to select)
```
### Action Buttons Detail
- **Two buttons side-by-side** in a flex row with `gap-3`
- Each button is a bordered card-style button (~equal width via `flex-1`)
- **"Publish & Share"** button: Globe icon, "Recommended" badge below, pink border/highlight when Published is currently selected
- **"Keep Private"** button: Lock icon, neutral border, pink highlight when Private is currently selected
- **Clicking either button calls both `onPrivateChange()` AND `onNext()`** — single action to select and continue
- Arrow icon (→) on each button reinforces that clicking advances the flow
- Desktop: side by side. Mobile (`< sm`): stack vertically
### Detail Cards
- Keep the existing Published and Private cards **exactly as-is** content-wise
- They remain clickable (toggling the selection) but do **not** auto-advance
- Add a subtle text divider above them: "What's the difference?" in muted text with horizontal rules
- When a user clicks a detail card, it updates the selection and the action buttons above visually reflect the change — but the user still needs to click an action button (or scroll back up) to continue. This is intentional: clicking a card means "I'm still reading/deciding."
- Consider slightly reducing vertical padding on cards (`p-4` → `p-3`) to reduce total page height
### Visual Treatment
- Action buttons use the same `var(--brand-pink)` theming as the rest of the step
- Selected action button: pink border + subtle glow (matching current card selection style)
- Unselected action button: `var(--card-border)` border, muted icon
- Both buttons have hover states with border color transition
- The "Recommended" label sits under the Publish button (not inside it) as a small badge
### Responsive Behavior
- **Desktop (≥640px / `sm`)**: Action buttons side-by-side
- **Mobile (<640px)**: Action buttons stack vertically, Publish on top
## Implementation
### Files to Change
1. **`frontend/components/job/steps/VisibilityStep.tsx`** — the only file that needs changes
### Steps
1. **Add action buttons section** after the header div and before the detail cards
- Two `<button>` elements in a flex container
- Each calls `onPrivateChange(value)` then `onNext()` on click
- Styled as card-like buttons with icon + label + optional badge
- Use existing CSS variable theming
2. **Add divider** between action buttons and detail cards
- Simple flex row with horizontal rules and muted text: "What's the difference?"
3. **Keep existing detail cards** unchanged (content, styling, click handlers)
- Only change: remove the bottom Continue button entirely
4. **Remove the bottom Continue button** — no longer needed since action buttons serve this purpose
### Code Sketch
```tsx
{/* Action buttons - select and continue */}
<div className="flex flex-col sm:flex-row gap-3">
<button
type="button"
onClick={() => { onPrivateChange(false); onNext(); }}
disabled={disabled}
className={`flex-1 rounded-lg border-2 p-4 transition-all text-center ${
!isPrivate
? 'border-[var(--brand-pink)] shadow-[0_0_12px_rgba(255,122,204,0.2)]'
: 'border-[var(--card-border)] hover:border-[var(--text-muted)]'
}`}
>
<Globe />
<span>Publish & Share</span>
<ArrowRight />
{/* Recommended badge below */}
</button>
<button
type="button"
onClick={() => { onPrivateChange(true); onNext(); }}
disabled={disabled}
className={`flex-1 rounded-lg border-2 p-4 transition-all text-center ${
isPrivate
? 'border-[var(--brand-pink)] shadow-[0_0_12px_rgba(255,122,204,0.2)]'
: 'border-[var(--card-border)] hover:border-[var(--text-muted)]'
}`}
>
<Lock />
<span>Keep Private</span>
<ArrowRight />
</button>
</div>
{/* Divider */}
<div className="flex items-center gap-3">
<div className="flex-1 h-px bg-[var(--card-border)]" />
<span className="text-xs text-[var(--text-muted)]">What's the difference?</span>
<div className="flex-1 h-px bg-[var(--card-border)]" />
</div>
{/* Existing detail cards (unchanged) */}
```
## Testing
- Visual: verify no-scroll path works on common viewport sizes (desktop, tablet, mobile)
- Functional: clicking action buttons correctly sets visibility AND advances to step 4
- Functional: clicking detail cards still toggles selection without advancing
- Functional: Back button still works
- Functional: disabled state prevents all interactions
- Accessibility: buttons are keyboard navigable, focus states visible
## Estimate
Small change — single component, ~40 lines added, ~6 lines removed. Should take one implementation session.
@@ -0,0 +1,58 @@
# Plan: Pre-generate Audio Editor Assets
**Created:** 2026-03-09
**Branch:** feat/sess-20260309-1749-pregenerate-audio-editor
**Status:** In Progress
## Overview
The audio editor UI takes 10-20 seconds to load because it generates waveform data and transcodes FLAC→OGG on-demand when the user opens the editor. The lyrics/instrumental review UI doesn't have this problem because `screens_worker` eagerly pre-generates all assets before the job reaches `awaiting_review`.
We need the same eager pre-generation for audio editing: transcode the input audio to OGG and generate waveform data *during* the download worker, before the job transitions to `awaiting_audio_edit`. Then the `input-audio-info` endpoint serves cached data instead of computing it from scratch.
## Current Flow (Slow)
```
audio_download_worker: downloads FLAC → saves to GCS → transitions to awaiting_audio_edit
(no pre-generation)
User opens editor → GET /input-audio-info →
1. download FLAC from GCS to Cloud Run tmp (~5-8s)
2. generate waveform from FLAC (pydub) (~2-3s)
3. transcode FLAC→OGG + upload to GCS (~3-5s)
4. generate signed URL (~0.5s)
Total: ~10-20s
```
## Target Flow (Fast)
```
audio_download_worker: downloads FLAC → saves to GCS →
pre-generate:
1. transcode FLAC→OGG (reuse AudioTranscodingService)
2. generate waveform data → save as JSON to GCS
→ transitions to awaiting_audio_edit
User opens editor → GET /input-audio-info →
1. load cached waveform JSON from GCS (~0.5s)
2. generate signed URL for cached OGG (~0.5s)
Total: ~1s
```
## Implementation Steps
1. [ ] Add `cache_waveform_data` and `load_cached_waveform` to `AudioAnalysisService`
2. [ ] Add pre-generation to `audio_download_worker` before `awaiting_audio_edit` transition
3. [ ] Modify `input-audio-info` endpoint to use cached waveform when available
4. [ ] Add unit tests for cache methods, download worker, and endpoint cache hit/miss
5. [ ] Run full test suite
## Files to Modify
| File | Description |
|------|-------------|
| `backend/services/audio_analysis_service.py` | Add waveform cache/load methods |
| `backend/workers/audio_download_worker.py` | Add pre-generation before state transition |
| `backend/api/routes/review.py` | Use cached waveform in `input-audio-info` |
| `backend/tests/test_audio_edit_routes.py` | Tests for cache hit/miss |
| `backend/tests/test_audio_download_worker.py` | Test for pre-generation call |
+2
View File
@@ -18,6 +18,8 @@ jest.mock('@/lib/api', () => ({
api: {
searchStandalone: jest.fn(),
searchAudio: jest.fn(),
searchCatalogTracks: jest.fn(),
checkCommunityVersions: jest.fn(),
createJobFromSearch: jest.fn(),
createJobFromUrl: jest.fn(),
uploadJobSmart: jest.fn(),
+612
View File
@@ -0,0 +1,612 @@
"use client"
import { useEffect, useState, useCallback } from "react"
import {
adminApi,
AudioEditReviewSummary,
AudioEditReviewListResponse,
AudioEditReviewDetail,
} from "@/lib/api"
import { useAdminSettings } from "@/lib/admin-settings"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Skeleton } from "@/components/ui/skeleton"
import {
Search,
Loader2,
Eye,
Code,
ChevronLeft,
ChevronRight,
Copy,
Check,
Clock,
Scissors,
Play,
} from "lucide-react"
import { toast } from "sonner"
const PAGE_SIZE = 20
function formatDuration(seconds?: number): string {
if (seconds == null || !Number.isFinite(seconds)) return "-"
const mins = Math.floor(seconds / 60)
const secs = Math.floor(seconds % 60)
return `${mins}:${secs.toString().padStart(2, "0")}`
}
function formatDurationChange(original?: number, current?: number): string {
if (original == null || current == null) return ""
const diff = current - original
if (Math.abs(diff) < 0.5) return ""
const sign = diff < 0 ? "-" : "+"
const abs = Math.abs(diff)
const mins = Math.floor(abs / 60)
const secs = Math.floor(abs % 60)
return `${sign}${mins}:${secs.toString().padStart(2, "0")}`
}
// ─── Edit Stack Viewer ────────────────────────────────────────────────────
function EditStackViewer({
editStack,
}: {
editStack: AudioEditReviewDetail["edit_stack"]
}) {
if (editStack.length === 0) {
return (
<div className="flex items-center justify-center h-32 text-muted-foreground">
No edits applied.
</div>
)
}
return (
<div className="space-y-2">
{editStack.map((entry, idx) => (
<div key={entry.edit_id || idx} className="border rounded-md p-3">
<div className="flex items-center gap-2 mb-1">
<Badge variant="outline" className="text-xs">
{idx + 1}. {entry.operation}
</Badge>
<span className="text-xs text-muted-foreground">
{new Date(entry.timestamp).toLocaleString()}
</span>
</div>
<div className="flex items-center gap-3 text-sm">
{entry.duration_before != null && (
<span className="text-muted-foreground text-xs">
{formatDuration(entry.duration_before)}
</span>
)}
{entry.duration_before != null && entry.duration_after != null && (
<span className="text-xs text-muted-foreground">&rarr;</span>
)}
{entry.duration_after != null && (
<span className="text-xs font-medium">
{formatDuration(entry.duration_after)}
</span>
)}
{entry.params && Object.keys(entry.params).length > 0 && (
<span className="text-xs text-muted-foreground ml-2">
{Object.entries(entry.params)
.map(([k, v]) => `${k}: ${typeof v === "number" ? formatDuration(v) : v}`)
.join(", ")}
</span>
)}
</div>
</div>
))}
</div>
)
}
// ─── Sessions Viewer ──────────────────────────────────────────────────────
function SessionsViewer({
sessions,
}: {
sessions: AudioEditReviewDetail["sessions"]
}) {
if (sessions.length === 0) {
return (
<div className="flex items-center justify-center h-32 text-muted-foreground">
No saved sessions.
</div>
)
}
return (
<div className="space-y-3">
{sessions.map((session) => (
<Card key={session.session_id}>
<CardContent className="p-4">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-2">
<Badge
variant={
session.trigger === "submit"
? "default"
: session.trigger === "manual"
? "secondary"
: "outline"
}
className="text-xs"
>
{session.trigger}
</Badge>
<span className="text-xs text-muted-foreground">
{session.edit_count} edit{session.edit_count !== 1 ? "s" : ""}
</span>
</div>
<span className="text-xs text-muted-foreground">
{new Date(session.updated_at).toLocaleString()}
</span>
</div>
{/* Duration info */}
{session.original_duration_seconds != null && (
<div className="flex items-center gap-2 text-sm mb-2">
<span className="text-muted-foreground">
{formatDuration(session.original_duration_seconds)}
</span>
<span className="text-muted-foreground">&rarr;</span>
<span className="font-medium">
{formatDuration(session.audio_duration_seconds)}
</span>
{session.audio_duration_seconds != null && (
<span className="text-xs text-red-500">
{formatDurationChange(
session.original_duration_seconds,
session.audio_duration_seconds
)}
</span>
)}
</div>
)}
{/* Operations breakdown */}
{session.summary?.operations_breakdown && (
<div className="flex flex-wrap gap-1">
{Object.entries(session.summary.operations_breakdown).map(
([op, count]) => (
<Badge key={op} variant="secondary" className="text-xs">
{op}: {count}
</Badge>
)
)}
</div>
)}
<div className="text-xs text-muted-foreground mt-2 font-mono truncate">
{session.session_id}
</div>
</CardContent>
</Card>
))}
</div>
)
}
// ─── Main Page ────────────────────────────────────────────────────────────
export default function AudioEditsPage() {
const { showTestData } = useAdminSettings()
// List state
const [reviews, setReviews] = useState<AudioEditReviewSummary[]>([])
const [total, setTotal] = useState(0)
const [hasMore, setHasMore] = useState(false)
const [offset, setOffset] = useState(0)
const [searchQuery, setSearchQuery] = useState("")
const [searchInput, setSearchInput] = useState("")
const [loading, setLoading] = useState(true)
// Detail dialog state
const [detailDialogOpen, setDetailDialogOpen] = useState(false)
const [rawDataDialogOpen, setRawDataDialogOpen] = useState(false)
const [selectedDetail, setSelectedDetail] = useState<AudioEditReviewDetail | null>(null)
const [detailLoading, setDetailLoading] = useState(false)
const fetchReviews = useCallback(async () => {
setLoading(true)
try {
const data: AudioEditReviewListResponse =
await adminApi.listAudioEditReviews({
limit: PAGE_SIZE,
offset,
exclude_test: !showTestData,
search: searchQuery || undefined,
})
setReviews(data.reviews)
setTotal(data.total)
setHasMore(data.has_more)
} catch (err) {
toast.error(
"Failed to load audio edit reviews: " +
(err instanceof Error ? err.message : String(err))
)
} finally {
setLoading(false)
}
}, [offset, searchQuery, showTestData])
useEffect(() => {
fetchReviews()
}, [fetchReviews])
const loadDetail = useCallback(async (jobId: string) => {
setDetailLoading(true)
try {
const detail = await adminApi.getAudioEditReview(jobId)
setSelectedDetail(detail)
return detail
} catch (err) {
toast.error(
"Failed to load detail: " +
(err instanceof Error ? err.message : String(err))
)
return null
} finally {
setDetailLoading(false)
}
}, [])
const handleViewDetail = useCallback(
async (jobId: string) => {
const detail = await loadDetail(jobId)
if (detail) setDetailDialogOpen(true)
},
[loadDetail]
)
const handleViewRawData = useCallback(
async (jobId: string) => {
const detail = await loadDetail(jobId)
if (detail) setRawDataDialogOpen(true)
},
[loadDetail]
)
const handleSearch = useCallback(() => {
setOffset(0)
setSearchQuery(searchInput)
}, [searchInput])
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key === "Enter") handleSearch()
},
[handleSearch]
)
const [copiedJson, setCopiedJson] = useState(false)
const handleCopyJson = useCallback(() => {
if (!selectedDetail) return
navigator.clipboard.writeText(JSON.stringify(selectedDetail, null, 2))
setCopiedJson(true)
toast.success("Copied to clipboard")
setTimeout(() => setCopiedJson(false), 2000)
}, [selectedDetail])
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold">Audio Edits</h1>
<p className="text-muted-foreground">
Review input audio editing sessions and edit history
</p>
</div>
{/* Search */}
<div className="flex gap-2">
<div className="relative flex-1 max-w-md">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search by artist, title, or email..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
onKeyDown={handleKeyDown}
className="pl-8"
/>
</div>
<Button onClick={handleSearch} variant="secondary">
Search
</Button>
</div>
{/* Results */}
<Card>
<CardHeader className="py-3">
<CardTitle className="text-base">
{loading
? "Loading..."
: `${total} job${total !== 1 ? "s" : ""} with audio edits`}
</CardTitle>
</CardHeader>
<CardContent className="p-0">
{loading ? (
<div className="p-4 space-y-3">
{Array.from({ length: 5 }).map((_, i) => (
<Skeleton key={i} className="h-12 w-full" />
))}
</div>
) : reviews.length === 0 ? (
<div className="flex items-center justify-center h-48 text-muted-foreground">
No audio edit reviews found.
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Artist / Title</TableHead>
<TableHead>Status</TableHead>
<TableHead>Edits</TableHead>
<TableHead>Duration</TableHead>
<TableHead>Sessions</TableHead>
<TableHead>Updated</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{reviews.map((review) => (
<TableRow key={review.job_id}>
<TableCell>
<div className="font-medium">{review.artist}</div>
<div className="text-sm text-muted-foreground">
{review.title}
</div>
</TableCell>
<TableCell>
<Badge
variant={
review.status === "complete"
? "default"
: review.status.includes("audio_edit")
? "secondary"
: "outline"
}
>
{review.status}
</Badge>
</TableCell>
<TableCell>
<span className="font-medium">{review.total_edits}</span>
{review.latest_trigger && (
<Badge variant="outline" className="ml-1 text-xs">
{review.latest_trigger}
</Badge>
)}
</TableCell>
<TableCell className="text-sm">
{review.original_duration != null ? (
<div className="flex items-center gap-1">
<span className="text-muted-foreground">
{formatDuration(review.original_duration)}
</span>
{review.current_duration != null &&
review.current_duration !== review.original_duration && (
<>
<span className="text-muted-foreground">
&rarr;
</span>
<span className="font-medium">
{formatDuration(review.current_duration)}
</span>
</>
)}
</div>
) : (
"-"
)}
</TableCell>
<TableCell className="text-sm">
{review.session_count}
</TableCell>
<TableCell className="text-sm text-muted-foreground">
{review.updated_at
? new Date(review.updated_at).toLocaleDateString()
: "-"}
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => handleViewDetail(review.job_id)}
disabled={detailLoading}
title="View Detail"
>
<Eye className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => handleViewRawData(review.job_id)}
disabled={detailLoading}
title="View Raw Data"
>
<Code className="w-4 h-4" />
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
{/* Pagination */}
{!loading && total > PAGE_SIZE && (
<div className="flex items-center justify-between p-4 border-t">
<Button
variant="outline"
size="sm"
disabled={offset === 0}
onClick={() =>
setOffset((o) => Math.max(0, o - PAGE_SIZE))
}
>
<ChevronLeft className="w-4 h-4 mr-1" /> Previous
</Button>
<span className="text-sm text-muted-foreground">
Showing {offset + 1}-{Math.min(offset + PAGE_SIZE, total)} of{" "}
{total}
</span>
<Button
variant="outline"
size="sm"
disabled={!hasMore}
onClick={() => setOffset((o) => o + PAGE_SIZE)}
>
Next <ChevronRight className="w-4 h-4 ml-1" />
</Button>
</div>
)}
</CardContent>
</Card>
{/* Detail Dialog */}
<Dialog open={detailDialogOpen} onOpenChange={setDetailDialogOpen}>
<DialogContent className="max-w-3xl w-full max-h-[90vh] flex flex-col">
<DialogHeader>
<DialogTitle>
{selectedDetail
? `${selectedDetail.job.artist} - ${selectedDetail.job.title}`
: "Loading..."}
</DialogTitle>
</DialogHeader>
<div className="flex-1 overflow-auto">
{detailLoading ? (
<div className="flex items-center justify-center h-48">
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
</div>
) : selectedDetail ? (
<Tabs defaultValue="edit-stack" className="w-full">
<TabsList className="w-full">
<TabsTrigger value="edit-stack" className="flex-1">
<Scissors className="w-3 h-3 mr-1" />
Edit Stack ({selectedDetail.edit_stack.length})
</TabsTrigger>
<TabsTrigger value="sessions" className="flex-1">
<Clock className="w-3 h-3 mr-1" />
Sessions ({selectedDetail.sessions.length})
</TabsTrigger>
<TabsTrigger value="audio" className="flex-1">
<Play className="w-3 h-3 mr-1" />
Audio
</TabsTrigger>
</TabsList>
<TabsContent value="edit-stack">
<ScrollArea className="h-[500px]">
<EditStackViewer editStack={selectedDetail.edit_stack} />
</ScrollArea>
</TabsContent>
<TabsContent value="sessions">
<ScrollArea className="h-[500px]">
<SessionsViewer sessions={selectedDetail.sessions} />
</ScrollArea>
</TabsContent>
<TabsContent value="audio">
<div className="space-y-4 p-2">
{selectedDetail.original_audio_url && (
<div>
<div className="text-sm font-medium mb-2">
Original Audio
</div>
<audio
controls
src={selectedDetail.original_audio_url}
className="w-full"
/>
</div>
)}
{selectedDetail.current_audio_url && (
<div>
<div className="text-sm font-medium mb-2">
Current Audio
{selectedDetail.original_audio_url
? " (after edits)"
: ""}
</div>
<audio
controls
src={selectedDetail.current_audio_url}
className="w-full"
/>
</div>
)}
{!selectedDetail.original_audio_url &&
!selectedDetail.current_audio_url && (
<div className="flex items-center justify-center h-32 text-muted-foreground">
No audio URLs available.
</div>
)}
</div>
</TabsContent>
</Tabs>
) : (
<div className="flex items-center justify-center h-48 text-muted-foreground">
No data available.
</div>
)}
</div>
</DialogContent>
</Dialog>
{/* Raw Data Dialog */}
<Dialog open={rawDataDialogOpen} onOpenChange={setRawDataDialogOpen}>
<DialogContent className="max-w-4xl w-full max-h-[85vh] flex flex-col">
<DialogHeader>
<DialogTitle>
Raw Data
{selectedDetail && (
<span className="text-sm font-normal text-muted-foreground ml-2">
{selectedDetail.job.artist} - {selectedDetail.job.title}
</span>
)}
</DialogTitle>
</DialogHeader>
<div className="flex-1 overflow-auto">
<div className="flex justify-end mb-2">
<Button variant="outline" size="sm" onClick={handleCopyJson}>
{copiedJson ? (
<Check className="w-3 h-3 mr-1" />
) : (
<Copy className="w-3 h-3 mr-1" />
)}
Copy
</Button>
</div>
<ScrollArea className="h-[500px]">
<pre className="text-xs bg-muted/50 p-3 rounded-md overflow-x-auto">
{JSON.stringify(selectedDetail, null, 2) ?? "null"}
</pre>
</ScrollArea>
</div>
</DialogContent>
</Dialog>
</div>
)
}
+10 -3
View File
@@ -9,11 +9,12 @@ import { ArrowLeft, AlertCircle } from "lucide-react"
import Link from "next/link"
import { LyricsAnalyzer } from "@/components/lyrics-review"
import { InstrumentalSelector } from "@/components/instrumental-review"
import { AudioEditor } from "@/components/audio-editor/AudioEditor"
import { ThemeToggle } from "@/components/ThemeToggle"
import type { CorrectionData } from "@/lib/lyrics-review/types"
import { isLocalMode, createLocalModeJob } from "@/lib/local-mode"
type RouteType = "review" | "instrumental" | "unknown"
type RouteType = "review" | "instrumental" | "audio-edit" | "unknown"
type AccessState =
| { status: "loading" }
@@ -34,7 +35,7 @@ function parseRouteFromPathname(pathname: string): { jobId: string | null; route
// Expected format: /app/jobs/{jobId}/{action}
// e.g., /app/jobs/local/review or /app/jobs/local/instrumental
const match = pathname.match(/^\/app\/jobs\/([^/]+)\/(review|instrumental)\/?$/)
const match = pathname.match(/^\/app\/jobs\/([^/]+)\/(review|instrumental|audio-edit)\/?$/)
if (match) {
const [, jobId, action] = match
@@ -54,7 +55,7 @@ function parseRouteFromHash(hash: string): { jobId: string | null; routeType: Ro
// Remove the leading '#' and parse
const hashPath = hash.substring(1)
// Support BOTH review and instrumental routes
const match = hashPath.match(/^\/?([^/]+)\/(review|instrumental)\/?$/)
const match = hashPath.match(/^\/?([^/]+)\/(review|instrumental|audio-edit)\/?$/)
if (match) {
const [, jobId, action] = match
@@ -69,6 +70,8 @@ function getExpectedStates(routeType: RouteType): string[] {
return ["awaiting_review", "in_review"]
case "instrumental":
return ["awaiting_review", "in_review"] // Same states for now
case "audio-edit":
return ["awaiting_audio_edit", "in_audio_edit"]
default:
return []
}
@@ -305,6 +308,10 @@ export function JobRouterClient() {
? accessState.routeType
: "review" // Fallback (shouldn't happen since we return early for other statuses)
if (currentRouteType === "audio-edit") {
return <AudioEditor job={job} />
}
if (currentRouteType === "instrumental") {
return <InstrumentalReviewWrapper job={job} isLocalMode={inLocalMode} />
}
+9
View File
@@ -67,6 +67,12 @@ export function AutoProcessor({ jobs, onJobsChanged }: AutoProcessorProps) {
await api.selectAudioResult(job.job_id, 0)
console.log(`[AutoProcessor] Auto-selected first audio result for job ${job.job_id}`)
break
case 'audio_edit':
// Auto-submit audio edit with no changes (skip editing)
await api.submitAudioEdit(job.job_id)
console.log(`[AutoProcessor] Auto-submitted audio edit (no changes) for job ${job.job_id}`)
break
}
// Refresh jobs to reflect the change
@@ -98,6 +104,9 @@ export function AutoProcessor({ jobs, onJobsChanged }: AutoProcessorProps) {
case 'awaiting_audio_selection':
processJob(job, 'audio')
break
case 'awaiting_audio_edit':
processJob(job, 'audio_edit')
break
}
}
}, [jobs, processJob])
@@ -40,6 +40,7 @@ describe('AdminJobActions', () => {
// Reset buttons
expect(screen.getByText('Audio')).toBeInTheDocument()
expect(screen.getByText('Audio Edit')).toBeInTheDocument()
expect(screen.getByText('Review')).toBeInTheDocument()
expect(screen.getByText('Reprocess')).toBeInTheDocument()
@@ -12,6 +12,7 @@ import {
Search,
ShieldAlert,
BookOpenCheck,
Scissors,
} from "lucide-react"
import {
@@ -64,6 +65,11 @@ const navItems = [
href: "/admin/edit-reviews",
icon: BookOpenCheck,
},
{
title: "Audio Edits",
href: "/admin/audio-edits",
icon: Scissors,
},
]
export function AdminSidebar() {
@@ -0,0 +1,220 @@
"use client"
import { useState, useEffect } from "react"
import { api, AudioEditSessionMeta, AudioEditSessionWithData, AudioEditEntry } from "@/lib/api"
import { Button } from "@/components/ui/button"
import { Spinner } from "@/components/ui/spinner"
import { X, History, ChevronRight } from "lucide-react"
interface AudioEditRestoreDialogProps {
jobId: string
onRestore: (entries: AudioEditEntry[]) => void
onStartFresh: () => void
}
function formatDate(dateStr: string): string {
const d = new Date(dateStr)
return d.toLocaleDateString(undefined, {
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit",
})
}
function formatDuration(seconds: number): string {
if (!Number.isFinite(seconds)) return "0:00"
const mins = Math.floor(Math.abs(seconds) / 60)
const secs = Math.floor(Math.abs(seconds) % 60)
const sign = seconds < 0 ? "-" : "+"
return `${sign}${mins}:${secs.toString().padStart(2, "0")}`
}
export function AudioEditRestoreDialog({
jobId,
onRestore,
onStartFresh,
}: AudioEditRestoreDialogProps) {
const [sessions, setSessions] = useState<AudioEditSessionMeta[]>([])
const [isLoading, setIsLoading] = useState(true)
const [selectedSessionId, setSelectedSessionId] = useState<string | null>(null)
const [selectedSession, setSelectedSession] = useState<AudioEditSessionWithData | null>(null)
const [isLoadingDetail, setIsLoadingDetail] = useState(false)
const [isRestoring, setIsRestoring] = useState(false)
// Load sessions list
useEffect(() => {
async function loadSessions() {
try {
const { sessions } = await api.listAudioEditSessions(jobId)
setSessions(sessions)
if (sessions.length > 0) {
setSelectedSessionId(sessions[0].session_id)
}
} catch (err) {
console.warn("Failed to load audio edit sessions:", err)
} finally {
setIsLoading(false)
}
}
loadSessions()
}, [jobId])
// Load selected session detail
useEffect(() => {
if (!selectedSessionId) return
async function loadDetail() {
setIsLoadingDetail(true)
try {
const session = await api.getAudioEditSession(jobId, selectedSessionId!)
setSelectedSession(session)
} catch (err) {
console.warn("Failed to load session detail:", err)
} finally {
setIsLoadingDetail(false)
}
}
loadDetail()
}, [jobId, selectedSessionId])
async function handleRestore() {
if (!selectedSession?.edit_data?.entries) return
setIsRestoring(true)
onRestore(selectedSession.edit_data.entries)
}
if (isLoading) {
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
<div
className="rounded-lg border p-6 max-w-lg w-full text-center"
style={{ borderColor: "var(--card-border)", backgroundColor: "var(--card)" }}
>
<Spinner className="w-6 h-6 mx-auto mb-2" />
<p className="text-sm text-muted-foreground">Checking for saved sessions...</p>
</div>
</div>
)
}
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
<div
className="rounded-lg border max-w-2xl w-full flex flex-col max-h-[80vh]"
style={{ borderColor: "var(--card-border)", backgroundColor: "var(--card)" }}
>
{/* Header */}
<div className="flex items-center justify-between p-4 border-b" style={{ borderColor: "var(--card-border)" }}>
<div className="flex items-center gap-2">
<History className="w-5 h-5 text-blue-400" />
<h2 className="text-lg font-semibold" style={{ color: "var(--text)" }}>
Saved Audio Edit Sessions
</h2>
</div>
<button onClick={onStartFresh} className="text-muted-foreground hover:text-foreground">
<X className="w-5 h-5" />
</button>
</div>
{/* Content */}
<div className="flex flex-1 min-h-0">
{/* Session list */}
<div
className="w-1/3 border-r overflow-y-auto p-2 space-y-1"
style={{ borderColor: "var(--card-border)" }}
>
{sessions.map((session, i) => (
<button
key={session.session_id}
onClick={() => setSelectedSessionId(session.session_id)}
className={`w-full text-left rounded p-2 text-xs transition-colors ${
selectedSessionId === session.session_id
? "bg-primary/10 border border-primary/30"
: "hover:bg-secondary/50"
}`}
>
<div className="flex items-center gap-1">
<ChevronRight className="w-3 h-3 shrink-0" />
<div className="min-w-0">
<p className="font-medium truncate" style={{ color: "var(--text)" }}>
{formatDate(session.created_at)}
</p>
<p className="text-muted-foreground">
{session.edit_count} edit{session.edit_count !== 1 ? "s" : ""} · {session.trigger}
{i === 0 && (
<span className="ml-1 text-blue-400">[Latest]</span>
)}
</p>
</div>
</div>
</button>
))}
</div>
{/* Session detail */}
<div className="flex-1 p-4 overflow-y-auto">
{isLoadingDetail ? (
<div className="flex items-center justify-center py-8">
<Spinner className="w-5 h-5" />
</div>
) : selectedSession?.edit_data?.entries ? (
<div className="space-y-3">
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>
Operations applied:
</p>
<div className="space-y-1.5">
{selectedSession.edit_data.entries.map((entry: AudioEditEntry, i: number) => (
<div key={entry.edit_id || i} className="flex items-center gap-2 text-xs">
<span className="text-muted-foreground w-4 text-right">{i + 1}.</span>
<span className="font-medium capitalize" style={{ color: "var(--text)" }}>
{entry.operation.replace(/_/g, " ")}
</span>
<span className="text-muted-foreground">
{Math.floor(entry.duration_before / 60)}:{String(Math.floor(entry.duration_before % 60)).padStart(2, "0")}
{" → "}
{Math.floor(entry.duration_after / 60)}:{String(Math.floor(entry.duration_after % 60)).padStart(2, "0")}
</span>
</div>
))}
</div>
{selectedSession.summary && (
<div className="text-xs text-muted-foreground pt-2 border-t" style={{ borderColor: "var(--card-border)" }}>
<p>
Duration change: {formatDuration(selectedSession.summary.duration_change_seconds)}
</p>
<p>
Net duration: {Math.floor(selectedSession.summary.net_duration_seconds / 60)}:
{String(Math.floor(selectedSession.summary.net_duration_seconds % 60)).padStart(2, "0")}
</p>
</div>
)}
</div>
) : (
<p className="text-sm text-muted-foreground">Select a session to preview</p>
)}
</div>
</div>
{/* Footer */}
<div className="flex items-center justify-end gap-2 p-4 border-t" style={{ borderColor: "var(--card-border)" }}>
<Button variant="outline" onClick={onStartFresh} disabled={isRestoring}>
Start Fresh
</Button>
<Button
onClick={handleRestore}
disabled={!selectedSession?.edit_data?.entries || isRestoring}
>
{isRestoring ? (
<>
<Spinner className="w-4 h-4 mr-1" />
Restoring...
</>
) : (
"Restore Selected"
)}
</Button>
</div>
</div>
</div>
)
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,418 @@
/**
* Tests for AudioEditor component.
*
* Tests loading state, error handling, waveform rendering,
* edit operations, and submit flow.
*/
import { render, screen, fireEvent, waitFor, act } from "@testing-library/react"
import { AudioEditor } from "../AudioEditor"
import { api, AudioEditInfo, AudioEditResponse } from "@/lib/api"
// Mock next/link
jest.mock("next/link", () => {
return function Link({ children, href, ...props }: { children: React.ReactNode; href: string; [key: string]: unknown }) {
return <a href={href} {...props}>{children}</a>
}
})
// Mock next/image
jest.mock("next/image", () => ({
__esModule: true,
default: (props: Record<string, unknown>) => <img {...props} />,
}))
// Mock ThemeToggle
jest.mock("@/components/ThemeToggle", () => ({
ThemeToggle: () => <div data-testid="theme-toggle" />,
}))
// Mock auto-save hook
jest.mock("@/hooks/use-audio-edit-autosave", () => ({
useAudioEditAutoSave: () => ({ saveSession: jest.fn() }),
}))
// Mock canvas
HTMLCanvasElement.prototype.getContext = jest.fn(() => ({
fillRect: jest.fn(),
fillText: jest.fn(),
measureText: jest.fn(() => ({ width: 20 })),
beginPath: jest.fn(),
moveTo: jest.fn(),
lineTo: jest.fn(),
stroke: jest.fn(),
setLineDash: jest.fn(),
fillStyle: "",
strokeStyle: "",
lineWidth: 1,
font: "",
textBaseline: "",
})) as jest.Mock
// Mock api
jest.mock("@/lib/api", () => {
const actual = jest.requireActual("@/lib/api")
return {
...actual,
api: {
getInputAudioInfo: jest.fn(),
applyAudioEdit: jest.fn(),
undoAudioEdit: jest.fn(),
redoAudioEdit: jest.fn(),
uploadAudioForJoin: jest.fn(),
submitAudioEdit: jest.fn(),
listAudioEditSessions: jest.fn(),
saveAudioEditSession: jest.fn(),
getAudioEditSession: jest.fn(),
},
}
})
const mockApi = api as jest.Mocked<typeof api>
const mockJob = {
job_id: "test-job-123",
status: "in_audio_edit",
progress: 50,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
artist: "Test Artist",
title: "Test Song",
}
const mockAudioInfo: AudioEditInfo = {
job_id: "test-job-123",
artist: "Test Artist",
title: "Test Song",
original_duration_seconds: 200,
current_duration_seconds: 200,
original_audio_url: "https://example.com/original.ogg",
current_audio_url: "https://example.com/current.ogg",
waveform_data: { amplitudes: Array(100).fill(0.5) },
original_waveform_data: { amplitudes: Array(100).fill(0.5) },
edit_stack: [],
can_undo: false,
can_redo: false,
}
const mockEditResponse: AudioEditResponse = {
status: "success",
edit_id: "edit-1",
operation: "trim_start",
duration_before: 200,
duration_after: 180,
current_audio_url: "https://example.com/edited.ogg",
waveform_data: { amplitudes: Array(90).fill(0.5) },
edit_stack: [
{
edit_id: "edit-1",
operation: "trim_start",
params: { end_seconds: 20 },
duration_before: 200,
duration_after: 180,
timestamp: new Date().toISOString(),
},
],
can_undo: true,
can_redo: false,
}
describe("AudioEditor", () => {
beforeEach(() => {
jest.clearAllMocks()
// Mock localStorage
Storage.prototype.getItem = jest.fn(() => null)
Storage.prototype.setItem = jest.fn()
// Default: no saved sessions
mockApi.listAudioEditSessions.mockResolvedValue({ sessions: [] })
mockApi.saveAudioEditSession.mockResolvedValue({ status: "saved", session_id: "s1" })
})
it("shows loading state initially", () => {
mockApi.getInputAudioInfo.mockReturnValue(new Promise(() => {})) // Never resolves
render(<AudioEditor job={mockJob} />)
expect(screen.getByText("Loading audio editor...")).toBeInTheDocument()
})
it("shows error state when loading fails", async () => {
mockApi.getInputAudioInfo.mockRejectedValue(new Error("Failed to load"))
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Failed to load audio")).toBeInTheDocument()
})
})
it("renders editor after loading", async () => {
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Audio Editor")).toBeInTheDocument()
})
expect(screen.getByText("Test Artist - Test Song")).toBeInTheDocument()
})
it("shows guidance panel by default", async () => {
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Audio Editor Tips")).toBeInTheDocument()
})
})
it("shows Original and Edited tabs", async () => {
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText(/Original/)).toBeInTheDocument()
expect(screen.getByText(/Edited/)).toBeInTheDocument()
})
})
it("shows 'Continue Without Editing' when no edits", async () => {
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Continue Without Editing")).toBeInTheDocument()
})
})
it("shows 'Submit & Continue' when there are edits", async () => {
const infoWithEdits = {
...mockAudioInfo,
current_duration_seconds: 180,
edit_stack: mockEditResponse.edit_stack,
can_undo: true,
}
mockApi.getInputAudioInfo.mockResolvedValue(infoWithEdits)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Submit & Continue")).toBeInTheDocument()
})
})
it("shows edit history when there are edits", async () => {
const infoWithEdits = {
...mockAudioInfo,
current_duration_seconds: 180,
edit_stack: mockEditResponse.edit_stack,
can_undo: true,
}
mockApi.getInputAudioInfo.mockResolvedValue(infoWithEdits)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText(/Edit History/)).toBeInTheDocument()
})
})
it("submits without confirm when no edits", async () => {
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
mockApi.submitAudioEdit.mockResolvedValue({ status: "success", message: "ok", job_id: "test-job-123" })
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Continue Without Editing")).toBeInTheDocument()
})
fireEvent.click(screen.getByText("Continue Without Editing"))
await waitFor(() => {
expect(mockApi.submitAudioEdit).toHaveBeenCalledWith("test-job-123", undefined)
})
})
it("shows confirm dialog when submitting with edits", async () => {
const infoWithEdits = {
...mockAudioInfo,
current_duration_seconds: 180,
edit_stack: mockEditResponse.edit_stack,
can_undo: true,
}
mockApi.getInputAudioInfo.mockResolvedValue(infoWithEdits)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Submit & Continue")).toBeInTheDocument()
})
fireEvent.click(screen.getByText("Submit & Continue"))
await waitFor(() => {
expect(screen.getByText("Submit Edited Audio?")).toBeInTheDocument()
})
})
it("shows success screen after submit", async () => {
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
mockApi.submitAudioEdit.mockResolvedValue({ status: "success", message: "ok", job_id: "test-job-123" })
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Continue Without Editing")).toBeInTheDocument()
})
fireEvent.click(screen.getByText("Continue Without Editing"))
await waitFor(() => {
expect(screen.getByText("Audio edit complete!")).toBeInTheDocument()
})
})
it("shows undo/redo buttons", async () => {
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByTitle("Undo (Ctrl+Z)")).toBeInTheDocument()
expect(screen.getByTitle("Redo (Ctrl+Shift+Z)")).toBeInTheDocument()
})
})
it("disables undo when canUndo is false", async () => {
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByTitle("Undo (Ctrl+Z)")).toBeDisabled()
})
})
it("enables undo when canUndo is true", async () => {
const infoWithUndo = { ...mockAudioInfo, can_undo: true, edit_stack: mockEditResponse.edit_stack }
mockApi.getInputAudioInfo.mockResolvedValue(infoWithUndo)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByTitle("Undo (Ctrl+Z)")).not.toBeDisabled()
})
})
it("calls undo API when clicking undo", async () => {
const infoWithUndo = {
...mockAudioInfo,
can_undo: true,
edit_stack: mockEditResponse.edit_stack,
current_duration_seconds: 180,
}
mockApi.getInputAudioInfo.mockResolvedValue(infoWithUndo)
mockApi.undoAudioEdit.mockResolvedValue({
...mockEditResponse,
edit_stack: [],
can_undo: false,
can_redo: true,
duration_after: 200,
})
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByTitle("Undo (Ctrl+Z)")).not.toBeDisabled()
})
fireEvent.click(screen.getByTitle("Undo (Ctrl+Z)"))
await waitFor(() => {
expect(mockApi.undoAudioEdit).toHaveBeenCalledWith("test-job-123")
})
})
it("shows Join button", async () => {
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Join")).toBeInTheDocument()
})
})
it("opens join dialog when clicking Join", async () => {
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Join")).toBeInTheDocument()
})
fireEvent.click(screen.getByText("Join"))
await waitFor(() => {
expect(screen.getByText("Join Audio")).toBeInTheDocument()
})
})
it("shows playback controls", async () => {
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByTitle("Back 5s")).toBeInTheDocument()
expect(screen.getByTitle("Forward 5s")).toBeInTheDocument()
})
})
it("shows restore dialog when saved sessions exist", async () => {
const sessions = [{
session_id: "s1",
job_id: "test-job-123",
edit_count: 2,
trigger: "auto",
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
}]
mockApi.listAudioEditSessions.mockResolvedValue({ sessions })
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
mockApi.getAudioEditSession.mockResolvedValue({
...sessions[0],
edit_data: { entries: mockEditResponse.edit_stack },
})
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Saved Audio Edit Sessions")).toBeInTheDocument()
})
})
it("does not show restore dialog when no sessions exist", async () => {
mockApi.listAudioEditSessions.mockResolvedValue({ sessions: [] })
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Audio Editor")).toBeInTheDocument()
})
expect(screen.queryByText("Saved Audio Edit Sessions")).not.toBeInTheDocument()
})
it("does not show restore dialog when edits already applied", async () => {
const sessions = [{
session_id: "s1",
job_id: "test-job-123",
edit_count: 2,
trigger: "auto",
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
}]
mockApi.listAudioEditSessions.mockResolvedValue({ sessions })
const infoWithEdits = {
...mockAudioInfo,
edit_stack: mockEditResponse.edit_stack,
can_undo: true,
}
mockApi.getInputAudioInfo.mockResolvedValue(infoWithEdits)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Audio Editor")).toBeInTheDocument()
})
expect(screen.queryByText("Saved Audio Edit Sessions")).not.toBeInTheDocument()
})
it("shows Save button when there are edits", async () => {
const infoWithEdits = {
...mockAudioInfo,
current_duration_seconds: 180,
edit_stack: mockEditResponse.edit_stack,
can_undo: true,
}
mockApi.getInputAudioInfo.mockResolvedValue(infoWithEdits)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Save")).toBeInTheDocument()
})
})
it("does not show Save button when no edits", async () => {
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Audio Editor")).toBeInTheDocument()
})
expect(screen.queryByText("Save")).not.toBeInTheDocument()
})
})
@@ -12,6 +12,7 @@ import {
CloudOff,
Music,
Mic,
Scissors,
} from "lucide-react"
interface AdminJobActionsProps {
@@ -107,6 +108,13 @@ export function AdminJobActions({ job, onRefresh }: AdminJobActionsProps) {
{isLoading("reset-awaiting_audio_selection") ? <Loader2 className="w-3 h-3 animate-spin" /> : <Music className="w-3 h-3 mr-0.5" />}
Audio
</Button>
<Button variant="ghost" size="sm" className="h-6 px-1.5 text-[11px] text-blue-400 hover:text-blue-300"
onClick={() => handleReset("awaiting_audio_edit", "Audio Edit")}
disabled={loading !== null}
>
{isLoading("reset-awaiting_audio_edit") ? <Loader2 className="w-3 h-3 animate-spin" /> : <Scissors className="w-3 h-3 mr-0.5" />}
Audio Edit
</Button>
<Button variant="ghost" size="sm" className="h-6 px-1.5 text-[11px] text-blue-400 hover:text-blue-300"
onClick={() => handleReset("awaiting_review", "Review")}
disabled={loading !== null}
@@ -1,6 +1,6 @@
"use client"
import { X, ExternalLink } from "lucide-react"
import { X, ExternalLink, Youtube, AlertTriangle } from "lucide-react"
import type { CommunityCheckResponse } from "@/lib/api"
interface CommunityVersionBannerProps {
@@ -40,7 +40,8 @@ export function CommunityVersionBanner({ data, onDismiss }: CommunityVersionBann
</button>
<div className="pr-6">
<p className="text-sm font-medium" style={{ color: "rgb(34, 197, 94)" }}>
<p className="text-sm font-medium flex items-center gap-1.5" style={{ color: "rgb(34, 197, 94)" }}>
<AlertTriangle className="w-4 h-4 shrink-0" />
A karaoke version of this song already exists!
</p>
<p className="text-xs mt-1" style={{ color: "var(--text-muted)" }}>
@@ -72,7 +73,8 @@ export function CommunityVersionBanner({ data, onDismiss }: CommunityVersionBann
</span>
)}
</span>
<span className="ml-auto shrink-0 text-[10px]" style={{ color: "var(--text-muted)" }}>
<span className="ml-auto shrink-0 text-[10px] flex items-center gap-1" style={{ color: "var(--text-muted)" }}>
<Youtube className="w-3 h-3 text-red-500" />
Watch on YouTube
</span>
</a>
+46 -2
View File
@@ -105,6 +105,7 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
const [displayArtist, setDisplayArtist] = useState("")
const [displayTitle, setDisplayTitle] = useState("")
const [isPrivate, setIsPrivate] = useState(false)
const [requiresAudioEdit, setRequiresAudioEdit] = useState(false)
// Custom style state
const [karaokeBackground, setKaraokeBackground] = useState<File | null>(null)
@@ -142,6 +143,11 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
setStep(3)
}
function handleArtistTitleCorrection(newArtist: string, newTitle: string) {
setArtist(newArtist)
setTitle(newTitle)
}
function handleSearchResultChosen(resultIndex: number) {
// Just store the choice — job is created at Step 3 confirm
setSelectedResultIndex(resultIndex)
@@ -161,13 +167,14 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
// URL fallback path — create job now with visibility from Step 3
const response = await api.createJobFromUrl(pendingUrl, effectiveArtist, effectiveTitle, {
is_private: isPrivate,
requires_audio_edit: requiresAudioEdit || undefined,
})
createdJobId = response.job_id
} else if (audioSource === "upload" && pendingFile) {
// Upload fallback path — upload and create job now with visibility from Step 3
const response = await api.uploadJobSmart(
pendingFile, effectiveArtist, effectiveTitle,
{ is_private: isPrivate },
{ is_private: isPrivate, requires_audio_edit: requiresAudioEdit || undefined },
)
createdJobId = response.job_id
} else if (searchSessionId && selectedResultIndex !== null) {
@@ -180,6 +187,7 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
display_artist: displayArtist.trim() || undefined,
display_title: displayTitle.trim() || undefined,
is_private: isPrivate,
requires_audio_edit: requiresAudioEdit || undefined,
})
createdJobId = response.job_id
} else {
@@ -235,6 +243,7 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
setDisplayArtist("")
setDisplayTitle("")
setIsPrivate(false)
setRequiresAudioEdit(false)
setKaraokeBackground(null)
setIntroBackground(null)
setColorOverrides({})
@@ -301,6 +310,39 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
</div>
</div>
{/* Step 1.5: Audio editing (conditional) */}
{requiresAudioEdit && (
<div className="flex gap-3">
<div className="flex flex-col items-center">
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0" style={{ backgroundColor: 'rgba(255, 122, 204, 0.15)' }}>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{ color: 'var(--brand-pink)' }}>
<path d="M13.5 3.5l-1-1L8 7l-1.5-1.5-1 1L8 9l5.5-5.5Z" fill="currentColor" opacity="0.85"/>
<path d="M2 12h12v1.5H2z" fill="currentColor" opacity="0.5"/>
</svg>
</div>
<div className="w-px flex-1 min-h-[20px]" style={{ backgroundColor: 'var(--card-border)' }} />
</div>
<div className="pb-4 pt-1">
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>You edit the audio</p>
<p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>
Trim, cut, or mute sections of the downloaded audio before processing begins.
</p>
<div className="flex items-center gap-2 mt-1.5 flex-wrap">
<span className="inline-block text-[10px] px-1.5 py-0.5 rounded-full font-medium" style={{ backgroundColor: 'rgba(255, 122, 204, 0.15)', color: 'var(--brand-pink)' }}>
You
</span>
<span className="flex items-center gap-1 text-[10px]" style={{ color: 'var(--text-muted)' }}>
<svg width="12" height="12" viewBox="0 0 16 16" fill="none">
<path d="M2 3.5A1.5 1.5 0 0 1 3.5 2h9A1.5 1.5 0 0 1 14 3.5v.401a1 1 0 0 1-.373.78L8.707 8.79a1 1 0 0 1-1.414 0L2.373 4.68A1 1 0 0 1 2 3.9V3.5Z" fill="currentColor" opacity="0.7"/>
<path d="M2 6.12l4.586 3.59a2 2 0 0 0 2.828 0L14 6.12V12.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 12.5V6.12Z" fill="currentColor" opacity="0.5"/>
</svg>
Email + chime when ready
</span>
</div>
</div>
</div>
)}
{/* Step 2: User review */}
<div className="flex gap-3">
<div className="flex flex-col items-center">
@@ -420,7 +462,7 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
{isCompleted ? "\u2713" : stepNum}
</div>
<span
className={`text-[10px] whitespace-nowrap transition-colors ${
className={`text-[10px] transition-colors hidden sm:inline ${
isActive ? 'font-medium' : ''
}`}
style={{ color: isActive ? 'var(--text)' : 'var(--text-muted)' }}
@@ -467,10 +509,12 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
title={title}
onSearchCompleted={handleSearchCompleted}
onSearchResultChosen={handleSearchResultChosen}
onArtistTitleCorrection={handleArtistTitleCorrection}
onUrlReady={handleUrlReady}
onFileReady={handleFileReady}
onBack={handleBackFromAudio}
noCredits={noCredits}
onAudioEditChange={setRequiresAudioEdit}
/>
)}
+13 -1
View File
@@ -84,7 +84,8 @@ export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
const isInteractive = job.status === "awaiting_review" ||
job.status === "in_review" ||
job.status === "awaiting_instrumental_selection" ||
job.status === "awaiting_audio_selection"
job.status === "awaiting_audio_selection" ||
job.status === "awaiting_audio_edit"
const isComplete = job.status === "complete"
const isFailed = job.status === "failed"
@@ -114,6 +115,17 @@ export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
)
}
if (job.status === "awaiting_audio_edit") {
return (
<a
href={`/app/jobs#/${job.job_id}/audio-edit`}
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-primary-500 hover:bg-primary-600 text-white"
>
Edit Audio
</a>
)
}
if (job.status === "awaiting_audio_selection") {
return (
<Button
@@ -0,0 +1,277 @@
/**
* Tests for AudioSourceStep component.
*
* Covers the new features added in this branch:
* - Catalog search fires in parallel on mount
* - Community check fires in parallel on mount
* - SongSuggestionPanel renders when catalog results arrive
* - CommunityVersionBanner renders when community data arrives
* - "Did you mean?" fuzzy banner renders for poor search + no exact catalog match
* - onArtistTitleCorrection callback is invoked on catalog/fuzzy correction
* - Error and loading states
* - Credit error shows Buy Credits
*/
import { render, screen, waitFor, act } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { api, ApiError } from "@/lib/api"
// Mock the api module
jest.mock("@/lib/api", () => ({
api: {
searchStandalone: jest.fn(),
searchCatalogTracks: jest.fn(),
checkCommunityVersions: jest.fn(),
createJobFromSearch: jest.fn(),
},
ApiError: class ApiError extends Error {
status: number
data?: any
constructor(message: string, status: number, data?: any) {
super(message)
this.name = "ApiError"
this.status = status
this.data = data
}
},
}))
// Mock BuyCreditsDialog
jest.mock("@/components/credits/BuyCreditsDialog", () => ({
BuyCreditsDialog: ({ open }: { open: boolean }) =>
open ? <div data-testid="buy-credits-dialog">Buy Credits</div> : null,
}))
// Mock audio-search-utils to provide simple implementations
jest.mock("@/lib/audio-search-utils", () => ({
groupResults: jest.fn(() => new Map()),
getSearchConfidence: jest.fn(() => ({
tier: 1,
bestResult: { index: 0, title: "Waterloo", artist: "ABBA", provider: "YouTube", url: "https://yt.com/1" },
bestCategory: "LOSSLESS",
explanation: "Perfect match",
warnings: [],
})),
getAvailabilityLabel: jest.fn(() => ({ text: "", tooltip: "" })),
checkFilenameMismatch: jest.fn(() => ({ isMismatch: false })),
getDisplayName: jest.fn((r: any) => r.title || ""),
formatCount: jest.fn((n: number) => `${n}`),
formatMetadata: jest.fn(() => ""),
formatQuality: jest.fn(() => ""),
}))
const mockApi = api as jest.Mocked<typeof api>
import { AudioSourceStep } from "../steps/AudioSourceStep"
const defaultProps = {
artist: "ABBA",
title: "Waterloo",
onSearchCompleted: jest.fn(),
onSearchResultChosen: jest.fn(),
onArtistTitleCorrection: jest.fn(),
onUrlReady: jest.fn(),
onFileReady: jest.fn(),
onBack: jest.fn(),
noCredits: false,
}
function setupMocks() {
mockApi.searchStandalone.mockResolvedValue({
search_session_id: "sess-123",
results: [
{ index: 0, title: "Waterloo", artist: "ABBA", provider: "YouTube", url: "https://yt.com/1" },
],
results_count: 1,
})
mockApi.searchCatalogTracks.mockResolvedValue([])
mockApi.checkCommunityVersions.mockResolvedValue({
has_community: false,
songs: [],
best_youtube_url: null,
})
}
describe("AudioSourceStep", () => {
beforeEach(() => {
jest.clearAllMocks()
setupMocks()
})
it("calls searchStandalone on mount with artist and title", async () => {
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(mockApi.searchStandalone).toHaveBeenCalledWith("ABBA", "Waterloo")
})
})
it("calls searchCatalogTracks on mount in parallel", async () => {
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(mockApi.searchCatalogTracks).toHaveBeenCalledWith("Waterloo", "ABBA", 5)
})
})
it("calls checkCommunityVersions on mount in parallel", async () => {
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(mockApi.checkCommunityVersions).toHaveBeenCalledWith("ABBA", "Waterloo")
})
})
it("calls onSearchCompleted with session ID when search resolves", async () => {
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(defaultProps.onSearchCompleted).toHaveBeenCalledWith("sess-123")
})
})
it("shows loading state while searching", () => {
// Make search hang
mockApi.searchStandalone.mockReturnValue(new Promise(() => {}))
render(<AudioSourceStep {...defaultProps} />)
expect(screen.getByText("Searching for audio sources...")).toBeInTheDocument()
})
it("shows 'Searching for Artist - Title' text", () => {
mockApi.searchStandalone.mockReturnValue(new Promise(() => {}))
render(<AudioSourceStep {...defaultProps} />)
expect(screen.getByText("ABBA - Waterloo")).toBeInTheDocument()
})
it("renders SongSuggestionPanel when catalog returns results", async () => {
mockApi.searchCatalogTracks.mockResolvedValue([
{ artist_name: "ABBA", track_name: "Waterloo (Remastered)" },
])
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(screen.getByTestId("song-suggestion-panel")).toBeInTheDocument()
})
})
it("renders CommunityVersionBanner when community data has results", async () => {
mockApi.checkCommunityVersions.mockResolvedValue({
has_community: true,
best_youtube_url: "https://youtube.com/watch?v=abc",
songs: [
{
title: "Waterloo",
artist: "ABBA",
community_tracks: [
{
brand_name: "Nomad Karaoke",
brand_code: "NK",
youtube_url: "https://youtube.com/watch?v=abc",
is_community: true,
},
],
},
],
})
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(
screen.getByText("A karaoke version of this song already exists!")
).toBeInTheDocument()
})
})
it("shows error message when search fails with ApiError", async () => {
mockApi.searchStandalone.mockRejectedValue(
new ApiError("Internal server error", 500)
)
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(screen.getByText("Internal server error")).toBeInTheDocument()
})
})
it("shows credit error with Buy Credits link on 402", async () => {
mockApi.searchStandalone.mockRejectedValue(
new ApiError("No credits", 402)
)
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(
screen.getByText(/out of credits/i)
).toBeInTheDocument()
expect(screen.getByText("Buy Credits")).toBeInTheDocument()
})
})
it("calls onBack when Back button is clicked", async () => {
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(mockApi.searchStandalone).toHaveBeenCalled()
})
const user = userEvent.setup()
await user.click(screen.getByText("Back"))
expect(defaultProps.onBack).toHaveBeenCalledTimes(1)
})
it("silently handles catalog search failure (does not show error)", async () => {
mockApi.searchCatalogTracks.mockRejectedValue(new Error("catalog down"))
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(mockApi.searchStandalone).toHaveBeenCalled()
})
// No error shown for catalog failure — it's a nice-to-have
expect(screen.queryByText("catalog down")).not.toBeInTheDocument()
})
it("silently handles community check failure", async () => {
mockApi.checkCommunityVersions.mockRejectedValue(new Error("community down"))
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(mockApi.searchStandalone).toHaveBeenCalled()
})
expect(screen.queryByText("community down")).not.toBeInTheDocument()
})
it("does not show SongSuggestionPanel when catalog returns empty array", async () => {
mockApi.searchCatalogTracks.mockResolvedValue([])
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(mockApi.searchStandalone).toHaveBeenCalled()
})
expect(screen.queryByTestId("song-suggestion-panel")).not.toBeInTheDocument()
})
it("does not show CommunityVersionBanner when has_community is false", async () => {
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(mockApi.checkCommunityVersions).toHaveBeenCalled()
})
expect(
screen.queryByText("A karaoke version of this song already exists!")
).not.toBeInTheDocument()
})
})
@@ -0,0 +1,147 @@
/**
* Tests for CommunityVersionBanner component.
*
* Verifies:
* - Returns null when no community versions exist
* - Renders community tracks with YouTube links
* - Shows "+N more" when more than 3 tracks
* - Dismiss button works
* - Warning icon (AlertTriangle) is rendered
*/
import { render, screen, fireEvent } from "@testing-library/react"
import { CommunityVersionBanner } from "../CommunityVersionBanner"
import type { CommunityCheckResponse } from "@/lib/api"
function makeResponse(overrides?: Partial<CommunityCheckResponse>): CommunityCheckResponse {
return {
has_community: true,
best_youtube_url: "https://youtube.com/watch?v=abc",
songs: [
{
title: "Waterloo",
artist: "ABBA",
community_tracks: [
{
brand_name: "Nomad Karaoke",
brand_code: "NK",
youtube_url: "https://youtube.com/watch?v=abc",
is_community: true,
},
],
},
],
...overrides,
}
}
describe("CommunityVersionBanner", () => {
it("returns null when has_community is false", () => {
const { container } = render(
<CommunityVersionBanner
data={makeResponse({ has_community: false })}
onDismiss={jest.fn()}
/>
)
expect(container.firstChild).toBeNull()
})
it("returns null when songs array is empty", () => {
const { container } = render(
<CommunityVersionBanner
data={makeResponse({ songs: [] })}
onDismiss={jest.fn()}
/>
)
expect(container.firstChild).toBeNull()
})
it("renders the warning text", () => {
render(
<CommunityVersionBanner data={makeResponse()} onDismiss={jest.fn()} />
)
expect(
screen.getByText("A karaoke version of this song already exists!")
).toBeInTheDocument()
})
it("renders community track links", () => {
render(
<CommunityVersionBanner data={makeResponse()} onDismiss={jest.fn()} />
)
const link = screen.getByText("Watch on YouTube").closest("a")
expect(link).toHaveAttribute("href", "https://youtube.com/watch?v=abc")
expect(link).toHaveAttribute("target", "_blank")
})
it("renders brand name and Community badge for brand_code tracks", () => {
render(
<CommunityVersionBanner data={makeResponse()} onDismiss={jest.fn()} />
)
expect(screen.getByText("Nomad Karaoke")).toBeInTheDocument()
expect(screen.getByText("Community")).toBeInTheDocument()
})
it("shows '+N more' when more than 3 tracks", () => {
const data = makeResponse({
songs: [
{
title: "Waterloo",
artist: "ABBA",
community_tracks: [
{ brand_name: "Brand A", brand_code: "A", youtube_url: "https://yt.com/1", is_community: true },
{ brand_name: "Brand B", brand_code: "B", youtube_url: "https://yt.com/2", is_community: true },
{ brand_name: "Brand C", brand_code: "C", youtube_url: "https://yt.com/3", is_community: true },
{ brand_name: "Brand D", brand_code: "D", youtube_url: "https://yt.com/4", is_community: true },
{ brand_name: "Brand E", brand_code: "E", youtube_url: "https://yt.com/5", is_community: true },
],
},
],
})
render(
<CommunityVersionBanner data={data} onDismiss={jest.fn()} />
)
expect(screen.getByText("+2 more versions")).toBeInTheDocument()
})
it("shows singular '+1 more version' for exactly 4 tracks", () => {
const data = makeResponse({
songs: [
{
title: "Waterloo",
artist: "ABBA",
community_tracks: [
{ brand_name: "Brand A", brand_code: "A", youtube_url: "https://yt.com/1", is_community: true },
{ brand_name: "Brand B", brand_code: "B", youtube_url: "https://yt.com/2", is_community: true },
{ brand_name: "Brand C", brand_code: "C", youtube_url: "https://yt.com/3", is_community: true },
{ brand_name: "Brand D", brand_code: "D", youtube_url: "https://yt.com/4", is_community: true },
],
},
],
})
render(
<CommunityVersionBanner data={data} onDismiss={jest.fn()} />
)
expect(screen.getByText("+1 more version")).toBeInTheDocument()
})
it("calls onDismiss when dismiss button is clicked", () => {
const onDismiss = jest.fn()
render(
<CommunityVersionBanner data={makeResponse()} onDismiss={onDismiss} />
)
fireEvent.click(screen.getByLabelText("Dismiss"))
expect(onDismiss).toHaveBeenCalledTimes(1)
})
it("renders hint text about checking existing versions", () => {
render(
<CommunityVersionBanner data={makeResponse()} onDismiss={jest.fn()} />
)
expect(
screen.getByText("Check if an existing version works for you before using a credit.")
).toBeInTheDocument()
})
})
@@ -0,0 +1,129 @@
/**
* Tests for SongInfoStep component.
*
* Key behavior tested:
* - Submit button disabled when artist or title is empty
* - Submit button enabled when both fields have content
* - Form submission calls onNext
* - Input changes call respective handlers
* - Tip text is rendered (guidance for users)
*/
import { render, screen, fireEvent } from "@testing-library/react"
import { SongInfoStep } from "../steps/SongInfoStep"
const defaultProps = {
artist: "",
title: "",
onArtistChange: jest.fn(),
onTitleChange: jest.fn(),
onNext: jest.fn(),
disabled: false,
}
function renderStep(overrides?: Partial<typeof defaultProps>) {
return render(<SongInfoStep {...defaultProps} {...overrides} />)
}
describe("SongInfoStep", () => {
beforeEach(() => {
jest.clearAllMocks()
})
it("renders artist and title input fields", () => {
renderStep()
expect(screen.getByTestId("guided-artist-input")).toBeInTheDocument()
expect(screen.getByTestId("guided-title-input")).toBeInTheDocument()
})
it("submit button is disabled when artist is empty", () => {
renderStep({ artist: "", title: "Some Song" })
const button = screen.getByRole("button", { name: /choose audio/i })
expect(button).toBeDisabled()
})
it("submit button is disabled when title is empty", () => {
renderStep({ artist: "Some Artist", title: "" })
const button = screen.getByRole("button", { name: /choose audio/i })
expect(button).toBeDisabled()
})
it("submit button is disabled when both fields are whitespace-only", () => {
renderStep({ artist: " ", title: " " })
const button = screen.getByRole("button", { name: /choose audio/i })
expect(button).toBeDisabled()
})
it("submit button is enabled when both fields have content", () => {
renderStep({ artist: "Queen", title: "Bohemian Rhapsody" })
const button = screen.getByRole("button", { name: /choose audio/i })
expect(button).not.toBeDisabled()
})
it("clicking submit calls onNext when fields are filled", () => {
const onNext = jest.fn()
renderStep({ artist: "Queen", title: "Bohemian Rhapsody", onNext })
fireEvent.click(screen.getByRole("button", { name: /choose audio/i }))
expect(onNext).toHaveBeenCalledTimes(1)
})
it("form submission via Enter calls onNext", () => {
const onNext = jest.fn()
renderStep({ artist: "Queen", title: "Bohemian Rhapsody", onNext })
fireEvent.submit(screen.getByTestId("guided-artist-input").closest("form")!)
expect(onNext).toHaveBeenCalledTimes(1)
})
it("does not call onNext on submit when fields are empty", () => {
const onNext = jest.fn()
renderStep({ artist: "", title: "", onNext })
fireEvent.submit(screen.getByTestId("guided-artist-input").closest("form")!)
expect(onNext).not.toHaveBeenCalled()
})
it("typing in artist input calls onArtistChange", () => {
const onArtistChange = jest.fn()
renderStep({ onArtistChange })
fireEvent.change(screen.getByTestId("guided-artist-input"), {
target: { value: "ABBA" },
})
expect(onArtistChange).toHaveBeenCalledWith("ABBA")
})
it("typing in title input calls onTitleChange", () => {
const onTitleChange = jest.fn()
renderStep({ onTitleChange })
fireEvent.change(screen.getByTestId("guided-title-input"), {
target: { value: "Waterloo" },
})
expect(onTitleChange).toHaveBeenCalledWith("Waterloo")
})
it("disables inputs when disabled prop is true", () => {
renderStep({ disabled: true })
expect(screen.getByTestId("guided-artist-input")).toBeDisabled()
expect(screen.getByTestId("guided-title-input")).toBeDisabled()
expect(screen.getByRole("button", { name: /choose audio/i })).toBeDisabled()
})
it("shows tip about specific versions", () => {
renderStep()
expect(
screen.getByText(/looking for a specific version/i)
).toBeInTheDocument()
})
it("shows guidance about custom lyrics", () => {
renderStep()
expect(
screen.getByText(/making a video with custom lyrics/i)
).toBeInTheDocument()
})
it("shows guidance about unreleased songs", () => {
renderStep()
expect(
screen.getByText(/have an unreleased song/i)
).toBeInTheDocument()
})
})
@@ -0,0 +1,128 @@
/**
* Tests for VisibilityStep component.
*
* Key behavior tested:
* - Action buttons at top that select visibility AND continue in one click
* - "Publish & Share" calls onPrivateChange(false) + onNext()
* - "Keep Private" calls onPrivateChange(true) + onNext()
* - Detail cards toggle the radio selection (without advancing)
* - Back button calls onBack
*/
import { render, screen, fireEvent } from "@testing-library/react"
import { VisibilityStep } from "../steps/VisibilityStep"
const defaultProps = {
isPrivate: false,
onPrivateChange: jest.fn(),
onNext: jest.fn(),
onBack: jest.fn(),
disabled: false,
}
function renderStep(overrides?: Partial<typeof defaultProps>) {
return render(<VisibilityStep {...defaultProps} {...overrides} />)
}
describe("VisibilityStep", () => {
beforeEach(() => {
jest.clearAllMocks()
})
it("renders the question heading", () => {
renderStep()
expect(screen.getByText("How should your video be shared?")).toBeInTheDocument()
})
it("renders Publish & Share and Keep Private action buttons", () => {
renderStep()
expect(screen.getByText("Publish & Share")).toBeInTheDocument()
expect(screen.getByText("Keep Private")).toBeInTheDocument()
})
it("clicking 'Publish & Share' calls onPrivateChange(false) and onNext()", () => {
const onPrivateChange = jest.fn()
const onNext = jest.fn()
renderStep({ onPrivateChange, onNext })
fireEvent.click(screen.getByText("Publish & Share"))
expect(onPrivateChange).toHaveBeenCalledWith(false)
expect(onNext).toHaveBeenCalledTimes(1)
})
it("clicking 'Keep Private' calls onPrivateChange(true) and onNext()", () => {
const onPrivateChange = jest.fn()
const onNext = jest.fn()
renderStep({ onPrivateChange, onNext })
fireEvent.click(screen.getByText("Keep Private"))
expect(onPrivateChange).toHaveBeenCalledWith(true)
expect(onNext).toHaveBeenCalledTimes(1)
})
it("clicking Back button calls onBack", () => {
const onBack = jest.fn()
renderStep({ onBack })
fireEvent.click(screen.getByText("Back"))
expect(onBack).toHaveBeenCalledTimes(1)
})
it("renders Published detail card with Recommended badge", () => {
renderStep()
expect(screen.getByText("Published")).toBeInTheDocument()
expect(screen.getByText("Recommended")).toBeInTheDocument()
})
it("renders Private detail card", () => {
renderStep()
expect(screen.getByText("Private")).toBeInTheDocument()
})
it("clicking Published detail card calls onPrivateChange(false) without calling onNext", () => {
const onPrivateChange = jest.fn()
const onNext = jest.fn()
renderStep({ onPrivateChange, onNext })
// Click the Published detail card (not the action button)
fireEvent.click(screen.getByText("Published"))
expect(onPrivateChange).toHaveBeenCalledWith(false)
expect(onNext).not.toHaveBeenCalled()
})
it("clicking Private detail card calls onPrivateChange(true) without calling onNext", () => {
const onPrivateChange = jest.fn()
const onNext = jest.fn()
renderStep({ onPrivateChange, onNext })
// Click the Private detail card (not the action button)
fireEvent.click(screen.getByText("Private"))
expect(onPrivateChange).toHaveBeenCalledWith(true)
expect(onNext).not.toHaveBeenCalled()
})
it("shows changeable note", () => {
renderStep()
expect(
screen.getByText("You can change the visibility anytime after the video is produced.")
).toBeInTheDocument()
})
it("disables all buttons when disabled prop is true", () => {
renderStep({ disabled: true })
// Both action buttons should be disabled
const publishButton = screen.getByText("Publish & Share").closest("button")
const privateButton = screen.getByText("Keep Private").closest("button")
const backButton = screen.getByText("Back").closest("button")
expect(publishButton).toBeDisabled()
expect(privateButton).toBeDisabled()
expect(backButton).toBeDisabled()
})
})
@@ -0,0 +1,173 @@
/**
* Tests for stringSimilarity and findFuzzyMatches pure functions.
*
* These are the core of the "Did you mean?" feature in AudioSourceStep.
* stringSimilarity uses LCS-based similarity with a substring boost.
* findFuzzyMatches uses stringSimilarity to rank catalog tracks against user input.
*/
import { stringSimilarity, findFuzzyMatches } from "../steps/AudioSourceStep"
import type { CatalogTrackResult } from "@/lib/api"
// ---------------------------------------------------------------------------
// stringSimilarity
// ---------------------------------------------------------------------------
describe("stringSimilarity", () => {
it("returns 1 for identical strings", () => {
expect(stringSimilarity("hello", "hello")).toBe(1)
})
it("returns 1 for case-insensitive identical strings", () => {
expect(stringSimilarity("Hello", "hello")).toBe(1)
expect(stringSimilarity("BOHEMIAN RHAPSODY", "bohemian rhapsody")).toBe(1)
})
it("returns 0 for empty string vs non-empty", () => {
expect(stringSimilarity("", "hello")).toBe(0)
expect(stringSimilarity("hello", "")).toBe(0)
})
it("returns 1 for both empty strings (handled by identity check)", () => {
// Both empty => al === bl => returns 1
expect(stringSimilarity("", "")).toBe(1)
})
it("returns 0.85 for substring match (a is substring of b)", () => {
expect(stringSimilarity("water", "waterloo")).toBe(0.85)
})
it("returns 0.85 for substring match (b is substring of a)", () => {
expect(stringSimilarity("waterloo", "water")).toBe(0.85)
})
it("does not trigger substring match for very short strings (< 3 chars)", () => {
const score = stringSimilarity("ab", "abc")
// "ab" length < 3, so no substring boost from first check
// "abc" length >= 3 and "abc".includes("ab") is false (wrong direction)
// Actually: al="ab", bl="abc". al.length >= 3 is false. bl.length >= 3 is true, al.includes(bl)="ab".includes("abc") is false.
// So falls through to LCS. LCS of "ab" and "abc" = 2, max(2,3) = 3, score = 2*2/5 = 0.8
expect(score).toBeGreaterThan(0)
expect(score).toBeLessThan(0.85)
})
it("returns high score for similar strings", () => {
const score = stringSimilarity("Bohemian Rhapsody", "Bohemian Rapsody")
expect(score).toBeGreaterThan(0.8)
})
it("returns low score for very different strings", () => {
const score = stringSimilarity("ABBA", "Metallica")
expect(score).toBeLessThan(0.5)
})
it("handles single character strings", () => {
const score = stringSimilarity("a", "b")
expect(score).toBe(0)
})
it("handles single character match", () => {
const score = stringSimilarity("a", "a")
expect(score).toBe(1)
})
})
// ---------------------------------------------------------------------------
// findFuzzyMatches
// ---------------------------------------------------------------------------
function makeTracks(names: Array<[string, string]>): CatalogTrackResult[] {
return names.map(([artist, track]) => ({
artist_name: artist,
track_name: track,
}))
}
describe("findFuzzyMatches", () => {
const tracks = makeTracks([
["ABBA", "Waterloo"],
["ABBA", "Dancing Queen"],
["ABBA", "Mamma Mia"],
["Queen", "Bohemian Rhapsody"],
["The Beatles", "Hey Jude"],
])
it("returns empty array when no tracks match above threshold", () => {
const result = findFuzzyMatches("zzzzzzzzzzzzz", tracks)
expect(result).toEqual([])
})
it("finds fuzzy match for misspelled title", () => {
const result = findFuzzyMatches("Watrloo", tracks)
expect(result.length).toBeGreaterThan(0)
expect(result[0].track_name).toBe("Waterloo")
})
it("excludes exact title match by default", () => {
const result = findFuzzyMatches("Waterloo", tracks)
// "Waterloo" exactly matches a track — should be excluded from fuzzy results
expect(result.every(t => t.track_name.toLowerCase() !== "waterloo")).toBe(true)
})
it("includes exact title match when allowExactTitle is true", () => {
const result = findFuzzyMatches("Waterloo", tracks, 0.6, true)
expect(result.some(t => t.track_name === "Waterloo")).toBe(true)
})
it("respects threshold parameter", () => {
// With a very high threshold, only very close matches pass
const strict = findFuzzyMatches("Watrloo", tracks, 0.99)
expect(strict).toEqual([])
// With a low threshold, more matches pass
const lenient = findFuzzyMatches("Watrloo", tracks, 0.3)
expect(lenient.length).toBeGreaterThan(0)
})
it("applies artist bonus when userArtist is provided", () => {
// Two tracks with similar titles but different artists
const tracksWithSimilar = makeTracks([
["ABBA", "Love Story"],
["Taylor Swift", "Love Story"],
])
const result = findFuzzyMatches("Love Storry", tracksWithSimilar, 0.6, false, "Taylor Swift")
// Taylor Swift version should rank higher due to artist bonus
if (result.length >= 2) {
expect(result[0].artist_name).toBe("Taylor Swift")
}
})
it("deduplicates results by artist+track name", () => {
const tracksWithDupes = makeTracks([
["ABBA", "Waterloo"],
["ABBA", "Waterloo"],
["ABBA", "Waterloo"],
])
const result = findFuzzyMatches("Watrloo", tracksWithDupes, 0.5)
expect(result.length).toBeLessThanOrEqual(1)
})
it("returns results sorted by score descending", () => {
// Create tracks with varying similarity to "Waterlo"
const tracksToSort = makeTracks([
["ABBA", "Waterloo"], // Very close
["ABBA", "Water"], // Less close
["ABBA", "Waterfalls"], // Medium
])
const result = findFuzzyMatches("Waterlo", tracksToSort, 0.3, true)
// The closest match should come first
if (result.length >= 2) {
expect(result[0].track_name).toBe("Waterloo")
}
})
it("handles empty tracks array", () => {
const result = findFuzzyMatches("Waterloo", [])
expect(result).toEqual([])
})
it("handles empty user title", () => {
const result = findFuzzyMatches("", tracks)
expect(result).toEqual([])
})
})
+577 -19
View File
@@ -1,7 +1,8 @@
"use client"
import { useState, useEffect, useMemo, useCallback, useRef } from "react"
import { api, ApiError } from "@/lib/api"
import { api, ApiError, CatalogTrackResult, CommunityCheckResponse } from "@/lib/api"
import { CommunityVersionBanner } from "@/components/job/CommunityVersionBanner"
import {
ExtendedAudioSearchResult,
groupResults,
@@ -16,7 +17,7 @@ import {
} from "@/lib/audio-search-utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Loader2, ChevronDown, ChevronUp, Upload, Youtube, ArrowLeft, Check, AlertTriangle, CheckCircle2, Lightbulb, Info } from "lucide-react"
import { Loader2, ChevronDown, ChevronUp, Upload, Youtube, ArrowLeft, Check, AlertTriangle, CheckCircle2, Lightbulb, Info, Search, X, Scissors, Zap } from "lucide-react"
import { BuyCreditsDialog } from "@/components/credits/BuyCreditsDialog"
interface AudioSourceStepProps {
@@ -24,12 +25,19 @@ interface AudioSourceStepProps {
title: string
onSearchCompleted: (searchSessionId: string) => void
onSearchResultChosen: (resultIndex: number) => void
onArtistTitleCorrection: (artist: string, title: string) => void
onUrlReady: (url: string) => void
onFileReady: (file: File) => void
onBack: () => void
noCredits: boolean
onAudioEditChange: (value: boolean) => void
}
type PendingChoice =
| { type: "search"; index: number }
| { type: "url"; url: string }
| { type: "file"; file: File }
/** Render an availability badge with tooltip */
function AvailabilityBadge({ seeders }: { seeders: number | undefined | null }) {
if (seeders === undefined || seeders === null) return null
@@ -92,19 +100,36 @@ export function AudioSourceStep({
title,
onSearchCompleted,
onSearchResultChosen,
onArtistTitleCorrection,
onUrlReady,
onFileReady,
onBack,
noCredits,
onAudioEditChange,
}: AudioSourceStepProps) {
const [results, setResults] = useState<ExtendedAudioSearchResult[]>([])
const [isSearching, setIsSearching] = useState(true)
const [error, setError] = useState("")
const [pendingChoice, setPendingChoice] = useState<PendingChoice | null>(null)
const [isCreditError, setIsCreditError] = useState(false)
const [showOtherOptions, setShowOtherOptions] = useState(false)
const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set())
const searchTriggered = useRef(false)
// Catalog song suggestions (parallel to audio search)
const [catalogResults, setCatalogResults] = useState<CatalogTrackResult[]>([])
const [catalogDismissed, setCatalogDismissed] = useState(false)
// Community version check (parallel to audio search)
const [communityData, setCommunityData] = useState<CommunityCheckResponse | null>(null)
const [communityDismissed, setCommunityDismissed] = useState(false)
// Fuzzy "Did you mean?" state
const [fuzzySuggestion, setFuzzySuggestion] = useState<CatalogTrackResult | null>(null)
const [fuzzyAlternatives, setFuzzyAlternatives] = useState<CatalogTrackResult[]>([])
const [fuzzyDismissed, setFuzzyDismissed] = useState(false)
const fuzzyTriggered = useRef(false)
const [showBuyCreditsDialog, setShowBuyCreditsDialog] = useState(false)
// Fallback form state
@@ -139,21 +164,111 @@ export function AudioSourceStep({
}
}, [artist, title, onSearchCompleted])
// Auto-trigger search on mount
// Auto-trigger audio search + catalog search in parallel on mount
useEffect(() => {
if (searchTriggered.current) return
searchTriggered.current = true
doSearch()
}, [doSearch])
// Fire catalog search in parallel (non-blocking)
api.searchCatalogTracks(title, artist, 5)
.then((tracks) => setCatalogResults(tracks))
.catch(() => {
// Silently fail — catalog search is a nice-to-have
})
// Fire community version check in parallel (non-blocking)
api.checkCommunityVersions(artist, title)
.then((data) => setCommunityData(data))
.catch(() => {
// Silently fail — community check is a nice-to-have
})
}, [doSearch, artist, title])
const confidence = useMemo(() => getSearchConfidence(results, title), [results, title])
const groupedResults = useMemo(() => groupResults(results), [results])
const otherResultsCount = results.length > 0 && confidence.bestResult ? results.length - 1 : 0
// Fuzzy "Did you mean?" — triggers when audio search is poor AND catalog didn't find a close title match
const catalogHasExactTitleMatch = useMemo(() =>
catalogResults.some((t) => t.track_name.toLowerCase() === title.toLowerCase()),
[catalogResults, title]
)
useEffect(() => {
if (fuzzyTriggered.current) return
if (isSearching) return // Wait for audio search to complete
if (catalogHasExactTitleMatch) return // Catalog found the exact song — no typo
if (confidence.tier <= 2) return // Audio search found good results — no typo likely
fuzzyTriggered.current = true
// Try artist name as query first, fall back to title if that returns nothing
api.searchCatalogTracks(artist, undefined, 20)
.then((tracks) => {
const matches = findFuzzyMatches(title, tracks)
if (matches.length > 0) {
setFuzzySuggestion(matches[0])
setFuzzyAlternatives(matches.slice(1))
return
}
// Fallback: search by title (handles case where artist field has garbage like "fox stevenson bruises")
return api.searchCatalogTracks(title, undefined, 20).then((titleTracks) => {
const titleMatches = findFuzzyMatches(title, titleTracks, 0.6, true, artist)
if (titleMatches.length > 0) {
setFuzzySuggestion(titleMatches[0])
setFuzzyAlternatives(titleMatches.slice(1))
}
})
})
.catch(() => {
// Silently fail
})
}, [isSearching, catalogResults, confidence.tier, artist, title])
function handleFuzzyAccept(track?: CatalogTrackResult) {
const chosen = track || fuzzySuggestion
if (!chosen) return
// Update parent's artist/title
onArtistTitleCorrection(chosen.artist_name, chosen.track_name)
// Reset and restart search with corrected name
setFuzzySuggestion(null)
setFuzzyAlternatives([])
setFuzzyDismissed(true)
setResults([])
setIsSearching(true)
setError("")
setCatalogResults([])
setCatalogDismissed(false)
setCommunityData(null)
setCommunityDismissed(false)
setShowOtherOptions(false)
searchTriggered.current = false
fuzzyTriggered.current = false
// doSearch will re-fire via the useEffect since searchTriggered is reset
// But artist/title are props — they update on next render, so we need to
// let the parent re-render us with new props first. Use a microtask.
Promise.resolve().then(() => {
searchTriggered.current = true
api.searchStandalone(chosen.artist_name, chosen.track_name)
.then((response) => {
onSearchCompleted(response.search_session_id)
setResults(response.results as ExtendedAudioSearchResult[])
})
.catch((err) => {
if (err instanceof ApiError) setError(err.message)
else setError("Search failed. Please try again.")
})
.finally(() => setIsSearching(false))
// Also re-run catalog + community check with corrected name
api.searchCatalogTracks(chosen.track_name, chosen.artist_name, 5)
.then((tracks) => setCatalogResults(tracks))
.catch(() => {})
api.checkCommunityVersions(chosen.artist_name, chosen.track_name)
.then((data) => setCommunityData(data))
.catch(() => {})
})
}
function handleSelect(index: number) {
// Don't call the API here — defer selectAudioResult to the Customize & Create step
// so the job stays in awaiting_audio_selection (hidden from Recent Jobs) until confirmed
onSearchResultChosen(index)
// Show audio edit question before advancing
setPendingChoice({ type: "search", index })
}
function handleBack() {
@@ -175,17 +290,100 @@ export function AudioSourceStep({
function handleUploadSubmit(e: React.FormEvent) {
e.preventDefault()
if (!uploadFile) return
onFileReady(uploadFile)
setPendingChoice({ type: "file", file: uploadFile })
}
function handleUrlSubmit(e: React.FormEvent) {
e.preventDefault()
if (!youtubeUrl.trim()) return
onUrlReady(youtubeUrl.trim())
setPendingChoice({ type: "url", url: youtubeUrl.trim() })
}
function handleAudioEditAnswer(wantsEdit: boolean) {
if (!pendingChoice) return
onAudioEditChange(wantsEdit)
// Now advance to the next step
if (pendingChoice.type === "search") {
onSearchResultChosen(pendingChoice.index)
} else if (pendingChoice.type === "url") {
onUrlReady(pendingChoice.url)
} else if (pendingChoice.type === "file") {
onFileReady(pendingChoice.file)
}
}
const isLossyBest = confidence.bestCategory === 'YOUTUBE'
// Audio edit question — shown after user selects audio, before advancing
if (pendingChoice) {
return (
<div className="space-y-5">
<div className="flex items-center justify-between">
<div>
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
Audio selected for <span className="font-medium" style={{ color: 'var(--text)' }}>{artist} - {title}</span>
</p>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => setPendingChoice(null)}
style={{ color: 'var(--text-muted)' }}
>
<ArrowLeft className="w-4 h-4 mr-1" />
Back
</Button>
</div>
<div className="flex flex-col gap-3">
{/* Default: use as-is (recommended for most users) */}
<button
type="button"
onClick={() => handleAudioEditAnswer(false)}
className="group rounded-lg border-2 p-4 transition-all text-left flex items-start gap-4 border-[var(--success)] hover:bg-[rgba(34,197,94,0.06)]"
style={{ backgroundColor: 'rgba(34, 197, 94, 0.03)' }}
>
<div className="mt-0.5 flex-shrink-0 rounded-full p-1.5" style={{ backgroundColor: 'rgba(34, 197, 94, 0.15)' }}>
<Zap className="w-5 h-5" style={{ color: 'var(--success)' }} />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="font-semibold" style={{ color: 'var(--text)' }}>Use audio as-is</span>
<span className="text-[10px] font-medium uppercase tracking-wide px-1.5 py-0.5 rounded" style={{ backgroundColor: 'rgba(34, 197, 94, 0.15)', color: 'var(--success)' }}>
Recommended
</span>
</div>
<p className="text-sm mt-1" style={{ color: 'var(--text-muted)' }}>
Start processing right away — best for most tracks
</p>
</div>
</button>
{/* Optional: edit first */}
<button
type="button"
onClick={() => handleAudioEditAnswer(true)}
className="group rounded-lg border-2 p-4 transition-all text-left flex items-start gap-4 border-[var(--card-border)] hover:border-[var(--brand-purple)]"
>
<div className="mt-0.5 flex-shrink-0 rounded-full p-1.5" style={{ backgroundColor: 'rgba(139, 92, 246, 0.12)' }}>
<Scissors className="w-5 h-5" style={{ color: 'var(--brand-purple)' }} />
</div>
<div className="flex-1 min-w-0">
<span className="font-semibold" style={{ color: 'var(--text)' }}>Edit audio first</span>
<p className="text-sm mt-1" style={{ color: 'var(--text-muted)' }}>
Trim, cut, or mute sections before processing
</p>
<p className="text-xs mt-2 flex items-start gap-1.5" style={{ color: 'var(--text-muted)' }}>
<Lightbulb className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" style={{ color: 'var(--brand-gold)' }} />
<span>Great for live recordings with intros to skip, or tracks with sections you want to remove</span>
</p>
</div>
</button>
</div>
</div>
)
}
return (
<>
<div className="space-y-4">
@@ -206,6 +404,38 @@ export function AudioSourceStep({
</Button>
</div>
{/* Song name suggestions from catalog */}
{catalogResults.length > 0 && !catalogDismissed && (
<SongSuggestionPanel
results={catalogResults}
artist={artist}
title={title}
onSelect={(track) => {
onArtistTitleCorrection(track.artist_name, track.track_name)
setCatalogDismissed(true)
}}
onDismiss={() => setCatalogDismissed(true)}
/>
)}
{/* Community version banner */}
{communityData?.has_community && !communityDismissed && (
<CommunityVersionBanner
data={communityData}
onDismiss={() => setCommunityDismissed(true)}
/>
)}
{/* "Did you mean?" fuzzy correction banner */}
{fuzzySuggestion && !fuzzyDismissed && (
<DidYouMeanBanner
suggestion={fuzzySuggestion}
alternatives={fuzzyAlternatives}
onAccept={handleFuzzyAccept}
onDismiss={() => setFuzzyDismissed(true)}
/>
)}
{/* Error display */}
{error && (
<div className="text-sm rounded p-3 text-red-400 bg-red-500/10">
@@ -357,7 +587,7 @@ function PickCard({
<CheckCircle2 className="w-3.5 h-3.5 text-green-400" />
) : null}
<span className={`text-xs font-semibold ${isPerfect ? 'text-green-400' : 'text-amber-400'}`}>
{isPerfect ? 'Perfect match found' : 'Recommended'}
{isPerfect ? 'Perfect match found' : 'Recommended Audio'}
</span>
{bestResult.is_lossless && (
<span className="text-[8px] px-1 py-0.5 rounded bg-green-600/20 text-green-400 font-medium">
@@ -378,20 +608,20 @@ function PickCard({
<div className="flex items-start gap-3">
<div className="flex-1 min-w-0">
<div className="flex items-baseline gap-1.5">
{bestResult.target_file && (
<div className="flex items-baseline gap-1.5">
<span className="text-[10px] shrink-0" style={{ color: 'var(--text-muted)' }}>Filename:</span>
<span className="font-medium text-sm font-mono break-all" style={{ color: 'var(--text)' }}>
{bestResult.target_file}
</span>
</div>
)}
<div className="flex items-baseline gap-1.5 mt-0.5">
<span className="text-[10px] shrink-0" style={{ color: 'var(--text-muted)' }}>Release:</span>
<span className="font-medium text-sm" style={{ color: 'var(--text)' }}>
{getDisplayName(bestResult)} - {bestResult.title}
</span>
</div>
{bestResult.target_file && (
<div className="flex items-baseline gap-1.5 mt-0.5">
<span className="text-[10px] shrink-0" style={{ color: 'var(--text-muted)' }}>Filename:</span>
<span className="font-medium text-xs font-mono break-all" style={{ color: 'var(--text)' }}>
{bestResult.target_file}
</span>
</div>
)}
<div className="flex items-center gap-1.5 flex-wrap mt-1.5">
<span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
{formatQuality(bestResult)}
@@ -778,6 +1008,334 @@ function ResultRow({
)
}
/** Song name suggestion panel — two modes: exact match confirmation vs correction suggestions */
function SongSuggestionPanel({
results,
artist,
title,
onSelect,
onDismiss,
}: {
results: CatalogTrackResult[]
artist: string
title: string
onSelect: (track: CatalogTrackResult) => void
onDismiss: () => void
}) {
const [showOthers, setShowOthers] = useState(false)
// Check if any result is a case-insensitive match for the user's input
const hasExactMatch = results.some(
(t) => t.artist_name.toLowerCase() === artist.toLowerCase() && t.track_name.toLowerCase() === title.toLowerCase()
)
// Results that differ from what the user typed (potential corrections)
const corrections = results.filter(
(t) => !(t.artist_name === artist && t.track_name === title)
)
// If the user already typed exactly right (case-sensitive), nothing to show
const hasExactCaseSensitiveMatch = results.some(
(t) => t.artist_name === artist && t.track_name === title
)
if (hasExactCaseSensitiveMatch && corrections.length === 0) {
// Perfect match, no alternatives — don't show the panel at all
return null
}
// Find the exact case-insensitive match (for casing correction)
const exactCaseInsensitiveMatch = hasExactMatch
? results.find(
(t) => t.artist_name.toLowerCase() === artist.toLowerCase() && t.track_name.toLowerCase() === title.toLowerCase()
)
: null
const hasCasingDifference = exactCaseInsensitiveMatch && (
exactCaseInsensitiveMatch.artist_name !== artist || exactCaseInsensitiveMatch.track_name !== title
)
// "Other" corrections excludes the exact case-insensitive match
const otherCorrections = corrections.filter(
(t) => !exactCaseInsensitiveMatch || t.artist_name !== exactCaseInsensitiveMatch.artist_name || t.track_name !== exactCaseInsensitiveMatch.track_name
)
// Mode 1: User's input matches a song (case-insensitive) — show confirmation with optional alternatives
if (hasExactMatch) {
return (
<div
className="border rounded-lg overflow-hidden border-green-500/30 bg-green-500/5"
data-testid="song-suggestion-panel"
>
<div className="px-3 py-2 flex items-center justify-between bg-green-500/10">
<div className="flex items-center gap-2">
<CheckCircle2 className="w-3.5 h-3.5 text-green-400" />
<span className="text-xs font-semibold text-green-400">
Song found in our database
</span>
</div>
<button
onClick={onDismiss}
className="text-[10px] flex items-center gap-1 hover:opacity-80"
style={{ color: 'var(--text-muted)' }}
>
<X className="w-3 h-3" />
Dismiss
</button>
</div>
<div className="px-3 py-2">
{hasCasingDifference && exactCaseInsensitiveMatch ? (
<div>
<p className="text-[10px] mb-1.5" style={{ color: 'var(--text-muted)' }}>
Use the official formatting?
</p>
<CatalogTrackList tracks={[exactCaseInsensitiveMatch]} onSelect={onSelect} />
</div>
) : (
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
Your artist and title matched a song in our database — looking good!
</p>
)}
{otherCorrections.length > 0 && (
<div className="mt-2">
<button
onClick={() => setShowOthers(!showOthers)}
className="flex items-center gap-1 text-[10px] hover:opacity-80"
style={{ color: 'var(--text-muted)' }}
>
{showOthers ? (
<><ChevronUp className="w-3 h-3" /> Hide other matches</>
) : (
<><ChevronDown className="w-3 h-3" /> Show {otherCorrections.length} other match{otherCorrections.length !== 1 ? 'es' : ''}</>
)}
</button>
{showOthers && (
<div className="mt-1.5 space-y-1">
<CatalogTrackList tracks={otherCorrections} onSelect={onSelect} />
</div>
)}
</div>
)}
</div>
</div>
)
}
// Mode 2: No exact match — show corrections prominently
return (
<div
className="border rounded-lg overflow-hidden border-blue-500/30 bg-blue-500/5"
data-testid="song-suggestion-panel"
>
<div className="px-3 py-2 flex items-center justify-between bg-blue-500/10">
<div className="flex items-center gap-2">
<Search className="w-3.5 h-3.5 text-blue-400" />
<span className="text-xs font-semibold text-blue-400">
Use official artist/title formatting?
</span>
</div>
<button
onClick={onDismiss}
className="text-[10px] flex items-center gap-1 hover:opacity-80"
style={{ color: 'var(--text-muted)' }}
>
<X className="w-3 h-3" />
Dismiss
</button>
</div>
<div className="px-3 py-2">
<p className="text-[10px] mb-2" style={{ color: 'var(--text-muted)' }}>
We found these in our song database. Click one to use the official artist/title formatting:
</p>
<CatalogTrackList tracks={corrections.length > 0 ? corrections : results} onSelect={onSelect} />
</div>
</div>
)
}
/** Reusable list of clickable catalog track rows */
function CatalogTrackList({
tracks,
onSelect,
}: {
tracks: CatalogTrackResult[]
onSelect: (track: CatalogTrackResult) => void
}) {
// Deduplicate by artist + track name (Spotify often returns the same song from different albums)
const uniqueTracks = tracks.filter((t, i, arr) =>
arr.findIndex((x) => x.artist_name === t.artist_name && x.track_name === t.track_name) === i
)
return (
<div className="space-y-1">
{uniqueTracks.map((track, i) => {
const duration = track.duration_ms
? `${Math.floor(track.duration_ms / 60000)}:${Math.floor((track.duration_ms % 60000) / 1000).toString().padStart(2, "0")}`
: null
return (
<button
key={track.track_id || `${track.artist_name}-${track.track_name}-${i}`}
onClick={() => onSelect(track)}
className="w-full text-left px-2.5 py-2 rounded-md text-xs flex items-center justify-between gap-2 transition-colors hover:bg-blue-500/10"
style={{ color: 'var(--text)' }}
>
<span className="min-w-0">
<span className="font-medium">{track.artist_name}</span>
<span style={{ color: 'var(--text-muted)' }}> — </span>
<span>{track.track_name}</span>
</span>
<span className="flex items-center gap-2 shrink-0">
{duration && (
<span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{duration}</span>
)}
<span className="text-[10px] px-1.5 py-0.5 rounded bg-blue-500/15 text-blue-400 font-medium">
Use
</span>
</span>
</button>
)
})}
</div>
)
}
/** Compute similarity between two strings using longest common subsequence ratio */
export function stringSimilarity(a: string, b: string): number {
const al = a.toLowerCase()
const bl = b.toLowerCase()
if (al === bl) return 1
// Substring match — very strong signal
if (al.length >= 3 && bl.includes(al)) return 0.85
if (bl.length >= 3 && al.includes(bl)) return 0.85
// LCS-based similarity
const m = al.length
const n = bl.length
if (m === 0 || n === 0) return 0
// Use two-row DP for LCS length
let prev = new Array(n + 1).fill(0)
let curr = new Array(n + 1).fill(0)
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (al[i - 1] === bl[j - 1]) {
curr[j] = prev[j - 1] + 1
} else {
curr[j] = Math.max(prev[j], curr[j - 1])
}
}
;[prev, curr] = [curr, prev]
curr.fill(0)
}
const lcsLen = prev[n]
return (2 * lcsLen) / (m + n)
}
/** Find fuzzy matches for a title among catalog tracks, sorted by relevance.
* When userArtist is provided, uses artist similarity as a tiebreaker
* (e.g. user typed "fox stevenson bruises" as artist — prefer Fox Stevenson over Lewis Capaldi). */
export function findFuzzyMatches(
userTitle: string,
tracks: CatalogTrackResult[],
threshold = 0.6,
allowExactTitle = false,
userArtist?: string,
): CatalogTrackResult[] {
const scored = tracks.map((track) => {
const titleScore = stringSimilarity(userTitle, track.track_name)
const artistBonus = userArtist ? stringSimilarity(userArtist, track.artist_name) * 0.2 : 0
return { track, titleScore, totalScore: titleScore + artistBonus }
})
return scored
.filter((s) => s.titleScore >= threshold)
.filter((s) => allowExactTitle || s.track.track_name.toLowerCase() !== userTitle.toLowerCase())
.sort((a, b) => b.totalScore - a.totalScore)
.map((s) => s.track)
// Deduplicate by artist+track name
.filter((t, i, arr) => arr.findIndex((x) => x.artist_name === t.artist_name && x.track_name === t.track_name) === i)
}
/** "Did you mean?" banner for typo correction */
function DidYouMeanBanner({
suggestion,
alternatives,
onAccept,
onDismiss,
}: {
suggestion: CatalogTrackResult
alternatives: CatalogTrackResult[]
onAccept: (track?: CatalogTrackResult) => void
onDismiss: () => void
}) {
const [showAlternatives, setShowAlternatives] = useState(false)
return (
<div
className="border rounded-lg overflow-hidden border-amber-500/40 bg-amber-500/5"
data-testid="did-you-mean-banner"
>
<div className="px-3 py-2 flex items-center justify-between bg-amber-500/10">
<div className="flex items-center gap-2">
<AlertTriangle className="w-3.5 h-3.5 text-amber-400" />
<span className="text-xs font-semibold text-amber-400">
Did you mean?
</span>
</div>
<button
onClick={onDismiss}
className="text-[10px] flex items-center gap-1 hover:opacity-80"
style={{ color: 'var(--text-muted)' }}
>
<X className="w-3 h-3" />
No thanks
</button>
</div>
<div className="px-3 py-3">
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>
We couldn&apos;t find great audio sources. Did you mean:
</p>
<button
onClick={() => onAccept()}
className="mt-2 w-full text-left px-3 py-2.5 rounded-md flex items-center justify-between gap-2 transition-colors border border-amber-500/30 hover:bg-amber-500/10"
>
<span className="text-sm" style={{ color: 'var(--text)' }}>
<span className="font-semibold">{suggestion.artist_name}</span>
<span style={{ color: 'var(--text-muted)' }}> — </span>
<span className="font-semibold">{suggestion.track_name}</span>
</span>
<span className="text-xs px-2 py-1 rounded bg-amber-500/15 text-amber-400 font-medium shrink-0">
Yes, search again
</span>
</button>
{alternatives.length > 0 && (
<div className="mt-2">
<button
onClick={() => setShowAlternatives(!showAlternatives)}
className="text-[11px] flex items-center gap-1 hover:opacity-80"
style={{ color: 'var(--text-muted)' }}
>
<ChevronDown className={`w-3 h-3 transition-transform ${showAlternatives ? 'rotate-180' : ''}`} />
{showAlternatives ? 'Hide' : 'Show'} {alternatives.length} other match{alternatives.length > 1 ? 'es' : ''}
</button>
{showAlternatives && (
<div className="mt-1.5 space-y-1">
{alternatives.slice(0, 5).map((alt, i) => (
<button
key={i}
onClick={() => onAccept(alt)}
className="w-full text-left px-3 py-2 rounded-md flex items-center justify-between gap-2 transition-colors border border-[var(--card-border)] hover:bg-amber-500/10 hover:border-amber-500/30"
>
<span className="text-xs" style={{ color: 'var(--text)' }}>
<span className="font-medium">{alt.artist_name}</span>
<span style={{ color: 'var(--text-muted)' }}> — </span>
<span className="font-medium">{alt.track_name}</span>
</span>
<span className="text-[10px] px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400 shrink-0">
Search
</span>
</button>
))}
</div>
)}
</div>
)}
</div>
</div>
)
}
/** Contextual guidance when search returns no results */
function NoResultsSection() {
return (
+2 -71
View File
@@ -1,13 +1,9 @@
"use client"
import { useCallback, useEffect, useRef, useState } from "react"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import { ArrowRight, Lightbulb, Pencil, Search, Upload, Youtube } from "lucide-react"
import { AutocompleteInput, AutocompleteSuggestion } from "@/components/ui/autocomplete-input"
import { CommunityVersionBanner } from "@/components/job/CommunityVersionBanner"
import { api, CommunityCheckResponse } from "@/lib/api"
interface SongInfoStepProps {
artist: string
@@ -28,55 +24,6 @@ export function SongInfoStep({
}: SongInfoStepProps) {
const canProceed = artist.trim() && title.trim()
// Community version check state
const [communityData, setCommunityData] = useState<CommunityCheckResponse | null>(null)
const [communityDismissed, setCommunityDismissed] = useState(false)
const communityCheckRef = useRef<ReturnType<typeof setTimeout> | null>(null)
// Track autocomplete — only active when artist field has a value
const fetchTrackSuggestions = useCallback(async (query: string): Promise<AutocompleteSuggestion[]> => {
if (!artist.trim()) return []
try {
const results = await api.searchCatalogTracks(query, artist.trim(), 10)
return results.map((r) => {
const mins = r.duration_ms ? Math.floor(r.duration_ms / 60000) : null
const secs = r.duration_ms ? Math.floor((r.duration_ms % 60000) / 1000) : null
const duration = mins !== null && secs !== null ? `${mins}:${secs.toString().padStart(2, "0")}` : ""
return {
key: r.track_id || `${r.artist_name}-${r.track_name}`,
label: r.track_name,
description: r.artist_name,
meta: duration,
data: r,
}
})
} catch {
return []
}
}, [artist])
// Community version check — debounced when both fields are filled
useEffect(() => {
if (communityCheckRef.current) clearTimeout(communityCheckRef.current)
setCommunityData(null)
setCommunityDismissed(false)
if (!artist.trim() || !title.trim()) return
communityCheckRef.current = setTimeout(async () => {
try {
const data = await api.checkCommunityVersions(artist.trim(), title.trim())
setCommunityData(data)
} catch {
// Silently fail — community check is non-blocking
}
}, 500)
return () => {
if (communityCheckRef.current) clearTimeout(communityCheckRef.current)
}
}, [artist, title])
function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (canProceed) onNext()
@@ -120,34 +67,18 @@ export function SongInfoStep({
</div>
<div className="space-y-2">
<Label htmlFor="guided-title" style={{ color: 'var(--text)' }}>Title</Label>
<AutocompleteInput
<Input
id="guided-title"
data-testid="guided-title-input"
placeholder="e.g. Bohemian Rhapsody"
value={title}
onChange={onTitleChange}
onSelect={(s) => {
onTitleChange(s.label)
// Overwrite artist with the canonical name from the selected track
if (s.data?.artist_name) {
onArtistChange(s.data.artist_name)
}
}}
fetchSuggestions={fetchTrackSuggestions}
onChange={(e) => onTitleChange(e.target.value)}
disabled={disabled}
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
/>
</div>
</div>
{/* Community version banner */}
{communityData?.has_community && !communityDismissed && (
<CommunityVersionBanner
data={communityData}
onDismiss={() => setCommunityDismissed(true)}
/>
)}
{/* Tip callout */}
<div
className="flex items-start gap-2.5 rounded-lg p-3 text-xs"
@@ -1,6 +1,6 @@
"use client"
import { ArrowLeft, Globe, Lock, ExternalLink, Sparkles } from "lucide-react"
import { ArrowLeft, ArrowRight, Globe, Lock, ExternalLink, Sparkles } from "lucide-react"
import { Button } from "@/components/ui/button"
interface VisibilityStepProps {
@@ -41,12 +41,62 @@ export function VisibilityStep({
</Button>
</div>
{/* Published option */}
{/* Action buttons — select and continue in one click */}
<div className="flex flex-col sm:flex-row gap-3">
<button
type="button"
onClick={() => { onPrivateChange(false); onNext(); }}
disabled={disabled}
className={`flex-1 rounded-lg border-2 p-4 transition-all text-center ${
!isPrivate
? 'border-[var(--brand-pink)] shadow-[0_0_12px_rgba(255,122,204,0.2)]'
: 'border-[var(--card-border)] hover:border-[var(--text-muted)]'
}`}
style={{ backgroundColor: !isPrivate ? 'rgba(255,122,204,0.05)' : 'transparent' }}
>
<div className="flex items-center justify-center gap-2">
<Globe className="w-5 h-5" style={{ color: !isPrivate ? 'var(--brand-pink)' : 'var(--text-muted)' }} />
<span className="font-semibold" style={{ color: 'var(--text)' }}>Publish & Share</span>
<ArrowRight className="w-4 h-4" style={{ color: 'var(--text-muted)' }} />
</div>
</button>
<button
type="button"
onClick={() => { onPrivateChange(true); onNext(); }}
disabled={disabled}
className={`flex-1 rounded-lg border-2 p-4 transition-all text-center ${
isPrivate
? 'border-[var(--brand-pink)] shadow-[0_0_12px_rgba(255,122,204,0.2)]'
: 'border-[var(--card-border)] hover:border-[var(--text-muted)]'
}`}
style={{ backgroundColor: isPrivate ? 'rgba(255,122,204,0.05)' : 'transparent' }}
>
<div className="flex items-center justify-center gap-2">
<Lock className="w-5 h-5" style={{ color: isPrivate ? 'var(--brand-pink)' : 'var(--text-muted)' }} />
<span className="font-semibold" style={{ color: 'var(--text)' }}>Keep Private</span>
<ArrowRight className="w-4 h-4" style={{ color: 'var(--text-muted)' }} />
</div>
</button>
</div>
<p className="text-xs text-center" style={{ color: 'var(--text-muted)' }}>
You can change the visibility anytime after the video is produced.
</p>
{/* Divider */}
<div className="flex items-center gap-3">
<div className="flex-1 h-px" style={{ backgroundColor: 'var(--card-border)' }} />
<span className="text-xs" style={{ color: 'var(--text-muted)' }}>What&apos;s the difference?</span>
<div className="flex-1 h-px" style={{ backgroundColor: 'var(--card-border)' }} />
</div>
{/* Published detail card */}
<button
type="button"
onClick={() => onPrivateChange(false)}
disabled={disabled}
className={`w-full text-left rounded-lg border-2 p-4 transition-all ${
className={`w-full text-left rounded-lg border-2 p-3 transition-all ${
!isPrivate
? 'border-[var(--brand-pink)] shadow-[0_0_12px_rgba(255,122,204,0.2)]'
: 'border-[var(--card-border)] hover:border-[var(--text-muted)]'
@@ -126,12 +176,12 @@ export function VisibilityStep({
</div>
</button>
{/* Private option */}
{/* Private detail card */}
<button
type="button"
onClick={() => onPrivateChange(true)}
disabled={disabled}
className={`w-full text-left rounded-lg border-2 p-4 transition-all ${
className={`w-full text-left rounded-lg border-2 p-3 transition-all ${
isPrivate
? 'border-[var(--brand-pink)] shadow-[0_0_12px_rgba(255,122,204,0.2)]'
: 'border-[var(--card-border)] hover:border-[var(--text-muted)]'
@@ -192,14 +242,6 @@ export function VisibilityStep({
</div>
</button>
{/* Continue button */}
<Button
onClick={onNext}
disabled={disabled}
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white shadow-[0_0_15px_rgba(255,122,204,0.3)] hover:shadow-[0_0_20px_rgba(255,122,204,0.5)] h-11 text-base"
>
Continue
</Button>
</div>
)
}
+36 -18
View File
@@ -216,12 +216,30 @@ test.describe('Demo Video Recording', () => {
await page.getByRole('button', { name: /^select$/i }).first().click();
}
await page.waitForTimeout(PACE.afterAction);
// Audio edit question — choose "Use audio as-is"
await page.getByText('Use audio as-is').click({ timeout: TIMEOUTS.action });
await page.waitForTimeout(PACE.afterAction);
marker('SCENE_4_END: Audio Selection');
// =========================================================================
// SCENE 5: Customize & Create (Guided Step 3)
// SCENE 5: Visibility (Guided Step 3)
// =========================================================================
marker('SCENE_5_START: Customize & Create');
marker('SCENE_5_START: Visibility');
await expect(page.getByRole('heading', { name: 'How should your video be shared?' })).toBeVisible({ timeout: TIMEOUTS.action });
await page.waitForTimeout(PACE.beforeImportant);
await page.screenshot({ path: 'test-results/demo-04b-visibility.png' });
// Choose "Publish & Share" for the demo
await page.getByRole('button', { name: /publish & share/i }).click();
await page.waitForTimeout(PACE.afterAction);
marker('SCENE_5_END: Visibility');
// =========================================================================
// SCENE 6: Customize & Create (Guided Step 4)
// =========================================================================
marker('SCENE_6_START: Customize & Create');
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible({ timeout: TIMEOUTS.action });
@@ -248,12 +266,12 @@ test.describe('Demo Video Recording', () => {
}
await page.screenshot({ path: 'test-results/demo-06-job-created.png' });
marker('SCENE_5_END: Customize & Create');
marker('SCENE_6_END: Customize & Create');
// =========================================================================
// SCENE 6: Processing Wait (will be sped up in post-processing)
// SCENE 7: Processing Wait (will be sped up in post-processing)
// =========================================================================
marker('SCENE_6_START: Processing Wait (SPEED_UP)');
marker('SCENE_7_START: Processing Wait (SPEED_UP)');
// Find job card
await page.waitForTimeout(3000);
@@ -295,12 +313,12 @@ test.describe('Demo Video Recording', () => {
await page.screenshot({ path: 'test-results/demo-07-ready-for-review.png' });
await page.waitForTimeout(PACE.afterStepComplete);
marker('SCENE_6_END: Processing Wait (SPEED_UP)');
marker('SCENE_7_END: Processing Wait (SPEED_UP)');
// =========================================================================
// SCENE 7: Lyrics Review
// SCENE 8: Lyrics Review
// =========================================================================
marker('SCENE_7_START: Lyrics Review');
marker('SCENE_8_START: Lyrics Review');
// Open review page
const reviewLink = jobCard.getByRole('link', { name: /review lyrics/i });
@@ -366,12 +384,12 @@ test.describe('Demo Video Recording', () => {
await proceedBtn.click();
await reviewPage.waitForTimeout(3000);
marker('SCENE_7_END: Lyrics Review');
marker('SCENE_8_END: Lyrics Review');
// =========================================================================
// SCENE 8: Instrumental Selection
// SCENE 9: Instrumental Selection
// =========================================================================
marker('SCENE_8_START: Instrumental Selection');
marker('SCENE_9_START: Instrumental Selection');
// Wait for instrumental UI
try {
@@ -415,12 +433,12 @@ test.describe('Demo Video Recording', () => {
}
}
marker('SCENE_8_END: Instrumental Selection');
marker('SCENE_9_END: Instrumental Selection');
// =========================================================================
// SCENE 9: Wait for Completion (will be sped up in post-processing)
// SCENE 10: Wait for Completion (will be sped up in post-processing)
// =========================================================================
marker('SCENE_9_START: Final Rendering (SPEED_UP)');
marker('SCENE_10_START: Final Rendering (SPEED_UP)');
await page.bringToFront();
if (await refreshBtn.isVisible().catch(() => false)) {
@@ -455,18 +473,18 @@ test.describe('Demo Video Recording', () => {
await page.waitForTimeout(PACE.afterStepComplete);
await page.screenshot({ path: 'test-results/demo-14-complete.png' });
marker('SCENE_9_END: Final Rendering (SPEED_UP)');
marker('SCENE_10_END: Final Rendering (SPEED_UP)');
// =========================================================================
// SCENE 10: Show Completed Job
// SCENE 11: Show Completed Job
// =========================================================================
marker('SCENE_10_START: Completion');
marker('SCENE_11_START: Completion');
// Let the viewer see the completed state with all download badges
await page.waitForTimeout(5000);
await page.screenshot({ path: 'test-results/demo-15-final.png' });
marker('SCENE_10_END: Completion');
marker('SCENE_11_END: Completion');
// =========================================================================
// DONE
+50 -7
View File
@@ -7,7 +7,7 @@ import { TEST_SONG, URLS, TIMEOUTS } from '../helpers/constants';
/**
* Production E2E Tests: Guided Job Creation Flow
*
* Tests the 3-step guided job creation flow (Song Info → Choose Audio → Customize & Create)
* Tests the 4-step guided job creation flow (Song Info → Choose Audio → Visibility → Customize & Create)
* against the real production backend. Uses route interception to capture outgoing
* request bodies while still letting them hit the real API.
*
@@ -167,13 +167,22 @@ test.describe('Guided Job Creation Flow', () => {
await page.getByRole('button', { name: /use this audio/i }).click();
console.log(' Step 2 complete: selected pick card');
// Step 3: Click "Create Karaoke Video" with defaults (no overrides, not private)
// Audio edit question — choose "Use audio as-is"
await page.getByText('Use audio as-is').click({ timeout: TIMEOUTS.action });
console.log(' Selected "Use audio as-is"');
// Step 3: Visibility — choose "Publish & Share" (default, not private)
await expect(page.getByRole('heading', { name: 'How should your video be shared?' })).toBeVisible({ timeout: TIMEOUTS.action });
await page.getByRole('button', { name: /publish & share/i }).click();
console.log(' Step 3 complete: selected Publish & Share');
// Step 4: Click "Create Karaoke Video" with defaults (no overrides)
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible({ timeout: TIMEOUTS.action });
await page.getByRole('button', { name: /create karaoke video/i }).click();
// Wait for success
await expect(page.getByText('Job Created')).toBeVisible({ timeout: TIMEOUTS.action });
console.log(' Step 3 complete: job created');
console.log(' Step 4 complete: job created');
// Assert: search body has correct params
expect(searchBody).toBeTruthy();
@@ -241,13 +250,21 @@ test.describe('Guided Job Creation Flow', () => {
test.skip(!hasPickCard, 'Search returned Tier 3 — skipping pick card test');
await page.getByRole('button', { name: /use this audio/i }).click();
// Step 3: Fill display overrides, check private, and confirm
// Audio edit question — choose "Use audio as-is"
await page.getByText('Use audio as-is').click({ timeout: TIMEOUTS.action });
console.log(' Selected "Use audio as-is"');
// Step 3: Visibility — choose "Keep Private"
await expect(page.getByRole('heading', { name: 'How should your video be shared?' })).toBeVisible({ timeout: TIMEOUTS.action });
await page.getByRole('button', { name: /keep private/i }).click();
console.log(' Selected Keep Private');
// Step 4: Fill display overrides and confirm
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible({ timeout: TIMEOUTS.action });
await page.locator('#guided-display-artist').fill('PIRI (Display)');
await page.locator('#guided-display-title').fill('DOG (Display)');
await page.locator('#guided-private').check();
console.log(' Filled display overrides and checked Private');
console.log(' Filled display overrides');
await page.getByRole('button', { name: /create karaoke video/i }).click();
@@ -333,6 +350,19 @@ test.describe('Guided Job Creation Flow', () => {
await page.locator('input[type="url"]').fill('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
await page.getByRole('button', { name: /use this url/i }).click();
// Audio edit question — choose "Use audio as-is"
await page.getByText('Use audio as-is').click({ timeout: TIMEOUTS.action });
console.log(' Selected "Use audio as-is"');
// Step 3: Visibility — choose "Publish & Share"
await expect(page.getByRole('heading', { name: 'How should your video be shared?' })).toBeVisible({ timeout: TIMEOUTS.action });
await page.getByRole('button', { name: /publish & share/i }).click();
console.log(' Selected Publish & Share');
// Step 4: Customize & Create — click create
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible({ timeout: TIMEOUTS.action });
await page.getByRole('button', { name: /create karaoke video/i }).click();
// Wait for success
await expect(page.getByText('Job Created')).toBeVisible({ timeout: TIMEOUTS.action });
console.log(' Job created via YouTube URL');
@@ -397,7 +427,20 @@ test.describe('Guided Job Creation Flow', () => {
await fileInput.setInputFiles(UPLOAD_FIXTURE_PATH);
// Click upload submit button
await page.getByRole('button', { name: /upload.*create/i }).click();
await page.getByRole('button', { name: /use this file/i }).click();
// Audio edit question — choose "Use audio as-is"
await page.getByText('Use audio as-is').click({ timeout: TIMEOUTS.action });
console.log(' Selected "Use audio as-is"');
// Step 3: Visibility — choose "Publish & Share"
await expect(page.getByRole('heading', { name: 'How should your video be shared?' })).toBeVisible({ timeout: TIMEOUTS.action });
await page.getByRole('button', { name: /publish & share/i }).click();
console.log(' Selected Publish & Share');
// Step 4: Customize & Create — click create
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible({ timeout: TIMEOUTS.action });
await page.getByRole('button', { name: /create karaoke video/i }).click();
// Wait for success
await expect(page.getByText('Job Created')).toBeVisible({ timeout: TIMEOUTS.action });
@@ -429,7 +429,20 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
console.log(' Audio source selected');
// --- Guided Step 3: Customize & Create ---
// --- Audio edit question (appears after selecting audio) ---
console.log(' Answering audio edit question...');
await page.getByText('Use audio as-is').click({ timeout: TIMEOUTS.action });
console.log(' Selected "Use audio as-is"');
// --- Guided Step 3: Visibility ---
console.log(' Waiting for Visibility step...');
await expect(page.getByRole('heading', { name: 'How should your video be shared?' })).toBeVisible({ timeout: TIMEOUTS.action });
// Click "Keep Private" — test jobs should never consume public NOMAD brand codes
await page.getByRole('button', { name: /keep private/i }).click();
console.log(' Selected "Keep Private" (NOMADNP prefix, no GDrive/YouTube)');
// --- Guided Step 4: Customize & Create ---
console.log(' Waiting for Customize & Create step...');
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible({ timeout: TIMEOUTS.action });
@@ -437,11 +450,6 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
await page.waitForTimeout(3000);
await page.screenshot({ path: 'test-results/05b-customize-step.png' });
// Enable private mode - test jobs should never consume public NOMAD brand codes
const privateCheckbox = page.locator('#guided-private');
await privateCheckbox.check();
console.log(' Enabled private mode (NOMADNP prefix, no GDrive/YouTube)');
// Accept defaults and create
await page.getByRole('button', { name: /create karaoke video/i }).click();
console.log(' Clicked "Create Karaoke Video"');
@@ -122,16 +122,23 @@ test.describe('Step 1: Song Info', () => {
await expect(page.getByRole('button', { name: /choose audio/i })).toBeVisible();
});
test('shows step indicator with 3 steps', async ({ page }) => {
test('shows step indicator with 4 steps', async ({ page }) => {
await setupApiFixtures(page, { mocks: APP_PAGE_MOCKS });
await page.goto('/app');
await page.waitForLoadState('networkidle');
// Step indicator should show 3 labels (use navigation region to avoid matching headings/buttons)
// Step indicator should show 4 numbered circles (labels hidden on mobile, visible on sm+)
const stepNav = page.getByLabel('Progress');
await expect(stepNav.getByText('Song Info')).toBeVisible();
await expect(stepNav.getByText('Choose Audio')).toBeVisible();
await expect(stepNav.getByText('Customize & Create')).toBeVisible();
await expect(stepNav).toBeVisible();
// On larger viewports, check step labels
const viewportWidth = page.viewportSize()?.width ?? 1280;
if (viewportWidth >= 640) {
await expect(stepNav.getByText('Song Info')).toBeVisible();
await expect(stepNav.getByText('Choose Audio')).toBeVisible();
await expect(stepNav.getByText('Visibility')).toBeVisible();
await expect(stepNav.getByText('Customize & Create')).toBeVisible();
}
});
test('Choose Audio button is disabled without inputs', async ({ page }) => {
@@ -309,7 +316,7 @@ test.describe('Step 2: Choose Audio - Search Results', () => {
// Should show file upload area
await expect(page.locator('input[type="file"]')).toBeAttached();
await expect(page.getByRole('button', { name: /upload.*create/i })).toBeVisible();
await expect(page.getByRole('button', { name: /use this file/i })).toBeVisible();
});
test('Back button returns to Step 1', async ({ page }) => {
@@ -362,12 +369,13 @@ test.describe('Step 2: Choose Audio - Search Results', () => {
});
});
test.describe('Step 2 → Step 3: Audio Selection to Customize', () => {
test.describe('Step 2 → Step 3 → Step 4: Audio Selection to Visibility to Customize', () => {
test.beforeEach(async ({ page }) => {
await setAuthToken(page, 'test-token');
});
test('selecting pick card advances to Step 3', async ({ page }) => {
// Helper: navigate from Step 1 through Step 2 (search + select + audio edit question) to Step 3 (Visibility)
async function navigateToVisibilityStep(page: import('@playwright/test').Page) {
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
await page.goto('/app');
await page.waitForLoadState('networkidle');
@@ -377,79 +385,83 @@ test.describe('Step 2 → Step 3: Audio Selection to Customize', () => {
await page.getByRole('button', { name: /choose audio/i }).click();
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
// Click "Use This Audio"
await page.getByRole('button', { name: /use this audio/i }).click();
// Should advance to Step 3 - Customize & Create
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible();
await expect(page.getByText('Title Card Preview')).toBeVisible();
// Answer the audio edit question (skip editing)
await expect(page.getByText('Do you want to review and edit this audio')).toBeVisible();
await page.getByText('No, use as-is').click();
}
test('selecting pick card shows audio edit question', async ({ page }) => {
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
await page.goto('/app');
await page.waitForLoadState('networkidle');
await page.getByTestId('guided-artist-input').fill('Queen');
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
await page.getByRole('button', { name: /choose audio/i }).click();
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
await page.getByRole('button', { name: /use this audio/i }).click();
// Should show audio edit question
await expect(page.getByText('Do you want to review and edit this audio')).toBeVisible();
await expect(page.getByText('No, use as-is')).toBeVisible();
await expect(page.getByText("Yes, I'll edit it first")).toBeVisible();
});
test('Step 3 shows display override fields pre-filled from search', async ({ page }) => {
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
await page.goto('/app');
await page.waitForLoadState('networkidle');
test('answering "No" to audio edit advances to Visibility step', async ({ page }) => {
await navigateToVisibilityStep(page);
await page.getByTestId('guided-artist-input').fill('Queen');
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
await page.getByRole('button', { name: /choose audio/i }).click();
// Should advance to Step 3 - Visibility
await expect(page.getByText('How should your video be shared?')).toBeVisible();
await expect(page.getByText('Publish & Share')).toBeVisible();
await expect(page.getByText('Keep Private')).toBeVisible();
});
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
await page.getByRole('button', { name: /use this audio/i }).click();
test('Step 3 shows visibility options with detail cards', async ({ page }) => {
await navigateToVisibilityStep(page);
// Should show display override fields with placeholders matching search values
// Should show both Published and Private detail cards
await expect(page.getByText('Published')).toBeVisible();
await expect(page.getByText('Recommended')).toBeVisible();
await expect(page.getByText('Keep Private')).toBeVisible();
});
test('clicking Publish & Share advances to Step 4 (Customize & Create)', async ({ page }) => {
await navigateToVisibilityStep(page);
// Click "Publish & Share" — this selects visibility and auto-advances
await page.getByText('Publish & Share').click();
// Should advance to Step 4 - Customize & Create
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible();
await expect(page.getByText('Title Card Artist')).toBeVisible();
});
test('Step 4 shows display override fields pre-filled from search', async ({ page }) => {
await navigateToVisibilityStep(page);
await page.getByText('Publish & Share').click();
// Should show display override fields
await expect(page.locator('#guided-display-artist')).toBeVisible();
await expect(page.locator('#guided-display-title')).toBeVisible();
// Labels should indicate "same as above"
// Labels should indicate title card fields
await expect(page.getByText('Title Card Artist')).toBeVisible();
await expect(page.getByText('Title Card Title')).toBeVisible();
});
test('Step 3 shows privacy toggle', async ({ page }) => {
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
await page.goto('/app');
await page.waitForLoadState('networkidle');
await page.getByTestId('guided-artist-input').fill('Queen');
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
await page.getByRole('button', { name: /choose audio/i }).click();
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
await page.getByRole('button', { name: /use this audio/i }).click();
// Privacy toggle should be visible
await expect(page.getByText(/private.*no youtube/i)).toBeVisible();
await expect(page.locator('#guided-private')).toBeVisible();
});
test('Step 3 shows "Create Karaoke Video" button', async ({ page }) => {
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
await page.goto('/app');
await page.waitForLoadState('networkidle');
await page.getByTestId('guided-artist-input').fill('Queen');
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
await page.getByRole('button', { name: /choose audio/i }).click();
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
await page.getByRole('button', { name: /use this audio/i }).click();
test('Step 4 shows "Create Karaoke Video" button', async ({ page }) => {
await navigateToVisibilityStep(page);
await page.getByText('Publish & Share').click();
await expect(page.getByRole('button', { name: /create karaoke video/i })).toBeVisible();
});
test('submitting Step 3 calls selectAudioResult and shows success', async ({ page }) => {
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
await page.goto('/app');
await page.waitForLoadState('networkidle');
await page.getByTestId('guided-artist-input').fill('Queen');
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
await page.getByRole('button', { name: /choose audio/i }).click();
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
await page.getByRole('button', { name: /use this audio/i }).click();
test('submitting Step 4 creates job and shows success', async ({ page }) => {
await navigateToVisibilityStep(page);
await page.getByText('Publish & Share').click();
// Click create
await page.getByRole('button', { name: /create karaoke video/i }).click();
@@ -461,16 +473,8 @@ test.describe('Step 2 → Step 3: Audio Selection to Customize', () => {
});
test('success state shows Create Another button', async ({ page }) => {
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
await page.goto('/app');
await page.waitForLoadState('networkidle');
await page.getByTestId('guided-artist-input').fill('Queen');
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
await page.getByRole('button', { name: /choose audio/i }).click();
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
await page.getByRole('button', { name: /use this audio/i }).click();
await navigateToVisibilityStep(page);
await page.getByText('Publish & Share').click();
await page.getByRole('button', { name: /create karaoke video/i }).click();
await expect(page.getByText('Job Created')).toBeVisible({ timeout: 5000 });
@@ -480,22 +484,13 @@ test.describe('Step 2 → Step 3: Audio Selection to Customize', () => {
await expect(page.getByTestId('guided-artist-input')).toBeVisible();
});
test('Back from Step 3 returns to Step 2', async ({ page }) => {
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
await page.goto('/app');
await page.waitForLoadState('networkidle');
test('Back from Step 3 (Visibility) returns to Step 2', async ({ page }) => {
await navigateToVisibilityStep(page);
await page.getByTestId('guided-artist-input').fill('Queen');
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
await page.getByRole('button', { name: /choose audio/i }).click();
await expect(page.getByText('How should your video be shared?')).toBeVisible();
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
await page.getByRole('button', { name: /use this audio/i }).click();
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible();
// Click Back
await page.getByRole('button', { name: /back/i }).click();
// Click Back (use exact match to avoid matching "background" text in detail cards)
await page.getByRole('button', { name: 'Back', exact: true }).click();
// Should return to Step 2 with results still visible
await expect(page.getByText('Perfect match found')).toBeVisible();
@@ -507,7 +502,7 @@ test.describe('Fallback Paths: YouTube URL and Upload', () => {
await setAuthToken(page, 'test-token');
});
test('YouTube URL path creates job and shows success', async ({ page }) => {
test('YouTube URL path goes through Visibility and Customize then creates job', async ({ page }) => {
await setupApiFixtures(page, {
mocks: [
...SEARCH_FLOW_MOCKS,
@@ -538,7 +533,19 @@ test.describe('Fallback Paths: YouTube URL and Upload', () => {
await page.locator('input[type="url"]').fill('https://youtube.com/watch?v=test');
await page.getByRole('button', { name: /use this url/i }).click();
// Should show success directly (skip Step 3 for fallback paths)
// Answer the audio edit question
await expect(page.getByText('Do you want to review and edit this audio')).toBeVisible({ timeout: 5000 });
await page.getByText('No, use as-is').click();
// Should advance to Visibility step
await expect(page.getByText('How should your video be shared?')).toBeVisible({ timeout: 5000 });
await page.getByText('Publish & Share').click();
// Should advance to Customize & Create step
await expect(page.getByRole('button', { name: /create karaoke video/i })).toBeVisible();
await page.getByRole('button', { name: /create karaoke video/i }).click();
// Should show success
await expect(page.getByText('Job Created')).toBeVisible({ timeout: 10000 });
});
});
+108
View File
@@ -0,0 +1,108 @@
import { useCallback, useEffect, useRef } from 'react'
import type { AudioEditEntry, AudioEditSessionSummary } from '@/lib/api'
import { api } from '@/lib/api'
interface UseAudioEditAutoSaveOptions {
jobId: string
editStack: AudioEditEntry[]
originalDuration: number
currentDuration: number
}
function computeSummary(
editStack: AudioEditEntry[],
originalDuration: number,
currentDuration: number
): AudioEditSessionSummary {
const breakdown: Record<string, number> = {}
for (const entry of editStack) {
breakdown[entry.operation] = (breakdown[entry.operation] || 0) + 1
}
return {
total_operations: editStack.length,
operations_breakdown: breakdown,
duration_change_seconds: currentDuration - originalDuration,
net_duration_seconds: currentDuration,
}
}
const AUTO_SAVE_EVERY_N_EDITS = 3
export function useAudioEditAutoSave({
jobId,
editStack,
originalDuration,
currentDuration,
}: UseAudioEditAutoSaveOptions) {
const lastBackupEditCount = useRef(0)
const isSaving = useRef(false)
// Store latest values in refs so visibilitychange handler always has current data
const editStackRef = useRef(editStack)
const originalDurationRef = useRef(originalDuration)
const currentDurationRef = useRef(currentDuration)
editStackRef.current = editStack
originalDurationRef.current = originalDuration
currentDurationRef.current = currentDuration
const doSave = useCallback(
async (trigger: 'auto' | 'submit' | 'manual') => {
const currentEditCount = editStackRef.current.length
// No edits yet
if (currentEditCount === 0) return
// No new edits since last backup
if (currentEditCount === lastBackupEditCount.current) return
// Already saving
if (isSaving.current) return
isSaving.current = true
try {
const summary = computeSummary(
editStackRef.current,
originalDurationRef.current,
currentDurationRef.current
)
const result = await api.saveAudioEditSession(jobId, {
edit_data: { entries: editStackRef.current },
edit_count: currentEditCount,
trigger,
summary,
})
if (result.status === 'saved' || result.status === 'skipped') {
lastBackupEditCount.current = currentEditCount
}
} catch (err) {
console.warn('Audio edit session auto-save failed:', err)
} finally {
isSaving.current = false
}
},
[jobId]
)
// Auto-save every N edits
useEffect(() => {
if (editStack.length === 0) return
const editsSinceBackup = editStack.length - lastBackupEditCount.current
if (editsSinceBackup >= AUTO_SAVE_EVERY_N_EDITS) {
doSave('auto')
}
}, [editStack.length, doSave])
// Save on page hide
useEffect(() => {
const handler = () => {
if (document.visibilityState === 'hidden') {
doSave('auto')
}
}
document.addEventListener('visibilitychange', handler)
return () => document.removeEventListener('visibilitychange', handler)
}, [doSave])
const saveSession = useCallback(
(trigger: 'auto' | 'submit' | 'manual') => doSave(trigger),
[doSave]
)
return { saveSession }
}
+275 -1
View File
@@ -166,6 +166,68 @@ export interface WaveformData {
sample_rate?: number;
}
export interface AudioEditEntry {
edit_id: string;
operation: string;
params: Record<string, unknown>;
duration_before: number;
duration_after: number;
timestamp: string;
}
export interface AudioEditInfo {
job_id: string;
artist?: string;
title?: string;
original_duration_seconds: number;
current_duration_seconds: number;
original_audio_url: string;
current_audio_url: string;
waveform_data: { amplitudes: number[] };
original_waveform_data: { amplitudes: number[] };
edit_stack: AudioEditEntry[];
can_undo: boolean;
can_redo: boolean;
}
export interface AudioEditSessionSummary {
total_operations: number;
operations_breakdown: Record<string, number>;
duration_change_seconds: number;
net_duration_seconds: number;
}
export interface AudioEditSessionMeta {
session_id: string;
job_id: string;
user_email?: string;
edit_count: number;
trigger: string;
summary?: AudioEditSessionSummary;
created_at: string;
updated_at: string;
}
export interface AudioEditSessionWithData extends AudioEditSessionMeta {
edit_data?: {
entries: AudioEditEntry[];
[key: string]: unknown;
};
}
export interface AudioEditResponse {
status: string;
edit_id?: string;
operation?: string;
duration_before: number;
duration_after: number;
current_audio_url: string;
waveform_data: { amplitudes: number[] };
edit_stack: AudioEditEntry[];
can_undo: boolean;
can_redo: boolean;
}
export type InstrumentalSelectionType = 'clean' | 'with_backing' | 'custom' | 'uploaded' | 'original';
export interface DownloadUrlsResponse {
@@ -393,6 +455,7 @@ export const api = {
color_overrides?: ColorOverrides;
non_interactive?: boolean;
is_private?: boolean;
requires_audio_edit?: boolean;
}
): Promise<UploadJobResponse> {
const formData = new FormData();
@@ -424,6 +487,9 @@ export const api = {
if (options?.is_private !== undefined) {
formData.append('is_private', String(options.is_private));
}
if (options?.requires_audio_edit) {
formData.append('requires_audio_edit', String(options.requires_audio_edit));
}
const response = await fetch(`${API_BASE_URL}/api/jobs/upload`, {
method: 'POST',
@@ -445,11 +511,13 @@ export const api = {
options?: {
is_private?: boolean;
existing_instrumental?: boolean;
requires_audio_edit?: boolean;
}
): Promise<CreateJobWithUploadUrlsResponse> {
const body: Record<string, any> = { artist, title, files };
if (options?.is_private !== undefined) body.is_private = options.is_private;
if (options?.existing_instrumental !== undefined) body.existing_instrumental = options.existing_instrumental;
if (options?.requires_audio_edit) body.requires_audio_edit = options.requires_audio_edit;
const response = await fetch(`${API_BASE_URL}/api/jobs/create-with-upload-urls`, {
method: 'POST',
@@ -526,7 +594,7 @@ export const api = {
file: File,
artist: string,
title: string,
options?: { is_private?: boolean },
options?: { is_private?: boolean; requires_audio_edit?: boolean },
onProgress?: (progress: UploadProgress) => void,
): Promise<UploadJobResponse> {
const SIGNED_URL_THRESHOLD = 25 * 1024 * 1024; // 25MB
@@ -590,6 +658,7 @@ export const api = {
color_overrides?: ColorOverrides;
non_interactive?: boolean;
is_private?: boolean;
requires_audio_edit?: boolean;
}
): Promise<{ status: string; job_id: string; message: string }> {
const body: Record<string, any> = { url };
@@ -603,6 +672,7 @@ export const api = {
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;
if (options?.requires_audio_edit) body.requires_audio_edit = options.requires_audio_edit;
const response = await fetch(`${API_BASE_URL}/api/jobs/create-from-url`, {
method: 'POST',
@@ -670,6 +740,123 @@ export const api = {
return handleResponse(response);
},
/**
* Submit audio edit (finalize and continue processing).
* For auto-processor: submits with no edits to skip the audio edit phase.
*/
/**
* Get input audio info for the audio editor.
*/
async getInputAudioInfo(jobId: string): Promise<AudioEditInfo> {
const response = await fetch(`${API_BASE_URL}/api/review/${jobId}/input-audio-info`, {
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
});
return handleResponse(response);
},
/**
* Apply an audio edit operation (trim, cut, mute, join).
*/
async applyAudioEdit(jobId: string, operation: string, params: Record<string, unknown>): Promise<AudioEditResponse> {
const response = await fetch(`${API_BASE_URL}/api/review/${jobId}/audio-edit/apply`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ operation, params }),
});
return handleResponse(response);
},
/**
* Undo the last audio edit operation.
*/
async undoAudioEdit(jobId: string): Promise<AudioEditResponse> {
const response = await fetch(`${API_BASE_URL}/api/review/${jobId}/audio-edit/undo`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
});
return handleResponse(response);
},
/**
* Redo a previously undone audio edit.
*/
async redoAudioEdit(jobId: string): Promise<AudioEditResponse> {
const response = await fetch(`${API_BASE_URL}/api/review/${jobId}/audio-edit/redo`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
});
return handleResponse(response);
},
/**
* Upload an audio file for join operations.
*/
async uploadAudioForJoin(jobId: string, file: File): Promise<{ upload_id: string; duration_seconds: number; filename: string }> {
const formData = new FormData();
formData.append('file', file);
const response = await fetch(`${API_BASE_URL}/api/review/${jobId}/audio-edit/upload`, {
method: 'POST',
headers: getAuthHeaders(),
body: formData,
});
return handleResponse(response);
},
async submitAudioEdit(jobId: string, editLog?: unknown): Promise<{ status: string; message: string; job_id: string }> {
const body = editLog ? { edit_log: editLog } : {};
const response = await fetch(`${API_BASE_URL}/api/review/${jobId}/audio-edit/submit`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(body),
});
return handleResponse(response);
},
/**
* Save an audio edit session snapshot.
*/
async saveAudioEditSession(
jobId: string,
data: {
edit_data: unknown;
edit_count: number;
trigger: string;
summary?: AudioEditSessionSummary;
}
): Promise<{ status: string; session_id?: string; reason?: string }> {
const response = await fetch(`${API_BASE_URL}/api/review/${jobId}/audio-edit-sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(data),
});
return handleResponse(response);
},
/**
* List audio edit sessions for a job.
*/
async listAudioEditSessions(
jobId: string
): Promise<{ sessions: AudioEditSessionMeta[] }> {
const response = await fetch(`${API_BASE_URL}/api/review/${jobId}/audio-edit-sessions`, {
headers: getAuthHeaders(),
});
return handleResponse(response);
},
/**
* Get a single audio edit session with full edit_data.
*/
async getAudioEditSession(
jobId: string,
sessionId: string
): Promise<AudioEditSessionWithData> {
const response = await fetch(`${API_BASE_URL}/api/review/${jobId}/audio-edit-sessions/${sessionId}`, {
headers: getAuthHeaders(),
});
return handleResponse(response);
},
/**
* Get instrumental analysis data for review
*/
@@ -854,6 +1041,7 @@ export const api = {
display_artist?: string;
display_title?: string;
is_private?: boolean;
requires_audio_edit?: boolean;
}): Promise<{ status: string; job_id: string; message: string }> {
const response = await fetch(`${API_BASE_URL}/api/jobs/create-from-search`, {
method: 'POST',
@@ -2083,6 +2271,30 @@ export const adminApi = {
);
return handleResponse(response);
},
async listAudioEditReviews(params?: {
limit?: number;
offset?: number;
exclude_test?: boolean;
search?: string;
}): Promise<AudioEditReviewListResponse> {
const searchParams = new URLSearchParams();
if (params?.limit) searchParams.set('limit', String(params.limit));
if (params?.offset) searchParams.set('offset', String(params.offset));
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
if (params?.search) searchParams.set('search', params.search);
const url = `${API_BASE_URL}/api/admin/audio-edit-reviews${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await fetch(url, { headers: getAuthHeaders() });
return handleResponse(response);
},
async getAudioEditReview(jobId: string): Promise<AudioEditReviewDetail> {
const response = await fetch(
`${API_BASE_URL}/api/admin/audio-edit-reviews/${encodeURIComponent(jobId)}`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
};
export interface EditReviewSummary {
@@ -2146,6 +2358,68 @@ export interface EditReviewDetail {
audio_url: string | null;
}
// Types for admin audio edit reviews
export interface AudioEditReviewSummary {
job_id: string;
artist: string;
title: string;
user_email: string;
status: string;
created_at?: string;
updated_at?: string;
session_count: number;
total_edits: number;
original_duration?: number;
current_duration?: number;
latest_trigger?: string;
}
export interface AudioEditReviewListResponse {
reviews: AudioEditReviewSummary[];
total: number;
has_more: boolean;
}
export interface AudioEditReviewDetail {
job: {
job_id: string;
artist: string;
title: string;
user_email: string;
status: string;
created_at?: string;
updated_at?: string;
};
sessions: Array<{
session_id: string;
job_id: string;
user_email: string;
created_at: string;
updated_at: string;
edit_count: number;
trigger: string;
audio_duration_seconds?: number;
original_duration_seconds?: number;
artist?: string;
title?: string;
summary: AudioEditSessionSummary;
edit_data_gcs_path: string;
data_hash: string;
}>;
edit_stack: Array<{
edit_id: string;
operation: string;
params: Record<string, unknown>;
gcs_path: string;
duration_before?: number;
duration_after?: number;
timestamp: string;
}>;
edit_log: unknown;
original_audio_url: string | null;
current_audio_url: string | null;
}
// Types for admin completion message API
export interface CompletionMessageResponse {
job_id: string;
+5
View File
@@ -45,6 +45,11 @@ const STATUS_CONFIG: Record<
downloading_audio: { step: 3, label: "Downloading audio", isBlocking: false, color: "text-blue-400" },
downloading: { step: 3, label: "Downloading", isBlocking: false, color: "text-blue-400" },
// Step 3.5: Audio Editing (optional, BLOCKING)
awaiting_audio_edit: { step: 3, label: "Edit audio", isBlocking: true, color: "text-amber-400" },
in_audio_edit: { step: 3, label: "Editing audio", isBlocking: true, color: "text-blue-400" },
audio_edit_complete: { step: 3, label: "Audio edited", isBlocking: false, color: "text-teal-400" },
// Step 4: Parallel Processing (Audio + Lyrics)
separating_stage1: { step: 4, label: "Separating audio (1/2)", isBlocking: false, color: "text-purple-400" },
separating_stage2: { step: 4, label: "Separating audio (2/2)", isBlocking: false, color: "text-purple-400" },
+1 -1
View File
@@ -89,7 +89,7 @@ export const LOCAL_MODE_USER = {
* Mock job object for local mode
*/
export function createLocalModeJob(options: {
routeType: 'review' | 'instrumental'
routeType: 'review' | 'instrumental' | 'audio-edit'
artist?: string
title?: string
}) {
+103 -2
View File
@@ -378,8 +378,13 @@ def create_video_encoding_job(
"""
Create the Cloud Run Job for video encoding.
Cloud Run Jobs provide up to 24-hour execution time for long-running video encoding.
This is used when video encoding might exceed the 30-minute Cloud Tasks timeout.
Cloud Run Jobs run to completion (up to 1 hour), immune to Cloud Run Service
deployment rollouts. This prevents the BackgroundTask termination issue where
a deployment kills the encoding orchestrator mid-flight (see incident 2026-03-08).
The video worker orchestrates: CDG/TXT packaging, GCE encoding submission/polling,
file download from GCS, YouTube/Dropbox/GDrive upload, and Discord notification.
It needs the same env vars and secrets as the Cloud Run Service for these features.
Args:
bucket: The GCS bucket for job artifacts.
@@ -405,6 +410,7 @@ def create_video_encoding_job(
},
),
envs=[
# Core configuration
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GOOGLE_CLOUD_PROJECT",
value=PROJECT_ID,
@@ -413,6 +419,101 @@ def create_video_encoding_job(
name="GCS_BUCKET_NAME",
value=bucket.name,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENVIRONMENT",
value="production",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCP_REGION",
value=REGION,
),
# GCE encoding worker
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="USE_GCE_ENCODING",
value="true",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENCODING_WORKER_URL",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/encoding-worker-url",
version="latest",
),
),
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENCODING_WORKER_API_KEY",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/encoding-worker-api-key",
version="latest",
),
),
),
# Distribution defaults
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_ENABLE_YOUTUBE_UPLOAD",
value="true",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_BRAND_PREFIX",
value="NOMAD",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_PRIVATE_BRAND_PREFIX",
value="NOMADNP",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_DROPBOX_PATH",
value="/MediaUnsynced/Karaoke/Tracks-Organized",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_PRIVATE_DROPBOX_PATH",
value="/MediaUnsynced/Karaoke/Tracks-NonPublished",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_GDRIVE_FOLDER_ID",
value="1laRKAyxo0v817SstfM5XkpbWiNKNAMSX",
),
# Discord webhook for release notifications
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_DISCORD_WEBHOOK_URL",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/discord-releases-webhook",
version="latest",
),
),
),
# Admin token for worker-to-service auth
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ADMIN_TOKENS",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/admin-tokens",
version="latest",
),
),
),
# Cloud Run service URL for triggering downstream workers
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="CLOUD_RUN_SERVICE_URL",
value="https://api.nomadkaraoke.com",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENABLE_CLOUD_TASKS",
value="true",
),
# SendGrid for completion emails
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="SENDGRID_API_KEY",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/sendgrid-api-key",
version="latest",
),
),
),
],
)
],
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.138.2"
version = "0.141.2"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"