Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2c52077b1d | ||
|
|
6dfc6b259a | ||
|
|
42e7d86ec4 | ||
|
|
4e451bb534 | ||
|
|
889289286b | ||
|
|
8500da1a42 | ||
|
|
88e15e3e12 | ||
|
|
c9f33ae6a4 | ||
|
|
a93cee9241 | ||
|
|
4996727ca9 | ||
|
|
e3cdb12967 | ||
|
|
2d21f092d5 | ||
|
|
ebf9a99b80 | ||
|
|
38dd1129e5 | ||
|
|
4c9361d020 | ||
|
|
b9dab56379 |
@@ -61,6 +61,32 @@ jobs:
|
||||
bunx svelte-kit sync
|
||||
bun run test
|
||||
|
||||
# CLAUDE.md has required `cargo fmt` + `cargo clippy` before every commit
|
||||
# for as long as the rule has existed, but nothing in CI checked either,
|
||||
# so the requirement rested entirely on memory. Both components are baked
|
||||
# into the builder image (Dockerfile.builder: `rustup component add
|
||||
# rustfmt clippy`) — nothing is installed at job time.
|
||||
- name: Check Rust formatting
|
||||
run: |
|
||||
cd src-tauri
|
||||
cargo fmt --all -- --check
|
||||
|
||||
# ⚠️ Advisory for now — clippy warnings do NOT fail this job yet.
|
||||
#
|
||||
# The tree carries ~51 pre-existing warnings; adding `-D warnings` today
|
||||
# would paint CI red on unrelated work. A compile *error* still fails the
|
||||
# step, so this is not a no-op: it stops new breakage and surfaces the
|
||||
# backlog in every run.
|
||||
#
|
||||
# TODO: once the existing warnings are cleared, tighten this to
|
||||
# cargo clippy --all-targets -- -D warnings
|
||||
# Flip that flag — do not delete the step. Track progress with
|
||||
# `cd src-tauri && cargo clippy --all-targets 2>&1 | grep -c '^warning'`.
|
||||
- name: Run clippy (advisory)
|
||||
run: |
|
||||
cd src-tauri
|
||||
cargo clippy --all-targets
|
||||
|
||||
- name: Run Rust tests
|
||||
run: |
|
||||
cd src-tauri
|
||||
|
||||
@@ -54,6 +54,22 @@ jobs:
|
||||
bun run test --run
|
||||
continue-on-error: false
|
||||
|
||||
# Same gate as build-and-test.yml. A release must not ship from a tree
|
||||
# that would fail the per-commit checks. rustfmt/clippy come from the
|
||||
# builder image; nothing is installed here.
|
||||
- name: Check Rust formatting
|
||||
run: |
|
||||
cd src-tauri
|
||||
cargo fmt --all -- --check
|
||||
continue-on-error: false
|
||||
|
||||
# Advisory until the ~51 pre-existing warnings are cleared; see the longer
|
||||
# note in build-and-test.yml. Tighten both to `-- -D warnings` together.
|
||||
- name: Run clippy (advisory)
|
||||
run: |
|
||||
cd src-tauri
|
||||
cargo clippy --all-targets
|
||||
|
||||
- name: Run Rust tests
|
||||
run: bun run test:rust
|
||||
continue-on-error: false
|
||||
|
||||
@@ -81,8 +81,20 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check minimum threshold
|
||||
MIN_THRESHOLD=50
|
||||
# Minimum coverage. RATCHET POLICY: this number only ever goes UP.
|
||||
#
|
||||
# It sits a few points under the coverage actually achieved, so a real
|
||||
# regression trips it. It was 50 while true coverage was 86%, which
|
||||
# meant nearly half the matrix could rot before CI said a word — a
|
||||
# gate that cannot fail is not a gate.
|
||||
#
|
||||
# When coverage rises durably, raise this to just under the new figure
|
||||
# (`bun run traces:coverage` prints it). Never lower it to make a red
|
||||
# build pass — add the missing TRACES comments instead.
|
||||
#
|
||||
# Keep in sync with MIN_COVERAGE_PERCENT in scripts/extract-traces.ts;
|
||||
# scripts/extract-traces.test.ts fails if the two drift apart.
|
||||
MIN_THRESHOLD=82
|
||||
if [ "$COVERAGE" -lt "$MIN_THRESHOLD" ]; then
|
||||
echo "❌ ERROR: Coverage ($COVERAGE%) is below minimum threshold ($MIN_THRESHOLD%)"
|
||||
exit 1
|
||||
@@ -90,6 +102,15 @@ jobs:
|
||||
|
||||
echo "✅ Coverage is acceptable ($COVERAGE% >= $MIN_THRESHOLD%)"
|
||||
|
||||
# Every ID named by a TRACES comment must be defined as a table row in
|
||||
# docs/requirements.md. The extractor used to accept any well-formed ID
|
||||
# silently, so a typo or a rename that missed a call site passed CI
|
||||
# unnoticed (DR-189 and UT-188 lived in three source files, defined
|
||||
# nowhere, for months). This covers UT/IT too, which the coverage
|
||||
# orphan list above deliberately ignores.
|
||||
- name: Validate requirement IDs
|
||||
run: bun run traces:validate
|
||||
|
||||
- name: Check modified files
|
||||
if: github.event_name == 'pull_request'
|
||||
run: |
|
||||
|
||||
@@ -9,6 +9,76 @@ generated trace matrix lives in [docs/traceability.md](docs/traceability.md).
|
||||
For how long each fixed defect had been shipping before it was found, see
|
||||
[docs/defect-windows.md](docs/defect-windows.md).
|
||||
|
||||
## v0.8.0
|
||||
|
||||
A security and correctness release, from an audit of the codebase against its own
|
||||
requirements and against current Android/Tauri practice. Most of it is invisible
|
||||
in use; three things change behaviour you can see, listed first.
|
||||
|
||||
### ✨ Changes
|
||||
|
||||
- **The app no longer backs its data up to your Google account.** It never
|
||||
should have: `allowBackup` was on by default, which sent the library catalogue
|
||||
and watch history off the device — and the credentials went with it in a form
|
||||
that could never be read again, because they are encrypted under an Android
|
||||
Keystore key and Keystore keys are never backed up. Restoring onto a new phone
|
||||
therefore produced ciphertext with no key: an authentication failure with no
|
||||
explanation. Backup is now off, for device-to-device transfer as well as cloud
|
||||
(a separate channel with the identical failure), and an unreadable credential
|
||||
blob is now treated as "logged out" rather than an error, so the next sign-in
|
||||
repairs it. (UR-012 → DR-135)
|
||||
|
||||
- **The app no longer offers itself as an Android TV app.** (This is about the
|
||||
app icon on a TV device's home screen — your TV shows library is untouched.)
|
||||
It advertised a leanback launcher entry without any of what makes a TV app work — no D-pad focus model,
|
||||
no banner, and a missing touchscreen declaration that fails Play's TV
|
||||
validation. Launching it on a TV would have landed you in a UI you could not
|
||||
navigate. It can be re-declared when TV support is actually built.
|
||||
|
||||
- **Lockscreen skip scrubs a film instead of leaving it.** While a video's audio
|
||||
plays in the background, the skip buttons jump 30 seconds forward and 10
|
||||
seconds back, rather than advancing to the next episode. There is no "next
|
||||
track" inside a film, and pressing skip to re-hear a line should not eject you
|
||||
from what you are watching. Music is unchanged: skip still moves through the
|
||||
queue. (UR-040, UR-006 → DR-201)
|
||||
|
||||
### 🔒 Security
|
||||
|
||||
- **The webview now runs under a Content-Security-Policy.** It had none, so any
|
||||
script reaching the web layer inherited the full IPC surface. `script-src` is
|
||||
now `'self'` with no inline or eval, and plugins and frames are refused
|
||||
outright. (UR-071 → DR-198)
|
||||
|
||||
- **The webview stops undoing the network security config.** It set a blanket
|
||||
cleartext opt-in by hand, along with file and content access it never used —
|
||||
defeating the config that exists to block exactly that, and whose own comment
|
||||
warned against it. (UR-071 → DR-199)
|
||||
|
||||
- **The asset protocol no longer reaches the database or the credential store.**
|
||||
Its scope was the whole app data directory; it is now the one subdirectory it
|
||||
serves. (UR-012, UR-071 → DR-198)
|
||||
|
||||
### 🐛 Fixes
|
||||
|
||||
- **A credential store that could not be read is now recoverable.** The decrypt
|
||||
failure surfaced as a hard error rather than a logged-out state, so the app got
|
||||
stuck instead of offering the login screen. (UR-012 → DR-135)
|
||||
|
||||
### 🔧 Internal
|
||||
|
||||
- CI now enforces the checks the contributor rules already required —
|
||||
`cargo fmt --check` and clippy — neither of which had ever run there. The
|
||||
traceability gate was also raised from 50% to 82%, a floor low enough that half
|
||||
the matrix could rot before it fired, and a new check fails the build on a
|
||||
requirement ID that no longer exists.
|
||||
- Twelve requirements marked "Done" carried no implementation trace at all;
|
||||
they are now tagged, and stale integration requirements that named a backend
|
||||
never built have been re-scoped to the ones that actually deliver them.
|
||||
Coverage moved 86% → 90%.
|
||||
- The Rust lint backlog is cleared (51 warnings → 0), and a flaky test that
|
||||
intermittently reddened CI is fixed — it was paying a cold module-transform
|
||||
cost inside a test body, not waiting on a timer.
|
||||
|
||||
## v0.7.0
|
||||
|
||||
### ✨ Changes
|
||||
|
||||
@@ -101,14 +101,22 @@ Tooling:
|
||||
bun run traces # extract traces (default format)
|
||||
bun run traces:json # JSON — e.g. | jq '.byType' or '.requirements."UR-005"'
|
||||
bun run traces:markdown # regenerate docs/traceability.md
|
||||
bun run traces:coverage # coverage gate — exits non-zero below the threshold
|
||||
bun run traces:validate # dangling-ID gate — every traced ID must be defined
|
||||
git diff --name-only | xargs grep -L "TRACES:" # find untraced changed files
|
||||
```
|
||||
|
||||
Every ID a `TRACES:` comment names must exist as a table row in
|
||||
`docs/requirements.md` — `traces:validate` fails otherwise, so a typo or a
|
||||
rename that missed a call site can no longer pass silently.
|
||||
|
||||
**CI is Gitea Actions** (`.gitea/workflows/`, remote `gitea.tourolle.paris`), not
|
||||
GitHub. `traceability-check.yml` fails the build if coverage drops below
|
||||
**50%** (`MIN_THRESHOLD`); `build-and-test.yml` runs frontend + Rust tests and an
|
||||
Android `cargo check`. See [docs/traceability-ci.md](docs/traceability-ci.md) and
|
||||
[docs/traces-quick-ref.md](docs/traces-quick-ref.md).
|
||||
**82%** (`MIN_THRESHOLD`, a *ratchet* — raise it as coverage climbs, never lower
|
||||
it to make a build pass) or if any traced ID is undefined; `build-and-test.yml`
|
||||
runs frontend + Rust tests, `cargo fmt --check`, an advisory `cargo clippy`, and
|
||||
an Android `cargo check`. See [docs/traceability-ci.md](docs/traceability-ci.md)
|
||||
and [docs/traces-quick-ref.md](docs/traces-quick-ref.md).
|
||||
|
||||
### Traces drive release notes
|
||||
|
||||
|
||||
@@ -50,6 +50,68 @@ pub struct EncryptedFileStorage; // AES-256-GCM fallback
|
||||
| Certificate Validation | System CA store (configurable for self-signed) |
|
||||
| Token Transmission | Bearer token in `Authorization` header only |
|
||||
| Token Refresh | Handled by Jellyfin server (long-lived tokens) |
|
||||
| Android cleartext | `res/xml/network_security_config.xml` blocks cleartext everywhere except `127.0.0.1` (the loopback media server, DR-137/DR-138). The manifest's `usesCleartextTraffic` is ignored once the config is present, so the config is the single authority |
|
||||
| Android WebView | `mixedContentMode = COMPATIBILITY` with `allowFileAccess`/`allowContentAccess` both `false` (DR-199). These are the second half of the cleartext policy: `ALWAYS_ALLOW` re-opened by hand what the network security config closes. Change the two together |
|
||||
|
||||
## Webview Content Security Policy
|
||||
|
||||
`app.security.csp` in `tauri.conf.json` (TRACES: UR-012, UR-071 | DR-198). It was
|
||||
`null` — CSP disabled — which meant any script that reached the web layer
|
||||
inherited the full IPC surface. Tauri computes the header from this value when it
|
||||
serves the embedded HTML, injecting a nonce for SvelteKit's inline bootstrap
|
||||
script, so `script-src` needs no `'unsafe-inline'`.
|
||||
|
||||
```
|
||||
default-src 'self';
|
||||
script-src 'self';
|
||||
style-src 'self' 'unsafe-inline';
|
||||
font-src 'self' data:;
|
||||
img-src 'self' data: blob: asset: http://asset.localhost http: https:;
|
||||
media-src 'self' blob: asset: http://asset.localhost http://127.0.0.1:* http: https:;
|
||||
connect-src 'self' ipc: http://ipc.localhost http: https:;
|
||||
worker-src 'self' blob:;
|
||||
object-src 'none'; frame-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'
|
||||
```
|
||||
|
||||
| Directive | Why |
|
||||
|-----------|-----|
|
||||
| `default-src 'self'` | Everything not named below is same-origin only. |
|
||||
| `script-src 'self'` | The genuinely restrictive half. Bundled JS only; Tauri's build-time nonce covers the one inline `<script>` in `index.html`. Adding `'unsafe-inline'` here would silently do nothing anyway — a nonce in a directive voids it. |
|
||||
| `style-src 'self' 'unsafe-inline'` | Svelte compiles `style="…"` attributes into markup, including `app.html`'s `display: contents` wrapper, and CSP treats a style *attribute* as inline. Safe only while no `<style>` **element** survives into `index.html`: Tauri would nonce it, and the nonce would then void `'unsafe-inline'`. The production build extracts all CSS to files, so it currently has none. |
|
||||
| `img-src` | Thumbnails come from two places: the asset protocol (`asset://localhost/…` on Linux/macOS, `http://asset.localhost/…` on Windows/Android — the same protocol, named differently by `convertFileSrc`) and, on a cache miss, straight from the Jellyfin server. `data:`/`blob:` cover inline and generated images. |
|
||||
| `media-src` | `<video>`/`<audio>` sources: HLS transcodes and progressive streams from the server, the token-guarded loopback media server on `http://127.0.0.1:<random port>` (DR-137), and `blob:` for the MSE object URL hls.js attaches. |
|
||||
| `connect-src` | `ipc:` / `http://ipc.localhost` is Tauri's `invoke` transport (custom scheme on Linux/macOS, `http` host on Windows/Android) — without it every command is blocked. `http:`/`https:` is hls.js fetching manifests and segments; ordinary API traffic goes through Rust and is not subject to CSP. |
|
||||
| `worker-src 'self' blob:` | hls.js runs its demuxer in a worker built from a blob (`enableWorker: true`). Without `blob:` it falls back to main-thread demuxing — playback survives but costs more CPU. |
|
||||
| `object-src`, `frame-src` = `'none'` | No plugins, no iframes; both are classic injection sinks. |
|
||||
| `base-uri 'self'`, `form-action 'self'`, `frame-ancestors 'none'` | Block `<base>` hijacking, form exfiltration and framing. `frame-ancestors` is only honoured when the policy is delivered as a header, which is platform-dependent; it is harmless where it is not. |
|
||||
|
||||
**`img-src`/`media-src`/`connect-src` are deliberately permissive.** The Jellyfin
|
||||
origin is typed in by the user at run time and is routinely plain `http` on a
|
||||
LAN, so it cannot be enumerated at build time. `http: https:` is a wide grant for
|
||||
*data* — but it still bars `file:`, `filesystem:` and scripting schemes, and it
|
||||
does not touch `script-src`, which is where an injected origin would actually
|
||||
hurt. A run-time policy naming the server exactly was considered and rejected:
|
||||
Tauri derives the header from immutable config at the moment it serves the HTML,
|
||||
so it would mean rebuilding the config and reloading the webview whenever the
|
||||
user adds or switches a server, to constrain a destination the user chooses
|
||||
anyway.
|
||||
|
||||
`devCsp` mirrors the policy with `'unsafe-inline' 'unsafe-eval'` on `script-src`
|
||||
and `ws:`/`wss:` on `connect-src`, because the Vite dev server injects styles and
|
||||
code and drives HMR over a websocket. It applies only to `tauri dev`.
|
||||
|
||||
### Asset protocol scope
|
||||
|
||||
`app.security.assetProtocol.scope` is `$APPDATA/thumbnails/**` — not the storage
|
||||
root. `imageCache.ts` is the only `convertFileSrc` caller left in the frontend:
|
||||
downloaded media moved to the loopback media server in DR-137, and downloaded
|
||||
audio is opened by MPV/ExoPlayer directly from its path. The old `$APPDATA/**`
|
||||
grant let the webview read the SQLite database and the encrypted-token fallback
|
||||
file alongside the thumbnails it actually needs.
|
||||
|
||||
If a new feature hands the webview a local file, widen this scope to that
|
||||
subdirectory specifically; a path outside it resolves to nothing and the webview
|
||||
reports `NETWORK_NO_SOURCE` (which is exactly how DR-134's failure presented).
|
||||
|
||||
## Local Data Protection
|
||||
|
||||
@@ -67,3 +129,4 @@ pub struct EncryptedFileStorage; // AES-256-GCM fallback
|
||||
3. **Logout Cleanup**: Token deletion from secure storage on logout
|
||||
4. **No Token Logging**: Tokens are never written to logs or debug output
|
||||
5. **IPC Security**: Tauri's IPC uses structured commands, not arbitrary code execution
|
||||
6. **Webview Containment**: A restrictive `script-src` keeps injected script off the IPC surface; the asset protocol is scoped to the thumbnail cache only (see above)
|
||||
|
||||
@@ -0,0 +1,532 @@
|
||||
# JellyTau Codebase Audit
|
||||
|
||||
**Date:** 2026-08-16 · **Version:** v0.6.0 · **Commit:** `be907b49` (master)
|
||||
|
||||
A review of the Rust/Svelte/Android codebase against its own requirements matrix
|
||||
and against current Android and Tauri v2 platform practice. Every finding was
|
||||
verified by running the project's own tooling or reading the code it points at —
|
||||
nothing here is inferred from documentation alone.
|
||||
|
||||
**Scale:** 55,835 LOC Rust · 50,490 LOC TS/Svelte · 530 requirements · 824 traces
|
||||
|
||||
| Severity | Count |
|
||||
|----------|-------|
|
||||
| High | 5 |
|
||||
| Medium | 9 |
|
||||
| Low | 6 |
|
||||
| Tests passing | 1,719 |
|
||||
| Untraced requirements | 86 |
|
||||
| Traceability coverage | 86% (285/330) |
|
||||
|
||||
> **Revisions, 2026-08-16.** Three rankings changed after device testing and
|
||||
> platform research, all documented in place:
|
||||
> - **B1 High → Low.** The predicted impact was refuted on a physical Android 16
|
||||
> device. The residual risk turned out to be a different, narrower one.
|
||||
> - **B7 Low → Medium, re-framed.** The original reading of predictive back was
|
||||
> backwards: at targetSdk 36 it is already enabled, not merely un-opted-into.
|
||||
> - **B8 added (Medium).** Android 16 Local Network Protections versus a
|
||||
> LAN-hosted Jellyfin server.
|
||||
> - **D3 Medium → Low.** The "820 unwraps" figure was a measurement error; the
|
||||
> real number is 19, and none are in command handlers.
|
||||
> - **B1's stated mechanism was wrong** even though its conclusion held. FGS
|
||||
> notifications are *not* exempt from `POST_NOTIFICATIONS`; media-session
|
||||
> notifications are. See B1 — the distinction changes what the fix should be.
|
||||
>
|
||||
> Original ranking was 6 High / 8 Medium / 5 Low.
|
||||
|
||||
**Verified by running:** `bun run check` · `bun run test` · `cargo test` ·
|
||||
`cargo clippy --all-targets` · `bun run check:boundary` · `bun run traces:json`
|
||||
|
||||
**Device-verified (2026-08-16):** B1 and B2 were checked against a physical HONOR
|
||||
ROD2-W09 running Android 16 (SDK 36) with the shipped app installed. B2 was
|
||||
confirmed; B1 was refuted and downgraded.
|
||||
|
||||
**Not covered:** the e2e suite (`test:e2e` is not wired into CI and was not run),
|
||||
Windows and Arch packaging paths, and the docs-site build. B3, C1 and C2 still
|
||||
need a device/desktop playback pass.
|
||||
|
||||
---
|
||||
|
||||
## A. Requirements versus code
|
||||
|
||||
The traceability matrix is the project's own claim about what is built. Of 530
|
||||
defined requirement IDs, 86 carry no `TRACES:` tag anywhere in the tree. Most of
|
||||
those gaps are documentation debt rather than missing features — which is
|
||||
precisely the problem, because it makes the matrix unreliable as evidence.
|
||||
|
||||
### A1 · High · Twelve requirements are marked "Done" but have zero traces
|
||||
|
||||
`UR-006` (lockscreen/BLE control), `UR-037` (video library presentation),
|
||||
`IR-006` (Android MediaSession), `IR-008` (audio focus), `IR-022` (person/cast
|
||||
API), `IR-024` (home-screen API) and six Jellyfin API requirements (`JA-006`,
|
||||
`JA-009`, `JA-013`, `JA-014`, `JA-015`, `JA-018`) all claim completion with
|
||||
nothing pointing at an implementation.
|
||||
|
||||
These features demonstrably work — lockscreen control, Next Up, favourites are
|
||||
all shipped. The code is there; the tags are not. That means the matrix currently
|
||||
over-reports on exactly the requirements a reviewer would most want to verify,
|
||||
and a regression in any of them would leave no trace to follow.
|
||||
|
||||
**Fix:** Tag the existing implementations. Highest value per keystroke in the
|
||||
whole audit: six of the twelve are single Jellyfin API call sites.
|
||||
|
||||
### A2 · Medium · Requirement statuses contradict each other across layers
|
||||
|
||||
`UR-020` (subtitle selection) and `UR-021` (audio track selection) are marked
|
||||
*Done*, while the integration requirements they decompose into — `IR-018` and
|
||||
`IR-019`, both libmpv-specific — are still *Planned*. Similarly `IR-005` (MPRIS)
|
||||
sits at *Planned* under a *Done* `UR-006`.
|
||||
|
||||
The likely truth is that these user requirements were satisfied through a
|
||||
different path than the one originally specified (HTML5 `<video>` and ExoPlayer
|
||||
rather than libmpv), and the IRs were never re-scoped. Left as-is, the matrix
|
||||
reads as though shipped features depend on unbuilt integrations.
|
||||
|
||||
**Fix:** Re-scope or retire the stale IRs so each Done UR rests on Done IRs.
|
||||
|
||||
### A3 · Medium · The traceability gate is set far below actual coverage
|
||||
|
||||
`traceability-check.yml` fails only below 50%. Real coverage is well above that,
|
||||
so the gate cannot catch a coverage regression until roughly half the matrix has
|
||||
rotted. A gate that can only fire after a catastrophe is not protecting anything.
|
||||
|
||||
**Measured coverage: 86% (285/330)** — UR 71/75, IR 19/32, DR 166/187, JA 29/36.
|
||||
IR is by far the weakest dimension, which corroborates A1.
|
||||
|
||||
**Fix applied:** `MIN_THRESHOLD` ratcheted 50 → 82, with the ratchet policy
|
||||
written into the workflow (only goes up; never lowered to make a red build pass).
|
||||
The same figure is mirrored as `MIN_COVERAGE_PERCENT` in
|
||||
`scripts/extract-traces.ts` so local `traces:coverage` gates on the same bar, and
|
||||
a test parses the workflow YAML and fails if the two drift apart.
|
||||
|
||||
### A4 · Low · Two traced IDs do not exist in the requirements document
|
||||
|
||||
`DR-189` and `UT-188` are referenced by `TRACES:` comments but are defined
|
||||
nowhere in `docs/requirements.md`. The extraction tool accepts them silently, so
|
||||
typos and renames pass unnoticed.
|
||||
|
||||
**Fix:** Add a dangling-ID check to the extractor and fail CI on it — cheap, and
|
||||
it keeps the matrix honest in both directions.
|
||||
|
||||
### A5 · Not a gap · The remaining untraced requirements are legitimately unbuilt
|
||||
|
||||
`UR-016`, `UR-022` and `UR-070` are Planned or Proposed, and `UR-031`
|
||||
(crossfade) is explicitly blocked by `DR-034`. Their absence from the trace graph
|
||||
is correct and needs no action — noted so it does not get swept into the fix list.
|
||||
|
||||
---
|
||||
|
||||
## B. Android platform practice
|
||||
|
||||
The app targets SDK 36 with a minSdk of 24. Several manifest and WebView settings
|
||||
still reflect an earlier target level.
|
||||
|
||||
### B1 · Low · `POST_NOTIFICATIONS` is declared but never requested at runtime
|
||||
|
||||
*Downgraded from High. The original ranking was refuted by device testing — the
|
||||
evidence is below, and it is the reason this finding is now near-trivial.*
|
||||
|
||||
The permission appears in the manifest, but there is no `requestPermissions` call
|
||||
anywhere in the Kotlin, Rust or TypeScript sources, and
|
||||
`JellyTauPlaybackService.startForeground()` runs with no `checkSelfPermission`
|
||||
guard. On Android 13+ notification permission defaults to denied.
|
||||
|
||||
This was ranked High on the theory that it would suppress the media notification
|
||||
and with it the lockscreen transport controls (`UR-006`). Testing on an HONOR
|
||||
ROD2-W09 running **Android 16 (SDK 36)**, with the shipped app installed and
|
||||
playing, shows otherwise. The permission is genuinely denied:
|
||||
|
||||
```
|
||||
POST_NOTIFICATIONS: granted=false, flags=[USER_SENSITIVE_WHEN_GRANTED|USER_SENSITIVE_WHEN_DENIED]
|
||||
appops POST_NOTIFICATION: ignore
|
||||
```
|
||||
|
||||
and the notification is nonetheless live and complete:
|
||||
|
||||
```
|
||||
ServiceRecord{... com.dtourolle.jellytau/.player.JellyTauPlaybackService}
|
||||
isForeground=true foregroundId=1 types=0x00000002
|
||||
foregroundNoti=Notification(flags=NO_CLEAR|FOREGROUND_SERVICE
|
||||
category=transport actions=3 vis=PUBLIC)
|
||||
```
|
||||
|
||||
**`UR-006` is not at risk.** But the *reason* is not the one this audit first
|
||||
gave, and the correction is load-bearing rather than pedantic.
|
||||
|
||||
The first explanation here was "foreground-service notifications are exempt." That
|
||||
is wrong. Android's own wording is that the permission covers "non-exempt
|
||||
(**including Foreground Services (FGS)**) notifications", and that users who deny
|
||||
it see FGS notices "in the Task Manager but [not] in the notification drawer" — an
|
||||
FGS notification is explicitly *not* exempt. What is exempt is **media-session**
|
||||
notifications. The platform predicate is `Notification.isMediaNotification()`,
|
||||
requiring `MediaStyle`/`DecoratedMediaCustomViewStyle` **and** a non-null
|
||||
`EXTRA_MEDIA_SESSION`; it is byte-identical across API 33–36, and
|
||||
`NotificationManagerService` has no FGS clause in either enforcement site.
|
||||
|
||||
Why the difference matters: under the FGS theory, anything the service posts is
|
||||
safe, and the code needs no care. Under the correct one, the exemption is earned
|
||||
per-notification by the token — so losing the token loses not just the shade entry
|
||||
but the lockscreen controls entirely, since SystemUI's media carousel
|
||||
(`MediaDataProcessor.onNotificationAdded`) gates on the *same* predicate. A
|
||||
token-less notification never even reaches the notification listener.
|
||||
|
||||
**The real risk here is not the permission — it is how narrowly the exemption is
|
||||
earned.** AOSP's `Notification.isMediaNotification()` grants it only when the
|
||||
style is `MediaStyle`/`DecoratedMediaCustomViewStyle` **and**
|
||||
`Notification.EXTRA_MEDIA_SESSION` holds a non-null *platform* session token. If
|
||||
either is missing while the permission is denied, the notification is **silently
|
||||
suppressed** — no exception, no log.
|
||||
|
||||
JellyTau earns it at two sites, both of which hang it on a null-safe call:
|
||||
|
||||
```kotlin
|
||||
androidx.media.app.NotificationCompat.MediaStyle()
|
||||
.setMediaSession(mediaSessionCompat?.sessionToken) // :273 and :466
|
||||
```
|
||||
|
||||
Ordering currently saves it — `mediaSessionCompat` is assigned in `onCreate`
|
||||
(:195) and `createBasicNotification()` is only reached from `onStartCommand`
|
||||
(:251) — and the device test confirms it works. But it is one reordering away
|
||||
from breaking invisibly, and only for users who denied the permission, which is
|
||||
a population most developers never test as.
|
||||
|
||||
**Fix:** Keep the permission declared — download-service FGS notifications are
|
||||
*not* covered by the media exemption, and this app has a downloads feature that
|
||||
may want them. Comment both `setMediaSession` sites to record what earns the
|
||||
exemption, and log loudly if the token is ever null at build time, converting a
|
||||
silent failure into a diagnosable one.
|
||||
|
||||
**Location:** `src-tauri/android/src/main/java/com/dtourolle/jellytau/player/JellyTauPlaybackService.kt:251`, `:273`, `:466`
|
||||
|
||||
### B2 · High · Cloud backup is on by default, and it will break credential restore
|
||||
|
||||
The manifest sets neither `android:allowBackup="false"` nor a
|
||||
`dataExtractionRules`/`fullBackupContent` file, so Android's default applies: the
|
||||
app's data directory is backed up to the user's Google account. That ships the
|
||||
SQLite catalogue — library metadata and watch history — off the device.
|
||||
|
||||
The credential path makes it worse rather than better. `SecureStorage.kt`
|
||||
encrypts with AES/GCM under an Android Keystore key, and Keystore keys are never
|
||||
backed up. A user restoring onto a new phone therefore gets the ciphertext
|
||||
without the key: undecryptable credentials and a silent authentication failure,
|
||||
with no code path that recognises the situation.
|
||||
|
||||
**Fix applied.** `allowBackup="false"`. Extraction rules that merely excluded the
|
||||
DB and credential prefs would have left nothing worth backing up: the SQLite
|
||||
catalogue is a rebuildable mirror of the server and watch state lives server-side,
|
||||
so there is no user-authored data to preserve.
|
||||
|
||||
**A gap this audit missed:** on API 31+, `allowBackup="false"` disables *cloud*
|
||||
backup but **not device-to-device transfer**, which reproduces the identical
|
||||
failure — the prefs travel, the Keystore key does not. A
|
||||
`data_extraction_rules.xml` excluding all five domains from both `<cloud-backup>`
|
||||
and `<device-transfer>` was added to close it.
|
||||
|
||||
**A real bug found while fixing this:** the Rust encrypted-file fallback in
|
||||
`credentials.rs` propagated a decrypt failure as `CredentialError::Encryption`,
|
||||
which `storage_get_access_token` turned into a hard `Err` — so an undecryptable
|
||||
blob was an error state, not a logout. It now logs and returns an empty map, so
|
||||
the caller sees `NotFound` → `Ok(None)` → login screen, and the next sign-in
|
||||
self-heals the file. `SecureStorage.getCredential` on the Kotlin side already
|
||||
returned null, but could not distinguish "nothing stored" from "unreadable" and
|
||||
left the dead blob in prefs forever; it now separates the cases and discards it.
|
||||
Three tests written and watched fail first, per the red→green rule.
|
||||
|
||||
### B3 · High · `MIXED_CONTENT_ALWAYS_ALLOW` undoes the network security config
|
||||
|
||||
`network_security_config.xml` is careful and well-argued: cleartext blocked
|
||||
everywhere, exempted only for `127.0.0.1` so the local media server can serve
|
||||
downloads. Its own comment warns "this must not become a blanket cleartext
|
||||
opt-in."
|
||||
|
||||
But `MainActivity.kt` sets `mixedContentMode = MIXED_CONTENT_ALWAYS_ALLOW`, which
|
||||
permits the WebView to load http subresources into an https page from any origin.
|
||||
Alongside it, `allowFileAccess = true` and `allowContentAccess = true` are both
|
||||
broader than anything the app needs, since Tauri serves the UI from its own scheme
|
||||
and media comes from the token-guarded loopback server. These read as leftovers
|
||||
from before the media server existed.
|
||||
|
||||
**Fix:** Drop to `MIXED_CONTENT_COMPATIBILITY_MODE` and set both file and content
|
||||
access to false, then verify offline video still plays.
|
||||
|
||||
**Location:** `src-tauri/android/src/main/java/com/dtourolle/jellytau/MainActivity.kt:504-507`
|
||||
|
||||
### B4 · Medium · Android TV is half-declared
|
||||
|
||||
The manifest advertises `LEANBACK_LAUNCHER` and a non-required leanback feature,
|
||||
but omits `<uses-feature android:name="android.hardware.touchscreen"
|
||||
android:required="false"/>` and an `android:banner`. That combination fails Play's
|
||||
TV validation, and on a real TV the app would launch into a UI with no D-pad focus
|
||||
model behind it.
|
||||
|
||||
**Fix:** Either commit to TV — add the feature declaration, a banner, and a focus
|
||||
pass — or remove the leanback category until you do.
|
||||
|
||||
### B5 · Medium · `jvmTarget` is pinned to 1.8 under compileSdk 36
|
||||
|
||||
The Kotlin target has not moved with the SDK. AGP 8 warns on it, and it locks the
|
||||
Kotlin sources out of APIs and desugaring behaviour that everything else in the
|
||||
toolchain assumes.
|
||||
|
||||
**Fix:** Move `jvmTarget` and the Java source/target compatibility to 17.
|
||||
|
||||
### B6 · Low · Media3 is several minor versions behind
|
||||
|
||||
`androidx.media3` is pinned at 1.5.0 across exoplayer, hls, session and common.
|
||||
Given how much of this app's hard-won behaviour lives in ExoPlayer edge cases —
|
||||
truncated progressive streams, background audio handoff, HLS resume — staying
|
||||
current on its bug-fix releases has unusually high value here.
|
||||
|
||||
**Fix:** Schedule a Media3 bump with a device pass over the playback regression list.
|
||||
|
||||
### B7 · Medium · Predictive back is already on, not merely un-opted-into
|
||||
|
||||
*Upgraded from Low, and re-framed — the original framing was backwards.*
|
||||
|
||||
The audit first read the absent `enableOnBackInvokedCallback` as the app
|
||||
*forgoing* the Android 13+ back-gesture preview. That is not what the flag means
|
||||
at this target level. Predictive back is enabled by default for apps targeting
|
||||
recent SDKs, and Android 16's own behaviour-change list carries "Migration or
|
||||
opt-out required for predictive back" — with the opt-out being removed. Targeting
|
||||
36, JellyTau is already getting predictive back; it simply hasn't been checked
|
||||
against it.
|
||||
|
||||
That matters more than a missing opt-in would, because the app does not use
|
||||
ordinary Android back. It runs a WebView with its own history model —
|
||||
`src/lib/utils/navigation.ts` tracks a depth counter, applies a popstate delta,
|
||||
and falls back to a path when `history.back()` would trap the user, with
|
||||
`scrollRestore.ts` keying off the same popstate events. That is exactly the kind
|
||||
of custom back handling predictive back is most likely to disagree with.
|
||||
|
||||
**Fix:** This is a device test, not a code change — exercise the back gesture
|
||||
(including the drag-and-release preview and the cancel) from a library page, a
|
||||
detail page, the player, and the settings screen, and watch for the depth counter
|
||||
desynchronising. Only change code if it misbehaves.
|
||||
|
||||
Separately and unrelatedly: `JellyTauPlaybackService` is `exported="true"` with a
|
||||
`MediaSessionService` intent filter — conventional for Media3, but it means any
|
||||
app on the device can attempt to bind and drive playback. Confirm the session's
|
||||
`onConnect` callback rejects unknown packages.
|
||||
|
||||
### B8 · Medium (forward-looking) · Android 16 Local Network Protections vs a LAN Jellyfin server
|
||||
|
||||
*New finding, surfaced while researching B1.*
|
||||
|
||||
Android 16's behaviour-change list includes **Local Network Permission**. JellyTau's
|
||||
entire purpose is reaching a Jellyfin server that, for most users, sits on the
|
||||
local network — so a permission gate on local-network access is a direct threat to
|
||||
the app's core function, not a peripheral concern.
|
||||
|
||||
Stated carefully, because the timing matters: in Android 16 this is **opt-in for
|
||||
testing**, not enforced by default, with enforcement signalled for a future
|
||||
release. Nothing is broken today, and the device test will not surface it. But
|
||||
this is the rare platform change that could stop the app working at all, and it
|
||||
is much cheaper to handle before it is mandatory.
|
||||
|
||||
**Fix:** Investigate what the permission will require, then test the app against
|
||||
it with the opt-in flag enabled on the Android 16 device already to hand. Track it
|
||||
as a release-blocking item for whichever Android version enforces it.
|
||||
|
||||
---
|
||||
|
||||
## C. Tauri v2 configuration
|
||||
|
||||
The capability model here is genuinely well done — see section E. The gaps are in
|
||||
the two settings that govern what a compromised web layer could reach.
|
||||
|
||||
### C1 · High · `"csp": null` contradicts the project's own security convention
|
||||
|
||||
`CLAUDE.md` lists "keep the CSP restrictive in `tauri.conf.json`" as a standing
|
||||
rule; the config disables CSP entirely. With it off, any script that reaches the
|
||||
web layer inherits the full IPC surface.
|
||||
|
||||
The realistic exposure today is low, and worth stating plainly rather than
|
||||
inflating: the frontend has a single `{@html}` — an app-owned icon in
|
||||
`GenericGenreBrowser.svelte`, not server data — and no `innerHTML`, `eval` or
|
||||
`new Function` outside tests. So this is a missing defence rather than an open
|
||||
hole. But it is the defence that stops the next careless interpolation of a
|
||||
Jellyfin-supplied string from becoming a full compromise.
|
||||
|
||||
**Fix:** Set a CSP permitting `'self'`, `asset.localhost`, `http://127.0.0.1:*`
|
||||
for media, and the configured Jellyfin origin for images. Expect one or two
|
||||
iterations against HLS playback.
|
||||
|
||||
### C2 · Medium · The asset protocol scope is wider than what it serves
|
||||
|
||||
`assetProtocol.scope` is `$APPDATA/**`, which covers the whole app data directory
|
||||
— the SQLite database and the credential store included — while the protocol only
|
||||
needs to reach cached thumbnails and downloaded media.
|
||||
|
||||
Since `DR-137` introduced the token-guarded loopback media server, the asset
|
||||
protocol's remaining job may be thumbnails alone, which would make the narrowing
|
||||
nearly free.
|
||||
|
||||
**Fix applied:** scoped to `$APPDATA/thumbnails/**`. Confirmed on device that
|
||||
`jellytau.db` (8 MB catalogue) and `shared_prefs` sit in the `$APPDATA` root and
|
||||
are now outside the grant.
|
||||
|
||||
**But device testing found the finding was aimed at the wrong thing.** The asset
|
||||
protocol is not narrowly used — it is **entirely unused at runtime**:
|
||||
|
||||
- `getCachedImageUrl` in `imageCache.ts` has **no production callers**. Its only
|
||||
references are its own test file. `convertFileSrc`'s sole production mention
|
||||
sits inside that uncalled function, so it never executes.
|
||||
- The real path is `MediaCard` → `CachedImage` → `commands.imageGetUrl()`, which
|
||||
returns **base64 from Rust**. Every image in the app is a `data:` URI delivered
|
||||
over IPC.
|
||||
- Confirmed on device: zero `asset.localhost` requests across a full session of
|
||||
browsing home, the library list and a poster grid; the thumbnail cache stayed
|
||||
at 12 files and never grew, because nothing calls `thumbnailSave` either.
|
||||
|
||||
Two consequences worth acting on, neither yet done:
|
||||
|
||||
1. **The `protocol-asset` Cargo feature and the whole `assetProtocol` config
|
||||
block can likely be removed**, which retires the attack surface rather than
|
||||
shrinking it. `imageCache.ts` is dead code and can go with it.
|
||||
2. **`img-src` in the new CSP can be much tighter.** It currently grants
|
||||
`http: https:` on the reasoning that thumbnails are fetched direct-from-server
|
||||
on a cache miss — but they are not; they arrive as data URIs. With no
|
||||
webview-side server image loads anywhere in `src/`, `img-src 'self' data:
|
||||
blob:` should suffice. That is a real tightening the CSP work left on the
|
||||
table because it reasoned from the dead code path.
|
||||
|
||||
Both need their own device pass, since a wrong `img-src` blanks every image.
|
||||
|
||||
### C3 · Low · Shipped desktop bundles have no update path
|
||||
|
||||
The bundle targets deb, rpm and nsis, but `tauri-plugin-updater` is not among the
|
||||
dependencies. Every desktop user upgrades by manually fetching a new package,
|
||||
which in practice means a long tail of installs pinned to whatever version they
|
||||
first downloaded.
|
||||
|
||||
**Fix:** Add the updater plugin with a signed release manifest, or document the
|
||||
manual upgrade path in the README so the omission is at least deliberate.
|
||||
|
||||
---
|
||||
|
||||
## D. CI and code health
|
||||
|
||||
Local discipline in this project is strong and well documented. CI enforces only
|
||||
part of it, which means the discipline holds exactly as long as every contributor
|
||||
remembers it.
|
||||
|
||||
### D1 · High · CI runs neither `cargo clippy` nor `cargo fmt --check`
|
||||
|
||||
`CLAUDE.md` requires both before committing. Neither appears anywhere in
|
||||
`.gitea/workflows/`. The build-and-test job runs the boundary check, the frontend
|
||||
tests, the Rust tests and an Android `cargo check` — a good set, with the two lint
|
||||
gates missing.
|
||||
|
||||
Clippy currently reports 51 warnings across the lib and its tests, including
|
||||
unused imports and a redundant import that a gate would have stopped at the door.
|
||||
|
||||
**Fix:** Add both to the test job. Start with `-D warnings` on new code only if
|
||||
clearing the existing 51 is too large a first step.
|
||||
|
||||
### D2 · Medium · A flaky test will intermittently redden CI
|
||||
|
||||
`offlineCatalog.test.ts` — "pushes include=true while the server is reachable"
|
||||
(`UT-068`) — timed out at the 5 s limit during a full-suite run, then passed twice
|
||||
in isolation taking 1.13 s and 0.61 s.
|
||||
|
||||
**Root cause (corrected):** this audit originally attributed it to a real
|
||||
wall-clock timer. It isn't. The cost is the **first dynamic
|
||||
`import("./offlineCatalog")`**, which pays to transform the service and its whole
|
||||
dependency graph (~1072 ms cold) inside a test body, charged against vitest's 5 s
|
||||
default. Later re-imports after `vi.resetModules()` cost ~30 ms. Under full-suite
|
||||
contention the cold transform alone crosses the limit.
|
||||
|
||||
**Fix applied:** warm the import once at collection time with a top-level
|
||||
`await import(...)`, so no test is timing the compiler. Slowest test 1072 ms →
|
||||
129 ms; file total 1170 ms → 238 ms. Timeout deliberately left at the default.
|
||||
A latent cross-test leak was also fixed alongside it — the store shim's
|
||||
subscribers were never cleared, so every module instance discarded by
|
||||
`resetModules()` kept pushing its own visibility value.
|
||||
|
||||
**Location:** `src/lib/services/offlineCatalog.test.ts:58`
|
||||
|
||||
### D3 · Low · ~~820~~ **19** production `unwrap()`/`expect()` calls
|
||||
|
||||
*Downgraded from Medium. This audit substantially overstated the problem, and the
|
||||
correction is worth recording because the measurement error is instructive.*
|
||||
|
||||
The original 820 figure came from grepping for `unwrap()`/`expect()` and filtering
|
||||
lines containing "test". That does not exclude test *modules* — it only excludes
|
||||
lines with "test" in them. Scripting the actual `#[cfg(test)]` boundaries gives
|
||||
**19 real production sites**, not 820. `player/mod.rs`'s 154 hits, for instance,
|
||||
are *all* past its `#[cfg(test)]` at line 2183, as are the bulk of
|
||||
`repository/offline.rs`, `storage/mod.rs` and `commands/download/mod.rs`.
|
||||
|
||||
**More importantly: zero bare unwraps exist in any `#[tauri::command]` handler.**
|
||||
The specific risk this finding was built around — a panic inside a command killing
|
||||
the task and stranding shared player state — is already absent.
|
||||
|
||||
The same correction applies to the lock half: all 33 raw `.lock().unwrap()` hits
|
||||
were in test modules (three weren't even code, but prose in `utils/lock.rs`'s doc
|
||||
comment). Production was already fully on `lock_safe()`/`read_safe()`/
|
||||
`write_safe()`. Converting them was consistency work, not a bug fix.
|
||||
|
||||
**What is genuinely worth doing** is a three-site cluster, all the same pattern —
|
||||
`Runtime::new().unwrap()` in threads owning playback-critical state:
|
||||
|
||||
| | Site | Consequence of a panic |
|
||||
|---|------|------------------------|
|
||||
| 1 | `session_poller/mod.rs:102` | Poller thread dies silently; it drives remote-mode state *and* offline→online recovery, so the app strands offline with nothing surfaced |
|
||||
| 2 | `player/mpv_backend.rs:424` | Position reporting stops mid-playback; the scrubber freezes while audio keeps going |
|
||||
| 3 | `player/android/mod.rs:761` | Same pattern across a JNI boundary; progress reporting dies and no resume points are written |
|
||||
|
||||
**Fix:** One shared helper returning `Option<Runtime>` and logging on failure
|
||||
retires all three. The remaining 16 are startup `expect()`s and two provably
|
||||
infallible calls.
|
||||
|
||||
### D4 · Low · Five files carry a disproportionate share of the complexity
|
||||
|
||||
`player/mod.rs` (4,726 lines), `repository/offline.rs` (4,696),
|
||||
`repository/online.rs` (3,702), `commands/player/mod.rs` (3,299) and
|
||||
`commands/download/mod.rs` (3,226), plus `VideoPlayer.svelte` (2,778) on the
|
||||
frontend.
|
||||
|
||||
These are the same files the changelog keeps returning to for deadlocks and
|
||||
playback regressions. Not a defect in itself, and not worth a speculative
|
||||
refactor — but the next time one of them needs substantial work, splitting it is
|
||||
likely cheaper than continuing to grow it.
|
||||
|
||||
---
|
||||
|
||||
## E. Verified sound
|
||||
|
||||
Things this audit specifically went looking for and found in good order —
|
||||
including one that looked alarming from the warning output and turned out to be
|
||||
fine.
|
||||
|
||||
| Area | Finding |
|
||||
|------|---------|
|
||||
| **The 9 "MutexGuard across await" warnings are test-only** | All nine sit in `#[tokio::test]` functions holding a serialization lock, not in the production async paths that `CLAUDE.md`'s deadlock gotcha warns about. |
|
||||
| **The local media server is exemplary** | Loopback-only bind, a 32-hex-char per-session token, lexical `..` folding rather than `canonicalize`, and a test asserting reads stay inside the data directory. |
|
||||
| **Tauri capabilities are minimal** | Three permissions total — `core:default`, `opener:default`, `core:path:default`. No blanket grants, no `withGlobalTauri`. |
|
||||
| **SQL is parameterised** | Two `format!`-built statements in the whole Rust tree, neither interpolating caller-controlled input into a query. |
|
||||
| **R8 keep rules are correct and explained** | JNI-loaded player and security classes, the JavascriptInterface bridges and Media3 are all kept, each with a comment naming the crash it prevents. |
|
||||
| **Type and boundary gates are green** | `svelte-check`: 0 errors, 0 warnings. `check:boundary` passes with three reviewed allowlist entries. 698 Rust tests and 1,021 frontend tests pass. |
|
||||
|
||||
---
|
||||
|
||||
## F. Suggested order
|
||||
|
||||
Sequenced so the cheap gates land before the work they would have caught. B2
|
||||
leads because it is the finding a user is most likely to actually feel.
|
||||
|
||||
*(B1 originally led this list. It was demoted to row 10 after device testing —
|
||||
see B1. This is a good advertisement for testing a finding before scheduling
|
||||
work against it.)*
|
||||
|
||||
| # | Finding | What it buys | Effort |
|
||||
|---|---------|--------------|--------|
|
||||
| 1 | B2 | Catalogue and credentials stop leaving the device; restore stops failing silently | S — **confirmed on device**: `ALLOW_BACKUP` set, Google transport active |
|
||||
| 3 | D1 | Lint discipline becomes enforced rather than remembered | S |
|
||||
| 4 | B3 | The network security config actually holds | S — needs an offline-playback check |
|
||||
| 5 | A1 | The matrix stops over-reporting on twelve shipped requirements | M — mostly mechanical |
|
||||
| 6 | D2 | CI stops flaking | S |
|
||||
| 7 | C1 · C2 | The web layer stops being one interpolation away from full IPC | M — iterate against HLS |
|
||||
| 8 | A2 · A3 · A4 | The matrix becomes self-consistent and defended by a real gate | M |
|
||||
| 9 | B4 · B5 · B6 · B7 | Platform hygiene brought level with the SDK target | M |
|
||||
| 10 | B1 · D3 · C3 · D4 | Long-tail robustness; opportunistic rather than scheduled | L |
|
||||
+45
-13
@@ -16,7 +16,7 @@ For a narrative overview of the system design, see
|
||||
| UR-003 | Play videos | High | Done |
|
||||
| UR-004 | Play audio uninterrupted | High | Done |
|
||||
| UR-005 | Control media playback (pause, play, skip, scrub) | High | Done |
|
||||
| UR-006 | Control media when device is on lock screen or via BLE headsets | Medium | Done |
|
||||
| UR-006 | Control media when device is on lock screen or via BLE headsets | Medium | Done (Android); **not implemented on Linux** — see IR-005 |
|
||||
| UR-007 | Navigate media in library | High | Done |
|
||||
| UR-008 | Search media across libraries | High | Done |
|
||||
| UR-009 | Connect to Jellyfin to access media | High | Done |
|
||||
@@ -101,7 +101,7 @@ External system integrations and platform-specific implementations.
|
||||
| IR-002 | Build scripts for Android and Linux | Build | UR-001 | Done |
|
||||
| IR-003 | Integration of libmpv for Linux playback | Playback | UR-003, UR-004 | Done |
|
||||
| IR-004 | Integration of ExoPlayer for Android playback | Playback | UR-003, UR-004 | In Progress (basic playback works, audio settings missing) |
|
||||
| IR-005 | MPRIS D-Bus integration for Linux lockscreen/media controls | Platform | UR-006 | Planned |
|
||||
| IR-005 | MPRIS D-Bus integration for Linux lockscreen/media controls | Platform | UR-006 | Planned — genuinely absent: no `mpris`/`souvlaki`/`zbus`/`dbus` code or dependency in the project (`zbus` appears in `Cargo.lock` only transitively, via `tauri-plugin-opener`), and no `navigator.mediaSession` use in the frontend. `player::update_lockscreen_metadata` is a no-op off Android. UR-006 is therefore Android-only |
|
||||
| IR-006 | Android MediaSession integration for lockscreen controls | Platform | UR-006 | Done |
|
||||
| IR-007 | Bluetooth AVRCP integration via system media session | Platform | UR-006 | Planned |
|
||||
| IR-008 | Android audio focus handling (pause on call) | Platform | UR-004, UR-006 | Done |
|
||||
@@ -115,8 +115,8 @@ External system integrations and platform-specific implementations.
|
||||
| IR-015 | Jellyfin API client for playback progress reporting | API | UR-019, UR-025 | Done |
|
||||
| IR-016 | Jellyfin API client for subtitle/audio track info | API | UR-020, UR-021 | Done |
|
||||
| IR-017 | Jellyfin API client for transcoding parameters | API | UR-022 | Planned |
|
||||
| IR-018 | libmpv subtitle rendering and selection | Playback | UR-020 | Planned |
|
||||
| IR-019 | libmpv audio track selection | Playback | UR-021 | Planned |
|
||||
| IR-018 | Subtitle rendering and selection in the **video** playback backends: ExoPlayer sideloads each track as a `MediaItem.SubtitleConfiguration` and selects by text-track-group position (Android), and the WebKitGTK HTML5 `<video>` element renders `<track kind="subtitles">` children carrying `data-stream-index` (Linux). **Originally scoped to libmpv, which never implemented it**: `MpvBackend` is the audio-only backend here and does not override `PlayerBackend::set_subtitle_track`, so the default `not_implemented()` still stands there. UR-020 is satisfied by the two paths above rather than by MPV | Playback | UR-020 | Done |
|
||||
| IR-019 | Audio track selection in the **video** playback backends: ExoPlayer switches track by index natively (Android), while the HTML5 `<video>` path cannot switch a track in the element and instead re-opens the stream at the chosen `AudioStreamIndex` and resumes at the same position (Linux) — the two outcomes `AudioTrackSwitchResponse` distinguishes. **Originally scoped to libmpv, which never implemented it**: `MpvBackend` does not override `PlayerBackend::set_audio_track`, so the default `not_implemented()` still stands there. UR-021 is satisfied by the two paths above rather than by MPV | Playback | UR-021 | Done |
|
||||
| IR-020 | libmpv/ExoPlayer equalizer integration | Playback | UR-027 | Done (Linux/MPV; Android parity pending) |
|
||||
| IR-022 | Jellyfin API client for person/cast data | API | UR-035, UR-036 | Done |
|
||||
| IR-023 | Database schema for person/cast caching | Storage | UR-035, UR-036 | Done |
|
||||
@@ -130,6 +130,26 @@ External system integrations and platform-specific implementations.
|
||||
| IR-031 | Android `WindowInsets` bridge: an `OnApplyWindowInsetsListener` on the decor view reports `systemBars() | displayCutout()` in CSS pixels, pushed into the WebView as `jt-inset` CSS custom properties plus a `jellytau-insets-changed` event, and pullable via the `AndroidInsets` JS bridge | Platform | UR-066 | Done (pending device verification) |
|
||||
| IR-032 | Whole-file background download of the item being played, reusing the existing resumable download worker and the Range-capable `/Videos/{id}/stream.mp4` endpoint; plus per-platform read-through caching hooks (ExoPlayer `CacheDataSource`, mpv `stream-record`) for direct-play sessions only | Storage | UR-071 | Proposed |
|
||||
|
||||
> **Where a UR is met by a different mechanism than its IR anticipated.** Several
|
||||
> integration requirements were written when libmpv was expected to be the single
|
||||
> playback backend. It is not: `MpvBackend` is the **audio-only** backend, Linux
|
||||
> plays video through a WebKitGTK HTML5 `<video>` element (HLS/h264), and Android
|
||||
> plays through ExoPlayer. So:
|
||||
>
|
||||
> * **UR-020 / UR-021** (subtitle and audio track selection) are Done, but not by
|
||||
> MPV — `MpvBackend` overrides neither `PlayerBackend::set_subtitle_track` nor
|
||||
> `set_audio_track`, leaving the trait's `not_implemented()` default. IR-018 and
|
||||
> IR-019 have been **re-scoped to the backends that actually deliver them**
|
||||
> (ExoPlayer sideloaded `SubtitleConfiguration`s and native track switching;
|
||||
> HTML5 `<track>` children and stream re-open at the chosen `AudioStreamIndex`)
|
||||
> and marked Done on that basis. IT-008 / IT-009 were re-worded to match.
|
||||
> * **UR-006** (lockscreen / BLE headset control) is Done **on Android only**, via
|
||||
> `MediaSessionCompat` (IR-006) and ExoPlayer/`AudioManager` focus (IR-008).
|
||||
> IR-005 (MPRIS) remains Planned because it genuinely does not exist — there is
|
||||
> no MPRIS/D-Bus code or dependency in the project, and
|
||||
> `player::update_lockscreen_metadata` is a no-op off Android. UR-006's status
|
||||
> was corrected rather than IR-005's.
|
||||
|
||||
### 2.2 Jellyfin API Requirements
|
||||
|
||||
API endpoints and data contracts required for Jellyfin integration.
|
||||
@@ -308,7 +328,7 @@ Internal architecture, components, and application logic.
|
||||
| DR-131 | The offline mutation queue is drained. `sync_queue` had producers and no consumer: `PlaybackReporter::queue_for_sync` writes a row for every start/stop/mark-played that cannot reach the server, `sync_mark_processing`/`_completed`/`_failed` were registered commands with no callers, and no Rust task processed the table — so queued watch positions never reached Jellyfin and the offline banner's count only ever grew. A drain hangs off the same `connectivity:reconnected` transition as DR-120 (in Rust, because a drain started by a component dies with it) and replays rows oldest-first, so a stale start cannot move the server's resume position backwards after a later stop. `update_progress` replays as *stopped at N* rather than as progress — replaying a mid-playback report hours later would claim the item is still playing — and payloads are read in both dialects that exist in users' databases (`position_ticks` from Rust, camelCase `positionMs` from the frontend helper). A failed row stays queued for the next reconnect; after `MAX_SYNC_ATTEMPTS` it is `abandoned` and stops counting, because a row nothing can ever push is what turns the queue into a counter that only grows. An *unreachable* server is not counted as an attempt at all — the row goes back to `pending` untouched — so opening the app offline a few times cannot abandon good rows; only a server that answers and refuses spends the budget. The drain also runs once at startup, because a queue built in a previous session would otherwise sit untouched for a whole run whenever the server was reachable the entire time and no offline→online transition ever fired. Requires `MediaRepository::mark_played` (JA-035) — the previous stand-in reported a stop at `i64::MAX` | Backend | UR-025, UR-002 | Done |
|
||||
| DR-132 | The pending-sync count is answerable. The offline banner's badge read "N pending sync(s)" and led nowhere, so it was taken for pending *transfers* and looked for on the Downloads page — which lists the `downloads` table and structurally cannot show `sync_queue` rows. The badge becomes a button opening the queue it counts: each row's operation, the item's title (resolved by a `LEFT JOIN items` in `sync_get_pending`, not a per-row frontend fetch), when it was queued, and the error of anything failing, plus a "Sync now" that runs the DR-131 drain on demand. The same list is a Settings section, because a row that keeps failing is still queued when the server is reachable and no banner is on screen. The drain emits `sync-queue-changed` so the badge updates on reconnect instead of lagging by up to one 10s poll | UI | UR-025 | Done |
|
||||
| DR-133 | A downloaded file has exactly one on-disk path, and the row that names it is authoritative. `downloads.file_path` starts relative to the storage root, but the worker rewrites it to the absolute path it actually wrote when the transfer completes — so a *completed* row is already rooted. The video player's offline branch rooted it a second time, handing the asset protocol `/data/user/0/app//data/user/0/app/videos/x.mp4`; the webview reported `MEDIA_ERR_SRC_NOT_SUPPORTED` with `NETWORK_NO_SOURCE`, so every downloaded video failed to play while audio — which resolves the same column through Rust's `resolve_local_media_path`, without re-rooting — played fine. The join is absolute-aware (POSIX, Windows drive letters and UNC) so rows written before completion still resolve | Playback | UR-071 | Done |
|
||||
| DR-134 | The webview can actually fetch the local files it is handed. `convertFileSrc` rewrites a path to `http://asset.localhost/…` unconditionally, but Tauri only answers that origin when the `protocol-asset` cargo feature is compiled in *and* `app.security.assetProtocol.enable` is set — neither was, so every such URL reached a protocol with no handler and the webview reported `NETWORK_NO_SOURCE`. This silently defeated both offline video (`<video src>`) and the cached-thumbnail path in `imageCache`, which fails soft to the server copy and so hid the breakage whenever the server was reachable. The scope is `$APPDATA/**` — the storage root under which the database, `downloads/` and the thumbnail cache all live — rather than an unrestricted grant, so the webview can read the app's own media and nothing else | Security | UR-071 | Done |
|
||||
| DR-134 | The webview can actually fetch the local files it is handed. `convertFileSrc` rewrites a path to `http://asset.localhost/…` unconditionally, but Tauri only answers that origin when the `protocol-asset` cargo feature is compiled in *and* `app.security.assetProtocol.enable` is set — neither was, so every such URL reached a protocol with no handler and the webview reported `NETWORK_NO_SOURCE`. This silently defeated both offline video (`<video src>`) and the cached-thumbnail path in `imageCache`, which fails soft to the server copy and so hid the breakage whenever the server was reachable. The scope was `$APPDATA/**` — the storage root under which the database, `downloads/` and the thumbnail cache all live — rather than an unrestricted grant; DR-198 narrows it further to `$APPDATA/thumbnails/**`, since DR-137 moved downloaded media off this protocol and thumbnails are all it still serves | Security | UR-071 | Done |
|
||||
| DR-140 | An audio track is pinned only when the user picked one. Jellyfin's `MediaStream.Index` is global across every stream in a media source, so index 0 is the *video* stream on virtually all files — yet `AudioStreamIndex=0` was sent as "the first audio track" on the HLS transcode URL, the background audio-only handoff URL, the direct-play fallback URL, and the `PlaybackInfo` negotiation body. A server that honours the request literally then transcodes the video stream into the audio slot and the result plays as a picture with no sound; only servers that silently correct the index hid the bug, which is why it presented as "some videos have no audio". The parameter is now omitted whenever no track has been chosen, so the server resolves the source's `DefaultAudioStreamIndex`; an explicit selection from `player_switch_audio_track` is still carried through unchanged. On the `static=true` direct-play URL it is dropped outright — the original file is served untouched, so the parameter could only mislead | Playback | UR-004, UR-040 | Done |
|
||||
| DR-147 | One search input per screen, and the URL is the search's single source of truth. The header bar rendered only under `/library/**` and merely *navigated* to `/search` (DR-063), so a desktop search handed the user to a screen whose input was a different element — the header box cleared itself and vanished, and the page's own box took over mid-word. That page then re-derived its input from `?q=` against `library.searchQuery` on every store write, so the next keystroke re-ran the effect and snapped the text back to the query the header had sent (and a scope chip back to the URL's scope); entering from the bottom-nav Search tab skipped it only because the effect early-returned on an empty query. The bar now renders on `/search` too (`showHeaderSearch`) and is the sole md+ input — the page's own input is `md:hidden` — and on that route it republishes the query into the URL with `replaceState`, so a whole session of typing costs one history entry. The page *consumes* that URL once per distinct value (`seedFromSearchUrl` against a non-reactive `applied` marker) instead of continuously reconciling it, and the scope chips publish through the same URL so the bar and the chips cannot disagree. Landing on `/search` with a seeded query focuses the bar and puts the caret at the end, because the box the user was typing in belonged to the unmounted route | UI | UR-049, UR-054 | Done |
|
||||
| DR-142 | An episode has exactly **one** surface, and it is complete. Two divergent renderings existed: `EpisodeFocusView` (reached from Continue Watching, the series episode list, the TV landing page and Downloads — i.e. every real entry point) offered only Play and Favourite, while the bare `/library/<episodeId>` page nobody routed to carried the download button, the series/season breadcrumbs and the cast section. Opening an episode the normal way therefore silently lost the ability to download it. The Focus View is now the single surface and carries the full §5B.2 composition — hero action row `Play / Download / Favourite`, series name and `SxEy` badge as links back to the series and to that season's anchor, then genres → cast → similar shows *below* the episode strip, never above it (DR-062). `/library/<episodeId>` redirects into it (`episodeRedirectTarget`, the same rule seasons follow under DR-103), and an episode with no `seriesId` renders the same component series-less rather than falling back to a second, lesser page. The focused episode is fetched in full rather than reused from the season fan-out, because that is a *list* query and carries neither cast nor genres — the sections would have rendered empty. The strip hides itself when the episode has no siblings, a card that only shows the episode you are already on being noise | UI | UR-048, UR-058 | Done |
|
||||
@@ -348,10 +368,14 @@ Internal architecture, components, and application logic.
|
||||
| DR-186 | The play overlay comes down when the backend plays. `isPlaying` was assigned once from the `player_play_item` response and thereafter only by the `player://state-changed` listener — a channel the backend never emits, the same dead wire that DR-182's first fix was mistakenly hung on. On the native path the flag therefore froze at whatever the initial response said: with ExoPlayer playing, the UI still believed it was paused, so the `bg-black/30` play-button overlay stayed raised across the whole video area and the transport button kept showing ▶. The video was simultaneously dimmed and covered while it played, which reads as "the overlay never goes away" and is easily mistaken for a second compositing fault. The mirror reads the same `player` store `playerEvents.ts` feeds, which is what the architecture already says is authoritative — the player reports state, the UI consumes it — and is gated to the native path so HTML5 keeps its element-event wiring, which is authoritative there | UI | UR-003, UR-005 | Done |
|
||||
| DR-187 | The system bars go away with the player, not only with the fullscreen button. `enterImmersive()` had exactly one caller, `toggleFullscreen()`, so opening the player left the status and navigation bars painted over it until the user pressed a button most never press. On the native path this is worse than cosmetic: the SurfaceView fills the content view, so the bars sit directly on top of the video. The player is a full-screen surface by construction — `fixed inset-0 z-50` over a `MATCH_PARENT` surface — so entry is the right moment. Called synchronously in `onMount` before any `await`, per the native-mode pitfall, and paired with the `exitImmersive()` already unconditional in `onDestroy`, so a player torn down while immersive cannot leave the rest of the app without bars | UI | UR-066, UR-003 | Done |
|
||||
| DR-188 | Native Android video is **ready to be the default except for the background-audio handoff**, and the flip therefore waits. The picture defects behind DR-172 are all found, fixed and device-verified — DR-185 (the app shell painted over the surface through a CSS rule targeting an attribute nothing set), DR-182 (nothing could lift the poster card on a path with no `<video>` element), DR-183 (the JS bridges raced the page load, so `setTransparent(true)` could never arrive), DR-184 (the SurfaceView was never detached), plus DR-186 and DR-187, the two UI defects only this path could reveal. On a device logcat now carries `WebView transparent = true` and `Marking media ready` with video on screen, which is the pair DR-172 went looking for and could not find, and skip, seek and rotation were exercised by hand. Turning the default on then surfaced a *different* unverified sub-path: the background-audio handoff could only *return* through the HTML5 element, so coming back from the lockscreen left playback dead, and the flip waited for that rather than shipping a verified sub-path over an unverified one as DR-161 had. **The default is now on.** The two defects holding it back are fixed and device-verified — DR-196 (the handoff return restarts the renderer that is actually on screen) and DR-194 (the letterbox bars are painted rather than retaining stale framebuffer content) — with the evidence this default has been held to since DR-161: an audio handoff at 69:54 returning to video playing at 70:18, and clean bars across playback, the control bar and a rotation round-trip. An explicit stored choice still wins in both directions, so an opt-out survives the flip (the stored value is null-checked rather than compared to "true", which would have silently re-enabled it for everyone who turned it off) | Android | UR-003, UR-004 | Done |
|
||||
| DR-189 | The control bar comes down on a touchscreen. Its hide timer was armed from exactly one place — the player container's `onmousemove` — and a touchscreen never fires `mousemove`, so on Android the bar was never scheduled to hide and sat over the video for the whole film. It went unnoticed for as long as the native video surface was itself invisible (DR-172/DR-185): with nothing behind it to obscure, a permanent control bar reads as the UI rather than as a defect. Two changes, because there were two faults. `revealControls()` replaces `handleMouseMove` and is called on entry and on every touch interaction as well as on mouse movement, so touch arms the countdown. And the countdown became an `$effect` over the state rather than a one-shot timer armed by the input event: the first attempt armed a timer on entry, three seconds later playback had not started, `shouldHideControls` correctly declined, and nothing ever re-armed it — the timer has to follow the conditions that *permit* hiding, which arrive on their own schedule. The decision itself is `shouldHideControls` in `controlsVisibility.ts`, pure and separated from the clock and the DOM, because what was wrong here was the conditions and not the `setTimeout`: the bar stays up while paused (a user who paused by tapping the surface has no other way back), mid-seek (the position readout is the point of the bar then), and while any track/subtitle/quality menu is open (the menus are anchored to the bar, so hiding it would take the open menu with it) | UI | UR-003, UR-066 | Done |
|
||||
| DR-191 | Forcing the WebView overlay to redraw from the Activity, because with the ExoPlayer **SurfaceView** beneath it the overlay's ordinary damage stopped reaching the screen: the page kept mutating — the clock text every second, the control bar's opacity going to 0 — while the display held whatever frame it last presented, over video that animated perfectly. Not a state defect; the live DOM showed the slider advancing 476 → 479 across three seconds behind a screen showing neither. Only **structural** changes got through, which is why the play overlay always appeared to work (an `{#if}` block, added and removed) while the progress bar never did, and why rotation lost the transport UI. A CSS animation cannot help, since opacity animates on the compositor without repainting the layer. **Superseded by DR-192**: this drove `postInvalidateOnAnimation` in a loop, which treats the symptom — the cause is the SurfaceView's separate layer, and removing that removes the need. Kept as the record of how the mechanism was identified | Android | UR-003, UR-004 | Superseded by DR-192 |
|
||||
| DR-195 | Play/pause works on the native path, because the frontend stops claiming a webview element is playing when there is none. `html5_playing` is Rust's record of "a webview `<video>` is active and in this state", and `toggle_playback`, `play` and `pause` all route transport to that element whenever it is set. The player route mirrored element state into it **unconditionally** — from `handleReportStart` and, fatally, from `handleReportProgress`, which VideoPlayer calls on a 10-second interval — so on the native path the frontend re-declared every ten seconds that an element was playing when none existed, and every transport intent was emitted into the void. The pause button was dead from the on-screen tap, from the control bar, and from a direct `player_toggle` invocation, while seek and skip kept working because `player_seek_video` decides elsewhere; that asymmetry is the signature. It also explains the flashing, since the control bar and the JRay overlay both key off `isPlaying`, which was being contradicted on every interval tick. DR-193 clearing the flag at load was necessary but insufficient on its own — the interval put it straight back. The mirror now lives in `mirrorElementStateToRust` in VideoPlayer, gated on `useHtml5Element`, which is the only place that knows whether an element renders at all; the route cannot tell the two paths apart, which is precisely how it came to lie. Confirmed on device by ADB: surface tap and control bar each pause (position frozen across repeated samples, transport label flipped) and resume | Playback | UR-005, UR-003 | Done |
|
||||
| DR-196 | Returning from background audio brings the picture back on the **native** path, because the return now restarts the renderer that is actually on screen. The two paths resume by different means: the webview `<video>` reloads off its stream URL, watched by an `$effect` that reinitialises HLS and lets `canplay` drive the seek — while ExoPlayer owns no element and nothing watches the URL on its behalf, so its playback is only ever started by an explicit `player_play_item` + adapter load, issued once from `onMount`. `exitBackgroundAudioHandoff` did only the URL assignment, for both paths, so on the native path it restarted nothing: `player_exit_background_audio` had already stopped the handoff's audio player, leaving the backend holding no item at all. The symptom is a black screen with a play overlay pinned at 0:00, a seek bar at zero, and a play button that does nothing — the process alive and the frontend still logging, since nothing crashed; the transition was simply dropped. The branch is decided by `planHandoffReturn` (pure, in `backgroundAudioHandoff.ts`), which also folds in `shouldResumeOnForeground` so a lockscreen pause during the handoff still wins over the snapshot taken on the way out. Subtitle configurations are reused from the ones resolved at mount, since ExoPlayer sideloads them as `MediaItem.SubtitleConfiguration`s and cannot accept one after `prepare()`. Verified on device: handoff to audio at 69:54, return restored video playing at 70:18 | Playback | UR-040, UR-003 | Done |
|
||||
| DR-197 | Continue Watching and Next Up stop showing the same episode. Jellyfin's `/Shows/NextUp` defaults `EnableResumable=true`, which returns a partially-watched episode as its own series' next up — precisely the episode `/Items/Resume` already returns — so the Home "Next Episode" row and the TV landing's Next Up row duplicated Continue Watching card for card. `build_next_up_endpoint` sends `EnableResumable=false`, and because servers predating that parameter ignore it, `filterInProgressNextUpItems` also drops any next-up entry whose id appears in the resume list. It is the mirror of DR-089 and lives beside it: same presentation-layer de-duplication over two lists the frontend already holds, no Jellyfin taxonomy involved. The resume filter still reads its frontier from the *unfiltered* Next Up list, so removing in-progress entries cannot resurrect a stale resume card. The division is then exact: Continue Watching offers episodes the viewer has started and not finished, Next Up offers the episode after the ones they finished | Repository | UR-059 | Done |
|
||||
| DR-200 | The lockscreen notification is exempt from `POST_NOTIFICATIONS`, because of the **session token**, not because it belongs to a foreground service — and the difference is what the code now records. `POST_NOTIFICATIONS` was declared in the manifest and requested nowhere, so on Android 13+ it sat permanently denied; an audit read that as a threat to UR-006, since the media notification is what carries the lockscreen transport controls. It is not. Android's own wording is that the permission covers "non-exempt (including Foreground Services (FGS)) notifications", with denied users seeing FGS notices "in the Task Manager but [not] in the notification drawer" — so an FGS notification is explicitly *not* exempt — while separately "Notifications related to media sessions are exempt from this behavior change". The platform predicate is `Notification.isMediaNotification()`, which requires `MediaStyle` **and** a non-null `EXTRA_MEDIA_SESSION`, and it is byte-identical across API 33–36. `NotificationManagerService` uses it to decide whether to drop the post, and SystemUI's media carousel (`MediaDataProcessor.onNotificationAdded`) is gated on the *same* predicate — so a token-less notification is not merely absent from the shade, it never reaches the notification listener and the lockscreen/Quick-Settings controls do not exist at all. Confirmed on device (HONOR ROD2-W09, Android 16 / SDK 36): appops `POST_NOTIFICATION: ignore`, `granted=false`, and the service simultaneously `isForeground=true` with `foregroundNoti=Notification(category=transport actions=3 vis=PUBLIC)`. So **no runtime permission request is added** — a prompt the app does not need is a prompt that can be permanently denied for nothing — and no `checkSelfPermission` gate is placed on `startForeground`, which would trade a cosmetic problem for the "did not then call Service.startForeground()" kill. What is added is the guard that matches the real precondition: `mediaSessionCompat?.sessionToken` is a null-safe call, and the exemption hangs entirely on it, so both builders now bind the token once and log an error if it is ever null while the permission is denied — converting a failure that is invisible unless the tester happened to deny the permission (most grant it reflexively) into a logcat line. The manifest declaration is *kept*, unrequested, and documented: media3 does not need it (media3-session declares no permissions and the `MediaSessionService` guide asks only for the two `FOREGROUND_SERVICE` ones), but the exemption covers media and self-managed-call notifications only, so a download-completion notice (UR-011) would be an ordinary notification and silently dropped — keeping the declaration is what makes adding one a one-file change | Android | UR-006 | Done |
|
||||
| DR-201 | A lockscreen skip means different things depending on what is playing, and the backend decides which. `onSkipToNext`/`onSkipToPrevious` forwarded a bare `"next"`/`"previous"` to Rust, which always advanced the queue — correct for music, wrong for a video whose audio is running through a background-audio handoff (UR-040), where the buttons should scrub. Pressing skip to re-hear a line jumped to the next *episode* instead. `resolve_skip_action` in `player/seek.rs` maps the command to either `Advance` or `SeekTo`, and `is_background_audio_active()` is the whole test: the handoff exists only for video, and an episode played through it reports `MediaType::Audio`, so media type cannot distinguish the case. Forward jumps 30s, back 10s — asymmetric because the back button replays dialogue just missed rather than travels — and both clamp to `[0, duration]`, since a negative offset is rejected by backends and a seek past the end reads as EOF and would advance, the very outcome being prevented. Routed through the same spawn-then-`seek_absolute` path as the scrubber, because a handoff seek re-opens the stream and must not run under the blocking lock (DR-159). The Kotlin keeps sending the same opaque command; only the `PlaybackStateCompat` gains `ACTION_FAST_FORWARD`/`ACTION_REWIND` so the system draws seek affordances rather than skip arrows that lie about what they do | Playback | UR-040, UR-006 | Done |
|
||||
| DR-199 | The webview stops undoing the network security config. `MainActivity.configureWebViewSettings` set `mixedContentMode = MIXED_CONTENT_ALWAYS_ALLOW` together with `allowFileAccess = true` and `allowContentAccess = true`, which is a blanket cleartext opt-in reached by hand — exactly the thing `network_security_config.xml` exists to prevent and its own comment warns against (DR-138). Nothing needed any of the three. `file://` is never loaded: cached thumbnails go through `convertFileSrc`, which on Android resolves to `http://asset.localhost/…` and is answered by wry's request interceptor rather than the filesystem, and downloaded media goes over the loopback HTTP server (DR-137), which exists precisely because the asset/file route cannot stream a large file. `content://` is never loaded either — the manifest's `FileProvider` is for outbound share intents, not webview navigation. And mixed content never arises: Tauri serves the UI from `http://tauri.localhost` (`use_https_scheme` defaults false and is not set in `tauri.conf.json`), while both `127.0.0.1` and `asset.localhost` are loopback/`.localhost` origins that Chromium treats as potentially trustworthy, so they are not mixed content to begin with. A plain-HTTP *remote* Jellyfin server would be, but the network security config already rejects it before any mixed-content check runs — so `ALWAYS_ALLOW` bought nothing and only widened the hole. `COMPATIBILITY_MODE` rather than `NEVER_ALLOW` is a deliberate hedge and not the default — the platform default at targetSdk 21+ *is* `NEVER_ALLOW` — because none of this can be verified anywhere but a device, and compatibility mode keeps passive content (images) working if the analysis missed a path. `allowFileAccess = false` restores the targetSdk-30+ default; `allowContentAccess = false` is a genuine tightening (its default is true) and is the first thing to look at if something that used to render stops. The two files now cross-reference each other so the pair cannot drift apart again | Security | UR-071 | Done (pending device verification) |
|
||||
| DR-194 | Stale pixels in the letterbox bars — the rotation "flash of the previous frame", a ghost control bar stranded in the top bar, each new clock digit drawn over the last (`35:42` with the `1` still showing through the `2`), and menus (sleep timer, quality) leaving their imprint behind. One cause for all of it: **nothing painted the bars.** The window surface is opaque (the theme is not translucent), and for an opaque surface HWUI deliberately does not clear the damaged region before replaying a frame — it assumes the view hierarchy covers every pixel. That hierarchy is window background → video `TextureView` → transparent WebView, and `fitSurfaceToScreen` sizes the TextureView to the *letterboxed* video rect, so the bars were the window background's alone to paint. `setTransparent(true)` cleared that background to `TRANSPARENT`, leaving the bars painted by nobody and whatever was last in the framebuffer surviving in them. Fixed by keeping the window background opaque black while compositing; the WebView's own background is what lets the video through, and the TextureView is drawn on top of the window background, so an opaque one cannot hide it. Three earlier fixes aimed at the window's rotation animation and at TextureView frame-retention (two `postOnAnimation` hops, an `onSurfaceTextureUpdated` reveal, then `ROTATION_ANIMATION_JUMPCUT` + `FLAG_FULLSCREEN`) all missed, because the pixels were never the animation's; the alpha-hiding among them made it worse by blanking the one view that reliably paints its own rect. Those are removed, `FLAG_FULLSCREEN` included — it fought edge-to-edge insets for no gain. Verified on device: ghosting reproduced with native video on, then absent after the fix, across playback, the control bar and a rotation round-trip | Android | UR-003, UR-066 | Done |
|
||||
| DR-193 | Play/pause reaches the player that is actually rendering. `toggle_playback`, `play` and `pause` all route to the webview element when `is_html5_active()`, which is `html5_playing.is_some()` — a flag written **only** by the element's own state reports and cleared only when it reports "stopped"/"idle" (or on a background-audio handoff). An element that went away without that final report, or webview-rendered music earlier in the same process, therefore left the flag set, and on Android's native video path every transport intent was emitted as a `ControlCommand` at an element that no longer existed: the pause button did nothing, from the on-screen tap and from the control bar alike, while seek and skip kept working because `player_seek_video` decides elsewhere. Whether it happened at all depended on what had played before, which is exactly what made it read as flaky rather than broken. `load_and_play` — the native load path, and the one the HTML5 video path deliberately avoids via `set_current_item` — now clears the flag, because loading into the native backend *is* the statement that native renders this item. Nothing is lost on the webview path: an element re-establishes its own authority the moment it reports again, so this is the existing "element is gone" semantics applied where it can be known directly rather than inferred from a report that may never arrive | Playback | UR-005, UR-003 | Done |
|
||||
| DR-192 | Native video presents through a **TextureView**, not a SurfaceView. A SurfaceView renders on its own layer *outside* the app window and punches a transparent region through it; everything drawn above that hole — for us the entire Svelte UI in a transparent WebView — depends on that composition path, and Android's own graphics documentation states that "overlays do not currently work correctly with SurfaceView or TextureView". The consequences were four symptoms of one cause (DR-191): a frozen progress bar, controls that would not fade, rotation losing the transport UI, and overlays that lingered after the DOM removed them. A TextureView is an ordinary view whose frames are drawn as a texture in the window's normal rendering pass, so there is no second layer and no transparent region, and the WebView above composites like it would over any other view — which is why media3 offers `surface_type="texture_view"` and why it is the standard remedy for ExoPlayer overlay problems. The trade is accepted rather than hidden: TextureView costs more power and memory than SurfaceView and adds a frame of latency, but hardware decode through MediaCodec is untouched, so the reason native video exists survives it. `setVideoTextureView` installs ExoPlayer's own `SurfaceTextureListener`, so the old `SurfaceHolder.Callback` wiring is deleted rather than ported — adding a listener of ours would displace it and the video would never appear. PiP needs no change, since a TextureView is a View and the aspect-ratio probe reads its measured bounds | Android | UR-003, UR-004, UR-041 | Done |
|
||||
@@ -366,6 +390,7 @@ Internal architecture, components, and application logic.
|
||||
| DR-137 | Local media is served to the player over a loopback HTTP server, not the asset protocol. Tauri's `asset` protocol answers a request carrying no `Range` header by reading the whole file into memory, and only advertises `Accept-Ranges: bytes` from *inside* its range branch — so the first request never learns ranges exist and a multi-gigabyte body is attempted instead. Chromium abandoned it with `PIPELINE_ERROR_READ` after ~31s, which reached the user as "downloaded video does not play offline". Real HTTP on `127.0.0.1` is chosen over a custom URI scheme deliberately: range support becomes a property of the transport rather than depending on whether a platform's webview forwards `Range` to a custom scheme. No response ever exceeds a 4 MiB chunk and bodies stream from the file handle, so memory is bounded regardless of file size. Because **loopback is shared between apps on Android**, the server binds `127.0.0.1` only and every URL carries a random per-session token; paths are additionally confined to the app data directory, so a leaked URL cannot read outside it. This is stage 1 of making the server the single media origin — remote passthrough and download-while-watching are deliberately out of scope here | Playback | UR-071 | Done |
|
||||
| DR-138 | Loopback is exempted from Android's cleartext ban, and nothing else is. Release builds set `usesCleartextTraffic="false"`, so the webview's request to the local media server (DR-137) was rejected by network security policy before any I/O — `<video>` failed in the same millisecond as `loadstart`, with `NETWORK_NO_SOURCE` and no server-side log at all, which is why it looked identical to a missing file. A `network-security-config` resource permits cleartext for `127.0.0.1` only and keeps `base-config cleartextTrafficPermitted="false"`, so a remote server must still be HTTPS; this is deliberately not a blanket opt-in. The manifest attribute is ignored once the config is present, so the config is the single authority. `sync-android-sources.sh` also had to learn to copy `res/xml`, which it skipped — the manifest references the resource, so a missed copy fails the resource link rather than degrading quietly | Security | UR-071 | Done |
|
||||
| DR-093 | Traceability coverage gate derives its requirement denominators from `requirements.md` at run time rather than hardcoded literals: `countDefinedRequirements` counts an ID only where it leads a markdown table row (ignoring the "Traces To" column and prose) and deduplicates IDs listed both in the definition tables and in the §3 traceability matrix; `computeCoverage` reports the *intersection* of traced and defined IDs so an ID traced in code but absent from `requirements.md` is surfaced as `orphaned` instead of inflating the ratio past 100%. UT/IT test identifiers are excluded as a separate taxonomy. CI and `bun run traces:coverage` share this computation and fail on both a sub-threshold and an impossible >100% result | Tooling | - | Done |
|
||||
| DR-198 | The webview runs under a real Content-Security-Policy, and the asset protocol is scoped to the one directory it still serves. `csp` was `null`, which disables CSP entirely: any script that reached the web layer — through a future `{@html}`, a dependency, or a devtools paste — would have inherited the whole IPC surface, and with it the user's session. `script-src 'self'` (Tauri injects a nonce for SvelteKit's inline bootstrap script at build time, so no `'unsafe-inline'` is needed) plus `object-src`/`frame-src 'none'` and `base-uri 'self'` is the part that is genuinely restrictive. `img-src`/`media-src`/`connect-src` cannot be: the Jellyfin origin is typed in by the user at run time and is commonly plain `http` on a LAN, so they allow `http:`/`https:` — a wide grant for *data*, but one that still bars `file:`, `filesystem:` and scripting schemes, and leaves `script-src` untouched. `style-src` keeps `'unsafe-inline'` because Svelte compiles `style="…"` attributes (including `app.html`'s `display: contents` wrapper) into markup; this is safe only while no `<style>` element survives into `index.html`, since a nonce there would make Tauri's injection outrank — and therefore void — `'unsafe-inline'`. `worker-src blob:` and `media-src blob:` are hls.js: it demuxes in a worker built from a blob and attaches MSE through `URL.createObjectURL`. `asset:` and `http://asset.localhost` are the same protocol under the two naming schemes `convertFileSrc` emits (custom scheme on Linux/macOS, `http` host on Windows/Android); `ipc:`/`http://ipc.localhost` is the invoke transport, which would otherwise be blocked by `connect-src`. A run-time CSP naming the server origin exactly was rejected: Tauri computes the header from immutable config when it serves the HTML, so it would mean rebuilding config and reloading the webview on every server change, for a policy the user can already point anywhere. The asset-protocol scope narrows from `$APPDATA/**` to `$APPDATA/thumbnails/**` — since DR-137 moved downloaded media to the loopback server, `imageCache` is the only `convertFileSrc` caller left, so the database and the encrypted-token fallback file no longer sit inside the grant | Security | UR-012, UR-071 | Done |
|
||||
|
||||
---
|
||||
|
||||
@@ -380,13 +405,13 @@ Internal architecture, components, and application logic.
|
||||
| UR-003 | IR-003, IR-004, IR-011 | DR-002, DR-004, DR-010, DR-182, DR-183, DR-184, DR-185, DR-186, DR-187, DR-188, DR-190, DR-191, DR-192, DR-193, DR-194, DR-195, DR-196 |
|
||||
| UR-004 | IR-003, IR-004, IR-008, IR-011 | DR-002, DR-004, DR-006, DR-129, DR-171, DR-176, DR-177, DR-181, DR-182, DR-183, DR-185, DR-188 |
|
||||
| UR-005 | - | DR-001, DR-005, DR-009, DR-178, DR-179, DR-186, DR-193, DR-195 |
|
||||
| UR-006 | IR-005, IR-006, IR-007, IR-008 | - |
|
||||
| UR-006 | IR-005, IR-006, IR-007, IR-008 | DR-200, DR-201 |
|
||||
| UR-007 | IR-010 | DR-007, DR-008, DR-016 |
|
||||
| UR-008 | IR-010 | DR-007, DR-011 |
|
||||
| UR-009 | IR-009, IR-010, IR-011 | - |
|
||||
| UR-010 | IR-012, IR-021 | DR-037, DR-059 |
|
||||
| UR-011 | IR-013 | DR-003, DR-015, DR-018 |
|
||||
| UR-012 | IR-009, IR-014 | - |
|
||||
| UR-012 | IR-009, IR-014 | DR-198 |
|
||||
| UR-013 | IR-013 | DR-017 |
|
||||
| UR-014 | IR-010 | DR-014, DR-019 |
|
||||
| UR-015 | - | DR-005, DR-020 |
|
||||
@@ -394,8 +419,8 @@ Internal architecture, components, and application logic.
|
||||
| UR-017 | - | DR-014, DR-021 |
|
||||
| UR-018 | IR-013 | DR-015, DR-018, DR-173 |
|
||||
| UR-019 | IR-015 | DR-022 |
|
||||
| UR-020 | IR-016, IR-018 | DR-023, DR-176 |
|
||||
| UR-021 | IR-016, IR-019 | DR-024 |
|
||||
| UR-020 | IR-016, IR-018 | DR-023, DR-176 | <!-- IR-018 delivered by ExoPlayer + HTML5 `<track>`, not libmpv -->
|
||||
| UR-021 | IR-016, IR-019 | DR-024 | <!-- IR-019 delivered by ExoPlayer + HLS stream re-open, not libmpv -->
|
||||
| UR-022 | IR-017 | DR-025 |
|
||||
| UR-023 | IR-010 | DR-026, DR-047, DR-048, DR-049 |
|
||||
| UR-024 | IR-010 | DR-027 |
|
||||
@@ -414,7 +439,7 @@ Internal architecture, components, and application logic.
|
||||
| UR-037 | IR-010 | DR-042 |
|
||||
| UR-038 | IR-010 | DR-043 |
|
||||
| UR-039 | - | DR-045, DR-046 |
|
||||
| UR-040 | IR-025 | DR-051, DR-052, DR-129, DR-130, DR-159, DR-178, DR-179, DR-180, DR-183, DR-190, DR-196 |
|
||||
| UR-040 | IR-025 | DR-051, DR-052, DR-129, DR-130, DR-159, DR-178, DR-179, DR-180, DR-183, DR-190, DR-196, DR-201 |
|
||||
| UR-041 | IR-026 | DR-053, DR-160, DR-161, DR-172, DR-182, DR-183, DR-184, DR-185, DR-188 |
|
||||
| UR-042 | IR-009, IR-014 | DR-054 |
|
||||
| UR-043 | IR-027 | DR-055 |
|
||||
@@ -444,7 +469,7 @@ Internal architecture, components, and application logic.
|
||||
| UR-068 | - | DR-119 |
|
||||
| UR-069 | - | DR-113, DR-114, DR-120 |
|
||||
| UR-070 | - | DR-121, DR-122 |
|
||||
| UR-071 | IR-032 | DR-123, DR-124, DR-125, DR-126, DR-127, DR-128, DR-133, DR-134, DR-135, DR-136, DR-137, DR-138, DR-170, DR-171, DR-180 |
|
||||
| UR-071 | IR-032 | DR-123, DR-124, DR-125, DR-126, DR-127, DR-128, DR-133, DR-134, DR-135, DR-136, DR-137, DR-138, DR-170, DR-171, DR-180, DR-198, DR-199 |
|
||||
| UR-072 | - | DR-156 |
|
||||
| UR-073 | - | DR-158 |
|
||||
| UR-074 | - | DR-162, DR-177, DR-181 |
|
||||
@@ -636,6 +661,7 @@ Internal architecture, components, and application logic.
|
||||
| UT-182 | An HLS video URL never carries `StartTimeTicks` — with a position supplied or not — while the master playlist, codec, media source and chosen audio track still ride on it | DR-181 | Done |
|
||||
| UT-183 | A reloaded stream is resumed by seeking the element to the absolute position with the transcode offset cleared to zero — never by carrying the position as an offset base, which since DR-181 would display the position while playing the item from its start — and a reload to 0:00 waits for no seek | DR-181 | Done |
|
||||
| UT-184 | The native reveal rule fires on `state === "playing"` and on a position tick carrying a position or a duration, and on nothing else — not `buffering`, `paused`, `stopped`, `ended` or `error`, not an empty tick, and not a negative position | DR-182 | Done |
|
||||
| UT-188 | The control-bar auto-hide rule permits hiding only during uninterrupted playback: it declines while paused, while a seek is in flight, and while a track/subtitle/quality menu is open — asserted against the pure `shouldHideControls` rule rather than a clock or a DOM | DR-189 | Done |
|
||||
| UT-189 | On the native path the player never calls `player_report_state` — driven through the real 10-second progress interval under fake timers, which is the call site that mattered; asserting on a freshly mounted player passes with the guard deleted and guards nothing | DR-195 | Done |
|
||||
| UT-187 | On the native path the play overlay follows the backend: it clears when the backend resumes after a pause and is raised again when the backend pauses, and the system bars are hidden on player entry rather than only by the fullscreen button | DR-186, DR-187 | Done |
|
||||
| UT-186 | Every attribute the native-video compositing block in app.css targets is set somewhere in the app — `[data-app-shell]` in particular — so a selector aimed at nothing fails the suite instead of failing silently on a device | DR-185 | Done |
|
||||
@@ -643,6 +669,12 @@ Internal architecture, components, and application logic.
|
||||
| UT-190 | `build_next_up_endpoint` sends `EnableResumable=false` with the user and limit, and no `SeriesId` filter when none was requested | DR-197, JA-036 | Done |
|
||||
| UT-191 | A per-series next-up query keeps `SeriesId` and the resumable exclusion, and defaults the limit | DR-197 | Done |
|
||||
| UT-192 | `filterInProgressNextUpItems` drops an episode present in the resume list, keeps the genuinely unstarted next episode, leaves the rest of the row intact, and is a no-op when nothing is in progress | DR-197 | Done |
|
||||
| UT-193 | The shipped Tauri security config stays restrictive: `csp` is set, `script-src` carries no `'unsafe-inline'`/`'unsafe-eval'`/wildcard, `object-src`/`frame-src` are `'none'`, the directives playback needs (asset scheme, loopback, `blob:`, `ipc:`) are present, and the asset-protocol scope covers only the thumbnail cache — never the storage root that holds the database | DR-198 | Done |
|
||||
| UT-194 | Normal audio (no background-audio handoff) keeps queue advance on both skip buttons | DR-201 | Done |
|
||||
| UT-195 | In background-audio mode a skip scrubs +30s/-10s instead of advancing the queue — the reported defect | DR-201 | Done |
|
||||
| UT-196 | Skipping back near the start clamps to zero rather than seeking negative | DR-201 | Done |
|
||||
| UT-197 | Skipping forward near the end clamps to the duration rather than running past it into an EOF-driven advance | DR-201 | Done |
|
||||
| UT-198 | An unknown duration still scrubs and still refuses to go negative | DR-201 | Done |
|
||||
|
||||
### Integration Tests
|
||||
|
||||
@@ -655,8 +687,8 @@ Internal architecture, components, and application logic.
|
||||
| IT-005 | MPRIS lockscreen controls on Linux | IR-005, UR-006 | Pending |
|
||||
| IT-006 | Offline mode with local database | IR-013, UR-002 | Pending |
|
||||
| IT-007 | Media download and local playback | DR-015, UR-011 | Pending |
|
||||
| IT-008 | Subtitle track selection via libmpv | IR-018, UR-020 | Pending |
|
||||
| IT-009 | Audio track selection via libmpv | IR-019, UR-021 | Pending |
|
||||
| IT-008 | Subtitle track selection on the video backends (ExoPlayer sideloaded tracks; HTML5 `<track>` children) — *not* via libmpv, which does not implement it | IR-018, UR-020 | Pending |
|
||||
| IT-009 | Audio track selection on the video backends (ExoPlayer track switch; HTML5 stream re-open at the chosen `AudioStreamIndex`) — *not* via libmpv, which does not implement it | IR-019, UR-021 | Pending |
|
||||
| IT-010 | Playback progress sync to Jellyfin | IR-015, UR-025 | Pending |
|
||||
| IT-011 | Resume playback from server position | IR-015, UR-019 | Pending |
|
||||
| IT-012 | Equalizer bands via libmpv | IR-020, UR-027 | Pending |
|
||||
|
||||
+42
-10
@@ -15,7 +15,7 @@ The CI/CD pipeline automatically validates that code changes are properly traced
|
||||
Traceability validation lives in `.gitea/workflows/traceability-check.yml`:
|
||||
|
||||
- ✅ Automatic trace extraction
|
||||
- ✅ Coverage validation against minimum threshold (50%)
|
||||
- ✅ Coverage validation against minimum threshold (82%, ratcheted)
|
||||
- ✅ Modified file checking
|
||||
- ✅ Artifact preservation
|
||||
- ✅ Summary reports
|
||||
@@ -43,7 +43,7 @@ Extracts all TRACES comments from:
|
||||
|
||||
### 2. Coverage Thresholds
|
||||
The workflow checks:
|
||||
- **Minimum overall coverage:** 50%
|
||||
- **Minimum overall coverage:** 82% (`MIN_THRESHOLD`)
|
||||
|
||||
Denominators are **derived from `docs/requirements.md` at run time** — they are
|
||||
never hardcoded here or in the workflow. Run `bun run traces:coverage` for the
|
||||
@@ -61,8 +61,39 @@ a `TRACES:` comment but is not defined in `requirements.md` is reported as
|
||||
**orphaned** and does not count toward coverage. UT/IT test identifiers are a
|
||||
separate taxonomy and are excluded entirely.
|
||||
|
||||
The workflow **fails** and blocks merge if coverage drops below 50% — or if it
|
||||
computes above 100%, which can only mean the gate is miscounting.
|
||||
The workflow **fails** and blocks merge if coverage drops below the threshold —
|
||||
or if it computes above 100%, which can only mean the gate is miscounting.
|
||||
|
||||
#### Ratchet policy
|
||||
|
||||
`MIN_THRESHOLD` **only ever goes up.** It is deliberately set a few points below
|
||||
the coverage actually achieved (82 against a real 86%), so a genuine regression
|
||||
trips it. It previously sat at 50 while true coverage was 86%: nearly half the
|
||||
matrix could have rotted before CI objected.
|
||||
|
||||
When coverage rises durably, raise the threshold to just under the new figure.
|
||||
**Never lower it to make a red build pass** — add the missing TRACES comments
|
||||
instead. The same number lives in `MIN_COVERAGE_PERCENT` in
|
||||
`scripts/extract-traces.ts` (so `bun run traces:coverage` gates locally on the
|
||||
same bar); `scripts/extract-traces.test.ts` fails if the two drift apart.
|
||||
|
||||
### 2b. Dangling requirement IDs
|
||||
|
||||
```bash
|
||||
bun run traces:validate
|
||||
```
|
||||
|
||||
Every ID named by a `TRACES:` comment must be defined as a table row in
|
||||
`docs/requirements.md`. The extractor used to accept any well-formed ID
|
||||
silently, so a typo or a rename that missed a call site passed unnoticed —
|
||||
`DR-189` and `UT-188` were referenced from three source files, defined nowhere,
|
||||
for months.
|
||||
|
||||
This check spans **all six** ID types (UR/IR/DR/JA/UT/IT), unlike the coverage
|
||||
`orphaned` list above, which considers only the four requirement types so that
|
||||
UT/IT noise cannot bury a real typo in the ratio's reporting. The workflow step
|
||||
**fails the build** on any dangling ID and prints each offender with the files
|
||||
that reference it.
|
||||
|
||||
### 3. Modified File Checking
|
||||
On pull requests, the workflow:
|
||||
@@ -120,13 +151,13 @@ TRACES: [UR-###, ...] | [IR-###, ...] | [DR-###, ...] | [JA-###, ...]
|
||||
|
||||
### On Push to Main Branch
|
||||
1. ✅ Extracts all traces from code
|
||||
2. ✅ Validates coverage is >= 50%
|
||||
2. ✅ Validates coverage is >= 82%
|
||||
3. ✅ Generates full traceability report
|
||||
4. ✅ Saves report as artifact
|
||||
|
||||
### On Pull Request
|
||||
1. ✅ Extracts all traces
|
||||
2. ✅ Validates coverage >= 50%
|
||||
2. ✅ Validates coverage >= 82%
|
||||
3. ✅ Checks modified files for TRACES
|
||||
4. ✅ Warns if new code lacks TRACES
|
||||
5. ✅ Suggests proper format
|
||||
@@ -134,7 +165,8 @@ TRACES: [UR-###, ...] | [IR-###, ...] | [DR-###, ...] | [JA-###, ...]
|
||||
|
||||
### Failure Scenarios
|
||||
The workflow **fails** (blocks merge) if:
|
||||
- Coverage drops below 50%
|
||||
- Coverage drops below 82%
|
||||
- A `TRACES:` comment names an ID `docs/requirements.md` does not define
|
||||
- JSON extraction fails
|
||||
- Invalid trace format
|
||||
|
||||
@@ -174,7 +206,7 @@ made the broken CI arithmetic look plausible for so long.
|
||||
As of July 2026 overall coverage is ~86% (182/212).
|
||||
|
||||
### Targets
|
||||
- **Short term** (Sprint): Maintain ≥50% overall
|
||||
- **Short term** (Sprint): Maintain ≥82% overall (the current ratchet)
|
||||
- **Medium term** (Month): Reach 70% overall coverage
|
||||
- **Long term** (Release): Reach 90% coverage with focus on:
|
||||
- IR requirements (API clients)
|
||||
@@ -209,14 +241,14 @@ When submitting a pull request:
|
||||
|
||||
- [ ] All new code has TRACES comments linking to requirements
|
||||
- [ ] TRACES format is correct: `// TRACES: UR-001 | DR-002`
|
||||
- [ ] Workflow passes (coverage ≥ 50%)
|
||||
- [ ] Workflow passes (coverage ≥ 82%)
|
||||
- [ ] No coverage regressions
|
||||
- [ ] Artifact traceability report was generated
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "Coverage below minimum threshold"
|
||||
**Problem:** Workflow fails with coverage < 50%
|
||||
**Problem:** Workflow fails with coverage < 82%
|
||||
|
||||
**Solution:**
|
||||
1. Run `bun run traces:json` locally
|
||||
|
||||
+2331
-1889
File diff suppressed because it is too large
Load Diff
@@ -133,13 +133,14 @@ bun run traces:json | jq '.requirements."UR-005"'
|
||||
### Before Committing
|
||||
1. Ensure all new code has TRACES
|
||||
2. Format is correct: `// TRACES: ...`
|
||||
3. Requirements exist in README.md
|
||||
4. No typos in requirement IDs
|
||||
3. Requirements exist in `docs/requirements.md` — `bun run traces:validate`
|
||||
4. No typos in requirement IDs (same command catches them)
|
||||
|
||||
## CI/CD Validation
|
||||
|
||||
The workflow automatically checks:
|
||||
- ✅ Coverage stays >= 50%
|
||||
- ✅ Coverage stays >= 82% (a ratchet — raise it, never lower it)
|
||||
- ✅ Every traced ID is defined in `docs/requirements.md`
|
||||
- ✅ New files have TRACES
|
||||
- ✅ JSON format is valid
|
||||
- ✅ Reports are generated
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "jellytau",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.0",
|
||||
"description": "",
|
||||
"type": "module",
|
||||
"packageManager": "bun@1.3.5",
|
||||
@@ -39,6 +39,7 @@
|
||||
"traces:json": "bun run scripts/extract-traces.ts --format json",
|
||||
"traces:markdown": "bun run scripts/extract-traces.ts --format markdown > docs/traceability.md",
|
||||
"traces:coverage": "bun run scripts/extract-traces.ts --format coverage",
|
||||
"traces:validate": "bun run scripts/extract-traces.ts --format validate",
|
||||
"release:notes": "bun run scripts/release-notes.ts"
|
||||
},
|
||||
"license": "MIT",
|
||||
|
||||
+10
-2
@@ -69,7 +69,8 @@ Extract requirement IDs (TRACES) from source code and generate a traceability ma
|
||||
bun run traces # Generate markdown report
|
||||
bun run traces:json # Generate JSON report
|
||||
bun run traces:markdown # Save to docs/traceability.md
|
||||
bun run traces:coverage # Coverage gate — exits non-zero below 50%
|
||||
bun run traces:coverage # Coverage gate — exits non-zero below the ratchet
|
||||
bun run traces:validate # Dangling-ID gate — every traced ID must be defined
|
||||
```
|
||||
|
||||
The script scans all TypeScript, Svelte, and Rust files (plus `scripts/`)
|
||||
@@ -84,6 +85,12 @@ derived from `docs/requirements.md` at run time; they are never hardcoded. An ID
|
||||
that appears in a `TRACES:` comment but is not defined in `requirements.md` is
|
||||
reported as *orphaned* and does not count toward coverage (see DR-093).
|
||||
|
||||
**`bun run traces:validate` is the dangling-ID gate.** It fails if any traced ID
|
||||
— including `UT`/`IT`, which coverage deliberately ignores — is not defined as a
|
||||
table row in `requirements.md`, printing each offender with the files that
|
||||
reference it. Without it the extractor accepted any well-formed ID silently, so
|
||||
typos and renames that missed a call site went unreported for months.
|
||||
|
||||
> **Removed:** `check-req-coverage.sh`, `check-test-coverage.sh`, and
|
||||
> `find-req-implementations.sh` were deleted in July 2026. They read an
|
||||
> undocumented `@req:` tag convention parallel to `TRACES:`, grepped `src-tauri/`
|
||||
@@ -104,7 +111,8 @@ See [docs/traceability.md](../docs/traceability.md) for the latest generated map
|
||||
|
||||
The traceability system is integrated with Gitea Actions CI/CD:
|
||||
- Automatically validates TRACES on every push and pull request
|
||||
- Enforces minimum 50% coverage threshold
|
||||
- Enforces a minimum coverage threshold (a ratchet: raise it, never lower it)
|
||||
- Fails on dangling IDs — traced but undefined in `requirements.md`
|
||||
- Warns if new code lacks TRACES comments
|
||||
- Generates traceability reports automatically
|
||||
|
||||
|
||||
@@ -14,7 +14,17 @@
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { countDefinedRequirements, computeCoverage } from "./extract-traces";
|
||||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
import {
|
||||
countDefinedRequirements,
|
||||
computeCoverage,
|
||||
findDanglingIds,
|
||||
MIN_COVERAGE_PERCENT,
|
||||
} from "./extract-traces";
|
||||
|
||||
// import.meta.dir is Bun-only; derive from import.meta.url under vitest.
|
||||
const HERE = path.dirname(new URL(import.meta.url).pathname);
|
||||
|
||||
describe("countDefinedRequirements", () => {
|
||||
it("counts a well-formed table row as a defined requirement", () => {
|
||||
@@ -82,6 +92,80 @@ Some prose explaining that UR-005 relates to DR-001 and JA-002.
|
||||
expect(defined.ids.has("DR-050")).toBe(true);
|
||||
expect(defined.ids.has("UR-999")).toBe(false);
|
||||
});
|
||||
|
||||
it("collects UT/IT rows separately, out of the coverage denominator", () => {
|
||||
// §4 defines the test taxonomy. Those rows must be known (so a TRACES
|
||||
// comment may name them) without ever moving the coverage ratio.
|
||||
const md = `
|
||||
| UR-001 | A | High | Done |
|
||||
| UT-001 | Player state transitions | DR-001 | Pending |
|
||||
| IT-004 | Playback end-to-end | DR-002 | Pending |
|
||||
`;
|
||||
const defined = countDefinedRequirements(md);
|
||||
expect(defined.total).toBe(1);
|
||||
expect(defined.ids.has("UT-001")).toBe(false);
|
||||
expect(defined.testIds.has("UT-001")).toBe(true);
|
||||
expect(defined.testIds.has("IT-004")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("findDanglingIds", () => {
|
||||
const defined = {
|
||||
UR: 1,
|
||||
IR: 0,
|
||||
DR: 1,
|
||||
JA: 0,
|
||||
total: 2,
|
||||
ids: new Set(["UR-001", "DR-001"]),
|
||||
testIds: new Set(["UT-001"]),
|
||||
};
|
||||
|
||||
it("flags a requirement ID that requirements.md does not define", () => {
|
||||
expect(findDanglingIds(["UR-001", "DR-189"], defined)).toEqual(["DR-189"]);
|
||||
});
|
||||
|
||||
it("flags an undefined UT/IT id, which the coverage orphan list cannot", () => {
|
||||
// The gap this closes: computeCoverage deliberately ignores UT/IT, so
|
||||
// UT-188 sat in three source files, defined nowhere, entirely unreported.
|
||||
expect(computeCoverage(["UT-188"], defined).orphaned).toEqual([]);
|
||||
expect(findDanglingIds(["UT-188"], defined)).toEqual(["UT-188"]);
|
||||
});
|
||||
|
||||
it("accepts every ID that is defined, requirement or test", () => {
|
||||
expect(findDanglingIds(["UR-001", "DR-001", "UT-001"], defined)).toEqual([]);
|
||||
});
|
||||
|
||||
it("deduplicates and sorts, so one typo is reported once", () => {
|
||||
expect(
|
||||
findDanglingIds(["DR-189", "DR-189", "UR-999", "DR-189"], defined)
|
||||
).toEqual(["DR-189", "UR-999"]);
|
||||
});
|
||||
|
||||
it("ignores IDs whose prefix is not a known trace type", () => {
|
||||
// e.g. an unrelated "AB-123" caught by the loose ID regex.
|
||||
expect(findDanglingIds(["AB-123"], defined)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("coverage threshold", () => {
|
||||
it("matches MIN_THRESHOLD in the Gitea traceability workflow", () => {
|
||||
// Two files must agree on the gate: the script (local `traces:coverage`)
|
||||
// and the workflow. Drift means the local gate and CI disagree about what
|
||||
// passes, which is how the 50%-while-actually-86% slack went unnoticed.
|
||||
const workflow = fs.readFileSync(
|
||||
path.resolve(HERE, "../.gitea/workflows/traceability-check.yml"),
|
||||
"utf-8"
|
||||
);
|
||||
const match = workflow.match(/^\s*MIN_THRESHOLD=(\d+)\s*$/m);
|
||||
expect(match).not.toBeNull();
|
||||
expect(Number(match![1])).toBe(MIN_COVERAGE_PERCENT);
|
||||
});
|
||||
|
||||
it("is a ratchet: never lower it to make a red build pass", () => {
|
||||
// Sanity bound. If coverage genuinely climbs, raise both numbers together.
|
||||
expect(MIN_COVERAGE_PERCENT).toBeGreaterThanOrEqual(82);
|
||||
expect(MIN_COVERAGE_PERCENT).toBeLessThanOrEqual(100);
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeCoverage", () => {
|
||||
@@ -92,6 +176,7 @@ describe("computeCoverage", () => {
|
||||
JA: 0,
|
||||
total: 4,
|
||||
ids: new Set(["UR-001", "UR-002", "DR-001", "DR-002"]),
|
||||
testIds: new Set<string>(),
|
||||
};
|
||||
|
||||
it("computes coverage as traced ∩ defined over defined", () => {
|
||||
@@ -138,7 +223,15 @@ describe("computeCoverage", () => {
|
||||
});
|
||||
|
||||
it("reports 0% rather than NaN when nothing is defined", () => {
|
||||
const empty = { UR: 0, IR: 0, DR: 0, JA: 0, total: 0, ids: new Set<string>() };
|
||||
const empty = {
|
||||
UR: 0,
|
||||
IR: 0,
|
||||
DR: 0,
|
||||
JA: 0,
|
||||
total: 0,
|
||||
ids: new Set<string>(),
|
||||
testIds: new Set<string>(),
|
||||
};
|
||||
const cov = computeCoverage([], empty);
|
||||
expect(cov.percent).toBe(0);
|
||||
expect(Number.isNaN(cov.percent)).toBe(false);
|
||||
@@ -163,20 +256,23 @@ describe("live requirements.md", () => {
|
||||
// (total 114) while the real file had grown to 211. Update these numbers
|
||||
// deliberately when requirements are added — that edit is the signal the
|
||||
// denominator is live rather than frozen.
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
// import.meta.dir is Bun-only; derive from import.meta.url under vitest.
|
||||
const here = path.dirname(new URL(import.meta.url).pathname);
|
||||
const md = fs.readFileSync(
|
||||
path.resolve(here, "../docs/requirements.md"),
|
||||
path.resolve(HERE, "../docs/requirements.md"),
|
||||
"utf-8"
|
||||
);
|
||||
const defined = countDefinedRequirements(md);
|
||||
|
||||
expect(defined.UR).toBe(75);
|
||||
expect(defined.IR).toBe(32);
|
||||
expect(defined.DR).toBe(187);
|
||||
// 192 = 187 + four requirements added independently on four audit branches,
|
||||
// plus DR-201 (lockscreen skip resolution). Originally 191 = 187 + four
|
||||
// that landed together: DR-189 (control-bar auto-hide), DR-198 (asset
|
||||
// scope/CSP), DR-199 (webview mixed-content) and DR-200 (the
|
||||
// POST_NOTIFICATIONS media-session exemption; renumbered from 198 on
|
||||
// merge, where it collided). Each branch bumped for its own — merged,
|
||||
// they sum. Resolve this by summing, never by taking one side.
|
||||
expect(defined.DR).toBe(192);
|
||||
expect(defined.JA).toBe(36);
|
||||
expect(defined.total).toBe(330);
|
||||
expect(defined.total).toBe(335);
|
||||
});
|
||||
});
|
||||
|
||||
+103
-3
@@ -37,8 +37,27 @@ interface TracesData {
|
||||
/** Requirements *defined* in requirements.md — the coverage denominators. */
|
||||
defined?: { UR: number; IR: number; DR: number; JA: number; total: number };
|
||||
coverage?: CoverageResult;
|
||||
/** Traced IDs of any type that requirements.md does not define. */
|
||||
dangling?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimum overall requirement coverage the traceability gate accepts.
|
||||
*
|
||||
* **Ratchet policy: this number only ever goes up.** It is set a few points
|
||||
* below the coverage actually achieved, so a real regression trips it instead of
|
||||
* being absorbed by slack. It sat at 50 while true coverage was 86%, which meant
|
||||
* half the matrix could rot before CI noticed. When coverage rises durably,
|
||||
* raise this to sit just under the new figure. Do **not** lower it to make a
|
||||
* failing build pass — add the missing TRACES comments instead.
|
||||
*
|
||||
* `.gitea/workflows/traceability-check.yml` carries the same number as
|
||||
* `MIN_THRESHOLD`; `scripts/extract-traces.test.ts` fails if the two drift.
|
||||
*
|
||||
* TRACES: | DR-093
|
||||
*/
|
||||
export const MIN_COVERAGE_PERCENT = 82;
|
||||
|
||||
// Repo root, derived from this script's location (scripts/ -> repo root).
|
||||
// Must NOT be hardcoded to a developer's machine, or CI checkouts see no files.
|
||||
//
|
||||
@@ -222,7 +241,10 @@ export interface DefinedRequirements {
|
||||
DR: number;
|
||||
JA: number;
|
||||
total: number;
|
||||
/** Requirement IDs (UR/IR/DR/JA) — the coverage denominator. */
|
||||
ids: Set<string>;
|
||||
/** Test IDs (UT/IT) from §4. A separate taxonomy: never part of coverage. */
|
||||
testIds: Set<string>;
|
||||
}
|
||||
|
||||
export interface CoverageResult {
|
||||
@@ -247,11 +269,18 @@ export interface CoverageResult {
|
||||
*/
|
||||
export function countDefinedRequirements(markdown: string): DefinedRequirements {
|
||||
const ids = new Set<string>();
|
||||
const ROW_ID = /^\|\s*(UR|IR|DR|JA)-(\d{3})\s*\|/;
|
||||
const testIds = new Set<string>();
|
||||
const ROW_ID = /^\|\s*(UR|IR|DR|JA|UT|IT)-(\d{3})\s*\|/;
|
||||
|
||||
for (const line of markdown.split("\n")) {
|
||||
const match = line.match(ROW_ID);
|
||||
if (match) ids.add(`${match[1]}-${match[2]}`);
|
||||
if (!match) continue;
|
||||
const id = `${match[1]}-${match[2]}`;
|
||||
// UT/IT rows live in §4 and are collected separately: they must not enter
|
||||
// the coverage denominator, but they still need to exist for a `TRACES:`
|
||||
// comment to be allowed to name them (see findDanglingIds).
|
||||
if (match[1] === "UT" || match[1] === "IT") testIds.add(id);
|
||||
else ids.add(id);
|
||||
}
|
||||
|
||||
const countOf = (type: string) =>
|
||||
@@ -264,9 +293,39 @@ export function countDefinedRequirements(markdown: string): DefinedRequirements
|
||||
JA: countOf("JA"),
|
||||
total: ids.size,
|
||||
ids,
|
||||
testIds,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Every traced ID that requirements.md defines nowhere — a typo, a rename that
|
||||
* missed a call site, or a reference to a deleted requirement.
|
||||
*
|
||||
* This is broader than `CoverageResult.orphaned`, which only ever considers the
|
||||
* four requirement types because a UT/IT entry among the orphans would corrupt
|
||||
* the coverage ratio's reporting. Dangling detection has no such constraint, so
|
||||
* it checks all six ID types against both defined sets. Before it existed, the
|
||||
* extractor accepted any well-formed ID silently: `DR-189` and `UT-188` were
|
||||
* referenced from `controlsVisibility.ts` and `VideoPlayer.svelte` for months
|
||||
* without being defined anywhere, and nothing reported it.
|
||||
*
|
||||
* TRACES: | DR-093
|
||||
*/
|
||||
export function findDanglingIds(
|
||||
tracedIds: string[],
|
||||
defined: DefinedRequirements
|
||||
): string[] {
|
||||
const KNOWN_TYPE = /^(UR|IR|DR|JA|UT|IT)-\d{3}$/;
|
||||
|
||||
const dangling = new Set(
|
||||
tracedIds
|
||||
.filter((id) => KNOWN_TYPE.test(id))
|
||||
.filter((id) => !defined.ids.has(id) && !defined.testIds.has(id))
|
||||
);
|
||||
|
||||
return [...dangling].sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* Coverage is the *intersection* of traced and defined IDs over defined IDs.
|
||||
*
|
||||
@@ -408,6 +467,13 @@ function reportCoverage(data: TracesData, minThreshold: number): number {
|
||||
console.log(" Fix the TRACES comment or add the requirement.");
|
||||
}
|
||||
|
||||
if (data.dangling && data.dangling.length > 0) {
|
||||
console.log("");
|
||||
console.log(
|
||||
`⚠️ Dangling IDs (incl. UT/IT): ${data.dangling.join(", ")} — run \`bun run traces:validate\`.`
|
||||
);
|
||||
}
|
||||
|
||||
// A ratio above 100% means the computation is broken (the condition that hid
|
||||
// the stale-denominator bug for so long). Fail loudly rather than report it.
|
||||
if (cov.percent > 100) {
|
||||
@@ -427,6 +493,37 @@ function reportCoverage(data: TracesData, minThreshold: number): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hard gate on dangling IDs: a `TRACES:` comment may only name an ID that
|
||||
* requirements.md actually defines. Prints every offender with the files that
|
||||
* reference it, so the fix is mechanical.
|
||||
*
|
||||
* TRACES: | DR-093
|
||||
*/
|
||||
function reportDangling(data: TracesData): number {
|
||||
const dangling = data.dangling ?? [];
|
||||
|
||||
if (dangling.length === 0) {
|
||||
console.log("✅ All traced IDs are defined in docs/requirements.md");
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log("❌ TRACES reference IDs that docs/requirements.md does not define:");
|
||||
console.log("");
|
||||
for (const id of dangling) {
|
||||
const files = [
|
||||
...new Set((data.requirements[id] ?? []).map((e) => e.file)),
|
||||
].sort();
|
||||
console.log(` ${id}`);
|
||||
for (const file of files) console.log(` ${file}`);
|
||||
}
|
||||
console.log("");
|
||||
console.log("Fix each one by either:");
|
||||
console.log(" • correcting the ID in the TRACES comment (typo/rename), or");
|
||||
console.log(" • adding the requirement as a table row in docs/requirements.md.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Main — guarded so this module stays importable from extract-traces.test.ts.
|
||||
if (import.meta.main) {
|
||||
const args = process.argv.slice(2);
|
||||
@@ -447,11 +544,14 @@ if (import.meta.main) {
|
||||
total: defined.total,
|
||||
};
|
||||
data.coverage = computeCoverage(allTraced, defined);
|
||||
data.dangling = findDanglingIds(allTraced, defined);
|
||||
|
||||
if (format === "json") {
|
||||
console.log(generateJson(data));
|
||||
} else if (format === "coverage") {
|
||||
process.exit(reportCoverage(data, 50));
|
||||
process.exit(reportCoverage(data, MIN_COVERAGE_PERCENT));
|
||||
} else if (format === "validate") {
|
||||
process.exit(reportDangling(data));
|
||||
} else {
|
||||
console.log(generateMarkdown(data));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* Guards the shipped webview security configuration.
|
||||
*
|
||||
* `csp` was `null` and the asset protocol was scoped to the whole storage root,
|
||||
* which is the directory holding the SQLite database and the encrypted-token
|
||||
* fallback file. Both are one-character regressions away and neither is visible
|
||||
* in any behavioural test, so they are asserted here instead: the restrictive
|
||||
* half of the policy must stay restrictive, and the permissive half must keep
|
||||
* the schemes playback actually needs.
|
||||
*
|
||||
* TRACES: UR-012, UR-071 | DR-198 | UT-193
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { readFileSync } from "fs";
|
||||
import { resolve } from "path";
|
||||
|
||||
const config = JSON.parse(
|
||||
readFileSync(resolve(__dirname, "../src-tauri/tauri.conf.json"), "utf-8")
|
||||
);
|
||||
|
||||
const security = config.app.security;
|
||||
|
||||
/** Split a CSP string into `directive -> sources`. */
|
||||
function directives(csp: string): Record<string, string[]> {
|
||||
const map: Record<string, string[]> = {};
|
||||
for (const part of csp.split(";")) {
|
||||
const [name, ...sources] = part.trim().split(/\s+/);
|
||||
if (name) map[name] = sources;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
describe("tauri.conf.json CSP", () => {
|
||||
it("is set at all — a null CSP hands any injected script the full IPC surface", () => {
|
||||
expect(typeof security.csp).toBe("string");
|
||||
expect(security.csp.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
const csp = directives(security.csp as string);
|
||||
|
||||
it("locks down script execution", () => {
|
||||
// Tauri injects a nonce for SvelteKit's inline bootstrap script at build
|
||||
// time, so 'self' alone is enough and inline/eval must never be re-added.
|
||||
expect(csp["script-src"]).toEqual(["'self'"]);
|
||||
expect(csp["object-src"]).toEqual(["'none'"]);
|
||||
expect(csp["frame-src"]).toEqual(["'none'"]);
|
||||
expect(csp["base-uri"]).toEqual(["'self'"]);
|
||||
expect(csp["default-src"]).toEqual(["'self'"]);
|
||||
});
|
||||
|
||||
it("keeps the schemes playback and thumbnails depend on", () => {
|
||||
// The asset protocol under both names convertFileSrc emits.
|
||||
expect(csp["img-src"]).toContain("asset:");
|
||||
expect(csp["img-src"]).toContain("http://asset.localhost");
|
||||
expect(csp["media-src"]).toContain("asset:");
|
||||
// hls.js: MSE object URLs, and its demuxer worker built from a blob.
|
||||
expect(csp["media-src"]).toContain("blob:");
|
||||
expect(csp["worker-src"]).toContain("blob:");
|
||||
// The token-guarded loopback media server (DR-137).
|
||||
expect(csp["media-src"]).toContain("http://127.0.0.1:*");
|
||||
// Tauri's invoke transport.
|
||||
expect(csp["connect-src"]).toContain("ipc:");
|
||||
expect(csp["connect-src"]).toContain("http://ipc.localhost");
|
||||
// The user's Jellyfin server: an arbitrary run-time origin, http on a LAN.
|
||||
for (const directive of ["img-src", "media-src", "connect-src"]) {
|
||||
expect(csp[directive]).toContain("http:");
|
||||
expect(csp[directive]).toContain("https:");
|
||||
}
|
||||
});
|
||||
|
||||
it("never widens a data directive into script execution", () => {
|
||||
for (const [name, sources] of Object.entries(csp)) {
|
||||
if (name === "script-src" || name === "worker-src") {
|
||||
expect(sources).not.toContain("'unsafe-eval'");
|
||||
expect(sources).not.toContain("'unsafe-inline'");
|
||||
}
|
||||
// A bare `*` would re-admit every scheme, including file:.
|
||||
expect(sources).not.toContain("*");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("tauri.conf.json asset protocol scope", () => {
|
||||
const scope: string[] = security.assetProtocol.scope;
|
||||
|
||||
it("covers only the thumbnail cache, not the storage root", () => {
|
||||
expect(scope).toEqual(["$APPDATA/thumbnails/**"]);
|
||||
// The database and the encrypted-token fallback live directly in $APPDATA.
|
||||
expect(scope).not.toContain("$APPDATA/**");
|
||||
});
|
||||
});
|
||||
Generated
+1
-1
@@ -2018,7 +2018,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jellytau"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"async-trait",
|
||||
|
||||
+10
-6
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "jellytau"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
description = "A Tauri App"
|
||||
authors = ["you"]
|
||||
edition = "2021"
|
||||
@@ -23,11 +23,15 @@ debug = "line-tables-only"
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
# protocol-asset serves downloaded media and cached thumbnails to the webview
|
||||
# over http://asset.localhost; without it convertFileSrc yields a URL nothing
|
||||
# answers. Paired with app.security.assetProtocol in tauri.conf.json, which
|
||||
# scopes it to $APPDATA/**.
|
||||
# TRACES: UR-071 | DR-134
|
||||
# protocol-asset serves cached thumbnails to the webview (asset://localhost on
|
||||
# Linux/macOS, http://asset.localhost on Windows/Android); without it
|
||||
# convertFileSrc yields a URL nothing answers. Paired with
|
||||
# app.security.assetProtocol in tauri.conf.json, which scopes it to
|
||||
# $APPDATA/thumbnails/** — the one directory still read through this protocol.
|
||||
# Downloaded media went the same way until DR-137 moved it to the loopback media
|
||||
# server, so the database, the encrypted-token fallback file and downloads/ are
|
||||
# all outside the grant now.
|
||||
# TRACES: UR-012, UR-071 | DR-134, DR-137, DR-198
|
||||
tauri = { version = "2", features = ["protocol-asset"] }
|
||||
tauri-plugin-opener = "2"
|
||||
tauri-plugin-os = "2"
|
||||
|
||||
@@ -107,8 +107,17 @@ android {
|
||||
)
|
||||
}
|
||||
}
|
||||
// Java 17 bytecode. AGP 8.11 already requires a JDK 17 toolchain to run
|
||||
// (the builder image ships openjdk-17), so "1.8" was only capping the
|
||||
// bytecode we emit, not the JDK in use. Kotlin's jvmTarget and javac's
|
||||
// source/targetCompatibility must agree or AGP 8 fails the build, so all
|
||||
// three move together.
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = "1.8"
|
||||
jvmTarget = "17"
|
||||
}
|
||||
buildFeatures {
|
||||
buildConfig = true
|
||||
|
||||
@@ -25,18 +25,81 @@
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
|
||||
<!--
|
||||
Declared, and deliberately NEVER requested at runtime. That is not an
|
||||
oversight, and an audit has flagged it once already — please read before
|
||||
"fixing" it in either direction.
|
||||
|
||||
Nothing the app posts today needs it. The only notification it produces is
|
||||
the playback service's, which is a MediaStyle notification carrying a valid
|
||||
MediaSession token, and "Notifications related to media sessions are exempt
|
||||
from this behavior change". Verified on device (HONOR ROD2-W09, Android 16
|
||||
/ SDK 36): appops `POST_NOTIFICATION: ignore`, granted=false, and the
|
||||
transport notification simultaneously live with all three actions and
|
||||
working lockscreen controls. So there is no permission dialog, because a
|
||||
prompt the app does not need is a prompt that can be permanently denied for
|
||||
nothing. Media3 does not require the declaration either — media3-session's
|
||||
own manifest declares no permissions, and the MediaSessionService guide
|
||||
asks only for the two FOREGROUND_SERVICE permissions above.
|
||||
|
||||
It stays declared because the exemption is narrow: it is a property of the
|
||||
NOTIFICATION (MediaStyle *and* a non-null session token), not of the
|
||||
foreground service, and it covers media and self-managed-call notifications
|
||||
only. A download-completion notice (UR-011) would be an ordinary
|
||||
notification and would be silently dropped. Adding one means requesting
|
||||
this permission at runtime — AndroidX ActivityResultContracts.
|
||||
RequestPermission from MainActivity, at the point the feature is used — and
|
||||
handling refusal; keeping the declaration is what makes that a one-file
|
||||
change. See JellyTauPlaybackService.warnIfNotificationWillBeDropped.
|
||||
|
||||
TRACES: UR-006 | DR-198
|
||||
-->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
|
||||
<!-- AndroidTV support -->
|
||||
<uses-feature android:name="android.software.leanback" android:required="false" />
|
||||
<!--
|
||||
Android TV is deliberately NOT declared here.
|
||||
|
||||
A LEANBACK_LAUNCHER category and an android.software.leanback uses-feature
|
||||
used to sit in this manifest, but nothing behind them: no D-pad focus
|
||||
model, no TV-sized layouts, and neither of the two declarations Play's TV
|
||||
validation also requires (android.hardware.touchscreen required="false"
|
||||
and an android:banner). That combination is the worst of both - it offers
|
||||
the app to TV launchers while failing TV review and shipping a UI that
|
||||
cannot be driven without a touchscreen.
|
||||
|
||||
Re-declare all four together (leanback feature, LEANBACK_LAUNCHER,
|
||||
touchscreen required="false", banner) once a focus pass has actually been
|
||||
done, not before.
|
||||
-->
|
||||
|
||||
<!--
|
||||
android:allowBackup / android:dataExtractionRules below:
|
||||
no cloud backup, no device-to-device transfer (UR-012).
|
||||
|
||||
Credentials are encrypted under an Android Keystore key, and Keystore keys
|
||||
are NEVER backed up. A restored install would therefore get the
|
||||
jellytau_secure_prefs ciphertext with no key to open it - the app would
|
||||
look signed in and silently fail every request, which is worse than a
|
||||
login screen. Everything else in the data dir (the SQLite catalogue:
|
||||
library metadata, watch history, download bookkeeping) is a rebuildable
|
||||
mirror of the Jellyfin server, so backing it up buys nothing and exports
|
||||
the user's library and viewing history to their Google account.
|
||||
|
||||
allowBackup covers API 24-30 completely, and kills *cloud* backup on API
|
||||
31+. It does NOT stop device-to-device transfer there, so
|
||||
@xml/data_extraction_rules (API 31+) excludes both channels explicitly. No
|
||||
android:fullBackupContent is needed: over the API 23-30 range where it
|
||||
would govern, allowBackup="false" has already turned backup off entirely.
|
||||
-->
|
||||
<application
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="${appLabel}"
|
||||
android:theme="@style/Theme.jellytau"
|
||||
android:hardwareAccelerated="true"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:usesCleartextTraffic="${usesCleartextTraffic}">
|
||||
android:usesCleartextTraffic="${usesCleartextTraffic}"
|
||||
android:allowBackup="false"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules">
|
||||
<activity
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|density"
|
||||
android:launchMode="singleTask"
|
||||
@@ -48,8 +111,7 @@
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
<!-- AndroidTV support -->
|
||||
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
|
||||
<!-- No LEANBACK_LAUNCHER: see the Android TV note above. -->
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
|
||||
@@ -502,9 +502,52 @@ class MainActivity : TauriActivity() {
|
||||
|
||||
javaScriptEnabled = true
|
||||
domStorageEnabled = true
|
||||
allowFileAccess = true
|
||||
allowContentAccess = true
|
||||
mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
|
||||
|
||||
// The three settings below used to read
|
||||
// allowFileAccess = true
|
||||
// allowContentAccess = true
|
||||
// mixedContentMode = MIXED_CONTENT_ALWAYS_ALLOW
|
||||
// which handed the webview a blanket cleartext opt-in and undid
|
||||
// res/xml/network_security_config.xml, whose whole point is that only
|
||||
// 127.0.0.1 is exempt from the cleartext ban and that this "must not
|
||||
// become a blanket cleartext opt-in" (DR-138). Nothing needed any of it:
|
||||
//
|
||||
// - `file://` is never loaded. Cached thumbnails go through
|
||||
// `convertFileSrc` (imageCache.ts), which on Android resolves to
|
||||
// `http://asset.localhost/...` — a Tauri custom protocol answered by
|
||||
// wry's request interceptor, not the filesystem. Downloaded media goes
|
||||
// through `media_local_url` → the loopback HTTP server on 127.0.0.1
|
||||
// (media_server.rs, DR-137), which exists precisely *because* the
|
||||
// asset/file route cannot stream a large file.
|
||||
// - `content://` is never loaded either. The manifest's FileProvider is
|
||||
// for outbound share intents, not for webview navigation.
|
||||
// - Mixed content never arises. Tauri serves the UI from
|
||||
// `http://tauri.localhost` (`use_https_scheme` is false by default and
|
||||
// is not set in tauri.conf.json), and both the loopback media server
|
||||
// and `asset.localhost` are loopback/`.localhost` origins, which
|
||||
// Chromium treats as potentially trustworthy — so they are not mixed
|
||||
// content in the first place. A plain-HTTP *remote* Jellyfin server
|
||||
// would be, but the network security config already rejects it before
|
||||
// the mixed-content check is ever reached, so ALWAYS_ALLOW bought
|
||||
// nothing and only widened the hole.
|
||||
//
|
||||
// COMPATIBILITY_MODE rather than NEVER_ALLOW is a deliberate hedge, not
|
||||
// the default: the platform default at targetSdk 21+ is NEVER_ALLOW, so
|
||||
// this is still one step looser than "stop overriding". It keeps passive
|
||||
// content (images) working if some path the analysis above missed turns
|
||||
// out to need it, which matters because this change cannot be verified
|
||||
// anywhere but a device. Tighten to NEVER_ALLOW once offline video and
|
||||
// cached artwork are confirmed on real hardware.
|
||||
//
|
||||
// `allowFileAccess = false` is the targetSdk-30+ platform default being
|
||||
// restored; `allowContentAccess = false` is a genuine tightening (its
|
||||
// default is true) and is the one to look at first if anything that used
|
||||
// to render stops.
|
||||
//
|
||||
// TRACES: UR-071 | DR-199
|
||||
allowFileAccess = false
|
||||
allowContentAccess = false
|
||||
mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
|
||||
|
||||
android.util.Log.d("MainActivity", "WebView fully configured for media playback")
|
||||
}
|
||||
|
||||
+159
-2
@@ -27,6 +27,17 @@ import com.google.common.util.concurrent.ListenableFuture
|
||||
*
|
||||
* Media commands are routed back to Rust via JNI to ensure proper
|
||||
* queue management for next/previous track operations.
|
||||
*
|
||||
* This class owns both sessions: the media3 [MediaSession] the service contract
|
||||
* requires, and the legacy [MediaSessionCompat] that actually carries the
|
||||
* lockscreen transport. The compat session is flagged
|
||||
* FLAG_HANDLES_MEDIA_BUTTONS or FLAG_HANDLES_TRANSPORT_CONTROLS, which is what
|
||||
* makes a Bluetooth headset's AVRCP play/pause/skip arrive as a transport
|
||||
* callback; every one of those callbacks is forwarded to Rust through
|
||||
* nativeOnMediaCommand rather than acted on locally, so the player stays the
|
||||
* single source of truth and the session remains a consumer of its state.
|
||||
*
|
||||
* TRACES: UR-006 | IR-006
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
class JellyTauPlaybackService : MediaSessionService() {
|
||||
@@ -228,6 +239,21 @@ class JellyTauPlaybackService : MediaSessionService() {
|
||||
nativeOnMediaCommand("previous")
|
||||
}
|
||||
|
||||
// Fast-forward/rewind map onto the same two commands on purpose.
|
||||
// Rust decides whether a skip advances the queue or scrubs
|
||||
// +30s/-10s, based on whether a background-audio handoff owns
|
||||
// playback (DR-201); routing these separately would put that
|
||||
// decision in two places and let them disagree.
|
||||
override fun onFastForward() {
|
||||
android.util.Log.d("JellyTauPlaybackService", "Lock screen: Fast-forward pressed")
|
||||
nativeOnMediaCommand("next")
|
||||
}
|
||||
|
||||
override fun onRewind() {
|
||||
android.util.Log.d("JellyTauPlaybackService", "Lock screen: Rewind pressed")
|
||||
nativeOnMediaCommand("previous")
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
android.util.Log.d("JellyTauPlaybackService", "Lock screen: Stop pressed")
|
||||
nativeOnMediaCommand("stop")
|
||||
@@ -245,9 +271,103 @@ class JellyTauPlaybackService : MediaSessionService() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this process could post an *ordinary* notification and have the
|
||||
* user see it.
|
||||
*
|
||||
* Deliberately **not** a gate on anything this service posts today — see
|
||||
* [warnIfNotificationWillBeDropped]. `POST_NOTIFICATIONS` is declared in the
|
||||
* manifest but never requested, so on Android 13+ this is normally `false`,
|
||||
* and that is the intended state. It is read only to decide whether a
|
||||
* token-less notification would be dropped.
|
||||
*/
|
||||
private fun hasPostNotificationsPermission(): Boolean =
|
||||
Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
|
||||
checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) ==
|
||||
android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||
|
||||
/**
|
||||
* The media-session token is what makes this service's notifications legal
|
||||
* without `POST_NOTIFICATIONS` — do not drop it.
|
||||
*
|
||||
* Android 13 (API 33) gates notifications behind the `POST_NOTIFICATIONS`
|
||||
* runtime permission, and a foreground-service notification is explicitly
|
||||
* **not** exempt: "Android 13 (API level 33) and higher supports a runtime
|
||||
* permission for sending non-exempt (including Foreground Services (FGS))
|
||||
* notifications from an app: POST_NOTIFICATIONS", and with it denied the
|
||||
* user "still see[s] notices related to foreground services in the Task
|
||||
* Manager but [doesn't] see them in the notification drawer".
|
||||
*
|
||||
* A *media-session* notification is exempt, however: "Notifications related
|
||||
* to media sessions are exempt from this behavior change." That exemption is
|
||||
* a property of the notification, not of the service — the platform decides
|
||||
* it from the posted `Notification` itself, which must carry `MediaStyle`
|
||||
* **and** a valid `MediaSession` token. Every notification this service
|
||||
* builds does (`MediaStyle().setMediaSession(mediaSessionCompat.sessionToken)`,
|
||||
* with `mediaSessionCompat` created in `onCreate`, i.e. before any post), so
|
||||
* the shade entry and the lockscreen transport controls behind UR-006 appear
|
||||
* whether or not the permission was ever granted. That is why this app asks
|
||||
* for nothing at runtime and shows the user no permission dialog.
|
||||
*
|
||||
* The trap it leaves is a silent one, and it is worse than a missing shade
|
||||
* entry — which is what this exists to make loud. The platform predicate is
|
||||
* `Notification.isMediaNotification()`, requiring MediaStyle **and** a
|
||||
* non-null `EXTRA_MEDIA_SESSION`; `NotificationManagerService` uses it to
|
||||
* decide whether to drop the post, and SystemUI's media carousel
|
||||
* (`MediaDataProcessor.onNotificationAdded`) is gated on *the same*
|
||||
* predicate. So a token-less notification is blocked before it reaches the
|
||||
* notification listener, and the lockscreen/Quick Settings transport
|
||||
* controls — the whole of UR-006 — never appear at all, with no error and no
|
||||
* log anywhere. `mediaSessionCompat?.sessionToken` is a null-safe call, so
|
||||
* that failure is one stray initialisation-order change away.
|
||||
*
|
||||
* The exemption also covers only media and self-managed-call notifications,
|
||||
* so a genuinely non-media notification — a download-completion notice
|
||||
* (UR-011), say — gets none of it. Adding one means requesting
|
||||
* `POST_NOTIFICATIONS` at runtime first (AndroidX
|
||||
* `ActivityResultContracts.RequestPermission`, launched from `MainActivity`
|
||||
* at the point the feature is used, handling refusal), not merely calling
|
||||
* `notify`; the manifest keeps the declaration so that stays a one-file
|
||||
* change. Verified unchanged across API 33–36.
|
||||
*
|
||||
* TRACES: UR-006 | DR-200
|
||||
*/
|
||||
private fun warnIfNotificationWillBeDropped(token: MediaSessionCompat.Token?) {
|
||||
if (token != null) return
|
||||
if (hasPostNotificationsPermission()) return
|
||||
android.util.Log.e(
|
||||
"JellyTauPlaybackService",
|
||||
"Posting a notification with NO MediaSession token while POST_NOTIFICATIONS " +
|
||||
"is denied: it is not exempt and Android will drop it silently. " +
|
||||
"Lockscreen/shade transport controls (UR-006) will be missing."
|
||||
)
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
// Start as foreground service immediately to avoid crash
|
||||
// Media3 will replace this with its own notification
|
||||
//
|
||||
// startForeground() is deliberately NOT gated on POST_NOTIFICATIONS, and
|
||||
// an audit asking for such a guard has been answered once already — do
|
||||
// not re-raise it. Two independent reasons:
|
||||
//
|
||||
// 1. The notification does not need the permission. It is exempt because
|
||||
// it is a media-session notification (see
|
||||
// warnIfNotificationWillBeDropped). Device evidence, HONOR ROD2-W09 on
|
||||
// Android 16 / SDK 36: appops reports `POST_NOTIFICATION: ignore` and
|
||||
// `granted=false`, while the same dumpsys shows this service
|
||||
// isForeground=true with `foregroundNoti=Notification(category=
|
||||
// transport actions=3 vis=PUBLIC)` live and the lockscreen transport
|
||||
// controls working.
|
||||
// 2. Skipping this call after startForegroundService() is a hard contract
|
||||
// violation — the system kills the process with "did not then call
|
||||
// Service.startForeground()". So a guard here would convert a cosmetic
|
||||
// problem into a crash.
|
||||
//
|
||||
// A denied permission must degrade to a missing *notification*, never to
|
||||
// a missing startForeground.
|
||||
//
|
||||
// TRACES: UR-006 | DR-200
|
||||
val notification = createBasicNotification()
|
||||
startForeground(NOTIFICATION_ID, notification)
|
||||
return super.onStartCommand(intent, flags, startId)
|
||||
@@ -263,6 +383,11 @@ class JellyTauPlaybackService : MediaSessionService() {
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
|
||||
)
|
||||
|
||||
// onCreate builds mediaSessionCompat, and onStartCommand cannot run
|
||||
// before onCreate, so this is expected to be non-null here.
|
||||
val sessionToken = mediaSessionCompat?.sessionToken
|
||||
warnIfNotificationWillBeDropped(sessionToken)
|
||||
|
||||
return NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
|
||||
.setContentTitle("JellyTau")
|
||||
.setContentText("Playing")
|
||||
@@ -270,7 +395,7 @@ class JellyTauPlaybackService : MediaSessionService() {
|
||||
.setContentIntent(pendingIntent)
|
||||
.setStyle(
|
||||
androidx.media.app.NotificationCompat.MediaStyle()
|
||||
.setMediaSession(mediaSessionCompat?.sessionToken)
|
||||
.setMediaSession(sessionToken)
|
||||
.setShowActionsInCompactView(0, 1, 2) // Show all 3 buttons in compact view
|
||||
)
|
||||
.addAction(
|
||||
@@ -433,6 +558,14 @@ class JellyTauPlaybackService : MediaSessionService() {
|
||||
PlaybackStateCompat.ACTION_STOP or
|
||||
PlaybackStateCompat.ACTION_SKIP_TO_NEXT or
|
||||
PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS or
|
||||
// Advertised so the system draws seek affordances alongside the
|
||||
// skip arrows: during a background-audio handoff the backend
|
||||
// resolves skip to a +30s/-10s scrub rather than a queue advance
|
||||
// (DR-201), and a control that scrubs should not look like one
|
||||
// that changes track. Rust owns which of the two a press means;
|
||||
// these only describe what the session can do.
|
||||
PlaybackStateCompat.ACTION_FAST_FORWARD or
|
||||
PlaybackStateCompat.ACTION_REWIND or
|
||||
PlaybackStateCompat.ACTION_SEEK_TO
|
||||
)
|
||||
.setState(
|
||||
@@ -446,6 +579,24 @@ class JellyTauPlaybackService : MediaSessionService() {
|
||||
/**
|
||||
* Update the notification with current media metadata and playback state.
|
||||
* This should be called whenever metadata or playback state changes.
|
||||
*
|
||||
* This `notify()` reuses [NOTIFICATION_ID], so while the service is
|
||||
* foreground it updates the foreground notification in place. It is **not**
|
||||
* guarded on the service being foreground, and does not need to be, because
|
||||
* the exemption that keeps it postable is a property of the notification
|
||||
* (MediaStyle + session token) rather than of the foreground state — see
|
||||
* [warnIfNotificationWillBeDropped].
|
||||
*
|
||||
* That distinction is load-bearing, because this *is* reachable with the
|
||||
* service alive but not foreground. Every caller arrives over JNI from Rust
|
||||
* on a non-main thread against [getInstance], which is non-null from
|
||||
* `onCreate` to `onDestroy`: it can therefore interleave between `onCreate`
|
||||
* and `onStartCommand`, and a media3 `MediaSessionService` is also created
|
||||
* by a plain *bind* from a MediaController with no `startForeground` at all.
|
||||
* Were the exemption a foreground-service one, those windows would silently
|
||||
* drop the update; being a media-session one, they do not.
|
||||
*
|
||||
* TRACES: UR-006 | DR-200
|
||||
*/
|
||||
private fun updateNotification(title: String, artist: String, isPlaying: Boolean) {
|
||||
val intent = packageManager.getLaunchIntentForPackage(packageName)
|
||||
@@ -456,6 +607,12 @@ class JellyTauPlaybackService : MediaSessionService() {
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
|
||||
)
|
||||
|
||||
// The token is what exempts this from POST_NOTIFICATIONS; losing it here
|
||||
// would make every metadata update vanish from the shade and lockscreen
|
||||
// while the service kept running. See warnIfNotificationWillBeDropped.
|
||||
val sessionToken = mediaSessionCompat?.sessionToken
|
||||
warnIfNotificationWillBeDropped(sessionToken)
|
||||
|
||||
val notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
|
||||
.setContentTitle(title)
|
||||
.setContentText(artist)
|
||||
@@ -463,7 +620,7 @@ class JellyTauPlaybackService : MediaSessionService() {
|
||||
.setContentIntent(pendingIntent)
|
||||
.setStyle(
|
||||
androidx.media.app.NotificationCompat.MediaStyle()
|
||||
.setMediaSession(mediaSessionCompat?.sessionToken)
|
||||
.setMediaSession(sessionToken)
|
||||
.setShowActionsInCompactView(0, 1, 2) // Show all 3 buttons in compact view
|
||||
)
|
||||
.addAction(
|
||||
|
||||
@@ -263,7 +263,15 @@ class JellyTauPlayer(private val appContext: Context) {
|
||||
.setContentType(C.AUDIO_CONTENT_TYPE_MUSIC)
|
||||
.build()
|
||||
|
||||
// Create ExoPlayer with audio focus handling
|
||||
// Create ExoPlayer with audio focus handling.
|
||||
//
|
||||
// For audio playback ExoPlayer manages focus itself: handleAudioFocus=true
|
||||
// makes it request AUDIOFOCUS_GAIN on play, duck on a transient loss, and
|
||||
// pause on a call or another app taking focus. Video re-applies this per
|
||||
// load with handleAudioFocus=false and drives focus manually instead (see
|
||||
// requestAudioFocus), because a video needs delayed-focus handling.
|
||||
//
|
||||
// TRACES: UR-004, UR-006 | IR-008
|
||||
exoPlayer = ExoPlayer.Builder(appContext)
|
||||
.setAudioAttributes(audioAttributes, /* handleAudioFocus= */ true)
|
||||
// Pause when the audio output is removed (wired headphones unplugged or
|
||||
@@ -1328,7 +1336,12 @@ class JellyTauPlayer(private val appContext: Context) {
|
||||
* Request audio focus for video playback.
|
||||
* This is critical for video to have audio on Android.
|
||||
*
|
||||
* TRACES: UR-004 | DR-145
|
||||
* The listener installed here is the pause-on-call path: AUDIOFOCUS_LOSS and
|
||||
* AUDIOFOCUS_LOSS_TRANSIENT (an incoming call is the latter) both pause,
|
||||
* LOSS_TRANSIENT_CAN_DUCK lowers the volume instead, and GAIN restores —
|
||||
* resuming only what we paused, via pendingPlayOnFocusGain.
|
||||
*
|
||||
* TRACES: UR-004, UR-006 | IR-008, DR-145
|
||||
*
|
||||
* @return true if focus was granted outright and playback may start now.
|
||||
* false for a DELAYED or refused request — the caller must hold playback
|
||||
|
||||
@@ -100,9 +100,27 @@ class SecureStorage private constructor(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a credential.
|
||||
*
|
||||
* Returns null for both "nothing stored" and "stored but undecryptable", but
|
||||
* treats them as distinct events. The second happens after a backup restore
|
||||
* or a device-to-device transfer: SharedPreferences travel, the Android
|
||||
* Keystore key that encrypted them never does, so the ciphertext can never
|
||||
* be read again on this install. That blob is discarded here rather than
|
||||
* left to fail on every subsequent read, which turns a permanently broken
|
||||
* credential into a clean logged-out state. (The app also declares
|
||||
* allowBackup="false" plus data-extraction rules so this should no longer
|
||||
* arise - this is the belt to that manifest's braces.)
|
||||
*/
|
||||
fun getCredential(key: String): String? {
|
||||
try {
|
||||
val encoded = prefs.getString(key, null) ?: return null
|
||||
val encoded = prefs.getString(key, null)
|
||||
if (encoded == null) {
|
||||
Log.d(TAG, "No credential stored for: $key")
|
||||
return null
|
||||
}
|
||||
|
||||
return try {
|
||||
val combined = Base64.decode(encoded, Base64.DEFAULT)
|
||||
|
||||
// Extract IV (first 12 bytes for GCM)
|
||||
@@ -114,10 +132,16 @@ class SecureStorage private constructor(context: Context) {
|
||||
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(), spec)
|
||||
|
||||
val decrypted = cipher.doFinal(encrypted)
|
||||
return String(decrypted, Charsets.UTF_8)
|
||||
String(decrypted, Charsets.UTF_8)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to get credential: $key", e)
|
||||
return null
|
||||
Log.w(
|
||||
TAG,
|
||||
"Credential '$key' is present but cannot be decrypted; discarding it and " +
|
||||
"reporting no credential. Signing in again will store a fresh one.",
|
||||
e
|
||||
)
|
||||
prefs.edit().remove(key).apply()
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Backup / transfer policy for JellyTau (API 31+; see android:allowBackup in
|
||||
AndroidManifest.xml for API 24-30).
|
||||
|
||||
Nothing is eligible for extraction, from either channel:
|
||||
|
||||
* cloud-backup - already off via android:allowBackup="false".
|
||||
* device-transfer - NOT covered by allowBackup on Android 12+, which is why
|
||||
this file exists. A D2D transfer would otherwise copy the same data the
|
||||
cloud backup used to.
|
||||
|
||||
Why nothing is extractable:
|
||||
|
||||
* Credentials are unrecoverable off-device. jellytau_secure_prefs holds
|
||||
AES-GCM ciphertext encrypted under an Android Keystore key, and Keystore
|
||||
keys are never backed up or transferred. Restoring the prefs without the
|
||||
key produces ciphertext nothing can read - a silent auth failure that looks
|
||||
like a broken app rather than a logged-out one.
|
||||
* Everything else is a rebuildable cache. The SQLite catalogue is a mirror of
|
||||
the Jellyfin server (library metadata, watch history, offline downloads);
|
||||
signing in again reproduces it, and watch state lives on the server anyway.
|
||||
Backing it up would export a user's library and viewing history to their
|
||||
Google account for no gain.
|
||||
|
||||
Exclude rules are listed per domain rather than relying on "root" alone,
|
||||
because database/, shared_prefs/, files/ and external storage are addressed
|
||||
as their own domains by the extraction engine.
|
||||
-->
|
||||
<data-extraction-rules>
|
||||
<cloud-backup>
|
||||
<exclude domain="root" />
|
||||
<exclude domain="file" />
|
||||
<exclude domain="database" />
|
||||
<exclude domain="sharedpref" />
|
||||
<exclude domain="external" />
|
||||
</cloud-backup>
|
||||
<device-transfer>
|
||||
<exclude domain="root" />
|
||||
<exclude domain="file" />
|
||||
<exclude domain="database" />
|
||||
<exclude domain="sharedpref" />
|
||||
<exclude domain="external" />
|
||||
</device-transfer>
|
||||
</data-extraction-rules>
|
||||
@@ -12,7 +12,12 @@
|
||||
remote server still has to be HTTPS — this must not become a blanket
|
||||
cleartext opt-in.
|
||||
|
||||
TRACES: UR-071 | DR-138
|
||||
This file is only half the policy. MainActivity.configureWebViewSettings sets
|
||||
the webview's mixedContentMode and its file/content access flags; setting
|
||||
MIXED_CONTENT_ALWAYS_ALLOW there re-opened by hand what this config closes,
|
||||
which is DR-199. Change the two together, or not at all.
|
||||
|
||||
TRACES: UR-071 | DR-138, DR-199
|
||||
-->
|
||||
<network-security-config>
|
||||
<base-config cleartextTrafficPermitted="false" />
|
||||
|
||||
@@ -418,13 +418,13 @@ mod tests {
|
||||
#[test]
|
||||
fn test_auth_manager_wrapper_structure() {
|
||||
// Verify wrapper type exists and has correct structure
|
||||
assert_eq!(std::mem::size_of::<AuthManagerWrapper>() > 0, true);
|
||||
assert!(std::mem::size_of::<AuthManagerWrapper>() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_session_verifier_wrapper_structure() {
|
||||
// Verify wrapper type exists and has correct structure
|
||||
assert_eq!(std::mem::size_of::<SessionVerifierWrapper>() > 0, true);
|
||||
assert!(std::mem::size_of::<SessionVerifierWrapper>() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -496,7 +496,7 @@ pub(crate) async fn requeue_mistyped_video_downloads(
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
|
||||
let query = Query::new(&format!(
|
||||
let query = Query::new(format!(
|
||||
"UPDATE downloads
|
||||
SET status = 'pending', stream_url = NULL, progress = 0,
|
||||
bytes_downloaded = 0, started_at = NULL, completed_at = NULL
|
||||
@@ -563,7 +563,7 @@ where
|
||||
),
|
||||
None => String::new(),
|
||||
};
|
||||
let rows_query = Query::new(&format!(
|
||||
let rows_query = Query::new(format!(
|
||||
"SELECT d.id, d.item_id,
|
||||
COALESCE(
|
||||
d.media_type,
|
||||
@@ -753,6 +753,7 @@ pub async fn resume_queued_downloads(
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::storage::db_service::RusqliteService;
|
||||
use crate::utils::lock::MutexSafe;
|
||||
use rusqlite::Connection;
|
||||
use std::sync::Mutex;
|
||||
|
||||
@@ -1012,14 +1013,14 @@ mod tests {
|
||||
resolve_pending_download_urls(&db, "/data", None, move |item_id, media_type, _q| {
|
||||
let seen = Arc::clone(&seen_c);
|
||||
async move {
|
||||
seen.lock().unwrap().push((item_id.clone(), media_type));
|
||||
seen.lock_safe().push((item_id.clone(), media_type));
|
||||
Some(format!("http://resolved/{item_id}"))
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let seen = seen.lock().unwrap().clone();
|
||||
let seen = seen.lock_safe().clone();
|
||||
let of = |id: &str| {
|
||||
seen.iter()
|
||||
.find(|(i, _)| i == id)
|
||||
@@ -1045,14 +1046,14 @@ mod tests {
|
||||
resolve_pending_download_urls(&db, "/data", None, move |_id, media_type, _q| {
|
||||
let seen = Arc::clone(&seen_c);
|
||||
async move {
|
||||
*seen.lock().unwrap() = media_type;
|
||||
*seen.lock_safe() = media_type;
|
||||
Some("http://x".to_string())
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(*seen.lock().unwrap(), "audio");
|
||||
assert_eq!(*seen.lock_safe(), "audio");
|
||||
}
|
||||
|
||||
/// An explicit `media_type` on the row always wins over the item's type.
|
||||
@@ -1069,14 +1070,14 @@ mod tests {
|
||||
resolve_pending_download_urls(&db, "/data", None, move |_id, media_type, _q| {
|
||||
let seen = Arc::clone(&seen_c);
|
||||
async move {
|
||||
*seen.lock().unwrap() = media_type;
|
||||
*seen.lock_safe() = media_type;
|
||||
Some("http://x".to_string())
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(*seen.lock().unwrap(), "video");
|
||||
assert_eq!(*seen.lock_safe(), "video");
|
||||
}
|
||||
|
||||
/// Rows already downloaded under the audio default hold an audio-only
|
||||
|
||||
@@ -97,6 +97,6 @@ mod tests {
|
||||
// due to its dependencies, so we just test the wrapper type structure
|
||||
|
||||
// This verifies the wrapper type exists and can hold Arc<Mutex>
|
||||
assert_eq!(std::mem::size_of::<ConnectivityMonitorWrapper>() > 0, true);
|
||||
assert!(std::mem::size_of::<ConnectivityMonitorWrapper>() > 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,10 @@ mod smart_cache;
|
||||
pub use pinning::*;
|
||||
pub use smart_cache::*;
|
||||
|
||||
/// One row of the series episode listing used when queueing a whole series:
|
||||
/// `(id, name, season_name, index_number, parent_index_number)`.
|
||||
type EpisodeRow = (String, String, Option<String>, Option<i32>, Option<i32>);
|
||||
|
||||
/// Wrapper for DownloadManager to be used as Tauri state
|
||||
pub struct DownloadManagerWrapper(pub Mutex<DownloadManager>);
|
||||
|
||||
@@ -596,6 +600,10 @@ pub(crate) async fn queue_album_tracks(
|
||||
/// TRACES: UR-018, UR-055 | DR-173 | UT-170
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
// Three of the eight arguments are Tauri `State<'_, _>` injections plus the
|
||||
// `AppHandle`, not caller input. Folding the rest into a struct would change the
|
||||
// IPC contract and the generated TypeScript for no readability gain.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn download_album(
|
||||
db: State<'_, DatabaseWrapper>,
|
||||
repository: State<'_, crate::commands::repository::RepositoryManagerWrapper>,
|
||||
@@ -807,7 +815,7 @@ pub async fn download_series(
|
||||
vec![QueryParam::String(series_id)],
|
||||
);
|
||||
|
||||
let episodes: Vec<(String, String, Option<String>, Option<i32>, Option<i32>)> = db_service
|
||||
let episodes: Vec<EpisodeRow> = db_service
|
||||
.query_many(episodes_query, |row| {
|
||||
Ok((
|
||||
row.get(0)?,
|
||||
@@ -912,6 +920,10 @@ pub async fn download_series(
|
||||
/// Queue all episodes of a specific season for download
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
// One of the eight arguments is a Tauri `State<'_, _>` injection; the rest are
|
||||
// the season's identifying fields. Folding them into a struct would change the
|
||||
// IPC contract and the generated TypeScript for no readability gain.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn download_season(
|
||||
db: State<'_, DatabaseWrapper>,
|
||||
season_id: String,
|
||||
@@ -2307,7 +2319,7 @@ pub async fn delete_downloads_under(
|
||||
)";
|
||||
|
||||
let file_query = Query::with_params(
|
||||
&format!("SELECT d.file_path FROM downloads d WHERE {SCOPE}"),
|
||||
format!("SELECT d.file_path FROM downloads d WHERE {SCOPE}"),
|
||||
vec![
|
||||
QueryParam::String(user_id.clone()),
|
||||
QueryParam::String(item_id.clone()),
|
||||
@@ -2323,7 +2335,7 @@ pub async fn delete_downloads_under(
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let delete_query = Query::with_params(
|
||||
&format!("DELETE FROM downloads WHERE id IN (SELECT d.id FROM downloads d WHERE {SCOPE})"),
|
||||
format!("DELETE FROM downloads WHERE id IN (SELECT d.id FROM downloads d WHERE {SCOPE})"),
|
||||
vec![
|
||||
QueryParam::String(user_id),
|
||||
QueryParam::String(item_id.clone()),
|
||||
|
||||
@@ -186,6 +186,7 @@ async fn run_drain(app: &tauri::AppHandle) -> Result<(), String> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::utils::lock::MutexSafe;
|
||||
use rusqlite::Connection;
|
||||
use std::sync::Mutex;
|
||||
|
||||
@@ -211,7 +212,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn calls(&self) -> Vec<(String, bool)> {
|
||||
let mut calls = self.calls.lock().unwrap().clone();
|
||||
let mut calls = self.calls.lock_safe().clone();
|
||||
calls.sort();
|
||||
calls
|
||||
}
|
||||
|
||||
@@ -360,7 +360,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_playback_reporter_wrapper_structure() {
|
||||
// Verify wrapper type can hold Arc<TokioMutex<Option<T>>>
|
||||
assert_eq!(std::mem::size_of::<PlaybackReporterWrapper>() > 0, true);
|
||||
assert!(std::mem::size_of::<PlaybackReporterWrapper>() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1478,8 +1478,22 @@ pub async fn player_seek_video(
|
||||
|
||||
/// Switch audio track - handles both HTML5 (stream reload) and native (direct switch)
|
||||
/// Note: Frontend should handle saving series preferences after this command succeeds
|
||||
///
|
||||
/// The split is the requirement: an HTML5 `<video>` element cannot be told to
|
||||
/// change audio track, so the stream is re-opened at the chosen
|
||||
/// `AudioStreamIndex` and the frontend seeks the reloaded element back to
|
||||
/// `position`; a native backend (ExoPlayer) switches in place by track-group
|
||||
/// index. libmpv implements neither — it is the audio-only backend here and
|
||||
/// leaves `PlayerBackend::set_audio_track` at its `not_implemented()` default,
|
||||
/// which is why IR-019 is met by these two paths rather than by MPV.
|
||||
///
|
||||
/// TRACES: UR-021 | IR-019, DR-024
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
// Two of the eight arguments are Tauri `State<'_, _>` injections, not caller
|
||||
// input. Folding the rest into a struct would change the IPC contract and the
|
||||
// generated TypeScript for no readability gain.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn player_switch_audio_track(
|
||||
player: State<'_, PlayerStateWrapper>,
|
||||
repository_manager: State<'_, super::repository::RepositoryManagerWrapper>,
|
||||
@@ -1559,6 +1573,10 @@ pub async fn player_switch_audio_track(
|
||||
/// TRACES: UR-074 | DR-162
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
// Three of the nine arguments are Tauri `State<'_, _>` injections, not caller
|
||||
// input. Folding the rest into a struct would change the IPC contract and the
|
||||
// generated TypeScript for no readability gain.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn player_set_stream_quality(
|
||||
player: State<'_, PlayerStateWrapper>,
|
||||
repository_manager: State<'_, super::repository::RepositoryManagerWrapper>,
|
||||
@@ -1650,6 +1668,9 @@ pub async fn player_set_stream_quality(
|
||||
Ok(StreamQualityResponse::Native { position })
|
||||
}
|
||||
|
||||
/// Set the active audio track on a native backend directly.
|
||||
///
|
||||
/// TRACES: UR-021 | IR-019, DR-024
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn player_set_audio_track(
|
||||
@@ -1663,6 +1684,14 @@ pub async fn player_set_audio_track(
|
||||
Ok(get_player_status(&controller))
|
||||
}
|
||||
|
||||
/// Set (or clear, with `None`) the active subtitle track on a native backend.
|
||||
///
|
||||
/// On Android this indexes ExoPlayer's *text track groups* — i.e. the position
|
||||
/// of the sideloaded `MediaItem.SubtitleConfiguration`, not the Jellyfin stream
|
||||
/// index. The HTML5 path never reaches here; it toggles its own `<track>`
|
||||
/// children. libmpv implements neither, leaving the trait default in place.
|
||||
///
|
||||
/// TRACES: UR-020 | IR-018, DR-023
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn player_set_subtitle_track(
|
||||
@@ -1784,7 +1813,7 @@ pub async fn player_get_status(
|
||||
let local_media = {
|
||||
let queue_arc = controller.queue();
|
||||
let queue = queue_arc.lock().map_err(|e| e.to_string())?;
|
||||
queue.current().map(|item| MergedMediaItem::from(item))
|
||||
queue.current().map(MergedMediaItem::from)
|
||||
};
|
||||
|
||||
let local_is_playing = status.state.is_playing();
|
||||
@@ -1808,10 +1837,7 @@ pub async fn player_get_status(
|
||||
log::info!("[PlayerCommands] Merging remote session state");
|
||||
|
||||
// Merge media item
|
||||
status.merged_media = session
|
||||
.now_playing_item
|
||||
.as_ref()
|
||||
.map(|item| MergedMediaItem::from(item));
|
||||
status.merged_media = session.now_playing_item.as_ref().map(MergedMediaItem::from);
|
||||
|
||||
// Merge isPlaying (NOT isPaused!)
|
||||
status.merged_is_playing = session
|
||||
@@ -2741,6 +2767,8 @@ pub async fn player_disable_jellyfin(player: State<'_, PlayerStateWrapper>) -> R
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::utils::lock::MutexSafe;
|
||||
|
||||
/// The subtitle list the frontend resolved must survive the IPC hop and end
|
||||
/// up on the `MediaItem` the native backend loads.
|
||||
///
|
||||
@@ -3063,7 +3091,7 @@ mod tests {
|
||||
let database = Database::open_in_memory().unwrap();
|
||||
{
|
||||
let conn = database.connection();
|
||||
let conn = conn.lock().unwrap();
|
||||
let conn = conn.lock_safe();
|
||||
conn.execute_batch(&format!(
|
||||
r#"
|
||||
INSERT INTO servers (id, name, url) VALUES ('srv', 'Test', 'http://test');
|
||||
@@ -3119,7 +3147,7 @@ mod tests {
|
||||
assert_eq!(switched, 1, "only the download whose file exists switches");
|
||||
|
||||
let queue = controller.queue();
|
||||
let queue_lock = queue.lock().unwrap();
|
||||
let queue_lock = queue.lock_safe();
|
||||
match &queue_lock.items()[0].source {
|
||||
MediaSource::Local {
|
||||
file_path,
|
||||
@@ -3148,7 +3176,7 @@ mod tests {
|
||||
index_number: Option<i32>,
|
||||
}
|
||||
|
||||
let mut tracks = vec![
|
||||
let mut tracks = [
|
||||
MockTrack {
|
||||
id: "track1".to_string(),
|
||||
name: "Song 1".to_string(),
|
||||
@@ -3241,7 +3269,7 @@ mod tests {
|
||||
}
|
||||
|
||||
// Create tracks in random order (not sorted)
|
||||
let mut tracks = vec![
|
||||
let mut tracks = [
|
||||
MockTrack {
|
||||
id: "id5".to_string(),
|
||||
name: "Track 5".to_string(),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Tauri commands for repository access
|
||||
//! Uses handle-based system: UUID -> Arc<HybridRepository>
|
||||
//!
|
||||
//! TRACES: UR-007, UR-035, UR-036 | JA-004, JA-005, JA-029, JA-030, JA-031
|
||||
//! TRACES: UR-007, UR-008, UR-023, UR-034, UR-035, UR-036 | IR-022, IR-024, JA-004, JA-005, JA-006, JA-029, JA-030, JA-031
|
||||
|
||||
use crate::utils::lock::MutexSafe;
|
||||
use std::collections::HashMap;
|
||||
@@ -67,6 +67,10 @@ pub struct RepositoryManagerWrapper(pub RepositoryManager);
|
||||
/// Returns a handle (UUID) for accessing the repository
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
// Four of the eight arguments are Tauri `State<'_, _>` injections, not caller
|
||||
// input. Folding the remaining four into a struct would change the IPC contract
|
||||
// and the generated TypeScript for no readability gain.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn repository_create(
|
||||
manager: State<'_, RepositoryManagerWrapper>,
|
||||
player: State<'_, crate::commands::player::PlayerStateWrapper>,
|
||||
@@ -294,7 +298,13 @@ pub async fn repository_get_latest_items(
|
||||
.map_err(|e| format!("{:?}", e))
|
||||
}
|
||||
|
||||
/// Get resume items (continue watching/listening)
|
||||
/// Get resume items (continue watching/listening).
|
||||
///
|
||||
/// The home screen's Continue Watching row and every library's "pick up where
|
||||
/// you left off" hero come through here; each item carries its own resume
|
||||
/// position in `UserData`.
|
||||
///
|
||||
/// TRACES: UR-019, UR-023, UR-034 | IR-024, JA-013, JA-015 | DR-026, DR-038
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn repository_get_resume_items(
|
||||
@@ -318,7 +328,9 @@ pub async fn repository_get_resume_items(
|
||||
})
|
||||
}
|
||||
|
||||
/// Get next up episodes
|
||||
/// Get next up episodes.
|
||||
///
|
||||
/// TRACES: UR-023, UR-034 | IR-024, JA-014 | DR-026
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn repository_get_next_up_episodes(
|
||||
@@ -1091,7 +1103,6 @@ mod tests {
|
||||
let handle = format!("{}", uuid);
|
||||
// UUID should convert to a non-empty string
|
||||
assert!(!handle.is_empty());
|
||||
assert!(handle.len() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -89,7 +89,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_session_poller_wrapper_structure() {
|
||||
// Test that wrapper type structure is correct
|
||||
assert_eq!(std::mem::size_of::<SessionPollerWrapper>() > 0, true);
|
||||
assert!(std::mem::size_of::<SessionPollerWrapper>() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1658,19 +1658,19 @@ mod tests {
|
||||
#[test]
|
||||
fn test_database_wrapper_structure() {
|
||||
// Verify DatabaseWrapper can be created and holds Mutex<Database>
|
||||
assert_eq!(std::mem::size_of::<DatabaseWrapper>() > 0, true);
|
||||
assert!(std::mem::size_of::<DatabaseWrapper>() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_credential_store_wrapper_structure() {
|
||||
// Verify CredentialStoreWrapper can be created
|
||||
assert_eq!(std::mem::size_of::<CredentialStoreWrapper>() > 0, true);
|
||||
assert!(std::mem::size_of::<CredentialStoreWrapper>() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_thumbnail_cache_wrapper_structure() {
|
||||
// Verify ThumbnailCacheWrapper holds Arc<ThumbnailCache>
|
||||
assert_eq!(std::mem::size_of::<ThumbnailCacheWrapper>() > 0, true);
|
||||
assert!(std::mem::size_of::<ThumbnailCacheWrapper>() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -481,6 +481,7 @@ pub async fn sync_process_pending(app: tauri::AppHandle) -> Result<DrainReport,
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::utils::lock::MutexSafe;
|
||||
use rusqlite::Connection;
|
||||
use std::sync::Mutex;
|
||||
|
||||
@@ -517,7 +518,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn calls(&self) -> Vec<QueuedOp> {
|
||||
self.calls.lock().unwrap().clone()
|
||||
self.calls.lock_safe().clone()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -527,7 +528,7 @@ mod tests {
|
||||
if let Some(err) = &self.fail_with {
|
||||
return Err(err.clone());
|
||||
}
|
||||
self.calls.lock().unwrap().push(op.clone());
|
||||
self.calls.lock_safe().push(op.clone());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
+107
-10
@@ -20,9 +20,6 @@ use sha2::{Digest, Sha256};
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
use hostname;
|
||||
|
||||
#[cfg(not(target_os = "android"))]
|
||||
const SERVICE_NAME: &str = "com.dtourolle.jellytau";
|
||||
|
||||
@@ -203,15 +200,12 @@ impl CredentialStore {
|
||||
|
||||
// secret-tool doesn't support --version, so we test with a search command
|
||||
// that will succeed even if no items are found
|
||||
match Command::new("secret-tool")
|
||||
Command::new("secret-tool")
|
||||
.arg("search")
|
||||
.arg("service")
|
||||
.arg("__nonexistent_test__")
|
||||
.output()
|
||||
{
|
||||
Ok(_) => true, // If command runs (even with no results), secret-tool is available
|
||||
Err(_) => false, // Command not found or can't execute
|
||||
}
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
#[cfg(all(not(target_os = "android"), not(target_os = "linux")))]
|
||||
@@ -471,6 +465,19 @@ impl CredentialStore {
|
||||
hasher.finalize().into()
|
||||
}
|
||||
|
||||
/// Load and decrypt the credential map.
|
||||
///
|
||||
/// A file that is present but **undecryptable** is deliberately reported as
|
||||
/// an *empty* credential set rather than as an error. The key never leaves
|
||||
/// the device it was derived on (Android Keystore keys are never backed up,
|
||||
/// and the file fallback's key is derived from machine identifiers), so a
|
||||
/// restored/transferred install gets ciphertext with no key and every read
|
||||
/// would fail *permanently*. Surfacing that as an error made session restore
|
||||
/// throw instead of falling back to the login screen: an unrecoverable app
|
||||
/// rather than a clean logged-out one. The next successful login re-encrypts
|
||||
/// the file with the current key, so the state self-heals.
|
||||
///
|
||||
/// TRACES: UR-012 | IR-014
|
||||
fn load_credentials_file(&self) -> Result<serde_json::Value, CredentialError> {
|
||||
if !self.credentials_path.exists() {
|
||||
return Ok(serde_json::json!({}));
|
||||
@@ -483,8 +490,31 @@ impl CredentialStore {
|
||||
return Ok(serde_json::json!({}));
|
||||
}
|
||||
|
||||
let decrypted = self.decrypt(&encrypted_data)?;
|
||||
serde_json::from_str(&decrypted).map_err(|e| CredentialError::Encryption(e.to_string()))
|
||||
let decrypted = match self.decrypt(&encrypted_data) {
|
||||
Ok(decrypted) => decrypted,
|
||||
Err(e) => {
|
||||
warn!(
|
||||
"Credentials file at {:?} exists but cannot be decrypted ({}); \
|
||||
treating as no stored credentials. This is expected after a \
|
||||
backup restore or device transfer - the encryption key does \
|
||||
not travel with the data. Signing in again will rewrite it.",
|
||||
self.credentials_path, e
|
||||
);
|
||||
return Ok(serde_json::json!({}));
|
||||
}
|
||||
};
|
||||
|
||||
match serde_json::from_str(&decrypted) {
|
||||
Ok(value) => Ok(value),
|
||||
Err(e) => {
|
||||
warn!(
|
||||
"Credentials file at {:?} decrypted to invalid JSON ({}); \
|
||||
treating as no stored credentials.",
|
||||
self.credentials_path, e
|
||||
);
|
||||
Ok(serde_json::json!({}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn save_credentials_file(&self, data: &serde_json::Value) -> Result<(), CredentialError> {
|
||||
@@ -856,6 +886,73 @@ pub use android_keystore::{
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Build a store pinned to the encrypted-file backend with an explicit key,
|
||||
/// so a test can simulate "same file, different machine key" (which is what
|
||||
/// a restored backup looks like).
|
||||
fn file_backed_store(credentials_path: PathBuf, encryption_key: [u8; 32]) -> CredentialStore {
|
||||
CredentialStore {
|
||||
using_keyring: false,
|
||||
credentials_path,
|
||||
encryption_key,
|
||||
}
|
||||
}
|
||||
|
||||
/// A credentials file we cannot decrypt must read as *no credentials stored*,
|
||||
/// not as a hard error. This is the restored-backup case: the ciphertext comes
|
||||
/// back but the key that encrypted it (Android Keystore / the machine-derived
|
||||
/// key) does not, so every read fails forever.
|
||||
///
|
||||
/// TRACES: UR-012 | IR-014
|
||||
#[test]
|
||||
fn undecryptable_credentials_file_reads_as_not_found() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(CREDENTIALS_FILENAME);
|
||||
|
||||
let original = file_backed_store(path.clone(), [1u8; 32]);
|
||||
original.save_to_file("user-1", "token-abc").unwrap();
|
||||
|
||||
// Restored onto a device whose derived key differs: same bytes, no key.
|
||||
let restored = file_backed_store(path.clone(), [2u8; 32]);
|
||||
match restored.get_token("user-1") {
|
||||
Err(CredentialError::NotFound) => {}
|
||||
other => panic!("expected NotFound for undecryptable ciphertext, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Garbage in the file (truncation, partial restore) is the same story.
|
||||
///
|
||||
/// TRACES: UR-012 | IR-014
|
||||
#[test]
|
||||
fn corrupt_credentials_file_reads_as_not_found() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(CREDENTIALS_FILENAME);
|
||||
fs::write(&path, "not base64 at all !!!").unwrap();
|
||||
|
||||
let store = file_backed_store(path, [3u8; 32]);
|
||||
match store.get_token("user-1") {
|
||||
Err(CredentialError::NotFound) => {}
|
||||
other => panic!("expected NotFound for corrupt file, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// …and the logged-out state must be recoverable: signing in again has to be
|
||||
/// able to write over the unreadable file rather than failing on load.
|
||||
///
|
||||
/// TRACES: UR-012 | IR-014
|
||||
#[test]
|
||||
fn login_after_undecryptable_file_rewrites_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(CREDENTIALS_FILENAME);
|
||||
|
||||
let original = file_backed_store(path.clone(), [1u8; 32]);
|
||||
original.save_to_file("user-1", "token-abc").unwrap();
|
||||
|
||||
let restored = file_backed_store(path.clone(), [2u8; 32]);
|
||||
restored.save_to_file("user-1", "token-fresh").unwrap();
|
||||
|
||||
assert_eq!(restored.get_from_file("user-1").unwrap(), "token-fresh");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encryption_roundtrip() {
|
||||
let store = CredentialStore::new();
|
||||
|
||||
@@ -119,11 +119,12 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn item(name: &str, kind: MediaKind) -> MediaItem {
|
||||
let mut item = MediaItem::default();
|
||||
item.id = format!("id-{}-{:?}", name, kind);
|
||||
item.name = name.to_string();
|
||||
item.kind = kind;
|
||||
item
|
||||
MediaItem {
|
||||
id: format!("id-{}-{:?}", name, kind),
|
||||
name: name.to_string(),
|
||||
kind,
|
||||
..MediaItem::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn names(items: &[MediaItem]) -> Vec<&str> {
|
||||
|
||||
@@ -389,14 +389,18 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_queue_precache_config() {
|
||||
let mut config = CacheConfig::default();
|
||||
config.queue_precache_enabled = false;
|
||||
let config = CacheConfig {
|
||||
queue_precache_enabled: false,
|
||||
..CacheConfig::default()
|
||||
};
|
||||
|
||||
let cache = SmartCache::new(config);
|
||||
assert!(!cache.should_precache_queue());
|
||||
|
||||
let mut new_config = CacheConfig::default();
|
||||
new_config.wifi_only = false;
|
||||
let new_config = CacheConfig {
|
||||
wifi_only: false,
|
||||
..CacheConfig::default()
|
||||
};
|
||||
cache.update_config(new_config);
|
||||
|
||||
assert!(cache.should_precache_queue());
|
||||
@@ -407,9 +411,11 @@ mod tests {
|
||||
// wifi_only must not short-circuit precaching: the network gate lives in
|
||||
// the download pump, which checks the *actual* transport. Enabling
|
||||
// WiFi-only while on WiFi should still precache.
|
||||
let mut config = CacheConfig::default();
|
||||
config.queue_precache_enabled = true;
|
||||
config.wifi_only = true;
|
||||
let config = CacheConfig {
|
||||
queue_precache_enabled: true,
|
||||
wifi_only: true,
|
||||
..CacheConfig::default()
|
||||
};
|
||||
|
||||
let cache = SmartCache::new(config);
|
||||
assert!(cache.should_precache_queue());
|
||||
@@ -422,7 +428,7 @@ mod tests {
|
||||
/// TRACES: UR-071 | DR-127 | UT-120
|
||||
#[tokio::test]
|
||||
async fn test_reclaim_expired_only_takes_expired_temporary_entries() {
|
||||
use crate::storage::db_service::{DatabaseService, RusqliteService};
|
||||
use crate::storage::db_service::RusqliteService;
|
||||
use rusqlite::Connection;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
|
||||
+64
-12
@@ -314,6 +314,10 @@ use download::DownloadManager;
|
||||
use jellyfin::{HttpClient, HttpConfig};
|
||||
#[cfg(target_os = "android")]
|
||||
use playback_mode::PlaybackModeManager;
|
||||
// Only the Android MediaSessionHandler resolves lockscreen skips; on other
|
||||
// targets this would be an unused import.
|
||||
#[cfg(target_os = "android")]
|
||||
use player::seek::{resolve_skip_action, SkipAction};
|
||||
use player::{MediaSessionManager, PlayerBackend, PlayerController, TauriEventEmitter};
|
||||
// NullBackend is used both for platforms without a native backend AND as a graceful
|
||||
// fallback when a native backend (MPV/ExoPlayer) fails to initialize, so the app can
|
||||
@@ -449,14 +453,55 @@ impl MediaSessionHandler {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip means different things depending on what is actually playing, so
|
||||
// the decision belongs here rather than in the Kotlin that drew the
|
||||
// button: music advances the queue, while a video whose audio is running
|
||||
// through a background-audio handoff scrubs instead (UR-040). Routed
|
||||
// through the same spawn-and-seek path as "seek:" above, because
|
||||
// `seek_absolute` rebuilds the stream during a handoff and must not run
|
||||
// under the blocking lock (DR-159).
|
||||
//
|
||||
// TRACES: UR-040, UR-006 | DR-201
|
||||
if command == "next" || command == "previous" {
|
||||
let is_next = command == "next";
|
||||
let player = self.player.clone();
|
||||
tokio::spawn(async move {
|
||||
let controller = player.lock().await;
|
||||
let action = resolve_skip_action(
|
||||
is_next,
|
||||
controller.is_background_audio_active(),
|
||||
controller.position(),
|
||||
controller.duration(),
|
||||
);
|
||||
let label = if is_next { "next" } else { "previous" };
|
||||
let result: Result<(), String> = match action {
|
||||
SkipAction::Advance => if is_next {
|
||||
controller.next()
|
||||
} else {
|
||||
controller.previous()
|
||||
}
|
||||
.map_err(|e| e.to_string()),
|
||||
SkipAction::SeekTo(position) => {
|
||||
info!(
|
||||
"[MediaSession] Background audio: '{}' scrubs to {:.1}s",
|
||||
label, position
|
||||
);
|
||||
controller.seek_absolute(position).await
|
||||
}
|
||||
};
|
||||
if let Err(e) = result {
|
||||
error!("[MediaSession] Skip '{}' failed: {}", label, e);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Use blocking_lock since this is called from a non-async JNI callback
|
||||
let controller = self.player.blocking_lock();
|
||||
|
||||
let result = match command {
|
||||
"play" => controller.play(),
|
||||
"pause" => controller.pause(),
|
||||
"next" => controller.next(),
|
||||
"previous" => controller.previous(),
|
||||
"stop" => controller.stop(),
|
||||
_ => {
|
||||
warn!("[MediaSession] Unknown command: {}", command);
|
||||
@@ -620,7 +665,7 @@ fn create_player_backend(
|
||||
match MpvBackend::new(Some(_event_emitter), playback_reporter, position_throttler) {
|
||||
Ok(backend) => {
|
||||
info!("Successfully initialized MPV backend for Linux");
|
||||
return Box::new(backend);
|
||||
Box::new(backend)
|
||||
}
|
||||
Err(e) => {
|
||||
error!("\n========================================");
|
||||
@@ -645,7 +690,7 @@ fn create_player_backend(
|
||||
// still browse the library and manage downloads, and the frontend
|
||||
// can show a "playback unavailable" notice via this event.
|
||||
emit_backend_init_failed(&app_handle, "mpv", e.to_string());
|
||||
return Box::new(NullBackend::new());
|
||||
Box::new(NullBackend::new())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1029,16 +1074,23 @@ fn set_env_if_unset(key: &str, value: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Downloaded media and cached thumbnails are handed to the webview as
|
||||
/// `http://asset.localhost/…` URLs by `convertFileSrc`. Tauri only answers that
|
||||
/// Cached thumbnails are handed to the webview as asset-protocol URLs by
|
||||
/// `convertFileSrc` (`asset://localhost/…` on Linux/macOS,
|
||||
/// `http://asset.localhost/…` on Windows/Android). Tauri only answers that
|
||||
/// origin when the `protocol-asset` cargo feature is compiled in *and*
|
||||
/// `app.security.assetProtocol.enable` is set in `tauri.conf.json`, which also
|
||||
/// scopes it to `$APPDATA/**` — the storage root holding the database,
|
||||
/// `downloads/` and the thumbnail cache. Both are required together: with either
|
||||
/// missing the URL resolves to nothing and the webview reports
|
||||
/// `NETWORK_NO_SOURCE`, which is how offline video came to fail silently.
|
||||
/// `app.security.assetProtocol.enable` is set in `tauri.conf.json`. Both are
|
||||
/// required together: with either missing the URL resolves to nothing and the
|
||||
/// webview reports `NETWORK_NO_SOURCE`, which is how offline video came to fail
|
||||
/// silently.
|
||||
///
|
||||
/// TRACES: UR-071 | DR-134
|
||||
/// The scope is `$APPDATA/thumbnails/**`, not the storage root: downloaded media
|
||||
/// moved to the loopback media server in DR-137, so `imageCache` is the only
|
||||
/// remaining `convertFileSrc` caller and the database and the encrypted-token
|
||||
/// fallback file — which share that root — never need to be readable by the
|
||||
/// webview. Widen it only if something other than thumbnails starts resolving
|
||||
/// through `convertFileSrc` again.
|
||||
///
|
||||
/// TRACES: UR-012, UR-071 | DR-134, DR-137, DR-198
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
// Initialize logger
|
||||
|
||||
@@ -624,7 +624,7 @@ impl PlaybackModeManager {
|
||||
);
|
||||
|
||||
// Log first few track IDs for debugging
|
||||
if queue_ids.len() > 0 {
|
||||
if !queue_ids.is_empty() {
|
||||
let preview: Vec<&str> = queue_ids.iter().take(3).map(|s| s.as_str()).collect();
|
||||
debug!("[PlaybackMode] First track IDs: {:?}...", preview);
|
||||
}
|
||||
@@ -914,7 +914,7 @@ mod tests {
|
||||
|
||||
impl PlayerEventEmitter for CapturingEmitter {
|
||||
fn emit(&self, event: PlayerStatusEvent) {
|
||||
self.events.lock().unwrap().push(event);
|
||||
self.events.lock_safe().push(event);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -942,7 +942,7 @@ mod tests {
|
||||
manager.set_mode(PlaybackMode::Local);
|
||||
manager.set_mode(PlaybackMode::Idle);
|
||||
|
||||
let events = emitter.events.lock().unwrap();
|
||||
let events = emitter.events.lock_safe();
|
||||
assert_eq!(events.len(), 3, "one event per real mode change");
|
||||
|
||||
match &events[0] {
|
||||
@@ -975,10 +975,10 @@ mod tests {
|
||||
|
||||
impl RemoteVolumeControl for RecordingVolumeControl {
|
||||
fn enable(&self, _initial_volume: i32) {
|
||||
self.calls.lock().unwrap().push("enable");
|
||||
self.calls.lock_safe().push("enable");
|
||||
}
|
||||
fn disable(&self) {
|
||||
self.calls.lock().unwrap().push("disable");
|
||||
self.calls.lock_safe().push("disable");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1014,7 +1014,7 @@ mod tests {
|
||||
manager.set_mode(PlaybackMode::Idle);
|
||||
|
||||
assert_eq!(
|
||||
*volume.calls.lock().unwrap(),
|
||||
*volume.calls.lock_safe(),
|
||||
vec!["enable", "disable"],
|
||||
"remote->idle must return volume control to the local speaker"
|
||||
);
|
||||
@@ -1033,7 +1033,7 @@ mod tests {
|
||||
manager.set_mode(PlaybackMode::Local);
|
||||
|
||||
assert_eq!(
|
||||
*volume.calls.lock().unwrap(),
|
||||
*volume.calls.lock_safe(),
|
||||
vec!["enable", "disable"],
|
||||
"remote->local must return volume control to the local speaker"
|
||||
);
|
||||
@@ -1053,7 +1053,7 @@ mod tests {
|
||||
manager.set_mode(PlaybackMode::Local);
|
||||
|
||||
assert!(
|
||||
volume.calls.lock().unwrap().is_empty(),
|
||||
volume.calls.lock_safe().is_empty(),
|
||||
"local/idle transitions must not touch remote volume routing"
|
||||
);
|
||||
}
|
||||
@@ -1074,7 +1074,7 @@ mod tests {
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
*volume.calls.lock().unwrap(),
|
||||
*volume.calls.lock_safe(),
|
||||
vec!["enable", "enable"],
|
||||
"remote->remote re-arms control without releasing it to local"
|
||||
);
|
||||
@@ -1091,7 +1091,7 @@ mod tests {
|
||||
manager.set_mode(PlaybackMode::Local);
|
||||
|
||||
assert_eq!(
|
||||
emitter.events.lock().unwrap().len(),
|
||||
emitter.events.lock_safe().len(),
|
||||
1,
|
||||
"repeated identical mode set emits only once"
|
||||
);
|
||||
|
||||
@@ -420,7 +420,18 @@ impl PlayerBackend for ExoPlayerBackend {
|
||||
None => JValue::Object(&null_obj),
|
||||
};
|
||||
|
||||
// Determine media type string for JNI
|
||||
// Determine media type string for JNI.
|
||||
//
|
||||
// This is not cosmetic: the string decides *which audio-focus mechanism*
|
||||
// runs on the Kotlin side. `JellyTauPlayer.load()` re-applies
|
||||
// `setAudioAttributes(attrs, handleAudioFocus = mediaType == AUDIO)`, so
|
||||
// "audio" leaves focus to ExoPlayer (request on play, duck on transient
|
||||
// loss, pause on a call) while "video" switches it to the manual
|
||||
// `AudioFocusRequest` path, which needs delayed-focus handling. Either
|
||||
// way the resulting pause comes back through `nativeOnStateChanged`, so
|
||||
// the Rust controller — not the focus listener — stays authoritative.
|
||||
//
|
||||
// TRACES: UR-004, UR-006 | IR-008
|
||||
let media_type_str = match media.media_type {
|
||||
MediaType::Video => "video",
|
||||
MediaType::Audio => "audio",
|
||||
@@ -1096,6 +1107,15 @@ pub extern "system" fn Java_com_dtourolle_jellytau_player_JellyTauPlayer_nativeO
|
||||
///
|
||||
/// Commands from lockscreen controls, notification buttons, and Bluetooth
|
||||
/// devices are routed through here to the Rust PlayerController.
|
||||
///
|
||||
/// This is the inbound half of UR-006: `MediaSessionCompat` is flagged
|
||||
/// `FLAG_HANDLES_MEDIA_BUTTONS`, so an AVRCP play/pause/skip from a headset
|
||||
/// arrives at the service's transport callback and lands here as a command
|
||||
/// string. The player stays authoritative — the session is a consumer that
|
||||
/// *requests*, and the resulting state comes back out through
|
||||
/// [`update_lockscreen_metadata`].
|
||||
///
|
||||
/// TRACES: UR-006 | IR-006
|
||||
#[no_mangle]
|
||||
pub extern "system" fn Java_com_dtourolle_jellytau_player_JellyTauPlaybackService_nativeOnMediaCommand(
|
||||
mut env: JNIEnv,
|
||||
@@ -1396,6 +1416,8 @@ use crate::player::LockscreenMetadata;
|
||||
/// running (in remote mode it is started via [`enable_remote_volume`]); if it
|
||||
/// isn't, this is a no-op rather than an error so it can be called freely on
|
||||
/// every poll tick.
|
||||
///
|
||||
/// TRACES: UR-006 | IR-006
|
||||
pub fn update_lockscreen_metadata(meta: &LockscreenMetadata) -> Result<(), String> {
|
||||
let vm = JAVA_VM.get().ok_or("JavaVM not initialized")?;
|
||||
let mut env = vm.attach_current_thread().map_err(|e| e.to_string())?;
|
||||
|
||||
@@ -6,6 +6,12 @@ use serde::{Deserialize, Serialize};
|
||||
/// Autoplay decision result - determines what happens after playback ends
|
||||
#[derive(specta::Type, Debug, Clone, Serialize)]
|
||||
#[serde(tag = "action", rename_all = "camelCase")]
|
||||
// `ShowNextEpisodePopup` carries two `MediaItem`s, so it dwarfs the unit
|
||||
// variants. Boxing them is not worth it here: this enum is constructed once per
|
||||
// end-of-item (never in a hot loop or a large collection), and it is an IPC type
|
||||
// — the indirection would have to stay invisible to serde/specta while every
|
||||
// match arm gained a deref, for no measurable gain.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum AutoplayDecision {
|
||||
/// Stop playback (no next item or timer expired)
|
||||
Stop,
|
||||
|
||||
@@ -98,9 +98,12 @@ pub trait PlayerBackend: Send + Sync {
|
||||
|
||||
/// Set the active audio track by stream index
|
||||
///
|
||||
/// @req-planned: UR-021 - Select audio track for video content
|
||||
/// @req-planned: IR-019 - libmpv audio track selection
|
||||
/// @req-planned: DR-024 - Audio track selection UI in video player
|
||||
/// Overridden by the Android (ExoPlayer) backend. `MpvBackend` deliberately
|
||||
/// does **not** override it — MPV is the audio-only backend here, so it keeps
|
||||
/// this `not_implemented()` default and the Linux video path switches track by
|
||||
/// re-opening the stream instead (`player_switch_audio_track`).
|
||||
///
|
||||
/// TRACES: UR-021 | IR-019, DR-024
|
||||
fn set_audio_track(&mut self, _stream_index: i32) -> Result<(), PlayerError> {
|
||||
// Default implementation does nothing - override in platform-specific backends
|
||||
Err(PlayerError::not_implemented())
|
||||
@@ -108,9 +111,12 @@ pub trait PlayerBackend: Send + Sync {
|
||||
|
||||
/// Set the active subtitle track by stream index (None to disable subtitles)
|
||||
///
|
||||
/// @req-planned: UR-020 - Select subtitles for video content
|
||||
/// @req-planned: IR-018 - libmpv subtitle rendering and selection
|
||||
/// @req-planned: DR-023 - Subtitle selection UI in video player
|
||||
/// Overridden by the Android (ExoPlayer) backend. `MpvBackend` deliberately
|
||||
/// does **not** override it, so it keeps this `not_implemented()` default;
|
||||
/// the Linux video path renders subtitles as `<track>` children of the
|
||||
/// WebKitGTK HTML5 `<video>` element and never calls this.
|
||||
///
|
||||
/// TRACES: UR-020 | IR-018, DR-023
|
||||
fn set_subtitle_track(&mut self, _stream_index: Option<i32>) -> Result<(), PlayerError> {
|
||||
// Default implementation does nothing - override in platform-specific backends
|
||||
Err(PlayerError::not_implemented())
|
||||
|
||||
@@ -30,6 +30,12 @@ use super::{MediaSessionType, SleepTimerMode};
|
||||
// queue_changed never reach the frontend, so the mini player never appears).
|
||||
// Keep serde and specta agreeing: snake_case fields, snake_case variant tags.
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
// `ShowNextEpisodePopup` carries two `MediaItem`s, so it dwarfs the small
|
||||
// position/state variants. Boxing them is rejected deliberately: this is a
|
||||
// serde + specta wire type whose generated TypeScript must not shift, and the
|
||||
// events are emitted a few times a second at most — never bulk-allocated — so
|
||||
// the size difference costs nothing measurable.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum PlayerStatusEvent {
|
||||
/// Playback position updated (emitted periodically during playback)
|
||||
PositionUpdate {
|
||||
|
||||
@@ -140,6 +140,8 @@ const RESUME_BACKOFF_STEP_SECS: u64 = 2;
|
||||
/// the local ExoPlayer is idle and so can't supply now-playing info. The session
|
||||
/// poller fills this in from the remote Jellyfin session and pushes it to the
|
||||
/// notification so the lockscreen stays in sync while casting.
|
||||
///
|
||||
/// TRACES: UR-006 | IR-006
|
||||
#[derive(Debug, Clone)]
|
||||
// Fields are read only by the Android MediaSession bridge; on other platforms
|
||||
// `update_lockscreen_metadata` is a no-op, so they're constructed but unread.
|
||||
@@ -157,6 +159,11 @@ pub struct LockscreenMetadata {
|
||||
|
||||
/// Push now-playing metadata to the Android lockscreen. No-op off Android, so the
|
||||
/// session poller can call it unconditionally and stay platform-agnostic.
|
||||
///
|
||||
/// No-op on Linux specifically because there is no MPRIS/D-Bus publisher — see
|
||||
/// IR-005, which is still Planned.
|
||||
///
|
||||
/// TRACES: UR-006 | IR-006
|
||||
pub fn update_lockscreen_metadata(_meta: &LockscreenMetadata) -> Result<(), String> {
|
||||
#[cfg(target_os = "android")]
|
||||
{
|
||||
|
||||
@@ -243,7 +243,7 @@ impl MpvBackend {
|
||||
});
|
||||
}
|
||||
}
|
||||
libmpv::events::Event::PropertyChange { name, .. } if name == "pause" => {
|
||||
libmpv::events::Event::PropertyChange { name: "pause", .. } => {
|
||||
// Handle pause state changes
|
||||
if let Ok(is_paused) = mpv.get_property::<bool>("pause") {
|
||||
let media_id = state
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
/// Tests for MpvBackend to prevent regressions
|
||||
///
|
||||
/// These tests are designed to catch common issues like:
|
||||
/// - Tokio runtime panics when spawning async tasks from std::thread
|
||||
/// - Position update thread failures
|
||||
/// - Event emission issues
|
||||
///
|
||||
/// TRACES: UR-003, UR-004 | IR-003 | IT-003, IT-004
|
||||
//! Tests for MpvBackend to prevent regressions
|
||||
//!
|
||||
//! These tests are designed to catch common issues like:
|
||||
//! - Tokio runtime panics when spawning async tasks from std::thread
|
||||
//! - Position update thread failures
|
||||
//! - Event emission issues
|
||||
//!
|
||||
//! TRACES: UR-003, UR-004 | IR-003 | IT-003, IT-004
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::utils::lock::MutexSafe;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tokio::sync::Mutex as TokioMutex;
|
||||
|
||||
@@ -67,14 +68,14 @@ mod tests {
|
||||
if let Ok(handle) = tokio::runtime::Handle::try_current() {
|
||||
// Has runtime (shouldn't happen in this test)
|
||||
handle.spawn(async move {
|
||||
*counter_clone.lock().unwrap() += 1;
|
||||
*counter_clone.lock_safe() += 1;
|
||||
});
|
||||
} else {
|
||||
// No runtime - use fallback (should happen in this test)
|
||||
std::thread::spawn(move || {
|
||||
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||
rt.block_on(async move {
|
||||
*counter_clone.lock().unwrap() += 1;
|
||||
*counter_clone.lock_safe() += 1;
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -85,7 +86,7 @@ mod tests {
|
||||
// Wait for async task to complete
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
|
||||
let count = *counter.lock().unwrap();
|
||||
let count = *counter.lock_safe();
|
||||
assert_eq!(
|
||||
count, 1,
|
||||
"Fallback pattern should execute async code successfully"
|
||||
@@ -109,13 +110,13 @@ mod tests {
|
||||
let position = i as f64 * 0.25;
|
||||
|
||||
// Store position (simulating event emission)
|
||||
positions_clone.lock().unwrap().push(position);
|
||||
positions_clone.lock_safe().push(position);
|
||||
}
|
||||
});
|
||||
|
||||
handle.join().unwrap();
|
||||
|
||||
let recorded_positions = positions.lock().unwrap();
|
||||
let recorded_positions = positions.lock_safe();
|
||||
assert_eq!(
|
||||
recorded_positions.len(),
|
||||
5,
|
||||
|
||||
@@ -806,11 +806,10 @@ mod tests {
|
||||
assert_eq!(queue.current_index(), Some(first_shuffled_index));
|
||||
|
||||
// Move through shuffle order
|
||||
for i in 1..shuffle_order.len() {
|
||||
for &expected_index in &shuffle_order[1..] {
|
||||
assert!(queue.has_next());
|
||||
let result = queue.next();
|
||||
assert!(result.is_some());
|
||||
let expected_index = shuffle_order[i];
|
||||
assert_eq!(queue.current_index(), Some(expected_index));
|
||||
}
|
||||
|
||||
|
||||
@@ -59,10 +59,149 @@ pub fn determine_video_seek_strategy(
|
||||
}
|
||||
}
|
||||
|
||||
// The four items below are consumed by the Android MediaSessionHandler; on other
|
||||
// targets only the tests exercise them, so dead-code analysis would flag them.
|
||||
|
||||
/// How far a lockscreen skip-forward jumps while background audio owns playback.
|
||||
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
|
||||
pub const SKIP_FORWARD_SECONDS: f64 = 30.0;
|
||||
|
||||
/// How far a lockscreen skip-back jumps while background audio owns playback.
|
||||
///
|
||||
/// Deliberately shorter than the forward jump: the back button is used to replay
|
||||
/// dialogue just missed, not to travel.
|
||||
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
|
||||
pub const SKIP_BACK_SECONDS: f64 = 10.0;
|
||||
|
||||
/// What a lockscreen skip button means for the playback that is actually running.
|
||||
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum SkipAction {
|
||||
/// Move to the next/previous queue entry — a track, or an episode.
|
||||
Advance,
|
||||
/// Scrub within the current item, to this absolute position in seconds.
|
||||
SeekTo(f64),
|
||||
}
|
||||
|
||||
/// Decide whether a lockscreen skip advances the queue or scrubs the current item.
|
||||
///
|
||||
/// Music gets queue advance, which is what the buttons look like they do. A video
|
||||
/// whose audio is playing through a background-audio handoff (UR-040) gets a
|
||||
/// relative scrub instead: there is no meaningful "next track" inside a film, and
|
||||
/// jumping to the next *episode* because the user wanted to re-hear a line is a
|
||||
/// much worse outcome than a scrub.
|
||||
///
|
||||
/// `is_background_audio` is the whole test, and it is sufficient on its own —
|
||||
/// the handoff exists only for video, and an episode played through it reports
|
||||
/// `MediaType::Audio`, so media type cannot distinguish this case (see the note
|
||||
/// at `PlayerController::auto_advance_to_next_episode`).
|
||||
///
|
||||
/// Clamped to `[0, duration]` so a skip near either end lands in the item rather
|
||||
/// than at a negative offset or past the end, which some backends treat as EOF
|
||||
/// and would turn a scrub into an unintended advance.
|
||||
///
|
||||
/// TRACES: UR-040, UR-006 | DR-201
|
||||
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
|
||||
pub fn resolve_skip_action(
|
||||
is_next: bool,
|
||||
is_background_audio: bool,
|
||||
position: f64,
|
||||
duration: Option<f64>,
|
||||
) -> SkipAction {
|
||||
if !is_background_audio {
|
||||
return SkipAction::Advance;
|
||||
}
|
||||
|
||||
let target = if is_next {
|
||||
position + SKIP_FORWARD_SECONDS
|
||||
} else {
|
||||
position - SKIP_BACK_SECONDS
|
||||
};
|
||||
|
||||
let clamped = match duration {
|
||||
Some(d) if d > 0.0 => target.clamp(0.0, d),
|
||||
_ => target.max(0.0),
|
||||
};
|
||||
|
||||
SkipAction::SeekTo(clamped)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Music (no background-audio handoff) keeps queue advance on both buttons.
|
||||
///
|
||||
/// TRACES: UR-006 | DR-201 | UT-194
|
||||
#[test]
|
||||
fn test_skip_advances_queue_for_normal_audio() {
|
||||
assert_eq!(
|
||||
resolve_skip_action(true, false, 42.0, Some(300.0)),
|
||||
SkipAction::Advance
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_skip_action(false, false, 42.0, Some(300.0)),
|
||||
SkipAction::Advance
|
||||
);
|
||||
}
|
||||
|
||||
/// The reported bug: in background-audio mode the lockscreen skip buttons
|
||||
/// advanced to the next/previous episode instead of scrubbing, so trying to
|
||||
/// re-hear a line jumped out of the film entirely.
|
||||
///
|
||||
/// TRACES: UR-040 | DR-201 | UT-195
|
||||
#[test]
|
||||
fn test_skip_scrubs_in_background_audio_mode() {
|
||||
assert_eq!(
|
||||
resolve_skip_action(true, true, 100.0, Some(3600.0)),
|
||||
SkipAction::SeekTo(130.0)
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_skip_action(false, true, 100.0, Some(3600.0)),
|
||||
SkipAction::SeekTo(90.0)
|
||||
);
|
||||
}
|
||||
|
||||
/// Skipping back near the start clamps to zero rather than going negative,
|
||||
/// which backends reject (the "Raw(-10)" class of error).
|
||||
///
|
||||
/// TRACES: UR-040 | DR-201 | UT-196
|
||||
#[test]
|
||||
fn test_skip_back_clamps_at_start() {
|
||||
assert_eq!(
|
||||
resolve_skip_action(false, true, 4.0, Some(3600.0)),
|
||||
SkipAction::SeekTo(0.0)
|
||||
);
|
||||
}
|
||||
|
||||
/// Skipping forward near the end clamps to the duration instead of running
|
||||
/// past it, which would read as end-of-stream and advance — the very thing
|
||||
/// this function exists to prevent.
|
||||
///
|
||||
/// TRACES: UR-040 | DR-201 | UT-197
|
||||
#[test]
|
||||
fn test_skip_forward_clamps_at_end() {
|
||||
assert_eq!(
|
||||
resolve_skip_action(true, true, 3590.0, Some(3600.0)),
|
||||
SkipAction::SeekTo(3600.0)
|
||||
);
|
||||
}
|
||||
|
||||
/// An unknown duration still scrubs, and still refuses to go negative.
|
||||
///
|
||||
/// TRACES: UR-040 | DR-201 | UT-198
|
||||
#[test]
|
||||
fn test_skip_without_duration_still_scrubs() {
|
||||
assert_eq!(
|
||||
resolve_skip_action(true, true, 10.0, None),
|
||||
SkipAction::SeekTo(40.0)
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_skip_action(false, true, 3.0, None),
|
||||
SkipAction::SeekTo(0.0)
|
||||
);
|
||||
}
|
||||
|
||||
/// Test video seek strategy for local files
|
||||
#[test]
|
||||
fn test_seek_strategy_local_file() {
|
||||
|
||||
@@ -159,6 +159,9 @@ mod tests {
|
||||
#[test]
|
||||
fn test_end_reason_clone() {
|
||||
let reason = EndReason::Finished;
|
||||
// Deliberately exercising the derived `Clone` impl, not a plain copy:
|
||||
// `EndReason` is also `Copy`, so clippy flags the call as redundant.
|
||||
#[allow(clippy::clone_on_copy)]
|
||||
let cloned = reason.clone();
|
||||
assert_eq!(reason, cloned);
|
||||
}
|
||||
|
||||
@@ -196,7 +196,7 @@ mod tests {
|
||||
|
||||
impl PlayerEventEmitter for RecordingEmitter {
|
||||
fn emit(&self, event: PlayerStatusEvent) {
|
||||
self.events.lock().unwrap().push(event);
|
||||
self.events.lock_safe().push(event);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -244,7 +244,7 @@ mod tests {
|
||||
let (mut b, events) = backend();
|
||||
b.load(&test_media()).unwrap();
|
||||
|
||||
let ev = events.lock().unwrap();
|
||||
let ev = events.lock_safe();
|
||||
let load = ev
|
||||
.iter()
|
||||
.find(|e| matches!(e, PlayerStatusEvent::WebviewAudioLoad { .. }))
|
||||
@@ -263,7 +263,7 @@ mod tests {
|
||||
b.pause().unwrap();
|
||||
b.seek(42.0).unwrap();
|
||||
|
||||
let ev = events.lock().unwrap();
|
||||
let ev = events.lock_safe();
|
||||
assert!(ev.iter().any(|e| matches!(
|
||||
e,
|
||||
PlayerStatusEvent::ControlCommand { action, .. } if action == "pause"
|
||||
|
||||
@@ -1134,6 +1134,16 @@ impl MediaRepository for HybridRepository {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
// `GATE_TEST_LOCK` below serialises the tests that flip the process-global
|
||||
// `INCLUDE_CATALOG_BROWSE` flag, so its guard is deliberately held across
|
||||
// the `.await` of the repository call under test — that await *is* the
|
||||
// critical section. This is not the production deadlock hazard the lint
|
||||
// targets: the lock is test-only, uncontended outside these tests, and each
|
||||
// `#[tokio::test]` runs on its own single-threaded runtime, so a held guard
|
||||
// cannot block another task on the same worker. Restructuring around it
|
||||
// would reintroduce the flag race the lock exists to prevent.
|
||||
#![allow(clippy::await_holding_lock)]
|
||||
|
||||
use super::*;
|
||||
use std::sync::Mutex;
|
||||
|
||||
|
||||
@@ -2510,6 +2510,16 @@ impl MediaRepository for OfflineRepository {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
// `CATALOG_BROWSE_LOCK` below serialises the tests that flip the
|
||||
// process-global `INCLUDE_CATALOG_BROWSE` flag, so its guard is deliberately
|
||||
// held across the `.await` of the query under test — that await *is* the
|
||||
// critical section. This is not the production deadlock hazard the lint
|
||||
// targets: the lock is test-only, uncontended outside these tests, and each
|
||||
// `#[tokio::test]` runs on its own single-threaded runtime, so a held guard
|
||||
// cannot block another task on the same worker. Restructuring around it
|
||||
// would reintroduce the flag race the lock exists to prevent.
|
||||
#![allow(clippy::await_holding_lock)]
|
||||
|
||||
use super::*;
|
||||
use crate::storage::db_service::RusqliteService;
|
||||
use rusqlite::Connection;
|
||||
@@ -2524,9 +2534,8 @@ mod tests {
|
||||
static CATALOG_BROWSE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn lock_catalog_browse() -> std::sync::MutexGuard<'static, ()> {
|
||||
CATALOG_BROWSE_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
use crate::utils::lock::MutexSafe;
|
||||
CATALOG_BROWSE_LOCK.lock_safe()
|
||||
}
|
||||
|
||||
/// TRACES: UR-065 | DR-108 | UT-111
|
||||
|
||||
@@ -760,7 +760,11 @@ struct JellyfinItem {
|
||||
/// `UserData` in the `Fields=` list so the shape is explicit rather than
|
||||
/// dependent on the server's default field set.
|
||||
///
|
||||
/// TRACES: UR-069 | DR-113, JA-034 | UT-099
|
||||
/// `PlaybackPositionTicks` is the server's resume position for the item, and the
|
||||
/// only place it is published — Jellyfin has no per-item "resume position"
|
||||
/// endpoint, so reading `UserData` *is* how a resume point is obtained.
|
||||
///
|
||||
/// TRACES: UR-019, UR-069 | DR-113, JA-013, JA-034 | UT-099
|
||||
#[derive(Debug, Deserialize, Clone)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct JellyfinUserData {
|
||||
@@ -854,6 +858,8 @@ fn build_get_items_endpoint(
|
||||
///
|
||||
/// Pulled out of `get_latest_items` so the query can be asserted without an
|
||||
/// HTTP server, matching `build_favorites_endpoint`.
|
||||
///
|
||||
/// TRACES: UR-024, UR-034 | IR-024, JA-016
|
||||
fn build_latest_items_endpoint(user_id: &str, parent_id: &str, limit: Option<usize>) -> String {
|
||||
format!(
|
||||
"/Users/{}/Items/Latest?ParentId={}&Limit={}&GroupItems=true&Fields=BackdropImageTags,ParentBackdropImageTags,UserData",
|
||||
@@ -875,7 +881,7 @@ fn build_latest_items_endpoint(user_id: &str, parent_id: &str, limit: Option<usi
|
||||
/// Pulled out of `get_next_up_episodes` so the query can be asserted without an
|
||||
/// HTTP server, matching `build_favorites_endpoint`.
|
||||
///
|
||||
/// TRACES: UR-059 | DR-197, JA-036 | UT-190, UT-191
|
||||
/// TRACES: UR-023, UR-059 | DR-197, JA-014, JA-036 | UT-190, UT-191
|
||||
fn build_next_up_endpoint(user_id: &str, series_id: Option<&str>, limit: Option<usize>) -> String {
|
||||
let mut endpoint = format!(
|
||||
"/Shows/NextUp?UserId={}&Limit={}&EnableResumable=false&Fields=BackdropImageTags,ParentBackdropImageTags,UserData",
|
||||
@@ -984,7 +990,7 @@ struct JellyfinMediaSource {
|
||||
}
|
||||
|
||||
impl JellyfinItem {
|
||||
fn to_media_item(self, server_id: String) -> MediaItem {
|
||||
fn into_media_item(self, server_id: String) -> MediaItem {
|
||||
// Extract image tags before consuming self
|
||||
let primary_tag = self.image_tags.as_ref().and_then(|tags| tags.primary());
|
||||
let backdrop_tags = self.backdrop_image_tags;
|
||||
@@ -1123,17 +1129,28 @@ impl MediaRepository for OnlineRepository {
|
||||
items: response
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| item.to_media_item(self.user_id.clone()))
|
||||
.map(|item| item.into_media_item(self.user_id.clone()))
|
||||
.collect(),
|
||||
total_record_count: response.total_record_count,
|
||||
})
|
||||
}
|
||||
|
||||
/// Fetch one item with every field the detail and player screens need.
|
||||
///
|
||||
/// The `Fields=` list is the load-bearing part: Jellyfin omits these unless
|
||||
/// they are named. `MediaStreams` is what makes the item's **audio and
|
||||
/// subtitle tracks** knowable at all — there is no separate "tracks"
|
||||
/// endpoint, so this single call is how the player learns which audio tracks
|
||||
/// an item offers (`to_media_item` maps them, and the player's selector
|
||||
/// filters them by `kind`). `People` is likewise how **cast and crew** are
|
||||
/// obtained.
|
||||
///
|
||||
/// TRACES: UR-021, UR-035 | IR-016, IR-022, JA-005, JA-009
|
||||
async fn get_item(&self, item_id: &str) -> Result<MediaItem, RepoError> {
|
||||
let endpoint = format!("/Users/{}/Items/{}?Fields=BackdropImageTags,ParentBackdropImageTags,People,MediaStreams,MediaSources,PremiereDate,UserData", self.user_id, item_id);
|
||||
|
||||
let item: JellyfinItem = self.get_json(&endpoint).await?;
|
||||
let media_item = item.to_media_item(self.user_id.clone());
|
||||
let media_item = item.into_media_item(self.user_id.clone());
|
||||
|
||||
Ok(media_item)
|
||||
}
|
||||
@@ -1148,10 +1165,18 @@ impl MediaRepository for OnlineRepository {
|
||||
let items: Vec<JellyfinItem> = self.get_json(&endpoint).await?;
|
||||
Ok(items
|
||||
.into_iter()
|
||||
.map(|item| item.to_media_item(self.user_id.clone()))
|
||||
.map(|item| item.into_media_item(self.user_id.clone()))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Continue Watching: the items this user has started and not finished.
|
||||
///
|
||||
/// `/Users/{uid}/Items/Resume` is the server-side answer to both "what goes
|
||||
/// in the Continue Watching row" and "where was this left off" — each item
|
||||
/// carries its own `UserData.PlaybackPositionTicks`, which is why `UserData`
|
||||
/// is named in `Fields=` rather than left to the server's default field set.
|
||||
///
|
||||
/// TRACES: UR-019, UR-023 | IR-024, JA-013, JA-015
|
||||
async fn get_resume_items(
|
||||
&self,
|
||||
parent_id: Option<&str>,
|
||||
@@ -1171,10 +1196,14 @@ impl MediaRepository for OnlineRepository {
|
||||
Ok(response
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| item.to_media_item(self.user_id.clone()))
|
||||
.map(|item| item.into_media_item(self.user_id.clone()))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// "Next Up": the episode that follows the ones this user has finished,
|
||||
/// per series — the Shows-scoped counterpart to Continue Watching.
|
||||
///
|
||||
/// TRACES: UR-023, UR-059 | IR-024, JA-014
|
||||
async fn get_next_up_episodes(
|
||||
&self,
|
||||
series_id: Option<&str>,
|
||||
@@ -1186,7 +1215,7 @@ impl MediaRepository for OnlineRepository {
|
||||
Ok(response
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| item.to_media_item(self.user_id.clone()))
|
||||
.map(|item| item.into_media_item(self.user_id.clone()))
|
||||
.collect())
|
||||
}
|
||||
|
||||
@@ -1206,7 +1235,7 @@ impl MediaRepository for OnlineRepository {
|
||||
let items: Vec<MediaItem> = response
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| item.to_media_item(self.user_id.clone()))
|
||||
.map(|item| item.into_media_item(self.user_id.clone()))
|
||||
.collect();
|
||||
|
||||
debug!("[get_recently_played_audio] Fetched {} items", items.len());
|
||||
@@ -1229,7 +1258,7 @@ impl MediaRepository for OnlineRepository {
|
||||
"[get_recently_played_audio] Grouping item '{}' into album '{}'",
|
||||
item.name, key
|
||||
);
|
||||
album_map.entry(key).or_insert_with(Vec::new).push(item);
|
||||
album_map.entry(key).or_default().push(item);
|
||||
} else {
|
||||
debug!(
|
||||
"[get_recently_played_audio] No album_id or album_name for item: '{}'",
|
||||
@@ -1344,10 +1373,15 @@ impl MediaRepository for OnlineRepository {
|
||||
Ok(response
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| item.to_media_item(self.user_id.clone()))
|
||||
.map(|item| item.into_media_item(self.user_id.clone()))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Continue Watching, narrowed to movies — the home screen's movie row and
|
||||
/// the movie library's own hero both want the unfinished films without the
|
||||
/// episodes mixed in.
|
||||
///
|
||||
/// TRACES: UR-019, UR-034 | IR-024, JA-013, JA-015
|
||||
async fn get_resume_movies(&self, limit: Option<usize>) -> Result<Vec<MediaItem>, RepoError> {
|
||||
let limit_str = limit.unwrap_or(16);
|
||||
let endpoint = format!(
|
||||
@@ -1359,7 +1393,7 @@ impl MediaRepository for OnlineRepository {
|
||||
Ok(response
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| item.to_media_item(self.user_id.clone()))
|
||||
.map(|item| item.into_media_item(self.user_id.clone()))
|
||||
.collect())
|
||||
}
|
||||
|
||||
@@ -1423,6 +1457,14 @@ impl MediaRepository for OnlineRepository {
|
||||
Ok(genres)
|
||||
}
|
||||
|
||||
/// Search every library the user can see.
|
||||
///
|
||||
/// `Recursive=true` with no `ParentId` is what makes this cross-library
|
||||
/// rather than folder-scoped; a caller narrowing the search passes the item
|
||||
/// types through `SearchOptions` (already expanded from an opaque
|
||||
/// `SearchScope` on this side of the boundary).
|
||||
///
|
||||
/// TRACES: UR-008 | IR-010, JA-006
|
||||
async fn search(
|
||||
&self,
|
||||
query: &str,
|
||||
@@ -1461,7 +1503,7 @@ impl MediaRepository for OnlineRepository {
|
||||
items: response
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| item.to_media_item(self.user_id.clone()))
|
||||
.map(|item| item.into_media_item(self.user_id.clone()))
|
||||
.collect(),
|
||||
total_record_count: response.total_record_count,
|
||||
})
|
||||
@@ -1839,7 +1881,7 @@ impl MediaRepository for OnlineRepository {
|
||||
Ok(response
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| item.to_media_item(self.server_url.clone()))
|
||||
.map(|item| item.into_media_item(self.server_url.clone()))
|
||||
.collect())
|
||||
}
|
||||
|
||||
@@ -1852,7 +1894,7 @@ impl MediaRepository for OnlineRepository {
|
||||
let items = response
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| item.to_media_item(self.server_url.clone()))
|
||||
.map(|item| item.into_media_item(self.server_url.clone()))
|
||||
.collect();
|
||||
Ok(SearchResult {
|
||||
items,
|
||||
@@ -2189,12 +2231,18 @@ impl MediaRepository for OnlineRepository {
|
||||
items: response
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| item.to_media_item(self.user_id.clone()))
|
||||
.map(|item| item.into_media_item(self.user_id.clone()))
|
||||
.collect(),
|
||||
total_record_count: response.total_record_count,
|
||||
})
|
||||
}
|
||||
|
||||
/// Un-favourite an item: the same `/Users/{uid}/FavoriteItems/{id}` resource
|
||||
/// as [`Self::mark_favorite`], removed rather than posted. Written out by
|
||||
/// hand rather than through `post_json` because it is the one favourite call
|
||||
/// that needs `DELETE`.
|
||||
///
|
||||
/// TRACES: UR-017 | JA-018, DR-021
|
||||
async fn unmark_favorite(&self, item_id: &str) -> Result<(), RepoError> {
|
||||
let endpoint = format!("/Users/{}/FavoriteItems/{}", self.user_id, item_id);
|
||||
let url = format!("{}{}", self.server_url, endpoint);
|
||||
@@ -2316,12 +2364,22 @@ impl MediaRepository for OnlineRepository {
|
||||
result
|
||||
}
|
||||
|
||||
/// A single Person item (actor, director, …) by id.
|
||||
///
|
||||
/// Jellyfin models people as ordinary items, so this is the plain item
|
||||
/// endpoint rather than anything under `/Persons`; the cast entries returned
|
||||
/// on an item's `People` field carry the ids this is called with.
|
||||
///
|
||||
/// TRACES: UR-035, UR-036 | IR-022, JA-030
|
||||
async fn get_person(&self, person_id: &str) -> Result<MediaItem, RepoError> {
|
||||
let endpoint = format!("/Users/{}/Items/{}", self.user_id, person_id);
|
||||
let item: JellyfinItem = self.get_json(&endpoint).await?;
|
||||
Ok(item.to_media_item(self.user_id.clone()))
|
||||
Ok(item.into_media_item(self.user_id.clone()))
|
||||
}
|
||||
|
||||
/// A person's filmography — every item they are credited on.
|
||||
///
|
||||
/// TRACES: UR-036 | IR-022, JA-031
|
||||
async fn get_items_by_person(
|
||||
&self,
|
||||
person_id: &str,
|
||||
@@ -2349,7 +2407,7 @@ impl MediaRepository for OnlineRepository {
|
||||
items: response
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| item.to_media_item(self.user_id.clone()))
|
||||
.map(|item| item.into_media_item(self.user_id.clone()))
|
||||
.collect(),
|
||||
total_record_count: response.total_record_count,
|
||||
})
|
||||
@@ -2373,7 +2431,7 @@ impl MediaRepository for OnlineRepository {
|
||||
items: response
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| item.to_media_item(self.user_id.clone()))
|
||||
.map(|item| item.into_media_item(self.user_id.clone()))
|
||||
.collect(),
|
||||
total_record_count: response.total_record_count,
|
||||
})
|
||||
@@ -2461,7 +2519,7 @@ impl MediaRepository for OnlineRepository {
|
||||
.into_iter()
|
||||
.map(|pi| PlaylistEntry {
|
||||
playlist_item_id: pi.playlist_item_id,
|
||||
item: pi.item.to_media_item(self.user_id.clone()),
|
||||
item: pi.item.into_media_item(self.user_id.clone()),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -2959,7 +3017,7 @@ mod tests {
|
||||
}))
|
||||
.expect("fixture must deserialize");
|
||||
|
||||
let streams = item.to_media_item("server-1".to_string()).media_streams;
|
||||
let streams = item.into_media_item("server-1".to_string()).media_streams;
|
||||
let streams = streams.expect("the item carries streams");
|
||||
let deliverable = |index: i32| {
|
||||
streams
|
||||
@@ -3554,7 +3612,7 @@ mod tests {
|
||||
}"#;
|
||||
|
||||
let item: JellyfinItem = serde_json::from_str(json).expect("item should deserialize");
|
||||
let media = item.to_media_item("server1".to_string());
|
||||
let media = item.into_media_item("server1".to_string());
|
||||
|
||||
let user_data = media.user_data.expect("user data should be mapped");
|
||||
assert_eq!(user_data.is_favorite, Some(true));
|
||||
@@ -3574,7 +3632,7 @@ mod tests {
|
||||
let json = r#"{"Id": "x", "Name": "No User Data", "Type": "Movie"}"#;
|
||||
|
||||
let item: JellyfinItem = serde_json::from_str(json).expect("item should deserialize");
|
||||
let media = item.to_media_item("server1".to_string());
|
||||
let media = item.into_media_item("server1".to_string());
|
||||
|
||||
assert!(media.user_data.is_none());
|
||||
}
|
||||
@@ -3618,7 +3676,7 @@ mod tests {
|
||||
}"#;
|
||||
|
||||
let jellyfin_item: JellyfinItem = serde_json::from_str(json).expect("Failed to parse");
|
||||
let media_item = jellyfin_item.to_media_item("test-server-id".to_string());
|
||||
let media_item = jellyfin_item.into_media_item("test-server-id".to_string());
|
||||
|
||||
assert_eq!(media_item.id, "album456");
|
||||
assert_eq!(media_item.name, "Love and Theft");
|
||||
|
||||
@@ -155,6 +155,10 @@ impl ThumbnailCache {
|
||||
}
|
||||
|
||||
/// Save thumbnail to cache
|
||||
// The arguments are the cache key (item/type/tag) plus the payload and its
|
||||
// dimensions — all independent scalars borrowed from the caller. A parameter
|
||||
// struct would only move the same list one level down.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn save_thumbnail(
|
||||
&self,
|
||||
db: Arc<RusqliteService>,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "jellytau",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.0",
|
||||
"identifier": "com.dtourolle.jellytau",
|
||||
"build": {
|
||||
"beforeDevCommand": "bun run dev",
|
||||
@@ -18,10 +18,11 @@
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null,
|
||||
"csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data: blob: asset: http://asset.localhost http: https:; media-src 'self' blob: asset: http://asset.localhost http://127.0.0.1:* http: https:; connect-src 'self' ipc: http://ipc.localhost http: https:; worker-src 'self' blob:; object-src 'none'; frame-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'",
|
||||
"devCsp": "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data: blob: asset: http://asset.localhost http: https:; media-src 'self' blob: asset: http://asset.localhost http://127.0.0.1:* http: https:; connect-src 'self' ipc: http://ipc.localhost http: https: ws: wss:; worker-src 'self' blob:; object-src 'none'; frame-src 'none'; base-uri 'self'; form-action 'self'",
|
||||
"assetProtocol": {
|
||||
"enable": true,
|
||||
"scope": ["$APPDATA/**"]
|
||||
"scope": ["$APPDATA/thumbnails/**"]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
+35
-2
@@ -118,16 +118,41 @@ async playerSetVolume(volume: number) : Promise<PlayerStatus> {
|
||||
async playerToggleMute() : Promise<PlayerStatus> {
|
||||
return await TAURI_INVOKE("player_toggle_mute");
|
||||
},
|
||||
/**
|
||||
* Set the active audio track on a native backend directly.
|
||||
*
|
||||
* TRACES: UR-021 | IR-019, DR-024
|
||||
*/
|
||||
async playerSetAudioTrack(streamIndex: number) : Promise<PlayerStatus> {
|
||||
return await TAURI_INVOKE("player_set_audio_track", { streamIndex });
|
||||
},
|
||||
/**
|
||||
* Switch audio track - handles both HTML5 (stream reload) and native (direct switch)
|
||||
* Note: Frontend should handle saving series preferences after this command succeeds
|
||||
*
|
||||
* The split is the requirement: an HTML5 `<video>` element cannot be told to
|
||||
* change audio track, so the stream is re-opened at the chosen
|
||||
* `AudioStreamIndex` and the frontend seeks the reloaded element back to
|
||||
* `position`; a native backend (ExoPlayer) switches in place by track-group
|
||||
* index. libmpv implements neither — it is the audio-only backend here and
|
||||
* leaves `PlayerBackend::set_audio_track` at its `not_implemented()` default,
|
||||
* which is why IR-019 is met by these two paths rather than by MPV.
|
||||
*
|
||||
* TRACES: UR-021 | IR-019, DR-024
|
||||
*/
|
||||
async playerSwitchAudioTrack(repositoryHandle: string, streamIndex: number, arrayIndex: number, useHtml5: boolean, currentPosition: number | null, mediaSourceId: string | null) : Promise<AudioTrackSwitchResponse> {
|
||||
return await TAURI_INVOKE("player_switch_audio_track", { repositoryHandle, streamIndex, arrayIndex, useHtml5, currentPosition, mediaSourceId });
|
||||
},
|
||||
/**
|
||||
* Set (or clear, with `None`) the active subtitle track on a native backend.
|
||||
*
|
||||
* On Android this indexes ExoPlayer's *text track groups* — i.e. the position
|
||||
* of the sideloaded `MediaItem.SubtitleConfiguration`, not the Jellyfin stream
|
||||
* index. The HTML5 path never reaches here; it toggles its own `<track>`
|
||||
* children. libmpv implements neither, leaving the trait default in place.
|
||||
*
|
||||
* TRACES: UR-020 | IR-018, DR-023
|
||||
*/
|
||||
async playerSetSubtitleTrack(streamIndex: number | null) : Promise<PlayerStatus> {
|
||||
return await TAURI_INVOKE("player_set_subtitle_track", { streamIndex });
|
||||
},
|
||||
@@ -1421,13 +1446,21 @@ async repositoryGetLatestItems(handle: string, parentId: string, limit: number |
|
||||
return await TAURI_INVOKE("repository_get_latest_items", { handle, parentId, limit });
|
||||
},
|
||||
/**
|
||||
* Get resume items (continue watching/listening)
|
||||
* Get resume items (continue watching/listening).
|
||||
*
|
||||
* The home screen's Continue Watching row and every library's "pick up where
|
||||
* you left off" hero come through here; each item carries its own resume
|
||||
* position in `UserData`.
|
||||
*
|
||||
* TRACES: UR-019, UR-023, UR-034 | IR-024, JA-013, JA-015 | DR-026, DR-038
|
||||
*/
|
||||
async repositoryGetResumeItems(handle: string, parentId: string | null, limit: number | null) : Promise<MediaItem[]> {
|
||||
return await TAURI_INVOKE("repository_get_resume_items", { handle, parentId, limit });
|
||||
},
|
||||
/**
|
||||
* Get next up episodes
|
||||
* Get next up episodes.
|
||||
*
|
||||
* TRACES: UR-023, UR-034 | IR-024, JA-014 | DR-026
|
||||
*/
|
||||
async repositoryGetNextUpEpisodes(handle: string, seriesId: string | null, limit: number | null) : Promise<MediaItem[]> {
|
||||
return await TAURI_INVOKE("repository_get_next_up_episodes", { handle, seriesId, limit });
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<!-- TRACES: UR-029, UR-051 | DR-069, DR-070 -->
|
||||
<!-- TRACES: UR-029, UR-037, UR-051 | DR-042, DR-069, DR-070 -->
|
||||
<script lang="ts">
|
||||
import type { MediaItem, Library } from "$lib/api/types";
|
||||
import MediaCard from "./MediaCard.svelte";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<!-- TRACES: UR-051, UR-052, UR-068 | DR-068, DR-078, DR-119 -->
|
||||
<!-- TRACES: UR-037, UR-051, UR-052, UR-068 | DR-042, DR-068, DR-078, DR-119 -->
|
||||
<script lang="ts">
|
||||
import type { MediaItem, Library } from "$lib/api/types";
|
||||
import { truncateMiddle } from "$lib/utils/truncateMiddle";
|
||||
|
||||
@@ -276,7 +276,15 @@
|
||||
});
|
||||
|
||||
|
||||
// Get available audio tracks from media streams
|
||||
// The audio tracks available for this item, as the server described them.
|
||||
//
|
||||
// Jellyfin has no separate "audio tracks" endpoint: the tracks arrive on the
|
||||
// item itself, in `MediaStreams`, which the backend asks for by name in
|
||||
// `get_item`'s `Fields=` list and tags with an opaque `kind`. Selecting by
|
||||
// that tag rather than by Jellyfin's `Type` string keeps the taxonomy on the
|
||||
// Rust side of the boundary.
|
||||
//
|
||||
// TRACES: UR-021 | IR-016, JA-009 | DR-024
|
||||
const audioTracks = $derived(() => {
|
||||
if (!media || !media.mediaStreams) {
|
||||
console.log("[VideoPlayer] No media or mediaStreams available");
|
||||
|
||||
@@ -41,7 +41,10 @@ export async function getCachedImageUrl(
|
||||
const cachedPath = await commands.thumbnailGetCached(itemId, imageType, tag);
|
||||
|
||||
if (cachedPath) {
|
||||
// Convert file path to asset URL for Tauri
|
||||
// Convert file path to asset URL for Tauri. This is the only remaining
|
||||
// convertFileSrc caller, which is why the asset-protocol scope is narrowed
|
||||
// to $APPDATA/thumbnails/** — a path outside it resolves to nothing.
|
||||
// TRACES: UR-012 | DR-134, DR-198
|
||||
return convertFileSrc(cachedPath);
|
||||
}
|
||||
} catch (e) {
|
||||
|
||||
@@ -23,6 +23,13 @@ const h = vi.hoisted(() => {
|
||||
fn(value);
|
||||
return () => subs.delete(fn);
|
||||
},
|
||||
// Drop subscribers left behind by module instances discarded via
|
||||
// `vi.resetModules()`. Without this, every previously-imported copy of the
|
||||
// service still reacts to `set()` and pushes its own visibility value.
|
||||
reset(v: T) {
|
||||
subs.clear();
|
||||
value = v;
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
@@ -31,6 +38,21 @@ const h = vi.hoisted(() => {
|
||||
};
|
||||
});
|
||||
|
||||
// Prime the module graph once, at collection time, instead of inside a test.
|
||||
//
|
||||
// Every test re-imports the service after `vi.resetModules()` so it gets a fresh
|
||||
// set of module-level subscriptions. The *first* of those imports also pays to
|
||||
// transform the service and its dependency graph — around a second of real
|
||||
// wall-clock work with a cold Vite cache. Charged to a test body that cost sat
|
||||
// close enough to vitest's 5s default that suite-wide contention (many workers
|
||||
// transforming at once) tipped this file into a timeout, while running the file
|
||||
// alone always passed. Warming here moves the compile out of the timed region;
|
||||
// the per-test re-imports that follow are cached and cost ~30ms.
|
||||
//
|
||||
// The timeout is deliberately left at the default: the point is to stop timing
|
||||
// the compiler, not to give it a bigger budget.
|
||||
await import("./offlineCatalog");
|
||||
|
||||
vi.mock("$lib/stores/connectivity", () => ({
|
||||
isConnected: { subscribe: h.isConnectedStore.subscribe },
|
||||
}));
|
||||
@@ -50,8 +72,8 @@ vi.mock("$lib/stores/auth", () => ({
|
||||
|
||||
describe("pushCatalogVisibility resolves reachable || showCatalog (UT-068)", () => {
|
||||
beforeEach(() => {
|
||||
h.isConnectedStore.reset(true);
|
||||
h.setShowServerCatalog.mockClear();
|
||||
h.isConnectedStore.set(true);
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
`/library/movies/genres`). They are now `?view=browse|all|genres` here; the
|
||||
old routes redirect.
|
||||
|
||||
TRACES: UR-007, UR-023, UR-034, UR-063 | DR-007, DR-038, DR-039, DR-105
|
||||
TRACES: UR-007, UR-023, UR-034, UR-037, UR-063 | DR-007, DR-038, DR-039, DR-042, DR-105
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
the last of which did not even share a prefix with the others). They are now
|
||||
`?view=browse|all|genres` here; the old routes redirect.
|
||||
|
||||
TRACES: UR-007, UR-023, UR-034, UR-063 | DR-007, DR-038, DR-039, DR-103, DR-105
|
||||
TRACES: UR-007, UR-023, UR-034, UR-037, UR-063 | DR-007, DR-038, DR-039, DR-042, DR-103, DR-105
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
|
||||
Reference in New Issue
Block a user