# AGENTS.md

This document provides developer-focused information for the MPV.Rocks Installer project. For user-facing documentation, see [README.md](README.md).

## Project Overview

MPV.Rocks Installer is a cross-platform Go application that provides a beautiful TUI for installing and managing MPV media player with both terminal and web interfaces.

**Supported Platforms:**
- Windows (x86_64-v2) - Windows 10/11
- Linux (x86_64, arm64) - Ubuntu, Fedora, Arch, Debian, etc.
- macOS (arm64, x86_64, universal) - macOS 11+

**Key Features:**
- Cross-platform MPV installation (MPV, Celluloid, IINA, MPC-QT, Infuse, Jellyfin MPV)
- Comprehensive system information display
- Hardware acceleration configuration with GPU codec detection
- Language preferences (123+ languages across 7 families)
- Automatic update detection and installation
- Real-time installation output streaming
- Web UI with SSE support and modal system
- **Non-blocking job system** - Install/uninstall/update in background with real-time progress
- **Toast notifications** - Success/error feedback with view details option
- **Tasks page** - View active and completed installation jobs

---

## Notes for Agent

- **Always utilize ToDo Tasks** for tracking implementations and work to do
- **When asking questions,** utilize the client's built in questions api when possible. Clients like opencode and Clause Code have this feature
- **You have access to subagents** for handling tasks on their own

**Active TODO Items:**
- Fix pre-existing test file errors in `pkg/config/config_test.go` (undefined references)
- Consider adding more GPU models to database as they're discovered
- Expand language database to include more regional variants
- Enhance accessibility support in Web UI
- Add drag-and-drop for language priority list (Phase 2 U1)

---

## Getting Started

### Prerequisites
- Go 1.26 or later (upgraded from 1.25)
- Make (for building)
- Git (optional, for version info)

### Quick Start
```bash
# Clone the repository
git clone https://gitgud.io/mike/mpv-manager.git
cd mpv-manager

# Install dependencies
make deps

# Build for your platform
make build

# Run the installer
./dist/mpv-manager
```

### Run Modes
```bash
# Web UI mode (default)
./mpv-manager
# or explicitly:
./mpv-manager web

# TUI mode
./mpv-manager tui

# CLI mode
./mpv-manager cli --method mpv-binary

# Debug mode (detailed logging to stderr)
./mpv-manager --debug

# Verbose mode (logs to console)
./mpv-manager --verbose

# Help
./mpv-manager --help
```

---

## Project Structure

```
mpv-manager/
├── cmd/
│   ├── mpv-manager/          # Main TUI application
│   ├── generate-info/         # Release JSON generator
│   └── gen-checksums/        # BLAKE3 checksum generator
├── pkg/
│   ├── platform/             # Platform detection (reusable)
│   ├── constants/           # Single source of truth for all constants
│   ├── config/              # Configuration management
│   ├── version/             # Version management and updates
│   ├── log/                # Logging infrastructure
│   ├── installer/           # Installation logic (platform-specific)
│   ├── locale/              # Language and regional data (123+ languages)
│   └── tui/                # TUI components (split into 6 files)
├── internal/
│   └── assets/             # Embedded configuration files (mpv.conf)
├── docs/                  # Comprehensive documentation (NEW!)
│   ├── SESSION_SUMMARIES.md   # All session summaries
│   ├── ARCHITECTURE.md       # System architecture and design
│   ├── TESTING.md            # Testing procedures and checklists
│   ├── TROUBLESHOOTING.md    # Common issues and solutions
│   ├── BUILD_DEPLOYMENT.md    # Build and deployment guide
│   ├── PLATFORM_GUIDES/
│   │   ├── WINDOWS.md          # Windows-specific docs
│   │   ├── LINUX.md           # Linux-specific docs
│   │   └── MACOS.md           # macOS-specific docs
│   └── FEATURES/
│       ├── FEATURES.md          # Comprehensive feature documentation
│       ├── LANGUAGE_PREFERENCES.md  # Language preferences feature
│       └── GPU_CODEC_DETECTION.md # GPU codec detection system
│   ├── IMPROVEMENT_PLAN.md      # Comprehensive improvement roadmap (GLM-5)
│   ├── VISUAL_UI_IMPROVEMENTS.md # Visual and UI enhancements
│   └── TECHNICAL_IMPROVEMENTS.md # Technical and code quality improvements
├── Makefile                # Build automation
├── go.mod                  # Go module definition
└── PROJECT_PLAN.md          # Detailed project roadmap
```

---

## Architecture

See [ARCHITECTURE.md](docs/ARCHITECTURE.md) for comprehensive system architecture information.

**Key Packages:**

| Package | Purpose | Key Functions |
|---------|-----------|---------------|
| `pkg/platform` | Platform detection and hardware info | Detect(), GetOS(), GetGPU(), DetectCodecs() |
| `pkg/constants` | Single source of truth for constants | All config keys, method IDs, HTTP constants |
| `pkg/config` | Configuration management | GetConfigValue(), SetConfigValue(), backup/restore |
| `pkg/version` | Version management and updates | GetCurrentVersion(), CheckForUpdate(), UpdateSelf() |
| `pkg/installer` | Cross-platform installation logic | Install(), Uninstall(), SetupFileAssociations() |
| `pkg/locale` | Language and regional data (123+ langs) | GetLanguage(), GetMajorLanguages() |
| `pkg/tui` | Terminal UI (Bubbletea) | All view and update logic |
| `pkg/web` | Web UI server and API | HTTP server, SSE streaming, modal system |

**Design Patterns:**
- InstallationHandler interface for platform-specific installers
- ConfigPreservationHandler for automatic config backups
- SSE streaming for real-time installation output
- Modal system for consistent confirmation dialogs
- Input validation on all API endpoints
- Retry pattern with exponential backoff (3 attempts: 1s, 2s, 3s)

---

## Documentation Index

All detailed documentation has been extracted from this file and organized into the docs/ directory.

### Core Documentation
- **[Architecture & Design](docs/ARCHITECTURE.md)** - System architecture, package organization, design patterns, data flow, component interaction
- **[Session Summaries](docs/SESSION_SUMMARIES.md)** - All development session summaries in chronological order (detailed implementation notes for each session)
- **[Testing Guide](docs/TESTING.md)** - Comprehensive testing procedures, checklists, platform-specific testing, coverage goals
- **[Troubleshooting](docs/TROUBLESHOOTING.md)** - Common issues, solutions, debugging procedures, platform-specific troubleshooting

### Platform-Specific Guides
- **[Windows Platform Guide](docs/PLATFORM_GUIDES/WINDOWS.md)** - Build, install, GPU detection, file associations, console handling
- **[Linux Platform Guide](docs/PLATFORM_GUIDES/LINUX.md)** - Distributions, package managers, GPU detection, permissions
- **[macOS Platform Guide](docs/PLATFORM_GUIDES/MACOS.md)** - Build, code signing, Apple Silicon, Gatekeeper

### Feature Documentation
- **[Features Overview](docs/FEATURES/FEATURES.md)** - Comprehensive overview of all features (installation, configuration, system info, HWA, updates, language preferences, Web UI, modals)
- **[Language Preferences](docs/FEATURES/LANGUAGE_PREFERENCES.md)** - TUI and Web UI implementation, API reference, database, configuration
- **[GPU Codec Detection](docs/FEATURES/GPU_CODEC_DETECTION.md)** - Detection methods, GPU database (37 entries), codec mapping, lookup algorithm, platform-specific detection

### Build & Deployment
- **[Build & Deployment Guide](docs/BUILD_DEPLOYMENT.md)** - Build procedures, cross-compilation, packaging, release procedure, deployment strategy

### Improvement & Planning (GLM-5 Analysis - Feb 2026)
- **[Comprehensive Improvement Plan](docs/IMPROVEMENT_PLAN.md)** - Overall improvement roadmap, Go 1.26 upgrade, security, architecture
- **[Visual & UI Improvements](docs/VISUAL_UI_IMPROVEMENTS.md)** - TUI and Web UI visual enhancements, accessibility, theming
- **[Technical Improvements](docs/TECHNICAL_IMPROVEMENTS.md)** - Code quality, refactoring, platform support, testing

---

## Recent Changes (Last 3 Sessions)

### Session 2026-02-20: Platform-Specific HWDEC Defaults & CLI Improvements

**Key Changes:**
- Implemented platform-specific hardware decoding recommendations based on OS and GPU vendor
- Added `GetRecommendedHWADecoder()` in `pkg/platform/gpu.go` for smart defaults
- Added `,auto` fallback suffix support in hwdec values (e.g., `nvdec-copy,auto`)
- Updated validation to accept hwdec values with fallback suffix
- Dynamic "Recommended" badge in both Web UI and TUI based on detected environment
- User preference saved to both mpv.conf and mpv-manager.json
- Added simple CLI subcommands: `./mpv-manager [web|tui|cli]` (alternative to `-m` flag)
- Updated help text with cleaner subcommand syntax
- Updated README with MIT license and new CLI syntax

**Platform-Specific Recommendations:**
| Platform | GPU | Recommended hwdec |
|----------|-----|-------------------|
| Windows | Nvidia | `nvdec-copy,auto` |
| Windows | AMD/Intel | `vulkan,auto` |
| Linux | Nvidia | `nvdec,auto` |
| Linux | AMD/Intel | `auto` |
| macOS | All | `auto` |

**Files Modified:**
- `pkg/platform/gpu.go` - Added `GetRecommendedHWADecoder()`, updated `GetHWAOptions()` with `,auto` variants
- `pkg/config/config.go` - Added `HWADecoderPreference` field and getter/setter
- `pkg/web/validation.go` - Updated regex for `,auto` suffix
- `pkg/web/server.go`, `pkg/web/api.go` - Pass recommended HWA to templates, save preference
- `internal/webassets/templates/hwaccel.html` - Dynamic Recommended badge
- `pkg/tui/hwaccel_config.go` - Dynamic recommended option
- `pkg/installer/config_preservation.go` - Set recommended on fresh install
- `cmd/mpv-manager/main.go` - Added subcommand syntax (web/tui/cli)

### Session 2026-02-14: Non-Blocking Job System & Real-Time Progress

**Key Changes:**
- Implemented complete job management system for background installations
- Created `pkg/web/jobs.go` (~450 lines) - Job Manager with progress tracking, output history, error details
- Enhanced SSE streaming in `pkg/web/sse.go` for real-time job events
- Added job-based API endpoints: `/api/jobs`, `/api/install/job`, `/api/uninstall/job`, `/api/apps/update/job`
- Created `internal/webassets/static/jobs.js` (~850 lines) - Frontend job management with SSE connection
- Created `internal/webassets/static/toast.js` (~250 lines) - Toast notification system
- Created `internal/webassets/templates/tasks.html` (~320 lines) - Tasks page for job history
- Added real-time modal updates when viewing in-progress jobs
- Added auto-refresh of installed apps/updates lists on job completion
- Added sidebar badge showing active tasks count
- Fixed button state management during jobs (spinner, disabled state)

**Features:**
- Non-blocking installations - user can navigate freely while install runs
- Real-time progress updates via SSE (progress %, output lines, status)
- Toast notifications for job start/complete/error with "View Details" button
- Tasks page showing active and recently completed jobs
- Job output viewer modal with full logs
- Support for install, update, and uninstall job types

**Documentation:** See [docs/IMPROVEMENT_PLAN.md](docs/IMPROVEMENT_PLAN.md) Phase 2 for implementation details.

### Session 2026-02-13: GLM-5 Comprehensive Analysis & Go 1.26 Upgrade

**Key Changes:**
- Upgraded Go from 1.25.6 to 1.26
- Updated dependencies: `bubbles` v0.21.0 → v1.0.0, various transitive updates
- All tests passing after upgrade
- Created comprehensive improvement documentation:
  - `docs/IMPROVEMENT_PLAN.md` - Overall roadmap, security, architecture
  - `docs/VISUAL_UI_IMPROVEMENTS.md` - TUI and Web UI visual enhancements
  - `docs/TECHNICAL_IMPROVEMENTS.md` - Code quality, refactoring, platform support

**Analysis Summary (GLM-5):**
- Architecture Grade: B+ (Good)
- Key strengths: Clean package organization, cross-platform support, security practices
- Main improvement areas: Global state, Web UI performance (TailwindCDN), accessibility, CSRF protection
- Language system: 5 data structures, needs consolidation, TUI needs retry logic

**Documentation:** See [docs/IMPROVEMENT_PLAN.md](docs/IMPROVEMENT_PLAN.md) for complete improvement roadmap.

### Session 2026-02-02: Language Preferences Improvements & TUI Integration

**Key Changes:**
- Fixed missing languages in Major Language list (expanded from 11 to 33 languages)
- Fixed flag mappings (CZ, DK, GR, IL, SE, PH)
- Removed "(modern)" suffix from Greek and Hebrew
- Improved layout heights (viewport-relative: 70vh, 45vh)
- Added clear search button with focus return
- Moved results count inside search box as badge
- Fixed duplicate code bug in POST handler (removed 42 lines)
- Implemented saveLanguagePreferencesWithRetry() with 3-attempt retry logic (1s, 2s, 3s)
- Comprehensive testing (39/40 tests PASS, 97.5% success rate)

**Documentation:** See [docs/FEATURES/LANGUAGE_PREFERENCES.md](docs/FEATURES/LANGUAGE_PREFERENCES.md) for complete implementation details and API reference.

### Session 2026-01-31: Phase 1.3 - Input Validation & Magic String Consolidation

**Key Changes:**
- Created `pkg/web/validation.go` with comprehensive validation functions (218 lines)
- Created `pkg/web/validation_test.go` with 136 test cases (98.0% coverage)
- Added 57 new constants to `pkg/constants/constants.go`
- Consolidated magic strings throughout codebase (replaced with constants in 6 files)
- Added validation to 4 API endpoints (config/apply, install, uninstall, app/update)
- Platform-specific validation for install methods
- Clear error messages for all validation failures

**Documentation:** See [docs/SESSION_SUMMARIES.md](docs/SESSION_SUMMARIES.md) for detailed implementation notes.

### Session 2026-01-31: Web UI Template Fixes & System Information Enhancements

**Key Changes:**
- Fixed Installed Apps template error (flattened AppGroupInfo struct)
- Fixed Check for Updates template error (added Platform field)
- Fixed runtime panic - "string" function not defined (created toString() helper)
- Enhanced System Information page with capitalization and icons
- Added helper functions: capitalize(), capitalizeArchitecture(), getOSLogo(), getDistroFamilyLogo()
- Capitalized OS Type, Architecture, Distribution, Distro Family
- Added icons for OS Type and Distro Family
- Template function registration in FuncMap

**Documentation:** See [docs/SESSION_SUMMARIES.md](docs/SESSION_SUMMARIES.md) for detailed implementation notes.

---

## Key Files Reference

| File | Lines | Purpose | Status |
|------|--------|-----------|--------|
| `pkg/constants/constants.go` | ~300 | Single source of truth for all constants | Active |
| `pkg/platform/gpu.go` | ~500 | GPU detection and codec lookup (37 GPU entries) | Active |
| `pkg/web/api.go` | ~2100 | HTTP API endpoints, modal system, validation, job handlers | Active |
| `pkg/web/jobs.go` | ~450 | Job Manager for non-blocking installations | Active |
| `pkg/web/sse.go` | ~175 | SSE streaming for job events | Active |
| `pkg/web/validation.go` | 218 | Input validation functions | Active |
| `pkg/web/validation_test.go` | 423 | Validation tests (136 test cases) | Active |
| `pkg/web/server.go` | ~400 | HTTP server, SSE, templates | Active |
| `pkg/installer/` | ~2000 | Cross-platform installation logic | Active |
| `pkg/tui/models_*.go` | ~2000 | TUI components (split into 6 files) | Active |
| `pkg/locale/` | ~500 | Language database (123+ languages) | Active |
| `internal/assets/locales.json` | ~4000 | Language data (123+ langs + variants) | Active |
| `internal/webassets/static/jobs.js` | ~850 | Job management, SSE, output viewer | Active |
| `internal/webassets/static/toast.js` | ~250 | Toast notifications system | Active |
| `internal/webassets/templates/tasks.html` | ~320 | Tasks page for job history | Active |

---

## Testing

See [docs/TESTING.md](docs/TESTING.md) for comprehensive testing procedures.

**Current Test Status:**
- `pkg/web`: 98.0% coverage (136/136 tests pass)
- Overall: ~75% coverage
- Test Coverage Goals:
  - pkg/web: 90% ✅ (exceeds 80% target)
  - pkg/version: 80% (in progress)
  - pkg/platform: 70% (medium priority)
  - pkg/installer: 70% (high priority)
  - pkg/config: 70% (high priority)

**Run Tests:**
```bash
# Run all tests
go test ./...

# Run tests with coverage
go test -cover ./...

# Run tests with verbose output
go test -v ./...
```

---

## Troubleshooting

See [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) for common issues and solutions.

**Common Issues:**
- **Installer crashes on startup** → Check CPU compatibility (x86-64-v2 baseline required)
- **Configuration not saving** → Check file permissions, disk space, concurrent writes
- **GPU detection fails** → Enable debug mode, check detection tools installed
- **Update installation fails** → Check network connectivity, firewall, BLAKE3 checksum
- **Windows silent crashes** → Build with GOAMD64=v2
- **macOS code signing** → Sign with Apple Developer certificate or remove quarantine
- **Linux permission denied** → Run with sudo, fix directory permissions

**Debug Mode:**
```bash
# Enable debug logging (shows all initialization steps)
./mpv-manager --debug

# Enable verbose mode (logs to console)
./mpv-manager --verbose
```

---

## Code Style

- Follow Go conventions (`go fmt ./...`)
- Use meaningful variable names
- Add comments for public APIs
- Keep functions focused and small
- Single source of truth for constants in `pkg/constants/`
- Platform-specific code in separate files (`windows.go`, `linux.go`, `macos.go`)

---

## Documentation Updates

**Maintain Documentation:**
- Update [PROJECT_PLAN.md](PROJECT_PLAN.md) for major changes and plans
- Update [AGENTS.md](AGENTS.md) for new features and things future agents should know
- Keep [README.md](README.md) focused on user-facing documentation
- Update [LOW_HANGING_FRUIT_PLAN.md](LOW_HANGING_FRUIT_PLAN.md) with completion status

**Phase-Specific Summaries:**
- [PHASE4_IMPLEMENTATION_SUMMARY.md](PHASE4_IMPLEMENTATION_SUMMARY.md) - System Information Page
- [PHASE5_HWA_SUMMARY.md](PHASE5_HWA_SUMMARY.md) - Hardware Acceleration enhancements
- [PHASE7_MODAL_SYSTEM_SUMMARY.md](PHASE7_MODAL_SYSTEM_SUMMARY.md) - Custom Modal System
