11 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 5.5 8490ab75eb chore(gemini): move every Gemini call from Vertex AI to the Gemini Developer API (#1108)
## Summary
Moves **every** Gemini call in gen off **Vertex AI** (billed to the
`nomadkaraoke` GCP project, ~$85/mo) onto the **Gemini Developer API**
using the `gemini-api-key` Secret Manager secret (an AI Studio key
billed outside this project). Once deployed and verified,
`aiplatform.googleapis.com` / `generativelanguage.googleapis.com` get
disabled in nomadkaraoke.

### Key injection
- `backend/services/gemini_client.get_genai_client(timeout_ms)` — key
from `GEMINI_API_KEY`, else Secret Manager `gemini-api-key` via
`settings.get_secret` (runtime SA already has project-level
`secretAccessor`). No `project`/`location`.
- Service: CI `--set-secrets ... GEMINI_API_KEY=gemini-api-key:latest`.
- Jobs: Pulumi secret env on `lyrics-transcription-job`,
`video-encoding-job` (renders + translations), `nomad-error-monitor` —
**already applied** (targeted `pulumi up`, only that env added). Other
jobs fall back to Secret Manager.
- Local scripts (`frontend/scripts/translate.py`,
`scripts/measure_autocorrect_cost.py`,
`scripts/test_agentic_correction.py`): env, else `gcloud secrets
versions access` (in-process only).
- **Rotation:** add a new secret version; new instances / job executions
pick it up. No code change.

### Degradation (quota / billing / invalid key; per-minute 429s stay
retryable)
| Caller | Behaviour |
|---|---|
| auto-correct | non-retryable 503 → compare mode drops the Gemini leg,
keeps Opus |
| match-judge / free-text / parse-titles / tenant bulk | existing
fallbacks (no suggestion / blanks / regex) |
| credit eval | `pending_review` (fail-closed, unchanged) |
| lyrics translation | no retry; render proceeds without translation,
status recorded |
| custom lyrics | clean 503 "temporarily unavailable…" (+ 5-min timeout
so it can't hang) |
| error-monitor LLM | no retry; alerts sent without AI summary |
| translate.py | exit 2 "Gemini quota/credit exhausted — top up AI
Studio or rotate gemini-api-key" |

`note_gemini_failure()` also sends one Discord ops alert per 6h
(Firestore-throttled across instances via new
`ops_alerts.send_throttled_ops_alert`).

### Infra
- Pulumi: removes `roles/aiplatform.user` from `karaoke-backend` —
**will be applied after this deploys and Vertex traffic is confirmed at
zero**.
- Agentic correction default model `gemini/gemini-3.8-flash`
(`vertexai/` prefix still accepted, routed to the Developer API).
- Version 0.261.1 → 0.262.0. Docs: CLAUDE.md, LESSONS-LEARNED, README,
ARCHITECTURE, API, etc.

## Testing
- New: `backend/tests/services/test_backend_gemini_client.py`
(classifier, key resolution, no-Vertex client kwargs, alert throttle,
per-caller degradation),
`tests/unit/lyrics_transcriber/test_agentic_gemini_provider.py`,
`frontend/scripts/test_gemini_client.py`, lyrics-translation quota test.
- `pytest backend/tests --ignore=backend/tests/emulator` — all pass;
`pytest tests/unit` — 2021 passed.
- Verified `gemini-3.8-flash` is listed on the Developer API and
answered a 5-token test call with the key.
- `translate.py --dry-run` on `frontend/messages` and
`backend/translations` OK.

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


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Updates**
* AI-powered lyric translation, custom lyrics, auto-correction, title
parsing, match judging, and related features now use the Gemini
Developer API.
* AI features use the configured Gemini API key. Quota, billing, or key
issues may show an unavailable message or use an existing fallback
instead of repeated attempts.
* **Documentation**
* Updated product, API, setup, and recovery guidance to reflect Gemini
API key configuration and usage.
* Updated guidance for handling AI service availability and quota
issues.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 21:58:53 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 17d60c58a0 fix(cost): low Gemini thinking for simple callers + dedupe proactive auto-correct (#1105)
## Summary
GCP cost cut: Vertex Gemini 3.8 Flash is now the largest variable cost
(~$85-90/mo), mostly thinking tokens.

### 1. `thinking_level="low"` for simple extraction/classification
callers
| Caller | Model setting | Before | After |
|---|---|---|---|
| `match_judge/ai.py`, `match_judge/free_text.py` | `match_judge_model`
| default (high/dynamic) | low |
| `tenant_bulk/analyze.py` (filename pairing) | `match_judge_model` |
default | low |
| `parse_titles/ai.py` | `parse_titles_model` | default | low |
| `credit_evaluation_service.py` (grant/deny) | `credit_eval_model` |
default | low |
| `frontend/scripts/translate.py` | n/a | medium | low |

**Unchanged on purpose:** auto-correct (quality eval), custom lyrics,
lyrics translation, and agentic correction (`agentic_ai_model` is
dormant because `SKIP_CORRECTION=true`; its router makes no LLM call).

Timeouts: low thinking only makes these calls faster, so the existing
deadlines (`match_judge_timeout_ms` 12s, `parse_titles_timeout_ms` 20s)
need no change.

**Live check (Vertex, ADC):** 8 match-judge cases plus a 4-file
parse-titles batch, default vs low. Same canonical artist/title on every
case and identical parses. One verdict changed: `beatles/hey jude` went
from content to cosmetic, and cosmetic is the correct label for a
casing/"The" fix. Thinking tokens dropped from 1519 to 167, and max
latency from 5.5s to 2.7s.
**translate.py A/B:** 5 ICU-plural/placeholder strings into es/de/ja/ar.
Low used 0 thinking tokens and medium used ~33k. Both preserved all
placeholders and produced equivalent quality.

### 2. Duplicate proactive auto-correct (job 96cf1100 and about 55% of
jobs)
Root cause: the lyrics worker calls `advance_to_screens_if_ready`
*before* `_trigger_proactive_auto_correct`. The screens worker's
`ensure_and_pre_apply` checks the suggestion cache while the proactive
run is still in flight, gets a miss, and starts a second identical
multi-model run (Claude Opus plus Gemini). In job 96cf1100 both runs
were on the same instance and finished 4s apart. From prod logs for
2026-09-17 to 10-01: **92 of 167 jobs generated twice** (9 of them
across instances), at about $0.07 per duplicate.

Fix (`backend/workers/auto_correct_worker.py`):
- In-process single-flight per job. A concurrent caller awaits the
in-flight task, shielded so it can't cancel it.
- Cross-instance GCS lease
(`jobs/{id}/lyrics/auto_correct_inflight.json`) with generation fencing
(create-only; stale takeover and release only against the observed/own
generation; owner token; 240s TTL; timed-out run keeps its lease). A
non-holder polls off the event loop for the holder's cache for up to
150s instead of regenerating. If the holder fails, the UI's existing
on-demand fallback takes over.

## Tests
- `backend/tests/test_proactive_auto_correct.py`: concurrent calls share
one run (fails on old code), waiting on a peer's lease, taking over a
stale lease, and not regenerating after a peer fails.
- `backend/tests/test_gemini_thinking_level.py`: each changed caller
sends `thinking_level=low`.
- Related suites pass locally. `test_internal_api.py` has 7 failures
locally that also fail on `origin/main` (local env).

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

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Improvements**
* AI-powered features now use a lower thinking level for tasks such as
title parsing, match evaluation, credit evaluation, bulk analysis, and
translation.
* Proactive auto-correct now coordinates concurrent suggestion requests,
reuses completed suggestions, and avoids starting a duplicate run when
another request is already in progress.
* If another request ends without producing suggestions, auto-correct
skips the request rather than immediately generating them again.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 19:35:22 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 e9465c73d4 chore: gemini-3.8-flash everywhere + auto-correct on Opus 5.5 (cost) (#1054)
## Why
GCP credits expired 2026-09-19; Vertex Gemini 3.1 Pro spend had grown $9
→ $37 → $105/30d. `gemini-3.8-flash` is $0.75/$3.75 per 1M (vs $2/$12
for 3.1 Pro; rises to $1.50/$7.50 on 2027-01-01). Opus 5.5 is $4/$20 (vs
$5/$25 for 4.8).

## Changes
- All Gemini defaults → `gemini-3.8-flash`: credit eval, custom lyrics,
auto-correct (default + compare leg), match judge, parse titles, tenant
bulk analyze, agentic AI router, error-monitor LLM analysis (also
`us-central1` → `global`, required for Gemini 3.x), frontend
`translate.py`.
- Auto-correct Claude leg `claude-opus-4-8` → `claude-opus-5-5` (ci.yml
env), with `effort: "high"` pinned (5.5 defaults to medium). Pricing
table gains both new models.
- Docs updated; version 0.241.1.

## Evidence (12 recent prod jobs, pre-review lyrics scored against the
human-reviewed final)
| Model | Precision | Word-level recall | $/job |
|---|---|---|---|
| gemini-3.1-pro-preview | 91% | 74% | $0.067 |
| gemini-3.8-flash | 98% | 38–41% | $0.020 |
| gemini-3.8-flash @ high thinking | 97% | 60% (4/12 timed out, 504) |
$0.041 |
| claude-opus-4-8 | 94% | 33% | $0.080 |
| claude-opus-5-5 (effort high) | 93% | 58% | $0.048 |

Flash for the Gemini leg is a deliberate cost/recall trade-off (Andrew
chose it); Opus 5.5 more than compensates. Also verified:
`gemini-3.8-flash` works on Vertex `global` (rejects
`thinking_level=minimal`; nothing here uses it), match-judge latency
median 3.3s / max 6.2s (< 12s timeout), Japanese translation smoke test
preserves ICU placeholders. Translation cache is keyed on English text +
locale, so no re-translation churn.

Tests: auto_correct, credit eval, custom lyrics, parse_titles,
error_monitor, agentic router suites pass locally.

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

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* AI-powered correction, translation, matching, title parsing, and
evaluation now use updated models, including Gemini 3.8 Flash and Claude
Opus 5.5.
* **Updates**
* AI service pricing reflects scheduled rate changes, including a Gemini
3.8 Flash rate change beginning January 1, 2027.
  * Application version updated to 0.241.1.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 14:53:04 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 6445864534 feat: frontend crash reporting → Discord alerts + auto cache bust (#725)
@coderabbitai ignore

## Summary

Gives us long-term peace of mind that frontend errors never reach users
silently. Every client-side crash is captured, shown to the user with
useful debug info, reported to the backend, alerted via the existing
Discord error channel, and — critically — after a fix ships, affected
users pick it up automatically.

## What this does

- **Backend endpoint** `POST /api/client-errors` — normalises inbound
reports and upserts into the same `error_patterns` Firestore collection
the backend already uses. No new Discord wiring needed:
`service="frontend"` patterns flow through the existing error-monitor
Cloud Run Job → Discord pipeline.
- **Three capture layers on the frontend**:
- Global `window.onerror` + `unhandledrejection` listeners (mounted once
per tab via `ClientErrorInit` in the locale layout)
- Next.js App Router `error.tsx` (per-locale) + `global-error.tsx`
(last-resort root)
- React `CrashReportBoundary` wrapping `LyricsReviewWrapper` +
`InstrumentalReviewWrapper` so a crash there renders in place rather
than white-screening the route
- **User-facing `CrashReport` card** — shows error name/message +
collapsible stack + debug info + build SHA; auto-sends on mount (catches
bugs in the wild without user action); has Copy / Send again / Try again
/ Back buttons.
- **Version-aware cache busting** so the next bug I fix actually reaches
affected users:
- `public/version.json` emitted at build time via a new `prebuild` hook.
- `isStale()` compares the compiled `NEXT_PUBLIC_COMMIT_SHA` against the
live `/version.json`.
- `ChunkLoadError` in the global handlers triggers a hard reload
(unregisters SWs, clears caches, navigates with `?_v=<sha>`
query-string) behind a 60 s circuit breaker to prevent reload loops.
- `CrashReport` shows a prominent "A newer version is available — Update
now" banner when stale; demotes "Try again" to secondary in that case.
- Ambient 10-minute poll dispatches a `karaoke:stale-version`
CustomEvent (no auto-reload ambient — only on crash).
- **Admin `/admin/_crash-test` page** — three buttons that fire async
throw / unhandled rejection / render-time throw, for post-deploy
pipeline verification.
- **Rate limiting** on the endpoint: 60/min per IP sliding window, plus
pattern-hash dedup collapsing viral bugs to a single pattern.
- **Privacy**: URL query strings + fragments stripped; user email only
sent if authenticated; no cookies / localStorage / form-value capture.
- **i18n**: `crashReport` namespace in `en.json` translated into all 32
locales.

Reuses existing env var `NEXT_PUBLIC_COMMIT_SHA` — no new build config.

## Review & verification

- 49 Jest suites / 800 tests pass (`make test`).
- New unit tests: `crash-reporter.test.ts`, `CrashReport.test.tsx`,
`CrashReportBoundary.test.tsx`, `version-check.test.ts`,
`test_frontend_ingestion.py`, `test_client_errors.py` — all green.
- Implemented task-by-task via subagent-driven workflow with spec + code
quality review per task (see
`docs/archive/2026-04-19-frontend-crash-reporting-plan.md`).
- E2E Playwright test deferred — the admin crash-test page covers manual
post-deploy verification.

## Test plan

- [ ] Deploy to prod.
- [ ] Visit `https://gen.nomadkaraoke.com/admin/_crash-test` as admin;
click each of the three buttons.
- [ ] Confirm a Discord alert arrives in the error channel (may take up
to ~15 min per the monitor Cloud Run schedule).
- [ ] Verify Firestore `error_patterns` contains 3 new docs with
`service="frontend"`.
- [ ] In a separate browser session already open to the app, simulate a
stale-bundle scenario (edit `public/version.json` on the CDN, or use an
older tab after a new deploy) — confirm `CrashReport` shows the "Update
now" banner if an error is thrown.
- [ ] Test the original Firefox Android bug (if it reproduces) and
verify the crash now lands in Discord with a usable stack trace.

## Follow-ups

- Source-map upload for readable production stacks (`Task 15` in the
plan).
- Consider forwarding the `source` payload field into
`PatternData.sample_message` if finer-grained Discord triage
(`window.onerror` vs `unhandledrejection` vs boundary) becomes valuable.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 21:14:12 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 9283d3c1ae feat: referral discount details UX + translation pipeline fix (#701)
@coderabbitai ignore

## Summary

- **Clickable "discount active" in dropdown**: Users who dismissed the
referral discount banner can click "discount active" in the user
dropdown to re-show it (clears localStorage dismissal, navigates to
dashboard)
- **Richer Buy Credits dialog**: Fetches and displays referrer's display
name and referral code alongside existing discount % and expiration info
- **Backend**: `no_track` query param on `GET /api/referrals/r/{code}`
to skip click tracking for display-only fetches
- **Translation pipeline fix**: `translate.py` dry-run no longer saves
snapshot (was causing subsequent runs to skip all translations), and
added missing-keys mode that compares against existing locale files
instead of re-translating everything when no snapshot exists

## Test plan

- [x] Backend unit test for `no_track=true` param
- [x] Frontend AuthStatus test updated with `next/navigation` mock
- [x] All 721 frontend tests passing
- [x] All backend tests passing
- [ ] Manual: dismiss discount banner → click "discount active" in
dropdown → verify banner re-appears on dashboard
- [ ] Manual: open Buy Credits dialog → verify referrer name and code
shown
- [ ] Manual: run `translate.py --dry-run` → verify snapshot not saved

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 18:19:03 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 04c7197445 feat(i18n): add translation cache, CI validation, and enforcement (#693)
## Summary
@coderabbitai ignore

- Add GCS translation cache (`translation_cache.py`) to `translate.py`
for instant repeated translations
- Add `--no-cache`, `--dry-run`, `--cache-bucket` CLI flags to
translation script
- Add `translation-check` CI job that validates all 33 locale files have
matching keys
- Add `.githooks/pre-commit` hook for auto-translation when `en.json`
changes
- Add i18n section to CLAUDE.md documenting 33-locale support and
enforcement rules

## Test plan
- [ ] `python frontend/scripts/translate.py --messages-dir
frontend/messages --target es --dry-run` shows cache stats
- [ ] `python frontend/scripts/validate-translations.py --messages-dir
frontend/messages` passes
- [ ] CI `translation-check` job runs on PR

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 01:22:39 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 ab330a3ed6 feat(i18n): scale to 33 languages with RTL support (#666)
## Summary
- Scale i18n from 3 languages (en/es/de) to 33 languages
- Upgrade translation pipeline: async parallel execution (5 concurrent)
+ incremental delta detection
- Add RTL support (`dir="rtl"`) for Arabic and Hebrew
- Replace LanguageSwitcher `<select>` with grouped scrollable dropdown
(flags + native names)
- RTL CSS audit: convert directional properties to logical equivalents
- 30 new frontend translation files (1062 keys each) + 30 backend files
(274 keys each)

### New languages
Portuguese, French, Japanese, Korean, Chinese, Italian, Dutch, Polish,
Turkish, Russian, Thai, Indonesian, Vietnamese, Filipino, Hindi, Arabic,
Swedish, Norwegian, Danish, Finnish, Czech, Romanian, Hungarian, Greek,
Hebrew, Malay, Ukrainian, Croatian, Slovak, Catalan

## Test plan
- [x] `next build` — 285 static pages generated (11 pages x 33 locales -
some deduped)
- [x] All translation files have 100% key parity
- [ ] Post-deploy: verify Japanese, Arabic (RTL), Portuguese render
correctly
- [ ] Post-deploy: verify LanguageSwitcher shows all 33 options

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 05:08:47 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8c1dfe5460 feat(i18n): Phase 3 frontend — next-intl infrastructure + 1062 strings (en/es/de) (#656)
@coderabbitai ignore

## Summary
- Phase 3 of the i18n multilingual initiative — makes the karaoke-gen
frontend fully multilingual (English, Spanish, German)
- Installs `next-intl` with `[locale]` path-based routing,
LanguageSwitcher, and `Accept-Language` API header
- Extracts **1,062 strings** from ~70 components into `messages/en.json`
across 31 namespaces
- Wires `useTranslations()` into all user-facing components (landing,
dashboard, auth, job flow, lyrics review, instrumental review, audio
editor, etc.)
- Admin pages (`/admin/*`) stay outside locale routing — intentionally
excluded from i18n scope
- Static export generates `/en/`, `/es/`, `/de/` directories (45 total
pages) for Cloudflare Pages
- `es.json`/`de.json` are English placeholders — translation via Gemini
pipeline pending
- Translation pipeline (`scripts/translate.py`) and glossary (55
karaoke-specific terms) included

## Key architecture decisions
- Root layout keeps ThemeProvider/TenantProvider (needed by admin pages
outside `[locale]`)
- Only NextIntlClientProvider added to `[locale]/layout.tsx`
- `job-status.ts` labels converted to translation keys; consumers
translate via `useTranslations('jobStatus')`
- Jest mock loads actual `en.json` so existing tests validate i18n
wiring without assertion changes

## Test plan
- [x] All 707 frontend tests pass (39 suites)
- [x] Static build generates all 45 pages across 3 locales
- [x] Admin pages render at `/admin/` without locale prefix
- [x] CodeRabbit review: 4 issues fixed, 7 pre-existing noted
- [ ] Post-deploy: verify `/en/` landing page renders correctly
- [ ] Post-deploy: verify LanguageSwitcher redirects to `/es/` and
`/de/`
- [ ] Post-deploy: verify `/admin/` still works without locale context

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 21:50:53 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 30105b1ad1 Update homepage screenshots and add demo recording tooling (#429)
## Summary
- Replace all 4 homepage AVIF screenshots with fresh captures from
production E2E test reflecting recent UX improvements
- Update screenshot labels and descriptions in landing page (page.tsx)
- Add demo video recording infrastructure: Playwright config, E2E spec,
and ffmpeg post-processing script
- Refresh all 16 docs/images screenshots from latest E2E happy path run

## Changes
- **Homepage screenshots**: Replaced job-dashboard, lyrics-review,
instrumental-review, and example-output AVIF/PNG files
- **Landing page copy**: Updated alt text, titles, descriptions to match
new UX (e.g., "Create Your Video", "Review Lyrics", "Choose Your
Instrumental", "Download & Share")
- **Demo tooling**: `playwright.demo.config.ts` (1280x720 recording),
`demo-recording.spec.ts` (paced walkthrough), `create-demo-video.mjs`
(ffmpeg post-processor)
- **npm scripts**: Added `test:e2e:demo`, `test:e2e:demo:headed`,
`demo:create-video`

## Test plan
- [x] All 483 unit tests pass
- [x] Next.js build succeeds
- [x] Screenshots verified from production E2E run
- [x] Demo recording spec tested against production (18.8 min run, all
10 scenes captured)

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 18:59:25 -05:00
Andrew Beveridge ☄️andClaude Opus 4.5 a1f9da2fb5 Implement hash-based routing for job review/instrumental pages (#311)
## Summary
- Switch from path-based routing (`/app/jobs/{id}/review`) to hash-based
routing (`/app/jobs#/{id}/review`)
- Eliminates the need for SPA redirect workarounds on static hosts
- URLs now correctly reflect the current view and survive page reload

## Benefits
- **Clean URLs**: URL always shows which job is being viewed
- **Reload works**: Browser hash is preserved, no sessionStorage needed
- **Simpler code**: Removed 100+ lines of SPA redirect logic
- **Universal compatibility**: Works on any static host

## Changes
**Frontend:**
- `client.tsx`: Parse route from URL hash instead of path/sessionStorage
- `JobCard.tsx`: Update link hrefs to hash-based format
- Remove SPA redirect script injection
- Remove Cloudflare rewrite rules (no longer needed)

**Backend:**
- `job_notification_service.py`: Update email URLs to new format
- Updated tests

## URL Format
- Old: `https://gen.nomadkaraoke.com/app/jobs/26391a79/review`
- New: `https://gen.nomadkaraoke.com/app/jobs#/26391a79/review`

Note: Local mode still uses path-based routing for compatibility with
dev server.

## Test plan
- [x] Frontend build passes
- [x] Frontend tests pass (JobCard)
- [x] Backend tests pass (job_notification_service)
- [ ] Manual: Click "Review Lyrics" button - navigates to hash URL
- [ ] Manual: Reload page - stays on same view
- [ ] Manual: Email link works with new format

@coderabbitai ignore

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 16:36:26 -08:00
Andrew Beveridge ☄️andClaude Opus 4.5 eaa4bc8415 fix(frontend): Add SPA routing for dynamic job URLs on GitHub Pages (#303)
## Summary
- Fix 404 errors for dynamic job URLs (e.g.,
`/app/jobs/26391a79/review/`) after frontend consolidation
- Implement SPA redirect pattern for GitHub Pages static export
- Add post-build script that injects redirect logic into 404.html
- Add path restoration in JobRouterClient via sessionStorage

## Problem
The frontend consolidation introduced a catch-all route
`/app/jobs/[[...slug]]` for dynamic job IDs. With Next.js static export
on GitHub Pages, only pre-rendered paths work. Dynamic paths like
`/app/jobs/26391a79/review/` resulted in 404s because they're not
pre-generated at build time.

## Solution
Implemented the SPA redirect pattern:
1. **404.html script** - Detects `/app/jobs/*` URLs, stores path in
sessionStorage, redirects to `/app/jobs/`
2. **JobRouterClient** - On mount, reads sessionStorage and navigates to
the correct route

Flow:
```
User visits /app/jobs/26391a79/review/
    ↓
GitHub Pages serves 404.html (path doesn't exist as static file)
    ↓
Injected script detects /app/jobs/* pattern
    ↓
Stores path in sessionStorage, redirects to /app/jobs/
    ↓
JobRouterClient loads, reads sessionStorage
    ↓
Navigates to /app/jobs/26391a79/review/ with correct component
```

## Test plan
- [x] All backend tests pass (1593 tests)
- [x] All frontend unit tests pass (181 tests)
- [x] Build succeeds with post-build script injection
- [ ] Manual: Verify `/app/jobs/{id}/review` loads correctly in
production

## Files Changed
- `frontend/scripts/spa-redirect-404.js` - Post-build script to inject
redirect
- `frontend/app/app/jobs/[[...slug]]/client.tsx` - Path restoration
logic
- `frontend/package.json` - Updated build script
- `frontend/public/_redirects` - For potential Cloudflare Pages
migration

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 12:31:51 -08:00