Skip to content

DO NOT MERGE: fixing playback reliability - #7

Closed
PolarWolf314 wants to merge 58 commits into
mainfrom
fix/playback-reliability
Closed

PolarWolf314 wants to merge 58 commits into
mainfrom
fix/playback-reliability

Conversation

@PolarWolf314

Copy link
Copy Markdown
Collaborator

No description provided.

- Vitest (node env, no DOM simulator) for client and server; bun test for
  converter, with unit + integration suites and npm scripts wired up
- Playwright config (chromium/firefox/webkit projects, serial workers) plus
  a chromium browser smoke spec; chromium browser downloaded
- vite.test.config.ts serves fixture media via a fixture publicDir and
  redirects the settings.json import to tests/fixtures/player-settings.json
  so user data is never read during browser tests
- generate-media.mjs synthesizes three tiny H.264/AAC clips (FFmpeg lavfi
  sources only, so licensed by construction) into the gitignored
  tests/fixtures/public/data/; idempotent with --force
- typecheck/lint now cover tests: client tsconfig includes tests + root
  configs, server gains tests/tsconfig.json, converter includes tests/;
  eslint lints src tests in client and server
- characterization smoke tests pin the client/server wire event strings
…ator

The skip path now runs the same ffprobe verification used after
generation and regenerates automatically when a fixture is truncated or
corrupt, instead of letting it slip through and surface later as cryptic
browser-test decode errors. Children killed by a signal are reported
with the signal name rather than 'status null', and main() is wrapped so
failures print a clean one-line error and set exit code 1.
…testing

Both shared.test.ts suites now pin every enum value of Connection,
WaitingRoom, Cinema and Admin (ClientEvents + ServerEvents) from their
own workspace's src/shared copies, closing the coverage gaps where a
rename on one side would go unnoticed. Also hoists the server eslint
ignores into a standalone global-ignores object mirroring the client
config, notes the playwright-install prerequisite where projects are
defined, and adds a Testing subsection to the README.
…ation

UI-independent issue/diagnostics data layer (PR 1 of the playback
reliability work). Known issue codes map to fixed neutral messages,
severity, blocking status, and permitted recovery actions. Repeated
reports of one incident key fold into a single issue with an occurrence
count; media network and decode failures share a per-media incident.
Subscribers get current-state replay, bounded active issues (16) evict
the least recently reported, and every entry point tolerates garbage,
circular, and primitive values without throwing.
…port

recordDiagnostic sanitizes every event to the allowlisted shape (error
names, numeric media codes, EXTENSION_ORIGIN marker, numeric readings)
and bounds history to 50 entries, evicting oldest first. exportDiagnostics
renders a human-readable, local-only report built exclusively from
allowlisted fields: usernames, URLs/IPs, query tokens, raw messages, and
stack traces never appear. Adds conservative user-agent engine detection
and an allowlisted socket-argument summarizer (kinds, never values).
…oundary

index.html now loads /src/bootstrap.ts, which installs last-resort
window error/unhandledrejection handlers before dynamically importing
main and calling its explicit initApp. The load-event wait moved into
bootstrap so a slow dynamic import can no longer miss it. Import or
initialization failures normalize into an app-init issue, render the
plain-text #startup-fallback container, and keep console.error
reporting instead of swallowing.

Runtime handlers preserve native console behavior, filter obvious
extension-origin scripts (chrome-/safari-web-/moz-extension and foreign
http origins) into EXTENSION_ORIGIN diagnostics rather than first-party
failures, and replace socket.onAny raw-argument logging with an
allowlisted console.debug summary (event name + argument kinds only).
- Split snapshot.ts responsibilities: report formatter + DIAGNOSTICS_HEADER
  moved to new report.ts; snapshot.ts keeps the data contract and pure
  helpers (normalizeErrorName moved in from issues.ts) with an accurate
  header; MAX_READINGS_PER_EVENT is exported once and imported elsewhere
- Freeze the issue catalog, its definitions, and recovery-action arrays at
  module scope so issue.recoveryActions.push throws instead of corrupting
  shared catalog state
- Guard issue eviction against non-finite clocks: when no finite lastSeen
  exists, fall back to deleting the first entry so the cap still holds
- Flag lookalike origins (http://localhost:1730.evil.com/x.js) via URL
  origin comparison instead of a prefix match; detector doc now reads
  broad detector, conservative attribution
- Widen recordDiagnostic input to DiagnosticEventInput (unknown-valued
  fields) and add withErrorName helper, removing the 4x conditional-spread
  duplication in runtime.ts/bootstrap.ts
- Validate media error codes against the real MediaError range (1-5) on
  both report and diagnostic paths; drop lookalikes such as HTTP 404
- Clarify bootstrap waitForPageLoad comment for the 'interactive' path
- Add tests: unsubscribe teardown, readings sanitization (safe/unsafe/
  non-finite/overflow), catalog freeze, non-finite clock cap, lookalike
  origins, and mediaErrorCode range; style cleanups (inline export
  function, unexport describeValueKind, case-insensitive import order)
Reading the localStorage global and its accessors can throw (SecurityError
when site data is blocked, QuotaExceededError in private mode), which used
to break username entry and playback. util/storage.ts wraps every access
in a never-throwing API (createSafeStorage/safeGetStorage) that mirrors
failed writes to an in-memory map so preferences hold for the session,
falls back to defaults for unreadable values, and reports one deduplicated
StorageUnavailable issue per failure. getUsername and the movie volume
path now go through it; a source-level pin keeps direct localStorage
access out of the rest of src until Task 6 makes those modules importable.
makeAudioController routed the video through an AudioContext with a
3 + 2 * volume loudness multiplier, and rebuilt that graph on every
cinema:users event. Playback now uses native audio: element.volume is the
only volume pathway, so a saved volume means what the user set (valid
zeros stay zero, nothing is auto-raised), and one module-scope
onvolumechange listener persists changes through the safe storage wrapper.
The initial persist-on-load side effect is dropped: writes only happen on
real user changes. Source-level pin until Task 6 makes the controller
Node-importable.
settings.json is now validated defensively at runtime in config.ts (file
and type must be non-blank strings; subtitles, when present, a list of
{label, srclang, file} strings): an unusable file yields empty derived
exports plus a safe problem token, reported as a new non-blocking
InvalidConfiguration issue inside initApp (after listeners attach), never
an import-time throw or an 'incompatible browser' dead end. main.ts keeps
its stable MOVIE_SOURCE/MOVIE_TYPE/SUBTITLES exports, now re-exported from
config.

The socket URL moves from a host string-replace (which broke on IPv6,
repeated ports, and https) to resolveSocketUrl: same hostname, server port
5000 unless overridden, wss on https pages, bracketed IPv6 literals. A
sanitized opt-in ?server= ws/wss override supports LAN deployments where
page and server hosts differ.
- storage: consult the failed-writes map before real storage so a failed
  write beats the stale stored value (canonical quota/private-mode case);
  drop redundant NaN check covered by Number.isFinite
- config: collapse throwing getters to problem tokens (hostile-property
  standard); un-export dead movieSettings/SERVER_PORT; make
  SocketLocationLike.port/host optional
- tests: narrow the Web Audio source pin to API tokens; drop the
  over-broad '.replace(' absence pin; add credentials-drop coverage;
  remove unused FakeStorage methods
createProjectionClock(now) anchors each applied snapshot at local receipt
time and projects position + elapsed while playing; paused snapshots never
advance; positions carry exactly (no drift threshold). Owns the two wire
revision rules: stale-drop within a connection epoch (apply returns false
for revisions below the highest applied) and epoch reset on reconnect
(server restart re-baselines revisions and discards the last snapshot).
Uses its own injected monotonic clock — never compares clock origins.
Server (Rooms/Cinema.ts): the frozen playing/time fields are replaced by
an authoritative PlaybackClock (performance.now-injected). Admin
play/pause/seek arrive as PlaybackCommand payloads validated at the
boundary — invalid shapes get cinema:command-rejected/invalid-command,
valid shapes for the wrong media get wrong-media — and every broadcast
(Users/Playing/Paused/Seeked) carries the freshly projected snapshot.
New admin Cinema.Select normalizes the announced mediaId (invalid ->
rejected), applies selectMedia (same-media = no-op), and broadcasts
cinema:state to the whole room including the host. Handlers wrap clock
work in a backstop catch so hostile payloads can never throw; real-socket
integration tests (socket.io-client added as a server devDep) pin the
rejections, the advancing late-joiner position over the wire, exact
pause/seek positions, and the same-media no-op vs different-media reset.

Client (minimal adaptation; Task 6 owns lifecycle hardening): config
derives MOVIE_MEDIA_ID via the shared normalizeMediaId; movie.ts applies
every snapshot through the projection clock (stale-drop + epoch reset on
connect/disconnect), reports InvalidServerState on rejections/invalid
snapshots and MediaMismatch on identity mismatch (still applying the
update), and admin play/pause/seek emit {mediaId, position}. The host
announces Cinema.Select from the Cinema.Users handler — the server
attaches its select listener in the same synchronous join block, so the
announcement cannot race a not-yet-attached listener the way an
Accepted-time emit could.
Server: narrow both Cinema backstops so a rejection always means
nothing was applied (broadcast sits outside the try), use
Cinema.snapshot() in onJoin, type listenToCommand's event as the
Play|Pause|Seek union, and fix test-churn indentation plus
integration hygiene (ioServer rename, nextEvent listener cleanup).

Client: drop dead projection ternaries, report InvalidConfiguration
when unusable settings degrade a host command to a local update, and
import normalizeMediaId via the shared barrel.

Shared (mirrored): rename isFinitePosition to isPositionSeconds,
drop the redundant isInteger check, strip leading slashes in
normalizeMediaId ('.//movie.mp4' -> 'movie.mp4'), with tests on
both sides.
logApplicationState used process.stdout.moveCursor/clearScreenDown
unconditionally; Node only implements them on TTY streams, so the first
admission under a pipe crashed the server (TypeError, verified against
the pre-refactor server). createLogger probes the stream and falls back
to plain sequential writes, keeps unchanged-state dedupe, and routes
info/warn/error through the injected stream for testability.
Room semantics rework (verified RED against the previous behavior first):
- add() is idempotent: a duplicate add no longer stacks a second
  disconnect hook and user-list entry (double approval produced two
  cinema:joined broadcasts and duplicate entries).
- remove() of a non-member is a no-op: no broadcasts, no listener changes.
- Rooms now bookkeep the exact listeners they register on a socket and
  remove only those. socket.removeAllListeners() is gone: it stripped
  every room's handlers at once, so approving an already-admitted user
  killed their active admin handlers mid-session (kick/ban stopped
  working after a stale approve of the host) and leaked ghost members.
  socket.io 4 findings documented in Room.ts: the framework only emits
  reserved events on the Socket emitter and never self-subscribes, so the
  blast radius was application state, not transport internals.
- A failed socket.join() rolls back seat, listeners, and the join
  announcement, so a failed host admission cannot brick Admins.isEmpty()
  forever.
- Approve resolves targets from the WaitingRoom only; approving someone
  who is not waiting is a no-op. Cinema-admission failure returns the
  user to the waiting room instead of leaving them roomless.
- Username release moved to a connection-scoped disconnect listener
  (rooms no longer own username state).
- Rooms/* no longer import src/index.ts: registry + services injected via
  createRooms (src/rooms.ts). The Task 4 integration harness mock of
  index.ts is deleted; tests/helpers/testApp.ts now provides the test
  wiring it was placeholder for.
src/app.ts now composes the HTTP server, Socket.IO server, room registry,
admission state, and logger; index.ts is startup wiring only (PORT,
listen, SIGINT/SIGTERM graceful shutdown). Importing domain code no
longer starts a server.

- Banned ips and active usernames moved from module-level sets into
  per-application AdmissionState (validation.ts); two applications share
  nothing (locked by an integration test: a user banned in app A
  connects fine to app B).
- HTTP fallback installed before Socket.IO attaches: GET / (and
  /healthz) answer 200 text, other non-socket.io paths get a bounded
  404. No room/user state is exposed over HTTP.
- Admission failures (e.g. join rejection) emit Connection.Rejected,
  disconnect, and release the reserved username; connection admission
  errors can no longer become unhandled rejections.
- Host reservation stays atomic across concurrent first connections
  (isEmpty check and the synchronous membership claim in Admins.add run
  with no await between them — locked by a fake-socket concurrency test
  with delayed joins).
- tests/integration/admission.test.ts covers preserved policy end to
  end: waiting-room ip rule, username rules, kick, ban (including the
  preserved localhost quirk where the ban loop scans admins only),
  readiness/404, and import-safety.
- cinema.test.ts evolved into playback.test.ts: same playback
  assertions over the REAL application (admission + approval flow), no
  vi.mock anywhere.
- testApp.ts placeholder grew into the shared test harness; a
  fakeSocket helper supports admission edge-case tests.
The approve button emitted Admin.Approve on every click; a double click
sent two admissions for the same user (server-side now idempotent, but
the duplicate emit was still wrong). The button disables itself for the
round-trip; the card it lives in is removed by the existing
WaitingRoom.Left flow once the approval lands, so the pending state
cannot outlive the list update.
socket.io invokes event handlers fire-and-forget and ignores the
returned promise, so a rejected async listener (e.g. the re-seat
join inside the approve-failure catch) surfaced as an
unhandledRejection and killed the process on Node >= 15.

Room.listen now wraps every listener in a guard that routes
rejections (and sync throws) to services.logger.error. RED/GREEN:
rooms.test.ts emits admin:approve with a failing re-seat join and
asserts the failure is logged and no unhandledRejection escapes.
hasIp was enforced only at the admission gate and onLeave deleted the
ip unconditionally, so during the approve-failure re-seat window
(remove then re-add) a same-ip peer still seated left the ip
unclaimed — a third same-ip connection could then be admitted, and
the ghost member kept hasIp true after everyone left.

ips is now a Map<string, number> refcount: increment on join,
decrement on leave, delete at zero. RED/GREEN: rooms.test.ts seats
two same-ip members, removes one, and asserts hasIp stays true until
both are gone.
If a member's socket disconnected while their admission join was
still pending, the disconnect listener removed them (broadcasting
onLeave), and the join's later rejection ran the rollback unseat a
second time — double-broadcasting Left to the room.

unseat now returns early for users who are no longer seated.
RED/GREEN: rooms.test.ts fires disconnect while a join is pending,
then rejects the join, and asserts exactly one cinema:left.
describe() JSON.stringify'd every non-string metadata item, which
turned Errors into "{}" (message/stack are not enumerable) and
THREW on circular structures — crashing the very error path that
must never fail.

Errors now log as their stack (String fallback when absent), and
stringify is wrapped with a String(item) fallback. RED/GREEN in
logging.test.ts; the approve re-seat test now also asserts the
underlying error text reaches the log.
The state rewriter moved the cursor up a hardcoded
STATE_BLOCK_LINES = 4 — wrong the moment a render spans a different
number of lines, and it also fired on the FIRST render, erasing four
lines of unrelated output (startup banner, interleaved logs).

The logger now records the height of each rendered block
(state lines + header) and only rewinds that many lines on the next
changed render; the first render writes without cursor movement.
RED/GREEN: logging.test.ts covers first render, an interleaved info
line, and blocks of differing heights.
rooms.test.ts carried a ~90-line inline FakeSocket that had drifted
from tests/helpers/fakeSocket.ts (it even lacked disconnect()). The
duplicate is gone; makeUser now maps onto
new FakeSocket(username, { address, joinBehavior }) from the helper.

The scattered `as never` socket casts (which would have silenced
passing literally anything) are replaced by asServerSocket(): the
helper's new SocketSurface interface pins down the socket surface
the server actually uses and FakeSocket now `implements` it, so the
double is compile-checked. A structural bridge to the real socket.io
type is impossible — component-emitter's on/off/emit are generically
constrained to the wire event maps with no plain-string fallback —
so the single documented widening cast remains, centralized in the
helper. Room.listen's guard also needed one targeted lint
suppression where no-misused-promises and
no-unnecessary-type-assertion are unsatisfiable together.
…t.io notes

- app.close() no longer double-closes: io.close(cb) already closes
  the http server it was constructed with, so the completion
  callback is passed straight through and awaited; idle keep-alive
  connections are dropped first when the runtime supports it.
- index.ts shutdown handles close failures (logged, exit 1) instead
  of always exiting 0, and a 5s force-exit timer guarantees a stuck
  connection cannot wedge shutdown.
- ClientEvents joins the import type line (it is type-only in
  app.ts).
- Room.ts's socket.io comment now states the facts verified against
  4.8.3: Socket extends StrictEventEmitter (component-emitter
  typing, not a plain Node EventEmitter) and the Socket constructor
  self-subscribes this.on('error', noop); the blast-radius
  conclusion stands.
- Admins.listenToBan documents the preserved loopback-ban quirk
  (getIdenticalUsers scans Admins only) pending policy review.
- Rooms/index.ts barrel deleted: nothing imported it.
Two 100ms sleeps papered over server-side completion: the username
release after a waiter's disconnect now waits for the WaitingRoom.Left
broadcast the host observes (fired by the same disconnect cleanup that
releases the name), and the stale duplicate approve is ordered behind
a cinema:select round-trip on the same socket — same-socket events are
handled in order, so the State reply proves the duplicate was fully
handled. Tests stay green and shed their timing dependence.
Flesh out the Task-1 stub: fake native media element (controllable play
promises, readyState/duration/error control, child tracking, native event
dispatch), captured command channel, real issue store, real projection
clock on an injectable virtual timeline. The only faked boundary is the
native element — everything else is production code.

First RED->GREEN slice: refused play requests report
PlaybackInteractionRequired (or stay silent for AbortError) with honest
paused state and no unhandled rejections; startPlayback is viewer-local;
admission restores volume and shows controls.
…op invalidation

Reconciliation now enforces POSITION as well as play state: continuous
snapshots (Playing/Paused/State) correct drift beyond 5s against the
PROJECTED position (the frozen-lastSeenTime rewind defect is pinned),
while seeked snapshots apply exactly at any distance. Positions clamp to
the known finite duration. Before loadedmetadata the seek defers and
re-projects on arrival, so the LATEST target wins and zombie seeks from a
superseded load or disconnect die on the load generation. A seek bumps the
op token, so an interrupted play's late rejection can never report.
Element and child-source error events (capture phase — child errors never
bubble) classify through mediaErrors into the coalescing media-playback
incident, carrying mediaErrorCode when a real code exists and staying
unknown for bare child failures. Deliberate aborts, emptied, suspend,
waiting and stalled are never fatal; buffering signals become diagnostics
only. ended never restarts playback in a loop, and a rewind seek resumes
from it. A foreign mediaId in a snapshot pauses locally, reports
MediaMismatch (reload action exposed via controller.reload), leaves the
server state untouched, and recovers when the media matches again.
Disconnect pauses synchronously (no hidden audio), hides the element,
strips controls, invalidates tokens and the revision epoch, and reports
ConnectionLost only for transport-level loss (kick/ban/deliberate close
have their own flows). Readmission restores controls without reloading a
usable element.

Trusted-emit policy decided and pinned: chromium fires UA media events
with isTrusted === true even for script-initiated play() (probed in the
browser suite), so trust is decided by ORIGIN — each programmatic
play/pause/seek reserves a marker its native event consumes, and a marker
reserved by a play() that ends up refused is handed back. Genuine native
control events emit exactly one command; disconnected hosts emit none.
Loads arm a cancellable 15s one-shot timer for the first usable frame:
SlowLoading reports once per load, superseded loads cancel via the load
generation, the bound lifts (and media incidents resolve) on
loadeddata/canplay, and nothing ever auto-reloads. retry() rebuilds the
current media and re-attempts playback through the gesture entry;
startPlayback reconciles through the projection (viewer-local only).
…roller

The controller owns behaviors; movie.ts now only grabs the #movie element
and socket, constructs the controller with real boundaries (typed command
channel, document element factory, safeStorage-backed volume preferences,
location.reload recovery), and forwards the socket events it owns. The
projection clock and revision epochs move fully into the controller.

Pin changes in nativeAudio.test.ts, both documented: the Web Audio absence
pin now scans the whole playback path (movie.ts + playback/*) instead of
movie.ts alone; the onvolumechange/writeStoredString source pins are
replaced by behavioral harness coverage (restore-on-admission,
persist-on-volumechange) plus a slim wiring pin that safeStorage is still
the persistence edge.
Playwright wiring: shared vite test server (fixture media + ?media=
allowlist via a test-only settings module that also exposes the issue
store for assertions), and per-test fixtures spawning the REAL
createApplication server via node --import tsx server/src/test-server.ts
on an ephemeral port (ready-line handshake; kill/restart on the same
port) plus a fresh chromium per test.

Cases: isTrusted design probe (UA media events are trusted for
script-initiated play, evidence for the marker policy), host boot+play
advancement, late viewer approval+sync, small exact seek (1->2s), host
pause propagation, host media switch -> viewer mismatch+pause, missing
media -> MediaUnusable without a crash, and server kill/restart ->
ConnectionLost, local pause/hide, recovery on reconnection.

Headless accommodations, all test-side and documented: muted+looped
element (audible media clocks stall at 0 in headless; 3s clips would
end-mid wait and end-of-media pauses are genuine host pauses), and a
browser per test (pages created after earlier media playback can stall
at currentTime 0 forever — a headless media-pipeline leak).
Controller (src/playback/controller.ts):
- pauseLocally() now early-returns on an already-paused element: real
  elements fire no native pause for it, so the unconditional marker
  leaked and swallowed the next GENUINE pause (admin lost a
  cinema:pause command; viewer skipped reconciliation). The opToken
  bump stays in both paths (belt-and-braces).
- document the consolidated programmatic-marker invariants next to the
  `programmatic` declaration (reserve-only-if-event-fires, reclaim on
  refusal, consume on native event, disconnect's pause unmarked,
  transition-only events).
- handleCommandRejected: collapse the identical dead branch to one
  report(InvalidServerState, rejection) call; drop the unused
  isCommandRejection import.
- extract invalidateCurrentLoad() for the opToken/loadGeneration/
  deferredSeek trio shared by ensureMediaLoaded and handleDisconnect.
- onMediaError reports through the local report() helper (detail shape
  { code } preserves mediaErrorCode extraction).
- fix the jammed statement after applyPosition's closing brace; note
  that deferred exact seeks stay exact across later continuous
  snapshots.

Harness/tests:
- FakeMediaElement.play() fires 'play' only on the paused->playing
  transition (same guard pause() has); header divergence note updated.
- playerHarness: receiveCommandRejected() helper and reportedIssues()
  (raw reportIssue inputs) for asserting rejection details.
- regression tests for the pause-marker leak (admin command + viewer
  reconcile) and for wrong-media/invalid-command rejections carrying
  their detail (PR 2 surface); drop dead issue-read code in the reload
  wiring test.

Browser test infrastructure:
- playback.spec.ts: wrap-aware drift (min(d, 3 - d)) for the looped
  3s fixture clips — kills the CI flake at the wrap boundary.
- roomServer.ts: kill the child before rejecting on readiness timeout
  (no orphan on timeout).
- playwright.config.ts: drop firefox/webkit projects (they cannot run
  with chromium-only --autoplay-policy; Task 9 wires the full matrix
  with per-browser launch options).
- move the test vite server to port 1732 so reuseExistingServer can
  never silently adopt a running dev server (fixture alias vs. real
  settings).
- testSettings.ts: console.warn on unrecognized ?media= values (names
  the bad value and the allowlist; bogus.mp4 stays allowlisted
  deliberately for the missing-media test).
- smoke.spec.ts: refresh the stale Task 6 comment.
Output naming policy: input basename with final extension replaced by
.mp4, always inside outDir (.mp4 inputs re-transcode to the same name in
a different directory). Explicit -f mp4 forces the MP4 muxer so a renamed
.mkv can never stay Matroska. describeOutputRefusal refuses clobbering an
existing output or input==output, naming both paths. Flags verified
against ffmpeg 9.0.2 (-h muxer=mp4 / -h encoder=libx264).
…derr tail

StderrTail concatenates chunks before trimming to 64KiB so diagnostics
split across chunk boundaries survive, and skips partial UTF-8 sequences
at the trim boundary. probeMedia parses ffprobe JSON into a typed
MediaProbe (fps from r_frame_rate with avg_frame_rate fallback, 0/0 ->
null), throws named ProbeErrors for malformed JSON / missing video
stream, and verifyOutputProbe enforces the mp4/h264/yuv420p/aac-stereo
postflight contract. describeSpawnFailure turns ENOENT into an
install-ffmpeg message.
checkLevel41Envelope implements the real Annex A Table A-1 constraints
(MaxMBPS 245,760 MB/s, MaxFS 8,192 MB/frame, MaxFR 68.75 fps; source
cited in the comment). Macroblock math is honest: dimensions round up to
16x16 blocks, so 2560x1440 is 14,400 MBs and rejected by MaxFS, 1080p60
by MaxMBPS, 4K by MaxFS at any rate. Unknown/zero fps is rejected as
unvalidated; DPB/reference-frame limits are left to libx264 (-level) and
documented as approximated. Rejections list measured values and limits.
doTranscode(input, outDir) now: refuses a clobbered output (naming both
paths), preflight-probes the input, checks the level 4.1 envelope before
any encoding, encodes into the converter-owned .tmp-<name>.mp4 so -y can
only ever clobber a stale temp, accumulates stderr across chunk
boundaries into a 64KiB tail, postflight-verifies mp4/h264/yuv420p/
aac-stereo (audio-less inputs stay audio-less), and promotes via an
explicit rename only after verification. Every failure path deletes the
temp file; errors carry the operation name and bounded stderr tail.
Progress moves to an injectable sink (pipe-safe by construction).
… exit

main.ts is now importable (import.meta.main guard) and drives the batch:
collision check for every derived output before any encoding starts,
serial conversion that continues past failures, per-file success/error
lines, and a final 'n converted, m failed' summary with process.exitCode
set when anything failed. Progress rendering is pipe-safe: plain \r +
padding on a TTY, complete silence when piped (moveCursor is gone).
Unit tests cover the pure pieces (formatProgressLine, renderer,
summarizeRun, collectInputFiles).
Generates lavfi fixtures into a mkdtemp'd os.tmpdir and drives the real
doTranscode path: mkv→verified mp4 (container/codec/pix_fmt/channels
probed independently, no temp leftovers), 4K rejection by the level 4.1
envelope with no output file, nonzero ffmpeg exit reported with stderr
tail and temp cleaned (temp path sabotaged with a directory), refusal to
overwrite a pre-existing output, and a clear probe error for non-media
input. Missing binaries fail the suite with an instructive error — no
skipIf. test:integration now runs with a 120s per-test timeout.
…ion guard

C1 (critical): cover-art streams defeated the level-4.1 envelope in both
directions — cover-first files were falsely rejected (envelope measured the
tiny high-fps cover) or falsely promoted (cover passed while ffmpeg encoded
an out-of-envelope feature; x264 only warns and exits 0).

- probeMedia: selectVideoStream mirrors ffmpeg's default selection — skip
  disposition.attached_pic===1 streams and still-image cover codecs
  (mjpeg/png/bmp/tiff), pick max pixel count, tie-break lowest index.
  Audio policy made explicit: first audio stream by index (used only for
  presence/display, where ffmpeg's most-channels rule is equivalent).
- verifyOutputProbe: output video dimensions must match the SELECTED input
  stream within 16px (macroblock padding drift), so selection drift can
  never promote out-of-envelope output.
- Integration regressions: cover-first MKV + 4K feature now rejected
  (32,400 MBs); cover-first MKV + 1080p feature now accepted with the
  feature's dimensions in the output.

I1: ffmpegArgs comment no longer claims -level enforces MaxFS/MaxMBPS
(warnings only); doTranscode scans retained stderr for '> level limit'
and surfaces x264 warnings on success (findX264LevelWarnings).

I2: preflight durationSeconds threaded onto every TranscodeProgress
emission; TTY percent display works in production.

I3: parseProgressReport replaced by stateful ProgressParser that buffers
on report boundaries (progress= terminator), immune to mid-key/mid-value
chunk splits; flush() emits a trailing unterminated report.

M1: StderrTail.push identical-ternary removed (isBuffer fast-path).
M2: deriveOutputPath dotfile/trailing-dot edges pinned in tests + docs;
collectInputFiles matches '.<ext>' case-insensitively, never a bare suffix.
M3: clock() carries rounding into minutes (no more 00:60.0).
M4: prettier (repo config, single quotes) applied to the six src files.
M5: collision-check sites cross-reference each other (TOCTOU + API safety).
M6: TODO(levels) notes the hardcoded 4.1 strings for a future LEVELS table.
M7: case-insensitive output collisions named up front in the batch pre-check.
M8: maxDpbMacroblocks kept as documented informational-only constant.
…view

The client served production via 'vite preview', whose static handler
(Vite 8.0.16) breaks the media-serving HTTP contract. Proven by the new
launcher-injected contract suite (tests/http/mediaServing.test.ts) run
against 'vite preview' over a real socket on a fixture dist (RED run,
2026-10-16, 8 of 13 contracts failed):

- Range: bytes=0-0 -> 206 with the ENTIRE 29922-byte fixture (expected 1)
- Range: bytes=-128 -> 206 with the FIRST 129 bytes (expected final 128)
- GET /data/nope.mp4 -> 200 with SPA index.html instead of a real 404
- /data/ 200 (no 404/no-listing), raw /../package.json traversal 200,
  /.env and symlink-escape requests served, no production cache headers
  (full output preserved in tests/http/mediaServing.test.ts header)

serve.mjs (node http + serve-handler@6.1.7, exact pin) now backs 'start':

- correct ranges via range-parser (0-0 -> 1 byte, -128 -> final 128,
  416 + 'bytes */total' when unsatisfiable), real 404s (no SPA fallback)
- directoryListing/symlinks/etag off (etag would SHA-1 whole movies),
  cleanUrls on so / serves index.html while /data/ 404s
- dotfiles (.env, .git) blocked before the handler (serve-handler only
  hides them from listings)
- cache policy: /** no-cache,must-revalidate; /assets/** immutable 1y;
  /data/** max-age=0,must-revalidate + Last-Modified
- PORT (1730) / HOST (0.0.0.0, LAN parity with 'vite preview --host')
  env wiring, EADDRINUSE + missing-dist fail-clear errors, SIGINT/SIGTERM
  graceful shutdown

Typecheck: tsconfig.node.json checks serve.mjs with checkJs + explicit
@types/node; main tsconfig allows importing it from the tests. ESLint
lints serve.mjs type-aware (two JSDoc-blind rules disabled for it,
documented in eslint.config.js). The suite defaults to serve.mjs and
stays green; HTTP_CONTRACT_TARGET=vite-preview replays the RED evidence.
- reword /data cache comment: handler ignores If-Modified-Since, so
  conditional 304s are a known deferred gap (media re-downloads on
  reuse today); align the etag:false and test comments with it
- killTree: settle when the child already died (including by signal —
  exitCode stays null) and from the SIGKILL timer itself, so afterAll
  can never hang on a dead child
- pin probe-verified behaviors: nested /assets/<dir>/<file> gets the
  immutable rule, /data/red.mp4?t=1 serves 200 with the media cache
  rule, /index.html 301s (two-hop chain /index.html -> /index -> /)
- detach the pre-listen error listener once listening succeeds so
  post-listen server errors are not silently swallowed
- double SIGINT/SIGTERM during shutdown force-exits(1) instead of
  re-entering the close() path; note keep-alive client can delay
  shutdown (acceptable for a LAN app)
- document multi-range truncation-to-first-range gap at the
  serve-handler delegation point (browsers never send multi-range)
… playback suite extensions

Re-add firefox and webkit Playwright projects with per-engine launch
options in one place (tests/browser/engineLaunch.ts): chromium keeps
--autoplay-policy=no-user-gesture-required, firefox gets autoplay prefs
via firefoxUserPrefs (media.autoplay.default=0), webkit needs none (its
play() is not gesture-blocked; its real limit is codecs).

webkit codec reality, verified on WebKit 26.6/macOS: the bundled build
has no H.264/AAC decoders and stalls media at HAVE_METADATA forever
(canPlayType answers "probably" anyway); VP8/VP9 WebM twins stall the
same way, so there is no codec to switch to. A cached per-engine decode
probe (muted <video> + event-driven wait) now gates the decode-dependent
tests: they run wherever the engine actually decodes (chromium, firefox,
Linux webkit via system GStreamer) and skip with a documented reason
where it does not (macOS webkit). Decode-independent tests — the
trusted-events probe, missing-media 404 classification, smoke — run on
every engine.

Suite extensions in the existing structure:
- red -> green -> blue: viewer follows two host media switches via the
  documented mismatch + reload + re-approval flow (a select resets the
  room paused at 0; the host then plays and the viewer resyncs)
- end of media: clip runs out for real (no loop) — host ends paused at
  the boundary (genuine native pause commands the room), a deliberately
  trailing viewer pauses NOT-ended (the pause provably came from the
  room), no restart loop, no failure issues
- truncated media: 40% prefix of red.mp4 served at test time classifies
  into the media-network/decode/unusable family without crashing

Headless accommodations generalized per engine (muted+loop everywhere;
ended test opts out of loop); host waits use lower bounds only — a
windowed range aliases with the poll cadence around the 3s clip cycle
and can be skipped forever. test:browser no longer pins --project=chromium.
…ival)

Docker validation of the Linux CI image (playwright v1.63.0-noble)
refined the webkit story into two distinct, verified limitations:

- macOS WebKit cannot decode H.264/AAC at all (previous commit).
- Linux WebKit DOES decode (system GStreamer via install-deps) and runs
  10 of 12 playback tests — but its media clock stalls permanently after
  seeking a playing element (both seek-choreography tests froze at the
  rewind), and it never fires an error event for truncated media (silent
  fetch stall instead of a classifyable failure).

The decode probe becomes a cached two-part capability probe:
- decodableMedia — tests needing real playback (unchanged set)
- seekableMedia — tests whose choreography seeks a playing element
  (precise-seek and end-of-media tests)

The truncated-media test asserts the classification family only on
engines that report the failure (chromium/firefox); on WebKit it pins
the honest part — no crash, element stays queryable — with the verified
behavior documented inline.

Also: the precise-seek test's 'host near 1s' windowed wait becomes a
lower bound (windowed waits alias with the poll cadence around a 3s
looping clip — same class as the ended-test fix in the previous commit).

Linux matrix evidence (playwright noble container): chromium 12/12,
firefox 12/12, webkit 10 passed + 2 capability skips, 0 failures.
… matrix)

Greenfield .github/workflows/checks.yml on every push and pull_request:

- client-server: pnpm workspace install (lockfile-frozen), fixture
  bootstrap (ffmpeg via apt — the http contract suite serves red.mp4),
  client check-all + vitest + build, server check-all + vitest + build.
- converter: bun (oven-sh/setup-bun@v2), lockfile-frozen install,
  check-all, unit tests, and the real-ffmpeg integration suite (apt
  ffmpeg; missing ffmpeg must fail honestly, never skip).
- browser: workspace install + fixtures, playwright install --with-deps
  chromium firefox webkit (browsers cached via actions/cache keyed on
  the lockfile), then test:browser across all three projects.

Actions pinned to current majors (checkout@v5, pnpm/action-setup@v5,
setup-node@v5 with pnpm cache on Node 22, setup-bun@v2, cache@v4);
permissions are read-only (contents: read), no secrets anywhere, and a
concurrency group cancels superseded runs.

Add a minimal root package.json carrying packageManager (pnpm@11.8.0 —
the version the lockfile is produced with) for pnpm/action-setup, which
adds the empty root importer to pnpm-lock.yaml. Gitignore the local
.pnpm-store/ index that root installs create.

Validation: actionlint clean; every job's command sequence dry-run
locally; the browser job additionally replayed end-to-end inside the
playwright v1.63.0-noble Linux container (34 passed / 2 capability
skips / 0 failed).
…/deploy notes

docs/playback-troubleshooting.md (new, operator-facing): how to read the
diagnostics export (what it contains, its local-only privacy contract,
how a user shares it today — the UI button ships in PR 2), the issue-code
table with proven causes vs unproven assumptions (no extension blame
without the EXTENSION_ORIGIN marker, no codec blame without the
direct-media check), the direct-media comparison procedure and what each
outcome means, the deliberate serve.mjs gaps (no 304 revalidation,
multi-range truncation), converter envelope rejections (what the error
means, what to do), the explicitly PENDING manual device matrix (Safari,
Arc regular/private, Windows Chrome/Firefox regular/private, Zen/Linux),
and a 'what we do NOT claim' section (engine tests != the original
incidents).

README: testing section gains the fixture bootstrap, the three-engine
browser matrix with its honest capability story, the http contract
suite, and CI; production section gains the documented serving gaps with
a pointer to the troubleshooting doc; operational notes for volume-as-
set (no hidden boost), coordinated client+server deploys (wire protocol
moves lockstep), and one distinct media URL per movie.
…e, CI polish

Code-review fixes for the browser playback suite:

- Probe visibility (CI): the capability probe now logs one summary
  line per engine on cache miss ('[capability-probe] <engine>:
  decodes=... seeks=... reportsTruncation=...') so the list reporter's
  stdout carries skip evidence; added the html reporter (open: never)
  and an actions/upload-artifact@v7 upload of client/playwright-report/
  with if: always() in the browser CI job (v7 verified as the current
  major).
- Truncation gating is probe-based, not engine-NAME based: new
  reportsTruncation capability, probed over HTTP (not blob — WebKit's
  stall is fetcher-side) by playing a truncated-probe.mp4 prefix and
  watching for a media error within 6s; decode-failed engines skip the
  truncation probe entirely (they cannot run the test anyway). The
  truncation logic is extracted into writeTruncatedFixture, shared
  with the test; the probe fixture is removed afterwards.
- Probe rejection no longer poisons the cache: the rejected promise is
  deleted so later tests re-probe, and the error is wrapped with
  'capability probe failed for <engine>' context.
- engineLaunch.ts: dead headless param removed; ENGINE_NAMES const
  array is the single source of the engine set (union derived from it;
  playwright.config.ts projects table and the playback launcher both
  consume it); unknown engine names now throw instead of silently
  falling back to chromium.
- Windowed staging predicates in the end-of-media test documented
  (first poll sample is immediate after the seek, so lock-step
  aliasing cannot skip the window from the start).
- CI: push trigger restricted to main (PRs already covered, no more
  double runs); ms-playwright cache keyed on the resolved Playwright
  package version instead of the whole lockfile (restore-key prefix
  fallback kept); client tests run via 'pnpm --dir client run test'.
- Root package.json declares license: MIT; playback-troubleshooting.md
  states plainly there is no in-app export button yet (forthcoming
  release) and what to collect manually.
…red types

- report.ts: gate the media= field on shared isMediaId (wire validation,
  via the shared barrel) instead of isSafeToken, so normalized path
  identities like movie.mp4 and films/a.mp4 actually render, as
  docs/playback-troubleshooting.md promises. isSafeToken still gates
  every other rendered field.
- issues.ts: rename the store's 64-char sanitization bound to
  MAX_ISSUE_MEDIA_ID_LENGTH so it no longer collides conceptually with
  the wire MAX_MEDIA_ID_LENGTH (255) in shared/PlaybackState.ts.
- README: add this PR's events to the shared-types lists
  (cinema:select client->server; cinema:state and
  cinema:command-rejected server->client).

Tests: RED->GREEN for media= rendering (dots + nested paths), extended
hostile-id rejection (encoded traversal, ../ segment, overlong).
…pecheck/build

The production typecheck and build statically import client/settings.json
(client/src/config.ts), but that file is gitignored user-local config, so
CI never has it: tsc died with TS2307 Cannot find module '../settings.json'.
Copy the tracked, shape-compatible settings.example.json in CI before any
client step that resolves the import. Verified locally: with the copy in
place, check-all, build, and the full client (257) + server (117) suites
pass; the remaining client-server job steps were run locally and pass.
Test files, test-only configs (playwright/vitest/vite.test), the test
bootstrap server, and the CI workflow move to a stacked PR so this PR
reviews production code only. No content changes here — files are
restored to their main (absent) state; the stacked PR reinstates them
byte-identically.
@PolarWolf314 PolarWolf314 mentioned this pull request Oct 17, 2026
Closed
@NachoToast

Copy link
Copy Markdown
Owner

image

@PolarWolf314
PolarWolf314 deleted the fix/playback-reliability branch October 17, 2026 10:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants