Compare commits

...
Author SHA1 Message Date
Andrew Beveridge ☄️ 1bc6dbe1a2 Merge pull request #100 from nomadkaraoke/fix/upload-endpoint-theme-support
Fix: Add theme support to /api/jobs/upload endpoint
2025-12-28 13:27:23 -05:00
Andrew Beveridge ☄️ 71b33a6b93 Merge pull request #101 from nomadkaraoke/feature/multiple-runners
feat: scale to 5 self-hosted GitHub runners for parallel CI jobs
2025-12-28 13:26:04 -05:00
Andrew BeveridgeandClaude Opus 4.5 c3e1edfcb4 feat: scale to 5 self-hosted GitHub runners for parallel CI jobs
- Replace single github-runner VM with 5 instances (github-runner-1 through 5)
- Enables parallel job execution across multiple PRs
- Each runner: e2-standard-4, 200GB SSD, same tooling
- Update README with new runner count and troubleshooting commands

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 13:11:49 -05:00
Andrew BeveridgeandClaude Opus 4.5 44c591a629 Fix: Add theme support to /api/jobs/upload endpoint
The /api/jobs/upload endpoint was missing theme_id and color_overrides
parameters, causing themes selected in the frontend to not be passed
through when creating jobs via file upload. This resulted in preview
videos having black backgrounds instead of themed backgrounds.

Changes:
- Add theme_id and color_overrides Form parameters to upload endpoint
- Change enable_cdg/enable_txt to Optional[bool] for smart defaults
- Add _resolve_cdg_txt_defaults() to enable CDG/TXT when theme is set
- Add _prepare_theme_for_job() call when theme_id is set (no custom style files)
- Pass theme_id and color_overrides to JobCreate
- Use theme's YouTube description template if no custom one provided

Root cause: The frontend was sending theme_id in the form data, but the
backend endpoint was not accepting this parameter, so it was silently
ignored. PR #72 fixed this for audio_search.py but this endpoint was missed.

Fixes issue where job c9516773 (file upload) had black background while
job 47475700 (song search) correctly showed themed background.

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 12:32:18 -05:00
Andrew Beveridge ☄️ 2203595e51 Merge pull request #99 from nomadkaraoke/feature/coderabbit-review-command
feat: add /coderabbit-review slash command
2025-12-28 12:17:40 -05:00
Andrew BeveridgeandClaude Opus 4.5 635c4e7ee6 feat: add /coderabbit-review slash command
Adds a Claude Code slash command that reviews and addresses CodeRabbit
comments on the current PR:
- Fetches both review threads and nitpick comments
- Analyzes each comment and decides if action is needed
- Makes appropriate code fixes
- Commits/pushes changes and resolves threads

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 12:16:28 -05:00
Andrew Beveridge ☄️ 1c5711cfa5 Merge pull request #98 from nomadkaraoke/docs/runner-setup
docs: add self-hosted runner documentation
2025-12-28 12:06:31 -05:00
Andrew Beveridge ☄️ 08d7db9943 Merge pull request #97 from nomadkaraoke/fix/runner-startup-script
fix: make runner startup script reproducible
2025-12-28 12:06:24 -05:00
Andrew BeveridgeandClaude Opus 4.5 7b5a150e81 docs: add self-hosted runner documentation
- Update README.md with CI/CD runner status
- Add lessons learned for self-hosted runner setup
- Create archive doc with full implementation details

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 12:05:27 -05:00
Andrew BeveridgeandClaude Opus 4.5 d2c8c24eee fix: make runner startup script reproducible
Fixes issues discovered during initial runner setup:

- Use `gpg --batch` for all GPG commands to avoid tty errors
- Install Python 3.13 via pyenv (not broken PPA/source build)
- Set up Python 3.13 in tool cache for setup-python action
- Use Temurin directly for Java 21 (skip broken Debian repos)

These changes ensure the runner VM can be recreated from scratch
and work correctly with GitHub Actions setup-python.

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 12:03:10 -05:00
Andrew Beveridge ☄️ 0b57b8f610 Merge pull request #95 from nomadkaraoke/feature/self-hosted-runner
feat: add self-hosted GitHub Actions runner on GCP
2025-12-28 11:51:59 -05:00
Andrew BeveridgeandClaude Opus 4.5 050ca6a441 fix: add setup-python and install-poetry to self-hosted runner jobs
Addresses CodeRabbit review feedback - the self-hosted runner jobs
need proper Python and Poetry setup via actions rather than relying
on pre-installed versions. This ensures Python 3.13 compatibility.

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 11:49:09 -05:00
Andrew BeveridgeandClaude Opus 4.5 2725352d89 feat: add self-hosted GitHub Actions runner on GCP
Adds a dedicated GCP VM (e2-standard-4, 200GB SSD) to run GitHub Actions
jobs that were hitting disk space limits on GitHub-hosted runners (14GB).

Infrastructure changes:
- New service account `github-runner` with minimal permissions
- Secret Manager secret for GitHub PAT (runner registration)
- Compute instance with startup script that installs Docker, Python 3.13,
  Node.js 20, Java 21, Poetry, FFmpeg, and registers as a GitHub runner

Workflow changes:
- `package-build-test` now uses self-hosted runner
- `backend-unit-tests` now uses self-hosted runner
- `backend-emulator-tests` now uses self-hosted runner
- `deploy-backend` now uses self-hosted runner
- Removed disk cleanup steps (no longer needed with 200GB)

Setup requires adding GitHub PAT to Secret Manager after `pulumi up`:
  echo -n "ghp_xxx" | gcloud secrets versions add github-runner-pat --data-file=-

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 11:18:50 -05:00
Andrew Beveridge ☄️ 762cdf03c9 Merge pull request #94 from nomadkaraoke/fix/pip-install-quotes-91
docs: Add quotes to pip install commands for cross-shell compatibility
2025-12-28 11:11:47 -05:00
Andrew BeveridgeandClaude Opus 4.5 7df3a21525 docs: Add quotes to pip install commands for cross-shell compatibility
Wrap package names with extras notation in double quotes to prevent
zsh and other shells from interpreting square brackets as glob patterns.

Fixes #91

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 11:10:09 -05:00
Andrew Beveridge ☄️ f72f772f96 Merge pull request #88 from nomadkaraoke/feature/mobile-ux-improvements
feat: improve mobile responsiveness across all UIs
2025-12-28 03:13:58 -05:00
Andrew BeveridgeandClaude Opus 4.5 7a30407fdb fix: Address CodeRabbit review feedback
- Add language identifier to markdown code block in docs
- Increase Undo/Redo button touch targets from 32px to 44px

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 03:08:53 -05:00
Andrew BeveridgeandClaude Opus 4.5 e0e35f5335 feat: improve mobile responsiveness across all UIs
- Main Frontend:
  - Stack Artist/Title inputs vertically on mobile (< 640px)
  - Improve tab button touch targets with min-height 44px
  - Make header responsive with icon-only buttons on small screens
  - Hide button text labels on mobile, show icons only

- Lyrics Review UI (Material UI):
  - Make handler panel width responsive (100% on mobile)
  - Fix button toolbar to wrap on mobile
  - Adjust heights for mobile viewports

- Instrumental Selection UI (Static HTML):
  - Add comprehensive mobile media queries
  - Stack bottom section vertically on mobile
  - Make selection panel full-width on mobile
  - Increase touch targets to 44px minimum
  - Allow scrolling on mobile viewports

- Testing:
  - Add mobile device projects to Playwright config (Pixel 7, iPhone 14)
  - Create comprehensive mobile responsiveness test suite
  - Test no horizontal overflow, touch targets, form usability

- Documentation:
  - Add MOBILE-UX-BEST-PRACTICES.md with patterns and guidelines

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 03:08:05 -05:00
Andrew Beveridge ☄️ 79be51c95d Merge pull request #89 from nomadkaraoke/refactor/documentation-restructure
docs: Restructure documentation for LLM agent clarity
2025-12-28 03:00:33 -05:00
19 changed files with 1442 additions and 147 deletions

No files matched your search

+109
View File
@@ -0,0 +1,109 @@
---
description: Review and address CodeRabbit comments on current PR
allowed-tools: Read, Glob, Grep, Edit, Write, Bash, mcp__github__pull_request_read, mcp__github__get_me, mcp__github__list_pull_requests, mcp__github__add_issue_comment
---
# CodeRabbit Comment Review
You are reviewing the current PR to address all CodeRabbit automated review comments.
## Your Task
### 1. Identify the Current PR
First, determine the current branch and find the associated PR:
```bash
git branch --show-current
```
Then use GitHub tools to find the PR for this branch in the `nomadkaraoke/karaoke-gen` repository.
### 2. Fetch CodeRabbit Comments
Get all review comments and regular comments on the PR:
**Review Comments (Potential Issues)**
- Use `pull_request_read` with `method: "get_review_comments"` to get all review comment threads
- Look for comments from the `coderabbitai` bot user
- These are typically marked as "Potential issue" and MUST be resolved before merge
**PR Comments (Including Nitpicks)**
- Use `pull_request_read` with `method: "get_comments"` to get regular PR comments
- CodeRabbit posts a summary comment that includes "Nitpick comments" section
- These should also be reviewed and considered for action
### 3. Analyze Each Comment
For each CodeRabbit comment:
1. Read the comment carefully to understand the concern
2. Look at the referenced code location
3. Decide if a code change is warranted:
- **Make changes** for: valid bugs, security issues, clear improvements, style violations
- **Skip changes** for: subjective preferences, false positives, already addressed, not applicable
4. If skipping, note the reason
### 4. Make Code Changes
For each comment requiring action:
1. Navigate to the file and line mentioned
2. Understand the surrounding context
3. Make the minimal change needed to address the concern
4. Verify the change doesn't break anything obvious
### 5. Commit and Push
After making all changes:
```bash
# Stage all changes
git add -A
# Commit with descriptive message
git commit -m "fix: address CodeRabbit review comments
- [list each fix briefly]
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>"
# Push to the PR branch
git push
```
### 6. Resolve Threads
After pushing:
- Reply to each CodeRabbit review thread indicating what was done
- If a comment was addressed, reply with what was changed
- If a comment was intentionally skipped, explain why
- This helps mark threads as resolved so the PR can be merged
## Output Format
Provide a summary report:
```
## CodeRabbit Review Summary
### Comments Addressed
- [ ] File:line - Brief description of issue → What was changed
### Comments Skipped (with reason)
- [ ] File:line - Issue → Reason for skipping
### Actions Taken
- Committed: [commit hash]
- Pushed to: [branch name]
- Threads replied to: [count]
### Status
Ready for merge: Yes/No (if No, explain why)
```
## Guidelines
- Focus on code quality improvements, not just making CodeRabbit happy
- Don't blindly accept every suggestion - use judgment
- Group related fixes into logical commits if needed
- Keep changes minimal and focused on the specific issues raised
- If a suggestion would require significant refactoring, note it for future work instead
+8 -85
View File
@@ -235,7 +235,7 @@ jobs:
package-build-test:
name: "Package - Build & Install (Test)"
runs-on: ubuntu-latest
runs-on: [self-hosted, linux, gcp]
needs: [changes, package-unit-tests, package-integration-tests]
if: >-
github.ref != 'refs/heads/main' && always() &&
@@ -258,28 +258,9 @@ jobs:
virtualenvs-create: true
virtualenvs-in-project: true
- name: Cache Poetry dependencies
uses: actions/cache@v4
with:
path: .venv
key: venv-package-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
restore-keys: |
venv-package-${{ runner.os }}-py3.13-
- name: Build package
run: poetry build
- name: Free disk space
uses: jlumbroso/free-disk-space@main
with:
tool-cache: false
android: true
haskell: true
dotnet: false
large-packages: false
docker-images: false
swap-storage: false
- name: Test package installation
run: |
pip install dist/*.whl
@@ -291,17 +272,10 @@ jobs:
backend-unit-tests:
name: "Backend - Unit Tests"
runs-on: ubuntu-latest
runs-on: [self-hosted, linux, gcp]
needs: changes
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.backend == 'true' || needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
steps:
- name: Free disk space
run: |
sudo rm -rf /usr/share/dotnet
sudo rm -rf /opt/ghc
sudo rm -rf /usr/local/share/boost
df -h
- name: Checkout code
uses: actions/checkout@v4
with:
@@ -318,14 +292,6 @@ jobs:
virtualenvs-create: true
virtualenvs-in-project: true
- name: Cache Poetry dependencies
uses: actions/cache@v4
with:
path: .venv
key: venv-backend-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
restore-keys: |
venv-backend-${{ runner.os }}-py3.13-
- name: Install dependencies
run: poetry install
@@ -343,21 +309,10 @@ jobs:
backend-emulator-tests:
name: "Backend - Emulator Integration Tests"
runs-on: ubuntu-latest
runs-on: [self-hosted, linux, gcp]
needs: changes
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.backend == 'true' || needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
steps:
- name: Free disk space
uses: jlumbroso/free-disk-space@main
with:
tool-cache: false
android: true
haskell: true
dotnet: true
large-packages: false
docker-images: false
swap-storage: false
- name: Checkout code
uses: actions/checkout@v4
with:
@@ -374,28 +329,12 @@ jobs:
virtualenvs-create: true
virtualenvs-in-project: true
- name: Cache Poetry dependencies
uses: actions/cache@v4
with:
path: .venv
key: venv-backend-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
restore-keys: |
venv-backend-${{ runner.os }}-py3.13-
- name: Set up Java 21 (required by Firestore emulator)
uses: actions/setup-java@v4
with:
distribution: "temurin"
java-version: "21"
- name: Set up Cloud SDK
uses: google-github-actions/setup-gcloud@v2
with:
version: "latest"
- name: Install Firestore emulator
run: gcloud components install beta cloud-firestore-emulator --quiet
- name: Install dependencies
run: poetry install
@@ -687,7 +626,7 @@ jobs:
deploy-backend:
name: "Deploy - Backend (Cloud Run)"
runs-on: ubuntu-latest
runs-on: [self-hosted, linux, gcp]
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
permissions:
contents: read
@@ -701,7 +640,6 @@ jobs:
steps:
# ============================================
# Check if deployment is needed FIRST
# This avoids wasting 3+ mins on disk cleanup when skipping
# ============================================
- name: Checkout code
uses: actions/checkout@v4
@@ -709,7 +647,7 @@ jobs:
submodules: false
fetch-depth: 0 # Need full history for tag check
- name: Set up Python (for version extraction)
- name: Set up Python 3.13
uses: actions/setup-python@v5
with:
python-version: "3.13"
@@ -733,21 +671,7 @@ jobs:
echo "✨ Tag v$VERSION does not exist - proceeding with deployment"
fi
# ============================================
# Free disk space only if deploying
# This prevents "No space left on device" errors during Docker build
# ============================================
- name: Free disk space (aggressive)
if: steps.version_check.outputs.needs_deploy == 'true'
uses: jlumbroso/free-disk-space@main
with:
tool-cache: true
android: true
haskell: true
dotnet: true
large-packages: true
docker-images: true
swap-storage: true
# No disk cleanup needed - self-hosted runner has 200GB SSD
- name: Authenticate to Google Cloud (Workload Identity)
if: steps.version_check.outputs.needs_deploy == 'true'
@@ -931,9 +855,8 @@ jobs:
echo "Branch: ${{ github.ref_name }}"
echo "Run: ${{ github.run_number }}"
echo ""
echo "📊 Cost savings: This build used FREE GitHub Actions instead of Cloud Build"
echo " Previously: ~\$0.064/min with N1_HIGHCPU_32"
echo " Now: \$0 (public repo) with registry-cached builds"
echo "📊 Built on self-hosted GCP runner (200GB SSD, no disk space issues)"
echo " Runner: gcp-runner with 4 vCPU, 16GB RAM"
- name: Skipped deployment summary
if: steps.version_check.outputs.needs_deploy == 'false'
+3 -3
View File
@@ -76,7 +76,7 @@ Run Whisper directly on your local machine using whisper-timestamped. Works on C
```bash
# Install with local Whisper support
pip install karaoke-gen[local-whisper]
pip install "karaoke-gen[local-whisper]"
# Optional: Configure model size (tiny, base, small, medium, large)
export WHISPER_MODEL_SIZE="medium"
@@ -98,7 +98,7 @@ export WHISPER_DEVICE="cpu"
```bash
# Pre-install CPU-only PyTorch first
pip install torch torchaudio --index-url https://download.pytorch.org/whl/cpu
pip install karaoke-gen[local-whisper]
pip install "karaoke-gen[local-whisper]"
```
Local Whisper runs automatically as a fallback when no cloud transcription services are configured.
@@ -633,7 +633,7 @@ Whisper models are downloaded on first use (~1-3GB depending on size). If downlo
#### whisper-timestamped Not Found
If you get "whisper-timestamped is not installed":
```bash
pip install karaoke-gen[local-whisper]
pip install "karaoke-gen[local-whisper]"
# Or install directly:
pip install whisper-timestamped
```
+74 -14
View File
@@ -341,9 +341,12 @@ async def upload_and_create_job(
style_cdg_instrumental_background: Optional[UploadFile] = File(None, description="CDG instrumental background"),
style_cdg_title_background: Optional[UploadFile] = File(None, description="CDG title screen background"),
style_cdg_outro_background: Optional[UploadFile] = File(None, description="CDG outro screen background"),
# Processing options (CDG/TXT require style config, disabled by default)
enable_cdg: bool = Form(False, description="Generate CDG+MP3 package (requires style config)"),
enable_txt: bool = Form(False, description="Generate TXT+MP3 package (requires style config)"),
# Theme configuration (use pre-made theme from GCS)
theme_id: Optional[str] = Form(None, description="Theme ID to use (e.g., 'nomad', 'default'). If set, CDG/TXT are enabled by default."),
color_overrides: Optional[str] = Form(None, description="JSON-encoded color overrides: artist_color, title_color, sung_lyrics_color, unsung_lyrics_color (hex #RRGGBB)"),
# Processing options (CDG/TXT require style config or theme, disabled by default unless theme is set)
enable_cdg: Optional[bool] = Form(None, description="Generate CDG+MP3 package. Default: True if theme_id set, False otherwise"),
enable_txt: Optional[bool] = Form(None, description="Generate TXT+MP3 package. Default: True if theme_id set, False otherwise"),
# Finalisation options
brand_prefix: Optional[str] = Form(None, description="Brand code prefix (e.g., NOMAD)"),
enable_youtube_upload: bool = Form(False, description="Upload to YouTube"),
@@ -477,7 +480,35 @@ async def upload_and_create_job(
# Extract request metadata for tracking and filtering
request_metadata = extract_request_metadata(request, created_from="upload")
# Parse color_overrides from JSON if provided
parsed_color_overrides: Dict[str, str] = {}
if color_overrides:
try:
parsed_color_overrides = json.loads(color_overrides)
except json.JSONDecodeError as e:
raise HTTPException(
status_code=400,
detail=f"Invalid color_overrides JSON: {e}"
)
# Resolve CDG/TXT defaults based on theme
resolved_cdg, resolved_txt = _resolve_cdg_txt_defaults(
theme_id, enable_cdg, enable_txt
)
# Check if any custom style files are being uploaded (overrides theme)
has_custom_style_files = any([
style_params,
style_intro_background,
style_karaoke_background,
style_end_background,
style_font,
style_cdg_instrumental_background,
style_cdg_title_background,
style_cdg_outro_background,
])
# Parse comma-separated model lists into arrays
parsed_backing_vocals_models = None
if backing_vocals_models:
@@ -492,8 +523,10 @@ async def upload_and_create_job(
artist=artist,
title=title,
filename=file.filename,
enable_cdg=enable_cdg,
enable_txt=enable_txt,
theme_id=theme_id,
color_overrides=parsed_color_overrides,
enable_cdg=resolved_cdg,
enable_txt=resolved_txt,
brand_prefix=brand_prefix,
enable_youtube_upload=enable_youtube_upload,
youtube_description=youtube_description,
@@ -521,9 +554,27 @@ async def upload_and_create_job(
# Record job creation metric
metrics.record_job_created(job_id, source="upload")
logger.info(f"Created job {job_id} for {artist} - {title}")
# If theme is set and no custom style files are being uploaded, prepare theme style now
# This copies the theme's style_params.json to the job folder so LyricsTranscriber
# can access the style configuration for preview videos
theme_style_params_path = None
theme_style_assets = {}
theme_youtube_desc = None
if theme_id and not has_custom_style_files:
try:
theme_style_params_path, theme_style_assets, theme_youtube_desc = _prepare_theme_for_job(
job_id, theme_id, parsed_color_overrides or None
)
logger.info(f"Applied theme '{theme_id}' to job {job_id}")
except HTTPException:
raise # Re-raise validation errors (e.g., theme not found)
except Exception as e:
logger.warning(f"Failed to prepare theme '{theme_id}' for job {job_id}: {e}")
# Continue without theme - job can still be processed with defaults
# Upload main audio file to GCS
audio_gcs_path = f"uploads/{job_id}/audio/{file.filename}"
logger.info(f"Uploading audio to GCS: {audio_gcs_path}")
@@ -592,21 +643,30 @@ async def upload_and_create_job(
update_data = {
'input_media_gcs_path': audio_gcs_path,
'filename': file.filename,
'enable_cdg': enable_cdg,
'enable_txt': enable_txt,
'enable_cdg': resolved_cdg,
'enable_txt': resolved_txt,
}
# Handle style assets - either from custom uploads or from theme
if style_assets:
# Custom style files uploaded
update_data['style_assets'] = style_assets
if 'style_params' in style_assets:
update_data['style_params_gcs_path'] = style_assets['style_params']
elif theme_style_assets:
# Theme style assets (no custom uploads)
update_data['style_assets'] = theme_style_assets
if theme_style_params_path:
update_data['style_params_gcs_path'] = theme_style_params_path
if brand_prefix:
update_data['brand_prefix'] = brand_prefix
if effective_discord_webhook_url:
update_data['discord_webhook_url'] = effective_discord_webhook_url
if youtube_description:
update_data['youtube_description_template'] = youtube_description
# Use theme YouTube description if no custom one provided
effective_youtube_description = youtube_description or theme_youtube_desc
if effective_youtube_description:
update_data['youtube_description_template'] = effective_youtube_description
# Native API distribution (use effective values which include defaults)
if effective_dropbox_path:
+128
View File
@@ -1606,5 +1606,133 @@ class TestIsUrlFunction:
assert is_url("") is False
class TestUploadEndpointThemeSupport:
"""Test that /jobs/upload endpoint supports theme configuration.
CRITICAL: These tests verify that the /api/jobs/upload endpoint correctly handles
theme_id and color_overrides parameters, ensuring preview videos have themed
backgrounds instead of black backgrounds.
This addresses a bug where:
- The frontend sends theme_id and color_overrides when uploading files
- But the backend /api/jobs/upload endpoint was ignoring these parameters
- Result: Jobs created via file upload had black backgrounds instead of themed ones
"""
def test_upload_endpoint_accepts_theme_id_parameter(self):
"""Verify the upload endpoint has theme_id as a form parameter.
CRITICAL: The frontend sends theme_id when uploading files with a theme.
If this parameter is missing from the endpoint, the theme is silently ignored
and preview videos will have black backgrounds instead of themed ones.
"""
from backend.api.routes import file_upload as file_upload_module
with open(file_upload_module.__file__, 'r') as f:
source_code = f.read()
has_theme_id_param = 'theme_id: Optional[str] = Form(' in source_code
assert has_theme_id_param, (
"file_upload.py /jobs/upload endpoint does not have theme_id as a Form parameter. "
"The frontend sends theme_id when uploading files with a theme, but the backend "
"ignores it. Add: theme_id: Optional[str] = Form(None, description='Theme ID...')"
)
def test_upload_endpoint_accepts_color_overrides_parameter(self):
"""Verify the upload endpoint has color_overrides as a form parameter."""
from backend.api.routes import file_upload as file_upload_module
with open(file_upload_module.__file__, 'r') as f:
source_code = f.read()
has_color_overrides_param = 'color_overrides: Optional[str] = Form(' in source_code
assert has_color_overrides_param, (
"file_upload.py /jobs/upload endpoint does not have color_overrides as a Form parameter. "
"The frontend sends color_overrides when customizing theme colors."
)
def test_upload_endpoint_calls_prepare_theme_for_job(self):
"""Verify the upload endpoint calls _prepare_theme_for_job when theme_id is set.
CRITICAL: When a job is created via the upload endpoint with a theme_id
(and no custom style files), the code must call _prepare_theme_for_job() to set:
1. style_params_gcs_path (pointing to the copied style_params.json)
2. style_assets (populated with asset mappings)
Without this, LyricsTranscriber won't have access to the theme's styles
and preview videos will have black backgrounds instead of themed ones.
"""
from backend.api.routes import file_upload as file_upload_module
with open(file_upload_module.__file__, 'r') as f:
source_code = f.read()
# The function should be called in upload_and_create_job
has_theme_prep_call = '_prepare_theme_for_job(' in source_code
assert has_theme_prep_call, (
"file_upload.py does not call _prepare_theme_for_job(). "
"When theme_id is provided to /jobs/upload without custom style files, "
"the endpoint MUST call _prepare_theme_for_job() to copy the theme's "
"style_params.json to the job folder."
)
def test_upload_endpoint_uses_resolve_cdg_txt_defaults(self):
"""Verify the upload endpoint uses _resolve_cdg_txt_defaults for theme-based defaults."""
from backend.api.routes import file_upload as file_upload_module
with open(file_upload_module.__file__, 'r') as f:
source_code = f.read()
has_resolve_call = '_resolve_cdg_txt_defaults(' in source_code
assert has_resolve_call, (
"file_upload.py does not call _resolve_cdg_txt_defaults(). "
"When theme_id is set, enable_cdg and enable_txt should default to True."
)
def test_upload_endpoint_has_optional_cdg_txt_params(self):
"""Verify enable_cdg and enable_txt are Optional[bool] to support theme defaults.
CRITICAL: If enable_cdg/enable_txt are bool instead of Optional[bool],
they will default to False and override the theme-based defaults.
"""
from backend.api.routes import file_upload as file_upload_module
with open(file_upload_module.__file__, 'r') as f:
source_code = f.read()
has_optional_cdg = 'enable_cdg: Optional[bool] = Form(' in source_code
has_optional_txt = 'enable_txt: Optional[bool] = Form(' in source_code
assert has_optional_cdg, (
"file_upload.py has enable_cdg as bool instead of Optional[bool]. "
"This prevents theme-based defaults from working."
)
assert has_optional_txt, (
"file_upload.py has enable_txt as bool instead of Optional[bool]. "
"This prevents theme-based defaults from working."
)
def test_job_create_includes_theme_id_and_color_overrides(self):
"""Verify JobCreate is called with theme_id and color_overrides."""
from backend.api.routes import file_upload as file_upload_module
with open(file_upload_module.__file__, 'r') as f:
source_code = f.read()
has_theme_id_in_job_create = 'theme_id=theme_id,' in source_code
has_color_overrides_in_job_create = 'color_overrides=parsed_color_overrides' in source_code
assert has_theme_id_in_job_create, (
"file_upload.py does not pass theme_id to JobCreate."
)
assert has_color_overrides_in_job_create, (
"file_upload.py does not pass color_overrides to JobCreate."
)
if __name__ == "__main__":
pytest.main([__file__, "-v"])
+13
View File
@@ -126,6 +126,19 @@ Migrated from Cloud Build to GitHub Actions for:
- Better visibility
- Faster feedback
### Self-Hosted Runner on GCP
GitHub-hosted runners have ~14GB disk, which caused failures during Docker builds. Solution: self-hosted runner on GCP with 200GB SSD.
**Key learnings:**
1. **GPG in startup scripts**: Always use `gpg --batch` for non-interactive execution
2. **setup-python on self-hosted**: Needs Python in tool cache at `$RUNNER/_work/_tool/Python/<version>/x64/` with `x64.complete` marker
3. **Debian vs Ubuntu**: PPAs don't work on Debian; use upstream repos (Temurin, NodeSource)
4. **pyenv for Python**: More reliable than source builds or distro packages for specific versions
See `docs/archive/2025-12-28-self-hosted-github-runner.md` for full details.
## Performance Observations
| Operation | Duration |
+318
View File
@@ -0,0 +1,318 @@
# Mobile UX Best Practices
This document outlines the mobile-first UX principles and implementation patterns used in this project to ensure a great experience across all screen sizes.
## Core Principles
### 1. Mobile-First Responsive Design
Design for the smallest screen first, then progressively enhance for larger screens.
```css
/* Base styles for mobile */
.element {
width: 100%;
padding: 12px;
}
/* Enhance for larger screens */
@media (min-width: 640px) {
.element {
width: 280px;
padding: 16px;
}
}
```
### 2. No Horizontal Overflow
The most critical mobile UX issue is horizontal scrolling. Always ensure content fits within the viewport width.
**Testing for overflow:**
```typescript
async function hasNoHorizontalOverflow(page: Page): Promise<boolean> {
return await page.evaluate(() => {
const docWidth = document.documentElement.scrollWidth;
const viewportWidth = window.innerWidth;
return docWidth <= viewportWidth + 2; // Small tolerance for rounding
});
}
```
**Common causes of horizontal overflow:**
- Fixed widths (e.g., `width: 340px`)
- Horizontal flex layouts without wrapping
- Images without `max-width: 100%`
- Tables without horizontal scroll containers
### 3. Touch Target Sizing
Interactive elements must be easily tappable. Follow these minimum sizes:
| Platform | Minimum Size | Recommended |
|----------|--------------|-------------|
| Apple iOS | 44x44px | 48x48px |
| Material Design | 48x48px | 48x48px |
| Web (general) | 32x32px | 44x44px |
**Implementation:**
```tsx
<Button className="min-h-[44px] px-3">
<Icon className="w-4 h-4" />
<span className="hidden sm:inline">Label</span>
</Button>
```
### 4. Progressive Disclosure
Show less content on mobile, with clear paths to access more:
- **Icon-only buttons on mobile, labels on desktop:**
```tsx
<Icon className="w-4 h-4 sm:mr-2" />
<span className="hidden sm:inline">Action Label</span>
```
- **Collapsed navigation on mobile**
- **Truncated text with expansion options**
## Layout Patterns
### Responsive Grid
Use responsive grid columns that stack on mobile:
```tsx
// Bad - always 2 columns
<div className="grid grid-cols-2 gap-4">
// Good - stack on mobile, 2 columns on larger screens
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
```
### Flexible Containers
Avoid fixed widths. Use percentage-based or responsive widths:
```css
/* Bad */
.sidebar {
width: 340px;
}
/* Good */
.sidebar {
width: 100%;
}
@media (min-width: 768px) {
.sidebar {
width: 340px;
}
}
```
### Flex Wrap for Toolbars
Allow toolbar items to wrap on smaller screens:
```tsx
<div className="flex flex-wrap gap-2 items-center">
{/* Items will wrap naturally */}
</div>
```
## Typography
### Readable Font Sizes
Minimum font sizes for readability without zooming:
| Element | Minimum Size | Recommended |
|---------|--------------|-------------|
| Body text | 14px | 16px |
| Labels | 12px | 14px |
| Small text/badges | 11px | 12px |
### Responsive Headings
```tsx
<h1 className="text-base sm:text-xl font-bold truncate">
Title Text
</h1>
```
## Form Design
### Input Fields on Mobile
- Stack form fields vertically on mobile
- Use full-width inputs for easier tapping
- Ensure proper input type for mobile keyboard optimization
```tsx
<input
type="email" // Shows email keyboard
inputMode="numeric" // Shows number pad
className="w-full min-h-[44px]"
/>
```
### Labels and Placeholders
- Labels should be visible (not just placeholders)
- Adequate spacing between label and input
- Clear validation feedback
## Testing Strategy
### Automated Testing with Playwright
Test across multiple viewport sizes representing real devices:
```typescript
const MOBILE_VIEWPORTS = {
'iPhone SE': { width: 375, height: 667 },
'iPhone 14': { width: 390, height: 844 },
'Pixel 7': { width: 412, height: 915 },
'iPad Mini': { width: 768, height: 1024 },
};
for (const [name, viewport] of Object.entries(MOBILE_VIEWPORTS)) {
test(`page works on ${name}`, async ({ page }) => {
await page.setViewportSize(viewport);
await page.goto('/');
// Test for horizontal overflow
const hasOverflow = await page.evaluate(() =>
document.documentElement.scrollWidth > window.innerWidth + 2
);
expect(hasOverflow).toBe(false);
});
}
```
### Visual Regression Testing
Capture screenshots at different viewports to catch visual regressions:
```typescript
await expect(page).toHaveScreenshot(`homepage-${deviceName}.png`, {
fullPage: true,
maxDiffPixelRatio: 0.1,
});
```
### Touch Target Validation
```typescript
const buttons = page.locator('button, a, [role="button"]');
for (const button of await buttons.all()) {
const box = await button.boundingBox();
if (box) {
expect(box.width).toBeGreaterThanOrEqual(32);
expect(box.height).toBeGreaterThanOrEqual(32);
}
}
```
## Framework-Specific Guidelines
### Tailwind CSS (Next.js Frontend)
Use responsive prefixes consistently:
```plaintext
sm: 640px - Small tablets and up
md: 768px - Tablets and up
lg: 1024px - Laptops and up
xl: 1280px - Desktops and up
```
**Common patterns:**
```tsx
// Stack on mobile, side-by-side on larger
className="flex flex-col sm:flex-row"
// Hide on mobile, show on larger
className="hidden sm:block"
// Reduce padding on mobile
className="p-3 sm:p-4"
// Smaller font on mobile
className="text-xs sm:text-sm"
```
### Material UI (Lyrics Review UI)
Use the `useMediaQuery` hook:
```tsx
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down('md'));
return (
<Box sx={{
flexDirection: isMobile ? 'column' : 'row',
width: isMobile ? '100%' : '280px',
}}>
```
### Vanilla CSS (Instrumental Review)
Use CSS media queries:
```css
.element {
width: 100%;
}
@media (min-width: 768px) {
.element {
width: 340px;
}
}
```
## Checklist for New Features
Before merging any UI changes, verify:
- [ ] No horizontal overflow on any mobile viewport (320px - 480px)
- [ ] All interactive elements are at least 44x44px
- [ ] Text is readable without zooming (minimum 11px)
- [ ] Form inputs stack vertically on mobile
- [ ] Navigation is accessible on mobile
- [ ] Images scale properly with `max-width: 100%`
- [ ] Modals/dialogs fit within mobile viewport
- [ ] Buttons show icons-only on very small screens
- [ ] Playwright mobile tests pass
## Common Fixes
### Fix: Horizontal Overflow
1. **Check for fixed widths** - Replace with responsive values
2. **Add flex-wrap** - Allow content to wrap
3. **Add overflow-x: hidden** - On containers (use sparingly)
4. **Check images** - Add `max-width: 100%`
### Fix: Touch Target Too Small
1. **Add minimum height** - `min-h-[44px]`
2. **Add padding** - `p-3` or `px-4 py-3`
3. **Use icon-only on mobile** - Hide text labels
### Fix: Text Too Small
1. **Use responsive font sizes** - `text-xs sm:text-sm`
2. **Set minimum body font size** - At least 14px
3. **Increase line height** - For better readability
## Resources
- [Apple Human Interface Guidelines - Touch Targets](https://developer.apple.com/design/human-interface-guidelines/accessibility)
- [Material Design - Touch Targets](https://m3.material.io/foundations/accessible-design/accessibility-basics)
- [Tailwind CSS Responsive Design](https://tailwindcss.com/docs/responsive-design)
- [Playwright Testing](https://playwright.dev/docs/test-mobile)
+1
View File
@@ -20,6 +20,7 @@
| Multi-format encoding | Working |
| Token-based auth | Working |
| Payment flow | Not started |
| CI/CD self-hosted runner | Working (GCP) |
## Known Issues
@@ -0,0 +1,80 @@
# Self-Hosted GitHub Actions Runner on GCP
**Date**: 2025-12-28
**Status**: Deployed and operational
## Problem
GitHub-hosted runners have ~14GB disk space. CI jobs were failing with "No space left on device" during:
- Docker builds (multi-stage, large dependencies)
- Emulator tests (Docker + Java + Firestore/GCS emulators)
- Package builds with poetry
Workarounds like `jlumbroso/free-disk-space` action helped but weren't reliable.
## Solution
Deployed a self-hosted runner on GCP with 200GB SSD via Pulumi IaC.
### Infrastructure Added
| Resource | Purpose |
|----------|---------|
| `github-runner` VM | e2-standard-4, 200GB SSD, Debian 12 |
| `github-runner` service account | Minimal permissions for runner |
| `github-runner-pat` secret | PAT for runner registration |
| IAM bindings | Artifact Registry reader, Secret Manager accessor, logging |
### Jobs Moved to Self-Hosted
- `package-build-test`
- `backend-unit-tests`
- `backend-emulator-tests`
- `deploy-backend`
These use `runs-on: [self-hosted, linux, gcp]` with labels.
## Issues Encountered
### 1. GPG tty errors in startup script
**Problem**: `gpg --dearmor` failed with "cannot open /dev/tty" in non-interactive startup.
**Fix**: Add `--batch` flag to all GPG commands.
### 2. setup-python can't find Python 3.13 on Debian 12
**Problem**: `actions/setup-python@v5` couldn't find pre-built Python 3.13 for Debian 12 on self-hosted runners.
**Fix**:
1. Install Python 3.13 via pyenv on the runner
2. Copy to tool cache: `_work/_tool/Python/3.13.0/x64/`
3. Create marker file: `x64.complete`
### 3. Java 21 not in Debian repos
**Problem**: `openjdk-21-jdk` not available in Debian 12 stable.
**Fix**: Use Temurin (Adoptium) repository directly.
## Key Files
- `infrastructure/__main__.py` - Runner VM and IAM setup
- `infrastructure/README.md` - Setup instructions
- `.github/workflows/ci.yml` - Jobs using self-hosted runner
## Lessons for Future
1. **Self-hosted runners need explicit tool setup** - Unlike GitHub-hosted, tools aren't pre-installed in expected locations
2. **setup-python tool cache location**: `$RUNNER_DIR/_work/_tool/Python/<version>/x64/`
3. **GPG in scripts**: Always use `--batch` for non-interactive execution
4. **Debian vs Ubuntu**: Many GitHub Actions assume Ubuntu; PPAs don't work on Debian
## Cost
~$50/month for e2-standard-4 running 24/7 (covered by GCP free credits).
## PRs
- #95: Initial self-hosted runner setup
- #97: Make startup script reproducible (pyenv, tool cache, GPG fixes)
+14 -12
View File
@@ -75,14 +75,14 @@ export default function HomePage() {
{/* Header */}
<header className="border-b backdrop-blur-sm sticky top-0 z-10" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}>
<div className="px-4 py-3 flex items-center justify-between">
<div className="flex items-center gap-3">
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" className="h-10" />
<div>
<h1 className="text-xl font-bold" style={{ color: 'var(--text)' }}>Karaoke Generator</h1>
<div className="px-3 sm:px-4 py-2 sm:py-3 flex items-center justify-between gap-2">
<div className="flex items-center gap-2 sm:gap-3 min-w-0">
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" className="h-8 sm:h-10 shrink-0" />
<div className="min-w-0">
<h1 className="text-base sm:text-xl font-bold truncate" style={{ color: 'var(--text)' }}>Karaoke Generator</h1>
</div>
</div>
<div className="flex items-center gap-2">
<div className="flex items-center gap-1 sm:gap-2 shrink-0">
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
@@ -90,15 +90,15 @@ export default function HomePage() {
variant="ghost"
size="sm"
onClick={toggleAutoMode}
className={autoModeEnabled ? "text-amber-400 hover:text-amber-300 bg-amber-500/10" : ""}
className={`min-h-[40px] px-2 sm:px-3 ${autoModeEnabled ? "text-amber-400 hover:text-amber-300 bg-amber-500/10" : ""}`}
style={!autoModeEnabled ? { color: 'var(--text-muted)' } : undefined}
>
{autoModeEnabled ? (
<Zap className="w-4 h-4 mr-2" />
<Zap className="w-4 h-4 sm:mr-2" />
) : (
<ZapOff className="w-4 h-4 mr-2" />
<ZapOff className="w-4 h-4 sm:mr-2" />
)}
Auto
<span className="hidden sm:inline">Auto</span>
</Button>
</TooltipTrigger>
<TooltipContent side="bottom" className="max-w-xs">
@@ -118,10 +118,11 @@ export default function HomePage() {
size="sm"
onClick={loadJobs}
disabled={isLoadingJobs || !isAuthenticated}
className="min-h-[40px] px-2 sm:px-3"
style={{ color: 'var(--text-muted)' }}
>
<RefreshCw className={`w-4 h-4 mr-2 ${isLoadingJobs ? 'animate-spin' : ''}`} />
Refresh
<RefreshCw className={`w-4 h-4 sm:mr-2 ${isLoadingJobs ? 'animate-spin' : ''}`} />
<span className="hidden sm:inline">Refresh</span>
</Button>
<AuthStatus />
{mounted && (
@@ -132,6 +133,7 @@ export default function HomePage() {
variant="ghost"
size="sm"
onClick={toggleTheme}
className="min-h-[40px] px-2 sm:px-3"
style={{ color: 'var(--text-muted)' }}
>
{isDarkMode ? (
+6 -6
View File
@@ -38,10 +38,10 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
variant="ghost"
size="sm"
onClick={handleLogout}
className="text-slate-400 hover:text-white"
className="text-slate-400 hover:text-white min-h-[40px] px-2 sm:px-3"
>
<LogOut className="w-4 h-4 mr-2" />
Logout
<LogOut className="w-4 h-4 sm:mr-2" />
<span className="hidden sm:inline">Logout</span>
</Button>
)
}
@@ -52,10 +52,10 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
variant="ghost"
size="sm"
onClick={() => setShowAuthDialog(true)}
className="text-amber-400 hover:text-amber-300"
className="text-amber-400 hover:text-amber-300 min-h-[40px] px-2 sm:px-3"
>
<KeyRound className="w-4 h-4 mr-2" />
Login
<KeyRound className="w-4 h-4 sm:mr-2" />
<span className="hidden sm:inline">Login</span>
</Button>
<AuthDialog
open={showAuthDialog}
+13 -13
View File
@@ -147,18 +147,18 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
return (
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList className="grid w-full grid-cols-3 bg-slate-800">
<TabsTrigger value="upload" className="gap-2 data-[state=active]:bg-slate-700">
<Upload className="w-4 h-4" />
Upload
<TabsList className="grid w-full grid-cols-3 bg-slate-800 h-auto">
<TabsTrigger value="upload" className="gap-1.5 sm:gap-2 py-3 min-h-[44px] text-xs sm:text-sm data-[state=active]:bg-slate-700">
<Upload className="w-4 h-4 shrink-0" />
<span className="truncate">Upload</span>
</TabsTrigger>
<TabsTrigger value="url" className="gap-2 data-[state=active]:bg-slate-700">
<Youtube className="w-4 h-4" />
URL
<TabsTrigger value="url" className="gap-1.5 sm:gap-2 py-3 min-h-[44px] text-xs sm:text-sm data-[state=active]:bg-slate-700">
<Youtube className="w-4 h-4 shrink-0" />
<span className="truncate">URL</span>
</TabsTrigger>
<TabsTrigger value="search" className="gap-2 data-[state=active]:bg-slate-700">
<Music className="w-4 h-4" />
Search
<TabsTrigger value="search" className="gap-1.5 sm:gap-2 py-3 min-h-[44px] text-xs sm:text-sm data-[state=active]:bg-slate-700">
<Music className="w-4 h-4 shrink-0" />
<span className="truncate">Search</span>
</TabsTrigger>
</TabsList>
@@ -193,7 +193,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
<div className="space-y-2">
<Label htmlFor="upload-artist" className="text-slate-200">Artist</Label>
<Input
@@ -271,7 +271,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
<div className="space-y-2">
<Label htmlFor="youtube-artist" className="text-slate-200">Artist (optional)</Label>
<Input
@@ -333,7 +333,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
<TabsContent value="search" className="mt-4">
<form onSubmit={handleSearchSubmit} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
<div className="space-y-2">
<Label htmlFor="search-artist" className="text-slate-200">Artist</Label>
<Input
+162
View File
@@ -0,0 +1,162 @@
import { test, expect, Page } from '@playwright/test';
/**
* Mobile Responsiveness E2E Tests
*
* Tests the entire user journey on mobile devices to ensure:
* 1. All content is visible and accessible
* 2. No horizontal scrolling occurs
* 3. Touch targets are appropriately sized
* 4. Text is readable without zooming
*/
// Common mobile viewport sizes
const MOBILE_VIEWPORTS = {
'iPhone SE': { width: 375, height: 667 },
'iPhone 14': { width: 390, height: 844 },
'Pixel 7': { width: 412, height: 915 },
};
// Helper to set auth token
async function setAuthToken(page: Page) {
const token = process.env.KARAOKE_ACCESS_TOKEN;
if (token) {
await page.evaluate((t) => {
localStorage.setItem('karaoke_access_token', t);
}, token);
}
}
// Helper to check no horizontal overflow
async function hasNoHorizontalOverflow(page: Page): Promise<boolean> {
return await page.evaluate(() => {
const docWidth = document.documentElement.scrollWidth;
const viewportWidth = window.innerWidth;
return docWidth <= viewportWidth + 2;
});
}
test.describe('Mobile Responsiveness', () => {
test.beforeEach(async ({ page }) => {
await setAuthToken(page);
});
for (const [deviceName, viewport] of Object.entries(MOBILE_VIEWPORTS)) {
test.describe(`${deviceName} (${viewport.width}x${viewport.height})`, () => {
test.beforeEach(async ({ page }) => {
await page.setViewportSize(viewport);
await page.goto('/');
await page.waitForLoadState('domcontentloaded');
await page.waitForTimeout(1000);
});
test('page loads without horizontal scroll', async ({ page }) => {
const noOverflow = await hasNoHorizontalOverflow(page);
expect(noOverflow).toBe(true);
});
test('header is visible and accessible', async ({ page }) => {
// Logo should be visible
const logo = page.locator('header img, .logo');
await expect(logo.first()).toBeVisible();
// Header title should be visible (may be truncated on mobile)
const title = page.locator('h1');
await expect(title.first()).toBeVisible();
});
test('form inputs are visible and usable', async ({ page }) => {
// Tab buttons should be visible
const tabs = page.locator('[role="tablist"] button, .tabs button');
if (await tabs.count() > 0) {
await expect(tabs.first()).toBeVisible();
}
// Check that Artist/Title inputs exist (after clicking upload tab if needed)
const uploadTab = page.locator('button:has-text("Upload")');
if (await uploadTab.count() > 0) {
await uploadTab.first().click();
await page.waitForTimeout(300);
}
// Artist input
const artistInput = page.locator('input').first();
if (await artistInput.count() > 0) {
const box = await artistInput.boundingBox();
if (box) {
expect(box.width).toBeGreaterThan(100);
}
}
});
test('buttons have adequate touch target size', async ({ page }) => {
const buttons = page.locator('button:visible');
const count = await buttons.count();
let smallButtonCount = 0;
for (let i = 0; i < Math.min(count, 10); i++) {
const button = buttons.nth(i);
const box = await button.boundingBox();
if (box && (box.width < 28 || box.height < 28)) {
smallButtonCount++;
}
}
// Allow some small buttons (icons) but not too many
expect(smallButtonCount).toBeLessThan(3);
});
});
}
});
test.describe('Mobile Interactions', () => {
test.beforeEach(async ({ page }) => {
await setAuthToken(page);
await page.setViewportSize({ width: 375, height: 667 });
await page.goto('/');
await page.waitForLoadState('domcontentloaded');
});
test('can switch between tabs', async ({ page }) => {
const urlTab = page.locator('button:has-text("URL")');
if (await urlTab.count() > 0) {
await urlTab.first().click();
await page.waitForTimeout(300);
// URL input should now be visible
const urlInput = page.locator('input[type="url"], input[placeholder*="youtube"], input[placeholder*="URL"]');
if (await urlInput.count() > 0) {
await expect(urlInput.first()).toBeVisible();
}
}
});
test('can type in input fields', async ({ page }) => {
// Find a text input (not file input)
const textInput = page.locator('input[type="text"], input[placeholder*="Artist"], input[placeholder*="title"]');
if (await textInput.count() > 0) {
await textInput.first().focus();
await textInput.first().fill('Test Input');
await expect(textInput.first()).toHaveValue('Test Input');
}
});
});
test.describe('Accessibility', () => {
test.beforeEach(async ({ page }) => {
await setAuthToken(page);
await page.setViewportSize({ width: 375, height: 667 });
await page.goto('/');
await page.waitForLoadState('domcontentloaded');
});
test('has proper viewport meta tag', async ({ page }) => {
const viewportMeta = await page.evaluate(() => {
const meta = document.querySelector('meta[name="viewport"]');
return meta?.getAttribute('content') || '';
});
expect(viewportMeta).toContain('width=device-width');
expect(viewportMeta).toContain('initial-scale=1');
});
});
+9
View File
@@ -82,6 +82,15 @@ export default defineConfig({
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
// Mobile device testing
{
name: 'mobile-chrome',
use: { ...devices['Pixel 7'] },
},
{
name: 'mobile-safari',
use: { ...devices['iPhone 14'] },
},
],
// Run local dev server before starting tests
+78 -1
View File
@@ -254,10 +254,87 @@ The function uses environment variables:
Known gaps are configured in `main.py` and should match your local `validate_and_sync.py`.
## Self-Hosted GitHub Actions Runners
Multiple GCP VMs run self-hosted GitHub Actions runners to:
- Solve disk space issues on GitHub-hosted runners (14GB vs 200GB)
- Enable parallel job execution across multiple runners
### Specs
- **Instances**: 5x e2-standard-4 (4 vCPU, 16GB RAM each)
- **Disk**: 200GB SSD per runner
- **Pre-installed**: Docker, Python 3.13, Node.js 20, Java 21, Poetry, FFmpeg, gcloud CLI
- **Labels**: `self-hosted`, `linux`, `x64`, `gcp`, `large-disk`
### Setup
1. Create a GitHub Personal Access Token (PAT) with `repo` scope:
- Go to https://github.com/settings/tokens
- Generate new token (classic)
- Select `repo` scope (full control of private repositories)
- Copy the token
2. Add the PAT to Secret Manager:
```bash
echo -n "ghp_your_token_here" | \
gcloud secrets versions add github-runner-pat --data-file=-
```
3. Run `pulumi up` to create the runner VMs
4. Verify the runners registered:
- Go to https://github.com/nomadkaraoke/karaoke-gen/settings/actions/runners
- You should see `gcp-runner-github-runner-1` through `gcp-runner-github-runner-5`
### Usage in Workflows
Jobs that need more disk space use the self-hosted runners:
```yaml
jobs:
build:
runs-on: [self-hosted, linux, gcp]
steps:
- uses: actions/checkout@v4
# ... rest of job
```
GitHub automatically distributes jobs across available runners.
### Troubleshooting
**Runner not appearing in GitHub:**
```bash
# Check startup logs (replace N with runner number 1-3)
gcloud compute ssh github-runner-N --zone=us-central1-a -- \
"sudo cat /var/log/github-runner-startup.log"
```
**Re-register runner:**
```bash
# Restart the VM to re-run startup script
gcloud compute instances reset github-runner-N --zone=us-central1-a
```
**Check runner service status:**
```bash
gcloud compute ssh github-runner-N --zone=us-central1-a -- \
"sudo systemctl status actions.runner.*"
```
**List all runners:**
```bash
for i in 1 2 3 4 5; do
echo "=== github-runner-$i ==="
gcloud compute instances describe github-runner-$i --zone=us-central1-a --format='get(status)'
done
```
## Next Steps
1. Run `pulumi up` to create infrastructure
2. Add secret values
2. Add secret values (including GitHub runner PAT)
3. Build and deploy Cloud Run service
4. Deploy GDrive validator function
5. Update documentation to reference Pulumi workflow
+273
View File
@@ -1182,3 +1182,276 @@ pulumi.export("gdrive_validator_function_name", gdrive_validator_function.name)
pulumi.export("gdrive_validator_scheduler_name", gdrive_validator_scheduler.name)
pulumi.export("gdrive_validator_service_account", gdrive_validator_sa.email)
# ==================== Self-Hosted GitHub Actions Runner ====================
# A dedicated VM running GitHub Actions runner for CI/CD jobs that need more
# disk space than GitHub-hosted runners provide (14GB vs 200GB here).
# This solves "No space left on device" errors during Docker builds.
# Service account for GitHub runner VM
github_runner_sa = serviceaccount.Account(
"github-runner-sa",
account_id="github-runner",
display_name="GitHub Actions Runner",
description="Service account for self-hosted GitHub Actions runner VM",
)
# Grant runner service account Artifact Registry reader (for pulling base images)
github_runner_artifact_reader = gcp.projects.IAMMember(
"github-runner-artifact-reader",
project=project_id,
role="roles/artifactregistry.reader",
member=github_runner_sa.email.apply(lambda email: f"serviceAccount:{email}"),
)
# Grant runner service account Secret Manager access (for PAT)
github_runner_secrets_iam = gcp.projects.IAMMember(
"github-runner-secrets-access",
project=project_id,
role="roles/secretmanager.secretAccessor",
member=github_runner_sa.email.apply(lambda email: f"serviceAccount:{email}"),
)
# Grant runner service account logging permissions
github_runner_logging_iam = gcp.projects.IAMMember(
"github-runner-logging-access",
project=project_id,
role="roles/logging.logWriter",
member=github_runner_sa.email.apply(lambda email: f"serviceAccount:{email}"),
)
# GitHub PAT secret for runner registration
# The PAT needs 'repo' scope to register a runner
github_runner_pat_secret = secretmanager.Secret(
"github-runner-pat",
secret_id="github-runner-pat",
replication=secretmanager.SecretReplicationArgs(
auto=secretmanager.SecretReplicationAutoArgs(),
),
)
# Startup script for the GitHub runner VM
GITHUB_RUNNER_STARTUP_SCRIPT = """#!/bin/bash
set -e
# Log to a file for debugging
exec > >(tee /var/log/github-runner-startup.log) 2>&1
echo "Starting GitHub Actions runner setup at $(date)"
# System updates and core dependencies
apt-get update
apt-get install -y \\
curl \\
git \\
jq \\
unzip \\
build-essential \\
libssl-dev \\
libffi-dev \\
software-properties-common \\
apt-transport-https \\
ca-certificates \\
gnupg \\
lsb-release
# ==================== Docker ====================
echo "Installing Docker..."
curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --batch --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian $(lsb_release -cs) stable" > /etc/apt/sources.list.d/docker.list
apt-get update
apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
# Configure Docker for the runner user
systemctl enable docker
systemctl start docker
# ==================== Python 3.13 via pyenv ====================
# setup-python action on self-hosted runners needs Python in the tool cache
echo "Installing Python 3.13 via pyenv..."
# Install pyenv dependencies
apt-get install -y make build-essential libssl-dev zlib1g-dev \\
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \\
libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev
# Install pyenv system-wide
export PYENV_ROOT=/opt/pyenv
curl https://pyenv.run | bash
# Add to system profile for future sessions
cat > /etc/profile.d/pyenv.sh << 'PYENV_PROFILE'
export PYENV_ROOT=/opt/pyenv
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
PYENV_PROFILE
# Source pyenv for current session
export PATH="/opt/pyenv/bin:$PATH"
eval "$(/opt/pyenv/bin/pyenv init -)"
# Install Python 3.13
/opt/pyenv/bin/pyenv install 3.13.0
/opt/pyenv/bin/pyenv global 3.13.0
# Create symlinks for system-wide access
ln -sf /opt/pyenv/shims/python3.13 /usr/local/bin/python3.13
ln -sf /opt/pyenv/shims/python3 /usr/local/bin/python3
ln -sf /opt/pyenv/shims/pip3 /usr/local/bin/pip3
# ==================== Node.js 20 ====================
echo "Installing Node.js 20..."
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt-get install -y nodejs
# ==================== Java 21 (for Firestore emulator) ====================
echo "Installing Java 21 via Temurin..."
# Use Temurin (Adoptium) - more reliable than Debian repos
curl -fsSL https://packages.adoptium.net/artifactory/api/gpg/key/public | gpg --batch --dearmor -o /usr/share/keyrings/adoptium.gpg
echo "deb [signed-by=/usr/share/keyrings/adoptium.gpg] https://packages.adoptium.net/artifactory/deb $(lsb_release -cs) main" > /etc/apt/sources.list.d/adoptium.list
apt-get update
apt-get install -y temurin-21-jdk
# ==================== FFmpeg ====================
echo "Installing FFmpeg..."
apt-get install -y ffmpeg
# ==================== Poetry ====================
echo "Installing Poetry..."
curl -sSL https://install.python-poetry.org | python3 -
ln -sf /root/.local/bin/poetry /usr/local/bin/poetry
# ==================== Google Cloud SDK ====================
echo "Installing Google Cloud SDK..."
curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg | gpg --batch --dearmor -o /usr/share/keyrings/cloud.google.gpg
echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" > /etc/apt/sources.list.d/google-cloud-sdk.list
apt-get update
apt-get install -y google-cloud-cli google-cloud-cli-firestore-emulator
# ==================== Create runner user ====================
echo "Creating runner user..."
useradd -m -s /bin/bash runner || true
usermod -aG docker runner
# ==================== GitHub Actions Runner ====================
echo "Setting up GitHub Actions Runner..."
RUNNER_VERSION="2.321.0"
RUNNER_DIR="/home/runner/actions-runner"
mkdir -p $RUNNER_DIR
cd $RUNNER_DIR
# Download runner
curl -o actions-runner-linux-x64-${RUNNER_VERSION}.tar.gz -L \\
https://github.com/actions/runner/releases/download/v${RUNNER_VERSION}/actions-runner-linux-x64-${RUNNER_VERSION}.tar.gz
tar xzf actions-runner-linux-x64-${RUNNER_VERSION}.tar.gz
rm actions-runner-linux-x64-${RUNNER_VERSION}.tar.gz
chown -R runner:runner $RUNNER_DIR
# Get GitHub PAT from Secret Manager
echo "Fetching GitHub PAT from Secret Manager..."
GITHUB_PAT=$(gcloud secrets versions access latest --secret=github-runner-pat)
if [ -z "$GITHUB_PAT" ]; then
echo "ERROR: GitHub PAT not found in Secret Manager"
exit 1
fi
# Get runner registration token using PAT
echo "Getting runner registration token..."
REGISTRATION_TOKEN=$(curl -s -X POST \\
-H "Authorization: token $GITHUB_PAT" \\
-H "Accept: application/vnd.github.v3+json" \\
https://api.github.com/repos/nomadkaraoke/karaoke-gen/actions/runners/registration-token | jq -r .token)
if [ -z "$REGISTRATION_TOKEN" ] || [ "$REGISTRATION_TOKEN" = "null" ]; then
echo "ERROR: Failed to get registration token"
exit 1
fi
# Configure runner (non-interactive)
echo "Configuring runner..."
cd $RUNNER_DIR
sudo -u runner ./config.sh \\
--url https://github.com/nomadkaraoke/karaoke-gen \\
--token "$REGISTRATION_TOKEN" \\
--name "gcp-runner-$(hostname)" \\
--labels "self-hosted,linux,x64,gcp,large-disk" \\
--work "_work" \\
--unattended \\
--replace
# Install and start runner as a service
echo "Installing runner service..."
./svc.sh install runner
./svc.sh start
echo "GitHub Actions runner setup complete at $(date)"
echo "Runner registered with labels: self-hosted,linux,x64,gcp,large-disk"
# ==================== Setup Python in tool cache ====================
# setup-python action looks for Python in RUNNER_TOOL_CACHE/_tool/Python
echo "Setting up Python 3.13 in tool cache for setup-python action..."
TOOL_CACHE="/home/runner/actions-runner/_work/_tool"
mkdir -p $TOOL_CACHE/Python/3.13.0/x64
# Copy pyenv Python to tool cache
cp -r /opt/pyenv/versions/3.13.0/* $TOOL_CACHE/Python/3.13.0/x64/
# Create marker file that setup-python looks for
touch $TOOL_CACHE/Python/3.13.0/x64.complete
# Fix permissions
chown -R runner:runner $TOOL_CACHE
echo "Python 3.13 added to tool cache"
# ==================== Docker cleanup cron ====================
# Prevent disk from filling up with old Docker images
echo "Setting up Docker cleanup cron..."
cat > /etc/cron.daily/docker-cleanup << 'CRON'
#!/bin/bash
# Clean up Docker resources older than 7 days
docker system prune -af --filter "until=168h"
CRON
chmod +x /etc/cron.daily/docker-cleanup
echo "Setup complete!"
"""
# GitHub runner VM instances (multiple runners for parallel job execution)
NUM_RUNNERS = 5
github_runner_vms = []
for i in range(1, NUM_RUNNERS + 1):
vm = gcp.compute.Instance(
f"github-runner-{i}",
name=f"github-runner-{i}",
machine_type="e2-standard-4", # 4 vCPU, 16GB RAM - good for Docker builds
zone="us-central1-a",
boot_disk=gcp.compute.InstanceBootDiskArgs(
initialize_params=gcp.compute.InstanceBootDiskInitializeParamsArgs(
image="debian-cloud/debian-12",
size=200, # GB - plenty for Docker builds and caches
type="pd-ssd", # SSD for faster I/O
),
),
network_interfaces=[gcp.compute.InstanceNetworkInterfaceArgs(
network="default",
access_configs=[gcp.compute.InstanceNetworkInterfaceAccessConfigArgs()], # Ephemeral IP is fine
)],
service_account=gcp.compute.InstanceServiceAccountArgs(
email=github_runner_sa.email,
scopes=["cloud-platform"],
),
metadata_startup_script=GITHUB_RUNNER_STARTUP_SCRIPT,
tags=["github-runner"],
allow_stopping_for_update=True,
# Ensure the secret exists before creating the VM
opts=pulumi.ResourceOptions(depends_on=[github_runner_pat_secret]),
)
github_runner_vms.append(vm)
# Export GitHub runner resources
pulumi.export("github_runner_vm_names", [vm.name for vm in github_runner_vms])
pulumi.export("github_runner_service_account", github_runner_sa.email)
@@ -576,6 +576,143 @@
font-size: 1.5rem;
color: var(--success);
}
/* Mobile responsiveness */
@media (max-width: 768px) {
.app {
padding: 12px;
gap: 8px;
height: auto;
min-height: 100vh;
overflow-y: auto;
}
body {
overflow: auto;
}
.header {
flex-direction: column;
align-items: flex-start;
gap: 8px;
}
.header-left {
width: 100%;
}
.header-right {
width: 100%;
justify-content: flex-start;
flex-wrap: wrap;
}
.logo {
font-size: 1rem;
}
.logo-img {
height: 32px;
}
.waveform-player {
flex: none;
min-height: 200px;
}
.waveform-toolbar {
flex-wrap: wrap;
padding: 8px 12px;
gap: 8px;
}
.toolbar-left,
.toolbar-center,
.toolbar-right {
flex-wrap: wrap;
}
.audio-toggle-group {
order: 10;
width: 100%;
justify-content: center;
}
.bottom-section {
flex-direction: column;
}
.mute-panel {
max-height: none;
}
.selection-panel {
width: 100%;
}
.selection-option {
padding: 12px;
}
.btn {
min-height: 44px;
padding: 8px 12px;
}
.btn-icon {
width: 44px;
height: 44px;
}
.audio-toggle {
padding: 8px 12px;
min-height: 40px;
}
.zoom-btn {
width: 40px;
height: 40px;
}
.time-display {
font-size: 0.9rem;
}
}
@media (max-width: 480px) {
.app {
padding: 8px;
}
.header-left {
flex-wrap: wrap;
}
.track-info {
width: 100%;
margin-top: 4px;
}
.waveform-toolbar {
padding: 6px 8px;
}
.toolbar-center {
width: 100%;
justify-content: center;
order: -1;
}
.toolbar-left {
order: 1;
}
.toolbar-right {
order: 2;
width: 100%;
justify-content: space-between;
}
}
</style>
</head>
<body>
@@ -148,12 +148,14 @@ export default function Header({
gap: 1,
mb: 1,
flexDirection: isMobile ? 'column' : 'row',
height: '140px'
height: isMobile ? 'auto' : '140px',
minHeight: isMobile ? 'auto' : '140px'
}}>
<Box sx={{
width: '280px',
width: isMobile ? '100%' : '280px',
minWidth: isMobile ? '100%' : '280px',
position: 'relative',
height: '100%'
height: isMobile ? 'auto' : '100%'
}}>
{isAgenticMode ? (
<AgenticCorrectionMetrics
@@ -261,17 +263,18 @@ export default function Header({
}}>
<Box sx={{
display: 'flex',
gap: 1,
flexDirection: isMobile ? 'column' : 'row',
alignItems: isMobile ? 'flex-start' : 'center',
height: '32px'
gap: 0.5,
flexDirection: 'row',
flexWrap: 'wrap',
alignItems: 'center',
minHeight: '44px'
}}>
<ModeSelector
effectiveMode={effectiveMode}
onChange={onModeChange}
/>
{!isReadOnly && (
<Box sx={{ display: 'flex', height: '32px' }}>
<Box sx={{ display: 'flex', height: '44px', alignItems: 'center' }}>
<Tooltip title="Undo">
<span>
<IconButton
@@ -282,8 +285,8 @@ export default function Header({
border: `1px solid ${theme.palette.divider}`,
borderRadius: '4px',
mx: 0.25,
height: '32px',
width: '32px'
height: '44px',
width: '44px'
}}
>
<UndoIcon fontSize="small" />
@@ -300,8 +303,8 @@ export default function Header({
border: `1px solid ${theme.palette.divider}`,
borderRadius: '4px',
mx: 0.25,
height: '32px',
width: '32px'
height: '44px',
width: '44px'
}}
>
<RedoIcon fontSize="small" />
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.76.24"
version = "0.76.26"
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"