Compare commits

...
2 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.6 789bf80646 Skip welcome credit AI evaluation for test emails (#638)
## Summary
- E2E test accounts (`@inbox.testmail.app`) were triggering the
Gemini-based credit evaluation on every daily test run, wasting LLM
credits and sending unnecessary denial emails
- Skip both the pre-compute (at magic link send) and inline evaluation
(at verification) for test emails — they get auto-granted directly

## Changes
- `backend/api/routes/users.py`: Skip background pre-compute thread for
test emails
- `backend/services/user_service.py`: Skip AI evaluation in
`grant_welcome_credits_if_eligible()` for test emails, go straight to
granting
- `backend/tests/test_anti_abuse.py`: Add test verifying AI eval is
skipped for testmail addresses

## Testing
- [x] All 2872 unit tests pass (8 pre-existing emulator failures
unrelated)
- [x] New test `test_skips_evaluation_for_test_emails` verifies behavior

## Review
- [x] Local CodeRabbit review completed — no findings

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 14:37:14 -04:00
Andrew Beveridge ☄️ c98da49da9 feat: add jobs search, status filter, and fix loading states (#637)
## Summary
- Add server-side text search to jobs list API (case-insensitive
substring match across artist, title, job_id)
- Replace eye icon toggle with status filter dropdown (All statuses,
Active, Failed, Completed, Cancelled, Awaiting review, Processing)
- Add debounced search input to Recent Jobs header
- Expand limit dropdown options (5, 10, 20, 50, 100, 1000)
- Fix loading state showing "No jobs yet" during cold starts (now shows
spinner)
- Fix API always fetching limit=100 regardless of dropdown selection

## Test plan
- [x] 8 unit tests for `_search_filter_jobs` (artist, title, job_id,
audio search fields, case insensitivity, None handling, empty string,
limit interaction)
- [x] Full backend test suite passes (2870 passed)
- [x] Frontend builds cleanly
- [ ] Manual: verify search filters jobs in real-time on dashboard
- [ ] Manual: verify status dropdown filters correctly
- [ ] Manual: verify loading spinner shows during cold starts instead of
"No jobs yet"

<!-- @coderabbitai ignore -->

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-03-30 05:03:05 +00:00
11 changed files with 284 additions and 297 deletions

No files matched your search

+25 -1
View File
@@ -538,6 +538,21 @@ def _prune_file_urls(data: Dict[str, Any]) -> Dict[str, Any]:
return data
def _search_filter_jobs(jobs: List[Dict[str, Any]], search: str) -> List[Dict[str, Any]]:
"""Filter job dicts by case-insensitive substring match across key fields."""
if not search:
return jobs
term = search.lower()
results = []
for job in jobs:
searchable = " ".join(
str(job.get(f) or "") for f in ("job_id", "artist", "title", "audio_search_artist", "audio_search_title")
)
if term in searchable.lower():
results.append(job)
return results
@router.get("", response_model=None)
async def list_jobs(
request: Request,
@@ -550,6 +565,7 @@ async def list_jobs(
limit: int = 100,
fields: Optional[str] = None,
hide_completed: bool = False,
search: Optional[str] = None,
auth_result: AuthResult = Depends(require_auth)
):
"""
@@ -568,6 +584,7 @@ async def list_jobs(
limit: Maximum number of jobs to return (default 100)
fields: Set to "summary" for reduced payload with only dashboard-required fields
hide_completed: If True, exclude successful completions (complete, prep_complete). Failed jobs remain visible.
search: Text search filter - matches against artist, title, audio_search_artist, audio_search_title, and job_id (case-insensitive substring). Only works with fields=summary.
Returns:
List of jobs matching filters, ordered by created_at descending.
@@ -615,6 +632,8 @@ async def list_jobs(
# --- Summary mode: field-projected query returning dicts ---
if fields == "summary":
exclude_statuses = _HIDE_COMPLETED_STATUSES if hide_completed else None
# When searching, fetch more results and filter in Python
fetch_limit = 1000 if search else limit
jobs_dicts = job_manager.list_jobs_summary(
status=status,
exclude_statuses=exclude_statuses,
@@ -624,13 +643,18 @@ async def list_jobs(
created_before=created_before_dt,
user_email=user_email_filter,
tenant_id=effective_tenant_id,
limit=limit,
limit=fetch_limit,
)
# Exclude test user jobs (Python-side, same as full mode)
if exclude_test and auth_result.is_admin:
jobs_dicts = [j for j in jobs_dicts if not is_test_email(j.get('user_email') or "")]
# Apply search filter if provided
if search:
jobs_dicts = _search_filter_jobs(jobs_dicts, search)
jobs_dicts = jobs_dicts[:limit] # Apply original limit after filtering
# Safety-net pruning (in case Firestore returned extra nested keys)
jobs_dicts = [_prune_file_urls(_prune_state_data(j)) for j in jobs_dicts]
+2 -1
View File
@@ -280,7 +280,8 @@ async def send_magic_link(
# Pre-compute credit evaluation in background for new users.
# By the time they check their email and click the link, the decision
# will be ready and verification will be instant.
if existing_user is None:
# Skip for test emails — they get auto-granted without evaluation.
if existing_user is None and not is_test_email(email):
thread = threading.Thread(
target=_precompute_credit_eval,
args=(magic_link.token, email),
+54 -48
View File
@@ -410,64 +410,70 @@ class UserService:
if txn.reason == "welcome_credit":
return False, "already_granted"
# AI evaluation: check for abuse signals before granting
# Use pre-computed result from magic link if available
try:
from backend.services.credit_evaluation_service import (
get_credit_evaluation_service,
CreditEvaluation,
)
precomputed_decision = (precomputed_eval or {}).get("credit_eval_decision")
if precomputed_decision:
logger.info(f"Using pre-computed credit eval for {email}: {precomputed_decision}")
evaluation = CreditEvaluation(
decision=precomputed_decision,
reasoning=(precomputed_eval or {}).get("credit_eval_reasoning", ""),
confidence=1.0,
error=(precomputed_eval or {}).get("credit_eval_error"),
# Skip AI evaluation for test emails (e.g. E2E test accounts)
# to avoid wasting LLM credits and sending unnecessary denial emails
from backend.utils.test_data import is_test_email
if not is_test_email(email):
# AI evaluation: check for abuse signals before granting
# Use pre-computed result from magic link if available
try:
from backend.services.credit_evaluation_service import (
get_credit_evaluation_service,
CreditEvaluation,
)
else:
eval_service = get_credit_evaluation_service()
evaluation = eval_service.evaluate(email, "welcome")
precomputed_decision = (precomputed_eval or {}).get("credit_eval_decision")
if precomputed_decision:
logger.info(f"Using pre-computed credit eval for {email}: {precomputed_decision}")
evaluation = CreditEvaluation(
decision=precomputed_decision,
reasoning=(precomputed_eval or {}).get("credit_eval_reasoning", ""),
confidence=1.0,
error=(precomputed_eval or {}).get("credit_eval_error"),
)
else:
eval_service = get_credit_evaluation_service()
evaluation = eval_service.evaluate(email, "welcome")
if evaluation.decision == "deny":
# Mark as evaluated but not granted so we don't re-evaluate
self.update_user(email, welcome_credits_granted=True)
logger.info(
f"Denied welcome credits to {email}: {evaluation.reasoning}"
)
try:
from backend.services.email_service import get_email_service
get_email_service().send_credit_denied_email(email, "welcome")
except Exception:
logger.exception(f"Failed to send credit denied email to {email}")
return False, "denied"
if evaluation.decision == "deny":
# Mark as evaluated but not granted so we don't re-evaluate
self.update_user(email, welcome_credits_granted=True)
logger.info(
f"Denied welcome credits to {email}: {evaluation.reasoning}"
)
try:
from backend.services.email_service import get_email_service
get_email_service().send_credit_denied_email(email, "welcome")
except Exception:
logger.exception(f"Failed to send credit denied email to {email}")
return False, "denied"
if evaluation.decision == "pending_review":
# Don't mark welcome_credits_granted — allow retry after manual review
logger.info(
f"Welcome credits pending review for {email}: {evaluation.reasoning}"
)
if evaluation.decision == "pending_review":
# Don't mark welcome_credits_granted — allow retry after manual review
logger.info(
f"Welcome credits pending review for {email}: {evaluation.reasoning}"
)
try:
from backend.services.email_service import get_email_service
email_service = get_email_service()
email_service.send_credit_review_needed_email(
email, "welcome", evaluation.reasoning, signals=evaluation.signals,
)
except Exception:
logger.exception(f"Failed to send review needed email for {email}")
return False, "pending_review"
except Exception:
logger.exception(f"Credit evaluation failed for {email} — pending review (fail-closed)")
try:
from backend.services.email_service import get_email_service
email_service = get_email_service()
email_service.send_credit_review_needed_email(
email, "welcome", evaluation.reasoning, signals=evaluation.signals,
email, "welcome", f"Evaluation error: {email}",
)
except Exception:
logger.exception(f"Failed to send review needed email for {email}")
pass
return False, "pending_review"
except Exception:
logger.exception(f"Credit evaluation failed for {email} — pending review (fail-closed)")
try:
from backend.services.email_service import get_email_service
email_service = get_email_service()
email_service.send_credit_review_needed_email(
email, "welcome", f"Evaluation error: {email}",
)
except Exception:
pass
return False, "pending_review"
else:
logger.info(f"Skipping credit evaluation for test email {email}")
# Grant welcome credits
welcome_credit = self.NEW_USER_FREE_CREDITS
+24
View File
@@ -236,6 +236,30 @@ class TestGrantWelcomeCredits:
assert granted is False
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_skips_evaluation_for_test_emails(self, mock_fs, mock_settings):
"""grant_welcome_credits_if_eligible skips AI evaluation for @inbox.testmail.app emails."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user = User(email="e2e.test@inbox.testmail.app", credits=0, credit_transactions=[])
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.user_service import UserService
service = UserService()
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
granted, status = service.grant_welcome_credits_if_eligible("e2e.test@inbox.testmail.app")
# AI evaluation should NOT have been called
mock_eval.return_value.evaluate.assert_not_called()
assert granted is True
assert status == "granted"
# =============================================================================
# Phase 2: Per-IP Signup Rate Limiting
+92
View File
@@ -736,3 +736,95 @@ class TestContentDispositionHeader:
decoded = unquote(utf8_part)
assert decoded == "周杰倫 - 青花瓷.mp4"
class TestSearchFiltering:
"""Tests for the search parameter on list_jobs summary mode."""
def _make_job_dict(self, job_id="job1", artist="Queen", title="Bohemian Rhapsody",
audio_search_artist=None, audio_search_title=None, status="complete"):
return {
"job_id": job_id,
"artist": artist,
"title": title,
"audio_search_artist": audio_search_artist,
"audio_search_title": audio_search_title,
"status": status,
"user_email": "admin@nomadkaraoke.com",
}
def test_search_filters_by_artist(self):
"""Search 'queen' should match job with artist='Queen'."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="j1", artist="Queen", title="We Will Rock You"),
self._make_job_dict(job_id="j2", artist="Eagles", title="Hotel California"),
]
result = _search_filter_jobs(jobs, "queen")
assert len(result) == 1
assert result[0]["job_id"] == "j1"
def test_search_filters_by_title(self):
"""Search 'california' should match job with title containing it."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="j1", artist="Queen", title="We Will Rock You"),
self._make_job_dict(job_id="j2", artist="Eagles", title="Hotel California"),
]
result = _search_filter_jobs(jobs, "california")
assert len(result) == 1
assert result[0]["job_id"] == "j2"
def test_search_filters_by_job_id(self):
"""Search by partial job_id."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="abc-123-def"),
self._make_job_dict(job_id="xyz-789-ghi"),
]
result = _search_filter_jobs(jobs, "abc-123")
assert len(result) == 1
assert result[0]["job_id"] == "abc-123-def"
def test_search_filters_by_audio_search_fields(self):
"""Search should also check audio_search_artist and audio_search_title."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="j1", artist="Display Name", title="Display Title",
audio_search_artist="Original Artist", audio_search_title="Original Song"),
]
result = _search_filter_jobs(jobs, "original artist")
assert len(result) == 1
def test_search_is_case_insensitive(self):
"""Search should be case-insensitive."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [self._make_job_dict(artist="QUEEN", title="Bohemian Rhapsody")]
result = _search_filter_jobs(jobs, "queen")
assert len(result) == 1
def test_search_handles_none_fields(self):
"""Search should not crash on None artist/title fields."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [self._make_job_dict(artist=None, title=None)]
result = _search_filter_jobs(jobs, "queen")
assert len(result) == 0
def test_search_empty_string_returns_all(self):
"""Empty search string should return all jobs."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="j1"),
self._make_job_dict(job_id="j2"),
]
result = _search_filter_jobs(jobs, "")
assert len(result) == 2
def test_search_returns_all_matches_for_limit_slicing(self):
"""Search returns all matches — caller applies limit separately."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [self._make_job_dict(job_id=f"j{i}", artist="Queen", title=f"Song {i}") for i in range(10)]
result = _search_filter_jobs(jobs, "queen")
assert len(result) == 10 # All 10 match; limit slicing is caller's job
# Verify caller can slice: simulates jobs_dicts[:limit] in route handler
assert len(result[:3]) == 3
+2
View File
@@ -141,6 +141,7 @@ GET /api/jobs?status=complete
GET /api/jobs?limit=10&offset=0
GET /api/jobs?exclude_test=false
GET /api/jobs?fields=summary&hide_completed=true
GET /api/jobs?fields=summary&search=bohemian
```
Query parameters:
@@ -149,6 +150,7 @@ Query parameters:
- `limit` / `offset` - Pagination
- `fields` (string, optional) - Set to `summary` to return only dashboard-required fields using Firestore field projection. Reduces payload from ~16MB to <500KB for large job lists.
- `hide_completed` (bool, default: false) - Exclude successful completions (complete, prep_complete) server-side. Failed jobs remain visible.
- `search` (string, optional) - Text search filter (summary mode only). Case-insensitive substring match against artist, title, audio_search_artist, audio_search_title, and job_id. When active, fetches up to 1000 results internally and filters in Python.
#### Delete Job
+3 -157
View File
@@ -2,7 +2,7 @@
* Unit tests for job-status.ts utility functions
*/
import { getJobStep, formatStepIndicator, isBlockingStatus, isNotifiableBlockingStatus, getJobProgressPercent, sortJobsByDate, getDisplayJobs, JobStep } from '../lib/job-status';
import { getJobStep, formatStepIndicator, isBlockingStatus, isNotifiableBlockingStatus, getJobProgressPercent, sortJobsByDate, JobStep } from '../lib/job-status';
import type { Job } from '../lib/api';
// Helper to create a minimal Job object for testing
@@ -556,159 +556,5 @@ describe('sortJobsByDate', () => {
});
});
describe('getDisplayJobs', () => {
// Helper: create jobs sorted by date (newest first)
function createDateSortedJobs(jobSpecs: Array<{ status: string; date: string }>): Job[] {
return jobSpecs
.map((spec, i) => ({
job_id: `job-${i}`,
status: spec.status,
progress: spec.status === 'complete' ? 100 : 0,
created_at: spec.date,
updated_at: spec.date,
}))
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
}
it('returns all active jobs when fewer than display limit (default hides completed/cancelled)', () => {
const jobs = createDateSortedJobs([
{ status: 'rendering_video', date: '2024-01-01T10:00:00Z' },
{ status: 'awaiting_review', date: '2024-01-01T11:00:00Z' },
{ status: 'failed', date: '2024-01-01T12:00:00Z' },
]);
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5);
expect(displayedJobs).toHaveLength(3);
expect(totalFetched).toBe(3);
});
it('returns empty array for empty input', () => {
const { displayedJobs, totalFetched } = getDisplayJobs([], 5);
expect(displayedJobs).toHaveLength(0);
expect(totalFetched).toBe(0);
});
it('limits to displayLimit', () => {
const jobs = createDateSortedJobs(
Array.from({ length: 10 }, (_, i) => ({ status: 'rendering_video', date: `2024-01-${String(i + 1).padStart(2, '0')}T12:00:00Z` }))
);
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5);
expect(displayedJobs).toHaveLength(5);
expect(totalFetched).toBe(10);
});
it('returns all jobs when displayLimit is -1 and showAll is true', () => {
const jobs = createDateSortedJobs(
Array.from({ length: 22 }, (_, i) => ({ status: 'complete', date: `2024-01-${String(i + 1).padStart(2, '0')}T12:00:00Z` }))
);
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, -1, true);
expect(displayedJobs).toHaveLength(22);
expect(totalFetched).toBe(22);
});
it('preserves date sort order from input', () => {
const jobs = createDateSortedJobs([
{ status: 'rendering_video', date: '2024-01-03T12:00:00Z' },
{ status: 'failed', date: '2024-01-04T12:00:00Z' },
{ status: 'awaiting_review', date: '2024-01-02T12:00:00Z' },
{ status: 'rendering_video', date: '2024-01-05T12:00:00Z' },
]);
const { displayedJobs } = getDisplayJobs(jobs, 10);
// Should be newest first
expect(displayedJobs[0].created_at).toBe('2024-01-05T12:00:00Z');
expect(displayedJobs[1].created_at).toBe('2024-01-04T12:00:00Z');
expect(displayedJobs[2].created_at).toBe('2024-01-03T12:00:00Z');
expect(displayedJobs[3].created_at).toBe('2024-01-02T12:00:00Z');
});
describe('default filtering (showAll=false)', () => {
it('hides complete, prep_complete, and cancelled by default (keeps failed and active)', () => {
const jobs = createDateSortedJobs([
{ status: 'awaiting_review', date: '2024-01-06T12:00:00Z' },
{ status: 'rendering_video', date: '2024-01-05T12:00:00Z' },
{ status: 'complete', date: '2024-01-04T12:00:00Z' },
{ status: 'failed', date: '2024-01-03T12:00:00Z' },
{ status: 'prep_complete', date: '2024-01-02T12:00:00Z' },
{ status: 'cancelled', date: '2024-01-01T12:00:00Z' },
]);
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, -1);
expect(totalFetched).toBe(6);
expect(displayedJobs).toHaveLength(3); // awaiting_review + rendering_video + failed
expect(displayedJobs.some(j => j.status === 'failed')).toBe(true);
expect(displayedJobs.some(j => j.status === 'complete')).toBe(false);
expect(displayedJobs.some(j => j.status === 'prep_complete')).toBe(false);
expect(displayedJobs.some(j => j.status === 'cancelled')).toBe(false);
});
it('respects display limit after filtering', () => {
const jobs = createDateSortedJobs([
{ status: 'rendering_video', date: '2024-01-10T12:00:00Z' },
{ status: 'rendering_video', date: '2024-01-09T12:00:00Z' },
{ status: 'rendering_video', date: '2024-01-08T12:00:00Z' },
{ status: 'rendering_video', date: '2024-01-07T12:00:00Z' },
{ status: 'rendering_video', date: '2024-01-06T12:00:00Z' },
{ status: 'rendering_video', date: '2024-01-05T12:00:00Z' },
{ status: 'rendering_video', date: '2024-01-04T12:00:00Z' },
...Array.from({ length: 10 }, (_, i) => ({ status: 'complete', date: `2024-01-${String(i + 1).padStart(2, '0')}T10:00:00Z` })),
]);
const { displayedJobs } = getDisplayJobs(jobs, 5);
// 7 active jobs after filtering, but limit is 5
expect(displayedJobs).toHaveLength(5);
});
it('returns empty when all jobs are terminal', () => {
const jobs = createDateSortedJobs([
...Array.from({ length: 5 }, (_, i) => ({ status: 'complete', date: `2024-01-${String(i + 1).padStart(2, '0')}T12:00:00Z` })),
...Array.from({ length: 3 }, (_, i) => ({ status: 'cancelled', date: `2024-01-${String(i + 6).padStart(2, '0')}T12:00:00Z` })),
]);
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5);
expect(displayedJobs).toHaveLength(0);
expect(totalFetched).toBe(8);
});
});
describe('showAll filter', () => {
it('shows all jobs including completed and cancelled when showAll is true', () => {
const jobs = createDateSortedJobs([
{ status: 'awaiting_review', date: '2024-01-04T12:00:00Z' },
{ status: 'complete', date: '2024-01-03T12:00:00Z' },
{ status: 'cancelled', date: '2024-01-02T12:00:00Z' },
{ status: 'failed', date: '2024-01-01T12:00:00Z' },
]);
const { displayedJobs } = getDisplayJobs(jobs, -1, true);
expect(displayedJobs).toHaveLength(4);
});
it('defaults to filtering when showAll is omitted', () => {
const jobs = createDateSortedJobs([
{ status: 'complete', date: '2024-01-02T12:00:00Z' },
{ status: 'failed', date: '2024-01-01T12:00:00Z' },
]);
const { displayedJobs } = getDisplayJobs(jobs, -1);
// Only failed should show (complete is hidden by default)
expect(displayedJobs).toHaveLength(1);
expect(displayedJobs[0].status).toBe('failed');
});
});
it('core bug fix: recently failed job appears at top of list (with showAll)', () => {
// The original bug: a newly failed job was invisible because priority sorting
// put all 45 complete jobs above it, and the limit of 10 truncated it.
// With date-based sorting, the newest job (failed) appears first.
const jobs = sortJobsByDate([
{ job_id: 'new-failed', status: 'failed', progress: 0, created_at: '2024-01-10T15:00:00Z', updated_at: '2024-01-10T15:00:00Z' },
...Array.from({ length: 45 }, (_, i) => ({
job_id: `complete-${i}`,
status: 'complete',
progress: 100,
created_at: `2024-01-${String(10 - Math.floor(i / 5)).padStart(2, '0')}T${String(12 - (i % 5)).padStart(2, '0')}:00:00Z`,
updated_at: '2024-01-01T00:00:00Z',
})),
]);
const { displayedJobs } = getDisplayJobs(jobs, 10, true);
// The failed job should be first (newest)
expect(displayedJobs[0].job_id).toBe('new-failed');
expect(displayedJobs[0].status).toBe('failed');
expect(displayedJobs).toHaveLength(10);
});
});
// Note: getDisplayJobs was removed — filtering is now handled server-side
// via the status and search query parameters on GET /api/jobs
+79 -50
View File
@@ -15,8 +15,8 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Music2, RefreshCw, Loader2, Moon, Sun, Eye, EyeOff, Gift, X, Shield, ShieldOff, HelpCircle, Mail, Phone } from "lucide-react"
import { sortJobsByDate, getDisplayJobs } from "@/lib/job-status"
import { Music2, RefreshCw, Loader2, Moon, Sun, Search, Gift, X, Shield, ShieldOff, HelpCircle, Mail, Phone } from "lucide-react"
import { sortJobsByDate } from "@/lib/job-status"
import { WarmingUpLoader } from "@/components/WarmingUpLoader"
import { JobCard } from "@/components/job"
import { GuidedJobFlow } from "@/components/job/GuidedJobFlow"
@@ -50,6 +50,7 @@ function AppPageContent() {
const [allJobs, setAllJobs] = useState<Job[]>([])
const [isLoadingJobs, setIsLoadingJobs] = useState(true)
const [isInitialLoad, setIsInitialLoad] = useState(true)
const [hasFetchedSuccessfully, setHasFetchedSuccessfully] = useState(false)
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null)
const [isVerifyingToken, setIsVerifyingToken] = useState(false)
const adminTokenHandled = useRef(false) // Track if admin_token was already processed
@@ -62,10 +63,12 @@ function AppPageContent() {
const saved = localStorage.getItem("nomad-karaoke-job-limit")
return saved ? Number(saved) : 10
})
const [showAll, setShowAll] = useState<boolean>(() => {
if (typeof window === "undefined") return false
return localStorage.getItem("nomad-karaoke-show-all") === "true"
const [statusFilter, setStatusFilter] = useState<string>(() => {
if (typeof window === "undefined") return "active"
return localStorage.getItem("nomad-karaoke-status-filter") || "active"
})
const [searchInput, setSearchInput] = useState("")
const [searchQuery, setSearchQuery] = useState("")
const [showAdminControls, setShowAdminControls] = useState<boolean>(() => {
if (typeof window === "undefined") return false
return localStorage.getItem("nomad-karaoke-admin-controls") === "true"
@@ -80,16 +83,16 @@ function AppPageContent() {
const isAdmin = user?.role === "admin" || user?.email?.endsWith("@nomadkaraoke.com")
// Filter out in-progress search jobs (managed by the guided flow, not standalone cards)
const visibleJobs = useMemo(
const jobs = useMemo(
() => allJobs.filter(job => job.status !== 'awaiting_audio_selection'),
[allJobs]
)
// Derive displayed jobs from visibleJobs + display limit + filter (instant, no re-fetch)
const { displayedJobs: jobs, totalFetched } = useMemo(
() => getDisplayJobs(visibleJobs, jobLimit, showAll),
[visibleJobs, jobLimit, showAll]
)
// Debounce search input — only update the query (which triggers API calls) after 300ms
useEffect(() => {
const timer = setTimeout(() => setSearchQuery(searchInput), 300)
return () => clearTimeout(timer)
}, [searchInput])
// Memoize loadJobs for use with visibility refresh
const loadJobs = useCallback(async () => {
@@ -99,24 +102,25 @@ function AppPageContent() {
return
}
try {
// Use summary mode for reduced payload (~12 fields instead of 50+)
const data = await api.listJobs({
limit: 100,
limit: jobLimit,
exclude_test: isAdmin ? !showTestData : undefined,
fields: 'summary',
status: statusFilter !== 'all' && statusFilter !== 'active' ? statusFilter : undefined,
hide_completed: statusFilter === 'active' ? true : undefined,
search: searchQuery || undefined,
})
// Sort by creation date (newest first)
setAllJobs(sortJobsByDate(data))
} catch (err: any) {
// Don't log auth errors - user just needs to authenticate
if (err?.status !== 401) {
console.error("Failed to load jobs:", err)
}
} finally {
setIsLoadingJobs(false)
setIsInitialLoad(false)
setHasFetchedSuccessfully(true)
}
}, [isAdmin, showTestData])
}, [isAdmin, showTestData, jobLimit, statusFilter, searchQuery])
// Enable notifications for job status changes (sound + title animation)
useJobNotifications(allJobs)
@@ -388,65 +392,90 @@ function AppPageContent() {
{/* Jobs List Card */}
<Card className="backdrop-blur min-w-0" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}>
<CardHeader className="px-3 sm:px-6">
<div className="flex items-center justify-between gap-2">
<CardTitle style={{ color: 'var(--text)' }}>Recent Jobs</CardTitle>
<div className="flex items-center justify-between gap-2 flex-wrap">
<div className="flex items-center gap-2">
<CardTitle style={{ color: 'var(--text)' }}>Recent Jobs</CardTitle>
{isLoadingJobs && <Loader2 className="w-4 h-4 animate-spin" style={{ color: 'var(--text-muted)' }} />}
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-7 w-7 p-0"
style={{ color: 'var(--text-muted)' }}
onClick={() => {
const next = !showAll
setShowAll(next)
localStorage.setItem("nomad-karaoke-show-all", String(next))
}}
>
{showAll ? <Eye className="w-3.5 h-3.5" /> : <EyeOff className="w-3.5 h-3.5" />}
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">
<p>{showAll ? "Hide completed/cancelled" : "Show all jobs"}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
<div className="flex items-center gap-2 flex-wrap">
<div className="relative">
<Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5" style={{ color: 'var(--text-muted)' }} />
<input
type="text"
placeholder="Search..."
aria-label="Search jobs"
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
className="h-7 w-[160px] sm:w-[200px] text-xs rounded-md border pl-7 pr-2"
style={{
backgroundColor: 'var(--input)',
borderColor: 'var(--border)',
color: 'var(--text)',
}}
/>
</div>
<Select value={statusFilter} onValueChange={(v) => {
setStatusFilter(v)
localStorage.setItem("nomad-karaoke-status-filter", v)
}}>
<SelectTrigger className="h-7 w-[130px] text-xs" aria-label="Filter by status">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All statuses</SelectItem>
<SelectItem value="active">Active</SelectItem>
<SelectItem value="failed">Failed</SelectItem>
<SelectItem value="complete">Completed</SelectItem>
<SelectItem value="cancelled">Cancelled</SelectItem>
<SelectItem value="awaiting_review">Awaiting review</SelectItem>
<SelectItem value="processing">Processing</SelectItem>
</SelectContent>
</Select>
<Select value={String(jobLimit)} onValueChange={(v) => {
const val = Number(v)
setJobLimit(val)
localStorage.setItem("nomad-karaoke-job-limit", String(val))
}}>
<SelectTrigger className="h-7 w-[80px] text-xs">
<SelectTrigger className="h-7 w-[70px] text-xs" aria-label="Results per page">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="5">5</SelectItem>
<SelectItem value="10">10</SelectItem>
<SelectItem value="20">20</SelectItem>
<SelectItem value="-1">All</SelectItem>
<SelectItem value="50">50</SelectItem>
<SelectItem value="100">100</SelectItem>
<SelectItem value="1000">1000</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<CardDescription style={{ color: 'var(--text-muted)' }}>
{!showAll
? `${jobs.length} active of ${totalFetched} total`
: jobs.length < totalFetched
? `Showing ${jobs.length} of ${totalFetched} jobs`
{!hasFetchedSuccessfully
? 'Loading...'
: searchQuery || statusFilter !== 'active'
? `${jobs.length} job${jobs.length !== 1 ? 's' : ''} matching filters`
: `${jobs.length} job${jobs.length !== 1 ? 's' : ''}`}
</CardDescription>
</CardHeader>
<CardContent className="px-3 sm:px-6">
{jobs.length === 0 ? (
<div className="text-center py-8" style={{ color: 'var(--text-muted)' }}>
<Music2 className="w-12 h-12 mx-auto mb-3 opacity-50" />
{totalFetched > 0 ? (
<p>No active jobs. Click the eye icon above to show all {totalFetched} job{totalFetched !== 1 ? 's' : ''}.</p>
{!hasFetchedSuccessfully ? (
<>
<Loader2 className="w-12 h-12 mx-auto mb-3 opacity-50 animate-spin" />
<p>Loading jobs...</p>
</>
) : searchQuery || statusFilter !== 'active' ? (
<>
<Search className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p>No jobs match your filters.</p>
</>
) : (
<p>No jobs yet. Create one to get started!</p>
<>
<Music2 className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p>No jobs yet. Create one to get started!</p>
</>
)}
</div>
) : (
+2
View File
@@ -427,6 +427,7 @@ export const api = {
exclude_test?: boolean;
fields?: 'summary';
hide_completed?: boolean;
search?: string;
}): Promise<Job[]> {
const searchParams = new URLSearchParams();
if (params?.status) searchParams.set('status', params.status);
@@ -434,6 +435,7 @@ export const api = {
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
if (params?.fields) searchParams.set('fields', params.fields);
if (params?.hide_completed !== undefined) searchParams.set('hide_completed', String(params.hide_completed));
if (params?.search) searchParams.set('search', params.search);
const url = `${API_BASE_URL}/api/jobs${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await fetch(url, {
-39
View File
@@ -294,42 +294,3 @@ export function sortJobsByDate(jobs: Job[]): Job[] {
});
}
/**
* Statuses hidden by default (shown only when showAll is true).
*/
const _HIDDEN_STATUSES = ["complete", "prep_complete", "cancelled"]
/**
* Select which jobs to display from a sorted list.
* By default, hides completed and cancelled jobs. When showAll is true, shows everything.
*
* @param sortedJobs - Jobs already sorted by sortJobsByDate
* @param displayLimit - Max jobs to show (-1 = show all)
* @param showAll - When true, show all jobs including completed and cancelled
* @returns Object with displayedJobs array and totalFetched count
*/
export function getDisplayJobs(
sortedJobs: Job[],
displayLimit: number,
showAll: boolean = false
): { displayedJobs: Job[]; totalFetched: number } {
const totalFetched = sortedJobs.length;
// By default, hide completed and cancelled jobs (keep failed/active visible)
const filteredJobs = showAll
? sortedJobs
: sortedJobs.filter((job) => {
const status = job.status?.toLowerCase() || ""
return !_HIDDEN_STATUSES.includes(status)
});
// Show all: -1 or fewer jobs than limit
if (displayLimit === -1 || filteredJobs.length <= displayLimit) {
return { displayedJobs: filteredJobs, totalFetched };
}
return {
displayedJobs: filteredJobs.slice(0, displayLimit),
totalFetched,
};
}
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.154.2"
version = "0.155.1"
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"