Compare commits

..

416 Commits

Author SHA1 Message Date
Jonathan Sykes
459a27b6eb Merge main into jamesdsp and register its assets 2026-10-09 18:37:35 +08:00
Jonathan Sykes
933e920701 Add JamesDSP integration plan 2026-10-09 18:30:26 +08:00
Jonathan Sykes
a1048f1c30 Verify transport geometry, playback states and themed icons across both engines 2026-10-09 16:12:28 +08:00
Jonathan Sykes
1e83951972 Reconcile transport drawing variants, admin controls and theme cascades 2026-10-09 16:10:02 +08:00
Jonathan Sykes
9a37715da4 Unify transport controls with themed SVG symbols and accessible playback states 2026-10-09 15:54:22 +08:00
Jonathan Sykes
0a5b113ebe Record combined migration, offline and cold-start verification 2026-10-09 15:47:35 +08:00
Jonathan Sykes
6ae81d1024 Merge autosave probes and reconcile the complete verification guide 2026-10-09 15:12:55 +08:00
Jonathan Sykes
52e51278d5 Merge persisted-settings verification and retain all harness documentation 2026-10-09 15:12:46 +08:00
Jonathan Sykes
d027696d4e Merge manifest hygiene and reconcile runtime exclusions with CSP response capture 2026-10-09 15:12:39 +08:00
Jonathan Sykes
4ba5130c80 Merge Phase 6 and reconcile offline completion, response capture and contract tests 2026-10-09 15:12:14 +08:00
Jonathan Sykes
ea221a4e90 Verify persisted settings and save-before-play through production updates 2026-10-09 15:09:09 +08:00
Jonathan Sykes
8a4144eb00 Document runtime exclusions and verify offline transfer savings 2026-10-09 14:56:31 +08:00
Jonathan Sykes
dd09f66578 Separate runtime manifest inputs from directly served files 2026-10-09 14:40:46 +08:00
Jonathan Sykes
cf27d4f15a Merge branch 'codex/ui-fixes' 2026-10-09 14:37:51 +08:00
Jonathan Sykes
9c988912de Complete phase 6 report with post-crash checks 2026-10-09 14:35:51 +08:00
Jonathan Sykes
6f0235f506 Record post-crash phase 6 verification 2026-10-09 14:34:59 +08:00
Jonathan Sykes
a497180352 Verify mobile geometry and themed media icons across browsers 2026-10-09 14:32:17 +08:00
Jonathan Sykes
2001e77cee Use theme-aware SVGs for download and offline actions 2026-10-09 14:28:42 +08:00
Jonathan Sykes
f161a5de74 Record autosave comparison results and native storage limits 2026-10-09 14:25:43 +08:00
Jonathan Sykes
0b8e398469 Record offline completeness and recovery verification 2026-10-09 10:59:50 +08:00
Jonathan Sykes
2fc6d5d4dc Release response streams used by cache metadata probes 2026-10-09 10:43:05 +08:00
Jonathan Sykes
f359e5dd39 Limit activation readiness checks to blocking assets 2026-10-09 10:34:57 +08:00
Jonathan Sykes
2c8d563d01 Keep offline completion outside the activation barrier 2026-10-09 10:28:11 +08:00
Jonathan Sykes
6b8d590638 Verify worker recovery and retained offline feature fallback 2026-10-09 09:54:30 +08:00
Jonathan Sykes
009a155568 Resume offline preparation on launch and show cache readiness 2026-10-09 09:33:57 +08:00
Jonathan Sykes
0251720fa2 Complete verified offline assets in a resumable worker job 2026-10-09 09:32:08 +08:00
Jonathan Sykes
97f4a7396e Exercise offline editors and interrupted worker recovery 2026-10-09 09:24:20 +08:00
Jonathan Sykes
b59fc7264a Verify device autosave behavior across frontend revisions 2026-10-09 09:16:58 +08:00
Jonathan Sykes
14716e648b Add offline completeness and feature regression harness 2026-10-09 09:15:29 +08:00
Jonathan Sykes
71608c2ce8 Clarify the diagnostic waterfall source 2026-10-09 09:11:45 +08:00
Jonathan Sykes
66bbda51c7 Keep saved thumbnails inside their grid column 2026-10-09 09:11:30 +08:00
Jonathan Sykes
ff3f934717 Record phase 6 measurements and compatibility verification 2026-10-08 12:06:13 +08:00
Jonathan Sykes
3de4cba402 Align toolbar controls and provide full touch targets 2026-10-08 12:04:56 +08:00
Jonathan Sykes
4b1f5204f8 Restore native boot scheduling without an extra core request 2026-10-08 11:25:03 +08:00
Jonathan Sykes
9408ee07e5 Limit the WebKit response handoff to uncontrolled visits 2026-10-08 10:08:35 +08:00
Jonathan Sykes
97eb31e732 Enforce stale core contracts in the worker without native startup I/O 2026-10-08 10:05:38 +08:00
Jonathan Sykes
57edb410c3 Keep native Chromium loading and prevent stale browser cache entries 2026-10-08 09:43:51 +08:00
Jonathan Sykes
c4a512bea6 Guard stale app execution against feature contract changes 2026-10-08 09:18:51 +08:00
Jonathan Sykes
3505dc3c0e Preserve verified N-1 app boot after a cache entry is lost 2026-10-08 09:10:28 +08:00
Jonathan Sykes
639f0a2257 Record cache reuse probes and reset each benchmark configuration 2026-10-08 09:06:40 +08:00
Jonathan Sykes
a86fa1cebe Cache the page-owned app response before starting the worker 2026-10-08 09:04:20 +08:00
Jonathan Sykes
e7a7cdc6b9 Preload classic layout CSS before the blocking head loader 2026-10-08 08:50:51 +08:00
Jonathan Sykes
799b1e7ed6 Trace cold request waterfalls and isolate the layout discovery regression 2026-10-08 08:45:00 +08:00
Jonathan Sykes
af6aabc3b7 Plan phase 6: diagnose and fix WebKit cold delivery 2026-10-08 08:27:08 +08:00
Jonathan Sykes
21c12733d3 Record final performance sweep and staged rollout instructions 2026-10-08 05:47:31 +08:00
Jonathan Sykes
a08d363f2d Measure complete CSS updates and fully cached warm reloads 2026-10-08 05:12:32 +08:00
Jonathan Sykes
ce5a159d4a Plan phase 5: measure final performance and document rollout 2026-10-08 05:09:07 +08:00
Jonathan Sykes
f133e1bb9f Document Phase 4 seams, measurements and remaining limitations 2026-10-08 05:03:55 +08:00
Jonathan Sykes
a7473cbca2 Verify six app seams and record Phase 4 performance measurements 2026-10-08 05:03:55 +08:00
Jonathan Sykes
2c5003575c Report unavailable lazy chunks without rejecting UI actions 2026-10-08 04:48:52 +08:00
Jonathan Sykes
b335f95f45 Load Stats view separately from listening-stat tracking 2026-10-08 04:46:40 +08:00
Jonathan Sykes
0475a1826c Load sharing and external-player tools on demand 2026-10-08 04:44:35 +08:00
Jonathan Sykes
94ea211605 Lazy-load watch-party sessions behind synchronous playback hooks 2026-10-08 04:42:35 +08:00
Jonathan Sykes
8e7fa1959a Load remote UI on intent and preserve synchronous host hooks 2026-10-08 04:41:30 +08:00
Jonathan Sykes
5fb9564468 Load the presenter client only on presenter entry 2026-10-08 04:39:52 +08:00
Jonathan Sykes
3c9a24ae45 Extract eager shell and shared view renderers before app boot 2026-10-08 04:38:37 +08:00
Jonathan Sykes
cdd26b6ae5 Plan phase 4: Extract eager renderers and five lazy clients 2026-10-08 04:35:55 +08:00
Jonathan Sykes
cd4a25ae23 Document Phase 3 delivery and remaining paint regression 2026-10-08 04:26:10 +08:00
Jonathan Sykes
b84050578b Verify staged lazy loading and record Phase 3 measurements 2026-10-08 04:19:02 +08:00
Jonathan Sykes
fab444b7b8 Start font preloads before the layout bootstrap 2026-10-08 04:12:16 +08:00
Jonathan Sykes
46ec9ab2ca Report layouts selected through imported settings to the worker 2026-10-08 04:02:43 +08:00
Jonathan Sykes
c1a546a5c6 Keep shared layout visibility defaults in eager styles 2026-10-08 03:56:47 +08:00
Jonathan Sykes
40b92ebc0d Request selected layout styles before common CSS blocks the bootstrap 2026-10-08 03:50:57 +08:00
Jonathan Sykes
524a7b7f1d Share the background asset warm pool across idle requests 2026-10-08 01:40:48 +08:00
Jonathan Sykes
173eab8026 Preserve Settings control search with lazy feature panels 2026-10-08 01:36:47 +08:00
Jonathan Sykes
ccfb7d90ba Preserve separate Car mode and voice controls during lazy setup 2026-10-08 01:32:43 +08:00
Jonathan Sykes
5d6a1545df Load layouts and optional features from staged asset caches 2026-10-08 01:29:50 +08:00
Jonathan Sykes
d98d444552 Embed build-local asset groups in stamped indexes 2026-10-08 00:50:18 +08:00
Jonathan Sykes
4853c2c977 Pin executing groups and guard lazy loads by core contracts 2026-10-08 00:47:50 +08:00
Jonathan Sykes
e1cb450032 Add ordered build-local loader and record staged apply decision 2026-10-08 00:33:07 +08:00
Jonathan Sykes
f804a23761 Add contract-checked fallback and background asset synchronization 2026-10-08 00:30:31 +08:00
Jonathan Sykes
895f20a4c9 Plan phase 3: Load layouts and features on demand 2026-10-08 00:27:50 +08:00
Jonathan Sykes
4950d3e417 Document incremental sync verification and performance gaps 2026-10-08 00:21:19 +08:00
Jonathan Sykes
92404563b3 Fail closed when worker update status is unavailable 2026-10-08 00:10:04 +08:00
Jonathan Sykes
5d1e5ec791 Verify explicit activation and legacy incremental migration 2026-10-08 00:03:14 +08:00
Jonathan Sykes
bb446c717f Keep single-tag rollback on the legacy worker path 2026-10-07 23:58:29 +08:00
Jonathan Sykes
5b25ccaa86 Publish asset state atomically and reject unavailable versions 2026-10-07 23:56:46 +08:00
Jonathan Sykes
54a07a0a2a Synchronize verified assets incrementally and guard update activation 2026-10-07 23:40:20 +08:00
Jonathan Sykes
04421a2145 Add an isolated beta compose stack 2026-10-07 23:30:29 +08:00
Jonathan Sykes
a1f16f2e3b Plan phase 2: Add incremental asset sync and migration verification 2026-10-07 23:20:59 +08:00
Jonathan Sykes
7434f2f486 Document Phase 1 verification and retained plain asset URLs 2026-10-07 23:14:14 +08:00
Jonathan Sykes
7c45d098b1 Verify production-client migration and record Phase 1 measurements 2026-10-07 23:12:48 +08:00
Jonathan Sykes
84546eeb7d Group all Glass Stage dependencies under the selected layout 2026-10-07 23:09:04 +08:00
Jonathan Sykes
d18d17cf29 Preserve legacy cache rules and pin service worker bytes at boot 2026-10-07 23:01:55 +08:00
Jonathan Sykes
6cb00d5073 Add per-file asset hashes and a rollback-compatible server manifest 2026-10-07 22:57:41 +08:00
Jonathan Sykes
ad85cb6eb4 Plan phase 1: Add per-file hashes and a backward-compatible manifest 2026-10-07 22:50:02 +08:00
Jonathan Sykes
be1d939afd Merge branch 'codex/prewarm-next'
# Conflicts:
#	frontend/index.html
2026-10-07 22:44:11 +08:00
Jonathan Sykes
491ec407a1 Expose more JamesDSP EQ bands 2026-10-07 19:24:36 +08:00
Jonathan Sykes
dce186c187 Add optional JamesDSP audio effects 2026-10-07 19:23:35 +08:00
Jonathan Sykes
93d3b05263 Document after-phase0 benchmark comparison and hidden timer validation 2026-10-07 17:23:01 +08:00
Jonathan Sykes
eb6aae7ae7 Add hidden timers Playwright verification script 2026-10-07 17:21:18 +08:00
Jonathan Sykes
09125f3f5c Record after-phase0 performance benchmark results 2026-10-07 17:21:08 +08:00
Jonathan Sykes
7bc5b4f8b5 Merge branch 'agy/phase0-perf' 2026-10-07 16:36:56 +08:00
Jonathan Sykes
d65b9e032a Prewarm upcoming queue streams 2026-10-07 16:30:15 +08:00
Jonathan Sykes
fcd98b6a4d Add queue prewarm candidate selection 2026-10-07 16:30:01 +08:00
Jonathan Sykes
4bc15a55e3 Add baseline benchmark results and report 2026-10-07 04:25:14 +08:00
Jonathan Sykes
64f8eae92b Add performance baseline harness, throttling proxy, and documentation 2026-10-07 03:53:20 +08:00
Jonathan Sykes
3f37c2a9ef Add shell fixture script and verify production build tag 2026-10-07 03:32:10 +08:00
Jonathan Sykes
233bf94e4c Pause non-playback UI timers while the page is hidden 2026-10-07 03:30:57 +08:00
Jonathan Sykes
722df3125f Add visibility-aware interval helper 2026-10-07 03:30:22 +08:00
Jonathan Sykes
2e58924971 Add shell consistency test between index.html and the service worker 2026-10-07 03:29:24 +08:00
Jonathan Sykes
b6dd2be40f Add server characterization tests for build tag, index stamping and cache headers 2026-10-07 03:28:45 +08:00
Jonathan Sykes
b77938ab4a Queue bounded stream prewarm requests 2026-10-07 03:13:30 +08:00
Jonathan Sykes
b4c776dcfe Add dark, light and contrast variants of the M3E sketch 2026-10-07 02:16:13 +08:00
Jonathan Sykes
2b286ae146 Stop the last song from restarting and freezing service-mode lyrics 2026-10-07 02:12:07 +08:00
Jonathan Sykes
128f8e95e3 Respect the notch in the Framework7 top bar, sidebar and full sheet 2026-10-06 09:16:49 +08:00
Jonathan Sykes
63ff2173d8 Lift player to body for iOS fullscreen so the app never shows around it 2026-10-06 09:14:06 +08:00
Jonathan Sykes
a143c8331d Stop video seek loop when returning from background 2026-10-06 09:14:06 +08:00
Jonathan Sykes
5b259a1ac1 Add M3E sketch of the Framework7 Swipe layout 2026-10-06 04:20:05 +08:00
Jonathan Sykes
1eda52e4c5 Stop tracking review screenshots 2026-10-06 04:19:01 +08:00
Jonathan Sykes
3be7a7b194 Fix fullscreen fit gesture clash and double swipe-remove in Framework7 layout 2026-10-06 04:19:01 +08:00
Jonathan Sykes
bd80ad1ea0 Align the design review score with its rating band 2026-10-06 04:16:15 +08:00
Jonathan Sykes
c30fd9fe78 Record the Framework7 design review 2026-10-06 04:15:25 +08:00
Jonathan Sykes
605d21a3e2 Use native icons in the Framework7 sidebar 2026-10-06 04:13:55 +08:00
Jonathan Sykes
cc4fb0d5c9 Simplify fullscreen playback controls 2026-10-06 04:12:28 +08:00
Jonathan Sykes
af38affdbe Make fullscreen video fill the viewport 2026-10-06 04:12:25 +08:00
Jonathan Sykes
034b3df7ae Complete Framework7 swipe gestures 2026-10-06 04:12:15 +08:00
Jonathan Sykes
d4497b0c05 Restyle the Framework7 layout 2026-10-06 04:12:09 +08:00
Jonathan Sykes
67fc6f584f Allow swipeout width transition in impeccable checks 2026-10-06 03:06:02 +08:00
Jonathan Sykes
a81f4ffa51 Refine fullscreen control overlay 2026-10-06 02:32:43 +08:00
Jonathan Sykes
1cad18826b Fill viewport in fullscreen playback 2026-10-06 02:32:36 +08:00
Jonathan Sykes
1ba3f8704b Style Framework7 swipe layout 2026-10-06 02:32:36 +08:00
Jonathan Sykes
0bda242a98 Add Framework7 Swipe layout with swipeout rows, up-next sheet and mini-bar gestures 2026-10-06 02:01:56 +08:00
Jonathan Sykes
1754933f7e Polish Bento scrolling and controls with full screen coverage 2026-10-04 23:44:51 +08:00
Jonathan Sykes
4e5b1584c6 Restore Bento theme integration lost during recovery 2026-10-04 22:47:33 +08:00
Jonathan Sykes
9589c38773 Apply Bento tiles to Settings, sheets and empty states 2026-10-04 22:46:23 +08:00
Jonathan Sykes
3baf67349f Bring Bento playback and Service mode into the new theme 2026-10-04 22:44:54 +08:00
Jonathan Sykes
e100d47143 Style Bento library rows and download recovery controls 2026-10-04 22:42:22 +08:00
Jonathan Sykes
838798ca9b Build the new Bento Hub shell and browsing tiles 2026-10-04 03:09:15 +08:00
Jonathan Sykes
04b620e3c7 Polish download action buttons in Classic and Glass Stage 2026-10-04 02:48:08 +08:00
Jonathan Sykes
2042c9b6fc Recover related videos with bounded discovery and retryable fallbacks 2026-10-04 02:42:02 +08:00
Jonathan Sykes
df4acfc9f1 Keep iPhone audio playing through background handoffs 2026-10-04 02:29:10 +08:00
Jonathan Sykes
536555e12d Add selectable fullscreen orientation and an iPhone landscape overlay 2026-10-04 02:26:54 +08:00
Jonathan Sykes
d43cce441b Use a free port for the Glass rail browser test 2026-10-04 02:18:38 +08:00
Jonathan Sykes
25ae810463 Glass Stage: float the section rail again, centred above the mini player 2026-10-04 02:17:48 +08:00
Jonathan Sykes
528e7c1ea1 Note the frontend import path rule for server modules 2026-10-03 22:13:03 +08:00
Jonathan Sykes
c6074bdbc5 Load the direct-transfer protocol from public/ inside the container image 2026-10-03 22:11:24 +08:00
Jonathan Sykes
49ba470740 Keep the Glass Stage notes toolbar on one row at every player width 2026-10-03 21:58:03 +08:00
Jonathan Sykes
729e73e131 Verify iPhone Glass tab alignment in WebKit with badges and safe-area spacing 2026-10-03 21:47:45 +08:00
Jonathan Sykes
3c0adb2577 Keep Glass Stage section navigation and panel content clear of playback chrome 2026-10-03 21:45:34 +08:00
Jonathan Sykes
d3f5133572 Record direct transfer coverage, fallback paths and verification results 2026-10-03 21:36:10 +08:00
Jonathan Sykes
90ef21297a Keep resume preparation and final verification outside connection timeouts 2026-10-03 20:49:08 +08:00
Jonathan Sykes
d78b06ff4b Close unconfirmed transfer paths and reject binary signalling envelopes 2026-10-03 20:45:04 +08:00
Jonathan Sykes
5661eea6e6 Preview compatible fragmented MP4 transfers while saving the verified copy 2026-10-03 20:43:03 +08:00
Jonathan Sykes
795a5aaed4 Prefer direct copies for playback, saves and exports within verified device groups 2026-10-03 20:38:51 +08:00
Jonathan Sykes
08ff8398b5 Transfer saved songs directly between paired devices with resumable OPFS writes 2026-10-03 20:32:45 +08:00
Jonathan Sykes
88e2e67eeb Authorize direct file invitations within paired rooms and parties 2026-10-03 20:26:07 +08:00
Jonathan Sykes
ef70da1806 Document device media paths and direct transfer requirements 2026-10-03 20:24:10 +08:00
Jonathan Sykes
d93fc0d70f Use Glass Stage icons for playlist and offline controls 2026-10-03 20:14:19 +08:00
Jonathan Sykes
79a3c28c8e Center Glass Stage tab icons above their labels 2026-10-03 20:11:10 +08:00
Jonathan Sykes
5e78374efb Explain save failures and keep download diagnostics available 2026-10-03 19:23:07 +08:00
Jonathan Sykes
f341b0c76e Restart failed saves through a guarded server retry 2026-10-03 19:16:08 +08:00
Jonathan Sykes
5485a3c2f4 Try alternate YouTube clients for unavailable save sources 2026-10-03 19:12:48 +08:00
Jonathan Sykes
613f8fb902 Cover Now Playing returns after browsing in both layouts 2026-10-03 18:29:48 +08:00
Jonathan Sykes
cdc367a972 Restore the playing playlist when returning to Now Playing 2026-10-03 18:28:58 +08:00
Jonathan Sykes
f2c9459a54 Unify Glass Stage navigation and page controls with Now Playing 2026-10-03 18:19:56 +08:00
Jonathan Sykes
8ea92c1aac Report phone playback metadata once per browser session 2026-10-03 17:56:01 +08:00
Jonathan Sykes
856ddda6a6 Backfill device song metadata and queue guarded server caching 2026-10-03 17:55:49 +08:00
Jonathan Sykes
9e960cf70f iPhone background audio in every playback mode; Classic playlist card actions; export sheet bar
- Dual mode (separate video + audio, used by adaptive streams and the iPhone EQ
  copies): going to the background now makes the audio the master, so progress,
  Now Playing and auto-advance keep working while iOS has the video suspended
  (the paused video used to be the only source of "ended", so playback stopped
  after the current song). The picture is re-synced on return.
- A track that starts while the app is in the background (auto-advance, the
  lock-screen Next button) starts as audio — iOS will not start a <video> there —
  and gets its picture back at the same position when the app returns.
- The handoff also runs on pagehide and when iOS pauses the master video while
  the page is hidden, for when visibilitychange arrives too late.
- Classic: playlist cards place their three actions as a 2x2 block (note + add
  on top, remove below) instead of the note button wrapping to the bottom-left.
- Save to this device: hide the full progress bar once the file is ready; it
  read as a squashed, broken button above "Save to Photos / Files".
2026-10-03 17:46:23 +08:00
Jonathan Sykes
ca836e0cd2 Align saved video actions and confirm storage removal 2026-10-03 16:10:46 +08:00
Jonathan Sykes
cf9b6f4133 Clarify download states and make the empty page useful 2026-10-03 16:05:42 +08:00
Jonathan Sykes
0374e19396 Add lazy piano transcription and optional leased server worker 2026-10-03 15:47:53 +08:00
Jonathan Sykes
d4354d220e Preserve and display bilingual and phonetic lyric cues 2026-10-03 15:20:52 +08:00
Jonathan Sykes
c8ab741d72 Upgrade to ten-band EQ with migrated curves and headphone widening 2026-10-03 15:16:09 +08:00
Jonathan Sykes
0b3e82a768 Add voice search and large-control Car mode 2026-10-03 15:10:30 +08:00
Jonathan Sykes
172e8231f0 Import worship setlists with confirmed song matches and keys 2026-10-03 15:09:51 +08:00
Jonathan Sykes
de89508bf4 Add centre-panned vocal reduction to live and saved audio 2026-10-03 14:59:44 +08:00
Jonathan Sykes
7d84fdb3dc Add transparent OBS lyrics output through presenter pairing 2026-10-03 14:58:20 +08:00
Jonathan Sykes
05e05ebace Add learnable MIDI pedal controls with hot-plug support 2026-10-03 14:56:06 +08:00
Jonathan Sykes
b72d2e36a6 Add floating synced lyrics with picture-in-picture fallback 2026-10-03 14:54:23 +08:00
Jonathan Sykes
d7721045fb Add host-approved party suggestions and live upvotes 2026-10-03 14:52:10 +08:00
Jonathan Sykes
75dbc468cc Add download controls and device storage breakdown 2026-10-03 14:47:57 +08:00
Jonathan Sykes
09ae6a2a85 Organize settings into searchable sections with responsive navigation 2026-10-03 14:42:39 +08:00
Jonathan Sykes
264bb26a36 iPhone: EQ and loudness levelling for saved songs that keep playing when locked
iOS stops Web Audio when the screen locks, so live processing can't reach a
locked phone. For saved songs, EqRender renders the same chain as the live EQ
(5 bands -> level gain -> limiter) offline into a 32 kHz stereo WAV in OPFS
(eq-renders/<id>.wav, written by the OPFS worker's new write op), one song at a
time in the background. Playback then takes the picture from the saved video
(muted) and the sound from that copy in dual mode — plain media playback, so it
continues with the screen locked; live gains are zeroed so nothing is applied
twice. Copies are re-rendered when the EQ curve or a song's loudness changes
and removed when nothing needs applying.

- Level volume is now on by default everywhere (on iPhone it reaches saved
  songs through these copies).
- New iPhone-only Settings -> Playback -> Live sound processing (off by
  default): live Web Audio EQ/levelling for streamed songs, stops when locked.
- The EQ dialog works on iPhone and explains where the curve applies.
2026-10-03 13:55:27 +08:00
Jonathan Sykes
2c6f285cfe Settings: the saved-videos list folds
Settings → Offline cache lists every saved video; it now sits in a collapsible
'Saved videos' section showing the count and total size, closed by default,
remembering how it was left.
2026-10-03 08:08:53 +08:00
Jonathan Sykes
258aad83dd Add piano transcription, interactive key visualizer, and practice queue features 2026-10-03 07:55:33 +08:00
Jonathan Sykes
2b38717c05 Add admin analytics, metadata collection, and grouped lyric cues
Queue reviewable Whisper drafts from the song list and lyrics editor. Preserve line breaks within one timed cue across editing, saving, reporting, and service views.

Add storage and listening analytics with a durable metadata collector, related-search depth, video limits, thumbnail storage, and a browsable metadata library.
2026-10-03 07:55:33 +08:00
Jonathan Sykes
716b61ffee Document feature ideas and enhancement roadmap across playback, audio, worship and library 2026-10-03 07:55:33 +08:00
Jonathan Sykes
5d94acf3f0 Chapter picker: tap the chapter badge to jump to any chapter
The CH badge by the scrubber is now a button opening a list of every chapter
(number, title, start time); the playing one is highlighted and scrolled into
view, a tap seeks there (and resumes if paused). Works with shared chapters and
YouTube's.
2026-10-03 07:50:15 +08:00
Jonathan Sykes
ea9e11d054 Loudness levelling (EBU R128, -14 LUFS) measured in the browser with WebAssembly
- frontend/wasm/loudness.c → loudness-wasm.js (1.5 KB, base64-embedded; built by
  scripts/build-loudness-wasm.sh with clang or Zig's clang): K-weighting + 100 ms
  energy steps. loudness.js does the 400 ms gating (abs -70 LUFS, rel -10 LU)
  with an identical JS fallback. EBU Tech 3341 sine cases measure -23.0/-33.0
  on both engines; a real track reads -21.7 vs ffmpeg ebur128 -21.8.
- The device measures from audio it already has (saved copy or the server
  cache's m4a sidecar, songs up to 12 min, decoded natively at 22.05 kHz) and
  reports the number to /api/loudness, so each song is measured once for
  everyone; the server stores numbers only, no audio processing.
- The EQ graph gains a level stage (gain -> limiter) that eases each track
  toward -14 LUFS (-12..+9 dB). Settings -> Playback -> Level volume: on by
  default on Android/desktop, opt-in on iPhone (Web Audio stops sound when the
  screen locks there).
2026-10-03 07:44:44 +08:00
Jonathan Sykes
796293c0a5 Admin upload card: styled file pickers, aligned fields, drag-and-drop
The raw browser file inputs (grey 'Choose File', truncated 'No fi...osen')
sat beside styled fields of other heights with Upload orphaned on its own row.
Now a drop zone that names the chosen file (size, type) and accepts drops, a
labelled Title / Artist / Cover row with a cover thumbnail preview, and a
clear 'choose a file first' message. Same IDs and upload code; stacks on phones.
2026-10-03 07:37:22 +08:00
Jonathan Sykes
47feded91b Sidebar: hide the Classic SVG nav icons outside the Classic layout
They relied on the hidden attribute, which browsers do not reliably honour on
SVG elements, so in Glass Stage each nav item drew a full-size black icon.
2026-10-03 07:29:38 +08:00
Jonathan Sykes
5154ef5f75 Collect discovered video metadata and recommend videos from listening history 2026-10-03 07:16:51 +08:00
Jonathan Sykes
343eb53d89 Redesign Classic layout for desktop and mobile 2026-10-03 06:44:22 +08:00
Jonathan Sykes
54fcd12119 YouTube chapters: extracted automatically, ticks on the seek bar and Glass scrubber, [ / ] to jump
- Server: chapters come from yt-dlp's `chapters` (creator chapters and
  description timestamps) whenever a video is resolved, kept in a yt_chapters
  table; GET /api/chapters?v= serves them (resolving once if needed, 30-day
  cache) so server-cached copies get them too. Never fails the player.
- Player: a video's shared chapters win; with none, YouTube's stand in —
  listed as "Chapters from YouTube", read-only (no edit/delete; + Chapter
  copies them into an editable list). They drive the existing seek-bar ticks
  (classic and Glass Stage), the chapter badge and the chapter list, and are
  cached offline with the video's notes.
- Keys: [ previous chapter (restarts the current one when >3 s in), ] next.
2026-10-03 03:52:50 +08:00
Jonathan Sykes
8084411f6a Bulk-select a channel's videos into a playlist; last card no longer hidden under the bottom bars
- Channel pages join the select-mode views: tap Select in the filter row, pick
  videos (or Select all — respects the filter), then + Queue / + Playlist.
  Delete is hidden there (nothing to delete on a channel).
- --bottom-chrome (the fixed bottom nav + mini player height) is now measured
  whenever the mini player shows/hides and on resize/rotation, not only while
  the section rail scrolls, and the list pane pads its end by it, so the last
  card scrolls fully clear with or without the mini player.
2026-10-03 02:21:55 +08:00
Jonathan Sykes
2dfce8a2fb iPhone/iPad: no page zoom; PCs keep browser zoom
Stray pinches and double-taps kept zooming the installed app. On iOS only the
viewport gets maximum-scale=1/user-scalable=no, Safari's gesture events are
cancelled and the page uses touch-action: manipulation. The player's own pinch
zoom (pointer events) still works.
2026-10-03 02:07:41 +08:00
Jonathan Sykes
9ce9a96f38 Channels load for every channel type; parallel saves setting (default 4)
Channels: one loader tries, in order, the Videos/Live/Shorts tabs (normal
channels), the uploads playlist (Topic channels), the Releases/Playlists tabs
expanded into their tracks (artist/music channels whose only content is albums,
e.g. Cathedral of Praise Worship), then the home page; bare names are resolved
to an id first. Nothing public → ok with a message, never a raw yt-dlp error.

Saves: SaveSlots caps concurrent offline saves (Settings → Offline cache →
Videos saved at once, 1–8, default 4); queued saves show "Waiting for a free
slot", and resumed saves now run up to the limit instead of one at a time.
2026-10-03 02:04:27 +08:00
Jonathan Sykes
71f1913d0b Optional profile password or key, with a credentials file to sign in other devices
Profiles without protection behave as before. Protected profiles store only an
argon2id hash; load, save, protection changes and the playlist inbox need the
secret (X-Profile-Secret), wrong guesses are throttled per profile and IP.
Settings: Protect (password or generated key), change/remove, export and import
a credentials file; loading a protected profile prompts for the secret.
2026-10-03 01:51:07 +08:00
Jonathan Sykes
91627dc0a9 Share target: shared YouTube links play, shared audio/video uploads to the user's library; page shortcuts
- manifest share_target (POST multipart: title/text/url + audio/video files)
  and eight shortcuts (Search, Queue, Saved, Downloads, History, Library,
  Notes, Settings). /?view=<page> now actually opens that page — the old
  shortcuts pointed at it but nothing read it.
- sw.js receives the share: files are parked in the ytp-share-inbox cache (not
  a versioned shell cache, so deploys never evict it) and the app is opened;
  links/text go to /?shared=. A server POST /share-target fallback covers the
  first visit before a worker is in control (links only).
- The app plays a YouTube link found anywhere in the shared text (watch,
  youtu.be, shorts, live, embed, music; keeps t=), otherwise searches the text.
  /?shared=<link> also works from an iOS Shortcut (iOS has no share target).
- Shared files upload with progress to PUT /api/uploads/shared and join a
  "Shared uploads" playlist; network failures stay in the inbox for the next
  open, refusals are dropped with the reason.
- The public route is bounded: audio/video only (ffprobe-validated, error text
  without server paths), 500 MB per file, 2 GB and 20 a day per device, 50 GB
  for all shared uploads, one at a time per device (all env-tunable). Shared
  uploads are unlisted: reachable by id, never in anyone else's search.
  uploads gains owner + listed columns (idempotent ALTER).
2026-10-03 01:33:51 +08:00
Jonathan Sykes
6581509ddd Update icon beside the search box after the update dialog is dismissed
Shown as soon as an update is offered, so Later, a backdrop tap or a failed
download all leave a one-tap way to update; it targets the newest build and
disappears while updating. The search form and box now shrink so the icon
never pushes Search off a phone screen.
2026-10-03 01:26:52 +08:00
Jonathan Sykes
65f5325a8e Search from service mode no longer strands the user on the home screen
In service mode's Video view the overlay lives inside the player pane, which
the home-over rule hid, while service mode kept the bottom bar and mini bar
hidden. Going home now leaves service mode first, and the rule spares the
service overlay.
2026-10-03 01:15:44 +08:00
Jonathan Sykes
caf0199c11 Fast lyric fitting for long videos; Search tab returns to the home screen while playing
- fitLyricLines measures text on a canvas with the line's own font and writes
  every --fit after measuring (it used an in-list DOM probe and wrote inside
  the loop, re-laying-out the whole list per line). 1200 lines: 600 ms -> 28 ms;
  sizes match the old method within 1 px. Service mode on long sermons with
  hundreds of transcribed lines opened slowly enough on phones to look broken.
- Bottom-nav Search while something plays shows the home screen (playlist
  board / hero) over the player pane; the media keeps playing unseen and the
  mini bar brings the player back (its close button too, so there is always a
  way back). Starting another video restores the player.
2026-10-03 01:10:15 +08:00
Jonathan Sykes
171a0bd127 Glass Stage buffered chip: 'Saved on device' for device copies, and measure the range around the playhead
It read the last buffered range, so seeking ahead made the figure jump, and a
device copy showed a meaningless partial percentage.
2026-10-03 01:00:09 +08:00
Jonathan Sykes
cbffa1fd8b Saves: paint progress only on Downloads rows, not on search/playlist cards
Every card of a video carries .downloading while it saves, so the progress
painter rewrote their channel line and its final repaint left 'Saving for
offline…' on the card after the save had finished.
2026-10-03 00:59:18 +08:00
Jonathan Sykes
16e2b24c31 Resumable saves: prepare reports the mp4's real size, not the cache row's mp4+m4a total
The media_cache row's size counts the audio sidecar too, so a device asked for
bytes past the end of the file and could never finish a ranged save.
2026-10-03 00:49:24 +08:00
Jonathan Sykes
56b3f4e449 Resumable saves: ranged downloads that survive dropped connections, reloads and app kills
Server
- /api/download/:id answers Range with a strong ETag ("<id>.<gen>") and honours
  If-Range; a stale partial gets the whole current file (streamed, so Bun does
  not re-apply the Range itself). Uploads get the same treatment.
- GET /api/download/:id/prepare never blocks: ready {gen,size,sha256,etag,ext},
  working (server still fetching), legacy (HEVC / too long / cache offline),
  failed. Recently refused prepares are remembered for 10 minutes.

Browser
- The OPFS worker saves in 8 MiB ranges, writes at the byte offset, flushes
  each chunk, retries each chunk 6 times with backoff (30 s idle timeout) and
  keeps the .part plus a .part.json sidecar naming the server copy it belongs
  to. A changed copy restarts cleanly; the finished file is hashed once and
  checked against the server's SHA-256.
- SaveQueue remembers unfinished saves and resumes them on start, online,
  return to the foreground and every 2 minutes while visible; one at a time.
- Downloads shows live MB progress, 'Preparing on server', 'Verifying', and
  paused saves with Resume and Cancel (confirmed).
- listVideos ignores the sidecars; new listPartials/discardPartial helpers.

Verified in Chromium through a connection-dropping proxy: paused at 8 MiB,
auto-resumed after a reload from byte 8388608, final SHA-256 matched.
2026-10-03 00:46:52 +08:00
Jonathan Sykes
c8601c5953 Merge remote-tracking branch 'github/claude/friendly-dirac-hz5pje' into resume-downloads 2026-10-03 00:28:45 +08:00
Jonathan Sykes
11ddb8a970 Uploads library on the USB drive with a nightly stable-disk copy; Topic channels resolve by name
- UPLOAD_DIR moves to the USB drive; reads fall back to UPLOAD_BACKUP_DIR on the
  ytplayer-data volume, and while the drive is offline new uploads land there
- scripts/ops/uploads-backup.sh (homelab cron, 03:30) copies both ways, never
  deletes; the server removes a deleted upload from both places
- /api/channel resolves a bare channel name ('Artist - Topic') to its id via a
  search, and the client falls back to the channel name for old saved entries
2026-10-02 22:38:05 +08:00
Jonathan Sykes
1f9a97a6ae Media cache on the homelab USB drive with an offline guard; Topic channels list their tracks
- MEDIA_DIR moves to /mnt/data/ytplayer (bind-mounted at /app/bulk); DB, lyrics,
  notes and uploads stay on the ytplayer-data volume
- MEDIA_VOLUME_MARKER: while the marker on the drive is missing the cache writes,
  serves and deletes nothing, so playback streams and an unmounted drive never
  fills the disk under its mountpoint or loses its index on a reboot
- Budget 250 GiB, keep 20 GiB free on the drive
- /api/channel falls back to the uploads playlist and the channel home page when
  a channel has no Videos tab (auto-generated '- Topic' music channels)
2026-10-02 21:21:23 +08:00
Jonathan Sykes
53da71ceb9 Service mode: one view button (default, lyrics, video, visualizer, album art) and a text-size box
- A single dock button cycles the service view; video is skipped in audio-only mode
- Visualizer reacts to the audio where the EQ graph is available and falls back
  to an ambient pulse on iOS so background playback is never routed through Web Audio
- Album art shows the song artwork with the letterbox cropped
- A-/A+ box steps lyrics, title and channel size from -2 to +2 in every theme
- Glass Stage dock is slightly more compact
2026-10-02 21:11:15 +08:00
Jonathan Sykes
985063648f Icon-only playlist header and filter-row actions, one-row transport, resumable update download
- Playlist title wraps within 90% of the width; rename and share are icons beside it,
  and tapping the title opens the rename box showing the full name
- Offline, pin, select and delete are icon buttons to the right of the filter input
- Transport is one row again: prev, back 10, play, forward 10, next
- Update download stages each file as it arrives so a retry only fetches what is
  missing, keeps 4 requests in flight and allows 5 minutes
2026-10-02 20:59:51 +08:00
Jonathan Sykes
236c129b90 Pin PyAV below 19 so faster-whisper can open audio again 2026-10-02 19:19:20 +08:00
Claude
0d92accd1d Run SHA-256 as WebAssembly with JS fallback; note ffmpeg.wasm as deferred 2026-10-02 11:10:51 +00:00
Jonathan Sykes
3f8c9fc365 Stop the lyrics worker from filling the disk: skip long audio, sweep stale temp files, back off after a crash 2026-10-02 15:06:10 +08:00
Claude
883c9e7ba0 Document search library, server search cache and versioned static caching 2026-10-02 02:15:36 +00:00
Claude
ee248d2303 IndexedDB search library (1000x100, 15-day copies, Update search), server video metadata for instant local results 2026-10-02 02:15:28 +00:00
Claude
1b10a994dd Version-stamped static URLs cached forever, thumbnail cache 25000 with throttled trimming 2026-10-02 02:11:38 +00:00
Claude
c69cc3a4bc Persistent server search cache: 200 results per query, 250k queries, 15-day stale-while-revalidate, refresh=1 2026-10-02 02:10:39 +00:00
Claude
14e2307a92 Keep search results with thumbnails until cleared in Settings; add stale-while-revalidate search and longer asset caching 2026-10-01 22:04:51 +00:00
Claude
61a8f63385 Make the channel name a visible link directly under the title 2026-10-01 21:54:39 +00:00
Claude
fecb824c9a Style the A-B group, Fullscreen and More buttons like the mockup 2026-10-01 21:54:17 +00:00
Claude
8c463f3834 Rebuild the Glass Stage A-B quick row and restyle the title block with a verified badge 2026-10-01 21:51:38 +00:00
Claude
6bf2636864 Bring Glass Stage closer to the mockup: HUD chips, sleep card, chapter badge, A-B group, playlist banner and P2P strip 2026-10-01 21:45:44 +00:00
Claude
19973c75c0 Add the Glass Stage layout theme with overlay controls, 10 s skips, quick chips and stacked tiles 2026-10-01 21:40:20 +00:00
Claude
36fc5ff9e4 Merge Queue and Playlist into one Add button and put Service mode in the common actions 2026-10-01 21:17:37 +00:00
Claude
859ecd2255 Move speaker and playback mode beside the volume slider with a volume-aware icon 2026-10-01 21:13:27 +00:00
Claude
9be4844b48 Show only the dots on More controls while A-B markers are present 2026-10-01 21:09:59 +00:00
Claude
b3a43c66db Label the fullscreen button, add a mini fullscreen icon and show A-B markers beside it 2026-10-01 21:09:00 +00:00
Claude
25e7a28b6a Merge shuffle, repeat list and loop one into one playback mode button 2026-10-01 21:03:48 +00:00
Claude
f9cb7edeb2 Replace transport emoji with centred SVG icons and distinguish loop-one from repeat-list 2026-10-01 21:02:23 +00:00
Claude
9f313f61af Move secondary player controls into a More controls sheet 2026-10-01 20:58:15 +00:00
Claude
88f878b8eb Move rarely used video actions into a More actions sheet 2026-10-01 20:55:04 +00:00
Claude
47826536a6 Make the refresh button 10% of the row width 2026-10-01 20:43:41 +00:00
Claude
9eb5e98048 Add Gallery action beside Save and an icon-only refresh beside Play all 2026-10-01 20:39:17 +00:00
Claude
02b337fcbc Add save-to-device export, server export route and an On other devices P2P list 2026-10-01 18:53:00 +00:00
Claude
08e95814e5 Support hour-long uploads and videos: raise body limit, stream uploads to disk, cache up to 3 h, add deferred-ideas note 2026-10-01 18:48:37 +00:00
Claude
9d74769029 Add deck tabs, uniform action buttons, lyric reports in the player panel and a song list in the lyrics studio 2026-09-30 15:57:11 +00:00
Claude
e64880c163 Redesign playlist header, player deck, now-playing actions and lyrics panel layout 2026-09-30 15:29:44 +00:00
Claude
3fb1d29d5a Redesign admin as a tabbed lyrics studio with undo, tap-sync pad and reported-line triage 2026-09-30 15:21:11 +00:00
Claude
04a74ab45d Redesign service-mode controls and add per-profile wrong-lyric-line reports 2026-09-30 15:15:07 +00:00
Claude
0d68e7e72f plan: record commit hashes in the queue index 2026-09-30 08:05:17 +00:00
Claude
84cd00368d Add a P2P panel to the admin page 2026-09-30 08:02:52 +00:00
Claude
c55cf1f651 plan: start 019-admin-p2p-panel-4dc623 2026-09-30 07:58:43 +00:00
Claude
60a28fc593 Restore an evicted server copy from an online holder 2026-09-30 07:58:42 +00:00
Claude
6d3cefa874 plan: start 018-server-rehydrate-from-peer-4fb8bd 2026-09-30 07:54:34 +00:00
Claude
c8837befed Download a verified file from another device over WebRTC 2026-09-30 07:54:34 +00:00
Claude
458aff757a plan: start 017-peer-transfer-1faaa7 2026-09-30 07:50:38 +00:00
Claude
8d57a654c1 Let a device hand a file to the server for hashing and validation 2026-09-30 07:50:38 +00:00
Claude
30e61de36f plan: start 016-intake-and-server-verification-cfe031 2026-09-30 07:45:13 +00:00
Claude
61d0274896 Show peer availability with stale markers and add Sharing settings 2026-09-30 07:45:13 +00:00
Claude
780624347f plan: start 015-availability-ui-and-settings-3b9397 2026-09-30 07:42:35 +00:00
Claude
6fa930ad62 Add the /ws/p2p presence and signalling hub and the holders endpoint 2026-09-30 07:42:35 +00:00
Claude
ef7d08f16a plan: start 014-p2p-presence-hub-ceced8 2026-09-30 07:38:47 +00:00
Claude
c629ff5836 Register devices and report verified holdings to the server 2026-09-30 07:38:47 +00:00
Claude
76e0d2f72d plan: start 013-device-identity-and-holdings-3ba493 2026-09-30 07:31:18 +00:00
Claude
6af96622dd Add the on-device IndexedDB file registry and hash saves while downloading 2026-09-30 07:31:18 +00:00
Claude
8b7b2a62bd plan: start 012-device-file-registry-288d55 2026-09-30 07:27:31 +00:00
Claude
b56be586ee Add an incremental SHA-256 library for the browser and node tests 2026-09-30 07:27:31 +00:00
Claude
a27788a80a plan: start 011-browser-sha256-e1793d 2026-09-30 07:25:56 +00:00
Claude
eb3fe45761 Count views and evict server copies by retention criteria before LRU 2026-09-30 07:25:56 +00:00
Claude
f12ca87131 plan: start 010-views-and-retention-d0c6ca 2026-09-30 07:18:52 +00:00
Claude
ea56d286b3 Hash every validated server copy and register it as verified content 2026-09-30 07:18:52 +00:00
Claude
b19193841c plan: start 009-server-content-hash-186e7f 2026-09-30 07:11:55 +00:00
Claude
167df35a97 Add P2P tables, config flags and db helpers 2026-09-30 07:11:55 +00:00
Claude
2d98b25340 plan: start 008-p2p-schema-and-config-127966 2026-09-30 07:04:53 +00:00
Claude
9cac21afce Keep one long-lived yt-dlp worker process instead of spawning per call 2026-09-30 07:04:53 +00:00
Claude
b8658f3a9d plan: start 007-ytdlp-worker-045800 2026-09-30 06:58:05 +00:00
Claude
556436da34 Answer searches from YouTube InnerTube directly with yt-dlp fallback 2026-09-30 06:58:05 +00:00
Claude
d61809f5c4 plan: start 006-innertube-search-48066b 2026-09-30 06:53:48 +00:00
Claude
b24366d6c0 Warm the stream cache for likely next plays 2026-09-30 06:53:48 +00:00
Claude
67c2f6e46c plan: start 005-warm-streams-on-intent-47b3d3 2026-09-30 06:50:31 +00:00
Claude
e2a60792b9 Coalesce concurrent resolveStreams calls for the same video 2026-09-30 06:50:31 +00:00
Claude
617df320c7 plan: start 004-coalesce-stream-resolves-a92d40 2026-09-30 06:47:04 +00:00
Claude
663a33573a Self-host the three web fonts and drop the render-blocking Google Fonts CSS 2026-09-30 06:47:04 +00:00
Claude
1001b85f40 plan: start 003-self-host-fonts-89466b 2026-09-30 06:45:11 +00:00
Claude
794410916a Serve the app shell gzip/brotli-compressed with ETags 2026-09-30 06:45:11 +00:00
Claude
7229ca16b9 plan: start 002-compress-and-etag-shell-bd459c 2026-09-30 06:41:54 +00:00
Claude
7781e0a116 Add startup, search and play timing marks plus yt-dlp duration logs 2026-09-30 06:41:50 +00:00
Claude
7b818baf8d plan: start 001-perf-timing-marks-105acc 2026-09-30 06:39:48 +00:00
Claude
c17bd4c9ac Queue executable speed and peer-to-peer sharing plans with tested patches and harnesses 2026-09-29 19:03:12 +00:00
Claude
a0ffc1b493 Refocus the improvement plan on speed and new features 2026-09-29 17:40:57 +00:00
Claude
92985d209a Add a phased improvement plan for the app 2026-09-29 17:35:55 +00:00
Jonathan Sykes
56d0838391 support shareable search links via a ?q= URL parameter 2026-09-30 00:19:20 +08:00
Jonathan Sykes
74777ef87f show a lightning icon on recent searches that will load instantly 2026-09-30 00:18:22 +08:00
Jonathan Sykes
6ff9f86bd8 cache /api/search results for 3 minutes to skip repeat yt-dlp spawns 2026-09-30 00:17:44 +08:00
Jonathan Sykes
4f0ee45980 cache recent search results locally so re-running one is instant 2026-09-30 00:16:35 +08:00
Jonathan Sykes
6480b314d5 remember recent searches on-device and show them under the search box 2026-09-29 22:08:16 +08:00
Jonathan Sykes
b6fdff2438 drop the boxed background on the saved-offline card badge 2026-09-28 20:30:13 +08:00
Jonathan Sykes
ba697e5d11 floor service-mode lyric font size and space out verses 2026-09-26 02:11:07 +08:00
Jonathan Sykes
05e85a0a3f Give untimed lyrics one uniform line size in service mode 2026-09-24 08:34:09 +08:00
Jonathan Sykes
d64c5f2613 Lift the section rail clear of the floating mini player 2026-09-22 14:58:31 +08:00
Jonathan Sykes
f411e49e4c Floor the party panel and rail above the bottom nav in CSS so a bad measurement cannot hide their controls 2026-09-22 14:44:30 +08:00
Jonathan Sykes
aa92fb1f05 Count a bottom bar that stops above the home indicator when placing the rail 2026-09-22 14:33:31 +08:00
Jonathan Sykes
c9e021a045 Keep the watch party panel above the bottom bars so its leave button is reachable 2026-09-22 14:23:39 +08:00
Jonathan Sykes
6c4571cb33 Measure the bottom bars so the section rail is never hidden behind the mini player 2026-09-22 14:09:03 +08:00
Jonathan Sykes
530d07d920 Add a mobile section rail that follows the scroll, jumps between cards and folds the one you are on 2026-09-22 13:47:26 +08:00
Jonathan Sykes
987697e759 Paint saved playlists before the launch sync and swap a background-downloaded update instantly 2026-09-22 13:27:12 +08:00
Jonathan Sykes
691e204d61 Pass an effort level to agy and default it to the one that actually finishes 2026-09-21 23:53:02 +08:00
Jonathan Sykes
2a4526578f Show lyrics in place of the video for watch parties and sing-alongs 2026-09-21 21:03:46 +08:00
Jonathan Sykes
0aa6c95494 Time correct lyrics from a machine transcript by aligning the two word streams 2026-09-21 20:16:02 +08:00
Jonathan Sykes
e6d14b9eb4 Find lyrics with agy when LRCLIB has nothing, keeping the best of several non-deterministic answers 2026-09-21 11:44:43 +08:00
Jonathan Sykes
808306ffce Keep the five transport buttons grouped on one line at every screen width 2026-09-21 10:33:06 +08:00
Jonathan Sykes
1ce3cb8949 Document the admin lyric editor, the lyrics skills and the LRCLIB matching guards 2026-09-20 18:07:08 +08:00
Jonathan Sykes
89d35562d3 Match LRCLIB on the song title when the channel is not the artist, and stop generic words like Christian or worship from vouching for an artist 2026-09-20 18:06:04 +08:00
Jonathan Sykes
2987f46037 Add a scrubbable timed lyric editor to the admin page, LRCLIB regeneration tooling with lyrics skills, and keep the five playback buttons on one row on phones 2026-09-20 17:55:49 +08:00
Jonathan Sykes
b983c6ca3c Fetch lyrics from LRCLIB (synced when available) and serve an admin media library of uploaded video and audio with cover art and embedded lyrics 2026-09-20 05:59:50 +08:00
Jonathan Sykes
9c1ec4ac51 Add presenter view, stats, lyrics worker, watch party with voice chat, timestamp sharing, soundbites, notes, transcript search, PiP, EQ, sleep fade, gestures and external players; fix the crossfade end-of-song race 2026-09-20 00:07:12 +08:00
Jonathan Sykes
ca07e1fdf1 Add gapless and crossfade playlist transitions with a mode toggle, and a waveform seek bar for audio-only playback 2026-09-19 16:12:33 +08:00
Jonathan Sykes
71fc51fb50 Add a lyrics-only service mode view with the sung line centred and auto-sized, and a free local faster-whisper script to transcribe saved songs 2026-09-19 08:33:00 +08:00
Jonathan Sykes
b82f17cd46 Add phone remote control: pair a phone with a 6-digit code or QR to drive a desktop instance's playback, queue, volume, sleep timer and service mode 2026-09-18 20:19:00 +08:00
Jonathan Sykes
524db986d2 Add shared synced lyrics, chapters and personal bookmarks with revision history, API tokens and an admin page 2026-09-18 18:10:10 +08:00
Jonathan Sykes
a20dd0a3a6 Replace saved copies that fail to play, reject truncated saves, and re-check the device cache when the app returns to the foreground 2026-09-18 10:11:20 +08:00
Jonathan Sykes
64f45a102d Check the playlist inbox when the app returns to the foreground and every two minutes while open
Sent playlists were only picked up on a cold start, so an installed PWA
resumed from the background never showed them.
2026-09-18 09:28:01 +08:00
Jonathan Sykes
e4ac04cb5c Sample two short windows before re-encoding a cached video and skip the full encode when HEVC will not save 15 percent 2026-09-14 00:51:14 +08:00
Jonathan Sykes
8b0060d42a Re-encode cached videos to HEVC when it saves at least 15 percent and serve them only to devices that can decode HEVC 2026-09-13 21:09:15 +08:00
Jonathan Sykes
91dab289c3 Show the update banner only when the running build differs from the server and make Refresh UI land the new shell on flaky links 2026-09-13 17:42:50 +08:00
Jonathan Sykes
5fb863ba25 Cache every played or saved video on the server via background jobs with a validation gate and a Broken re-download button 2026-09-13 09:45:01 +08:00
Jonathan Sykes
292a0c7e29 Show the video inline in service mode and keep audio alive in the background 2026-09-08 17:36:55 +08:00
Jonathan Sykes
a3089dde74 Add a service mode shortcut to the now-playing bar and a video panel toggle 2026-09-08 16:59:43 +08:00
Jonathan Sykes
3e1b56610f Let a shared playlist be sent to another user by name 2026-09-08 15:52:46 +08:00
Jonathan Sykes
9366b1749c Keep service mode full-bleed on iOS and hide the player chrome behind it 2026-09-08 11:55:15 +08:00
Jonathan Sykes
765a00b412 Drop the old Windows desktop build artifacts from the tree 2026-09-08 11:44:14 +08:00
Jonathan Sykes
e91fe83cc7 Fill the phone screen in service mode and open it on the playing song 2026-09-08 06:51:03 +08:00
Jonathan Sykes
06f80debc0 Prefer h264 formats for saves so cached copies play on every device 2026-09-01 07:02:57 +08:00
Jonathan Sykes
a159c1e642 Note deferred cookies-jar work for the YouTube bot gate in the backlog 2026-08-27 10:28:48 +08:00
Jonathan Sykes
d073d20060 Retry yt-dlp against alternate player clients when YouTube demands sign-in 2026-08-27 07:22:02 +08:00
Jonathan Sykes
94fff8f862 Report live streams as unsupported instead of an empty quality list 2026-08-24 01:07:18 +08:00
Jonathan Sykes
c141959654 Serialize saves, disable idle timeout, cap savable length at 3h 2026-08-24 00:21:18 +08:00
Jonathan Sykes
04c419d151 Coalesce save downloads, kill them on disconnect, refuse live and over-long videos 2026-08-23 23:50:10 +08:00
Jonathan Sykes
ea9e372c1e Rate-limit save downloads so they no longer starve playback 2026-08-23 23:13:45 +08:00
Jonathan Sykes
d1ba9d1e9c Fix play proxy cancel crashing the server on client disconnect 2026-08-23 22:54:31 +08:00
Jonathan Sykes
831063125d Enable bun as yt-dlp JS runtime to avoid throttled stream URLs 2026-08-23 22:41:37 +08:00
Jonathan Sykes
8177f5c665 Chunk playback proxy at 10MB and merge adaptive streams for saves 2026-08-23 15:43:01 +08:00
Jonathan Sykes
c8a9755e93 Restrict playback proxy to direct https streams, prefer adaptive
Newer yt-dlp surfaces HLS (m3u8) and DASH-segment formats whose url is a
manifest, not media bytes; proxying those served the video element an
unplayable m3u8 and broke Range seeking (416). Keep only protocol=https
formats, and prefer adaptive video-only streams (paired with the separate
audio) over progressive muxed formats, which are more reliable.
2026-08-23 15:15:02 +08:00
Jonathan Sykes
defc8a7f1a Proxy YouTube playback through server to fix intermittent 403s
Direct googlevideo URLs are bound to the extractor's IP and expire, so the
browser fetching them from a different IP got intermittent 403s on playback.
Route playback through a same-origin /api/play proxy that fetches the stream
server-side (matching the extractor IP) with yt-dlp's own http_headers and
forwards Range headers for seeking; fall back to piping yt-dlp for SABR/itag-18
formats a plain GET can't fetch. Prefer adaptive streams over progressive in
the playback fallback order.
2026-08-23 15:04:18 +08:00
Jonathan Sykes
ee78c8561b fix playlist name overflow with 2-line clamp 2026-08-17 02:13:51 +00:00
Jonathan Sykes
c08558cfb4 Enhance 5 layout themes with structural CSS — topbar, nav accents, mini-bar, ambient layers 2026-08-17 00:29:52 +00:00
Jonathan Sykes
9c2146aef8 Fix layout theme grid overrides breaking mobile — wrap in min-width:861px 2026-08-17 00:21:50 +00:00
Jonathan Sykes
eb6ed215fe Add 6 selectable layout themes to Settings (Appearance) 2026-08-16 16:33:26 +00:00
Jonathan Sykes
d01aedd4b2 Record the new playlist and set-list features in the backlog 2026-08-16 13:58:41 +00:00
Jonathan Sykes
8ef16a8b38 Add per-song notes on playlist entries 2026-08-16 13:58:22 +00:00
Jonathan Sykes
14e1d8e3dd Add service mode set-list view with screen wake lock 2026-08-16 13:51:27 +00:00
Jonathan Sykes
c5f47514ad Show per-playlist offline status and add a keep-offline pin 2026-08-16 13:45:19 +00:00
Jonathan Sykes
b868dabe27 Add bulk import of a YouTube playlist URL 2026-08-16 13:39:02 +00:00
Jonathan Sykes
27b28f767b Add shareable single-playlist links with additive import 2026-08-16 13:32:18 +00:00
Jonathan Sykes
57413a07a1 Hide the list pane on the home view until the first search 2026-08-16 12:58:05 +00:00
Jonathan Sykes
5a9304780a Give the empty-home playlist grid the full pane height instead of a clipped 16:9 box 2026-08-16 08:52:18 +00:00
Jonathan Sykes
4fd68ae88e Document cache layout, offline thumbnails and test invocation 2026-08-16 08:48:50 +00:00
Jonathan Sykes
49198ff239 Cache video thumbnails for offline use 2026-08-15 07:26:56 +00:00
Jonathan Sykes
fa9ef000b9 Show playlists instead of the branding hero on the empty home 2026-08-15 07:19:46 +00:00
Jonathan Sykes
b2154bd9c4 Add shareable profile link to settings and sidebar 2026-08-15 06:58:43 +00:00
Claude Worker
70460232f0 feat: Add scrubber with A/B markers for video editing/downloading 2026-07-18 17:59:20 +00:00
Claude Worker
046aa67108 feat: Add visual scrubber to video editor
Task #69 completed by ClaudeQueue

ClaudeQueue
2026-07-18 17:50:27 +00:00
Claude Worker
8c0776f97d feat: Add support for editing video
Add an Edit
2026-07-18 16:43:15 +00:00
Jonathan Sykes
94dba16ff6 Add plan-queue and run-queue skills 2026-07-16 20:51:51 +08:00
Jonathan Sykes
6fff68884b add per-song remember-position flag and playlist play-in-full mode 2026-07-14 15:15:11 +08:00
Jonathan Sykes
3afb22b305 document repo map and local dev, add deploy-prod skill
- CLAUDE.md gains a repo map, endpoint list, and local dev setup
  (server serves only ./public — symlink ../frontend once)
- new deploy-prod skill captures the Dokploy deploy + buildTag
  verification flow; track .agents/.claude skills and skills-lock.json
- ignore server/data, test-results, .claude/worktrees
2026-07-11 13:44:57 +08:00
Jonathan Sykes
70b5214ce8 fix intermittent 403 on video save by letting yt-dlp fetch the stream itself 2026-07-11 00:45:37 +08:00
Jonathan Sykes
88c89d66af fix portrait PWA nav dead while playing by making body the scroll container 2026-07-10 13:55:31 +08:00
Jonathan Sykes
b72c079fb4 respect repeat settings when a-b loop reaches point b 2026-07-04 18:11:21 +08:00
Jonathan Sykes
327a67004d Show build time in GMT+8 with 'built N ago' in Settings About 2026-07-04 12:49:41 +08:00
Jonathan Sykes
b8c7ad4ad1 fix: let list pane shrink in stacked layout so settings can scroll in mid-width windows 2026-07-03 06:05:16 +08:00
Jonathan Sykes
94140a5433 feat: add passkey-style online profiles for cross-device sync and show build time in About 2026-07-03 05:16:05 +08:00
Jonathan Sykes
048817bcf4 fix: fall back to copy when OPFS move() throws on WebKit and retry failed worker downloads on the main thread 2026-07-03 05:16:05 +08:00
Jonathan Sykes
76f8ec525d feat: add opt-in save-before-playing setting backed by server-compiled single-file downloads 2026-07-03 00:07:50 +08:00
Jonathan Sykes
ba05f0dafe fix: make audio the playback clock in dual mode so video rebuffering never pauses or seeks live audio; harden viewport anchor guard and add modal backdrop dismiss 2026-07-02 23:58:42 +08:00
Jonathan Sykes
ed9f93b0b7 fix: stop playback stutter and save failures via async yt-dlp, per-download OPFS workers, lazy playback blobs, GPU composite trims, and landscape pane scrolling 2026-07-02 23:40:49 +08:00
Jonathan Sykes
2af2eebacc feat: redesign portrait PWA as mobile app UI with thumb-zone transport, bottom-sheet modals, and floating mini-player 2026-07-02 22:38:14 +08:00
Jonathan Sykes
722457312c fix: re-anchor stray iOS layout-viewport scroll that broke nav taps 2026-07-02 21:48:31 +08:00
Jonathan Sykes
a73781a048 docs: record deploy procedure, update-flow architecture, and data-model quirks 2026-07-02 21:15:35 +08:00
Jonathan Sykes
4a18990058 fix: inject BUILD_TAG into sw.js via regex so a fallback bump cannot freeze the SW version 2026-07-02 21:07:22 +08:00
Jonathan Sykes
e6f032a6f2 feat: add shuffle toggle for upcoming tracks with S shortcut 2026-07-02 21:01:28 +08:00
Jonathan Sykes
6039dc80c1 fix: hash every served frontend file into the build tag so any shell change busts caches 2026-07-02 13:40:36 +08:00
Jonathan Sykes
dd71f6b2ab fix: fetch and activate the new service worker on Refresh UI when none is waiting yet 2026-07-02 13:40:36 +08:00
Jonathan Sykes
f36f6aeee1 fix: only treat a waiting service worker as an update when a controller exists 2026-07-02 13:40:36 +08:00
Claude Worker
8018060d26 feat: update ready keeps showing even after updating
Task #61 completed by ClaudeQueue

ClaudeQueue
2026-07-01 17:40:50 +00:00
Claude Worker
42ff13b135 feat: audio playback issue
Task #60 completed by ClaudeQueue

ClaudeQueue
2026-07-01 07:26:33 +00:00
Claude Worker
18ad8152bf feat: fix repetitive update available prompt
Task #58 completed by ClaudeQueue

ClaudeQueue
2026-07-01 06:37:12 +00:00
Claude Worker
395af38246 feat: update ready reloade stuck
Task #55 completed by ClaudeQueue

ClaudeQueue
2026-07-01 02:38:45 +00:00
Claude Worker
50cf655b71 feat: fullscreen video button not working in pwa mode
Task #52 completed by ClaudeQueue

ClaudeQueue
2026-07-01 02:18:50 +00:00
Claude Worker
ffeef5d520 feat: audio playback intermittent issue
Task #50 completed by ClaudeQueue

ClaudeQueue
2026-07-01 01:53:09 +00:00
Claude Worker
7cf3517dd3 feat: ensure ui automatically updates regardless of version number
Task #53 completed by ClaudeQueue

ClaudeQueue
2026-06-30 21:14:06 +00:00
Claude Worker
2b195d3b6b feat: add topbar adjustments for notch devices on pwa
Task #47 completed by ClaudeQueue

ClaudeQueue
2026-06-30 20:45:00 +00:00
Jonathan Sykes
d01f51a7d0 fix: send SKIP_WAITING to waiting SW, not active controller, to break reload loop 2026-07-01 04:43:33 +08:00
Jonathan Sykes
ebe60a7be2 fix: start next track at beginning (or A point) instead of resuming, and store A-B per playlist
When auto-advancing through a queue or playlist — or stepping with
next/prev — the next video previously jumped to its saved resume
timestamp. A freshly selected track now starts at the beginning, or at
the A marker when an A-B loop is set for it. Resuming still applies when
you reopen a single video directly.

A-B markers set while playing from a playlist are now stored on that
playlist's own copy of the video (entry.ab), so each playlist keeps its
own loop and the markers sync to the database alongside the playlist.
Non-playlist playback keeps using the global per-video marker map.

Bumps service worker to v1.0.3 to bust the client cache.
2026-07-01 04:29:00 +08:00
Jonathan Sykes
79359dba44 feat: show app version and server build tag in settings
Adds an About section at the bottom of Settings displaying the app
version. In WEB mode it fetches /api/version and appends the live
server build tag so you can confirm which deploy is running.
2026-07-01 04:04:15 +08:00
Jonathan Sykes
30a05d3ebd fix: make sidebar scroll as one unit so playlists stay reachable on short screens
The sidebar contained two .playlist-list blocks each with flex:1 and its own
overflow-y:auto, nested inside the sidebar's own scroll. On screens too short
to fit everything, those inner flex regions collapsed toward zero height and
the playlists became unreachable. Drop the inner scroll/flex-grow and let the
whole sidebar scroll as a single unit at any screen size.
2026-07-01 03:58:52 +08:00
Jonathan Sykes
fec069479f chore: bump service worker version to v1.0.2 to trigger client updates 2026-07-01 01:24:45 +08:00
Jonathan Sykes
041fc6a974 feat: add Reset UI section in settings (force refresh + full reset app) 2026-07-01 01:18:45 +08:00
Jonathan Sykes
6738644d4b feat: poll /api/version buildTag to detect new deploys and prompt reload
Server stamps a BUILD_TAG (stable per process, changes on restart/deploy)
into GET /api/version alongside the existing version string. Cache-Control
is set to no-store so the response is never cached by the SW or browser.

Client (WEB mode only) baselines the tag on first fetch after boot, then
rechecks every 5 minutes. On mismatch it calls the existing showUpdateBanner()
so the user sees the 'Update ready — Reload now' toast and can reload at will.

This mirrors the build-id polling pattern used across the BukidBountyApp
derivatives to avoid stale UI after deploys.
2026-07-01 01:13:37 +08:00
Claude Worker
d9371fdea4 feat: fix portrait mode design in pwa — YouTube-style bottom bar
Task #46 completed by ClaudeQueue

ClaudeQueue
2026-06-30 17:02:25 +00:00
Claude Worker
fc61defba5 feat: fix portrait mode design in pwa
Task #44 completed by ClaudeQueue

ClaudeQueue
2026-06-30 15:36:12 +00:00
Claude Worker
136e21f1fa feat: Follow-up: add portrait orientation design for mobile that only triggers in portrait pwa mode
Task #43 completed by ClaudeQueue

ClaudeQueue
2026-06-30 08:01:54 +00:00
Claude Worker
02153d877d feat: add portrait orientation design for mobile that only triggers in portrait pwa mode
Task #42 completed by ClaudeQueue

ClaudeQueue
2026-06-30 06:51:31 +00:00
ClaudeQueue
05e78677b0 feat: side bar playlist and other items not present on some screensizes. make completely responsive
Task #40 completed by ClaudeQueue

ClaudeQueue
2026-06-30 01:06:54 +00:00
Jonathan Sykes
f266c4ffb9 fix: bump service worker cache to v1.0.1 to evict stale app shell
Existing PWA installs cache the app shell (app.js et al.) cache-first under
ytplayer-v1.0.0. Without a version bump they'd keep serving the old app.js
that lacked WEB-mode OPFS support, so the offline-cache fix would never reach
already-installed clients. Bumping forces activate → old cache delete →
re-fetch, and triggers the in-app 'Update ready' banner.
2026-06-30 08:40:23 +08:00
Jonathan Sykes
84d6487125 feat: wire up WEB-mode OPFS offline cache for PWA
The PWA conversion shipped sw.js, opfs.js, manifest and icons, but app.js
was never updated to use them — it still routed cache_* calls through the
native bridge (call('cache.list', ...)), which throws 'No native bridge
available' in a browser. That surfaced as 'Offline cache unavailable /
not available in this build' on the Saved videos and Settings pages.

- Add WEB mode detection (no Tauri/zero bridge present)
- Route cache_* through OPFS (opfsDownload/Status/List/Delete/Clear)
- Proxy downloads via /api/download so the browser never hits YouTube CDN
- Load fingerprint.js + opfs.js; add manifest link and PWA meta tags
- Relax CSP to allow blob: media/img and worker-src 'self' for the SW
2026-06-30 08:37:45 +08:00
Jonathan Sykes
847e99cd51 feat: add Traefik labels for worship.hesed.sbs via homelab Dokploy
- Join dokploy-network so homelab Traefik can discover the container
- Remove host port binding (Traefik routes directly via service discovery)
- Add HTTP→HTTPS redirect and HTTPS router with letsencrypt cert
- VPS Traefik passthrough for worship.hesed.sbs already added on server
2026-06-30 07:13:25 +08:00
Jonathan Sykes
4efa1d1182 feat: convert to PWA — OPFS storage, service worker, Bun/Hono server
- Move native shells (Zig/src, Tauri/src-tauri, app.zon, releases) to legacy/
- Add Bun + Hono server with yt-dlp proxy endpoints (search, channel, streams,
  download), libsql (concurrent SQLite fork) for fingerprint-keyed playlist/
  history sync, and static file serving for the frontend
- Add Dockerfile + docker-compose.yml (single container, volume-mounted DB)
- Add frontend/sw.js: app-shell cache-first, /api/* network-only,
  thumbnails stale-while-revalidate, SW_UPDATE_AVAILABLE broadcast,
  SKIP_WAITING message handler for seamless auto-update
- Add frontend/manifest.webmanifest: standalone PWA, vermilion theme,
  search/history shortcuts
- Add frontend/icons/icon-{192,512}.png: generated PWA icons
- Add frontend/fingerprint.js: canvas+UA djb2 fingerprint, localStorage-cached,
  exposes window.getFingerprint() for server-side playlist keying
- Add frontend/opfs.js: full OPFS video store (writeFromResponse streams
  directly without full-file buffering), exposes window.OPFS
- Add scripts/make-pwa-icons.js: regenerate icons without external deps
- Patch frontend/app.js: WEB mode detection, webFetch + opfs* bridge wrappers,
  API object routes to WEB helpers when no native bridge present,
  Player.loadVideo handles OPFS blob URLs + revokes them on next load,
  SW registration + update banner in boot()
- Patch frontend/index.html: manifest link, theme-color, Apple PWA meta,
  CSP blob:/worker-src, fingerprint.js + opfs.js script tags
- Patch frontend/styles.css: .toast-update + .toast-reload-btn for update banner
- Native Tauri/Zig builds unchanged — all new code is additive via WEB flag
2026-06-30 06:43:23 +08:00
Jonathan Sykes
8a30fcfc4f build: refresh Windows release artifacts (v1.0.0) 2026-06-21 21:23:12 +08:00
Jonathan Sykes
fea26fd435 feat: make channel names clickable in related, up-next, and mini-bar 2026-06-21 21:13:44 +08:00
Jonathan Sykes
68d4921149 build: refresh Windows release artifacts (v1.0.0) 2026-06-21 18:46:13 +08:00
Jonathan Sykes
20cd2f29ba feat: sleep timer, A-B loop, related panel, smart playlists, history delete/search, batch ops, auto-backup 2026-06-21 18:43:26 +08:00
Jonathan Sykes
3ad2e40606 Refresh Windows release artifacts and sync build outputs 2026-06-21 16:15:30 +08:00
Jonathan Sykes
f497eecebd Merge branch 'main' of ssh://git2.hesed.sbs:6612/josh/ytplayer
# Conflicts:
#	frontend/app.js
2026-06-21 15:43:45 +08:00
Jonathan Sykes
38511fa450 feat: queue, channel view, downloads/saved pages, repeat/loop, accessibility, perf, multithreading 2026-06-21 15:39:58 +08:00
Claude Worker
44fa24ca52 refactor: tidy playlist-menu label and catch blocks
Pre-push code analysis pass for task #1

ClaudeQueue
2026-06-18 18:48:07 +00:00
Claude Worker
95dc9e3f98 feat: Prevent UI hanging during video save or playlist add
Task #1 completed by ClaudeQueue

ClaudeQueue
2026-06-18 18:43:48 +00:00
Jonathan Sykes
b67e40348b Move all completed items to Done section with commit hashes 2026-06-14 15:30:00 +08:00
Jonathan Sykes
d15d9021b7 Add cache cap, playlist export/import, yt-dlp build flag
Cache cap: dropdown setting (no limit / 1/2/5/10 GB) stored in
settings.cacheCap (actual eviction handled by native side).
Export: downloads playlists as JSON via Blob. Import: file reader
merges new playlists by id. yt-dlp: feature gate 'embed-ytdlp'
(default on), skip with --no-default-features for faster debug builds.

Files:
- frontend/app.js: exportPlaylists/importPlaylists, cache cap select
- src-tauri/Cargo.toml: [features] embed-ytdlp
- src-tauri/src/main.rs: #[cfg(feature = embed-ytdlp)] guards
2026-06-14 15:29:10 +08:00
Jonathan Sykes
c6b8dfceb8 Add rotating quick-search chips, video_id sanitize, retry button
Rotating chips: 4 sets of 4 chips rotate every 8 seconds on the
hero landing. Sanitize video_id: new sanitizeId() strips path
separators and dangerous chars. Retry button: appears on stream
extraction failure, re-triggers Player.loadVideo.

Files:
- frontend/app.js: sanitizeId(), CHIP_SETS + rotateChips(),
  retry button in loadVideo catch
2026-06-14 15:23:14 +08:00
Jonathan Sykes
c1855a1a91 Add persistent mini now-playing bar
Fixed bar at bottom of window when video is playing. Shows title,
channel, progress, play/pause toggle. Click to restore player view.

Files:
- frontend/index.html: mini-bar markup
- frontend/app.js: showMiniBar/hideMiniBar/updateMiniBar, wiring
- frontend/styles.css: .mini-bar, .mini-bar-inner, .mini-progress styles
2026-06-14 15:18:57 +08:00
Jonathan Sykes
4376cd9e88 Add up-next queue panel
Shows upcoming videos in the autoplay queue below now-playing meta.
Clickable to jump to any video. Hidden when queue has 1 item or empty.
Updates on playFromList, playNext, playPrev. Hidden in empty player state.

Files:
- frontend/index.html: upnext section in player pane
- frontend/app.js: renderUpNext(), wired into playFromList/playNext/playPrev
- frontend/styles.css: .upnext, .upnext-item, .upnext-list styles
2026-06-14 14:44:52 +08:00
Jonathan Sykes
0ba0f56a54 Add drag-to-reorder within playlists
Cards in playlist view are draggable. Visual feedback: opacity on
source card, accent border on drop target. Reorder persists to store.

Files:
- frontend/app.js: dragSource state, drag/drop handlers on cards,
  container-level dragover guard in wireUI
- frontend/styles.css: .card.dragging, .card.drag-over styles
2026-06-14 14:41:05 +08:00
Jonathan Sykes
a4d6b825d5 Replace single toast with stacked toast queue
Multiple toasts can appear simultaneously, capped at 3. Oldest
toast auto-evicts when cap is reached. Each toast auto-dismisses
with a fade-up exit animation.

- frontend/app.js: toast() now creates DOM elements in toastContainer
- frontend/index.html: single #toast replaced with #toastContainer
- frontend/styles.css: .toast-container flexbox row, .toast-exit animation
2026-06-14 14:36:07 +08:00
Jonathan Sykes
ddfa1494c6 Remember and restore last playback position per video
Saves playback position to store on pause and periodically every
10s during playback. Restores position (>1s) when the same video
is loaded again, showing a 'Resumed from 0:42' toast.

Files:
- frontend/app.js: resumePositions in data, save in pause/timeupdate,
  restore in Player.afterLoad, boot merge includes resumePositions
2026-06-14 14:31:19 +08:00
Jonathan Sykes
81aced9bc5 Add download progress bar on card thumbnails
Replaces pulse-only state with a visible progress bar animation:
- Indeterminate bar slides across the bottom of card thumbnails during download
- markCardCacheState dynamically adds/removes the bar element
- renderCard includes the bar for newly rendered downloading cards
- Now-playing button already showed '⏳ Saving…' state

Files:
- frontend/app.js: dl-progress in renderCard, markCardCacheState dynamic bar
- frontend/styles.css: .dl-progress, .dl-bar with dlSlide animation
2026-06-14 14:23:52 +08:00
Jonathan Sykes
c676786144 Add keyboard-shortcut help overlay
Press '?' to open a styled overlay showing all keyboard shortcuts,
Esc to close. Lists Space (play/pause), arrow keys (seek/volume),
F (fullscreen), M (mute), ? (help), Esc (close).

Files:
- frontend/app.js: toggleShortcutHelp(), wireShortcutHelp(), '?' and Esc handlers
- frontend/index.html: shortcut-overlay markup with .shortcut-grid
- frontend/styles.css: .shortcut-overlay, .shortcut-panel, .shortcut-row, kbd styles
2026-06-14 14:19:42 +08:00
Jonathan Sykes
da2ad27244 Add loading skeletons for search results
Replace bare 'Searching…' text with 8 animated skeleton cards that
mirror the real card layout (thumbnail, title, channel, menu dot).
Shimmer animation sweeps across placeholder blocks until results arrive.

Files:
- frontend/app.js: showSearchSkeletons() function, wired into search submit
- frontend/styles.css: .skeleton-card, .skeleton-shimmer, .skeleton-line, .skeleton-dot styles with shimmer animation
2026-06-14 14:14:05 +08:00
Jonathan Sykes
460aaae234 Add empty-state designs for empty playlists and history
Replaces bare status text with visual empty-state components:
- History: clock icon, 'Nothing watched yet' title, description, 'Search videos' CTA
- Playlist: music icon, 'This playlist is empty' title, description with tip, 'Browse videos' CTA
- Search: unchanged (hero landing handles this case)
- CTA buttons navigate to search view for quick action
2026-06-14 13:55:48 +08:00
Jonathan Sykes
4d5d105e70 Redesign landing page: hero with gradient brand wordmark, value pills (no ads / no sign-in / offline playlists), and clickable quick-search chips; refresh Windows installers 2026-06-14 12:03:14 +08:00
Jonathan Sykes
7ab486f15f Rebuild Windows installers from the current frontend - Save, Add-to-playlist (card + now-playing), and playlist auto-preload UI are now actually bundled (prior installers shipped a stale frontend) 2026-06-14 11:55:10 +08:00
Jonathan Sykes
fed2aef969 Embed yt-dlp into the binary so the standalone exe is self-contained (extract to cache on first run); drop now-redundant resource bundle; refresh Windows installers 2026-06-14 11:44:29 +08:00
Jonathan Sykes
63560a8e61 Add offline cache & preload, Save/add-to-playlist UI, Settings page; player stream fallback + progressive-first ordering; protocol-asset feature; refresh Windows installers 2026-06-14 11:36:01 +08:00
Jonathan Sykes
5375843c82 Add Windows v1.0.0 build artifacts (NSIS + MSI installers, standalone exe) 2026-06-14 10:53:39 +08:00
569 changed files with 444681 additions and 557 deletions

View File

@@ -0,0 +1,32 @@
---
name: deploy-prod
description: Deploy ytplayer to production (worship.hesed.sbs) via the Dokploy API and verify the deploy landed. Use when the user says deploy, ship to prod, release, push to production, or asks why production doesn't show a change (pushing git does NOT deploy). Manual-only — never deploy without an explicit request.
---
# Deploy ytplayer to production
Production is the web PWA at **https://worship.hesed.sbs**, running on the homelab Dokploy remote node; the control plane is Dokploy on the VPS. **Pushing to git does NOT deploy** — deploys are triggered explicitly.
## Steps
1. Confirm the change is pushed: `git -C ~/development/personal/ytplayer status -sb` must show no unpushed commits (`git push origin main` pushes both remotes).
2. Record the current build tag: `curl -s https://worship.hesed.sbs/api/version` → note `buildTag`.
3. Trigger the deploy (API key in `~/development/.secrets/dokploy-api.env`; compose ID `wprYCM8T51f7JtSHb983p`, project `ytplayer`, env `production`):
```bash
ssh -i ~/.ssh/tmp_vps/dokploy_session root@193.160.119.172 \
"curl -s -X POST -H 'x-api-key: $KEY' -H 'Content-Type: application/json' \
-d '{\"composeId\":\"wprYCM8T51f7JtSHb983p\"}' http://localhost:3000/api/compose.deploy"
```
4. Poll until done (build ≈ 5–6 min; poll every ~60s, give up after ~12 min):
```bash
# composeStatus: idle|running|done|error
... http://localhost:3000/api/compose.one?composeId=wprYCM8T51f7JtSHb983p
```
5. Verify: `curl -s https://worship.hesed.sbs/api/version` — **`buildTag` must differ** from step 2. Unchanged tag = the deploy did not land; report that, don't claim success.
6. Report old tag → new tag and the compose status to the user.
## If something goes wrong
- `composeStatus: error` → fetch the deployment logs via the Dokploy API and report the failing step verbatim.
- Homelab node unreachable on LAN is normal; everything above goes through the VPS hop (`ssh root@193.160.119.172`, then `ssh root@10.8.0.2` over WireGuard if you need the node itself). App container: `ytplayer-main-1dihzn-ytplayer-1`.
- Prod DB (for cleanup of `Probe */Recon *` test records): libsql file `/app/data/ytplayer.db` inside the container — delete children (`video_history`) first.

View File

@@ -0,0 +1,153 @@
---
name: lyrics-agy
description: Find lyrics (with timings when they exist) for worship.hesed.sbs songs using agy, the flat-rate Antigravity CLI, via the agy-bridge MCP server. Use when LRCLIB has no match, when a song still has no lyrics or bad machine-transcribed ones, or when the user says "ask agy for the lyrics". Also how to paste lyrics you already have into a song.
---
# Lyrics from agy
agy searches the open web and, when the song has a caption track or a published
sync, returns **timed** lyrics in LRC form. It is flat-rate, so a run costs
nothing per song — but it is the **last** resort, after LRCLIB (`lyrics-lookup`,
`lyrics-regenerate`), because LRCLIB's synced lyrics are published data while
agy's are derived.
Script: `scripts/lyrics/agy_lyrics.py`.
## Run it
```bash
cd ~/development/personal/ytplayer
export YTP_ADMIN_PASSWORD='…' # or YTP_TOKEN=ytp_…
# every song that still has no lyrics — dry run first, ALWAYS
python3 scripts/lyrics/agy_lyrics.py --missing
python3 scripts/lyrics/agy_lyrics.py --missing --apply
# one song, replacing lyrics that are wrong
python3 scripts/lyrics/agy_lyrics.py --ids ZHl6EwSwjv0 --overwrite --apply
# lyrics you already have (LRC or plain text), no agy call at all
python3 scripts/lyrics/agy_lyrics.py --ids ZHl6EwSwjv0 --from-file words.txt --overwrite --apply
```
Every run backs the current lyrics up to
`Documents/ytplayer-lyrics-backup-<stamp>.json` before writing, and the server
keeps each previous version as a restorable revision.
**One song takes ~2 minutes per attempt**, and `--tries` defaults to 3, so a
batch is slow. Run it detached rather than in a foreground command that will hit
a timeout:
```bash
setsid nohup python3 scripts/lyrics/agy_lyrics.py --missing --apply \
> /tmp/agy-lyrics.log 2>&1 < /dev/null &
```
## How it calls agy
Through MCPJungle, so no agy CLI contract is hard-coded here:
```bash
mcpjungle invoke agy-bridge__agy_ask --input '{"dir": "<repo>", "prompt": "…"}'
mcpjungle invoke agy-bridge__fetch_output --input '{"keep_id": "ask-…"}'
```
Four things about that interface cost real debugging time — do not rediscover them:
1. **`dir` is required.** Without it the call fails schema validation.
2. **The answer arrives on STDERR**, not stdout. Read both streams or you get
an empty string and conclude, wrongly, that agy found nothing.
3. **Long answers are truncated** with `fetch_output(keep_id='…') for more`.
A full set of lyrics is almost always longer than the cap, so always follow
the `keep_id` — otherwise you silently save half a song.
4. **agy can fail and still look like a success.** A quota-exhausted instance
returns prose like `WHY: agy-ask failed (rc=1)` inside a `STATUS: ok`
envelope. One such line even carried a `[05:37.76]` stamp and parsed as a
perfectly good synced lyric. `FAILED` in the script rejects those; keep it.
## It is not deterministic — that is the main gotcha
The same question can come back synced, plain, or empty on consecutive calls.
Observed in one sitting on "Jesus At The Centre": 39 timed lines, then 43
untimed, then nothing. So the script asks up to `--tries` times and keeps the
**best** answer (`score()`: any timed lines beats none, then more lines beats
fewer), stopping early once a timed answer arrives.
If a song saves untimed and you believe a timed version exists, just run it
again with `--overwrite`.
## What it filters out, and why
agy streams its own progress into the answer. Everything below is dropped
before parsing, and every pattern is there because it once ended up saved as a
lyric line:
- `STATUS:` / `SUMMARY:` / `MODEL:` / `INSTANCE:` / `AGY-META:` / `WHY:` envelopes
- `Waiting for task execution…`, `Background task <uuid> completed with…`
- section labels that are not sung (`Verse 1`, `[Chorus]`, `x2`)
- anything over 200 characters (a paragraph of commentary, not a sung line)
After filtering, an answer shorter than `--min-lines` (6) is rejected outright.
## Reviewing before you trust it
agy derives timings, so check them once per song before relying on them in a
service:
- The last timestamp should land near the song's length (a 384 s song ending at
367 s is right; one ending at 120 s means it only got a verse).
- Timestamps must increase monotonically.
- Open `/admin?v=<id>`, press play and watch the highlighted line track the
vocal. Fix drift with **Shift all**, or retime individual lines with **Set** /
**Tap mode**.
Untimed results are fine — the app shows them as a plain scrolling list, and
Tap mode turns them into synced lyrics in one pass of the song.
## Provenance tags
Written into `data.tags` so a later run can tell where lyrics came from:
| Tag | Meaning |
|---|---|
| `from the web via agy (synced)` | agy, with timings |
| `from the web via agy (untimed) — check and Tap-sync` | agy, words only |
| `from a file (<name>) (synced\|untimed)` | `--from-file` |
## Right words + real timings: `retime_lyrics.py`
The two sources fail in opposite ways — the web (LRCLIB plain, agy) has the
right words and line breaks but no timings; Whisper has a time for every line
but mishears words and breaks lines mid-phrase ("To show for the / years").
Rather than re-rolling agy for a timed answer that may never come, align them:
```bash
# correct words in a file (LRCLIB plain text, agy output, or pasted lyrics)
python3 scripts/lyrics/retime_lyrics.py --id MU5dlCRTLY8 --words correct.txt
python3 scripts/lyrics/retime_lyrics.py --id MU5dlCRTLY8 --words correct.txt --apply
# take timings from a backup rather than what is live
… --id ID --words w.txt --times-from ytplayer-lyrics-backup-….json
```
It matches on a **word stream, not line to line**, precisely because the line
breaks disagree: each transcript line's words are spread across the gap to the
next line, `difflib` aligns the two word sequences, and a correct line takes the
time of the earliest transcript word inside it. Times are forced monotonic, and
lines that matched nothing are interpolated between their neighbours. On "Take
Me to the End": 46 correct lines, 44 timed directly, 2 interpolated — and the
anchors came out identical to Whisper's own line times.
Check the report before `--apply`: it warns when the last line lands past the
end of the song, which means the alignment slipped.
## When a song has NO lyrics, check LRCLIB again first
`lyrics-regenerate` only revisits songs that already have lyrics, and the
lyrics-worker transcribes anything with none — so a song can end up with a
Whisper transcript even though LRCLIB had the real words all along. That is
exactly what happened to "Take Me to the End". Before reaching for agy on a
freshly transcribed song, search LRCLIB by hand; if it has the words, the
`retime_lyrics.py` route above beats everything else.
Related: `lyrics-lookup` (LRCLIB first, then this), `lyrics-regenerate`
(replace wrong lyrics from LRCLIB), `deploy-prod`.

View File

@@ -0,0 +1,93 @@
---
name: lyrics-lookup
description: Find and inject lyrics for songs saved on worship.hesed.sbs that have none — LRCLIB first (free, often synced), then an agy web search (untimed), then local faster-whisper transcription. Use when the user asks to add/fill/inject lyrics, says a song has no lyrics, or asks to transcribe saved songs. For replacing lyrics that are already there but wrong, use lyrics-regenerate instead.
---
# Add lyrics to songs that don't have any
Shared lyrics live on the server (`video_notes`, kind `lyrics`) and every user of
worship.hesed.sbs sees the same ones. Every save keeps the previous version as a
revision (`video_note_revs`), so nothing is destroyed — but **never overwrite
existing lyrics from this skill**; that is `lyrics-regenerate`'s job, and it takes
a backup first.
## Sources, cheapest and best first
| Order | Source | Timed? | Cost | Where |
|---|---|---|---|---|
| 1 | **LRCLIB** | usually synced | free, no key | server-side: `POST /api/notes/<id>/lyrics/web` |
| 2 | **agy web search** (Genius/AZLyrics/hymnary…) | no — untimed | flat-rate agy | `web_lyrics.py --agy` |
| 3 | **faster-whisper** on this machine | synced (word timings) | free, ~0.65× real time | `auto_lyrics.py` |
Never reach for ElevenLabs Scribe or any credit-billed ASR — the user asked for
free transcription only.
## Credentials
Writing needs admin. Either env var works for every script:
```bash
export YTP_ADMIN_PASSWORD='…' # the /admin password, see the ytplayer-admin-password memory
export YTP_TOKEN='ytp_…' # or an API token minted at /admin
```
The password is also vault secret `YTPLAYER_ADMIN_PASSWORD`
(`~/development/.secrets/ytplayer-admin.env`) — use it through
`vault__secret_exec` when you must not print it.
## Run it
```bash
cd ~/development/personal/ytplayer
# 1) LRCLIB for everything that has no lyrics, then agy for the leftovers
YTP_ADMIN_PASSWORD=… python3 scripts/lyrics/web_lyrics.py --missing --agy
# just look, change nothing
YTP_ADMIN_PASSWORD=… python3 scripts/lyrics/web_lyrics.py --missing --dry-run
# 2) transcribe what the web doesn't have (needs the venv below)
YTP_ADMIN_PASSWORD=… ~/.local/share/lyrics-asr/.venv/bin/python \
scripts/lyrics/auto_lyrics.py --missing
```
`--missing` lists songs from `GET /api/admin/media` and keeps only the ones with
`lyricsLines == 0`. Use `--ids A,B,C` to aim at specific videos. Ids are YouTube
ids (11 chars) or uploads (`upl_<12 hex>`).
Whisper venv, once:
```bash
uv venv ~/.local/share/lyrics-asr/.venv --python 3.12
~/.local/share/lyrics-asr/.venv/bin/pip install -r scripts/lyrics/requirements.txt
```
The same transcriber also runs unattended as the `lyrics-worker` container in
`docker-compose.yml` (`auto_lyrics.py --watch 300 --state …`), which is what gives
newly downloaded songs lyrics "at their own pace". It authenticates with
`LYRICS_WORKER_TOKEN`.
## What lands in the database
```jsonc
{ "lines": [{ "t": 12.4, "text": "Holy You are", "kind": "line" }], // t null = untimed
"tags": ["from LRCLIB (synced)"], // provenance — always tag
"offset": 0 }
```
Tags in use: `from LRCLIB (synced)` / `(plain text)`, `from the web (untimed) — check and Tap-sync`,
`auto-transcribed`, `from the file (synced)` (embedded in an admin upload).
The tag is how later runs tell machine lyrics from published ones — keep it accurate.
## Things that bite
- **LRCLIB 503/429** on bursts. `lrclib_regen.py:http_json` already retries with
backoff; if you write new code against LRCLIB, copy it. Keep ~0.4 s between calls.
- **Wrong-artist matches.** A common title ("Still") matches another genre's song.
`artist_ok()` in `lrclib_regen.py` is the verification — port it rather than
trusting a title+duration hit.
- **Karaoke / minus-one tracks have no vocals.** Whisper returns noise; the script
calls them instrumental below `--min-words 25` and skips them. That's correct.
- **Untimed lyrics are fine.** The app shows them as a plain scrolling list and the
user can Tap-sync them in the admin lyric editor.
- **Never redistribute.** These are third-party lyrics in a private library.

View File

@@ -0,0 +1,98 @@
---
name: lyrics-regenerate
description: Back up and replace lyrics on worship.hesed.sbs that are wrong, mistimed or misheard — typically machine transcripts — with published lyrics from LRCLIB. Use when the user says lyrics are incorrect/off/mistimed, names songs whose lyrics are bad, or asks to re-check songs on LRCLIB. Always backs up first and never writes an unverified artist match.
---
# Replace bad lyrics from LRCLIB
Machine transcripts (Whisper, Scribe) mishear words and drift out of time.
LRCLIB's published lyrics are usually correct and often **synced**. This skill
swaps them in — backup first, artist verified, one song at a time.
Script: `scripts/lyrics/lrclib_regen.py`.
## The rule: back up before you touch anything
The server keeps every previous version as a revision, and `/admin` can restore
one, but the script **also** writes an offline JSON backup of the current lyrics
of every song it will consider — on a dry run too. Do not skip it, do not write
your own one-off loop that lacks it.
```
/mnt/c/Users/josh/Documents/ytplayer-lyrics-backup-<YYYYmmdd-HHMMSS>.json
```
(`--backup-dir` or `YTP_BACKUP_DIR` to move it; on the devbox it falls back to `~/`.)
## Run it
```bash
cd ~/development/personal/ytplayer
export YTP_ADMIN_PASSWORD='…' # or YTP_TOKEN=ytp_…
# 1) ALWAYS dry-run first and read every line of the output
python3 scripts/lyrics/lrclib_regen.py --tagged auto-transcribed
# 2) apply once the matches look right
python3 scripts/lyrics/lrclib_regen.py --tagged auto-transcribed --apply
```
Picking the songs:
| Flag | Picks |
|---|---|
| `--ids A,B,C` | exactly those videos |
| `--tagged auto-transcribed` | songs whose lyrics carry that tag (machine transcripts) |
| `--since '2026-09-19 01:45' --until '2026-09-19 02:00'` | songs whose lyrics were **saved** in that window |
| *(none)* | every song the server has lyrics for |
`--since/--until` is the one to reach for when the user says *"the songs that got
lyrics at the same time as X"* — read X's `updatedAt` from
`GET /api/notes/<id>` and bracket it by a few minutes.
Other flags: `--tolerance 6` (max duration difference, seconds), `--loose`
(accept matches whose artist doesn't line up — risky, see below).
## Reading the output
```
eJBlOV6cM7Y LRCLIB synced | Israel Houghton – Holy You Are | 41 lines (was 38)
_n6dfB2Z-Ko UNSURE plain | Night Ranger – Still | 52 lines (was 44)
↳ artist doesn't match "Hillsong Worship" / the video title — left alone (use --loose to accept)
tYM05iaVu3I no match | Jesus At The Centre | … | keeping 60 lines (auto-transcribed)
```
- **LRCLIB** — verified match, will be written on `--apply`.
- **UNSURE** — title and duration fit but the artist doesn't appear in the channel
name or the video title. **Left alone by default. Do not pass `--loose` to make
it go away** — check the song by hand instead; this guard is what stopped a
Hillsong song being overwritten with a Night Ranger one.
- **no match** — LRCLIB doesn't have it. Existing lyrics are kept. Fall back to
`web_lyrics.py --agy --ids <id> --overwrite`, or fix it in the admin lyric editor.
Replaced songs are tagged `from LRCLIB (synced)` / `(plain text)`, which is also
how you tell later what has already been fixed.
## Restoring
- Per song, in the UI: `/admin` → recent edits → **Restore** on the older revision.
- From the JSON backup: `PUT /api/notes/<id>/lyrics` with
`{"data": <songs[id].data>, "baseRev": <current rev from GET /api/notes/<id>>}`.
Use the *current* rev, not the backed-up one — `baseRev` is optimistic
concurrency, not a version to travel back to.
## Gotchas
- **LRCLIB rate-limits**: 503/429 on bursts. `http_json()` retries with backoff and
the loop sleeps 0.4 s between songs. A song that fails all retries is reported and
skipped — re-run it later rather than hammering.
- **Duration match is ±6 s** against `/api/streams` metadata. Live or extended cuts
legitimately miss; raise `--tolerance` deliberately, per song.
- **Title cleaning** strips "(Official Video)", "Lyrics", "[HD]" etc.
`clean_title`'s `NOISE` regex is used with `.sub()` and `.search()` — never give
it a `/g`-style shared match state; a stateful regex silently skipped every other
song once already.
- **Karaoke/minus-one** versions match the original recording's lyrics, which is
usually what you want, but the timing won't line up. Check before applying.
Related skills: `lyrics-lookup` (songs with **no** lyrics), `deploy-prod`.

View File

@@ -0,0 +1,149 @@
---
name: mobile-app-ui-design
description: Design high-quality mobile app UI/UX screens, flows, and components. Use this skill whenever the user asks to design a mobile app screen, create app mockups, build mobile UI components, improve an existing mobile app design, create onboarding flows, design mobile navigation, or requests any mobile-first interface work. Also trigger when the user mentions app design, mobile UI, mobile UX, screen design, app mockups, wireframes, or wants to build React Native / Flutter / SwiftUI style interfaces as visual prototypes. Even if the user just says "design an app" or "make this screen look better", use this skill.
---
# Mobile App UI/UX Design Skill
This skill guides the creation of professional, polished mobile app interfaces that follow proven design principles used by top-tier apps like Airbnb, Duolingo, Spotify, Revolut, and Phantom.
## Core Philosophy
Great mobile UI isn't about flashiness — it's about intentionality. Every pixel, every spacing value, every color choice should serve the user. The goal is to create interfaces that feel smooth, personal, and alive — not just functional.
Before designing anything, understand three things:
1. **What is the user trying to accomplish?** (reduce friction to that goal)
2. **How should this make the user feel?** (trust, delight, confidence, calm)
3. **What's the one thing they should notice first?** (visual hierarchy)
## Design Process
Follow this sequence for any mobile screen:
### Step 1: Understand the Context
- What type of app? (fitness, finance, social, productivity, health, crypto, etc.)
- Who is the user? (new, returning, power user — adapt the experience)
- What's the primary action on this screen?
- What industry design conventions apply? (See `references/industry-conventions.md`)
### Step 2: Structure First (UX Lens)
- Map the user flow: what screen comes before and after?
- Identify the MVP elements — only what's essential for this screen
- Place primary actions in the **thumb zone** (bottom 1/3 of screen)
- Follow the **F-pattern** reading order for content layout
- Reduce interaction cost: expose content directly instead of hiding behind taps
- Turn empty states into opportunities with guidance, illustration, and a CTA
- Choose the right input method: sliders/scroll wheels for one-time setup, text fields for repeated/precise entry
### Step 3: Apply Visual Design (UI Lens)
Follow these rules in order:
#### Typography
- Use **one font family** (two max, with clear hierarchy purpose)
- Maximum **4 font sizes** and **2 font weights**
- Use monospace variants for large numbers (prices, stats, metrics)
- Keep text containers under 600px wide for readability
- Create hierarchy with size, weight, and opacity — not just bold everything
#### Color System (60/30/10 Rule)
- **60%** — neutral base (white, light gray, or dark background)
- **30%** — complementary color (black text, dark elements)
- **10%** — brand/accent color (CTAs, key indicators, icons)
- Use **opacity variations** of the neutral color for text hierarchy: 100% for headings, 80% for body, 60-70% for secondary text
- Use the accent color at 5% opacity for secondary buttons and subtle card highlights
- Match shadow colors to the background (tint shadows, never pure gray/black on colored backgrounds)
- Save strong colors (like red) for meaningful moments — overuse kills hierarchy
#### Spacing (8-Point Grid System)
- All spacing values must be divisible by **8 or 4** (8, 12, 16, 24, 32, 48, 64, 80, 96)
- Use **relationship-based spacing**: related elements closer together, unrelated further apart
- Multiplier rule: if related text elements are 16px apart, the gap to the next group should be 2× (32px)
- Section vertical padding: at least 80-96px (160px for major sections on larger screens)
- Card internal padding: 24-32px baseline
- Larger text = larger spacing needed
#### Shadows
- Always use **soft shadows** — never harsh/distinct
- Match shadow color to the background with a tinted hue
- Use subtle white inner shadows on buttons to add dimension
- Add faded drop shadows for depth without heaviness
#### Visual Cues & Imagery
- Use icons, emojis, illustrations, and images to make information digestible
- User avatars/photos > initials > generic icons (for representing people)
- Color-coded categories with soft solid backgrounds + clean isolated images
- Keep visual style consistent across the entire app — no random stock photo mix
- Use AI-generated or curated visuals with matching color palettes
### Step 4: Design for Emotion (Peak-End Rule)
The user will remember two moments: the **peak** (most intense) and the **end** (last impression).
- **Identify your peak moment**: completing a core task, hitting a milestone, finding what they want
- **Design the peak**: micro-animations, celebratory feedback, sparkles, badges, encouraging copy
- **Design the ending**: summary card, progress affirmation, gentle nudge to return
- Add **emotional feedback loops**: success states should feel rewarding (bounce, glow, sparkle)
- Celebrate small wins — success states don't need to be huge, but they should feel intentional
- Use motion and animation as trust signals, especially in high-stakes domains (finance, crypto, health)
### Step 5: Polish & Details
- Add subtle glow effects behind key elements (blur + opacity)
- Use tiny white inner shadows on primary buttons
- Add 5% opacity primary-color borders on secondary elements
- Consider micro-animations for state changes
- Ensure all tap targets are at least 44×44pt
- Check contrast ratios for accessibility
- Design error states, empty states, loading states, and success states
## Smart Patterns to Apply
### Personalization by User Stage
- **New users**: simple welcome, guided setup, minimal options
- **Returning users**: personalized content, routine-focused, progress indicators
- **Power users**: advanced stats, optimization tools, dense information
### Smarter Search
Never show a blank search screen. Include:
- Recent searches
- Popular/trending items
- Personalized recommendations
### Order/Status Tracking
- Open with a confident status message
- Humanize with photos, names, quick-action buttons
- Use visual timelines instead of text-based date lists
### Category Screens
- Use color-coded cards with soft backgrounds and clean isolated images
- Ensure visual consistency across all category items
- Create rhythm in the layout for effortless scanning
### Selection Over Manual Input
- Offer tappable selections for common options (job titles, preferences, etc.)
- Include icons/emojis alongside options for personality
- Provide an "Other" option with manual input as fallback
## Anti-Patterns to Avoid
- Overusing flashy gradients and blur effects (unless you can truly pull it off)
- More than 4 font sizes or 3 font weights
- Random spacing values (use the 8-point grid!)
- Hiding key content behind banners or extra taps
- Placing CTAs outside the thumb zone
- Generic empty states with no guidance
- Using sliders for frequent/precise data entry
- Making all information the same visual weight (no hierarchy)
- Emphasizing labels over values (e.g., making "Sales" bigger than "591")
- Pure gray/black shadows on colored backgrounds
## Implementation Notes
When building these designs as React artifacts or HTML:
- Use Tailwind CSS utility classes for spacing, colors, and typography
- Import Lucide React for clean, consistent iconography
- Use Recharts for any data visualization
- Apply CSS transitions for micro-interactions and state changes
- Use CSS variables for the color system
- Mobile-first: design for 375px width (iPhone SE) as baseline
- Use `rounded-2xl` or `rounded-3xl` for modern card aesthetics
- Apply `backdrop-blur` for glassmorphism effects where appropriate
For deeper guidance on industry-specific conventions and emotional design patterns, read `references/industry-conventions.md`.

1
.claude/skills/deploy-prod Symbolic link
View File

@@ -0,0 +1 @@
../../.agents/skills/deploy-prod

1
.claude/skills/lyrics-agy Symbolic link
View File

@@ -0,0 +1 @@
../../.agents/skills/lyrics-agy

View File

@@ -0,0 +1 @@
../../.agents/skills/lyrics-lookup

View File

@@ -0,0 +1 @@
../../.agents/skills/lyrics-regenerate

View File

@@ -0,0 +1 @@
../../.agents/skills/mobile-app-ui-design

View File

@@ -0,0 +1,71 @@
---
name: plan-queue
description: Author detailed, weak-model-executable plan files into the current repo's plans/ queue (plans/queue|active|done|failed + INDEX.md). The strong model does ALL exploration and thinking up front so a cheap executor can later apply the plan with zero codebase discovery. Use when the user says "/plan-queue <task>", "queue a plan for X", "add X to the plan queue", "plan this for the weak model". Companion skill: run-queue executes the queue. Manually-triggered only.
---
# plan-queue
Turn a task description into a **self-contained plan file** in the repo's
`plans/queue/`, detailed enough that a weak/cheap model can execute it without
exploring the codebase. Multiple tasks in one invocation → one plan file each.
## Layout (create on first use in a repo)
```
plans/
INDEX.md # ordered table of all plans
queue/ # not started
active/ # currently executing (max 1)
done/
failed/
```
`INDEX.md` starts as:
```markdown
# Plan Queue Index
| Seq | ID | Title | Status | Commit | Notes |
|-----|----|-------|--------|--------|-------|
```
## Procedure
1. **Scaffold**: if `plans/INDEX.md` doesn't exist, create the layout above
(`.gitkeep` in the four dirs so git tracks them).
2. **Explore deeply** (strong-model work): read every file the change touches,
find existing utilities to reuse, note exact paths, line anchors, and
signatures. The goal: the executor must need **zero** exploration.
3. **Name the plan**: next `NNN` = highest seq across all four dirs + 1
(zero-padded 3 digits). `HASH` = first 6 chars of
`sha1(title + timestamp)`. Filename: `NNN-<kebab-slug>-<HASH>.md` in
`plans/queue/`.
4. **Write the plan** following `plan-template.md` in this skill directory.
Every section is mandatory. Be near-diff-level specific in Steps for
anything non-trivial; paste real code snippets into Context.
5. **Index**: append a row to `INDEX.md` (`Status: queued`, Commit blank).
6. **Commit** the new plan file(s) + INDEX.md: `plan: add NNN-<slug>`.
Do NOT push. Never add AI attribution to the commit.
## Rules for plan quality (this is the whole point)
- **Front-load context.** Paste the actual current code of the region being
changed into the plan. The executor should never have to grep.
- **Steps are mechanical.** "Edit `src/auth.ts:42`: change X to Y" — not
"improve the auth flow".
- **Guardrails.** Always fill "Out of scope / do NOT touch" — weak models
drift without it.
- **Verification is copy-pasteable.** Exact commands + expected output.
- **Independence.** Each plan must leave the repo working (buildable/tests
green) on its own, since it gets its own commit. If a task can't, split it
differently or use `depends_on`.
- `depends_on:` in frontmatter lists plan IDs (the NNN-slug-hash basename)
that must be in `done/` first. Use it so many plans can be queued without
conflict.
## Conflict avoidance when queueing many plans
When authoring several plans in one batch, keep their file footprints
disjoint where possible; where they must overlap, chain them with
`depends_on` and write the later plan against the code **as it will be after
the earlier plan** (say so explicitly in its Context section).

View File

@@ -0,0 +1,59 @@
---
id: NNN-slug-hash # matches filename (without .md)
title: Short imperative title
created: YYYY-MM-DD
depends_on: [] # e.g. [001-add-user-model-a3f9c2]
est_files: 2 # rough count of files the executor will touch
---
# NNN — Title
## Objective
One paragraph: what "done" looks like, in behavioral terms.
## Context the executor must NOT rediscover
Everything a weak model needs so it never explores:
- Exact file paths with line anchors (`src/foo.ts:120-145`) and what's there.
- Signatures of functions/utilities to REUSE (with their paths).
- Pasted snippets of the current code around each edit site.
- Any project conventions that apply (naming, error handling, test style).
```lang
// paste the relevant current code here
```
## Steps
1. Edit `path/to/file.ext` — concrete, mechanical instruction. For tricky
edits, show the exact before/after or a unified diff.
2. Create `path/to/new-file.ext` with: (full contents or precise spec).
3. ...
## Out of scope / do NOT touch
- Files/behaviors the executor must leave alone.
- Refactors NOT to attempt, even if tempting.
## Verification
Run exactly:
```bash
<build/test/lint commands>
```
Expected: <what passing looks like, specific output to check>.
## Report format (executor: follow exactly)
Output ONLY the following, no other prose:
1. `git diff` (unified) of all changes.
2. Raw output of the Verification commands.
3. `Findings:` — max 10 lines: surprises, deviations from the steps, anything
skipped and why.
Do not commit. Do not push. Do not touch files outside the Steps.

View File

@@ -0,0 +1,17 @@
#!/usr/bin/env bash
# sync-to-repos.sh — copy the canonical plan-queue + run-queue skills from
# ~/.claude/skills/ into .claude/skills/ of every git repo under
# ~/development/personal/. Re-run after editing the skills to prevent drift.
set -euo pipefail
SRC="$HOME/.claude/skills"
BASE="$HOME/development/personal"
for gitdir in "$BASE"/*/.git; do
repo="$(dirname "$gitdir")"
dest="$repo/.claude/skills"
mkdir -p "$dest"
rm -rf "$dest/plan-queue" "$dest/run-queue"
cp -r "$SRC/plan-queue" "$SRC/run-queue" "$dest/"
echo "synced: $repo"
done

View File

@@ -0,0 +1,93 @@
---
name: run-queue
description: Execute the repo's plan queue (plans/queue/) sequentially - dispatch each plan to a cheap executor (claude-custom gateway via delegate.sh by default, or an in-session haiku Agent), review the returned diff + findings, verify, fix if needed, commit per plan, and push to all remotes only when the entire queue is done and verified. Resumable after token exhaustion or crashes via plans/active/. Use when the user says "/run-queue", "run the plan queue", "execute the queued plans". Companion skill: plan-queue authors the plans. Manually-triggered only.
---
# run-queue
Sequentially execute every plan in `plans/queue/` (authored by `plan-queue`).
The strong model (you) orchestrates and reviews; a weak model executes.
Token contract: you read only plan files, returned diffs/findings, and
verification output — never re-explore the repo yourself unless a fix round
requires it.
## Invocation
```
/run-queue [--executor gateway|agent] [--model TIER] [--max-fix N] [--dry-run]
```
Defaults: `--executor gateway --model haiku --max-fix 2`.
`--dry-run`: print the resolved execution order (respecting `depends_on`) and
exit without dispatching.
## Orchestration loop
### 0. Preconditions
- Repo has `plans/INDEX.md`; working tree is clean (if not, stop and ask —
never clobber uncommitted user work).
### 1. Resume check
If `plans/active/` contains a plan (previous run died / tokens exhausted):
- The plan-start commit is the checkpoint, so `git checkout -- . && git clean -fd`
(confirm nothing untracked is user work first) to reset any half-applied
edits, then re-dispatch that plan (step 3). This is always safe because
every plan starts from a clean committed state.
### 2. Pick next plan
- Lowest `NNN` in `plans/queue/` whose `depends_on` entries are ALL in
`plans/done/`. If a plan is blocked, skip to the next unblocked one; if
everything remaining is blocked, report and stop.
- `git mv plans/queue/<plan> plans/active/`, set its INDEX.md row to
`in-progress`, commit: `plan: start NNN-<slug>`. This commit is the resume
checkpoint.
### 3. Dispatch to the executor
Build the prompt with `run-plan.sh` (this skill dir):
- **gateway** (default): `~/.claude/skills/run-queue/run-plan.sh -d <repo-root> [-m TIER] plans/active/<plan>.md`
— wraps the plan in the executor preamble and calls
`~/.claude/skills/delegate-task/delegate.sh` (timeout 1800s, retries on).
- **agent**: `run-plan.sh -p plans/active/<plan>.md` prints the prompt only;
pass it to the Agent tool (`subagent_type: general-purpose`,
`model: haiku`, `run_in_background: false`, cwd = repo).
### 4. Review (strong model, diff-only)
Read ONLY the executor's report (diff + verification output + findings).
Then **run the plan's Verification commands yourself** — never trust the
executor's pasted output.
- **Pass** → step 5.
- **Fail** → up to `--max-fix` rounds:
- Small gap: fix it directly yourself (Edit tool).
- Larger miss: reset the tree (`git checkout -- . && git clean -fd`),
re-dispatch with a corrective addendum appended to the prompt
(`run-plan.sh -a "addendum text" ...`).
- **Exhausted fix rounds** → reset tree, append `## Failure notes` (what
failed, last error) to the plan file, `git mv` it to `plans/failed/`,
INDEX row → `failed`, commit `plan: fail NNN-<slug>`, continue with the
next plan that doesn't depend on it.
### 5. Complete the plan
- Append `## Execution log` to the plan file: executor+model, attempts,
fix rounds, the executor's Findings verbatim.
- `git mv plans/active/<plan> plans/done/`, INDEX row → `done` + commit hash
placeholder, then ONE commit containing code changes + plan move + INDEX:
message = the plan's title, plain human style. **Never** add
Co-Authored-By/AI attribution (global rule). Backfill the commit hash into
the INDEX row on the next commit or amend before creating it.
- Loop to step 2.
### 6. Ship gate (only when queue/ is empty)
- If `plans/failed/` is non-empty: report the failures, do NOT push. Done.
- Else: run the repo's full verification once more (union of the plans'
Verification commands, or the project's standard build/test), then push
every local branch's current state to **all** configured remotes
(`git remote` loop), ship-it style.
- **Webhook warning**: if the repo auto-deploys on push (e.g. BarangaySystem
via Gitea webhooks), say so before pushing and ask, unless the user already
told you to ship in this conversation.
## Reporting
End with: plans completed/failed (titles), one-line finding per plan, commits
created, and whether the push happened.

View File

@@ -0,0 +1,67 @@
#!/usr/bin/env bash
# run-plan.sh — dispatch one plan-queue plan file to a cheap executor.
#
# Usage:
# run-plan.sh [-d REPO_DIR] [-m TIER] [-t SECS] [-a "addendum"] [-p] plans/active/NNN-slug-hash.md
#
# -d DIR repo root the executor works in (default: cwd)
# -m TIER model tier alias for delegate.sh (default: haiku)
# -t SECS timeout (default: 1800)
# -a TEXT corrective addendum appended to the prompt (fix rounds)
# -p print the built prompt to stdout and exit (for Agent-tool mode)
set -euo pipefail
DIR="$(pwd)"
MODEL="haiku"
TIMEOUT=1800
ADDENDUM=""
PRINT_ONLY=0
while getopts "d:m:t:a:p" opt; do
case "$opt" in
d) DIR="$OPTARG" ;;
m) MODEL="$OPTARG" ;;
t) TIMEOUT="$OPTARG" ;;
a) ADDENDUM="$OPTARG" ;;
p) PRINT_ONLY=1 ;;
*) exit 2 ;;
esac
done
shift $((OPTIND - 1))
PLAN="${1:?usage: run-plan.sh [opts] <plan-file>}"
[ -f "$PLAN" ] || { echo "plan file not found: $PLAN" >&2; exit 1; }
PROMPT_FILE="$(mktemp)"
trap 'rm -f "$PROMPT_FILE"' EXIT
{
cat <<'PREAMBLE'
You are a plan EXECUTOR. Apply the plan below exactly.
Rules:
- Follow the Steps in order. Do not explore beyond the files the plan names.
- Do not refactor, rename, or "improve" anything outside the Steps.
- Respect the "Out of scope / do NOT touch" section absolutely.
- Run the Verification commands after making the changes.
- Do NOT commit, do NOT push, do NOT create branches.
- Your final output must be ONLY, in this order:
1. The full `git diff` (unified) of your changes.
2. The raw output of the Verification commands.
3. `Findings:` followed by at most 10 lines (surprises, deviations, skips).
No other prose, no explanations, no step-by-step narration.
=== PLAN ===
PREAMBLE
cat "$PLAN"
if [ -n "$ADDENDUM" ]; then
printf '\n=== CORRECTION (a previous attempt failed — apply this too) ===\n%s\n' "$ADDENDUM"
fi
} > "$PROMPT_FILE"
if [ "$PRINT_ONLY" -eq 1 ]; then
cat "$PROMPT_FILE"
exit 0
fi
exec "$HOME/.claude/skills/delegate-task/delegate.sh" \
-m "$MODEL" -d "$DIR" -t "$TIMEOUT" -f "$PROMPT_FILE"

26
.gitignore vendored Normal file → Executable file
View File

@@ -24,3 +24,29 @@ node_modules/
# local data # local data
*.tmp *.tmp
.DS_Store .DS_Store
# runtime/local artifacts
server/data/
test-results/
.impeccable/review/
.claude/worktrees/
server/public
# Old Tauri/Windows desktop build outputs — published artifacts, not source.
# They are still in git history; keeping them out of the tip keeps deploy clones small.
legacy/releases/
# python caches from scripts/lyrics
__pycache__/
plans/codex-shots*/
plans/codex-report*.md
# performance harness artifacts and temp files
perf/fixtures/
perf/.tmp/
# UI regression screenshots and local measurements
plans/ui-shots/
# Transport regression screenshots
plans/transport-shots/

27
.impeccable/config.json Normal file
View File

@@ -0,0 +1,27 @@
{
"buildPath": "code",
"detector": {
"ignoreRules": [],
"ignoreFiles": [],
"ignoreValues": [
{
"rule": "broken-image",
"value": "*",
"files": [
"frontend/index.html"
],
"createdAt": "2026-10-02T23:14:10.804Z",
"reason": "Agent verified all three matching images are hidden dynamic artwork targets (artImg, serviceArt, rvThumb); app.js assigns their src when media metadata is available."
},
{
"rule": "layout-transition",
"value": "*",
"files": [
"frontend/theme-f7.css"
],
"createdAt": "2026-10-05T18:33:43.625Z",
"reason": "Framework7 swipeout reveal retains its existing width transition for the action area"
}
]
}
}

View File

@@ -0,0 +1,69 @@
---
target_identity: "file:/home/josh/development/personal/ytplayer/frontend/index.html"
target_fingerprint: "sha256:5f16cc1d66caa47d5d1ae35afe92b5206825e66772d974d72fd90effac161d27"
target_path: /home/josh/development/personal/ytplayer/frontend/index.html
timestamp: 2026-10-05T20-14-49Z
slug: frontend-index-html
---
Method: dual-agent (A: /root/critique_design · B: /root/critique_evidence)
# Design Health Score
| # | Heuristic | Score | Key issue |
|---|---|---:|---|
| 1 | Visibility of System Status | 3/4 | Active tab and playback state are clear; row actions depend on an undisclosed swipe. |
| 2 | Match System / Real World | 3/4 | Grouped lists, bottom tabs and sheet use familiar iOS patterns. |
| 3 | User Control and Freedom | 3/4 | Player and sheets can be collapsed or closed; long swipe removal remains a high consequence gesture. |
| 4 | Consistency and Standards | 3/4 | F7 components now share the same token-based visual treatment; some underlying CSS layers overlap. |
| 5 | Error Prevention | 2/4 | Long-left removes a row without a confirmation step. |
| 6 | Recognition Rather Than Recall | 2/4 | Swipe row actions are not apparent before discovery. |
| 7 | Flexibility and Efficiency | 3/4 | Gestures and bottom tabs offer quick navigation for touch users. |
| 8 | Aesthetic and Minimalist Design | 3/4 | Light, dark and contrast treatments stay restrained; row actions can obscure content while open. |
| 9 | Error Recovery | 2/4 | No explicit undo is provided for a swipe removal. |
| 10 | Help and Documentation | 1/4 | Only the mini-player has a visual gesture affordance; row and tab gestures lack a persistent hint. |
| **Total** | | **25/40** | **Acceptable; interaction discovery is the main gap.** |
# Design Specificity Verdict
**LLM assessment:** The F7 layout now reads as a media player: native line icons, an inset media list, accent-led controls, glass navigation and a sheet for Up Next. The large title hierarchy and player/list relationship fit the product. It is no longer just the mini-player that changes. The remaining weakest point is that row actions and tab movement rely on gesture knowledge users may not have.
**Deterministic scan:** The scoped Impeccable detector scan across `frontend/index.html`, `frontend/app.js`, `frontend/f7-layout.js`, `frontend/fullscreen-orientation.css`, `frontend/fullscreen-orientation.js` and `frontend/theme-f7.css` reported 129 findings: 60 warnings and 69 advisories. Categories: low contrast 22, design-system-radius 35, undersized-ui-text 22, design-system-font-size 20, thin-border/wide-shadow 10, dark-glow 4, design-system-color 4, clipped overflow 3, gradient text 2, layout transition 2, tiny text 2, marquee 2, pulsing dot 1. It found no issues in the two gesture/fullscreen logic modules. Most radius/type findings refer to the intended F7 control scale or circular/icon controls; many remaining findings point to shared prototype content and pre-existing theme variants in the large single HTML document. The contrast findings around bright accent fills and dim secondary text merit future contextual review, especially against the detector's assumed body-text size.
**Browser visualization:** The detector overlay could not be injected into the selected live page. The available browser inspection loaded the default Classic layout and returned `Unexpected token '<'` from API/script requests served as HTML, so no reliable user-visible overlay is available. Separate Playwright captures were made on the static frontend with the F7 layout enabled and inspected directly.
# Cognitive Load
The tab bar reduces destination recall to six visible choices. The list header, filter and grouped items scan predictably. Hidden row actions and swipe-to-change-tab are not discoverable from the screen itself; the small grabber only hints at mini-player movement and does not label what the movement does. No screen presents more than four primary decision points at once.
# Emotional Journey
Search and queue selection are direct, and the full-player sheet preserves the sense of continuity while browsing. Filling the screen with a real video makes fullscreen feel intentional. A long swipe that removes a row can create a negative surprise because the outcome is not previewed or recoverable.
# What's Working
- The F7 treatment now spans search, sidebar, home, list, settings, player, mini-player, tabs, sheets and auxiliary panels.
- Fill/Fit is explicit, persisted, and also toggles by center double-tap or multi-touch.
- The classic regression pair is pixel-identical at 390×844.
# Priority Issues
1. **[P2] Row gestures are hard to discover.** Users see an ellipsis, but do not know that left/right reveals Playlist, Remove and Queue. Add a one-time, dismissible hint or a small visible interaction cue. Suggested command: `/impeccable clarify`.
2. **[P2] Swipe removal has weak recovery.** A long left swipe removes immediately, with no Undo affordance. Give the toast a short Undo action or reduce the destructive gesture to a normal revealed button. Suggested command: `/impeccable harden`.
# Persona Red Flags
- **Jordan (First-Timer):** Can find Search and Queue from the bottom bar, but cannot infer that a song row can be swiped to add it to a playlist or remove it.
- **Alex (Power User):** Can move quickly through tabs and the mini-player, but a long-left removal has no quick undo if the wrong row is removed.
- **Morgan (Accessibility-focused listener):** Touch actions have generous targets, but gestures have no equivalent hint and depend on a screen reader user discovering the menu path.
# Minor Observations
- The critique found overlapping F7 declarations in `theme-f7.css`; current precedence is predictable but the file would be easier to maintain if these layers were consolidated.
- The queue/settings duplicate heading and the redundant settings list filter were fixed during this pass; Queue's Play action is now the filled primary action.
- The section rail remains usable as a compact floating control above the tab bar.
- The detector's font-size advisories in compact badges and section labels are intentional density choices; check any future increase in text scale against them.
# Questions to Consider
- Would a single dismissible swipe hint be enough, or should Queue/Playlist/Remove stay visible behind each row menu?
- Should long-left remove remain as a shortcut if the toast gains Undo, or should removal require tapping the revealed action?

328
.impeccable/design.json Normal file
View File

@@ -0,0 +1,328 @@
{
"schemaVersion": 2,
"generatedAt": "2026-10-02T21:37:12.817947+00:00",
"title": "Design System: YT Player — Classic",
"extensions": {
"colorMeta": {
"accent": {
"role": "primary",
"displayName": "Accent"
},
"accent-bright": {
"role": "primary",
"displayName": "Accent Bright"
},
"accent-deep": {
"role": "primary",
"displayName": "Accent Deep"
},
"bg": {
"role": "neutral",
"displayName": "Bg"
},
"bg-1": {
"role": "neutral",
"displayName": "Bg 1"
},
"bg-2": {
"role": "neutral",
"displayName": "Bg 2"
},
"bg-3": {
"role": "neutral",
"displayName": "Bg 3"
},
"line": {
"role": "neutral",
"displayName": "Line"
},
"line-soft": {
"role": "neutral",
"displayName": "Line Soft"
},
"text": {
"role": "neutral",
"displayName": "Text"
},
"text-2": {
"role": "neutral",
"displayName": "Text 2"
},
"text-dim": {
"role": "neutral",
"displayName": "Text Dim"
},
"on-primary": {
"role": "neutral",
"displayName": "On Primary"
},
"on-play": {
"role": "neutral",
"displayName": "On Play"
},
"light-bg": {
"role": "neutral",
"displayName": "Light Bg"
},
"light-bg-1": {
"role": "neutral",
"displayName": "Light Bg 1"
},
"light-bg-2": {
"role": "neutral",
"displayName": "Light Bg 2"
},
"light-bg-3": {
"role": "neutral",
"displayName": "Light Bg 3"
},
"light-line": {
"role": "neutral",
"displayName": "Light Line"
},
"light-line-soft": {
"role": "neutral",
"displayName": "Light Line Soft"
},
"light-text": {
"role": "neutral",
"displayName": "Light Text"
},
"light-text-2": {
"role": "neutral",
"displayName": "Light Text 2"
},
"light-text-dim": {
"role": "neutral",
"displayName": "Light Text Dim"
},
"light-accent": {
"role": "primary",
"displayName": "Light Accent"
},
"light-accent-bright": {
"role": "primary",
"displayName": "Light Accent Bright"
},
"light-accent-deep": {
"role": "primary",
"displayName": "Light Accent Deep"
},
"contrast-bg": {
"role": "neutral",
"displayName": "Contrast Bg"
},
"contrast-bg-2": {
"role": "neutral",
"displayName": "Contrast Bg 2"
},
"contrast-bg-3": {
"role": "neutral",
"displayName": "Contrast Bg 3"
},
"contrast-line": {
"role": "neutral",
"displayName": "Contrast Line"
},
"contrast-line-soft": {
"role": "neutral",
"displayName": "Contrast Line Soft"
},
"contrast-text-dim": {
"role": "neutral",
"displayName": "Contrast Text Dim"
},
"contrast-accent": {
"role": "primary",
"displayName": "Contrast Accent"
},
"contrast-accent-bright": {
"role": "primary",
"displayName": "Contrast Accent Bright"
}
},
"typographyMeta": {
"display": {
"displayName": "Display",
"purpose": "Empty-home heading."
},
"headline": {
"displayName": "Headline",
"purpose": "Now-playing media title."
},
"title": {
"displayName": "Title",
"purpose": "Browsing heading."
},
"body": {
"displayName": "Body",
"purpose": "Interface text."
},
"label": {
"displayName": "Label",
"purpose": "Suggestion chips."
},
"media-title": {
"displayName": "Media Title",
"purpose": "Browsing media titles."
},
"time": {
"displayName": "Time",
"purpose": "Tabular transport timestamps."
}
},
"shadows": [
{
"name": "dialog-dark",
"value": "0 18px 50px -12px rgba(0, 0, 0, 0.7)",
"purpose": "Inherited dialog and sheet elevation in dark mode."
},
{
"name": "dialog-light",
"value": "0 18px 50px -18px rgba(0, 0, 0, 0.25)",
"purpose": "Inherited dialog and sheet elevation in light mode."
},
{
"name": "playing-edge",
"value": "inset 2px 0 var(--accent)",
"purpose": "Selected media row indicator, not ambient elevation."
}
],
"motion": [
{
"name": "ease",
"value": "cubic-bezier(0.22, 1, 0.36, 1)",
"purpose": "Inherited interface easing."
},
{
"name": "color-state",
"value": "background 0.16s, color 0.16s",
"purpose": "Recurring inherited color state transition."
},
{
"name": "reduced-duration",
"value": "0.001ms",
"purpose": "Explicit preference and operating-system reduced motion."
}
],
"breakpoints": [
{
"name": "stacked-max",
"value": "1200px"
},
{
"name": "mobile-max",
"value": "860px"
},
{
"name": "xl-navigation-max",
"value": "420px"
},
{
"name": "narrow-thumbnail-max",
"value": "380px"
},
{
"name": "transport-wide-container-min",
"value": "620px"
},
{
"name": "transport-narrow-container-max",
"value": "300px"
}
]
},
"components": [
{
"name": "Filled action",
"kind": "button",
"refersTo": "button-primary",
"description": "Classic list action.",
"html": "<button class=\"ds-primary\">Play all</button>",
"css": ".ds-primary { background:var(--accent-deep,#c6442f);color:#fff;border:0;border-radius:8px;min-height:44px;padding:8px 12px;font:800 14px var(--ui,\"Hanken Grotesk\",system-ui,sans-serif);cursor:pointer;transition:background .16s,color .16s; }.ds-primary:focus-visible { outline:2px solid var(--accent,#f06b53);outline-offset:3px; }"
},
{
"name": "Search action",
"kind": "button",
"refersTo": "button-search",
"description": "Quiet search submission, accented on hover.",
"html": "<button class=\"ds-search\">Search</button>",
"css": ".ds-search { background:var(--bg-3,#2b2e33);color:var(--text,#f3f1ed);border:0;border-radius:8px;min-height:46px;padding:0 22px;font:600 14px var(--ui,\"Hanken Grotesk\",system-ui,sans-serif);cursor:pointer;transition:background .16s,color .16s; }.ds-search:hover { background:var(--accent-deep,#c6442f);color:#fff; }.ds-search:focus-visible { outline:2px solid var(--accent,#f06b53);outline-offset:3px; }"
},
{
"name": "Play control",
"kind": "button",
"refersTo": "button-play",
"description": "Circular primary transport.",
"html": "<button class=\"ds-play\" aria-label=\"Play\"><svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"m8 5 11 7-11 7z\" fill=\"currentColor\"/></svg></button>",
"css": ".ds-play { display:grid;place-items:center;width:64px;height:64px;border:0;border-radius:50%;background:var(--accent,#f06b53);color:#171719;cursor:pointer;transition:background .16s; }.ds-play:hover { background:var(--accent-bright,#ff947e); }.ds-play:focus-visible { outline:2px solid var(--accent,#f06b53);outline-offset:3px; }"
},
{
"name": "Search field",
"kind": "input",
"refersTo": "input-search",
"description": "Full-width media query field.",
"html": "<input class=\"ds-input\" aria-label=\"Search media\" placeholder=\"Search YouTube…\">",
"css": ".ds-input { background:var(--bg-1,#18191c);color:var(--text,#f3f1ed);border:1px solid var(--line,#42464d);border-radius:8px;min-height:46px;padding:11px 14px;font:16px var(--ui,\"Hanken Grotesk\",system-ui,sans-serif);caret-color:var(--accent,#f06b53);transition:border-color .2s,background .2s; }.ds-input::placeholder { color:var(--text-dim,#a1a5ac);opacity:1; }.ds-input:focus-visible { outline:2px solid var(--accent,#f06b53);outline-offset:3px; }"
},
{
"name": "Suggestion chip",
"kind": "chip",
"refersTo": "chip",
"description": "Media search suggestion.",
"html": "<button class=\"ds-chip\">Jazz</button>",
"css": ".ds-chip { min-height:44px;padding:10px 14px;background:var(--bg-2,#202226);border:1px solid var(--line-soft,#2b2e33);border-radius:8px;color:var(--text,#f3f1ed);font:500 14px var(--ui,\"Hanken Grotesk\",system-ui,sans-serif);cursor:pointer;transition:background .16s,border-color .16s; }.ds-chip:hover { border-color:var(--accent,#f06b53); }.ds-chip:focus-visible { outline:2px solid var(--accent,#f06b53);outline-offset:3px; }"
},
{
"name": "Active navigation",
"kind": "nav",
"refersTo": "nav-active",
"description": "Sidebar selection with stroked SVG.",
"html": "<button class=\"ds-nav\" aria-current=\"page\"><svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><circle cx=\"10.5\" cy=\"10.5\" r=\"6.5\"/><path d=\"m16 16 5 5\"/></svg>Search</button>",
"css": ".ds-nav { display:flex;align-items:center;gap:12px;min-height:44px;padding:10px 12px;border:0;border-radius:var(--radius-sm,8px);background:var(--bg-3,#2b2e33);color:var(--text,#f3f1ed);font:14px var(--ui,\"Hanken Grotesk\",system-ui,sans-serif);cursor:pointer;transition:color .18s,background .18s; }.ds-nav svg { fill:none;stroke:var(--accent,#f06b53);stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round; }.ds-nav:focus-visible { outline:2px solid var(--accent,#f06b53);outline-offset:3px; }"
},
{
"name": "Playing media row",
"kind": "card",
"refersTo": "media-row",
"description": "Divider-separated selected media without a raster fixture.",
"html": "<div class=\"ds-row\" tabindex=\"0\"><div class=\"ds-thumb\" aria-label=\"Media thumbnail area\"></div><div><div class=\"ds-title\">Media title</div><div class=\"ds-channel\">Channel</div></div><button class=\"ds-row-menu\" aria-label=\"Media actions\"><svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"5\" r=\"1.5\"/><circle cx=\"12\" cy=\"12\" r=\"1.5\"/><circle cx=\"12\" cy=\"19\" r=\"1.5\"/></svg></button></div>",
"css": ".ds-row { display:grid;grid-template-columns:88px minmax(0,1fr) 44px;gap:12px;padding:12px 8px;border-bottom:1px solid var(--line-soft,#2b2e33);background:var(--bg-3,#2b2e33);box-shadow:inset 2px 0 var(--accent,#f06b53);color:var(--text,#f3f1ed);font-family:var(--ui,\"Hanken Grotesk\",system-ui,sans-serif); }.ds-thumb { width:88px;aspect-ratio:16/9;border-radius:6px;background:var(--bg-2,#202226); }.ds-title { font-size:14px;font-weight:600;line-height:1.45; }.ds-channel { font-size:12px;color:var(--text-dim,#a1a5ac);margin-top:5px; }.ds-row-menu { min-width:44px;min-height:44px;background:transparent;color:var(--text,#f3f1ed);border:0;cursor:pointer; }.ds-row-menu svg { fill:currentColor; }.ds-row:focus-visible { outline:2px solid var(--accent,#f06b53);outline-offset:3px; }.ds-row-menu:focus-visible { outline:2px solid var(--accent,#f06b53);outline-offset:3px; }"
}
],
"narrative": {
"northStar": "Quiet Media Studio",
"overview": "Classic is a matte charcoal media workspace with warm white type and restrained vermilion. Watching and listening share the same visual priority; playback, browsing, and library controls remain legible together. This system applies only when the Classic layout is selected. Other theme families retain their own visual authority.\n\nThe implemented world uses tonal surfaces, fine dividers, bundled typography, and generous control targets. Light, high contrast, text scale, compact density, and reduced motion are supported appearance preferences. Source evidence is frontend/theme-classic.css, with inherited typography and preference values from frontend/styles.css and frontend/refresh.css; the approved direction lives in .impeccable/surfaces/frontend-theme-classic-css.md.",
"keyCharacteristics": [
"Matte tonal layers and fine dividers.",
"Restrained vermilion for playback, actions, and selection.",
"Bricolage headings, Hanken interface text, JetBrains timing.",
"Responsive workspace with persistent access to playback."
],
"rules": [
{
"name": "The Classic Scope Rule",
"body": "Apply these rules only to Classic; shared markup does not make them rules for other layout families.",
"section": "colors"
},
{
"name": "The Tonal Surface Rule",
"body": "Use surface tone and fine dividers for resting depth; reserve the inherited ambient shadow for dialogs and sheets.",
"section": "elevation"
}
],
"dos": [
"Do keep Classic overrides scoped to the selected Classic layout.",
"Do use tonal surfaces and fine dividers for workspace hierarchy.",
"Do preserve light, high contrast, text scale, density, safe areas, and reduced motion.",
"Do use inline SVG for navigation icons and retain visible keyboard focus.",
"Do use media thumbnails as user content."
],
"donts": [
"Don't add ambient glow or grain to Classic.",
"Don't force empty home into the video aspect ratio.",
"Don't hide row actions until hover or reduce established control targets to fit a crowded layout.",
"Don't transfer this visual world to other layout families."
]
}
}

View File

@@ -0,0 +1,26 @@
---
version: 1
slug: "frontend-theme-classic-css"
primary_target: "frontend/theme-classic.css"
related_targets: ["frontend/index.html","frontend/app.js"]
---
# Classic surface
Mode: Operate. Scope: Classic in the shared web frontend, mobile browser/PWA and desktop. Preserve features and all other layout themes. User approved code-first implementation of the full redesign plan.
## Direction contract
THESIS: A quiet media workspace gives watching and listening equal attention. Empty home is useful content, never content trapped in a video frame.
OWN-WORLD: Matte charcoal, warm white type, restrained vermilion, 12px corners, fine dividers. Bundled Hanken UI, Bricolage headings, JetBrains timing. No ambient glow or grain. Respect light and high-contrast preferences.
STORY: Search or choose a playlist, play, then browse without losing playback. Existing features and factual copy survive.
FIRST VIEWPORT: Desktop has a 232px library sidebar, flexible video/workspace and 340–420px browsing pane under search. Phones have search above content, centered transport under video, and existing navigation at the bottom. Empty home replaces the video proportions with a fully visible introduction or playlist collection.
FORM: User-pinned quiet studio workspace; concept seed 6fcc153a was run, but its assignment and catalog alternatives do not override the explicitly approved plan. Signature interaction: scrolling from playback into browsing reveals the existing mini-player above navigation; selecting it returns to playback without moving the document viewport.
FINISH: unreviewed and undocumented is unfinished; this build ends with the finish review, the verdict, DESIGN.md, and every shipping raster carrying its provenance
Constraints: no generated artwork needed; existing media thumbnails are user content. Existing untracked mockups remain untouched. No deployment.

73
BACKLOG.md Executable file
View File

@@ -0,0 +1,73 @@
# YT Player — Improvement Backlog
The `/loop` works through this top-to-bottom, **one item per iteration**. Tick an item
(`[x]`) only after it builds, verifies, and is committed + pushed. Add new ideas to the
bottom as they come up.
## Build & verify protocol (every iteration)
1. Edit the **canonical source** in WSL (`~/development/personal/ytplayer`).
2. Sync changed files **individually** into `C:\ytbuild\ytplayer` — never
`Copy-Item -Recurse` onto an existing dir (it nests as `frontend\frontend`).
3. `npx tauri build` in `C:\ytbuild\ytplayer`.
4. Launch with `--remote-debugging-port=922x` and verify via CDP/screenshot
(retry the launch a few times — Smart App Control is intermittent).
5. **Only if it builds and verifies:** refresh `releases/`, commit (no AI attribution),
`git push origin main`, then tick the item here.
## UX / polish
- [x] Empty-state designs for empty playlists and empty history (match the new hero).
- [x] Loading skeletons for search results instead of a bare "Searching…".
- [x] Keyboard-shortcut help overlay (press `?`), listing space / arrows / f / m.
- [x] Download/preload progress indicator on cards (percent or a bar, not just a pulse).
- [x] Remember and restore the last playback position per video.
- [x] Toast queue (stack multiple toasts instead of replacing).
## Features
- [x] Drag-to-reorder videos within a playlist.
- [x] "Up next" queue panel showing the autoplay queue.
- [x] Persistent mini now-playing bar when browsing other views.
- [x] Cache size cap in Settings (auto-evict oldest past a limit).
- [x] Export / import playlists as JSON.
- [x] More / trending quick-search chips on the hero, rotated.
- [x] Share a single playlist by link, imported additively (never replaces).
- [x] Bulk-import a YouTube playlist URL into a new playlist.
- [x] Per-playlist "available offline" status + a keep-offline pin.
- [x] Service mode: set-list view with a screen wake lock.
- [x] Per-song notes (key / capo / arrangement cues) on playlist entries.
## Robustness
- [ ] **Cookies jar for the YouTube bot gate (deferred 2026-08-27 — not being tackled yet).**
`runYtdlpResilient()` already recovers from "Sign in to confirm you're not a bot"
by retrying against `YTDLP_FALLBACK_CLIENTS`, so saves no longer fail. The residual
cost: while the gate is active, `tv_simply`/`android_vr`/`mweb` typically expose only
progressive itag 18, so those saves land at **360p instead of 720p** (`web_embedded`
keeps the full adaptive ladder when it works). Fix would be to supply a Netscape
cookies jar so the default client stays available: the server already honours
`YTDLP_COOKIES=<path>` when the file exists — what's missing is mounting the jar into
the container (compose volume + env) and a refresh story for when the cookies expire.
Only worth doing if 360p saves become noticeable in practice.
- [x] Sanitize `video_id` in `cache_download` (reject path separators).
- [x] Gate the embedded yt-dlp behind a build flag so debug builds compile faster.
- [x] Surface yt-dlp extraction failures with a retry button.
## Done
- [x] Empty-state designs for empty playlists and empty history (match the new hero). `460aaae`
- [x] Loading skeletons for search results instead of a bare "Searching…". `da2ad27`
- [x] Keyboard-shortcut help overlay (press `?`), listing space / arrows / f / m. `c676786`
- [x] Download/preload progress indicator on cards (percent or a bar, not just a pulse). `81aced9`
- [x] Remember and restore the last playback position per video. `ddfa149`
- [x] Toast queue (stack multiple toasts instead of replacing). `a4d6b82`
- [x] Drag-to-reorder videos within a playlist. `0ba0f56`
- [x] "Up next" queue panel showing the autoplay queue. `4376cd9`
- [x] Persistent mini now-playing bar when browsing other views. `c1855a1`
- [x] Cache size cap in Settings (auto-evict oldest past a limit). `d15d902`
- [x] Export / import playlists as JSON. `d15d902`
- [x] More / trending quick-search chips on the hero, rotated. `c6b8dfc`
- [x] Sanitize `video_id` in `cache_download` (reject path separators). `c6b8dfc`
- [x] Gate the embedded yt-dlp behind a build flag so debug builds compile faster. `d15d902`
- [x] Surface yt-dlp extraction failures with a retry button. `c6b8dfc`
- [x] Share a single playlist by link, imported additively. `27b28f7`
- [x] Bulk-import a YouTube playlist URL. `b868dab`
- [x] Per-playlist offline status + keep-offline pin. `c5f4751`
- [x] Service mode set-list view with screen wake lock. `14e1d8e`
- [x] Per-song notes on playlist entries. `8ef16a8`

564
CLAUDE.md Normal file
View File

@@ -0,0 +1,564 @@
# ytplayer — project facts for agents
## What this is
Ad-free YouTube player. Three shells share `frontend/`: **web PWA** (Bun + Hono in
`server/`, the production deployment), Tauri (Windows), zero-native (Linux/macOS).
The PWA is what runs in production; `legacy/` holds the old native-only docs.
## Repo map
| Path | What lives there |
|------|------------------|
| `frontend/app.js` | The entire UI (~3.6k lines, no framework): player, playlists, search, settings, sync |
| `frontend/sw.js` + `frontend/sw-update.js` | Service worker + update flow (FRAGILE — see below) |
| `frontend/opfs.js` / `opfs-worker.js` | OPFS offline audio cache |
| `frontend/fingerprint.js` | Browser fingerprint used as the sync key |
| `frontend/async-guard.js` | Stale-async-response guard (unit-tested) |
| `server/server.js` | Bun + Hono backend — endpoint list is in its header comment |
| `server/db.js` | libsql schema/queries (`users`, `profiles`, `video_history`, `media_cache`…) |
| `server/media-cache.js` | Server-side video cache: background fetch jobs, validation gate, x264 lane, LRU |
| `bin/yt-dlp` | Downloaded by `npm run setup`, gitignored |
| `scripts/` | icon generation, yt-dlp setup, push helper |
| `tests/` | Playwright e2e specs · unit tests live next to sources in `frontend/*.test.js` |
| `legacy/` | Old native-shell docs — do not treat as current |
API endpoints (notes/admin routes are listed in the header of `server/notes.js`): `GET /api/search|channel|streams|download/:id|version|user/data|profile/load`,
`GET /api/media/:id|media/:id/status|media/stats`, `POST /api/media/:id/redownload`,
`POST /api/user/sync|profile/create|profile/save`, `GET /sw.js` (BUILD_TAG-injected), `GET /*` static.
JSON shapes mirror the Tauri Rust bridge exactly — don't change one side alone
(`/api/streams`' `data.serverCached` is additive and web-only).
## Long videos (1 h+)
- Bun's default request-body cap is 128 MB — `Bun.serve` sets `maxRequestBodySize` to 5 GiB;
routes enforce their own limits (uploads 4 GB, intake `P2P_INTAKE_MAX_BYTES` 3 GiB). Without it
every large upload/intake died with 413.
- Admin uploads use `PUT /api/admin/uploads/stream?name=…` (raw body → disk in chunks, browser
sends the `File` itself); cover images go to `PUT /api/admin/uploads/:id/art`. The multipart
`POST /api/admin/uploads` parses the whole body in memory — scripts with small files only.
- Videos over `transcode.maxSeconds` are never re-encoded (lane would be tied up for hours).
- Deferred ideas (Cloudflare Worker fetch, Android device download, ffmpeg.wasm client editing): `docs/deferred-ideas.md`.
## Save to device + "On other devices"
- `exportToDevice(video)` (app.js, helpers in `frontend/export.js`): puts the file in Photos / Files / Downloads.
Source order: copy saved in OPFS → server copy (`GET /api/export/:id?name=`, attachment + Range; direct
download on desktop, via OPFS + share sheet on phones) → online P2P holder → normal save via server.
Buttons appear only once the file is ready: `navigator.share` needs a fresh tap.
- `GET /api/p2p/available` + view `{type:'p2p'}` = the "📡 On other devices" list (sidebar, web only):
verified files with ≥1 sharing holder, online first, stale flagged. Rows play, export, or go to a playlist.
## Layout themes + Glass Stage
- Settings → Layout theme sets `html[data-layout]`; rules live in `styles.css` (older ones) and
`frontend/theme-glass.css` (**glass-stage**: frosted cards, coral glow). Glass Stage also changes layout:
overlay on the video (quality chip, Video / Audio-only, −10 / play / +10, shown when paused or after a tap),
deck row prev · −10 · play · +10 · next, volume pod + labelled mode pill, quick-setting chips (`#deckChips`,
refreshed every 1.5 s by the `glassStage` IIFE), four stacked icon tiles and secondary actions as a pill row,
floating mini player. Elements that only this theme shows (`.stg-overlay`, `.skip10`, `.deck-chips`, `.vol-pod`
extras, `.mode-name`) are in the shared markup and hidden by default.
- **f7-swipe** (`frontend/f7-layout.js` + `theme-f7.css`): classic look + Framework7 gestures. Loads
`vendor/framework7-swipe.min.js` (F7 9.2.0 core+Store+Swipeout+Modal+Sheet, rebuilt from
`vendor/framework7-swipe.entry.js`) only when picked. Cards are wrapped in `li.swipeout` (Queue / Playlist /
Remove, via `card._video`), swipe up on the mini bar = F7 "Up next" sheet, sideways = next/prev, left-edge
swipe = sidebar. F7's touch module swallows programmatic `.click()`s, so `app.off('click')` +
`app.off('touchend')` run after init — keep that, or app.js buttons driven by `.click()` silently stop working.
- Now-playing tiles are `[svg.ti][span.tl]`; change state text with `setTile(btn, label)`, never `textContent`.
## Saved searches + caching notes
- `SearchLibrary` (app.js) keeps every search: metadata index in localStorage `ytpSearchIndex` (sync, ~250 KB),
result lists in IndexedDB `ytpSearchLibrary` (≤1000 queries × 100 results incl. thumbnail URLs; `get()` is async).
A saved copy is trusted 15 days (`FRESH_MS`): a fresh one is shown with NO network call, an older one is shown then
refreshed. The "Update search" button (`#searchMeta`) calls `API.search(q,{refresh:true})` → `/api/search?refresh=1`
which skips every server cache. The search box's recent list and its "Clear this list" only touch
`ytpRecentSearches`; results are deleted ONLY in Settings → Saved searches. Thumbnails are warmed into the SW
`ytplayer-thumbs` cache (`THUMB_CACHE_MAX` 25000, trimmed every 100th put — `cache.keys()` is costly at that size).
Browse view: `{type:'savedSearches'}`. Web Workers were NOT added: IndexedDB/fetch are already async off-thread I/O and
postMessage would clone the same data; DOM rendering can't move to a worker.
- Server `/api/search` (`server/search-cache.js`, tables `search_cache` + `video_meta`): memory (200, 10 min fresh) →
libsql (up to 200 YouTube cards per query via `innertube.searchDeep` continuation paging; ≤250,000 queries AND
`SEARCH_CACHE_MAX_BYTES` 2 GiB, LRU) → YouTube. Stale copies are served for 15 days while refreshing in the background.
Every card seen is also stored in `video_meta` (≤500k); `GET /api/search/local?q=` matches known videos by title/channel
(all words) + uploads in ms, and the app paints them while the real search loads. yt-dlp fallback still returns 25.
- Static files: index.html is stamped with `?v=<BUILD_TAG>` on local css/js (`indexHtml()`); a request whose `v` equals the
running build is `immutable, max-age=1y`, anything else `no-cache`. The SW `cacheFirst` matches `?v=` URLs with
`ignoreSearch` against the plain-URL precache. A new build = new URLs, so old ones simply get evicted.
`/fonts` and `/icons` are cached 30 days.
## SHA-256 in WebAssembly (`frontend/sha256.js`)
- `Sha256.create()` runs its block function as WebAssembly (`frontend/wasm/sha256.c` → `scripts/build-sha256-wasm.sh`
→ generated `frontend/sha256-wasm.js`, base64, ~2 KB) and falls back to pure JS if WebAssembly is missing, the CSP
refuses it, or the load-time self-test ("abc") fails. ~150 MB/s vs ~65 MB/s in JS (Node/Chromium; phones are slower
but the ratio holds). It is synchronous on purpose (callers aren't async) — fine because the module is under 4 KB.
- Needs `'wasm-unsafe-eval'` in index.html's CSP `script-src`. Workers pull the blob in with `importScripts('/sha256-wasm.js')`
from inside sha256.js; the file is in the SW `SHELL` list. After editing the C file, re-run the build script and commit both.
`Sha256.engine()` says which one is active; `create({js:true})` forces JS (tests).
## Server media cache (`server/media-cache.js`)
- Every played (`/api/streams`, LOW priority, ≤ `MEDIA_AUTO_MAX_SECONDS`, default 3 h) or saved
(`/api/download`, HIGH, ≤ 3 h) video gets ONE copy: `$MEDIA_DIR/<id>.<gen>.mp4`
(≤720p H.264 8-bit + AAC, faststart) + `<id>.<gen>.m4a` audio sidecar for audio-only
mode. `MEDIA_DIR` defaults to `./data/media` (the `ytplayer-data` volume in prod).
- Jobs are server-owned — **never pass a request AbortSignal into them**; a client
closing its tab must not kill a fetch. Downloads still run inside `withSaveSlot`.
- **Validation gate** (`validateMedia`): h264 yuv420p + AAC, container/stream durations
cover the source, a full `-c copy` demux pass with zero stderr, head + tail decode.
The demux pass is what catches a faststart file whose index is intact but whose
data is cut. Nothing reaches the cache dir without passing it; failures back off
(15 min · 2^n, max 24 h) and saves fall back to the legacy per-request path.
- `gen` is in the filename and URL (`/api/media/<id>?g=<gen>`): a URL never serves
different bytes. A replaced gen is kept 30 min so in-flight Range playback survives.
- **Compression lane** (rev `OPT_REV` = 2): niced x265 8-bit `-preset medium -crf 28`,
`hvc1` tag, anime-style tuning (`X265_TUNING`), `-fpsmax 30`, audio copied — kept only
if ≥15% smaller, and the copy's `vcodec` becomes `hevc`. **Sample-first**: videos ≥60 s
get two 10-s windows encoded first and compared with the source's own packet bytes
over the same timestamps; the full encode only runs if the prediction clears the 15%
bar (a skip costs ~20 s of video; a full encode ~2× realtime on the homelab).
**Why:** re-encoding YouTube's already-compressed H.264 usually needs MORE bits for
LOWER quality (generation loss) — on prod 0 of 5 videos shrank at CRF 28, one grew 25%
(VMAF 93.6 at 126% of source; capping to 60–70% drops VMAF to ~84–87). Only videos
where YouTube over-spent bits win (a live worship video: −34%). AnimeOut-style sizes
come from pristine Blu-ray sources, which YouTube never gives us. Bumping `OPT_REV`
re-queues every cached copy once at boot.
- **HEVC gating**: an HEVC copy is served only to clients that send `?hevc=1` on
`/api/streams` and `/api/download` (app.js `hevcCapable()` = canPlayType hvc1, minus a
per-device `ytpNoHevc` flag set when an HEVC copy fails to play). Everyone else gets
the pre-cache behaviour (YouTube proxy / legacy H.264 save). Verified: iPhone XR, Galaxy
S10, Windows Chrome play HEVC; AV1 fails on the XR (no decoder), so it isn't used.
The validation gate requires `hvc1` (Safari refuses `hev1`) and 8-bit 4:2:0.
- **Budget**: `MEDIA_CACHE_MAX_BYTES` (10 GiB) LRU by `last_access` (anything played in
the last 10 min is protected) + `MEDIA_MIN_FREE_BYTES` (5 GiB) disk guard → skip, stream.
- **Broken**: `POST /api/media/:id/redownload` (now-playing ⚠ Broken button). When a
client falls back from a cached copy (`/api/streams?nocache=1`) the server also
re-validates its copy and refetches it if it fails — never trusts one device's error.
- Ops: `curl https://worship.hesed.sbs/api/media/stats`; files under
`/app/data/media` in the container.
## Lyrics · chapters · bookmarks (`server/notes.js`, `frontend/lyrics-core.js`)
- **Shared per video** (every user sees the same copy): `video_notes` holds the live
lyrics / chapters doc per `(video_id, kind)`; **every save** also lands in
`video_note_revs` as a full snapshot (history + undo). A daily JSON dump of all
live notes goes to `<DB dir>/backups/notes-YYYY-MM-DD.json` (30 kept).
- **Who writes**: a user linked to an online profile (body `profile` must exist —
same trust level as the profile API), a script with an API token
(`Authorization: Bearer ytp_…`, only a SHA-256 is stored), or the admin
(signed httpOnly cookie). Saves are optimistic: client sends `baseRev`, gets
409 + `current` if someone saved in between (UI asks "Keep mine / Load theirs").
- **Personal, not shared**: bookmarks (`data.bookmarks[videoId]`) and the per-song
sync offset (`data.lyricOffsets[videoId]`) — both ride the profile sync.
Line shows at `t + doc.offset + personal offset` (positive = later).
- Editor text format = LRC superset: `[1:23.45] line`, `# Section`, `! band cue`,
`@ Key G, 70 BPM` tags, multi-stamp LRC lines and `[offset:±ms]` accepted.
- Captions: `GET /api/notes/:id/captions` (preview) and token/admin-only
`POST /api/notes/:id/lyrics/auto` pick human subs first, else the auto track in
the spoken language (`*-orig`), never a machine translation. Auto captions of
**music** are mostly junk ("oh", "n to") — expect to hand-fix or paste lyrics.
- **Admin**: `/admin` (frontend/admin.html, never cached by the SW) — tokens,
edit feed with view/restore, caption injection, JSON export, API examples.
Disabled unless `ADMIN_PASSWORD` is set (Dokploy Environment tab; compose passes
`${ADMIN_PASSWORD:-}`). Login is rate-limited per IP.
- **Service mode → 🎵 Lyrics** (`data.settings.serviceLyrics`, `serviceLyricsAutoscroll`):
lyrics-only view; the sung line is centred, highlighted and sized to the
largest font that fits ONE row. Sizing is measured with a hidden real
`.sl-line` in TWO passes — Bricolage Grotesque has an optical-size axis, so
glyphs get relatively wider at small sizes and a single 100px measurement
over-fits on phones. Re-fit (in place, never rebuilding rows — that would
move the scroll position) on resize, `document.fonts` load, and +900 ms.
Lyrics-only and the 📺 video panel are mutually exclusive.
- **Free batch transcription**: `scripts/lyrics/auto_lyrics.py` (faster-whisper
`large-v3-turbo` int8 on CPU, no API key/credits; venv at
`~/.local/share/lyrics-asr/.venv`). `--missing` uses `GET /api/admin/media`
(admin or token). Measured on the 16-core laptop: ~0.3–0.65× real time;
openai-whisper medium was ~2.5×. **`vad_filter` must stay False** — VAD calls
sung music non-speech and returns an empty transcript. Karaoke/minus-one
tracks have no vocals (reported "instrumental?"); their lyrics were read from
the on-screen text (frame sampling + OCR), not audio. ElevenLabs Scribe also
works but spends the TTS credit balance (free tier = 10k/month).
- Offline: the last-seen notes per video are cached in localStorage
(`ytpNotesCache`, 200 videos), so saved songs keep their lyrics offline.
- **Toast cap bug (fixed with this feature):** `toast()` used
`while (children.length > 3)` with a deferred remove — the 4th toast spun
forever and Chrome killed the tab ("Target crashed" in Playwright, no JS
error). Never cap with a loop whose exit depends on a deferred removal.
## Playlist transitions + waveform (`Transition` / `Wave` in app.js)
- `data.settings.transition` = `off` | `gapless` | `crossfade` (`crossfadeSec`,
default 6); the ↦/⇥/⤨ button cycles it with a 6-s toast. Applies only to
playlist/queue playback with a next song, not with loop-one or an A-B loop.
- A hidden **bridge `<audio>`** preloads the next song's audio ~25 s early
(offline copy, else `/api/streams`). Crossfade starts it `crossfadeSec` early
and ramps both volumes; gapless starts it when the song ends. Then the queue
advances normally with `Player._handoff` set: `_startPlayback()` seeks the
new track to the bridge's position, plays, and releases the bridge on
`playing` (failsafe 5 s / 20 s). afterLoad skips resume/A-marker seeks
during a handoff; `onTrackEnded` ignores `ended` while one runs.
- iOS ignores `element.volume`, so crossfade degrades to gapless there.
- **End-of-song race (fixed):** the song's last `timeupdate` arrives with the
element already `paused` (it ended), and `ended` can beat the fade timer.
Both used to look like "user paused" → the crossfade was cancelled and the
next song restarted from 0. `tick()` and `onTrackEnded` (`Transition.onEnded()`)
now finish the handoff when a fade is running at the end.
- Waveform: `GET /api/media/:id/peaks` = 400 RMS buckets (0..100, ^0.7 so
quiet verses stay visible) from ffmpeg over the server-cached copy, memoised
per file path (gen). Audio-only mode draws it on `#waveCanvas` BEHIND the
range input (made transparent, still the control), + hover time tooltip and
"⚡ Jump to the loudest part" (loudest ~5 s window). Not cached on the server
→ plain seek bar. Envelopes are kept in localStorage (`ytpPeaks`, 80 songs).
- Tested with real audio: a local server whose media_cache holds 20-s clips
(upsertMedia rows + `<id>.1.m4a/.mp4` files) — Playwright's Chromium plays
AAC; launch with `--autoplay-policy=no-user-gesture-required`.
## Uploads + web lyrics
- **Uploads** (`server/uploads.js`, `UPLOAD_DIR`, table `uploads`): an admin
posts a file to `/api/admin/uploads` (multipart, ≤ 4 GB, admin cookie or API
token). ffprobe runs ONCE and gives everything: title/artist/album tags,
duration, whether there is a REAL video stream (a cover picture also appears
as a video stream — check `disposition.attached_pic`), the cover itself
(extracted to `<id>.art.jpg`; an uploaded image wins) and embedded lyrics
tags (`LYRICS` / `lyrics-eng` / `UNSYNCEDLYRICS` / `©lyr`) which are parsed
with `parseLrc` and saved as that song's shared lyrics (synced when in LRC
form). Ids are `upl_<12 hex>` and are accepted anywhere a video id is:
`/api/streams` (audio → `audioUrl` + art, video → one "Original" quality),
`/api/download`, peaks/gif/clip (`audioSourcePath`/`videoSourcePath`), notes.
`/api/search` puts the library first and still answers when yt-dlp fails.
The app: 📁 Library view, `isUploadId`/`isMediaId` helpers, audio uploads
force audio mode so the cover art shows where the video would be.
- **Web lyrics**: `POST /api/notes/:id/lyrics/web` asks **LRCLIB** (free,
key-less, often SYNCED) using a cleaned title/artist + duration
(`cleanTitle`/`cleanArtist`/`pickLrclib`, ± 6 s). Profile users, tokens and
admins may call it; the lyrics worker tries it BEFORE transcribing.
`scripts/lyrics/web_lyrics.py --missing --agy` adds an agy web-search
fallback (plain text → untimed lines, to be timed with Tap-sync).
Gotcha fixed here: a `/g` regex reused for `.test()` skips every other call
(lastIndex) — `cleanTitle` keeps a stateless copy.
## Watch party, sharing, playback extras (all in app.js unless noted)
- **Lyrics instead of the video** (`Notes.stageLyrics`, `#stageLyrics` inside
`.player-stage`): a per-device view for watch parties and sing-alongs —
`data.settings.stageLyrics` / `stageLyricsAutoscroll`. It reuses the service-mode
machinery (`fitLyricLines`, `LyricsCore.activeIndex`, the same `.sl-line`
classes) and is driven from the normal playback tick. The `<video>` is only
**hidden** (`visibility`), never unloaded, so playback, audio and party sync
carry on untouched — that is why it is safe for a guest to switch views
mid-party. Toggle from the watch-party panel or the bar inside the stage
(hover on desktop, always visible on touch).
- **Watch party** (`server/party.js`, `Party`): `/ws/party` (Bun has ONE websocket
handler — sockets are tagged `ws.data.hub = 'party'` and routed in server.js).
Host drives; guests extrapolate the host's `state` from the server-stamped
`ts` (clock offset from `hello.now`), seek when > 1.5 s off, mirror
play/pause. Guest actions within the 1.5 s "quiet" window after a sync are
ignored; later ones → a `cmd` (if the host allows control) or "off sync"
(Re-sync button). `playNext/playPrev` → `Party.intercept`, and guests never
auto-advance or crossfade. Chat is relayed (≤ 500 chars, 400 ms flood guard,
last 60 kept). Voice = WebRTC mesh, the smaller pid offers, STUN only (no
TURN — strict NATs won't connect). Host resumes after a reload with the
`secret` from `hello` (party survives 5 min without its host).
- **Timestamp sharing** (`Share`): `/?v=<id>&t=<sec>` deep links (handled at
boot via `playVideoAt`), YouTube `youtu.be/<id>?t=`, GIFs from
`GET /api/media/:id/gif` (palettegen, ≤ 6 s, server-cached videos only) and
soundbites from `GET /api/media/:id/clip?fmt=mp3|m4r` (m4r ≤ 40 s, written to a
temp file so it's a normal faststart MP4 — iPhones reject fragmented ones).
- **External players** (`External`): hands out `/api/media/<id>` (the single-file
server copy) via Android `intent:` (VLC / MX / chooser), iOS `vlc-x-callback`,
desktop `vlc://`, or an `.m3u` (this video or the queue's cached songs).
- **Notes**: bookmarks with `kind:'note'` hold multi-line text (≤ 2000) and carry
`vt`/`vc` (video title/channel); the 📝 Notes view lists them all, exports
Markdown. **Transcript search** = 🔎 tab over the lyrics or the YouTube
captions (`/api/notes/:id/captions`, cached per video).
- **PiP** mirrors the PiP window's play/pause onto the whole player (dual mode's
sound is on `<audio>`). **EQ**: 5 BiquadFilters; media elements are wired in
only once a non-flat curve is picked (irreversible), disabled on iOS (Web
Audio suspends on lock → would kill background audio). **Sleep timer**: fade
over `sleepFade` s, then pause / "close" (window.close, falls back) / black
curtain; "end of this song" also blocks Transition. **Gestures**: double-tap
thirds ±10 s / play, pinch 1–3× (CSS transform), vertical swipes for volume /
brightness (CSS filter) only in fullscreen or `body.landscape-fs` (inline the
page keeps `touch-action: pan-y` so it still scrolls).
- Local media tests: seed `media_cache` rows + `<id>.1.m4a/.mp4` files; the
Playwright `channel: 'chromium'` build plays H.264/AAC; `--use-fake-device-for-media-stream`
gives WebRTC a fake mic.
## Presenter view, stats, lyrics worker
- **Presenter** (`Presenter` in app.js, `/?present=<code>`): a lyrics-only
projector/TV screen. Pairs through the phone-remote relay like a phone
(listen-only); the host's `state` carries `v.id`, `cur`, `rate`, `paused` and
`off` (the host's personal lyric offset), and the presenter extrapolates the
position between the ~1/s updates. Host modal → "Open presenter window
here" opens a popup to drag onto a second display; `/api/remote/qr/<code>?kind=present`
is its QR. Keys: F / double-click fullscreen, B blank screen. Forced dark
tokens so it stays readable if the device is in light theme.
- **`fitLyricLines(list)`** is the shared one-row font fitter for service-mode
lyrics and the presenter — re-run it on font load, resize and +900 ms
(first fit on a fresh page happens before Bricolage loads).
- **Stats** (`frontend/stats-core.js`, pure + tested; `StatsTrack` + `renderStats`):
`data.stats.days[YYYY-MM-DD] = {s, p, songs:{id:plays}}` (local days, 400
kept) synced with the profile. Seconds = media-time deltas while playing
(seeks/pauses excluded, divided by playback rate); a play = 30 s heard in one
load; commits every 60 s / on play / on page hide to avoid profile-push spam.
Streak = consecutive days ≥ 5 min (today may still be pending).
- **lyrics-worker** (compose service, `scripts/lyrics/Dockerfile`): runs
`auto_lyrics.py --missing --watch 300` forever — one song per cycle, nice 10,
`cpus: 2`, `mem_limit: 3g`, audio fetched from `http://ytplayer:3000` over the
private `lyrics` network (never the WAN). Auth = env `LYRICS_WORKER_TOKEN`
(≥ 24 chars) accepted by notes.js as `api:lyrics-worker` without a DB row;
unset → the worker idles. `/data/state.json` remembers instrumentals (never
retried) and failures (backoff 15 min·2^n). Model (~1.6 GB) downloads to the
`lyrics-models` volume on first start.
## Phone remote (`server/remote.js`, `Remote` in app.js)
- Desktop tab playing to a TV = **host**; phone = **remote**. Both are browser
tabs of this app, so the server relays over `/ws/remote` (Bun `server.upgrade`
in the `Bun.serve` fetch wrapper, before Hono). Mockup:
`docs/mockups/mock-06-remote-control.html` (it assumed a LAN host + mDNS; the web
app can't do that, so it's a server relay + a 6-digit code instead).
- Host secret lives in the desktop's localStorage (`ytpRemoteHost`); room id =
hash(secret). Pairing (`POST /api/remote/pair`) is a one-time 6-digit code
(10 min) → phone gets `token = HMAC(secret, remoteId)` (`ytpRemotePair`).
**Nothing about phones is stored server-side**: tokens are re-checked against
the connected host's secret, so server restarts / desktop reloads keep phones
paired, and "Unpair all" (new secret) revokes every phone at once.
- The host pushes `state` (≤1/s, deduped) and `queue` (`{items, idx}` of the live
`queue`/`queueIndex`); commands are whitelisted server-side (`REMOTE_COMMANDS`)
and run by `runCommand()` on the host with the same functions the UI uses.
- `REMOTE_SAME_NETWORK=1` = pairing requires the phone and desktop to share a
public IP (first `X-Forwarded-For` hop). Off by default — verify that the
VPS→homelab Traefik chain forwards the real client IP before turning it on.
- QR: `GET /api/remote/qr/:code` (server-side SVG via `qrcode`) encodes
`<origin>/?pair=<code>`; the app consumes and strips `?pair=` at boot.
## Local dev
```bash
npm run setup # download bin/yt-dlp (once)
cd server && bun install
ln -s ../frontend public # once — the server serves ONLY ./public (Docker copies frontend/ there)
bun --hot server.js # http://localhost:3000
node --test frontend/ # unit tests (run from repo root)
npx playwright test # e2e (see Testing below)
```
Local DB file: `server/data/ytplayer.db` (gitignored). `BUILD_TAG` is computed from `./public` contents.
## Production deployment (web PWA)
- URL: **https://worship.hesed.sbs** (Traefik label in `docker-compose.yml`)
- Runs on the **homelab** Dokploy remote node; control plane is Dokploy on the VPS
(`193.160.119.172`, API key in `~/development/.secrets/dokploy-api.env`).
- Compose ID: **`wprYCM8T51f7JtSHb983p`** (project `ytplayer`, env `production`).
- **Pushing to git does NOT deploy.** Trigger explicitly (build ≈ 5–6 min):
```bash
ssh -i ~/.ssh/tmp_vps/dokploy_session root@193.160.119.172 \
"curl -s -X POST -H 'x-api-key: $KEY' -H 'Content-Type: application/json' \
-d '{\"composeId\":\"wprYCM8T51f7JtSHb983p\"}' http://localhost:3000/api/compose.deploy"
# poll composeStatus via /api/compose.one?composeId=... until done|error
```
- Confirm the deploy landed: `curl https://worship.hesed.sbs/api/version` — the
`buildTag` (content hash of every file under `./public`) must change.
- Homelab node is NOT always reachable on LAN; SSH via the VPS hop:
`ssh root@193.160.119.172` → `ssh root@10.8.0.2` (WireGuard). Container name:
`ytplayer-main-1dihzn-ytplayer-1`. DB: libsql file `/app/data/ytplayer.db`
(query with `docker exec <c> bun -e '...' `using `@libsql/client`).
## Update-flow architecture (fragile — read before touching)
- `GET /sw.js` is served by the server with the real `BUILD_TAG` **injected by
regex** over the fallback expression in `frontend/sw.js`. Never switch back to
an exact-string replace: when the fallback literal was bumped (`v1.0.3`→`v1.0.4`)
the exact match silently failed, the SW version froze, and **no client ever
received another update** while `/api/version` kept announcing one — the
"Update available keeps showing" bug.
- `BUILD_TAG` hashes **every** file under `./public` recursively. Don't reduce it
to a file subset; a change to an unlisted shell file would stop busting caches.
- **The banner has ONE rule** (`maybeShowUpdateBanner` in app.js): show it only
when the build this page runs differs from `/api/version`. The server stamps
the running build into index.html (`<meta name="ytp-build">`, at request
time like sw.js's BUILD_TAG); the SW caches that index.html with the rest of the
shell, so the meta always describes the code in the tab. The poll, a waiting
worker and the SW_UPDATE_AVAILABLE broadcast are only *prompts to re-check*.
This loop was "fixed" three times by chasing individual triggers — don't add
a trigger that calls `showUpdateBanner()` directly.
- **Background download + instant swap (added 2026-09-22).** A new worker
precaches the whole shell during `install`, so by the time the user presses
"Refresh UI" the build is usually already on disk. `applyUpdate` asks the
**waiting** worker `CACHE_STATUS` over a `MessageChannel`; when it answers
`ready: true` (it re-checks every SHELL url, since a cache can be evicted)
the download is skipped entirely and the swap is immediate.
Two rules keep this safe: the probe is **opt-in** (`askStatus`) — never
implicit, because a probe awaiting a reply hangs forever if the caller
injects a `setTimeout` that never fires (the existing tests do exactly
that) — and *any* doubt (no reply, timeout, thrown error, `ready: false`)
falls back to the all-or-nothing download below, which is still what
guarantees correctness. `maybeShowUpdateBanner` also calls `prefetchUpdate()`
→ `registration.update()` so the download starts the moment a new build is
seen rather than when the user clicks.
- **Refresh UI** (`frontend/sw-update.js`): `refreshShellInPlace()` re-downloads
every file the shell caches hold — cache-busted (`?__ytpfresh=`) so even an
OLD worker's cache-first handler can't answer from its cache, 3 tries per file,
all-or-nothing — and writes them into every versioned shell cache; then it
activates a waiting worker (SKIP_WAITING) if any and reloads once. A failed
download shows an error toast and re-offers later; it never reloads into the
old shell. `checkUpdateOutcome()` verifies after the reload (sessionStorage,
max 3 attempts) instead of looping.
- **Why it kept looping on prod:** the VPS→homelab link is slow and drops
requests. The SW install (`cache.addAll`, all-or-nothing) failed, Refresh UI
reloaded into the old cached shell, and the partial `ytplayer-<tag>` cache
left by the failed install later made activate broadcast "update available"
to pages that were already current. sw.js now precaches with
`cache: 'reload'`, retries each file, and deletes its partial cache on failure.
- Reproduce with the throttling/stalling proxy approach: WebKit (Playwright on
the Windows side) or Chrome over CDP against a scratch copy of the server,
stalling every Nth shell request after "deploying" v2. A fast local link never
shows the bug.
## Cache layout & offline thumbnails
- Three cache families, and the split matters on activate: the **versioned shell
cache** `ytplayer-<BUILD_TAG>` is evicted on every deploy, while the **utility
caches** `ytplayer-thumbs` and `ytplayer-fonts` are listed in `UTILITY_CACHES`
and deliberately survive it. Adding a new utility cache means adding it there
too, or it gets wiped on the next deploy.
- **Thumbnails are cache-first, not stale-while-revalidate** — a given thumbnail
URL is immutable, so revalidating just burns a round trip per image per launch.
- **The opaque-response trap (this silently emptied the thumb cache for months).**
An `<img>` to another origin is a **no-cors** request, so `fetch(request)` in the
SW resolves to an **opaque** response with `status === 0` — not 200. The old
guard was `if (r.status === 200) cache.put(...)`, which rejected every single
thumbnail, so `ytplayer-thumbs` was permanently empty and offline showed broken
images (measured on prod: 0 entries after browsing pages full of visible thumbs).
Fix in `thumbnail()`: re-issue the request in `cors` mode — ytimg/ggpht all send
`Access-Control-Allow-Origin: *` — and cache that readable response; an opaque
one is accepted only as a last resort. **Never reintroduce a bare `status === 200`
check on a cross-origin subresource.**
- Thumbnail hosts live in `THUMB_HOSTS`. An unlisted host doesn't error — it just
bypasses the cache and breaks offline, so add mirrors/avatar hosts there.
- The thumb cache is capped at `THUMB_CACHE_MAX` (800, oldest-first via the
insertion-ordered `cache.keys()`). Keep a cap: CacheStorage and the OPFS offline
audio share one origin quota, and opaque entries are padded to ~7 MB each for
quota accounting, so an unbounded thumb cache can evict saved audio.
- App side (`app.js`): `warmThumb()` pulls artwork through the SW when a video is
saved offline, and `warmOfflineThumbs()` runs a bounded launch backfill
(`THUMB_WARM_MAX` = 400, 4 at a time) over cached ids + playlist videos so
libraries saved before this fix repair themselves. Thumbnails only cache when
something requests them — a device needs one online launch to get offline art.
- `staleWhileRevalidate()` (fonts) must not `return cached || networkFetch` bare:
the fetch resolves to `null` offline and `respondWith(null)` throws. It ends
with `|| Response.error()`.
## Section rail + foldable cards (phones)
`SectionRail` in app.js draws a floating right-hand rail on phones with one
icon per visible card (player · now playing · lyrics · related · list). It
follows the scroll, a tap jumps to that card, and a tap on the card you are
**already** on folds/unfolds it (`data.settings.foldedCards`, per device).
Folding hides a card's body but never its header, so it stays a landmark you
can scroll to and reopen; the Related card's own +/− button routes through
`SectionRail.setFolded` so the two can never disagree.
Two things about this page that break naive implementations:
- **The document does not scroll.** `.player-pane` is the scroll container in
the browser, but the installed PWA in portrait scrolls `.body` instead
(`.player-pane` becomes `overflow-y: visible` there). `scrollerOf()` walks up
to whichever ancestor actually scrolls, and `viewBox()` measures against it.
- **Scroll events do not bubble**, so a `window` scroll listener never fires
for an element scroller — the listener is on `document` with `capture: true`.
Cards also appear outside `render()` (Related arrives with the video's related
list), so `onScroll` re-runs `build()`, which is a no-op unless the visible set
changed; without that the rail could highlight nothing at all.
## First paint vs. the network (launch)
`boot()` used to `await` the profile pull and the shared-playlist inbox before
the first `render()`, so on a slow link the sidebar stayed empty for as long as
the network took. Everything the device knows is already in localStorage, so it
now paints immediately and reconciles afterwards:
- `?list=` / `?profile=` share links still run **before** the first paint — they
*replace* the synced slice, so painting first would flash the old playlists
and swap them out. They are skipped entirely when the parameter is absent.
- `syncOnLaunch()` then runs the network pass with a spinner (`#syncSpinner`,
beside the Playlists header, `setSyncing()` is counted so the last finisher
clears it) and re-renders **only if** `playlistFingerprint()` changed — a
needless render would drop the sidebar's scroll position.
## Data model quirks
- Client state persists in localStorage key **`_ytpdata`** and syncs (debounced
400 ms) to `POST /api/user/sync`, keyed by a browser fingerprint.
- **A-B loop markers are per-song-per-playlist**: stored on the playlist's own
copy of the video (`entry.ab = {a, b}`) when playback source is that playlist;
`data.abMarkers[videoId]` is only the fallback for non-playlist playback.
- **Online profiles** (`profiles` table, `/api/profile/*`): named cross-device
sync where the lowercase profile NAME is the only credential (passkey-style,
by design). Client stores `data.profile = {name, syncedAt}`; sync is
last-write-wins — push debounced on every persist(), pull on app launch when
the server's `updated_at` is newer than the local `syncedAt`.
- **Profile share links**: `?profile=<name>` is consumed by `adoptProfileFromUrl()`
at boot, before any rendering. It strips the param via `replaceState` (so a
reload can't re-fire it) and confirms first when the device already has
playlists/history or another profile — adopting *replaces* the synced slice.
The name comes off the URL untrusted, hence `escapeHtml()` on it.
- **Empty-home playlist grid**: `renderHomePlaylists()` swaps the branding hero in
`#playerPlaceholder` for the user's playlists (hero is the no-playlists
fallback). It is driven from the tail of `renderSidebar()` — not from
`render()` — so every playlist mutation refreshes both in one place.
## Testing
- Unit: **`node --test frontend/*.test.js`** (sw, sw-update, async-guard, video-edit, lyrics-core, stats-core, sha256).
Server: **`cd server && bun run test`** — runs each file in its own process (db.js is a
singleton, so two test files in one `bun test` run share one temp DB; bare `bun test`
also drags in the frontend node tests via the `public` symlink). media-cache needs a
60 s hook timeout for its ffmpeg fixtures.
Local e2e needs a CURRENT yt-dlp — a 2-month-old one 403s on every download.
The directory form `node --test frontend/` fails on Node 22 with
`Cannot find module .../frontend` — it resolves the dir as a module, not a test
glob. That's the harness, not the tests.
- E2E: `npx playwright test` — WebKit iPhone-12 profile against a static serve of
`frontend/` (needs `npx playwright install webkit`). A spurious update banner
will make the settings-panel specs fail with `#modal intercepts pointer events`
— that failure mode is a real app bug, not test flake. On the WSL laptop the
WebKit install fails host validation (missing `libgtk-4`, `libgstreamer*`, …,
needs `sudo npx playwright install-deps`); chromium is already downloaded, so
ad-hoc rendering/offline checks can drive it directly instead.
- Service-worker behaviour (thumb caching, offline) is only provable in a real
browser: serve `frontend/` statically, let the SW take control (needs a second
reload), then `context.setOffline(true)` and assert `img.naturalWidth > 0` plus
the `ytplayer-thumbs` entry count. Asserting against the browser's own HTTP
cache proves nothing — check the Cache API entry count.
- Test records on prod use `Probe */Recon *` names; clean via the container DB,
children (`video_history`) first.
## Harness
Skills live in `.agents/skills/` (symlinked into `.claude/skills/`):
- **deploy-prod** — the Dokploy deploy + buildTag verification flow (manual-only; use for any "deploy"/"release" request).
- **mobile-app-ui-design** — UI/UX design work on the PWA screens.
- **lyrics-lookup** — fill in songs that have NO lyrics (LRCLIB → agy web search → local faster-whisper).
- **lyrics-regenerate** — back up, then replace wrong/mistimed lyrics from LRCLIB (`scripts/lyrics/lrclib_regen.py`).
- **lyrics-agy** — last resort when LRCLIB has nothing: agy (flat-rate) searches the web and often returns
LRC-timed lyrics (`scripts/lyrics/agy_lyrics.py`). Also the `--from-file` path for pasting lyrics you already have.
agy is NOT deterministic — the script asks up to `--tries` times and keeps the best (timed > untimed > longer).
Its answer arrives on **stderr**, long answers are truncated behind a `keep_id`, and a quota-failed instance
returns error prose inside a `STATUS: ok` envelope that will parse as lyrics if you let it.
### Matching a song on LRCLIB (learned the hard way)
`/api/streams` gives the YouTube **channel**, not the artist, so a title+artist
query finds nothing for a lyric-video channel ("Integrity Worship", "Christian
Lyrics") — `lrclib_lookup` falls back to a title-only search and then ranks
candidates whose artist *verifies* 50 points above those that don't. Two guards
sit on the result, and both exist because they caught a real wrong song:
- `artist_ok()` ignores `GENERIC` words. Channel "**Christian** Lyrics" once
vouched for a track featuring **Christian** Burns (Nicky Romero, "Still the
Same Man"). Never verify an artist on a word that says nothing about who
recorded the song.
- `title_run()` compares **whole words, never substrings** — "Still" is a
substring of "(You Can Still) Rock in America", and a one-word title is
rejected outright. It gates the `LENGTH` rule (same title, within 3 s of the
same length ⇒ accept even when the artist can't be checked).
An unverified match is printed as `UNSURE` and skipped; `--loose` overrides that
and is almost always the wrong answer.
### Admin lyric editor (`frontend/admin.html`)
`/admin?v=<id>` (or the Edit/Lyrics buttons) opens a song with its audio from
`/api/streams`, the waveform from `/api/media/:id/peaks`, and one row per line:
**Set** stamps the playhead, ±0.2 s nudges, **Tap mode** stamps the highlighted
line on Space and walks down, plus shift-all, line/section/cue kinds, a ✎ Text
LRC view and a ⤓ LRCLIB pull. Saves are optimistic (`baseRev`, 409 → keep
mine / load theirs). **Rows are built once per load and then only their classes
and values change** — re-rendering on every tick would steal focus from the
field being typed in and reset the scroll position.
## Commit rules
One changeset = one commit, single-line imperative message, **no AI attribution
of any kind** (global rule). `git push origin main` pushes to both remotes.
- Server code must not import `../frontend/...` directly: the Docker image copies frontend/ to `server/public/`. Use the existsSync fallback pattern (see piano.js / direct-relay.js).

243
DESIGN.md Normal file
View File

@@ -0,0 +1,243 @@
---
name: "YT Player — Classic"
description: "Quiet matte studio for watching and listening; applies only to the Classic layout."
colors:
accent: "#f06b53"
accent-bright: "#ff947e"
accent-deep: "#c6442f"
bg: "#121315"
bg-1: "#18191c"
bg-2: "#202226"
bg-3: "#2b2e33"
line: "#42464d"
line-soft: "#2b2e33"
text: "#f3f1ed"
text-2: "#c3c4c7"
text-dim: "#a1a5ac"
on-primary: "#ffffff"
on-play: "#171719"
light-bg: "#f4f2ee"
light-bg-1: "#ffffff"
light-bg-2: "#efece6"
light-bg-3: "#e5e0d8"
light-line: "#d8d2c8"
light-line-soft: "#e6e1d9"
light-text: "#1b1a18"
light-text-2: "#4a4843"
light-text-dim: "#625e59"
light-accent: "#ff4b32"
light-accent-bright: "#ff6a52"
light-accent-deep: "#b43623"
contrast-bg: "#000000"
contrast-bg-2: "#0a0a0a"
contrast-bg-3: "#161616"
contrast-line: "#ffffff"
contrast-line-soft: "#9a9a9a"
contrast-text-dim: "#d8d8d8"
contrast-accent: "#ff5a3c"
contrast-accent-bright: "#ff8a6c"
typography:
display:
fontFamily: "\"Bricolage Grotesque\", Georgia, serif"
fontSize: "clamp(36px, 4vw, 60px)"
fontWeight: 800
lineHeight: 1.05
letterSpacing: "-0.035em"
headline:
fontFamily: "\"Bricolage Grotesque\", Georgia, serif"
fontSize: "clamp(22px, 2vw, 30px)"
fontWeight: 700
lineHeight: 1.25
letterSpacing: "-0.02em"
title:
fontFamily: "\"Bricolage Grotesque\", Georgia, serif"
fontSize: "26px"
fontWeight: 700
lineHeight: 1.2
body:
fontFamily: "\"Hanken Grotesk\", system-ui, sans-serif"
fontSize: "14px"
lineHeight: 1.45
label:
fontFamily: "\"Hanken Grotesk\", system-ui, sans-serif"
fontSize: "14px"
fontWeight: 500
media-title:
fontFamily: "\"Hanken Grotesk\", system-ui, sans-serif"
fontSize: "14px"
fontWeight: 600
lineHeight: 1.45
time:
fontFamily: "\"JetBrains Mono\", ui-monospace, monospace"
fontSize: "12px"
rounded:
flat: "0px"
thumbnail: "6px"
sm: "8px"
md: "12px"
circle: "50%"
spacing:
small: "8px"
control-gap: "14px"
compact: "16px"
standard: "24px"
components:
button-primary:
backgroundColor: "{colors.accent-deep}"
textColor: "{colors.on-primary}"
rounded: "{rounded.sm}"
padding: "8px 12px"
button-search:
backgroundColor: "{colors.bg-3}"
textColor: "{colors.text}"
rounded: "{rounded.sm}"
padding: "0 22px"
button-play:
backgroundColor: "{colors.accent}"
textColor: "{colors.on-play}"
rounded: "{rounded.circle}"
width: "64px"
height: "64px"
input-search:
backgroundColor: "{colors.bg-1}"
textColor: "{colors.text}"
rounded: "{rounded.sm}"
padding: "11px 14px"
chip:
backgroundColor: "{colors.bg-2}"
textColor: "{colors.text}"
typography: "{typography.label}"
rounded: "{rounded.sm}"
padding: "10px 14px"
nav-active:
backgroundColor: "{colors.bg-3}"
textColor: "{colors.text}"
padding: "10px 12px"
media-row:
textColor: "{colors.text}"
rounded: "{rounded.flat}"
padding: "12px 8px"
panel:
backgroundColor: "{colors.bg-1}"
rounded: "{rounded.md}"
---
# Design System: YT Player — Classic
## Overview
**Creative North Star: "Quiet Media Studio"**
Classic is a matte charcoal media workspace with warm white type and restrained vermilion. Watching and listening share the same visual priority; playback, browsing, and library controls remain legible together. This system applies only when the Classic layout is selected. Other theme families retain their own visual authority.
The implemented world uses tonal surfaces, fine dividers, bundled typography, and generous control targets. Light, high contrast, text scale, compact density, and reduced motion are supported appearance preferences. Source evidence is frontend/theme-classic.css, with inherited typography and preference values from frontend/styles.css and frontend/refresh.css; the approved direction lives in .impeccable/surfaces/frontend-theme-classic-css.md.
**Key Characteristics:**
- Matte tonal layers and fine dividers.
- Restrained vermilion for playback, actions, and selection.
- Bricolage headings, Hanken interface text, JetBrains timing.
- Responsive workspace with persistent access to playback.
## Colors
The default palette is matte charcoal with warm white text and a restrained vermilion accent. Frontmatter values are normative; unprefixed tokens describe Classic dark mode, while light and contrast tokens record implemented preference variants.
### Primary
- **Vermilion:** accent marks playback, focus, active navigation icons, selection, and the playing row edge. Accent bright is the play hover and active lyric emphasis; accent deep is the filled action and brand surface.
- **Action white / play charcoal:** the two implemented foregrounds for filled actions and circular transport.
### Neutral
- **Studio charcoal:** bg is the workspace; bg-1 is sidebar, browsing, fields, and support panels; bg-2 is chips, secondary actions, and mini-player; bg-3 carries active navigation, tabs, and playing rows.
- **Fine dividers:** line-soft separates rows and regions; line marks stronger edges, including the mini-player boundary.
- **Warm white / secondary / muted:** text, text-2, and text-dim distinguish titles, supporting copy, and metadata.
- **Light preference:** warm paper workspace, white panels, pale neutral layers, and dark text. Classic overrides muted text and deep accent for this preference; the other light accent values are inherited.
- **High contrast preference:** black primary surfaces, white foregrounds and strong lines; bg-1 inherits the same black as bg, text and text-2 inherit white, and accent-deep shares contrast-accent. These aliases are not separate color primitives.
**The Classic Scope Rule.** Apply these rules only to Classic; shared markup does not make them rules for other layout families.
## Typography
**Display Font:** bundled Bricolage Grotesque, with Georgia and serif fallbacks.
**Body Font:** bundled Hanken Grotesk, with system-ui and sans-serif fallbacks.
**Label/Mono Font:** bundled JetBrains Mono, with ui-monospace and monospace fallbacks, for timing and data.
Headings provide character; interface text stays compact and readable. Timing uses tabular numerals.
### Hierarchy
- **Display:** empty-home heading; the frontmatter clamp becomes a fixed (42px) on the mobile layout.
- **Headline:** now-playing title, with wrapping permitted for long media names.
- **Title:** browsing heading; playlist home uses (28px), reducing to (26px) on mobile.
- **Body:** interface baseline; empty-home supporting copy uses (17px), (1.65) leading, and (45ch) maximum width, reducing to (16px) on mobile.
- **Label:** chips and related compact actions; navigation captions stay at 11px, including narrow screens.
- **Media title:** semibold titles in browsing rows; supporting channel metadata uses (12px).
- **Time:** transport timestamps in the mono family with tabular numbers.
Font preferences scale the whole UI to (0.9), (1), (1.12), or (1.26). Classic compensates the application height for that zoom.
## Layout
Desktop uses a (232px) library sidebar, a flexible playback workspace, and a browsing pane sized with `clamp(340px, 29%, 420px)`. Search spans up to (860px). Workspace padding is the standard spacing token; compact density uses the compact token and halves row block padding from (12px) to (6px).
At viewport widths of (1200px) and below, playback and browsing stack in one scrolling body. At (860px) and below, the workspace becomes one column with mobile navigation and safe-area-aware padding. Home playlists use a two-column grid on mobile; desktop uses automatically filled columns with a (138px) minimum. Empty home has natural height rather than video proportions. Above (1200px), the playing video width is capped at `min(100%, calc(42dvh * 16 / 9))`.
Transport responds to its own container: at (620px) and above it uses two columns with seek and quick actions spanning both; at (300px) and below it uses five equal transport columns and (44px) controls. At (420px) and below with extra-large text, bottom navigation becomes a three-column grid. Below (380px), the thumbnail width remains (88px); navigation captions retain (11px).
Browsing rows use an (88px) thumbnail column, flexible text, and a (44px) action column. Most actions have at least (44px) targets; search uses (46px), quick transport actions (48px), and mobile navigation at least (58px) height. The main play control uses the frontmatter size, reduces to (56px) in the wide transport container, and (44px) in the narrowest container.
The mini-player sits above mobile navigation and below the desktop workspace. Navigation, mini-player, and section-rail heights feed a combined clearance used by content and toasts. Returning from the mini-player brings playback into view without changing the document viewport.
## Elevation & Depth
Resting workspace surfaces are flat. Classic disables ambient bleed, grain, blur on navigation and mini-player, hero animation, card entrance animation, and thumbnail hover zoom. The playing row uses a narrow inset accent edge rather than a glow. Dialogs, shortcut panels, and more sheets retain the inherited soft ambient shadow; dark and light shadow values are recorded in the sidecar.
**The Tonal Surface Rule.** Use surface tone and fine dividers for resting depth; reserve the inherited ambient shadow for dialogs and sheets.
## Shapes
Panels and the video stage use the medium radius; fields, chips, action buttons, tabs, and navigation details use the small radius. Thumbnails use the thumbnail radius. Browsing rows have flat corners and a bottom divider. The primary transport remains circular. The section rail rounds only its upper corners; mini-player surfaces remain flat across their width.
## Components
### Buttons
Quiet surface buttons use bg-2 or bg-3 with primary text. The search action changes from bg-3 to accent-deep with white text on hover. Filled list and empty-state actions use accent-deep and white. Circular play uses accent with its dark foreground and changes to accent-bright on hover. Controls keep their established target sizes. Keyboard focus uses an accent outline (2px) with (3px) offset.
### Chips
Suggestion chips use bg-2, primary text, a line-soft border, the small radius, and label typography. Home capability descriptors remain unboxed text rather than duplicating action-chip surfaces.
### Cards / Containers
Media results are divider-separated rows rather than floating cards. Actions stay visible. The playing row uses bg-3 and an inset accent line (2px). Notes, up-next, and related containers use bg-1 and the medium radius; playlist collections keep natural height with no fading overflow mask.
### Inputs / Fields
Search uses bg-1, primary text, the small radius, and a (46px) minimum height. Placeholder text uses text-dim at full opacity and the caret uses accent. Settings fields retain at least (44px) height. Focus receives the shared visible outline.
### Navigation
Sidebar entries have (44px) minimum height, restrained spacing, inline stroked SVG icons (20px), and no decorative leading active marker. Active entries use bg-3 with primary text and an accent icon. Mobile navigation uses a matte bg-1 surface, muted inactive text, and an accent icon in the active entry; safe-area padding and text-scale layout remain part of the component.
### Playback and Mini-player
Playback combines a video stage, centered compact transport, timing, wrapped quick actions, and metadata. The mini-player uses bg-2 with a top line, no blur or shadow, and usable (44px) targets. The section rail and toast placement share the measured bottom clearance. Classic section-rail actions use the same inline stroked SVG vocabulary as navigation; other layouts retain their existing icons.
State transitions inherit the existing short interface timings; the sidecar records the inherited easing and recurring color transition. Explicit reduced motion and the operating-system preference reduce animation and transition durations to (0.001ms), with one animation iteration. The explicit preference also sets automatic scrolling.
## Do's and Don'ts
### Do:
- **Do** keep Classic overrides scoped to the selected Classic layout.
- **Do** use tonal surfaces and fine dividers for workspace hierarchy.
- **Do** preserve light, high contrast, text scale, density, safe areas, and reduced motion.
- **Do** use inline SVG for navigation icons and retain visible keyboard focus.
- **Do** use media thumbnails as user content.
### Don't:
- **Don't** add ambient glow or grain to Classic.
- **Don't** force empty home into the video aspect ratio.
- **Don't** hide row actions until hover or reduce established control targets to fit a crowded layout.
- **Don't** transfer this visual world to other layout families.

74
Dockerfile Normal file
View File

@@ -0,0 +1,74 @@
# ============================================================================
# YT Player PWA — Docker image
#
# Base: oven/bun:1-debian (Bun runtime on Debian slim)
# yt-dlp: downloaded from GitHub releases at build time (stays current)
# libsql: embedded via @libsql/client (no separate DB container needed)
#
# Build: docker compose build
# Run: docker compose up
# ============================================================================
FROM oven/bun:1-debian
# ---- System dependencies ----
# python3 is required by yt-dlp for some extraction paths
# ca-certificates for HTTPS fetches from yt-dlp
# ffmpeg lets yt-dlp merge bestvideo+bestaudio into a single mp4 for the
# "Save before playing" download path (GET /api/download?mux=1)
RUN apt-get update -qq && \
apt-get install -y --no-install-recommends \
curl \
python3 \
ffmpeg \
ca-certificates && \
rm -rf /var/lib/apt/lists/*
# Optional malware scanner for P2P admission (P2P_MALWARE_SCAN=1). Off by
# default: build with --build-arg INSTALL_CLAMAV=1 to include it.
ARG INSTALL_CLAMAV=0
RUN if [ "$INSTALL_CLAMAV" = "1" ]; then \
apt-get update -qq && apt-get install -y --no-install-recommends clamav clamav-freshclam && \
freshclam --quiet || true; rm -rf /var/lib/apt/lists/*; \
fi
# ---- Install yt-dlp ----
RUN curl -fsSL \
https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp \
-o /usr/local/bin/yt-dlp && \
chmod +x /usr/local/bin/yt-dlp
# yt-dlp needs a JS runtime to solve YouTube's "n" challenge. Without one the
# stream URLs it returns are THROTTLED to ~50 KB/s by googlevideo (720p
# playback stalled / fell back to 144p, saves crawled) and some formats go
# missing. Only deno is enabled by default; bun is already in this image, so
# enable it via the system-wide config every yt-dlp invocation reads.
RUN printf -- '--js-runtimes bun:/usr/local/bin/bun\n' > /etc/yt-dlp.conf
WORKDIR /app
# ---- Install Node/Bun deps ----
COPY server/package.json ./
RUN bun install --production
# ---- Copy server source ----
COPY server/ ./
# ---- Copy built frontend (served as static files from ./public) ----
COPY frontend/ ./public/
# ---- Stamp the build time (shown in Settings → About) ----
# Runs after the COPY layers, so any source change produces a fresh stamp
# while a fully-cached (unchanged) build keeps its original one.
RUN date -u +"%Y-%m-%dT%H:%M:%SZ" > /app/build-time.txt
# ---- Persistent data directory (volume-mounted) ----
RUN mkdir -p /app/data
EXPOSE 3000
# Healthcheck — ping the version endpoint
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD curl -sf http://localhost:3000/api/version || exit 1
CMD ["bun", "server.js"]

36
PRODUCT.md Normal file
View File

@@ -0,0 +1,36 @@
# YT Player
<!-- impeccable:product-schema 1 -->
## Platform
web
## Users
People watching videos and listening to music on desktop and mobile. The confirmed Classic brief gives watching and listening equal priority.
## Product Purpose
Search and play YouTube media, organize playlists, and keep saved media available offline. The web PWA and desktop wrappers share the same frontend.
The web home and Search views also recommend familiar favorites and discoveries from server-collected metadata and listening summaries. Metadata and artwork collection cover search results and playlists as well as played videos, independently of media-file caching.
## Capabilities and Constraints
Preserve playback, playlists, queue, lyrics, notes, A–B loops, audio-only mode, offline storage, sharing, and settings. The frontend is plain HTML, CSS, and JavaScript with a Bun/Hono web backend. Classic is the default layout; other layouts share markup and must retain their behavior. Appearance settings include dark, light, contrast, font scale, density, performance, and reduced motion.
## Brand Commitments
Keep the YT Player name and existing factual copy. The approved Classic redesign uses a quiet dark studio direction. Other layout themes remain independent.
## Evidence on Hand
Existing frontend, bundled fonts, local icons, and browser tests. No invented customer claims or production data.
## Product Principles
- Playback and browsing must remain reachable together.
- Mobile browser and installed PWA should offer consistent Classic navigation.
- Empty, populated, and playing states each need an appropriate layout.
- User data and appearance preferences survive theme changes.

33
README.md Normal file → Executable file
View File

@@ -18,6 +18,13 @@ or Node runtime.
- 🎵 **Audio-only mode** — great for music, saves bandwidth - 🎵 **Audio-only mode** — great for music, saves bandwidth
- 📂 **On-device playlists** — create, rename, delete, add/remove videos. Stored - 📂 **On-device playlists** — create, rename, delete, add/remove videos. Stored
locally as JSON; nothing leaves your machine locally as JSON; nothing leaves your machine
- 💾 **Offline cache / preload** — a **Save** button and an **Add to playlist**
button on the now-playing video download a self-contained copy into a permanent
file cache, so it plays instantly and works offline. Videos added to a playlist
are auto-preloaded and kept until you remove them.
- ⚙ **Settings page** — playback defaults (quality, volume, audio-only) plus cache
management: see storage used, toggle auto-preload, and delete cached videos
individually or all at once
- 🕘 **Watch history** - 🕘 **Watch history**
- ⏯ Full controls: seek, volume, playback speed, quality switching, fullscreen, - ⏯ Full controls: seek, volume, playback speed, quality switching, fullscreen,
next/prev, and keyboard shortcuts (`space`, `←/→`, `f`, `m`) next/prev, and keyboard shortcuts (`space`, `←/→`, `f`, `m`)
@@ -57,6 +64,17 @@ The web UI talks to the native side over whichever bridge is present
| `yt.streams { videoId }` | `ytStreams` | `{ ok, data:{ meta, audioUrl, qualities[] } }` | | `yt.streams { videoId }` | `ytStreams` | `{ ok, data:{ meta, audioUrl, qualities[] } }` |
| `store.load {}` | `storeLoad` | playlists / history / settings | | `store.load {}` | `storeLoad` | playlists / history / settings |
| `store.save { data }` | `storeSave` | `{ ok }` | | `store.save { data }` | `storeSave` | `{ ok }` |
| `cache.download { videoId }` | `cache_download` | downloads a single-file copy into the offline cache |
| `cache.status { videoId }` | `cache_status` | `{ ok, cached, path?, size? }` |
| `cache.list {}` | `cache_list` | `{ ok, items:[{id,size,path}], total }` |
| `cache.delete { videoId }` | `cache_delete` | removes one cached file |
| `cache.clear {}` | `cache_clear` | removes all cached files |
> The offline cache is implemented in the **Tauri (Windows)** shell. Files live
> in `<app_cache_dir>/videos/<videoId>.<ext>` and persist until deleted from the
> Settings page. The frontend falls back to live streaming if a cached file is
> missing, and the cache calls degrade gracefully on shells that don't implement
> them.
Because the bridge is size-limited, the Zig handlers parse `yt-dlp`'s large JSON Because the bridge is size-limited, the Zig handlers parse `yt-dlp`'s large JSON
and return only the compact fields the UI needs. and return only the compact fields the UI needs.
@@ -98,6 +116,21 @@ The installer lands in
`src-tauri\target\release\bundle\` (`nsis\*-setup.exe` and `msi\*.msi`). `src-tauri\target\release\bundle\` (`nsis\*-setup.exe` and `msi\*.msi`).
`yt-dlp.exe` is bundled as an app resource, so the installed app is self-contained. `yt-dlp.exe` is bundled as an app resource, so the installed app is self-contained.
### One-shot release
`scripts\release.ps1` does the whole flow — build, copy installers into
`.\releases`, then commit and push through WSL git:
```powershell
pwsh -File scripts\release.ps1
```
To only commit + push from WSL (e.g. after building separately):
```bash
bash scripts/push.sh "your commit message"
```
> Already in WSL and just want it running fast? Your WSL is WSLg-enabled, so you > Already in WSL and just want it running fast? Your WSL is WSLg-enabled, so you
> can instead build the **Linux** (zero-native) target and its window appears on > can instead build the **Linux** (zero-native) target and its window appears on
> your Windows desktop — see [Setup & run](#setup--run). That needs WSL running > your Windows desktop — see [Setup & run](#setup--run). That needs WSL running

0
appicon.png Normal file → Executable file
View File

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

34
docker-compose.beta.yml Normal file
View File

@@ -0,0 +1,34 @@
# Beta stack (beta.worship.hesed.sbs). Separate from prod on purpose: own named
# volumes (no shared DB or media drive), no hardcoded Traefik labels (Dokploy
# injects the domain routing), no lyrics/piano workers.
services:
ytplayer:
build: .
restart: unless-stopped
volumes:
- ytplayer-beta-data:/app/data
environment:
PORT: "3000"
DB_PATH: "/app/data/ytplayer.db"
MEDIA_DIR: "/app/data/media"
UPLOAD_DIR: "/app/data/uploads"
MEDIA_CACHE_MAX_BYTES: "10737418240"
APP_VERSION: "1.0.0-beta"
ADMIN_PASSWORD: "${ADMIN_PASSWORD:-}"
P2P_ENABLED: "${P2P_ENABLED:-0}"
healthcheck:
test: ["CMD", "curl", "-sf", "http://localhost:3000/api/version"]
interval: 30s
timeout: 5s
retries: 3
start_period: 15s
networks:
- dokploy-network
volumes:
ytplayer-beta-data:
driver: local
networks:
dokploy-network:
external: true

137
docker-compose.yml Normal file
View File

@@ -0,0 +1,137 @@
services:
ytplayer:
build: .
restart: unless-stopped
volumes:
# libsql DB file persists across container rebuilds
- ytplayer-data:/app/data
# Bulk media on the homelab's USB drive (/mnt/data, mounted nofail): the
# re-fetchable media cache and the uploads library. The DB, lyrics and
# notes stay on ytplayer-data. If the drive is missing, the marker file
# below is missing too: the cache pauses (playback streams) and uploads
# are served from the nightly backup copy on ytplayer-data.
- /mnt/data/ytplayer:/app/bulk
environment:
PORT: "3000"
PIANO_WORKER_ENABLED: "${PIANO_WORKER_ENABLED:-0}"
PIANO_WORKER_TOKEN: "${PIANO_WORKER_TOKEN:-}"
MEDIA_DIR: "/app/bulk/media"
MEDIA_VOLUME_MARKER: "/app/bulk/.hl-data"
MEDIA_CACHE_MAX_BYTES: "268435456000" # 250 GiB of the 458 GiB drive
MEDIA_MIN_FREE_BYTES: "21474836480" # keep 20 GiB free on the drive
UPLOAD_DIR: "/app/bulk/uploads"
UPLOAD_VOLUME_MARKER: "/app/bulk/.hl-data"
# Second copy on the stable disk, refreshed nightly by
# scripts/ops/uploads-backup.sh on the homelab host; reads fall back to it.
UPLOAD_BACKUP_DIR: "/app/data/uploads-backup"
DB_PATH: "/app/data/ytplayer.db"
APP_VERSION: "1.0.0"
# Unlocks /admin (API tokens, lyric/chapter history + restore). Set it in
# Dokploy's Environment tab — never commit it. Unset = admin disabled.
ADMIN_PASSWORD: "${ADMIN_PASSWORD:-}"
# Phone remote: "1" = a phone may only pair with a screen on the same
# network (same public IP as seen by the server). Off by default.
REMOTE_SAME_NETWORK: "${REMOTE_SAME_NETWORK:-0}"
# Shared secret the lyrics-worker uses to list songs and upload lyrics.
# Set in Dokploy's Environment tab (same value feeds both services).
LYRICS_WORKER_TOKEN: "${LYRICS_WORKER_TOKEN:-}"
# Peer-to-peer sharing (docs/p2p-architecture.md). ON by default.
P2P_ENABLED: "${P2P_ENABLED:-1}"
# Malware scan before a file's hash is admitted. OFF by default; needs an
# image built with INSTALL_CLAMAV=1. Hashing + media validation always run.
P2P_MALWARE_SCAN: "${P2P_MALWARE_SCAN:-0}"
# P2P_STALE_DAYS: "7" # holder shown as stale after this many days unchecked
# P2P_KEEP_MIN_VIEWS: "3" # server keeps copies with ≥ this many views…
# P2P_KEEP_DAYS: "30" # …in this many days
# P2P_KEEP_RECENT_DAYS: "14" # …or played this recently
# P2P_INTAKE_DIR: "/app/data/p2p-intake" # quarantine for device uploads (never served)
# P2P_INTAKE_MAX_BYTES: "3221225472" # 3 GiB
# Optional: force yt-dlp search instead of InnerTube API
# SEARCH_INNERTUBE: "0" # force yt-dlp search
# Optional: override yt-dlp binary path if you mount a custom one
# YTDLP_PATH: "/usr/local/bin/yt-dlp"
# YTDLP_WORKER: "0" # disable the long-lived yt-dlp worker pool
# YTDLP_WORKERS: "2" # pool size
# Server media cache (server/media-cache.js) — defaults shown.
# (MEDIA_DIR / MEDIA_CACHE_MAX_BYTES / MEDIA_MIN_FREE_BYTES set above;
# defaults without them: /app/data/media, 10 GiB, 5 GiB)
# MEDIA_AUTO_MAX_SECONDS: "3600" # longest video auto-cached on play
# MEDIA_TRANSCODE: "1" # 0 disables the compression lane
# MEDIA_CODEC: "hevc" # hevc | h264
# MEDIA_CRF: "28"
# MEDIA_PRESET: "medium"
# MEDIA_THREADS: "2"
# MEDIA_OPT_MAX_SECONDS: "3600" # don't re-encode videos longer than this
healthcheck:
test: ["CMD", "curl", "-sf", "http://localhost:3000/api/version"]
interval: 30s
timeout: 5s
retries: 3
start_period: 15s
networks:
- dokploy-network
- lyrics
labels:
- "traefik.enable=true"
- "traefik.http.routers.ytplayer-http.rule=Host(`worship.hesed.sbs`)"
- "traefik.http.routers.ytplayer-http.entrypoints=web"
- "traefik.http.routers.ytplayer-http.middlewares=redirect-to-https"
- "traefik.http.routers.ytplayer-https.rule=Host(`worship.hesed.sbs`)"
- "traefik.http.routers.ytplayer-https.entrypoints=websecure"
- "traefik.http.routers.ytplayer-https.tls.certresolver=letsencrypt"
- "traefik.http.services.ytplayer-svc.loadbalancer.server.port=3000"
# Handles requested Whisper drafts and transcribes saved songs without lyrics, with
# faster-whisper on CPU (no API keys, no credits). Separate container so it
# never competes with playback/downloads: capped CPU + memory, low priority,
# and it fetches audio from the ytplayer service over the private network.
lyrics-worker:
build: ./scripts/lyrics
restart: unless-stopped
depends_on:
- ytplayer
environment:
YTP_BASE: "http://ytplayer:3000"
YTP_TOKEN: "${LYRICS_WORKER_TOKEN:-}"
WHISPER_MODEL: "large-v3-turbo" # ~1.6 GB download on first start
WHISPER_THREADS: "2"
WATCH_SECONDS: "300"
volumes:
- lyrics-models:/models
- lyrics-state:/data
cpus: "2"
mem_limit: 3g
networks:
- lyrics
# Optional high-fidelity transcription. Never starts without --profile piano.
piano-worker:
profiles: ["piano"]
build: ./scripts/piano
restart: unless-stopped
depends_on: [ytplayer]
environment:
YTP_BASE: "http://ytplayer:3000"
YTP_TOKEN: "${PIANO_WORKER_TOKEN:-}"
PIANO_THREADS: "2"
volumes:
- piano-models:/models
cpus: "2"
mem_limit: 6g
networks: [lyrics]
volumes:
ytplayer-data:
driver: local
piano-models:
driver: local
lyrics-models:
driver: local
lyrics-state:
driver: local
networks:
dokploy-network:
external: true
lyrics:
driver: bridge

View File

@@ -0,0 +1,122 @@
# Lyrics and server analytics
## Whisper drafts
In `/admin#editor`, every song has a Whisper button alongside its Open button.
The loaded song also has **Transcribe with Whisper**. Both enqueue the same
server job; duplicate active requests reuse that job. The existing CPU
faster-whisper container polls explicit requests every ten seconds and returns
a timed draft even when that song already has lyrics. Manual requests always
use Whisper, bypassing LRCLIB.
**Use transcript in editor** loads the draft for review. **Save lyrics** publishes
it through the existing revision history and conflict checks. Until saved,
shared lyrics remain unchanged. Applying a draft can be undone, including the
original sync offset. Queued/running jobs survive restarts; worker leases expire
after two minutes and heartbeat every 25 seconds. After three failed worker
attempts the job reports a failure. Completed/failed drafts are retained for
30 days; cleanup runs when workers report progress.
A YouTube video must already have a ready server media copy; uploads are also
supported. The existing maximum of one hour and 40 MiB audio input applies.
Songs without enough recognized vocals fail visibly. Transcription accuracy
and word timing depend on the singing and audio mix; review before saving.
Deploy the updated server and rebuild the `lyrics-worker` image. Both need the
same `LYRICS_WORKER_TOKEN` (at least 24 characters; compose passes it to the
worker as `YTP_TOKEN`). A configured token permits queuing; the status endpoint
also reports whether a worker has recently polled. No paid transcription API
is involved.
Admin endpoints (admin cookie or API token):
- `POST /api/admin/transcriptions/:video` queues a draft.
- `GET /api/admin/transcriptions/:video` returns the latest draft/progress.
Worker-only endpoints require the worker token:
- `POST /api/lyrics-worker/claim` claims one job.
- `POST /api/lyrics-worker/jobs/:job` reports progress/results with its lease.
## Grouped lyric lines
One lyric cue can contain multiple visual lines with one timestamp. In the
admin editor, **Shift+Enter** inserts a tight line break. On phones, select the
cue and use **Line break** in its options. Ordinary Enter or **Below** adds a
separate cue with its own timing. Both visual lines of a grouped cue highlight
and seek together in service mode, with a smaller internal gap than the space
between cues. The player panel, stage and presenter views also preserve breaks.
Text editing/export uses a continuation prefix to preserve the grouping:
```text
[0:12.00] Because You are God
| You can do anything
[0:18.00] Another separate cue
```
The continuation belongs to the preceding cue. JSON stores its text as
`"Because You are God\nYou can do anything"`. Saving, revisions and text
round trips retain the single timestamp. Reporting a wrong lyric also preserves the grouped text. Existing single-line lyrics work
unchanged.
## Server analytics and metadata collector
Open **Stats** (`/admin#analytics`). It shows cached video and upload totals,
recorded plays, discovery sources, metadata/thumbnail payload sizes, and
available filesystem space for media, uploads and the database. Paths on the
same device share their free space; their capacities must not be added.
Media totals come from library records and exclude temporary files and
filesystem overhead. Metadata bytes exclude indexes and SQLite overhead.
The collector accepts a search, a total unique-video limit (1–500), and depth:
- **0:** only the specified search.
- **1:** also search channels and tags found in its results.
- **2/3:** follow up to two/three related rounds.
The total limit applies across every round. The collector reserves result
budget for deeper rounds, deduplicates video IDs and related queries, and stops
after at most 24 searches. Duplicate, unavailable or empty results can produce
fewer videos than requested. Up to three collections may be queued/running;
one executes at a time per server. Atomic ownership leases prevent two
servers from claiming the same job. Progress is saved after each discovery
batch and video. An expired interrupted job resumes its pending items.
**Stop collection** cancels future work; an extraction already in progress
can finish its network request before the cancellation is observed.
Discovery cards enter the same catalog used for recommendations. Each video
is then enriched through yt-dlp without downloading media. The server stores
full descriptive fields (including descriptions, dates, engagement counts,
language, tags, chapters, thumbnail variants and format specifications) in
`video_details`. Expiring media URLs and request headers are excluded. Details
are capped at 500 KB per video and follow catalog eviction. Thumbnail image
bytes use the existing durable thumbnail queue, host restrictions and budget
(default 512 MiB). Failures stay visible in job history; successful cards remain
stored even when enrichment fails. Refresh analytics to update the aggregate
numbers after collection; job progress polls automatically while this tab is
open.
The metadata library supports title/channel/tag filtering, 50-row pages and a
raw descriptive metadata view. Admin cookie or API token is required for:
- `GET /api/admin/analytics`
- `GET /api/admin/metadata?q=...&offset=...`
- `GET /api/admin/metadata/:id`
- `GET /api/admin/collections`
- `POST /api/admin/collections` with `{query,maxVideos,depth}`
- `POST /api/admin/collections/:id/cancel`
## Verification
Run `bun run test` in `server`, `npm test` at the repo root,
`python3 -m unittest discover -s scripts/lyrics -p test_auto_lyrics.py`, and
`npx playwright test -c playwright.admin.config.js`. Admin browser fixtures
cover Whisper review/save/undo, unsaved edits, failures, mobile actions,
grouped cues and service highlighting, and analytics collector controls.
Design review fixed the primary action’s white-on-gradient contrast by using a
solid purple fill, and fixed tablet navigation overflow. No new findings were
suppressed. Existing admin play/tap gradient contrast and decorative glow
findings remain outside these controls. Real viewport captures passed the
mobile dashboard/collector and desktop visual checks.

View File

@@ -0,0 +1,22 @@
# Classic redesign verification
## Scope
Classic's responsive web UI, including desktop, mobile browser and simulated installed-PWA navigation. Synthetic playlist/media metadata was used for browser checks and screenshots; no production profiles or playlists were changed. No deployment was performed.
## Automated checks
- `npx playwright test --config playwright.classic.config.js`: 11 passed. Covers empty home at 320/390/768/1024/1280/1440px, navigation during a populated player state, mini-player return, advanced controls, theme switching, rotation, extra-large text at 320px, and cached Classic CSS on offline reload.
- `node --test --test-isolation=none frontend/*.test.js`: 72 passed after rebasing onto the latest remote changes (65 passed before the rebase). Explicitly disabling process isolation exposes individual test results in this environment; the default isolated runner initially reported only nine file-level passes. The latest suite ran outside the sandbox because the WebAssembly fallback test spawns Node.
- Existing portrait-PWA, viewport-anchor and fullscreen smoke tests run in Chromium: 9 passed, 4 failed. The same tests against unchanged HEAD frontend assets produced the identical 9/4 result. The four baseline failures are the fullscreen fallback/audio-only expectations and the portrait rotation/wide layout checks that expect the empty-home list pane to be visible.
- `node --check frontend/app.js` and `git diff --check` passed.
## Visual evidence
Local browser captures live under `.impeccable/review/` (ignored build evidence): desktop/mobile player and empty home, mobile playlists and settings, desktop light appearance, and a 320px phone with extra-large text. They use labeled synthetic preview artwork. The final capture pass measured no main-pane or control-deck horizontal overflow and an app height equal to the viewport for every captured size.
Impeccable's detector ran once against the changed UI targets. Its findings refer to the shared index and inherited styling, including other themes; the report is not proof of active Classic contrast or full accessibility conformance. The independent reviewer requested SVG section shortcuts and readable footer captions. Both fixes were confirmed resolved with a `ship` verdict covering the scored fixes, recorded in `.impeccable/review/finish-review.md`. The replacement reviewer inspected local captures directly after the external vision tool stalled; the original reviewer had stopped at a usage limit.
## Limits
No real iOS/Android device or WebKit browser run was available. Media fixture checks validate layout/navigation, not a live YouTube stream, audio synchronization, or native fullscreen. Other layout themes retain their styles; regression checks cover switching and data preservation, not exhaustive visual audits of every theme.

44
docs/deferred-ideas.md Normal file
View File

@@ -0,0 +1,44 @@
# Deferred ideas
Parked on purpose; nothing here is built.
## Cloudflare Worker as a YouTube fetch fallback (deferred 2026-10-01)
Idea: a free Cloudflare Worker (e.g. https://gist.github.com/hizkifw/ae229eb0c5ff809fc2a4a88735bfd604)
that fetches the watch page, decodes the signature cipher and streams a chosen
`itag`, so downloads come from somewhere other than the server's single IP.
Why it was not adopted yet (read from the gist, never deployed or tested):
- The fetch still happens from Cloudflare's datacenter egress, which YouTube
often challenges or blocks; the IP is shared with every other Worker.
- It uses the old watch-page + cipher approach (ytdl-core). No PO tokens, no
throttle handling, adaptive formats only, so it breaks as YouTube changes.
- Free tier CPU (~10 ms/request, check current limits) may not cover decoding
the player script, and proxying large media may breach Cloudflare's terms.
- Stream URLs are bound to the fetching IP, so the Worker has to relay the
bytes itself.
If revisited: deploy with `wrangler`, test ~10 real videos, and if it works add
it as the last tier behind an env var (`YT_WORKER_URL`): server cache → server
yt-dlp → Worker, with the result going through `validateMedia`. A newer Worker
could use the Android/iOS client endpoints (no cipher) but hits the same IP and
token blocks.
## Device-side download (Android app) (deferred 2026-10-01)
A web page cannot fetch googlevideo.com (CORS, PO tokens), and a yt-dlp WASM
build does not change that. The workable route is an Android app that runs
yt-dlp (or an equivalent extractor) on the phone's own IP, checks the server
cache first, then uploads the finished file in the background through the
device intake (`POST /api/p2p/intake`, `server/p2p-intake.js`). The server's
yt-dlp stays as the fallback when the device fails.
## Client-side video editing with ffmpeg.wasm (deferred 2026-10-02)
Skipped on purpose. ffmpeg.wasm is about 25–30 MB, and fast (multi-threaded)
use needs cross-origin isolation (COOP/COEP). That would break the YouTube
thumbnails and avatars unless every image host sends CORP headers, and we do not
control `i.ytimg.com` / `ggpht.com`. The server already trims video (edit & download
runs ffmpeg there), so the browser gains nothing it needs. Revisit only if offline
editing becomes a requirement; then load it lazily from a worker and measure the
isolation fallout first.

View File

@@ -0,0 +1,904 @@
{
"title": "YT Player \u2014 Framework7 Swipe (contrast)",
"brief": "Ad-free YouTube/worship player PWA. Framework7 iOS-style layout with swipe gestures, built on the app's own tokens.",
"frame": "phone",
"platform": "web",
"paletteKey": "coral",
"theme": {
"dark": true,
"bothModes": false,
"contrast": "high",
"shape": "rounded",
"font": "system",
"emphasized": false,
"motion": "expressive"
},
"frames": [
{
"id": "search",
"name": "Search",
"x": 0,
"y": 0,
"note": "Home + search results. Big title, rounded search field, results as an inset grouped list.",
"swipe": {
"left": "queue"
}
},
{
"id": "queue",
"name": "Queue",
"x": 492,
"y": 0,
"note": "Queued songs. Swipe a row left for Playlist/Remove (long swipe removes), right for Queue. Swipe sideways on empty space to change tab.",
"swipe": {
"right": "search"
}
},
{
"id": "player",
"name": "Now playing",
"x": 984,
"y": 0,
"note": "Video on top, Apple Music\u2013style transport, icon action row. Swipe down to collapse to the mini player.",
"swipe": {
"down": "queue"
}
},
{
"id": "upnext",
"name": "Up next",
"x": 1476,
"y": 0,
"note": "Bottom sheet opened by swiping up on the mini player. Half height, drag up for full, down to close."
},
{
"id": "fullscreen",
"name": "Fullscreen",
"x": 1968,
"y": 0,
"note": "Edge-to-edge video (Fill by default). Minimal icon-only controls over a soft bottom gradient; auto-hide.",
"bg": "inverseSurface"
}
],
"groups": [
{
"id": "g2",
"x": 0,
"y": 0,
"axis": "x",
"items": [
{
"id": "i1",
"kind": "topAppBar",
"label": "Search",
"icon": "menu",
"variant": "filled",
"icon2": "directions_car",
"note": "Translucent navbar; menu opens the sidebar (also left-edge swipe)."
}
]
},
{
"id": "g4",
"x": 16,
"y": 96,
"axis": "x",
"items": [
{
"id": "i3",
"kind": "searchBar",
"label": "Search YouTube",
"icon": null,
"variant": "filled",
"icon2": "mic",
"note": "Rounded F7 searchbar with inline mic; Enter searches."
}
]
},
{
"id": "g8",
"x": 16,
"y": 164,
"axis": "x",
"items": [
{
"id": "i5",
"kind": "chip",
"label": "lofi beats",
"icon": null,
"variant": "filled"
},
{
"id": "i6",
"kind": "chip",
"label": "live news",
"icon": null,
"variant": "filled"
},
{
"id": "i7",
"kind": "chip",
"label": "worship",
"icon": null,
"variant": "filled"
}
]
},
{
"id": "g10",
"x": 16,
"y": 212,
"axis": "x",
"items": [
{
"id": "i9",
"kind": "text",
"label": "Results",
"icon": null,
"variant": "filled",
"size": 28,
"bold": true
}
]
},
{
"id": "g15",
"x": 16,
"y": 260,
"axis": "y",
"items": [
{
"id": "i11",
"kind": "listItem",
"label": "Goodness of God",
"icon": "smart_display",
"variant": "filled",
"supporting": "Bethel Music \u00b7 5:12",
"icon2": "more_horiz",
"action": {
"to": "player",
"transition": "slide"
}
},
{
"id": "i12",
"kind": "listItem",
"label": "Way Maker",
"icon": "smart_display",
"variant": "filled",
"supporting": "Leeland \u00b7 3:12",
"icon2": "more_horiz",
"action": {
"to": "player",
"transition": "slide"
}
},
{
"id": "i13",
"kind": "listItem",
"label": "Build My Life",
"icon": "smart_display",
"variant": "filled",
"supporting": "Housefires \u00b7 6:04",
"icon2": "more_horiz",
"action": {
"to": "player",
"transition": "slide"
}
},
{
"id": "i14",
"kind": "listItem",
"label": "Graves Into Gardens",
"icon": "smart_display",
"variant": "filled",
"supporting": "Elevation \u00b7 6:41",
"icon2": "more_horiz",
"action": {
"to": "player",
"transition": "slide"
}
}
]
},
{
"id": "g17",
"x": 16,
"y": 700,
"axis": "x",
"items": [
{
"id": "i16",
"kind": "listItem",
"label": "Way Maker",
"icon": "music_note",
"variant": "tonal",
"supporting": "Leeland \u00b7 3:12",
"icon2": "play_arrow",
"action": {
"to": "player",
"transition": "slideUp"
},
"note": "Floating glass mini player. Tap opens the player, swipe left/right = next/previous, swipe up = Up next sheet."
}
]
},
{
"id": "g19",
"x": 0,
"y": 788,
"axis": "x",
"items": [
{
"id": "i18",
"kind": "bottomNav",
"label": "",
"icon": null,
"variant": "filled",
"tabs": [
{
"icon": "search",
"label": "Search"
},
{
"icon": "queue_music",
"label": "Queue"
},
{
"icon": "history",
"label": "History"
},
{
"icon": "download_done",
"label": "Saved"
},
{
"icon": "more_horiz",
"label": "More"
}
],
"selected": 0,
"actions": {
"tab:0": {
"to": "search",
"transition": "fade"
},
"tab:1": {
"to": "queue",
"transition": "fade"
}
},
"note": "Translucent blurred tab bar; badge on Queue."
}
]
},
{
"id": "g21",
"x": 492,
"y": 0,
"axis": "x",
"items": [
{
"id": "i20",
"kind": "topAppBar",
"label": "Queue",
"icon": "menu",
"variant": "filled",
"icon2": "checklist"
}
]
},
{
"id": "g24",
"x": 508,
"y": 96,
"axis": "x",
"items": [
{
"id": "i22",
"kind": "button",
"label": "Play queue",
"icon": "play_arrow",
"variant": "filled",
"size": 182
},
{
"id": "i23",
"kind": "button",
"label": "Clear",
"icon": "clear_all",
"variant": "tonal",
"size": 182
}
]
},
{
"id": "g29",
"x": 508,
"y": 168,
"axis": "y",
"items": [
{
"id": "i25",
"kind": "listItem",
"label": "Way Maker",
"icon": "smart_display",
"variant": "filled",
"supporting": "Leeland \u00b7 3:12",
"icon2": "drag_handle",
"note": "Swipe right \u2192 Queue (accent action)."
},
{
"id": "i26",
"kind": "listItem",
"label": "Build My Life",
"icon": "smart_display",
"variant": "filled",
"supporting": "Housefires \u00b7 6:04",
"icon2": "drag_handle",
"note": "Swipe left \u2192 Playlist + Remove pills."
},
{
"id": "i27",
"kind": "listItem",
"label": "Graves Into Gardens",
"icon": "smart_display",
"variant": "filled",
"supporting": "Elevation \u00b7 6:41",
"icon2": "drag_handle",
"note": "Long swipe left removes the row."
},
{
"id": "i28",
"kind": "listItem",
"label": "Goodness of God",
"icon": "smart_display",
"variant": "filled",
"supporting": "Bethel Music \u00b7 5:12",
"icon2": "drag_handle",
"note": ""
}
]
},
{
"id": "g32",
"x": 508,
"y": 480,
"axis": "x",
"items": [
{
"id": "i30",
"kind": "button",
"label": "Playlist",
"icon": "playlist_add",
"variant": "tonal"
},
{
"id": "i31",
"kind": "button",
"label": "Remove",
"icon": "delete",
"variant": "filled"
}
]
},
{
"id": "g34",
"x": 508,
"y": 548,
"axis": "x",
"items": [
{
"id": "i33",
"kind": "text",
"label": "Swipe actions revealed (example row)",
"icon": null,
"variant": "filled",
"size": 14
}
]
},
{
"id": "g36",
"x": 508,
"y": 700,
"axis": "x",
"items": [
{
"id": "i35",
"kind": "listItem",
"label": "Way Maker",
"icon": "music_note",
"variant": "tonal",
"supporting": "Leeland \u00b7 3:12",
"icon2": "play_arrow",
"action": {
"to": "player",
"transition": "slideUp"
},
"note": "Floating glass mini player. Tap opens the player, swipe left/right = next/previous, swipe up = Up next sheet."
}
]
},
{
"id": "g38",
"x": 492,
"y": 788,
"axis": "x",
"items": [
{
"id": "i37",
"kind": "bottomNav",
"label": "",
"icon": null,
"variant": "filled",
"tabs": [
{
"icon": "search",
"label": "Search"
},
{
"icon": "queue_music",
"label": "Queue"
},
{
"icon": "history",
"label": "History"
},
{
"icon": "download_done",
"label": "Saved"
},
{
"icon": "more_horiz",
"label": "More"
}
],
"selected": 1,
"actions": {
"tab:0": {
"to": "search",
"transition": "fade"
},
"tab:1": {
"to": "queue",
"transition": "fade"
}
},
"note": "Translucent blurred tab bar; badge on Queue."
}
]
},
{
"id": "g40",
"x": 984,
"y": 0,
"axis": "x",
"items": [
{
"id": "i39",
"kind": "topAppBar",
"label": "Now playing",
"icon": "keyboard_arrow_down",
"variant": "filled",
"icon2": "more_horiz",
"actions": {
"icon": {
"to": "back",
"transition": "slideDown"
}
}
}
]
},
{
"id": "g42",
"x": 984,
"y": 88,
"axis": "x",
"items": [
{
"id": "i41",
"kind": "image",
"label": "",
"icon": null,
"variant": "filled",
"size": 412,
"note": "16:9 video stage; the fullscreen button opens Fullscreen."
}
]
},
{
"id": "g44",
"x": 1000,
"y": 320,
"axis": "x",
"items": [
{
"id": "i43",
"kind": "text",
"label": "Way Maker",
"icon": null,
"variant": "filled",
"size": 24,
"bold": true
}
]
},
{
"id": "g46",
"x": 1000,
"y": 356,
"axis": "x",
"items": [
{
"id": "i45",
"kind": "text",
"label": "Leeland",
"icon": null,
"variant": "filled",
"size": 16
}
]
},
{
"id": "g48",
"x": 1000,
"y": 396,
"axis": "x",
"items": [
{
"id": "i47",
"kind": "slider",
"label": "",
"icon": null,
"variant": "filled",
"value": 35,
"note": "Thin seek track, accent fill."
}
]
},
{
"id": "g54",
"x": 1048,
"y": 456,
"axis": "x",
"items": [
{
"id": "i49",
"kind": "iconButton",
"label": "",
"icon": "skip_previous",
"variant": "text"
},
{
"id": "i50",
"kind": "iconButton",
"label": "",
"icon": "replay_10",
"variant": "text"
},
{
"id": "i51",
"kind": "iconButton",
"label": "",
"icon": "play_arrow",
"variant": "filled"
},
{
"id": "i52",
"kind": "iconButton",
"label": "",
"icon": "forward_10",
"variant": "text"
},
{
"id": "i53",
"kind": "iconButton",
"label": "",
"icon": "skip_next",
"variant": "text"
}
]
},
{
"id": "g61",
"x": 1024,
"y": 540,
"axis": "x",
"items": [
{
"id": "i55",
"kind": "iconButton",
"label": "",
"icon": "playlist_add",
"variant": "text"
},
{
"id": "i56",
"kind": "iconButton",
"label": "",
"icon": "download",
"variant": "text"
},
{
"id": "i57",
"kind": "iconButton",
"label": "",
"icon": "lyrics",
"variant": "text"
},
{
"id": "i58",
"kind": "iconButton",
"label": "",
"icon": "share",
"variant": "text"
},
{
"id": "i59",
"kind": "iconButton",
"label": "",
"icon": "fullscreen",
"variant": "text",
"action": {
"to": "fullscreen",
"transition": "expand"
}
},
{
"id": "i60",
"kind": "iconButton",
"label": "",
"icon": "more_horiz",
"variant": "text"
}
]
},
{
"id": "g63",
"x": 984,
"y": 788,
"axis": "x",
"items": [
{
"id": "i62",
"kind": "bottomNav",
"label": "",
"icon": null,
"variant": "filled",
"tabs": [
{
"icon": "search",
"label": "Search"
},
{
"icon": "queue_music",
"label": "Queue"
},
{
"icon": "history",
"label": "History"
},
{
"icon": "download_done",
"label": "Saved"
},
{
"icon": "more_horiz",
"label": "More"
}
],
"selected": 1,
"actions": {
"tab:0": {
"to": "search",
"transition": "fade"
},
"tab:1": {
"to": "queue",
"transition": "fade"
}
},
"note": "Translucent blurred tab bar; badge on Queue."
}
]
},
{
"id": "g65",
"x": 1476,
"y": 0,
"axis": "x",
"items": [
{
"id": "i64",
"kind": "topAppBar",
"label": "Queue",
"icon": "menu",
"variant": "filled"
}
]
},
{
"id": "g67",
"x": 1476,
"y": 380,
"axis": "x",
"items": [
{
"id": "i66",
"kind": "box",
"label": "",
"icon": null,
"variant": "filled",
"size": 412,
"size2": 512,
"checked": true,
"fill": "surfaceContainerHigh",
"note": "F7 sheet with grab handle; backdrop tap closes."
}
]
},
{
"id": "g69",
"x": 1492,
"y": 404,
"axis": "x",
"items": [
{
"id": "i68",
"kind": "text",
"label": "Up next",
"icon": null,
"variant": "filled",
"size": 20,
"bold": true
}
]
},
{
"id": "g73",
"x": 1492,
"y": 448,
"axis": "y",
"items": [
{
"id": "i70",
"kind": "listItem",
"label": "Build My Life",
"icon": "smart_display",
"variant": "filled",
"supporting": "Housefires \u00b7 6:04",
"action": {
"to": "player",
"transition": "fade"
}
},
{
"id": "i71",
"kind": "listItem",
"label": "Graves Into Gardens",
"icon": "smart_display",
"variant": "filled",
"supporting": "Elevation \u00b7 6:41",
"action": {
"to": "player",
"transition": "fade"
}
},
{
"id": "i72",
"kind": "listItem",
"label": "Goodness of God",
"icon": "smart_display",
"variant": "filled",
"supporting": "Bethel Music \u00b7 5:12",
"action": {
"to": "player",
"transition": "fade"
}
}
]
},
{
"id": "g75",
"x": 1968,
"y": 0,
"axis": "x",
"items": [
{
"id": "i74",
"kind": "box",
"label": "",
"icon": null,
"variant": "filled",
"size": 412,
"size2": 892,
"fill": "inverseSurface",
"note": "Video fills the screen (object-fit cover). Fit/Fill toggle in the controls."
}
]
},
{
"id": "g77",
"x": 1984,
"y": 24,
"axis": "x",
"items": [
{
"id": "i76",
"kind": "text",
"label": "Way Maker \u2014 Leeland",
"icon": null,
"variant": "filled",
"size": 14
}
]
},
{
"id": "g79",
"x": 2316,
"y": 12,
"axis": "x",
"items": [
{
"id": "i78",
"kind": "iconButton",
"label": "",
"icon": "fullscreen_exit",
"variant": "text",
"action": {
"to": "player",
"transition": "fade"
}
}
]
},
{
"id": "g81",
"x": 1984,
"y": 790,
"axis": "x",
"items": [
{
"id": "i80",
"kind": "slider",
"label": "",
"icon": null,
"variant": "filled",
"value": 35
}
]
},
{
"id": "g85",
"x": 1984,
"y": 828,
"axis": "x",
"items": [
{
"id": "i82",
"kind": "iconButton",
"label": "",
"icon": "pause",
"variant": "text"
},
{
"id": "i83",
"kind": "iconButton",
"label": "",
"icon": "screen_rotation",
"variant": "text"
},
{
"id": "i84",
"kind": "iconButton",
"label": "",
"icon": "fit_screen",
"variant": "text",
"note": "Fit \u2194 Fill."
}
]
}
]
}

View File

@@ -0,0 +1,904 @@
{
"title": "YT Player \u2014 Framework7 Swipe (dark)",
"brief": "Ad-free YouTube/worship player PWA. Framework7 iOS-style layout with swipe gestures, built on the app's own tokens.",
"frame": "phone",
"platform": "web",
"paletteKey": "coral",
"theme": {
"dark": true,
"bothModes": true,
"contrast": "standard",
"shape": "rounded",
"font": "system",
"emphasized": false,
"motion": "expressive"
},
"frames": [
{
"id": "search",
"name": "Search",
"x": 0,
"y": 0,
"note": "Home + search results. Big title, rounded search field, results as an inset grouped list.",
"swipe": {
"left": "queue"
}
},
{
"id": "queue",
"name": "Queue",
"x": 492,
"y": 0,
"note": "Queued songs. Swipe a row left for Playlist/Remove (long swipe removes), right for Queue. Swipe sideways on empty space to change tab.",
"swipe": {
"right": "search"
}
},
{
"id": "player",
"name": "Now playing",
"x": 984,
"y": 0,
"note": "Video on top, Apple Music\u2013style transport, icon action row. Swipe down to collapse to the mini player.",
"swipe": {
"down": "queue"
}
},
{
"id": "upnext",
"name": "Up next",
"x": 1476,
"y": 0,
"note": "Bottom sheet opened by swiping up on the mini player. Half height, drag up for full, down to close."
},
{
"id": "fullscreen",
"name": "Fullscreen",
"x": 1968,
"y": 0,
"note": "Edge-to-edge video (Fill by default). Minimal icon-only controls over a soft bottom gradient; auto-hide.",
"bg": "inverseSurface"
}
],
"groups": [
{
"id": "g2",
"x": 0,
"y": 0,
"axis": "x",
"items": [
{
"id": "i1",
"kind": "topAppBar",
"label": "Search",
"icon": "menu",
"variant": "filled",
"icon2": "directions_car",
"note": "Translucent navbar; menu opens the sidebar (also left-edge swipe)."
}
]
},
{
"id": "g4",
"x": 16,
"y": 96,
"axis": "x",
"items": [
{
"id": "i3",
"kind": "searchBar",
"label": "Search YouTube",
"icon": null,
"variant": "filled",
"icon2": "mic",
"note": "Rounded F7 searchbar with inline mic; Enter searches."
}
]
},
{
"id": "g8",
"x": 16,
"y": 164,
"axis": "x",
"items": [
{
"id": "i5",
"kind": "chip",
"label": "lofi beats",
"icon": null,
"variant": "filled"
},
{
"id": "i6",
"kind": "chip",
"label": "live news",
"icon": null,
"variant": "filled"
},
{
"id": "i7",
"kind": "chip",
"label": "worship",
"icon": null,
"variant": "filled"
}
]
},
{
"id": "g10",
"x": 16,
"y": 212,
"axis": "x",
"items": [
{
"id": "i9",
"kind": "text",
"label": "Results",
"icon": null,
"variant": "filled",
"size": 28,
"bold": true
}
]
},
{
"id": "g15",
"x": 16,
"y": 260,
"axis": "y",
"items": [
{
"id": "i11",
"kind": "listItem",
"label": "Goodness of God",
"icon": "smart_display",
"variant": "filled",
"supporting": "Bethel Music \u00b7 5:12",
"icon2": "more_horiz",
"action": {
"to": "player",
"transition": "slide"
}
},
{
"id": "i12",
"kind": "listItem",
"label": "Way Maker",
"icon": "smart_display",
"variant": "filled",
"supporting": "Leeland \u00b7 3:12",
"icon2": "more_horiz",
"action": {
"to": "player",
"transition": "slide"
}
},
{
"id": "i13",
"kind": "listItem",
"label": "Build My Life",
"icon": "smart_display",
"variant": "filled",
"supporting": "Housefires \u00b7 6:04",
"icon2": "more_horiz",
"action": {
"to": "player",
"transition": "slide"
}
},
{
"id": "i14",
"kind": "listItem",
"label": "Graves Into Gardens",
"icon": "smart_display",
"variant": "filled",
"supporting": "Elevation \u00b7 6:41",
"icon2": "more_horiz",
"action": {
"to": "player",
"transition": "slide"
}
}
]
},
{
"id": "g17",
"x": 16,
"y": 700,
"axis": "x",
"items": [
{
"id": "i16",
"kind": "listItem",
"label": "Way Maker",
"icon": "music_note",
"variant": "tonal",
"supporting": "Leeland \u00b7 3:12",
"icon2": "play_arrow",
"action": {
"to": "player",
"transition": "slideUp"
},
"note": "Floating glass mini player. Tap opens the player, swipe left/right = next/previous, swipe up = Up next sheet."
}
]
},
{
"id": "g19",
"x": 0,
"y": 788,
"axis": "x",
"items": [
{
"id": "i18",
"kind": "bottomNav",
"label": "",
"icon": null,
"variant": "filled",
"tabs": [
{
"icon": "search",
"label": "Search"
},
{
"icon": "queue_music",
"label": "Queue"
},
{
"icon": "history",
"label": "History"
},
{
"icon": "download_done",
"label": "Saved"
},
{
"icon": "more_horiz",
"label": "More"
}
],
"selected": 0,
"actions": {
"tab:0": {
"to": "search",
"transition": "fade"
},
"tab:1": {
"to": "queue",
"transition": "fade"
}
},
"note": "Translucent blurred tab bar; badge on Queue."
}
]
},
{
"id": "g21",
"x": 492,
"y": 0,
"axis": "x",
"items": [
{
"id": "i20",
"kind": "topAppBar",
"label": "Queue",
"icon": "menu",
"variant": "filled",
"icon2": "checklist"
}
]
},
{
"id": "g24",
"x": 508,
"y": 96,
"axis": "x",
"items": [
{
"id": "i22",
"kind": "button",
"label": "Play queue",
"icon": "play_arrow",
"variant": "filled",
"size": 182
},
{
"id": "i23",
"kind": "button",
"label": "Clear",
"icon": "clear_all",
"variant": "tonal",
"size": 182
}
]
},
{
"id": "g29",
"x": 508,
"y": 168,
"axis": "y",
"items": [
{
"id": "i25",
"kind": "listItem",
"label": "Way Maker",
"icon": "smart_display",
"variant": "filled",
"supporting": "Leeland \u00b7 3:12",
"icon2": "drag_handle",
"note": "Swipe right \u2192 Queue (accent action)."
},
{
"id": "i26",
"kind": "listItem",
"label": "Build My Life",
"icon": "smart_display",
"variant": "filled",
"supporting": "Housefires \u00b7 6:04",
"icon2": "drag_handle",
"note": "Swipe left \u2192 Playlist + Remove pills."
},
{
"id": "i27",
"kind": "listItem",
"label": "Graves Into Gardens",
"icon": "smart_display",
"variant": "filled",
"supporting": "Elevation \u00b7 6:41",
"icon2": "drag_handle",
"note": "Long swipe left removes the row."
},
{
"id": "i28",
"kind": "listItem",
"label": "Goodness of God",
"icon": "smart_display",
"variant": "filled",
"supporting": "Bethel Music \u00b7 5:12",
"icon2": "drag_handle",
"note": ""
}
]
},
{
"id": "g32",
"x": 508,
"y": 480,
"axis": "x",
"items": [
{
"id": "i30",
"kind": "button",
"label": "Playlist",
"icon": "playlist_add",
"variant": "tonal"
},
{
"id": "i31",
"kind": "button",
"label": "Remove",
"icon": "delete",
"variant": "filled"
}
]
},
{
"id": "g34",
"x": 508,
"y": 548,
"axis": "x",
"items": [
{
"id": "i33",
"kind": "text",
"label": "Swipe actions revealed (example row)",
"icon": null,
"variant": "filled",
"size": 14
}
]
},
{
"id": "g36",
"x": 508,
"y": 700,
"axis": "x",
"items": [
{
"id": "i35",
"kind": "listItem",
"label": "Way Maker",
"icon": "music_note",
"variant": "tonal",
"supporting": "Leeland \u00b7 3:12",
"icon2": "play_arrow",
"action": {
"to": "player",
"transition": "slideUp"
},
"note": "Floating glass mini player. Tap opens the player, swipe left/right = next/previous, swipe up = Up next sheet."
}
]
},
{
"id": "g38",
"x": 492,
"y": 788,
"axis": "x",
"items": [
{
"id": "i37",
"kind": "bottomNav",
"label": "",
"icon": null,
"variant": "filled",
"tabs": [
{
"icon": "search",
"label": "Search"
},
{
"icon": "queue_music",
"label": "Queue"
},
{
"icon": "history",
"label": "History"
},
{
"icon": "download_done",
"label": "Saved"
},
{
"icon": "more_horiz",
"label": "More"
}
],
"selected": 1,
"actions": {
"tab:0": {
"to": "search",
"transition": "fade"
},
"tab:1": {
"to": "queue",
"transition": "fade"
}
},
"note": "Translucent blurred tab bar; badge on Queue."
}
]
},
{
"id": "g40",
"x": 984,
"y": 0,
"axis": "x",
"items": [
{
"id": "i39",
"kind": "topAppBar",
"label": "Now playing",
"icon": "keyboard_arrow_down",
"variant": "filled",
"icon2": "more_horiz",
"actions": {
"icon": {
"to": "back",
"transition": "slideDown"
}
}
}
]
},
{
"id": "g42",
"x": 984,
"y": 88,
"axis": "x",
"items": [
{
"id": "i41",
"kind": "image",
"label": "",
"icon": null,
"variant": "filled",
"size": 412,
"note": "16:9 video stage; the fullscreen button opens Fullscreen."
}
]
},
{
"id": "g44",
"x": 1000,
"y": 320,
"axis": "x",
"items": [
{
"id": "i43",
"kind": "text",
"label": "Way Maker",
"icon": null,
"variant": "filled",
"size": 24,
"bold": true
}
]
},
{
"id": "g46",
"x": 1000,
"y": 356,
"axis": "x",
"items": [
{
"id": "i45",
"kind": "text",
"label": "Leeland",
"icon": null,
"variant": "filled",
"size": 16
}
]
},
{
"id": "g48",
"x": 1000,
"y": 396,
"axis": "x",
"items": [
{
"id": "i47",
"kind": "slider",
"label": "",
"icon": null,
"variant": "filled",
"value": 35,
"note": "Thin seek track, accent fill."
}
]
},
{
"id": "g54",
"x": 1048,
"y": 456,
"axis": "x",
"items": [
{
"id": "i49",
"kind": "iconButton",
"label": "",
"icon": "skip_previous",
"variant": "text"
},
{
"id": "i50",
"kind": "iconButton",
"label": "",
"icon": "replay_10",
"variant": "text"
},
{
"id": "i51",
"kind": "iconButton",
"label": "",
"icon": "play_arrow",
"variant": "filled"
},
{
"id": "i52",
"kind": "iconButton",
"label": "",
"icon": "forward_10",
"variant": "text"
},
{
"id": "i53",
"kind": "iconButton",
"label": "",
"icon": "skip_next",
"variant": "text"
}
]
},
{
"id": "g61",
"x": 1024,
"y": 540,
"axis": "x",
"items": [
{
"id": "i55",
"kind": "iconButton",
"label": "",
"icon": "playlist_add",
"variant": "text"
},
{
"id": "i56",
"kind": "iconButton",
"label": "",
"icon": "download",
"variant": "text"
},
{
"id": "i57",
"kind": "iconButton",
"label": "",
"icon": "lyrics",
"variant": "text"
},
{
"id": "i58",
"kind": "iconButton",
"label": "",
"icon": "share",
"variant": "text"
},
{
"id": "i59",
"kind": "iconButton",
"label": "",
"icon": "fullscreen",
"variant": "text",
"action": {
"to": "fullscreen",
"transition": "expand"
}
},
{
"id": "i60",
"kind": "iconButton",
"label": "",
"icon": "more_horiz",
"variant": "text"
}
]
},
{
"id": "g63",
"x": 984,
"y": 788,
"axis": "x",
"items": [
{
"id": "i62",
"kind": "bottomNav",
"label": "",
"icon": null,
"variant": "filled",
"tabs": [
{
"icon": "search",
"label": "Search"
},
{
"icon": "queue_music",
"label": "Queue"
},
{
"icon": "history",
"label": "History"
},
{
"icon": "download_done",
"label": "Saved"
},
{
"icon": "more_horiz",
"label": "More"
}
],
"selected": 1,
"actions": {
"tab:0": {
"to": "search",
"transition": "fade"
},
"tab:1": {
"to": "queue",
"transition": "fade"
}
},
"note": "Translucent blurred tab bar; badge on Queue."
}
]
},
{
"id": "g65",
"x": 1476,
"y": 0,
"axis": "x",
"items": [
{
"id": "i64",
"kind": "topAppBar",
"label": "Queue",
"icon": "menu",
"variant": "filled"
}
]
},
{
"id": "g67",
"x": 1476,
"y": 380,
"axis": "x",
"items": [
{
"id": "i66",
"kind": "box",
"label": "",
"icon": null,
"variant": "filled",
"size": 412,
"size2": 512,
"checked": true,
"fill": "surfaceContainerHigh",
"note": "F7 sheet with grab handle; backdrop tap closes."
}
]
},
{
"id": "g69",
"x": 1492,
"y": 404,
"axis": "x",
"items": [
{
"id": "i68",
"kind": "text",
"label": "Up next",
"icon": null,
"variant": "filled",
"size": 20,
"bold": true
}
]
},
{
"id": "g73",
"x": 1492,
"y": 448,
"axis": "y",
"items": [
{
"id": "i70",
"kind": "listItem",
"label": "Build My Life",
"icon": "smart_display",
"variant": "filled",
"supporting": "Housefires \u00b7 6:04",
"action": {
"to": "player",
"transition": "fade"
}
},
{
"id": "i71",
"kind": "listItem",
"label": "Graves Into Gardens",
"icon": "smart_display",
"variant": "filled",
"supporting": "Elevation \u00b7 6:41",
"action": {
"to": "player",
"transition": "fade"
}
},
{
"id": "i72",
"kind": "listItem",
"label": "Goodness of God",
"icon": "smart_display",
"variant": "filled",
"supporting": "Bethel Music \u00b7 5:12",
"action": {
"to": "player",
"transition": "fade"
}
}
]
},
{
"id": "g75",
"x": 1968,
"y": 0,
"axis": "x",
"items": [
{
"id": "i74",
"kind": "box",
"label": "",
"icon": null,
"variant": "filled",
"size": 412,
"size2": 892,
"fill": "inverseSurface",
"note": "Video fills the screen (object-fit cover). Fit/Fill toggle in the controls."
}
]
},
{
"id": "g77",
"x": 1984,
"y": 24,
"axis": "x",
"items": [
{
"id": "i76",
"kind": "text",
"label": "Way Maker \u2014 Leeland",
"icon": null,
"variant": "filled",
"size": 14
}
]
},
{
"id": "g79",
"x": 2316,
"y": 12,
"axis": "x",
"items": [
{
"id": "i78",
"kind": "iconButton",
"label": "",
"icon": "fullscreen_exit",
"variant": "text",
"action": {
"to": "player",
"transition": "fade"
}
}
]
},
{
"id": "g81",
"x": 1984,
"y": 790,
"axis": "x",
"items": [
{
"id": "i80",
"kind": "slider",
"label": "",
"icon": null,
"variant": "filled",
"value": 35
}
]
},
{
"id": "g85",
"x": 1984,
"y": 828,
"axis": "x",
"items": [
{
"id": "i82",
"kind": "iconButton",
"label": "",
"icon": "pause",
"variant": "text"
},
{
"id": "i83",
"kind": "iconButton",
"label": "",
"icon": "screen_rotation",
"variant": "text"
},
{
"id": "i84",
"kind": "iconButton",
"label": "",
"icon": "fit_screen",
"variant": "text",
"note": "Fit \u2194 Fill."
}
]
}
]
}

View File

@@ -0,0 +1,904 @@
{
"title": "YT Player \u2014 Framework7 Swipe (light)",
"brief": "Ad-free YouTube/worship player PWA. Framework7 iOS-style layout with swipe gestures, built on the app's own tokens.",
"frame": "phone",
"platform": "web",
"paletteKey": "coral",
"theme": {
"dark": false,
"bothModes": true,
"contrast": "standard",
"shape": "rounded",
"font": "system",
"emphasized": false,
"motion": "expressive"
},
"frames": [
{
"id": "search",
"name": "Search",
"x": 0,
"y": 0,
"note": "Home + search results. Big title, rounded search field, results as an inset grouped list.",
"swipe": {
"left": "queue"
}
},
{
"id": "queue",
"name": "Queue",
"x": 492,
"y": 0,
"note": "Queued songs. Swipe a row left for Playlist/Remove (long swipe removes), right for Queue. Swipe sideways on empty space to change tab.",
"swipe": {
"right": "search"
}
},
{
"id": "player",
"name": "Now playing",
"x": 984,
"y": 0,
"note": "Video on top, Apple Music\u2013style transport, icon action row. Swipe down to collapse to the mini player.",
"swipe": {
"down": "queue"
}
},
{
"id": "upnext",
"name": "Up next",
"x": 1476,
"y": 0,
"note": "Bottom sheet opened by swiping up on the mini player. Half height, drag up for full, down to close."
},
{
"id": "fullscreen",
"name": "Fullscreen",
"x": 1968,
"y": 0,
"note": "Edge-to-edge video (Fill by default). Minimal icon-only controls over a soft bottom gradient; auto-hide.",
"bg": "inverseSurface"
}
],
"groups": [
{
"id": "g2",
"x": 0,
"y": 0,
"axis": "x",
"items": [
{
"id": "i1",
"kind": "topAppBar",
"label": "Search",
"icon": "menu",
"variant": "filled",
"icon2": "directions_car",
"note": "Translucent navbar; menu opens the sidebar (also left-edge swipe)."
}
]
},
{
"id": "g4",
"x": 16,
"y": 96,
"axis": "x",
"items": [
{
"id": "i3",
"kind": "searchBar",
"label": "Search YouTube",
"icon": null,
"variant": "filled",
"icon2": "mic",
"note": "Rounded F7 searchbar with inline mic; Enter searches."
}
]
},
{
"id": "g8",
"x": 16,
"y": 164,
"axis": "x",
"items": [
{
"id": "i5",
"kind": "chip",
"label": "lofi beats",
"icon": null,
"variant": "filled"
},
{
"id": "i6",
"kind": "chip",
"label": "live news",
"icon": null,
"variant": "filled"
},
{
"id": "i7",
"kind": "chip",
"label": "worship",
"icon": null,
"variant": "filled"
}
]
},
{
"id": "g10",
"x": 16,
"y": 212,
"axis": "x",
"items": [
{
"id": "i9",
"kind": "text",
"label": "Results",
"icon": null,
"variant": "filled",
"size": 28,
"bold": true
}
]
},
{
"id": "g15",
"x": 16,
"y": 260,
"axis": "y",
"items": [
{
"id": "i11",
"kind": "listItem",
"label": "Goodness of God",
"icon": "smart_display",
"variant": "filled",
"supporting": "Bethel Music \u00b7 5:12",
"icon2": "more_horiz",
"action": {
"to": "player",
"transition": "slide"
}
},
{
"id": "i12",
"kind": "listItem",
"label": "Way Maker",
"icon": "smart_display",
"variant": "filled",
"supporting": "Leeland \u00b7 3:12",
"icon2": "more_horiz",
"action": {
"to": "player",
"transition": "slide"
}
},
{
"id": "i13",
"kind": "listItem",
"label": "Build My Life",
"icon": "smart_display",
"variant": "filled",
"supporting": "Housefires \u00b7 6:04",
"icon2": "more_horiz",
"action": {
"to": "player",
"transition": "slide"
}
},
{
"id": "i14",
"kind": "listItem",
"label": "Graves Into Gardens",
"icon": "smart_display",
"variant": "filled",
"supporting": "Elevation \u00b7 6:41",
"icon2": "more_horiz",
"action": {
"to": "player",
"transition": "slide"
}
}
]
},
{
"id": "g17",
"x": 16,
"y": 700,
"axis": "x",
"items": [
{
"id": "i16",
"kind": "listItem",
"label": "Way Maker",
"icon": "music_note",
"variant": "tonal",
"supporting": "Leeland \u00b7 3:12",
"icon2": "play_arrow",
"action": {
"to": "player",
"transition": "slideUp"
},
"note": "Floating glass mini player. Tap opens the player, swipe left/right = next/previous, swipe up = Up next sheet."
}
]
},
{
"id": "g19",
"x": 0,
"y": 788,
"axis": "x",
"items": [
{
"id": "i18",
"kind": "bottomNav",
"label": "",
"icon": null,
"variant": "filled",
"tabs": [
{
"icon": "search",
"label": "Search"
},
{
"icon": "queue_music",
"label": "Queue"
},
{
"icon": "history",
"label": "History"
},
{
"icon": "download_done",
"label": "Saved"
},
{
"icon": "more_horiz",
"label": "More"
}
],
"selected": 0,
"actions": {
"tab:0": {
"to": "search",
"transition": "fade"
},
"tab:1": {
"to": "queue",
"transition": "fade"
}
},
"note": "Translucent blurred tab bar; badge on Queue."
}
]
},
{
"id": "g21",
"x": 492,
"y": 0,
"axis": "x",
"items": [
{
"id": "i20",
"kind": "topAppBar",
"label": "Queue",
"icon": "menu",
"variant": "filled",
"icon2": "checklist"
}
]
},
{
"id": "g24",
"x": 508,
"y": 96,
"axis": "x",
"items": [
{
"id": "i22",
"kind": "button",
"label": "Play queue",
"icon": "play_arrow",
"variant": "filled",
"size": 182
},
{
"id": "i23",
"kind": "button",
"label": "Clear",
"icon": "clear_all",
"variant": "tonal",
"size": 182
}
]
},
{
"id": "g29",
"x": 508,
"y": 168,
"axis": "y",
"items": [
{
"id": "i25",
"kind": "listItem",
"label": "Way Maker",
"icon": "smart_display",
"variant": "filled",
"supporting": "Leeland \u00b7 3:12",
"icon2": "drag_handle",
"note": "Swipe right \u2192 Queue (accent action)."
},
{
"id": "i26",
"kind": "listItem",
"label": "Build My Life",
"icon": "smart_display",
"variant": "filled",
"supporting": "Housefires \u00b7 6:04",
"icon2": "drag_handle",
"note": "Swipe left \u2192 Playlist + Remove pills."
},
{
"id": "i27",
"kind": "listItem",
"label": "Graves Into Gardens",
"icon": "smart_display",
"variant": "filled",
"supporting": "Elevation \u00b7 6:41",
"icon2": "drag_handle",
"note": "Long swipe left removes the row."
},
{
"id": "i28",
"kind": "listItem",
"label": "Goodness of God",
"icon": "smart_display",
"variant": "filled",
"supporting": "Bethel Music \u00b7 5:12",
"icon2": "drag_handle",
"note": ""
}
]
},
{
"id": "g32",
"x": 508,
"y": 480,
"axis": "x",
"items": [
{
"id": "i30",
"kind": "button",
"label": "Playlist",
"icon": "playlist_add",
"variant": "tonal"
},
{
"id": "i31",
"kind": "button",
"label": "Remove",
"icon": "delete",
"variant": "filled"
}
]
},
{
"id": "g34",
"x": 508,
"y": 548,
"axis": "x",
"items": [
{
"id": "i33",
"kind": "text",
"label": "Swipe actions revealed (example row)",
"icon": null,
"variant": "filled",
"size": 14
}
]
},
{
"id": "g36",
"x": 508,
"y": 700,
"axis": "x",
"items": [
{
"id": "i35",
"kind": "listItem",
"label": "Way Maker",
"icon": "music_note",
"variant": "tonal",
"supporting": "Leeland \u00b7 3:12",
"icon2": "play_arrow",
"action": {
"to": "player",
"transition": "slideUp"
},
"note": "Floating glass mini player. Tap opens the player, swipe left/right = next/previous, swipe up = Up next sheet."
}
]
},
{
"id": "g38",
"x": 492,
"y": 788,
"axis": "x",
"items": [
{
"id": "i37",
"kind": "bottomNav",
"label": "",
"icon": null,
"variant": "filled",
"tabs": [
{
"icon": "search",
"label": "Search"
},
{
"icon": "queue_music",
"label": "Queue"
},
{
"icon": "history",
"label": "History"
},
{
"icon": "download_done",
"label": "Saved"
},
{
"icon": "more_horiz",
"label": "More"
}
],
"selected": 1,
"actions": {
"tab:0": {
"to": "search",
"transition": "fade"
},
"tab:1": {
"to": "queue",
"transition": "fade"
}
},
"note": "Translucent blurred tab bar; badge on Queue."
}
]
},
{
"id": "g40",
"x": 984,
"y": 0,
"axis": "x",
"items": [
{
"id": "i39",
"kind": "topAppBar",
"label": "Now playing",
"icon": "keyboard_arrow_down",
"variant": "filled",
"icon2": "more_horiz",
"actions": {
"icon": {
"to": "back",
"transition": "slideDown"
}
}
}
]
},
{
"id": "g42",
"x": 984,
"y": 88,
"axis": "x",
"items": [
{
"id": "i41",
"kind": "image",
"label": "",
"icon": null,
"variant": "filled",
"size": 412,
"note": "16:9 video stage; the fullscreen button opens Fullscreen."
}
]
},
{
"id": "g44",
"x": 1000,
"y": 320,
"axis": "x",
"items": [
{
"id": "i43",
"kind": "text",
"label": "Way Maker",
"icon": null,
"variant": "filled",
"size": 24,
"bold": true
}
]
},
{
"id": "g46",
"x": 1000,
"y": 356,
"axis": "x",
"items": [
{
"id": "i45",
"kind": "text",
"label": "Leeland",
"icon": null,
"variant": "filled",
"size": 16
}
]
},
{
"id": "g48",
"x": 1000,
"y": 396,
"axis": "x",
"items": [
{
"id": "i47",
"kind": "slider",
"label": "",
"icon": null,
"variant": "filled",
"value": 35,
"note": "Thin seek track, accent fill."
}
]
},
{
"id": "g54",
"x": 1048,
"y": 456,
"axis": "x",
"items": [
{
"id": "i49",
"kind": "iconButton",
"label": "",
"icon": "skip_previous",
"variant": "text"
},
{
"id": "i50",
"kind": "iconButton",
"label": "",
"icon": "replay_10",
"variant": "text"
},
{
"id": "i51",
"kind": "iconButton",
"label": "",
"icon": "play_arrow",
"variant": "filled"
},
{
"id": "i52",
"kind": "iconButton",
"label": "",
"icon": "forward_10",
"variant": "text"
},
{
"id": "i53",
"kind": "iconButton",
"label": "",
"icon": "skip_next",
"variant": "text"
}
]
},
{
"id": "g61",
"x": 1024,
"y": 540,
"axis": "x",
"items": [
{
"id": "i55",
"kind": "iconButton",
"label": "",
"icon": "playlist_add",
"variant": "text"
},
{
"id": "i56",
"kind": "iconButton",
"label": "",
"icon": "download",
"variant": "text"
},
{
"id": "i57",
"kind": "iconButton",
"label": "",
"icon": "lyrics",
"variant": "text"
},
{
"id": "i58",
"kind": "iconButton",
"label": "",
"icon": "share",
"variant": "text"
},
{
"id": "i59",
"kind": "iconButton",
"label": "",
"icon": "fullscreen",
"variant": "text",
"action": {
"to": "fullscreen",
"transition": "expand"
}
},
{
"id": "i60",
"kind": "iconButton",
"label": "",
"icon": "more_horiz",
"variant": "text"
}
]
},
{
"id": "g63",
"x": 984,
"y": 788,
"axis": "x",
"items": [
{
"id": "i62",
"kind": "bottomNav",
"label": "",
"icon": null,
"variant": "filled",
"tabs": [
{
"icon": "search",
"label": "Search"
},
{
"icon": "queue_music",
"label": "Queue"
},
{
"icon": "history",
"label": "History"
},
{
"icon": "download_done",
"label": "Saved"
},
{
"icon": "more_horiz",
"label": "More"
}
],
"selected": 1,
"actions": {
"tab:0": {
"to": "search",
"transition": "fade"
},
"tab:1": {
"to": "queue",
"transition": "fade"
}
},
"note": "Translucent blurred tab bar; badge on Queue."
}
]
},
{
"id": "g65",
"x": 1476,
"y": 0,
"axis": "x",
"items": [
{
"id": "i64",
"kind": "topAppBar",
"label": "Queue",
"icon": "menu",
"variant": "filled"
}
]
},
{
"id": "g67",
"x": 1476,
"y": 380,
"axis": "x",
"items": [
{
"id": "i66",
"kind": "box",
"label": "",
"icon": null,
"variant": "filled",
"size": 412,
"size2": 512,
"checked": true,
"fill": "surfaceContainerHigh",
"note": "F7 sheet with grab handle; backdrop tap closes."
}
]
},
{
"id": "g69",
"x": 1492,
"y": 404,
"axis": "x",
"items": [
{
"id": "i68",
"kind": "text",
"label": "Up next",
"icon": null,
"variant": "filled",
"size": 20,
"bold": true
}
]
},
{
"id": "g73",
"x": 1492,
"y": 448,
"axis": "y",
"items": [
{
"id": "i70",
"kind": "listItem",
"label": "Build My Life",
"icon": "smart_display",
"variant": "filled",
"supporting": "Housefires \u00b7 6:04",
"action": {
"to": "player",
"transition": "fade"
}
},
{
"id": "i71",
"kind": "listItem",
"label": "Graves Into Gardens",
"icon": "smart_display",
"variant": "filled",
"supporting": "Elevation \u00b7 6:41",
"action": {
"to": "player",
"transition": "fade"
}
},
{
"id": "i72",
"kind": "listItem",
"label": "Goodness of God",
"icon": "smart_display",
"variant": "filled",
"supporting": "Bethel Music \u00b7 5:12",
"action": {
"to": "player",
"transition": "fade"
}
}
]
},
{
"id": "g75",
"x": 1968,
"y": 0,
"axis": "x",
"items": [
{
"id": "i74",
"kind": "box",
"label": "",
"icon": null,
"variant": "filled",
"size": 412,
"size2": 892,
"fill": "inverseSurface",
"note": "Video fills the screen (object-fit cover). Fit/Fill toggle in the controls."
}
]
},
{
"id": "g77",
"x": 1984,
"y": 24,
"axis": "x",
"items": [
{
"id": "i76",
"kind": "text",
"label": "Way Maker \u2014 Leeland",
"icon": null,
"variant": "filled",
"size": 14
}
]
},
{
"id": "g79",
"x": 2316,
"y": 12,
"axis": "x",
"items": [
{
"id": "i78",
"kind": "iconButton",
"label": "",
"icon": "fullscreen_exit",
"variant": "text",
"action": {
"to": "player",
"transition": "fade"
}
}
]
},
{
"id": "g81",
"x": 1984,
"y": 790,
"axis": "x",
"items": [
{
"id": "i80",
"kind": "slider",
"label": "",
"icon": null,
"variant": "filled",
"value": 35
}
]
},
{
"id": "g85",
"x": 1984,
"y": 828,
"axis": "x",
"items": [
{
"id": "i82",
"kind": "iconButton",
"label": "",
"icon": "pause",
"variant": "text"
},
{
"id": "i83",
"kind": "iconButton",
"label": "",
"icon": "screen_rotation",
"variant": "text"
},
{
"id": "i84",
"kind": "iconButton",
"label": "",
"icon": "fit_screen",
"variant": "text",
"note": "Fit \u2194 Fill."
}
]
}
]
}

904
docs/design/f7-swipe.json Normal file
View File

@@ -0,0 +1,904 @@
{
"title": "YT Player \u2014 Framework7 Swipe",
"brief": "Ad-free YouTube/worship player PWA. Framework7 iOS-style layout with swipe gestures, built on the app's own tokens.",
"frame": "phone",
"platform": "web",
"paletteKey": "coral",
"theme": {
"dark": true,
"bothModes": true,
"contrast": "standard",
"shape": "rounded",
"font": "system",
"emphasized": false,
"motion": "expressive"
},
"frames": [
{
"id": "search",
"name": "Search",
"x": 0,
"y": 0,
"note": "Home + search results. Big title, rounded search field, results as an inset grouped list.",
"swipe": {
"left": "queue"
}
},
{
"id": "queue",
"name": "Queue",
"x": 492,
"y": 0,
"note": "Queued songs. Swipe a row left for Playlist/Remove (long swipe removes), right for Queue. Swipe sideways on empty space to change tab.",
"swipe": {
"right": "search"
}
},
{
"id": "player",
"name": "Now playing",
"x": 984,
"y": 0,
"note": "Video on top, Apple Music\u2013style transport, icon action row. Swipe down to collapse to the mini player.",
"swipe": {
"down": "queue"
}
},
{
"id": "upnext",
"name": "Up next",
"x": 1476,
"y": 0,
"note": "Bottom sheet opened by swiping up on the mini player. Half height, drag up for full, down to close."
},
{
"id": "fullscreen",
"name": "Fullscreen",
"x": 1968,
"y": 0,
"note": "Edge-to-edge video (Fill by default). Minimal icon-only controls over a soft bottom gradient; auto-hide.",
"bg": "inverseSurface"
}
],
"groups": [
{
"id": "g2",
"x": 0,
"y": 0,
"axis": "x",
"items": [
{
"id": "i1",
"kind": "topAppBar",
"label": "Search",
"icon": "menu",
"variant": "filled",
"icon2": "directions_car",
"note": "Translucent navbar; menu opens the sidebar (also left-edge swipe)."
}
]
},
{
"id": "g4",
"x": 16,
"y": 96,
"axis": "x",
"items": [
{
"id": "i3",
"kind": "searchBar",
"label": "Search YouTube",
"icon": null,
"variant": "filled",
"icon2": "mic",
"note": "Rounded F7 searchbar with inline mic; Enter searches."
}
]
},
{
"id": "g8",
"x": 16,
"y": 164,
"axis": "x",
"items": [
{
"id": "i5",
"kind": "chip",
"label": "lofi beats",
"icon": null,
"variant": "filled"
},
{
"id": "i6",
"kind": "chip",
"label": "live news",
"icon": null,
"variant": "filled"
},
{
"id": "i7",
"kind": "chip",
"label": "worship",
"icon": null,
"variant": "filled"
}
]
},
{
"id": "g10",
"x": 16,
"y": 212,
"axis": "x",
"items": [
{
"id": "i9",
"kind": "text",
"label": "Results",
"icon": null,
"variant": "filled",
"size": 28,
"bold": true
}
]
},
{
"id": "g15",
"x": 16,
"y": 260,
"axis": "y",
"items": [
{
"id": "i11",
"kind": "listItem",
"label": "Goodness of God",
"icon": "smart_display",
"variant": "filled",
"supporting": "Bethel Music \u00b7 5:12",
"icon2": "more_horiz",
"action": {
"to": "player",
"transition": "slide"
}
},
{
"id": "i12",
"kind": "listItem",
"label": "Way Maker",
"icon": "smart_display",
"variant": "filled",
"supporting": "Leeland \u00b7 3:12",
"icon2": "more_horiz",
"action": {
"to": "player",
"transition": "slide"
}
},
{
"id": "i13",
"kind": "listItem",
"label": "Build My Life",
"icon": "smart_display",
"variant": "filled",
"supporting": "Housefires \u00b7 6:04",
"icon2": "more_horiz",
"action": {
"to": "player",
"transition": "slide"
}
},
{
"id": "i14",
"kind": "listItem",
"label": "Graves Into Gardens",
"icon": "smart_display",
"variant": "filled",
"supporting": "Elevation \u00b7 6:41",
"icon2": "more_horiz",
"action": {
"to": "player",
"transition": "slide"
}
}
]
},
{
"id": "g17",
"x": 16,
"y": 700,
"axis": "x",
"items": [
{
"id": "i16",
"kind": "listItem",
"label": "Way Maker",
"icon": "music_note",
"variant": "tonal",
"supporting": "Leeland \u00b7 3:12",
"icon2": "play_arrow",
"action": {
"to": "player",
"transition": "slideUp"
},
"note": "Floating glass mini player. Tap opens the player, swipe left/right = next/previous, swipe up = Up next sheet."
}
]
},
{
"id": "g19",
"x": 0,
"y": 788,
"axis": "x",
"items": [
{
"id": "i18",
"kind": "bottomNav",
"label": "",
"icon": null,
"variant": "filled",
"tabs": [
{
"icon": "search",
"label": "Search"
},
{
"icon": "queue_music",
"label": "Queue"
},
{
"icon": "history",
"label": "History"
},
{
"icon": "download_done",
"label": "Saved"
},
{
"icon": "more_horiz",
"label": "More"
}
],
"selected": 0,
"actions": {
"tab:0": {
"to": "search",
"transition": "fade"
},
"tab:1": {
"to": "queue",
"transition": "fade"
}
},
"note": "Translucent blurred tab bar; badge on Queue."
}
]
},
{
"id": "g21",
"x": 492,
"y": 0,
"axis": "x",
"items": [
{
"id": "i20",
"kind": "topAppBar",
"label": "Queue",
"icon": "menu",
"variant": "filled",
"icon2": "checklist"
}
]
},
{
"id": "g24",
"x": 508,
"y": 96,
"axis": "x",
"items": [
{
"id": "i22",
"kind": "button",
"label": "Play queue",
"icon": "play_arrow",
"variant": "filled",
"size": 182
},
{
"id": "i23",
"kind": "button",
"label": "Clear",
"icon": "clear_all",
"variant": "tonal",
"size": 182
}
]
},
{
"id": "g29",
"x": 508,
"y": 168,
"axis": "y",
"items": [
{
"id": "i25",
"kind": "listItem",
"label": "Way Maker",
"icon": "smart_display",
"variant": "filled",
"supporting": "Leeland \u00b7 3:12",
"icon2": "drag_handle",
"note": "Swipe right \u2192 Queue (accent action)."
},
{
"id": "i26",
"kind": "listItem",
"label": "Build My Life",
"icon": "smart_display",
"variant": "filled",
"supporting": "Housefires \u00b7 6:04",
"icon2": "drag_handle",
"note": "Swipe left \u2192 Playlist + Remove pills."
},
{
"id": "i27",
"kind": "listItem",
"label": "Graves Into Gardens",
"icon": "smart_display",
"variant": "filled",
"supporting": "Elevation \u00b7 6:41",
"icon2": "drag_handle",
"note": "Long swipe left removes the row."
},
{
"id": "i28",
"kind": "listItem",
"label": "Goodness of God",
"icon": "smart_display",
"variant": "filled",
"supporting": "Bethel Music \u00b7 5:12",
"icon2": "drag_handle",
"note": ""
}
]
},
{
"id": "g32",
"x": 508,
"y": 480,
"axis": "x",
"items": [
{
"id": "i30",
"kind": "button",
"label": "Playlist",
"icon": "playlist_add",
"variant": "tonal"
},
{
"id": "i31",
"kind": "button",
"label": "Remove",
"icon": "delete",
"variant": "filled"
}
]
},
{
"id": "g34",
"x": 508,
"y": 548,
"axis": "x",
"items": [
{
"id": "i33",
"kind": "text",
"label": "Swipe actions revealed (example row)",
"icon": null,
"variant": "filled",
"size": 14
}
]
},
{
"id": "g36",
"x": 508,
"y": 700,
"axis": "x",
"items": [
{
"id": "i35",
"kind": "listItem",
"label": "Way Maker",
"icon": "music_note",
"variant": "tonal",
"supporting": "Leeland \u00b7 3:12",
"icon2": "play_arrow",
"action": {
"to": "player",
"transition": "slideUp"
},
"note": "Floating glass mini player. Tap opens the player, swipe left/right = next/previous, swipe up = Up next sheet."
}
]
},
{
"id": "g38",
"x": 492,
"y": 788,
"axis": "x",
"items": [
{
"id": "i37",
"kind": "bottomNav",
"label": "",
"icon": null,
"variant": "filled",
"tabs": [
{
"icon": "search",
"label": "Search"
},
{
"icon": "queue_music",
"label": "Queue"
},
{
"icon": "history",
"label": "History"
},
{
"icon": "download_done",
"label": "Saved"
},
{
"icon": "more_horiz",
"label": "More"
}
],
"selected": 1,
"actions": {
"tab:0": {
"to": "search",
"transition": "fade"
},
"tab:1": {
"to": "queue",
"transition": "fade"
}
},
"note": "Translucent blurred tab bar; badge on Queue."
}
]
},
{
"id": "g40",
"x": 984,
"y": 0,
"axis": "x",
"items": [
{
"id": "i39",
"kind": "topAppBar",
"label": "Now playing",
"icon": "keyboard_arrow_down",
"variant": "filled",
"icon2": "more_horiz",
"actions": {
"icon": {
"to": "back",
"transition": "slideDown"
}
}
}
]
},
{
"id": "g42",
"x": 984,
"y": 88,
"axis": "x",
"items": [
{
"id": "i41",
"kind": "image",
"label": "",
"icon": null,
"variant": "filled",
"size": 412,
"note": "16:9 video stage; the fullscreen button opens Fullscreen."
}
]
},
{
"id": "g44",
"x": 1000,
"y": 320,
"axis": "x",
"items": [
{
"id": "i43",
"kind": "text",
"label": "Way Maker",
"icon": null,
"variant": "filled",
"size": 24,
"bold": true
}
]
},
{
"id": "g46",
"x": 1000,
"y": 356,
"axis": "x",
"items": [
{
"id": "i45",
"kind": "text",
"label": "Leeland",
"icon": null,
"variant": "filled",
"size": 16
}
]
},
{
"id": "g48",
"x": 1000,
"y": 396,
"axis": "x",
"items": [
{
"id": "i47",
"kind": "slider",
"label": "",
"icon": null,
"variant": "filled",
"value": 35,
"note": "Thin seek track, accent fill."
}
]
},
{
"id": "g54",
"x": 1048,
"y": 456,
"axis": "x",
"items": [
{
"id": "i49",
"kind": "iconButton",
"label": "",
"icon": "skip_previous",
"variant": "text"
},
{
"id": "i50",
"kind": "iconButton",
"label": "",
"icon": "replay_10",
"variant": "text"
},
{
"id": "i51",
"kind": "iconButton",
"label": "",
"icon": "play_arrow",
"variant": "filled"
},
{
"id": "i52",
"kind": "iconButton",
"label": "",
"icon": "forward_10",
"variant": "text"
},
{
"id": "i53",
"kind": "iconButton",
"label": "",
"icon": "skip_next",
"variant": "text"
}
]
},
{
"id": "g61",
"x": 1024,
"y": 540,
"axis": "x",
"items": [
{
"id": "i55",
"kind": "iconButton",
"label": "",
"icon": "playlist_add",
"variant": "text"
},
{
"id": "i56",
"kind": "iconButton",
"label": "",
"icon": "download",
"variant": "text"
},
{
"id": "i57",
"kind": "iconButton",
"label": "",
"icon": "lyrics",
"variant": "text"
},
{
"id": "i58",
"kind": "iconButton",
"label": "",
"icon": "share",
"variant": "text"
},
{
"id": "i59",
"kind": "iconButton",
"label": "",
"icon": "fullscreen",
"variant": "text",
"action": {
"to": "fullscreen",
"transition": "expand"
}
},
{
"id": "i60",
"kind": "iconButton",
"label": "",
"icon": "more_horiz",
"variant": "text"
}
]
},
{
"id": "g63",
"x": 984,
"y": 788,
"axis": "x",
"items": [
{
"id": "i62",
"kind": "bottomNav",
"label": "",
"icon": null,
"variant": "filled",
"tabs": [
{
"icon": "search",
"label": "Search"
},
{
"icon": "queue_music",
"label": "Queue"
},
{
"icon": "history",
"label": "History"
},
{
"icon": "download_done",
"label": "Saved"
},
{
"icon": "more_horiz",
"label": "More"
}
],
"selected": 1,
"actions": {
"tab:0": {
"to": "search",
"transition": "fade"
},
"tab:1": {
"to": "queue",
"transition": "fade"
}
},
"note": "Translucent blurred tab bar; badge on Queue."
}
]
},
{
"id": "g65",
"x": 1476,
"y": 0,
"axis": "x",
"items": [
{
"id": "i64",
"kind": "topAppBar",
"label": "Queue",
"icon": "menu",
"variant": "filled"
}
]
},
{
"id": "g67",
"x": 1476,
"y": 380,
"axis": "x",
"items": [
{
"id": "i66",
"kind": "box",
"label": "",
"icon": null,
"variant": "filled",
"size": 412,
"size2": 512,
"checked": true,
"fill": "surfaceContainerHigh",
"note": "F7 sheet with grab handle; backdrop tap closes."
}
]
},
{
"id": "g69",
"x": 1492,
"y": 404,
"axis": "x",
"items": [
{
"id": "i68",
"kind": "text",
"label": "Up next",
"icon": null,
"variant": "filled",
"size": 20,
"bold": true
}
]
},
{
"id": "g73",
"x": 1492,
"y": 448,
"axis": "y",
"items": [
{
"id": "i70",
"kind": "listItem",
"label": "Build My Life",
"icon": "smart_display",
"variant": "filled",
"supporting": "Housefires \u00b7 6:04",
"action": {
"to": "player",
"transition": "fade"
}
},
{
"id": "i71",
"kind": "listItem",
"label": "Graves Into Gardens",
"icon": "smart_display",
"variant": "filled",
"supporting": "Elevation \u00b7 6:41",
"action": {
"to": "player",
"transition": "fade"
}
},
{
"id": "i72",
"kind": "listItem",
"label": "Goodness of God",
"icon": "smart_display",
"variant": "filled",
"supporting": "Bethel Music \u00b7 5:12",
"action": {
"to": "player",
"transition": "fade"
}
}
]
},
{
"id": "g75",
"x": 1968,
"y": 0,
"axis": "x",
"items": [
{
"id": "i74",
"kind": "box",
"label": "",
"icon": null,
"variant": "filled",
"size": 412,
"size2": 892,
"fill": "inverseSurface",
"note": "Video fills the screen (object-fit cover). Fit/Fill toggle in the controls."
}
]
},
{
"id": "g77",
"x": 1984,
"y": 24,
"axis": "x",
"items": [
{
"id": "i76",
"kind": "text",
"label": "Way Maker \u2014 Leeland",
"icon": null,
"variant": "filled",
"size": 14
}
]
},
{
"id": "g79",
"x": 2316,
"y": 12,
"axis": "x",
"items": [
{
"id": "i78",
"kind": "iconButton",
"label": "",
"icon": "fullscreen_exit",
"variant": "text",
"action": {
"to": "player",
"transition": "fade"
}
}
]
},
{
"id": "g81",
"x": 1984,
"y": 790,
"axis": "x",
"items": [
{
"id": "i80",
"kind": "slider",
"label": "",
"icon": null,
"variant": "filled",
"value": 35
}
]
},
{
"id": "g85",
"x": 1984,
"y": 828,
"axis": "x",
"items": [
{
"id": "i82",
"kind": "iconButton",
"label": "",
"icon": "pause",
"variant": "text"
},
{
"id": "i83",
"kind": "iconButton",
"label": "",
"icon": "screen_rotation",
"variant": "text"
},
{
"id": "i84",
"kind": "iconButton",
"label": "",
"icon": "fit_screen",
"variant": "text",
"note": "Fit \u2194 Fill."
}
]
}
]
}

View File

@@ -0,0 +1,11 @@
# Backfill songs played from device storage
A web player's first actual playback of a YouTube video in a session reports its known title, artist/channel, duration and thumbnail to `POST /api/media/:id/meta`. Local OPFS playback therefore no longer depends on `/api/streams` being called. Offline plays are held in memory until the browser returns online. Uploads and edited copies are excluded. Playback never waits for the report.
The server accepts only 11-character YouTube IDs, bounded strings, numeric duration and approved HTTPS YouTube artwork (local catalog artwork maps to the canonical thumbnail). Bodies are capped at 8 KB. Reports are limited to 20 per IP per minute and 100 globally, with a maximum of 32 outstanding backfill fetches. A response contains `{ok, known, cache}`; `known` describes whether a media row existed before the report, and `cache` is ready, queued, downloading, validating, unavailable or busy. Metadata can be registered even when the cache volume is offline or the queue is busy.
Device hints fill missing media fields with an atomic SQLite merge; existing titles, artists, durations, art and richer metadata are retained. Catalog ingestion also fills gaps and queues the existing bounded thumbnail collector. Admin's song list includes metadata-only entries, so its lyric tools have a title and artist before downloading completes. Inclusion in that list does not imply cached media is ready; `cacheStatus` reports the actual state.
Missing copies use the normal low-priority automatic `ensureCached` job, including its deduplication, single fetch lane, yt-dlp path, validation, duration/backoff limits, LRU byte budget, disk guard and USB volume marker. No parallel downloader or cache directory is introduced. Existing copies and in-progress jobs are skipped. Download failure keeps song metadata; the usual cache retry policy applies on later sessions. Offline-volume and busy responses do not force a fetch or bypass safety limits.
Verification: server validation/merge/route tests, admin metadata-only listing test, frontend once-per-session/offline reporter tests, all frontend unit tests, app syntax and server build. On a real phone, play a previously unknown OPFS song, inspect `/api/admin/media`, then verify a normal media-cache job and lyrics lookup. Repeat the play to confirm no second report; also test with the server's cache volume unavailable.

7
docs/equalizer.md Normal file
View File

@@ -0,0 +1,7 @@
# Equalizer and stereo width
`frontend/eq-core.js` is the single band/preset definition for both live EQ and EqRender: 31, 62, 125, 250, 500, 1000, 2000, 4000, 8000 and 16000 Hz. Existing five-band curves migrate by logarithmic frequency interpolation; edge gains extend to the new endpoints. Migration preserves user curves instead of replacing them with a new preset.
The headphone widener is off by default. It delays the right channel by up to 15 ms (Haas effect); it can colour speaker playback and mono mixes. Live EQ and saved-song renders use the same widener graph, vocal matrix and bands. Render signatures include all three, so changed settings invalidate old processed copies. iPhone streams still require the existing Live sound processing opt-in; saved copies use OfflineAudioContext. A new rendered copy is used on a subsequent playback.
Review with actual headphones and an iPhone: centre image at 0%, mono compatibility at higher values, rendered/live EQ correspondence, and lock-screen playback of saved songs. Model-based separation is outside this feature; see vocal-stems.md.

304
docs/feature-ideas.md Normal file
View File

@@ -0,0 +1,304 @@
# ytplayer — Feature Ideas & Enhancement Roadmap
> **Status:** Research & Proposed Roadmap
> **Target:** Web PWA, Tauri (Windows), zero-native (macOS / Linux)
> **Date:** October 2026
---
## 1. Context & Architecture Baseline
`ytplayer` is an ad-free, privacy-preserving media engine with a dual identity:
1. **Ad-Free Media Player & Offline PWA**: Built with vanilla JS on the frontend and Bun + Hono on the backend (libsql SQLite database). It uses `yt-dlp` and InnerTube for direct stream extraction without Google accounts, and caches media locally (OPFS in browser, single-file H.264/HEVC faststart on server, WebRTC P2P mesh between devices).
2. **Live Worship & Stage Performance Tool**: Equipped with **Service Mode** (wake-locked setlist view, auto-scaling lyric fonts, per-song arrangement notes), synchronized LRC lyrics with section/cue tags, and a **Presenter screen** (`/?present=<code>`) with QR pairing.
This document synthesizes high-value feature opportunities gathered from research into modern YouTube frontends (FreeTube, ReVanced, SmartTube, Namida), modern music players (Plexamp, Spotube), and live stage tools (Planning Center Music Stand, OnSong, MultiTracks Playback).
---
## 2. Feature Proposals by Domain
### Domain 1: Smart YouTube & Playback Experience
#### 1.1 SponsorBlock & Non-Music Segment Skipping
* **The Concept**: Automatically skip or visually mark sponsored segments, self-promos, interaction reminders, and non-music sections.
* **Why it matters**: Music videos frequently feature skits, prolonged silent pauses, or spoken intros. Skipping `music_offtopic` ensures the music starts immediately.
* **Technical Path**:
* Free, unauthenticated REST API: `GET https://sponsor.ajay.app/api/skipSegments?videoID=<id>&categories=["sponsor","intro","outro","music_offtopic","selfpromo"]`.
* Highlight segments as color-coded spans over the seek bar (`#timeline` / Glass Stage scrubber).
* During the playback tick in `frontend/app.js`, if `currentTime` enters a skippable segment and auto-skip is enabled in Settings, seek to the segment end and show an "Unskip" toast.
* Server media cache can optionally apply `--sponsorblock-mark` during ffmpeg intake.
#### 1.2 Automatic YouTube Chapter Extraction & Interactive Scrubber
* **The Concept**: Automatically parse video chapters from YouTube metadata and display chapter splits on the progress bar.
* **Why it matters**: Currently, chapters are only created manually. Full albums, sermons, conference talks, and live sets already have timestamps in video descriptions.
* **Technical Path**:
* In `server/server.js` (`/api/streams`), expose `chapters: [{ start_time, end_time, title }]` directly from InnerTube or `yt-dlp`.
* Render tick marks / gaps on the progress scrubber for each chapter boundary.
* Display the current chapter title next to the timestamp.
* Add keyboard shortcuts: `[` (previous chapter) and `]` (next chapter).
#### 1.3 Return YouTube Dislike (RYD) & Quality Rating
* **The Concept**: Show community like/dislike ratios and ratings for videos.
* **Why it matters**: Helps identify misleading arrangements, clickbait, poor audio rips, or broken videos before playback.
* **Technical Path**:
* Query `https://returnyoutubedislikeapi.com/votes?videoId=<id>` (public, CORS-enabled).
* Display a discreet like ratio bar or percentage badge on the video card and now-playing details.
#### 1.4 On-Screen Subtitles & Closed Captions (CC) Overlay
* **The Concept**: Render synchronized captions directly over the video playback stage.
* **Why it matters**: `ytplayer` currently only uses captions for transcript search or importing into lyrics. Spoken sermons, tutorials, foreign tracks, and non-musical videos need readable on-screen subtitles.
* **Technical Path**:
* Add a `CC` button on the player controls.
* Fetch timed lines from `/api/notes/:id/captions`.
* Render an HTML overlay synchronized to `Player.master.currentTime` with settings for font size, background opacity, and positioning.
#### 1.5 Silence Skipping (Talk & Sermon Mode)
* **The Concept**: Automatically speed up or skip past silent gaps in spoken-word media.
* **Why it matters**: Long sermons, podcasts, and talks often have pauses; skipping silence saves 10–20% of listening time without altering speech tone.
* **Technical Path**:
* Connect an `AnalyserNode` or `AudioWorklet` in the Web Audio graph.
* If audio energy (RMS) stays below -45 dB for >800 ms, ramp `playbackRate` to 2.5× until speech resumes.
---
### Domain 2: Audiophile & Music Player Polish
#### 2.1 EBU R128 / LUFS Loudness Normalization
* **The Concept**: Eliminate jarring volume jumps between tracks in playlists and queues.
* **Why it matters**: YouTube master volumes vary widely (-24 LUFS to -8 LUFS). Normalization ensures consistent listening levels.
* **Technical Path**:
* When generating waveform peaks in `server/media-cache.js`, run ffmpeg's `ebur128` filter once to measure integrated loudness (LUFS).
* Store `lufs` in the database and pass it via `/api/streams` and `/api/media/:id`.
* In `frontend/app.js`, apply a Web Audio `GainNode` to normalize tracks to a standard -14 LUFS target.
#### 2.2 Real-Time Pitch Shifting & Independent Tempo Adjustment
* **The Concept**: Transpose playback key (±6 semitones) without altering tempo, or slow down tempo without changing pitch.
* **Why it matters**: Singers and worship teams often need to adapt songs to a band's vocal key. Instrumentalists need to slow down fast sections to learn them.
* **Technical Path**:
* Use an AudioWorklet running a Phase Vocoder or `SoundTouchJS` DSP processor.
* Provide stepper controls for semitone transposition and tempo percentage (0.5×–1.5×).
#### 2.3 Ambient Glow / Reactive Lighting Mode
* **The Concept**: A soft dynamic glow behind the video player that mirrors current video colors (similar to YouTube Ambient Mode or Apple Music dynamic art).
* **Technical Path**:
* Render video frames onto an offscreen 16×16 `<canvas>` at ~10 FPS.
* Display a blurred canvas (`filter: blur(50px)`) directly behind the player container with smooth CSS opacity.
* Auto-disable when `settings.perfMode` is active or under `prefers-reduced-motion`.
#### 2.4 Smart Autoplay Radio / Endless Mix
* **The Concept**: Keep playing related songs when the active playlist or queue concludes.
* **Technical Path**:
* Fetch candidate related tracks via InnerTube `next` continuity tokens.
* Re-rank candidates using the client's local `StatsTrack` (`playCount`, listening duration, and skips) to favor familiar favorites while avoiding immediate repeats.
#### 2.5 Audio Stem Separation & Vocal Attenuator (Karaoke / Rehearsal Mode)
* **The Concept**: Mute or attenuate lead vocals in real time (`🎤 Vocal: 100% ────● 0%`), or isolate the vocal track for harmony practice.
* **Why it matters**: Gives singers clean backing tracks for rehearsal and live events even when official minus-one recordings do not exist.
* **Technical Path**:
* Client-side: Run `demucs-onnx` with WebGPU acceleration to process saved OPFS tracks offline.
* Server-side: Provide `GET /api/media/:id/stems` (caching `.vocals.m4a` and `.instrumental.m4a` alongside the existing `.m4a` audio sidecar in `server/media-cache.js`).
* Frontend: Two synchronized audio elements or Web Audio `GainNode` faders for seamless real-time blending.
#### 2.6 10-Band Graphic Equalizer & Spatial Hall Simulation
* **The Concept**: Upgrade the existing 5-band filter in `EQ` (`frontend/app.js`) to a full 10-band graphic equalizer with acoustic presets and spatial audio widening.
* **Technical Path**:
* 10 `BiquadFilterNode` bands (31Hz, 62Hz, 125Hz, 250Hz, 500Hz, 1kHz, 2kHz, 4kHz, 8kHz, 16kHz).
* Presets: *Vocal Clarity (speech presence boost), Acoustic Warmth, Worship Stage, Bass Punch, and Flat*.
* Spatial stereo widener using a Haas-effect micro-delay and `StereoPannerNode` for an immersive headphone soundstage.
---
### Domain 3: Live Worship, Band & Stage Performance Engine
#### 3.1 Interactive ChordPro Sheets & Live Transposition
* **The Concept**: Display chords inline or above lyrics with 1-tap live transposition and capo calculation.
* **Why it matters**: Replaces the need for external music stand apps (Planning Center Music Stand, OnSong) on stage.
* **Technical Path**:
* Extend `frontend/lyrics-core.js` to parse ChordPro directives (`[G]`, `[D/F#]`, `{key: G}`).
* Add a Transpose controller (+1 / -1 semitone, Capo selector) that dynamically recalculates chord symbols in real time.
* Add a view toggle: "Lyrics Only" vs. "Chords & Lyrics".
#### 3.2 Bluetooth Foot Pedal / Page-Turner Support
* **The Concept**: Hands-free navigation for musicians on stage using standard Bluetooth foot pedals (AirTurn, PageFlip, Donner, Stomp).
* **Why it matters**: Musicians cannot remove their hands from instruments while playing.
* **Technical Path**:
* Standard foot pedals map to keyboard keys: `PageDown`, `PageUp`, `ArrowUp`, `ArrowDown`.
* Extend the global `keydown` listener in `frontend/app.js` to handle pedal events in Service Mode:
* `PageDown` / `PageUp`: Scroll down / up by one lyric section.
* Configurable actions: Next/Previous track, trigger A-B loop, or jump to Chorus.
#### 3.3 Confidence Monitor & Stage Clock (Presenter Mode)
* **The Concept**: A high-visibility stage display mode for the Presenter screen (`/?present=<code>`).
* **Why it matters**: Singers and worship leaders need glanceable cues for upcoming lyrics, section names, and remaining time.
* **Technical Path**:
* In `Presenter` (`frontend/app.js`), provide a **Confidence Monitor** layout:
* **Current Line**: Extra-large, high-contrast text.
* **Next Line Preview**: Smaller, dimmed text directly underneath.
* **Section Badge**: Prominent label (e.g. `# CHORUS 2`).
* **Stage Clock & Timer**: Current wall clock plus elapsed/remaining song timer.
#### 3.4 Broadcast Lower-Third Overlay for OBS & Live Streams
* **The Concept**: A dedicated live stream output URL (`/?present=<code>&mode=lowerthird`) designed to be added as a transparent Browser Source in OBS, vMix, or ATEM.
* **Why it matters**: Enables churches and streamers to overlay synchronized lower-third lyrics onto their video feed without separate presentation software.
* **Technical Path**:
* Transparent background (`background: transparent;`).
* Auto-updating 2-line broadcast graphic with smooth slide/fade transitions and drop-shadows.
* Driven in real-time by the host or phone remote via the existing WebSocket relay in `server/remote.js`.
#### 3.5 Section Quick-Jump Pad
* **The Concept**: A grid of buttons representing song sections (`[Intro]`, `[Verse 1]`, `[Chorus]`, `[Bridge]`, `[Outro]`).
* **Why it matters**: Worship teams often repeat choruses or spontaneously transition between sections during live services.
* **Technical Path**:
* Parse `# Section` headers from synced lyrics in `frontend/lyrics-core.js`.
* Render an arrangement button strip in Service Mode.
* Tapping a section immediately seeks playback to that section's start timestamp.
#### 3.6 Hardware MIDI Controller Integration (Web MIDI API)
* **The Concept**: Direct plug-and-play support for hardware USB/Bluetooth MIDI pedalboards (Morningstar MC3/MC6, Looptimus, Behringer FCB1010) without native drivers.
* **Technical Path**:
* Use the browser `navigator.requestMIDIAccess()` API.
* Map MIDI Note-On and CC messages to player actions (Play/Pause, Next Track, Chorus Repeat, Tap Tempo, Mute).
#### 3.7 Planning Center Services (PCO) & SongSelect Setlist Importer
* **The Concept**: One-click setlist and chord chart importing from Planning Center Services and CCLI SongSelect.
* **Technical Path**:
* Import setlist text or CSV files from PCO.
* Auto-match titles with YouTube media, attaching keys (`@ Key E`) and chord sheets directly to playlist entries.
#### 3.8 Bilingual & Phonetic Lyrics (Romanization / Transliteration)
* **The Concept**: Simultaneous dual-language or phonetic pronunciation lyrics (e.g. Mandarin with Pinyin, Spanish/English).
* **Technical Path**:
* Extend `frontend/lyrics-core.js` to parse secondary translation lines.
* Display translations or romanized cues in smaller muted text under the primary lyric line.
#### 3.9 Visual Metronome & Count-In Click
* **The Concept**: Visual flash or gentle audio click count-in before track playback begins.
* **Why it matters**: Enables the band to start playing on beat before the recorded track introduces audio.
* **Technical Path**:
* When `@ 70 BPM` metadata is present in song notes, offer an optional 4-beat visual flash on the stage frame or Web Audio click before playback starts.
---
### Domain 4: Interactive Piano Transcription, Sheet Music & Practice Engine
#### 4.1 Automatic Audio-to-Piano Transcription (Polyphonic Audio to Score)
* **The Concept**: Transcribe piano melodies and chords from recorded audio into polyphonic note events (MIDI / MusicXML).
* **Why it matters**: Allows musicians, vocalists, and students to learn the exact piano parts played in any YouTube song or uploaded track.
* **Technical Path**:
* **Option A (Client-Side WASM / WebGPU)**: Run Spotify's **Basic Pitch** model (`@spotify/basic-pitch`) in the browser via TensorFlow.js or ONNX Runtime Web. It performs polyphonic pitch prediction directly on decoded audio frames without server compute.
* **Option B (Server-Side Worker, like `lyrics-worker`)**: Run ByteDance's `piano_transcription_inference` (High-Resolution Piano Transcription on PyTorch/ONNX) inside a container worker. Saves `<id>.notes.json` / `<id>.mid` to the cache directory.
* Output data shape: Array of note events `[{ pitch: 60, start: 1.25, end: 1.85, velocity: 84 }]`.
#### 4.2 Sheet Music Generation & Real-Time Scrolling Score
* **The Concept**: Convert transcribed note events into standard grand staff sheet music (Treble and Bass clefs) rendered on screen.
* **Technical Path**:
* Render sheet notation on an HTML5 `<canvas>` or `<svg>` using **VexFlow** or **OpenSheetMusicDisplay (OSMD)**.
* Display a vertical playhead cursor that scrolls synchronously with `Player.master.currentTime`.
* Support instant transposition: adjusting the song key shifts the musical notation and key signature on the fly.
#### 4.3 Interactive Virtual Piano & Falling Notes (Synthesia Style)
* **The Concept**: A responsive 88-key or 61-key virtual piano keyboard that visualizes which keys to press in sync with playback.
* **Visual Modes**:
* **Falling Notes Mode**: Vertical roll above the keyboard where color-coded note bars fall downward toward the keys (Treble notes in Amber/Coral, Bass notes in Cyan/Blue). When a bar hits the key line, the corresponding piano key illuminates and depresses.
* **Sheet Music + Lit Keys Mode**: Traditional score at the top, illuminated keyboard at the bottom highlighting active notes in real time.
* **Technical Path**:
* Canvas-rendered piano keyboard with responsive key sizing that fits desktop, tablet, and mobile orientations.
* Note rendering loop tied to `requestAnimationFrame` and driven by the current playback timestamp.
#### 4.4 Queued Song & Section Learning Mode
* **The Concept**: A dedicated learning queue and practice loop system that guides users step-by-step through mastering a song.
* **Features**:
* **Queue Practice Sessions**: Queue an entire song, specific sections (e.g. `[Intro]`, `[Verse 1]`, `[Chorus]`), or arbitrary A-B loop bars into the practice queue.
* **Tempo Slowdown (Pitch-Preserved)**: Slow down playback to 50%, 65%, 75%, or 90% speed without altering key.
* **Speed Ramp Auto-Trainer**: Start a looped section at 60% speed; each time the user completes the loop, speed automatically increases by +5% until 100% full tempo is achieved.
* **Loop Pause Interval**: A configurable 1–2 beat pause between repetitions to allow players to reset their hand position.
#### 4.5 Interactive "Wait-for-Note" Practice via Hardware MIDI Input
* **The Concept**: Connect any USB or Bluetooth digital piano / MIDI keyboard to the computer or tablet. The player pauses and waits for the user to press the correct key(s) before advancing!
* **Technical Path**:
* Listen to incoming MIDI `noteon` events via the Web MIDI API (`navigator.requestMIDIAccess()`).
* Compare the user's played MIDI note number against active notes in the transcription dataset.
* If the note is correct, turn the key green and resume playback to the next note event. If incorrect, turn the key red and provide visual guidance on the virtual keyboard.
#### 4.6 Technical Feasibility Analysis
| Component | Technical Feasibility | Resource Cost & Constraints | Recommendation |
|:---|:---|:---|:---|
| **Audio-to-MIDI Transcription** | **High (Proven)** | Basic Pitch: ~15 MB model file, runs on client WebGPU/CPU in ~0.3×–0.8× real time. ByteDance: higher accuracy, requires ~1.5 GB PyTorch model on server. | Use **Basic Pitch (WASM/ONNX)** on client for instant preview; offload to homelab server worker for full-song high-fidelity scores. |
| **Piano Roll / Virtual Keyboard** | **High (Straightforward)** | Pure HTML5 Canvas rendering. Minimal CPU overhead (~60 FPS with <5% CPU usage). | Built natively into frontend without heavy external dependencies. |
| **Sheet Music Engraving** | **High (Proven)** | **VexFlow** (~180 KB minified) renders standard grand staff notation cleanly from JSON notes. | Dynamic import (`import()`) of VexFlow only when the user opens Sheet View. |
| **Interactive MIDI Feedback** | **High (Zero-latency)** | Web MIDI API is supported natively in Chrome, Edge, and Opera (and via polyfill in Firefox/Safari). Latency is sub-5ms. | Native browser event listeners listening to MIDI input. |
---
### Domain 5: Collaboration, Windowing & Mobile Experience
#### 5.1 Document Picture-in-Picture (Always-On-Top Lyrics & Chords)
* **The Concept**: An always-on-top floating desktop window containing interactive synchronized lyrics, chords, and transport controls.
* **Technical Path**:
* Use the Chrome/Edge `documentPictureInPicture.requestWindow({ width: 420, height: 500 })` API.
* Moves the active `#stageLyrics` or ChordPro view into the floating window with full DOM interactivity.
#### 5.2 Voice Search & Driving Car Mode
* **The Concept**: A hands-free, distraction-free interface for driving or kitchen listening.
* **Features**:
* **Voice Search**: Microphone button on the search bar powered by `webkitSpeechRecognition` for real-time speech-to-query search.
* **Car Mode**: One-tap toggle for a simplified layout with giant 100px touch buttons (Play/Pause, Next, Previous, 15s Rewind) and disabled scroll lists.
#### 5.3 Collaborative Setlists & Playlists
* **The Concept**: Multiple devices editing a single playlist simultaneously with live sync.
* **Technical Path**:
* Extend playlist sync in `server/db.js` with shared write keys.
* Broadcast item reordering and song additions over the existing WebSocket hub in `server/party.js`.
#### 5.4 Watch Party DJ Mode & Upvote Queue
* **The Concept**: Allow guests in a watch party (`/ws/party`) to submit song requests that the group can upvote.
* **Technical Path**:
* Add a "Suggested Queue" tab in the watch party drawer.
* Upvotes dynamically sort songs; when current playback finishes, the highest-voted song plays next.
---
### Domain 6: Library, Offline & Sync Innovations
#### 6.1 Visual Download Manager & Storage Dashboard
* **The Concept**: A unified management dashboard in Settings for offline media.
* **Technical Path**:
* Show active download tasks with real-time progress bars.
* List storage usage grouped by playlist, audio vs. video format, and OPFS vs. server cache.
* Add controls: "Pause All", "Resume All", and "Retry Failed".
#### 6.2 Smart Auto-Offline Favorites
* **The Concept**: Keep a user's most essential songs available offline automatically.
* **Technical Path**:
* Setting: *"Keep Top 25 Most-Played Songs Offline"* or *"Keep Active Setlist Offline"*.
* Automated background routine checks local `playCount` and triggers cache downloads for missing items during idle time.
#### 6.3 Self-Contained Offline Playlist Bundling (Zip Export)
* **The Concept**: Export a full offline bundle containing playlist JSON plus the saved audio/video files for complete air-gapped device migration.
---
## 3. Implementation Matrix & Recommended Phases
| Phase | Feature | Effort | Prerequisites & Reused Modules |
|:---|:---|:---:|:---|
| **Phase 1: Quick Wins** | **SponsorBlock & Non-Music Skip** | Low | Free SponsorBlock API, playback tick in `frontend/app.js` |
| | **Automatic YouTube Chapter Ticks** | Low | InnerTube metadata in `server/server.js`, timeline scrubber |
| | **Bluetooth Foot Pedal Shortcuts** | Low | Keydown event listener in `frontend/app.js` |
| | **Section Quick-Jump Pad** | Low | Lyric section parser in `frontend/lyrics-core.js` |
| | **Voice Search (SpeechRecognition)** | Low | Web Speech API, search input handler |
| **Phase 2: Stage & Audio** | **EBU R128 LUFS Normalization** | Medium | ffmpeg `ebur128` in `server/media-cache.js`, Web Audio GainNode |
| | **ChordPro Display & Transpose** | Medium | `frontend/lyrics-core.js`, chord parser |
| | **Confidence Monitor Stage View** | Medium | `Presenter` & `fitLyricLines` in `frontend/app.js` |
| | **OBS Lower-Third Overlay** | Low-Med | `server/remote.js` WebSocket relay, transparent route |
| | **On-Screen Subtitles (CC)** | Medium | `/api/notes/:id/captions`, overlay renderer |
| **Phase 3: Piano & Interactive Learning** | **Interactive Piano Roll & Key Visualizer** | Medium | HTML5 Canvas keyboard renderer, note event synchronizer |
| | **Audio-to-MIDI Transcription** | Medium-High | Spotify Basic Pitch (WASM) / ByteDance transcription worker |
| | **Sheet Music View (VexFlow)** | Medium | VexFlow dynamic import, MusicXML / MIDI generator |
| | **Wait-for-Note Practice (Web MIDI)**| Medium | Web MIDI API (`navigator.requestMIDIAccess`), practice queue |
| **Phase 4: Advanced Engine** | **Audio Stem Separation (Karaoke)** | High | ONNX Runtime Web / server Demucs |
| | **Pitch Shift & Tempo Worklet** | High | AudioWorklet / `SoundTouchJS` DSP |
| | **Document Picture-in-Picture** | Low-Med | Chrome Document PiP API |
| | **Collaborative Setlists** | High | WebSocket hub in `server/party.js` |

View File

@@ -0,0 +1,88 @@
# Fullscreen orientation and iPhone audio continuity
## Task A — done
Settings → Listening → Video & fullscreen offers Auto (follow device), Landscape,
and Portrait. The choice persists on this device and can be cycled from the
fullscreen controls. Supported browsers request fullscreen and then lock the
selected orientation; Auto leaves orientation unlocked. Exit releases our lock.
When orientation locking or element fullscreen is unavailable, the player uses a
viewport overlay. A portrait viewport with Landscape selected rotates the existing
stage and its controls 90 degrees; Portrait in a landscape viewport rotates it
in the opposite direction. Safe-area padding follows the rotated axes. Touch
seeking, double-tap seeking, volume/brightness swipes and pinch movement use
inverse coordinates. The video stays in its existing DOM position to avoid
interrupting WebKit playback. Controls and browser fullscreen exit restore the
inline surface, including when a native orientation lock was rejected.
Safari's custom overlay fills the available dynamic viewport; it cannot force
Safari to hide browser chrome or change the phone's physical orientation. An
installed PWA has no browser toolbar occupying that viewport.
Files: `frontend/fullscreen-orientation.js`, `.css`, `.test.js`, small hooks in
`app.js`, `index.html`, `sw.js`, `tests/fullscreen-orientation.spec.js` and
`playwright.fullscreen.config.js`.
## Task B — done; physical iPhone verification remains
The previous progressive handoff loaded the audio source and sought it only when
the page was hidden, then paused the video before transferring master ownership.
That required a cold audio decoder start and allowed pause-handler re-entry.
Foreground recovery also sought the video, whose shared seeking handler then
sought the still-playing audio. Repeated play/playing/focus/watchdog handlers
could independently issue the same audio play/seek requests.
On iPhone, progressive playback now uses the existing dual playback path from the
start: a muted video and an audible audio element. Saved files use the same local
source; streams prefer their audio-only URL, falling back to the muxed source.
EQ-render playback already used this path and remains unchanged. Locking promotes
the already-playing audio to master without loading, seeking or restarting it.
Unlocking aligns only the silent video; its internal seek does not propagate to
the audible audio. Pending play requests are shared, small drift does not cause
seeks, and the watchdog never seeks an element to itself. Hidden focus events do
not restore the video prematurely. The audio clock still owns background progress
and ended events, preserving auto-advance and lock-screen playback intent.
This uses an audio decoder alongside video while visible. Audio-only playback
and tracks that start while already backgrounded retain their existing paths.
Browsers other than iPhone retain their foreground progressive path. Their cold
handoff fallback now sets master ownership before media events and waits for audio
to play before pausing video; returning keeps that audio playing while video resumes.
Files: `frontend/audio-continuity.js`, `.test.js`, player/event hooks in `app.js`,
`index.html`, `sw.js`, `tests/audio-continuity.spec.js`, and
`playwright.audio-continuity.config.js`.
## Validation and hardware review
- 132 frontend unit tests pass, including orientation mapping, source selection,
small-drift policy, concurrent play deduplication, autoplay rejection retry, and
stale pending requests after pause/source reset.
- `node --check frontend/app.js` and `bun build --no-bundle server/server.js` pass.
- Eight fullscreen browser cases pass in Chromium/WebKit at 390 × 844, covering
Classic and Glass Stage overlays, visible controls, quick toggle, exit/restore,
lock/unlock calls and browser exit after lock rejection.
- Four audio browser cases use real local PCM media in Chromium/WebKit, with an
iPhone user agent, covering saved and streamed progressive attachments. Repeated
visibility/pagehide/focus/pageshow events keep the same advancing audio element
with zero audio loads, pauses, seeks or additional play calls.
- All 155 server tests pass with `YTDLP_PATH=/tmp/ytplayer-test-yt-dlp` (the existing
local test ZIPAPP). The initial default run failed because the system Python
environment lacked `yt_dlp`; no server changes were necessary.
Review on an actual iPhone in Safari and installed PWA: saved MP4, streamed songs,
EQ renders, multiple lock/unlock and app switches, auto-advance while locked,
Media Session controls, seeking and PiP. Test Landscape/Portrait with safe areas,
rotation and touch swipes in both themes. On Android/PWA, verify an actual native
orientation lock and release; browser tests verify API calls with a controlled
orientation implementation.
iOS may suspend JavaScript, pause media or interrupt the audio session during lock,
app switching, route changes or incoming calls. A web app cannot guarantee a zero
OS-level gap. These tests demonstrate removal of application-induced source
reloads and audio seeks; desktop WebKit cannot simulate physical iOS suspension.
Tracks first started in the background still reattach their picture on return;
that existing transition also needs hardware review.
No server imports were added, and nothing was pushed or deployed.

View File

@@ -0,0 +1,18 @@
# Glass Stage control consistency
Glass navigation and browsing controls now use Now Playing's existing vocabulary: 20 px SVGs with rounded 1.9 strokes, translucent tile surfaces, 18 px button corners, muted foregrounds, coral active/destructive states, and visible focus rings. Navigation badges use the same palette with readable 11 px counts.
The stylesheet is entirely scoped to `html[data-layout="glass-stage"]`. Existing hidden navigation SVGs are reused. A small Glass-only module draws legacy button glyphs without changing IDs, listeners or existing accessible labels; switching away restores the original glyphs and removes its temporary accessibility labels. It observes page updates only while Glass is selected. The existing Now Playing design remains the reference.
Coverage: bottom tabs and badges, sidebar rows, search/queue/history/playlist row actions, saved-file actions, download controls, Settings navigation/buttons, notes tabs and mini-player buttons. Glass row actions reserve space so long titles remain readable. Section shortcuts sit lower-left rather than covering right-hand file actions. Downloads' bottom-tab label stays fully visible.
Validation:
- 115 frontend unit tests; app/module syntax; server no-bundle build.
- Browser coverage for Classic and Glass at 390 and 1440 px across seven page states; keyboard button commands, focus, theme restoration, mini-player controls, settings reachability and file-action hit testing.
- Fourteen Classic before/after screenshots compare against the same fixture with the new assets disabled. Control geometry and computed styles match exactly. PNG comparison allows at most 16 isolated browser rasterization pixels in the entire screenshot (roughly 0.005% at phone size); no layout/theme difference is tolerated.
- Batched visual review and a single confirmation of the label/shortcut corrections. The apparent clipped Settings row is within its normal scroll container; a test reaches the final row.
Captures are local files under `/tmp/glass-polish-before-*` and `/tmp/glass-polish-after-*`, plus `/tmp/glass-polish-navigation-notes-mini.png` and `/tmp/glass-polish-settings-end.png`. Before/after fixtures suppress animations and automatic saving so playback/network timing cannot change the comparison. The installed bottom navigation is exposed in one isolated fixture because ordinary Chromium is not an installed PWA.
Reviewer: check a real installed iPhone PWA's bottom bar, mini-player clearance and theme switching, plus keyboard/hover behavior on desktop. No playback implementation, Classic stylesheet, credentials or deployment was changed.

View File

@@ -0,0 +1,67 @@
# Glass Stage iPhone layout follow-up
The supplied production screenshots came from build `16c08b099a31`, before the
Task A/B changes. This follow-up preserves the Glass Stage colours, glass tiles,
stroke icons and all existing control ids/actions. Every CSS rule is scoped to
`html[data-layout="glass-stage"]`; Classic retains its original rail and labels.
## Panel shortcuts and bottom chrome
The Glass section rail was a fixed horizontal overlay positioned above the mini
player. Clearing the player did not clear a panel heading or filter underneath.
`glass-panel-layout.js` moves that same rail, with its existing listeners, into
`#listPane` before the heading. It restores the original location when leaving
Glass Stage. The rail now occupies its own row instead of covering content.
The module measures the visible fixed bottom navigation and mini player. The
navigation's measured height already contains the home-indicator safe area;
the mini player sits eight pixels above that height. Scroll clearance includes
both bars and a 16 px gap, without counting the safe area twice. Portrait uses
one shared scroller and reserves that clearance once at its tail; desktop panes
reserve it individually. The mini player's outer card clips the progress strip
inside its rounded border, rather than leaving a separate line below it.
## Bottom navigation
The uploaded rightward icon shift is reproduced by the pre-Task-A CSS from
`f2c9459`: installed-PWA padding of `4px 16px` remained on a fixed-width icon box.
Task A (`79a3c28`) already resets that padding to zero. The new regression test
runs an iPhone 13 browser profile at 390 px, including 34 px bottom safe-area
allowance, Queue/Downloads badges and an active pill. In both Chromium and
WebKit, SVG and icon-box centres match label centres within 0.6 CSS px. The old
CSS shifts every icon more than eight CSS px. No further nav CSS change was
needed; this is committed verification of the existing fix.
## Notes toolbar
The toolbar's Glass override explicitly enabled `flex-wrap:wrap`. It now keeps
one row. Container queries respond to the player card's available width, even
when a desktop player column is narrow. Spacing tightens first, the longer
Chapters & bookmarks label becomes icon/count at narrow card widths, and all
labels become icon-only on the smallest cards. Full accessible names and title
hints remain. Every action retains a minimum 44 px target, and the fold chevron
stays at the row's right end. Status text truncates within the remaining space.
Glass label wrappers and added names restore exactly when switching to Classic.
## Verification
- 125 frontend unit tests pass, including measured chrome-clearance logic.
- `node --check frontend/app.js` and `bun build --no-bundle server/server.js` pass.
- Chromium and WebKit: all five panel shortcuts at 390 and 1440 px; final list
row clears playback chrome; progress strip stays inside its card.
- Classic geometry and before/after screenshot comparisons pass in both browsers
at 390 and 1440 px, within the 32-pixel isolated rasterization tolerance.
- iPhone-profile navigation alignment/badges pass in both engines at 390 px.
- Toolbar stays one row at 320, 360, 390, 430 and 1440 px in both engines, including
long status text and chapter counts; theme round-trip restoration passes.
- Batched visual review of six WebKit captures found no overlap, alignment,
clipping or wrapping defects in the requested areas.
Run `npx playwright test -c playwright.glass-panel.config.js` for the 22 browser
cases. WebKit was installed locally for these checks; these are browser/iPhone
profile tests, not tests on physical iPhone hardware. Review the installed PWA
on an actual iPhone after the reviewer deploys, particularly when the mini
player appears/disappears and after rotating the phone.
Before/after captures are saved under
`/home/josh/deliverables/ytplayer-done9/`. No push or deployment was performed.

191
docs/improvement-plan.md Normal file
View File

@@ -0,0 +1,191 @@
# ytplayer — Speed & Features Plan (2026-09-29)
Scope: **make the app faster** (startup, search, pressing play, moving around)
and **add new features**, led by **peer-to-peer video sharing**. Hardening/refactor
work is intentionally out of scope.
## Integrated roadmap (what is queued and executable today)
Everything below is broken into step-by-step plans a smaller model can execute
without exploring the code — see `plans/INDEX.md`. All 19 were dry-run end to end.
| Order | Plans | What it delivers | Source |
|-------|-------|------------------|--------|
| 1 | `001` | Timing marks (`ytp:boot`, `ytp:search`, `ytp:tap-to-play`) + yt-dlp duration logs | A "Measuring" |
| 2 | `002`–`003` | Compressed + ETagged shell (app.js 426 → 94 KB), self-hosted fonts | A1.1–A1.3 |
| 3 | `004`–`005` | One yt-dlp resolve per video at a time; resolve likely next plays before the tap | A3.1–A3.2 |
| 4 | `006`–`007` | Search via InnerTube (~0.8 s, yt-dlp fallback); long-lived yt-dlp workers | A2.1, A3.3 |
| 5 | `008`–`019` | **Peer-to-peer sharing** — design and rules in `docs/p2p-architecture.md` | Part B0 |
Not queued yet (write plans for them with `/plan-queue` when reached): A1.4 minify,
A1.5 deferred boot work, A1.6 lazy modules, A2.2 suggestions, A2.3/A2.4, A3.4/A3.5,
A4 (VPS media cache), A5 polish, and the Part B feature list.
## Where the time goes today (measured against prod)
Measured with `curl` from a cloud container on 2026-09-29, so absolute numbers
include this client's network; the *differences* are what matter.
| What | Measured | Of which is the app itself |
|------|----------|----------------------------|
| Trivial request (`/api/version`) | ~1.25 s (≈0.9 s TLS setup, ≈0.35 s request) | ~0.35 s round trip through VPS → WireGuard → homelab |
| Download `app.js` | 2.8 s at ~150 KB/s | **426 KB sent uncompressed** — no `content-encoding`, no ETag |
| `/api/search` (new query) | 4.1–5.0 s | ~3.5 s is one yt-dlp spawn (already `--flat-playlist`) |
| `/api/search` (repeat, 3-min cache) | 1.2 s | cache hit = baseline |
| `/api/streams` (first play) | **7.5 s** | ~6 s is `yt-dlp -J` |
| `/api/streams` (second play) | 1.2 s | `streamCache` hit |
Shell sizes: `app.js` 426 KB → **118 KB gzip**; `styles.css` 161 KB → 32 KB;
`index.html` 32 KB → 8 KB. Total first load **618 KB → 158 KB** just by
compressing. Plus a render-blocking Google Fonts stylesheet (3 families, 10
weights) before first paint.
The three biggest wins, in order: **(1) compress + ETag the shell, (2) stop
paying a cold yt-dlp spawn on every search and first play, (3) start that work
before the user taps.**
---
## Part A — Speed
### A1. App startup (first paint, cold and warm)
| # | Change | Expected gain | Effort |
|---|--------|---------------|--------|
| A1.1 | **Compress static + JSON.** At boot (and when `BUILD_TAG` changes) pre-compress every shell file with `Bun.gzipSync` / brotli, keep them in memory, serve by `Accept-Encoding` with `Vary: Accept-Encoding`. JSON API responses via `hono/compress`. **Never** compress `/api/play`, `/api/media/*` (Range media). | Shell 618 → ~158 KB; ~2 s off a cold load at the measured rate | S |
| A1.2 | **ETags on the shell.** Everything is `Cache-Control: no-cache`, which is right (see CLAUDE.md update flow), but without an ETag every revalidation re-downloads the full body. Use the content hash already computed for `BUILD_TAG` per file → `304 Not Modified`. Keeps the update-flow rules intact. | Non-SW loads and SW revalidations drop to a few hundred bytes | S |
| A1.3 | **Self-host the fonts** as subset `woff2` (Latin only, only the weights used: `--ui`, `--display`, `--mono`), `<link rel="preload">` the display face, `font-display: swap`. Removes 2 third-party origins (DNS + TLS each) from the critical path and makes fonts work offline via the existing `ytplayer-fonts` cache. `fitLyricLines` already re-fits on `document.fonts` load, so late swaps are safe. | 0.3–1 s off first paint on mobile | S |
| A1.4 | **`defer` the scripts** and minify at Docker build time with esbuild `--minify-whitespace --minify-syntax` (**no identifier mangling** — the files share top-level globals as classic scripts). Keep sources unminified in git; `BUILD_TAG` still hashes `./public`. | app.js gzip ~118 → ~80 KB, parse time down | S |
| A1.5 | **Defer non-critical boot work.** `boot()` wires everything synchronously. Move `warmOfflineThumbs`, `preloadPlaylist` sweeps, stats commits, remote/party sockets and the inbox poll behind `requestIdleCallback` (fallback `setTimeout 1500`). Measure with a `performance.mark` around boot first. | Faster time-to-interactive on older phones | M |
| A1.6 | **Lazy-load rare features** (Party, Presenter, Remote, EQ, Share/GIF, the video editor) with `import()` on first use. Needs those sections pulled out of `app.js` into their own files — do only the ones that are large and self-contained. Every new file must be added to the SW `SHELL` list (or offline breaks). | 20–35 % less JS parsed at start | M–L |
### A2. Search (4–5 s → target < 1.5 s)
| # | Change | Effort |
|---|--------|--------|
| A2.1 | **Direct InnerTube search.** Call `https://www.youtube.com/youtubei/v1/search` from Bun with `fetch` (WEB client context), map `videoRenderer` items to the existing slim card shape. One HTTPS call instead of starting Python. Keep yt-dlp as the automatic fallback on any parse error / non-200, so a YouTube change degrades to today's speed, not to broken. Add a contract test on a saved response fixture. | M |
| A2.2 | **Suggestions as you type** from `suggestqueries.google.com/complete/search?client=youtube&ds=yt` (proxied + cached server-side, debounced 150 ms client-side), mixed with the existing on-device `RecentSearches`. | S |
| A2.3 | **Start the search on Enter-intent**: fire the request on the debounced input once the query is stable for ~600 ms, so pressing Enter usually hits the 3-min server cache (the ⚡ indicator already exists). | S |
| A2.4 | **Stream results in**: render the library/uploads hits (local DB, instant) immediately, then the YouTube results when they land. | S |
### A3. Pressing play (7.5 s cold → target < 2 s)
| # | Change | Effort |
|---|--------|--------|
| A3.1 | **Coalesce concurrent resolves.** `resolveStreams()` checks `streamCache` but has no in-flight map, so a warm-up + the real request (or two devices) spawn two yt-dlp processes for one id. Add `inflightStreams: Map<id, Promise>`. Prerequisite for A3.2. | S |
| A3.2 | **Warm on intent.** New `GET /api/streams/warm?v=` (204, fire-and-forget, low priority, capped concurrency) that fills `streamCache`. Client calls it: for the top 3 results when a search renders; on `pointerdown`/hover of a card (≥150 ms hover on desktop); for the next 2 queue items when a song starts. Cold plays then hit the 1.2 s cached path. | S–M |
| A3.3 | **Persistent extractor process.** Replace per-call `spawn(yt-dlp)` with a small long-lived Python worker (`scripts/ytdlp-worker.py`) that imports `yt_dlp` once and answers JSON requests over stdin/stdout (or a unix socket). Saves Python start-up, extractor import and — with a persistent `--cache-dir` on the data volume — repeated player-JS / n-challenge work. Keep the spawn path as fallback; restart the worker if it dies or after N requests. Applies to search/channel/expand too. | M |
| A3.4 | **Instant UI on tap.** Show title, thumbnail (already cached by the SW), lyrics and related immediately from the card data while `/api/streams` is pending, with a thin progress bar on the player — no blank player. | S |
| A3.5 | **Fast first frame**: start playback on the lowest adaptive height that looks acceptable on the device (e.g. 360p on phones), then switch up once buffered, instead of waiting on the highest quality's first bytes through the proxy. | M |
### A4. Playback throughput & seeking
- **The VPS → homelab WireGuard link carries every media byte** (`/api/play`
proxies googlevideo; the server cache serves from the homelab). Measure it
(`iperf3` over the tunnel) before optimising anything else here.
- If it's the bottleneck: a small **Traefik/nginx cache on the VPS** for
`/api/media/<id>?g=<gen>` — those URLs are immutable by design (the gen is in
the URL), so they can be cached aggressively with Range support
(`slice` module). Hot songs then come straight from the VPS.
- Mark `/api/media/<id>?g=` responses `Cache-Control: public, max-age=31536000,
immutable` so repeat plays on the same device hit the browser cache.
- Waveform peaks: `ytpPeaks` is already local; also send peaks with a long
`max-age` since they're per-gen.
### A5. Feels-faster polish
- View Transitions API between Home ↔ playlist ↔ search (progressive; no-op
where unsupported).
- Optimistic playlist edits (add/remove/reorder paint first, sync after — the
sync is already debounced).
- `content-visibility: auto` on long playlist/history lists; virtualise lists
over ~300 rows.
- Image decoding: `loading="lazy" decoding="async"` + fixed aspect-ratio boxes on
every thumbnail (no layout shift while scrolling results).
### Measuring (do this first, keep it running)
- Add `performance.mark`s: `boot-start`, `first-render`, `search-submit →
results-rendered`, `play-tap → playing`. Report the medians to a tiny
`POST /api/perf` (sampled, no PII) and show p50/p90 in `/admin`.
- Server-side: log yt-dlp duration per call type, and cache hit rates for
search/streams/media.
- Targets: cold load < 2 s on 4G, repeat load < 0.5 s (SW), search < 1.5 s,
tap-to-sound < 2 s cold / < 1 s warmed.
---
## Part B — New features
### B0. Peer-to-peer video sharing (queued: plans 008–019)
The server keeps the user list, the video list and metadata; every validated copy
gets a content id = SHA-256 of its bytes; devices that save a video become persistent
**holders**; when YouTube and the server copy are gone, devices serve each other over
WebRTC and can restore the server's copy. Rules the owner set (2026-09-29):
**P2P is on by default**, the **server malware scan is off by default** (hashing +
media validation always run), and holder records are **persistent** — the UI shows
when each was last verified and marks old ones **stale** instead of dropping them.
Full design, data model, flows and security rules: `docs/p2p-architecture.md`.
The earlier phase 02–06 draft is superseded; its differences are listed at the end of
that document.
### Other features (not queued yet)
Ranked by fit with how the app is actually used (worship sets, sing-alongs,
offline playback). Each is sized; most reuse machinery that already exists.
### B1. Worship & service
| Feature | What it is | Reuses | Effort |
|---------|-----------|--------|--------|
| **Service plans** | Date-stamped set lists: songs in order + key, notes, who leads; a read-only share link for the band; one tap opens service mode on it. | playlists, per-song notes, share codes, service mode | M |
| **Chord charts** | ChordPro import/paste, chords shown above lyric lines, **transpose** ± semitones using the existing `@ Key G` tag, capo helper. | lyrics editor + `lyrics-core.js` parser | M–L |
| **Confidence monitor** | Presenter variant for the stage: current line large, next line below, song section and a clock. | Presenter + `fitLyricLines` | S |
| **Presenter themes** | Background colour/image/looping video, font choice, safe-area margins, lower-third mode for livestreams (transparent background for OBS). | Presenter | M |
| **Pitch shift** | Play a song in the band's key: pitch-preserving key change via a Web Audio worklet (desktop/Android; iOS keeps original because of the Web Audio lock-screen issue already documented). | EQ wiring, rate control | M |
| **Count-in & click** | Optional metronome click + 4-beat count-in from the `@ 70 BPM` tag for practice. | lyrics tags, Web Audio | S |
| **Section loops** | Loop a chorus/bridge by tapping a `# Section` in the lyrics (sets A-B from the section's stamps). | A-B loop, lyric sections | S |
### B2. Listening & discovery
| Feature | What it is | Effort |
|---------|-----------|--------|
| **Radio / autoplay mix** | When the queue ends, keep going with related videos weighted by your play counts and skips. | M |
| **Smart playlists v2** | Rules like "played ≥ 5× in 30 days", "saved offline", "has synced lyrics", "under 5 min". `SMART_PLAYLISTS` already exists — make them user-defined. | S–M |
| **Stats wrap-up** | Monthly/yearly recap card (top songs, minutes, streak) from `data.stats`, shareable as an image. | S |
| **Sleep/wake alarm** | Start a playlist at a set time (while the app is open / PWA foreground). | S |
| **Lyrics search** | Search across all saved songs' lyrics ("which song has *'goodness of God'*"). Server-side over `video_notes`. | S |
### B3. Offline & library
| Feature | What it is | Effort |
|---------|-----------|--------|
| **Download manager** | One screen: queued/active/done saves with progress, retry, pause-all, storage used per playlist. | M |
| **Auto-offline favourites** | Keep the N most-played songs saved automatically, evict the least-played. | S |
| **Uploads for everyone** | Let profile users (not just admin) upload audio to their own library, with a per-profile quota. | M |
### B4. Together
| Feature | What it is | Effort |
|---------|-----------|--------|
| **Collaborative playlists** | A playlist several profiles can edit (last-write-wins per entry, change feed). | M–L |
| **Party queue voting** | Guests suggest songs; host approves or upvotes decide order. | M |
| **Reactions in party** | Lightweight emoji reactions over the video/lyrics. | S |
---
## Suggested order
1. **Run the queue** (`/run-queue`): plans `001`–`007` (speed), then `008`–`019`
(peer-to-peer). Deploy after `007` and measure with the `ytp:*` marks and the
`[ytdlp]` log lines before starting P2P.
2. **Next speed plans to write:** A3.4 instant UI on tap, A2.2 suggestions,
A1.5 deferred boot work, then measure the WireGuard link (A4) and decide on the
VPS media cache.
3. **Then features**, starting with the small high-fit ones: section loops,
confidence monitor, count-in, lyrics search, stats wrap-up — then
service plans and chord charts.
Each item is sized to be one commit (CLAUDE.md commit rules); queue new ones with
the `plan-queue` skill.

12
docs/lyric-languages.md Normal file
View File

@@ -0,0 +1,12 @@
# Translations and pronunciation
A cue can contain a primary lyric and translation separated by ` / `:
```
[1:23.45] 主你的恩典 / Your grace is enough
!pinyin: zhǔ nǐ de ēndiǎn
```
The translation and phonetic text share the primary cue timestamp. They are smaller and muted beneath it in stage lyrics, Service mode, Presenter and OBS. The notes API preserves optional `secondary` and `phonetic` fields. Existing documents with only text, timing and kind remain unchanged.
Use `| ` continuation lines (or Shift+Enter in the editor) for tight breaks within a cue. A continuation can also carry `Primary / Translation`. Multiple timestamps copy translations and pronunciation to every occurrence. A slash without surrounding spaces, such as `and/or`, remains literal. Ordinary `! Band cue` lines retain their existing meaning.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,36 @@
# Now Playing list return regression
The shared browsing list retains the last page independently of the live playback
queue. Search home hides `#listPane`; the mini-player previously only removed
`home-over` and scrolled. It did not reset that hidden flag or replace the previous
page with the playing playlist. At 390 px the original code fails in both Classic
and Glass Stage with `#listPane` still hidden after tapping the mini-player.
The separate `#upnext` card remained intact in this reproduction.
Returning now rebuilds the source playlist and Up next. If its source playlist
was removed (or playback came from search/channel/history), the list displays the
live queue, without replacing it with the unrelated editable saved queue.
Mini-player, close, Player jump, user-picked track/deep-link reveal and browser
history returns share the restoration. Auto-advance still skips the reveal hook.
History entries retain browsing views, and Settings section entries remain owned
by Settings. Repeated restoration does not add duplicate player history entries.
Run `npx playwright test --config playwright.now-playing.config.js`.
The 20 cases cover both themes at 390/1440 px, return controls, Back/Forward,
missing source playlists, stale Up next DOM, repeated returns and an exhausted
queue. Synthetic tracks avoid dependence on YouTube decoding/network; the
track-reveal case exercises the shared post-load hook, rather than real media
loading. Headless Chromium exposes the mini-player via test CSS because it is
not an installed phone PWA. The Player jump is tested only at phone width,
where that navigation exists.
Validation: 115 frontend unit tests, app syntax check, server build and 20 browser
cases pass. Replaying the 390 px mini-player tests with the original app script
fails in both themes at the hidden list assertion; the patched script passes.
No server implementation or tests changed.
On a real iPhone, confirm the same browse/return sequence in Safari and the
installed PWA, plus Back/Forward and an actual shared video deep link. Confirm
playback keeps its position and the page scrolls to the player without shifting
the document viewport. Desktop checks cover both themes; no playback/background,
playlist action layout or device-export implementation was changed.

155
docs/p2p-architecture.md Normal file
View File

@@ -0,0 +1,155 @@
# Peer-to-peer video sharing — architecture (2026-09-29)
Source of truth for plans `008`–`019` in `plans/queue/`. Every P2P plan links here
instead of repeating the rules. It replaces the earlier "phase 02–06" draft; the
differences are listed at the end.
## What the owner asked for
> Peer-to-peer saving of videos. The server stores the user list, the video list and
> metadata. While the original source is online, a video is available for streaming
> and download. When it is downloaded to a device, the server records that device in
> the list of holders, so the video stays reachable from devices after the source is
> gone. Top or recent files stay on the server under a total space limit; files that
> don't meet the criteria (e.g. number of views, also stored on the server) are
> deleted first. The video id is the file hash of the highest-quality copy. The
> database grows over time. Each device has its own database that can be synced or
> added to the server's, with verification that the file exists. A file must first be
> downloaded by the server and checked before its hash is added to the server DB.
Corrections to the earlier draft (owner, 2026-09-29):
1. **P2P is ON by default** (server and every client).
2. **The server's malware scan is OFF by default** (admin opt-in). Hashing and the
media validation gate are ALWAYS on and cannot be turned off.
3. **Holder records are persistent, not short-lived leases.** A device stays listed
as a holder until it says the file is gone, fails a check, or its reported list no
longer contains it. The UI shows when each holder was last verified and marks it
**stale** when that is older than `P2P_STALE_DAYS` (default 7). Online-right-now is
a separate, live signal.
## Vocabulary
| Term | Meaning |
|------|---------|
| **source** | Where bytes originally come from: YouTube (via yt-dlp) or a server upload (`upl_…`). |
| **video id** | Existing ids (`dQw4w9WgXcQ`, `upl_…`). Still used everywhere in the app and API. |
| **content id (`cid`)** | Lowercase hex SHA-256 of the exact file bytes. The P2P identity of a file. One video id can have several cids over time (a better master, the HEVC copy). |
| **master** | The best copy the server keeps for a video: today the validated ≤720p H.264+AAC faststart MP4 in `MEDIA_DIR` (`<id>.<gen>.mp4`). The compression lane's HEVC copy is a second, separately hashed file. Raising the master quality later just creates new cids linked by `video_id`. |
| **verified content** | A `p2p_content` row. Exists only after the server itself held the complete bytes, computed the SHA-256 itself and `validateMedia()` passed (plus the malware scan if enabled). |
| **holder** | A device that reported holding a cid. Row in `p2p_holders`, never deleted by time. |
| **online** | The device has an open `/ws/p2p` socket right now (in memory only). |
| **stale** | `now - last_verified_at > P2P_STALE_DAYS`. Shown in the UI, still listed. |
## Data model (server, libsql — grows forever)
Added by plan 008 in `server/p2p-db.js` (`initP2pSchema()` runs after `initDb()`):
```sql
p2p_content (cid PK, video_id, size, height, vcodec, acodec, duration, meta JSON,
origin 'server'|'intake', status 'verified'|'revoked',
scan 'skipped'|'clean', created_at ms, verified_at ms)
p2p_devices (device_id PK 'dev_<16hex>', secret_hash, fingerprint, profile,
share 0|1, created_at ms, last_seen_at ms)
p2p_holders (cid, device_id, status 'active'|'removed', trust 'reported'|'challenged',
first_reported_at ms, last_verified_at ms, removed_at ms NULL,
PRIMARY KEY (cid, device_id))
video_views (video_id, day 'YYYY-MM-DD', n, PRIMARY KEY (video_id, day))
media_cache.sha256 -- new column: cid of the current <id>.<gen>.mp4
```
"User list" = the existing `users` (fingerprints) and `profiles` tables plus
`p2p_devices`. Nothing is ever deleted from `p2p_content`; a bad file is `revoked`.
## Configuration (`server/p2p-config.js`, plan 008)
| Env | Default | Meaning |
|-----|---------|---------|
| `P2P_ENABLED` | `1` (on) | `0` turns off every P2P route, the hub and client features. |
| `P2P_MALWARE_SCAN` | `0` (off) | `1` runs `P2P_SCAN_CMD <file>` before admission; exit 0 = clean, 1 = infected (rejected), other = error (not admitted, retried later). |
| `P2P_SCAN_CMD` | `clamscan --no-summary --infected` | Needs an image built with `--build-arg INSTALL_CLAMAV=1`. |
| `P2P_STALE_DAYS` | `7` | Holder older than this is shown as stale. |
| `P2P_KEEP_MIN_VIEWS` | `3` | Retention: views in the last `P2P_KEEP_DAYS` that make a server copy "top". |
| `P2P_KEEP_DAYS` | `30` | Window for counting views. |
| `P2P_KEEP_RECENT_DAYS` | `14` | Retention: played this recently = "recent". |
| `P2P_INTAKE_DIR` | `<DB dir>/p2p-intake` | Quarantine for device uploads. Never served. |
| `P2P_INTAKE_MAX_BYTES` | `3 GiB` | Largest accepted intake upload. |
Client settings (`data.settings`, per profile): `p2pShare: true` (let other devices
download my saved videos, and report holdings), `p2pReceive: true` (fetch from other
devices when YouTube and the server can't serve).
## Flows
1. **Server fetch (existing media cache) → verified content** (plan 009).
`runFetch` / `runOptimize` hash the promoted file, store `media_cache.sha256`, run the
scan if enabled, then upsert `p2p_content` (`origin 'server'`). `/api/download` sends
`X-Content-SHA256`. A backfill hashes already-cached files at boot, one at a time.
2. **Device save** (plan 012). The OPFS worker hashes while it writes. If the server
sent `X-Content-SHA256` and the hash differs, the save fails (bonus integrity check).
The device DB (`IndexedDB ytp-device`, store `files`) records `{videoId, cid, size,
savedAt, lastCheckedAt, state}`; `state` is `verified` when the hashes matched,
`unverified` when the server sent no hash, `unhashed` for old saves and the
main-thread fallback path.
3. **Holdings sync** (plan 013). Device registers once (`POST /api/p2p/device` →
`deviceId` + `secret`, kept in `localStorage.ytpDevice`). It reports its holdings
(`POST /api/p2p/holdings`, full list at launch, deltas after save/delete). The server
accepts only cids in `p2p_content` with `status='verified'`; unknown cids come back
in `unknown` (candidates for intake). When the server still has the file it returns
up to 5 **range challenges**; a correct answer sets `trust='challenged'`, a wrong one
removes the holder. `last_verified_at` = time of the last report where the device
re-checked the file (exists, same size; full re-hash every 30 days). A full report
marks every active holder row of that device that is missing from the list as
`removed`. There is **no TTL**.
4. **Presence** (plan 014). `/ws/p2p` socket per device, authenticated with the device
secret. Online status lives only in memory. The hub also relays WebRTC signalling
between two online devices and carries server → device requests (plan 018).
5. **Availability** (plans 014/015). `GET /api/p2p/holders?v=<videoId>` lists cids and
their holders: opaque peer id (never the fingerprint/profile), `online`,
`lastVerifiedAt`, `stale`, `trust`, plus `serverHas`. The UI shows e.g.
"📡 On 3 devices · 1 online now · last checked 2 d ago", with stale holders greyed.
6. **Peer download** (plan 017). WebRTC data channel (STUN only, same ICE list as watch
party), 64 KiB frames with `bufferedAmount` back-pressure, receiver writes through a
worker into OPFS while hashing; only a matching SHA-256 is committed. The new copy
is a holder at the next report. Download-then-play; no progressive peer streaming.
Used when `/api/streams` fails and the device has no copy, and from a
"Get from a device" button.
7. **Intake** (plan 016). A device can hand a file to the server
(`POST /api/p2p/intake` → ticket, `PUT` the bytes). The server writes it to the
quarantine dir, hashes it, runs `validateMedia()`, runs the scan if enabled, and only
then inserts `p2p_content` (`origin 'intake'`). If the server has no copy of that
video it adopts the file into the media cache (budget permitting).
8. **Rehydrate** (plan 018). When a video is requested, its source fails, the server
evicted its copy, and a verified holder is online with `p2pShare` on, the hub asks
that device to upload it through intake (known cid → quick accept).
9. **Retention** (plan 010). Views are counted per video per day. When the media cache
needs room it evicts in this order: copies that are neither "top"
(`views in P2P_KEEP_DAYS ≥ P2P_KEEP_MIN_VIEWS`) nor "recent" (played within
`P2P_KEEP_RECENT_DAYS`), fewest views first, then oldest; only then the qualifying
ones by LRU. The 10-minute play protection and `MEDIA_CACHE_MAX_BYTES` stay.
Evicting a server copy never deletes `p2p_content` or holder rows.
## Security rules every plan must keep
- No cid enters `p2p_content` unless the SERVER computed it over bytes it holds and
`validateMedia` passed. Clients can never insert or edit content rows, views or trust.
- Intake files live in `P2P_INTAKE_DIR`, never under `./public` or `MEDIA_DIR`, and
are deleted on failure.
- Device secrets: 32 random bytes, only `sha256(secret)` stored, compared with
`timingSafeEqual`.
- Holder lists never expose fingerprints, profile names or IPs; a peer id is
`sha256('peer:' + device_id).slice(0, 12)`.
- The hub relays signalling only between two authenticated, online devices, with a
per-socket message budget.
- `P2P_ENABLED=0` must leave the rest of the app working exactly as before.
- Jobs stay server-owned; never pass a request `AbortSignal` into them (CLAUDE.md).
## Where this differs from the earlier phase 02–06 draft
| Earlier draft | Now |
|---------------|-----|
| "Default-off" P2P subsystem; "no inventory/upload from default settings" | P2P on by default; devices report holdings and seed by default (can be turned off). |
| Mandatory scanner, "scan skip is failure" | Scanner off by default (`P2P_MALWARE_SCAN=0`); hash + `validateMedia` mandatory. |
| Short-lived online leases; "cache availability only as an expiring hint" | Persistent holder rows with `last_verified_at` and a stale marker; online status is separate. |
| Migrate all localStorage (`_ytpdata`) to IndexedDB first | Not now: the device DB holds files + cids only. `_ytpdata` stays in localStorage (lower risk). |
| Collections, invitations, scoped principals, signed manifests, TURN, renditions lineage | Deferred. Scope is one shared catalog + device secrets; add later if needed. |
| Separate `server/p2p/*` directory with migrations ledger | Flat files `server/p2p-*.js` matching the repo's style (`party.js`, `remote.js`). |

153
docs/p2p-transfer.md Normal file
View File

@@ -0,0 +1,153 @@
# Direct device media transfers
## Existing paths (audit before implementation)
| Path | Existing media-byte route | Relevant code |
| --- | --- | --- |
| Paired remote | Controls only; the host plays its own source. No existing file-send action. | `frontend/app.js` Remote; `server/remote.js` |
| Presenter and OBS | Lyrics, timing and metadata only; neither currently plays host media. | Presenter and overlay modules; remote relay |
| Watch Party playback | Each guest loads independently through normal server/YouTube playback, unless already saved locally. | Party `applyState`, `Player.loadVideo`; `server/party.js` |
| Watch Party voice | Direct WebRTC audio; server forwards SDP/ICE only. | Party voice mesh, party `rtc` relay |
| On other devices / failed playback | Existing verified-file DataChannel download, 64 KiB frames, SHA-256 validation, worker writes OPFS. Only offered after server failure in playback. | `p2p-transfer.js`, `p2p-recv-worker.js`, `getFromPeers` |
| Save / preload | Server download first, then OPFS. | `preload`, `API.cacheDownload`, download endpoints |
| Export to Files / Photos | Local OPFS first, server URL next, peer fallback last. Native share is an OS export, not paired-device transfer. | `exportToDevice`, `export.js` |
| Profile / playlist share and send | Metadata only. Sending a playlist does not transfer its media files. | Profile/playlist sync APIs |
| Verify & share | Explicit device upload to server intake; hash and media validation admit it into the server cache. | `P2PClient.contribute`, `p2p-intake.js` |
| Automatic rehydration | Server requests a holder to upload its full file to intake. This is an implicit media-byte server path. | `createRehydrator`, client `upload-request` handler |
| Admin uploads / original YouTube downloads | Intentional server ingestion of original media; separate from direct device transfer. | Upload and media-cache endpoints |
| VLC / external player URLs | HTTP server media URLs; these players cannot consume this application's DataChannel. | External player actions |
The current file protocol has no resume: its receiver truncates partial files and
removes them on failure. Connection timeout is 20 seconds per holder. Device
signalling authenticates a device, but does not constrain its destination to a
verified profile or paired room. Profile names supplied at device registration
are not proof of profile membership. Existing server-verified holdings also
exclude files whose bytes the server has never admitted.
## Implementation design
Reuse ordered RTCDataChannel transfers with public STUN only. The WebSocket
server carries bounded, validated signalling and metadata, never file chunks.
Pair authorization must come from an authenticated remote/party room or a
verified profile session, not an arbitrary client-supplied profile name.
A receiver explicitly accepts an invitation before saving. A cryptographically
random, expiring, one-use invitation binds sender, receiver and file identity;
subsequent signalling remains bound to that pair. Reject replay, mismatched
identities, binary WebSocket messages and unrecognized protocol fields.
Send 64 KiB chunks with bufferedAmount backpressure. Persist a partial OPFS file
and resume at its exact committed byte offset. Rehash the retained prefix before
continuing and verify total size and SHA-256 before promoting the file into the
saved store; only then record metadata. A changed hash/size cannot reuse a partial.
Use a 10-second connection deadline and an explicit, clearly labelled server
fallback offer. Direct mode must not silently rehydrate server media from a
device. Register “Direct device transfer (P2P)” in Settings, default on.
Party playback should request a host's saved file when announced, then play the
receiver's OPFS copy. Remote controls and presenter lyrics retain their existing
behaviour; add explicit receive/play actions rather than automatically starting
media in a control-only screen. A manual send action targets authenticated peers.
Ordinary faststart MP4 cannot safely be appended as arbitrary MediaSource chunks.
Progressive playback requires supported fragmented media and codec detection;
otherwise use the completed, verified file (including iOS). Do not claim that
raw MP4 chunks provide progressive playback.
## Verification required before release
Pure tests cover protocol parsing, chunk bounds, offsets, invitation replay and
pair authorization. A two-page localhost browser test must transfer real bytes
into OPFS through WebRTC and assert that server HTTP/WS logs contain only
signalling and metadata. Exercise interruption/resume and explicit fallback.
Review real iPhone foreground/background behaviour and restrictive NAT failure.
## Implemented behaviour
- `direct-protocol.js` strips unexpected fields and validates file claims and
bounded signalling; `direct-relay.js` binds invitations to authenticated room
members. Accepting an invitation is one-use, and only the bound pair can signal.
- Remote, presenter and party relays carry the new protocol. Presenter and OBS
still display lyrics/control metadata; they do not automatically play media.
A presenter can explicitly accept a file sent by its paired host.
- Settings → Direct device transfer provides the default-on toggle and send
buttons for currently connected paired/party/profile peers. Send the currently
playing **saved** song; the receiving device confirms every copy.
- The paired remote has “Play here from paired screen” when its host has saved
media. Party guests and ordinary playback resolve an advertised direct source
before loading media. Saves and exports do the same; the existing OS export
sheet is preserved.
- `/ws/p2p` now has a profile-scoped, ephemeral file-id directory. Protected
profiles require password/key proof, checked against the server profile hash.
Unprotected profiles retain their existing name-based access policy. Claims
are **not** admitted as server-verified media. Each device advertises at most
1,000 local ids per directory update; use paired-room sending for larger libraries.
- The legacy unconfirmed global signalling path is refused. Older clients need
to reload the updated application to transfer files. This closes a bypass of
receiver confirmation and room/profile membership.
- `direct-media.js` uses public STUN, ordered 64 KiB DataChannel chunks and
bufferedAmount backpressure. `direct-recv-worker.js` writes partials directly
to OPFS, rehashes their retained prefix and verifies exact size plus SHA-256
before promotion. File extensions are preserved. A disconnected partial can
be resumed by sending/requesting the same file again, including non-aligned offsets.
- The 10-second deadline covers connection establishment. Prefix rehashing and
final verification do not consume it. Idle transfer timeout is 30 seconds.
Failures retain partial data and offer an explicit **Use server copy** action.
Automatic holder-to-server rehydration is blocked while direct mode is on;
**Verify & share** remains an intentional, explicit server upload.
- `direct-stream.js` supports progressive preview for compatible fragmented
H.264 MP4 through MediaSource. Ordinary faststart MP4, unsupported codecs,
unavailable MediaSource and preview buffer exhaustion use the complete file.
iPhone playback should be reviewed using that completed-file path. A preview
is interactive and independent of the main player's host clock; main party
playback follows the host after the verified copy is ready.
## Paths that still use server media
Original YouTube acquisition, server uploads, intentional Verify & share intake,
external VLC/M3U HTTP URLs and explicitly accepted server fallbacks still use the
server. If no connected device advertises a local copy, normal original-source
playback/download is preserved; this is not a transfer of another device's file.
Profile/playlist shares, chapters, lyrics, presenter state and OBS state remain
metadata/control only. Direct discovery requires an online paired room or an
existing profile, and the browser must remain available to serve its OPFS file.
No TURN service, deployment change or secret configuration is required.
## Checks and reviewer follow-up
Run:
```sh
node --test frontend/*.test.js
node --check frontend/app.js
bun build --no-bundle server/server.js
bun test server/direct-relay.test.js server/p2p-hub.test.js server/remote.test.js server/party.test.js
npx playwright test -c playwright.direct.config.js
npx playwright test -c playwright.glass-navigation.config.js
```
The two-page localhost test uses the production relay and transport, separate
browser stores, a real RTCDataChannel and actual OPFS writes. It resumes a 2 MB
file at byte 12,345, verifies the resulting SHA-256 and asserts that the server
log contains only invitation/acceptance/signalling/completion. A second case
adds 12 seconds of resume preparation to prove it is outside the 10-second
connection deadline. This is a local transport proof, not proof that arbitrary
NATs will connect.
Check real iPhone foreground/background suspension, large-file quota and final
promotion, iOS completed-file playback, restrictive/symmetric NAT fallback,
paired screen playback, party host changes during a copy, protected-profile
credential changes/reconnect, OS export gestures, and an actual fragmented MP4
MediaSource preview on desktop. Public STUN cannot overcome every NAT; declined
invitations do not start media acquisition. Peer directories update when the
presence socket connects and when local saves complete, rather than promising
availability of offline/backgrounded devices.
Final verification on 2026-10-03: 123 frontend unit tests, 22 touched server
tests (including remote and party), app syntax and server build, 8 Glass/Classic
navigation browser tests at 390/1440 px, and both direct-transfer browser cases
passed. The first navigation run lost its reused localhost server; a fresh-server
rerun passed all eight cases without a code change. Classic screenshot comparisons
remain within the test's rasterization tolerance. No real iPhone or restrictive
NAT test was performed here, and no code was pushed or deployed.

View File

@@ -0,0 +1,28 @@
# Piano transcription
Commit 258aad8 added ideas, not runtime code. The implementation is now opt-in under Settings → Piano transcription.
## What runs where
- **Browser:** `frontend/piano-engine.mjs` imports pinned Spotify Basic Pitch 1.0.1 and TensorFlow.js 4.22.0 only after “Transcribe in browser”. It resamples to mono 22,050 Hz in OfflineAudioContext, prefers WebGPU, and falls back to WebGL/CPU. Dependencies load from esm.sh; model/weights load from jsDelivr. Neither the engine nor model is in the service-worker install shell. No audio is uploaded by this path. Processing still needs a network on first use. File/device/server-cached audio is limited to 100 MB and 15 minutes. Basic Pitch is instrument-agnostic, not piano stem separation; mixtures may produce inaccurate notes.
- **Device cache:** IndexedDB `ytp-piano/notes`, per video id, stores the engine label and compact JSON sequence. Export produces `<id>.notes.json`. Each note is `{pitch,start,end,velocity,hand}`. Timing is in seconds; velocity is 1–127. Missing hands use a middle-C split (pitch < 60 = left), which is a visual aid, not reliable fingering. Settings shows an 88-key synced visualizer and a manual practice queue of 8-second A–B loops.
- **Server:** optional `server/piano.js` queues authenticated jobs in SQLite; `scripts/piano/worker.py` downloads server media on the private compose network and runs ByteDance's `piano_transcription_inference` on CPU. This does not run in the web server. Model loading happens at the first claimed job. The worker is off by default and the compose `piano` profile is inactive by default. The checkpoint is about 165 MB; runtime memory needs substantially more (container limit 6 GB).
## Enable the optional worker
Configure a dedicated random `PIANO_WORKER_TOKEN` of at least 24 characters and `PIANO_WORKER_ENABLED=1` for the app and worker. Enable the compose `piano` profile and build/start the worker during a separately approved deployment. It shares the existing private `lyrics` network, keeps its checkpoint in `piano-models`, and is limited to two CPUs. Nothing is pushed or deployed by these changes.
Use an admin API token in the Settings server-request field (kept only in the mounted UI, not persisted), or call the contract directly. Save the song on the server first. “Load server result” retrieves the finished sequence and stores it on the device. Worker jobs survive server restarts, have heartbeat leases and three attempts; expired workers cannot publish. Queue capacity is ten. Replacing a server media generation marks its old sequence stale.
## API contract
- `GET /api/media/:id/piano`: public `{ok,enabled,job}`; `job` is null or `{videoId,status,notes,error,updatedAt}`. Notes are available only after completion. Status: queued/running/ready/failed/stale.
- `POST /api/media/:id/piano`: existing admin session/API-token authentication. Returns an existing valid job or queues one (202). Worker off → 503; uncached source → 409; duration over 15 minutes → 422; queue full → 429.
- `POST /api/piano-worker/claim`: dedicated Bearer worker token; returns a job with lease and server-relative audioPath, or null. Claims are atomic.
- `POST /api/piano-worker/:id`: dedicated worker token plus JSON `{lease,action}`. Actions: heartbeat; complete with `notes`; fail with `error`. Invalid/expired leases → 409. Results are bounded and validated before saving.
The model path is based on [Spotify's browser API](https://github.com/spotify/basic-pitch-ts) and [ByteDance's inference package](https://github.com/qiuqiangkong/piano_transcription_inference). Their upstream licences apply. The browser's TFJS dependency override is pinned and tested with a synthetic WAV; review GPU performance and accuracy with real recordings.
## Review on devices
Verify no model request before Transcribe, GPU/CPU fallback, mobile memory limits, cache survival after reload, JSON export, keyboard alignment with seeking, and A–B practice loop timing. Run the optional worker against a short known piano recording before enabling it for users; heavy-model/container inference is not covered by ordinary unit tests. This version does not provide model-based stem separation, score notation, pedal transcription display, or MIDI wait-for-note practice.

59
docs/recommendations.md Normal file
View File

@@ -0,0 +1,59 @@
# Recommendations and the video catalog
Home and the Search menu show **Recommended for you**, with play, queue, playlist actions, refresh, and an explanation per pick. Saved picks remain available when the server cannot be reached. Cold starts explain how to get recommendations without blocking search.
## Server collection
`video-catalog.js` owns collection independently of downloaded media and the search-result cache. It preserves richer fields when sparse cards arrive and serializes writes so simultaneous discoveries cannot erase each other's metadata.
| Source | Collection path |
| --- | --- |
| Fresh YouTube searches | Awaited ingestion in `fetchYoutube`, including background refreshes; Innertube cards or yt-dlp fallback cards |
| Memory/persistent search hits | Successful JSON response collector |
| Browser saved searches | `/api/catalog/collect`, including the IndexedDB-only fast path; pending query keys retry on launch, reconnect, and every minute |
| Channels, expanded/shared playlists, related-video searches | Successful JSON response collector |
| Played, warmed, or saved videos | Full yt-dlp extraction in `resolveStreamsUncached`, plus cached-stream responses |
| Local/imported playlists, queue, history, linked profiles | Successful sync/profile/share requests and read responses |
| Other GET APIs surfacing video cards | Shared successful-JSON response collector; recommendations themselves are excluded |
| Older server data | Durable paged backfill of known cards, search results, media metadata, history, playlists, shared playlists, and profiles |
The catalog records YouTube video IDs, titles, channels, duration, thumbnail URL, available tags/categories, description excerpts, and extractor view counts. It tracks discovery source separately from listening counts. Local uploads already have server metadata/art in the upload tables; custom device-only edits are excluded from the public YouTube catalog.
Thumbnail **bytes** are stored in SQLite, not merely URLs. Two workers fetch allowed HTTPS YouTube image hosts, reject redirects, allow JPEG/PNG/WebP, cap images at 1 MiB, and time out after eight seconds. Failed jobs persist with backoff up to one day and resume after restart. `/api/catalog/:id/thumbnail` serves stored images; recommendation and local-search cards prefer this URL once ready. The service worker caches these URLs for offline images.
Retention is bounded: `VIDEO_META_MAX` defaults to 500,000 videos and `VIDEO_THUMB_MAX_BYTES` to 512 MiB of image data. Metadata trimming prefers unplayed entries and cleans up associated jobs/source/channel rows. Image eviction preserves metadata, disables automatic re-download, and permits re-fetch on a new discovery. SQLite can reuse freed pages; the byte budget measures live image data, not the physical database file. Failed or evicted images fall back to the original thumbnail URL. Existing source images can be unavailable; metadata collection does not require successful image retrieval.
## Listening and ranking
The existing StatsCore tracker counts a play after **30 seconds actually listened**, rather than counting search appearances, stream requests, or media-cache hits. `/api/user/sync` submits daily per-video snapshots. The server uses monotonic maximum counts per listener/day/video so repeated saves, retries, and reloads do not multiply plays. It retains 400 days and caps ingestion at 10,000 day/video entries per sync.
Anonymous listeners use device fingerprints. Linked listeners use the profile name and existing profile password/key gate. Linking devices merges earlier anonymous daily summaries into the profile with maxima and removes the device copies, so synchronized profile history is counted once. Recommendations and browser snapshots switch with the active profile. This uses the app's cumulative daily statistics; it does not introduce event-level reconciliation of independently edited or concurrently modified profile histories.
The algorithm runs on the server in `recommendations.js`:
1. Select up to 300 globally most-played videos, 100 personal favorites, and 600 recent discoveries. Fetch older candidates from up to ten favorite channels using an indexed channel table.
2. Build channel and title/tag/category interests from the listener's top 20 videos.
3. Score with logarithmic weights for personal plays, channel affinity, shared metadata tokens, global plays, and plays in the last 30 days.
4. Keep at most three videos from a channel and reserve up to half the picks for familiar favorites when discoveries exist.
5. Return playable cards and plain-language reasons; prefer stored thumbnail URLs.
There is no `media_cache` filter or dependency. Unplayed search results and cached or uncached videos all qualify. An empty listener history falls back to global most-played videos, then recent discoveries. A completely empty catalog returns an empty list; recommendations do not launch unsolicited extraction searches.
## API
- `GET /api/recommendations?fp=<fingerprint>[&profile=<name>][&limit=12]`: `{ok, results}`; limit 1–24. Protected profiles require `X-Profile-Secret`. Personal responses use `Cache-Control: no-store`.
- `POST /api/catalog/collect`: `{cards: [...]}`, at most 500 cards and 512,000 request characters. Normalized cards reject unsafe IDs and arbitrary thumbnail hosts.
- `GET /api/catalog/:id/thumbnail`: stored image bytes or 404.
- `/api/user/sync` additionally accepts `stats` and `profileName`; protected profiles use the existing secret header.
## Verification
- 16 Bun catalog/recommendation tests: all pass, covering source collection, richer-field preservation, concurrency, cache eviction, thumbnails, durable retry/backfill, ranking, indexed retrieval of older channel matches, idempotent analytics, profile scope and deduplication.
- 9 Chromium recommendation UI tests: all pass, covering 320/390/1440px, caption contrast >=4.5:1, actions, Search navigation during playback, saved-search submission, offline retries, failure states and profile switching.
- Existing 11 Classic browser checks and 72 frontend unit tests: all pass.
- Isolated live Bun server: protected-profile access, recommendation persistence across restart, two-device deduplication (eight plays remain eight), and a real 21,011-byte YouTube thumbnail stored and served after restart all pass. No production profiles or media were changed.
- Visual review: desktop cards and both mobile section captures are readable and reachable. Initial mobile captures were taken after scrolling to the final action; corrected captures show the section heading and first cards. Desktop retained visible Try chips because its content did not need to scroll; this is a capture expectation difference, not a clipping defect.
Design-hook triage: the new recommendation stylesheet has no findings and measured Classic caption contrast passes. One file/value exception suppresses the shared HTML's three intentionally empty, hidden dynamic artwork images; JavaScript supplies their `src`. The other 15 inherited shared-shell findings (legacy contrast, gradient/glow styling, 11px captions, and intentional app scroll-container clipping) remain unsuppressed and outside this feature's styling changes.
No real mobile device/WebKit run or production deployment was performed.

View File

@@ -0,0 +1,39 @@
# Related-video recovery
The old Now Playing related loader called `/api/search` with the complete title.
That endpoint follows up to 14 InnerTube pages to collect 200 results, then uses
resilient yt-dlp if necessary. Related displayed only eight cards. It had no
alternate query or catalog fallback, silently caught failures, and hid its panel.
It also read mutable `current` after awaiting the request, allowing a previous
song's response to populate the next song's recommendations.
A read-only production probe (`/api/search?q=Rock Medley&refresh=1`) returned 200
results successfully during this investigation. No persistent IP/account/region
block was reproduced, and no privileged production logs or credentials were used.
The exact intermittent upstream YouTube rejection cannot be established from
that successful probe. The failure handling and request coupling above are
verified directly in the previous code and reproduced in tests.
The new `/api/related` endpoint first reads one InnerTube watch-next response,
including compact and modern lockup video cards. A local real request for
`wZzRoXymOUU` parsed 20 recommendations. Failures/empty results fall back to bounded
single-page title/channel searches, then the existing resilient yt-dlp search
path, then videos already known to the server. It excludes the current song,
deduplicates, returns eight cards, shares in-flight work and caches successful
results. Failed responses are not cached; Retry bypasses the success cache.
The YouTube work has an 18-second total budget with per-operation timeouts.
The existing `SEARCH_INNERTUBE=0` switch still disables InnerTube.
Every new discovery goes through the existing metadata catalog/thumbnail collector.
A metadata persistence failure cannot hide otherwise playable cards. Related's
client snapshots the song and ignores superseded responses. When all sources are
unavailable, its panel stays visible with a friendly message and Retry, rather
than disappearing. Catalog fallback is explicitly labelled.
Validation: frontend loader tests cover filtering, errors, retry refresh and stale
responses. Server tests cover renderer parsing, next/search/catalog fallbacks,
metadata collection, cache/in-flight deduplication, deadline exhaustion, and route
validation. Browser tests in both themes, Chromium and WebKit at 390 px, exercise
503 → Retry → results and assert that the section rail retains its parent.
No changes to the Glass section rail; no push or deployment.

View File

@@ -0,0 +1,17 @@
# Remaining features and screen refinement
All changes are local commits on main. Nothing was pushed or deployed.
| Feature | Status | Main files | Validation / reviewer checks |
| --- | --- | --- | --- |
| 9. Ten-band EQ | Done | frontend/eq-core.js, eq-core.test.js, app.js, styles.css; docs/equalizer.md | Five-band curves migrate; live playback and EqRender share bands/presets/widening. Unit and four Classic/Glass browser cases passed. Check headphones, mono compatibility, and saved versus live processing on a real iPhone. |
| 10. Bilingual lyrics | Done | frontend/lyrics-core.js, lyrics-display.js and tests; lower-third.js, app.js, server/notes.js and tests; docs/lyric-languages.md | Primary/secondary/phonetic text preserves timing and round trips. Service, stage, Presenter and OBS use shared display logic. Frontend and 18 server notes tests passed. Check font coverage, multiline fitting and remote output on real devices. |
| 11. Piano transcription | Done; optional heavy worker awaits real inference validation | frontend/piano-core.js, piano-engine.mjs, piano.js and tests; server/piano.js and tests; scripts/piano/; docs/piano-transcription.md | Browser Basic Pitch/TFJS loads only on request, chooses WebGPU where available with WebGL/CPU fallback, caches compact notes with hand heuristic, and supports visualizer/practice queue. Real repeated browser inference passed without growing tensor count. Four server and two Python worker tests passed. ByteDance worker scaffolding, leased API contract and optional compose profile are implemented and off by default; no heavy container was started. Check a known piano recording before enabling it. |
| Downloads polish | Done | frontend/downloads-page.js and tests, offline-pages.css, downloads.js, small app.js hooks; tests/offline-pages.spec.js | Drawn SVG empty state, no empty filter, storage information and Saved link. Active/queued/paused/failed groups reuse the existing manager and confirmed cancellation. Classic/Glass at 390 and 1440 px checked. Test real slow downloads, pause/resume, failure/retry and navigation while saving. |
| Saved polish | Done | frontend/saved-page.js and test, saved-page.css, renderSaved hooks; tests/offline-pages.spec.js | Storage summary and confirmed Clear all share one row. Export/delete have separate horizontal 44 px targets and SVG icons; long titles truncate. Individual deletions confirm, and failed storage operations retain records. Existing save-to-device sheet is called unchanged. Check iPhone export/share and real storage removal. |
Common asset changes are registered in frontend/index.html and the service-worker shell list. The protected background playback methods, Classic playlist actions and save-to-device sheet were not edited.
Final checks: every frontend/*.test.js, app.js syntax, server no-bundle build, and the offline-page browser suite. Feature-specific server and Python tests were run with their respective feature commits. The 21-case settings suite and real Basic Pitch inference also passed. Offline-page tests cover all four layout/width combinations, filtering, cancellation, delete failure and action geometry.
Impeccable context loading, polish and craft-floor references were followed. Batched screenshots were assessed; final screenshots wait for the incumbent card reveal animation to finish. The manual detector found one advisory: the restrained Downloads empty-state heading is 20 px, intentionally smaller than the browsing title; no global typography change was made. The pre-existing design sidecar was reported stale and left outside this refinement.

View File

@@ -0,0 +1,138 @@
# Resumable save / download — plan
Status: **implemented 2026-10-03** (items 1–7; item 6 without the wake lock).
Verified end to end in Chromium through a connection-dropping proxy: a 19 MB
save paused after its retries with 8 MiB kept, resumed by itself after a
reload from byte 8388608, and the stored file's SHA-256 matched the server's.
As built: prepare is `GET /api/download/:id/prepare` (states ready / working /
legacy / failed); the partial's owner is a `<file>.part.json` sidecar in OPFS
(no IndexedDB record); the queue of unfinished saves is `localStorage.ytpSaveQueue`
(`SaveQueue` in app.js); pure helpers live in `frontend/resume-core.js`. Goal: saving a long video (≥ 1 h, hundreds of MB)
to the device must survive dropped connections, app backgrounding, reloads and
the slow homelab link — continuing from where it stopped instead of starting over.
## Why long saves get stuck today
| Piece | Today | Problem for big files |
|---|---|---|
| `frontend/app.js` `opfsDownload()` (~273) | one `fetch('/api/download/<id>')` for the whole file | any drop = total loss; no progress survives a reload |
| `frontend/opfs.js` `writeFromResponse()` (~178), `opfs-worker.js` (~40) | writes a `.part`, checks `Content-Length`, **deletes the `.part` on any failure** | the bytes already received are thrown away |
| `server/server.js` `/api/download/:id` (~1549) → `cachedDownloadResponse()` (~1527) | streams the cached copy with `Content-Length` only | **no `Range` / `Accept-Ranges`** → the client cannot ask for "the rest" |
| `/api/download/:id` when the server has no copy yet (~1620) | streams yt-dlp output live | not resumable at all; one stall kills it |
| iOS / Safari | backgrounding suspends `fetch` | the single long request dies whenever the phone locks |
Already in place and reusable: `rangeFileResponse()` (~1265, used by
`/api/media/:id` and `/api/export/:id`) does correct 206/`Content-Range`;
`/api/media/:id/status` reports cache-job progress; `sha256.js` hashes
incrementally; the OPFS worker uses `createSyncAccessHandle`, which can write at
any offset; Bun `idleTimeout` is already 0.
## Design
**Rule: the device only ever downloads a finished, validated server copy, in
byte ranges.** Fetching from YouTube is the server's job (the media cache),
never part of a device transfer.
```
tap Save ──► POST /api/media/:id/prepare ──► server media-cache job (HIGH)
│ │ status/progress
│◄── poll GET /api/media/:id/status ◄────────┘ "Preparing on server 42%"
▼ ready: { gen, size, sha256 }
for each missing chunk (8 MiB):
GET /api/media/:id?g=<gen> Range: bytes=a-b If-Range: "<id>.<gen>"
write at offset a (OPFS sync handle, in the worker)
record bytesDone in IndexedDB
all chunks ──► hash whole .part, compare sha256 ──► rename to final
```
### Server (Bun) — `server/server.js`, `server/media-cache.js`
1. **Range on the download path.** `/api/download/:id` with a cached copy (and
uploads) answers through `rangeFileResponse()`, plus `Accept-Ranges: bytes`
and a strong `ETag: "<id>.<gen>"` (uploads: `"<id>"`). Honor `If-Range`: when
the ETag no longer matches (copy was re-downloaded → new gen), send a full 200
so the client knows to restart. Keep `X-Content-SHA256`.
2. **Generation-pinned URLs.** Chunks use `/api/media/:id?g=<gen>` (already
immutable + ranged). A finished copy is never rewritten in place (new gen =
new file), so bytes for one gen never change under the client.
3. **Pin while downloading.** Eviction must not remove a copy a device is in the
middle of fetching: `media.touch(id)` on every ranged hit already refreshes
LRU; add a short "in transfer" protect window (reuse `EVICT_PROTECT_MS`).
4. **Prepare endpoint.** `POST /api/media/:id/prepare` → `ensureCached(id, {priority: HIGH})`
and return `status()` immediately (no waiting). `status()` gains
`{ progress, gen, size, sha256 }` so the client can show
"Preparing on server" with a percentage and knows the exact target.
5. **Long videos.** `MAX_SAVE_SECONDS` / `MEDIA_AUTO_MAX_SECONDS` stay as the
policy limits; when they refuse, `prepare` returns the reason so the UI can
say so instead of hanging. The yt-dlp live-stream path of `/api/download`
stays only as a legacy fallback for short videos.
6. **Uploads.** Same Range/ETag treatment (they already sit on disk; with the
USB drive move, the backup-dir fallback in `uploads.js` serves either copy —
both are byte-identical, so the ETag is the same).
### Browser — `frontend/app.js`, `frontend/opfs-worker.js`, `frontend/opfs.js`, `frontend/device-db.js`
1. **Transfer record (IndexedDB, `device-db.js`).** One row per saving video:
`{ id, gen, size, sha256, chunk, bytesDone, state: preparing|downloading|verifying|done|failed, updatedAt, error }`.
This is what survives reloads, crashes and app kills.
2. **Chunked worker download (`opfs-worker.js`).** Replace the single fetch with a
loop over missing ranges: `Range: bytes=start-end`, `If-Range: "<id>.<gen>"`,
per-chunk `AbortController` timeout (60 s), up to 5 retries with backoff
(2 s → 30 s). Write with `accessHandle.write(buf, { at: start })`, `flush()`
every chunk, update `bytesDone` after the flush (so the record never claims
bytes that are not on disk). On start, trust `min(record.bytesDone, .part size)`.
- 200 instead of 206 or an ETag mismatch → the server copy changed: truncate
the `.part`, reset the record to the new gen, start over (rare).
- 416 → `.part` is longer than the file: truncate to `size` and verify.
3. **Never delete progress on failure.** `.part` + record are kept on errors and
only removed on user cancel, on success, or when the record is older than 7
days (sweep at startup, alongside OPFS quota checks).
4. **Verify at the end, not during.** Hashing across resumes is done by
re-reading the finished `.part` in the worker with `sha256.js` (no hash state
to persist), then compare with the server's `sha256`; mismatch → discard and
restart once, then mark failed. Rename `.part` → final as today.
5. **Auto-resume triggers.** App start, `online`, `visibilitychange` → visible,
and the SW `sync` event where supported: resume every record in
`downloading`/`preparing`. One transfer at a time (the homelab uplink is the
bottleneck), next in queue starts when one finishes.
6. **Browsers without worker sync access handles.** Detect up front. Where only
`createWritable` exists (some desktop Chromium contexts), use
`createWritable({ keepExistingData: true })` + `seek(start)` per chunk. If
neither exists, keep today's "not supported" error — do not fall back to an
unresumable path silently.
7. **UI.**
- Save button / Downloads list show `Preparing on server 40%`,
`Downloading 312 / 742 MB`, `Paused — will resume`, `Verifying…`.
- Pause / Resume / Cancel per item in **Downloads** (Cancel deletes `.part`).
- A paused item resumes by itself on the triggers above; a toast only on
final success or a hard failure (with the reason from the server).
- Keep the screen awake (existing wake-lock helper) while a foreground
download runs, opt-out in Settings, so iOS does not suspend it.
8. **Save-to-device export** (`exportToDevice`, ~8000) already uses the ranged
`/api/export/:id`; no change beyond using the same ETag.
### Browser support matrix (target)
| Browser | Write at offset | Resume across reload | Notes |
|---|---|---|---|
| Chrome / Edge / Android Chrome | worker sync handle | yes | |
| Safari / iOS 16.4+ (PWA + tab) | worker sync handle | yes | suspended when backgrounded → resumes on `visibilitychange` |
| Firefox 111+ | worker sync handle | yes | |
| Older browsers without OPFS sync handles | — | — | clear "not supported" message, Save-to-device export still works |
## Work items (each one commit, tests first)
1. Server: Range + strong ETag + `If-Range` on `/api/download/:id` (cached + uploads). Tests: 206 slices, full 200 on ETag mismatch, 416 past the end.
2. Server: `POST /api/media/:id/prepare`; `status()` returns `{ progress, gen, size, sha256 }`; in-transfer eviction protect. Tests in `media-cache.test.js`.
3. Browser: transfer record store in `device-db.js` + startup sweep (node tests with a fake IDB).
4. Browser: chunked, resumable worker download in `opfs-worker.js` (pure chunk planner + retry policy as testable functions; node tests with a fake fetch that drops mid-chunk, returns 200 on ETag change, and 416).
5. Browser: wire `opfsDownload()` / `preload()` to prepare → poll → chunked download; auto-resume triggers; one-at-a-time queue.
6. UI: progress states, Pause / Resume / Cancel in Downloads, wake lock while downloading.
7. End-to-end check against a local server with a 1 h+ fixture: kill the network mid-way (Playwright `context.setOffline`), reload the page, confirm it resumes from the last chunk and the final SHA-256 matches; run the same in WebKit (Windows Playwright, see CLAUDE.md) for Safari behaviour.
## Out of scope
- Resuming the server-side YouTube fetch itself (the media cache already restarts
jobs on boot and retries with backoff).
- Background downloads while the iOS app is fully closed (no Background Fetch on
iOS); the transfer resumes the next time the app is opened.

80
docs/theme-bento-hub.md Normal file
View File

@@ -0,0 +1,80 @@
# New Bento Hub theme
The old Bento rules in `frontend/styles.css` have been removed. The replacement
is `frontend/theme-bento-hub.css`, scoped to `html[data-layout="bento-hub"]`.
The stylesheet, small theme helper, and self-hosted Plus Jakarta Sans fonts are
included in the service-worker shell cache. Classic remains the default.
## Match to the reference
The reference is `docs/mockups/bento-hub/index.html` and `SPEC.md` (local design
sources). The implementation uses their obsidian surfaces, solar-gold primary
controls, cyan listening/status cues, Plus Jakarta Sans and JetBrains Mono,
16px outer / 10px inner corners, stroke SVG icons, search capsule, playlist
artwork collages, bordered collection rows, and floating mini player.
Coverage includes the desktop sidebar and phone navigation, Home and search,
Now Playing, all three notes tabs, stage lyrics, up next, playlist and channel
views, Queue and batch selection, History, Saved, all download states and their
Retry/Cancel controls, Settings overview and sections, Service mode, modals,
control sheets, and empty states. Floating chrome has measured clearance;
content scrolls inside the remaining viewport. `#sectionRail` stays fixed and
attached directly to `body`. It is never moved into a panel or scroll container.
## Deliberate differences
- Content and navigation remain the real app's. Home shows actual playlists
and recommendations. Counts, artwork, progress, lyrics and wake-lock state
come from existing data; there are no invented verification badges, transfer
speeds, subscriber counts, or guarantees that the screen will stay awake.
- The desktop sidebar uses the spec's 260px width rather than the HTML mockup's
240px. The drawer extends through 1023px. The existing app stacks its player
at phone widths; its browsing and player controls remain accessible there.
- Now Playing keeps the real control deck, playlist panel, volume, looping,
fullscreen, notes and More controls. Notes remain with the player instead of
reproducing the mockup's separate static lyrics column. Service keeps its
view, autoscroll, floating lyrics, reporting and text-size controls; these
wrap when necessary rather than overlapping.
- Settings keeps its section registry, back/history behavior, live summaries,
search and desktop two-pane navigation. Layout selection remains the existing
select rather than duplicating it with mockup-only theme chips.
- Functional text has an 11px floor and controls have 44px minimum targets.
Muted dark text and the light-theme gold were adjusted for contrast. Existing
font scaling, density, contrast, reduced-motion and performance preferences
continue to apply. Service lyrics keep their adjustable sizing.
- Mockup frames omit the shell on several screens and contain empty space or
sample rows. Real pages retain the full shell and scrollable content. Video
fixture art is synthetic; a real playing video fills the video stage.
## Verification and screenshots
Run `node scripts/test-bento-theme.js` for a reproducible comparison. It extracts
pre-Bento commit `04b620e` into a temporary directory, captures Classic and Glass
before shots, then checks the current app. It does not modify the checkout.
`BENTO_BASE_COMMIT` can select another baseline; `BENTO_SCREENSHOT_DIR` can select
an output directory. Default output is `~/deliverables/ytplayer-done13/`.
The Playwright matrix covers 23 screens at 390px and 1440px in Chromium and
WebKit. It also checks centered navigation icons, download action appearance,
fixed rail ownership, sidebar and mini-player navigation, floating clearance,
theme switching restoration, and light/high-contrast appearance. The reference
is opened at both widths and each reference frame is captured when the local
mockup is present. No local mockup files are added to these implementation
commits. Static fixtures freeze the Classic mini-player's initial observer and
native indeterminate progress to avoid unrelated animation/scroll races.
Before/after comparisons allow at most 40 subpixel rasterization differences
in a whole screenshot; substantial geometry or styling differences fail. The
additional theme-switch check tolerates one RGB level per channel to account
for Chromium recompositing rounded corners, while retaining the 40-pixel limit.
Frontend unit tests include floating-chrome clearance with and without safe
areas/hidden bars and Bento-only SVG mapping without changing Glass glyphs.
The usual frontend tests, app syntax check and server build are run after each
screen group. Server source and imports are unchanged.
On a real iPhone, review safe-area clearance in Safari and installed mode,
keyboard and orientation changes, the floating rail, mini-player return,
Service controls, and actual video playback. On desktop, review long titles,
sidebar drawer at tablet widths, keyboard focus, Settings navigation and theme
switching. WebKit automation checks layout; it does not emulate all iOS media
or safe-area behavior. Nothing was pushed or deployed.

5
docs/vocal-stems.md Normal file
View File

@@ -0,0 +1,5 @@
# Vocal reduction and future stems
The Vocal control uses a stereo mid/side matrix, not source separation. The same `frontend/vocal-reducer.js` graph runs in live Web Audio and EqRender's OfflineAudioContext. At 100% it is identity; at 0% it retains the stereo side and removes the centre. Centred instruments are reduced too, and mono can disappear. Live processing on iPhone requires the existing opt-in; saved songs render in the background and keep lock-screen playback.
TODO: add optional Demucs source separation. Follow the lyrics-worker deployment pattern, with its own model volume, token and resource limits. Suggested contract: `POST /api/media/:id/stems` starts an idempotent job, `GET /api/media/:id/stems` returns queued/running/ready/failed plus vocal/instrumental URLs. The worker fetches server audio over the private network, runs Demucs, atomically publishes stems and retains model/version/source-hash provenance. Authenticate job creation, cap concurrency and file size, and never fetch arbitrary user URLs. Keep the worker and feature off by default. No stems API or model currently runs.

View File

@@ -0,0 +1,109 @@
# Rock Medley save investigation
Video: `wZzRoXymOUU` — **Rock Medley**, Petra - Topic, 605 seconds.
Investigation date: 2026-10-03. Main was pulled with `--ff-only` before changes.
No production shell, credentials, cookies, vault, deployment or proxy was used.
## Evidence
YouTube's public oEmbed endpoint returns HTTP 200, the correct title/artist and
thumbnail. This confirms the ID, but not playback permission. The watch page's
initial player response on this development machine returns:
```json
{"status":"UNPLAYABLE","reason":"Video unavailable"}
```
The server's metadata invocation (`-J --no-warnings URL`) and the exact cache
save invocation fail with `ERROR: [youtube] wZzRoXymOUU: Video unavailable`.
Providing Bun as the JS runtime mirrors the Docker image's `/etc/yt-dlp.conf`.
The error occurs during player extraction, before selecting/downloading a
format. The server uses a ladder of selectors, not a hard-coded format ID.
| Local extractor | Default result |
| --- | --- |
| PATH yt-dlp 2026.07.04 | Video unavailable |
| Repository binary 2026.08.19 | Video unavailable |
| Downloaded nightly 2026.09.27.232945 | Video unavailable |
With 2026.08.19, explicit `web_embedded`, `web_safari`, `tv_simply`, `android_vr`,
`mweb` and `web_music` clients all fail for this song too. A control video
(`0gfX0dFLaBc`) succeeds from the same machine/runtime. This is video-specific
upstream playability refusal, not a demonstrated stale-extractor, missing-format
or broken-JS-runtime problem. It is **not exclusively reproducible on prod**.
The generic response does not establish region, IP, account or licensing as the
specific cause. Cookies or PO tokens were not requested or tested.
Upstream release notes: [2026.08.19](https://github.com/yt-dlp/yt-dlp/releases/tag/2026.08.19).
[yt-dlp documentation](https://github.com/yt-dlp/yt-dlp#dependencies) describes
runtime dependencies; no dependency update resolved this local reproduction.
The Dockerfile is unchanged because an update alone is not a proven remedy.
Its existing release-download layer is cached by Docker, so a future intentional
extractor update must rebuild that layer, rather than assume new app code updates
it automatically.
## Changes
1. Shared extraction now tries a bounded client ladder for generic unavailable
and missing-format errors, as well as bot checks. This covers both metadata
probes and actual saves. Explicit private/member/age/country/removal errors,
local disk errors, cancellation and explicit client overrides do not trigger
that ladder. The final diagnostic preserves the original failure and lists
attempted clients; it does not mislabel the song as deleted.
2. Explicit Retry POSTs `/api/download/:id/retry` before preparing a device save.
It clears stale preparation/stream hints and calls the normal cache with
`force:true` to bypass a **failed row's** cooldown. It does not delete ready
media or duplicate running jobs. USB-volume, free-space/budget, duration and
validation rules still belong to the existing cache. Repeated failed retries
are limited to one per song per 15 seconds. Normal automatic resumes do not
force a retry. Manual Retry follows the same new client ladder.
3. Downloads, Settings → Downloads & storage, and save-failure toasts use plain
language. Expandable “Technical details” retains the raw tool error as text,
never HTML. Controls remain usable in both themes at 390/1440 px.
## Remaining reviewer check
**These changes do not demonstrate a successful download of Rock Medley.**
The local default and all tested clients still receive YouTube's refusal.
To establish the production-specific reason, the reviewer should compare:
- Actual yt-dlp version and the invocation below inside the deployed container.
- Logged-out YouTube playback on the homelab's outbound network versus the
working phone network; repeat with the phone on that same network if possible.
- If only authenticated playback works, confirm whether the video needs account
access before considering the existing optional read-only cookies mechanism.
Do not assume a PO token is required without extractor diagnostics saying so.
- If the failure tracks a network/region, use a permitted outbound network where
the video is available, or a permitted alternate source/upload/device copy.
Merely changing a region hint does not prove actual playback eligibility.
No network, cookies, token, Docker or deployment workaround was guessed or
silently enabled. After any confirmed environment correction, Retry now starts
a genuine fresh attempt instead of just returning the old backoff failure.
```sh
# Metadata probe, same as the server (Docker config supplies the Bun runtime)
yt-dlp -J --no-warnings 'https://www.youtube.com/watch?v=wZzRoXymOUU'
# Cache save, same selector/merge/rate args as the server's defaults
yt-dlp 'https://www.youtube.com/watch?v=wZzRoXymOUU' --no-warnings --no-playlist \
-f 'bv*[height<=720][vcodec^=avc1]+ba[ext=m4a]/bv*[height<=720][vcodec^=avc1]+ba/b[ext=mp4][vcodec^=avc1]/bv*[height<=720]+ba/b[ext=mp4]/b' \
--merge-output-format mp4 --limit-rate 2M -o /tmp/rock-medley-check.mp4
```
Tests: `node --test frontend/*.test.js`; app syntax check; unbundled server build;
`bun test server/ytdlp-resilience.test.js server/download-retry.test.js
server/media-cache.test.js`; and
`npx playwright test --config playwright.download-retry.config.js`.
The existing pool tests additionally need an importable yt-dlp zipapp:
`YTDLP_PATH=/path/to/zipapp bun test server/ytdlp-pool.test.js`. The installed
PATH executable here is a Python entry-point script, not an importable zipapp;
providing the downloaded nightly zipapp makes all pool tests pass without any
production code or environment changes.
Final validation: **118 frontend unit tests, 44 server tests and 13 browser cases
pass**, plus the app syntax check and server build. Browser cases cover the real
Retry controls in both Downloads and Settings, normal resumes, friendly failures,
44 px details controls, safe raw text and overflow at phone/desktop widths.
A real iPhone Safari/PWA save should still be checked after deployment, especially
pause/resume of a partial copy and retry after a network change.

1509
frontend/admin.html Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,84 @@
const {test}=require('node:test');
const assert=require('node:assert/strict');
const {webcrypto,createHash}=require('node:crypto');
const vm=require('node:vm');
const {readFileSync}=require('node:fs');
function fixture({cached=false,tampered=false,enabled=true,loading=false,quota=false,insecure=false,previous=false,contract=1,capture=true,controller=true,parser=false}={}){
const source='window.appRuns=(window.appRuns||0)+1; window.boot=()=>window.bootRuns=(window.bootRuns||0)+1; document.addEventListener("DOMContentLoaded",boot);',hash=createHash('sha256').update(source).digest('hex'), key='/app.js?v='+hash.slice(0,10);
const oldSource='window.oldApp=true;'+source, oldHash=createHash('sha256').update(oldSource).digest('hex').slice(0,10), oldKey='/app.js?v='+oldHash;
const held=new Map(), appended=[],writes=[],listeners={};let calls=0;
const response=()=>new Response(tampered?'bad':source,{headers:{'X-Asset-Hash':hash.slice(0,10)}});
if(cached)held.set(key,response());
if(previous){held.set(oldKey,new Response(oldSource,{headers:{'X-Asset-Hash':oldHash}}));held.set('/__ytp_asset_state',Response.json({previous:{files:{'/app.js':{h:oldHash}},groups:{core:{contract,files:['/app.js']}}}}));}
const root={crypto:insecure?undefined:webcrypto,TextDecoder,Uint8Array,btoa,console,AssetSyncCore:require('./asset-sync-core'),navigator:{serviceWorker:{controller:controller?{}:null}},Lazy:{captureApp:capture,manifest:{groups:{core:{contract:1,files:['/app.js']}},appCache:enabled,files:{'/app.js':{h:hash.slice(0,10)}}},url:()=>key},fetch:async()=>{calls++;return previous?new Response(oldSource,{headers:{'X-Asset-Hash':oldHash}}):response();},caches:{open:async()=>({match:async k=>held.get(k)?.clone(),put:async(k,r)=>{if(quota)throw Error('quota');held.set(k,r.clone());}})}};
const doc=root.document={readyState:loading?'loading':'complete',currentScript:parser?{}:null,write:value=>{writes.push(value);vm.runInContext(source,context);},querySelector:()=>({content:"script-src 'self' 'sha256-"+Buffer.from(hash,'hex').toString('base64')+"'"}),addEventListener:(name,fn)=>(listeners[name] ||= []).push(fn),createElement:()=>({remove(){this.removed=true;}}),head:{append(node){appended.push(node);if(node.textContent)vm.runInContext(node.textContent,context);else {queueMicrotask(async()=>{if(previous && node.src===key){const state=await held.get('/__ytp_asset_state').clone().json();if(!root.AssetSyncCore.fallback(root.Lazy.manifest,state.previous,'/app.js'))return node.onerror();vm.runInContext(oldSource,context);}else vm.runInContext(node.src===oldKey?oldSource:source,context);node.onload();});}}}};
root.window=root;const context=vm.createContext(root);
vm.runInContext(readFileSync(require.resolve('./section-rail.js'),'utf8'),context);
return {root,held,appended,writes,listeners,key,calls:()=>calls,doc,response,oldKey};
}
test('cold boot caches verified app before execution so worker skips its download',async()=>{
const f=fixture();await f.root.AppBootstrap.ready;assert.equal(f.calls(),1);assert.ok(f.held.has(f.key));assert.equal(f.root.appRuns,1);assert.equal(f.root.bootRuns,1);assert.equal(f.appended[0].src,undefined);assert.equal(f.appended[0].removed,true);
});
test('offline boot reads the exact cached app without network or re-evaluation',async()=>{
const f=fixture({cached:true});await f.root.AppBootstrap.ready;assert.equal(f.calls(),0);assert.equal(f.root.appRuns,1);assert.equal(f.root.bootRuns,1);
});
test('tampered cached bytes are rejected before execution',async()=>{
const f=fixture({cached:true,tampered:true});await assert.rejects(f.root.AppBootstrap.ready,/hash/);assert.equal(f.root.appRuns,undefined);
});
test('native and rollback boot use the original external classic script',async()=>{
const f=fixture({enabled:false});await f.root.AppBootstrap.ready;assert.equal(f.calls(),0);assert.equal(f.appended[0].src,f.key);assert.equal(f.root.bootRuns,1);
});
test('boot waits for the normal DOM event when the parser has not finished',async()=>{
const f=fixture({loading:true});await f.root.AppBootstrap.ready;assert.equal(f.root.bootRuns,undefined);for(const fn of f.listeners.DOMContentLoaded)fn();assert.equal(f.root.appRuns,1);assert.equal(f.root.bootRuns,1);
});
test('quota failure still executes the verified response without deleting saved data',async()=>{
const f=fixture({quota:true});await f.root.AppBootstrap.ready;assert.equal(f.calls(),1);assert.equal(f.root.appRuns,1);assert.equal(f.root.bootRuns,1);
});
test('the early head response is consumed without a second page fetch',async()=>{
const f=fixture();f.root.Lazy.appResponse=Promise.resolve(f.response());await f.root.AppBootstrap.ready;
assert.equal(f.calls(),0);assert.ok(f.held.has(f.key));assert.equal(f.root.appRuns,1);
});
test('insecure local HTTP boot retains external execution without WebCrypto',async()=>{
const f=fixture({insecure:true});await f.root.AppBootstrap.ready;assert.equal(f.calls(),0);assert.equal(f.appended[0].src,f.key);assert.equal(f.root.bootRuns,1);
});
test('missing current app uses verified same-contract N-1 offline through the controlling worker',async()=>{
const f=fixture({previous:true});await f.root.AppBootstrap.ready;
assert.equal(f.appended[0].src,f.oldKey);assert.equal(f.root.oldApp,true);assert.equal(f.root.bootRuns,1);assert.equal(f.held.has(f.key),false);
});
test('an incompatible previous core never executes against the new shell',async()=>{
const f=fixture({previous:true,contract:2});await assert.rejects(f.root.AppBootstrap.ready,/hash/);assert.equal(f.root.appRuns,undefined);
});
test('a feature contract change also prevents stale core execution',async()=>{
const f=fixture({previous:true});f.root.Lazy.manifest.groups['feature:test']={contract:2,files:[]};
const state=await f.held.get('/__ytp_asset_state').json();state.previous.groups['feature:test']={contract:1,files:[]};f.held.set('/__ytp_asset_state',Response.json(state));
await assert.rejects(f.root.AppBootstrap.ready,/hash/);assert.equal(f.root.appRuns,undefined);
});
test('native-cache engines use their external script and keep normal code-cache behavior',async()=>{
const f=fixture({capture:false,controller:false});await f.root.AppBootstrap.ready;assert.equal(f.calls(),0);assert.equal(f.appended[0].src,f.key);assert.equal(f.root.bootRuns,1);
});
test('native-cache engines still reject an incompatible retained core',async()=>{
const f=fixture({capture:false,previous:true,contract:2});await assert.rejects(f.root.AppBootstrap.ready,/Unable to load player/);assert.equal(f.root.appRuns,undefined);
});
test('native-cache engines use the validated current cache entry without decoding its body',async()=>{
const f=fixture({capture:false,cached:true});await f.root.AppBootstrap.ready;assert.equal(f.calls(),0);assert.equal(f.appended[0].src,f.key);assert.equal(f.root.bootRuns,1);
});
test('native parser boot preserves classic evaluation before the original DOM event',async()=>{
const f=fixture({capture:false,loading:true,parser:true});
assert.equal(f.root.appRuns,1);assert.equal(f.root.bootRuns,undefined);
assert.deepEqual(f.writes,['<script src="'+f.key+'"></script>']);assert.equal(f.appended.length,0);
for(const fn of f.listeners.DOMContentLoaded)fn();await f.root.AppBootstrap.ready;
assert.equal(f.root.bootRuns,1);assert.equal(f.calls(),0);
});

View File

@@ -0,0 +1,84 @@
const {test}=require('node:test');
const assert=require('node:assert/strict');
const {readFileSync}=require('node:fs');
const {createHash}=require('node:crypto');
const {join}=require('node:path');
const app=readFileSync(join(__dirname,'app.js'),'utf8');
test('Phase 4 preserves the exact playback, continuity, tracking and queue bodies',()=>{
{const start=app.indexOf("const Player = {");assert.ok(start>=0,"Player");const body=app.slice(start,start+30343);assert.equal(createHash('sha256').update(body).digest('hex'),"373df46f4f994717472d26a6bac07449f6ca0a930cb666bfe3895d1dc65aa351","Player body unchanged");}
{const start=app.indexOf("const Transition = (() => {");assert.ok(start>=0,"Transition");const body=app.slice(start,start+8588);assert.equal(createHash('sha256').update(body).digest('hex'),"71997a537078308a41f0cbf8e29fd1658fb3a199c4f5a25d8af0931f1c2a6d50","Transition body unchanged");}
{const start=app.indexOf("const Wave = (() => {");assert.ok(start>=0,"Wave");const body=app.slice(start,start+5241);assert.equal(createHash('sha256').update(body).digest('hex'),"7252f4e856c59aef8aabfcd394ce4bcba656110cbd01a1a8af662eeb48166a3c","Wave body unchanged");}
{const start=app.indexOf("const StatsTrack = (() => {");assert.ok(start>=0,"StatsTrack");const body=app.slice(start,start+1462);assert.equal(createHash('sha256').update(body).digest('hex'),"9aae2631ba3bfad918319579b7120814af06c84949394d04e52c65345332d514","StatsTrack body unchanged");}
{const start=app.indexOf("function wirePlayerEvents() {");assert.ok(start>=0,"wirePlayerEvents");const body=app.slice(start,start+4913);assert.equal(createHash('sha256').update(body).digest('hex'),"1c5a2b5ce310f6aef6764325eda85a95f47e4f507f2049036ce1da206379908c","wirePlayerEvents body unchanged");}
{const start=app.indexOf("function persist() {");assert.ok(start>=0,"persist");const body=app.slice(start,start+147);assert.equal(createHash('sha256').update(body).digest('hex'),"01e5c5dbc80616266db09b3829dc45b66476a3256b1c169d8e44f4983b24ac45","persist body unchanged");}
{const start=app.indexOf("function playFromList(list, index, source = '', { playFull = false } = {}) {");assert.ok(start>=0,"playFromList");const body=app.slice(start,start+401);assert.equal(createHash('sha256').update(body).digest('hex'),"f8009c9674b3478959997dca881fb7b9e1ab3708c98e5abdf1958d752e47ee41","playFromList body unchanged");}
{const start=app.indexOf("function advanceQueue() {");assert.ok(start>=0,"advanceQueue");const body=app.slice(start,start+596);assert.equal(createHash('sha256').update(body).digest('hex'),"be405b9c163e3d41a949ef11f6022ef13115b04083e3b6ad21d97beba1f45ae6","advanceQueue body unchanged");}
{const start=app.indexOf("function playNext() {");assert.ok(start>=0,"playNext");const body=app.slice(start,start+143);assert.equal(createHash('sha256').update(body).digest('hex'),"859d2ffd2e8c89a8d9c0dd0cf429fd403675452cedba2e34aa3dc72683d4f8c6","playNext body unchanged");}
{const start=app.indexOf("function playPrev() {");assert.ok(start>=0,"playPrev");const body=app.slice(start,start+268);assert.equal(createHash('sha256').update(body).digest('hex'),"ece8d33bd03c8146a6a702534c8fed50ff606170685b08d730b19d9d3c68cf48","playPrev body unchanged");}
{const start=app.indexOf("function onTrackEnded() {");assert.ok(start>=0,"onTrackEnded");const body=app.slice(start,start+702);assert.equal(createHash('sha256').update(body).digest('hex'),"d6e147238ad9656fa1c2335973b37597749bcfd02df1a66390b306fe1194ae0d","onTrackEnded body unchanged");}
{const start=app.indexOf("function sleepFadeSec() {");assert.ok(start>=0,"sleepFadeSec");const body=app.slice(start,start+138);assert.equal(createHash('sha256').update(body).digest('hex'),"3f986c8cc474d8313476e9c209b9264e3724011ffaee887f47178bb5155a4d77","sleepFadeSec body unchanged");}
{const start=app.indexOf("function applySleepFade(remaining) {");assert.ok(start>=0,"applySleepFade");const body=app.slice(start,start+346);assert.equal(createHash('sha256').update(body).digest('hex'),"9bd0fa697b271c6b80c128ff1d0a7b00afcb3ccf08f98b5c7e7dc86fd4329681","applySleepFade body unchanged");}
{const start=app.indexOf("function startSleepTimer(minutes, { endOfSong = false } = {}) {");assert.ok(start>=0,"startSleepTimer");const body=app.slice(start,start+487);assert.equal(createHash('sha256').update(body).digest('hex'),"f0a93401ab90196096074cb607b28d52c5903e11dbdfb8ddb95114e143af2409","startSleepTimer body unchanged");}
{const start=app.indexOf("function cancelSleepTimer() {");assert.ok(start>=0,"cancelSleepTimer");const body=app.slice(start,start+253);assert.equal(createHash('sha256').update(body).digest('hex'),"cf396ab758a70eede6af7444539a82ca15af801a9a57024dd5542067e9fa771a","cancelSleepTimer body unchanged");}
{const start=app.indexOf("function finishSleep() {");assert.ok(start>=0,"finishSleep");const body=app.slice(start,start+662);assert.equal(createHash('sha256').update(body).digest('hex'),"7ee93bf760bad5f39f4644339963918c5b369b2acc554b8e561c1a1f070ac6fb","finishSleep body unchanged");}
{const start=app.indexOf("const EQ = (() => {");assert.ok(start>=0,"EQ");const body=app.slice(start,start+7917);assert.equal(createHash('sha256').update(body).digest('hex'),"f0cba011c94f33e6fd0ab778021f4c97238262dfa0a8dd40bf3f17149c227528","EQ body unchanged");}
{const start=app.indexOf("const EqRender = (() => {");assert.ok(start>=0,"EqRender");const body=app.slice(start,start+5912);assert.equal(createHash('sha256').update(body).digest('hex'),"f014dd41dafebc33f09e87be866074afd7a2443c5bb452103a435585353a828f","EqRender body unchanged");}
{const start=app.indexOf("const Level = (() => {");assert.ok(start>=0,"Level");const body=app.slice(start,start+3892);assert.equal(createHash('sha256').update(body).digest('hex'),"e48ad7797384ac31bb8b864662fc2a546b04470b981042f016874ba750957226","Level body unchanged");}
});
test('eager shell and Settings definitions load before app state and defer reading it',()=>{
const html=readFileSync(join(__dirname,'index.html'),'utf8');
for(const file of ['shell-core.js','views-core.js','section-rail.js']) {
assert.ok(html.indexOf('src="'+file+'"')<=html.indexOf('src="section-rail.js"'));
const vm=require('node:vm');const doc={readyState:'complete',addEventListener(){},createElement:()=>({}),head:{append(){}}};const globals={document:doc,Lazy:{manifest:{appCache:false},url:()=>'/app.js'},console};globals.window=globals;const context=vm.createContext(globals);
// Evaluation before any data/$/els/Player declaration must be safe.
vm.runInContext(readFileSync(join(__dirname,file),'utf8'),context);
}
const views=readFileSync(join(__dirname,'views-core.js'),'utf8');
assert.ok(views.includes('async function renderSettings()'));
});
test('remote facade preserves synchronous no-session and loaded changed hooks',()=>{
const source=app.match(/\/\* Remote facade \*\/([\s\S]*?)\/\* End remote facade \*\//)?.[1];
assert.ok(source,'remote facade is present');
const context=require('node:vm').createContext({window:{},Lazy:{proxy:()=>({}),onLoad(){}}});
require('node:vm').runInContext(source+';globalThis.api=Remote;',context);
assert.equal(context.api.changed(),undefined);
let calls=0;context.window.YT={Remote:{changed:()=>{calls++;return 'sync';}}};
assert.equal(context.api.changed(),'sync');assert.equal(calls,1);
});
test('watch-party facade keeps playback decisions synchronous before and after loading',()=>{
const source=app.match(/\/\* Party facade \*\/([\s\S]*?)\/\* End party facade \*\//)?.[1];assert.ok(source);
const context=require('node:vm').createContext({window:{},Lazy:{proxy:()=>({}),onLoad(){}}});
require('node:vm').runInContext(source+';globalThis.api=Party;',context);
for(const method of ['guestActive','intercept','nextDJ'])assert.equal(context.api[method]('next'),false);
context.window.YT={Party:{guestActive:()=>true,intercept:action=>action==='next',nextDJ:()=>true}};
for(const method of ['guestActive','intercept','nextDJ'])assert.equal(context.api[method]('next'),true);
});
test('Share and External stay behind lazy entry proxies',()=>{
assert.match(app,/const Share = Lazy\.proxy\('feature:share-external'/);
assert.match(app,/const External = Lazy\.proxy\('feature:share-external'/);
const chunk=readFileSync(join(__dirname,'share-external.js'),'utf8');
const context=require('node:vm').createContext({window:{},navigator:{userAgent:''},location:{origin:'https://fixture.test'},isUploadId:()=>false});
require('node:vm').runInContext(chunk,context);
assert.equal(typeof context.window.YT.Share.open,'function');
const text=context.window.YT.External.m3u([{id:'benchmedia01',title:'Fixture'}]);
assert.match(text,/#EXTM3U/);assert.match(text,/benchmedia01/);
});
test('listening tracking does not pull in the lazy Stats view',()=>{
const {groups}=JSON.parse(readFileSync(join(__dirname,'assets.json'),'utf8'));
assert.deepEqual(groups['feature:stats-view'].files,['/stats-view.js']);
assert.deepEqual(groups['feature:stats-view'].dependencies,['feature:stats']);
assert.deepEqual(groups['feature:stats'].files,['/stats-core.js']);
assert.match(app,/Lazy\.proxy\('feature:stats-view', \['render'\], 'StatsView'\)/);
});
test('an unavailable Stats chunk reports an error without rejecting the UI navigation',async()=>{
const source=app.match(/function renderStats\(\) \{[\s\S]*?\n\}/)?.[0];assert.ok(source);
const seen=[],context=require('node:vm').createContext({Lazy:{proxy:()=>({render:()=>Promise.reject(new Error('Unavailable fixture chunk'))})},toast:text=>seen.push(text)});
require('node:vm').runInContext(source+';globalThis.render=renderStats;',context);
await context.render();assert.deepEqual(seen,['Unavailable fixture chunk']);
});

8771
frontend/app.js Normal file → Executable file

File diff suppressed because it is too large Load Diff

204
frontend/asset-sync-core.js Normal file
View File

@@ -0,0 +1,204 @@
/* Exact, resumable asset synchronization shared by pages and workers. */
(function (root) {
'use strict';
const CACHE = 'ytplayer-assets';
const STATE = '/__ytp_asset_state';
const url = (path, file) => path + '?v=' + file.h;
function paths(manifest) {
return Object.keys(manifest.files).sort();
}
function blocking(manifest, previous, activeLayout) {
const names = new Set(Object.entries(manifest.groups)
.filter(([name, group]) => name === 'core' || !group.background ||
name === 'layout:' + activeLayout ||
(previous?.groups[name] && previous.groups[name].contract !== group.contract))
.map(([name]) => name));
for (const name of names) for (const dependency of manifest.groups[name].dependencies || []) names.add(dependency);
return [...new Set([...names].flatMap(name => manifest.groups[name].files))].sort();
}
function plan(manifest, keys) {
const held = new Set(keys);
return {
missing: paths(manifest).map(path => url(path, manifest.files[path])).filter(key => !held.has(key)),
blocking: blocking(manifest).map(path => url(path, manifest.files[path])),
};
}
function retained(current, previous) {
const currentPaths = new Set(paths(current));
const keep = new Set([...currentPaths].map(path => url(path, current.files[path])));
if (previous) for (const path of paths(previous)) {
if (!currentPaths.has(path) || current.files[path]?.h !== previous.files[path].h) keep.add(url(path, previous.files[path]));
}
return keep;
}
function fallback(manifest, previous, path) {
if (!manifest.files[path] || !previous?.files[path]) return null;
const group = Object.keys(manifest.groups).find(name => manifest.groups[name].files.includes(path));
if (!group || !previous.groups[group]?.files.includes(path) ||
manifest.groups[group].contract !== previous.groups[group].contract) return null;
// A stale core must understand every group contract in the new shell.
if (path === "/app.js" && Object.entries(manifest.groups).some(([name, entry]) =>
previous.groups[name]?.contract !== entry.contract)) return null;
return url(path, previous.files[path]);
}
async function state(cache) {
const response = await cache.match(STATE);
return response ? response.json() : null;
}
function verifiedProbe(response, hash) {
if (!response) return false;
const valid = response.headers.get('X-Asset-Hash') === hash;
// Metadata checks must release Blob/data-pipe readers. They never consume
// asset bytes, and cancelling this response does not remove its cache entry.
response.body?.cancel().catch(() => {});
return valid;
}
async function status(manifest, cache, { previous, activeLayout, offline = true } = {}) {
const found = await Promise.all(blocking(manifest, previous, activeLayout).map(async path => {
const response = await cache.match(url(path, manifest.files[path]));
return verifiedProbe(response, manifest.files[path].h);
}));
const missing = found.filter(value => !value).length;
return { ready: missing === 0, missing, version: manifest.buildTag, ...(offline ? await completeness(manifest, cache) : {}) };
}
// All concurrent messages/layout jobs in this worker share six download slots.
let downloads = 0;
const waiters = [];
async function downloadSlot(task) {
if (downloads >= 6) await new Promise(resolve => waiters.push(resolve));
else downloads++;
try { return await task(); }
finally { const next = waiters.shift(); if (next) next(); else downloads--; }
}
const pendingDownloads = new Map();
async function sharedDownload(key, task) {
while (pendingDownloads.has(key)) await pendingDownloads.get(key).catch(() => {});
const promise = downloadSlot(task);
pendingDownloads.set(key, promise);
try { return await promise; }
finally { pendingDownloads.delete(key); }
}
async function syncAssets(manifest, { cache, fetchFn, concurrency = 6, attempts = 3, activeLayout, groups, all = false }) {
const previous = (await state(cache))?.current;
const missing = [];
const selected = all ? paths(manifest) : groups ? [...new Set(groups.flatMap(name => manifest.groups[name]?.files || []))].sort()
: blocking(manifest, previous, activeLayout);
for (const path of selected) {
const key = url(path, manifest.files[path]);
const response = await cache.match(key);
if (!verifiedProbe(response, manifest.files[path].h)) missing.push(key);
}
const count = missing.length;
let failure;
await Promise.all(Array.from({ length: Math.max(1, Math.min(6, concurrency, count)) }, async () => {
while (missing.length) {
const key = missing.shift();
try { await sharedDownload(key, async () => {
const held = await cache.match(key);
if (verifiedProbe(held, key.split('v=')[1])) return;
let error;
for (let attempt = 0; attempt < Math.min(3, attempts); attempt++) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 30000);
try {
const response = await fetchFn(key, { credentials: 'same-origin', signal: controller.signal });
if (!response.ok || response.headers.get('X-Asset-Hash') !== key.split('v=')[1]) {
throw new Error('Asset hash mismatch: ' + key);
}
// Keep the timeout through body consumption, not just response headers.
await cache.put(key, response);
error = null;
break;
} catch (err) { error = err; }
finally { clearTimeout(timer); }
}
if (error) throw error;
}); } catch (error) { failure = error; }
}
}));
if (failure) throw failure;
if (!groups && !all && !(await status(manifest, cache, { previous, activeLayout, offline: false })).ready) throw new Error('Incomplete blocking assets');
return { refreshed: count, caches: 1 };
}
// Verified cache entries are the durable progress journal. Counters are rebuilt
// after worker termination or browser eviction; never trust a stored ready bit.
async function completeness(manifest, cache) {
const files = paths(manifest);
const missingFiles = (await Promise.all(files.map(async path => {
const response = await cache.match(url(path, manifest.files[path]));
return verifiedProbe(response, manifest.files[path].h) ? null : path;
}))).filter(Boolean);
const total = files.length;
return { offlineReady: missingFiles.length === 0, cached: total - missingFiles.length, total, missingFiles };
}
const completionKey = manifest => '/__ytp_completion/' + manifest.buildTag;
async function complete(manifest, { cache, fetchFn, cycles = 4, now = Date.now,
sleep = ms => new Promise(resolve => setTimeout(resolve, ms)), baseDelay = 1000,
maxDelay = 30000, notify = () => {}, force = false } = {}) {
const key = completionKey(manifest), saved = await cache.match(key);
let job = saved ? await saved.json() : { failures: 0, nextRetryAt: 0 };
let snapshot = await completeness(manifest, cache);
const publish = async running => {
job = { ...job, ...snapshot, running, version: manifest.buildTag };
await cache.put(key, Response.json(job));
await notify(job);
};
if (snapshot.offlineReady) { job.failures = 0; job.nextRetryAt = 0; await publish(false); return job; }
if (!force && job.nextRetryAt > now()) await sleep(Math.min(maxDelay, job.nextRetryAt - now()));
for (let cycle = 0; cycle < cycles; cycle++) {
await publish(true);
let error;
try { await syncAssets(manifest, { cache, fetchFn, all: true }); }
catch (failure) { error = failure; }
snapshot = await completeness(manifest, cache);
if (snapshot.offlineReady) { job.failures = 0; job.nextRetryAt = 0; job.error = null; await publish(false); return job; }
job.failures++;
const delay = Math.min(maxDelay, baseDelay * 2 ** Math.min(job.failures - 1, 10));
job.nextRetryAt = now() + delay;
job.error = String(error?.message || 'Incomplete offline cache');
await publish(cycle + 1 < cycles);
if (cycle + 1 < cycles) await sleep(delay);
}
return job;
}
async function commit(manifest, cache, { previousClients, activeLayout } = {}) {
const old = await state(cache);
if (!(await status(manifest, cache, { previous: old?.current, activeLayout, offline: false })).ready) {
throw new Error('Incomplete blocking assets');
}
const sameBuild = old?.current?.buildTag === manifest.buildTag;
const previous = sameBuild ? old.previous : old?.current;
const next = {
current: manifest, previous,
previousClients: previousClients || (sameBuild ? old.previousClients : []),
};
// One state write publishes the complete build and its old-tab affinity.
await cache.put(STATE, new Response(JSON.stringify(next), { headers: { 'Content-Type': 'application/json' } }));
const keep = retained(manifest, previous);
for (const request of await cache.keys()) {
const parsed = new URL(request.url);
const key = parsed.pathname + parsed.search;
if (parsed.searchParams.has('v') && !keep.has(key)) await cache.delete(key);
}
return next;
}
const api = { CACHE, STATE, url, paths, blocking, plan, retained, fallback, status, completeness, completionKey, complete, syncAssets, state, commit };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else root.AssetSyncCore = api;
})(typeof globalThis !== 'undefined' ? globalThis : this);

View File

@@ -0,0 +1,104 @@
const {test}=require('node:test');
const assert=require('node:assert/strict');
const core=require('./asset-sync-core');
const manifest=(a='a',b='b')=>({buildTag:a+b,files:{'/a.js':{h:a},'/index.html':{h:b}},groups:{core:{files:['/a.js','/index.html']}}});
function cache(){const entries=new Map();return {entries,async match(k){return entries.get(k)?.clone()},async put(k,r){entries.set(k,r.clone())},async keys(){return [...entries.keys()].map(url=>({url:'http://local'+url}))},async delete(k){return entries.delete(k)}}}
const response=h=>new Response(h,{headers:{'X-Asset-Hash':h}});
test('exact diff shares unchanged URLs; retains N-1 and prunes N-2',()=>{assert.deepEqual(core.plan(manifest(),['/a.js?v=a']).missing,['/index.html?v=b']);assert.deepEqual([...core.retained(manifest('c'),manifest())].sort(),['/a.js?v=a','/a.js?v=c','/index.html?v=b']);});
test('interrupted sync resumes verified files and refuses a mismatched hash',async()=>{const c=cache();let fail=true;let calls=[];const fetchFn=async u=>{calls.push(u);if(u.includes('index')&&fail)return response('wrong');return response(u.split('=')[1])};await assert.rejects(core.syncAssets(manifest(),{cache:c,fetchFn}),/hash/);assert.ok(await c.match('/a.js?v=a'));fail=false;calls=[];await core.syncAssets(manifest(),{cache:c,fetchFn});assert.deepEqual(calls,['/index.html?v=b']);await c.delete('/a.js?v=a');assert.equal((await core.status(manifest(),c)).missing,1);});
test('commit is atomic and pruning keeps only current and previous changed versions',async()=>{const c=cache();await c.put('/a.js?v=z',response('z'));await core.syncAssets(manifest(),{cache:c,fetchFn:async u=>response(u.split('=')[1])});await core.commit(manifest(),c);await core.syncAssets(manifest('c'),{cache:c,fetchFn:async u=>response(u.split('=')[1])});await core.commit(manifest('c'),c);assert.ok(await c.match('/a.js?v=a'));assert.equal(await c.match('/a.js?v=z'),undefined);await core.syncAssets(manifest('d'),{cache:c,fetchFn:async u=>response(u.split('=')[1])});await core.commit(manifest('d'),c);assert.equal(await c.match('/a.js?v=a'),undefined);});
test('downloads are capped at six and each failure gets three attempts',async()=>{const c=cache(),files={},list=[];for(let i=0;i<13;i++){const p='/'+i+'.js';files[p]={h:String(i)};list.push(p)}const m={buildTag:'pool',files,groups:{core:{files:list}}};let active=0,max=0;const tries={};await core.syncAssets(m,{cache:c,concurrency:20,fetchFn:async u=>{active++;max=Math.max(max,active);await new Promise(r=>setTimeout(r,5));active--;tries[u]=(tries[u]||0)+1;if(tries[u]<3)throw Error('drop');return response(u.split('=')[1])}});assert.equal(max,6);assert.ok(Object.values(tries).every(n=>n===3));});
test('background files do not block, but active layout and contract changes do',()=>{const m=manifest();m.groups.extra={background:true,contract:2,files:['/extra.js']};m.files['/extra.js']={h:'e'};assert.deepEqual(core.blocking(m),['/a.js','/index.html']);assert.ok(core.blocking(m,{groups:{extra:{contract:1}}}).includes('/extra.js'));m.groups['layout:classic']={background:true,files:['/classic.css']};m.files['/classic.css']={h:'c'};assert.ok(core.blocking(m,null,'classic').includes('/classic.css'));});
test('removed files survive one previous build for open tabs',()=>{const previous=manifest(),current=manifest('c');delete current.files['/a.js'];current.groups.core.files=['/index.html'];assert.ok(core.retained(current,previous).has('/a.js?v=a'));});
test('staged fallback permits only the previous same-contract version of a shipped group file', () => {
const old = manifest(), next = manifest('c');
old.groups.core.contract = next.groups.core.contract = 1;
assert.equal(core.fallback(next, old, '/a.js'), '/a.js?v=a');
next.groups.core.contract = 2;
assert.equal(core.fallback(next, old, '/a.js'), null);
assert.equal(core.fallback(next, old, '/missing.js'), null);
});
test('background synchronization fills all groups without publishing a new current manifest', async () => {
const c = cache(), m = manifest();
m.groups.optional = { contract: 1, background: true, files: ['/extra.js'] };
m.files['/extra.js'] = { h: 'e' };
const fetchFn = async key => response(key.split('=')[1]);
await core.syncAssets(m, { cache: c, fetchFn });
assert.equal(await c.match('/extra.js?v=e'), undefined);
await core.commit(m, c);
const before = await core.state(c);
const result = await core.syncAssets(m, { cache: c, fetchFn, groups: ['optional'] });
assert.equal(result.refreshed, 1);
assert.ok(await c.match('/extra.js?v=e'));
assert.deepEqual(await core.state(c), before);
});
test('active layouts also block on shared dependencies, while other layouts stay background', () => {
const m=manifest(); m.groups['layout:glass-stage']={contract:1,background:true,files:['/glass.css'],dependencies:['feature:controls']}; m.groups['feature:controls']={contract:1,background:true,files:['/controls.js']}; m.groups['layout:bento-hub']={contract:1,background:true,files:['/bento.css']};
for(const path of ['/glass.css','/controls.js','/bento.css'])m.files[path]={h:'h'};
assert.deepEqual(core.blocking(m,null,'glass-stage'),['/a.js','/controls.js','/glass.css','/index.html']);
});
test('removing group membership retains the old tab URL even if the physical file is still shipped unchanged',()=>{
const previous=manifest(),current=manifest();current.groups.core.files=['/index.html'];
assert.ok(core.retained(current,previous).has('/a.js?v=a'));
});
test('completion includes ungrouped runtime files and exposes verified missing paths', async () => {
const c=cache(), m=manifest();m.files['/worker.js']={h:'w'};
await core.syncAssets(m,{cache:c,fetchFn:async u=>response(u.split('=')[1])});
const status=await core.status(m,c);
assert.equal(status.ready,true);assert.equal(status.offlineReady,false);
assert.deepEqual(status.missingFiles,['/worker.js']);assert.equal(status.cached,2);assert.equal(status.total,3);
await core.complete(m,{cache:c,fetchFn:async u=>response(u.split('=')[1])});
assert.equal((await core.status(m,c)).offlineReady,true);
});
test('completion persists backoff and resumes only missing files after a worker restart',async()=>{
const c=cache(),m=manifest();let clock=1000;const calls=[];
await core.complete(m,{cache:c,cycles:1,now:()=>clock,baseDelay:10,fetchFn:async u=>{if(u.includes('index'))throw Error('offline');return response('a');}});
const checkpoint=await(await c.match(core.completionKey(m))).json();
assert.equal(checkpoint.running,false);assert.equal(checkpoint.failures,1);assert.equal(checkpoint.nextRetryAt,1010);
await core.complete(m,{cache:c,now:()=>clock,sleep:async ms=>{assert.equal(ms,10);clock+=ms;},fetchFn:async u=>{calls.push(u);return response(u.split('=')[1]);}});
assert.deepEqual(calls,['/index.html?v=b']);
const status=await(await c.match(core.completionKey(m))).json();assert.equal(status.offlineReady,true);assert.equal(status.failures,0);
await c.delete('/a.js?v=a');assert.equal((await core.status(m,c)).offlineReady,false);
});
test('completion retries with exponential backoff and keeps making progress past a failed asset',async()=>{
const c=cache(),m=manifest(),delays=[];let tries=0;
const job=await core.complete(m,{cache:c,baseDelay:5,sleep:async ms=>delays.push(ms),fetchFn:async u=>{if(u.includes('a.js')&&++tries<=6)throw Error('drop');return response(u.split('=')[1]);}});
assert.deepEqual(delays,[5,10]);assert.equal(job.offlineReady,true);assert.ok(await c.match('/index.html?v=b'));
});
test('overlapping layout and completion jobs share a six-download ceiling',async()=>{
const c=cache(),m=manifest();m.groups.extra={background:true,files:[]};
for(let i=0;i<15;i++){const p='/extra'+i+'.js';m.files[p]={h:String(i)};m.groups.extra.files.push(p);}
let active=0,peak=0;const calls=new Map();
const fetchFn=async u=>{active++;peak=Math.max(active,peak);calls.set(u,(calls.get(u)||0)+1);await new Promise(r=>setTimeout(r,3));active--;return response(u.split('=')[1]);};
await Promise.all([core.complete(m,{cache:c,fetchFn}),core.syncAssets(m,{cache:c,fetchFn,groups:['extra']})]);
assert.ok(peak<=6);assert.ok([...calls.values()].every(count=>count===1));
});
test('blocking commit never waits on an optional file readiness probe',{timeout:1000},async()=>{
const c=cache(),m=manifest();m.files['/extra.js']={h:'extra'};m.groups.extra={files:['/extra.js'],background:true,contract:1};
await c.put('/a.js?v=a',response('a'));await c.put('/index.html?v=b',response('b'));
const match=c.match;let extraProbes=0;c.match=async key=>{if(key==='/extra.js?v=extra'){extraProbes++;return new Promise(()=>{});}return match(key);};
await core.commit(m,c);assert.equal(extraProbes,0);assert.equal((await core.state(c)).current.buildTag,m.buildTag);
c.match=match;assert.equal((await core.status(m,c)).offlineReady,false);
});
test('metadata probes release response streams while stored asset bodies remain readable',async()=>{
const c=cache(),m=manifest();await c.put('/a.js?v=a',response('a'));await c.put('/index.html?v=b',response('b'));
const match=c.match,probes=[];c.match=async key=>{const r=await match(key);if(r)probes.push(r);return r;};
assert.equal((await core.status(m,c)).offlineReady,true);assert.ok(probes.length>0);assert.ok(probes.every(r=>r.bodyUsed));
assert.equal(await(await match('/a.js?v=a')).text(),'a');assert.equal(await(await match('/index.html?v=b')).text(),'b');
});
test('stale app core requires every feature contract to match the new shell',()=>{
const old={files:{'/app.js':{h:'old'}},groups:{core:{contract:1,files:['/app.js']},extra:{contract:1,files:[]}}};
const next=structuredClone(old);next.files['/app.js'].h='new';next.groups.extra.contract=2;
assert.equal(core.fallback(next,old,'/app.js'),null);next.groups.extra.contract=1;assert.equal(core.fallback(next,old,'/app.js'),'/app.js?v=old');
});

View File

@@ -0,0 +1,77 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const vm=require('node:vm');const fs=require('node:fs');const core=require('./asset-sync-core');
function environment(){
const stores=new Map(),listeners={},messages=[],skips=[],fetches=[],selfMessages=[];const m={buildTag:'next',files:{'/index.html':{h:'index'},'/app.js':{h:'app'}},groups:{core:{files:['/index.html','/app.js']}}};
const storage={async keys(){return [...stores.keys()]},async delete(n){return stores.delete(n)},async open(n){if(!stores.has(n)){const map=new Map();stores.set(n,{async match(k){return map.get(typeof k==='string'?k:new URL(k.url).pathname+new URL(k.url).search)?.clone()},async put(k,r){map.set(k,r.clone())},async keys(){return [...map.keys()].map(k=>({url:'https://local'+k}))},async delete(k){return map.delete(typeof k==='string'?k:new URL(k.url).pathname+new URL(k.url).search)}})}return stores.get(n)}};
const sandbox={__BUILD_TAG__:'next',__ASSET_SYNC__:true,AssetSyncCore:core,importScripts:()=>{},caches:storage,URL,Response,Request,Headers,setTimeout,clearTimeout,crypto:require('node:crypto').webcrypto,console,fetch:async u=>{fetches.push(u);return u==='/api/manifest'?Response.json(m):new Response(u,{headers:{'X-Asset-Hash':m.files[u.split('?')[0]]?.h || ''}})},self:{registration:{active:{postMessage:data=>selfMessages.push(data)}},location:{origin:'https://local'},addEventListener:(t,f)=>listeners[t]=f,skipWaiting:()=>skips.push(1),clients:{claim:async()=>{},matchAll:async()=>[{id:'old',postMessage:x=>messages.push(x)}]}}};
vm.runInNewContext(fs.readFileSync(__dirname+'/sw.js','utf8'),sandbox);
async function dispatch(t,e={}){const tasks=[];listeners[t]({...e,waitUntil:v=>tasks.push(v)});await Promise.all(tasks)}
async function request(url,mode='cors',clientId='new'){let p;const tasks=[];listeners.fetch({request:{url:'https://local'+url,method:'GET',mode},clientId,waitUntil:v=>tasks.push(v),respondWith:v=>p=v});const response=await p;await Promise.all(tasks);return response;}
return {storage,m,skips,fetches,dispatch,request,sandbox,selfMessages,async complete(){for(const data of selfMessages.splice(0))await dispatch('message',{data});}};
}
test('install does not activate or publish; CACHE_STATUS is honest; activation commits and exact requests self-heal',async()=>{const e=environment();await e.dispatch('install');assert.equal(e.skips.length,0);const cache=await e.storage.open(core.CACHE);assert.equal(await core.state(cache),null);let reply;await e.dispatch('message',{data:{type:'CACHE_STATUS'},ports:[{postMessage:r=>reply=r}]});assert.equal(reply.ready,true);await e.dispatch('activate');await e.complete();assert.equal((await core.state(cache)).current.buildTag,'next');assert.equal((await e.request('/playlist/x','navigate')).headers.get('X-Asset-Hash'),'index');await cache.delete('/app.js?v=app');assert.equal((await core.status(e.m,cache)).ready,false);await e.dispatch('message',{data:{type:'CACHE_STATUS'},ports:[{postMessage:r=>reply=r}]});assert.equal((await core.status(e.m,cache)).offlineReady,true);assert.equal(reply.version,'next');assert.equal((await e.request('/app.js')).headers.get('X-Asset-Hash'),'app');assert.ok(await cache.match('/app.js?v=app'));assert.equal(await cache.match('/app.js?v=stale'),undefined);assert.equal((await e.request('/app.js?v=stale')).status,409);});
test('reported playback defers explicit activation until pause; install never calls skipWaiting',async()=>{const e=environment(),source={id:'p'};await e.dispatch('message',{data:{type:'SKIP_WAITING'}});assert.equal(e.skips.length,0);await e.dispatch('message',{source,data:{type:'PLAYING',value:true}});await e.dispatch('message',{source,data:{type:'SKIP_WAITING'}});assert.equal(e.skips.length,0);await e.dispatch('message',{source,data:{type:'PLAYING',value:false}});assert.equal(e.skips.length,1);});
test('staged same-contract responses use verified N-1 without poisoning the new URL',async()=>{
const e=environment(); const cache=await e.storage.open(core.CACHE);
const old={buildTag:'old',files:{'/extra.js':{h:'old'}},groups:{core:{files:[],contract:1},'feature:extra':{files:['/extra.js'],contract:1,background:true}}};
e.m.groups.core.contract=1; e.m.groups['feature:extra']={files:['/extra.js'],contract:1,background:true}; e.m.files['/extra.js']={h:'new'};
await cache.put(core.STATE,Response.json({current:old})); await cache.put('/extra.js?v=old',new Response('old body',{headers:{'X-Asset-Hash':'old','Cache-Control':'public, max-age=31536000, immutable','Content-Encoding':'gzip','Content-Length':'9'}}));
await e.dispatch('install'); await e.dispatch('activate');await e.complete();
assert.ok(await cache.match('/extra.js?v=new'));await cache.delete('/extra.js?v=new');
assert.equal(await cache.match('/extra.js?v=new'),undefined);
const stale=await e.request('/extra.js?v=new'); assert.equal(await stale.text(),'old body');assert.equal(stale.headers.get('X-Asset-Hash'),'old');assert.equal(stale.headers.get('Cache-Control'),'no-store');assert.equal(stale.headers.get('Content-Encoding'),null);assert.equal(stale.headers.get('Content-Length'),null);assert.equal(await cache.match('/extra.js?v=new'),undefined);
await e.dispatch('message',{data:{type:'WARM_ASSETS',saveData:true}}); assert.ok(await cache.match('/extra.js?v=new'));
await e.dispatch('message',{data:{type:'WARM_ASSETS',saveData:false}}); assert.equal((await cache.match('/extra.js?v=new')).headers.get('X-Asset-Hash'),'new');
assert.equal((await e.request('/extra.js?v=new')).headers.get('X-Asset-Hash'),'new');
});
test('a changed background contract is downloaded before ready and cannot fall back after commit',async()=>{
const e=environment(),cache=await e.storage.open(core.CACHE);
const old={buildTag:'old',files:{'/extra.js':{h:'old'}},groups:{core:{files:[],contract:1},'feature:extra':{files:['/extra.js'],contract:1,background:true}}};
e.m.groups.core.contract=1;e.m.groups['feature:extra']={files:['/extra.js'],contract:2,background:true};e.m.files['/extra.js']={h:'new'};
await cache.put(core.STATE,Response.json({current:old}));await cache.put('/extra.js?v=old',new Response('old body',{headers:{'X-Asset-Hash':'old'}}));
await e.dispatch('install');assert.equal((await core.state(cache)).current.buildTag,'old');
assert.equal((await cache.match('/extra.js?v=new')).headers.get('X-Asset-Hash'),'new');
let reply;await e.dispatch('message',{data:{type:'CACHE_STATUS'},ports:[{postMessage:r=>reply=r}]});assert.equal(reply.ready,true);
await e.dispatch('activate');await e.complete();await cache.delete('/extra.js?v=new');
const response=await e.request('/extra.js?v=new');assert.equal(response.headers.get('X-Asset-Hash'),'new');assert.notEqual(await response.text(),'old body');
});
test('overlapping idle warm messages share one download pool',async()=>{
const e=environment();e.m.files['/extra.js']={h:'extra'};e.m.groups['feature:extra']={files:['/extra.js'],contract:1,background:true};
await e.dispatch('install');await e.dispatch('activate');await e.complete();
await Promise.all([e.dispatch('message',{data:{type:'WARM_ASSETS',saveData:false}}),e.dispatch('message',{data:{type:'WARM_ASSETS',saveData:false}})]);
assert.equal(e.fetches.filter(url=>url==='/extra.js?v=extra').length,1);
});
test('waiting status does not start completion and activation delegates it to its own event',async()=>{
const e=environment();e.m.files['/extra.js']={h:'extra'};e.m.groups['feature:extra']={files:['/extra.js'],contract:1,background:true};
await e.dispatch('install');let reply;await e.dispatch('message',{data:{type:'CACHE_STATUS'},ports:[{postMessage:r=>reply=r}]});
assert.equal(reply.ready,true);assert.equal(reply.offlineReady,false);assert.ok(!e.fetches.includes('/extra.js?v=extra'));
let release,started;const gate=new Promise(r=>release=r),begin=new Promise(r=>started=r),fetch=e.sandbox.fetch;
e.sandbox.fetch=async url=>{if(url==='/extra.js?v=extra'){started();await gate;}return fetch(url);};
await e.dispatch('activate');const cache=await e.storage.open(core.CACHE);
assert.equal((await core.state(cache)).current.buildTag,'next');assert.equal((await core.status(e.m,cache)).ready,true);
assert.equal((await core.status(e.m,cache)).offlineReady,false);assert.equal(e.selfMessages[0].type,'COMPLETE_ASSETS');
const job=e.complete();await begin;assert.equal(await cache.match('/extra.js?v=extra'),undefined);release();await job;
assert.equal((await core.status(e.m,cache)).offlineReady,true);
});
test('page-captured app is reused on first install without a worker download',async()=>{
const e=environment(),cache=await e.storage.open(core.CACHE);
await cache.put('/app.js?v=app',new Response('page captured app',{headers:{'X-Asset-Hash':'app'}}));
await e.dispatch('install');assert.equal(e.fetches.includes('/app.js?v=app'),false);
assert.equal(await(await cache.match('/app.js?v=app')).text(),'page captured app');
assert.equal(e.skips.length,0);assert.equal(await core.state(cache),null);
});
test('worker never supplies stale app to a native script when a feature contract changed',async()=>{
const e=environment(),cache=await e.storage.open(core.CACHE);
const old={buildTag:'old',files:{'/app.js':{h:'old'}},groups:{core:{contract:1,files:['/app.js']},extra:{contract:1,files:[]}}};
e.m.groups.core.contract=1;e.m.groups.extra={contract:2,background:true,files:[]};
await cache.put(core.STATE,Response.json({current:old}));await cache.put('/app.js?v=old',new Response('old app',{headers:{'X-Asset-Hash':'old'}}));
await e.dispatch('install');await e.dispatch('activate');await cache.delete('/app.js?v=app');
e.sandbox.fetch=async()=>{throw Error('offline')};
const response=await e.request('/app.js?v=app');assert.equal(response.status,503);assert.equal(await response.text(),'Offline');
});

377
frontend/assets.json Normal file
View File

@@ -0,0 +1,377 @@
{
"groups": {
"core": {
"contract": 2,
"eager": true,
"files": [
"/index.html",
"/styles.css",
"/service-ui.css",
"/refresh.css",
"/layout-base.css",
"/recommendations.css",
"/flag-ui.js",
"/async-guard.js",
"/visible-timer.js",
"/asset-sync-core.js",
"/sw-update.js",
"/fingerprint.js",
"/opfs.js",
"/opfs-worker.js",
"/lyrics-core.js",
"/lyrics-display.js",
"/sha256.js",
"/resume-core.js",
"/loudness-wasm.js",
"/loudness.js",
"/sha256-wasm.js",
"/settings-sections.js",
"/related-videos.js",
"/related-videos.css",
"/audio-continuity.js",
"/fullscreen-orientation.js",
"/fullscreen-orientation.css",
"/download-actions.js",
"/download-actions.css",
"/download-errors.js",
"/downloads.js",
"/downloads-page.js",
"/offline-pages.css",
"/saved-page.js",
"/server-backfill.js",
"/saved-page.css",
"/prewarm-next.js",
"/settings-sections.css",
"/app.js",
"/manifest.webmanifest",
"/icons/icon-192.png",
"/icons/icon-512.png",
"/fonts/fonts.css",
"/fonts/BricolageGrotesque-latin-ext.woff2",
"/fonts/BricolageGrotesque-latin.woff2",
"/fonts/HankenGrotesk-latin-ext.woff2",
"/fonts/HankenGrotesk-latin.woff2",
"/fonts/JetBrainsMono-latin-ext.woff2",
"/fonts/JetBrainsMono-latin.woff2",
"/lazy.js",
"/feature-bootstrap.js",
"/eq-parameters.js",
"/assets.json",
"/device-db.js",
"/shell-core.js",
"/views-core.js",
"/section-rail.js"
],
"background": false
},
"layout:glass-stage": {
"contract": 1,
"eager": false,
"files": [
"/theme-glass.css",
"/theme-glass-panel.css",
"/glass-panel-layout.js"
],
"background": true,
"dependencies": [
"feature:layout-controls"
]
},
"layout:classic": {
"contract": 1,
"eager": false,
"files": [
"/theme-classic.css"
],
"background": true
},
"layout:bento-hub": {
"contract": 1,
"eager": false,
"files": [
"/theme-bento-hub.css",
"/bento-hub.js",
"/fonts/PlusJakartaSans-latin.woff2",
"/fonts/PlusJakartaSans-latin-ext.woff2"
],
"background": true,
"dependencies": [
"feature:layout-controls"
]
},
"layout:f7-swipe": {
"contract": 1,
"eager": false,
"files": [
"/theme-f7.css",
"/vendor/framework7-swipe.min.js",
"/f7-layout.js"
],
"background": true
},
"feature:piano": {
"contract": 1,
"eager": false,
"files": [
"/piano-core.js",
"/piano.js",
"/piano-engine.mjs"
],
"background": true
},
"feature:midi": {
"contract": 1,
"eager": false,
"files": [
"/midi.js"
],
"background": true
},
"feature:party-dj": {
"contract": 1,
"eager": false,
"files": [
"/party-dj.js"
],
"background": true
},
"feature:lyrics-window": {
"contract": 1,
"eager": false,
"files": [
"/lyrics-window.js"
],
"background": true
},
"feature:lower-third": {
"contract": 1,
"eager": false,
"files": [
"/lower-third.js",
"/lower-third.css"
],
"background": true
},
"feature:vocal-reducer": {
"contract": 1,
"eager": false,
"files": [
"/vocal-reducer.js"
],
"background": true
},
"feature:eq-core": {
"contract": 1,
"eager": false,
"files": [
"/eq-core.js"
],
"background": true
},
"feature:setlist-import": {
"contract": 1,
"eager": false,
"files": [
"/setlist-import.js"
],
"background": true
},
"feature:car-mode": {
"contract": 1,
"eager": false,
"files": [
"/car-mode.js",
"/car-mode.css"
],
"background": true
},
"feature:p2p": {
"contract": 1,
"eager": false,
"files": [
"/p2p-core.js",
"/p2p-client.js",
"/p2p-transfer.js",
"/p2p-recv-worker.js",
"/hash-worker.js"
],
"background": true
},
"feature:direct": {
"contract": 1,
"eager": false,
"files": [
"/direct-protocol.js",
"/direct-stream.js",
"/direct-media.js",
"/direct-media.css",
"/direct-recv-worker.js"
],
"background": true,
"dependencies": [
"feature:p2p"
]
},
"feature:video-edit": {
"contract": 1,
"eager": false,
"files": [
"/video-edit.js"
],
"background": true
},
"feature:stats": {
"contract": 1,
"eager": false,
"files": [
"/stats-core.js"
],
"background": true
},
"feature:export": {
"contract": 1,
"eager": false,
"files": [
"/export.js"
],
"background": true
},
"feature:playlist": {
"contract": 1,
"eager": true,
"files": [],
"embeddedIn": [
"/app.js"
],
"background": false
},
"feature:settings": {
"contract": 1,
"eager": true,
"files": [],
"embeddedIn": [
"/app.js",
"/settings-sections.js",
"/settings-sections.css",
"/views-core.js"
],
"background": false
},
"feature:service-mode": {
"contract": 1,
"eager": true,
"files": [],
"embeddedIn": [
"/app.js",
"/service-ui.css"
],
"background": false
},
"feature:lyrics-editor": {
"contract": 1,
"eager": true,
"files": [],
"embeddedIn": [
"/app.js",
"/lyrics-core.js",
"/lyrics-display.js"
],
"background": false
},
"feature:layout-controls": {
"contract": 1,
"eager": false,
"background": true,
"files": [
"/theme-glass-controls.css",
"/glass-controls.js"
]
},
"layout:sanctuary-stage": {
"contract": 1,
"eager": false,
"background": true,
"files": []
},
"layout:liturgical": {
"contract": 1,
"eager": false,
"background": true,
"files": []
},
"layout:living-hymnal": {
"contract": 1,
"eager": false,
"background": true,
"files": []
},
"layout:broadcaster": {
"contract": 1,
"eager": false,
"background": true,
"files": []
},
"layout:contemplative": {
"contract": 1,
"eager": false,
"background": true,
"files": []
},
"feature:presenter": {
"contract": 1,
"eager": false,
"background": true,
"files": [
"/presenter.js"
]
},
"feature:remote-client": {
"contract": 1,
"eager": false,
"background": true,
"files": [
"/remote-client.js"
]
},
"feature:watch-party": {
"contract": 1,
"eager": false,
"background": true,
"files": [
"/watch-party-client.js"
]
},
"feature:share-external": {
"contract": 1,
"eager": false,
"background": true,
"files": [
"/share-external.js"
]
},
"feature:stats-view": {
"contract": 1,
"eager": false,
"background": true,
"files": [
"/stats-view.js"
],
"dependencies": [
"feature:stats"
]
},
"feature:jamesdsp": {
"contract": 1,
"eager": false,
"files": [
"/vendor/jamesdsp/controller.js",
"/vendor/jamesdsp/jamesdsp-node.js",
"/vendor/jamesdsp/worklet.js",
"/vendor/jamesdsp/params.js",
"/vendor/jamesdsp/dsp/jamesdsp.js",
"/vendor/jamesdsp/dsp/jamesdsp.wasm"
],
"background": false
}
}
}

45
frontend/async-guard.js Executable file
View File

@@ -0,0 +1,45 @@
/* ============================================================================
* async-guard — tiny concurrency helper shared by the frontend.
*
* Keeps long-running native operations (offline-cache download/delete, playlist
* mutations) from being triggered twice at once for the same target, so the UI
* stays responsive and on-device state can't be corrupted by rapid clicks.
*
* Framework-free and dependency-free on purpose:
* • Loads as a plain <script> under CSP `script-src 'self'` (browser global
* `window.AsyncGuard`).
* • `require`-able by `node --test` (CommonJS `module.exports`).
* ========================================================================== */
(function (root) {
'use strict';
/**
* Run `fn` exclusively for `key`: if an operation for `key` is already
* in-flight (tracked in `set`), this call is a no-op and resolves to
* `undefined`. Otherwise `key` is added to `set`, `fn` runs, and `key` is
* removed once it settles — on success AND on failure — so a failed
* operation can be retried.
*
* @param {Set<string>} set in-flight key registry (caller owns it)
* @param {string} key identifies the target being operated on
* @param {() => (any|Promise<any>)} fn the work to run exclusively
* @returns {Promise<any>} fn's resolved value, or undefined if skipped
*/
async function runExclusive(set, key, fn) {
if (set.has(key)) return undefined;
set.add(key);
try {
return await fn();
} finally {
set.delete(key);
}
}
const AsyncGuard = { runExclusive };
if (typeof module !== 'undefined' && module.exports) {
module.exports = AsyncGuard;
} else {
root.AsyncGuard = AsyncGuard;
}
})(typeof globalThis !== 'undefined' ? globalThis : this);

68
frontend/async-guard.test.js Executable file
View File

@@ -0,0 +1,68 @@
'use strict';
const { test } = require('node:test');
const assert = require('node:assert');
const { runExclusive } = require('./async-guard');
// A controllable promise so a test can hold an operation "in flight".
function deferred() {
let resolve, reject;
const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
return { promise, resolve, reject };
}
test('runs fn and returns its resolved value', async () => {
const set = new Set();
const out = await runExclusive(set, 'a', async () => 42);
assert.strictEqual(out, 42);
assert.strictEqual(set.size, 0, 'key freed after success');
});
test('skips a second concurrent call for the same key (fn runs once)', async () => {
const set = new Set();
let calls = 0;
const d = deferred();
const first = runExclusive(set, 'k', async () => { calls++; await d.promise; return 'first'; });
// Second call while the first is still in flight — must be a no-op.
const second = await runExclusive(set, 'k', async () => { calls++; return 'second'; });
assert.strictEqual(second, undefined, 'skipped call resolves to undefined');
assert.strictEqual(calls, 1, 'fn invoked only once');
d.resolve();
assert.strictEqual(await first, 'first');
});
test('different keys run in parallel', async () => {
const set = new Set();
const dA = deferred();
const dB = deferred();
let aDone = false;
const a = runExclusive(set, 'A', async () => { await dA.promise; aDone = true; return 'A'; });
const b = runExclusive(set, 'B', async () => { await dB.promise; return 'B'; });
assert.strictEqual(set.size, 2, 'both keys in flight at once');
// B can finish before A — proves they are not serialized.
dB.resolve();
assert.strictEqual(await b, 'B');
assert.strictEqual(aDone, false, 'A still in flight while B completed');
dA.resolve();
assert.strictEqual(await a, 'A');
assert.strictEqual(set.size, 0);
});
test('frees the key after failure so a retry is possible', async () => {
const set = new Set();
await assert.rejects(
runExclusive(set, 'x', async () => { throw new Error('boom'); }),
/boom/,
);
assert.strictEqual(set.has('x'), false, 'key freed even on throw');
// Retry now succeeds because the key was released.
const out = await runExclusive(set, 'x', async () => 'ok');
assert.strictEqual(out, 'ok');
});
test('supports a synchronous fn', async () => {
const set = new Set();
const out = await runExclusive(set, 's', () => 7);
assert.strictEqual(out, 7);
assert.strictEqual(set.size, 0);
});

View File

@@ -0,0 +1,31 @@
(function (root) {
'use strict';
function progressiveSource(current, videoSource) {
return current?.eqAudioUrl || current?.localUrl || current?.audioUrl || videoSource || '';
}
function needsAlignment(time, clock, threshold = 0.3) {
return Number.isFinite(time) && Number.isFinite(clock) && Math.abs(time - clock) >= threshold;
}
function create() {
const pending = new WeakMap();
function play(element) {
if (pending.has(element)) return pending.get(element);
if (!element.paused) return Promise.resolve();
let request;
try { request = Promise.resolve(element.play()); } catch (error) { request = Promise.reject(error); }
// Preserve the intent to play after an OS interruption; the watchdog retries.
request = request.catch(() => {}).finally(() => { if (pending.get(element) === request) pending.delete(element); });
pending.set(element, request); return request;
}
function resume(element, clock) {
// An ended element is finished, not interrupted: play() would restart it from 0.
if (!element || !element.paused || element.ended || pending.has(element)) return;
if (clock && element !== clock && needsAlignment(element.currentTime, clock.currentTime)) element.currentTime = clock.currentTime;
return play(element);
}
return { play, resume, reset: element => pending.delete(element) };
}
const api = { progressiveSource, needsAlignment, create };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else { root.AudioContinuity = api; root.audioContinuity = create(); }
})(globalThis);

View File

@@ -0,0 +1,49 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { progressiveSource, needsAlignment, create } = require('./audio-continuity');
test('iPhone progressive audio uses saved/EQ sources before remote fallbacks', () => {
assert.equal(progressiveSource({ localUrl: 'blob:saved', audioUrl: 'remote' }, 'mux'), 'blob:saved');
assert.equal(progressiveSource({ eqAudioUrl: 'blob:eq', localUrl: 'blob:saved' }), 'blob:eq');
assert.equal(progressiveSource({ audioUrl: 'audio' }, 'mux'), 'audio');
assert.equal(progressiveSource({}, 'mux'), 'mux');
});
test('small drift and invalid clocks do not trigger an audible seek', () => {
assert.equal(needsAlignment(50.05, 50), false);
assert.equal(needsAlignment(49, 50), true);
assert.equal(needsAlignment(NaN, 50), false);
});
test('simultaneous play, visibility and watchdog resumes share one pending play', async () => {
let finish, calls = 0, seeks = 0;
const audio = { paused: true, get currentTime() { return 10; }, set currentTime(value) { seeks++; }, play() { calls++; return new Promise(resolve => { finish = resolve; }); } };
const controller = create();
controller.resume(audio, { currentTime: 10.05 });
controller.resume(audio, { currentTime: 12 });
const pending = controller.play(audio);
assert.equal(calls, 1); assert.equal(seeks, 0);
finish(); await pending;
controller.resume(audio, audio); // never seek an element to itself
assert.equal(seeks, 0); assert.equal(calls, 2); finish();
});
test('rejected autoplay can retry and only paused, misaligned secondaries seek', async () => {
const controller = create(); let calls = 0;
const audio = { paused: true, currentTime: 0, play() { calls++; return Promise.reject(new Error('OS suspension')); } };
await controller.play(audio); await controller.resume(audio, { currentTime: 4 });
assert.equal(calls, 2); assert.equal(audio.currentTime, 4);
audio.paused = false; controller.resume(audio, { currentTime: 10 });
assert.equal(audio.currentTime, 4); assert.equal(calls, 2);
});
test('a new play after pause/source reset is not blocked by a stale promise', async () => {
const controller = create(), finishes = []; let calls = 0;
const audio = { paused: true, play() { calls++; return new Promise(resolve => finishes.push(resolve)); } };
const old = controller.play(audio); controller.reset(audio);
const fresh = controller.play(audio); assert.equal(calls, 2);
finishes[0](); await old;
assert.equal(controller.play(audio), fresh); // old completion cannot discard the new request
finishes[1](); await fresh;
});
test('an ended element is never resumed (last song must not restart from 0)', () => {
let calls = 0;
const audio = { paused: true, ended: true, currentTime: 200, play() { calls++; return Promise.resolve(); } };
create().resume(audio, { currentTime: 200 });
assert.equal(calls, 0);
});

65
frontend/autosave.test.js Normal file
View File

@@ -0,0 +1,65 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
// Exercise the actual app functions without DOM/player/network dependencies.
const source = fs.readFileSync(require('node:path').join(__dirname, 'app.js'), 'utf8');
function harness({ autoPreload = true, cached = [], result = { ok: true, cached: true }, error } = {}) {
const calls = [], jobs = new Map();
const video = { id: 'benchmedia01', title: 'Local clip' };
const context = vm.createContext({
data: { settings: { autoPreload }, playlists: [{ id: 'pl', videos: [video] }], pinnedPlaylists: [] },
cachedIds: new Set(cached), downloading: new Set(), downloadMeta: new Map(), saveControllers: new Map(),
view: { type: 'home' }, current: null, window: {}, AbortController,
slim: v => v, markCardCacheState() {}, renderSidebar() {}, updateDownloadBadge() {}, toast() {},
SaveSlots: { acquire: async () => {}, release() {} },
SaveQueue: { add: v => jobs.set(v.id, { status: 'queued' }), remove: id => jobs.delete(id), progress() {}, state: (id, status, message) => jobs.set(id, { status, message }) },
API: { cacheDownload: async id => { calls.push(id); if (error) throw error; return result; } },
recordDeviceFile() {}, warmThumb() {}, thumbUrlFor: () => '', cacheMutations: 0,
});
const preload = source.slice(source.indexOf('async function preload(video,'), source.indexOf('// A device copy that failed to play.'));
const playlists = source.slice(source.indexOf('function preloadPlaylist(pl)'), source.indexOf('// Update a single card\'s saved badge'));
vm.runInContext(preload + playlists, context);
return { context, calls, jobs, video };
}
test('auto preload tops up playlists, while pinned playlists save with the setting off', async () => {
const h = harness({ autoPreload: false });
h.context.preloadPlaylist(h.context.data.playlists[0]);
await new Promise(r => setImmediate(r));
assert.deepEqual(h.calls, []);
h.context.data.pinnedPlaylists = ['pl'];
h.context.preloadPinnedPlaylists();
await new Promise(r => setImmediate(r));
assert.deepEqual(h.calls, [h.video.id]);
assert.ok(h.context.cachedIds.has(h.video.id));
assert.equal(h.jobs.size, 0);
assert.equal(h.context.downloading.size, 0);
const enabled = harness();
enabled.context.preloadPlaylist(enabled.context.data.playlists[0]);
await new Promise(r => setImmediate(r));
assert.deepEqual(enabled.calls, [enabled.video.id]);
});
test('a repeated save shares the in-flight operation and does not download an existing copy', async () => {
const h = harness();
await Promise.all([h.context.preload(h.video), h.context.preload(h.video)]);
await h.context.preload(h.video);
assert.deepEqual(h.calls, [h.video.id]);
assert.ok(h.context.cachedIds.has(h.video.id));
assert.equal(h.context.saveControllers.size, 0);
});
test('failed and interrupted saves do not acquire a Saved badge and can be attempted again', async () => {
for (const options of [{ result: { ok: false, error: 'server failed' } }, { error: new Error('storage quota') }, { result: { ok: false, paused: true } }]) {
const h = harness(options);
await h.context.preload(h.video, { quiet: true });
assert.equal(h.context.cachedIds.has(h.video.id), false);
assert.equal(h.context.downloading.size, 0);
assert.equal(h.context.saveControllers.size, 0);
assert.ok(h.jobs.has(h.video.id));
await h.context.preload(h.video, { quiet: true });
assert.equal(h.calls.length, 2);
}
});

40
frontend/bento-hub.js Normal file
View File

@@ -0,0 +1,40 @@
/* Bento-only artwork and measured clearance. Navigation and player nodes stay put. */
(function(root){
'use strict';
function chromeClearance(height,boxes){
const occupied=boxes.filter(b=>b.visible&&b.fixed&&b.height>0&&b.top>=height/2).map(b=>height-b.top);
return Math.max(0,...occupied)+16;
}
function mount(doc){
let frame=0,active=false;const html=doc.documentElement;
const resize=new root.ResizeObserver(schedule),observer=new root.MutationObserver(schedule);
function paint(){
frame=0;const on=html.dataset.layout==='bento-hub';
if(!on){if(active){resize.disconnect();observer.disconnect();html.style.removeProperty('--bento-bottom-clearance');doc.querySelectorAll('.bento-collage,.bento-search-icon').forEach(n=>n.remove());doc.querySelectorAll('.bento-search-label').forEach(n=>n.replaceWith(...n.childNodes));}active=false;return;}
if(!active){active=true;observer.observe(doc.body,{childList:true,subtree:true,attributes:true,attributeFilter:['class','hidden']});for(const id of ['bottomNav','miniBar','sectionRail']){const el=doc.getElementById(id);if(el)resize.observe(el);}}
const search=doc.querySelector('.search-btn');
if(search&&!search.querySelector('.bento-search-icon')){
const label=doc.createElement('span');label.className='bento-search-label';label.append(...search.childNodes);
const icon=doc.createElementNS('http://www.w3.org/2000/svg','svg');icon.classList.add('bento-search-icon');icon.setAttribute('aria-hidden','true');icon.setAttribute('viewBox','0 0 24 24');icon.innerHTML='<circle cx="10.5" cy="10.5" r="6.5"/><path d="m16 16 5 5"/>';search.append(label,icon);
}
const boxes=['bottomNav','miniBar','sectionRail'].map(id=>doc.getElementById(id)).filter(Boolean).map(el=>{const r=el.getBoundingClientRect(),s=root.getComputedStyle(el);return {top:r.top,height:r.height,fixed:s.position==='fixed',visible:s.display!=='none'&&s.visibility!=='hidden'};});
const clearance=chromeClearance(root.innerHeight,boxes)+'px';if(html.style.getPropertyValue('--bento-bottom-clearance')!==clearance)html.style.setProperty('--bento-bottom-clearance',clearance);
for(const card of doc.querySelectorAll('.home-pl-card')){
if(card.querySelector('.bento-collage'))continue;
// Use actual playlist artwork; never invent an image or a verification badge.
const name=card.querySelector('.home-pl-name')?.textContent;
const playlist=root.BentoHub.playlists?.().find(p=>p.name===name);
const images=(playlist?.videos||[]).filter(v=>v.thumbnail).slice(0,4);
if(images.length<4)continue;
const collage=doc.createElement('span');collage.className='bento-collage';collage.setAttribute('aria-hidden','true');
for(const video of images){const img=doc.createElement('img');img.src=video.thumbnail;img.alt='';img.loading='lazy';collage.append(img);}
card.querySelector('.home-pl-thumb')?.prepend(collage);
}
}
function schedule(){if(!frame)frame=root.requestAnimationFrame(paint);}
new root.MutationObserver(schedule).observe(html,{attributes:true,attributeFilter:['data-layout']});root.addEventListener('resize',schedule);paint();
}
const api={chromeClearance,playlists:null};
if(typeof module!=='undefined')module.exports=api;
else {root.BentoHub=api; if(root.document.readyState==='loading')root.document.addEventListener('DOMContentLoaded',()=>mount(root.document),{once:true});else mount(root.document);}
})(typeof window==='undefined'?globalThis:window);

View File

@@ -0,0 +1,12 @@
const test=require('node:test'),assert=require('node:assert/strict');
const {chromeClearance}=require('./bento-hub');
test('clearance follows the highest visible floating control, including safe area',()=>{
assert.equal(chromeClearance(844,[{visible:true,fixed:true,top:746,height:98},{visible:true,fixed:true,top:666,height:72},{visible:true,fixed:true,top:602,height:56}]),258);
});
test('hidden and scrolling content cannot reserve fullscreen bottom space',()=>{
assert.equal(chromeClearance(844,[{visible:false,fixed:true,top:602,height:56},{visible:true,fixed:false,top:500,height:100},{visible:true,fixed:true,top:0,height:64}]),16);
});
test('desktop mini player reserves its real height and margin; no chrome is 16px',()=>{
assert.equal(chromeClearance(844,[{visible:true,fixed:true,top:760,height:72}]),100);
assert.equal(chromeClearance(844,[]),16);
});

6
frontend/car-mode.css Normal file
View File

@@ -0,0 +1,6 @@
.car-mode { position: fixed; inset: 0; z-index: 20000; background: #070809; color: #fff; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); overflow: auto; display: flex; flex-direction: column; gap: 20px; }
.car-mode h1 { font: 650 clamp(24px, 4vw, 42px)/1.25 system-ui; margin: auto 0; overflow-wrap: anywhere; text-align: center; }
.car-controls { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; width: min(100%, 800px); margin: auto; }
.car-controls button { min-height: 110px; font: 650 clamp(22px, 3vw, 36px)/1.2 system-ui; background: #fff; color: #050607; border: 3px solid #fff; border-radius: 16px; }
.car-exit { align-self: flex-start; min-height: 52px; padding: 12px 20px; background: #070809; color: #fff; border: 2px solid #fff; border-radius: 8px; }
.car-mode button:focus-visible { outline: 4px solid #61caff; outline-offset: 4px; }

29
frontend/car-mode.js Normal file
View File

@@ -0,0 +1,29 @@
/* Voice search and a deliberately sparse, high-contrast transport. */
(function(root) {
'use strict';
function transcript(event) { let text = ''; for (let i = event.resultIndex || 0; i < (event.results?.length || 0); i++) if (event.results[i].isFinal) text += `${event.results[i][0]?.transcript || ''} `; return text.trim(); }
let adapter, overlay, timer, savedFocus, previous = [];
function close() { if (!overlay) return; clearInterval(timer); overlay.remove(); overlay = null; for (const [node, inert] of previous) node.inert = inert; previous = []; savedFocus?.focus?.(); }
function open() {
if (overlay) return;
const doc = root.document; savedFocus = doc.activeElement; previous = [...doc.body.children].map(node => [node, node.inert]); previous.forEach(([node]) => { node.inert = true; });
overlay = doc.createElement('section'); overlay.className = 'car-mode'; overlay.setAttribute('role', 'dialog'); overlay.setAttribute('aria-modal', 'true'); overlay.setAttribute('aria-label', 'Car mode');
const exit = doc.createElement('button'); exit.type = 'button'; exit.className = 'car-exit'; exit.textContent = 'Exit Car mode'; exit.onclick = close;
const title = doc.createElement('h1'); const controls = doc.createElement('div'); controls.className = 'car-controls'; let toggle;
for (const [label, action] of [['Previous', 'prev'], ['Play / Pause', 'toggle'], ['15 s back', 'back'], ['Next', 'next']]) { const b = doc.createElement('button'); b.type = 'button'; b.innerHTML = root.TransportIcons.svg({prev:'previous',toggle:'play',back:'back15',next:'next'}[action]) + '<span>' + label + '</span>'; b.setAttribute('aria-label', label); b.onclick = () => adapter.action(action); if (action === 'toggle') toggle = b; controls.append(b); }
const update = () => { const state = adapter.state(); title.textContent = state.title || 'Choose a song before entering Car mode'; root.TransportIcons.set(toggle, state.paused ? 'play' : 'pause'); toggle.insertAdjacentHTML('beforeend','<span>' + (state.paused ? 'Play' : 'Pause') + '</span>'); }; update();
overlay.append(exit, title, controls); doc.body.append(overlay); timer = setInterval(update, 500); exit.focus();
overlay.onkeydown = e => { if (e.key === 'Escape') { e.preventDefault(); close(); } else if (e.key === 'Tab') { const buttons = [...overlay.querySelectorAll('button')], first = buttons[0], last = buttons.at(-1); if (e.shiftKey && doc.activeElement === first) { e.preventDefault(); last.focus(); } else if (!e.shiftKey && doc.activeElement === last) { e.preventDefault(); first.focus(); } } e.stopPropagation(); };
}
function configure(options) {
adapter = options; const doc = root.document, Recognition = root.SpeechRecognition || root.webkitSpeechRecognition;
if (Recognition) {
const b = doc.getElementById('voiceSearchBtn') || doc.createElement('button'); b.id='voiceSearchBtn'; b.type = 'button'; b.className = 'icon-btn voice-search'; b.title = 'Voice search'; b.setAttribute('aria-label', 'Voice search'); b.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10v2a7 7 0 0 0 14 0v-2M12 19v3m-4 0h8"/></svg>'; if(!b.isConnected)adapter.input.after(b);
let recognition, listening = false;
b.onclick = () => { if (listening) { recognition.abort(); return; } recognition = new Recognition(); recognition.lang = doc.documentElement.lang || root.navigator.language || 'en-US'; recognition.continuous = false; recognition.interimResults = false; recognition.onstart = () => { listening = true; b.setAttribute('aria-pressed', 'true'); b.title = 'Listening… tap to cancel'; }; recognition.onend = () => { listening = false; b.setAttribute('aria-pressed', 'false'); b.title = 'Voice search'; }; recognition.onerror = e => adapter.toast(`Voice search: ${e.error === 'not-allowed' ? 'microphone permission was denied' : e.error}`); recognition.onresult = e => { const query = transcript(e); if (query) { adapter.input.value = query; adapter.search(); } }; try { recognition.start(); } catch (error) { adapter.toast(error.message); } };
}
const car = doc.getElementById('carModeBtn') || doc.createElement('button'); car.id='carModeBtn'; car.type = 'button'; car.className = 'icon-btn'; car.title = 'Car mode'; car.setAttribute('aria-label', 'Car mode'); car.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><path d="m5 8 2-5h10l2 5M3 8h18v10H3zM5 18v3m14-3v3M6 12h2m8 0h2"/></svg>'; if(!car.isConnected)doc.getElementById('searchForm').after(car); car.onclick = open;
root.SettingsSections.register({ id: 'voice-car', title: 'Voice & Car mode', cluster: 'Listening', summary: () => Recognition ? 'Voice search available · Car mode' : 'Car mode · voice unavailable', render(container) { const p = doc.createElement('p'); p.textContent = Recognition ? 'Use the microphone beside Search to speak a query. Recognition availability and processing depend on your browser.' : 'Voice search is unavailable in this browser.'; const b = doc.createElement('button'); b.type = 'button'; b.className = 'settings-back'; b.textContent = 'Enter Car mode'; b.onclick = open; container.append(p, b); } });
}
const api = { transcript, configure, open, close }; if (typeof module !== 'undefined') module.exports = api; else root.CarMode = api;
})(typeof window !== 'undefined' ? window : globalThis);

27
frontend/car-mode.test.js Normal file
View File

@@ -0,0 +1,27 @@
const { test } = require('node:test'), assert = require('node:assert/strict'); const { transcript } = require('./car-mode');
test('voice search submits only final results from the result index', () => { const interim = [{transcript:'wrong'}]; interim.isFinal = false; const final = [{transcript:'Amazing Grace'}]; final.isFinal = true; assert.equal(transcript({results:[interim, final]}), 'Amazing Grace'); assert.equal(transcript({resultIndex:2,results:[final,final]}), ''); assert.equal(transcript({}), ''); });
test('lazy Car mode keeps four independent transport buttons and the voice entry in place', () => {
const vm=require('node:vm'),fs=require('node:fs');
class Element {
constructor(tag){this.tag=tag;this.children=[];this.inert=false;}
append(...nodes){for(const node of nodes){node.remove();node.parent=this;this.children.push(node);}}
remove(){if(this.parent){this.parent.children=this.parent.children.filter(n=>n!==this);this.parent=null;}}
after(node){this.parent.append(node);}
setAttribute(name,value){this[name]=value;}
focus(){}
insertAdjacentHTML(position,html){this.innerHTML+=html;}
get isConnected(){return !!this.parent;}
}
const body=new Element('body'),input=new Element('input'),form=new Element('form'),voice=new Element('button');form.id='searchForm';voice.id='voiceSearchBtn';body.append(form,input,voice);
const all=node=>[node,...node.children.flatMap(all)],doc={body,documentElement:{lang:'en'},createElement:tag=>new Element(tag),getElementById:id=>all(body).find(n=>n.id===id)};
let section;const actions=[],root={document:doc,TransportIcons:require('./download-actions').transport,navigator:{},SpeechRecognition:function(){},SettingsSections:{register:s=>section=s}};
vm.runInNewContext(fs.readFileSync(__dirname+'/car-mode.js','utf8'),{window:root,setInterval:()=>1,clearInterval:()=>{}});
root.CarMode.configure({input,action:action=>actions.push(action),state:()=>({paused:true,title:'Song'})});
root.CarMode.open();const overlay=body.children.find(n=>n.className==='car-mode'),controls=overlay.children.find(n=>n.className==='car-controls');
assert.equal(controls.children.length,4);assert.equal(new Set(controls.children).size,4);assert.equal(voice.parent,body);
controls.children.forEach(b=>b.onclick());assert.deepEqual(actions,['prev','toggle','back','next']);
root.CarMode.close();assert.equal(voice.parent,body);assert.equal(body.inert,false);
const panel=new Element('section');body.append(panel);section.render(panel);
assert.equal(voice.parent,body,'settings must not steal the voice entry');assert.equal(panel.children.at(-1).textContent,'Enter Car mode');
});

76
frontend/device-db.js Normal file
View File

@@ -0,0 +1,76 @@
/* ============================================================================
* device-db.js — this device's own file registry (IndexedDB "ytp-device")
*
* One record per saved video, next to the bytes in OPFS:
* { videoId, cid, size, savedAt, lastCheckedAt, state }
* cid SHA-256 of the stored file (P2P content id) or null
* state 'verified' hash computed on save and equal to the server's
* 'unverified' hash computed, but the server sent none to compare
* 'unhashed' saved before hashing existed / main-thread fallback
* The P2P client (p2p-client.js) reads this to report holdings; OPFS stays the
* source of truth for what is playable (a record without a file is ignored).
* Every call resolves (null / [] on failure) — private windows can block IDB.
* See docs/p2p-architecture.md.
* ========================================================================== */
(function () {
'use strict';
const DB_NAME = 'ytp-device';
const VERSION = 1;
let _open = null;
function open() {
if (!_open) {
_open = new Promise((resolve, reject) => {
const r = indexedDB.open(DB_NAME, VERSION);
r.onupgradeneeded = () => {
const d = r.result;
if (!d.objectStoreNames.contains('files')) {
const s = d.createObjectStore('files', { keyPath: 'videoId' });
s.createIndex('cid', 'cid', { unique: false });
}
};
r.onsuccess = () => resolve(r.result);
r.onerror = () => reject(r.error);
r.onblocked = () => reject(new Error('device-db blocked'));
});
_open.catch(() => { _open = null; });
}
return _open;
}
const done = (req) => new Promise((resolve, reject) => {
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
async function store(mode) {
const d = await open();
return d.transaction('files', mode).objectStore('files');
}
async function safe(fn, fallback) {
try { return await fn(); } catch { return fallback; }
}
window.DeviceDB = {
isSupported: () => typeof indexedDB !== 'undefined',
putFile: (rec) => safe(async () => {
if (!rec || !rec.videoId) return null;
await done((await store('readwrite')).put({
videoId: String(rec.videoId),
cid: rec.cid || null,
size: Number(rec.size) || 0,
savedAt: Number(rec.savedAt) || Date.now(),
lastCheckedAt: Number(rec.lastCheckedAt) || Date.now(),
state: rec.state || 'unhashed',
}));
return true;
}, null),
getFile: (videoId) => safe(async () => (await done((await store('readonly')).get(String(videoId)))) || null, null),
getByCid: (cid) => safe(async () => (await done((await store('readonly')).index('cid').get(String(cid)))) || null, null),
listFiles: () => safe(async () => (await done((await store('readonly')).getAll())) || [], []),
deleteFile: (videoId) => safe(async () => { await done((await store('readwrite')).delete(String(videoId))); return true; }, null),
clear: () => safe(async () => { await done((await store('readwrite')).clear()); return true; }, null),
};
}());

View File

@@ -0,0 +1,6 @@
.direct-transfer-dialog{max-width:min(420px,calc(100vw - 32px));padding:24px;border:1px solid var(--border);border-radius:var(--radius,16px);background:var(--surface,#202026);color:var(--text,#fff)}
.direct-transfer-dialog::backdrop{background:rgba(0,0,0,.65)}
.direct-transfer-dialog p{line-height:1.6;color:var(--text-2);overflow-wrap:anywhere}
.direct-transfer-dialog button,#settings-section-direct-transfer button{min-height:44px;padding:10px 16px;margin:4px;border:1px solid var(--border);border-radius:10px;background:var(--surface-2,#303039);color:var(--text,#fff)}
.direct-transfer-dialog button:focus-visible,#settings-section-direct-transfer button:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
#settings-section-direct-transfer label{display:flex;align-items:center;gap:12px;min-height:44px}

168
frontend/direct-media.js Normal file
View File

@@ -0,0 +1,168 @@
/* Paired-room transport; signalling only goes to the server. */
(function (root) {
'use strict';
const waiting = new Map();
let profilePeers = [];
const rooms = new Map(), transfers = new Map(), pending = new Map();
let hooks = { settings: () => ({}), persist() {}, current: () => null, saved() {}, notify() {}, fallback() {} };
const enabled = () => hooks.settings().directTransfer !== false && !!root.RTCPeerConnection;
function attach(key, room) { rooms.set(key, room); }
function send(key, m) { const r = rooms.get(key); if (!r) throw Error('Paired device disconnected'); r.send(m); }
function signal(key, token, data) { send(key, { type: 'direct', action: 'signal', token, data }); }
async function offer(key, to, meta) {
if (!enabled()) throw Error('Direct device transfer is unavailable or turned off');
if (!meta?.id) throw Error('Choose a saved song first');
if (pending.has(`${key}:${to}:${meta.id}`) || [...transfers.values()].some(s => s.key === key && s.peer === to && s.claim.id === meta.id)) return;
const file = await root.OPFS.getFileObject(meta.id);
if (!file) throw Error('Save this song on this device before sending it');
const hash = root.Sha256.create();
for (let at = 0; at < file.size; at += 1024 * 1024) hash.update(new Uint8Array(await file.slice(at, at + 1024 * 1024).arrayBuffer()));
const claim = root.DirectProtocol.file({ ...meta, cid: hash.hex(), size: file.size, extension: file.name.split('.').pop().toLowerCase(), streamMime: await root.DirectStream?.inspect(file), title: meta.title || meta.id });
if (!claim) throw Error('Unsupported file metadata');
const pendingKey = `${key}:${to}:${claim.id}`;
const item = { file, claim }; pending.set(pendingKey, item);
setTimeout(() => { if (pending.get(pendingKey) === item) pending.delete(pendingKey); }, 60000);
send(key, { type: 'direct', action: 'invite', to, file: claim });
hooks.notify('Waiting for the receiving device to accept');
}
function finish(s, error) {
if (s.done) return; s.done = true; clearTimeout(s.timer); clearTimeout(s.idle);
s.pc?.close(); transfers.delete(s.token);
if (error) s.preview?.close(); else s.preview?.end();
if (s.worker) { s.worker.postMessage({ op: 'abort' }); setTimeout(() => s.worker.terminate(), 1000); }
if (error) { waiting.get(s.claim.id)?.resolve(false); waiting.delete(s.claim.id); hooks.notify(`${error}. Partial copy kept for resume.`); hooks.fallback(s.claim, () => offer(s.key, s.peer, s.claim).catch(e => hooks.notify(e.message))); }
}
function connection(s, receiver) {
clearTimeout(s.timer);
const pc = s.pc = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] });
s.ice = s.ice || [];
pc.onicecandidate = e => { if (e.candidate) signal(s.key, s.token, { kind: 'ice', candidate: e.candidate.toJSON() }); };
s.timer = setTimeout(() => finish(s, 'Direct connection failed after 10 seconds'), 10000);
pc.onconnectionstatechange = () => { if (['failed', 'closed'].includes(pc.connectionState)) finish(s, 'Direct connection closed'); };
const bump = () => { clearTimeout(s.idle); s.idle = setTimeout(() => finish(s, 'Direct transfer stalled'), 30000); };
const channel = dc => {
s.dc = dc; dc.binaryType = 'arraybuffer'; dc.bufferedAmountLowThreshold = 1024 * 1024;
dc.onopen = () => { clearTimeout(s.timer); bump(); if (receiver && s.offset != null) dc.send(JSON.stringify({ t: 'get', offset: s.offset })); };
dc.onclose = () => { if (!s.done && !s.verifying) setTimeout(() => { if (!s.done && !s.verifying) finish(s, 'Direct channel closed'); }, 3000); };
dc.onmessage = async e => {
bump();
try {
if (receiver) {
if (typeof e.data === 'string') { const m = JSON.parse(e.data); if (m.t === 'end') { s.verifying = true; clearTimeout(s.idle); s.worker.postMessage({ op: 'finish' }); } else throw Error('Unexpected file control'); }
else { s.preview?.push(e.data); s.worker.postMessage({ op: 'chunk', buf: e.data }, [e.data]); }
} else {
if (typeof e.data !== 'string' || s.started) throw Error('Unexpected file request');
const m = JSON.parse(e.data); if (m.t !== 'get') throw Error('Unexpected file request');
let pos = root.DirectProtocol.offset(m.offset, s.file.size); s.started = true;
while (pos < s.file.size && !s.done) {
if (dc.bufferedAmount > 4 * 1024 * 1024) await new Promise((resolve, reject) => {
const timeout = setTimeout(() => { cleanup(); reject(Error('Peer stopped receiving')); }, 10000);
const cleanup = () => { clearTimeout(timeout); dc.removeEventListener('bufferedamountlow', low); dc.removeEventListener('close', closed); };
const low = () => { cleanup(); resolve(); }, closed = () => { cleanup(); reject(Error('Peer disconnected')); };
dc.addEventListener('bufferedamountlow', low); dc.addEventListener('close', closed);
});
const range = root.DirectProtocol.nextChunk(pos, s.file.size);
dc.send(await s.file.slice(range.start, range.end).arrayBuffer()); pos = range.end; bump();
}
if (!s.done) { dc.send(JSON.stringify({ t: 'end' })); clearTimeout(s.idle); s.idle = setTimeout(() => finish(s, 'Receiver did not finish verification'), 30 * 60000); }
}
} catch (err) { finish(s, err.message); }
};
};
if (receiver) channel(pc.createDataChannel('file', { ordered: true })); else pc.ondatachannel = e => channel(e.channel);
return pc;
}
async function accept(key, m) {
const s = { key, token: m.token, claim: m.file, peer: m.from, receiver: true }; transfers.set(m.token, s);
s.preview = m.file.streamMime ? root.DirectStream?.create(m.file.streamMime, m.file.title) : null;
const wait = waiting.get(m.file.id); if (wait) clearTimeout(wait.timer);
send(key, { type: 'direct', action: 'accept', token: m.token });
s.worker = window.Lazy ? window.Lazy.worker('/direct-recv-worker.js') : new Worker('/direct-recv-worker.js');
s.worker.onmessage = async e => {
const result = e.data;
if (result.op === 'opened') {
s.offset = result.offset;
connection(s, true);
const offer = await s.pc.createOffer(); await s.pc.setLocalDescription(offer); signal(key, m.token, { kind: 'offer', sdp: offer.sdp });
} else if (result.op === 'done') {
send(key, { type: 'direct', action: 'complete', token: m.token });
await hooks.saved(result.file); waiting.get(result.file.id)?.resolve(true); waiting.delete(result.file.id); publish(); hooks.notify(`Saved ${result.file.title} directly from the other device`); finish(s);
} else if (result.op === 'error') finish(s, result.error);
};
s.worker.postMessage({ op: 'open', file: m.file });
}
async function handle(key, m) {
if (m.type !== 'direct') return;
if (m.action === 'request') { if (enabled() && hooks.settings().p2pShare !== false) offer(key, m.from, hooks.meta?.(m.id) || { id: m.id, title: m.id }).catch(e => hooks.notify(e.message)); return; }
try {
if (m.action === 'invite') {
if (!enabled() || !root.DirectProtocol.file(m.file)) return send(key, { type: 'direct', action: 'decline', token: m.token });
confirmReceive(key, m); return;
}
if (m.action === 'invited') {
const p = pending.get(`${key}:${m.to}:${m.file.id}`); if (!p) return;
pending.delete(`${key}:${m.to}:${m.file.id}`);
const s = { key, token: m.token, peer: m.to, claim: p.claim, file: p.file }; transfers.set(m.token, s); s.timer = setTimeout(() => finish(s), 60000); return;
}
const s = transfers.get(m.token); if (!s || s.key !== key || m.from !== s.peer) return;
if (m.action === 'accept') { s.accepted = true; clearTimeout(s.timer); s.timer = setTimeout(() => finish(s, 'Receiver stopped preparing the file'), 30 * 60000); }
else if (m.action === 'decline' || m.action === 'complete') finish(s);
else if (m.action === 'signal') {
const d = m.data;
if (!s.pc && !s.receiver && s.accepted) { if (d.kind === 'ice') { (s.ice ||= []).push(d.candidate); return; } if (d.kind === 'offer') connection(s, false); }
if (!s.pc) return;
if (d.kind === 'ice') { if (s.pc.remoteDescription) await s.pc.addIceCandidate(d.candidate); else s.ice.push(d.candidate); }
else {
await s.pc.setRemoteDescription({ type: d.kind, sdp: d.sdp });
for (const c of s.ice.splice(0)) await s.pc.addIceCandidate(c);
if (d.kind === 'offer') { const a = await s.pc.createAnswer(); await s.pc.setLocalDescription(a); signal(key, m.token, { kind: 'answer', sdp: a.sdp }); }
}
}
} catch (e) { const s = transfers.get(m.token); if (s) finish(s, e.message); else hooks.notify(e.message); }
}
function confirmReceive(key, m) {
const dialog = document.createElement('dialog'); dialog.className = 'direct-transfer-dialog';
const heading = document.createElement('h2'); heading.textContent = 'Save from your paired device?';
const text = document.createElement('p'); text.textContent = `${m.file.title} · ${(m.file.size / 1024 ** 2).toFixed(1)} MB. Media travels directly between devices. Keep both screens open. Playback starts after the full copy is verified.`;
const yes = document.createElement('button'); yes.textContent = 'Accept & save';
const no = document.createElement('button'); no.textContent = 'Decline';
const decline = () => { waiting.get(m.file.id)?.resolve(false); waiting.delete(m.file.id); send(key, { type: 'direct', action: 'decline', token: m.token }); dialog.remove(); };
yes.onclick = () => { dialog.remove(); accept(key, m).catch(e => hooks.notify(e.message)); }; no.onclick = decline; dialog.oncancel = decline;
dialog.append(heading, text, yes, no); document.body.append(dialog); dialog.showModal();
}
async function publish() {
if (!root.P2PClient?.isConnected()) return;
const files = await root.OPFS.listVideos({ strict: true });
root.P2PClient.send({ type: 'direct-inventory', ids: enabled() && hooks.settings().p2pShare !== false ? files.map(f => f.id) : [] });
}
function source(id) { if (!enabled()) return null; for (const [key, room] of rooms) { const peer = room.peers().find(p => p.files?.includes(id)); if (peer) return { key, peer }; } return null; }
function hasSource(id) { return !!source(id); }
function obtain(id) {
if (!hasSource(id)) return Promise.resolve(null);
if (waiting.has(id)) return waiting.get(id).promise;
const { key, peer } = source(id);
let resolve; const promise = new Promise(r => { resolve = r; });
const wait = { promise, resolve }; waiting.set(id, wait);
send(key, { type: 'direct', action: 'request', to: peer.id, id });
wait.timer = setTimeout(() => { if (waiting.get(id)?.promise === promise) { waiting.delete(id); resolve(false); hooks.notify('The other device did not accept or is unavailable'); hooks.fallback(hooks.meta?.(id) || { id, title: id }); } }, 60000);
return promise;
}
function configure(h) {
hooks = { ...hooks, ...h };
if (root.P2PClient) {
root.P2PClient.onMessage('hello', () => { attach('profile', { send: root.P2PClient.send, peers: () => profilePeers }); publish(); });
root.P2PClient.onMessage('direct-peers', m => { profilePeers = m.peers || []; });
root.P2PClient.onMessage('direct', m => handle('profile', m));
}
root.SettingsSections.register({ id: 'direct-transfer', title: 'Direct device transfer', cluster: 'Library & storage', summary: () => enabled() ? 'On · paired devices only' : 'Off or unsupported', icon: '<path d="M4 6h6v12H4zM14 6h6v12h-6M10 10h4m-4 4h4"/>', render(container) {
const label = document.createElement('label'); const toggle = document.createElement('input'); toggle.type = 'checkbox'; toggle.checked = hooks.settings().directTransfer !== false;
toggle.onchange = () => { hooks.settings().directTransfer = toggle.checked; hooks.persist(); publish(); }; label.append(toggle, ' Direct device transfer (P2P)');
const help = document.createElement('p'); help.textContent = 'Pair through Remote or join a Watch Party, then send your currently playing saved song. The receiver confirms before saving. Keep both devices open. No TURN relay is used.';
container.append(label, help);
for (const [key, r] of rooms) for (const peer of r.peers()) {
const b = document.createElement('button'); b.textContent = `Send saved song to ${peer.name}`; b.style.minHeight = '44px'; b.onclick = () => offer(key, peer.id, hooks.current()).catch(e => hooks.notify(e.message)); container.append(b);
}
} });
}
root.DirectMedia = { configure, attach, handle, offer, enabled, obtain, hasSource, publish };
}(globalThis));

View File

@@ -0,0 +1,41 @@
/* Shared bounded control protocol: media bytes belong exclusively on DataChannel. */
(function (root) {
'use strict';
const CHUNK = 65536;
const text = (v, n) => typeof v === 'string' && v.length <= n && !/[\u0000-\u001f]/.test(v);
const id = (v) => text(v, 128) && /^[A-Za-z0-9_-]+$/.test(v);
function file(v) {
if (!v || !id(v.id) || !/^[a-f0-9]{64}$/.test(v.cid) || !Number.isSafeInteger(v.size) || v.size <= 0 || v.size > 4 * 1024 ** 3) return null;
if (!text(v.title, 300) || !text(v.channel || '', 200)) return null;
const streamMime = typeof v.streamMime === 'string' && /^video\/mp4; codecs="avc1\.[a-f0-9]{6}(, mp4a\.40\.2)?"$/.test(v.streamMime) ? v.streamMime : '';
return { streamMime, extension: /^(mp4|m4a|webm|ogg|opus|mkv|mp3|wav|aac)$/.test(v.extension) ? v.extension : 'mp4', id: v.id, cid: v.cid, size: v.size, title: v.title, channel: v.channel || '', duration: Number.isFinite(v.duration) && v.duration >= 0 ? v.duration : 0 };
}
function parse(value) {
if (typeof value === 'string') { if (value.length > 65536) return null; try { value = JSON.parse(value); } catch { return null; } }
if (!value || typeof value !== 'object' || Array.isArray(value) || value.type !== 'direct') return null;
const m = { type: 'direct', action: value.action };
if (value.action === 'request') return id(value.to) && id(value.id) ? { ...m, to: value.to, id: value.id } : null;
if (value.action === 'invite') {
const f = file(value.file); if (!id(value.to) || !f) return null;
return { ...m, to: value.to, file: f };
}
if (!['accept', 'decline', 'signal', 'complete'].includes(value.action) || !id(value.token)) return null;
m.token = value.token;
if (value.action === 'signal') {
const d = value.data;
if (!d || typeof d !== 'object') return null;
if (['offer', 'answer'].includes(d.kind) && typeof d.sdp === 'string' && d.sdp.length <= 60000) m.data = { kind: d.kind, sdp: d.sdp };
else if (d.kind === 'ice' && d.candidate && text(d.candidate.candidate, 2048)) {
const c = d.candidate;
if (!(c.sdpMid == null || text(c.sdpMid, 64)) || !(c.sdpMLineIndex == null || Number.isInteger(c.sdpMLineIndex) && c.sdpMLineIndex >= 0 && c.sdpMLineIndex < 100)) return null;
m.data = { kind: 'ice', candidate: { candidate: c.candidate, sdpMid: c.sdpMid ?? null, sdpMLineIndex: c.sdpMLineIndex ?? null } };
} else return null;
}
return m;
}
function offset(v, size) { if (!Number.isSafeInteger(v) || v < 0 || v > size) throw new Error('Invalid resume offset'); return v; }
function nextChunk(pos, size) { offset(pos, size); return { start: pos, end: Math.min(size, pos + CHUNK) }; }
const api = { CHUNK, file, parse, offset, nextChunk };
if (typeof module !== 'undefined') module.exports = api;
root.DirectProtocol = api;
}(typeof globalThis !== 'undefined' ? globalThis : this));

View File

@@ -0,0 +1,18 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const p = require('./direct-protocol.js');
test('direct protocol strips unexpected payload and validates file claims', () => {
const m = p.parse({ type: 'direct', action: 'invite', to: 'peer', file: { id: 'video', title: 'Song', cid: 'a'.repeat(64), size: 10, bytes: 'secret' }, bytes: 'not relayed' });
assert.equal(m.file.size, 10); assert.equal(m.bytes, undefined); assert.equal(m.file.bytes, undefined);
assert.equal(p.parse({ ...m, file: { ...m.file, size: Infinity } }), null);
assert.equal(p.parse(new Uint8Array(4)), null);
});
test('chunks retain exact resume offset and never exceed file end', () => {
assert.deepEqual(p.nextChunk(17, 100000), { start: 17, end: 65553 });
assert.deepEqual(p.nextChunk(99999, 100000), { start: 99999, end: 100000 });
for (const n of [-1, 100001, 0.5, NaN]) assert.throws(() => p.offset(n, 100000));
});
test('signalling only admits bounded SDP or ICE, never byte frames', () => {
assert.equal(p.parse({ type: 'direct', action: 'signal', token: 'abc', data: { kind: 'bytes', data: [1, 2] } }), null);
assert.equal(p.parse({ type: 'direct', action: 'signal', token: 'abc', data: { kind: 'offer', sdp: 'x'.repeat(60001) } }), null);
});

View File

@@ -0,0 +1,40 @@
'use strict';
let dir, handle, access, hash, pos = 0, claim, name;
let chain = Promise.resolve();
self.onmessage = e => { chain = chain.then(() => run(e.data)); };
async function close() { if (access) { access.flush(); access.close(); access = null; } }
async function run(m) {
try {
if (!self.Sha256) { self.__ASSET_URLS__=m.assetUrls || {}; importScripts(self.__ASSET_URLS__.sha256 || '/sha256.js'); }
if (m.op === 'open') {
claim = m.file;
if (!/^[A-Za-z0-9_-]{1,128}$/.test(claim.id) || !/^[a-f0-9]{64}$/.test(claim.cid)) throw Error('Invalid file identity');
dir = await (await navigator.storage.getDirectory()).getDirectoryHandle('videos', { create: true });
name = `${claim.id}.${claim.cid}.direct.part`;
handle = await dir.getFileHandle(name, { create: true });
access = await handle.createSyncAccessHandle();
pos = access.getSize(); if (pos > claim.size) { access.truncate(0); pos = 0; }
hash = self.Sha256.create();
for (let at = 0; at < pos; at += 1024 * 1024) { const b = new Uint8Array(Math.min(1024 * 1024, pos - at)); access.read(b, { at }); hash.update(b); }
self.postMessage({ op: 'opened', offset: pos });
} else if (m.op === 'chunk') {
const b = new Uint8Array(m.buf);
if (!access || b.length > 65536 || pos + b.length > claim.size) throw Error('Invalid file chunk');
if (access.write(b, { at: pos }) !== b.length) throw Error('Incomplete OPFS write');
hash.update(b); pos += b.length; access.flush();
self.postMessage({ op: 'progress', received: pos });
} else if (m.op === 'abort') { await close(); self.postMessage({ op: 'closed' }); }
else if (m.op === 'finish') {
await close();
if (pos !== claim.size || hash.hex() !== claim.cid) { await dir.removeEntry(name); throw Error('File verification failed; retry starts from zero'); }
const extension = /^(mp4|m4a|webm|ogg|opus|mkv|mp3|wav|aac)$/.test(claim.extension) ? claim.extension : 'mp4';
const final = `${claim.id}.${extension}`;
// Copy only after verification; existing saved playback remains intact until then.
const out = await (await dir.getFileHandle(final, { create: true })).createSyncAccessHandle();
try { const f = await handle.getFile(); for (let at = 0; at < f.size; at += 1024 * 1024) out.write(new Uint8Array(await f.slice(at, at + 1024 * 1024).arrayBuffer()), { at }); out.truncate(f.size); out.flush(); } finally { out.close(); }
await dir.removeEntry(name);
for await (const [old, entry] of dir.entries()) { if (entry.kind === 'file' && old !== final && old.startsWith(claim.id + '.') && /\.(mp4|m4a|webm|ogg|opus|mkv|mp3|wav|aac)$/.test(old)) await dir.removeEntry(old); }
self.postMessage({ op: 'done', file: claim });
}
} catch (e) { await close(); self.postMessage({ op: 'error', error: e.message }); }
}

44
frontend/direct-stream.js Normal file
View File

@@ -0,0 +1,44 @@
/* Progressive preview is only safe for fragmented MP4, never ordinary MP4 chunks. */
(function (root) {
'use strict';
function inspectBytes(bytes) {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const str = (at, n) => String.fromCharCode(...bytes.subarray(at, at + n));
let at = 0, moov = null;
while (at + 8 <= bytes.length) {
const size = view.getUint32(at); if (size < 8 || at + size > bytes.length) break;
if (str(at + 4, 4) === 'moov') { moov = bytes.subarray(at + 8, at + size); break; }
at += size;
}
if (!moov) return null;
const tagAt = (tag) => { for (let i = 4; i + 4 <= moov.length; i++) if (String.fromCharCode(...moov.subarray(i, i + 4)) === tag) return i; return -1; };
if (tagAt('mvex') < 0) return null;
const avc = tagAt('avcC'), audio = tagAt('mp4a');
if (avc < 0 || avc + 8 > moov.length || moov[avc + 4] !== 1) return null;
const codec = Array.from(moov.subarray(avc + 5, avc + 8), b => b.toString(16).padStart(2, '0')).join('');
return `video/mp4; codecs="avc1.${codec}${audio >= 0 ? ', mp4a.40.2' : ''}"`;
}
async function inspect(file) { return inspectBytes(new Uint8Array(await file.slice(0, 1024 * 1024).arrayBuffer())); }
function create(mime, title) {
if (!root.MediaSource?.isTypeSupported(mime)) return null;
const media = new MediaSource(), url = URL.createObjectURL(media), queue = [];
let buffer, queued = 0, ended = false, stopped = false;
const dialog = document.createElement('dialog'); dialog.className = 'direct-transfer-dialog';
const heading = document.createElement('h2'); heading.textContent = title;
const note = document.createElement('p'); note.textContent = 'Direct preview · the full copy is still being saved and verified. Tap Play when ready.';
const video = document.createElement('video'); video.controls = true; video.playsInline = true; video.src = url; video.style.width = '100%';
const close = document.createElement('button'); close.textContent = 'Close preview';
const dispose = () => { stopped = true; queue.length = 0; video.pause(); video.removeAttribute('src'); video.load(); URL.revokeObjectURL(url); dialog.remove(); };
close.onclick = dispose; dialog.oncancel = e => { e.preventDefault(); dispose(); }; dialog.append(heading, note, video, close); document.body.append(dialog); dialog.showModal();
function flush() {
if (stopped || !buffer || buffer.updating) return;
if (queue.length) { const b = queue.shift(); queued -= b.byteLength; try { buffer.appendBuffer(b); } catch { dispose(); } }
else if (ended && media.readyState === 'open') { try { media.endOfStream(); } catch {} }
}
media.addEventListener('sourceopen', () => { try { buffer = media.addSourceBuffer(mime); buffer.addEventListener('updateend', flush); buffer.addEventListener('error', dispose); flush(); } catch { dispose(); } }, { once: true });
return { push(bytes) { if (stopped) return; queued += bytes.byteLength; if (queued > 8 * 1024 * 1024) { dispose(); return; } queue.push(bytes.slice(0)); flush(); }, end() { ended = true; flush(); }, close: dispose };
}
const api = { inspectBytes, inspect, create };
if (typeof module !== 'undefined') module.exports = api;
root.DirectStream = api;
}(globalThis));

View File

@@ -0,0 +1,12 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { inspectBytes } = require('./direct-stream.js');
function box(type, payload = Buffer.alloc(0)) { const b = Buffer.alloc(8 + payload.length); b.writeUInt32BE(b.length); b.write(type, 4); payload.copy(b, 8); return b; }
test('progressive playback only accepts a complete fragmented MP4 initialization', () => {
const codec = box('avcC', Buffer.from([1, 0x64, 0, 0x1f]));
const fragmented = Buffer.concat([box('ftyp'), box('moov', Buffer.concat([box('mvex'), codec, box('mp4a')]))]);
assert.equal(inspectBytes(fragmented), 'video/mp4; codecs="avc1.64001f, mp4a.40.2"');
assert.equal(inspectBytes(Buffer.concat([box('ftyp'), box('moov', codec)])), null);
assert.equal(inspectBytes(fragmented.subarray(0, fragmented.length - 1)), null);
assert.equal(inspectBytes(Buffer.alloc(0)), null);
});

View File

@@ -0,0 +1,38 @@
/* Shared quiet controls; use each layout's existing surface and focus tokens. */
:is(.dl-row,.download-job) .download-action { display:inline-flex; align-items:center; justify-content:center; flex:none; gap:8px; height:auto; min-height:44px; min-width:44px; padding:8px 14px; border:1px solid var(--line); border-radius:var(--radius-sm); background:var(--bg-2); color:var(--text); font:600 13px var(--ui); line-height:1.4; cursor:pointer; white-space:nowrap; }
:is(.dl-row,.download-job) .download-action:hover { background:var(--bg-3); border-color:var(--accent); }
:is(.dl-row,.download-job) .download-action.danger { color:var(--accent); }
:is(.dl-row,.download-job) .download-action:focus-visible { outline:2px solid var(--accent); outline-offset:3px; }
:is(.dl-row,.download-job) .download-action:disabled { opacity:.5; cursor:not-allowed; }
.download-action-icon { width:20px; height:20px; flex:none; fill:none; stroke:currentColor; stroke-width:1.9; stroke-linecap:round; stroke-linejoin:round; pointer-events:none; }
html[data-layout="glass-stage"] :is(.dl-row,.download-job) .download-action { border-radius:18px; border-color:var(--glass-line); background:var(--tile); color:var(--text-2); box-shadow:none; }
html[data-layout="glass-stage"] :is(.dl-row,.download-job) .download-action:hover { border-color:var(--glass-line); background:var(--tile-hi); color:var(--text); }
html[data-layout="glass-stage"] :is(.dl-row,.download-job) .download-action.danger { color:var(--accent-bright); }
html[data-layout="glass-stage"] :is(.dl-row,.download-job) .download-action:focus-visible { outline-color:var(--accent-bright); }
/* Transport drawings and touch targets survive layout/state changes. */
.transport-icon { display:inline-block; flex:none; width:24px; height:24px; vertical-align:middle; fill:none; stroke:currentColor; stroke-width:1.8; stroke-linecap:round; stroke-linejoin:round; pointer-events:none; }
.transport-shape { display:none; }
.transport-shape-classic { display:inline; }
html:is([data-layout="f7-swipe"],[data-layout="glass-stage"],[data-layout="bento-hub"]) .transport-shape-classic { display:none; }
html[data-layout="f7-swipe"] .transport-shape-f7-swipe,
html[data-layout="glass-stage"] .transport-shape-glass-stage,
html[data-layout="bento-hub"] .transport-shape-bento-hub { display:inline; }
html[data-layout="f7-swipe"] .transport-shape-f7-swipe { fill:currentColor; stroke-width:.7; }
html[data-layout="f7-swipe"] .transport-icon:is([data-transport-icon="play"],[data-transport-icon="pause"],[data-transport-icon="previous"],[data-transport-icon="next"],[data-transport-icon="forward"]),
html[data-layout="f7-swipe"] #controls .transport-icon:is([data-transport-icon="play"],[data-transport-icon="pause"],[data-transport-icon="previous"],[data-transport-icon="next"],[data-transport-icon="forward"]) { fill:currentColor; stroke-width:.7; }
html[data-layout="f7-swipe"] :is([data-transport-icon="back10"],[data-transport-icon="forward10"],[data-transport-icon="back15"]) .transport-shape { fill:none; stroke-width:2; }
html[data-layout="glass-stage"] .transport-icon,
html[data-layout="glass-stage"] #controls .transport-icon { stroke-width:1.5; }
html[data-layout="bento-hub"] .transport-icon { stroke-width:2; stroke-linejoin:round; }
button:has(> .transport-icon), a.np-btn:has(> .transport-icon) { min-width:44px; min-height:44px; }
button:has(> .transport-icon) { align-items:center; justify-content:center; }
html[data-layout="f7-swipe"] :is(#playBtn,#stgPlay,.service-btn-play,.rv-play) { border-radius:50%; }
html[data-layout="f7-swipe"] #playBtn { width:64px; height:64px; }
html[data-layout="glass-stage"] :is(#playBtn,.mini-btn,.rv-tbtn):has(> .transport-icon) { background:var(--tile,rgba(255,255,255,.08)); border:1px solid var(--line); backdrop-filter:blur(12px); }
html[data-layout="bento-hub"] :is(#playBtn,.mini-btn,.service-btn,.rv-tbtn):has(> .transport-icon) { border-radius:16px; }
.car-controls .transport-icon { width:36px; height:36px; margin-right:12px; }
.gh-seek .transport-icon, .empty-icon .transport-icon { width:48px; height:48px; }
.ph-logo .transport-icon { width:60%; height:60%; }
.home-pl-play:has(> .transport-icon) { min-width:44px; min-height:44px; }

View File

@@ -0,0 +1,101 @@
/* One action control for the Downloads page and Settings download manager. */
(function(root) {
'use strict';
// One SVG definition per media concept; every instance inherits its control colour.
const mediaPaths = {
download: '<path d="M12 3v12m-5-5 5 5 5-5M4 17v4h16v-4"/>',
offline: '<circle cx="12" cy="12" r="9"/><path d="m7.5 12 3 3 6-6"/>',
progress: '<path d="M12 3a9 9 0 1 1-9 9"/>'
};
const variants = {
'classic': mediaPaths,
'f7-swipe': {
download: '<path d="M12 3v12m-5-5 5 5 5-5M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"/>',
offline: '<circle cx="12" cy="12" r="9"/><path d="m8 12 3 3 5-6"/>',
progress: '<path d="M12 3a9 9 0 1 1-9 9"/>'
},
'glass-stage': {
download: '<path d="M12 4v11m-4-4 4 4 4-4M5 20h14"/>',
offline: '<circle cx="12" cy="12" r="8"/><path d="m8.5 12 2.5 2.5 4.5-5"/>',
progress: '<path d="M12 4a8 8 0 1 1-8 8"/>'
},
'bento-hub': {
download: '<path d="M12 4v11m-4-4 4 4 4-4M5 17v3h14v-3"/>',
offline: '<rect x="4" y="4" width="16" height="16" rx="4"/><path d="m8 12 3 3 5-6"/>',
progress: '<path d="M12 4a8 8 0 1 1-8 8"/>'
}
};
const use = kind => `<use href="#media-${kind}"/>`;
const svg = (kind, extra = '') => `<svg class="media-icon ${extra}" data-media-icon="${kind}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${use(kind)}</svg>`;
const media = { paths: mediaPaths, use, svg };
if (root.document) {
const defs = root.document.createElementNS('http://www.w3.org/2000/svg', 'svg');
defs.setAttribute('aria-hidden', 'true'); defs.setAttribute('width', '0'); defs.setAttribute('height', '0');
defs.style.position = 'absolute'; defs.style.pointerEvents = 'none';
defs.innerHTML = '<defs>' + Object.keys(mediaPaths).map(kind => `<g id="media-${kind}">${Object.entries(variants).map(([layout, paths]) => `<g class="media-shape media-shape-${layout}">${paths[kind]}</g>`).join('')}</g>`).join('') + '</defs>';
root.document.body.appendChild(defs);
root.MediaIcons = media;
}
// Select variants on visible use elements: ancestor CSS in referenced SVG groups
// can report changed styles without repainting the cloned geometry in Chromium.
const transportPaths = {
play: '<path d="m8 5 11 7-11 7z"/>',
pause: '<rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/>',
previous: '<path d="m19 5-10 7 10 7zM5 5v14"/>',
next: '<path d="m5 5 10 7-10 7zM19 5v14"/>',
forward: '<path d="m3 5 9 7-9 7zM12 5l9 7-9 7z"/>'
};
for (const seconds of [10,15]) for (const direction of ['back','forward']) {
transportPaths[direction + seconds] = (direction === 'back'
? '<path d="M4 12a8 8 0 1 0 3-6.2M4 4v4.5h4.5"/>'
: '<path d="M20 12a8 8 0 1 1-3-6.2M20 4v4.5h-4.5"/>') +
`<text x="12" y="15.5" text-anchor="middle" font-size="7.5" font-weight="700" fill="currentColor" stroke="none">${seconds}</text>`;
}
const transportVariants = Object.fromEntries(['classic','f7-swipe','glass-stage','bento-hub'].map(layout => [layout,{...transportPaths}]));
Object.assign(transportVariants['f7-swipe'], {
play: '<path d="M8 5.8a1 1 0 0 1 1.5-.86l10 6.2a1 1 0 0 1 0 1.72l-10 6.2A1 1 0 0 1 8 18.2z"/>',
previous: '<rect x="4" y="5" width="3" height="14" rx="1.5"/><path d="M19 6a1 1 0 0 0-1.5-.86l-8.5 6a1 1 0 0 0 0 1.72l8.5 6A1 1 0 0 0 19 18z"/>',
next: '<rect x="17" y="5" width="3" height="14" rx="1.5"/><path d="M5 6a1 1 0 0 1 1.5-.86l8.5 6a1 1 0 0 1 0 1.72l-8.5 6A1 1 0 0 1 5 18z"/>'
});
const transport = {
paths: transportPaths, variants: transportVariants,
svg(kind) {
if (!transportPaths[kind]) throw new Error('Unknown transport icon: ' + kind);
return `<svg class="transport-icon" data-transport-icon="${kind}" viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true">${Object.keys(transportVariants).map(layout=>`<use class="transport-shape transport-shape-${layout}" href="#transport-${kind}${layout==='classic'?'':'-'+layout}"/>`).join('')}</svg>`;
},
set(button, kind, label) {
if (!button) return;
const iconId=button.querySelector?.('.transport-icon')?.id;
button.innerHTML = this.svg(kind);
if(iconId)button.querySelector('.transport-icon').id=iconId;
button.setAttribute('aria-label', label || (kind === 'pause' ? 'Pause' : 'Play'));
}
};
if (root.document) {
const defs = root.document.createElementNS('http://www.w3.org/2000/svg','svg');
defs.setAttribute('aria-hidden','true'); defs.setAttribute('width','0'); defs.setAttribute('height','0');
defs.style.position='absolute'; defs.style.pointerEvents='none';
defs.innerHTML='<defs>'+Object.keys(transportPaths).flatMap(kind=>Object.entries(transportVariants).map(([layout,paths])=>`<g id="transport-${kind}${layout==='classic'?'':'-'+layout}">${paths[kind]}</g>`)).join('')+'</defs>';
root.document.body.appendChild(defs); root.TransportIcons=transport;
}
const paths = {
retry: '<path d="M3 11a9 9 0 1 1 2.6 7M3 3v8h8"/>',
cancel: '<path d="m6 6 12 12M6 18 18 6"/>',
pause: '<path d="M8 5v14M16 5v14"/>',
resume: '<path d="m9 5 10 7-10 7z"/>',
};
function create(doc, action, title) {
if (!paths[action]) throw new Error('Unknown download action');
const label = action[0].toUpperCase() + action.slice(1);
const button = doc.createElement('button'); button.type = 'button';
button.className = `dl-act download-action${action === 'cancel' ? ' danger' : ''}`;
button.setAttribute('aria-label', `${label} ${title}`);
const icon = doc.createElementNS('http://www.w3.org/2000/svg', 'svg');
icon.setAttribute('viewBox', '0 0 24 24'); icon.setAttribute('aria-hidden', 'true'); icon.setAttribute('focusable', 'false');
icon.classList.add('download-action-icon'); icon.innerHTML = paths[action];
const text = doc.createElement('span'); text.textContent = label;
button.append(icon, text); return button;
}
const api = { create, media, transport };
if (typeof module !== 'undefined' && module.exports) module.exports = api; else root.DownloadActions = api;
})(globalThis);

View File

@@ -0,0 +1,28 @@
/* Plain-language save failures, with the original diagnostic kept on demand. */
(function(root) {
'use strict';
function message(error) {
const raw = String(error?.message || error || '').trim();
if (!raw) return 'Could not save this video. Try Retry.';
if (/not available in your country|geo.?restricted/i.test(raw)) return 'This video is unavailable in the server’s region. It may still play on your device.';
if (/private video|members.only|join this channel|confirm your age|age.restricted/i.test(raw)) return 'YouTube requires access this server does not have to save this video.';
if (/removed by|video has been removed|copyright claim/i.test(raw)) return 'YouTube is no longer making this video available to the server.';
if (/sign in to confirm|not a bot/i.test(raw)) return 'YouTube temporarily blocked the server’s download request. Try Retry later.';
if (/video unavailable/i.test(raw)) return 'YouTube isn’t letting the server save this video. Try Retry; it may still play on YouTube.';
if (/requested format (?:is )?not available|no video formats found/i.test(raw)) return 'No downloadable version was available. Try Retry to check other download methods.';
if (/^ERROR:|^WARNING:|Traceback|yt-dlp exited|yt-dlp not found/i.test(raw)) return 'The server could not save this video. Try Retry.';
// Existing plain-language connection/quota/validation messages remain useful.
return raw.length <= 180 && !raw.includes('\n') ? raw : 'Could not save this video. Try Retry.';
}
function appendDetails(container, error) {
if (!error) return;
const doc = container.ownerDocument;
const details = doc.createElement('details'); details.className = 'download-error-details';
const summary = doc.createElement('summary'); summary.textContent = 'Technical details';
const pre = doc.createElement('pre'); pre.textContent = String(error?.message || error);
details.append(summary, pre); container.append(details);
return details;
}
const api = { message, appendDetails };
if (typeof module !== 'undefined') module.exports = api; else root.DownloadErrors = api;
})(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -0,0 +1,24 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { message } = require('./download-errors.js');
const { formatJobStatus } = require('./downloads-page.js');
test('unavailable songs get useful copy without claiming that they were removed', () => {
const raw = 'ERROR: [youtube] wZzRoXymOUU: Video unavailable\nYouTube clients tried: default, web_embedded, web_safari';
assert.equal(message(raw), 'YouTube isn’t letting the server save this video. Try Retry; it may still play on YouTube.');
assert.equal(formatJobStatus({ status: 'failed', error: raw }), 'Failed: ' + message(raw));
});
test('known restrictions and bot failures have distinct explanations', () => {
assert.match(message('Video unavailable. not available in your country'), /server’s region/);
assert.match(message('Video unavailable. Private video'), /requires access/);
assert.match(message('Video unavailable. Confirm your age'), /requires access/);
assert.match(message('Video has been removed'), /no longer/);
assert.match(message('Sign in to confirm you are not a bot'), /temporarily blocked/);
assert.match(message('Requested format is not available'), /other download methods/);
});
test('missing and raw tool failures get a short fallback; existing useful messages survive', () => {
assert.equal(message(null), 'Could not save this video. Try Retry.');
assert.equal(message('ERROR: mysterious extractor failure'), 'The server could not save this video. Try Retry.');
assert.equal(message('Connection lost'), 'Connection lost');
assert.equal(message('Please wait a few seconds before trying again.'), 'Please wait a few seconds before trying again.');
assert.equal(message('a'.repeat(200)), 'Could not save this video. Try Retry.');
});

292
frontend/downloads-page.js Normal file
View File

@@ -0,0 +1,292 @@
/* Downloads page UI module. Grouped jobs, storage info, confirmed cancellation. */
(function (root) {
'use strict';
const actionButtons = typeof module !== 'undefined' ? require('./download-actions.js') : root.DownloadActions;
const errors = typeof module !== 'undefined' ? require('./download-errors.js') : root.DownloadErrors;
const bytes = n => {
if (typeof n !== 'number' || isNaN(n) || n <= 0) return '0 MB';
return n >= 1073741824 ? `${(n / 1073741824).toFixed(1)} GB` : `${(n / 1048576).toFixed(1)} MB`;
};
function escapeHtml(str) {
return String(str || '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
function formatJobStatus(job) {
if (job.status === 'failed') {
return job.error ? `Failed: ${errors.message(job.error)}` : 'Save failed';
}
if (job.status === 'paused') {
return 'Paused — resume when you’re ready';
}
if (job.status === 'queued') {
return 'Waiting for a free slot…';
}
const p = job.progress;
if (p) {
if (p.phase === 'waiting') return 'Waiting for a free slot…';
if (p.phase === 'preparing') return `Preparing on server… ${Math.round((p.elapsed || 0) / 1000)} s`;
if (p.phase === 'verifying') return 'Verifying…';
if (p.total) {
return `${(p.received / 1048576).toFixed(1)} / ${(p.total / 1048576).toFixed(1)} MB`;
}
}
return 'Saving for offline…';
}
function groupJobs(jobs) {
const groups = {
active: [],
queued: [],
paused: [],
failed: []
};
for (const job of jobs || []) {
const st = job.status || 'paused';
if (groups[st]) {
groups[st].push(job);
} else {
groups.paused.push(job);
}
}
return groups;
}
function confirmCancel(job, options) {
const title = job.title || job.id;
const message = `Cancel saving “${title}”?`;
const subtext = 'The part already downloaded will be deleted.';
if (options.showModal && typeof options.showModal === 'function') {
const body = options.doc ? options.doc.createTextNode(subtext) : subtext;
options.showModal(message, body, [
{ label: 'Keep', onClick: options.closeModal || (() => {}) },
{
label: 'Cancel save',
danger: true,
onClick: () => {
options.onAction(job.id, 'cancel');
if (options.closeModal) options.closeModal();
if (options.refresh) options.refresh();
}
}
]);
} else if (typeof root.confirm === 'function') {
if (root.confirm(`${message}\n${subtext}`)) {
options.onAction(job.id, 'cancel');
if (options.refresh) options.refresh();
}
} else {
options.onAction(job.id, 'cancel');
if (options.refresh) options.refresh();
}
}
let watcher;
function render(container, options = {}) {
clearInterval(watcher);
if (!container) return;
const doc = container.ownerDocument || document;
const downloadsApi = options.downloadsApi || root.Downloads;
const jobs = options.jobs || (downloadsApi && downloadsApi.getJobs ? downloadsApi.getJobs() : []);
const onAction = options.onAction || (downloadsApi && downloadsApi.action ? downloadsApi.action.bind(downloadsApi) : () => {});
const onNavigateSaved = options.onNavigateSaved || (() => {});
container.replaceChildren();
if (options.isActive && options.refresh) {
const state = items => JSON.stringify(items.map(j => [j.id, j.status, j.error]));
const signature = state(jobs);
watcher = setInterval(() => {
if (!options.isActive()) { clearInterval(watcher); return; }
if (signature !== state(downloadsApi.getJobs())) options.refresh();
}, 1000);
}
const query = (options.filter || '').toLowerCase();
const visibleJobs = jobs.filter(job => `${job.title || job.id} ${job.channel || ''}`.toLowerCase().includes(query));
if (jobs.length && !visibleJobs.length) {
const message = doc.createElement('p'); message.className = 'status'; message.textContent = 'No downloads match your filter.'; container.append(message); return;
}
if (!jobs.length) {
// Calm SVG Empty State
const empty = doc.createElement('div');
empty.className = 'empty-state dl-empty-state';
empty.innerHTML = `
<div class="empty-icon dl-empty-icon-wrapper" aria-hidden="true">
<svg class="dl-empty-svg media-icon" data-media-icon="download" viewBox="0 0 24 24" aria-hidden="true"><use href="#media-download"/></svg>
</div>
<h3 class="empty-title">No active downloads</h3>
<p class="empty-desc">Saves in progress appear here with live status. Videos you save land in <strong>Saved</strong>.</p>
<p class="dl-how-to-save">Save videos for offline listening using the Save button on any track or playlist.</p>
<div class="dl-storage-note">Calculating storage…</div>
`;
const cta = doc.createElement('button');
cta.type = 'button';
cta.className = 'empty-cta dl-saved-cta';
cta.textContent = 'View saved videos';
cta.addEventListener('click', onNavigateSaved);
empty.appendChild(cta);
container.appendChild(empty);
if (downloadsApi && downloadsApi.getFiles) {
Promise.resolve(downloadsApi.getFiles()).then(files => {
const storageNote = empty.querySelector('.dl-storage-note');
if (storageNote && files) {
const playlists = downloadsApi.getPlaylists ? downloadsApi.getPlaylists() : [];
const stats = downloadsApi.breakdown ? downloadsApi.breakdown(files, playlists) : null;
const totalStr = stats ? bytes(stats.total) : bytes(files.reduce((a, b) => a + (b.size || 0), 0));
storageNote.textContent = `Device storage used by saved media: ${totalStr}`;
}
}).catch(() => {
const storageNote = empty.querySelector('.dl-storage-note');
if (storageNote) storageNote.textContent = '';
});
}
return;
}
// Summary Header
const summary = doc.createElement('div');
summary.className = 'saved-summary dl-summary';
const totalCount = jobs.length;
summary.textContent = `${totalCount} download${totalCount === 1 ? '' : 's'}`;
const savedLinkBtn = doc.createElement('button');
savedLinkBtn.type = 'button';
savedLinkBtn.className = 'dl-saved-link';
savedLinkBtn.textContent = 'View saved';
savedLinkBtn.addEventListener('click', onNavigateSaved);
summary.appendChild(savedLinkBtn);
container.appendChild(summary);
// Grouped Consistent Rows
const groups = groupJobs(visibleJobs);
const sections = [
{ key: 'active', title: 'Active downloads' },
{ key: 'queued', title: 'Queued' },
{ key: 'paused', title: 'Paused' },
{ key: 'failed', title: 'Failed' }
];
for (const sec of sections) {
const secJobs = groups[sec.key];
if (!secJobs || !secJobs.length) continue;
const groupDiv = doc.createElement('div');
groupDiv.className = `dl-group dl-group-${sec.key}`;
const groupHeading = doc.createElement('h4');
groupHeading.className = 'dl-group-title';
groupHeading.textContent = `${sec.title} (${secJobs.length})`;
groupDiv.appendChild(groupHeading);
for (const job of secJobs) {
const isPaused = job.status === 'paused';
const isFailed = job.status === 'failed';
const isActive = job.status === 'active' || job.status === 'queued';
const row = doc.createElement('div');
row.className = `card downloading dl-row ${isPaused ? 'dl-paused' : ''} ${isFailed ? 'dl-failed' : ''} ${isActive ? 'dl-active' : ''}`;
row.dataset.id = job.id;
const thumbUrl = job.thumbnail || (options.thumbUrlFor ? options.thumbUrlFor(job.id, job) : '');
const p = job.progress;
const pct = p && p.total ? Math.max(1, Math.min(100, (p.received / p.total) * 100)) : null;
row.innerHTML = `
<div class="thumb">
<img loading="lazy" decoding="async" src="${escapeHtml(thumbUrl)}" alt="" />
<div class="dl-progress"><div class="dl-bar ${pct !== null ? 'determinate' : ''}" style="${pct !== null ? 'width:' + pct + '%' : ''}"></div></div>
</div>
<div class="card-info">
<div class="card-title">${escapeHtml(job.title || job.id)}</div>
<div class="card-channel">${escapeHtml(formatJobStatus(job))}</div>
</div>
`;
if (isFailed && job.error) errors.appendDetails(row.querySelector('.card-info'), job.error);
const acts = doc.createElement('div');
acts.className = 'dl-actions';
if (isActive) {
const pauseBtn = actionButtons.create(doc, 'pause', job.title || job.id);
pauseBtn.setAttribute('aria-label', `Pause ${job.title || job.id}`);
pauseBtn.onclick = (e) => {
e.stopPropagation();
onAction(job.id, 'pause');
if (options.refresh) options.refresh();
};
acts.appendChild(pauseBtn);
} else if (isPaused) {
const resumeBtn = actionButtons.create(doc, 'resume', job.title || job.id);
resumeBtn.setAttribute('aria-label', `Resume ${job.title || job.id}`);
resumeBtn.onclick = (e) => {
e.stopPropagation();
onAction(job.id, 'resume');
if (options.refresh) options.refresh();
};
acts.appendChild(resumeBtn);
} else if (isFailed) {
const retryBtn = actionButtons.create(doc, 'retry', job.title || job.id);
retryBtn.setAttribute('aria-label', `Retry ${job.title || job.id}`);
retryBtn.onclick = (e) => {
e.stopPropagation();
onAction(job.id, 'retry');
if (options.refresh) options.refresh();
};
acts.appendChild(retryBtn);
}
const cancelBtn = actionButtons.create(doc, 'cancel', job.title || job.id);
cancelBtn.setAttribute('aria-label', `Cancel ${job.title || job.id}`);
cancelBtn.onclick = (e) => {
e.stopPropagation();
confirmCancel(job, {
showModal: options.showModal,
closeModal: options.closeModal,
doc,
onAction,
refresh: options.refresh
});
};
acts.appendChild(cancelBtn);
row.querySelector('.card-info').appendChild(acts);
groupDiv.appendChild(row);
}
container.appendChild(groupDiv);
}
if (groups.paused.length && root.OPFS && root.OPFS.listPartials) {
root.OPFS.listPartials().then(parts => {
for (const p of parts) {
const row = container.querySelector(`.card.dl-paused[data-id="${CSS.escape(p.id)}"]`);
if (!row || !p.size) continue;
const bar = row.querySelector('.dl-bar');
if (bar) {
bar.classList.add('determinate');
bar.style.width = Math.max(1, Math.min(100, (p.received / p.size) * 100)) + '%';
}
const ch = row.querySelector('.card-channel');
if (ch) {
ch.textContent = `Paused at ${(p.received / 1048576).toFixed(1)} / ${(p.size / 1048576).toFixed(1)} MB — resume when you’re ready`;
}
}
}).catch(() => {});
}
}
const api = { render, groupJobs, formatJobStatus, escapeHtml, bytes };
if (typeof module !== 'undefined') module.exports = api; else root.DownloadsPage = api;
})(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -0,0 +1,50 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const DownloadsPage = require('./downloads-page.js');
test('groupJobs categorizes active, queued, paused, and failed jobs correctly', () => {
const jobs = [
{ id: '1', title: 'Job 1', status: 'active' },
{ id: '2', title: 'Job 2', status: 'queued' },
{ id: '3', title: 'Job 3', status: 'paused' },
{ id: '4', title: 'Job 4', status: 'failed', error: 'Network error' }
];
const groups = DownloadsPage.groupJobs(jobs);
assert.equal(groups.active.length, 1);
assert.equal(groups.queued.length, 1);
assert.equal(groups.paused.length, 1);
assert.equal(groups.failed.length, 1);
assert.equal(groups.active[0].id, '1');
assert.equal(groups.failed[0].error, 'Network error');
});
test('formatJobStatus produces plain text labels without emojis for all job states', () => {
assert.equal(DownloadsPage.formatJobStatus({ status: 'failed', error: 'Connection lost' }), 'Failed: Connection lost');
assert.equal(DownloadsPage.formatJobStatus({ status: 'failed' }), 'Save failed');
assert.equal(DownloadsPage.formatJobStatus({ status: 'paused' }), 'Paused — resume when you’re ready');
assert.equal(DownloadsPage.formatJobStatus({ status: 'queued' }), 'Waiting for a free slot…');
assert.equal(
DownloadsPage.formatJobStatus({ status: 'active', progress: { received: 10485760, total: 52428800 } }),
'10.0 / 50.0 MB'
);
assert.equal(
DownloadsPage.formatJobStatus({ status: 'active', progress: { phase: 'preparing', elapsed: 3000 } }),
'Preparing on server… 3 s'
);
assert.equal(DownloadsPage.formatJobStatus({ status: 'active', progress: { phase: 'verifying' } }), 'Verifying…');
assert.equal(DownloadsPage.formatJobStatus({ status: 'active' }), 'Saving for offline…');
});
test('bytes formatting handles bytes, MB, GB and invalid input safely', () => {
assert.equal(DownloadsPage.bytes(0), '0 MB');
assert.equal(DownloadsPage.bytes(10485760), '10.0 MB');
assert.equal(DownloadsPage.bytes(1073741824), '1.0 GB');
assert.equal(DownloadsPage.bytes(-100), '0 MB');
assert.equal(DownloadsPage.bytes(null), '0 MB');
});
test('escapeHtml escapes dangerous HTML characters', () => {
assert.equal(DownloadsPage.escapeHtml('<script>alert("xss")</script>'), '&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;');
assert.equal(DownloadsPage.escapeHtml('Tom & Jerry'), 'Tom &amp; Jerry');
});

59
frontend/downloads.js Normal file
View File

@@ -0,0 +1,59 @@
/* Download controls and device storage accounting. */
(function(root) {
'use strict';
const actionButtons = typeof module !== 'undefined' ? require('./download-actions.js') : root.DownloadActions;
const errors = typeof module !== 'undefined' ? require('./download-errors.js') : root.DownloadErrors;
const bytes = n => n >= 1073741824 ? `${(n / 1073741824).toFixed(1)} GB` : `${(n / 1048576).toFixed(1)} MB`;
function breakdown(files, playlists) {
const kinds = { video: 0, audio: 0, eq: 0 }, byId = new Map();
for (const f of files) { const size = Math.max(0, Number(f.size) || 0); kinds[f.kind in kinds ? f.kind : 'video'] += size; byId.set(f.id, (byId.get(f.id) || 0) + size); }
return { total: Object.values(kinds).reduce((a, b) => a + b, 0), kinds, playlists: playlists.map(p => ({ id: p.id, name: p.name || p.title || 'Playlist', size: [...new Set((p.videos || []).map(v => v.id))].reduce((n, id) => n + (byId.get(id) || 0), 0) })) };
}
let adapter, total = 0;
function configure(options) {
adapter = options;
root.SettingsSections.register({ id: 'downloads-storage', title: 'Downloads & storage', cluster: 'Library & storage', description: 'Active queued paused failed saves, disk usage and playlist sizes', icon: '<use href="#media-download"/>', summary: () => `${adapter.slots()} at once · ${bytes(total)}`, render(container) {
const doc = container.ownerDocument;
const heading = doc.createElement('h3'); heading.textContent = 'Downloads & storage';
const jobs = doc.createElement('div'); jobs.className = 'download-manager'; jobs.setAttribute('aria-label', 'Download manager');
const storage = doc.createElement('div'); storage.className = 'download-storage';
container.append(heading, jobs, storage);
let alive = true, signature = '';
function paint() {
const items = adapter.jobs(); const next = JSON.stringify(items); if (next === signature) return; signature = next;
jobs.replaceChildren();
if (!items.length) { const p = doc.createElement('p'); p.textContent = 'No pending downloads.'; jobs.append(p); }
for (const job of items) {
const row = doc.createElement('div'); row.className = 'download-job';
const title = doc.createElement('b'); title.textContent = job.title || job.id;
const status = doc.createElement('small'); status.textContent = job.error ? errors.message(job.error) : job.status;
const progress = doc.createElement('progress'); progress.max = job.progress?.total || 1; if (job.progress?.total) progress.value = job.progress.received || 0; progress.setAttribute('aria-label', `Saving ${job.title || job.id}`);
const actions = doc.createElement('div');
for (const action of [...(['active', 'queued'].includes(job.status) ? ['pause'] : [job.status === 'failed' ? 'retry' : 'resume']), 'cancel']) {
const button = actionButtons.create(doc, action, job.title || job.id); button.onclick = () => { adapter.action(job.id, action); signature = ''; paint(); }; actions.append(button);
}
row.append(title, status, progress, actions);
if (job.error) errors.appendDetails(row, job.error);
jobs.append(row);
}
}
async function disk() {
try {
const [files, estimate] = await Promise.all([adapter.files(), root.navigator.storage?.estimate?.() || {}]); if (!alive) return;
const stats = breakdown(files, adapter.playlists()); total = stats.total; storage.replaceChildren();
for (const text of [`Device media: ${bytes(total)}`, `Video ${bytes(stats.kinds.video)} · Audio ${bytes(stats.kinds.audio)} · EQ renders ${bytes(stats.kinds.eq)}`, estimate.quota ? `Available browser storage: ${bytes(Math.max(0, estimate.quota - (estimate.usage || 0)))}` : 'Available browser storage is not reported.', ...stats.playlists.map(p => `${p.name}: ${bytes(p.size)}`), 'Playlist totals include shared files; device totals count each file once. Browser quota is not total device free space.']) { const p = doc.createElement('p'); p.textContent = text; storage.append(p); }
storage.dispatchEvent(new Event('change', { bubbles: true }));
} catch { storage.textContent = 'Storage details are unavailable on this device.'; }
}
paint(); disk(); const timer = setInterval(paint, 1000), diskTimer = setInterval(disk, 15000);
return () => { alive = false; clearInterval(timer); clearInterval(diskTimer); };
} });
}
function getJobs() { return adapter && typeof adapter.jobs === 'function' ? adapter.jobs() : []; }
function action(id, act) { if (adapter && typeof adapter.action === 'function') return adapter.action(id, act); }
function getFiles() { return adapter && typeof adapter.files === 'function' ? adapter.files() : Promise.resolve([]); }
function getPlaylists() { return adapter && typeof adapter.playlists === 'function' ? adapter.playlists() : []; }
function getSlots() { return adapter && typeof adapter.slots === 'function' ? adapter.slots() : 4; }
function snapshot() { return { jobs: getJobs(), slots: getSlots(), playlists: getPlaylists() }; }
const api = { configure, breakdown, bytes, getJobs, action, getFiles, getPlaylists, getSlots, snapshot }; if (typeof module !== 'undefined') module.exports = api; else root.Downloads = api;
})(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -0,0 +1,17 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { breakdown, bytes } = require('./downloads.js');
test('storage counts media once and shared playlist files within each playlist', () => {
const result = breakdown([{ id: 'a', size: 100, kind: 'video' }, { id: 'a', size: 20, kind: 'eq' }, { id: 'b', size: 30, kind: 'audio' }], [{ id: 'one', videos: [{ id: 'a' }, { id: 'a' }] }, { id: 'two', videos: [{ id: 'a' }, { id: 'b' }] }]);
assert.equal(result.total, 150); assert.deepEqual(result.kinds, { video: 100, audio: 30, eq: 20 }); assert.deepEqual(result.playlists.map(p => p.size), [120, 150]);
});
test('storage ignores invalid and negative sizes', () => { assert.equal(breakdown([{ id: 'a', size: -10 }, { id: 'b', size: 'bad' }], []).total, 0); assert.equal(bytes(1073741824), '1.0 GB'); });
test('pausing a worker terminates it once and ignores later completion', async () => {
const vm = require('node:vm'), fs = require('node:fs'); let worker;
class Worker { constructor() { worker = this; this.terminated = 0; } postMessage() {} terminate() { this.terminated++; } }
const window = {};
vm.runInNewContext(fs.readFileSync(require.resolve('./opfs.js'), 'utf8'), { window, navigator: {}, Worker, URL, AbortController });
const controller = new AbortController(); const result = window.OPFS.downloadVideo('video', '/download', { signal: controller.signal });
controller.abort(); assert.equal((await result).paused, true); assert.equal(worker.terminated, 1);
worker.onmessage({ data: { type: 'done' } }); assert.equal(worker.terminated, 1);
});

17
frontend/eq-core.js Normal file
View File

@@ -0,0 +1,17 @@
/* Shared live/offline EQ definitions and legacy curve migration. */
(function(root) {
'use strict';
const { bands, presets, migrate, width } = typeof module !== 'undefined' ? require('./eq-parameters') : root.EqParameters;
function createWidener(context, source, value = 0) {
const splitter = context.createChannelSplitter(2), output = context.createChannelMerger(2), delay = context.createDelay(.05);
source.connect(splitter); splitter.connect(output, 0, 0); splitter.connect(delay, 1); delay.connect(output, 0, 1);
delay.delayTime.value = width(value) / 100 * .015;
return { output, set: next => delay.delayTime.setTargetAtTime(width(next) / 100 * .015, context.currentTime, .03) };
}
function register(adapter) { root.SettingsSections.register({ id: 'equalizer', title: 'Equalizer & stereo', cluster: 'Listening', summary: () => `${presets[adapter.settings().eq?.preset]?.name || 'Custom'} · ${width(adapter.settings().stereoWidth) ? 'Widened' : 'Original stereo'}`, render(container) {
const doc = container.ownerDocument, button = doc.createElement('button'); button.type = 'button'; button.className = 'settings-back'; button.textContent = 'Open ten-band equalizer'; button.onclick = adapter.open;
const label = doc.createElement('label'); label.className = 'set-row'; label.textContent = 'Headphone stereo widener (optional)'; const input = doc.createElement('input'); input.type = 'range'; input.min = '0'; input.max = '100'; input.value = String(width(adapter.settings().stereoWidth)); input.setAttribute('aria-label', 'Headphone stereo width'); const out = doc.createElement('output'); out.textContent = `${input.value}%`; input.oninput = () => { adapter.settings().stereoWidth = Number(input.value); out.textContent = `${input.value}%`; adapter.persist(); adapter.apply(); }; label.append(input, out);
const note = doc.createElement('p'); note.textContent = 'Off at 0%. Adds up to 15 ms delay to the right channel for headphones. May colour the sound on speakers or when summed to mono. On iPhone, saved songs use processed copies; streamed songs require Live sound processing.'; container.append(button,label,note);
} }); }
const api = { bands, presets, migrate, width, createWidener, register }; if (typeof module !== 'undefined') module.exports = api; else root.EqCore = api;
})(typeof window !== 'undefined' ? window : globalThis);

4
frontend/eq-core.test.js Normal file
View File

@@ -0,0 +1,4 @@
const { test } = require('node:test'), assert = require('node:assert/strict'); const { bands, presets, migrate, width } = require('./eq-core');
test('ten bands and every preset share one frequency definition', () => { assert.deepEqual(bands.map(b=>b.f), [31,62,125,250,500,1000,2000,4000,8000,16000]); for (const preset of Object.values(presets)) assert.equal(preset.g.length, 10); });
test('legacy curves interpolate in log frequency and retain anchor values', () => { const result = migrate([6,2,-2,4,0]); assert.equal(result[0],6); assert.equal(result[3],2); assert.equal(result[5],-2); assert.equal(result[7],4); assert.equal(result[9],0); assert.ok(result[4] > -2 && result[4] < 2); assert.deepEqual(migrate([0,0,0,0,0]), presets.flat.g); });
test('current curves are stable and clamp bad gains; widening defaults off', () => { assert.deepEqual(migrate(presets.acoustic.g), presets.acoustic.g); assert.equal(migrate([99,-99,NaN])[0],12); assert.equal(migrate([99,-99,NaN])[1],-12); assert.equal(width(undefined),0); assert.equal(width(500),100); });

25
frontend/eq-parameters.js Normal file
View File

@@ -0,0 +1,25 @@
/* Eager settings values; audio graphs remain in lazy feature groups. */
(function(root) {
'use strict';
const frequencies = [31,62,125,250,500,1000,2000,4000,8000,16000];
const bands = frequencies.map((f,i) => ({ f, label: f >= 1000 ? `${f/1000}k` : String(f), type: i === 0 ? 'lowshelf' : i === 9 ? 'highshelf' : 'peaking' }));
const clamp = n => Math.max(-12, Math.min(12, Number(n) || 0));
function migrate(values) {
if (!Array.isArray(values)) return frequencies.map(() => 0);
if (values.length !== 5) return frequencies.map((_,i) => clamp(values[i]));
const old = [60,250,1000,4000,12000], curve = values.map(clamp);
return frequencies.map(f => { if (f <= old[0]) return curve[0]; if (f >= old[4]) return curve[4]; const i = old.findIndex(x => x >= f), weight = Math.log(f / old[i-1]) / Math.log(old[i] / old[i-1]); return Math.round((curve[i-1] * (1-weight) + curve[i] * weight) * 10) / 10; });
}
const presets = {
flat: { name: 'Flat', g: frequencies.map(() => 0) },
bass: { name: 'Bass boost', g: [5,7,5,3,1,0,0,0,0,0] },
vocal: { name: 'Vocal clarity', g: [-3,-4,-2,0,1,2,3,4,1,0] },
acoustic: { name: 'Acoustic live', g: [-2,-1,0,-2,-1,1,2,2,1,0] },
classical: { name: 'Classical', g: migrate([4,2,-1,1,3]) },
treble: { name: 'Treble boost', g: [0,0,0,0,0,0,1,3,5,6] },
};
const width = value => Math.max(0, Math.min(100, Number(value) || 0));
const amount = value => Math.max(0, Math.min(100, Number.isFinite(Number(value)) ? Number(value) : 100));
const api = { bands, presets, migrate, width, amount };
if (typeof module !== 'undefined') module.exports = api; else root.EqParameters = api;
})(typeof window !== 'undefined' ? window : globalThis);

75
frontend/export.js Normal file
View File

@@ -0,0 +1,75 @@
/* Put a video file on the device itself (Photos / Files / Downloads).
* Pure helpers + the three ways a browser can do it; the app decides which
* source (saved copy, server copy, other devices) the bytes come from.
* DeviceExport.fileName(title, ext) → safe "Title.ext"
* DeviceExport.canShareFile(file) → Web Share with files works here
* DeviceExport.canPickLocation() → "Save as…" dialog exists (desktop Chromium)
* DeviceExport.share(file, name, title) → share sheet ("Save Video" → Photos / Files)
* DeviceExport.pick(file, name) → stream into a user-chosen file
* DeviceExport.download(urlOrFile, name) → plain browser download
*/
(function (root) {
'use strict';
const BAD = /[\u0000-\u001f\\/:*?"<>|]+/g;
function fileName(title, ext, fallback) {
const base = String(title || '').replace(BAD, ' ').replace(/\s+/g, ' ').trim().slice(0, 120)
|| String(fallback || 'video');
const e = String(ext || 'mp4').replace(/^\./, '').toLowerCase().replace(/[^a-z0-9]/g, '') || 'mp4';
return `${base}.${e}`;
}
const mimeFor = (name) => (/\.(m4a|mp3|aac|opus|ogg|flac|wav)$/i.test(name) ? 'audio/mp4' : /\.webm$/i.test(name) ? 'video/webm' : 'video/mp4');
const typed = (file, name) => (file.type ? file : new File([file], name, { type: mimeFor(name) }));
function canShareFile(file) {
try {
if (!navigator.canShare || !navigator.share || !file) return false;
return navigator.canShare({ files: [typed(file, file.name || 'video.mp4')] });
} catch { return false; }
}
const canPickLocation = () => typeof root.showSaveFilePicker === 'function' && !/Android|iPhone|iPad/i.test(navigator.userAgent || '');
// Resolves 'shared' | 'cancelled'; rejects on a real failure.
async function share(file, name, title) {
// new File() over an OPFS file does not copy it — it stays disk-backed.
const f = new File([file], name, { type: file.type || mimeFor(name) });
try {
await navigator.share({ files: [f], title: title || name });
return 'shared';
} catch (e) {
if (e && e.name === 'AbortError') return 'cancelled';
throw e;
}
}
async function pick(file, name) {
let handle;
try {
handle = await root.showSaveFilePicker({ suggestedName: name, types: [{ description: 'Video', accept: { [mimeFor(name)]: ['.' + name.split('.').pop()] } }] });
} catch (e) {
if (e && e.name === 'AbortError') return 'cancelled';
throw e;
}
const w = await handle.createWritable();
await file.stream().pipeTo(w); // chunked: a multi-GB file is never held in memory
return 'saved';
}
// A File/Blob → object URL; a string → used as the href directly (server copy).
function download(src, name) {
const isStr = typeof src === 'string';
const href = isStr ? src : URL.createObjectURL(src);
const a = document.createElement('a');
a.href = href;
a.download = name;
a.rel = 'noopener';
document.body.appendChild(a);
a.click();
a.remove();
if (!isStr) setTimeout(() => URL.revokeObjectURL(href), 10 * 60 * 1000);
return 'started';
}
root.DeviceExport = { fileName, canShareFile, canPickLocation, share, pick, download };
if (typeof module !== 'undefined' && module.exports) module.exports = root.DeviceExport;
})(typeof window !== 'undefined' ? window : globalThis);

10
frontend/export.test.js Normal file
View File

@@ -0,0 +1,10 @@
const test = require('node:test');
const assert = require('node:assert');
const { fileName } = require('./export.js');
test('fileName strips path and reserved characters and keeps the extension', () => {
assert.strictEqual(fileName('AC/DC: Back "In" Black?', 'mp4'), 'AC DC Back In Black .mp4'.replace(' .', '.'));
assert.strictEqual(fileName(' ', '.M4A', 'abc123'), 'abc123.m4a');
assert.strictEqual(fileName('x'.repeat(300), 'mp4').length, 124);
assert.strictEqual(fileName('Song', '../../x'), 'Song.x');
});

244
frontend/f7-layout.js Normal file
View File

@@ -0,0 +1,244 @@
/* Framework7 Swipe layout: the classic design with Framework7 swipe gestures.
* Cards become F7 swipeouts, swiping up on the mini bar opens an F7 "Up next"
* sheet, and the mini bar / screen edge take horizontal swipes. Framework7 is
* loaded only when this layout is first selected. */
(function(root){
'use strict';
const LAYOUT='f7-swipe',F7_SRC='vendor/framework7-swipe.min.js';
// Which swipe actions a card gets in a given view. Pure, so it is testable.
function cardActions(viewType,canDelete){
const left=[{act:'queue',label:'Queue'}];
const right=[{act:'playlist',label:'Playlist'}];
if(canDelete)right.push({act:'remove',label:'Remove',danger:true});
return {left,right};
}
// Classify a finished drag. Returns 'left'|'right'|'up'|'down'|null.
function swipeDirection(dx,dy,min){
min=min||48;const ax=Math.abs(dx),ay=Math.abs(dy);
if(Math.max(ax,ay)<min)return null;
if(ax>ay*1.4)return dx<0?'left':'right';
if(ay>ax*1.4)return dy<0?'up':'down';
return null;
}
function tabSwipeIndex(active,count,direction){
if(direction!=='left'&&direction!=='right'||count<1)return -1;
return Math.max(0,Math.min(count-1,active+(direction==='left'?1:-1)));
}
function mount(doc){
const html=doc.documentElement;let app=null,loading=null,active=false,sheet=null,cardsObserver=null;
const on=()=>html.dataset.layout===LAYOUT;
// app.js top-level `let` bindings are shared across classic scripts but are not on window.
/* global view, queue, queueIndex, queueSource */
const g=(name)=>{try{switch(name){case 'view':return view;case 'queue':return queue;case 'queueIndex':return queueIndex;case 'queueSource':return queueSource;}}catch(_){}return undefined;};
function loadF7(){
if(root.Framework7)return Promise.resolve(root.Framework7);
if(!loading)loading=new Promise((res,rej)=>{const s=doc.createElement('script');s.src=root.Lazy?.url('/vendor/framework7-swipe.min.js')||F7_SRC;s.onload=()=>res(root.Framework7);s.onerror=()=>{loading=null;rej(new Error('Framework7 failed to load'));};doc.head.append(s);});
return loading;
}
function ensureApp(){
return loadF7().then((F7)=>{
if(!app){
app=new F7({el:'body',theme:'ios',touch:{activeState:false,touchRipple:false,touchHighlight:false,tapHold:false},swipeout:{noFollow:false,removeElements:false},sheet:{backdrop:true,closeByBackdropClick:true}});
// F7's touch module swallows any click whose target isn't the touched element and
// cancels the click after a moved touch. app.js relies on programmatic .click()
// calls, and F7 can't be torn down, so drop those two app-wide handlers.
app.off('click');app.off('touchend');
}
return app;
});
}
// ---- Swipeout cards ----
// Framework7 only animates <a> children of the actions box, so these are links acting as buttons.
function actionBtn(a){const b=doc.createElement('a');b.setAttribute('role','button');b.tabIndex=0;b.className='swipeout-action f7s-act'+(a.danger?' f7s-danger':'');b.dataset.act=a.act;b.textContent=a.label;return b;}
function closeRow(li){
if(app){try{app.swipeout.close(li);return;}catch{}}
li.classList.remove('f7s-touch-open','swipeout-opened');li.querySelector('.swipeout-content')?.style.removeProperty('transform');
li.querySelectorAll('.swipeout-actions-opened').forEach(el=>el.classList.remove('swipeout-actions-opened'));
li.querySelectorAll('.f7s-act').forEach(el=>el.style.removeProperty('transform'));
}
function openRow(li,side){
const box=li.querySelector(`.swipeout-actions-${side}`);if(!box)return;
doc.querySelectorAll('li.f7s-row.f7s-touch-open').forEach(other=>{if(other!==li)closeRow(other);});
if(app){try{app.swipeout.open(li,side);if(li.classList.contains('swipeout-opened'))return;}catch{}}
const width=[...box.children].reduce((sum,el)=>sum+el.offsetWidth,0)+16;
li.classList.add('f7s-touch-open','swipeout-opened');box.classList.add('swipeout-actions-opened');
li.querySelector('.swipeout-content').style.transform=`translate3d(${side==='right'?-width:width}px,0,0)`;
box.querySelectorAll('.f7s-act').forEach(el=>el.style.transform='scale(1)');
}
function wrapCard(card){
if(!card.classList||!card.classList.contains('card')||card.closest('li.swipeout')||card.classList.contains('skeleton-card')||!card._video)return;
const li=doc.createElement('li');li.className='swipeout f7s-row';
card.replaceWith(li);card.classList.add('swipeout-content');li.append(card);
const acts=cardActions(g('view')?.type,!!card.querySelector('.card-del'));
for(const side of ['left','right']){
if(!acts[side].length)continue;
const box=doc.createElement('div');box.className='swipeout-actions-'+side;acts[side].forEach(a=>box.append(actionBtn(a)));li.append(box);
}
}
function unwrapAll(){
doc.querySelectorAll('li.f7s-row').forEach(li=>{const c=li.querySelector('.swipeout-content');if(c){c.classList.remove('swipeout-content');c.style.transform='';li.replaceWith(c);}else li.remove();});
}
function wrapAll(){doc.querySelectorAll('#cards .card').forEach(wrapCard);}
function onAction(e){
const btn=e.target.closest('.f7s-act');if(!btn)return;
const li=btn.closest('li.swipeout'),card=li&&li.querySelector('.card'),v=card&&card._video;
e.stopPropagation();closeRow(li);if(!v)return;
if(btn.dataset.act==='queue')root.addToQueue&&root.addToQueue(v);
else if(btn.dataset.act==='playlist')root.openCardMenu&&root.openCardMenu(v);
else if(btn.dataset.act==='remove'){const del=card.querySelector('.card-del');if(del)del.click();}
}
// ---- Up next sheet ----
function upcoming(){const q=g('queue')||[],i=g('queueIndex');return q.slice((typeof i==='number'?i:-1)+1);}
function renderSheet(){
const list=sheet.el.querySelector('.f7s-sheet-list'),items=upcoming();
list.innerHTML='';
if(!items.length){const p=doc.createElement('p');p.className='f7s-empty';p.textContent='Nothing queued after this song.';list.append(p);return;}
items.forEach((v,k)=>{
const li=doc.createElement('li');li.className='f7s-up';
li.innerHTML='<div class="f7s-up-info"><div class="f7s-up-title"></div><div class="f7s-up-ch"></div></div>';
if(v.thumbnail){const img=doc.createElement('img');img.alt='';img.loading='lazy';img.decoding='async';img.src=v.thumbnail;li.prepend(img);}
li.querySelector('.f7s-up-title').textContent=v.title||'';li.querySelector('.f7s-up-ch').textContent=v.channel||'';
li.addEventListener('click',()=>{const q=g('queue')||[],i=g('queueIndex');sheet.close();root.playFromList&&root.playFromList(q,(typeof i==='number'?i:-1)+1+k,g('queueSource'));});
list.append(li);
});
}
function openSheet(){
ensureApp().then((a)=>{
if(!sheet){
const el=doc.createElement('div');el.className='sheet-modal f7s-sheet';
el.innerHTML='<div class="sheet-modal-inner"><div class="f7s-grab" aria-hidden="true"></div><div class="f7s-sheet-head"><span>Up next</span></div><ul class="f7s-sheet-list"></ul></div>';
doc.body.append(el);
sheet=a.sheet.create({el,swipeToClose:true,breakpoints:[0.5],backdropBreakpoint:0.5,backdrop:true,closeByBackdropClick:true,swipeHandler:'.f7s-grab, .f7s-sheet-head'});
}
renderSheet();sheet.open();
}).catch(()=>{});
}
function closeSheet(){
const modal=sheet&&sheet.el&&sheet.el.f7Modal;if(!modal)return;
sheet.el.classList.remove('f7s-full');modal.setBreakpoint(0);
// F7 emits its initial `opened` transition after the sheet animation. If a
// very fast drag reaches the handle during that transition, repeat close
// after that event so its initial breakpoint cannot reopen the sheet.
setTimeout(()=>{if(modal.opened)modal.setBreakpoint(0);},360);
}
// ---- Mini bar + edge swipes (F7 has no component for these) ----
let drag=null,swallowClick=false;
function down(e){
if(!on()||e.pointerType==='touch'||e.pointerType==='mouse'&&e.button!==0)return;
const mini=e.target.closest&&e.target.closest('#miniBar');
const sidebarOpen=!!doc.querySelector('.app.sidebar-open');
const edge=!mini&&e.clientX<22&&!e.target.closest('.player-stage');
const inSidebar=sidebarOpen&&e.target.closest&&e.target.closest('#sidebar, #sidebarBackdrop');
const inRow=!!(e.target.closest&&e.target.closest('.f7s-row, .card, input, textarea, select, button, a, [role="slider"], #seek, #volume'));
const inPlayer=e.target.closest&&e.target.closest('#playerPane:not(.empty)');
const inBody=e.target.closest&&e.target.closest('.body');
if(!mini&&!edge&&!inSidebar&&(!inBody||inRow)&&!(inPlayer&&!inRow))return;
const kind=mini?'mini':edge?'edge':inSidebar?'sidebar':inPlayer?'player':'tabs';
drag={x:e.clientX,y:e.clientY,kind};
}
function up(e){
if(!drag)return;const d=drag;drag=null;
const dir=swipeDirection(e.clientX-d.x,e.clientY-d.y,d.kind==='mini'?36:56);if(!dir)return;
if(d.kind==='mini'){
swallowClick=true;setTimeout(()=>{swallowClick=false;},400);
if(dir==='left')root.playNext&&root.playNext();
else if(dir==='right')root.playPrev&&root.playPrev();
else if(dir==='up')openSheet();
}else if(d.kind==='sheet'){
if(dir==='up'&&sheet){sheet.el.f7Modal.setBreakpoint(1);sheet.el.classList.add('f7s-full');}
else if(dir==='down')closeSheet();
}else if(d.kind==='edge'&&dir==='right')root.openSidebar&&root.openSidebar();
else if(d.kind==='sidebar'&&dir==='left')root.closeSidebar&&root.closeSidebar();
else if(d.kind==='tabs'&&(dir==='left'||dir==='right')){
const tabs=[...doc.querySelectorAll('#bottomNav .bottom-nav-btn')].filter(b=>!b.disabled&&!b.hidden);
const active=Math.max(0,tabs.findIndex(b=>b.classList.contains('active'))),next=tabSwipeIndex(active,tabs.length,dir);
if(tabs[next]&&next!==active){swallowClick=true;setTimeout(()=>{swallowClick=false;},400);tabs[next].click();}
}else if(d.kind==='player'&&dir==='down'&&innerWidth<=860&&!doc.fullscreenElement&&!doc.querySelector('.orientation-fullscreen')){
const search=doc.querySelector('#bottomNav .bottom-nav-btn[data-view="search"]');if(search)search.click();
}
}
function click(e){if(swallowClick&&e.target.closest&&e.target.closest('#miniBar')){e.stopPropagation();e.preventDefault();swallowClick=false;}}
let touchDrag=null,rowDrag=null;
function touchDown(e){
if(!on()||!e.changedTouches.length)return;
const t=e.changedTouches[0],target=e.target,mini=target.closest&&target.closest('#miniBar');
if(target.closest&&target.closest('.f7s-grab, .f7s-sheet-head')){touchDrag={x:t.clientX,y:t.clientY,kind:'sheet'};rowDrag=null;return;}
const row=target.closest&&target.closest('li.f7s-row');
if(row){rowDrag={row,x:t.clientX,y:t.clientY};touchDrag=null;return;}
const sidebarOpen=!!doc.querySelector('.app.sidebar-open'),edge=!mini&&t.clientX<22&&!target.closest('.player-stage');
const inSidebar=sidebarOpen&&target.closest&&target.closest('#sidebar, #sidebarBackdrop');
const inRow=!!(target.closest&&target.closest('.f7s-row, .card, input, textarea, select, button, a, [role="slider"], #seek, #volume'));
const inPlayer=target.closest&&target.closest('#playerPane:not(.empty)'),inBody=target.closest&&target.closest('.body');
if(!mini&&!edge&&!inSidebar&&(!inBody||inRow)&&!(inPlayer&&!inRow))return;
touchDrag={x:t.clientX,y:t.clientY,kind:mini?'mini':edge?'edge':inSidebar?'sidebar':inPlayer?'player':'tabs'};
}
function finish(d,x,y){
if(!d)return;const dir=swipeDirection(x-d.x,y-d.y,d.kind==='mini'?36:56);if(!dir)return;
if(d.kind==='mini'){
swallowClick=true;setTimeout(()=>{swallowClick=false;},400);
if(dir==='left')root.playNext&&root.playNext();else if(dir==='right')root.playPrev&&root.playPrev();else if(dir==='up')openSheet();
}else if(d.kind==='sheet'){
if(dir==='up'&&sheet){sheet.el.f7Modal.setBreakpoint(1);sheet.el.classList.add('f7s-full');}
else if(dir==='down')closeSheet();
}else if(d.kind==='edge'&&dir==='right')root.openSidebar&&root.openSidebar();
else if(d.kind==='sidebar'&&dir==='left')root.closeSidebar&&root.closeSidebar();
else if(d.kind==='tabs'&&(dir==='left'||dir==='right')){
const tabs=[...doc.querySelectorAll('#bottomNav .bottom-nav-btn')].filter(b=>!b.disabled&&!b.hidden);
const active=Math.max(0,tabs.findIndex(b=>b.classList.contains('active'))),next=tabSwipeIndex(active,tabs.length,dir);
if(tabs[next]&&next!==active){swallowClick=true;setTimeout(()=>{swallowClick=false;},400);tabs[next].click();}
}else if(d.kind==='player'&&dir==='down'&&innerWidth<=860&&!doc.fullscreenElement&&!doc.querySelector('.orientation-fullscreen')){
const search=doc.querySelector('#bottomNav .bottom-nav-btn[data-view="search"]');if(search)search.click();
}
}
function touchUp(e){
if(!e.changedTouches.length)return;const t=e.changedTouches[0];
if(rowDrag){const d=rowDrag;rowDrag=null;const dx=t.clientX-d.x,dy=t.clientY-d.y;
if(Math.abs(dx)>Math.max(56,Math.abs(dy)*1.4)){
const card=d.row.querySelector('.card');
// A long swipe left removes once; F7's own overswipe is not relied on, so this is the only path.
if(dx< -170){const remove=card&&card.querySelector('.card-del');if(remove)remove.click();}
else if(dx<0)openRow(d.row,'right');
else if(d.row.querySelector('.swipeout-actions-left'))openRow(d.row,'left');
else {const v=card&&card._video;v&&root.addToQueue&&root.addToQueue(v);}
}
return;
}
if(!touchDrag)return;const d=touchDrag;touchDrag=null;finish(d,t.clientX,t.clientY);
}
function activate(){
active=true;
ensureApp().then(()=>{if(!active)return;wrapAll();}).catch(()=>{});
const cards=doc.getElementById('cards');
if(cards){cardsObserver=new root.MutationObserver(()=>{if(app)wrapAll();});cardsObserver.observe(cards,{childList:true});}
doc.addEventListener('click',onAction,true);
}
function deactivate(){
active=false;if(cardsObserver){cardsObserver.disconnect();cardsObserver=null;}
doc.removeEventListener('click',onAction,true);
if(sheet&&sheet.opened)sheet.close(false);
unwrapAll();
}
function sync(){if(on()&&!active)activate();else if(!on()&&active)deactivate();}
doc.addEventListener('pointerdown',down,{passive:true});
doc.addEventListener('pointerup',up,{passive:true});
doc.addEventListener('pointercancel',()=>{drag=null;},{passive:true});
doc.addEventListener('touchstart',touchDown,{passive:true,capture:true});
doc.addEventListener('touchend',touchUp,{passive:true,capture:true});
doc.addEventListener('touchcancel',()=>{touchDrag=null;rowDrag=null;},{passive:true,capture:true});
doc.addEventListener('click',click,true);
doc.addEventListener('click',e=>{if(e.target.classList?.contains('sheet-backdrop'))closeSheet();},true);
new root.MutationObserver(sync).observe(html,{attributes:true,attributeFilter:['data-layout']});
sync();
}
const api={cardActions,swipeDirection,tabSwipeIndex};
if(typeof module!=='undefined')module.exports=api;
else {root.F7Swipe=api; if(root.document.readyState==='loading')root.document.addEventListener('DOMContentLoaded',()=>mount(root.document),{once:true});else mount(root.document);}
})(typeof window==='undefined'?globalThis:window);

View File

@@ -0,0 +1,27 @@
const test = require('node:test');
const assert = require('node:assert');
const { cardActions, swipeDirection, tabSwipeIndex } = require('./f7-layout');
test('cardActions: every view gets Queue, removable rows get Playlist and Remove', () => {
assert.deepStrictEqual(cardActions('queue', true).left.map((a) => a.act), ['queue']);
assert.deepStrictEqual(cardActions('queue', true).right.map((a) => a.act), ['playlist', 'remove']);
assert.deepStrictEqual(cardActions('search', false).left.map((a) => a.act), ['queue']);
assert.deepStrictEqual(cardActions('search', false).right.map((a) => a.act), ['playlist']);
});
test('swipeDirection classifies clear swipes and ignores short or diagonal drags', () => {
assert.strictEqual(swipeDirection(-80, 5), 'left');
assert.strictEqual(swipeDirection(80, -10), 'right');
assert.strictEqual(swipeDirection(4, -70), 'up');
assert.strictEqual(swipeDirection(10, 20), null);
assert.strictEqual(swipeDirection(60, 60), null);
assert.strictEqual(swipeDirection(40, 0, 36), 'right');
});
test('tabSwipeIndex moves between bottom tabs and clamps at either end', () => {
assert.strictEqual(tabSwipeIndex(0, 5, 'left'), 1);
assert.strictEqual(tabSwipeIndex(3, 5, 'right'), 2);
assert.strictEqual(tabSwipeIndex(4, 5, 'left'), 4);
assert.strictEqual(tabSwipeIndex(0, 5, 'right'), 0);
assert.strictEqual(tabSwipeIndex(2, 5, 'up'), -1);
});

View File

@@ -0,0 +1,77 @@
/* Thin eager entries and configuration for optional, stateful feature modules. */
(function(root) {
'use strict';
const Lazy = root.Lazy, doc = root.document;
if (!Lazy) return;
const specs = [
['Piano','piano','configure','piano','Piano transcription','Live & worship','Off · load model on request'],
['MidiPedals','midi','configure','midi','MIDI pedalboard','Live & worship','Off'],
['PartyDJ','party-dj','register','party-dj','Watch party','Live & worship','Shared suggestions · host approval'],
['LyricsWindow','lyrics-window','configure','floating-lyrics','Floating lyrics','Live & worship','Floating lyrics window'],
['LowerThird','lower-third','register','broadcast','Presenter & broadcast','Live & worship','Projector · OBS lower third'],
['EqCore','eq-core','register','equalizer','Equalizer & stereo','Listening','Flat · Original stereo'],
['VocalReducer','vocal-reducer','register','vocal-reducer','Vocal reducer','Listening','100% · centre-panned vocals'],
['SetlistImport','setlist-import','configure','setlist-import','Setlist import','Library & storage','Planning Center · SongSelect · ChordPro'],
['CarMode','car-mode','configure','voice-car','Voice & Car mode','Listening','Voice search · Car mode'],
['DirectMedia','direct','configure','direct-transfer','Direct device transfer','Library & storage','Paired devices only'],
];
function button(id, text, anchor, name, action, className='np-btn') {
if (!anchor || doc.getElementById(id)) return;
const b=doc.createElement('button'); b.id=id; b.type='button'; b.className=className; b.textContent=text; b.setAttribute('aria-label',text);
if(id==='carModeBtn')b.innerHTML='<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><path d="m5 8 2-5h10l2 5M3 8h18v10H3zM5 18v3m14-3v3M6 12h2m8 0h2"/></svg>';
if(id==='voiceSearchBtn')b.innerHTML='<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10v2a7 7 0 0 0 14 0v-2M12 19v3m-4 0h8"/></svg>';
if(id.startsWith('floating-')){b.title='Open floating lyrics';b.setAttribute('aria-label','Open floating lyrics window');}
b.title ||= text;
b.onclick=()=>Lazy.load(name).then(action).catch(error=>root.dispatchEvent(new CustomEvent('ytp-lazy-error',{detail:{error}})));
anchor.after(b); Lazy.intent(b,name);
}
for (const [globalName, suffix, setup, id, title, cluster, summary] of specs) {
const group='feature:'+suffix;
const facade=Lazy.proxy(group,['open','close','obtain','publish','attach','handle','offer','paint','fade'],globalName);
let configured=false;
facade[setup]=options=>{
if (configured) return; configured=true;
Lazy.onLoad(group,()=>root[globalName][setup](options));
root.SettingsSections.register({id,title,cluster,lazyGroup:group,summary:()=>{
const s=options?.settings?.() || {};
if(globalName==='Piano')return s.pianoEnabled?'On · browser or optional worker':'Off · load model on request';
if(globalName==='MidiPedals')return s.midiEnabled?'On · pedal mappings':'Off';
if(globalName==='EqCore')return `${root.EqParameters.presets[s.eq?.preset]?.name || 'Custom'} · ${root.EqParameters.width(s.stereoWidth)?'Widened':'Original stereo'}`;
if(globalName==='VocalReducer')return `${root.EqParameters.amount(s.vocalLevel ?? 100)}% · centre-panned vocals`;
if(globalName==='DirectMedia')return facade.enabled()?'On · paired devices only':'Off or unsupported';
if(globalName==='CarMode')return root.SpeechRecognition||root.webkitSpeechRecognition?'Voice search available · Car mode':'Car mode · voice unavailable';
if(globalName==='LyricsWindow')return root.documentPictureInPicture?.requestWindow?'Interactive window available':root.HTMLCanvasElement?.prototype.captureStream&&doc.pictureInPictureEnabled?'Lyric video PiP available':'Not supported on this browser';
return summary;
},
render(container,context) {
let disposed=false, cleanup;
container.textContent='Loading…';
Lazy.load(group).then(()=>{
if (disposed || !container.isConnected) return;
container.replaceChildren(); cleanup=root.SettingsSections.get(id).render(container,context);
}).catch(error=>{if(!disposed)container.textContent=error.message;});
return ()=>{disposed=true; if(typeof cleanup==='function')cleanup();};
},
});
if (globalName==='CarMode') {
button('carModeBtn','Car mode',doc.getElementById('searchForm'),group,()=>root.CarMode.open(),'icon-btn');
if(root.SpeechRecognition||root.webkitSpeechRecognition)button('voiceSearchBtn','Voice search',options.input,group,()=>doc.getElementById('voiceSearchBtn').click(),'icon-btn voice-search');
}
if (globalName==='LyricsWindow' && (root.documentPictureInPicture?.requestWindow || (root.HTMLCanvasElement?.prototype.captureStream && doc.pictureInPictureEnabled))) {
for(const anchor of ['stageLyricsAuto','serviceAutoscrollBtn','pipBtn'])button('floating-'+anchor,'⧉ Lyrics',doc.getElementById(anchor),group,()=>doc.getElementById('floating-'+anchor).click());
}
};
if(globalName==='LowerThird') {
facade.active=()=>new URLSearchParams(root.location.search).get('overlay')==='lowerthird';
facade.url=(origin,code)=>{const u=new URL('/',origin);u.searchParams.set('overlay','lowerthird');u.searchParams.set('code',String(code));return u.href;};
}
if(globalName==='DirectMedia') {
let settings=()=>({}); const configure=facade.configure;
facade.configure=options=>{settings=options.settings;configure(options);};
facade.enabled=()=>settings().directTransfer!==false && !!root.RTCPeerConnection;
facade.hasSource=()=>false;
}
if(globalName==='LyricsWindow')facade.element=()=>null;
root[globalName]=facade;
}
})(typeof window !== 'undefined' ? window : globalThis);

81
frontend/fingerprint.js Normal file
View File

@@ -0,0 +1,81 @@
/* ============================================================================
* fingerprint.js — stable browser identifier for server-side playlist sync
*
* Combines canvas rendering, UA, screen geometry, and hardware hints into a
* short hex string. The result is stored in localStorage so the same ID
* survives page reloads, and only regenerated when localStorage is cleared.
*
* Not for tracking — used exclusively so the server can associate playlist
* and history rows with this browser without requiring a login.
* ========================================================================== */
(function () {
'use strict';
// djb2 hash over a string → 32-bit unsigned int
function djb2(str) {
let h = 5381;
for (let i = 0; i < str.length; i++) {
h = (((h << 5) + h) + str.charCodeAt(i)) >>> 0;
}
return h;
}
// Render a small canvas to capture GPU/font rasterisation differences,
// then hash the pixel data. Falls back to empty string if canvas is blocked.
function canvasHash() {
try {
const c = document.createElement('canvas');
c.width = 200; c.height = 40;
const ctx = c.getContext('2d');
if (!ctx) return '';
ctx.textBaseline = 'top';
ctx.font = '14px Arial';
ctx.fillStyle = '#f60';
ctx.fillRect(125, 1, 62, 20);
ctx.fillStyle = '#069';
ctx.fillText('YTPlayer🎵', 2, 15);
ctx.fillStyle = 'rgba(102,204,0,0.7)';
ctx.fillText('YTPlayer🎵', 4, 17);
return djb2(c.toDataURL()).toString(16);
} catch {
return '';
}
}
function generateFingerprint() {
const parts = [
navigator.userAgent || '',
String(screen.width) + 'x' + String(screen.height),
String(screen.colorDepth),
Intl.DateTimeFormat().resolvedOptions().timeZone || '',
navigator.language || '',
String(navigator.hardwareConcurrency || 0),
String(navigator.deviceMemory || 0),
canvasHash(),
];
// Combine all component hashes into one 16-char hex fingerprint
const combined = parts.reduce((acc, p) => acc + '|' + p, '');
const h1 = djb2(combined);
const h2 = djb2(combined.split('').reverse().join(''));
return h1.toString(16).padStart(8, '0') + h2.toString(16).padStart(8, '0');
}
window.getFingerprint = function getFingerprint() {
try {
let fp = localStorage.getItem('_ytpfp');
if (!fp || fp.length < 8) {
fp = generateFingerprint();
localStorage.setItem('_ytpfp', fp);
}
return fp;
} catch {
// localStorage blocked (e.g. private mode on some browsers) — generate
// ephemeral fingerprint that survives the page session via a closure.
if (!window._ytpfpEphemeral) {
window._ytpfpEphemeral = generateFingerprint();
}
return window._ytpfpEphemeral;
}
};
}());

120
frontend/flag-ui.js Normal file
View File

@@ -0,0 +1,120 @@
/* Report-a-wrong-lyric-line: API client + bottom sheet. No dependencies.
* window.FlagUI.open({videoId, text, existing, profile}) -> Promise<result|null>
* result = {action:'saved'|'withdrawn', id?, reason, note}
* Descriptions are optional; a bare report is valid. */
(function () {
'use strict';
const REASONS = [
['words', 'Wrong words'], ['timing', 'Wrong timing'],
['typo', 'Typo'], ['other', 'Other'],
];
const NOTE_MAX = 500;
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const base = (id) => `/api/notes/${encodeURIComponent(id)}/flags`;
const jpost = (url, body) => fetch(url, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
});
async function list(videoId, profile) {
try {
const r = await fetch(base(videoId), { headers: profile ? { 'X-Profile': profile } : {} });
if (!r.ok) return [];
const j = await r.json();
return Array.isArray(j.flags) ? j.flags : [];
} catch { return []; }
}
async function submit(videoId, profile, text, reason, note) {
const r = await jpost(base(videoId), { profile, text, reason, note });
const j = await r.json().catch(() => ({}));
return { status: r.status, ...j };
}
async function withdraw(videoId, profile, id) {
const r = await jpost(`${base(videoId)}/${id}/withdraw`, { profile });
return r.ok;
}
const ICON = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 21V4M5 4h11l-2 4 2 4H5"/></svg>';
function open({ videoId, text, existing, profile }) {
return new Promise((resolve) => {
const mine = existing && existing.mine ? existing : null;
const others = existing ? Math.max(0, (existing.count || 0) - (mine ? 1 : 0)) : 0;
let reason = mine ? mine.reason || '' : '';
const back = document.createElement('div');
back.className = 'fs-backdrop';
back.innerHTML = `
<div class="fs-sheet" role="dialog" aria-modal="true" aria-label="Report a wrong line">
<div class="fs-grab"></div>
<div class="fs-title">
<span class="fs-badge">${ICON}</span>
<div><h2>${mine ? 'Your report' : 'Report this line'}</h2>
<small>Helps whoever maintains the lyrics find mistakes</small></div>
<button class="fs-x" type="button" aria-label="Close">✕</button>
</div>
<blockquote class="fs-quote">${esc(text)}</blockquote>
${others ? `<div class="fs-notice info">${others} other ${others === 1 ? 'person has' : 'people have'} reported this line too.</div>` : ''}
<div class="fs-label">What’s wrong? <em>optional</em></div>
<div class="fs-chips">${REASONS.map(([k, l]) => `<button type="button" class="fs-chip" data-r="${k}" aria-pressed="${reason === k}">${l}</button>`).join('')}</div>
<div class="fs-label">Describe it <em>optional</em></div>
<textarea class="fs-note" maxlength="${NOTE_MAX}" placeholder="e.g. it should say “sound”, not “sownd”"></textarea>
<div class="fs-count"><span class="fs-n">0</span>/${NOTE_MAX}</div>
<div class="fs-err fs-notice err" hidden></div>
<div class="fs-actions ${mine ? 'three' : ''}">
<button type="button" class="fs-btn fs-cancel">Cancel</button>
${mine ? '<button type="button" class="fs-btn danger fs-withdraw">Withdraw</button>' : ''}
<button type="button" class="fs-btn primary fs-send">${mine ? 'Update report' : 'Send report'}</button>
</div>
</div>`;
const $ = (s) => back.querySelector(s);
const ta = $('.fs-note');
ta.value = mine ? mine.note || '' : '';
const count = () => { $('.fs-n').textContent = ta.value.length; };
count();
ta.addEventListener('input', count);
const prevFocus = document.activeElement;
let done = false;
const close = (val) => {
if (done) return;
done = true;
document.removeEventListener('keydown', onKey, true);
back.classList.add('closing');
setTimeout(() => { back.remove(); if (prevFocus && prevFocus.focus) try { prevFocus.focus(); } catch {} }, 190);
resolve(val);
};
const onKey = (e) => { if (e.key === 'Escape') { e.stopPropagation(); close(null); } };
document.addEventListener('keydown', onKey, true);
back.addEventListener('click', (e) => { if (e.target === back) close(null); });
$('.fs-x').onclick = $('.fs-cancel').onclick = () => close(null);
back.querySelectorAll('.fs-chip').forEach((b) => b.addEventListener('click', () => {
reason = reason === b.dataset.r ? '' : b.dataset.r; // tap again to clear
back.querySelectorAll('.fs-chip').forEach((c) => c.setAttribute('aria-pressed', String(c.dataset.r === reason)));
}));
const fail = (msg) => { const e = $('.fs-err'); e.textContent = msg; e.hidden = false; };
const busy = (on) => back.querySelectorAll('.fs-btn').forEach((b) => { b.disabled = on; });
$('.fs-send').onclick = async () => {
busy(true);
try {
const r = await submit(videoId, profile, text, reason, ta.value.trim());
if (r.ok) return close({ action: 'saved', id: r.id, reason, note: ta.value.trim() });
busy(false);
fail(r.stale ? 'This line was just changed — it may already be fixed.'
: r.status === 401 ? 'Link an online profile to report lines.'
: r.status === 429 ? 'Slow down a little — too many reports.' : (r.error || 'Could not send the report.'));
} catch { busy(false); fail('You appear to be offline.'); }
};
const w = $('.fs-withdraw');
if (w) w.onclick = async () => {
busy(true);
try {
if (await withdraw(videoId, profile, mine.id)) return close({ action: 'withdrawn' });
} catch {}
busy(false); fail('Could not withdraw — try again.');
};
document.body.appendChild(back);
setTimeout(() => ta.blur(), 0);
$('.fs-send').focus();
});
}
window.FlagUI = { open, list, submit, withdraw, REASONS };
})();

Some files were not shown because too many files have changed in this diff Show More