Compare commits

..
10 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.6 ef0bb20094 Fix review session autosave: use edit-count instead of timer (#511)
## Summary

- The 60s interval timer reset on every edit (React dependency
tracking), so active editing could delay saves indefinitely
- Replace with edit-count-based autosave: saves every 3 edits since last
backup
- Uses refs instead of callback dependencies so the save function stays
stable

## Changes

- `use-review-session-autosave.ts`: Replace `setInterval` with
`useEffect` on `historyLength` that checks `editsSinceBackup >= 3`
- Store data/initialData/historyLength in refs so `doSave` callback only
depends on `apiClient`
- Updated tests to match new behavior (11 tests passing)

## Testing
- [x] All 608 frontend tests pass
- [x] New tests for edit-count-based auto-save behavior

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 03:52:43 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 51cd0eadc5 Extend search session TTL to 7 days and handle expiry gracefully (#510)
## Summary
- Extended search session TTL from 30 minutes to 7 days so users who
leave a tab open mid-flow don't hit "Search expired"
- Added graceful frontend handling when sessions do expire — redirects
to re-search with a friendly message instead of raw error
- Updated API docs and tests to match

## Changes
- `backend/api/routes/audio_search.py`: TTL `timedelta(minutes=30)` →
`timedelta(days=7)`
- `frontend/components/job/GuidedJobFlow.tsx`: Catch 404/"Search
expired" errors, clear stale session, redirect to Step 2 with friendly
message preserving song info
- `backend/tests/test_standalone_search.py`: Updated test helper TTL to
match
- `docs/API.md`: Updated TTL reference from "30-min" to "7-day"

## Testing
- [x] All 31 search-specific tests pass
- [x] Full backend suite passes (2212 passed)

## Review
- [x] Local CodeRabbit review completed (no issues with these changes)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 03:23:46 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 f1ec70924e Add lyrics review session backup/restore system (#509)
## Summary

- Server-side auto-save of lyrics review sessions (every 60s if dirty,
on preview, on page hide) with SHA-256 deduplication
- Split-pane restore UI with session browser, edit diff preview, and
cross-job search
- Auto-prompts on load if saved sessions exist; falls back to
localStorage for local mode

## Changes

### Backend
- **New model**: `ReviewSession` + `ReviewSessionSummary` dataclasses
with Firestore serialization
- **5 new API endpoints** under `/api/review/`: save, list, get, delete
sessions + cross-job search
- **Firestore**: 8 new methods for review session CRUD using
subcollection pattern (`jobs/{jobId}/review_sessions/{sessionId}`)
- **GCS storage**: Correction data stored in GCS (can exceed Firestore's
1MB doc limit); metadata in Firestore
- **Deduplication**: SHA-256 hash comparison skips saving identical data

### Frontend
- **`useReviewSessionAutoSave` hook**: 60s interval auto-save,
visibilitychange save, exposed `saveSession()` for manual/preview
triggers
- **`SessionRestoreDialog`**: Split-pane modal with session list + edit
diff preview, "This Job"/"All Jobs" tabs, cross-job search, duration
mismatch warning
- **`LyricsAnalyzer` integration**: Auto-checks for saved sessions on
load, "Save Progress" and "Session History" toolbar buttons, triggers
save on preview

### Docs
- API.md: 5 new review session endpoints documented
- README.md: Feature added to Current State table + Recent Changes
- LESSONS-LEARNED.md: GCS + Firestore metadata pattern

### Also included (from #508)
- Job observability improvements: timeline metadata, `log_to_job()`
helper

## Testing
- [x] 18 backend unit tests (model serialization, all API endpoints,
deduplication, auth, 404s)
- [x] 10 auto-save hook tests (triggers, deduplication tracking,
interval, read-only, error handling, summary computation)
- [x] 16 SessionRestoreDialog tests (rendering, restore flow, tab
switching, cross-job search, empty states)
- [x] All 607 frontend tests pass
- [x] All 2409 backend tests pass

## Review
- [x] CodeRabbit CLI review completed locally (1 fix applied:
beforeunload → visibilitychange)
- [x] Test review completed (26 new frontend tests added)
- [x] Docs review completed

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 00:23:42 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 9d8bf3a952 Improve job observability with timeline metadata and log_to_job (#508)
@coderabbitai ignore

## Summary
- Add `metadata` field to `TimelineEvent` for structured output details
(brand codes, YouTube video IDs, Dropbox paths, GDrive file IDs)
- Add `log_to_job()` helper for API endpoints to write to Firestore job
log subcollections
- Plumb `timeline_metadata` through `job_manager.transition_to_state()`
and `firestore_service.update_job_status()`
- Capture output details in completion timeline events for full
traceability
- Log edit/delete cleanup operations to both Cloud Logging and Firestore
job logs
- Snapshot previous outputs before cleanup for audit trail
- Enhance distribution logging with video_id, folder path, and file IDs

## Context
After shipping "edit completed tracks," tracing edited jobs was
difficult because timeline events lacked output details, cleanup
operations weren't logged to Firestore, and previous outputs were
overwritten with no history. These changes make the job's Firestore
document self-documenting — any agent or human can read the timeline and
understand the full lifecycle.

## Test plan
- [x] 7 new unit tests for `TimelineEvent.metadata` and `log_to_job()`
helper
- [x] All 103 backend tests pass
- [ ] Verify in production after deploy: edit a test job and confirm
timeline metadata appears in Firestore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 23:08:17 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 e04337fa5d Fix broken notification and CLI review URLs (#507)
## Summary
- Push notifications were sending users to `/review/{id}` and
`/instrumental/{id}` which 404 on Cloudflare Pages static hosting
- Remote CLI was opening browser to path-based URLs missing the `#/`
hash fragment
- Documentation referenced incorrect URL formats

All URLs now correctly use hash-based routing: `/app/jobs#/{id}/review`
and `/app/jobs#/{id}/instrumental`

## Changes
- **backend/services/push_notification_service.py** — Fixed notification
click URLs
- **backend/api/routes/jobs.py** — Fixed edit track response
`review_url`
- **karaoke_gen/utils/remote_cli.py** — Fixed CLI browser open URLs
- **karaoke_gen/utils/cli_args.py** — Fixed help text
- **Tests** — Updated assertions in push notification and remote CLI
tests
- **Docs** — Fixed URL examples in API.md, README.md, TESTING.md
- **pyproject.toml** — Bump version 0.137.0 → 0.137.1

## Test plan
- [x] Backend push notification tests pass (35 tests)
- [x] Remote CLI tests pass (174 tests)
- [x] Full backend test suite passes (103 tests)
- [x] Frontend unit tests pass (581 tests)

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 21:22:28 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 3f568373fd Add edit completed tracks feature (#506)
## Summary

- Add ability to edit completed karaoke tracks: cleans up existing
outputs (YouTube, Dropbox, GDrive, GCS), recycles brand code, resets
state to AWAITING_REVIEW
- Support optional artist/title metadata updates during edit (triggers
screens regeneration)
- New `POST /api/jobs/{job_id}/edit` endpoint with cleanup tracking and
review URL response
- Edit button in OutputLinks for completed jobs with confirmation modal
explaining implications

## Changes

### Backend
- `backend/api/routes/jobs.py` - New edit endpoint with full output
cleanup (YouTube, Dropbox, GDrive, GCS finals), brand code recycling,
state transition, and optional metadata update
- `backend/models/job.py` - Added COMPLETE → AWAITING_REVIEW state
transition and `edit_count` field
- `backend/tests/test_edit_completed_track.py` - 14 unit tests covering
success, metadata updates, validation, and cleanup

### Frontend
- `frontend/components/job/EditTrackModal.tsx` - Confirmation modal with
optional artist/title editing
- `frontend/components/job/OutputLinks.tsx` - Edit button (amber) for
completed jobs with outputs
- `frontend/lib/api.ts` - `editCompletedTrack()` API method and
`EditTrackResponse` type
- `frontend/components/__tests__/OutputLinks.test.tsx` - 3 new tests for
Edit button visibility

### Docs
- `docs/API.md` - Documented new endpoint
- `docs/README.md` - Added recent changes entry
- `docs/archive/2026-03-06-edit-completed-tracks-plan.md` -
Implementation plan

## Test plan

- [x] 14 backend unit tests for edit endpoint (success, metadata,
validation, cleanup)
- [x] 3 frontend tests for Edit button visibility (complete job, deleted
outputs, non-complete)
- [x] All 576 frontend unit tests passing
- [ ] Manual: Edit a completed track, verify outputs are cleaned up and
review reopens
- [ ] Manual: Edit with metadata change, verify screens regenerate

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 02:23:38 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 4d0e3bd1fb Add job creation observability (creation_params + OTel spans) (#505)
## Summary

- Store user's original choices (`is_private`, `is_admin`,
`created_from`) in a `creation_params` dict on the job Firestore
document for permanent observability
- Add OTel span attributes (`job_id`, `job.source`, `job.is_private`) to
all 7 job creation endpoints for Cloud Trace searchability

## Context

Investigation of job `fdcc82a6` revealed that while the system correctly
recorded `is_private: true`, we had no way to definitively prove what
the frontend sent. Cloud Trace request sizes provided forensic evidence,
but this required manual byte-counting. These changes ensure future
investigations can answer "what did the user choose?" directly.

## Changes
- **`backend/models/job.py`** — Added `creation_params` field to Job
model
- **`backend/services/job_manager.py`** — Populate `creation_params` at
job creation
- **`backend/api/routes/jobs.py`** — Span attributes on URL + guided
search endpoints
- **`backend/api/routes/file_upload.py`** — Span attributes on upload,
signed URL, URL, and finalise endpoints
- **`backend/api/routes/audio_search.py`** — Span attributes on audio
search endpoint
- **`backend/api/routes/users.py`** — Span attributes on made-for-you
endpoint
- **`backend/tests/test_private_tracks.py`** — 2 new tests for
creation_params
- **`docs/LESSONS-LEARNED.md`** — Documented Cloud Trace forensic
technique

## Test plan
- [x] All 103 backend tests pass (including 27 private tracks tests)
- [x] 2 new unit tests verify creation_params population and defaults

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 02:01:53 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 5391ac8465 fix: prepare nomad theme style_params for visibility change (#504)
## Summary

Fixes screens worker failure when changing visibility from private to
public: `style_params_gcs_path is required`.

## Root Cause

`change_to_public()` was setting `style_params_gcs_path: None` when
resetting to the nomad theme. The screens worker requires this path to
generate title/end screens.

## Fix

Call `_prepare_theme_for_job("nomad")` to properly copy the nomad
theme's `style_params.json` to the job folder before updating the job
and triggering the screens worker.

## Testing

- [x] 22/22 backend visibility tests pass
- [x] Test now verifies `style_params_gcs_path` is set (not None)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 00:50:10 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 89ade0462c test: add visibility change button tests and lesson learned (#503)
## Summary

Follow-up to #501 and #502 — adds the frontend tests that would have
caught the summary projection bug, plus a lesson learned entry.

## Changes

- 5 new frontend tests for the Change Visibility button (`is_private`
rendering, tenant exclusion, in-progress guard, non-complete exclusion)
- Lesson learned in `docs/LESSONS-LEARNED.md` about always testing the
summary projection layer when adding new fields

## Testing

- [x] 14/14 OutputLinks tests pass (5 new)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 00:33:23 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 7322825a2e fix: add is_private to summary field projection (#502)
## Summary

Hotfix for #501 — the Change Visibility button always showed "Make
Private" because `is_private` was missing from the dashboard's Firestore
field projection.

## Changes

- Add `is_private` to `SUMMARY_FIELD_PATHS` in `firestore_service.py`
- Add `state_data.visibility_change_in_progress` to both the projection
and prune allowlist
- Add regression tests verifying visibility fields are included

## Root Cause

The dashboard uses `fields=summary` which projects only specific fields
from Firestore. `is_private` was not in the projection list, so it was
always `undefined` on the frontend, causing `!!job.is_private` to always
be `false`.

## Testing

- [x] New regression tests pass
- [x] All existing summary endpoint tests pass (10/10)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 00:16:11 -05:00
43 changed files with 4371 additions and 58 deletions

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.
+25 -1
View File
@@ -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
@@ -1591,6 +1592,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 +1731,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 +1775,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,
+10 -2
View File
@@ -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)
+21
View File
@@ -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,
@@ -657,6 +658,11 @@ 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")
@@ -1230,6 +1236,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 +1711,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")
@@ -2002,6 +2018,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")
+311 -3
View File
@@ -33,13 +33,14 @@ 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
@@ -131,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)
@@ -202,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']
@@ -1932,6 +2235,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)
+208
View File
@@ -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,188 @@ 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}
+6
View File
@@ -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)
+9 -2
View File
@@ -142,10 +142,10 @@ STATE_TRANSITIONS = {
JobStatus.UPLOADING: [JobStatus.NOTIFYING, JobStatus.COMPLETE, JobStatus.FAILED],
JobStatus.NOTIFYING: [JobStatus.COMPLETE, JobStatus.FAILED],
# Terminal states - COMPLETE allows visibility change re-processing
# 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.LYRICS_COMPLETE], # Visibility change: private->public re-processing
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 +179,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 +306,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 +316,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
+107
View File
@@ -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", ""),
)
+250 -4
View File
@@ -10,6 +10,7 @@ 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
logger = logging.getLogger(__name__)
@@ -75,18 +76,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 +180,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 +676,217 @@ 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 []
def delete_search_session(self, session_id: str) -> None:
"""Delete a search session after it has been consumed by job creation.
@@ -710,3 +924,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}")
+18 -8
View File
@@ -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")
@@ -407,7 +413,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 +427,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,15 +437,15 @@ 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
# Tokens don't expire - they're job-scoped so low risk, and natural expiry happens when job completes
if new_status == JobStatus.AWAITING_REVIEW:
@@ -446,14 +454,14 @@ class JobManager:
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 +469,7 @@ class JobManager:
status=new_status,
progress=progress,
message=message,
timeline_metadata=timeline_metadata,
state_data=merged_state_data
)
else:
@@ -468,7 +477,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
@@ -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(
+11 -5
View File
@@ -152,15 +152,21 @@ class VisibilityChangeService:
except Exception:
pass
# Step 3: Reset styles and update job fields
# Step 4: Set status to LYRICS_COMPLETE with regen_restore_status
# Step 5: Clear progress keys and set guard flag
# 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_params_gcs_path": None,
"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",
+6 -1
View File
@@ -163,6 +163,7 @@ class TestChangeToPublic:
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()
@@ -176,6 +177,7 @@ class TestChangeToPublic:
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):
@@ -188,6 +190,7 @@ class TestChangeToPublic:
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()
@@ -210,7 +213,8 @@ class TestChangeToPublic:
assert style_update is not None
assert style_update["theme_id"] == "nomad"
assert style_update["color_overrides"] == {}
assert style_update["style_assets"] == {}
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"
@@ -225,6 +229,7 @@ class TestChangeToPublic:
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()
+251
View File
@@ -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"]
+132
View File
@@ -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
+44
View File
@@ -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):
+312
View File
@@ -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"] == []
+21
View File
@@ -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
+1 -1
View File
@@ -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,
+27 -4
View File
@@ -364,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")
@@ -859,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")
+3 -3
View File
@@ -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}")
+97 -1
View File
@@ -295,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
@@ -404,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:
@@ -565,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:**
+29
View File
@@ -36,6 +36,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 +456,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."
@@ -870,3 +876,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.
+8 -1
View File
@@ -34,6 +34,7 @@
| **Custom video styling (private jobs)** | Working |
| **Song lookup autocomplete** | Working (via karaoke-decide catalog) |
| **Community version detection** | Working (via karaokenerds.com) |
| **Review session backup/restore** | Working (auto-save + restore UI) |
## Known Issues
@@ -45,6 +46,12 @@
## Recent Changes
- **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).
@@ -124,7 +131,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
View File
@@ -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
@@ -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.
@@ -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
@@ -153,6 +219,36 @@ describe('OutputLinks', () => {
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')
+160
View File
@@ -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>
)
}
+9 -1
View File
@@ -200,7 +200,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.")
}
+24 -1
View File
@@ -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, Lock, Globe } from "lucide-react"
import { Download, Loader2, ExternalLink, FolderOpen, Copy, Mail, Settings, Lock, Globe, Pencil } from "lucide-react"
import { useAuth } from "@/lib/auth"
import {
Dialog,
@@ -26,6 +26,7 @@ import {
} 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
@@ -48,6 +49,7 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
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)
@@ -352,6 +354,19 @@ export function OutputLinks({ job, onJobUpdated }: 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
@@ -478,6 +493,14 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Edit Track Modal */}
<EditTrackModal
job={job}
open={showEditModal}
onOpenChange={setShowEditModal}
onEditStarted={onJobUpdated}
/>
</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 && (
<> &middot; {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()
})
})
@@ -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,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 }
}
+94
View File
@@ -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;
@@ -1264,6 +1275,18 @@ export const api = {
});
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
@@ -2256,6 +2279,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>
@@ -2270,6 +2319,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 }>
}
/**
@@ -2411,6 +2465,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)
},
}
}
+1 -1
View File
@@ -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)",
)
+2 -2
View File
@@ -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
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.136.0"
version = "0.138.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"
+1 -1
View File
@@ -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."""