mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-02 09:58:08 +09:00
Compare commits
No files matched your search
@@ -0,0 +1,149 @@
|
||||
# Plan: Improve Job Observability
|
||||
|
||||
**Created:** 2026-03-07
|
||||
**Branch:** feat/sess-20260307-2216-improve-job-observability
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
After shipping the "edit completed tracks" feature, we found it very difficult to trace what actually happened to edited jobs. Timeline events are too sparse (no output details), cleanup operations aren't logged to Cloud Logging or Firestore, state_data gets fully overwritten during re-processing (losing history of previous outputs), and API endpoints don't write to the job's Firestore log subcollection.
|
||||
|
||||
The goal is to make it trivially easy for future agents and humans to reconstruct the complete lifecycle of any job by reading its timeline and Firestore logs.
|
||||
|
||||
## Problem Analysis
|
||||
|
||||
### What we found investigating two edited jobs:
|
||||
|
||||
1. **Timeline events only have `status`, `timestamp`, `progress`, `message`** — no output details like YouTube video IDs, brand codes, Dropbox links, or GDrive file IDs
|
||||
2. **Edit endpoint cleanup results never logged** — the `cleanup_results` dict is built and returned in the HTTP response but never logged to Cloud Logging or the job's Firestore log subcollection
|
||||
3. **Distribution details incomplete in logs** — YouTube logs the URL but not video_id separately; Dropbox doesn't log folder path; GDrive doesn't log file IDs
|
||||
4. **`state_data` fully overwritten on re-processing** — `video_worker.py:342-354` does `{**job.state_data, ...}`, so any `DELETE_FIELD` operations from the edit endpoint get lost when old keys are re-merged from the in-memory copy
|
||||
5. **`outputs_deleted_at` cleared by video worker** — intentionally, but loses audit trail
|
||||
6. **No Firestore job logs from API endpoints** — edit/admin endpoints only log to Cloud Run stdout, not to `jobs/{job_id}/logs/`
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] Add `metadata` dict to `TimelineEvent` for structured output details
|
||||
- [ ] Log all cleanup operations (success AND failure) to both Cloud Logging and Firestore job logs
|
||||
- [ ] Log distribution output details (YouTube video ID, Dropbox path, brand code, GDrive file IDs) in timeline events and Firestore logs
|
||||
- [ ] Preserve previous output details in timeline when a job is edited (snapshot before cleanup)
|
||||
- [ ] Add helper to write Firestore job logs from API endpoints (not just workers)
|
||||
- [ ] Ensure edit/admin delete endpoints write to Firestore job logs
|
||||
- [ ] No breaking changes to existing timeline format (additive only)
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### 1. Add `metadata` field to `TimelineEvent`
|
||||
|
||||
The `TimelineEvent` model gains an optional `metadata: Optional[Dict[str, Any]]` field. This allows any timeline event to carry structured data without changing the schema. The field is additive — existing events without metadata continue to work.
|
||||
|
||||
Key events that gain metadata:
|
||||
- **`complete`**: `{youtube_url, youtube_video_id, dropbox_link, brand_code, gdrive_file_ids}`
|
||||
- **Edit initiated**: `{previous_outputs: {youtube_url, dropbox_link, brand_code, gdrive_files}, cleanup_results: {...}}`
|
||||
- **Outputs deleted**: `{deleted_outputs: {...}, cleanup_results: {...}}`
|
||||
|
||||
### 2. Write Firestore job logs from API endpoints
|
||||
|
||||
Create a simple helper function that API route handlers can call to append logs to the job's Firestore subcollection. Workers already have `JobLogAdapter` — we just need a lightweight equivalent for API routes:
|
||||
|
||||
```python
|
||||
def log_to_job(job_id: str, worker: str, level: str, message: str, metadata: dict = None):
|
||||
"""Write a log entry to the job's Firestore log subcollection."""
|
||||
entry = WorkerLogEntry.create(job_id, worker, level, message, metadata)
|
||||
FirestoreService().append_log_to_subcollection(job_id, entry)
|
||||
```
|
||||
|
||||
### 3. Enhance distribution logging in video_worker_orchestrator
|
||||
|
||||
After each distribution upload succeeds, log the details with structured metadata:
|
||||
- YouTube: video_id, video_url, channel
|
||||
- Dropbox: folder_path, sharing_link
|
||||
- GDrive: file_ids dict
|
||||
- Brand code: code, prefix, allocated vs recycled
|
||||
|
||||
### 4. Snapshot previous outputs on edit
|
||||
|
||||
Before the edit endpoint clears state_data distribution keys, capture the current values in the timeline event's metadata. This preserves the history permanently in the timeline array (which is append-only via `ArrayUnion`).
|
||||
|
||||
### 5. Log cleanup results from edit/admin endpoints
|
||||
|
||||
After cleanup runs, log each step's result to both Cloud Logging and the Firestore job log subcollection with structured metadata.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1: Add `metadata` to `TimelineEvent` model
|
||||
- [ ] Add `metadata: Optional[Dict[str, Any]] = None` to `TimelineEvent` in `backend/models/job.py`
|
||||
- [ ] No migration needed — Firestore is schemaless, existing events just won't have the field
|
||||
|
||||
### Step 2: Create `log_to_job` helper
|
||||
- [ ] Add `log_to_job()` function in `backend/services/firestore_service.py` (or a small utility module)
|
||||
- [ ] Takes `job_id`, `worker`, `level`, `message`, optional `metadata`
|
||||
- [ ] Wraps `WorkerLogEntry.create()` + `append_log_to_subcollection()`
|
||||
- [ ] Catches and suppresses errors (logging should never break the caller)
|
||||
|
||||
### Step 3: Update `transition_to_state` to accept metadata
|
||||
- [ ] Add optional `timeline_metadata: Optional[Dict[str, Any]] = None` parameter to `job_manager.transition_to_state()`
|
||||
- [ ] Pass through to `update_job_status()` → `TimelineEvent` construction
|
||||
- [ ] Update `firestore_service.update_job_status()` to accept and pass `timeline_metadata`
|
||||
|
||||
### Step 4: Enhance edit endpoint logging
|
||||
- [ ] Before cleanup: snapshot current distribution outputs (`youtube_url`, `dropbox_link`, `brand_code`, `gdrive_files`) into `previous_outputs` dict
|
||||
- [ ] After each cleanup step: log result to Cloud Logging AND call `log_to_job()`
|
||||
- [ ] After all cleanup: include `previous_outputs` and `cleanup_results` in the timeline event metadata
|
||||
- [ ] The "Track edit initiated" timeline event gains metadata: `{initiated_by, previous_outputs, cleanup_results}`
|
||||
|
||||
### Step 5: Enhance admin delete-outputs endpoint logging
|
||||
- [ ] Same pattern as edit endpoint: snapshot outputs, log each cleanup step, include in timeline metadata
|
||||
- [ ] The "Outputs deleted by admin" timeline event gains metadata: `{deleted_by, deleted_outputs, cleanup_results}`
|
||||
|
||||
### Step 6: Enhance distribution logging in video_worker_orchestrator
|
||||
- [ ] YouTube upload success: log video_id and video_url with metadata `{video_id, video_url}`
|
||||
- [ ] Dropbox upload success: log folder_path and sharing_link with metadata `{folder_path, sharing_link}`
|
||||
- [ ] GDrive upload success: log file_ids with metadata `{file_ids: {...}}`
|
||||
- [ ] Brand code allocation: log with metadata `{brand_code, source: "allocated"|"recycled"}`
|
||||
|
||||
### Step 7: Add output details to `complete` timeline event
|
||||
- [ ] When `video_worker.py` calls `transition_to_state(COMPLETE)`, pass `timeline_metadata` with distribution output details
|
||||
- [ ] Include: `youtube_url`, `youtube_video_id`, `dropbox_link`, `brand_code`, `gdrive_file_ids`, `edit_count`
|
||||
|
||||
### Step 8: Tests
|
||||
- [ ] Unit test: `TimelineEvent` with metadata serializes correctly
|
||||
- [ ] Unit test: `log_to_job` writes to subcollection
|
||||
- [ ] Unit test: edit endpoint includes `previous_outputs` and `cleanup_results` in timeline event
|
||||
- [ ] Unit test: `complete` transition includes output metadata
|
||||
- [ ] Verify existing tests still pass
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/models/job.py` | Modify | Add `metadata` field to `TimelineEvent` |
|
||||
| `backend/services/firestore_service.py` | Modify | Add `log_to_job()` helper, update `update_job_status()` to accept timeline metadata |
|
||||
| `backend/services/job_manager.py` | Modify | Add `timeline_metadata` param to `transition_to_state()` |
|
||||
| `backend/api/routes/jobs.py` | Modify | Enhance edit endpoint with cleanup logging, output snapshots, timeline metadata |
|
||||
| `backend/api/routes/admin.py` | Modify | Enhance delete-outputs endpoint similarly |
|
||||
| `backend/workers/video_worker_orchestrator.py` | Modify | Add structured metadata to distribution log messages |
|
||||
| `backend/workers/video_worker.py` | Modify | Pass output metadata in `complete` transition (both orchestrator and legacy paths) |
|
||||
| `backend/tests/test_edit_completed_track.py` | Modify | Verify timeline metadata in edit tests |
|
||||
| `backend/tests/test_observability.py` | Create | Tests for TimelineEvent metadata and log_to_job |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests**: TimelineEvent metadata serialization, log_to_job helper, edit endpoint timeline metadata assertions
|
||||
- **Existing test verification**: `make test` must pass — changes are additive so existing tests should be unaffected
|
||||
- **No E2E tests needed**: This is purely backend logging/observability — no UI changes
|
||||
|
||||
## What This Does NOT Include
|
||||
|
||||
- **Dedicated admin UI for viewing job logs** — existing admin page already shows timeline
|
||||
- **Log aggregation/search UI** — Cloud Logging and Firestore viewer already serve this purpose
|
||||
- **Changing state_data overwrite behavior** — the `{**job.state_data, ...}` pattern in video_worker.py is intentional; instead we preserve history in timeline events
|
||||
- **Changing outputs_deleted_at clearing** — video worker clearing it after re-processing is correct behavior; the edit history lives in timeline metadata instead
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
All changes are additive (new optional field on TimelineEvent, additional log writes). Rolling back just means deploying the previous version — no data migration needed.
|
||||
|
||||
## Open Questions
|
||||
|
||||
None — the approach is straightforward and low-risk.
|
||||
@@ -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 }}"
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
| API reference | `docs/API.md` |
|
||||
| Past learnings | `docs/LESSONS-LEARNED.md` |
|
||||
| **Operational runbooks** | `docs/TROUBLESHOOTING.md` |
|
||||
| GDrive validator & gaps | `docs/GDRIVE-VALIDATOR.md` |
|
||||
| **Product communication** | `docs/PRODUCT-COMMUNICATION-GUIDE.md` |
|
||||
| Brand style guide | `docs/BRAND-STYLE-GUIDE.md` |
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ from backend.services.flacfetch_client import get_flacfetch_client, FlacfetchSer
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.audio_search_service import get_audio_search_service, NoResultsError, AudioSearchError
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.firestore_service import log_to_job
|
||||
from backend.utils.test_data import is_test_email
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
@@ -1045,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
|
||||
@@ -1081,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",
|
||||
@@ -1591,6 +1609,19 @@ async def delete_job_outputs(
|
||||
"gdrive": {"status": "skipped", "reason": "no gdrive_files in state_data"},
|
||||
}
|
||||
|
||||
# Snapshot current outputs before cleanup (preserved in timeline metadata)
|
||||
deleted_outputs = {}
|
||||
if state_data.get('youtube_url'):
|
||||
deleted_outputs['youtube_url'] = state_data['youtube_url']
|
||||
if state_data.get('dropbox_link'):
|
||||
deleted_outputs['dropbox_link'] = state_data['dropbox_link']
|
||||
if state_data.get('brand_code'):
|
||||
deleted_outputs['brand_code'] = state_data['brand_code']
|
||||
if state_data.get('gdrive_files'):
|
||||
deleted_outputs['gdrive_files'] = state_data['gdrive_files']
|
||||
|
||||
log_to_job(job_id, "admin", "INFO", f"Output deletion initiated by {admin_email}", {"deleted_outputs": deleted_outputs})
|
||||
|
||||
# Clean up YouTube
|
||||
youtube_url = state_data.get('youtube_url')
|
||||
if youtube_url:
|
||||
@@ -1717,11 +1748,17 @@ async def delete_job_outputs(
|
||||
update_payload[f"state_data.{key}"] = DELETE_FIELD
|
||||
cleared_keys.append(key)
|
||||
|
||||
# Add timeline event
|
||||
# Add timeline event with structured metadata
|
||||
timeline_event = {
|
||||
"status": job.status, # Keep current status
|
||||
"timestamp": deletion_timestamp.isoformat(),
|
||||
"message": f"Outputs deleted by admin ({admin_email})",
|
||||
"metadata": {
|
||||
"action": "outputs_deleted",
|
||||
"deleted_by": admin_email,
|
||||
"deleted_outputs": deleted_outputs,
|
||||
"cleanup_results": results,
|
||||
},
|
||||
}
|
||||
update_payload["timeline"] = ArrayUnion([timeline_event])
|
||||
|
||||
@@ -1755,6 +1792,10 @@ async def delete_job_outputs(
|
||||
f"Brand Code: {brand_code_status}. "
|
||||
f"Cleared state_data keys: {cleared_keys}"
|
||||
)
|
||||
log_to_job(job_id, "admin", "INFO", f"Outputs deleted by {admin_email}: {overall_status}", {
|
||||
"cleanup_results": results,
|
||||
"cleared_keys": cleared_keys,
|
||||
})
|
||||
|
||||
return DeleteOutputsResponse(
|
||||
status=overall_status,
|
||||
|
||||
@@ -50,6 +50,7 @@ from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
from backend.middleware.tenant import get_tenant_config_from_request
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.services.tracing import add_span_attribute
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from pathlib import Path
|
||||
|
||||
@@ -692,6 +693,11 @@ async def search_audio(
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "audio_search")
|
||||
add_span_attribute("job.is_private", body.is_private)
|
||||
|
||||
logger.info(f"Created job {job_id} for audio search: {body.artist} - {body.title}")
|
||||
|
||||
# Update job with audio search fields
|
||||
@@ -1029,7 +1035,9 @@ async def search_audio_standalone(
|
||||
)
|
||||
results_dicts.append(r.to_dict())
|
||||
|
||||
# Store session in Firestore (TTL: 30 minutes)
|
||||
# Store session in Firestore (TTL: 7 days)
|
||||
# Long TTL so users who leave a tab open mid-flow don't hit "Search expired".
|
||||
# Sessions are tiny docs (~2 KB) and cleaned up by Firestore TTL policy.
|
||||
session_id = str(uuid.uuid4())
|
||||
now = datetime.utcnow()
|
||||
session_data = {
|
||||
@@ -1041,7 +1049,7 @@ async def search_audio_standalone(
|
||||
'results': results_dicts,
|
||||
'remote_search_id': audio_search_service.last_remote_search_id,
|
||||
'created_at': now.isoformat(),
|
||||
'ttl_expiry': now + timedelta(minutes=30),
|
||||
'ttl_expiry': now + timedelta(days=7),
|
||||
}
|
||||
firestore_service = FirestoreService()
|
||||
firestore_service.create_search_session(session_data)
|
||||
|
||||
@@ -40,6 +40,7 @@ from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
from backend.middleware.tenant import get_tenant_config_from_request
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.services.tracing import add_span_attribute
|
||||
from backend.services.youtube_download_service import (
|
||||
get_youtube_download_service,
|
||||
YouTubeDownloadError,
|
||||
@@ -161,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."""
|
||||
@@ -427,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.
|
||||
@@ -657,11 +663,20 @@ async def upload_and_create_job(
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "upload")
|
||||
add_span_attribute("job.is_private", is_private)
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="upload")
|
||||
|
||||
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
|
||||
@@ -1230,6 +1245,11 @@ async def create_job_with_upload_urls(
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "signed_url_upload")
|
||||
add_span_attribute("job.is_private", effective_is_private)
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="upload")
|
||||
|
||||
@@ -1700,6 +1720,11 @@ async def create_job_from_url(
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "url")
|
||||
add_span_attribute("job.is_private", body.is_private)
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="url")
|
||||
|
||||
@@ -1718,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}")
|
||||
@@ -2002,6 +2031,11 @@ async def create_finalise_only_job(
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "finalise")
|
||||
add_span_attribute("job.is_private", body.is_private)
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="finalise")
|
||||
|
||||
|
||||
+376
-3
@@ -33,13 +33,15 @@ from backend.services.worker_service import get_worker_service
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.theme_service import get_theme_service
|
||||
from backend.config import get_settings
|
||||
from backend.services.tracing import add_span_attribute
|
||||
from backend.api.dependencies import require_admin, require_auth
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.services.metrics import metrics
|
||||
from backend.middleware.tenant import get_tenant_from_request
|
||||
from backend.utils.test_data import is_test_email
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from backend.services.firestore_service import FirestoreService, log_to_job
|
||||
from backend.models.requests import ChangeVisibilityRequest, ChangeVisibilityResponse
|
||||
from pydantic import BaseModel, Field, validator
|
||||
|
||||
|
||||
@@ -130,9 +132,14 @@ async def create_job(
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job.job_id)
|
||||
add_span_attribute("job.source", "url")
|
||||
add_span_attribute("job.is_private", job_create.is_private)
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job.job_id, source="url")
|
||||
|
||||
|
||||
# Trigger both workers in parallel using asyncio.gather
|
||||
# (FastAPI's BackgroundTasks runs async tasks sequentially)
|
||||
background_tasks.add_task(_trigger_workers_parallel, job.job_id)
|
||||
@@ -201,11 +208,308 @@ def _check_job_ownership(job: Job, auth_result: AuthResult) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
class EditTrackRequest(BaseModel):
|
||||
"""Request body for editing a completed track."""
|
||||
artist: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
|
||||
|
||||
class EditTrackResponse(BaseModel):
|
||||
"""Response from editing a completed track."""
|
||||
status: str
|
||||
job_id: str
|
||||
message: str
|
||||
review_url: str
|
||||
review_token: str
|
||||
metadata_updated: bool
|
||||
cleanup_results: Dict[str, Any]
|
||||
|
||||
|
||||
@router.post("/{job_id}/edit", response_model=EditTrackResponse)
|
||||
async def edit_completed_track(
|
||||
job_id: str,
|
||||
request: EditTrackRequest,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Edit a completed track by cleaning up distributed outputs and reopening review.
|
||||
|
||||
This allows users to correct lyrics, change instrumental selection, or update
|
||||
artist/title metadata on a completed job. The existing outputs (YouTube, Dropbox,
|
||||
GDrive, GCS finals) are deleted, the brand code is recycled, and the job is
|
||||
reset to AWAITING_REVIEW so the user can make changes and re-submit.
|
||||
|
||||
No additional credits are consumed — the original credit covers re-edits.
|
||||
"""
|
||||
import re
|
||||
from datetime import timezone
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
# Check ownership
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to edit this job")
|
||||
|
||||
# Only completed jobs can be edited
|
||||
if job.status != JobStatus.COMPLETE.value and job.status != "complete":
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Only completed jobs can be edited. Current status: {job.status}"
|
||||
)
|
||||
|
||||
# Prevent editing if outputs already deleted (edit already in progress)
|
||||
if job.outputs_deleted_at:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="This job is already being edited (outputs were already deleted)"
|
||||
)
|
||||
|
||||
user_email = auth_result.user_email or "unknown"
|
||||
state_data = job.state_data or {}
|
||||
cleanup_results = {}
|
||||
|
||||
# Snapshot current outputs before cleanup (preserved in timeline metadata)
|
||||
previous_outputs = {}
|
||||
if state_data.get('youtube_url'):
|
||||
previous_outputs['youtube_url'] = state_data['youtube_url']
|
||||
if state_data.get('dropbox_link'):
|
||||
previous_outputs['dropbox_link'] = state_data['dropbox_link']
|
||||
if state_data.get('brand_code'):
|
||||
previous_outputs['brand_code'] = state_data['brand_code']
|
||||
if state_data.get('gdrive_files'):
|
||||
previous_outputs['gdrive_files'] = state_data['gdrive_files']
|
||||
|
||||
log_to_job(job_id, "edit", "INFO", f"Edit initiated by {user_email}", {"previous_outputs": previous_outputs})
|
||||
|
||||
# --- Phase 1: Clean up distributed outputs ---
|
||||
|
||||
# Delete YouTube video
|
||||
youtube_url = state_data.get('youtube_url')
|
||||
if youtube_url:
|
||||
try:
|
||||
video_id_match = re.search(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)', youtube_url)
|
||||
if video_id_match:
|
||||
video_id = video_id_match.group(1)
|
||||
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from backend.services.youtube_service import get_youtube_service
|
||||
youtube_service = get_youtube_service()
|
||||
if youtube_service.is_configured:
|
||||
finalise = KaraokeFinalise(
|
||||
dry_run=False,
|
||||
non_interactive=True,
|
||||
user_youtube_credentials=youtube_service.get_credentials_dict()
|
||||
)
|
||||
success = finalise.delete_youtube_video(video_id)
|
||||
cleanup_results["youtube"] = {"status": "success" if success else "failed", "video_id": video_id}
|
||||
else:
|
||||
cleanup_results["youtube"] = {"status": "skipped", "reason": "YouTube not configured"}
|
||||
else:
|
||||
cleanup_results["youtube"] = {"status": "failed", "reason": f"Could not extract video ID from {youtube_url}"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting YouTube video for job {job_id}: {e}", exc_info=True)
|
||||
cleanup_results["youtube"] = {"status": "error", "error": str(e)}
|
||||
else:
|
||||
cleanup_results["youtube"] = {"status": "skipped", "reason": "no youtube_url"}
|
||||
log_to_job(job_id, "edit", "INFO", f"YouTube cleanup: {cleanup_results['youtube'].get('status')}", cleanup_results["youtube"])
|
||||
|
||||
# Delete Dropbox folder
|
||||
brand_code = state_data.get('brand_code')
|
||||
dropbox_path = getattr(job, 'dropbox_path', None)
|
||||
if brand_code and dropbox_path:
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
dropbox = get_dropbox_service()
|
||||
if dropbox.is_configured:
|
||||
base_name = f"{job.artist} - {job.title}"
|
||||
folder_name = f"{brand_code} - {base_name}"
|
||||
full_path = f"{dropbox_path}/{folder_name}"
|
||||
success = dropbox.delete_folder(full_path)
|
||||
cleanup_results["dropbox"] = {"status": "success" if success else "failed", "path": full_path}
|
||||
else:
|
||||
cleanup_results["dropbox"] = {"status": "skipped", "reason": "Dropbox not configured"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting Dropbox folder for job {job_id}: {e}", exc_info=True)
|
||||
cleanup_results["dropbox"] = {"status": "error", "error": str(e)}
|
||||
else:
|
||||
cleanup_results["dropbox"] = {"status": "skipped", "reason": "no brand_code or dropbox_path"}
|
||||
log_to_job(job_id, "edit", "INFO", f"Dropbox cleanup: {cleanup_results['dropbox'].get('status')}", cleanup_results["dropbox"])
|
||||
|
||||
# Delete Google Drive files
|
||||
gdrive_files = state_data.get('gdrive_files')
|
||||
if gdrive_files:
|
||||
try:
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
gdrive = get_gdrive_service()
|
||||
if gdrive.is_configured:
|
||||
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
|
||||
delete_results = gdrive.delete_files(file_ids)
|
||||
all_success = all(delete_results.values())
|
||||
cleanup_results["gdrive"] = {"status": "success" if all_success else "partial", "files": delete_results}
|
||||
else:
|
||||
cleanup_results["gdrive"] = {"status": "skipped", "reason": "Google Drive not configured"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting Google Drive files for job {job_id}: {e}", exc_info=True)
|
||||
cleanup_results["gdrive"] = {"status": "error", "error": str(e)}
|
||||
else:
|
||||
cleanup_results["gdrive"] = {"status": "skipped", "reason": "no gdrive_files"}
|
||||
log_to_job(job_id, "edit", "INFO", f"GDrive cleanup: {cleanup_results['gdrive'].get('status')}", cleanup_results["gdrive"])
|
||||
|
||||
# Delete GCS finals folder
|
||||
try:
|
||||
storage = StorageService()
|
||||
finals_prefix = f"jobs/{job_id}/finals/"
|
||||
deleted_count = storage.delete_folder(finals_prefix)
|
||||
cleanup_results["gcs_finals"] = {"status": "success", "deleted_count": deleted_count}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting GCS finals for job {job_id}: {e}", exc_info=True)
|
||||
cleanup_results["gcs_finals"] = {"status": "error", "error": str(e)}
|
||||
|
||||
# Recycle brand code if Dropbox + GDrive cleanup both succeeded
|
||||
dropbox_ok = cleanup_results.get("dropbox", {}).get("status") in ("success", "skipped")
|
||||
gdrive_ok = cleanup_results.get("gdrive", {}).get("status") in ("success", "skipped")
|
||||
if brand_code and dropbox_ok and gdrive_ok:
|
||||
try:
|
||||
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
|
||||
prefix, number = BrandCodeService.parse_brand_code(brand_code)
|
||||
get_brand_code_service().recycle_brand_code(prefix, number)
|
||||
cleanup_results["brand_code"] = {"status": "recycled", "code": brand_code}
|
||||
logger.info(f"Recycled brand code {brand_code} during edit for job {job_id}")
|
||||
except (ValueError, Exception) as e:
|
||||
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
|
||||
cleanup_results["brand_code"] = {"status": "failed", "error": str(e)}
|
||||
|
||||
# Check for critical cleanup failures before proceeding
|
||||
critical_failures = [
|
||||
svc for svc in ["dropbox", "gdrive"]
|
||||
if cleanup_results.get(svc, {}).get("status") == "error"
|
||||
]
|
||||
if critical_failures:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Cleanup failed for {', '.join(critical_failures)}. "
|
||||
f"Job not modified. Please try again or contact support."
|
||||
)
|
||||
|
||||
# --- Phase 2: Update job record ---
|
||||
|
||||
db = FirestoreService().db
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
update_payload: Dict[str, Any] = {
|
||||
"outputs_deleted_at": now,
|
||||
"outputs_deleted_by": user_email,
|
||||
"updated_at": now,
|
||||
"edit_count": (job.edit_count if hasattr(job, 'edit_count') else 0) + 1,
|
||||
}
|
||||
|
||||
# Clear distribution state_data keys
|
||||
output_keys = ["youtube_url", "youtube_video_id", "dropbox_link", "brand_code", "gdrive_files"]
|
||||
for key in output_keys:
|
||||
if key in state_data:
|
||||
update_payload[f"state_data.{key}"] = DELETE_FIELD
|
||||
|
||||
# Clear processing state so workers re-run from scratch
|
||||
processing_keys = ["render_progress", "video_progress", "encoding_progress", "review_complete"]
|
||||
for key in processing_keys:
|
||||
if key in state_data:
|
||||
update_payload[f"state_data.{key}"] = DELETE_FIELD
|
||||
|
||||
# --- Phase 3: Update metadata if provided ---
|
||||
|
||||
metadata_updated = False
|
||||
if request.artist and request.artist != job.artist:
|
||||
update_payload["artist"] = request.artist
|
||||
metadata_updated = True
|
||||
if request.title and request.title != job.title:
|
||||
update_payload["title"] = request.title
|
||||
metadata_updated = True
|
||||
|
||||
# If metadata changed, delete screens so they get regenerated
|
||||
if metadata_updated:
|
||||
try:
|
||||
screens_prefix = f"jobs/{job_id}/screens/"
|
||||
storage = StorageService()
|
||||
storage.delete_folder(screens_prefix)
|
||||
logger.info(f"Deleted screens for job {job_id} due to metadata change")
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to delete screens for job {job_id}: {e}")
|
||||
|
||||
# Clear screens progress so screens worker re-runs
|
||||
if "screens_progress" in state_data:
|
||||
update_payload[f"state_data.screens_progress"] = DELETE_FIELD
|
||||
|
||||
# Add timeline event with structured metadata
|
||||
edit_number = (job.edit_count if hasattr(job, 'edit_count') else 0) + 1
|
||||
timeline_event = {
|
||||
"status": "complete",
|
||||
"timestamp": now.isoformat(),
|
||||
"message": f"Track edit initiated by {user_email} (edit #{edit_number})",
|
||||
"metadata": {
|
||||
"action": "edit_initiated",
|
||||
"initiated_by": user_email,
|
||||
"edit_number": edit_number,
|
||||
"previous_outputs": previous_outputs,
|
||||
"cleanup_results": cleanup_results,
|
||||
},
|
||||
}
|
||||
update_payload["timeline"] = ArrayUnion([timeline_event])
|
||||
|
||||
# Apply Firestore update
|
||||
job_ref.update(update_payload)
|
||||
|
||||
# --- Phase 4: Transition state to AWAITING_REVIEW ---
|
||||
# This auto-generates a review token via transition_to_state
|
||||
job_manager.transition_to_state(
|
||||
job_id,
|
||||
JobStatus.AWAITING_REVIEW,
|
||||
progress=60,
|
||||
message="Track reopened for editing",
|
||||
)
|
||||
|
||||
# If metadata changed, trigger screens worker in background
|
||||
if metadata_updated:
|
||||
background_tasks.add_task(worker_service.trigger_screens_worker, job_id)
|
||||
|
||||
# Fetch updated job to get the review token
|
||||
updated_job = job_manager.get_job(job_id)
|
||||
if not updated_job:
|
||||
logger.error(f"Job {job_id} not found after state transition to AWAITING_REVIEW")
|
||||
raise HTTPException(status_code=500, detail="Job state update failed unexpectedly")
|
||||
review_token = updated_job.review_token or ""
|
||||
|
||||
logger.info(
|
||||
f"User {user_email} initiated edit #{edit_number} for job {job_id}. "
|
||||
f"Metadata updated: {metadata_updated}. "
|
||||
f"Cleanup: YouTube={cleanup_results.get('youtube', {}).get('status')}, "
|
||||
f"Dropbox={cleanup_results.get('dropbox', {}).get('status')}, "
|
||||
f"GDrive={cleanup_results.get('gdrive', {}).get('status')}"
|
||||
)
|
||||
log_to_job(job_id, "edit", "INFO", f"Edit #{edit_number} complete: reopened for review", {
|
||||
"cleanup_results": cleanup_results,
|
||||
"metadata_updated": metadata_updated,
|
||||
})
|
||||
|
||||
return EditTrackResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
message="Track reopened for editing. Previous outputs have been removed.",
|
||||
review_url=f"/app/jobs#/{job_id}/review",
|
||||
review_token=review_token,
|
||||
metadata_updated=metadata_updated,
|
||||
cleanup_results=cleanup_results,
|
||||
)
|
||||
|
||||
|
||||
_SUMMARY_STATE_DATA_KEYS = {
|
||||
'brand_code', 'youtube_url', 'dropbox_link',
|
||||
'audio_progress', 'lyrics_progress',
|
||||
'audio_complete', 'lyrics_complete',
|
||||
'backing_vocals_analysis',
|
||||
'backing_vocals_analysis', 'visibility_change_in_progress',
|
||||
}
|
||||
_SUMMARY_FILE_URLS_KEYS = {'finals', 'videos', 'packages'}
|
||||
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete']
|
||||
@@ -1781,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):
|
||||
@@ -1931,6 +2236,11 @@ async def create_job_from_search(
|
||||
|
||||
logger.info(f"Created job {job_id} from search session {body.search_session_id}")
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "guided_search")
|
||||
add_span_attribute("job.is_private", body.is_private)
|
||||
|
||||
metrics.record_job_created(job_id, source="guided_search")
|
||||
|
||||
# Apply default theme style to job (copy style_params.json to job folder)
|
||||
@@ -1958,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)
|
||||
@@ -1987,3 +2299,64 @@ async def create_job_from_search(
|
||||
logger.error(f"Error creating job from search: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Change Visibility Endpoint
|
||||
# =============================================================================
|
||||
|
||||
@router.post("/{job_id}/change-visibility", response_model=ChangeVisibilityResponse)
|
||||
async def change_visibility(
|
||||
job_id: str,
|
||||
request: ChangeVisibilityRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Change job visibility between public and private.
|
||||
|
||||
Public -> Private (fast, ~1-2 min):
|
||||
- Removes YouTube/GDrive/Dropbox outputs
|
||||
- Redistributes existing files to private destination
|
||||
|
||||
Private -> Public (slow, ~15-30 min):
|
||||
- Resets custom styling to default Nomad theme
|
||||
- Regenerates screens, re-renders video, publishes publicly
|
||||
"""
|
||||
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_result.user_email or "unknown"
|
||||
is_admin = auth_result.is_admin
|
||||
|
||||
from backend.services.visibility_change_service import VisibilityChangeService
|
||||
service = VisibilityChangeService(job_manager)
|
||||
|
||||
# Validate (skip job-exists check since we already handled it)
|
||||
error = service.validate_change(job, user_email, is_admin, request.target_visibility)
|
||||
if error:
|
||||
status_code = 403 if "your own jobs" in error else 400
|
||||
raise HTTPException(status_code=status_code, detail=error)
|
||||
|
||||
current_is_private = getattr(job, 'is_private', False)
|
||||
previous_visibility = "private" if current_is_private else "public"
|
||||
|
||||
try:
|
||||
if request.target_visibility == "private":
|
||||
result = await service.change_to_private(job_id, job, user_email)
|
||||
else:
|
||||
result = await service.change_to_public(job_id, job, user_email)
|
||||
|
||||
return ChangeVisibilityResponse(
|
||||
status=result["status"],
|
||||
job_id=job_id,
|
||||
message=result["message"],
|
||||
previous_visibility=previous_visibility,
|
||||
new_visibility=request.target_visibility,
|
||||
reprocessing_required=result["reprocessing_required"],
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error changing visibility for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Failed to change visibility: {str(e)}")
|
||||
@@ -26,7 +26,9 @@ from fastapi.responses import FileResponse, RedirectResponse, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.models.review_session import ReviewSession, ReviewSessionSummary
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.job_logging import job_log_context, JobLogger
|
||||
from backend.services.tracing import create_span, add_span_attribute, add_span_event
|
||||
@@ -63,6 +65,27 @@ def _get_audio_hash(job_id: str) -> str:
|
||||
return hashlib.md5(job_id.encode()).hexdigest()
|
||||
|
||||
|
||||
# Cross-job search endpoint MUST be registered before {job_id} routes
|
||||
# to avoid FastAPI matching "sessions" as a job_id path parameter.
|
||||
@router.get("/sessions/search")
|
||||
async def search_review_sessions(
|
||||
q: str = "",
|
||||
limit: int = 20,
|
||||
auth_info: Tuple[str, str] = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Search review sessions across all jobs (admin only).
|
||||
|
||||
Query params:
|
||||
- q: Search text (matches artist, title, or job_id)
|
||||
- limit: Max results (default 20)
|
||||
"""
|
||||
firestore_svc = FirestoreService()
|
||||
results = firestore_svc.search_review_sessions(query_text=q, limit=limit)
|
||||
|
||||
return {"sessions": results}
|
||||
|
||||
|
||||
@router.get("/{job_id}/ping")
|
||||
async def ping(job_id: str):
|
||||
"""Health check endpoint expected by frontend."""
|
||||
@@ -905,3 +928,851 @@ async def get_waveform_data(
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error generating waveform data: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error generating waveform: {str(e)}")
|
||||
|
||||
|
||||
# ============================================
|
||||
# Review Session Endpoints (backup/restore)
|
||||
# ============================================
|
||||
|
||||
|
||||
@router.post("/{job_id}/sessions")
|
||||
async def save_review_session(
|
||||
job_id: str,
|
||||
data: Dict[str, Any],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Save a review session snapshot for backup/restore.
|
||||
|
||||
Stores correction data in GCS and metadata in Firestore subcollection.
|
||||
Skips save if the data is identical to the most recent session (deduplication).
|
||||
|
||||
Request body:
|
||||
- correction_data: Full CorrectionData object
|
||||
- edit_count: Number of edits in this session
|
||||
- trigger: "auto" | "preview" | "manual"
|
||||
- summary: { total_segments, total_words, corrections_made, changed_words[] }
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
firestore_svc = FirestoreService()
|
||||
storage = StorageService()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
correction_data = data.get("correction_data")
|
||||
if not correction_data:
|
||||
raise HTTPException(status_code=400, detail="correction_data is required")
|
||||
|
||||
# Compute hash for deduplication
|
||||
data_json = json.dumps(correction_data, sort_keys=True, default=str)
|
||||
data_hash = hashlib.sha256(data_json.encode()).hexdigest()
|
||||
|
||||
# Check if identical to most recent session
|
||||
latest_hash = firestore_svc.get_latest_review_session_hash(job_id)
|
||||
if latest_hash == data_hash:
|
||||
logger.info(f"Job {job_id}: Skipping duplicate review session save")
|
||||
return {"status": "skipped", "reason": "identical_data"}
|
||||
|
||||
# Get audio duration from backing_vocals_analysis if available
|
||||
audio_duration = None
|
||||
backing_analysis = job.state_data.get("backing_vocals_analysis", {})
|
||||
if backing_analysis:
|
||||
audio_duration = backing_analysis.get("total_duration_seconds")
|
||||
|
||||
# Build session
|
||||
user_email = auth_info[0] if auth_info else ""
|
||||
summary_data = data.get("summary", {})
|
||||
|
||||
session = ReviewSession(
|
||||
job_id=job_id,
|
||||
user_email=user_email,
|
||||
edit_count=data.get("edit_count", 0),
|
||||
trigger=data.get("trigger", "auto"),
|
||||
audio_duration_seconds=audio_duration,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
summary=ReviewSessionSummary.from_dict(summary_data),
|
||||
data_hash=data_hash,
|
||||
)
|
||||
|
||||
# Upload correction data to GCS
|
||||
gcs_path = f"jobs/{job_id}/review_sessions/{session.session_id}.json"
|
||||
storage.upload_json(gcs_path, correction_data)
|
||||
session.correction_data_gcs_path = gcs_path
|
||||
|
||||
# Save metadata to Firestore
|
||||
firestore_svc.save_review_session(job_id, session)
|
||||
|
||||
logger.info(f"Job {job_id}: Saved review session {session.session_id} (trigger={session.trigger}, edits={session.edit_count})")
|
||||
return {
|
||||
"status": "saved",
|
||||
"session_id": session.session_id,
|
||||
"created_at": session.created_at.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{job_id}/sessions")
|
||||
async def list_review_sessions(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
List all review sessions for a job (metadata only, no correction_data).
|
||||
Ordered by updated_at descending (most recent first).
|
||||
"""
|
||||
firestore_svc = FirestoreService()
|
||||
sessions = firestore_svc.list_review_sessions(job_id)
|
||||
|
||||
return {
|
||||
"sessions": [
|
||||
{
|
||||
"session_id": s.session_id,
|
||||
"job_id": s.job_id,
|
||||
"user_email": s.user_email,
|
||||
"created_at": s.created_at.isoformat() if s.created_at else None,
|
||||
"updated_at": s.updated_at.isoformat() if s.updated_at else None,
|
||||
"edit_count": s.edit_count,
|
||||
"trigger": s.trigger,
|
||||
"audio_duration_seconds": s.audio_duration_seconds,
|
||||
"artist": s.artist,
|
||||
"title": s.title,
|
||||
"summary": s.summary.to_dict(),
|
||||
}
|
||||
for s in sessions
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{job_id}/sessions/{session_id}")
|
||||
async def get_review_session(
|
||||
job_id: str,
|
||||
session_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Get a single review session with full correction_data loaded from GCS.
|
||||
"""
|
||||
firestore_svc = FirestoreService()
|
||||
storage = StorageService()
|
||||
|
||||
session = firestore_svc.get_review_session(job_id, session_id)
|
||||
if not session:
|
||||
raise HTTPException(status_code=404, detail="Review session not found")
|
||||
|
||||
# Load correction data from GCS
|
||||
correction_data = None
|
||||
if session.correction_data_gcs_path:
|
||||
try:
|
||||
correction_data = storage.download_json(session.correction_data_gcs_path)
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error loading correction data for session {session_id}: {e}")
|
||||
raise HTTPException(status_code=500, detail="Error loading session correction data")
|
||||
|
||||
return {
|
||||
"session_id": session.session_id,
|
||||
"job_id": session.job_id,
|
||||
"user_email": session.user_email,
|
||||
"created_at": session.created_at.isoformat() if session.created_at else None,
|
||||
"updated_at": session.updated_at.isoformat() if session.updated_at else None,
|
||||
"edit_count": session.edit_count,
|
||||
"trigger": session.trigger,
|
||||
"audio_duration_seconds": session.audio_duration_seconds,
|
||||
"artist": session.artist,
|
||||
"title": session.title,
|
||||
"summary": session.summary.to_dict(),
|
||||
"correction_data": correction_data,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/{job_id}/sessions/{session_id}")
|
||||
async def delete_review_session(
|
||||
job_id: str,
|
||||
session_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Delete a review session (metadata + GCS data)."""
|
||||
firestore_svc = FirestoreService()
|
||||
storage = StorageService()
|
||||
|
||||
session = firestore_svc.get_review_session(job_id, session_id)
|
||||
if not session:
|
||||
raise HTTPException(status_code=404, detail="Review session not found")
|
||||
|
||||
# Delete GCS data
|
||||
if session.correction_data_gcs_path:
|
||||
try:
|
||||
storage.delete_file(session.correction_data_gcs_path)
|
||||
except Exception:
|
||||
logger.warning(f"Job {job_id}: Could not delete GCS file for session {session_id}")
|
||||
|
||||
# Delete Firestore doc
|
||||
firestore_svc.delete_review_session(job_id, session_id)
|
||||
|
||||
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(edit_data, gcs_path)
|
||||
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', [])
|
||||
|
||||
# Get metadata for the original audio
|
||||
metadata = edit_service.get_metadata_from_gcs(job.input_media_gcs_path)
|
||||
|
||||
# Waveform for original audio
|
||||
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, edit_log_path)
|
||||
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 (same as normal post-download flow)
|
||||
worker_service = get_worker_service()
|
||||
await asyncio.gather(
|
||||
worker_service.trigger_audio_worker(job_id),
|
||||
worker_service.trigger_lyrics_worker(job_id),
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"message": "Audio edit saved. Processing will continue with edited audio.",
|
||||
"job_id": job_id,
|
||||
"edits_applied": len(edit_stack),
|
||||
}
|
||||
@@ -66,6 +66,7 @@ from backend.services.youtube_download_service import (
|
||||
YouTubeDownloadError,
|
||||
)
|
||||
from backend.exceptions import InvalidStateTransitionError
|
||||
from backend.services.tracing import add_span_attribute
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -578,6 +579,11 @@ async def _handle_made_for_you_order(
|
||||
job = job_manager.create_job(job_create, is_admin=True)
|
||||
job_id = job.job_id
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "made_for_you")
|
||||
add_span_attribute("job.is_private", False)
|
||||
|
||||
logger.info(f"Created made-for-you job {job_id} for {_mask_email(customer_email)} (owned by {_mask_email(ADMIN_EMAIL)})")
|
||||
|
||||
# Prepare theme style assets for the job (same as audio_search endpoint)
|
||||
|
||||
@@ -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", ""),
|
||||
)
|
||||
+23
-4
@@ -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],
|
||||
@@ -142,10 +154,10 @@ STATE_TRANSITIONS = {
|
||||
JobStatus.UPLOADING: [JobStatus.NOTIFYING, JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
JobStatus.NOTIFYING: [JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
|
||||
# Terminal states - COMPLETE, PREP_COMPLETE have no transitions
|
||||
# Terminal states - COMPLETE allows edit (reopen review) and visibility change
|
||||
# FAILED and CANCELLED allow retry transitions to resume from checkpoints
|
||||
# PREP_COMPLETE allows continuation from combined review
|
||||
JobStatus.COMPLETE: [],
|
||||
JobStatus.COMPLETE: [JobStatus.AWAITING_REVIEW, JobStatus.LYRICS_COMPLETE], # Edit track or visibility change
|
||||
JobStatus.PREP_COMPLETE: [JobStatus.AWAITING_REVIEW, JobStatus.FAILED], # Continue from combined review
|
||||
JobStatus.FAILED: [
|
||||
JobStatus.DOWNLOADING, # Retry from beginning (if input audio exists)
|
||||
@@ -179,6 +191,7 @@ class TimelineEvent(BaseModel):
|
||||
timestamp: str
|
||||
progress: Optional[int] = None
|
||||
message: Optional[str] = None
|
||||
metadata: Optional[Dict[str, Any]] = None
|
||||
|
||||
|
||||
class LogEntry(BaseModel):
|
||||
@@ -305,6 +318,9 @@ class Job(BaseModel):
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = False # Private tracks: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive
|
||||
|
||||
# Creation-time decision params (for observability — what did the user actually choose?)
|
||||
creation_params: Dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
# Output deletion tracking (for admin cleanup without deleting job)
|
||||
outputs_deleted_at: Optional[datetime] = None # Timestamp when outputs were deleted by admin
|
||||
outputs_deleted_by: Optional[str] = None # Admin email who deleted outputs
|
||||
@@ -312,6 +328,9 @@ class Job(BaseModel):
|
||||
# Credit refund tracking (prevents double-refund on cancel→delete or fail→delete)
|
||||
credit_refunded: bool = False
|
||||
|
||||
# Edit tracking (how many times a completed track has been re-edited)
|
||||
edit_count: int = 0
|
||||
|
||||
# Processing state
|
||||
track_output_dir: Optional[str] = None # Local output directory (temp)
|
||||
audio_hash: Optional[str] = None # Hash for deduplication
|
||||
|
||||
@@ -142,3 +142,24 @@ class RetryJobRequest(BaseModel):
|
||||
"""Request to retry a failed job."""
|
||||
from_stage: Optional[str] = None # Optional: restart from specific stage
|
||||
|
||||
|
||||
class ChangeVisibilityRequest(BaseModel):
|
||||
"""Request to change job visibility (public/private)."""
|
||||
target_visibility: str # "public" or "private"
|
||||
|
||||
@validator('target_visibility')
|
||||
def validate_target(cls, v):
|
||||
if v not in ('public', 'private'):
|
||||
raise ValueError("target_visibility must be 'public' or 'private'")
|
||||
return v
|
||||
|
||||
|
||||
class ChangeVisibilityResponse(BaseModel):
|
||||
"""Response from change visibility endpoint."""
|
||||
status: str # "success", "processing", "error"
|
||||
job_id: str
|
||||
message: str
|
||||
previous_visibility: str # "public" or "private"
|
||||
new_visibility: str # "public" or "private"
|
||||
reprocessing_required: bool
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
"""
|
||||
Review session model for persisting lyrics review progress.
|
||||
|
||||
Stored as a Firestore subcollection: jobs/{job_id}/review_sessions/{session_id}
|
||||
Full correction 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 ReviewSessionSummary:
|
||||
"""Compact summary of edits in a review session, for list views."""
|
||||
total_segments: int = 0
|
||||
total_words: int = 0
|
||||
corrections_made: int = 0
|
||||
changed_words: List[Dict[str, Any]] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"total_segments": self.total_segments,
|
||||
"total_words": self.total_words,
|
||||
"corrections_made": self.corrections_made,
|
||||
"changed_words": self.changed_words,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> "ReviewSessionSummary":
|
||||
return cls(
|
||||
total_segments=data.get("total_segments", 0),
|
||||
total_words=data.get("total_words", 0),
|
||||
corrections_made=data.get("corrections_made", 0),
|
||||
changed_words=data.get("changed_words", []),
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ReviewSession:
|
||||
"""
|
||||
A saved snapshot of a lyrics review editing session.
|
||||
|
||||
Stored at: jobs/{job_id}/review_sessions/{session_id}
|
||||
Correction data stored at: jobs/{job_id}/review_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" | "preview" | "manual"
|
||||
audio_duration_seconds: Optional[float] = None
|
||||
artist: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
summary: ReviewSessionSummary = field(default_factory=ReviewSessionSummary)
|
||||
correction_data_gcs_path: str = ""
|
||||
|
||||
# Hash of the correction 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,
|
||||
"artist": self.artist,
|
||||
"title": self.title,
|
||||
"summary": self.summary.to_dict(),
|
||||
"correction_data_gcs_path": self.correction_data_gcs_path,
|
||||
"data_hash": self.data_hash,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> "ReviewSession":
|
||||
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 = ReviewSessionSummary.from_dict(summary_data) if isinstance(summary_data, dict) else ReviewSessionSummary()
|
||||
|
||||
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"),
|
||||
artist=data.get("artist"),
|
||||
title=data.get("title"),
|
||||
summary=summary,
|
||||
correction_data_gcs_path=data.get("correction_data_gcs_path", ""),
|
||||
data_hash=data.get("data_hash", ""),
|
||||
)
|
||||
@@ -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}")
|
||||
@@ -10,6 +10,8 @@ from google.cloud.firestore_v1 import FieldFilter
|
||||
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__)
|
||||
@@ -75,18 +77,20 @@ class FirestoreService:
|
||||
status: JobStatus,
|
||||
progress: Optional[int] = None,
|
||||
message: Optional[str] = None,
|
||||
timeline_metadata: Optional[Dict[str, Any]] = None,
|
||||
**additional_fields
|
||||
) -> None:
|
||||
"""Update job status and add timeline event."""
|
||||
try:
|
||||
doc_ref = self.db.collection(self.collection).document(job_id)
|
||||
|
||||
|
||||
# Create timeline event
|
||||
timeline_event = TimelineEvent(
|
||||
status=status.value,
|
||||
timestamp=datetime.utcnow().isoformat(),
|
||||
progress=progress,
|
||||
message=message
|
||||
message=message,
|
||||
metadata=timeline_metadata,
|
||||
)
|
||||
|
||||
# Prepare updates
|
||||
@@ -177,11 +181,11 @@ class FirestoreService:
|
||||
# Fields needed by the dashboard summary view
|
||||
SUMMARY_FIELD_PATHS = [
|
||||
'job_id', 'status', 'progress', 'created_at', 'artist', 'title',
|
||||
'error_message', 'non_interactive', 'outputs_deleted_at', 'user_email',
|
||||
'error_message', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
|
||||
'state_data.brand_code', 'state_data.youtube_url', 'state_data.dropbox_link',
|
||||
'state_data.audio_progress', 'state_data.lyrics_progress',
|
||||
'state_data.audio_complete', 'state_data.lyrics_complete',
|
||||
'state_data.backing_vocals_analysis',
|
||||
'state_data.backing_vocals_analysis', 'state_data.visibility_change_in_progress',
|
||||
'file_urls.finals', 'file_urls.videos', 'file_urls.packages',
|
||||
]
|
||||
|
||||
@@ -673,6 +677,326 @@ class FirestoreService:
|
||||
transaction = self.db.transaction()
|
||||
return _read_and_delete(transaction, doc_ref)
|
||||
|
||||
# ============================================
|
||||
# Review Session Subcollection Methods
|
||||
# ============================================
|
||||
# These methods store review session snapshots in a subcollection
|
||||
# (jobs/{job_id}/review_sessions) for lyrics review backup/restore.
|
||||
|
||||
def save_review_session(self, job_id: str, session: ReviewSession) -> str:
|
||||
"""
|
||||
Save a review session to the subcollection.
|
||||
|
||||
Stores at: jobs/{job_id}/review_sessions/{session_id}
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
session: ReviewSession instance
|
||||
|
||||
Returns:
|
||||
session_id
|
||||
"""
|
||||
try:
|
||||
session.job_id = job_id
|
||||
sessions_ref = self.db.collection(self.collection).document(job_id).collection("review_sessions")
|
||||
doc_ref = sessions_ref.document(session.session_id)
|
||||
doc_ref.set(session.to_dict())
|
||||
logger.info(f"Saved review session {session.session_id} for job {job_id}")
|
||||
return session.session_id
|
||||
except Exception as e:
|
||||
logger.error(f"Error saving review session for job {job_id}: {e}")
|
||||
raise
|
||||
|
||||
def list_review_sessions(self, job_id: str) -> List[ReviewSession]:
|
||||
"""
|
||||
List all review sessions for a job, ordered by updated_at descending.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
|
||||
Returns:
|
||||
List of ReviewSession instances (metadata only, no correction_data)
|
||||
"""
|
||||
try:
|
||||
sessions_ref = self.db.collection(self.collection).document(job_id).collection("review_sessions")
|
||||
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING)
|
||||
docs = query.stream()
|
||||
return [ReviewSession.from_dict(doc.to_dict()) for doc in docs]
|
||||
except Exception as e:
|
||||
logger.error(f"Error listing review sessions for job {job_id}: {e}")
|
||||
return []
|
||||
|
||||
def get_review_session(self, job_id: str, session_id: str) -> Optional[ReviewSession]:
|
||||
"""
|
||||
Get a single review session by ID.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
session_id: Session ID
|
||||
|
||||
Returns:
|
||||
ReviewSession or None
|
||||
"""
|
||||
try:
|
||||
doc_ref = (
|
||||
self.db.collection(self.collection)
|
||||
.document(job_id)
|
||||
.collection("review_sessions")
|
||||
.document(session_id)
|
||||
)
|
||||
doc = doc_ref.get()
|
||||
if not doc.exists:
|
||||
return None
|
||||
return ReviewSession.from_dict(doc.to_dict())
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting review session {session_id} for job {job_id}: {e}")
|
||||
raise
|
||||
|
||||
def delete_review_session(self, job_id: str, session_id: str) -> None:
|
||||
"""
|
||||
Delete a review session.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
session_id: Session ID
|
||||
"""
|
||||
try:
|
||||
doc_ref = (
|
||||
self.db.collection(self.collection)
|
||||
.document(job_id)
|
||||
.collection("review_sessions")
|
||||
.document(session_id)
|
||||
)
|
||||
doc_ref.delete()
|
||||
logger.info(f"Deleted review session {session_id} for job {job_id}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting review session {session_id} for job {job_id}: {e}")
|
||||
raise
|
||||
|
||||
def delete_review_sessions_subcollection(self, job_id: str, batch_size: int = 500) -> int:
|
||||
"""
|
||||
Delete all review sessions for a job (used when deleting a job).
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
batch_size: Number of documents to delete per batch
|
||||
|
||||
Returns:
|
||||
Number of sessions deleted
|
||||
"""
|
||||
try:
|
||||
sessions_ref = self.db.collection(self.collection).document(job_id).collection("review_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} review sessions for job {job_id}")
|
||||
|
||||
return deleted_count
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting review sessions subcollection for job {job_id}: {e}")
|
||||
return 0
|
||||
|
||||
def get_latest_review_session_hash(self, job_id: str) -> Optional[str]:
|
||||
"""
|
||||
Get the data_hash of the most recent review session for deduplication.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
|
||||
Returns:
|
||||
data_hash string or None if no sessions exist
|
||||
"""
|
||||
try:
|
||||
sessions_ref = self.db.collection(self.collection).document(job_id).collection("review_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 review session hash for job {job_id}: {e}")
|
||||
return None
|
||||
|
||||
def search_review_sessions(
|
||||
self,
|
||||
query_text: str = "",
|
||||
job_id: Optional[str] = None,
|
||||
limit: int = 20,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Search review sessions across all jobs using collection group query.
|
||||
|
||||
Args:
|
||||
query_text: Search text (prefix-matched against artist_lower or title_lower)
|
||||
job_id: If provided, search only within this job
|
||||
limit: Maximum results
|
||||
|
||||
Returns:
|
||||
List of session dicts with job context
|
||||
"""
|
||||
try:
|
||||
if job_id:
|
||||
# Search within a specific job
|
||||
sessions_ref = self.db.collection(self.collection).document(job_id).collection("review_sessions")
|
||||
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING).limit(limit)
|
||||
docs = query.stream()
|
||||
return [doc.to_dict() for doc in docs]
|
||||
|
||||
# Collection group query across all jobs
|
||||
sessions_ref = self.db.collection_group("review_sessions")
|
||||
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING).limit(limit)
|
||||
docs = query.stream()
|
||||
results = [doc.to_dict() for doc in docs]
|
||||
|
||||
# Filter in Python for text search (Firestore doesn't support LIKE)
|
||||
if query_text:
|
||||
q_lower = query_text.lower()
|
||||
results = [
|
||||
r for r in results
|
||||
if q_lower in (r.get("artist") or "").lower()
|
||||
or q_lower in (r.get("title") or "").lower()
|
||||
or q_lower in (r.get("job_id") or "").lower()
|
||||
]
|
||||
|
||||
return results
|
||||
|
||||
except Exception as e:
|
||||
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.
|
||||
|
||||
@@ -710,3 +1034,35 @@ def get_firestore_client() -> firestore.Client:
|
||||
_firestore_client = firestore.Client(project=settings.google_cloud_project)
|
||||
return _firestore_client
|
||||
|
||||
|
||||
_log_service: Optional["FirestoreService"] = None
|
||||
|
||||
|
||||
def _get_log_service() -> "FirestoreService":
|
||||
"""Return a cached FirestoreService instance for log_to_job."""
|
||||
global _log_service
|
||||
if _log_service is None:
|
||||
_log_service = FirestoreService()
|
||||
return _log_service
|
||||
|
||||
|
||||
def log_to_job(job_id: str, worker: str, level: str, message: str, metadata: Optional[Dict[str, Any]] = None) -> None:
|
||||
"""
|
||||
Write a log entry to a job's Firestore log subcollection.
|
||||
|
||||
This is a convenience function for API endpoints that need to log
|
||||
to a job's log history (workers already have JobLogAdapter for this).
|
||||
|
||||
Args:
|
||||
job_id: Job ID to log to
|
||||
worker: Worker/source name (e.g., "api", "edit", "admin")
|
||||
level: Log level (INFO, WARNING, ERROR)
|
||||
message: Log message
|
||||
metadata: Optional structured metadata dict
|
||||
"""
|
||||
try:
|
||||
entry = WorkerLogEntry.create(job_id, worker, level, message, metadata)
|
||||
_get_log_service().append_log_to_subcollection(job_id, entry)
|
||||
except Exception as e:
|
||||
logger.debug(f"Failed to write job log for {job_id}: {e}")
|
||||
|
||||
@@ -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,
|
||||
],
|
||||
|
||||
@@ -120,8 +120,14 @@ class JobManager:
|
||||
customer_notes=job_create.customer_notes,
|
||||
# Private (non-published) track mode
|
||||
is_private=job_create.is_private,
|
||||
# Capture creation-time decision params for observability
|
||||
creation_params={
|
||||
"is_private": job_create.is_private,
|
||||
"is_admin": is_admin,
|
||||
"created_from": job_create.request_metadata.get("created_from", "unknown"),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
self.firestore.create_job(job)
|
||||
logger.info(f"Created new job {job_id} with status PENDING")
|
||||
|
||||
@@ -344,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}")
|
||||
|
||||
@@ -407,7 +421,8 @@ class JobManager:
|
||||
progress: Optional[int] = None,
|
||||
message: Optional[str] = None,
|
||||
state_data_updates: Optional[Dict[str, Any]] = None,
|
||||
raise_on_invalid: bool = True
|
||||
raise_on_invalid: bool = True,
|
||||
timeline_metadata: Optional[Dict[str, Any]] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Transition job to new state with validation.
|
||||
@@ -420,6 +435,7 @@ class JobManager:
|
||||
state_data_updates: Updates to state_data field
|
||||
raise_on_invalid: If True (default), raise InvalidStateTransitionError
|
||||
on invalid transitions. If False, return False silently.
|
||||
timeline_metadata: Optional structured metadata to attach to the timeline event
|
||||
|
||||
Returns:
|
||||
True if transition succeeded, False if failed (only when raise_on_invalid=False)
|
||||
@@ -429,31 +445,31 @@ class JobManager:
|
||||
"""
|
||||
if not self.validate_state_transition(job_id, new_status, raise_on_invalid=raise_on_invalid):
|
||||
return False
|
||||
|
||||
|
||||
updates = {
|
||||
'status': new_status,
|
||||
'updated_at': datetime.utcnow()
|
||||
}
|
||||
|
||||
|
||||
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
|
||||
updates['review_token_expires_at'] = None # No expiry - token is job-scoped
|
||||
logger.info(f"Generated review token for job {job_id} (no expiry)")
|
||||
|
||||
|
||||
# If we have state_data_updates, merge them with existing state_data
|
||||
merged_state_data = None
|
||||
if state_data_updates:
|
||||
job = self.get_job(job_id)
|
||||
if job:
|
||||
merged_state_data = {**job.state_data, **state_data_updates}
|
||||
|
||||
|
||||
# Update job status (includes timeline event), passing state_data if present
|
||||
if merged_state_data is not None:
|
||||
self.update_job_status(
|
||||
@@ -461,6 +477,7 @@ class JobManager:
|
||||
status=new_status,
|
||||
progress=progress,
|
||||
message=message,
|
||||
timeline_metadata=timeline_metadata,
|
||||
state_data=merged_state_data
|
||||
)
|
||||
else:
|
||||
@@ -468,7 +485,8 @@ class JobManager:
|
||||
job_id=job_id,
|
||||
status=new_status,
|
||||
progress=progress,
|
||||
message=message
|
||||
message=message,
|
||||
timeline_metadata=timeline_metadata,
|
||||
)
|
||||
|
||||
# Apply review token update separately if generated
|
||||
@@ -521,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:
|
||||
@@ -611,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
|
||||
|
||||
@@ -243,12 +243,12 @@ class PushNotificationService:
|
||||
if action_type == "lyrics":
|
||||
notif_title = "Review Lyrics"
|
||||
notif_body = f'"{title}" by {artist} needs lyrics review'
|
||||
url = f"/review/{job_id}"
|
||||
url = f"/app/jobs#/{job_id}/review"
|
||||
tag = f"lyrics-{job_id}"
|
||||
else: # instrumental
|
||||
notif_title = "Select Instrumental"
|
||||
notif_body = f'"{title}" by {artist} needs instrumental selection'
|
||||
url = f"/instrumental/{job_id}"
|
||||
url = f"/app/jobs#/{job_id}/instrumental"
|
||||
tag = f"instrumental-{job_id}"
|
||||
|
||||
return await self.send_push(
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
"""
|
||||
Visibility change service for completed jobs.
|
||||
|
||||
Handles changing a job's visibility between public and private:
|
||||
- Public -> Private: redistribute existing finals to private destination (fast, ~1-2 min)
|
||||
- Private -> Public: reset styles, regenerate screens, re-render, re-encode (slow, ~15-30 min)
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class VisibilityChangeService:
|
||||
"""Service for changing job visibility after completion."""
|
||||
|
||||
def __init__(self, job_manager: Optional[JobManager] = None):
|
||||
self.job_manager = job_manager or JobManager()
|
||||
|
||||
def validate_change(self, job, user_email: str, is_admin: bool, target_visibility: str) -> Optional[str]:
|
||||
"""Validate a visibility change request. Returns error message or None if valid."""
|
||||
if not job:
|
||||
return "Job not found"
|
||||
|
||||
if job.status != JobStatus.COMPLETE.value and job.status != "complete":
|
||||
return f"Can only change visibility on completed jobs. Current status: {job.status}"
|
||||
|
||||
if getattr(job, 'tenant_id', None):
|
||||
return "Cannot change visibility on tenant jobs"
|
||||
|
||||
current_is_private = getattr(job, 'is_private', False)
|
||||
target_is_private = target_visibility == "private"
|
||||
|
||||
if current_is_private == target_is_private:
|
||||
current = "private" if current_is_private else "public"
|
||||
return f"Job is already {current}"
|
||||
|
||||
# Check user owns the job or is admin
|
||||
if not is_admin and job.user_email != user_email:
|
||||
return "You can only change visibility on your own jobs"
|
||||
|
||||
# Check for in-progress visibility change
|
||||
state_data = job.state_data or {}
|
||||
if state_data.get('visibility_change_in_progress'):
|
||||
return "A visibility change is already in progress for this job"
|
||||
|
||||
return None
|
||||
|
||||
async def change_to_private(self, job_id: str, job, user_email: str) -> dict:
|
||||
"""
|
||||
Change a public job to private (fast path).
|
||||
|
||||
Deletes distributed outputs (YouTube/Dropbox/GDrive) but keeps GCS finals,
|
||||
then redistributes to private destination.
|
||||
"""
|
||||
logger.info(f"[job:{job_id}] Starting visibility change: public -> private (by {user_email})")
|
||||
|
||||
db = self.job_manager.firestore.db
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
|
||||
# Set guard flag
|
||||
job_ref.update({
|
||||
"state_data.visibility_change_in_progress": True,
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
})
|
||||
|
||||
try:
|
||||
# Step 1: Delete distributed outputs (keep GCS finals)
|
||||
await self._delete_distributed_outputs(job_id, job, keep_gcs_finals=True)
|
||||
|
||||
# Step 2: Update job to private
|
||||
job_ref.update({
|
||||
"is_private": True,
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
"timeline": ArrayUnion([{
|
||||
"status": "complete",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"message": f"Visibility changed to private by {user_email}",
|
||||
}]),
|
||||
})
|
||||
|
||||
# Step 3: Trigger redistribution via video worker
|
||||
from backend.workers.video_worker import redistribute_video
|
||||
success = await redistribute_video(job_id)
|
||||
|
||||
if not success:
|
||||
raise RuntimeError("Redistribution failed - check worker logs")
|
||||
|
||||
# Clear guard flag (redistribution updates state_data with new brand_code etc.)
|
||||
job_ref.update({
|
||||
"state_data.visibility_change_in_progress": DELETE_FIELD,
|
||||
})
|
||||
|
||||
logger.info(f"[job:{job_id}] Visibility change to private complete")
|
||||
return {
|
||||
"status": "success",
|
||||
"message": "Job changed to private. Outputs redistributed to private destination.",
|
||||
"reprocessing_required": False,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Visibility change to private failed: {e}", exc_info=True)
|
||||
# Clear guard flag on failure
|
||||
job_ref.update({
|
||||
"state_data.visibility_change_in_progress": DELETE_FIELD,
|
||||
})
|
||||
raise
|
||||
|
||||
async def change_to_public(self, job_id: str, job, user_email: str) -> dict:
|
||||
"""
|
||||
Change a private job to public (slow path).
|
||||
|
||||
Resets custom styles, deletes all outputs/screens/rendered video,
|
||||
and triggers full re-processing from screens worker onward.
|
||||
"""
|
||||
logger.info(f"[job:{job_id}] Starting visibility change: private -> public (by {user_email})")
|
||||
|
||||
db = self.job_manager.firestore.db
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
storage = StorageService()
|
||||
|
||||
# Step 1: Delete distributed outputs + GCS finals
|
||||
await self._delete_distributed_outputs(job_id, job, keep_gcs_finals=False)
|
||||
|
||||
# Step 2: Delete screens and rendered video from GCS
|
||||
for path in [
|
||||
f"jobs/{job_id}/screens/title.mov",
|
||||
f"jobs/{job_id}/screens/title.jpg",
|
||||
f"jobs/{job_id}/screens/title.png",
|
||||
f"jobs/{job_id}/screens/end.mov",
|
||||
f"jobs/{job_id}/screens/end.jpg",
|
||||
f"jobs/{job_id}/screens/end.png",
|
||||
f"jobs/{job_id}/videos/with_vocals.mkv",
|
||||
f"jobs/{job_id}/videos/with_vocals.mov",
|
||||
]:
|
||||
try:
|
||||
storage.delete_file(path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Delete custom style files from GCS
|
||||
try:
|
||||
style_prefix = f"jobs/{job_id}/style/"
|
||||
storage.delete_folder(style_prefix)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Step 3: Prepare nomad theme style files for the job
|
||||
from backend.api.routes.file_upload import _prepare_theme_for_job
|
||||
style_params_path, style_assets_dict, _youtube_desc = _prepare_theme_for_job(
|
||||
job_id=job_id, theme_id="nomad"
|
||||
)
|
||||
|
||||
# Step 4: Reset styles and update job fields
|
||||
# Step 5: Set status to LYRICS_COMPLETE with regen_restore_status
|
||||
# Step 6: Clear progress keys and set guard flag
|
||||
update_payload = {
|
||||
"is_private": False,
|
||||
"theme_id": "nomad",
|
||||
"color_overrides": {},
|
||||
"style_assets": style_assets_dict,
|
||||
"style_params_gcs_path": style_params_path,
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"state_data.visibility_change_in_progress": True,
|
||||
"state_data.regen_restore_status": "review_complete",
|
||||
"state_data.audio_complete": True,
|
||||
"state_data.lyrics_complete": True,
|
||||
"state_data.screens_progress": DELETE_FIELD,
|
||||
"state_data.render_progress": DELETE_FIELD,
|
||||
"state_data.video_progress": DELETE_FIELD,
|
||||
"state_data.encoding_progress": DELETE_FIELD,
|
||||
"outputs_deleted_at": None,
|
||||
"outputs_deleted_by": None,
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
"timeline": ArrayUnion([{
|
||||
"status": "lyrics_complete",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"message": f"Visibility change to public initiated by {user_email}. "
|
||||
"Re-processing from screens generation.",
|
||||
}]),
|
||||
}
|
||||
job_ref.update(update_payload)
|
||||
|
||||
# Step 6: Trigger screens worker
|
||||
from backend.services.worker_service import get_worker_service
|
||||
worker_service = get_worker_service()
|
||||
triggered = await worker_service.trigger_screens_worker(job_id)
|
||||
|
||||
if not triggered:
|
||||
logger.error(f"[job:{job_id}] Failed to trigger screens worker for visibility change")
|
||||
# Restore to complete status on failure
|
||||
job_ref.update({
|
||||
"status": "complete",
|
||||
"is_private": True,
|
||||
"state_data.visibility_change_in_progress": DELETE_FIELD,
|
||||
"state_data.regen_restore_status": DELETE_FIELD,
|
||||
})
|
||||
raise RuntimeError("Failed to trigger screens worker")
|
||||
|
||||
logger.info(f"[job:{job_id}] Visibility change to public initiated, screens worker triggered")
|
||||
return {
|
||||
"status": "processing",
|
||||
"message": "Visibility change to public started. The video will be re-rendered "
|
||||
"with default branding and published publicly. This takes ~15-30 minutes.",
|
||||
"reprocessing_required": True,
|
||||
}
|
||||
|
||||
async def _delete_distributed_outputs(self, job_id: str, job, keep_gcs_finals: bool = False):
|
||||
"""Delete distributed outputs (YouTube, Dropbox, GDrive) and recycle brand code."""
|
||||
import re
|
||||
|
||||
state_data = job.state_data or {}
|
||||
|
||||
# Delete YouTube video
|
||||
youtube_url = state_data.get('youtube_url')
|
||||
if youtube_url:
|
||||
try:
|
||||
video_id_match = re.search(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)', youtube_url)
|
||||
if video_id_match:
|
||||
video_id = video_id_match.group(1)
|
||||
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from backend.services.youtube_service import get_youtube_service
|
||||
youtube_service = get_youtube_service()
|
||||
if youtube_service.is_configured:
|
||||
finalise = KaraokeFinalise(
|
||||
dry_run=False, non_interactive=True,
|
||||
user_youtube_credentials=youtube_service.get_credentials_dict()
|
||||
)
|
||||
finalise.delete_youtube_video(video_id)
|
||||
logger.info(f"[job:{job_id}] Deleted YouTube video {video_id}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to delete YouTube video: {e}")
|
||||
|
||||
# Delete Dropbox folder
|
||||
brand_code = state_data.get('brand_code')
|
||||
dropbox_path = getattr(job, 'dropbox_path', None)
|
||||
if brand_code and dropbox_path:
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
dropbox = get_dropbox_service()
|
||||
if dropbox.is_configured:
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
|
||||
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
|
||||
folder_name = f"{brand_code} - {safe_artist} - {safe_title}"
|
||||
full_path = f"{dropbox_path}/{folder_name}"
|
||||
dropbox.delete_folder(full_path)
|
||||
logger.info(f"[job:{job_id}] Deleted Dropbox folder {full_path}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to delete Dropbox folder: {e}")
|
||||
|
||||
# Delete Google Drive files
|
||||
gdrive_files = state_data.get('gdrive_files')
|
||||
if gdrive_files:
|
||||
try:
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
gdrive = get_gdrive_service()
|
||||
if gdrive.is_configured:
|
||||
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
|
||||
gdrive.delete_files(file_ids)
|
||||
logger.info(f"[job:{job_id}] Deleted Google Drive files")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to delete Google Drive files: {e}")
|
||||
|
||||
# Delete GCS finals if requested
|
||||
if not keep_gcs_finals:
|
||||
try:
|
||||
storage = StorageService()
|
||||
deleted_count = storage.delete_folder(f"jobs/{job_id}/finals/")
|
||||
if deleted_count > 0:
|
||||
logger.info(f"[job:{job_id}] Deleted {deleted_count} GCS finals files")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to delete GCS finals: {e}")
|
||||
|
||||
# Recycle brand code
|
||||
if brand_code:
|
||||
try:
|
||||
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
|
||||
prefix, number = BrandCodeService.parse_brand_code(brand_code)
|
||||
get_brand_code_service().recycle_brand_code(prefix, number)
|
||||
logger.info(f"[job:{job_id}] Recycled brand code {brand_code}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to recycle brand code: {e}")
|
||||
|
||||
# Clear distribution state_data
|
||||
db = self.job_manager.firestore.db
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
update = {}
|
||||
for key in ['youtube_url', 'brand_code', 'dropbox_link', 'gdrive_files']:
|
||||
if key in state_data:
|
||||
update[f"state_data.{key}"] = DELETE_FIELD
|
||||
if update:
|
||||
job_ref.update(update)
|
||||
@@ -0,0 +1,489 @@
|
||||
"""
|
||||
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
|
||||
|
||||
|
||||
# --- 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"
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,369 @@
|
||||
"""
|
||||
Tests for the visibility change service.
|
||||
|
||||
Tests validation logic and the two visibility change flows:
|
||||
- Public -> Private (fast redistribution)
|
||||
- Private -> Public (full re-processing)
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, AsyncMock, patch
|
||||
from types import SimpleNamespace
|
||||
|
||||
from backend.services.visibility_change_service import VisibilityChangeService
|
||||
|
||||
|
||||
def _make_job(
|
||||
job_id="test-123",
|
||||
status="complete",
|
||||
is_private=False,
|
||||
tenant_id="",
|
||||
user_email="user@example.com",
|
||||
state_data=None,
|
||||
):
|
||||
"""Create a mock job object for testing."""
|
||||
return SimpleNamespace(
|
||||
job_id=job_id,
|
||||
status=status,
|
||||
is_private=is_private,
|
||||
tenant_id=tenant_id,
|
||||
user_email=user_email,
|
||||
state_data=state_data or {},
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
outputs_deleted_at=None,
|
||||
dropbox_path="/Tracks-Organized",
|
||||
file_urls={"finals": {"lossy_4k_mp4": "gs://test/4k.mp4"}},
|
||||
)
|
||||
|
||||
|
||||
class TestValidation:
|
||||
"""Test validation logic for visibility changes."""
|
||||
|
||||
def setup_method(self):
|
||||
self.service = VisibilityChangeService(job_manager=MagicMock())
|
||||
|
||||
def test_validates_job_exists(self):
|
||||
error = self.service.validate_change(None, "user@example.com", False, "private")
|
||||
assert error == "Job not found"
|
||||
|
||||
def test_validates_complete_status(self):
|
||||
job = _make_job(status="generating_video")
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert "completed jobs" in error
|
||||
|
||||
def test_validates_not_tenant_job(self):
|
||||
job = _make_job(tenant_id="vocalstar")
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert "tenant" in error
|
||||
|
||||
def test_validates_different_visibility(self):
|
||||
job = _make_job(is_private=True)
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert "already private" in error
|
||||
|
||||
def test_validates_same_visibility_public(self):
|
||||
job = _make_job(is_private=False)
|
||||
error = self.service.validate_change(job, "user@example.com", False, "public")
|
||||
assert "already public" in error
|
||||
|
||||
def test_validates_ownership(self):
|
||||
job = _make_job(user_email="owner@example.com")
|
||||
error = self.service.validate_change(job, "other@example.com", False, "private")
|
||||
assert "your own jobs" in error
|
||||
|
||||
def test_admin_can_change_any_job(self):
|
||||
job = _make_job(user_email="owner@example.com")
|
||||
error = self.service.validate_change(job, "admin@example.com", True, "private")
|
||||
assert error is None
|
||||
|
||||
def test_owner_can_change_own_job(self):
|
||||
job = _make_job(user_email="user@example.com")
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert error is None
|
||||
|
||||
def test_validates_no_concurrent_change(self):
|
||||
job = _make_job(state_data={"visibility_change_in_progress": True})
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert "already in progress" in error
|
||||
|
||||
def test_valid_public_to_private(self):
|
||||
job = _make_job(is_private=False)
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert error is None
|
||||
|
||||
def test_valid_private_to_public(self):
|
||||
job = _make_job(is_private=True)
|
||||
error = self.service.validate_change(job, "user@example.com", False, "public")
|
||||
assert error is None
|
||||
|
||||
|
||||
class TestChangeToPrivate:
|
||||
"""Test public -> private visibility change."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_calls_redistribute(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=False, state_data={
|
||||
"youtube_url": "https://youtube.com/watch?v=abc",
|
||||
"brand_code": "NOMAD-0001",
|
||||
"dropbox_link": "https://dropbox.com/test",
|
||||
})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock) as mock_delete, \
|
||||
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=True) as mock_redist:
|
||||
|
||||
result = await service.change_to_private("test-123", job, "user@example.com")
|
||||
|
||||
assert result["status"] == "success"
|
||||
assert result["reprocessing_required"] is False
|
||||
mock_delete.assert_called_once_with("test-123", job, keep_gcs_finals=True)
|
||||
mock_redist.assert_called_once_with("test-123")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sets_is_private_true(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=False, state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=True):
|
||||
|
||||
await service.change_to_private("test-123", job, "user@example.com")
|
||||
|
||||
# Check that is_private was set to True in one of the update calls
|
||||
update_calls = mock_job_ref.update.call_args_list
|
||||
found_private_update = any(
|
||||
call.args[0].get("is_private") is True
|
||||
for call in update_calls
|
||||
)
|
||||
assert found_private_update
|
||||
|
||||
|
||||
class TestChangeToPublic:
|
||||
"""Test private -> public visibility change."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_triggers_screens_worker(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=True, state_data={
|
||||
"brand_code": "NOMADNP-0001",
|
||||
"dropbox_link": "https://dropbox.com/test",
|
||||
})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
|
||||
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {"bg": "bg.png"}, None)) as mock_theme, \
|
||||
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
|
||||
|
||||
mock_storage = MagicMock()
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
mock_worker = MagicMock()
|
||||
mock_worker.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
mock_worker_svc.return_value = mock_worker
|
||||
|
||||
result = await service.change_to_public("test-123", job, "user@example.com")
|
||||
|
||||
assert result["status"] == "processing"
|
||||
assert result["reprocessing_required"] is True
|
||||
mock_worker.trigger_screens_worker.assert_called_once_with("test-123")
|
||||
mock_theme.assert_called_once_with(job_id="test-123", theme_id="nomad")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resets_styles_to_nomad_theme(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=True, state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
|
||||
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {"bg": "bg.png"}, None)), \
|
||||
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
|
||||
|
||||
mock_storage_cls.return_value = MagicMock()
|
||||
mock_worker = MagicMock()
|
||||
mock_worker.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
mock_worker_svc.return_value = mock_worker
|
||||
|
||||
await service.change_to_public("test-123", job, "user@example.com")
|
||||
|
||||
# Verify the update payload resets styles
|
||||
update_calls = mock_job_ref.update.call_args_list
|
||||
# Find the main update call (the one with theme_id)
|
||||
style_update = None
|
||||
for call in update_calls:
|
||||
payload = call.args[0]
|
||||
if "theme_id" in payload:
|
||||
style_update = payload
|
||||
break
|
||||
|
||||
assert style_update is not None
|
||||
assert style_update["theme_id"] == "nomad"
|
||||
assert style_update["color_overrides"] == {}
|
||||
assert style_update["style_assets"] == {"bg": "bg.png"}
|
||||
assert style_update["style_params_gcs_path"] == "jobs/test-123/style/style_params.json"
|
||||
assert style_update["is_private"] is False
|
||||
assert style_update["status"] == "lyrics_complete"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rollback_on_worker_failure(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=True, state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
|
||||
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {}, None)), \
|
||||
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
|
||||
|
||||
mock_storage_cls.return_value = MagicMock()
|
||||
mock_worker = MagicMock()
|
||||
mock_worker.trigger_screens_worker = AsyncMock(return_value=False)
|
||||
mock_worker_svc.return_value = mock_worker
|
||||
|
||||
with pytest.raises(RuntimeError, match="Failed to trigger screens worker"):
|
||||
await service.change_to_public("test-123", job, "user@example.com")
|
||||
|
||||
# Verify rollback was attempted
|
||||
rollback_call = mock_job_ref.update.call_args_list[-1]
|
||||
payload = rollback_call.args[0]
|
||||
assert payload["status"] == "complete"
|
||||
assert payload["is_private"] is True
|
||||
|
||||
|
||||
class TestChangeToPrivateErrors:
|
||||
"""Test error handling in public -> private flow."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rollback_on_redistribute_failure(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=False, state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=False):
|
||||
|
||||
with pytest.raises(RuntimeError, match="Redistribution failed"):
|
||||
await service.change_to_private("test-123", job, "user@example.com")
|
||||
|
||||
# Guard flag should be cleared on failure (DELETE_FIELD sentinel)
|
||||
last_update = mock_job_ref.update.call_args_list[-1]
|
||||
val = last_update.args[0].get("state_data.visibility_change_in_progress")
|
||||
assert "delete" in str(type(val)).lower() or "sentinel" in str(val).lower()
|
||||
|
||||
|
||||
class TestDeleteDistributedOutputs:
|
||||
"""Test cleanup of distributed outputs."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_recycles_brand_code(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(state_data={"brand_code": "NOMAD-0042"})
|
||||
|
||||
with patch("backend.services.brand_code_service.get_brand_code_service") as mock_bcs, \
|
||||
patch("backend.services.brand_code_service.BrandCodeService.parse_brand_code", return_value=("NOMAD", 42)):
|
||||
mock_brand_svc = MagicMock()
|
||||
mock_bcs.return_value = mock_brand_svc
|
||||
|
||||
await service._delete_distributed_outputs("test-123", job, keep_gcs_finals=True)
|
||||
|
||||
mock_brand_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_clears_distribution_state_keys(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(state_data={
|
||||
"youtube_url": "https://youtube.com/watch?v=abc",
|
||||
"brand_code": "NOMAD-0001",
|
||||
"dropbox_link": "https://dropbox.com/test",
|
||||
})
|
||||
|
||||
with patch("backend.services.brand_code_service.get_brand_code_service") as mock_bcs, \
|
||||
patch("backend.services.brand_code_service.BrandCodeService.parse_brand_code", return_value=("NOMAD", 1)):
|
||||
mock_bcs.return_value = MagicMock()
|
||||
|
||||
# Patch YouTube deletion to avoid real service calls
|
||||
with patch("backend.services.youtube_service.get_youtube_service") as mock_yt, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service") as mock_dbx:
|
||||
mock_yt.return_value = MagicMock(is_configured=False)
|
||||
mock_dbx.return_value = MagicMock(is_configured=False)
|
||||
|
||||
await service._delete_distributed_outputs("test-123", job, keep_gcs_finals=True)
|
||||
|
||||
update_call = mock_job_ref.update.call_args
|
||||
payload = update_call.args[0]
|
||||
# Verify keys are set to DELETE_FIELD sentinel
|
||||
for key in ["state_data.youtube_url", "state_data.brand_code", "state_data.dropbox_link"]:
|
||||
assert key in payload, f"Expected {key} in update payload"
|
||||
assert "sentinel" in str(payload[key]).lower() or "delete" in str(type(payload[key])).lower()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_deletes_gcs_finals_when_not_kept(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls:
|
||||
mock_storage = MagicMock()
|
||||
mock_storage.delete_folder.return_value = 3
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
|
||||
await service._delete_distributed_outputs("test-123", job, keep_gcs_finals=False)
|
||||
|
||||
mock_storage.delete_folder.assert_called_once_with("jobs/test-123/finals/")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skips_gcs_finals_deletion_when_kept(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls:
|
||||
mock_storage = MagicMock()
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
|
||||
await service._delete_distributed_outputs("test-123", job, keep_gcs_finals=True)
|
||||
|
||||
mock_storage.delete_folder.assert_not_called()
|
||||
|
||||
|
||||
class TestStateTransitions:
|
||||
"""Test that the COMPLETE -> LYRICS_COMPLETE state transition is valid."""
|
||||
|
||||
def test_complete_allows_lyrics_complete_transition(self):
|
||||
from backend.models.job import STATE_TRANSITIONS, JobStatus
|
||||
allowed = STATE_TRANSITIONS[JobStatus.COMPLETE]
|
||||
assert JobStatus.LYRICS_COMPLETE in allowed
|
||||
@@ -0,0 +1,251 @@
|
||||
"""
|
||||
Unit tests for the edit completed track endpoint.
|
||||
|
||||
Tests POST /api/jobs/{job_id}/edit which allows users to reopen
|
||||
completed tracks for editing (lyrics, instrumental, metadata).
|
||||
"""
|
||||
import pytest
|
||||
from datetime import datetime, UTC
|
||||
from unittest.mock import MagicMock, AsyncMock, patch, Mock
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def complete_job():
|
||||
"""A completed job with distribution data."""
|
||||
return Job(
|
||||
job_id="test-edit-123",
|
||||
status="complete",
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
user_email="user@example.com",
|
||||
dropbox_path="/Karaoke/Organized",
|
||||
edit_count=0,
|
||||
state_data={
|
||||
"youtube_url": "https://youtu.be/abc123",
|
||||
"brand_code": "NOMAD-1234",
|
||||
"dropbox_link": "https://dropbox.com/...",
|
||||
"gdrive_files": {"mp4": "file_id_1", "mp4_720p": "file_id_2"},
|
||||
"audio_complete": True,
|
||||
"lyrics_complete": True,
|
||||
"render_progress": {"stage": "complete"},
|
||||
"video_progress": {"stage": "complete"},
|
||||
"encoding_progress": {"stage": "complete"},
|
||||
"review_complete": True,
|
||||
"corrected_lyrics": {"segments": []},
|
||||
"instrumental_selection": "clean",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager(complete_job):
|
||||
"""Mock JobManager with common methods."""
|
||||
manager = MagicMock()
|
||||
manager.get_job.return_value = complete_job
|
||||
manager.transition_to_state.return_value = True
|
||||
return manager
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_worker_service():
|
||||
"""Mock WorkerService."""
|
||||
service = MagicMock()
|
||||
service.trigger_audio_worker = AsyncMock(return_value=True)
|
||||
service.trigger_lyrics_worker = AsyncMock(return_value=True)
|
||||
service.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
service.trigger_video_worker = AsyncMock(return_value=True)
|
||||
service.trigger_render_video_worker = AsyncMock(return_value=True)
|
||||
return service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(mock_job_manager, mock_worker_service):
|
||||
"""Create TestClient with mocked dependencies."""
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = "nomad"
|
||||
|
||||
def mock_job_manager_factory(*args, **kwargs):
|
||||
return mock_job_manager
|
||||
|
||||
# After edit, return updated job with review token
|
||||
updated_job = Job(
|
||||
job_id="test-edit-123",
|
||||
status="awaiting_review",
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
user_email="user@example.com",
|
||||
review_token="test-review-token-abc",
|
||||
edit_count=1,
|
||||
)
|
||||
|
||||
def get_job_side_effect(job_id):
|
||||
# First call returns complete job, second returns updated job
|
||||
if mock_job_manager.get_job.call_count <= 1:
|
||||
return mock_job_manager.get_job.return_value
|
||||
return updated_job
|
||||
|
||||
mock_job_manager.get_job.side_effect = get_job_side_effect
|
||||
|
||||
with patch('backend.api.routes.jobs.job_manager', mock_job_manager), \
|
||||
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
|
||||
patch('backend.api.routes.jobs.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.api.routes.jobs.StorageService') as mock_storage_cls, \
|
||||
patch('backend.api.routes.jobs.FirestoreService') as mock_fs_cls, \
|
||||
patch('backend.services.job_manager.JobManager', mock_job_manager_factory), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')):
|
||||
mock_storage_cls.return_value.delete_folder.return_value = 3
|
||||
from backend.main import app
|
||||
from fastapi.testclient import TestClient
|
||||
yield TestClient(app)
|
||||
|
||||
|
||||
class TestEditCompletedTrackSuccess:
|
||||
"""Tests for successful edit initiation."""
|
||||
|
||||
def test_edit_returns_200(self, client, auth_headers):
|
||||
"""Edit a completed job returns 200."""
|
||||
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_edit_returns_review_url(self, client, auth_headers):
|
||||
"""Response includes review URL."""
|
||||
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
|
||||
data = response.json()
|
||||
assert "review_url" in data
|
||||
assert "test-edit-123" in data["review_url"]
|
||||
assert "review" in data["review_url"]
|
||||
|
||||
def test_edit_returns_review_token(self, client, auth_headers):
|
||||
"""Response includes review token."""
|
||||
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
|
||||
data = response.json()
|
||||
assert data["review_token"] == "test-review-token-abc"
|
||||
|
||||
def test_edit_transitions_to_awaiting_review(self, client, mock_job_manager, auth_headers):
|
||||
"""Job state transitions to AWAITING_REVIEW."""
|
||||
client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
|
||||
mock_job_manager.transition_to_state.assert_called_once_with(
|
||||
"test-edit-123",
|
||||
JobStatus.AWAITING_REVIEW,
|
||||
progress=60,
|
||||
message="Track reopened for editing",
|
||||
)
|
||||
|
||||
def test_edit_without_metadata_change(self, client, auth_headers):
|
||||
"""Edit without metadata returns metadata_updated=false."""
|
||||
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
|
||||
data = response.json()
|
||||
assert data["metadata_updated"] is False
|
||||
|
||||
def test_edit_does_not_trigger_screens_without_metadata(self, client, mock_worker_service, auth_headers):
|
||||
"""Screens worker not triggered when metadata unchanged."""
|
||||
client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
|
||||
mock_worker_service.trigger_screens_worker.assert_not_called()
|
||||
|
||||
|
||||
class TestEditWithMetadataUpdate:
|
||||
"""Tests for editing with artist/title changes."""
|
||||
|
||||
def test_edit_with_artist_change(self, client, auth_headers):
|
||||
"""Edit with new artist returns metadata_updated=true."""
|
||||
response = client.post(
|
||||
"/api/jobs/test-edit-123/edit",
|
||||
headers=auth_headers,
|
||||
json={"artist": "New Artist"},
|
||||
)
|
||||
data = response.json()
|
||||
assert data["metadata_updated"] is True
|
||||
|
||||
def test_edit_with_title_change(self, client, auth_headers):
|
||||
"""Edit with new title returns metadata_updated=true."""
|
||||
response = client.post(
|
||||
"/api/jobs/test-edit-123/edit",
|
||||
headers=auth_headers,
|
||||
json={"title": "New Song Title"},
|
||||
)
|
||||
data = response.json()
|
||||
assert data["metadata_updated"] is True
|
||||
|
||||
def test_edit_with_same_artist_no_metadata_update(self, client, auth_headers):
|
||||
"""Edit with same artist does not flag metadata_updated."""
|
||||
response = client.post(
|
||||
"/api/jobs/test-edit-123/edit",
|
||||
headers=auth_headers,
|
||||
json={"artist": "Test Artist"},
|
||||
)
|
||||
data = response.json()
|
||||
assert data["metadata_updated"] is False
|
||||
|
||||
def test_edit_triggers_screens_on_metadata_change(self, client, mock_worker_service, auth_headers):
|
||||
"""Screens worker triggered when metadata changes."""
|
||||
client.post(
|
||||
"/api/jobs/test-edit-123/edit",
|
||||
headers=auth_headers,
|
||||
json={"artist": "New Artist"},
|
||||
)
|
||||
mock_worker_service.trigger_screens_worker.assert_called_once_with("test-edit-123")
|
||||
|
||||
|
||||
class TestEditValidation:
|
||||
"""Tests for validation and error cases."""
|
||||
|
||||
def test_edit_non_complete_job_returns_400(self, client, mock_job_manager, auth_headers):
|
||||
"""Cannot edit a job that isn't complete."""
|
||||
pending_job = Job(
|
||||
job_id="test-pending",
|
||||
status="pending",
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
)
|
||||
mock_job_manager.get_job.side_effect = None
|
||||
mock_job_manager.get_job.return_value = pending_job
|
||||
|
||||
response = client.post("/api/jobs/test-pending/edit", headers=auth_headers, json={})
|
||||
assert response.status_code == 400
|
||||
assert "completed" in response.json()["detail"].lower() or "complete" in response.json()["detail"].lower()
|
||||
|
||||
def test_edit_already_deleted_outputs_returns_400(self, client, mock_job_manager, auth_headers):
|
||||
"""Cannot edit a job whose outputs are already deleted."""
|
||||
deleted_job = Job(
|
||||
job_id="test-deleted",
|
||||
status="complete",
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
outputs_deleted_at=datetime.now(UTC),
|
||||
)
|
||||
mock_job_manager.get_job.side_effect = None
|
||||
mock_job_manager.get_job.return_value = deleted_job
|
||||
|
||||
response = client.post("/api/jobs/test-deleted/edit", headers=auth_headers, json={})
|
||||
assert response.status_code == 400
|
||||
assert "already" in response.json()["detail"].lower()
|
||||
|
||||
def test_edit_nonexistent_job_returns_404(self, client, mock_job_manager, auth_headers):
|
||||
"""Cannot edit a job that doesn't exist."""
|
||||
mock_job_manager.get_job.side_effect = None
|
||||
mock_job_manager.get_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/nonexistent/edit", headers=auth_headers, json={})
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
class TestEditCleanup:
|
||||
"""Tests for output cleanup during edit."""
|
||||
|
||||
def test_cleanup_results_in_response(self, client, auth_headers):
|
||||
"""Response includes cleanup results."""
|
||||
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
|
||||
data = response.json()
|
||||
assert "cleanup_results" in data
|
||||
assert "gcs_finals" in data["cleanup_results"]
|
||||
@@ -0,0 +1,132 @@
|
||||
"""
|
||||
Tests for job observability improvements.
|
||||
|
||||
Covers:
|
||||
- TimelineEvent metadata field
|
||||
- log_to_job helper function
|
||||
- Timeline metadata in state transitions
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from backend.models.job import TimelineEvent
|
||||
|
||||
|
||||
class TestTimelineEventMetadata:
|
||||
"""Tests for the metadata field on TimelineEvent."""
|
||||
|
||||
def test_timeline_event_without_metadata(self):
|
||||
"""Existing events without metadata still work."""
|
||||
event = TimelineEvent(
|
||||
status="complete",
|
||||
timestamp="2026-03-07T12:00:00",
|
||||
progress=100,
|
||||
message="Done!",
|
||||
)
|
||||
data = event.model_dump(mode='json')
|
||||
assert data["status"] == "complete"
|
||||
assert data["metadata"] is None
|
||||
|
||||
def test_timeline_event_with_metadata(self):
|
||||
"""Events can include structured metadata."""
|
||||
metadata = {
|
||||
"action": "completed",
|
||||
"brand_code": "NOMAD-1234",
|
||||
"youtube_url": "https://youtube.com/watch?v=abc123",
|
||||
"gdrive_file_ids": {"mp4": "file1", "cdg": "file2"},
|
||||
}
|
||||
event = TimelineEvent(
|
||||
status="complete",
|
||||
timestamp="2026-03-07T12:00:00",
|
||||
progress=100,
|
||||
message="Karaoke generation complete!",
|
||||
metadata=metadata,
|
||||
)
|
||||
data = event.model_dump(mode='json')
|
||||
assert data["metadata"]["brand_code"] == "NOMAD-1234"
|
||||
assert data["metadata"]["youtube_url"] == "https://youtube.com/watch?v=abc123"
|
||||
assert data["metadata"]["gdrive_file_ids"]["mp4"] == "file1"
|
||||
|
||||
def test_timeline_event_with_edit_metadata(self):
|
||||
"""Edit-initiated events include previous outputs and cleanup results."""
|
||||
metadata = {
|
||||
"action": "edit_initiated",
|
||||
"initiated_by": "user@example.com",
|
||||
"edit_number": 1,
|
||||
"previous_outputs": {
|
||||
"youtube_url": "https://youtube.com/watch?v=old123",
|
||||
"brand_code": "NOMAD-0042",
|
||||
"dropbox_link": "https://dropbox.com/sh/old",
|
||||
},
|
||||
"cleanup_results": {
|
||||
"youtube": {"status": "success", "video_id": "old123"},
|
||||
"dropbox": {"status": "success", "path": "/Karaoke/NOMAD-0042"},
|
||||
"gdrive": {"status": "skipped", "reason": "no gdrive_files"},
|
||||
},
|
||||
}
|
||||
event = TimelineEvent(
|
||||
status="complete",
|
||||
timestamp="2026-03-07T12:00:00",
|
||||
message="Track edit initiated by user@example.com (edit #1)",
|
||||
metadata=metadata,
|
||||
)
|
||||
data = event.model_dump(mode='json')
|
||||
assert data["metadata"]["previous_outputs"]["youtube_url"] == "https://youtube.com/watch?v=old123"
|
||||
assert data["metadata"]["cleanup_results"]["youtube"]["status"] == "success"
|
||||
|
||||
def test_timeline_event_metadata_roundtrip(self):
|
||||
"""Metadata survives serialization/deserialization."""
|
||||
metadata = {"brand_code": "NOMAD-1234", "nested": {"key": "value"}}
|
||||
event = TimelineEvent(
|
||||
status="complete",
|
||||
timestamp="2026-03-07T12:00:00",
|
||||
metadata=metadata,
|
||||
)
|
||||
data = event.model_dump(mode='json')
|
||||
restored = TimelineEvent(**data)
|
||||
assert restored.metadata == metadata
|
||||
|
||||
|
||||
class TestLogToJob:
|
||||
"""Tests for the log_to_job helper function."""
|
||||
|
||||
@patch('backend.services.firestore_service._get_log_service')
|
||||
def test_log_to_job_writes_to_subcollection(self, mock_get_service):
|
||||
"""log_to_job creates a WorkerLogEntry and writes to Firestore."""
|
||||
mock_service = MagicMock()
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
from backend.services.firestore_service import log_to_job
|
||||
log_to_job("job123", "edit", "INFO", "Edit started", {"key": "value"})
|
||||
|
||||
mock_service.append_log_to_subcollection.assert_called_once()
|
||||
call_args = mock_service.append_log_to_subcollection.call_args
|
||||
assert call_args[0][0] == "job123"
|
||||
entry = call_args[0][1]
|
||||
assert entry.worker == "edit"
|
||||
assert entry.level == "INFO"
|
||||
assert entry.message == "Edit started"
|
||||
assert entry.metadata == {"key": "value"}
|
||||
|
||||
@patch('backend.services.firestore_service._get_log_service')
|
||||
def test_log_to_job_suppresses_errors(self, mock_get_service):
|
||||
"""log_to_job should never raise — logging failures must be silent."""
|
||||
mock_get_service.side_effect = Exception("Firestore down")
|
||||
|
||||
from backend.services.firestore_service import log_to_job
|
||||
# Should not raise
|
||||
log_to_job("job123", "edit", "INFO", "Edit started")
|
||||
|
||||
@patch('backend.services.firestore_service._get_log_service')
|
||||
def test_log_to_job_without_metadata(self, mock_get_service):
|
||||
"""log_to_job works without metadata."""
|
||||
mock_service = MagicMock()
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
from backend.services.firestore_service import log_to_job
|
||||
log_to_job("job123", "admin", "WARNING", "Something happened")
|
||||
|
||||
mock_service.append_log_to_subcollection.assert_called_once()
|
||||
entry = mock_service.append_log_to_subcollection.call_args[0][1]
|
||||
assert entry.metadata is None
|
||||
@@ -85,6 +85,50 @@ class TestJobModelIsPrivate:
|
||||
|
||||
assert job.is_private is False
|
||||
|
||||
def test_create_job_stores_creation_params(self):
|
||||
"""JobManager.create_job should store creation_params for observability."""
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
manager = JobManager()
|
||||
manager.firestore = Mock()
|
||||
manager.firestore.create_job = Mock()
|
||||
|
||||
job_create = JobCreate(
|
||||
artist="Test",
|
||||
title="Song",
|
||||
theme_id="nomad",
|
||||
is_private=True,
|
||||
request_metadata={"created_from": "guided_flow"},
|
||||
)
|
||||
|
||||
job = manager.create_job(job_create, is_admin=False)
|
||||
|
||||
assert job.creation_params == {
|
||||
"is_private": True,
|
||||
"is_admin": False,
|
||||
"created_from": "guided_flow",
|
||||
}
|
||||
|
||||
def test_creation_params_defaults_created_from_unknown(self):
|
||||
"""creation_params should default created_from to 'unknown' when not in metadata."""
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
manager = JobManager()
|
||||
manager.firestore = Mock()
|
||||
manager.firestore.create_job = Mock()
|
||||
|
||||
job_create = JobCreate(
|
||||
artist="Test",
|
||||
title="Song",
|
||||
theme_id="nomad",
|
||||
)
|
||||
|
||||
job = manager.create_job(job_create, is_admin=True)
|
||||
|
||||
assert job.creation_params["created_from"] == "unknown"
|
||||
assert job.creation_params["is_private"] is False
|
||||
assert job.creation_params["is_admin"] is True
|
||||
|
||||
|
||||
class TestGetEffectiveDistributionForJob:
|
||||
"""Tests for get_effective_distribution_for_job() helper."""
|
||||
|
||||
@@ -772,7 +772,7 @@ class TestNotificationFormatting:
|
||||
assert payload["title"] == "Review Lyrics"
|
||||
assert "Test Song" in payload["body"]
|
||||
assert "Test Artist" in payload["body"]
|
||||
assert "/review/test-job-123" in payload["url"]
|
||||
assert "/app/jobs#/test-job-123/review" in payload["url"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_blocking_notification_instrumental(self, push_service):
|
||||
@@ -802,7 +802,7 @@ class TestNotificationFormatting:
|
||||
import json
|
||||
payload = json.loads(call_args[1]["data"])
|
||||
assert payload["title"] == "Select Instrumental"
|
||||
assert "/instrumental/test-job-123" in payload["url"]
|
||||
assert "/app/jobs#/test-job-123/instrumental" in payload["url"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_completion_notification(self, push_service):
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
"""
|
||||
Unit tests for review session backup/restore feature.
|
||||
|
||||
Tests the ReviewSession model, Firestore CRUD methods, and API endpoints.
|
||||
"""
|
||||
import pytest
|
||||
import json
|
||||
import hashlib
|
||||
from datetime import datetime, timezone
|
||||
from unittest.mock import patch, MagicMock, AsyncMock
|
||||
|
||||
from backend.models.review_session import ReviewSession, ReviewSessionSummary
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def ensure_auth_overrides():
|
||||
"""Ensure auth dependency overrides are set for endpoint tests.
|
||||
|
||||
The global conftest autouse fixture should handle this, but some tests
|
||||
in the broader suite can leave dependency_overrides in a dirty state.
|
||||
This fixture ensures a clean slate for review session endpoint tests.
|
||||
"""
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_auth, require_review_auth
|
||||
|
||||
async def mock_require_auth():
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Test admin token",
|
||||
is_admin=True,
|
||||
user_email="test@example.com",
|
||||
)
|
||||
|
||||
async def mock_require_review_auth(job_id: str = "test123"):
|
||||
return (job_id, "full")
|
||||
|
||||
app.dependency_overrides[require_auth] = mock_require_auth
|
||||
app.dependency_overrides[require_review_auth] = mock_require_review_auth
|
||||
yield
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
app.dependency_overrides.pop(require_review_auth, None)
|
||||
|
||||
|
||||
# ============================================
|
||||
# Model Tests
|
||||
# ============================================
|
||||
|
||||
|
||||
class TestReviewSessionSummary:
|
||||
def test_to_dict(self):
|
||||
summary = ReviewSessionSummary(
|
||||
total_segments=10,
|
||||
total_words=100,
|
||||
corrections_made=5,
|
||||
changed_words=[{"original": "hello", "corrected": "hallo", "segment_index": 0}],
|
||||
)
|
||||
d = summary.to_dict()
|
||||
assert d["total_segments"] == 10
|
||||
assert d["corrections_made"] == 5
|
||||
assert len(d["changed_words"]) == 1
|
||||
|
||||
def test_from_dict(self):
|
||||
data = {
|
||||
"total_segments": 15,
|
||||
"total_words": 200,
|
||||
"corrections_made": 8,
|
||||
"changed_words": [],
|
||||
}
|
||||
summary = ReviewSessionSummary.from_dict(data)
|
||||
assert summary.total_segments == 15
|
||||
assert summary.corrections_made == 8
|
||||
|
||||
def test_from_dict_missing_fields(self):
|
||||
summary = ReviewSessionSummary.from_dict({})
|
||||
assert summary.total_segments == 0
|
||||
assert summary.changed_words == []
|
||||
|
||||
|
||||
class TestReviewSession:
|
||||
def test_to_dict_and_from_dict_roundtrip(self):
|
||||
session = ReviewSession(
|
||||
session_id="test-session-1",
|
||||
job_id="job-123",
|
||||
user_email="user@example.com",
|
||||
edit_count=42,
|
||||
trigger="preview",
|
||||
audio_duration_seconds=222.5,
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
data_hash="abc123hash",
|
||||
correction_data_gcs_path="jobs/job-123/review_sessions/test-session-1.json",
|
||||
summary=ReviewSessionSummary(total_segments=10, total_words=100, corrections_made=5),
|
||||
)
|
||||
d = session.to_dict()
|
||||
restored = ReviewSession.from_dict(d)
|
||||
|
||||
assert restored.session_id == "test-session-1"
|
||||
assert restored.job_id == "job-123"
|
||||
assert restored.edit_count == 42
|
||||
assert restored.trigger == "preview"
|
||||
assert restored.audio_duration_seconds == 222.5
|
||||
assert restored.artist == "Test Artist"
|
||||
assert restored.data_hash == "abc123hash"
|
||||
assert restored.summary.total_segments == 10
|
||||
|
||||
def test_from_dict_string_timestamps(self):
|
||||
data = {
|
||||
"session_id": "s1",
|
||||
"created_at": "2026-03-07T12:00:00Z",
|
||||
"updated_at": "2026-03-07T12:15:00Z",
|
||||
}
|
||||
session = ReviewSession.from_dict(data)
|
||||
assert session.created_at.year == 2026
|
||||
assert session.updated_at.minute == 15
|
||||
|
||||
def test_default_values(self):
|
||||
session = ReviewSession()
|
||||
assert session.trigger == "auto"
|
||||
assert session.edit_count == 0
|
||||
assert session.audio_duration_seconds is None
|
||||
assert session.session_id # auto-generated
|
||||
|
||||
|
||||
# ============================================
|
||||
# API Endpoint Tests
|
||||
# ============================================
|
||||
|
||||
|
||||
class TestSaveReviewSessionEndpoint:
|
||||
"""Tests for POST /api/review/{job_id}/sessions"""
|
||||
|
||||
@patch("backend.api.routes.review.StorageService")
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
@patch("backend.api.routes.review.JobManager")
|
||||
def test_save_session_success(self, MockJobManager, MockFirestore, MockStorage, test_client):
|
||||
mock_job = MagicMock(spec=Job)
|
||||
mock_job.artist = "Test Artist"
|
||||
mock_job.title = "Test Song"
|
||||
mock_job.state_data = {"backing_vocals_analysis": {"total_duration_seconds": 180.0}}
|
||||
|
||||
MockJobManager.return_value.get_job.return_value = mock_job
|
||||
MockFirestore.return_value.get_latest_review_session_hash.return_value = None
|
||||
MockStorage.return_value.upload_json.return_value = None
|
||||
MockFirestore.return_value.save_review_session.return_value = "session-id"
|
||||
|
||||
response = test_client.post(
|
||||
"/api/review/job-123/sessions",
|
||||
json={
|
||||
"correction_data": {"corrected_segments": [], "original_segments": []},
|
||||
"edit_count": 5,
|
||||
"trigger": "manual",
|
||||
"summary": {"total_segments": 10, "total_words": 100, "corrections_made": 5},
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "saved"
|
||||
assert "session_id" in data
|
||||
|
||||
@patch("backend.api.routes.review.StorageService")
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
@patch("backend.api.routes.review.JobManager")
|
||||
def test_save_session_deduplication(self, MockJobManager, MockFirestore, MockStorage, test_client):
|
||||
"""Should skip save if data hash matches latest session."""
|
||||
mock_job = MagicMock(spec=Job)
|
||||
mock_job.artist = "Test Artist"
|
||||
mock_job.title = "Test Song"
|
||||
mock_job.state_data = {}
|
||||
|
||||
correction_data = {"corrected_segments": [{"text": "hello"}], "original_segments": []}
|
||||
data_json = json.dumps(correction_data, sort_keys=True, default=str)
|
||||
expected_hash = hashlib.sha256(data_json.encode()).hexdigest()
|
||||
|
||||
MockJobManager.return_value.get_job.return_value = mock_job
|
||||
MockFirestore.return_value.get_latest_review_session_hash.return_value = expected_hash
|
||||
|
||||
response = test_client.post(
|
||||
"/api/review/job-123/sessions",
|
||||
json={"correction_data": correction_data, "edit_count": 5, "trigger": "auto"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "skipped"
|
||||
assert response.json()["reason"] == "identical_data"
|
||||
# GCS upload should NOT have been called
|
||||
MockStorage.return_value.upload_json.assert_not_called()
|
||||
|
||||
@patch("backend.api.routes.review.JobManager")
|
||||
def test_save_session_job_not_found(self, MockJobManager, test_client):
|
||||
MockJobManager.return_value.get_job.return_value = None
|
||||
response = test_client.post(
|
||||
"/api/review/job-123/sessions",
|
||||
json={"correction_data": {"foo": "bar"}, "edit_count": 1},
|
||||
)
|
||||
assert response.status_code == 404
|
||||
|
||||
@patch("backend.api.routes.review.JobManager")
|
||||
def test_save_session_missing_correction_data(self, MockJobManager, test_client):
|
||||
mock_job = MagicMock(spec=Job)
|
||||
MockJobManager.return_value.get_job.return_value = mock_job
|
||||
response = test_client.post(
|
||||
"/api/review/job-123/sessions",
|
||||
json={"edit_count": 1},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
class TestListReviewSessionsEndpoint:
|
||||
"""Tests for GET /api/review/{job_id}/sessions"""
|
||||
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
def test_list_sessions(self, MockFirestore, test_client):
|
||||
session = ReviewSession(
|
||||
session_id="s1",
|
||||
job_id="job-123",
|
||||
user_email="user@test.com",
|
||||
edit_count=10,
|
||||
trigger="auto",
|
||||
artist="Artist",
|
||||
title="Song",
|
||||
)
|
||||
MockFirestore.return_value.list_review_sessions.return_value = [session]
|
||||
|
||||
response = test_client.get("/api/review/job-123/sessions")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data["sessions"]) == 1
|
||||
assert data["sessions"][0]["session_id"] == "s1"
|
||||
assert data["sessions"][0]["edit_count"] == 10
|
||||
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
def test_list_sessions_empty(self, MockFirestore, test_client):
|
||||
MockFirestore.return_value.list_review_sessions.return_value = []
|
||||
response = test_client.get("/api/review/job-123/sessions")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["sessions"] == []
|
||||
|
||||
|
||||
class TestGetReviewSessionEndpoint:
|
||||
"""Tests for GET /api/review/{job_id}/sessions/{session_id}"""
|
||||
|
||||
@patch("backend.api.routes.review.StorageService")
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
def test_get_session_with_data(self, MockFirestore, MockStorage, test_client):
|
||||
session = ReviewSession(
|
||||
session_id="s1",
|
||||
job_id="job-123",
|
||||
correction_data_gcs_path="jobs/job-123/review_sessions/s1.json",
|
||||
)
|
||||
MockFirestore.return_value.get_review_session.return_value = session
|
||||
MockStorage.return_value.download_json.return_value = {"corrected_segments": []}
|
||||
|
||||
response = test_client.get("/api/review/job-123/sessions/s1")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["session_id"] == "s1"
|
||||
assert data["correction_data"] == {"corrected_segments": []}
|
||||
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
def test_get_session_not_found(self, MockFirestore, test_client):
|
||||
MockFirestore.return_value.get_review_session.return_value = None
|
||||
response = test_client.get("/api/review/job-123/sessions/nonexistent")
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
class TestDeleteReviewSessionEndpoint:
|
||||
"""Tests for DELETE /api/review/{job_id}/sessions/{session_id}"""
|
||||
|
||||
@patch("backend.api.routes.review.StorageService")
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
def test_delete_session(self, MockFirestore, MockStorage, test_client):
|
||||
session = ReviewSession(
|
||||
session_id="s1",
|
||||
job_id="job-123",
|
||||
correction_data_gcs_path="jobs/job-123/review_sessions/s1.json",
|
||||
)
|
||||
MockFirestore.return_value.get_review_session.return_value = session
|
||||
|
||||
response = test_client.delete("/api/review/job-123/sessions/s1")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "deleted"
|
||||
MockStorage.return_value.delete_file.assert_called_once()
|
||||
MockFirestore.return_value.delete_review_session.assert_called_once()
|
||||
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
def test_delete_session_not_found(self, MockFirestore, test_client):
|
||||
MockFirestore.return_value.get_review_session.return_value = None
|
||||
response = test_client.delete("/api/review/job-123/sessions/nonexistent")
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
class TestSearchReviewSessionsEndpoint:
|
||||
"""Tests for GET /api/review/sessions/search"""
|
||||
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
def test_search_sessions(self, MockFirestore, test_client):
|
||||
MockFirestore.return_value.search_review_sessions.return_value = [
|
||||
{"session_id": "s1", "job_id": "j1", "artist": "Artist A"},
|
||||
]
|
||||
response = test_client.get("/api/review/sessions/search?q=Artist")
|
||||
assert response.status_code == 200
|
||||
assert len(response.json()["sessions"]) == 1
|
||||
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
def test_search_sessions_empty(self, MockFirestore, test_client):
|
||||
MockFirestore.return_value.search_review_sessions.return_value = []
|
||||
response = test_client.get("/api/review/sessions/search?q=nonexistent")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["sessions"] == []
|
||||
@@ -382,6 +382,27 @@ class TestSummaryEndpoint:
|
||||
reduces payload size for the dashboard polling use case.
|
||||
"""
|
||||
|
||||
def test_summary_projection_includes_visibility_fields(self):
|
||||
"""Verify SUMMARY_FIELD_PATHS includes is_private and visibility_change_in_progress.
|
||||
|
||||
These fields are required for the Change Visibility button on the dashboard.
|
||||
Without them, the button shows incorrect state (always 'Make Private').
|
||||
"""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
paths = FirestoreService.SUMMARY_FIELD_PATHS
|
||||
assert 'is_private' in paths, "is_private must be in summary projection for visibility button"
|
||||
assert 'state_data.visibility_change_in_progress' in paths, \
|
||||
"visibility_change_in_progress must be in summary projection to prevent concurrent changes"
|
||||
|
||||
def test_prune_state_data_keeps_visibility_change_key(self):
|
||||
"""Verify _prune_state_data preserves visibility_change_in_progress."""
|
||||
from backend.api.routes.jobs import _prune_state_data
|
||||
|
||||
data = {'state_data': {'visibility_change_in_progress': True, 'corrected_lyrics': 'strip me'}}
|
||||
result = _prune_state_data(data)
|
||||
assert 'visibility_change_in_progress' in result['state_data']
|
||||
assert 'corrected_lyrics' not in result['state_data']
|
||||
|
||||
def test_prune_state_data_keeps_allowed_keys(self):
|
||||
"""Verify _prune_state_data keeps only dashboard-required keys."""
|
||||
from backend.api.routes.jobs import _prune_state_data
|
||||
|
||||
@@ -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."""
|
||||
|
||||
@@ -45,7 +45,7 @@ def _make_mock_job_manager(job=None):
|
||||
|
||||
def _make_search_session(user_email="test@example.com", expired=False, tenant_id=None):
|
||||
now = datetime.utcnow()
|
||||
ttl = now - timedelta(hours=1) if expired else now + timedelta(minutes=30)
|
||||
ttl = now - timedelta(hours=1) if expired else now + timedelta(days=7)
|
||||
return {
|
||||
"session_id": "sess-abc-123",
|
||||
"user_email": user_email,
|
||||
|
||||
@@ -135,6 +135,20 @@ 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)
|
||||
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(
|
||||
|
||||
@@ -195,14 +195,22 @@ async def generate_screens(job_id: str) -> bool:
|
||||
regen_restore_status = state_data.get('regen_restore_status')
|
||||
|
||||
if regen_restore_status:
|
||||
# Admin-triggered regen: restore original status instead of going to review
|
||||
logger.info(f"[job:{job_id}] Admin screen regen complete, restoring status to {regen_restore_status}")
|
||||
# Admin/visibility-change regen: restore target status instead of going to review
|
||||
logger.info(f"[job:{job_id}] Screen regen complete, restoring status to {regen_restore_status}")
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD as _DEL
|
||||
db = job_manager.firestore.db
|
||||
db.collection("jobs").document(job_id).update({
|
||||
"status": regen_restore_status,
|
||||
"state_data.regen_restore_status": _DEL,
|
||||
})
|
||||
|
||||
# If restoring to review_complete, trigger render worker to continue pipeline
|
||||
# (used by visibility change: private -> public)
|
||||
if regen_restore_status == JobStatus.REVIEW_COMPLETE.value:
|
||||
logger.info(f"[job:{job_id}] Triggering render worker for visibility change pipeline")
|
||||
from backend.services.worker_service import get_worker_service
|
||||
worker_service = get_worker_service()
|
||||
await worker_service.trigger_render_video_worker(job_id)
|
||||
else:
|
||||
# Normal flow: transition to combined review
|
||||
logger.info(f"[job:{job_id}] Screens generated, awaiting combined review")
|
||||
|
||||
@@ -349,6 +349,8 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
}
|
||||
if result.distribution_warnings:
|
||||
state_update['distribution_warnings'] = result.distribution_warnings
|
||||
# Clear visibility change guard flag if set (from visibility change flow)
|
||||
state_update.pop('visibility_change_in_progress', None)
|
||||
job_manager.update_job(job_id, {'state_data': state_update})
|
||||
|
||||
# Send Pushbullet alert if any distribution uploads failed
|
||||
@@ -362,14 +364,27 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
)
|
||||
|
||||
# Mark job as complete (triggers completion email with youtube_url now available)
|
||||
duration = time.time() - start_time
|
||||
completion_metadata = {
|
||||
"action": "completed",
|
||||
"brand_code": result.brand_code,
|
||||
"youtube_url": result.youtube_url,
|
||||
"youtube_upload_queued": result.youtube_upload_queued,
|
||||
"dropbox_link": result.dropbox_link,
|
||||
"gdrive_file_ids": result.gdrive_files,
|
||||
"edit_count": getattr(job, 'edit_count', 0),
|
||||
"duration_seconds": round(duration, 1),
|
||||
}
|
||||
if result.distribution_warnings:
|
||||
completion_metadata["distribution_warnings"] = result.distribution_warnings
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.COMPLETE,
|
||||
progress=100,
|
||||
message="Karaoke generation complete!"
|
||||
message="Karaoke generation complete!",
|
||||
timeline_metadata=completion_metadata,
|
||||
)
|
||||
|
||||
duration = time.time() - start_time
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
root_span.set_attribute("brand_code", result.brand_code or '')
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=video orchestrator=true status=success duration={duration:.1f}s")
|
||||
@@ -410,6 +425,158 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
logger.debug(f"Cleaned up temp directory: {temp_dir}")
|
||||
|
||||
|
||||
async def redistribute_video(job_id: str) -> bool:
|
||||
"""
|
||||
Redistribute existing finals for a completed job (no re-encoding).
|
||||
|
||||
Used by visibility change (public -> private) to redistribute existing
|
||||
encoded files to a different destination without re-rendering or re-encoding.
|
||||
|
||||
Downloads finals from GCS, runs only organization + distribution stages.
|
||||
"""
|
||||
from backend.workers.video_worker_orchestrator import (
|
||||
VideoWorkerOrchestrator,
|
||||
OrchestratorConfig,
|
||||
)
|
||||
from backend.services.job_defaults_service import get_effective_distribution_for_job
|
||||
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
job_log = create_job_logger(job_id, "video-redistribute")
|
||||
|
||||
logger.info(f"[job:{job_id}] WORKER_START worker=video-redistribute")
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
logger.error(f"[job:{job_id}] Job not found for redistribution")
|
||||
return False
|
||||
|
||||
temp_dir = tempfile.mkdtemp(prefix=f"karaoke_redist_{job_id}_")
|
||||
|
||||
try:
|
||||
# Download existing finals from GCS by listing the finals folder
|
||||
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
|
||||
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
|
||||
|
||||
downloaded_files = {}
|
||||
blobs = storage.list_files(f"jobs/{job_id}/finals/")
|
||||
for blob_name in blobs:
|
||||
filename = os.path.basename(blob_name)
|
||||
if not filename:
|
||||
continue
|
||||
local_path = os.path.join(temp_dir, filename)
|
||||
try:
|
||||
storage.download_file(blob_name, local_path)
|
||||
downloaded_files[filename] = local_path
|
||||
job_log.info(f"Downloaded {filename} from GCS")
|
||||
except Exception as e:
|
||||
job_log.warning(f"Could not download {filename}: {e}")
|
||||
|
||||
# Also download CDG/TXT packages if they exist
|
||||
package_blobs = storage.list_files(f"jobs/{job_id}/packages/")
|
||||
for blob_name in package_blobs:
|
||||
filename = os.path.basename(blob_name)
|
||||
if not filename:
|
||||
continue
|
||||
local_path = os.path.join(temp_dir, filename)
|
||||
try:
|
||||
storage.download_file(blob_name, local_path)
|
||||
downloaded_files[filename] = local_path
|
||||
job_log.info(f"Downloaded package {filename} from GCS")
|
||||
except Exception as e:
|
||||
job_log.warning(f"Could not download package {filename}: {e}")
|
||||
|
||||
if not downloaded_files:
|
||||
raise RuntimeError("No finals files found in GCS for redistribution")
|
||||
|
||||
# Get effective distribution settings for the (now-updated) job
|
||||
# Re-read job since is_private was just toggled
|
||||
job = job_manager.get_job(job_id)
|
||||
dist = get_effective_distribution_for_job(job)
|
||||
|
||||
# Load YouTube credentials if needed
|
||||
youtube_credentials = None
|
||||
if dist.enable_youtube_upload:
|
||||
youtube_service = get_youtube_service()
|
||||
if youtube_service.is_configured:
|
||||
youtube_credentials = youtube_service.get_credentials_dict()
|
||||
|
||||
# Create a minimal orchestrator config for distribution only
|
||||
config = OrchestratorConfig(
|
||||
job_id=job_id,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
# Input files - not needed for distribution, but required by dataclass
|
||||
title_video_path="",
|
||||
karaoke_video_path="",
|
||||
instrumental_audio_path="",
|
||||
output_dir=temp_dir,
|
||||
# Distribution settings
|
||||
enable_youtube_upload=dist.enable_youtube_upload,
|
||||
brand_prefix=dist.brand_prefix,
|
||||
discord_webhook_url=dist.discord_webhook_url,
|
||||
youtube_credentials=youtube_credentials,
|
||||
youtube_description_template=dist.youtube_description,
|
||||
dropbox_path=dist.dropbox_path,
|
||||
gdrive_folder_id=dist.gdrive_folder_id,
|
||||
enable_cdg=getattr(job, 'enable_cdg', False),
|
||||
enable_txt=getattr(job, 'enable_txt', False),
|
||||
)
|
||||
|
||||
orchestrator = VideoWorkerOrchestrator(
|
||||
config=config,
|
||||
job_manager=job_manager,
|
||||
storage=storage,
|
||||
job_logger=job_log,
|
||||
)
|
||||
|
||||
# Map downloaded files to orchestrator result attributes by filename patterns
|
||||
for filename, path in downloaded_files.items():
|
||||
lower = filename.lower()
|
||||
if 'lossless' in lower and '4k' in lower and lower.endswith('.mp4'):
|
||||
orchestrator.result.final_video = path
|
||||
elif 'lossless' in lower and lower.endswith('.mkv'):
|
||||
orchestrator.result.final_video_mkv = path
|
||||
elif 'lossy' in lower and '4k' in lower:
|
||||
orchestrator.result.final_video_lossy = path
|
||||
elif '720p' in lower:
|
||||
orchestrator.result.final_video_720p = path
|
||||
elif 'cdg' in lower and lower.endswith('.zip'):
|
||||
orchestrator.result.final_karaoke_cdg_zip = path
|
||||
elif 'txt' in lower and lower.endswith('.zip'):
|
||||
orchestrator.result.final_karaoke_txt_zip = path
|
||||
|
||||
# Run only organization + distribution + notifications
|
||||
await orchestrator._run_organization()
|
||||
await orchestrator._run_distribution()
|
||||
await orchestrator._run_notifications()
|
||||
|
||||
# Update job state_data with new distribution results
|
||||
state_update = dict(job.state_data or {})
|
||||
state_update['brand_code'] = orchestrator.result.brand_code
|
||||
state_update['youtube_url'] = orchestrator.result.youtube_url
|
||||
state_update['dropbox_link'] = orchestrator.result.dropbox_link
|
||||
state_update['gdrive_files'] = orchestrator.result.gdrive_files
|
||||
state_update.pop('visibility_change_in_progress', None)
|
||||
|
||||
job_manager.update_job(job_id, {
|
||||
'state_data': state_update,
|
||||
'outputs_deleted_at': None,
|
||||
'outputs_deleted_by': None,
|
||||
})
|
||||
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=video-redistribute status=success")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] WORKER_END worker=video-redistribute status=error error={e}")
|
||||
return False
|
||||
|
||||
finally:
|
||||
if os.path.exists(temp_dir):
|
||||
shutil.rmtree(temp_dir)
|
||||
|
||||
|
||||
async def generate_video(job_id: str) -> bool:
|
||||
"""
|
||||
Generate final karaoke videos.
|
||||
@@ -705,14 +872,24 @@ async def generate_video_legacy(job_id: str) -> bool:
|
||||
})
|
||||
|
||||
# Mark job as complete (triggers completion email with youtube_url now available)
|
||||
duration = time.time() - start_time
|
||||
completion_metadata = {
|
||||
"action": "completed",
|
||||
"brand_code": result.get('brand_code'),
|
||||
"youtube_url": result.get('youtube_url'),
|
||||
"dropbox_link": result.get('dropbox_link'),
|
||||
"gdrive_file_ids": result.get('gdrive_files'),
|
||||
"edit_count": getattr(job, 'edit_count', 0),
|
||||
"duration_seconds": round(duration, 1),
|
||||
}
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.COMPLETE,
|
||||
progress=100,
|
||||
message="Karaoke generation complete!"
|
||||
message="Karaoke generation complete!",
|
||||
timeline_metadata=completion_metadata,
|
||||
)
|
||||
|
||||
duration = time.time() - start_time
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
root_span.set_attribute("brand_code", result.get('brand_code', ''))
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=video status=success duration={duration:.1f}s")
|
||||
|
||||
@@ -638,7 +638,7 @@ class VideoWorkerOrchestrator:
|
||||
|
||||
if video_url:
|
||||
self.result.youtube_url = video_url
|
||||
self.job_log.info(f"Uploaded to YouTube: {video_url}")
|
||||
self.job_log.info(f"Uploaded to YouTube: {video_url} (video_id={video_id})")
|
||||
|
||||
# Record upload in pending buffer (bridges ~7min GCP monitoring delay)
|
||||
try:
|
||||
@@ -715,7 +715,7 @@ class VideoWorkerOrchestrator:
|
||||
except Exception as e:
|
||||
self.job_log.warning(f"Failed to create Dropbox sharing link: {e}")
|
||||
|
||||
self.job_log.info("Dropbox upload complete")
|
||||
self.job_log.info(f"Dropbox upload complete: {remote_folder}")
|
||||
|
||||
except Exception as e:
|
||||
self.job_log.error(f"Dropbox upload failed: {e}")
|
||||
@@ -752,7 +752,7 @@ class VideoWorkerOrchestrator:
|
||||
)
|
||||
|
||||
self.result.gdrive_files = uploaded
|
||||
self.job_log.info(f"Google Drive upload complete: {len(uploaded)} files")
|
||||
self.job_log.info(f"Google Drive upload complete: {len(uploaded)} files (ids={uploaded})")
|
||||
|
||||
except Exception as e:
|
||||
self.job_log.error(f"Google Drive upload failed: {e}")
|
||||
|
||||
+128
-1
@@ -156,6 +156,37 @@ Query parameters:
|
||||
DELETE /api/jobs/{job_id}
|
||||
```
|
||||
|
||||
#### Change Visibility
|
||||
|
||||
Toggle a completed job between public and private. Only the job owner or admin can use this.
|
||||
|
||||
```http
|
||||
POST /api/jobs/{job_id}/change-visibility
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"target_visibility": "private" // or "public"
|
||||
}
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"status": "success",
|
||||
"job_id": "abc123",
|
||||
"message": "Job changed to private. Outputs redistributed to private destination.",
|
||||
"previous_visibility": "public",
|
||||
"new_visibility": "private",
|
||||
"reprocessing_required": false
|
||||
}
|
||||
```
|
||||
|
||||
**Two flows depending on direction:**
|
||||
- **Public → Private**: Fast (~1-2 min). Deletes distributed outputs (YouTube/Dropbox/GDrive), keeps GCS finals, redistributes to private destination.
|
||||
- **Private → Public**: Slow (~15-30 min). Clears custom styles, resets to Nomad theme, regenerates screens, re-renders and re-encodes video.
|
||||
|
||||
**Validation:** Job must be `complete`, not a tenant job, not already at target visibility, and no concurrent visibility change in progress.
|
||||
|
||||
### Review
|
||||
|
||||
The combined review flow allows users to review lyrics AND select instrumental track in a single session.
|
||||
@@ -264,6 +295,43 @@ Error (duration mismatch):
|
||||
}
|
||||
```
|
||||
|
||||
#### Edit Completed Track
|
||||
|
||||
```http
|
||||
POST /api/jobs/{job_id}/edit
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"artist": "Updated Artist", // optional, only if changing
|
||||
"title": "Updated Title" // optional, only if changing
|
||||
}
|
||||
```
|
||||
|
||||
Reopens a completed track for editing. Cleans up all distributed outputs (YouTube, Dropbox, GDrive, GCS finals), recycles the brand code, and resets the job to `awaiting_review`. A new review token is issued automatically. No additional credits consumed.
|
||||
|
||||
If `artist` or `title` are provided and differ from current values, title/end screens are deleted and the screens worker is triggered to regenerate them in the background.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"status": "success",
|
||||
"job_id": "abc123",
|
||||
"message": "Track reopened for editing. Previous outputs have been removed.",
|
||||
"review_url": "/app/jobs#/abc123/review",
|
||||
"review_token": "...",
|
||||
"metadata_updated": true,
|
||||
"cleanup_results": {
|
||||
"youtube": {"status": "success", "video_id": "xyz"},
|
||||
"dropbox": {"status": "success", "path": "/Karaoke/..."},
|
||||
"gdrive": {"status": "success"},
|
||||
"gcs_finals": {"status": "success", "deleted_count": 4},
|
||||
"brand_code": {"status": "recycled", "code": "NOMAD-1234"}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Requirements:** Job must be in `complete` state with `outputs_deleted_at` not set. User must own the job or be admin.
|
||||
|
||||
#### Get Style Upload URLs
|
||||
|
||||
```http
|
||||
@@ -373,6 +441,65 @@ Content-Type: application/json
|
||||
|
||||
Stores annotations to `jobs/{job_id}/lyrics/annotations.json`. Merges with existing annotations if present.
|
||||
|
||||
#### Review Sessions
|
||||
|
||||
Server-side backup/restore of lyrics review editing sessions. Correction data is stored in GCS; metadata in Firestore subcollection `jobs/{job_id}/review_sessions/{session_id}`.
|
||||
|
||||
##### Save Review Session
|
||||
|
||||
```http
|
||||
POST /api/review/{job_id}/sessions
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"correction_data": { "corrected_segments": [...], "original_segments": [...] },
|
||||
"edit_count": 5,
|
||||
"trigger": "auto", // "auto" | "preview" | "manual"
|
||||
"summary": {
|
||||
"total_segments": 10,
|
||||
"total_words": 100,
|
||||
"corrections_made": 5,
|
||||
"changed_words": [{"original": "hello", "corrected": "hallo", "segment_index": 0}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Deduplicates via SHA-256 hash of correction_data. Returns `{"status": "skipped", "reason": "identical_data"}` if data hasn't changed since last save.
|
||||
|
||||
Auth: Review token (same as correction data access).
|
||||
|
||||
##### List Review Sessions
|
||||
|
||||
```http
|
||||
GET /api/review/{job_id}/sessions
|
||||
```
|
||||
|
||||
Returns session metadata (no correction_data). Ordered by most recent first.
|
||||
|
||||
##### Get Review Session
|
||||
|
||||
```http
|
||||
GET /api/review/{job_id}/sessions/{session_id}
|
||||
```
|
||||
|
||||
Returns full session including correction_data downloaded from GCS.
|
||||
|
||||
##### Delete Review Session
|
||||
|
||||
```http
|
||||
DELETE /api/review/{job_id}/sessions/{session_id}
|
||||
```
|
||||
|
||||
Deletes both GCS data and Firestore metadata.
|
||||
|
||||
##### Search Review Sessions (Cross-Job)
|
||||
|
||||
```http
|
||||
GET /api/review/sessions/search?q=artist+name&limit=20
|
||||
```
|
||||
|
||||
Searches across all jobs. Requires admin auth. Matches against artist, title, and job_id fields.
|
||||
|
||||
### Instrumental Selection (Finalise-Only Jobs)
|
||||
|
||||
For finalise-only jobs (where audio prep was done externally), instrumental selection is handled separately:
|
||||
@@ -534,7 +661,7 @@ Content-Type: application/json
|
||||
}
|
||||
```
|
||||
|
||||
Searches for audio **without creating a job**. Returns a short-lived search session (30-min TTL).
|
||||
Searches for audio **without creating a job**. Returns a search session (7-day TTL).
|
||||
Credits are checked here but **not deducted** — deduction happens at job creation.
|
||||
|
||||
**Response:**
|
||||
|
||||
@@ -113,13 +113,13 @@ Notifications are sent when:
|
||||
| `karaoke-backend@` SA | `roles/cloudfunctions.invoker` | gdrive-validator function | Post-job trigger |
|
||||
| `karaoke-backend@` SA | `roles/run.invoker` | gdrive-validator Cloud Run service | Gen2 function HTTP access |
|
||||
|
||||
### Known Gaps
|
||||
### Known Gaps (Historical Only)
|
||||
|
||||
The validator knows about expected sequence gaps (historical missing numbers). These are configured identically in both:
|
||||
The validator knows about expected sequence gaps from the pre-generator era (before Dec 2024). These are configured identically in both:
|
||||
- `infrastructure/functions/gdrive_validator/main.py` (Cloud Function)
|
||||
- `scripts/validate_and_sync.py` (local script)
|
||||
|
||||
When a new gap is discovered intentionally (e.g., a track was removed), update the `KNOWN_GAPS` dict in **both** files.
|
||||
**Do NOT add new entries to `KNOWN_GAPS`.** All new gaps are bugs — see [Sequence Gap Detected](#sequence-gap-detected) for the investigation and fix procedure.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -189,11 +189,62 @@ The post-job trigger uses a 5-minute Cloud Tasks delay (via `gdrive-validation-q
|
||||
5. The trigger only fires for non-private jobs (jobs with `gdrive_folder_id` set)
|
||||
6. If Cloud Tasks scheduling fails, the orchestrator falls back to immediate validation
|
||||
|
||||
### False Positive Gaps
|
||||
### Sequence Gap Detected
|
||||
|
||||
If the validator reports gaps that are intentional:
|
||||
1. Add the gap number(s) to `KNOWN_GAPS` in both `main.py` and `scripts/validate_and_sync.py`
|
||||
2. Redeploy the cloud function with `./deploy.sh`
|
||||
**IMPORTANT: Never add new entries to `KNOWN_GAPS`.** The existing known gaps are historical (pre-generator era, over a year old). Every new gap is a real bug that must be investigated and fixed.
|
||||
|
||||
**Investigation steps:**
|
||||
|
||||
1. **Identify the missing brand code(s)** from the alert (e.g., "MP4: missing 1295")
|
||||
|
||||
2. **Check if a job exists** with that brand code:
|
||||
```python
|
||||
# Query Firestore for the brand code
|
||||
db.collection('jobs').where(
|
||||
filter=FieldFilter('state_data.brand_code', '==', 'NOMAD-XXXX')
|
||||
).get()
|
||||
```
|
||||
|
||||
3. **If no job found**, the brand code was allocated but the job was deleted, failed, or re-triggered with a new brand code. Check Cloud Run logs for the allocation:
|
||||
```bash
|
||||
gcloud logging read \
|
||||
'resource.type="cloud_run_revision" AND resource.labels.service_name="karaoke-backend" AND "Allocated brand code: NOMAD-XXXX"' \
|
||||
--project=nomadkaraoke --limit=10 --format="table(timestamp,jsonPayload.message)" --freshness=7d
|
||||
```
|
||||
|
||||
4. **Find the job that consumed it** by checking logs around the allocation timestamp:
|
||||
```bash
|
||||
# Search for the brand code in all log messages
|
||||
gcloud logging read \
|
||||
'resource.type="cloud_run_revision" AND resource.labels.service_name="karaoke-backend" AND "NOMAD-XXXX"' \
|
||||
--project=nomadkaraoke --limit=50 --format="table(timestamp,jsonPayload.message)" --freshness=7d
|
||||
```
|
||||
|
||||
5. **Determine root cause** — common scenarios:
|
||||
- **Job re-triggered** (admin reset): First run allocates brand code N, second run allocates N+M. Brand code N is orphaned.
|
||||
- **E2E test cleanup missed recycling**: Test job consumed a number but cleanup didn't return it.
|
||||
- **Job failed mid-distribution**: Brand code allocated but GDrive upload never happened.
|
||||
|
||||
6. **Fix — recycle the brand code** so the next public job fills the gap:
|
||||
```python
|
||||
import os
|
||||
os.environ['GOOGLE_CLOUD_PROJECT'] = 'nomadkaraoke'
|
||||
from google.cloud import firestore
|
||||
db = firestore.Client(project='nomadkaraoke')
|
||||
|
||||
doc_ref = db.collection('brand_code_counters').document('NOMAD')
|
||||
doc = doc_ref.get()
|
||||
data = doc.to_dict()
|
||||
recycled = data.get('recycled', [])
|
||||
recycled.append(XXXX) # The missing number
|
||||
recycled.sort()
|
||||
doc_ref.update({'recycled': recycled, 'last_updated': firestore.SERVER_TIMESTAMP})
|
||||
```
|
||||
The `BrandCodeService` always allocates the smallest recycled number first, so the next public job will fill the gap.
|
||||
|
||||
7. **Check for orphan files** in GDrive that need manual cleanup (e.g., a CDG zip from a partial first run). Local `gcloud` auth typically lacks GDrive write scopes, so report orphan files to the user for manual deletion.
|
||||
|
||||
8. **Add the incident to History** (below) so future agents can see patterns.
|
||||
|
||||
### Duplicate Brand Code Detected
|
||||
|
||||
@@ -222,3 +273,4 @@ The cloud function does metadata-only checks via the GDrive API (fast, cheap, ca
|
||||
- **2025-12-24**: Initial cloud function deployed with Pushbullet notifications and daily Cloud Scheduler trigger
|
||||
- **2026-02-28**: Added SendGrid email (primary), kept Pushbullet (fallback). Added post-job trigger from backend. Added `scripts/check_public_share.py` for manual invocation. Motivated by NOMAD-1271 duplicate brand code incident where daily-only checks left a duplicate undetected for ~24 hours.
|
||||
- **2026-03-02**: NOMAD-1276 incident fix. Post-job trigger now uses 5-minute Cloud Tasks delay instead of immediate invocation, preventing false "all clear" when E2E test files are still in GDrive during cleanup. Also fixed cross-folder gap detection (uses global max across all folders) and added 28 unit tests for the Cloud Function.
|
||||
- **2026-03-06**: NOMAD-1295 gap. Stale GCE encoding cache (#499) caused job `f4a552bf` to produce bad output on first run (allocated NOMAD-1295, only CDG uploaded). Admin re-triggered the job, which allocated a new brand code (NOMAD-1297) without recycling 1295. Fix: recycled 1295 back to the pool. Updated docs to clarify that new gaps must always be investigated and fixed, never added to KNOWN_GAPS.
|
||||
+44
-2
@@ -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.
|
||||
|
||||
---
|
||||
|
||||
@@ -36,6 +39,9 @@ Audio separation and lyrics transcription run in parallel. Both can fail indepen
|
||||
### GCE Instance Selection for FFmpeg
|
||||
AMD EPYC (C4D series) significantly outperforms Intel Xeon (C4 series) for CPU-bound FFmpeg encoding with libass. C4D-highcpu-32 is ~5x faster than C4-standard-8. C4D requires `hyperdisk-balanced` disk type.
|
||||
|
||||
### Large Documents: GCS + Firestore Metadata (Mar 2026)
|
||||
When a document's payload can exceed Firestore's 1MB limit (e.g., CorrectionData at 100KB+ per session), store the payload in GCS and keep only metadata in Firestore. Use SHA-256 hash deduplication to avoid re-uploading identical data. For cross-document queries (e.g., searching sessions across jobs), use Firestore collection group queries on the metadata subcollection with Python-side text filtering — Firestore doesn't support LIKE/substring queries natively.
|
||||
|
||||
### Queue Instead of Skip for External API Limits (Mar 2026)
|
||||
When an external API has a daily quota (e.g., YouTube Data API v3's 10,000 units/day), **never silently skip** the operation when the limit is reached. Instead: (1) Track actual quota units consumed, not just operation counts — a hard "10 uploads/day" limit was far too conservative when each upload costs ~300 of 10,000 available units, (2) Queue failed operations for automatic retry when quota resets — users expected YouTube uploads and got nothing, with no notification, (3) Send follow-up notifications when deferred operations complete. **GCP Cloud Monitoring as single source of truth**: Initially we self-tracked per-operation costs in Firestore, but the estimates drifted from reality (4,493 estimated vs 2,682 actual). GCP Cloud Monitoring's `serviceruntime.googleapis.com/quota/rate/net_usage` metric has only ~7 min delay — viable as the primary data source. Use a lightweight Firestore "pending buffer" for the delay window, with entries auto-expiring after 10 min. Sum raw per-minute datapoints (no aggregation) to match the GCP Console number. Use the external API's timezone for reset calculations (YouTube resets at midnight Pacific Time, not UTC).
|
||||
|
||||
@@ -453,6 +459,9 @@ except Exception as e:
|
||||
|
||||
## Testing Insights
|
||||
|
||||
### New Features Must Test the Summary Projection (Mar 2026)
|
||||
When adding new fields that the dashboard needs, you must add them to **both** `SUMMARY_FIELD_PATHS` (Firestore projection) and `_SUMMARY_STATE_DATA_KEYS` (Python prune allowlist). The dashboard uses `fields=summary` which projects only listed fields — any unlisted field comes back as `undefined`. Unit tests that mock the job object directly won't catch this because they bypass the projection layer entirely. **Always add a regression test** asserting the field is in `SUMMARY_FIELD_PATHS` when introducing new fields the frontend depends on. The Change Visibility feature shipped with `is_private` missing from the projection, causing the button to always show "Make Private".
|
||||
|
||||
### Test Webhook Handlers with Unit Tests
|
||||
Webhook handlers contain critical business logic. Test exact parameters passed to service methods, not just that "something happened."
|
||||
|
||||
@@ -846,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
|
||||
@@ -870,3 +889,26 @@ Even with idempotent endpoints (PR #413) and basic retry logic (PR #242), jobs c
|
||||
3. **Cloud Run service naming matters for debugging** — The service is `karaoke-backend`, not `karaoke-gen-api`. Wrong name returns empty logs, wasting investigation time.
|
||||
4. **Cross-folder gap detection needs global context** — Per-folder max misses trailing gaps when folders have different highest numbers. Use the global max across all folders as the upper bound.
|
||||
|
||||
### Verifying Request Bodies via Cloud Trace Request Size (2026-03-07)
|
||||
|
||||
**Problem:** A job was created with `is_private=true` but the user believed they selected "Published." No request body logging existed to prove what the frontend actually sent.
|
||||
|
||||
**Solution:** Cloud Trace captures `/http/request/size` on every span. By computing the exact byte length of the JSON body with `is_private: true` vs `is_private: false` (compact serialization, no spaces), the sizes matched exactly — 143 bytes for `true`, confirming the frontend sent `is_private: true`.
|
||||
|
||||
**Prevention:** Added two observability mechanisms:
|
||||
1. **`creation_params`** — A dict stored on the job Firestore document capturing the user's original choices (`is_private`, `is_admin`, `created_from`). Persists forever, no log retention concerns.
|
||||
2. **OTel span attributes** — `job.is_private`, `job.source`, `job_id` added to all 4 job creation endpoint spans. Searchable in Cloud Trace for 30 days.
|
||||
|
||||
**Key insight:** When investigating "what did the client send?", Cloud Trace request size can serve as a forensic tool even without request body logging. Compact JSON serialization (`JSON.stringify` with no spaces) is deterministic, so byte-level size matching is reliable.
|
||||
|
||||
### Timeline Metadata for Job Traceability (2026-03-07)
|
||||
|
||||
**Problem:** After shipping the "edit completed tracks" feature, tracing what happened to edited jobs was very difficult. Timeline events only had `status`, `timestamp`, `progress`, `message` — no output details. Cleanup operations (YouTube deletion, Dropbox removal) weren't logged to Firestore. Previous outputs were overwritten in `state_data` with no history. API endpoints (edit, admin-delete) logged to Cloud Run stdout but not to the job's Firestore log subcollection.
|
||||
|
||||
**Solution:**
|
||||
1. **`TimelineEvent.metadata`** — Optional `Dict[str, Any]` field on timeline events. Completion events now capture `brand_code`, `youtube_url`, `dropbox_link`, `gdrive_file_ids`, `duration_seconds`. Edit/delete events capture `previous_outputs` and `cleanup_results`.
|
||||
2. **`log_to_job()` helper** — Module-level function in `firestore_service.py` that writes to the job's Firestore log subcollection. Wraps errors silently so logging never breaks the caller. Used by API endpoints that previously only logged to stdout.
|
||||
3. **Plumbed `timeline_metadata`** through `job_manager.transition_to_state()` → `firestore_service.update_job_status()`.
|
||||
|
||||
**Key insight:** The job's Firestore document (timeline + log subcollection) should be the single source of truth for "what happened to this job." Cloud Logging has retention limits and requires knowing which service to search. Timeline metadata makes the job self-documenting — any agent or human can read the timeline and understand the full lifecycle without cross-referencing logs.
|
||||
|
||||
+13
-2
@@ -32,8 +32,9 @@
|
||||
| **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) |
|
||||
|
||||
## Known Issues
|
||||
|
||||
@@ -45,6 +46,16 @@
|
||||
|
||||
## 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).
|
||||
|
||||
- **Edit Completed Tracks** (2026-03-06): Users can now edit completed karaoke tracks — correcting lyrics, changing instrumental selection, or updating artist/title metadata — without consuming additional credits. Clicking "Edit" on a completed job opens a confirmation modal (with optional artist/title editing), then cleans up all distributed outputs (YouTube video deleted, Dropbox folder removed, GDrive files deleted, GCS finals purged, brand code recycled), resets the job to `awaiting_review`, and redirects to the existing review screen. After re-review, the standard pipeline re-renders and re-distributes with a fresh brand code. New endpoint: `POST /api/jobs/{job_id}/edit`. New Job model field: `edit_count`. State machine updated: `COMPLETE → AWAITING_REVIEW` transition allowed. See [archive/2026-03-06-edit-completed-tracks-plan.md](archive/2026-03-06-edit-completed-tracks-plan.md) and [API.md](API.md#edit-completed-track).
|
||||
|
||||
- **Change Visibility** (2026-03-06): Users can now toggle completed jobs between public and private via a "Make Public"/"Make Private" button on the job card. Two distinct flows: Public→Private is fast (~1-2 min, redistributes existing finals), Private→Public is slow (~15-30 min, resets styles to Nomad theme, regenerates screens, re-renders video). Confirmation modal explains the implications. Tenant jobs excluded. See [archive/2026-03-06-change-visibility-plan.md](archive/2026-03-06-change-visibility-plan.md) and [API.md](API.md#change-visibility).
|
||||
|
||||
- **Tenant Portal UI Rework** (2026-03-04): Replaced the multi-step consumer wizard with a streamlined 4-field form (Artist, Title, Mixed Audio, Instrumental Audio) for B2B tenant portals. Vocal Star's portal now uses the new `TenantJobFlow` component instead of `GuidedJobFlow`. All tenant jobs are automatically private with tenant-specific distribution: Dropbox delivery to `/MediaUnsynced/Karaoke/Tracks-VocalStar`, Google Drive upload to tenant folder, VSTAR brand prefix. Backend adds `_apply_tenant_overrides()` helper that forces private, applies locked theme, and overlays tenant distribution settings. Private tenant jobs now use their own Dropbox/GDrive paths instead of the NonPublished override. Frontend conditionally renders `TenantJobFlow` vs `GuidedJobFlow` based on tenant detection. See [archive/2026-03-04-tenant-portal-ui-rework.md](archive/2026-03-04-tenant-portal-ui-rework.md).
|
||||
|
||||
- **Custom Video Styling for Private Jobs** (2026-03-04): Users who select "Private (no YouTube upload)" can now customize their karaoke video styling. New options in the guided flow's customize step: upload a custom **karaoke background image** (replaces the starfield behind lyrics), upload a custom **title card background image**, and change **artist/title text colors** via color pickers. Both backgrounds show accurate canvas-based live previews. Style assets are uploaded to GCS via signed URLs after job creation (non-blocking — job falls back to default theme on upload failure). Backend: 2 new endpoints (`style-upload-urls`, `style-uploads-complete`) that validate ownership, cutoff status, and merge custom assets into the theme's `style_params.json`. See [API.md](API.md#get-style-upload-urls).
|
||||
@@ -122,7 +133,7 @@
|
||||
|
||||
- **Fast Preview Video Option** (2026-01-10): Added toggle in lyrics review UI to render preview videos with black background (~10s) instead of theme background image (~30-60s). Default is now black background for faster iteration during review. Users can enable theme background via checkbox when they want to verify the final look. See [API.md](API.md#generate-preview).
|
||||
|
||||
- **Frontend Consolidation** (2026-01-09): Consolidated three separate frontends into a single Next.js application. Previously: (1) Main frontend (Next.js + Tailwind), (2) Lyrics Review (React + Vite + MUI, ~14k lines), and (3) Instrumental Review (vanilla HTML/JS, ~1.7k lines) were deployed separately. Now all UIs are unified in the main frontend at `/app/jobs/{id}/review` and `/app/jobs/{id}/instrumental`. Benefits: single deployment to Cloudflare Pages, no external redirects during user workflows, unified design system (Radix/Tailwind), simpler authentication via job ownership model. See [archive/2026-01-09-frontend-consolidation-plan.md](archive/2026-01-09-frontend-consolidation-plan.md) and [tasks/](tasks/).
|
||||
- **Frontend Consolidation** (2026-01-09): Consolidated three separate frontends into a single Next.js application. Previously: (1) Main frontend (Next.js + Tailwind), (2) Lyrics Review (React + Vite + MUI, ~14k lines), and (3) Instrumental Review (vanilla HTML/JS, ~1.7k lines) were deployed separately. Now all UIs are unified in the main frontend at `/app/jobs#/{id}/review` and `/app/jobs#/{id}/instrumental`. Benefits: single deployment to Cloudflare Pages, no external redirects during user workflows, unified design system (Radix/Tailwind), simpler authentication via job ownership model. See [archive/2026-01-09-frontend-consolidation-plan.md](archive/2026-01-09-frontend-consolidation-plan.md) and [tasks/](tasks/).
|
||||
|
||||
- **Admin Login Token for Made-For-You Orders** (2026-01-10): Added one-click admin login via email. When a made-for-you order is placed, the admin notification email now includes a direct link with an embedded login token (`?admin_token=TOKEN`). Clicking this link auto-authenticates the admin and opens the job directly - no manual login required. Tokens expire after 24 hours. Also added: BCC to `done@nomadkaraoke.com` on all job completion emails, fixed timezone display (EST→ET for DST correctness). See [API.md](API.md#verify-magic-link).
|
||||
|
||||
|
||||
+1
-1
@@ -495,7 +495,7 @@ async function debug() {
|
||||
const page = await browser.newContext().then(c => c.newPage());
|
||||
|
||||
await page.addInitScript(t => localStorage.setItem('karaoke_access_token', t), TOKEN);
|
||||
await page.goto(`https://gen.nomadkaraoke.com/app/jobs/${JOB_ID}/review/`);
|
||||
await page.goto(`https://gen.nomadkaraoke.com/app/jobs#/${JOB_ID}/review`);
|
||||
|
||||
// Debug interactively - the browser stays open
|
||||
await page.pause(); // Opens Playwright inspector
|
||||
|
||||
+18
-1
@@ -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.
|
||||
|
||||
---
|
||||
|
||||
@@ -98,6 +98,23 @@ gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
|
||||
---
|
||||
|
||||
## GDrive validator reports sequence gap
|
||||
|
||||
**Symptoms:** Email from "Nomad Karaoke GDrive Validator" reporting `SEQUENCE GAPS: MP4: missing XXXX`.
|
||||
|
||||
**Key principle: Never add to `KNOWN_GAPS`.** All known gaps are historical (pre-generator, 2024). Every new gap is a real bug.
|
||||
|
||||
**Full investigation and fix procedure:** See [docs/GDRIVE-VALIDATOR.md § Sequence Gap Detected](GDRIVE-VALIDATOR.md#sequence-gap-detected).
|
||||
|
||||
**Quick reference:**
|
||||
1. Query Firestore for the missing brand code (`state_data.brand_code == 'NOMAD-XXXX'`)
|
||||
2. If no job found, check Cloud Run logs for `"Allocated brand code: NOMAD-XXXX"` to find when/how it was consumed
|
||||
3. Determine root cause from logs (job re-trigger, failed distribution, etc.)
|
||||
4. Recycle the brand code number into `brand_code_counters/NOMAD.recycled` — the next public job will fill the gap
|
||||
5. Report any orphan GDrive files to the user for manual cleanup
|
||||
|
||||
---
|
||||
|
||||
## Google Drive uploads missing (gdrive_files empty)
|
||||
|
||||
**Symptoms:** Jobs complete successfully but `state_data.gdrive_files` is empty `{}`. Cloud Run logs show `BrokenPipeError` or `SSL: UNEXPECTED_EOF_WHILE_READING`.
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
# Change Visibility Plan
|
||||
|
||||
> **Date**: 2026-03-06
|
||||
> **Branch**: `feat/sess-20260306-1750-change-visibility`
|
||||
> **Status**: Draft
|
||||
|
||||
## Problem
|
||||
|
||||
Users who accidentally select the wrong visibility (public/private) during job creation have no way to change it after the job completes. Currently, only admins can toggle `is_private` via the PATCH endpoint, and when toggling to private it only auto-deletes outputs -- it doesn't re-distribute to the correct destination.
|
||||
|
||||
Example: Job `fdcc82a6` was accidentally created as private but should be public.
|
||||
|
||||
## Requirements
|
||||
|
||||
1. Any user who can see a job (creator or admin) can change visibility on completed jobs
|
||||
2. A confirmation modal explains exactly what will happen before proceeding
|
||||
3. Modal wording varies based on direction (public->private vs private->public)
|
||||
4. Tenant jobs (Vocal Star, Singa) are excluded -- this is consumer gen only
|
||||
5. No cooldown/rate limiting needed
|
||||
|
||||
## Two Distinct Flows
|
||||
|
||||
### Flow A: Public -> Private (simpler, faster)
|
||||
|
||||
The video content doesn't change -- same nomad theme, same screens. We just need to move outputs from public destinations to private ones.
|
||||
|
||||
**Steps:**
|
||||
1. Delete distributed outputs (YouTube, Dropbox `/Tracks-Organized/`, GDrive) but **keep GCS finals**
|
||||
2. Recycle the NOMAD brand code
|
||||
3. Set `is_private = true` on the job
|
||||
4. Re-run distribution only: allocate NOMADNP brand code, upload finals to Dropbox `/Tracks-NonPublished/`
|
||||
5. Update job state_data with new brand_code and dropbox_link
|
||||
6. Clear `outputs_deleted_at` flag
|
||||
7. Mark job as complete
|
||||
|
||||
**Expected duration:** ~1-2 minutes (just file uploads)
|
||||
|
||||
### Flow B: Private -> Public (complex, slower)
|
||||
|
||||
Private jobs may have custom styles (backgrounds, colors) that don't conform to the public Nomad branding. We must reset to defaults and re-process from screens onward.
|
||||
|
||||
**Steps:**
|
||||
1. Delete distributed outputs (Dropbox `/Tracks-NonPublished/`) + delete GCS finals + delete screens + delete `with_vocals.mkv`
|
||||
2. Recycle the NOMADNP brand code
|
||||
3. **Permanently clear custom style data:**
|
||||
- Reset `theme_id` to `"nomad"` (or whatever the default is)
|
||||
- Clear `color_overrides` to `{}`
|
||||
- Clear `style_assets` to `{}`
|
||||
- Delete any custom style files from GCS (`jobs/{job_id}/style/`)
|
||||
4. Set `is_private = false` on the job
|
||||
5. Set job status to `LYRICS_COMPLETE` (entry point for screens worker)
|
||||
6. Clear relevant progress keys: `screens_progress`, `render_progress`, `video_progress`, `encoding_progress`
|
||||
7. Trigger screens worker, which cascades through: screens -> awaiting_review (auto-skip, since review is already done) -> render -> encode -> distribute publicly
|
||||
8. Job returns to `COMPLETE` with public outputs (YouTube, Dropbox `/Tracks-Organized/`, GDrive)
|
||||
|
||||
**Expected duration:** ~15-30 minutes (re-render + re-encode + distribute)
|
||||
|
||||
**Key gotcha:** After regenerating screens, the pipeline normally transitions to `AWAITING_REVIEW`. But we've already completed review -- we need to auto-skip review and proceed to rendering. We'll use a `regen_restore_status` mechanism (already exists for the `regenerate-screens` endpoint) to signal the screens worker to restore to `REVIEW_COMPLETE` instead of `AWAITING_REVIEW`, which triggers the render worker.
|
||||
|
||||
## Architecture
|
||||
|
||||
### New Backend Endpoint
|
||||
|
||||
```
|
||||
POST /api/jobs/{job_id}/change-visibility
|
||||
```
|
||||
|
||||
**Auth:** Requires authenticated user who is the job creator OR an admin.
|
||||
|
||||
**Request body:**
|
||||
```json
|
||||
{
|
||||
"target_visibility": "public" | "private"
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"status": "success" | "processing" | "error",
|
||||
"job_id": "...",
|
||||
"message": "...",
|
||||
"previous_visibility": "public" | "private",
|
||||
"new_visibility": "public" | "private",
|
||||
"reprocessing_required": true | false
|
||||
}
|
||||
```
|
||||
|
||||
**Why a new endpoint instead of extending admin PATCH?**
|
||||
- The PATCH endpoint is admin-only; this needs to work for regular users
|
||||
- The logic is complex enough to warrant its own endpoint with clear semantics
|
||||
- We need to orchestrate multiple steps atomically (delete outputs, update fields, trigger workers)
|
||||
- The existing PATCH toggle-to-private behavior is kept as-is for admin convenience (backwards compat)
|
||||
|
||||
**Validation:**
|
||||
- Job must be in `COMPLETE` status (not `FAILED`, `PREP_COMPLETE`, or in-progress)
|
||||
- Job must not be a tenant job (`tenant_id` must be null)
|
||||
- Target visibility must differ from current visibility
|
||||
- Job must not already be undergoing a visibility change (guard against double-clicks)
|
||||
|
||||
### Backend Implementation Details
|
||||
|
||||
#### Public -> Private (distribution-only re-run)
|
||||
|
||||
This flow is novel -- we don't have an existing mechanism to re-run just distribution. Options:
|
||||
|
||||
**Option 1: Dedicated `_redistribute` function** (recommended)
|
||||
Create a lightweight function that:
|
||||
1. Downloads finals from GCS to a temp dir
|
||||
2. Creates an OrchestratorConfig with private distribution settings
|
||||
3. Runs only `_run_organization()` + `_run_distribution()` + `_run_notifications()` stages
|
||||
4. Updates job state_data
|
||||
|
||||
This avoids re-encoding entirely. We'd extract the distribution stages into a callable unit.
|
||||
|
||||
**Option 2: Re-run full video worker with cached encoding**
|
||||
The GCE encoding worker has a cache -- if the job was recently encoded, it returns cached results. But this is fragile (cache might be cleared) and still downloads/re-uploads files unnecessarily.
|
||||
|
||||
Going with Option 1.
|
||||
|
||||
**Implementation:**
|
||||
- New function in `video_worker.py`: `async def redistribute_video(job_id: str) -> bool`
|
||||
- Modeled after `generate_video_orchestrated()` but skips encoding
|
||||
- Downloads existing finals from GCS `jobs/{job_id}/finals/`
|
||||
- Creates orchestrator with appropriate distribution config
|
||||
- Runs organization + distribution stages only
|
||||
|
||||
#### Private -> Public (full re-process)
|
||||
|
||||
This reuses existing infrastructure more directly:
|
||||
1. Call modified `delete_job_outputs()` that also cleans up screens and rendered video
|
||||
2. Reset style fields on the job document
|
||||
3. Set status to `LYRICS_COMPLETE` with `regen_restore_status = "review_complete"`
|
||||
4. Trigger screens worker via `worker_service.trigger_screens_worker(job_id)`
|
||||
5. The screens worker generates screens, then sees `regen_restore_status` and restores to `REVIEW_COMPLETE`
|
||||
6. `REVIEW_COMPLETE` triggers render worker -> video worker -> `COMPLETE`
|
||||
|
||||
**Issue: Screens worker `regen_restore_status` behavior**
|
||||
|
||||
Looking at the existing `regenerate-screens` endpoint (admin.py:2003), it sets `regen_restore_status` to the original status. The screens worker checks this and restores to that status instead of going to `AWAITING_REVIEW`.
|
||||
|
||||
For our case, we want to restore to `REVIEW_COMPLETE` (not back to `COMPLETE`), so the pipeline continues through render + encode. This fits the existing mechanism perfectly -- we just set `regen_restore_status = "review_complete"`.
|
||||
|
||||
**Issue: Screens worker does NOT auto-trigger the render worker**
|
||||
|
||||
Verified: The screens worker's `regen_restore_status` handling (screens_worker.py:197-204) just does a raw Firestore update to set the status -- it does **not** trigger any downstream worker. The render worker is only triggered from the `complete-review` API endpoint (jobs.py:992).
|
||||
|
||||
**Solution:** Modify the screens worker's `regen_restore_status` handling to also trigger the render worker when the restore status is `review_complete`. This is the cleanest approach because:
|
||||
- The trigger logic stays in the worker pipeline (not in a separate polling mechanism)
|
||||
- It's a small, focused change to `screens_worker.py`
|
||||
- It reuses `worker_service.trigger_render_video_worker(job_id)`
|
||||
|
||||
```python
|
||||
# In screens_worker.py, after restoring status:
|
||||
if regen_restore_status == "review_complete":
|
||||
# Visibility change flow: trigger render worker to continue pipeline
|
||||
from backend.services.worker_service import get_worker_service
|
||||
worker_service = get_worker_service()
|
||||
await worker_service.trigger_render_video_worker(job_id)
|
||||
```
|
||||
|
||||
#### Modified `delete_job_outputs` for Public -> Private
|
||||
|
||||
The current `delete_job_outputs()` always deletes GCS finals. For public->private, we need to keep them. Two approaches:
|
||||
|
||||
**Option A: Add `keep_gcs_finals` parameter** (recommended)
|
||||
Add an optional parameter to `delete_job_outputs()`: `keep_gcs_finals: bool = False`. When True, skip the GCS finals deletion step. The endpoint still deletes YouTube/Dropbox/GDrive and recycles the brand code.
|
||||
|
||||
**Option B: Create separate helper function**
|
||||
Extract the YouTube/Dropbox/GDrive deletion into a helper. More code duplication.
|
||||
|
||||
Going with Option A -- minimal change, backwards compatible.
|
||||
|
||||
### Frontend Implementation
|
||||
|
||||
#### Button Location
|
||||
|
||||
Add a "Change Visibility" button to the `OutputLinks` component (`frontend/components/job/OutputLinks.tsx`), visible when:
|
||||
- Job status is `complete`
|
||||
- Job is not a tenant job
|
||||
- Job is not currently being re-processed (guard state)
|
||||
|
||||
The button shows the current visibility and what it would change to:
|
||||
- For public jobs: "Make Private" with a Lock icon
|
||||
- For private jobs: "Make Public" with a Globe icon
|
||||
|
||||
#### Confirmation Modal
|
||||
|
||||
Uses the existing `AlertDialog` component from `@radix-ui/react-alert-dialog`.
|
||||
|
||||
**Public -> Private modal:**
|
||||
```
|
||||
Title: Make This Track Private?
|
||||
|
||||
This will:
|
||||
- Remove the video from YouTube
|
||||
- Remove files from Google Drive
|
||||
- Move Dropbox files from public to private folder
|
||||
- Assign a new private brand code (NOMADNP)
|
||||
|
||||
The video content won't change. This usually takes about 1-2 minutes.
|
||||
|
||||
You can change it back to public later, but that will require
|
||||
re-rendering the video (~15-30 minutes).
|
||||
|
||||
[Cancel] [Make Private]
|
||||
```
|
||||
|
||||
**Private -> Public modal:**
|
||||
```
|
||||
Title: Make This Track Public?
|
||||
|
||||
This will:
|
||||
- Remove any custom styling (backgrounds, colors) and
|
||||
reset to the standard Nomad Karaoke theme
|
||||
- Regenerate title and end screens
|
||||
- Re-render the karaoke video with default branding
|
||||
- Publish to YouTube, Google Drive, and Dropbox
|
||||
|
||||
This process takes approximately 15-30 minutes. You'll receive
|
||||
an email when it's complete.
|
||||
|
||||
Any custom styling you applied will be permanently removed.
|
||||
|
||||
[Cancel] [Make Public]
|
||||
```
|
||||
|
||||
#### During Re-processing (Private -> Public)
|
||||
|
||||
While the job is being re-processed:
|
||||
- The button is disabled and shows a spinner: "Changing to Public..."
|
||||
- Job status will cycle through intermediate states (`LYRICS_COMPLETE` -> `GENERATING_SCREENS` -> etc.)
|
||||
- The job card should show these intermediate statuses normally
|
||||
- When it reaches `COMPLETE` again, the button returns to normal
|
||||
|
||||
For public->private, the change is fast enough (~1-2 min) that we can show a loading spinner on the button and poll for completion.
|
||||
|
||||
#### API Integration
|
||||
|
||||
New method in `frontend/lib/api.ts`:
|
||||
|
||||
```typescript
|
||||
// In the public api object (not adminApi, since regular users can use this)
|
||||
async changeVisibility(jobId: string, targetVisibility: 'public' | 'private'): Promise<ChangeVisibilityResponse> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/jobs/${jobId}/change-visibility`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders()
|
||||
},
|
||||
body: JSON.stringify({ target_visibility: targetVisibility }),
|
||||
}
|
||||
);
|
||||
return handleResponse(response);
|
||||
}
|
||||
```
|
||||
|
||||
## State Machine Considerations
|
||||
|
||||
New state transitions needed:
|
||||
- `COMPLETE` -> `LYRICS_COMPLETE` (for private->public re-processing)
|
||||
|
||||
This transition doesn't currently exist in `STATE_TRANSITIONS`. We need to add it. The `COMPLETE` -> `LYRICS_COMPLETE` transition is safe because:
|
||||
- We've already validated the job has completed audio+lyrics processing
|
||||
- We're resetting screens/render/video progress markers
|
||||
- The screens worker will pick up from `LYRICS_COMPLETE` as normal
|
||||
|
||||
Also need: `COMPLETE` -> `GENERATING_VIDEO` (for public->private redistribution, if we transition through video worker states during redistribution). Actually, for the redistribution-only path, we might want a simpler approach -- keep the job in `COMPLETE` status during redistribution since it's a fast operation, or use a new transient state.
|
||||
|
||||
**Decision:** For public->private (fast redistribution), we'll:
|
||||
1. Set a flag `state_data.visibility_change_in_progress = true` to prevent concurrent changes
|
||||
2. Keep status as `COMPLETE` (since the operation is fast and the job is still "complete")
|
||||
3. Run redistribution in a background task
|
||||
4. Clear the flag when done
|
||||
|
||||
For private->public (full re-process), we'll:
|
||||
1. Set `visibility_change_in_progress = true`
|
||||
2. Transition to `LYRICS_COMPLETE` (triggering the normal pipeline)
|
||||
3. The flag gets cleared when the job reaches `COMPLETE` again
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
### Phase 1: Backend - Change Visibility Endpoint
|
||||
|
||||
**Files to modify:**
|
||||
- `backend/api/routes/jobs.py` -- Add `POST /jobs/{job_id}/change-visibility` endpoint
|
||||
- `backend/api/routes/admin.py` -- Add `keep_gcs_finals` param to `delete_job_outputs()`
|
||||
- `backend/models/job.py` -- Add `COMPLETE -> LYRICS_COMPLETE` state transition
|
||||
- `backend/models/requests.py` -- Add request/response models
|
||||
|
||||
**Files to create:**
|
||||
- `backend/services/visibility_change_service.py` -- Core logic for both flows
|
||||
|
||||
### Phase 2: Backend - Redistribution Function
|
||||
|
||||
**Files to modify:**
|
||||
- `backend/workers/video_worker.py` -- Add `redistribute_video()` function
|
||||
- `backend/workers/video_worker_orchestrator.py` -- Possibly extract distribution stages
|
||||
|
||||
### Phase 3: Frontend - Button + Modal
|
||||
|
||||
**Files to modify:**
|
||||
- `frontend/components/job/OutputLinks.tsx` -- Add Change Visibility button + modal
|
||||
- `frontend/lib/api.ts` -- Add `changeVisibility()` method + response types
|
||||
|
||||
### Phase 4: Testing
|
||||
|
||||
**Files to create:**
|
||||
- `backend/tests/test_change_visibility.py` -- Unit tests for the visibility change service
|
||||
- `backend/tests/test_redistribute.py` -- Unit tests for the redistribution function
|
||||
- `frontend/e2e/production/change-visibility.spec.ts` -- E2E test (if feasible)
|
||||
|
||||
**Test cases:**
|
||||
1. Public -> Private: outputs deleted, finals preserved, redistributed to private destination
|
||||
2. Private -> Public: styles reset, screens regenerated, full pipeline completes
|
||||
3. Validation: rejects non-complete jobs, tenant jobs, same-visibility changes, concurrent changes
|
||||
4. Auth: job creator can change, admin can change, other users cannot
|
||||
5. Edge cases: job with no YouTube URL, job with no brand code, job with outputs already deleted
|
||||
|
||||
## Risk Assessment
|
||||
|
||||
| Risk | Impact | Mitigation |
|
||||
|------|--------|------------|
|
||||
| Pipeline fails mid-visibility-change (private->public) | Job stuck in intermediate state | Use existing `FAILED` state handling; admin can restart |
|
||||
| GCS finals deleted before redistribution completes (public->private) | Need to re-encode | Use `keep_gcs_finals=True` to preserve them |
|
||||
| Race condition: user clicks button twice | Double processing | `visibility_change_in_progress` guard flag |
|
||||
| Screens worker doesn't auto-trigger render after regen | Pipeline stalls | **Resolved**: Modify screens worker to trigger render worker when `regen_restore_status == "review_complete"` |
|
||||
| Custom style files left as orphans in GCS | Storage waste | Clean up `jobs/{job_id}/style/` during private->public |
|
||||
|
||||
## Open Questions (Resolved)
|
||||
|
||||
1. **Who can trigger?** Anyone who can see the job (creator or admin). -> New user-facing endpoint.
|
||||
2. **Skip re-encoding for public->private?** Yes, keep GCS finals and redistribute only.
|
||||
3. **How far back for private->public?** From `LYRICS_COMPLETE` (screens -> render -> encode -> distribute).
|
||||
4. **Tenant jobs?** Excluded. Consumer gen only.
|
||||
5. **Custom style data?** Permanently cleared on private->public. Explained in modal.
|
||||
6. **Rate limiting?** None needed.
|
||||
@@ -0,0 +1,262 @@
|
||||
# Edit Completed Tracks — Implementation Plan
|
||||
|
||||
> Created: 2026-03-06
|
||||
> Branch: feat/sess-20260306-1705-edit-completed-tracks
|
||||
|
||||
## Overview
|
||||
|
||||
Allow users to edit completed karaoke tracks — correcting lyrics, changing instrumental selection, or updating artist/title metadata — without consuming additional credits. The existing outputs are cleaned up (YouTube, Dropbox, GDrive, GCS) before re-opening the review screens, and a fresh brand code is allocated when the edited track is re-distributed.
|
||||
|
||||
## Design Decisions
|
||||
|
||||
| Decision | Answer |
|
||||
|----------|--------|
|
||||
| Brand code on edit | New code allocated (old one recycled) |
|
||||
| Credit cost | Free (credit already consumed at job creation) |
|
||||
| Edit limit | None |
|
||||
| Metadata edits (artist/title) | Supported via confirmation modal |
|
||||
| UX approach | Reopen review on same job (approach A) |
|
||||
|
||||
## User Flow
|
||||
|
||||
```
|
||||
Completed job detail page
|
||||
→ User clicks "Edit Track"
|
||||
→ Confirmation modal appears:
|
||||
- Explains: existing outputs will be deleted, track re-rendered after review
|
||||
- Asks: "Do you need to update the artist or title?"
|
||||
- If yes: shows editable artist/title input fields (pre-filled)
|
||||
- If no: fields hidden
|
||||
- [Cancel] [Confirm & Edit]
|
||||
→ On confirm:
|
||||
- Frontend calls POST /api/jobs/{job_id}/edit
|
||||
- Backend: cleanup outputs → reset state → issue review token
|
||||
- Frontend redirects to review screen (/app/jobs#/{jobId}/review)
|
||||
→ User edits lyrics / instrumental as usual
|
||||
→ User submits review
|
||||
→ Standard pipeline: render → encode → distribute (new brand code)
|
||||
→ Job returns to COMPLETE with fresh outputs
|
||||
```
|
||||
|
||||
## Implementation
|
||||
|
||||
### Phase 1: Backend — Edit Endpoint
|
||||
|
||||
**New endpoint: `POST /api/jobs/{job_id}/edit`**
|
||||
|
||||
File: `backend/api/routes/jobs.py` (or new `backend/api/routes/edit.py`)
|
||||
|
||||
Request body:
|
||||
```json
|
||||
{
|
||||
"artist": "Updated Artist", // optional, only if user wants to change
|
||||
"title": "Updated Title" // optional, only if user wants to change
|
||||
}
|
||||
```
|
||||
|
||||
Auth: Job owner (via session token) OR admin.
|
||||
|
||||
Logic:
|
||||
1. **Validate** job is in `COMPLETE` state and user owns it
|
||||
2. **Validate** `outputs_deleted_at` is not set (prevent editing already-in-progress edits)
|
||||
3. **Cleanup distributed outputs** (reuse logic from admin `delete-outputs`):
|
||||
a. Delete YouTube video (if exists)
|
||||
b. Delete Dropbox folder (if exists)
|
||||
c. Delete Google Drive files (if exists)
|
||||
d. Delete GCS `finals/` folder
|
||||
e. Recycle brand code (if Dropbox + GDrive both succeeded)
|
||||
f. Clear state_data keys: `youtube_url`, `youtube_video_id`, `brand_code`, `dropbox_link`, `gdrive_files`
|
||||
g. Set `outputs_deleted_at` + `outputs_deleted_by`
|
||||
4. **Update metadata** (if provided):
|
||||
a. Update `artist` and/or `title` fields on the job
|
||||
b. If metadata changed: delete existing screen files from GCS (`screens/` folder)
|
||||
c. Clear `screens_progress` from state_data so screens worker re-runs
|
||||
5. **Reset processing state**:
|
||||
a. Clear state_data keys: `render_progress`, `video_progress`, `encoding_progress`, `review_complete`
|
||||
b. Keep: `audio_complete`, `lyrics_complete`, `corrected_lyrics`, `instrumental_selection`, `instrumental_options`
|
||||
c. Keep all stems and lyrics files in GCS
|
||||
6. **Transition state**: `COMPLETE` → `AWAITING_REVIEW`
|
||||
7. **Issue review token**: Generate new `review_token` with expiration
|
||||
8. **Increment edit counter**: `edit_count += 1` (new field)
|
||||
9. **Log timeline event**: `"Track edit initiated by {user_email} (edit #{edit_count})"`
|
||||
10. **Return** review URL + token
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"review_url": "/app/jobs#/{jobId}/review",
|
||||
"review_token": "abc123..."
|
||||
}
|
||||
```
|
||||
|
||||
**Error cases:**
|
||||
- Job not in COMPLETE state → 400
|
||||
- User doesn't own job → 403
|
||||
- Cleanup fails critically (Dropbox folder still exists) → 500, don't reset state
|
||||
- Job already being edited (status != COMPLETE) → 400
|
||||
|
||||
### Phase 2: Backend — State Machine Updates
|
||||
|
||||
File: `backend/models/job.py`
|
||||
|
||||
1. Add `COMPLETE → AWAITING_REVIEW` to `STATE_TRANSITIONS` dict (conditional on edit endpoint)
|
||||
2. Add new field to Job model:
|
||||
```python
|
||||
edit_count: int = 0
|
||||
```
|
||||
|
||||
### Phase 3: Backend — Post-Review Pipeline Adjustments
|
||||
|
||||
File: `backend/workers/screens_worker.py`
|
||||
|
||||
- When triggered after an edit with metadata changes, screens worker already handles regeneration
|
||||
- The edit endpoint clears `screens_progress` and deletes screen files, so screens worker will re-run naturally
|
||||
- No changes needed if screens worker already checks for missing screen files
|
||||
|
||||
File: `backend/workers/render_video_worker.py`
|
||||
|
||||
- No changes needed — render worker reads current `corrected_lyrics` and `instrumental_selection` from state_data
|
||||
- Will pick up whatever the user selected during re-review
|
||||
|
||||
File: `backend/workers/video_worker_orchestrator.py`
|
||||
|
||||
- Already clears `outputs_deleted_at` after successful distribution (lines 564-578)
|
||||
- Already allocates new brand code via `allocate_brand_code()` during distribution
|
||||
- No changes needed
|
||||
|
||||
### Phase 4: Frontend — Edit Button + Confirmation Modal
|
||||
|
||||
**Edit button on completed job view**
|
||||
|
||||
File: `frontend/app/app/jobs/[[...slug]]/client.tsx` (or wherever job detail is rendered)
|
||||
|
||||
- Show "Edit Track" button only when job status is `complete`
|
||||
- Button opens the confirmation modal
|
||||
|
||||
**Confirmation modal component**
|
||||
|
||||
New file: `frontend/components/job/EditTrackModal.tsx`
|
||||
|
||||
Content:
|
||||
- Warning text: "This will remove your current video from YouTube, Dropbox, and Google Drive. After you complete the review again, a new version will be rendered and re-distributed."
|
||||
- Toggle/checkbox: "I need to update the artist or title"
|
||||
- When checked, show:
|
||||
- Artist input (pre-filled with current `job.artist`)
|
||||
- Title input (pre-filled with current `job.title`)
|
||||
- [Cancel] button
|
||||
- [Confirm & Edit] button → calls API, shows loading state, redirects to review on success
|
||||
|
||||
**API call**
|
||||
|
||||
File: `frontend/lib/api.ts`
|
||||
|
||||
Add:
|
||||
```typescript
|
||||
editCompletedTrack(jobId: string, updates?: { artist?: string; title?: string }): Promise<{ review_url: string; review_token: string }>
|
||||
```
|
||||
|
||||
### Phase 5: Frontend — Review Screen Adjustments
|
||||
|
||||
File: `frontend/app/app/jobs/[[...slug]]/client.tsx` (JobRouterClient)
|
||||
|
||||
- Currently only renders review screens for `AWAITING_REVIEW` / `IN_REVIEW` states — this already works
|
||||
- The edit endpoint transitions the job to `AWAITING_REVIEW`, so existing routing handles it
|
||||
|
||||
**One adjustment needed:** If the user edited metadata (artist/title), the screens worker needs to run before or after review. Two options:
|
||||
|
||||
- **Option A (simpler):** Edit endpoint triggers screens worker immediately after resetting state. Screens regenerate in background while user reviews lyrics. By the time review is submitted, screens should be ready. The existing coordination logic (screens_progress check) handles this.
|
||||
|
||||
- **Option B:** Defer screen regeneration to after review submission, same as initial flow. Slightly slower end-to-end but no parallel coordination concerns.
|
||||
|
||||
**Recommendation:** Option A — trigger screens worker during edit if metadata changed. The 30-second screen generation will finish well before the user completes their review edits.
|
||||
|
||||
### Phase 6: Testing
|
||||
|
||||
**Backend unit tests:**
|
||||
- `test_edit_completed_track.py`:
|
||||
- Happy path: COMPLETE job → edit → state becomes AWAITING_REVIEW
|
||||
- With metadata: artist/title updated, screens cleared
|
||||
- Without metadata: artist/title unchanged, screens preserved
|
||||
- Auth: owner can edit, non-owner gets 403
|
||||
- State guard: non-COMPLETE jobs rejected
|
||||
- Cleanup: verify YouTube/Dropbox/GDrive/GCS deletion called
|
||||
- Brand code: verify recycled during cleanup
|
||||
- Edit count: incremented correctly
|
||||
- Timeline: event logged
|
||||
|
||||
**Frontend tests:**
|
||||
- EditTrackModal renders correctly
|
||||
- Toggle shows/hides metadata fields
|
||||
- Confirm calls API with correct payload
|
||||
- Loading state during API call
|
||||
- Redirect to review on success
|
||||
- Error display on failure
|
||||
|
||||
**E2E production test:**
|
||||
- Create job → complete → edit → re-review → verify new outputs
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
### New Files
|
||||
- `frontend/components/job/EditTrackModal.tsx` — Confirmation modal
|
||||
- `backend/tests/test_edit_completed_track.py` — Backend tests
|
||||
|
||||
### Modified Files
|
||||
- `backend/api/routes/jobs.py` — Add edit endpoint (or create `edit.py`)
|
||||
- `backend/models/job.py` — Add `edit_count` field, update STATE_TRANSITIONS
|
||||
- `frontend/lib/api.ts` — Add `editCompletedTrack()` method
|
||||
- `frontend/app/app/jobs/[[...slug]]/client.tsx` — Add Edit button to completed job view
|
||||
|
||||
### No Changes Needed
|
||||
- `backend/workers/render_video_worker.py` — Already reads current state_data
|
||||
- `backend/workers/video_worker_orchestrator.py` — Already allocates new brand code, clears outputs_deleted_at
|
||||
- `backend/workers/screens_worker.py` — Already handles missing screens
|
||||
- `backend/services/brand_code_service.py` — Allocation/recycling already works
|
||||
- `frontend/components/lyrics-review/LyricsAnalyzer.tsx` — Reused as-is
|
||||
- `frontend/components/instrumental-review/InstrumentalSelector.tsx` — Reused as-is
|
||||
|
||||
## Sequence Diagram
|
||||
|
||||
```
|
||||
User Frontend Backend Workers
|
||||
| | | |
|
||||
|-- Click "Edit" ----->| | |
|
||||
| |-- Show modal ------->| |
|
||||
|-- Confirm edit ----->| | |
|
||||
| |-- POST /edit ------->| |
|
||||
| | |-- Delete YouTube --->|
|
||||
| | |-- Delete Dropbox --->|
|
||||
| | |-- Delete GDrive ---->|
|
||||
| | |-- Delete GCS ------->|
|
||||
| | |-- Recycle brand code |
|
||||
| | |-- Reset state ------>|
|
||||
| | |-- Issue review token |
|
||||
| | |-- (if metadata changed:
|
||||
| | | trigger screens worker)
|
||||
| |<-- review_url -------| |
|
||||
|<-- Redirect to review| | |
|
||||
| | | |
|
||||
|-- Edit lyrics ------>| | |
|
||||
|-- Select instrumental| | |
|
||||
|-- Submit review ---->| | |
|
||||
| |-- POST /complete --->| |
|
||||
| | |-- Trigger render --->|
|
||||
| | | |-- Render video
|
||||
| | | |-- Encode formats
|
||||
| | | |-- Allocate brand code
|
||||
| | | |-- Upload YouTube
|
||||
| | | |-- Upload Dropbox
|
||||
| | | |-- Upload GDrive
|
||||
| | | |-- Clear outputs_deleted_at
|
||||
| | |<-- COMPLETE ---------|
|
||||
|<-- Job complete -----| | |
|
||||
```
|
||||
|
||||
## Risk Assessment
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|------------|
|
||||
| Cleanup fails mid-way (e.g., YouTube deleted but Dropbox fails) | Don't reset job state on critical failure. User sees error, job stays COMPLETE with partial cleanup. Admin can investigate. |
|
||||
| User abandons review after edit (outputs deleted, never re-submitted) | Job sits in AWAITING_REVIEW. Same as any unreviewed job. Could add reminder email after 24h. |
|
||||
| Race condition: two edit requests simultaneously | Use Firestore transaction for state transition. Second request fails validation (job no longer COMPLETE). |
|
||||
| Screens not ready when user submits review quickly | Existing coordination logic in pipeline handles this — render worker waits for screens_complete flag. |
|
||||
@@ -0,0 +1,464 @@
|
||||
# Lyrics Review Session Backup & Restore
|
||||
|
||||
**Date:** 2026-03-07
|
||||
**Branch:** `feat/sess-20260307-2332-lyrics-review-sessions`
|
||||
**Status:** Planning
|
||||
|
||||
## Problem
|
||||
|
||||
The lyrics review process can take 1+ hours for difficult songs. Currently, progress is saved to browser localStorage using a fragile key based on a hash of the first segment's text. This has several issues:
|
||||
|
||||
1. **Fragile matching** — hash of first segment text can collide or mismatch across jobs
|
||||
2. **Browser-local only** — lost on browser clear, different device, or incognito
|
||||
3. **No history** — only stores the latest state, no way to browse previous sessions
|
||||
4. **Confusing restore UX** — bare `window.confirm()` dialog with no context about what's being restored
|
||||
5. **No cross-job restore** — can't apply edits from a previous job to a new one (needed for style-change redeliveries)
|
||||
|
||||
## Solution Overview
|
||||
|
||||
Server-side review session storage with automatic periodic backup, rich restore UI, and cross-job session search.
|
||||
|
||||
### Phases
|
||||
|
||||
| Phase | Scope | Description |
|
||||
|-------|-------|-------------|
|
||||
| 1 | Backend API + storage | Firestore subcollection, save/list/get endpoints |
|
||||
| 2 | Auto-save from frontend | Periodic backup (60s interval, on preview, on dirty changes) |
|
||||
| 3 | Restore UI | Session browser with edit preview, auto-prompt on load |
|
||||
| 4 | Cross-job restore | Search sessions across jobs, duration mismatch warning |
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Backend API + Storage
|
||||
|
||||
### Data Model
|
||||
|
||||
Store sessions in a Firestore **subcollection**: `jobs/{jobId}/review_sessions/{sessionId}`
|
||||
|
||||
This follows the existing pattern used for worker logs (`jobs/{jobId}/logs/{logId}`).
|
||||
|
||||
#### `ReviewSession` document schema
|
||||
|
||||
```python
|
||||
{
|
||||
"session_id": str, # Auto-generated document ID
|
||||
"job_id": str, # Parent job ID (denormalized for cross-job queries)
|
||||
"user_email": str, # Who created this session
|
||||
"created_at": datetime, # First save timestamp
|
||||
"updated_at": datetime, # Last save timestamp
|
||||
"edit_count": int, # Number of edits in this session
|
||||
"is_auto_save": bool, # True for periodic auto-saves, False for manual saves
|
||||
"trigger": str, # "auto" | "preview" | "manual"
|
||||
"audio_duration_seconds": float | None, # Input audio duration (for cross-job matching)
|
||||
"artist": str | None, # From correction_data.metadata
|
||||
"title": str | None, # From correction_data.metadata
|
||||
|
||||
# Summary for list view (avoid loading full correction_data)
|
||||
"summary": {
|
||||
"total_segments": int,
|
||||
"total_words": int,
|
||||
"corrections_made": int,
|
||||
"changed_words": [ # First N changed words for preview
|
||||
{"original": str, "corrected": str, "segment_index": int}
|
||||
],
|
||||
},
|
||||
|
||||
# Full correction data (stored in GCS, NOT in Firestore doc)
|
||||
"correction_data_gcs_path": str, # "jobs/{jobId}/review_sessions/{sessionId}.json"
|
||||
}
|
||||
```
|
||||
|
||||
**Why GCS for correction_data?** CorrectionData can be large (100KB+). Firestore has a 1MB document limit, and storing large blobs in Firestore is inefficient for reads/writes. The summary field provides enough info for list views without loading full data.
|
||||
|
||||
#### Store audio duration on Job
|
||||
|
||||
Add `input_audio_duration_seconds: Optional[float]` to the `Job` model. Populate it during job creation (audio worker already has access to ffprobe). This enables cross-job duration comparison without re-computing.
|
||||
|
||||
### API Endpoints
|
||||
|
||||
All under the existing review router (`/api/review/{job_id}/...`), using the existing `require_review_auth` dependency.
|
||||
|
||||
#### `POST /api/review/{job_id}/sessions`
|
||||
|
||||
Save a review session snapshot.
|
||||
|
||||
**Request body:**
|
||||
```json
|
||||
{
|
||||
"correction_data": { ... },
|
||||
"edit_count": 42,
|
||||
"trigger": "auto",
|
||||
"summary": {
|
||||
"total_segments": 15,
|
||||
"total_words": 230,
|
||||
"corrections_made": 12,
|
||||
"changed_words": [
|
||||
{"original": "world", "corrected": "word", "segment_index": 3}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Response:** `{ "session_id": "abc123", "created_at": "..." }`
|
||||
|
||||
**Logic:**
|
||||
1. Upload `correction_data` to GCS at `jobs/{jobId}/review_sessions/{sessionId}.json`
|
||||
2. Create Firestore subcollection document with metadata + summary
|
||||
3. Denormalize `job_id`, `artist`, `title`, `audio_duration_seconds` from parent job
|
||||
|
||||
#### `GET /api/review/{job_id}/sessions`
|
||||
|
||||
List all sessions for a job (metadata only, no correction_data).
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"sessions": [
|
||||
{
|
||||
"session_id": "abc123",
|
||||
"created_at": "2026-03-07T12:00:00Z",
|
||||
"updated_at": "2026-03-07T12:15:00Z",
|
||||
"edit_count": 42,
|
||||
"trigger": "auto",
|
||||
"summary": { ... },
|
||||
"user_email": "andrew@..."
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Ordered by `updated_at` descending. No pagination needed initially (unlikely to exceed 50 sessions per job).
|
||||
|
||||
#### `GET /api/review/{job_id}/sessions/{session_id}`
|
||||
|
||||
Get full session data (loads correction_data from GCS).
|
||||
|
||||
**Response:** Full session document + `correction_data` from GCS.
|
||||
|
||||
#### `DELETE /api/review/{job_id}/sessions/{session_id}`
|
||||
|
||||
Delete a session (admin only). Removes both Firestore doc and GCS file.
|
||||
|
||||
#### `GET /api/review/sessions/search` (Phase 4)
|
||||
|
||||
Cross-job session search. Requires admin auth.
|
||||
|
||||
**Query params:** `?q=<search>&limit=20`
|
||||
|
||||
Search by artist, title, or job_id across all jobs. Uses Firestore collection group query on `review_sessions`.
|
||||
|
||||
**Response:** Same as list endpoint but includes `job_id`, `artist`, `title` per session.
|
||||
|
||||
### Backend Implementation Files
|
||||
|
||||
| File | Changes |
|
||||
|------|---------|
|
||||
| `backend/models/review_session.py` | New: `ReviewSession` dataclass |
|
||||
| `backend/models/job.py` | Add `input_audio_duration_seconds` field |
|
||||
| `backend/services/firestore_service.py` | Add session CRUD methods using subcollection pattern |
|
||||
| `backend/api/routes/review.py` | Add session endpoints |
|
||||
| `backend/workers/audio_worker.py` | Store audio duration on job after ffprobe |
|
||||
|
||||
### Cleanup / Retention
|
||||
|
||||
- Auto-save sessions older than 90 days: eligible for cleanup (can add TTL field like worker logs)
|
||||
- Manual/preview-triggered sessions: kept indefinitely
|
||||
- When a job is deleted, cascade delete its review_sessions subcollection
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Auto-Save from Frontend
|
||||
|
||||
### Save Strategy
|
||||
|
||||
Replace the current localStorage-on-every-edit approach with a smarter dual strategy:
|
||||
|
||||
1. **localStorage** — continues to save on every edit (instant, for crash recovery within same browser)
|
||||
2. **Server backup** — periodic saves to the backend API
|
||||
|
||||
### Server Backup Triggers
|
||||
|
||||
| Trigger | Condition | `trigger` field |
|
||||
|---------|-----------|-----------------|
|
||||
| Periodic timer | Every 60 seconds, IF at least 1 edit since last backup | `"auto"` |
|
||||
| Preview video | When user generates a preview video | `"preview"` |
|
||||
| Page unload | `beforeunload` event, IF dirty since last backup | `"auto"` |
|
||||
| Manual save | User clicks explicit "Save Progress" button | `"manual"` |
|
||||
|
||||
### Dirty Tracking
|
||||
|
||||
Track a `lastBackupEditCount` ref. Compare against current `history.length` to determine if there are new edits since last backup.
|
||||
|
||||
### Implementation
|
||||
|
||||
New custom hook: `useReviewSessionAutoSave()`
|
||||
|
||||
```typescript
|
||||
// frontend/hooks/use-review-session-autosave.ts
|
||||
|
||||
function useReviewSessionAutoSave({
|
||||
jobId: string,
|
||||
data: CorrectionData,
|
||||
initialData: CorrectionData,
|
||||
historyLength: number,
|
||||
isReadOnly: boolean,
|
||||
apiClient: ReviewApiClient,
|
||||
}) {
|
||||
// Track last backup state
|
||||
const lastBackupEditCount = useRef(0)
|
||||
|
||||
// Compute summary from data diff (changed words, counts)
|
||||
const computeSummary = useCallback(...)
|
||||
|
||||
// Save function (called by timer, preview trigger, etc.)
|
||||
const saveSession = useCallback(async (trigger: string) => {
|
||||
if (historyLength <= 1) return // No edits yet
|
||||
if (historyLength === lastBackupEditCount.current) return // No new edits
|
||||
|
||||
await apiClient.saveReviewSession(jobId, {
|
||||
correction_data: data,
|
||||
edit_count: historyLength - 1,
|
||||
trigger,
|
||||
summary: computeSummary(initialData, data),
|
||||
})
|
||||
|
||||
lastBackupEditCount.current = historyLength
|
||||
}, [data, historyLength, ...])
|
||||
|
||||
// 60-second interval
|
||||
useEffect(() => {
|
||||
if (isReadOnly) return
|
||||
const timer = setInterval(() => saveSession("auto"), 60_000)
|
||||
return () => clearInterval(timer)
|
||||
}, [saveSession, isReadOnly])
|
||||
|
||||
// beforeunload
|
||||
useEffect(() => {
|
||||
const handler = () => saveSession("auto")
|
||||
window.addEventListener("beforeunload", handler)
|
||||
return () => window.removeEventListener("beforeunload", handler)
|
||||
}, [saveSession])
|
||||
|
||||
return { saveSession } // Expose for preview trigger
|
||||
}
|
||||
```
|
||||
|
||||
### Frontend API Client Additions
|
||||
|
||||
```typescript
|
||||
// In frontend/lib/api.ts - lyricsReviewApi
|
||||
|
||||
async saveReviewSession(jobId, data): Promise<{ session_id: string }>
|
||||
async listReviewSessions(jobId): Promise<{ sessions: ReviewSession[] }>
|
||||
async getReviewSession(jobId, sessionId): Promise<ReviewSessionFull>
|
||||
async deleteReviewSession(jobId, sessionId): Promise<void>
|
||||
async searchReviewSessions(query): Promise<{ sessions: ReviewSession[] }> // Phase 4
|
||||
```
|
||||
|
||||
### Frontend Files
|
||||
|
||||
| File | Changes |
|
||||
|------|---------|
|
||||
| `frontend/hooks/use-review-session-autosave.ts` | New: auto-save hook |
|
||||
| `frontend/lib/api.ts` | Add session API methods |
|
||||
| `frontend/lib/lyrics-review/types.ts` | Add `ReviewSession`, `ReviewSessionSummary` types |
|
||||
| `frontend/components/lyrics-review/LyricsAnalyzer.tsx` | Wire up auto-save hook, add "Save Progress" button |
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Restore UI
|
||||
|
||||
### Behavior on Load
|
||||
|
||||
When `LyricsAnalyzer` mounts:
|
||||
|
||||
1. Call `GET /api/review/{job_id}/sessions` to check for saved sessions
|
||||
2. **If sessions exist**: show the Session Restore dialog (replaces the old `window.confirm`)
|
||||
3. **If no sessions**: proceed normally (also check localStorage as fallback for backward compat)
|
||||
|
||||
### Session Restore Dialog
|
||||
|
||||
A modal dialog with a split-pane layout:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Saved Review Sessions [×] │
|
||||
├───────────────────────┬─────────────────────────────────┤
|
||||
│ Session List │ Edit Preview │
|
||||
│ │ │
|
||||
│ ▸ Mar 7, 2:15 PM │ Segment 3: │
|
||||
│ 42 edits · preview │ "hello world" → "hello word" │
|
||||
│ [Most recent] │ │
|
||||
│ │ Segment 7: │
|
||||
│ ▸ Mar 7, 1:30 PM │ "singing loud" → "singing out"│
|
||||
│ 38 edits · auto │ │
|
||||
│ │ Segment 12: │
|
||||
│ ▸ Mar 6, 11:00 PM │ (deleted word "um") │
|
||||
│ 15 edits · auto │ │
|
||||
│ │ ... +39 more changes │
|
||||
│ │ │
|
||||
├───────────────────────┴─────────────────────────────────┤
|
||||
│ [Start Fresh] [Restore Selected] │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
#### Session List (left pane)
|
||||
|
||||
Each session shows:
|
||||
- Date/time (relative: "2 hours ago", absolute on hover)
|
||||
- Edit count
|
||||
- Trigger badge: `auto` / `preview` / `manual`
|
||||
- Selected state (highlight)
|
||||
|
||||
#### Edit Preview (right pane)
|
||||
|
||||
When a session is selected, show a compact diff view:
|
||||
- List of changed words grouped by segment
|
||||
- Show original → corrected text
|
||||
- Color-coded: green for additions, red for deletions, yellow for changes
|
||||
- Scroll if many edits, with a summary count at bottom
|
||||
|
||||
#### Actions
|
||||
|
||||
- **Start Fresh** — dismiss dialog, use initial data (no restore)
|
||||
- **Restore Selected** — load the selected session's full `correction_data`, replace current state
|
||||
|
||||
### "Save Progress" Button & Session Browser
|
||||
|
||||
Add to the LyricsAnalyzer toolbar:
|
||||
- **Save Progress** button (triggers manual save)
|
||||
- **Session History** button — opens the same Session Restore dialog at any time (not just on load)
|
||||
|
||||
### Frontend Files
|
||||
|
||||
| File | Changes |
|
||||
|------|---------|
|
||||
| `frontend/components/lyrics-review/SessionRestoreDialog.tsx` | New: the restore modal |
|
||||
| `frontend/components/lyrics-review/SessionListItem.tsx` | New: session list item component |
|
||||
| `frontend/components/lyrics-review/SessionEditPreview.tsx` | New: edit diff preview |
|
||||
| `frontend/components/lyrics-review/LyricsAnalyzer.tsx` | Mount dialog on load, add toolbar buttons |
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Cross-Job Session Restore
|
||||
|
||||
### Power User Feature
|
||||
|
||||
Add a tab/toggle in the Session Restore dialog: **"This Job"** | **"All Jobs"**
|
||||
|
||||
When "All Jobs" is selected:
|
||||
- Show a search box (search by artist, title, or job ID)
|
||||
- Query `GET /api/review/sessions/search?q=...`
|
||||
- Results show sessions from other jobs with job context (artist - title, job ID)
|
||||
|
||||
### Duration Mismatch Warning
|
||||
|
||||
When restoring from a different job:
|
||||
|
||||
1. Compare `session.audio_duration_seconds` with current job's `audio_duration_seconds`
|
||||
2. If durations differ by more than 2 seconds, show a warning:
|
||||
|
||||
```
|
||||
⚠️ Duration Mismatch
|
||||
|
||||
The selected session is from a track with a different duration:
|
||||
This job: 3:42 (222s)
|
||||
Source session: 4:01 (241s)
|
||||
|
||||
Timing alignment may not match. Word timestamps from the
|
||||
source session will be preserved as-is.
|
||||
|
||||
[Cancel] [Restore Anyway]
|
||||
```
|
||||
|
||||
3. If durations match (within 2s), restore silently
|
||||
|
||||
### Collection Group Index
|
||||
|
||||
Firestore collection group queries require a **composite index** on `review_sessions`:
|
||||
- Fields: `artist` (ASC), `title` (ASC), `updated_at` (DESC)
|
||||
- Add via `firestore.indexes.json` or Pulumi
|
||||
|
||||
### Backend: Search Implementation
|
||||
|
||||
The search endpoint uses Firestore collection group query:
|
||||
|
||||
```python
|
||||
@router.get("/sessions/search")
|
||||
async def search_sessions(q: str, limit: int = 20, auth=Depends(require_admin)):
|
||||
# Collection group query across all jobs' review_sessions
|
||||
sessions_ref = db.collection_group("review_sessions")
|
||||
|
||||
# Search by artist OR title containing query (case-insensitive prefix)
|
||||
# Firestore doesn't support LIKE queries, so we use range queries
|
||||
# for prefix matching, or store lowercase variants for matching
|
||||
results = sessions_ref.where("artist_lower", ">=", q.lower())
|
||||
.where("artist_lower", "<=", q.lower() + "\uf8ff")
|
||||
.limit(limit)
|
||||
.get()
|
||||
|
||||
# Also search by title and job_id, merge results
|
||||
...
|
||||
```
|
||||
|
||||
**Note:** Firestore's text search is limited. For the MVP, searching by exact job_id + prefix matching on artist/title should be sufficient. If full-text search is needed later, consider Algolia or a simple in-memory filter on the client after fetching recent sessions.
|
||||
|
||||
### Frontend Files
|
||||
|
||||
| File | Changes |
|
||||
|------|---------|
|
||||
| `frontend/components/lyrics-review/SessionRestoreDialog.tsx` | Add "All Jobs" tab, search input |
|
||||
| `frontend/components/lyrics-review/DurationWarning.tsx` | New: duration mismatch warning |
|
||||
| `frontend/lib/api.ts` | Add `searchReviewSessions()` |
|
||||
|
||||
---
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Backend Tests
|
||||
|
||||
| Test | Type | What |
|
||||
|------|------|------|
|
||||
| `test_review_session_crud.py` | Unit | Create, list, get, delete sessions via Firestore service |
|
||||
| `test_review_session_endpoints.py` | Integration | API endpoint tests with auth |
|
||||
| `test_review_session_gcs.py` | Unit | GCS upload/download of correction data |
|
||||
| `test_audio_duration_storage.py` | Unit | Duration stored on job creation |
|
||||
|
||||
### Frontend Tests
|
||||
|
||||
| Test | Type | What |
|
||||
|------|------|------|
|
||||
| `SessionRestoreDialog.test.tsx` | Unit | Renders session list, selection, restore action |
|
||||
| `SessionEditPreview.test.tsx` | Unit | Diff computation and display |
|
||||
| `use-review-session-autosave.test.ts` | Unit | Timer behavior, dirty tracking, save triggers |
|
||||
| `lyrics-review-sessions.spec.ts` | E2E | Full flow: edit → auto-save → reload → restore |
|
||||
|
||||
---
|
||||
|
||||
## Migration / Backward Compatibility
|
||||
|
||||
1. **localStorage fallback** — keep the existing localStorage load/save as a fallback. If no server sessions exist, check localStorage. Gradually phase out once server sessions are proven reliable.
|
||||
2. **No schema migration needed** — new Firestore subcollection, new GCS paths. No existing data affected.
|
||||
3. **Feature flag** — not needed; server session save is additive. The restore dialog replaces `window.confirm()` which is strictly better.
|
||||
|
||||
---
|
||||
|
||||
## Open Questions
|
||||
|
||||
1. **Session limit per job?** — Should we cap at e.g. 50 sessions per job and auto-prune oldest auto-saves? Probably yes to avoid unbounded growth.
|
||||
2. **Session deduplication** — If user makes 0 additional edits between auto-save intervals, we skip the save (dirty tracking handles this). But should we also deduplicate if the correction_data hasn't actually changed (e.g. undo then redo)?
|
||||
3. **Compression** — CorrectionData JSON can be large. Should we gzip before storing in GCS? Probably not for MVP; GCS handles compression at the storage layer.
|
||||
|
||||
---
|
||||
|
||||
## Estimated Scope
|
||||
|
||||
| Phase | Backend | Frontend | Total |
|
||||
|-------|---------|----------|-------|
|
||||
| 1 | ~300 lines | 0 | Medium |
|
||||
| 2 | 0 | ~150 lines | Small |
|
||||
| 3 | 0 | ~400 lines | Medium |
|
||||
| 4 | ~100 lines | ~200 lines | Medium |
|
||||
| Tests | ~300 lines | ~300 lines | Medium |
|
||||
|
||||
Phases 1-3 form the core feature. Phase 4 (cross-job) can be deferred to a follow-up PR if needed.
|
||||
@@ -0,0 +1,95 @@
|
||||
# Edit Input Audio — Master Plan
|
||||
|
||||
**Date:** 2026-03-08
|
||||
**Branch:** `feat/sess-20260308-1232-edit-input-audio`
|
||||
**Status:** Planning
|
||||
|
||||
## 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:** Planning
|
||||
**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.
|
||||
@@ -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(),
|
||||
|
||||
@@ -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} />
|
||||
}
|
||||
|
||||
@@ -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])
|
||||
|
||||
@@ -134,6 +134,72 @@ describe('OutputLinks', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('visibility change button', () => {
|
||||
it('shows "Make Public" for private complete jobs', () => {
|
||||
const privateJob: Job = {
|
||||
...baseJob,
|
||||
is_private: true,
|
||||
}
|
||||
|
||||
render(<OutputLinks job={privateJob} />)
|
||||
|
||||
expect(screen.getByText('Make Public')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Make Private')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows "Make Private" for public complete jobs', () => {
|
||||
const publicJob: Job = {
|
||||
...baseJob,
|
||||
is_private: false,
|
||||
}
|
||||
|
||||
render(<OutputLinks job={publicJob} />)
|
||||
|
||||
expect(screen.getByText('Make Private')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Make Public')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides button when visibility change is in progress', () => {
|
||||
const inProgressJob: Job = {
|
||||
...baseJob,
|
||||
state_data: {
|
||||
...baseJob.state_data,
|
||||
visibility_change_in_progress: true,
|
||||
},
|
||||
}
|
||||
|
||||
render(<OutputLinks job={inProgressJob} />)
|
||||
|
||||
expect(screen.queryByText('Make Public')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Make Private')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides button for non-complete jobs', () => {
|
||||
const pendingJob: Job = {
|
||||
...baseJob,
|
||||
status: 'generating_video',
|
||||
}
|
||||
|
||||
render(<OutputLinks job={pendingJob} />)
|
||||
|
||||
expect(screen.queryByText('Make Public')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Make Private')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides button for tenant jobs', () => {
|
||||
const { useTenant } = require('@/lib/tenant')
|
||||
useTenant.mockReturnValue({
|
||||
tenantId: 'vocalstar',
|
||||
features: { youtube_upload: true, dropbox_upload: true },
|
||||
})
|
||||
|
||||
render(<OutputLinks job={baseJob} />)
|
||||
|
||||
expect(screen.queryByText('Make Public')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Make Private')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('shows nothing when job has no file_urls and no state_data (non-admin)', () => {
|
||||
// Reset to non-admin user
|
||||
@@ -142,16 +208,47 @@ describe('OutputLinks', () => {
|
||||
|
||||
const emptyJob: Job = {
|
||||
...baseJob,
|
||||
status: 'generating_video',
|
||||
file_urls: undefined,
|
||||
state_data: undefined,
|
||||
}
|
||||
|
||||
render(<OutputLinks job={emptyJob} />)
|
||||
|
||||
// Should show "No outputs available yet" for non-admin
|
||||
// Should show "No outputs available yet" for non-admin, non-complete job
|
||||
expect(screen.getByText('No outputs available yet')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows Edit button for completed jobs with outputs', () => {
|
||||
render(<OutputLinks job={baseJob} />)
|
||||
|
||||
expect(screen.getByText('Edit')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides Edit button when outputs are deleted', () => {
|
||||
const deletedJob: Job = {
|
||||
...baseJob,
|
||||
outputs_deleted_at: '2026-01-15T10:00:00Z',
|
||||
}
|
||||
|
||||
render(<OutputLinks job={deletedJob} />)
|
||||
|
||||
expect(screen.queryByText('Edit')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides Edit button for non-complete jobs', () => {
|
||||
const pendingJob: Job = {
|
||||
...baseJob,
|
||||
status: 'pending',
|
||||
}
|
||||
|
||||
render(<OutputLinks job={pendingJob} />)
|
||||
|
||||
expect(screen.queryByText('Edit')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('handles partial file_urls gracefully', () => {
|
||||
// Reset to non-admin user
|
||||
const { useAuth } = require('@/lib/auth')
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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>
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { api, Job } from "@/lib/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Loader2 } from "lucide-react"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
|
||||
interface EditTrackModalProps {
|
||||
job: Job
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onEditStarted?: () => void
|
||||
}
|
||||
|
||||
export function EditTrackModal({ job, open, onOpenChange, onEditStarted }: EditTrackModalProps) {
|
||||
const [updateMetadata, setUpdateMetadata] = useState(false)
|
||||
const [artist, setArtist] = useState(job.artist || "")
|
||||
const [title, setTitle] = useState(job.title || "")
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const handleConfirm = async () => {
|
||||
setIsSubmitting(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const updates: { artist?: string; title?: string } = {}
|
||||
if (updateMetadata) {
|
||||
const trimmedArtist = artist?.trim()
|
||||
const trimmedTitle = title?.trim()
|
||||
if (trimmedArtist && trimmedArtist !== job.artist) updates.artist = trimmedArtist
|
||||
if (trimmedTitle && trimmedTitle !== job.title) updates.title = trimmedTitle
|
||||
}
|
||||
|
||||
const result = await api.editCompletedTrack(job.job_id, updates)
|
||||
|
||||
onOpenChange(false)
|
||||
|
||||
// Navigate to review screen using server-provided URL
|
||||
if (result.review_url) {
|
||||
window.location.hash = result.review_url.replace(/^\/app\/jobs#/, '')
|
||||
} else {
|
||||
window.location.hash = `/${job.job_id}/review`
|
||||
}
|
||||
|
||||
onEditStarted?.()
|
||||
} catch (err: any) {
|
||||
setError(err.message || "Failed to start edit. Please try again.")
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
if (!isSubmitting) {
|
||||
onOpenChange(newOpen)
|
||||
if (!newOpen) {
|
||||
setError(null)
|
||||
setUpdateMetadata(false)
|
||||
setArtist(job.artist || "")
|
||||
setTitle(job.title || "")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[480px]" onClick={(e) => e.stopPropagation()}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit Completed Track</DialogTitle>
|
||||
<DialogDescription>
|
||||
This will remove the current video from YouTube, Dropbox, and Google Drive.
|
||||
After you complete the review again, a new version will be rendered and re-distributed.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="update-metadata"
|
||||
checked={updateMetadata}
|
||||
onChange={(e) => setUpdateMetadata(e.target.checked)}
|
||||
className="rounded"
|
||||
/>
|
||||
<Label htmlFor="update-metadata" className="cursor-pointer">
|
||||
I need to update the artist or title
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{updateMetadata && (
|
||||
<div className="grid gap-3 pl-6">
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="edit-artist" className="text-right">
|
||||
Artist
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-artist"
|
||||
value={artist}
|
||||
onChange={(e) => setArtist(e.target.value)}
|
||||
className="col-span-3"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="edit-title" className="text-right">
|
||||
Title
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
className="col-span-3"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-red-500">{error}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleConfirm}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Cleaning up...
|
||||
</>
|
||||
) : (
|
||||
"Confirm & Edit"
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -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 {
|
||||
@@ -200,7 +208,15 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError) {
|
||||
setSubmitError(err.message)
|
||||
if (err.message.includes("Search expired") || (err.status === 404 && audioSource === "search")) {
|
||||
// Search session expired — clear it and send user back to re-search
|
||||
setSearchSessionId(null)
|
||||
setSelectedResultIndex(null)
|
||||
setStep(2)
|
||||
setSubmitError("Your search results expired. Please search again — your song info is still saved.")
|
||||
} else {
|
||||
setSubmitError(err.message)
|
||||
}
|
||||
} else {
|
||||
setSubmitError("Failed to start processing. Please try again.")
|
||||
}
|
||||
@@ -227,6 +243,7 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
setDisplayArtist("")
|
||||
setDisplayTitle("")
|
||||
setIsPrivate(false)
|
||||
setRequiresAudioEdit(false)
|
||||
setKaraokeBackground(null)
|
||||
setIntroBackground(null)
|
||||
setColorOverrides({})
|
||||
@@ -293,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">
|
||||
@@ -412,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)' }}
|
||||
@@ -459,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}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -187,7 +199,7 @@ export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
|
||||
{/* Output links for completed jobs, or admin link for admins on any job */}
|
||||
{(isComplete || isAdmin) && (
|
||||
<div className="mt-2">
|
||||
<OutputLinks job={job} />
|
||||
<OutputLinks job={job} onJobUpdated={onRefresh} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useRef, useCallback, useEffect, useState } from "react"
|
||||
import { api, adminApi, Job } from "@/lib/api"
|
||||
import { useTenant } from "@/lib/tenant"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Download, Loader2, ExternalLink, FolderOpen, Copy, Mail, Settings } from "lucide-react"
|
||||
import { Download, Loader2, ExternalLink, FolderOpen, Copy, Mail, Settings, Lock, Globe, Pencil } from "lucide-react"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import {
|
||||
Dialog,
|
||||
@@ -14,14 +14,26 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { EditTrackModal } from "./EditTrackModal"
|
||||
|
||||
interface OutputLinksProps {
|
||||
job: Job
|
||||
onJobUpdated?: () => void
|
||||
}
|
||||
|
||||
export function OutputLinks({ job }: OutputLinksProps) {
|
||||
export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
// Use file_urls from job directly - no API call needed
|
||||
const downloadUrls = job.file_urls || null
|
||||
// Use state_data from job directly - no API call needed
|
||||
@@ -35,6 +47,9 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
const [emailInput, setEmailInput] = useState("")
|
||||
const [isSendingEmail, setIsSendingEmail] = useState(false)
|
||||
const [emailSent, setEmailSent] = useState(false)
|
||||
const [showVisibilityDialog, setShowVisibilityDialog] = useState(false)
|
||||
const [isChangingVisibility, setIsChangingVisibility] = useState(false)
|
||||
const [showEditModal, setShowEditModal] = useState(false)
|
||||
const copyTimeoutRef = useRef<NodeJS.Timeout | null>(null)
|
||||
const messageTimeoutRef = useRef<NodeJS.Timeout | null>(null)
|
||||
const emailTimeoutRef = useRef<NodeJS.Timeout | null>(null)
|
||||
@@ -49,7 +64,7 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
}, [])
|
||||
|
||||
const { user } = useAuth()
|
||||
const { features } = useTenant()
|
||||
const { features, tenantId } = useTenant()
|
||||
const isAdmin = user?.role === 'admin'
|
||||
|
||||
// Check if outputs have been deleted by admin
|
||||
@@ -59,6 +74,11 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
const showYoutubeLink = features.youtube_upload && youtubeUrl && !outputsDeleted
|
||||
const showDropboxLink = features.dropbox_upload && dropboxUrl && !outputsDeleted
|
||||
|
||||
// Visibility change: available for completed consumer jobs (not tenant)
|
||||
const isPrivate = !!job.is_private
|
||||
const visibilityChangeInProgress = !!job.state_data?.visibility_change_in_progress
|
||||
const canChangeVisibility = job.status === "complete" && !tenantId && !visibilityChangeInProgress
|
||||
|
||||
const copyToClipboard = useCallback(async (url: string) => {
|
||||
// Check if clipboard API is available
|
||||
if (!navigator?.clipboard?.writeText) {
|
||||
@@ -138,6 +158,22 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
}
|
||||
}, [job.job_id, emailInput])
|
||||
|
||||
const handleChangeVisibility = useCallback(async () => {
|
||||
const targetVisibility = isPrivate ? 'public' : 'private'
|
||||
setIsChangingVisibility(true)
|
||||
setShowVisibilityDialog(false)
|
||||
|
||||
try {
|
||||
await api.changeVisibility(job.job_id, targetVisibility)
|
||||
onJobUpdated?.()
|
||||
} catch (err) {
|
||||
console.error("Failed to change visibility:", err)
|
||||
alert(`Failed to change visibility. ${err instanceof Error ? err.message : 'Please try again.'}`)
|
||||
} finally {
|
||||
setIsChangingVisibility(false)
|
||||
}
|
||||
}, [job.job_id, isPrivate, onJobUpdated])
|
||||
|
||||
const hasOutputs = showYoutubeLink || showDropboxLink || (downloadUrls && Object.keys(downloadUrls).length > 0)
|
||||
|
||||
// Check if we have any downloads (and outputs haven't been deleted)
|
||||
@@ -155,7 +191,7 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{/* Links, Downloads, and Admin Tools - all in one row */}
|
||||
{(hasDownloads || hasExternalLinks || isAdmin) && (
|
||||
{(hasDownloads || hasExternalLinks || isAdmin || canChangeVisibility) && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{/* Links first */}
|
||||
{hasExternalLinks && (
|
||||
@@ -265,6 +301,29 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Change Visibility Button */}
|
||||
{canChangeVisibility && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => { e.stopPropagation(); setShowVisibilityDialog(true) }}
|
||||
disabled={isChangingVisibility}
|
||||
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-[#252525] hover:bg-[#333333] text-[var(--text)] border border-[var(--card-border)] transition-colors disabled:opacity-50"
|
||||
title={isPrivate ? "Make this track public" : "Make this track private"}
|
||||
>
|
||||
{isChangingVisibility ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin" />
|
||||
) : isPrivate ? (
|
||||
<Globe className="w-3 h-3" />
|
||||
) : (
|
||||
<Lock className="w-3 h-3" />
|
||||
)}
|
||||
{isChangingVisibility
|
||||
? (isPrivate ? "Making Public..." : "Making Private...")
|
||||
: (isPrivate ? "Make Public" : "Make Private")
|
||||
}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Admin Email Tools (only when job has outputs) */}
|
||||
{isAdmin && hasOutputs && (
|
||||
<div className="flex">
|
||||
@@ -295,6 +354,19 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Edit Track (visible when job is complete and has outputs) */}
|
||||
{job.status === "complete" && !outputsDeleted && hasOutputs && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => { e.stopPropagation(); setShowEditModal(true) }}
|
||||
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-amber-600 hover:bg-amber-500 text-white transition-colors"
|
||||
title="Edit lyrics, instrumental, or metadata"
|
||||
>
|
||||
<Pencil className="w-3 h-3" />
|
||||
Edit
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Admin Link (always visible for admins) */}
|
||||
{isAdmin && (
|
||||
<a
|
||||
@@ -310,7 +382,7 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!hasOutputs && !isAdmin && (
|
||||
{!hasOutputs && !isAdmin && !canChangeVisibility && (
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>No outputs available yet</p>
|
||||
)}
|
||||
|
||||
@@ -371,6 +443,64 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Change Visibility Confirmation Dialog */}
|
||||
<AlertDialog open={showVisibilityDialog} onOpenChange={setShowVisibilityDialog}>
|
||||
<AlertDialogContent onClick={(e) => e.stopPropagation()}>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{isPrivate ? "Make This Track Public?" : "Make This Track Private?"}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription asChild>
|
||||
<div className="space-y-3">
|
||||
{isPrivate ? (
|
||||
<>
|
||||
<p>This will:</p>
|
||||
<ul className="list-disc pl-5 space-y-1">
|
||||
<li>Remove any custom styling (backgrounds, colors) and reset to the standard Nomad Karaoke theme</li>
|
||||
<li>Regenerate title and end screens</li>
|
||||
<li>Re-render the karaoke video with default branding</li>
|
||||
<li>Publish to YouTube, Google Drive, and Dropbox</li>
|
||||
</ul>
|
||||
<p>This process takes approximately 15-30 minutes. You'll receive an email when it's complete.</p>
|
||||
<p className="font-medium" style={{ color: 'var(--text)' }}>
|
||||
Any custom styling you applied will be permanently removed.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p>This will:</p>
|
||||
<ul className="list-disc pl-5 space-y-1">
|
||||
<li>Remove the video from YouTube</li>
|
||||
<li>Remove files from Google Drive</li>
|
||||
<li>Move Dropbox files from the public folder to the private folder</li>
|
||||
<li>Assign a new private brand code</li>
|
||||
</ul>
|
||||
<p>The video content won't change. This usually takes about 1-2 minutes.</p>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
You can change it back to public later, but that will require re-rendering the video (~15-30 minutes).
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleChangeVisibility}>
|
||||
{isPrivate ? "Make Public" : "Make Private"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* Edit Track Modal */}
|
||||
<EditTrackModal
|
||||
job={job}
|
||||
open={showEditModal}
|
||||
onOpenChange={setShowEditModal}
|
||||
onEditStarted={onJobUpdated}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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([])
|
||||
})
|
||||
})
|
||||
@@ -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 } 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,86 @@ 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="rounded-lg border p-5 space-y-4"
|
||||
style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}
|
||||
>
|
||||
<h3 className="text-base font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Do you want to review and edit this audio before it gets transcribed?
|
||||
</h3>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
Trim, cut, mute, or join sections of the downloaded audio before lyrics are transcribed and synced.
|
||||
Useful for trimming intro/outro from a live version, shortening a lengthy outro, etc.
|
||||
</p>
|
||||
|
||||
<div className="flex flex-col sm:flex-row gap-3 pt-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleAudioEditAnswer(false)}
|
||||
className="flex-1 rounded-lg border-2 p-4 transition-all text-center border-[var(--card-border)] hover:border-[var(--text-muted)]"
|
||||
>
|
||||
<span className="font-semibold" style={{ color: 'var(--text)' }}>No, use as-is</span>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>Proceed directly to transcription</p>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleAudioEditAnswer(true)}
|
||||
className="flex-1 rounded-lg border-2 p-4 transition-all text-center border-[var(--card-border)] hover:border-[var(--brand-pink)]"
|
||||
>
|
||||
<span className="font-semibold" style={{ color: 'var(--text)' }}>Yes, I'll edit it first</span>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>Trim, cut, or mute before processing</p>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-4">
|
||||
@@ -206,6 +390,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 +573,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 +594,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 +994,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'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 (
|
||||
|
||||
@@ -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'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>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback, useMemo, memo } from 'react'
|
||||
import { useState, useEffect, useCallback, useMemo, useRef, memo } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Video, Check, CheckCircle2 } from 'lucide-react'
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
ModalContent,
|
||||
} from '@/lib/lyrics-review/types'
|
||||
import type { EditLog, EditLogEntry, EditFeedbackReason } from '@/lib/lyrics-review/types'
|
||||
import type { InstrumentalSelectionType } from '@/lib/api'
|
||||
import type { InstrumentalSelectionType, LyricsReviewApiClient } from '@/lib/api'
|
||||
import { lyricsReviewApi } from '@/lib/api'
|
||||
import { cn } from '@/lib/utils'
|
||||
import ReferenceView from './ReferenceView'
|
||||
@@ -48,6 +48,8 @@ import {
|
||||
getModalState,
|
||||
} from '@/lib/lyrics-review/utils/keyboardHandlers'
|
||||
import { createEditLog, addEditEntry, attachFeedback } from '@/lib/lyrics-review/utils/editLog'
|
||||
import { useReviewSessionAutoSave } from '@/hooks/use-review-session-autosave'
|
||||
import SessionRestoreDialog from './SessionRestoreDialog'
|
||||
import Header from './Header'
|
||||
import GapNavigator from './GapNavigator'
|
||||
import { getWordsFromIds } from '@/lib/lyrics-review/utils/wordUtils'
|
||||
@@ -77,6 +79,11 @@ interface ApiClient {
|
||||
}>
|
||||
getPreviewVideoUrl: (hash: string) => string
|
||||
completeReview: () => Promise<{ status: string; job_status: string; message: string }>
|
||||
// Review session methods (optional - available in cloud mode)
|
||||
saveReviewSession?: LyricsReviewApiClient['saveReviewSession']
|
||||
listReviewSessions?: LyricsReviewApiClient['listReviewSessions']
|
||||
getReviewSession?: LyricsReviewApiClient['getReviewSession']
|
||||
deleteReviewSession?: LyricsReviewApiClient['deleteReviewSession']
|
||||
}
|
||||
|
||||
export interface LyricsAnalyzerProps {
|
||||
@@ -150,6 +157,11 @@ export default function LyricsAnalyzer({
|
||||
// Stats panel visibility
|
||||
const [statsVisible, setStatsVisible] = useState(false)
|
||||
|
||||
// Session restore state
|
||||
const [sessionRestoreOpen, setSessionRestoreOpen] = useState(false)
|
||||
const [savedSessions, setSavedSessions] = useState<import('@/lib/api').ReviewSession[]>([])
|
||||
const [sessionsLoading, setSessionsLoading] = useState(false)
|
||||
|
||||
// Advanced mode for transcription view (Simple/Advanced toggle)
|
||||
const [advancedMode, setAdvancedMode] = useState(() => {
|
||||
if (typeof window === 'undefined') return false
|
||||
@@ -197,22 +209,86 @@ export default function LyricsAnalyzer({
|
||||
setHistoryIndex(0)
|
||||
}, [initialData])
|
||||
|
||||
// Load saved data
|
||||
// Load saved sessions on mount - check server first, fall back to localStorage
|
||||
useEffect(() => {
|
||||
const savedData = loadSavedData(initialData)
|
||||
if (savedData && typeof window !== 'undefined' && window.confirm('Found saved progress for this song. Would you like to restore it?')) {
|
||||
setHistory([savedData])
|
||||
setHistoryIndex(0)
|
||||
if (isReadOnly || !apiClient?.listReviewSessions) {
|
||||
// Local mode or read-only: use localStorage fallback
|
||||
const savedData = loadSavedData(initialData)
|
||||
if (savedData && typeof window !== 'undefined' && window.confirm('Found saved progress for this song. Would you like to restore it?')) {
|
||||
setHistory([savedData])
|
||||
setHistoryIndex(0)
|
||||
}
|
||||
return
|
||||
}
|
||||
}, [initialData])
|
||||
|
||||
// Save data
|
||||
// Cloud mode: check for server-side sessions
|
||||
let cancelled = false
|
||||
setSessionsLoading(true)
|
||||
apiClient.listReviewSessions().then(result => {
|
||||
if (cancelled) return
|
||||
setSessionsLoading(false)
|
||||
if (result.sessions.length > 0) {
|
||||
setSavedSessions(result.sessions)
|
||||
setSessionRestoreOpen(true)
|
||||
} else {
|
||||
// Fall back to localStorage if no server sessions
|
||||
const savedData = loadSavedData(initialData)
|
||||
if (savedData && typeof window !== 'undefined' && window.confirm('Found saved progress for this song. Would you like to restore it?')) {
|
||||
setHistory([savedData])
|
||||
setHistoryIndex(0)
|
||||
}
|
||||
}
|
||||
}).catch(() => {
|
||||
if (cancelled) return
|
||||
setSessionsLoading(false)
|
||||
// Fall back to localStorage on error
|
||||
const savedData = loadSavedData(initialData)
|
||||
if (savedData && typeof window !== 'undefined' && window.confirm('Found saved progress for this song. Would you like to restore it?')) {
|
||||
setHistory([savedData])
|
||||
setHistoryIndex(0)
|
||||
}
|
||||
})
|
||||
|
||||
return () => { cancelled = true }
|
||||
}, [initialData, isReadOnly]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Handler for restoring a session from the dialog
|
||||
const handleSessionRestore = useCallback((correctionData: CorrectionData) => {
|
||||
setHistory([correctionData])
|
||||
setHistoryIndex(0)
|
||||
}, [])
|
||||
|
||||
// Handler to open session browser from toolbar
|
||||
const handleOpenSessionBrowser = useCallback(async () => {
|
||||
if (!apiClient?.listReviewSessions) return
|
||||
setSessionsLoading(true)
|
||||
try {
|
||||
const result = await apiClient.listReviewSessions()
|
||||
setSavedSessions(result.sessions)
|
||||
} catch {
|
||||
setSavedSessions([])
|
||||
}
|
||||
setSessionsLoading(false)
|
||||
setSessionRestoreOpen(true)
|
||||
}, [apiClient])
|
||||
|
||||
// Save data (localStorage - instant crash recovery)
|
||||
useEffect(() => {
|
||||
if (!isReadOnly) {
|
||||
saveData(data, initialData)
|
||||
}
|
||||
}, [data, isReadOnly, initialData])
|
||||
|
||||
// Server-side session auto-save (periodic backup)
|
||||
const { saveSession } = useReviewSessionAutoSave({
|
||||
jobId: jobId ?? '',
|
||||
data,
|
||||
initialData,
|
||||
historyLength: history.length,
|
||||
isReadOnly: isReadOnly || !apiClient?.saveReviewSession,
|
||||
apiClient: apiClient as LyricsReviewApiClient,
|
||||
})
|
||||
|
||||
// Flash handler (defined early so gap navigation can use it)
|
||||
const handleFlash = useCallback((type: FlashType, info?: HighlightInfo) => {
|
||||
setFlashingType(null)
|
||||
@@ -766,8 +842,10 @@ export default function LyricsAnalyzer({
|
||||
if (typeof window !== 'undefined' && window.isAudioPlaying && window.toggleAudioPlayback) {
|
||||
window.toggleAudioPlayback()
|
||||
}
|
||||
// Trigger server-side session save on preview (signals completion milestone)
|
||||
saveSession('preview')
|
||||
setIsReviewModalOpen(true)
|
||||
}, [])
|
||||
}, [saveSession])
|
||||
|
||||
// Submit to server (save corrections, don't complete review yet)
|
||||
const handleSubmitToServer = useCallback(async () => {
|
||||
@@ -1191,6 +1269,25 @@ export default function LyricsAnalyzer({
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{apiClient?.saveReviewSession && (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => saveSession('manual')}
|
||||
disabled={history.length <= 1}
|
||||
>
|
||||
Save Progress
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleOpenSessionBrowser}
|
||||
>
|
||||
Session History
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<span className="text-sm text-muted-foreground">Lyrics look good?</span>
|
||||
<Button onClick={handleFinishReview} disabled={isReviewComplete}>
|
||||
{isReviewComplete ? 'Review Complete' : 'Preview Video'}
|
||||
@@ -1323,6 +1420,17 @@ export default function LyricsAnalyzer({
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{apiClient?.saveReviewSession && (
|
||||
<SessionRestoreDialog
|
||||
open={sessionRestoreOpen}
|
||||
onClose={() => setSessionRestoreOpen(false)}
|
||||
onRestore={handleSessionRestore}
|
||||
sessions={savedSessions}
|
||||
apiClient={apiClient as LyricsReviewApiClient}
|
||||
isLoading={sessionsLoading}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Loader2, Clock, Search, AlertTriangle } from 'lucide-react'
|
||||
import type { ReviewSession, ReviewSessionWithData, LyricsReviewApiClient } from '@/lib/api'
|
||||
import type { CorrectionData } from '@/lib/lyrics-review/types'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface SessionRestoreDialogProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onRestore: (data: CorrectionData) => void
|
||||
sessions: ReviewSession[]
|
||||
apiClient: LyricsReviewApiClient
|
||||
currentAudioDuration?: number | null
|
||||
isLoading?: boolean
|
||||
}
|
||||
|
||||
function formatRelativeTime(dateStr: string | null): string {
|
||||
if (!dateStr) return 'Unknown'
|
||||
const date = new Date(dateStr)
|
||||
const now = new Date()
|
||||
const diffMs = now.getTime() - date.getTime()
|
||||
const diffMin = Math.floor(diffMs / 60000)
|
||||
const diffHr = Math.floor(diffMin / 60)
|
||||
const diffDay = Math.floor(diffHr / 24)
|
||||
|
||||
if (diffMin < 1) return 'Just now'
|
||||
if (diffMin < 60) return `${diffMin}m ago`
|
||||
if (diffHr < 24) return `${diffHr}h ago`
|
||||
if (diffDay < 7) return `${diffDay}d ago`
|
||||
return date.toLocaleDateString()
|
||||
}
|
||||
|
||||
function formatAbsoluteTime(dateStr: string | null): string {
|
||||
if (!dateStr) return ''
|
||||
return new Date(dateStr).toLocaleString()
|
||||
}
|
||||
|
||||
function TriggerBadge({ trigger }: { trigger: string }) {
|
||||
const colors: Record<string, string> = {
|
||||
auto: 'bg-gray-100 text-gray-600',
|
||||
preview: 'bg-blue-100 text-blue-700',
|
||||
manual: 'bg-green-100 text-green-700',
|
||||
}
|
||||
return (
|
||||
<span className={cn('px-1.5 py-0.5 rounded text-xs font-medium', colors[trigger] || colors.auto)}>
|
||||
{trigger}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function EditPreview({ session }: { session: ReviewSession }) {
|
||||
const { summary } = session
|
||||
const changedWords = summary?.changed_words || []
|
||||
|
||||
if (changedWords.length === 0) {
|
||||
return (
|
||||
<div className="text-sm text-muted-foreground italic p-4">
|
||||
No word-level changes recorded in this session.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2 p-2 overflow-y-auto max-h-[400px]">
|
||||
<div className="text-xs text-muted-foreground mb-2">
|
||||
{summary.corrections_made} change{summary.corrections_made !== 1 ? 's' : ''} across {summary.total_segments} segments
|
||||
</div>
|
||||
{changedWords.map((change, i) => (
|
||||
<div key={i} className="flex items-start gap-2 text-sm py-1 border-b border-border/50 last:border-0">
|
||||
<span className="text-muted-foreground text-xs min-w-[24px] text-right">
|
||||
S{change.segment_index + 1}
|
||||
</span>
|
||||
<span className="text-red-500 line-through">{change.original}</span>
|
||||
<span className="text-muted-foreground">→</span>
|
||||
<span className="text-green-600 font-medium">{change.corrected}</span>
|
||||
</div>
|
||||
))}
|
||||
{summary.corrections_made > changedWords.length && (
|
||||
<div className="text-xs text-muted-foreground pt-1">
|
||||
+{summary.corrections_made - changedWords.length} more changes
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function SessionRestoreDialog({
|
||||
open,
|
||||
onClose,
|
||||
onRestore,
|
||||
sessions,
|
||||
apiClient,
|
||||
currentAudioDuration,
|
||||
isLoading = false,
|
||||
}: SessionRestoreDialogProps) {
|
||||
const [selectedSessionId, setSelectedSessionId] = useState<string | null>(null)
|
||||
const [isRestoring, setIsRestoring] = useState(false)
|
||||
const [searchMode, setSearchMode] = useState<'this-job' | 'all-jobs'>('this-job')
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [crossJobSessions, setCrossJobSessions] = useState<ReviewSession[]>([])
|
||||
const [isSearching, setIsSearching] = useState(false)
|
||||
const [durationWarning, setDurationWarning] = useState<{ source: number; current: number } | null>(null)
|
||||
|
||||
// Auto-select most recent session
|
||||
useEffect(() => {
|
||||
if (sessions.length > 0 && !selectedSessionId) {
|
||||
setSelectedSessionId(sessions[0].session_id)
|
||||
}
|
||||
}, [sessions, selectedSessionId])
|
||||
|
||||
const displayedSessions = searchMode === 'this-job' ? sessions : crossJobSessions
|
||||
|
||||
const selectedSession = displayedSessions.find(s => s.session_id === selectedSessionId) || null
|
||||
|
||||
const handleSearch = useCallback(async () => {
|
||||
if (!searchQuery.trim()) return
|
||||
setIsSearching(true)
|
||||
try {
|
||||
// Use fetch directly for cross-job search (not part of job-scoped client)
|
||||
const { getAccessToken, API_BASE_URL } = await import('@/lib/api')
|
||||
const token = getAccessToken()
|
||||
const headers: HeadersInit = {}
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`
|
||||
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/review/sessions/search?q=${encodeURIComponent(searchQuery)}&limit=20`,
|
||||
{ headers }
|
||||
)
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setCrossJobSessions(data.sessions || [])
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Cross-job search failed:', err)
|
||||
} finally {
|
||||
setIsSearching(false)
|
||||
}
|
||||
}, [searchQuery])
|
||||
|
||||
const handleRestore = useCallback(async () => {
|
||||
if (!selectedSession) return
|
||||
setIsRestoring(true)
|
||||
try {
|
||||
// Check duration mismatch for cross-job restores
|
||||
if (
|
||||
searchMode === 'all-jobs' &&
|
||||
currentAudioDuration &&
|
||||
selectedSession.audio_duration_seconds &&
|
||||
Math.abs(currentAudioDuration - selectedSession.audio_duration_seconds) > 2
|
||||
) {
|
||||
setDurationWarning({
|
||||
source: selectedSession.audio_duration_seconds,
|
||||
current: currentAudioDuration,
|
||||
})
|
||||
setIsRestoring(false)
|
||||
return
|
||||
}
|
||||
|
||||
await doRestore()
|
||||
} catch (err) {
|
||||
console.error('Failed to restore session:', err)
|
||||
setIsRestoring(false)
|
||||
}
|
||||
}, [selectedSession, searchMode, currentAudioDuration])
|
||||
|
||||
const doRestore = useCallback(async () => {
|
||||
if (!selectedSession) return
|
||||
setIsRestoring(true)
|
||||
try {
|
||||
// For cross-job sessions, we need to fetch from that job's endpoint
|
||||
const jobId = selectedSession.job_id
|
||||
const sessionId = selectedSession.session_id
|
||||
|
||||
let correctionData: CorrectionData | null = null
|
||||
|
||||
if (searchMode === 'this-job') {
|
||||
const full = await apiClient.getReviewSession(sessionId)
|
||||
correctionData = full.correction_data
|
||||
} else {
|
||||
// Cross-job: use direct fetch
|
||||
const { getAccessToken, API_BASE_URL } = await import('@/lib/api')
|
||||
const token = getAccessToken()
|
||||
const headers: HeadersInit = {}
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`
|
||||
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/review/${jobId}/sessions/${sessionId}`,
|
||||
{ headers }
|
||||
)
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
correctionData = data.correction_data
|
||||
}
|
||||
}
|
||||
|
||||
if (correctionData) {
|
||||
onRestore(correctionData)
|
||||
onClose()
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to restore session:', err)
|
||||
} finally {
|
||||
setIsRestoring(false)
|
||||
setDurationWarning(null)
|
||||
}
|
||||
}, [selectedSession, searchMode, apiClient, onRestore, onClose])
|
||||
|
||||
const formatDuration = (seconds: number) => {
|
||||
const m = Math.floor(seconds / 60)
|
||||
const s = Math.round(seconds % 60)
|
||||
return `${m}:${s.toString().padStart(2, '0')}`
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open && !durationWarning} onOpenChange={(o) => !o && onClose()}>
|
||||
<DialogContent className="max-w-3xl max-h-[80vh] flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Saved Review Sessions</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Tab switcher */}
|
||||
<div className="flex gap-2 border-b pb-2">
|
||||
<Button
|
||||
variant={searchMode === 'this-job' ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setSearchMode('this-job')}
|
||||
>
|
||||
This Job ({sessions.length})
|
||||
</Button>
|
||||
<Button
|
||||
variant={searchMode === 'all-jobs' ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setSearchMode('all-jobs')}
|
||||
>
|
||||
All Jobs
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Cross-job search */}
|
||||
{searchMode === 'all-jobs' && (
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Search by artist, title, or job ID..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
|
||||
/>
|
||||
<Button onClick={handleSearch} disabled={isSearching} size="sm">
|
||||
{isSearching ? <Loader2 className="h-4 w-4 animate-spin" /> : <Search className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : displayedSessions.length === 0 ? (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
{searchMode === 'all-jobs' ? 'Search for sessions across all jobs' : 'No saved sessions found'}
|
||||
</div>
|
||||
) : (
|
||||
/* Split pane: session list (left) + preview (right) */
|
||||
<div className="flex gap-4 min-h-[300px] flex-1 overflow-hidden">
|
||||
{/* Session list */}
|
||||
<div className="w-1/2 overflow-y-auto border rounded-md">
|
||||
{displayedSessions.map((session) => (
|
||||
<button
|
||||
key={session.session_id}
|
||||
onClick={() => setSelectedSessionId(session.session_id)}
|
||||
className={cn(
|
||||
'w-full text-left px-3 py-2.5 border-b last:border-0 hover:bg-accent/50 transition-colors',
|
||||
selectedSessionId === session.session_id && 'bg-accent'
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium" title={formatAbsoluteTime(session.updated_at)}>
|
||||
<Clock className="h-3 w-3 inline mr-1 opacity-50" />
|
||||
{formatRelativeTime(session.updated_at)}
|
||||
</span>
|
||||
<TriggerBadge trigger={session.trigger} />
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-0.5">
|
||||
{session.edit_count} edit{session.edit_count !== 1 ? 's' : ''}
|
||||
{searchMode === 'all-jobs' && session.artist && (
|
||||
<> · {session.artist} - {session.title}</>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Edit preview */}
|
||||
<div className="w-1/2 border rounded-md overflow-y-auto">
|
||||
{selectedSession ? (
|
||||
<EditPreview session={selectedSession} />
|
||||
) : (
|
||||
<div className="text-sm text-muted-foreground p-4 italic">
|
||||
Select a session to preview changes
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
Start Fresh
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleRestore}
|
||||
disabled={!selectedSession || isRestoring}
|
||||
>
|
||||
{isRestoring && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
|
||||
Restore Selected
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Duration mismatch warning dialog */}
|
||||
<Dialog open={!!durationWarning} onOpenChange={() => setDurationWarning(null)}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-5 w-5 text-yellow-500" />
|
||||
Duration Mismatch
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
{durationWarning && (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
The selected session is from a track with a different duration:
|
||||
</p>
|
||||
<div className="bg-muted rounded-md p-3 text-sm space-y-1">
|
||||
<div>This job: <strong>{formatDuration(durationWarning.current)}</strong> ({Math.round(durationWarning.current)}s)</div>
|
||||
<div>Source session: <strong>{formatDuration(durationWarning.source)}</strong> ({Math.round(durationWarning.source)}s)</div>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Timing alignment may not match. Word timestamps from the source session will be preserved as-is.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setDurationWarning(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={doRestore} disabled={isRestoring}>
|
||||
{isRestoring && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
|
||||
Restore Anyway
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import { render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import SessionRestoreDialog from '../SessionRestoreDialog'
|
||||
import type { ReviewSession, LyricsReviewApiClient, ReviewSessionWithData } from '@/lib/api'
|
||||
|
||||
function makeSession(overrides: Partial<ReviewSession> = {}): ReviewSession {
|
||||
return {
|
||||
session_id: 'session-1',
|
||||
job_id: 'job-1',
|
||||
user_email: 'user@test.com',
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
edit_count: 5,
|
||||
trigger: 'auto',
|
||||
audio_duration_seconds: 180,
|
||||
artist: 'Test Artist',
|
||||
title: 'Test Song',
|
||||
summary: {
|
||||
total_segments: 10,
|
||||
total_words: 100,
|
||||
corrections_made: 3,
|
||||
changed_words: [
|
||||
{ original: 'hello', corrected: 'hallo', segment_index: 0 },
|
||||
{ original: 'world', corrected: 'werld', segment_index: 1 },
|
||||
],
|
||||
},
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makeMockApiClient(): LyricsReviewApiClient {
|
||||
return {
|
||||
submitCorrections: jest.fn(),
|
||||
submitAnnotations: jest.fn(),
|
||||
submitEditLog: jest.fn(),
|
||||
updateHandlers: jest.fn(),
|
||||
addLyrics: jest.fn(),
|
||||
getAudioUrl: jest.fn(),
|
||||
generatePreviewVideo: jest.fn(),
|
||||
getPreviewVideoUrl: jest.fn(),
|
||||
completeReview: jest.fn(),
|
||||
saveReviewSession: jest.fn(),
|
||||
listReviewSessions: jest.fn(),
|
||||
getReviewSession: jest.fn().mockResolvedValue({
|
||||
session_id: 'session-1',
|
||||
correction_data: { corrected_segments: [] },
|
||||
} as Partial<ReviewSessionWithData>),
|
||||
deleteReviewSession: jest.fn(),
|
||||
}
|
||||
}
|
||||
|
||||
describe('SessionRestoreDialog', () => {
|
||||
const defaultProps = {
|
||||
open: true,
|
||||
onClose: jest.fn(),
|
||||
onRestore: jest.fn(),
|
||||
sessions: [makeSession()],
|
||||
apiClient: makeMockApiClient(),
|
||||
currentAudioDuration: 180,
|
||||
}
|
||||
|
||||
it('renders dialog with title when open', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} />)
|
||||
expect(screen.getByText('Saved Review Sessions')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not render content when closed', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} open={false} />)
|
||||
expect(screen.queryByText('Saved Review Sessions')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows loading spinner when isLoading', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} isLoading={true} />)
|
||||
// Should not show session list
|
||||
expect(screen.queryByText('5 edits')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows empty state when no sessions', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} sessions={[]} />)
|
||||
expect(screen.getByText('No saved sessions found')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('displays session list with edit count', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} />)
|
||||
expect(screen.getByText('5 edits')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows trigger badge', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} />)
|
||||
expect(screen.getByText('auto')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows edit preview for selected session', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} />)
|
||||
// First session should be auto-selected
|
||||
expect(screen.getByText('hello')).toBeInTheDocument()
|
||||
expect(screen.getByText('hallo')).toBeInTheDocument()
|
||||
expect(screen.getByText('world')).toBeInTheDocument()
|
||||
expect(screen.getByText('werld')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows correction count in preview', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} />)
|
||||
expect(screen.getByText(/3 changes? across 10 segments/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows "No word-level changes" when summary has no changed_words', () => {
|
||||
const session = makeSession({
|
||||
summary: { total_segments: 5, total_words: 50, corrections_made: 0, changed_words: [] },
|
||||
})
|
||||
render(<SessionRestoreDialog {...defaultProps} sessions={[session]} />)
|
||||
expect(screen.getByText('No word-level changes recorded in this session.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders multiple sessions in the list', () => {
|
||||
const sessions = [
|
||||
makeSession({ session_id: 's1', edit_count: 3, trigger: 'manual' }),
|
||||
makeSession({ session_id: 's2', edit_count: 10, trigger: 'preview' }),
|
||||
]
|
||||
render(<SessionRestoreDialog {...defaultProps} sessions={sessions} />)
|
||||
expect(screen.getByText('3 edits')).toBeInTheDocument()
|
||||
expect(screen.getByText('10 edits')).toBeInTheDocument()
|
||||
expect(screen.getByText('manual')).toBeInTheDocument()
|
||||
expect(screen.getByText('preview')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls onRestore with correction data when Restore Selected is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const apiClient = makeMockApiClient()
|
||||
const onRestore = jest.fn()
|
||||
const correctionData = { corrected_segments: [{ id: 's1', text: 'test', words: [], start_time: 0, end_time: 1 }] }
|
||||
|
||||
;(apiClient.getReviewSession as jest.Mock).mockResolvedValue({
|
||||
session_id: 'session-1',
|
||||
correction_data: correctionData,
|
||||
})
|
||||
|
||||
render(
|
||||
<SessionRestoreDialog
|
||||
{...defaultProps}
|
||||
apiClient={apiClient}
|
||||
onRestore={onRestore}
|
||||
/>
|
||||
)
|
||||
|
||||
await user.click(screen.getByText('Restore Selected'))
|
||||
|
||||
expect(apiClient.getReviewSession).toHaveBeenCalledWith('session-1')
|
||||
expect(onRestore).toHaveBeenCalledWith(correctionData)
|
||||
})
|
||||
|
||||
it('calls onClose when Start Fresh is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onClose = jest.fn()
|
||||
render(<SessionRestoreDialog {...defaultProps} onClose={onClose} />)
|
||||
|
||||
await user.click(screen.getByText('Start Fresh'))
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows tab buttons for This Job and All Jobs', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} />)
|
||||
expect(screen.getByText(/This Job/)).toBeInTheDocument()
|
||||
expect(screen.getByText('All Jobs')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows session count in This Job tab', () => {
|
||||
const sessions = [makeSession({ session_id: 's1' }), makeSession({ session_id: 's2' })]
|
||||
render(<SessionRestoreDialog {...defaultProps} sessions={sessions} />)
|
||||
expect(screen.getByText('This Job (2)')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows search input when All Jobs tab is selected', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<SessionRestoreDialog {...defaultProps} />)
|
||||
|
||||
await user.click(screen.getByText('All Jobs'))
|
||||
expect(screen.getByPlaceholderText('Search by artist, title, or job ID...')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows artist and title for cross-job sessions', async () => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
// Mock the global fetch for cross-job search
|
||||
const mockFetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
sessions: [
|
||||
makeSession({ session_id: 'cross-1', artist: 'Other Artist', title: 'Other Song', edit_count: 7 }),
|
||||
],
|
||||
}),
|
||||
})
|
||||
global.fetch = mockFetch
|
||||
|
||||
render(<SessionRestoreDialog {...defaultProps} />)
|
||||
|
||||
// Switch to All Jobs tab
|
||||
await user.click(screen.getByText('All Jobs'))
|
||||
|
||||
// Type search query and submit
|
||||
const input = screen.getByPlaceholderText('Search by artist, title, or job ID...')
|
||||
await user.type(input, 'Other Artist{Enter}')
|
||||
|
||||
// Wait for results
|
||||
expect(mockFetch).toHaveBeenCalled()
|
||||
|
||||
// Should show the cross-job session with artist info
|
||||
expect(await screen.findByText(/Other Artist/)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -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 });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import { useReviewSessionAutoSave } from '../use-review-session-autosave'
|
||||
import type { CorrectionData } from '@/lib/lyrics-review/types'
|
||||
import type { LyricsReviewApiClient } from '@/lib/api'
|
||||
|
||||
// Minimal CorrectionData factory
|
||||
function makeCorrectionData(overrides: Partial<CorrectionData> = {}): CorrectionData {
|
||||
return {
|
||||
original_segments: [],
|
||||
reference_lyrics: {},
|
||||
anchor_sequences: [],
|
||||
gap_sequences: [],
|
||||
resized_segments: [],
|
||||
corrections_made: 0,
|
||||
confidence: 1,
|
||||
corrections: [],
|
||||
corrected_segments: [],
|
||||
metadata: {
|
||||
anchor_sequences_count: 0,
|
||||
gap_sequences_count: 0,
|
||||
total_words: 0,
|
||||
correction_ratio: 0,
|
||||
},
|
||||
correction_steps: [],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makeSegment(words: string[]) {
|
||||
return {
|
||||
id: `seg-${Math.random()}`,
|
||||
text: words.join(' '),
|
||||
words: words.map((text) => ({
|
||||
id: `w-${Math.random()}`,
|
||||
text,
|
||||
start_time: 0,
|
||||
end_time: 1,
|
||||
confidence: 1,
|
||||
})),
|
||||
start_time: 0,
|
||||
end_time: 1,
|
||||
}
|
||||
}
|
||||
|
||||
function makeMockApiClient(overrides: Partial<LyricsReviewApiClient> = {}): LyricsReviewApiClient {
|
||||
return {
|
||||
submitCorrections: jest.fn(),
|
||||
submitAnnotations: jest.fn(),
|
||||
submitEditLog: jest.fn(),
|
||||
updateHandlers: jest.fn(),
|
||||
addLyrics: jest.fn(),
|
||||
getAudioUrl: jest.fn(),
|
||||
generatePreviewVideo: jest.fn(),
|
||||
getPreviewVideoUrl: jest.fn(),
|
||||
completeReview: jest.fn(),
|
||||
saveReviewSession: jest.fn().mockResolvedValue({ status: 'saved', session_id: 'test-session' }),
|
||||
listReviewSessions: jest.fn().mockResolvedValue({ sessions: [] }),
|
||||
getReviewSession: jest.fn(),
|
||||
deleteReviewSession: jest.fn(),
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('useReviewSessionAutoSave', () => {
|
||||
it('does not save when historyLength <= 1 (no edits)', async () => {
|
||||
const apiClient = makeMockApiClient()
|
||||
const { result } = renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: makeCorrectionData(),
|
||||
initialData: makeCorrectionData(),
|
||||
historyLength: 1,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
|
||||
expect(apiClient.saveReviewSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('saves when historyLength > 1 and trigger is manual', async () => {
|
||||
const apiClient = makeMockApiClient()
|
||||
// Use historyLength=2 (below auto-save threshold of 3)
|
||||
const { result } = renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: makeCorrectionData(),
|
||||
initialData: makeCorrectionData(),
|
||||
historyLength: 2,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledTimes(1)
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledWith(
|
||||
expect.any(Object),
|
||||
1, // historyLength - 1
|
||||
'manual',
|
||||
expect.objectContaining({
|
||||
total_segments: expect.any(Number),
|
||||
corrections_made: expect.any(Number),
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('does not save again if historyLength has not changed since last save', async () => {
|
||||
const apiClient = makeMockApiClient()
|
||||
const { result } = renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: makeCorrectionData(),
|
||||
initialData: makeCorrectionData(),
|
||||
historyLength: 2,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledTimes(1)
|
||||
|
||||
// Second call with same historyLength should be skipped
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('does not auto-save in read-only mode', async () => {
|
||||
const apiClient = makeMockApiClient()
|
||||
// historyLength=4 would trigger auto-save (4 >= 3 edits threshold) but read-only prevents it
|
||||
renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: makeCorrectionData(),
|
||||
initialData: makeCorrectionData(),
|
||||
historyLength: 4,
|
||||
isReadOnly: true,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
expect(apiClient.saveReviewSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('auto-saves after 3 edits since last backup', async () => {
|
||||
const apiClient = makeMockApiClient()
|
||||
const props = {
|
||||
jobId: 'job-1',
|
||||
data: makeCorrectionData(),
|
||||
initialData: makeCorrectionData(),
|
||||
historyLength: 1,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
}
|
||||
|
||||
const { rerender } = renderHook(
|
||||
(p) => useReviewSessionAutoSave(p),
|
||||
{ initialProps: props }
|
||||
)
|
||||
|
||||
// 1 edit (historyLength 2) — no save yet
|
||||
await act(async () => {
|
||||
rerender({ ...props, historyLength: 2 })
|
||||
})
|
||||
expect(apiClient.saveReviewSession).not.toHaveBeenCalled()
|
||||
|
||||
// 2 edits (historyLength 3) — auto-save fires (3 - 0 >= 3)
|
||||
await act(async () => {
|
||||
rerender({ ...props, historyLength: 3 })
|
||||
})
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledTimes(1)
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledWith(
|
||||
expect.any(Object),
|
||||
2,
|
||||
'auto',
|
||||
expect.any(Object)
|
||||
)
|
||||
})
|
||||
|
||||
it('auto-saves again after another 3 edits', async () => {
|
||||
const apiClient = makeMockApiClient()
|
||||
const props = {
|
||||
jobId: 'job-1',
|
||||
data: makeCorrectionData(),
|
||||
initialData: makeCorrectionData(),
|
||||
historyLength: 1,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
}
|
||||
|
||||
const { rerender } = renderHook(
|
||||
(p) => useReviewSessionAutoSave(p),
|
||||
{ initialProps: props }
|
||||
)
|
||||
|
||||
// First auto-save at historyLength 3
|
||||
await act(async () => {
|
||||
rerender({ ...props, historyLength: 3 })
|
||||
})
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledTimes(1)
|
||||
|
||||
// 3 more edits from lastBackup=3: fires at historyLength 6
|
||||
await act(async () => {
|
||||
rerender({ ...props, historyLength: 4 })
|
||||
})
|
||||
await act(async () => {
|
||||
rerender({ ...props, historyLength: 5 })
|
||||
})
|
||||
await act(async () => {
|
||||
rerender({ ...props, historyLength: 6 })
|
||||
})
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('handles save failure gracefully without throwing', async () => {
|
||||
const consoleWarn = jest.spyOn(console, 'warn').mockImplementation()
|
||||
const apiClient = makeMockApiClient({
|
||||
saveReviewSession: jest.fn().mockRejectedValue(new Error('Network error')),
|
||||
})
|
||||
const { result } = renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: makeCorrectionData(),
|
||||
initialData: makeCorrectionData(),
|
||||
historyLength: 2,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
|
||||
expect(consoleWarn).toHaveBeenCalledWith(
|
||||
'Review session auto-save failed:',
|
||||
expect.any(Error)
|
||||
)
|
||||
consoleWarn.mockRestore()
|
||||
})
|
||||
|
||||
it('computes correct summary with word changes', async () => {
|
||||
const apiClient = makeMockApiClient()
|
||||
const initialData = makeCorrectionData({
|
||||
corrected_segments: [makeSegment(['hello', 'world', 'foo'])],
|
||||
})
|
||||
const currentData = makeCorrectionData({
|
||||
corrected_segments: [makeSegment(['hallo', 'world', 'bar'])],
|
||||
})
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: currentData,
|
||||
initialData,
|
||||
historyLength: 2,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
|
||||
const summary = (apiClient.saveReviewSession as jest.Mock).mock.calls[0][3]
|
||||
expect(summary.total_segments).toBe(1)
|
||||
expect(summary.total_words).toBe(3)
|
||||
expect(summary.corrections_made).toBe(2)
|
||||
expect(summary.changed_words).toHaveLength(2)
|
||||
expect(summary.changed_words[0]).toEqual(
|
||||
expect.objectContaining({ original: 'hello', corrected: 'hallo', segment_index: 0 })
|
||||
)
|
||||
})
|
||||
|
||||
it('caps changed_words at 50', async () => {
|
||||
const apiClient = makeMockApiClient()
|
||||
// Create segments with 60 different words
|
||||
const initialWords = Array.from({ length: 60 }, (_, i) => `word${i}`)
|
||||
const currentWords = Array.from({ length: 60 }, (_, i) => `changed${i}`)
|
||||
const initialData = makeCorrectionData({
|
||||
corrected_segments: [makeSegment(initialWords)],
|
||||
})
|
||||
const currentData = makeCorrectionData({
|
||||
corrected_segments: [makeSegment(currentWords)],
|
||||
})
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: currentData,
|
||||
initialData,
|
||||
historyLength: 2,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
|
||||
const summary = (apiClient.saveReviewSession as jest.Mock).mock.calls[0][3]
|
||||
expect(summary.corrections_made).toBe(60)
|
||||
expect(summary.changed_words).toHaveLength(50) // Capped at 50
|
||||
})
|
||||
|
||||
it('saves with preview trigger', async () => {
|
||||
const apiClient = makeMockApiClient()
|
||||
// Use historyLength=2 so auto-save doesn't fire first (threshold is 3)
|
||||
const { result } = renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: makeCorrectionData(),
|
||||
initialData: makeCorrectionData(),
|
||||
historyLength: 2,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSession('preview')
|
||||
})
|
||||
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledWith(
|
||||
expect.any(Object),
|
||||
1,
|
||||
'preview',
|
||||
expect.any(Object)
|
||||
)
|
||||
})
|
||||
|
||||
it('does not update lastBackupHistoryLength on non-saved/skipped status', async () => {
|
||||
const apiClient = makeMockApiClient({
|
||||
saveReviewSession: jest.fn().mockResolvedValue({ status: 'error' }),
|
||||
})
|
||||
// Use historyLength=2 so auto-save doesn't fire
|
||||
const { result } = renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: makeCorrectionData(),
|
||||
initialData: makeCorrectionData(),
|
||||
historyLength: 2,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
// Should still try on second call since first didn't save
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useCallback, useEffect, useRef } from 'react'
|
||||
import type { CorrectionData } from '@/lib/lyrics-review/types'
|
||||
import type { LyricsReviewApiClient, ReviewSessionSummary } from '@/lib/api'
|
||||
|
||||
interface UseReviewSessionAutoSaveOptions {
|
||||
jobId: string
|
||||
data: CorrectionData
|
||||
initialData: CorrectionData
|
||||
historyLength: number
|
||||
isReadOnly: boolean
|
||||
apiClient: LyricsReviewApiClient
|
||||
}
|
||||
|
||||
function computeSummary(initialData: CorrectionData, currentData: CorrectionData): ReviewSessionSummary {
|
||||
const changedWords: ReviewSessionSummary['changed_words'] = []
|
||||
|
||||
// Compare corrected_segments to find changed words
|
||||
const initialSegments = initialData.corrected_segments || []
|
||||
const currentSegments = currentData.corrected_segments || []
|
||||
|
||||
let totalWords = 0
|
||||
for (let si = 0; si < currentSegments.length && si < initialSegments.length; si++) {
|
||||
const initialWords = initialSegments[si]?.words || []
|
||||
const currentWords = currentSegments[si]?.words || []
|
||||
totalWords += currentWords.length
|
||||
|
||||
for (let wi = 0; wi < currentWords.length && wi < initialWords.length; wi++) {
|
||||
if (currentWords[wi].text !== initialWords[wi].text) {
|
||||
changedWords.push({
|
||||
original: initialWords[wi].text,
|
||||
corrected: currentWords[wi].text,
|
||||
segment_index: si,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Also count words in segments beyond the initial count
|
||||
for (let si = initialSegments.length; si < currentSegments.length; si++) {
|
||||
totalWords += (currentSegments[si]?.words || []).length
|
||||
}
|
||||
|
||||
return {
|
||||
total_segments: currentSegments.length,
|
||||
total_words: totalWords || currentSegments.reduce((sum, s) => sum + (s.words?.length || 0), 0),
|
||||
corrections_made: changedWords.length,
|
||||
changed_words: changedWords.slice(0, 50), // Cap at 50 for storage
|
||||
}
|
||||
}
|
||||
|
||||
const AUTO_SAVE_EVERY_N_EDITS = 3
|
||||
|
||||
export function useReviewSessionAutoSave({
|
||||
jobId,
|
||||
data,
|
||||
initialData,
|
||||
historyLength,
|
||||
isReadOnly,
|
||||
apiClient,
|
||||
}: UseReviewSessionAutoSaveOptions) {
|
||||
const lastBackupHistoryLength = useRef(0)
|
||||
const isSaving = useRef(false)
|
||||
// Store latest values in refs so visibilitychange handler always has current data
|
||||
const dataRef = useRef(data)
|
||||
const initialDataRef = useRef(initialData)
|
||||
const historyLengthRef = useRef(historyLength)
|
||||
dataRef.current = data
|
||||
initialDataRef.current = initialData
|
||||
historyLengthRef.current = historyLength
|
||||
|
||||
const doSave = useCallback(
|
||||
async (trigger: 'auto' | 'preview' | 'manual') => {
|
||||
const currentHistoryLength = historyLengthRef.current
|
||||
// No edits yet (only initial state in history)
|
||||
if (currentHistoryLength <= 1) return
|
||||
// No new edits since last backup
|
||||
if (currentHistoryLength === lastBackupHistoryLength.current) return
|
||||
// Already saving
|
||||
if (isSaving.current) return
|
||||
|
||||
isSaving.current = true
|
||||
try {
|
||||
const summary = computeSummary(initialDataRef.current, dataRef.current)
|
||||
const result = await apiClient.saveReviewSession(
|
||||
dataRef.current,
|
||||
currentHistoryLength - 1,
|
||||
trigger,
|
||||
summary
|
||||
)
|
||||
if (result.status === 'saved' || result.status === 'skipped') {
|
||||
lastBackupHistoryLength.current = currentHistoryLength
|
||||
}
|
||||
} catch (err) {
|
||||
// Don't break the editing experience on backup failure
|
||||
console.warn('Review session auto-save failed:', err)
|
||||
} finally {
|
||||
isSaving.current = false
|
||||
}
|
||||
},
|
||||
[apiClient]
|
||||
)
|
||||
|
||||
// Auto-save every N edits
|
||||
useEffect(() => {
|
||||
if (isReadOnly || historyLength <= 1) return
|
||||
const editsSinceBackup = historyLength - lastBackupHistoryLength.current
|
||||
if (editsSinceBackup >= AUTO_SAVE_EVERY_N_EDITS) {
|
||||
doSave('auto')
|
||||
}
|
||||
}, [historyLength, isReadOnly, doSave])
|
||||
|
||||
// Save on page hide
|
||||
useEffect(() => {
|
||||
if (isReadOnly) return
|
||||
|
||||
const handler = () => {
|
||||
if (document.visibilityState === 'hidden') {
|
||||
doSave('auto')
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('visibilitychange', handler)
|
||||
return () => document.removeEventListener('visibilitychange', handler)
|
||||
}, [isReadOnly, doSave])
|
||||
|
||||
// Expose saveSession that uses current refs
|
||||
const saveSession = useCallback(
|
||||
(trigger: 'auto' | 'preview' | 'manual') => doSave(trigger),
|
||||
[doSave]
|
||||
)
|
||||
|
||||
return { saveSession }
|
||||
}
|
||||
+304
-1
@@ -75,6 +75,7 @@ export interface Job {
|
||||
user_email?: string;
|
||||
outputs_deleted_at?: string;
|
||||
outputs_deleted_by?: string;
|
||||
edit_count?: number;
|
||||
existing_instrumental_gcs_path?: string;
|
||||
// Audio search fields
|
||||
audio_search_artist?: string;
|
||||
@@ -98,6 +99,16 @@ export interface UploadJobResponse {
|
||||
distribution_services?: Record<string, any>;
|
||||
}
|
||||
|
||||
export interface EditTrackResponse {
|
||||
status: string;
|
||||
job_id: string;
|
||||
message: string;
|
||||
review_url: string;
|
||||
review_token: string;
|
||||
metadata_updated: boolean;
|
||||
cleanup_results: Record<string, any>;
|
||||
}
|
||||
|
||||
export interface InstrumentalOption {
|
||||
id: string;
|
||||
label: string;
|
||||
@@ -155,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 {
|
||||
@@ -382,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();
|
||||
@@ -413,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',
|
||||
@@ -434,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',
|
||||
@@ -515,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
|
||||
@@ -579,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 };
|
||||
@@ -592,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',
|
||||
@@ -659,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
|
||||
*/
|
||||
@@ -843,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',
|
||||
@@ -1252,6 +1451,30 @@ export const api = {
|
||||
});
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async changeVisibility(jobId: string, targetVisibility: 'public' | 'private'): Promise<ChangeVisibilityResponse> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/change-visibility`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...getAuthHeaders(),
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ target_visibility: targetVisibility }),
|
||||
});
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async editCompletedTrack(jobId: string, updates?: { artist?: string; title?: string }): Promise<EditTrackResponse> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/edit`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...getAuthHeaders(),
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(updates || {}),
|
||||
});
|
||||
return handleResponse(response);
|
||||
},
|
||||
};
|
||||
|
||||
// Types for credits/payment
|
||||
@@ -2244,6 +2467,32 @@ export interface OverrideAudioSourceResponse {
|
||||
/**
|
||||
* API client interface for LyricsAnalyzer component
|
||||
*/
|
||||
// Review Session types (backup/restore)
|
||||
export interface ReviewSessionSummary {
|
||||
total_segments: number
|
||||
total_words: number
|
||||
corrections_made: number
|
||||
changed_words: Array<{ original: string; corrected: string; segment_index: number }>
|
||||
}
|
||||
|
||||
export interface ReviewSession {
|
||||
session_id: string
|
||||
job_id: string
|
||||
user_email: string
|
||||
created_at: string | null
|
||||
updated_at: string | null
|
||||
edit_count: number
|
||||
trigger: 'auto' | 'preview' | 'manual'
|
||||
audio_duration_seconds: number | null
|
||||
artist: string | null
|
||||
title: string | null
|
||||
summary: ReviewSessionSummary
|
||||
}
|
||||
|
||||
export interface ReviewSessionWithData extends ReviewSession {
|
||||
correction_data: CorrectionData | null
|
||||
}
|
||||
|
||||
export interface LyricsReviewApiClient {
|
||||
submitCorrections: (data: CorrectionData) => Promise<void>
|
||||
submitAnnotations: (annotations: Omit<CorrectionAnnotation, 'annotation_id' | 'timestamp'>[]) => Promise<void>
|
||||
@@ -2258,6 +2507,11 @@ export interface LyricsReviewApiClient {
|
||||
}>
|
||||
getPreviewVideoUrl: (hash: string) => string
|
||||
completeReview: () => Promise<{ status: string; job_status: string; message: string }>
|
||||
// Review session methods
|
||||
saveReviewSession: (data: CorrectionData, editCount: number, trigger: string, summary: ReviewSessionSummary) => Promise<{ status: string; session_id?: string; reason?: string }>
|
||||
listReviewSessions: () => Promise<{ sessions: ReviewSession[] }>
|
||||
getReviewSession: (sessionId: string) => Promise<ReviewSessionWithData>
|
||||
deleteReviewSession: (sessionId: string) => Promise<{ status: string }>
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2399,6 +2653,46 @@ export function createLyricsReviewApiClient(jobId: string): LyricsReviewApiClien
|
||||
})
|
||||
return handleResponse(response)
|
||||
},
|
||||
|
||||
// Review session methods
|
||||
async saveReviewSession(data: CorrectionData, editCount: number, trigger: string, summary: ReviewSessionSummary) {
|
||||
const response = await fetch(`${API_BASE_URL}/api/review/${jobId}/sessions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders()
|
||||
},
|
||||
body: JSON.stringify({
|
||||
correction_data: data,
|
||||
edit_count: editCount,
|
||||
trigger,
|
||||
summary,
|
||||
}),
|
||||
})
|
||||
return handleResponse<{ status: string; session_id?: string; reason?: string }>(response)
|
||||
},
|
||||
|
||||
async listReviewSessions() {
|
||||
const response = await fetch(`${API_BASE_URL}/api/review/${jobId}/sessions`, {
|
||||
headers: getAuthHeaders()
|
||||
})
|
||||
return handleResponse<{ sessions: ReviewSession[] }>(response)
|
||||
},
|
||||
|
||||
async getReviewSession(sessionId: string) {
|
||||
const response = await fetch(`${API_BASE_URL}/api/review/${jobId}/sessions/${sessionId}`, {
|
||||
headers: getAuthHeaders()
|
||||
})
|
||||
return handleResponse<ReviewSessionWithData>(response)
|
||||
},
|
||||
|
||||
async deleteReviewSession(sessionId: string) {
|
||||
const response = await fetch(`${API_BASE_URL}/api/review/${jobId}/sessions/${sessionId}`, {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders()
|
||||
})
|
||||
return handleResponse<{ status: string }>(response)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2680,5 +2974,14 @@ export interface RefundResponse {
|
||||
session_id: string;
|
||||
}
|
||||
|
||||
export interface ChangeVisibilityResponse {
|
||||
status: string;
|
||||
job_id: string;
|
||||
message: string;
|
||||
previous_visibility: string;
|
||||
new_visibility: string;
|
||||
reprocessing_required: boolean;
|
||||
}
|
||||
|
||||
export { ApiError };
|
||||
|
||||
@@ -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" },
|
||||
|
||||
@@ -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
|
||||
}) {
|
||||
|
||||
@@ -39,6 +39,8 @@ EMAIL_FROM = os.environ.get("EMAIL_FROM", "gen@nomadkaraoke.com")
|
||||
NOTIFY_ON_SUCCESS = os.environ.get("NOTIFY_ON_SUCCESS", "true").lower() == "true"
|
||||
|
||||
# Known gaps configuration - matches the local validate_and_sync.py script
|
||||
# These are HISTORICAL ONLY (pre-generator era, before Dec 2024). Do NOT add new entries.
|
||||
# New gaps are bugs — see docs/GDRIVE-VALIDATOR.md § "Sequence Gap Detected" for fix procedure.
|
||||
# Format: Directory name -> List of ranges (inclusive) or individual numbers to exclude
|
||||
KNOWN_GAPS = {
|
||||
"MP4": [
|
||||
|
||||
@@ -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",
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
],
|
||||
|
||||
@@ -378,7 +378,7 @@ def create_parser(prog: str = "karaoke-gen") -> argparse.ArgumentParser:
|
||||
"--review-ui-url",
|
||||
default=os.environ.get('REVIEW_UI_URL', os.environ.get('LYRICS_REVIEW_UI_URL', 'https://gen.nomadkaraoke.com')),
|
||||
help="Frontend base URL for remote mode. Defaults to 'https://gen.nomadkaraoke.com'. "
|
||||
"Review UIs are at /app/jobs/{id}/review and /app/jobs/{id}/instrumental. "
|
||||
"Review UIs are at /app/jobs#/{id}/review and /app/jobs#/{id}/instrumental. "
|
||||
"For local mode: defaults to bundled frontend (from lyrics_transcriber/frontend/). "
|
||||
"(env: REVIEW_UI_URL or LYRICS_REVIEW_UI_URL)",
|
||||
)
|
||||
|
||||
@@ -1508,7 +1508,7 @@ class JobMonitor:
|
||||
"""Open the lyrics review UI in browser."""
|
||||
# Build the review URL using the consolidated frontend route
|
||||
frontend_base = self.config.review_ui_url.rstrip('/')
|
||||
url = f"{frontend_base}/app/jobs/{job_id}/review"
|
||||
url = f"{frontend_base}/app/jobs#/{job_id}/review"
|
||||
|
||||
self.logger.info(f"Opening lyrics review UI: {url}")
|
||||
self.open_browser(url)
|
||||
@@ -1900,7 +1900,7 @@ class JobMonitor:
|
||||
"""Open browser to instrumental review UI and wait for selection."""
|
||||
# Build the review URL using the consolidated frontend route
|
||||
frontend_base = self.config.review_ui_url.rstrip('/')
|
||||
review_url = f"{frontend_base}/app/jobs/{job_id}/instrumental"
|
||||
review_url = f"{frontend_base}/app/jobs#/{job_id}/instrumental"
|
||||
|
||||
self.logger.info("")
|
||||
self.logger.info("=" * 60)
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.135.2"
|
||||
version = "0.140.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"
|
||||
|
||||
@@ -921,7 +921,7 @@ class TestJobMonitor:
|
||||
mock_open_browser.assert_called_once()
|
||||
call_url = mock_open_browser.call_args[0][0]
|
||||
# New consolidated frontend URL format
|
||||
assert call_url == "https://review.example.com/app/jobs/job-123/review"
|
||||
assert call_url == "https://review.example.com/app/jobs#/job-123/review"
|
||||
|
||||
def test_log_timeline_updates(self, monitor):
|
||||
"""Test logging timeline events."""
|
||||
|
||||
Reference in new issue
Block a user