Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
docs: audit of 2 November 2026 — device baseline, what this branch fixed, and 149 findings (21 confirmed, 8 refuted, 120 still to verify)
kota-zo658fac2151a8
diff --git a/docs/audit-2026-11-02.md b/docs/audit-2026-11-02.mdnew file mode 100644index 00000000..ca75aa09--- /dev/null+++ b/docs/audit-2026-11-02.md@@ -0,0 +1,892 @@+# Audit Myspoti — chargement, lecture, interface, extensions, build (2 novembre 2026)++Base : `main` à `8e8898af` (2.3.0), branche `audit/deep-2026-11`. Téléphone : Galaxy S24 (SM-S921B, Android API 37), build debug `app.myspoti.dev`.++Méthode : 11 auditeurs en lecture seule (démarrage, lecture, réseau/cache, Compose Immersive, Compose classique, UI/UX, concurrence/mémoire, extensions, build/taille, outils/docs, imports open source), puis contre-vérification adverse. La vérification a été arrêtée en cours pour économiser le quota : **21 constats confirmés, 8 réfutés, 120 à vérifier** avant toute correction. Une ligne « à vérifier » est l'avis d'un seul auditeur, pas un fait établi.++## 1. Mesures de référence sur le téléphone++- Démarrage à froid (logcat `Displayed`, debug) : ~1,37 s ; `Choreographer: Skipped 96 frames` (~800 ms de thread principal bloqué) au démarrage. `am start -W` ne rend jamais `TotalTime` (LaunchState UNKNOWN).+- Démarrage à froid → la CLI dit `signedIn` (horloge de l'hôte) : 1,77 à 1,81 s.+- Moteur Spotify (`tools/tap_latency.py`, n=5) : tap sur un titre médiane **1 625 ms** (882–2 647) ; suivant 609 ms ; précédent 391 ms ; reprise 112 ms.+- Chemin extension (Tidal, lecteur local), `next` → nouveau titre joué (hôte, polling CLI compris) : médiane ~1,9 s. Vu une fois : l'extension `lossless` a mis **11,9 s** à rendre un flux (timeout Deezer), la lecture a attendu tout ce temps.+- Écran lecteur 12 s (`qa.py --perf`, debug) : 183 images, 16 en retard ; CPU app 130 %, rendu 104 %.+- `playback_test.py` (extensions coupées, autres builds Myspoti arrêtées) : 18/19.++## 2. Corrigé dans cette branche++- **Pub audible après un choix de titre** (scénario `ad_pick`, audible 2 fois sur 2 avant, 0 sur 4 passes après ; `ad_taps`, `ad_previous`, `ad_pick` : 16/16). `media.mute` baissait le volume une seule fois ; la page le remontait (nouveau titre, sa montée de volume, un volume Spotify Connect) et la pub s'entendait jusqu'au passage suivant, ~2 s plus tard. Un garde sur `volumechange`/`playing` tient chaque élément silencieux tant que la pub est coupée ou la page « hushed », posé dès le premier `play()` par le hook de début de document (`ControlRelay.kt`) et repris par le pont (`player-bridge.js`), qui remplace l'ancien garde propre à `media.hush`.+- **`playback_test.py` lit le log de la seule app testée** (`logcat --uid`) : une autre build Myspoti installée (`app.myspoti.automix2`, page gelée en arrière-plan) écrit sous les mêmes tags et faisait échouer 14 scénarios sur 19 avec ses propres timeouts.+- **`myspoti-cli`** trouve l'adb du SDK (`~/android-sdk/platform-tools/adb`) quand aucun n'est dans le PATH, comme `cdp.py`.++## 3. Constats++Triés par état puis par gravité. Chemins relatifs à la racine du dépôt.++### Confirmé (21)++- **[medium] The WebView and the whole engine are built synchronously in Application.onCreate, before the first frame** — `base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt:153` (cold-start, effort L)+ - Impact : Every cold start's time to first frame includes Chromium init and the rest of the engine set-up. The user sees the splash longer, and on low-end devices this is likely the biggest single item before the first frame. Background starts (Android Auto, a media button) pay it too, but there it is wanted.+ - Correction : Measure first, then make the WebView lazy while keeping the host object eager.++0) Measure. Wrap each step of Graph.init and MyspotiRuntime.start in androidx.tracing `trace("...")` sections. Record a Perfetto trace of a cold start (the manifest is already profileable) and run `am start -S -W` 10 times. Go on only if the WebPlayerHost/createView slice (WebViewChromiumAwInit.startChromium) is large, more than about 80 ms on the reference phone.++1) base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt+- Replace `var view: WebView = createView()` (l.153) with a private nullable backing field `_view`, plus a main-thread getter `val view: WebView get() = _view ?: createView().also { _view = it }`.+- The renderer-crash rebuild() path assigns `_view` directly.+- Any early access then builds the view on demand instead of crashing. `relay` (lateinit, set in createView) is only read after the view exists. Check that `media`'s lambda `relay.identityPair()` and resetConnections() never run before that.+- attach(container, visible): when `_view == null`, store the container and the visible flag and return. ensureView() then adds the view to the stored container once it exists, using the same code path as today.+- Add `fun ensureView()`, which posts on main, builds the view, and re-attaches it to the stored container if there is one.++2) base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt+- Keep start() eager for host, spotify, the flows and the status loop, but remove `host.load()` and the ops refresh from it.+- Add `fun ensureEngine()`. It is idempotent and guarded by a flag. It calls host.ensureView() and, unless data saver is on, host.load() and the updater.refresh launch.+- resume() (data saver) calls ensureEngine().+- Make sure the status loop and isSignedIn() never touch `host.view`; they only read flows.++3) Callers of ensureEngine()+- MainActivity.onCreate (base/app/src/main/java/app/myspoti/MainActivity.kt, after setContentView l.182): `window.decorView.doOnPreDraw { it.post { MyspotiRuntime.ensureEngine() } }`. Do not use a plain Handler.post from Application.onCreate, which runs before the first traversal.+- PlaybackService.onCreate/onGetRoot and the media-button and widget entry points call it right away. This keeps A27, Android Auto from a cold start.+- Leave the GrapheneOS watchLoad watchdog and the attach() retry as they are.++4) Optional: on WebViews that support it, call androidx.webkit `WebViewCompat.startUpWebView(WebViewStartUpConfig.Builder(executor).build(), callback)` (webkit 1.13.0, already in libs.versions.toml) from Application.onCreate, and create the view in its callback. That moves Chromium's start-up off the main thread, so moving it after the first frame does not just turn into a freeze on the first screen. Fall back to step 3 otherwise.++5) With data saver active, no WebView is created until resume().++Gate: tools/playback_test.py, a cold start from Android Auto (A27), a cold start from a media button, the sign-in flow from a fresh install (attach with visible=true before the view exists), and data saver on then off. Compare the TotalTime and time-to-ready medians before and after. Ship only if time-to-ready does not get worse.+- **[medium] Player and sheets open on the stock purple palette and fade for 1.4 s every time: cover colours are never cached and Palette runs on the main thread** — `base/app/src/main/java/com/music/spotui/ui/look/MeshGradient.kt:247` (compose-immersive, effort S)+ - Impact : Visible on every player open, not just song changes: the backdrop starts purple and pink and morphs to the cover colours over 1.4 s, and the pale tint of the credits, glyphs and handle shifts over 0.6 s. Every song-options or quality sheet opened on a cover also warms in from a purple-derived tint. On every song change while the player is up, and on every sheet open, the main thread spends a few milliseconds per Palette run (scaling plus quantization, up to two passes) right during the cover crossfade or the sheet's opening animation. That is a likely dropped frame on mid-range phones.+ - Correction : The main change is in base/app/src/main/java/com/music/spotui/ui/look/MeshGradient.kt.++1. Add a process-wide cache next to FallbackColors, mirroring di/Palette.kt:+`private val meshCache = android.util.LruCache<String, MeshPalette>(100)`+Add `@Volatile private var lastMesh: MeshPalette? = null`, the last palette computed, used to seed a cover that is not cached yet.++2. Change rememberArtworkColors:+- Start the state from the cache: `var palette by remember { mutableStateOf(imageUrl?.let { meshCache[it] } ?: lastMesh ?: MeshPalette(FallbackColors)) }`.+- Keep `remember` un-keyed, so a song change still goes straight from the old palette to the new one, as the existing comment wants.+- In `DisposableEffect(imageUrl)`, first check `meshCache[imageUrl]?.let { palette = it; return@DisposableEffect onDispose {} }` and skip the Glide load entirely.+- When imageUrl is null, keep today's fallback reset.++3. Move the quantisation off the main thread.+- In loadArtwork's onResourceReady, copy the 128 px bitmap: `val copy = resource.copy(Bitmap.Config.ARGB_8888, false)` (about 64 KB). The copy is needed because onDispose → Glide.clear() can return the original bitmap to Glide's BitmapPool while the work is still running.+- Run `artworkMeshColors(copy)` on a background thread, for example a coroutine on Dispatchers.Default launched from the effect's scope, or replace the DisposableEffect with a LaunchedEffect that suspends on the Glide callback through suspendCancellableCoroutine.+- Back on the main thread: `meshCache.put(url, result); lastMesh = result; palette = result`. Ignore the result if the effect has already been disposed or re-keyed.++4. Optional warm-up, so even the first open of a new song is right:+- Add `fun warmArtworkColors(context: Context, url: String)` in MeshGradient.kt, doing the same load-and-compute and filling meshCache.+- Call it from base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt, where the current and next song's cover colours are already prefetched (lines ~196-200 and ~238-239), when the Immersive look is active. It shares the same COVER_DECODE_PX decode, so Glide reuses the bitmap.++5. No change is needed to the animation specs in ImmersivePlayer.kt, ImmersiveSheet.kt or MeshGradientBackground. With a cached initial value, animateColorAsState starts at the right colour and does not animate. A first-seen cover keeps its intended warm-in fade.++6. Optional, low priority: in base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSheet.kt, LocalImmersiveSheetTint could carry State-backed colours, or the rows could read `.accent` in draw lambdas, so rows do not recompose during the 400 ms first-seen fade.++To verify: with the Immersive look, open, close and reopen the player on the same song. The backdrop should appear in the cover colours from the first frame, with no purple/pink morph. Song-options sheets on a known cover should also open already tinted.+- **[medium] Song-row "playing" bars recompose and re-measure every frame while music plays, including under the full-screen player** — `base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveCover.kt:158` (compose-immersive, effort S)+ - Impact : As long as music plays and the playing song's row or card is on any page (playlist, album, Library, artist, Home shelves), the app recomposes and re-lays out at full display rate (60 to 120 Hz) forever. That continuous frame loop also keeps the RenderThread busy and prevents LTPO panels from lowering the refresh rate, which costs battery for the whole listening session.+ - Correction : Change only base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveCover.kt (ImmersivePlayingBars). Callers keep their signatures.+1. Drop rememberInfiniteTransition/animateFloat. Use the project's own throttled, lifecycle-aware clock instead: `val running = !reduceMotion && !com.music.spotui.ui.navigation.PlayerSheet.open.value; val clock = com.music.spotui.ui.components.rememberFrameClock(running, fps = 30)`. The 30 fps rate is further capped by EnergySettings.progressFps, and the clock already stops when the app is not STARTED.+2. Draw the bars in the draw phase only. Use `Box(modifier.size(24.dp).clip(RoundedCornerShape(6.dp)).background(Color.Black.copy(alpha = 0.52f)).drawWithCache { onDrawBehind { ... } })` or a Canvas. Read `clock.value` only inside the draw lambda. For each index i (minimum = 0.38f/0.78f/0.52f, period = 520 + i*130 ms, peak 1f at 260 + i*50 ms), compute the height from `clock.value / 1_000_000`. Copy the keyframes as a piecewise-linear function with Reverse repeat (fold the time into [0, period], mirroring every other period). When `!running`, use `minimum`, the resting height already used under reduce motion. Draw `drawRoundRect(Color.White, topLeft = Offset(x_i, bottom - 14.dp.toPx()*h), size = Size(3.dp.toPx(), 14.dp.toPx()*h), cornerRadius = CornerRadius(2.dp.toPx()))`, with the three bars centered (3dp wide, 2dp gap, 14dp tall zone, bottom-aligned as now).+Result: no recomposition or relayout per frame. About 30 frames per second or fewer while visible, under the energy policy. No frames requested by the bars while the full player covers the page or the app is in the background.+To check: Layout Inspector should show the recomposition count of ImmersivePlayingBars staying flat. With the full player open on a playing playlist, `dumpsys gfxinfo` framestats should show only the player's 15 fps ticks.+- **[medium] Downloads page re-sorts every downloaded track and recomposes every visible row 2.5 times a second while a download runs** — `base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveDownloadsScreen.kt:79` (compose-immersive, effort S)+ - Impact : While downloads run (a playlist or album batch can queue hundreds), the Downloads page does a full sort of all downloads plus a recomposition of every visible row 2.5 times a second per concurrent download. Scrolling the page during a batch download competes with this work, and battery use goes up for as long as the page is open.+ - Correction : File: base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveDownloadsScreen.kt+1. Line 79: `val tracks by remember { derivedStateOf { OfflineStore.tracks.values.sortedByDescending { it.addedAt } } }`. This reads only the `tracks` map.+2. Line 80: `val waiting by remember { derivedStateOf { OfflineDownloader.requests.values.filter { !OfflineStore.isDownloaded(it.trackId) } } }`.+3. Lines 82-85: `val stoppable by remember { derivedStateOf { waiting.count { val s = OfflineStore.status[it.trackId]; s == OfflineStatus.Queued || s is OfflineStatus.Downloading } } }`. The derived state still re-evaluates on each status write, but it only invalidates the screen when the Int changes. Alternatively, derive a Boolean `hasStoppable`.+4. Line 92: `val shown = remember(tracks, find) { if (find.isBlank()) tracks else tracks.filter { matchesFind(find, it.title, it.artist, it.album) } }`.+5. In the `itemsIndexed(shown)` block:+ - `val song = remember(t) { OfflineStore.toSong(t) }`. This stops the per-tick `File.isFile` stat.+ - Make the row click independent of the list instance: `val currentTracks by rememberUpdatedState(tracks)` at screen level, then `onClick = { play(currentTracks.indexOf(t).coerceAtLeast(0)) }`. Or compute the index at tap time from `OfflineStore.tracks`.+ - `play()` should also read `currentTracks`.+6. Keep reading `OfflineStore.status[r.trackId]` only inside the `items(waiting)` rows, as at line 183. Those rows legitimately update.++Optional, in base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt `fetchWithProgress`: skip `setStatus` when the progress has not moved by at least 0.01 since the last write. This cuts the writes for stalled or slow downloads.++How to verify: open Layout Inspector during an album download. Downloaded ImmersiveSongRow rows should show 0 recompositions per second, and the screen scope should recompose only when a track finishes or the stoppable count changes.+- **[medium] Every pick from a shuffled or sorted list redacts and serialises the full play order on the main thread before sending** — `base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt:187` (playback, effort S)+ - Impact : Several ms to tens of ms of main-thread regex work and allocation on the critical path of every pick from a large shuffled or sorted list, plus a second large string build.+ - Correction : Change one file, `base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt`, in `call()`. Optionally add a defensive cap in `LogMask.kt`.++1) In `Bridge.call()`, serialise the args once with `val argsText = args.toString()` and put `$argsText` in the script instead of `$args`. The page must still receive the full order, unchanged.++2) For the log line at line 187, log a summary of the args instead of the raw object. Add a private helper in `Bridge.kt`:+```kotlin+private fun loggable(args: JsonObject): String {+ val big = args.filterValues { it is JsonArray && it.size > 3 }+ if (big.isEmpty()) return args.toString()+ return JsonObject(args.mapValues { (k, v) -> if (k in big) JsonPrimitive("[${(v as JsonArray).size} items]") else v }).toString()+}+```+Then write: `if (!quiet) logger?.invoke("call #$id $method${label?.let { " ($it)" }.orEmpty()} ${LogMask.shown(loggable(args))}")`.++Use the same helper in the quiet FAILED line (line 216): `LogMask.shown(loggable(args), 100)`. Redaction still runs on everything that is logged, so no secret leaks. The log keeps `contextUri`, `trackUri`, `index` and `positionMs`, which are what bug reports read, and now shows `"order":"[2000 items]"`. The rule is generic: any JSON array longer than 3 entries is summarised, with no special case for `player.play`. This also covers `queue.reorder` and `service.call` args lists.++3) Optional, defensive, in `base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/LogMask.kt`. In `shown()`, redact only a bounded head when the text is very large:+```kotlin+val head = if (text.length > 16_384) text.take(16_384) else text+val clean = redact(head)+val total = clean.length + (text.length - head.length)+```+Then cut to `max` and report `+(total - max)`. A secret cut at the 16 KB boundary could only reach the 200 visible characters if earlier redactions removed about 16 KB of text, so this is safe. It also bounds the other large callers, such as page messages and big results on the "ok" line.++4) Tests:+- Extend `base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/LogMaskTest.kt` for the cap if step 3 is done.+- Add a Bridge test with the existing fake host used by `SpotifyPlayerCharacterizationTest`/`PickDuringAdTest`: a `player.play` with a 2,000-entry order logs `"[2000 items]"`, and the evaluated script still contains all 2,000 uris.++Measure by comparing the Logbook gap between the user tap (SongPlayer "playing … in …") and "call #N player.play" on a shuffled Liked Songs pick, before and after the change.+- **[low] No app baseline profile and no startup measurement (reportFullyDrawn, trace sections, startup script)** — `base/app/build.gradle.kts:164` (cold-start, effort M)+ - Impact : The first cold starts after each install or update (frequent with betas) are slower and the first home scroll and player open jank more. For Compose apps, Google reports roughly 20-40 % faster startup with a baseline profile. The gains of the other findings also cannot be measured or protected without a startup metric.+ - Correction : 1) New Gradle module base/baselineprofile (com.android.test plus the androidx.baselineprofile plugin, version matching the AGP; deps androidx.benchmark:benchmark-macro-junit4, androidx.test.ext:junit, androidx.test.uiautomator). Add `include(":baselineprofile")` to base/settings.gradle.kts, with targetProjectPath = ":app" and `useConnectedDevices = true` (generation needs the owner's signed-in phone on API 33+, so do not use managed devices or CI).+2) In base/app/build.gradle.kts: add `id("androidx.baselineprofile")` to plugins and `baselineProfile(project(":baselineprofile"))` to dependencies. Add `baselineProfile { saveInSrc = true; automaticGenerationDuringBuild = false; dexLayoutOptimization = true }` so that CI builds use the checked-in src/release/generated/baselineProfiles/baseline-prof.txt and never need a device. Keep profileinstaller 1.4.1, which already installs the profile on sideloaded installs.+3) In baselineprofile/src/main/.../BaselineProfileGenerator.kt, use BaselineProfileRule.collect(packageName = "app.myspoti", includeInStartupProfile = true). The journey: pressHome; startActivityAndWait; wait for the Home feed; fling Home; open Library; open and close the now-playing screen. Do this for the classic look (ui/screens) and the immersive look (ui/immersive). If it is easier to drive, switch looks through the settings UI. Add a StartupBenchmark with CompilationMode.None() vs Partial(BaselineProfileMode.Require) that reports timeToInitialDisplayMs and timeToFullDisplayMs.+4) Fully-drawn signal: in base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt (near line 114, `val feed = (home as? Response.Success)?.data`) and in .../ui/immersive/screens/ImmersiveHomeScreen.kt (near line 95), add `ReportDrawnWhen { home is Response.Success }` from androidx.activity.compose, which is already transitive through activity-compose. Optionally wrap the body of Graph.init(this) and SongPlayer.attachEngine in base/app/src/main/java/app/myspoti/MyspotiApplication.kt (lines 19-26) with `androidx.tracing.trace("Graph.init") { ... }` so Perfetto shows them. This needs androidx.tracing:tracing-ktx, which is already transitive through compose.+5) Add tools/startup_time.py, in the style of tap_latency.py. For N runs: `adb shell am force-stop <pkg>`, then `adb shell am start -S -W -n <pkg>/<MainActivity>`, parse TotalTime, and read `Fully drawn <pkg>/...: +Xms` from `logcat -d -s ActivityTaskManager`. Print the median and p90. Optionally run `adb shell cmd package compile -m verify -f <pkg>` first to measure the worst case.+Expected gain: modest. It affects the first cold starts and first scrolls after each install or update, until background dexopt. Measure before claiming numbers.+- **[low] Lyric rows read their animated blur, glow, colour, brightness and gap height during composition: 5 to 7 rows recompose on every frame of each line change** — `base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricsPanel.kt:744` (compose-immersive, effort M)+ - Impact : On every line change (every 2 to 5 s for the whole song), several rows recompose on every frame for 200 to 420 ms. Each recomposition rebuilds the row's full modifier chain (blur layer with a new RenderEffect, clip, drawWithCache, secondaryClick, lastPress, combinedClickable) and re-enters PanelVoice and SweptLyricLine. The gap row also re-measures the LazyColumn on every frame. This lands at the same moment as the list's own animateScrollBy and the staggered translationY, which is the busiest frame window of the most-watched Immersive screen. Expect missed frames on mid-range phones, especially at 120 Hz.+ - Correction : Change only base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricsPanel.kt (and optionally base/app/src/main/java/com/music/spotui/ui/look/SweptLyricLine.kt for glow).++1. Blur in PanelRow (the biggest win, about 6 rows per line change):+ - Change `val blur by animateDpAsState(...)` to `val blur = animateDpAsState(...)`, keeping the State.+ - Replace `.blur(blur, BlurredEdgeTreatment.Unbounded)` at line 744 with:+ `.graphicsLayer { val r = blur.value.toPx(); renderEffect = if (r > 0f) BlurEffect(r, r, TileMode.Decal) else null; clip = false }`+ This is what Modifier.blur with Unbounded does: no shape, clip=false, Decal.+ - Keep it as its own graphicsLayer after the scale/alpha/translation layer so the layer order is unchanged.+ - Do NOT cache or quantize the BlurEffect: the radius has to follow the tween.++2. GapRow:+ - Change its parameters to `blur: State<Dp>` and `lineAlpha: () -> Float`. PanelRow passes `blur` and `{ lineAlpha }`, keeping `lineAlpha` as the existing delegate.+ - Apply the same graphicsLayer blur at line 1139.+ - Read `lineAlpha()` and `swell` only inside the existing graphicsLayer: keep `swell` as a State and use `swell.value`.+ - Replace `.height((GAP_ROW_HEIGHT + GAP_ROW_SPACING) * swell)` with `.layout { m, c -> val h = ((GAP_ROW_HEIGHT + GAP_ROW_SPACING).toPx() * swell.value).roundToInt(); val p = m.measure(c.copy(minHeight = 0, maxHeight = Constraints.Infinity)); layout(p.width, h) { p.place(0, 0) } }`. Keep `.clipToBounds()`. This saves recomposition only; the LazyColumn still re-measures each frame, which is inherent.++3. Glow (optional, 2 rows per line change):+ - Keep `glow` as a State in PanelRow.+ - Change PanelVoice's and SweptLyricLine's `glowAlpha: Float` to `glowAlpha: () -> Float`, with default `{ 0f }` in SweptLyricLine and `if (browsing) { { 0f } } else glow::value` in PanelVoice.+ - In SweptLyricLine, read it inside the existing `.graphicsLayer { alpha = glowAlpha() }`. Gate the glow Text's presence on a boolean `glowing = isActive && glowing && !browsing` instead of `glowAlpha > 0.01f`, so composition does not read the animated value. The layer at alpha≈0 costs nothing visible during the 420 ms fade-out; or keep the Text until the animation settles by also checking `glowState.isRunning`.+ - Check the other SweptLyricLine callers (LookPreview, the one-line strip) and update them.++4. Colour, lit and tail: leave them unless profiling shows a need. Moving them to draw requires BasicText with a ColorProducer (inside SweptLyricLine too). That is more churn for 2 rows of draw-only Text updates.++Measure with Layout Inspector recomposition counts on PanelRow, GapRow and PanelVoice during playback with the lyrics open, and with tools/qa.py gfxinfo before and after. Expect fewer recompositions but at most a marginal change in frame times, since the blur re-render cost is unchanged.+- **[low] Player tint is animated during composition: the whole player and the clickable artist credit are rebuilt on every frame for 600 ms at each song change** — `base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt:219` (compose-immersive, effort M)+ - Impact : Each song change (skip, auto-advance, crossfade half-way), and each player open because of the palette problem above, recomposes ImmersivePlayer's body, both BoxWithConstraints scopes, PlayerCredits, every tint reader and the marquee'd artist Text for about 36 frames at 60 Hz, or about 72 at 120 Hz. The new AnnotatedString forces a full text re-layout and re-creates the link handling on every frame. All of this overlaps the cover crossfade, the mesh colour fade and the Canvas fade-in, when the main thread is busiest.+ - Correction : Apply the steps in order. Step 1 alone fixes the per-frame AnnotatedString rebuild and is nearly free. Steps 2 and 3 stop the large scopes from recomposing.++1. In base/app/src/main/java/com/music/spotui/ui/components/ArtistChooser.kt, rememberArtistCredit (lines 142-171):+ - Remove `color` from the `remember` keys, or better, from the signature.+ - Build the link styles without a colour so the links take the Text's own colour: `TextLinkStyles(style = SpanStyle(), pressedStyle = SpanStyle(textDecoration = TextDecoration.Underline))`. The styles object must still be non-null, so the theme's accent link colour is not applied.+ - Key the remember on `(artists, line)` only.+ - Update every caller, including ImmersivePlayer.kt:591 and any Classic-look caller found with `grep -rn rememberArtistCredit`. Check that each caller's Text already sets `color =`; ImmersivePlayer.kt:595 does.+ - Check on a device that the artist names keep the tint colour, and do not turn the accent colour, before and after a press.++2. In base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt, stop reading the animated value in the BoxWithConstraints scopes:+ - Keep the State instead of delegating: `val tintState = animateColorAsState(...)`.+ - Change LocalPlayerTint in PlayerControls.kt:92 to `staticCompositionLocalOf<State<Color>> { mutableStateOf(Color.White) }` and provide `tintState`. The provided object never changes, so the providing scope stops recomposing.+ - Readers use `LocalPlayerTint.current.value`. Only the small composables that read it (CircleGlyph, ScrubTimes, VolumeRow, the toggle chips) then recompose. Better, readers that only paint a background read it at draw time: `Modifier.drawBehind { drawRect(LocalPlayerTint value captured as State .value.copy(alpha = ...)) }`. Background readers are at PlayerControls.kt lines 194, 371, 386, 402 and 438.+ - Replace the handle's `background(tint.copy(alpha = 0.35f))` (ImmersivePlayer.kt lines 314 and 714) with `drawBehind { drawRoundRect/drawCircle(tintState.value.copy(alpha = 0.35f)) }`. Keep the clip(CircleShape).++3. Change the parameter type from `tint: Color` to `tint: () -> Color` for PlayerCredits (line 532) and LandscapePlayer (line 695), and pass `{ tintState.value }`:+ - In PlayerCredits, read `tint()` in the explicit badge's drawBehind (line 578).+ - For the artist and source lines (lines 595 and 608), use `BasicText(..., color = ColorProducer { tint().copy(alpha = ...) })` so the colour is read at draw time. Alternatively, keep Material `Text` but move each line into its own small composable that reads `tint()`, so only that line recomposes.++4. Apply the same change to ImmersivePodcastPlayer.kt:145 and its LocalPlayerTint readers (lines 500-531).++To verify: in Layout Inspector, across one skip, the recomposition count of the two BoxWithConstraints content lambdas and of PlayerCredits should go from about 36 or more to 1-2. Only the tint readers should keep counting per frame (or none, where the colour is read at draw time).+- **[low] Glass modifier is never equal to the previous one: every recomposition of a glass surface rebuilds its whole RenderEffect chain, and every tap recomposes the caller** — `base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/DrawBackdropModifier.kt:115` (compose-immersive, effort S)+ - Impact : Every play/pause, buffering flip, song change, press and release on the mini player, the top bar or the pill, and every frame of the bar-control size animation (next finding) re-creates 3 to 4 native RenderEffect objects per glass surface and forces the effect layer to re-render. The effect is small per event, but it happens on the most frequently touched controls, and on press it lands exactly when the lens bulge animation starts.+ - Correction : 1. base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/ShapeProvider.kt: give ShapeProvider identity-of-block equality:+ override fun equals(other: Any?): Boolean = this === other || (other is ShapeProvider && other.shapeBlock === shapeBlock)+ override fun hashCode(): Int = System.identityHashCode(shapeBlock)+ Use `===` on shapeBlock, not `==`, so a new lambda (a real shape change) is still unequal. When the elements compare equal, update() is skipped and the node keeps its old ShapeProvider. That provider holds the identical shapeBlock, and its cached outline stays valid, because createOutline re-checks `_shape != shape` on every call.+ This one change covers DrawBackdropElement, HighlightElement, ShadowElement and InnerShadowElement, since they all compare shapeProvider. Callers need no change: immersiveLiquidGlass (`{ shape }`, memoized by strong skipping), immersivePageFrost (a non-capturing lambda) and GlassSelectionPill (a remembered shape) all pass stable blocks. Add a one-line "Vendored change" comment, since this is vendored Kyant0/backdrop code.+2. Optional, low value: in base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveGlass.kt, rewrite rememberGlassPress so it does not read `pressed` during composition:+ val a = remember(source) { Animatable(0f) }+ LaunchedEffect(source) { source.interactions.collect { when (it) { is PressInteraction.Press -> launch { a.animateTo(1f, ImmersiveMotion.pressSpring()) }; is PressInteraction.Release, is PressInteraction.Cancel -> launch { a.animateTo(0f, ImmersiveMotion.releaseSpring()) } } } }+ return remember(a) { { a.value } }+ Keep the early `return null` for a null source or reduce motion. Animatable's mutator cancels the previous animateTo, so release interrupts press exactly as animateFloatAsState does today.+3. To verify: add a temporary counter in DrawBackdropNode.updateEffects. Toggle play/pause with the mini player still: today it fires once per glass surface per toggle; after the fix it should not fire. During a press, rebuilds per frame are expected, by design.+- **[low] Tab bar and pill leave composition on every fold and unfold (and when the keyboard opens): glass nodes re-attach and recompile AGSL shaders on the first frame of the animation** — `base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveChrome.kt:205` (compose-immersive, effort M)+ - Impact : Fold and unfold happen constantly: 32 dp of scroll in either direction. At the start of each unfold the main thread composes the tab bar, allocates new GraphicsLayers and compiles 4 runtime shaders (SkSL compile, typically a few milliseconds each on mid-range SoCs). The result is a hitch on the first frame of the very animation the user is watching. The keyboard case also rebuilds everything on every search open and close.+ - Correction : Primary fix, low risk: share compiled RuntimeShaders across the process.+- In base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/RuntimeShaderCache.kt, change `RuntimeShaderCacheImpl`:+ - Keep the `RuntimeShaderCache` interface.+ - Back `obtainRuntimeShader(key, string)` with a process-wide map: `internal object SharedRuntimeShaders { private val map = HashMap<String, RuntimeShader>(); fun get(key: String, src: String) = map.getOrPut(key) { RuntimeShader(src) } }`. Key by `key` (or by `src` itself, to guard against two shaders sharing a key).+ - Make `clear()` a no-op, or drop it, so that `BackdropEffectScope.reset()` (BackdropEffectScope.kt:94) and `HighlightNode.onDetach` (highlight/HighlightModifier.kt:~158) no longer throw the compiled shaders away.+- Add a comment that the cache is main-thread-only. Every caller already sets all uniforms immediately before use:+ - Lens.kt:55-66 creates the `RuntimeShaderEffect` right after `apply{}`. The platform copies the builder's uniforms into the RenderEffect at creation.+ - HighlightStyle `createShader` sets its uniforms and draws right away. `setFloatUniform` discards the native instance, so earlier recorded display lists keep their own SkShader.+- Check the other `obtainRuntimeShader` users before sharing:+ - effects/RenderEffect.kt:42 (`runtimeShaderEffect`).+ - HighlightStyle.Ambient.+ - Confirm none of them keeps the RuntimeShader object and mutates it later, after the effect or draw was created.++Optional, only if a Perfetto trace still shows a long first frame: keep the 56 dp `MinimizedTabPill` composed permanently. It is a single cheap surface; place it plainly, or skip placing it, when progress == 0, and remove its semantics and pointer input when it is hidden. Do NOT keep the full `TabBarContent` composed at alpha 0:+- Its glass would keep the page-sampling ticker running.+- It would keep its graphics layers.+- It would sit in a placement layer, contrary to the constraint at ImmersiveChrome.kt:243-245.++IME: leave the early return at ImmersiveChrome.kt:172 as it is; the rebuild happens once per keyboard close. If needed, move the inset read out of composition: `val imeUp by remember { derivedStateOf { ime.getBottom(density) > 0 } }` with a captured `WindowInsets.ime`. This stops ImmersiveBottomChrome from recomposing on every frame of the keyboard animation.++How to measure: run Perfetto while scrolling Home to fold and unfold the chrome 10 times, and look for RuntimeShader / nativeCreateShaderBuilder slices in Choreographer#doFrame before and after the cache change.+- **[low] Library list is rebuilt and Collator-sorted on every recomposition (each search keystroke, download start or finish): the issue the previous audit reported for the Classic library, unfixed and duplicated in Immersive** — `base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveLibraryScreen.kt:196` (compose-immersive, effort S)+ - Impact : With a few hundred to a thousand library items and Alphabetical or Creator sort, every letter typed in the library search re-sorts the whole library with a Collator on the main thread, which can take several milliseconds on a mid-range phone and causes stutter while typing. The same happens each time a download starts or finishes while the Library tab is open.+ - Correction : 1) `base/app/src/main/java/com/music/spotui/data/local/LibraryOrder.kt`+- Replace the per-call `Collator.getInstance()` at line 77 with a private `ThreadLocal.withInitial { Collator.getInstance().apply { strength = Collator.PRIMARY } }`, the same pattern as `textOrder` in `ContextScreen.kt:1452`.+- In `arrange`, call `.get()` on it.+- Optionally drop the trailing `sortedBy { !it.pinned }` pass when no entry is pinned (`if (sorted.any { it.pinned })`).++2) `base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveLibraryScreen.kt`+- Split `libraryEntries` (lines 333-367) into two parts:+ - a @Composable part that only resolves the 4 strings and `packageName`;+ - a plain function `assembleLibrary(base: List<LibraryEntry>, localName, downloadsName, likedName, localSubtitle, packageName): Pair<List<LibraryEntry>, Int>`. It holds the current body: `hasDownloads` from `OfflineStore.tracks`/`OfflineDownloader.requests`, `LocalPlaylists.list()`, the `LibraryOrder.version` read, and `arrange(...)`.+- At line 196, replace the call with:+ `val data = (entries as? Response.Success)?.data.orEmpty()`+ `val assembled by remember(data, localName, downloadsName, likedName, localSubtitle, packageName) { derivedStateOf { assembleLibrary(data, ...) } }`+ `val (allEntries, pinned) = assembled`+- derivedStateOf then tracks `LibraryOrder.sort`, `LibraryOrder.version`, `LocalPlaylists.playlists` and the two offline maps automatically. A keystroke or chip change no longer re-sorts, and `allEntries` keeps its identity, so the `remember(kind, allEntries, ...)` on line 200 compares by reference.+- Optional: compute `hasDownloads` in its own `derivedStateOf { tracks.isNotEmpty() || requests.isNotEmpty() }` and pass it as a key or parameter. A download's per-track map writes then stop invalidating the assembly unless emptiness actually flips.++3) `base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt` (lines ~298-332)+- Apply the same change: move the `allEntries`/`rootPinned` assembly into the shared `assembleLibrary` (make it internal, e.g. in `data/local` or a shared ui file, so both looks use one copy) behind `remember(...) { derivedStateOf { ... } }`.+- Then wrap the `LibraryChips.apply` and search filter at lines 335-345 in `remember(chip, allEntries, followedArtists, followedShows, searchQuery, myId)`, as Immersive already does.++4) Optional, same pattern: `ui/immersive/pages/ImmersiveLibraryPages.kt:131-134`. There, `arranged` is recomputed on every recomposition of the folder page. Wrap it in `remember(entries, uri) { derivedStateOf { LibraryOrder.version; LibraryOrder.arrange(...) } }`.++How to verify: wrap `arrange` in `android.os.Trace.beginSection("LibraryOrder.arrange")`/`endSection`, set the sort to Alphabetical, and type 10 characters in the library search. Expect 0 arrange sections after the fix (about 10 before). Then check that changing the sort, moving an item, creating or deleting a local playlist, and the first download starting or the last one being removed all still update the list.+- **[low] Top bar and floating header controls animate their size during composition: the bar and its actions recompose on every frame of every fold** — `base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveTopBar.kt:92` (compose-immersive, effort S)+ - Impact : Each fold or unfold (every change of scroll direction past 32 dp) recomposes ImmersiveTopBar or ImmersiveFloatingHeader, every action composable and their glass modifiers on every frame of the chrome spring. Combined with the ShapeProvider finding, that also rebuilds the effect chain of the back button and the actions pill on every frame, during scrolling, when frame time is tightest.+ - Correction : The goal: the animated control size should be read only in layout and draw, never in composition.++1. ImmersiveTopBar.kt: change `rememberBarControlSize()` to return `() -> Dp`.+ - Code: `val anim = animateDpAsState(...); return remember(anim) { { anim.value } }`+ - Do not use `by` delegation, because it reads the value in composition.++2. Change `LocalBarControlSize` to `staticCompositionLocalOf<() -> Dp> { { BarControlSize } }`.+ - The provided lambda is remembered and never changes, so providing it causes no recomposition.+ - Update the KDoc at lines 85-89 and 425 to say that readers must call it in layout/draw.++3. Add a private helper `Modifier.squareSize(size: () -> Dp)`. Its body: `layout { m, _ -> val s = size().roundToPx(); val p = m.measure(Constraints.fixed(s, s)); layout(s, s) { p.place(0, 0) } }`.+ - Back button (line 188): replace `.size(controlSize)` with `.squareSize(controlSize)`, in the same position in the chain, so wideClickable and the glass surface keep their order.+ - Back icon (line 196): give it a fixed `Modifier.size(BarControlSize * 0.64f).graphicsLayer { val k = controlSize() / BarControlSize; scaleX = k; scaleY = k }`.++4. ImmersiveBarAction (lines 293-302): `val size = LocalBarControlSize.current` (the lambda).+ - Use `.squareSize(size)` in place of `.size(size)`.+ - Give the Icon a fixed `size(BarControlSize * 0.5f)` with the same graphicsLayer scale as the back icon.++5. ImmersiveHomeScreen.kt:205-214:+ - Make the outer tap Box's width a layout modifier: `size() + 20.dp` wide, fixed height ImmersiveHeaderContentHeight.+ - Make the inner disc box `.squareSize(size).graphicsLayer { scaleX = size() / 44.dp; scaleY = scaleX }`, where the lambda is called inside the block.++6. Lines 212 and 454: provide the remembered lambda.++Keep `animateContentSize` on the actions Row as it is: it still animates when actions are added or removed, and the per-frame width change now comes from the layout modifier.++Verify with Layout Inspector recomposition counts: ImmersiveTopBar, ImmersiveFloatingHeader and ImmersiveBarAction should stay at 0 across a fold or unfold, and the controls should still visibly shrink from 44 dp to 38 dp.++This pairs with the separate ShapeProvider finding: `shape = { shape }` in ImmersiveGlass.kt:227 should also be remembered.+- **[low] Lyrics clock runs a per-frame withFrameNanos loop even for line-synced lyrics, which need no frame-accurate clock** — `base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricClock.kt:90` (compose-immersive, effort S)+ - Impact : For the whole duration of a song shown with line-synced lyrics (a large share of Myspoti's sources, per the panel's header comment), the main thread wakes on every vsync. By the project's own observation, this keeps LTPO displays at their maximum refresh rate, with no visible benefit.+ - Correction : Files:+- `base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricClock.kt`+- `base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricsPanel.kt`++1. In `ImmersiveLyricClock.kt`, add a parameter to `rememberLyricsPlayhead(trackKey, playing, nextEventMs: (Long) -> Long? = { null })`.+ - The lambda returns the song time of the next moment the panel must change: a line start, or a line start minus its scroll lead.+ - It returns null when the clock must tick every frame.+ - Read the lambda through `rememberUpdatedState` so it is not a `LaunchedEffect` key.++2. In the `playing` branch, keep the per-frame `withFrameNanos` loop as it is. After each frame, add:+ - `val next = nextEvent(head.clock.longValue)`+ - If `next == null` (a word-synced line, a swept background, or a running gap), loop to the next frame as now.+ - Otherwise, `delay(((next - head.clock.longValue) - 12).coerceIn(0, 250))` before the next `withFrameNanos`. The 250 ms cap keeps seek detection (`SEEK_JUMP_MS = 800`) and resyncing responsive.+ - Do not call `engine.restart()` between ticks. `LyricClock.frame` handles a larger `dt`.+ - In the `!SongPlayer.positionMoving()` early-return path, also wait up to about 120 ms, like `PAUSED_POLL_MS`, instead of re-running every frame while buffering.++3. In `LyricsList` (`ImmersiveLyricsPanel.kt`, around line 412), build the lambda with `remember(rows)`:+ - If the row being sung or the next row `isWordSynced`, has `backgroundSwept != null`, or `isGap` with `now < untilMs`, return null. Simplest form: `val perFrame = rows.any { it.isWordSynced || it.backgroundSwept != null }`. If `perFrame` is true, always return null, so fully word-synced songs behave exactly as today.+ - Otherwise, take `i = rows.indexOfLast { it.timeMs <= now }` and look at row `i`:+ - If it is a gap still running, return null.+ - Else let `n = rows.getOrNull(i + 1) ?: return 250-ms-ahead` and return `minOf(n.timeMs, n.timeMs - scrollLead(rows, now))`, taking the earlier boundary that is still `> now`. If neither is, fall back to `n.timeMs`.+ - Pass it as `rememberLyricsPlayhead(trackKey, playing && isSynced, nextEvent)`.+ - This keeps `leadLine` (the scroll start) and `activeRow` (the line lighting) on the frame they would have landed on, give or take about 12 ms.++4. Optionally, cap the per-frame branch by `EnergySettings.state.value.policy` in saver mode, as `rememberFrameClock` does.++How to verify: with line-synced lyrics open, `adb shell dumpsys gfxinfo <pkg>` and a Perfetto trace should show the main thread's Choreographer#doFrame callbacks dropping from about 60 or 120 per second to a few per second between lines. Line highlight and scroll timing should be unchanged against a word-synced song.+- **[low] Glass diagnostic report builds a String on every glass draw, even after its 14-line cap** — `base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveGlass.kt:329` (compose-immersive, effort S)+ - Impact : Each glass surface redraw allocates a list, an IntSize and a roughly 100-character String, and walks the layout tree twice. With 4 to 6 surfaces redrawn every frame during the 3 s settle window, fold animations, presses and sheet slides, that is a steady stream of garbage in draw. It is minor, but free to remove.+ - Correction : File: base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveGlass.kt, `PageBackdrop.report()` and its companion.+1. Make the first statement of `report()` `if (reports >= 14) return`. With several surfaces this alone removes the cost after the first frames, because the cap is reached almost immediately.+2. For the case where the cap is never reached, also skip the string when nothing changed:+ - Compute a cheap state key without allocating. Inline the recorded size as a max loop over `page.sources` (or add a non-allocating `recordedSizeOrZero()` in LayerBackdrop.kt that loops instead of using mapNotNull and maxByOrNull).+ - Pack the fields into a Long, e.g. `key = (recW and 0xFFFF).toLong() shl 48 or (recH and 0xFFFF).toLong() shl 32 or (surfW and 0xFFFF).toLong() shl 16 or (surfH and 0xFFFF).toLong()`. Mix the booleans usable/attached/sameWindow and the source/coordinates null-or-attached states into a separate Int `flags`.+ - Keep `@Volatile var lastKey = Long.MIN_VALUE` and `lastFlags` in the companion. Return before `buildString` if both are unchanged.+ - Only then build the line, keep the existing `line == lastReport` check, and log.++Do NOT move or cache the `findRoot()` and `isInsideSource()` calls in `drawBackdrop`. They drive rendering, not logging.++Optional: gate the whole `report()` call behind `BuildConfig.DEBUG` or the existing diagnostics flag, if the Logbook line is not wanted in release builds.++To verify: track allocations in the Android Studio memory profiler while scrolling Home with Liquid Glass on. StringBuilder, String and ArrayList allocations attributed to PageBackdrop.report should drop to zero after the first state lines.+- **[low] Recovery after a page reload waits a fixed 1.5 s after the new page is already ready (ad stuck, stalled song, pick made during a reload)** — `base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt:348` (playback, effort S)+ - Impact : Every stuck-ad reload ('the song after it plays within a second', measured 20/10), every 'past the end' or 'paused at the end' stall reload, and every pick or skip made while a reload is under way gets +1.5 s of silence after the page is able to play.+ - Correction : File: base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt (only this file).++1. Add a helper next to awaitDeviceJoined():+```kotlin+/** A new page just ready: settled once its device has joined and it has reported a state; RESTORE_GAP_MS at most (the old fixed wait). */+private suspend fun awaitPageSettled(seqAtReady: Int) {+ val device = app.myspoti.spotify.bridge.PageDevice+ if (!device.reported) { delay(RESTORE_GAP_MS); return } // CDP, or no join seen yet in this process: keep today's guard+ val started = System.currentTimeMillis()+ withTimeoutOrNull(RESTORE_GAP_MS) {+ device.joined.first { it }+ while (stateSeq == seqAtReady) delay(50)+ }+ bridge.logger?.invoke("new page settled after ${System.currentTimeMillis() - started} ms")+}+```+2. reloadAndPlayOn: read `val seq = stateSeq` right after `if (!reloadAndWait(reload)) return@runCatching`, then replace line 348 `if (next) delay(1_500)` with `if (next) awaitPageSettled(seq)`. Keep the userMoveAt check and `playOnNewPage { playOn(s) }` as they are; playOnNewPage's awaitDeviceJoined then returns at once.+3. Page-back collector (lines 302 and 304): read `val seq = stateSeq` where the page becomes ready (next to `pageReadyAt = ...`). Change PICK to `scope.launch { awaitPageSettled(seq); playPickAfterReload() }` and INTENT to `scope.launch { runCatching { awaitPageSettled(seq); playIntent() } }`. awaitDeviceJoined is already part of the helper.+4. Do not touch the `delay(1_500)` inside reloadAndWait (line 445). It runs while the new page is still loading, keeps the old page's "ready" from being taken for the new one, and costs nothing. Do not touch `delay(RESTORE_GAP_MS * attempt)` in resumeAfterReload (a retry backoff).++Expected gain: about 0.6 to 1.2 s less silence per reload recovery on Android. Never slower than today, because 1.5 s stays the upper bound. Check with playback_test.py (reload, frozen and ad scenarios): in the Logbook, the gap between "new page settled after N ms" and the next "call #… player.play (play on|pick after reload|intent)" line should be under 100 ms. Also confirm that no "sent again after DEVICE_NOT_FOUND" line and no restored-session overwrite appear (the new song must stay playing and not fall back to the old one paused).+- **[low] End-of-song stall recovery acts on 2 s ticks: 'past the end' costs 3.5-5.5 s of silence and 'paused at the end' 8-12 s** — `base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt:803` (playback, effort S)+ - Impact : Several seconds of silence between two songs whenever the page stops at a song's end. The code's own intent is 'Next song quickly' (1 s).+ - Correction : File: base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt, watchStalls() only.++Approach: make the loop's own wait shorter when a deadline is known. Do not use `wake.trySend`: a message on `wake` adds a 3.05 s delay meant for ads (line 606).++1. Add a local `var dueAt = 0L` next to `key`/`since`.++2. Replace the timeout on line 605 with:+ `val base = if (quiet) WATCH_IDLE_TICK_MS else WATCH_TICK_MS`+ `val until = if (dueAt > 0) (dueAt - System.currentTimeMillis()).coerceIn(50L, base) else base`+ and pass `until` to `withTimeoutOrNull`. At the top of the iteration, set `dueAt = 0L`.++3. Where the key is first recorded (line 803), when reason is not SILENT, set `dueAt = now + wait` before `continue`. Move the `val wait = ...` line above line 803 to do this. The next iteration then wakes exactly at since+wait and acts. "Past the end" goes to about +1 s after detection; "paused at the end" acts at since+8 s with no rounding to the 4 s idle tick.++4. Optional, for "past the end" detection itself: after `tickCrossfade(...)`, when `s` is playing (not paused, not buffering, not ad, not remoteActive) and has an item with durationMs > 0, compute `val endAt = now + (s.item.durationMs + 1_500 - s.positionAt(now))`. If `endAt` falls before the next normal tick, set `dueAt = minOf(dueAt.takeIf { it > 0 } ?: Long.MAX_VALUE, endAt + 20)`, so the tick that first sees the stall runs right at end+1.5 s. Expected silence is then about 2.5 s instead of 3.5-5.5 s.++5. Keep STUCK_MS (8 s) for "paused at the end"; do not lower it without measurements. Keep all existing guards: userPaused/pausedByUser, remoteActive, repairsHeld(), recoveryHeld(), the licence-refused branch, and the ping check.++6. Validate with tools/playback_test.py scenario `song_end`. In the logbook, the time between X's end ("track change … left at") and "player stalled (past the end) on X, attempt 1" should drop to about 2.5 s. Also check that ordinary song changes on a healthy page never log a stall (no false positives from the shorter effective grace).+- **[low] Relayed track-playback replies are fully JSON-parsed 1-4 times before they go back to the page (on the path to first sound)** — `base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt:375` (playback, effort S)+ - Impact : Every play, skip and natural song change on a free account waits several ms to tens of ms extra, depending on body size and phone, for work the page does not need. MediaManifests.record is pure bookkeeping for extensions.+ - Correction : File: base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt, handle() at lines 365-383.+1) Keep only what changes the reply before reply(): the `withoutAds` call (line 368) and `val sent = given?.first ?: text`. Call `reply(id, doc, it.code, out.toString(), sent)` straight after that.+2) Move the rest so it runs after reply(), on the same OkHttp thread (it no longer delays the page): the `given?.second` "ad left out" logging and counters, the `whyKept` block (lines 371-372), `MediaManifests.record(sent)` (line 375) and the `adAhead` block (lines 378-381). Keep their order and conditions exactly as they are now. Optionally also move the logging-only cluster blocks below reply() (clusterSummary/clusterBrief and the debug "cluster devices" parse, lines 350-362, plus keepAdSample at line 365), but leave PageDevice.joined(), devices.answered(), onDeviceRegistered and PageDevice.commandLost() before reply(), because the app's mirror relies on them.+3) Optional, to parse once, in base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt: add internal overloads `MediaManifests.record(root: JsonObject)` and `AdBlock.adAhead(root: JsonObject)` (and `whyKept(marker, root)`). In ControlRelay, parse once with `runCatching { Json.parseToJsonElement(sent).jsonObject }` only when `"manifest" in sent || AD_HINT matches`, then pass that tree to the overloads. Keep the String versions for the existing tests (AdQueueTest and the tests that check withoutAds/adAhead).+Measure: log `uptimeMillis()` from handle() entry to reply() for /track-playback/ on a free account, before and after.+- **[low] Every bridge call and every relay reply waits its turn at the back of the main looper, even when already on the main thread** — `base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt:659` (playback, effort S)+ - Impact : Each hop waits behind the frame being drawn and any queued UI work. That is roughly 0-16 ms on a smooth frame and much more on a janky one, several times per tap or skip.+ - Correction : **1. `base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt`, `evaluate()` (around line 648)**+- Add `if (Looper.myLooper() == Looper.getMainLooper()) { runCatching { view.evaluateJavascript(script, null) }.onFailure { Logbook.log("script not run in the page: ${it.message}") }; return }` before the existing post path.+- Keep the existing `CompletableDeferred` + `main.post` path for calls from other threads.++**2. Same file, `evaluateValue()` (around line 659)**+- Keep the `CompletableDeferred`.+- When on the main looper, call `runCatching { view.evaluateJavascript(script) { done.complete(it) } }.onFailure { done.completeExceptionally(BridgeException("page not reachable: ${it.message}")) }` directly, with no `main.post`.+- Otherwise, post as today.+- Then `return done.await()`. The `evaluateJavascript` callback is always delivered asynchronously, so there is no re-entrancy problem.++**3. `base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt`, line 44**+- Add a second handler, `private val replies = Handler.createAsync(Looper.getMainLooper())`. The minimum SDK is 29, so no `HandlerCompat` is needed.+- Use it only in `reply()` (line 390): `replies.post { replyNow(id, script, posted) }`.+- Keep `main` for `checkAudio`'s `postDelayed` and anything else that is not on the reply path.+- Replies stay in FIFO order among themselves, because all of them are async messages on the same looper. They now skip the Choreographer sync barrier instead of waiting for the traversal.++**4. Measurement**+- Add a temporary `uptimeMillis` delta log to the post path of `evaluateValue`, or compare the existing "relay reply #N waited" lines.+- Compare `tools` `tap_latency.py` medians before and after.++**Do not implement** the `JavaScriptReplyProxy.postMessage` variant in this change.+- **[low] Every page load and reload boots on the heavy home route, then parks on /preferences, slowing time-to-ready and every recovery reload** — `base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt:476` (playback, effort S)+ - Impact : Slower 'ready' on cold start. More importantly, recovery reloads compete on network and on the page's main thread with home rendering while the song that should resume is starting. The extra silence after a reload is likely hundreds of ms on mid-range phones (the bridge comment measured ~1 s main-thread hold for a home redraw).+ - Correction : 1. base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt+ - Add a companion constant `private const val IDLE_PATH = "preferences"` with a comment saying it must match IDLE_ROUTE in player-bridge.js.+ - Add `private fun playerStart(): String = playerRoot() + IDLE_PATH`.+ - Replace `playerRoot()` with `playerStart()` in four places:+ - load(), both calls (lines 429-430). watchLoad receives the URL as a parameter, so it follows automatically.+ - reload() else branch (line 484).+ - retryPlayerPage (line 533).+ - the attach fallback (line 701).+ - Root learning (line 294): add `private val PLAYER_ROOT_PREFIX = Regex("""^https://open\.spotify\.com/intl-[a-z]{2,3}(?:-[a-zA-Z]{2,4})?/""")`. In onPageStarted, use `PLAYER_ROOT_PREFIX.find(url)?.value?.let { if (it != roots.getString(ROOT_KEY, null)) roots.edit().putString(ROOT_KEY, it).apply() }`. This learns the root from `/intl-fr/preferences` (or any intl player URL) as well as from `/intl-fr/`. Keep `PLAYER_ROOT.matches` as the validator in playerRoot(). Do not clear a stored root when a non-intl URL is seen, which matches current behaviour.+ - Rewrite the stale KDoc on reload() (line 478). It now loads the idle route under the learnt language root, which boots the player like any Web Player route.+2. base/api-spotify/src/main/resources/bridge/player-bridge.js, park() (line 794): change the guard to `!location.pathname.endsWith(IDLE_ROUTE)`. A page loaded directly on `/intl-xx/preferences` then does not get a needless history.replace. Keep park() as the safety net for page-initiated navigations.+3. Verify before merging:+ - First run while signed out: confirm `/preferences` does not redirect to accounts.spotify.com, or that the sign-in flow still behaves the same if it does.+ - Sign-in continue URL and an account whose language root is plain "/".+ - drmWatch still sees a DRM request within DRM_WATCH_MS on the `/preferences` load.+ - The full tools/playback_test.py battery.+ - Logbook "page start" → ready timings, 5 runs each on cold start and on a forced reload (e.g. the ad-recovery reload), before and after.+ - If the first-run redirect shows up in the trace, also check that the root is learnt from the redirected URL.+- **[low] LocalPlayer republishes the whole queue and the now-playing state on every ExoPlayer event (including each isLoading toggle)** — `base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt:108` (playback, effort S)+ - Impact : With a long local queue (the Downloaded list, Local Files or a large extension list, 1,000+ songs), the main thread rebuilds thousands of SongsModel and QueueItem objects. The default policy then deep-compares them, every few seconds during playback and in bursts around transitions. This costs battery and adds UI jank. Nothing breaks.+ - Correction : 1. base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt:108. Replace the bare publish() with a filtered call:+```kotlin+override fun onEvents(player: Player, events: Player.Events) {+ // Buffer top-ups and command/track-info changes change nothing the screens show.+ val noise = intArrayOf(Player.EVENT_IS_LOADING_CHANGED, Player.EVENT_AVAILABLE_COMMANDS_CHANGED,+ Player.EVENT_TRACKS_CHANGED, Player.EVENT_MEDIA_METADATA_CHANGED, Player.EVENT_PLAYLIST_METADATA_CHANGED)+ if ((0 until events.size()).all { events.get(it) in noise }) return+ publish(queue = events.containsAny(Player.EVENT_TIMELINE_CHANGED, Player.EVENT_MEDIA_ITEM_TRANSITION, Player.EVENT_POSITION_DISCONTINUITY))+}+```++2. Same file, publish() (line 1059). Change the signature to `private fun publish(queue: Boolean = true)` and run the last two lines only when needed:+```kotlin+if (queue) { SongPlayer.onLocalQueue(t, upcoming(), queuedCount()); QueueSync.localChanged(queuedUris()) }+```+Keep the `queued -= ...` / playingQueued bookkeeping and onLocalState unconditional. All explicit callers (queue edits, arrange, castChanged, lines 315/677/693/702/712/726/781/1023/1034/1055) keep the default `queue = true`, so app-driven edits still republish the queue.++3. base/app/src/main/java/com/music/spotui/di/SongPlayer.kt, onLocalState (around lines 2847-2850). Do not build `rest` from the whole upcoming queue before saveLastTrack's dedupe. Either:+- Compute the dedupe key first, i.e. `"$likeUri|$isPlaying|$liked|${LastSession.SOURCE_LOCAL}"`, matching saveLastTrack's `"$uri|$playing|$liked|$source"` (playing is set to isPlaying just above). Skip the call when it equals savedLast.+- Or change saveLastTrack's `queue` parameter to a lazy `(() -> List<SongsModel>)?` that is invoked only after the `key == savedLast` check passes, and pass `{ listOf(song) + LocalPlayer.upcoming().map { localSong(it.second) }.filter { it.spotifyTrackId.isNotBlank() } }`.++To check the fix, count publish() calls and onLocalQueue invocations per minute while streaming an extension song with a 1,000-song queue. Expect several per buffer cycle before, and only at transitions, seeks and play/pause after. Confirm that the "Next in queue" and "Up next" lists and the notification still update after a skip, seek, queue add, reorder, shuffle toggle and Cast play/pause.+- **[low] Picks still read the device list before sending the play, unlike skips and resume; the 'fresh for 10 s' cache is dead code** — `base/app/src/main/java/com/music/spotui/di/SongPlayer.kt:2322` (playback, effort S)+ - Impact : 8-36 ms on every pick, up to 2 s on a slow or busy page, before the play command leaves. There is also misleading dead code.+ - Correction : Cleanup only. Do not change how picks or the queue skipTo call transport, and do not add the cache back: the owner chose to keep the unconditional read after measuring it at 8-36 ms (HANDOFF item 6).++In base/app/src/main/java/com/music/spotui/di/SongPlayer.kt:+1. Delete the field `@Volatile private var devicesFreshUntil = 0L` (line 2308) and its KDoc line "When [takeBackPlayback] last read the device list; 0 = never read (read it now)."+2. Delete both `devicesFreshUntil = 0L` assignments (line 2322, and line 2339 with its comment "Whatever happened, the list just changed under us: read it again next time.").+3. Delete `private const val DEVICES_FRESH_MS = 10_000L` (line 1779) and its KDoc (1775-1778).+4. Rewrite the comment at the top of takeBackPlayback (2311-2321) so it matches the code. Remove the sentence "The list is read again only once the entry is older than [DEVICES_FRESH_MS] — a takeover within those seconds is still caught...". Keep the history and measurement: the read used to be suspected of making taps slow (963 ms vs 554 ms), the 15/10 run measured it at 8-36 ms from the page cache, and it is kept unconditional so a device that took playback is pulled back at once. Also keep the reason the "device list read in N ms" log line exists.++No behaviour change. To check: `grep -n "devicesFreshUntil\|DEVICES_FRESH_MS"` returns nothing, and the module compiles.++### À vérifier (120)++- **[high] No app baseline/startup profile: the 80k lines of Compose UI start interpreted/JIT on every sideloaded install** — `base/app/build.gradle.kts:164` (build-size, effort M)+ - Impact : Slower cold start (Google's published numbers for Compose apps: about 20-30% on startup), plus jank the first time each screen is scrolled (Home, library lists, player sheet), after every install and update. For a beta channel with frequent updates, users spend a large share of their time in this unprofiled state.+ - Correction : Add a `:baselineprofile` module (com.android.test + `androidx.baselineprofile` plugin 1.4.x + androidx.benchmark:benchmark-macro-junit4). Apply `id("androidx.baselineprofile")` in :app with `dependencies { baselineProfile(project(":baselineprofile")) }` and `baselineProfile { automaticGenerationDuringBuild = false; saveInSrc = true }`. Write a generator (BaselineProfileRule) that runs on the owner's signed-in test phone against the `-PoverDev` release build (the manifest already has `<profileable android:shell="true"/>`). Its journey: cold start, wait for the Home feed, scroll it, open an album, start playback, open the player and lyrics, back to the Library tab, and once with the Immersive look. Commit the generated `src/release/generated/baselineProfiles/baseline-prof.txt` and `startup-prof.txt`, so CI does not need a device. The startup profile also lets R8 put startup classes in classes.dex (dex layout optimization). Quick interim step that needs no device: a hand-written `base/app/src/main/baseline-prof.txt` with wildcard rules for the startup path, e.g. `HSPLapp/myspoti/MainActivity;->**(**)**`, `HSPLcom/music/spotui/ui/navigation/**;->**(**)**`, `HSPLcom/music/spotui/ui/theme/**;->**(**)**`, `HSPLapp/myspoti/host/android/**;->**(**)**`, `HSPLapp/myspoti/spotify/bridge/**;->**(**)**`. AGP expands the wildcards and R8 rewrites them to the obfuscated names. Optionally log `ProfileVerifier.getCompilationStatusAsync()` in the diagnostic report, so testers' reports show whether a profile was compiled.+- **[high] Whole PlayerScreen recomposes every frame during the Canvas cross-fade, the cover-colour fade and the pill fade** — `base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt:343` (compose-classic, effort S)+ - Impact : On every track change, which is exactly when the user is watching the pager slide, the cover cross-fade and the title fade, the full player is recomposed and re-subcomposed for about 1.4 s (two 680 ms Canvas fades) or 450 ms (no Canvas). This costs composition time on the UI thread in every one of those frames, with nested SubcomposeLayouts and every pager page. Likely dropped frames on mid-range phones during the skip animation.+ - Correction : Read the animation state only in draw or layer lambdas:+- Keep `canvasProgress` and use `Modifier.graphicsLayer { alpha = canvasProgress.value }` for the CanvasVideo and the dim Box.+- Use `graphicsLayer { val a = 1f - canvasProgress.value; alpha = a; val g = 1f + (1f - a) * 0.06f; scaleX = g; scaleY = g }` in the pager. Delete the `canvasAlpha` and `coverAlpha` locals.+- Change `InlineLyrics` / `LyricsOverlay` / `LyricsScreen` to take `accentColor: () -> Color` or the `State<Color>`, and read it in `drawBehind` / `paletteFor` only where needed. Alternatively pass `coverColor` (the target, which changes once) instead of the animated value.+- For `pillIn`, decide visibility with `videoReady || videoOn || transition.isRunning` and read `pillIn` only inside the graphicsLayer.+- PodcastPlayerScreen: `drawBehind { drawRect(Brush.verticalGradient(listOf(tint, AppBackground))) }` with `tint` read in the lambda.+- **[high] Classic QueueSheet composes every upcoming track eagerly (one LazyColumn item holding a Column of all rows)** — `base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt:830` (compose-classic, effort M)+ - Impact : Opening 'Queue' while a 500-1000-song Downloads or Local Files list plays composes and measures 500-1000 rows. Each row has a Glide request, two pointerInput detectors and nested Rows. That is a freeze of hundreds of milliseconds or more when the sheet opens, plus a full re-layout on each track change while the sheet is open. Spotify's web nextUp can also be long.+ - Correction : Make the rows real lazy items. Use `items(queued, key = { "q:" + it.uid + it.uri })`, plain `item` entries for the two headers, and `items(nextUp, key = { "n:" + it.uid + it.uri })`, each with `Modifier.animateItem()`. Move the drag logic to item offsets the way LibraryScreeen.kt l.452-498 already does (follow the dragged key through `listState.layoutInfo.visibleItemsInfo`, move it in the backing list, edge auto-scroll with `scrollBy`). This is the same reorder pattern as the library and needs no fixed row height arithmetic. As a stop-gap, cap the displayed nextUp (e.g. the first 100) with a 'and N more' row. The classic QueueScreen (screens/QueueScreen.kt l.123/129) is already lazy, but its keys include the index (`"n" + i + it.uid + it.uri`). Drop `i` so rows keep identity when the queue shifts by one on each song change.+- **[high] Offline downloads have no foreground service or job: they stop once the app leaves the screen without music playing** — `base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt:88` (concurrency-memory, effort M)+ - Impact : A big playlist download, the main reason people use offline mode, only makes progress while the app is on screen or music is playing. Downloads interrupted by a freeze end as Failed (IOException/timeout) and need a manual retry, and files can be left half-written in tmp.+ - Correction : On API 34+, run the queue as a user-initiated data transfer job: JobScheduler `JobInfo.Builder(...).setUserInitiated(true).setRequiredNetwork(...)` plus the `RUN_USER_INITIATED_JOBS` permission, posting a progress notification through `setNotification`. On API 29-33, use a short `dataSync` foreground service (add `FOREGROUND_SERVICE_DATA_SYNC`) that starts when `enqueueAll` adds work and stops when `pending` is empty, showing 'Téléchargement x/y' with a stop action that calls `stopAll()`. Alternatively, a WorkManager `CoroutineWorker` with `setForeground(ForegroundInfo(..., FOREGROUND_SERVICE_TYPE_DATA_SYNC))` covers both ranges in one code path. Keep the existing in-process workers as the engine and let the service or job only keep the process alive. Do the same for PodcastDownloader.+- **[high] Download queue rewritten whole with fsync on every change, several times on the main thread (ANR risk when removing a list mid-download)** — `base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt:243` (concurrency-memory, effort S)+ - Impact : Each fsync on UFS/eMMC costs about 5-30 ms, so removing or stopping a large download list can freeze the UI for seconds and can trip the 5 s input ANR. During a normal 1,000-song download, the pending file is rewritten 1,000 times with O(n) content, which is O(n²) bytes plus 1,000 fsyncs. That wastes flash writes and battery and delays taps that wait on the same lock.+ - Correction : Turn savePending (and OfflineCollections.save) into a coalesced background writer. Mark it dirty, then run a single job on `Dispatchers.IO.limitedParallelism(1)` that waits about 500 ms, snapshots `pending` under the lock, and writes outside the lock. Use `writeTextSafely(..., sync = false)` for intermediate writes and keep one fsync for stopAll/forgetSession/app background. Add a batch `removeAll(ids)` to OfflineDownloader so OfflineCollections.remove does one cancel pass with one save. Move OfflineCollections.sync() off Main: only the SnapshotStateMap writes need the main thread, and those can be posted.+- **[high] A cancelled or timed-out hook call keeps running on the extension's single thread and blocks the next song's request (head-of-line blocking)** — `base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt:246` (extensions, effort M)+ - Impact : Skipping fast, or tapping a song while a prefetch, page-warm, blocks or status call is in flight on the same extension, makes the new song wait behind the abandoned request: up to 15 s (audio) or 30 s (download) of silence before playback, or a fallback to Spotify after QUEUE_MS + budget. This also burns the source's rate limits on songs nobody will hear. It matches the 'fast skip' complaints (B4 in RESTE-A-FAIRE).+ - Correction : 1) In run(), catch InterruptedException around the waits. Then: cancel the task (`task.cancel(true)`), and if it has already started, set `deadline = 0` so the next instruction-observer tick throws TimeLimit; re-set the interrupt flag and rethrow.+2) In observeInstructionCount, also throw TimeLimit when `Thread.currentThread().isInterrupted`.+3) Keep the OkHttp `Call`s in flight per runtime (a set filled in AndroidHost.http/BasicHttp.send) and `call.cancel()` them on abandon or timeout. Use `callTimeout(timeout)` instead of `timeout*2`.+4) Optionally replace the 10 ms polling loop with a CountDownLatch for 'began'.+- **[high] sources.race recompiles the whole script and builds up to 4 fresh Rhino sandboxes for every lookup** — `base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt:515` (extensions, effort M)+ - Impact : Hundreds of ms of CPU per audio or download request on mid-range phones, multiplied by the number of lanes. This adds directly to tap-to-sound latency and drains battery during batch downloads, where every track runs a race. The top-level code also runs again on every lookup (the docs ask authors to make it idempotent).+ - Correction : 1) Cache compiled scripts: a process-wide `val COMPILED_PRELUDE by lazy` and an LRU `Map<sha256(script), Script>`. Rhino supports exec of one compiled Script in several scopes. 2) Keep the lane children alive for the parent's lifetime: a `ConcurrentHashMap<lane, ExtensionRuntime>`, created on first use and closed in close(). The race then only runs `child.call`. Rebuild a child only after a fault. 3) Run lane children on the parent's existing pool instead of a new executor each.+- **[high] Show/podcast page: every page of episodes is emitted as the same mutable ArrayList, so StateFlow drops the updates (list stuck at ~50 episodes) and the UI reads a list that is still being changed on IO** — `base/app/src/main/java/com/music/spotui/data/api/Api.kt:502` (network-data, effort S)+ - Impact : For any podcast with more than 50 episodes (most of them), the episode list shows only the first page. The other pages (up to 500 rows) appear only if an unrelated snapshot read happens to recompute `rows`, for example when the finished-episodes set loads non-empty, so the result is nondeterministic. 'Oldest first' sorting then shows the wrong 'oldest' episodes. Composition iterating the ArrayList while the IO thread runs `rows +=` can throw ConcurrentModificationException or IndexOutOfBounds, which crashes the app on show open. The play queue built from `items` can also change under the player.+ - Correction : In pageOf, pass `rows.toList()`, or keep `rows` local and emit `ShowPage(model, rows.toList(), ...)` as getShowEpisodes and getPlaylistPage (`songs.toList()`) already do. Optionally throttle emits like PLAYLIST_EMIT_MS. While there:+- fetch `api.podcasts.show(uri)` (l.490) in parallel with the first episodes page, as getAlbumPage does with `async`, instead of before it;+- add the same memory/disk stale-while-revalidate the album page has (see the SWR finding), so a revisit does not start from Response.Loading.+- **[high] No Baseline or Startup Profile for Myspoti's own code (about 80k lines of Compose)** — `base/app/build.gradle.kts:164` (oss-research, effort M)+ - Impact : Google measures a 20 to 40% cold-start gain and less first-scroll jank from Baseline Profiles in Compose apps. Today Myspoti's own composables pay that cost on every cold start and on first navigation. Sideloaded builds (GitHub, Obtainium) never get Play's cloud profiles, so this is the only way they get AOT compilation. A Startup Profile also turns on dex layout optimization, which puts startup classes in the primary dex.+ - Correction : Add a `:baselineprofile` com.android.test module modeled on android/nowinandroid `benchmarks/` (Apache-2.0, https://github.com/android/nowinandroid): `baselineprofile/StartupBaselineProfile.kt` (`BaselineProfileRule().collect(pkg, includeInStartupProfile = true)`) plus one journey per hot path (open Home, open a playlist and fling it, open the player, swipe to lyrics, Library). Gramophone's `baselineprofile/` module (GPL-3.0, https://github.com/FoedusProgramme/Gramophone) is a music-app template that also shows `startup-prof.txt` checked in under `app/src/release/generated/baselineProfiles`. In app/build.gradle.kts, add `id("androidx.baselineprofile")` (benchmark-baseline-profile-gradle-plugin 1.5.0), `baselineProfile(project(":baselineprofile"))` and `baselineProfile { dexLayoutOptimization = true; automaticGenerationDuringBuild = false }`. Commit the generated profiles so CI release builds do not need a device. The app needs a signed-in Spotify session, so generate with `useConnectedDevices = true` on the test phone against a `-PoverDev` release, after the owner agrees to use the phone. In MainActivity, add `ReportDrawnWhen { homeLoaded }` so TTFD can be measured.+- **[high] qa.py --build installs and tests the previous APK when the build fails without a Kotlin 'e:' line** — `tools/qa.py:52` (tools-docs, effort S)+ - Impact : A broken change can pass the playback battery, which HANDOFF calls 'la porte'. Perf comparisons (--save/--compare) are attributed to the wrong build. This is the worst kind of tooling failure: a false green.+ - Correction : Treat any non-zero returncode as a failure: `if r.returncode != 0: out['build'] = 'FAILED: ' + ' | '.join(errors[:3] or tail_of_output); return False`, where tail_of_output is the last 5 lines of stderr. Before installing, also check that the APK's mtime is newer than the build start (or delete app-debug.apk before building), and print the installed versionCode or git hash, e.g. via a BuildConfig field shown by `myspoti-cli status`.+- **[medium] Blanket R8 keep rules copied from a template defeat shrinking and obfuscation for gms/firebase/protobuf/mlkit, all enums, all Serializable, the extensions module and data entities** — `base/app/proguard-rules.pro:24` (build-size, effort S)+ - Impact : A larger release APK (probably about 1-1.5 MB of dex, to confirm by measurement) and more dex to load and verify at startup. Enum unboxing and class merging are disabled across the app and libraries, and Rhino's unusable optimizer/ codegen (50 KB; Android always runs isInterpretedMode = true) is kept as well. The contradictory Rhino comment misleads anyone maintaining the file.+ - Correction : Delete lines 13-14 (bouncycastle), 16 (enum: AGP's proguard-android-optimize.txt already keeps values()/valueOf), 17 (Serializable), 24-35 (firebase/gms/protobuf/protos), 49-57 (room/work/glance), 60-61 (metrolist, data.entity) and 83 (mlkit blanket; keep line 82). Replace line 88 with `-keeppackagenames app.myspoti.extensions` and `-keep,allowoptimization class app.myspoti.extensions.ExtensionRuntime`, or make the lookup absolute: `getResource("/app/myspoti/extensions/prelude.js")`, as Gql.kt already does with "/spotify/gql-ops.json". Keep the NewPipe/Rhino rules (NewPipe's own app uses them) but fix the contradictory comment. Line 62 (`@Serializable ... { *; }`) can also go, since kotlinx-serialization 1.11 ships its own R8 rules. Do this one rule group at a time and test after each.+- **[medium] Dead and theme-only dependencies: 5 Ktor artifacts (0 imports), mediarouter (0 uses), Material Components used only as the XML theme parent** — `base/app/build.gradle.kts:154` (build-size, effort S)+ - Impact : A larger resources.arsc (2.71 MB, stored uncompressed and mmapped at every start), a heavier theme to resolve when the activity starts, slower debug builds and bigger debug APKs, more dependency surface to keep updated (and a supply-chain surface), and a misleading comment claiming a feature that is not wired.+ - Correction : Remove the five Ktor lines and the ktor-* entries in libs.versions.toml. Remove mediarouter, or actually declare `<receiver android:name="androidx.mediarouter.media.MediaTransferReceiver" android:exported="true"/>` if the output-switcher transfer is wanted. Switch Theme.Myspoti's parent to `Theme.AppCompat.DayNight.NoActionBar`: AppCompat stays, since MainActivity is an AppCompatActivity and AppLanguage uses AppCompatDelegate. Keep the platform items (android:colorBackground, statusBarColor, splash attributes). Drop the M3-only items (colorPrimaryContainer, colorSurfaceVariant...), which Compose never reads, then remove `implementation(libs.material)`.+- **[medium] material-icons-extended (frozen 1.7.8) makes up about 40% of the debug APK's bytecode for 215 icons actually used** — `base/app/build.gradle.kts:151` (build-size, effort M)+ - Impact : The 115 MB debug APK slows every `adb install` on the test phone and every debug dex merge, and makes the CI debug artifact larger (uploaded on every push, 14-day retention). It also adds a frozen dependency that will drift against newer Compose versions.+ - Correction : Generate the 215 icons as source: copy their ImageVector builders from the Apache-2.0 material-icons sources (androidx/compose/material/icons/{filled,outlined,rounded}/*.kt in AOSP androidx) into a `ui/icons` package, keeping the license header and the same `Icons.Filled.X` extension shape so call sites only change their imports. Alternatively use Material Symbols XML vectors via painterResource. Then drop material-icons-extended (material-icons-core is enough if some core icons remain). Meanwhile, local test builds should keep using `-Pabis=arm64-v8a`.+- **[medium] Release builds never run before a tag, and R8 mapping.txt is thrown away although beta logs capture obfuscated crash traces** — `.github/workflows/android.yml:52` (build-size, effort S)+ - Impact : A minification bug ships in a beta before anyone sees it, and crash reports from testers cannot be retraced, since the mapping for that versionCode is gone once the runner ends.+ - Correction : (1) In the build job on pushes to main, add `./gradlew assembleRelease -PoverDev -Pabis=arm64-v8a`. It signs with the debug key and is not a stable release, so the key guard is skipped. It catches R8 and lintVital failures, and can be cached. (2) In the release job, after each assembleRelease, copy `app/build/outputs/mapping/release/mapping.txt` to `release-apks/mapping-$CHANNEL-$VERSION.txt` (R8 output does not depend on the ABI, so one is enough) and upload it with `actions/upload-artifact` (long retention) or as a release asset. (3) Document `retrace mapping.txt trace.txt` for BetaLogs reports.+- **[medium] Third-party actions that handle the signing key are tag-pinned, and the JitPack dependency is unverified** — `.github/workflows/android.yml:143` (build-size, effort M)+ - Impact : A re-tagged or compromised action (as in the tj-actions/changed-files incident, March 2025), or a tampered JitPack artifact, could exfiltrate the beta or stable signing key, or get malicious code signed into an update that Obtainium and the in-app updater install. Installed apps can never move to a new key without being reinstalled.+ - Correction : Pin every third-party action to a full commit SHA, with the tag as a comment, and let Dependabot (github-actions ecosystem) bump them. Split signing: build unsigned in one job, then sign in a minimal job that runs only `apksigner sign` (build-tools) with the secrets, and add `apksigner verify --print-certs` checked against the expected SHA-256 cert fingerprint of each channel. Turn on Gradle dependency verification (`./gradlew --write-verification-metadata sha256 help`) at least for the com.github.* JitPack group, and restrict JitPack with `exclusiveContent { forRepository { maven("https://jitpack.io") }; filter { includeGroup("com.github.TeamNewPipe") } }`.+- **[medium] The offline download index is read, parsed and every file stat'd on the main thread at each launch** — `base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt:137` (cold-start, effort M)+ - Impact : Cost grows with the number of downloads. For a few thousand songs it means a JSON parse of several hundred KB, thousands of stat() calls and two large listFiles(), plausibly 50-200 ms of blocked main thread on mid and low-end phones on every cold start, added straight to time to first frame.+ - Correction : Run OfflineStore.init/load and OfflineCollections.init on a background dispatcher (one IO thread, keeping the existing folderLock). Expose a `loaded: StateFlow<Boolean>` / CompletableDeferred that the readers (`isDownloaded`, `tracks`, OfflineDataSource, Library 'Downloaded') await or observe, as LocalPlaylists already does with `ensureLoaded()` (LocalPlaylists.kt:59-74). Move the sweep of leftover files (the listFiles + delete part) to a delayed low-priority job. Do the same for PodcastDownloader.resumePending as OfflineDownloader does.+- **[medium] The client token is minted again on every launch: an extra round trip before the first GQL call, and no connection pre-warm** — `base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt:97` (cold-start, effort S)+ - Impact : One to two extra network round trips plus TLS handshakes (roughly 150-600 ms on mobile networks) before the first fresh Home, Library or Liked data after every cold start. It also adds one clienttoken mint per launch per device, a request pattern no real browser tab shows (the page keeps its own token).+ - Correction : Persist ClientToken (value, expiresAtMs, plus the clientId/appVersion it was minted for) in `files/spotify/client-token.json` (or let the host pass a load/save callback as it does for deviceId). Load it in SpotifyHttp's constructor and reuse it while `expiresAtMs - now > 1 h` and clientId still matches. Even better, ask the page for its own client token through the bridge (the page's client-token provider service) so app and page present the same one. Separately, pre-warm connections: right at engine start, fire a cheap background `HEAD https://api-partner.spotify.com/` and `HEAD https://clienttoken.spotify.com/` (or `OkHttp Call` with `Request.cacheControl(FORCE_NETWORK)` and ignore the result) on the same client, so the pool holds warm HTTP/2 connections (OkHttp keeps them 5 min) when 'ready' arrives.+- **[medium] GqlOpsUpdater refetches open.spotify.com, and all JS bundles after each Spotify build, at every cold start, in parallel with the WebView** — `base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt:110` (cold-start, effort S)+ - Impact : Every cold start adds one extra full HTML document fetch. On launches after a Spotify deploy, it adds several MB of duplicate JS downloads exactly while the hidden page is booting, which slows time to 'ready' on slow or mobile networks and costs data. It also gives every install a shared request signature.+ - Correction : Defer the refresh until after the bridge is 'ready' plus an idle delay (for example 30 s), only on unmetered networks, and at most once per N hours (store the last check time next to gql-ops.json). Better still, read the build id from the live page through the bridge (its `appServerConfig` script or the page's own buildVersion) and skip the HTML fetch entirely when it matches the cached `buildVersion`. Download bundles only when it differs, and then after the page is ready. Use `browserUserAgent` (the Fingerprint UA) instead of the constant.+- **[medium] The bridge is injected only at onPageFinished; it could start at document start and say 'ready' as soon as PlayerAPI exists** — `base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt:141` (cold-start, effort M)+ - Impact : Time to 'ready to play' and to the first fresh data includes waiting for the load event (fonts, preloads, late resources) plus a round trip, even though Spotify's PlayerAPI is usually resolvable earlier. Moving the visibility override earlier also keeps the page from being throttled during its boot.+ - Correction : Register player-bridge.js once with `WebViewCompat.addDocumentStartJavaScript(view, bridgeSource, setOf("https://open.spotify.com"))` when DOCUMENT_START_SCRIPT and WEB_MESSAGE_LISTENER are supported. Its boot() already tolerates a missing `#main`/body (the try/catch and the 250 ms retry). Replace the 250 ms DOM scan with a MutationObserver on `#main` (or a backoff). Keep the onPageFinished evaluate as the fallback, which is idempotent thanks to the `window.Myspoti.version` guard, and keep passing `__mspPage`/`__mspReannounce` through it. Preload `BridgeScript.source` on a background thread at engine start (or read it from assets via `context.assets`).+- **[medium] A full Liked Songs reload (every page, sequential) starts the moment the player is ready, also on mobile data** — `base/app/src/main/java/app/myspoti/MyspotiApplication.kt:57` (cold-start, effort S)+ - Impact : For an account with 2000-4000 likes, the daily first launch fires 40-80 sequential GQL requests and a large JSON write at the very moment the user first taps Home, Library or Play. That competes with the home refresh and the first play on the network and the token lock, and costs mobile data.+ - Correction : Delay the full reload: after ready, wait about 20-30 s (or until no user command for N s), then run it only on unmetered networks. On metered, keep the head merge (`likedHead()`, one request) even past 24 h, and do the full pass later on Wi-Fi. Optionally parallelise pages 2..n with a small semaphore once the total is known, so the pass finishes sooner when it does run.+- **[medium] Hidden tickers keep requesting frames while the player is open: inline lyrics card at 30 fps while only its header peeks, seek bar and elapsed label under the full lyrics** — `base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt:887` (compose-classic, effort S)+ - Impact : With the player open and the card peeking: about 30 + 4-15 + 4 frames per second, where only the seek bar's 4-15 are useful. With the lyrics open: about 30 (visible) + 30 + 4-15 + 4 (all hidden). This defeats the LTPO goal written in FrameClock ('between ticks nothing asks for a frame, so the LTPO screen can drop its refresh rate') and costs battery and UI-thread time while music plays, the app's most common state.+ - Correction : (a) Run InlineLyrics' clock only when its line area is visible and the overlay is closed. Pass `running = playing && cardLinesVisible && !showLyrics`. Compute `cardLinesVisible` with a `derivedStateOf` on the player LazyColumn's `layoutInfo`: item 1 visible with more than ~70dp shown. Only animateScroll when visible; otherwise use `scrollToItem` lazily on becoming visible.+(b) Give `rememberFrameClock` for the seek bar `running = songPlayingState && !audioBuffering && !showLyrics && !mv.fullscreen.value`.+(c) Drive ElapsedLabel from the same frame clock: `val secs by remember { derivedStateOf { frame.value; position() / 1000 } }`. It then recomposes once per second, on a frame that already exists, and needs no 250 ms loop.+(d) Optionally provide one player-wide clock through a CompositionLocal so all consumers tick on the same frames.+- **[medium] Cover colour can stick to the wrong song: Palette callbacks are not cancelled or checked against the current cover** — `base/app/src/main/java/com/music/spotui/di/Palette.kt:67` (compose-classic, effort S)+ - Impact : Scenario: song A has a cached colour. Tap next to B, whose colour is not cached, so its request starts. Within a second, tap previous back to A, whose cached colour applies at once. B's decode and palette then finish and set `coverColor`/`tintColor`/the mini-player `tint` to B's colour. The player gradient and mini player stay in the wrong colour for the whole of A. The same happens with two quick skips whose decodes finish out of order, or with a failed load of the skipped song (NEUTRAL grey).+ - Correction : Make extraction a cancellable suspend function, for example `suspend fun firstColor(context, url): Color?` built with `suspendCancellableCoroutine { cont -> val target = object : CustomTarget<Bitmap>(...) { onResourceReady -> cont.resume(bitmap) }; Glide.with(context.applicationContext)...into(target); cont.invokeOnCancellation { Glide.with(context.applicationContext).clear(target) } }`. Then run `withContext(Dispatchers.Default) { Palette.from(bmp).generate() }` and cache the result. Callers become `LaunchedEffect(uri) { coverColor = Palette.secondColor(context, uri) ?: NEUTRAL }`, and cancellation removes stale results. Minimal patch: `val current by rememberUpdatedState(songCoverUri)` and `if (current == requested) coverColor = it` in each callback.+- **[medium] Immersive mesh palette: Palette.generate() runs synchronously on the main thread, often in the opening frame** — `base/app/src/main/java/com/music/spotui/ui/look/MeshGradient.kt:251` (compose-classic, effort S)+ - Impact : Each track change in the Immersive player, and the opening of each Immersive sheet or header, runs one or two palette quantizations (about 112x112 px, 24 colours) on the UI thread. That is several milliseconds on mid-range phones, during a sheet slide-in or the player's open animation, often in the first frame because the cover is already in Glide's memory cache.+ - Correction : Use `produceState(initial = lastPalette, imageUrl) { val bmp = awaitBitmap(...) /* cancellable as above */; value = withContext(Dispatchers.Default) { MeshPalette(artworkMeshColors(bmp)) } }`. Keep a small process LRU (url to MeshPalette), like `Palette.colors` in di/Palette.kt, so reopening a sheet or returning to a song gets its colours in the first frame with no work. Keep the behaviour of holding the previous palette until the new one is ready.+- **[medium] Playlist header recounts downloads over the whole list on every recomposition, and every 400 ms progress tick invalidates all visible rows** — `base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt:860` (compose-classic, effort M)+ - Impact : While a big playlist or Liked Songs downloads, which is exactly when the user stays on that page after tapping Download, each progress tick re-runs the header's count over the whole list (thousands of snapshot-map reads) and every visible row's item lambda. That is 2.5 times per second per download. The same O(n) loop also runs for each frame of the header colour fade on page open and on every play/pause.+ - Correction : (1) Wrap the counts: `val dl by remember(ids) { derivedStateOf { ids.count {...} to ids.any {...} } }`. Recomposition then no longer recounts, and a tick that changes neither number invalidates nothing.+(2) Better: separate progress from status in the store. Add `OfflineStore.progress: SnapshotStateMap<String, Float>`, written by the 400 ms watcher and read only by the DownloadBadge of that row (`DownloadBadge(progress = { OfflineStore.progress[id] })` read inside `CircularProgressIndicator(progress = {...})`). `status` then changes only on real transitions (Queued, Downloading, Done or Failed).+(3) Read `tint` in `drawBehind` for the header gradient (as the top bar already does with `barAlpha`).+(4) Optionally keep per-collection counters in OfflineCollections so the header reads O(1).+- **[medium] Library list still rebuilt, re-sorted (new Collator each time) and re-filtered on every recomposition (previous audit, not fixed)** — `base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt:307` (compose-classic, effort S)+ - Impact : Each library-search keystroke, pull-to-refresh state change, completed download (an OfflineStore.tracks put) and queued download rebuilds the full library: copies, concatenation, a Collator clone and an ICU-collated sort of several hundred to thousands of entries, chip filtering, then an O(n) list equality in the LaunchedEffect. That is a few milliseconds per event on large libraries, plus a one-frame stale list on every change.+ - Correction : Hoist the assembly into `remember`/`derivedStateOf` keyed on its real inputs: `val allEntries by remember(entries, likedName, localName, downloadsName, localSubtitle) { derivedStateOf { /* reads hasDownloads, LocalPlaylists, LibraryOrder.version/sort/custom inside */ ... } }`, and the same for `chipEntries` and `filtered` on (chip, followedArtists, followedShows, myId, searchQuery). Better: move it into LibraryViewModel as a `combine(...)` flow computed on Dispatchers.Default and exposed as one StateFlow. Reuse the per-thread collator introduced for ContextScreen (audit commit e824eb0) in `LibraryOrder.arrange`. Pass the result straight to the list and derive `rows` with `remember(entries)` instead of a LaunchedEffect, so there is no one-frame lag.+- **[medium] LibraryViewModel parses the cached library from SharedPreferences on the main thread when the Library tab first opens** — `base/app/src/main/java/com/music/spotui/ui/viewmodel/LibraryViewModel.kt:51` (compose-classic, effort S)+ - Impact : The first tap on the Library tab blocks the UI thread for the prefs load plus the JSON parse of the whole library (hundreds of entries with names and cover URLs), right during the 150 ms tab fade-in. On large libraries that is visible as a stutter on the first Library open after each cold start.+ - Correction : Load in the background and keep the instant-offline behaviour: `viewModelScope.launch(Dispatchers.IO) { val cached = getCachedLibraryEntries(context); if (cached.isNotEmpty() && server == null) { server = cached; show() } ... }`. Or pre-warm it at app start on IO (the app already prefetches other things) into a process-level holder, so the ViewModel gets the parsed list synchronously when it exists. Optionally store the cache as a small file read with kotlinx.serialization instead of a large string inside a prefs XML.+- **[medium] FastScrollbar reads LazyListState.layoutInfo and firstVisibleItemIndex in composition, so it recomposes on every scroll frame** — `base/app/src/main/java/com/music/spotui/ui/components/FastScrollbar.kt:39` (compose-classic, effort S)+ - Impact : While any long list scrolls or flings, the most jank-sensitive moment, the Recomposer must recompose FastScrollbar on every frame, including on short lists where it renders nothing. The thumb also moves in whole-item steps (index-based), which looks jumpy on lists with tall headers.+ - Correction : `val total by remember(state) { derivedStateOf { state.layoutInfo.totalItemsCount } }`. Read the position inside the placement lambda: `.offset { val info = state.layoutInfo; val f = (state.firstVisibleItemIndex + state.firstVisibleItemScrollOffset / (info.visibleItemsInfo.firstOrNull()?.size ?: 1).toFloat()) / (total - 1); IntOffset(0, (f.coerceIn(0f, 1f) * (info.viewportSize.height - thumbPx)).roundToInt()) }`. Use `graphicsLayer { alpha = alphaState.value }` instead of `Modifier.alpha(alpha)` read in composition.+- **[medium] Download index re-read, backed up and rewritten with fsync on every added or removed song (quadratic I/O for big lists)** — `base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt:302` (concurrency-memory, effort S)+ - Impact : With N downloads (index ≈ 500 B/song), a k-song batch costs O(k·N) parse, copy and write work. For 1,000 songs that is roughly 3 × 250 MB of I/O and JSON work, which drains battery during big syncs and keeps the IO pool busy so other IO work (cover loads, ScreenCache) waits. Removal also floods the main thread with 1,000 posts and 1,000 SnapshotStateMap writes, so the Downloads screen recomposes 1,000 times.+ - Correction : Keep the last-written index in memory and drop the `readIndex(indexFile)` re-parse: the backup can be the previous in-memory serialization, or a rename of the old file. Coalesce writes like savePending, using a dirty flag plus a single-threaded writer with a short delay. Add `OfflineStore.removeMany(ids)` that deletes files and writes the index once and posts one `downloadsDeleted(songs)`, then call it from OfflineCollections.remove/sync and OfflineDownloader.removeAll.+- **[medium] Every ExoPlayer event batch rebuilds the whole local queue twice on the main thread, with linear scans over all downloads** — `base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt:108` (concurrency-memory, effort S)+ - Impact : onEvents fires on each play/pause, buffering change, loading toggle and discontinuity, several times per song and in bursts on skips. Playing Liked Songs (3,000 tracks) from the local player means about 6,000 object allocations, a structural equality pass over a 3,000-item EngineQueue, and several O(downloads) scans each time, all on the main thread. That causes visible frame drops on skip and seek on mid-range phones and extra GC churn during playback.+ - Correction : (a) In publish(), skip the queue path unless EVENT_TIMELINE_CHANGED, EVENT_MEDIA_ITEM_TRANSITION or a queue edit happened (`events.containsAny(...)`). (b) In onLocalState, build `rest` only when saveLastTrack's key changed: move the dedupe check before the mapping, or pass a lazy lambda. (c) Give OfflineStore a `byLocal: HashMap<Long, OfflineTrack>` maintained in add/remove/load so byLocalId is O(1). (d) Cache isOnline from DataSaver's existing network callback instead of calling getNetworkCapabilities per event.+- **[medium] Process-lifetime caches that never shrink: artist pages, extension stream answers, video MediaSources, Canvas lookups** — `base/app/src/main/java/com/music/spotui/data/api/Api.kt:768` (concurrency-memory, effort S)+ - Impact : Memory grows with browsing and listening time and is never returned while the process lives. With PlaybackService keeping the process alive for days, that means hundreds of artist models and MediaSource graphs. The result is more GC pauses (jank) and higher LMK risk for the playback process, which then means music stopping in the background on low-RAM devices.+ - Correction : Replace these maps with bounded LRUs: `android.util.LruCache` or the existing `LinkedHashMap(accessOrder=true)` + removeEldestEntry pattern used by AutoBrowser/LyricsApi. Suggested caps: ArtistCache 20 entries, CanvasCache 500, ExtensionAudio.known 64 (also drop expired entries in `keep()`), MusicVideoController.sources 8 (and remove when `freshSource` finds it stale), isrcs 2,000. Optionally clear the big ones from `Application.onTrimMemory(TRIM_MEMORY_UI_HIDDEN)`.+- **[medium] Download index, downloaded-lists file and directory listings read on the main thread in Application.onCreate** — `base/app/src/main/java/com/music/spotui/di/Graph.kt:27` (concurrency-memory, effort M)+ - Impact : With about 1,000 downloads, the index is around 500 KB: JSON parse, 1,000 stat calls and two directory listings add roughly 50-150 ms to every cold start before the first frame, more on slow eMMC phones. The same cost hits Android Auto and widget cold starts.+ - Correction : Load OfflineStore and OfflineCollections on a background thread at init: `Thread`/IO coroutine, then post the `tracks`/`collections` SnapshotStateMap fill to main. Expose a `loaded: StateFlow<Boolean>` or CompletableDeferred that downloads-dependent paths (`isDownloaded` in play routing, resumePending) await. The encrypt-in-place thread already works this way. Check file existence lazily on play instead of stat-ing every file at startup, and run the stray sweep off the critical path.+- **[medium] Page-warm and next-song prefetch share the extension thread with the user's tap, and warm tells the extension the song is about to play (ahead=false)** — `base/app/src/main/java/com/music/spotui/extensions/ExtensionAudio.kt:104` (extensions, effort M)+ - Impact : The first tap on a freshly opened playlist can be slower than with warm turned off. Extensions treat warm requests as urgent plays (they may do 'side work that only matters once the song plays'), and each page open costs 3 × N-sources requests against the sources' rate limits.+ - Correction : Pass `ahead = true` from warm() (`Extensions.audio(..., ahead = true)`). Give runtime calls a priority: let ExtensionRuntime.call take a `priority` flag, and turn the single-thread executor into a PriorityBlockingQueue-backed ThreadPoolExecutor(1,1), so a user-initiated request jumps ahead of queued ahead/warm/status/event work. Combined with the cancellation fix, also cancel the page's warm job when the user taps a song.+- **[medium] Lyrics from extensions always wait for the slowest provider, even when the first one already gave the best possible answer** — `base/app/src/main/java/com/music/spotui/extensions/HookDispatch.kt:35` (extensions, effort S)+ - Impact : With two lyrics extensions, one fast and one slow or timing out, lyrics appear up to 8-9 s late on every song, even though the top one answered in about 300 ms. Very visible on the lyrics screen and in the player's lyrics card.+ - Correction : Add a `maxRank` parameter to bestInOrder: return as soon as the answers of all earlier candidates are in and the current best has `rank == maxRank`, then cancel the rest. More generally, stop when no pending earlier candidate exists and every later one cannot exceed the current best. In LyricsApi, show `own` at once and swap in the extension's answer when it arrives (a StateFlow update) instead of awaiting it.+- **[medium] A stale status probe runs serially before the audio request on the critical path** — `base/app/src/main/java/com/music/spotui/extensions/Extensions.kt:820` (extensions, effort S)+ - Impact : The first song tapped after more than 5 min idle or in the background (from the notification, Android Auto, or reopening the app) pays a full `status` round-trip, usually one network request and up to 5.5 s, before its audio request even starts.+ - Correction : Don't block on a stale probe. Send the audio request right away and launch the probe in the background (`scope.launch { probe(id, rt) }`). Treat a Found or NotFound outcome of the real request as proof the source is live (`health.record(id, live)`) so it never needs a separate probe. Keep blocking only for sources whose last status said inactive.+- **[medium] At cold start, the first audio request waits for every enabled extension to load one by one, not just the audio sources** — `base/app/src/main/java/com/music/spotui/extensions/Extensions.kt:171` (extensions, effort S)+ - Impact : A song tapped (or resumed from the notification or Android Auto) in the first seconds after launch can wait up to 5 s and then fall back to Spotify, even though the audio-source extension itself would load in about 100 ms. One slow extension (13 s with the retry) holds up all the others.+ - Correction : Sort the start order so extensions granted audio.source or download.source come first, then lyrics, then the rest. Replace the single `started` deferred with one deferred per extension (or per action), and in audio() wait only for the enabled audio-source extensions (`startedFor(Action.AUDIO_SOURCE)`). Combined with the compile cache above, the prelude compile also goes away.+- **[medium] Extension blocks (player buttons, menu entries, home and search) wait for the slowest extension, queue behind long hooks, and are re-requested from all extensions by any unthrottled ui.refresh** — `base/app/src/main/java/com/music/spotui/extensions/Extensions.kt:676` (extensions, effort M)+ - Impact : Player buttons and menu entries pop in late (seconds, sometimes more than 30 s), causing layout shifts in the bottom sheet and the player. A badly written extension calling ui.refresh in a playback listener makes every extension redraw and re-run its hooks, which wastes CPU and requests.+ - Correction : 1) Wrap blocks() in `withTimeoutOrNull(BLOCKS_MS + 300)` and emit results progressively (a Flow that shows each extension's group as it arrives, keeping the priority order). 2) Skip, rather than queue, a blocks call to an extension that is busy (`busy[id] > 0`) and serve its last answer from a small LRU keyed by (id, hook, input) with a TTL of about 30 s. 3) Replace the global blocksTick with a per (extensionId, surface) tick, debounce it (250 ms) and rate-limit ui.refresh in ExtensionRuntime (for example 10/min, like notify).+- **[medium] Background auto-update inflates untrusted repository archives with no total size cap (zip bomb leads to OOM)** — `base/extensions/src/main/kotlin/app/myspoti/extensions/Sources.kt:208` (extensions, effort S)+ - Impact : A hostile or compromised extension repository can make the app run out of memory on every launch, and the OOM can hit the main or UI thread rather than the IO thread that `runCatching` covers, which looks like a crash loop. It can also just waste hundreds of MB of RAM during a background check.+ - Correction : In fromArchive, buffer only the names a package can contain (`manifest.json`, `*.js`, `*.png`, LICENSE*, README.md). Keep a running uncompressed total and throw past, say, MAX_ZIP*2 (4 MB). Skip other entries without reading them (closeEntry). Better still, read manifest.json first, then only `manifest.main` and the icon.+- **[medium] webview.auth URLs are not limited to the extension's declared hosts, and hidden mode gives a silent channel to any website** — `base/extensions/src/main/kotlin/app/myspoti/extensions/Host.kt:121` (extensions, effort S)+ - Impact : This bypasses the per-host network permission the user approved. Data the extension holds (now playing, storage, Spotify results it was granted) can be sent to undeclared hosts with no on-screen sign. The permission is labelled critical, which limits the exposure, but the install prompt's host list becomes misleading.+ - Correction : Require the auth url host (and an https callback host) to match the manifest's network hosts, using the same `hostMatches` rules, or add an `auth.hosts` field shown in the install prompt. Rate-limit hidden opens (for example 3 per hour) and log every hidden sign-in that completes without being shown.+- **[medium] GraphQL responses and every bridge message are parsed to JsonElement on the caller's thread, often the main thread** — `base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt:351` (network-data, effort M)+ - Impact : GraphQL pages are large: home feed and playlist pages are hundreds of kB of JSON. Building the JsonElement tree plus mapping costs tens of ms on mid-range phones, so frames drop while a screen slides in (Discover/New releases, podcasts discover), and whenever direct HTTP fails and the bridge path is used (network switch, see the next finding).+ - Correction : Make parsing dispatcher-independent at the source:+- In HttpGql.query, wrap the parse and checkErrors in `withContext(Dispatchers.Default)`. Better still, give SpotifyHttp a `sendJson()` that parses inside the IO block (`it.body.source()` → `Json.decodeFromBufferedSource`, or `parseToJsonElement` over the stream) so the String copy disappears too. Do the same in BridgeGql.+- In Bridge, parse `raw` off the main thread: collect `host.messages` with `.map { json.parseToJsonElement(it) }.flowOn(Dispatchers.Default)`, keep only `handle(msg)` on Main, and complete pending deferreds from Default.+- In the Spotify* classes, run the mapping under `withContext(Dispatchers.Default)` per public method, or add `flowOn(Dispatchers.Default)` to the Api flows.+- **[medium] The API HTTP client (every screen's reads) is a bare OkHttpClient(): no ping, no eviction on network change, 10 s default timeouts. The relay client was hardened against exactly this** — `base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt:34` (network-data, effort S)+ - Impact : After Wi-Fi to mobile data (or back), or after a carrier NAT dropped the idle HTTP/2 connection to api-partner, the next screen loads ride the dead multiplexed connection. Every in-flight read waits the 10 s read timeout, then HttpGql falls back to the slower page bridge, where the JSON is parsed on the main thread (previous finding). The user sees spinners for about 10 s on Home/playlist/library refresh after leaving the house, the same symptom the relay fix addressed for playback commands.+ - Correction : Create one base client in host-android (for example `Http.base = OkHttpClient.Builder().connectTimeout(10s).readTimeout(10s).pingInterval(15s).build()`) and pass it to `SpotifyApi(http = ...)`. Derive every other client with `Http.base.newBuilder()...`, which shares the pool and dispatcher. Call `Http.base.connectionPool.evictAll()` from the same `onAvailable` network callback that resets the relay. Optionally add `retryOnConnectionFailure` plus one retry of a read GraphQL query on SocketTimeoutException before the bridge fallback, since reads are idempotent.+- **[medium] Glide images use HttpURLConnection with a 2.5 s connect/read timeout and no retry: covers stay grey on slow or mobile networks** — `base/app/src/main/java/com/music/spotui/data/DataSaverGlide.kt:29` (network-data, effort S)+ - Impact : On 3G/4G with high latency, or on a cold DNS/TLS to i.scdn.co, the TCP+TLS handshake plus the first byte often exceed 2.5 s. Covers then fail and stay as grey squares until the row is recycled, the same symptom as the 'pochettes non chargées' reports (B25), which were only partly explained by `spotify:image:` ids. Lists load covers more slowly than necessary even on good networks (no HTTP/2, a separate connection per concurrent fetch).+ - Correction : Use Glide's OkHttp integration (`com.github.bumptech.glide:okhttp3-integration:5.0.0-rc01`, Apache-2.0, same project as the Glide already shipped). Register `OkHttpUrlLoader.Factory(Http.base.newBuilder().addInterceptor(DataSaver.interceptor).build())` with `registry.replace(GlideUrl::class.java, InputStream::class.java, ...)`. That gives the shared HTTP/2 pool, sane timeouts (10-15 s) and the DataSaver guard as an interceptor, which replaces the custom Fetcher wrapper. As a minimum, if no dependency is wanted, pass `.set(HttpGlideUrlLoader.TIMEOUT, 15_000)` via `GlideBuilder.setDefaultRequestOptions(RequestOptions().timeout(15_000))` in `Glide.init`.+- **[medium] Cold start pays an extra serialized round trip before the first fresh data: the client token is minted on every launch (kept only in memory) and no connection is pre-warmed** — `base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt:232` (network-data, effort S)+ - Impact : On every cold start, the first direct request (Home refresh, library, a playlist) waits for DNS+TCP+TLS+request to clienttoken.spotify.com, roughly 200-600 ms on mobile. It does so while holding the lock that every other request needs, then pays a second fresh handshake to api-partner. Spotify also sees a newly minted client token at every launch, the same 'new client every start' signal the team removed for the device id (backlog B9).+ - Correction : Store the ClientToken (value plus expiresAtMs) in a small private file or SharedPreferences under the host (the token is per install/device id, not per account, which matches `forgetWebToken` keeping it). Load it in the SpotifyHttp constructor and only mint when it expires within 1 h. Alternatively, reuse the page's own `client-token` header, which the relay already sees (ControlRelay echoes the page's headers), so the direct requests and the page present one identity.+At `MyspotiRuntime.start`, fire a cheap warm-up off the main thread to put a live HTTP/2 connection in the shared pool by the time the bridge is ready: a HEAD/OPTIONS to `https://api-partner.spotify.com/` and, if the token is missing, the mint itself.+- **[medium] GqlOpsUpdater downloads open.spotify.com on every cold start and about 6 MB of JS (334 bundles) on every Spotify build change, also over mobile data, competing with the WebView at startup** — `base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt:110` (network-data, effort M)+ - Impact : About 6 MB of mobile data and roughly 20 MB of decoded JS text scanned on IO threads on most days' first launch, exactly while the hidden WebView is downloading the same page and bundles. Bandwidth contention delays page-ready, and so playback readiness and every data load gated on `ready()`. Plus 167 kB of HTML on every cold start.+ - Correction : - Rate-limit: skip the HTML check if the last check was less than 12-24 h ago (store `checkedAt` in the cache file).+- Only run when unmetered and after the page is ready (or 30-60 s after start).+- Make it reactive: refresh when a direct query fails with PersistedQueryNotFound or an unknown-operation error, and download only the main bundles first; fetch chunks only if ops the app actually uses are still missing (84 of 179 ops are in the 3 main bundles).+- Scan with okio `BufferedSource` line/segment reads instead of `body.string()`.+- Use the shared client and pool.+- Better still, have player-bridge.js read the hashes from the already-loaded page's operation definitions, which costs zero network.+- **[medium] Two caches for the same library: the SharedPreferences copy (read and JSON-parsed on the main thread) drops pinned/addedAt/uri, so Your Library first paints in the wrong order and then jumps** — `base/app/src/main/java/com/music/spotui/ui/viewmodel/LibraryViewModel.kt:51` (network-data, effort S)+ - Impact : Every Library open after a cold start shows a first frame where pinned playlists are not at the top, have no pin icon, and 'Recently added' order is wrong. A few ms to a few hundred ms later the ScreenCache copy arrives and rows jump. During that window, the long-press menu's pin/unpin acts on `entry.uri == ""` (LibraryExtras.kt:623). The SharedPreferences read plus org.json parse of the whole library runs on the main thread when the ViewModel is created. The library is serialized and written twice per refresh.+ - Correction : Delete the LibraryCachePref entries cache. Seed LibraryViewModel from `Api.HomeCache.libraryRoot` (memory), and preload `ScreenCache.libraryRoot.read()` into HomeCache on an IO coroutine at app start (Graph.init or PagePrefetch.start already read it). Move the followed-artists cache into ScreenCache as an `Entry("followed_artists", ListSerializer(ArtistsModel.serializer()))`. On upgrade, remove the old "LibraryCache" prefs file.+- **[medium] Liked Songs, library levels and artist discography are paged sequentially (50 per request), while playlists already page 4 at a time** — `base/app/src/main/java/com/music/spotui/data/api/Api.kt:892` (network-data, effort M)+ - Impact : A 3,000-song Liked Songs list is 60 back-to-back requests: about 15-20 s at about 300 ms each before the list is complete. The player context, hearts and `LikedCache` stay stale until then, every day after the 24 h TTL and on every pull-to-refresh. Library folders with hundreds of items and big artists' discographies (6 pages) wait N round trips. The previous audit's 'artist page reloads everything' is mitigated by ArtistCache but still sequential.+ - Correction : Factor getPlaylistPage's page-scheduler into one helper, `pagedParallel(first: Page<T>, pageSize, parallel = 4, emitEveryMs = 350) { offset -> fetch(offset) }`, and use it in allLiked (keep the `onPage` callback, throttled), libraryLevel and the discography loop. Check whether `fetchLibraryTracks` accepts `limit: 100`, as the web player's playlist query does, to halve the request count.+- **[medium] Offline bookkeeping does full-file JSON rewrites with fsync on the main thread (collections.json, pending.json on every downloaded-list open), and O(N) index rewrites per added or removed song** — `base/app/src/main/java/com/music/spotui/data/offline/OfflineCollections.kt:155` (network-data, effort M)+ - Impact : With Liked Songs downloaded (thousands of ids in collections.json), each open of a downloaded list costs a JSON build plus a 2-phase write with fsync on the UI thread. fsync on phone flash takes from a few ms to over 100 ms, so frames stall right when the page appears. Removing a 500-song downloaded playlist means 500 rounds of parse + copy + write + fsync of an index that grows with the library (seconds of IO, blocking `OfflineStore.add` from running downloads). Downloading N songs writes O(N²) bytes of pending.json.+ - Correction : - Move save() and savePending() onto a single-thread IO scope (as ScreenCache does), coalesce bursts (debounce about 300 ms, write the latest state), and skip sync's save when ids, name and quality are unchanged (store syncedAt in memory, or persist it lazily).+- In OfflineStore: add `removeAll(ids)`/`addAll` that write the index once. Replace the read-parse-copy backup with `indexFile.renameTo(backupFile)` before the atomic write, tracking `lastWriteComplete` in memory.+- Use `sync = false` for pending.json, since losing the last few queue entries in a power cut is acceptable, as the lyrics cache already does.+- **[medium] Offline index, downloaded-list index and local playlists are parsed on the main thread in Application.onCreate, before the first frame** — `base/app/src/main/java/com/music/spotui/di/Graph.kt:27` (network-data, effort M)+ - Impact : Cold-start time-to-first-frame grows linearly with the user's downloads. With 2,000 songs that is about a 1 MB index parse, 2,000 stat() calls, two directory listings of 2,000+ entries and a collections.json with thousands of ids, all on the main thread before any Activity draws, typically 100-300 ms on mid-range devices. That is the population that relies on the app most offline.+ - Correction : Keep init() cheap: set `root` and start the load on a background thread (`Dispatchers.IO`), publishing to the SnapshotStateMaps on Main when done. Expose `OfflineStore.loaded: StateFlow<Boolean>`, and have the few callers that need the index at once (LocalPlayer resume, OfflineCollections.offlinePage, isOnline fallbacks) `await` it. Do the leftover-file sweep (listFiles and delete) a few seconds after startup at low priority, since it is not needed for correctness at launch. Same for OfflineCollections and LocalPlaylists. Load gql-ops on IO before the first query (the bundled table can serve until then).+- **[medium] Stale-while-revalidate gaps: playlists opened by the user are never kept on disk (only the 4 prefetched ones are), and show pages have no cache at all** — `base/app/src/main/java/com/music/spotui/data/api/PagePrefetch.kt:176` (network-data, effort S)+ - Impact : After process death (common on Android in the background), any playlist other than the top 4 of the library, such as a Daily Mix, Discover Weekly, a friend's list or a search result, opens with a spinner and waits for ready() plus 2 round trips, instead of painting at once like albums do. Every show/podcast page shows a spinner on each visit.+ - Correction : In PagePrefetch.refreshed, drop the `pageSavedAt(id) == null` condition: write every complete page of 1,000 tracks or fewer and call `ScreenCache.prunePages(KEEP)` after the write. Consider KEEP about 20, since files are small. Give getShowPage the albumPage treatment: `ScreenCache.showPage(id)` read before the network, written after the final emit, pruned to about 20. Optionally an in-memory map like `ContextViewModel.recent`.+- **[medium] Glide loads every cover over the platform HttpURLConnection stack instead of the app's OkHttp; Glide is also an outdated build** — `base/app/src/main/java/com/music/spotui/data/DataSaverGlide.kt:34` (oss-research, effort S)+ - Impact : Home, playlist and grid screens request dozens of 300 to 640 px covers at once. Over HTTP/1.1 they queue behind Glide's 4 source threads, and new connections pay a separate TLS handshake. With OkHttp and HTTP/2 they share one TLS connection to i.scdn.co (multiplexed, HPACK). Covers then pop in sooner on a cold Home and while scrolling fast, especially on mobile data and high-latency networks. Glide also skips five bug-fix releases.+ - Correction : Add `com.github.bumptech.glide:okhttp3-integration:5.0.9` (Glide: BSD, part MIT and Apache-2.0, https://github.com/bumptech/glide). In DataSaverGlide.install, register `OkHttpUrlLoader.Factory(sharedClient.newBuilder().addInterceptor(DataSaver.interceptor).build())` and delete the custom Loader and Fetcher, because the interceptor already throws DataSaver.Blocked. Bump glide to 5.0.9 and glide compose to 1.0.0-beta10. Optional: in the Home shelves and ContextScreen LazyColumn, use Glide compose's `rememberGlidePreloadingData` to fetch the next screen of covers ahead of the scroll. Ideally derive this client from one app-wide OkHttpClient: at least nine separate `OkHttpClient.Builder()` instances exist (PlayerSheets, GeniusMeaning, UpdateChecker, AccountBrowser, NowPlayingWidget, YouTubeSource, …), each with its own pool and dispatcher.+- **[medium] No media resumption: the service ignores EXTRA_RECENT, so Android shows no 'resume Myspoti' card after reboot or after the app is killed** — `host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt:492` (oss-research, effort S)+ - Impact : After a reboot, after the system kills the process, or after the session ends, Myspoti disappears from the Quick Settings media carousel. Spotify, YouTube Music and Media3-based players (Metrolist via MediaLibrarySession) keep a play card there. Users must open the app and wait for the WebView to resume, instead of tapping play in the shade. Headset or Bluetooth play-to-resume after boot is also lost.+ - Correction : Port UAMP's EXTRA_RECENT handling (Apache-2.0, https://github.com/android/uamp, `common/src/main/java/com/example/android/uamp/media/MusicService.kt` lines ~290-325, plus `PersistentStorage.kt`). In onGetRoot, if `rootHints?.getBoolean(BrowserRoot.EXTRA_RECENT) == true` and the caller mayBrowse, return `BrowserRoot(RECENT_ROOT_ID, null)`. In onLoadChildren(RECENT_ROOT_ID), return one FLAG_PLAYABLE MediaItem built from the `myspoti_last_track` prefs (add `MediaLibrary.recent(context)` to the interface at PlaybackService.kt:80, implemented in AutoBrowser from SongPlayer's prefs, with no network and no waiting on the page). Route onPlay and onPlayFromMediaId for that id through the existing cold-start path built for Android Auto (A27, `awaitPlayer`). This is the same contract Media3's `MediaLibrarySession.Callback.onPlaybackResumption` implements, without migrating off androidx.media.+- **[medium] No loudness normalization or ReplayGain in the local player, so extension and downloaded FLACs play at their mastered level** — `base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt:86` (oss-research, effort M)+ - Impact : The same queue mixes Spotify-played tracks with extension-sourced or downloaded lossless files. Lossless masters vary by several dB (modern masters around -8 LUFS against older ones around -16), so the level jumps from track to track and users reach for the volume key. Crossfades between a loud and a quiet master also sound uneven. Metrolist, Gramophone and Spotify's own apps all offer normalization.+ - Correction : (1) Gain stage: port Metrolist's `app/src/main/kotlin/com/metrolist/music/playback/audio/VolumeNormalizationAudioProcessor.kt` (GPL-3.0, https://github.com/mostafaalagamy/Metrolist; about 120 lines, a BaseAudioProcessor that applies a millibel gain across PCM 16, 24, 32 and float). Add it before EqualizerProcessor in `Renderers.buildAudioSink`, with peak-aware clamping. (2) Gain sources, in order: a new optional `gainDb`/`peak` field in the audio-source and download-source answers, parsed next to `bitDepth` in Hooks.kt:157 and documented in API.md as feature `audio.gain` (the lossless services extensions wrap expose track gain in their playback APIs); REPLAYGAIN_TRACK_GAIN or R128_TRACK_GAIN read from `Format.metadata` VorbisComment entries in onTracksChanged, using the parsing part of Gramophone's `app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainUtil.kt` (GPL-3.0-or-later, https://github.com/FoedusProgramme/Gramophone; the parsing only, not its forked-Media3 processor); and the gain persisted on OfflineTrack at download time. (3) A Settings → Playback toggle 'Normalize volume' (target -14 LUFS, off by default to respect the owner's sound). Credit both files in THIRD_PARTY_NOTICES.md.+- **[medium] Lyrics romanization depends on the source supplying it; port Metrolist's on-device romanizers** — `base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt:548` (oss-research, effort S)+ - Impact : The UI, the pref and the rendering for romanized lines are all built, but users who cannot read Hangul, Cyrillic or Devanagari rarely get to use them. Myspoti ships Russian, Greek and Chinese translations and switched its font for Cyrillic users (#62), so this audience exists.+ - Correction : Port the data-free romanizers from Metrolist `app/src/main/kotlin/com/metrolist/music/lyrics/LyricsUtils.kt` (GPL-3.0, https://github.com/mostafaalagamy/Metrolist): `romanizeKorean` (pure Hangul decomposition, about 45 lines plus the HANGUL_ROMAJA_MAP table), `romanizeCyrillic` with its Russian, Ukrainian, Serbian, Bulgarian, Belarusian, Kyrgyz and Macedonian tables, `romanizeHindi`, `romanizePunjabi`, `katakanaToRomaji` for kana-only lines, and the `is*` detectors. For Chinese, add TinyPinyin (`com.github.promeG:tinypinyin:2.0.3`, Apache-2.0, small). Skip kuromoji-ipadic (Apache-2.0, adds about 13 MB to the APK); leave kanji to LyricsPlus or extensions. Wire it as a post-processing step in LyricsApi (after `resolve`, before the cache and LyricsDisk write, LyricsApi.kt:112-131): fill `romanization` only where the source gave none and the line's script matches, on Dispatchers.Default. Credit the file in THIRD_PARTY_NOTICES.md.+- **[medium] Extensions run in interpreted Rhino and recompile about 100 KB of JS on every start and on each slow-load retry; no heap cap. Consider QuickJS through Zipline** — `base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt:119` (oss-research, effort L)+ - Impact : Cold start: seconds of CPU on a busy phone before the audio-source extension is live. Until then, plays fall back to Spotify or wait, and the extension may be turned off (the code comment says this already happened). Every hook call (audio-source resolution on skip, lyrics, blocks) runs in an interpreter that is roughly 10× slower than a bytecode VM. A runaway allocation in a third-party script can OOM the whole app process, not just the sandbox.+ - Correction : Step 1 (S, no new dependency): cache the compiled `Script` objects by package sha256 (Rhino interpreted Scripts can run in fresh scopes), so the slow-load retry and a re-enable do not recompile. Step 2 (L): replace Rhino with QuickJS through Cash App's Zipline (Apache-2.0, https://github.com/cashapp/zipline, `zipline/src/hostMain/kotlin/app/cash/zipline/QuickJs.kt`). It exposes `interruptHandler` (the equivalent of the instruction observer used for the time limit), `memoryLimit` and `maxStackSize` (a real heap cap per extension), and `compile(source, fileName): ByteArray` / `execute(bytecode)`, so the bytecode can be stored next to the package and loaded in milliseconds. QuickJS is ES2023, which removes Rhino's ES6-only limits documented in API.md:780. Keep the host API identical (prelude.js + `__host`), and run the existing extensions test suite plus the extensions-cli against both engines before switching.+- **[medium] The APK ships third-party libraries with no license notices or licenses screen; THIRD_PARTY_NOTICES has a dead backdrop URL and leaves out Manrope** — `THIRD_PARTY_NOTICES.md:56` (oss-research, effort S)+ - Impact : MIT requires shipping the copyright notice with all copies, Apache-2.0 §4 requires giving recipients the license, and OFL requires shipping its notice with the font. Binary-only users (GitHub and Obtainium installs) get none of these. The credit link for the Liquid Glass code is also broken. A project that complains about uncredited forks (CLAUDE.md) should be exemplary here.+ - Correction : Add AboutLibraries (Apache-2.0, https://github.com/mikepenz/AboutLibraries): Gradle plugin `com.mikepenz.aboutlibraries.plugin` plus `com.mikepenz:aboutlibraries-compose-m3:15.3.0`. It generates the dependency and license list at build time. Show it from AboutSheet as 'Open-source licences' via `LibrariesContainer()`, in the app's dark theme, and add manual entries for the vendored sources (BitChord, Spotui, Echo-Music, Convx, backdrop, Inter, Manrope, cast_channel.proto). In THIRD_PARTY_NOTICES.md, change the backdrop URL to https://github.com/Kyant0/AndroidLiquidGlass and add a 'Manrope — SIL OFL 1.1' section pointing to base/licenses/Manrope-OFL.txt.+- **[medium] Unit-test totals count stale XML results and ignore Gradle's exit code (qa.py --unit, handoff_state.sh)** — `tools/qa.py:61` (tools-docs, effort S)+ - Impact : `qa.py --unit` and ANNEXE-ETAT can report e.g. '{tests: 600, failed: 0}' while :app's tests don't even compile, or while a module was not run. The test count drifts upward with whatever old results are left in build dirs.+ - Correction : Fail on the returncode: if non-zero, set out['unit'] = {'failed': 'build/compile', 'tail': last lines of output}. Read only the XML files written by this run: pass `--rerun-tasks` for the test tasks, or keep only files with mtime >= the run start. Better still, call the single aggregate task from the next finding and parse only its modules.+- **[medium] No canonical unit-test command: README, CONTRIBUTING, CI and qa.py each run a different subset; :extensions-cli tests never run** — `README.md:167` (tools-docs, effort S)+ - Impact : A contributor who follows README or CONTRIBUTING never runs the extension-sandbox tests, which the security model depends on. :extensions-cli can break silently, since even CI never runs its tests. Test counts quoted in docs differ by source.+ - Correction : In base/build.gradle.kts add `tasks.register("unitTests") { dependsOn(":app:testDebugUnitTest", ":host-android:testDebugUnitTest", ":api-spotify:test", ":extensions:test", ":extensions-cli:test", ":host-cdp:test", ":api:test") }`. :api:test can be dropped if :api keeps having no tests. Use `./gradlew unitTests` in README, CONTRIBUTING, CI, qa.py and handoff_state.sh. Optionally add `:app:lintDebug` to CI (with a baseline file) and a `python3 -m py_compile tools/*.py` step, so a broken import between the tools (qa -> playback_test -> cdp) is caught.+- **[medium] The 'stop on licence 429' safety guard can never fire: the app does not log widevine URLs as 'http 429'** — `tools/qa.py:45` (tools-docs, effort S)+ - Impact : qa.py's docstring promises: "a run that triggers them is stopped, since more runs would only make Spotify's limit on the test account last". That protection is dead. Battery runs (and pilot scenario F) keep hammering a rate-limited account, prolonging the limit, and report licence_429: 0. Failures caused by the limit then look like app regressions.+ - Correction : Count what the app actually logs: `re.search(r'licence answer 429|Spotify is limiting audio licences', l)`. Weight the 'limiting' line as an immediate stop, because it already means 429 x LIMIT_COUNT. Since 'licence answer' is capped at 6 per page, a more robust source is the Refusal402 summary. Expose it through the debug TEST receiver (a `licences` cmd logging the counters) or through `myspoti-cli status`, and read it there. Put the predicate in one shared place (pilot_lib already imports qa's helper pattern), not in two copies.+- **[medium] A crashed or timed-out playback battery is reported as a clean run (0/0, no failures); unknown --only names are silently ignored** — `tools/qa.py:86` (tools-docs, effort S)+ - Impact : The 'gate' can pass with nothing tested, both by hand and in unattended pilot runs, and a typo in a scenario name looks like a pass.+ - Correction : In step_battery: record `out['battery']['exit'] = r.returncode`, and add a failure 'runner crashed: <last 3 stderr lines>' when the return code is non-zero and no FAIL line explains it, or when total == 0. Catch TimeoutExpired and record it as a failure. In playback_test.main, validate the names: `unknown = (only | skip) - {n for n, _, _ in SCENARIOS}; if unknown: sys.exit(f'unknown scenario(s): {unknown}')`. In pilot sc_F, fail when the summary is missing or shows 0 total.+- **[medium] ui_smoke.py cannot see ANRs, and the crash checks also flag other apps' crashes** — `tools/ui_smoke.py:63` (tools-docs, effort S)+ - Impact : The UI crawler's docstring says it 'fails on a crash, an ANR or the app leaving', but main-thread stalls long enough to ANR, which is the class of UI bug the audit is hunting, pass silently. Unrelated crashes cause false failures in the battery.+ - Correction : Add `ActivityManager:E` (or `*:S ActivityManager:E`) to the logcat filter and match `ANR in app.myspoti.dev`. Also check `dumpsys window` for 'Application Not Responding'. For crashes, match only blocks that contain `Process: app.myspoti.dev` (the line AndroidRuntime prints in a FATAL EXCEPTION block), or start logcat with `--pid=$(pidof PKG)` and re-arm it after a relaunch. Optionally run `dumpsys activity anr` / check `/data/anr` timestamps at the end of the walk.+- **[medium] Every phone tool assumes adb at ~/android-sdk/platform-tools/adb, and device selection differs per script (several ignore --serial and ANDROID_SERIAL)** — `tools/cdp.py:11` (tools-docs, effort S)+ - Impact : New contributors can't run any tool out of the box. With a phone plus an emulator, or two phones (the documented pull_back needs a second Connect device, often a second phone), the pilot and latency tools either crash or drive the wrong device. Driving the wrong device breaks the owner's rule 'un appareil, un pilote'.+ - Correction : Create one helper module, tools/_adb.py: `ADB = os.environ.get('ADB') or shutil.which('adb') or os.path.expanduser('~/Android/Sdk/platform-tools/adb')`, and a `serial()` that reads --serial, then $ANDROID_SERIAL, then the only listed device, and refuses with several devices (copy pick_serial from myspoti-cli). Use it in cdp, playback_test, pilot_lib (pass -s everywhere, including the logcat Popen), tap_latency, skip_latency and qa. In capture.sh and routecap.sh use `ADB=${ADB:-$(command -v adb)}`. adb itself honours ANDROID_SERIAL, so exporting it also covers the shell scripts.+- **[medium] capture.sh records the beta app, not the debug build the other tools use, and its UID lookup breaks when .dev or .stable is installed** — `tools/capture.sh:11` (tools-docs, effort S)+ - Impact : A capture session taken while reproducing a bug on the dev build records an empty or wrong logcat, the wrong app's frame stats and no media-session state. Nothing tells the user the capture is wrong until they read it.+ - Correction : Add `PKG=${PKG:-app.myspoti.dev}` and use it everywhere. Get the exact UID with `pm list packages -U "$PKG" | grep -E "^package:$PKG " | ...` or `dumpsys package "$PKG" | grep -m1 userId=`, and fail loudly if it is empty or has more than one value. Use the same package for gfxinfo and the media_session sed pattern.+- **[medium] No single performance benchmark command: no cold-start, time-to-content, memory or scroll-jank numbers; latency scripts are separate, unsaved and partly broken** — `tools/qa.py:120` (tools-docs, effort M)+ - Impact : Speed work (HANDOFF §6.6, the 2026-10-18 audit) is measured ad hoc. Regressions in startup, skip latency or list jank between releases go unnoticed, and before/after claims can't be reproduced with one command.+ - Correction : Add `tools/qa.py --bench [--n 5]`, written to tools/qa-results/<name>.json and comparable with --compare. It should include:+(1) cold start x n: `am force-stop; am start -W -n app.myspoti.dev/app.myspoti.MainActivity`, recording TotalTime and WaitTime;+(2) time-to-content: add `reportFullyDrawn()` in MainActivity once Home's first section renders, then read 'Fully drawn' from logcat;+(3) the median of tap/next/previous/resume from tap_latency (import its functions, and drop skip_latency.py or make it `tap_latency --modes key-next`);+(4) scroll jank: `dumpsys gfxinfo reset`, five `input swipe` on Home and Library, then janky% and p90/p95 frame times from `gfxinfo <pkg> framestats`;+(5) PSS from `dumpsys meminfo` for the app and its renderer;+(6) APK size per ABI.+For the latency probes, read the media element through the bridge's own `media.state` call instead of Spotify internals. Longer term, add a :baselineprofile/:macrobenchmark module with androidx.benchmark (Apache-2.0, https://github.com/android/performance-samples) to generate an app Baseline Profile; Compose apps typically gain 20-30% on cold start.+- **[medium] Agent handoff docs (HANDOFF.md, ANNEXE-ETAT.txt, docs/RESTE-A-FAIRE.md) describe 2.0.0 and mislead whoever picks up the repo** — `HANDOFF.md:1` (tools-docs, effort M)+ - Impact : Any agent or contributor told to 'skim HANDOFF first' (this audit's own instructions do) starts with wrong module locations, a wrong download architecture and wrong test and scenario counts. The rule that ANNEXE outranks HANDOFF turns a two-week-old snapshot into 'truth'.+ - Correction : Either refresh the files or retire them:+(a) Regenerate ANNEXE with a fixed handoff_state.sh (use the canonical test task, drop the podcast section, add a 'generated at version X' line, and refuse to run when HEAD is far from the stamped commit). Rewrite HANDOFF §2, §3 and §12 for the 7-module layout (api, api-spotify, host-android, host-cdp, extensions, extensions-cli, app) and the extension-based downloads. Update the counts in RESTE-A-FAIRE.+(b) Move the non-private parts (architecture map, invariants §4, the explored dead ends §6, the tool commands §9) into a tracked docs/ARCHITECTURE.md and tools/README.md, and keep only account/device details in the ignored file. Then the docs live with the code and are reviewed with it.+Add a 'last verified at <version>' line at the top of each file.+- **[medium] Network failures are shown as "nothing here" or a blank page (follow lists, New releases, Artist releases), with no retry** — `base/app/src/main/java/com/music/spotui/ui/screens/FollowListScreen.kt:67` (ui-ux, effort S)+ - Impact : Offline, on a flaky network, or when Spotify returns 429/5xx, the user is told a profile has no followers, that there are no new releases, or sees an empty releases page. This is false and gives no way to recover except leaving and reopening the page. It is common in a music app used on the move.+ - Correction : Use a 3-state result: null = loading, Result.failure = error, success = data. Keep the exception instead of `getOrDefault(emptyList())`, and on failure show `ErrorRetry(stringResource(R.string.page_load_failed)) { attempt++ }` (Classic) or `ImmersiveMessageState(page_load_failed, actionLabel = retry_button, onAction = { attempt++ })` (Immersive), with `attempt` used as a key of the LaunchedEffect / produceState. For Artist releases, add an `is Response.Error ->` branch calling `artistViewModel.loadArtistOverview(...)` again, which needs a force flag if the VM de-duplicates.+- **[medium] Category page: dead-end error in both looks (no retry, and the ViewModel blocks a reload); Classic shows errors and empty states with a fixed-height "Snackbar" component** — `base/app/src/main/java/com/music/spotui/ui/screens/CategoryScreen.kt:100` (ui-ux, effort S)+ - Impact : A Browse category that fails once stays failed until the user backs out and opens it again. The Classic message is a white toast-like bar that looks transient, has no button, and clips its 2nd line at larger font sizes or with long category names ("Couldn't load <title>"). The Library one covers the Local Files / Downloaded rows.+ - Correction : CategoryViewModel: add `fun retry() { genreKey = null; load(genre) }` (or a force flag). Both screens: ErrorRetry / ImmersiveMessageState with retry_button. Replace the `Snackbar` composable as a page state with the existing `ErrorRetry` (error) or a plain centered message (empty), or at least change `.height(48.dp)` to `.heightIn(min = 48.dp)` with padding. Library: put the error banner in the list (as a header item) rather than drawing it over the rows.+- **[medium] Raw exception messages shown to users (Immersive show page, Recently played), and Classic Recently played has no retry** — `base/app/src/main/java/com/music/spotui/ui/immersive/podcast/ImmersiveShowScreen.kt:197` (ui-ux, effort S)+ - Impact : French (or any) users see untranslated technical English such as "Unable to resolve host "api-partner.spotify.com": No address associated with hostname" or "java.net.SocketTimeoutException", and the Immersive podcast page and the Classic recents page are dead ends.+ - Correction : Never pass Throwable.message to the UI. Map to localized strings (page_load_failed; add a dedicated offline string if wanted) and log the message instead. ImmersiveShowScreen: `ImmersiveMessageState(stringResource(R.string.page_load_failed), actionLabel = stringResource(R.string.retry_button), onAction = { vm.loadShow(showId) })`. RecentlyPlayed (both): drop the %1$s argument or keep it only in the diagnostic log; Classic: add `var generation` as the LaunchedEffect key plus ErrorRetry, as the Immersive version already does.+- **[medium] Language picker offers 69 languages but ~53 are only ~13% translated, so picking one gives a mostly-English UI** — `base/app/src/main/java/com/music/spotui/data/AppLanguage.kt:14` (ui-ux, effort S)+ - Impact : A Japanese, Dutch, Swedish or Turkish user (or one who picks that language in the app) gets a patchwork UI: Spotify-derived labels in their language and 87% of the app in English. Arabic, Hebrew, Persian and Urdu users additionally get a mirrored (RTL) layout around English text. The picker suggests support that does not exist.+ - Correction : Split AVAILABLE into complete and partial languages, computed at build time or kept by hand: list only languages with at least 90% coverage, or show partial ones under a "Partially translated" header with a percentage. Add a unit test that parses res/values*/ and fails if a language in AVAILABLE drops below the threshold, which also catches regressions when keys are added. Optionally open the remaining locales on Weblate/Crowdin.+- **[medium] Immersive Settings has no Canvas switch and no "Canvas only on Wi-Fi" switch, although the Immersive player plays Canvas** — `base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt:514` (ui-ux, effort S)+ - Impact : An Immersive user who finds Canvas distracting, or wants to save mobile data and battery, cannot turn it off or restrict it to Wi-Fi without switching to the Classic look, finding the switch there, and switching back. The only Immersive escape is the global energy saver, which also disables other things.+ - Correction : Add two ImmersiveSwitchRow entries to the Immersive Display (or Data) page, mirroring Classic: `ImmersiveSwitchRow(stringResource(R.string.settings_item_canvas_title), checked = energy.canvasEnabled && !energy.policy.saverEnabled, enabled = !energy.policy.saverEnabled, onChecked = EnergySettings::setCanvasEnabled, detail = ...)` and the canvas_wifi_only row bound to set/isCanvasWifiOnly. The strings already exist and are translated. Consider a test that compares the preference setters reachable from both settings screens.+- **[medium] Update dialog cannot scroll (buttons cut off on short windows or large fonts) and cannot be closed while the APK downloads** — `base/app/src/main/java/com/music/spotui/App.kt:370` (ui-ux, effort S)+ - Impact : In split-screen (a phone half is about 350dp tall), landscape (Settings offers a landscape mode), or with font size 1.5-2x, the Column runs out of height: the Update button and "Not now" get 0 height and disappear, so the user cannot update from the card. During a download on a slow connection the whole app sits behind a modal card that cannot be dismissed for minutes (music plays, but browsing is impossible).+ - Correction : Wrap the dialog's Column in `Modifier.verticalScroll(rememberScrollState())`, or better, keep the buttons pinned: notes `Modifier.weight(1f, fill = false)` inside a Column with `heightIn(max = screenHeight * 0.9f)`. Same for SupportDialog. While busy, let Back and "Not now" hide the card (`release = null` without `updater.reset()`), keep the download running in the composition-independent scope (or WorkManager/a notification with progress), and show the card again when installing starts or fails.+- **[medium] Edge-to-edge without side insets: in landscape (a Settings option) or with a cutout, page content goes under the side navigation bar and the camera cutout** — `base/app/src/main/java/app/myspoti/MainActivity.kt:99` (ui-ux, effort M)+ - Impact : Phone in landscape with 3-button navigation: the nav bar sits on the right edge, over list rows' trailing menus, hearts and the page's right column. With a side camera cutout (most phones in landscape), the left of titles and covers is hidden. Lists, the Classic player and sheets are affected; only the bottom bars are inset.+ - Correction : Apply horizontal safe insets once at the root of the page area: in App.kt wrap MyNavHost (and PlayerOverlay/ImmersivePlayerOverlay content) with `Modifier.windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal))`, keeping backgrounds and headers drawn full-bleed by applying the padding to content rather than to backgrounds (or use `consumeWindowInsets` plus per-list `contentPadding`). Do the same in LookStep/Setup/Welcome.+- **[low] Gradle workers capped at 2 on every machine, including 4-vCPU CI runners and the 8-core dev box** — `base/gradle.properties:5` (build-size, effort S)+ - Impact : CI runs and local builds take longer than they need to. Independent module tasks (kotlin compile of :api/:api-spotify/:extensions, dexing, lint analysis) are serialized onto 2 workers.+ - Correction : Keep the conservative default for the laptop if wanted, but override it in CI: `env: GRADLE_OPTS: -Dorg.gradle.workers.max=4`, or add `--max-workers=4` to the gradlew calls. Locally, put `org.gradle.workers.max=6` in ~/.gradle/gradle.properties. Optionally replace the two release builds with AGP `splits { abi { isEnable = true; reset(); include("arm64-v8a", "armeabi-v7a"); isUniversalApk = false } }`, which produces both APKs from one invocation and keeps the per-ABI names.+- **[low] Lint is never run in CI and lintDebug currently fails with 1215 errors, most of them noise, which hides real Compose issues** — `base/app/build.gradle.kts:48` (build-size, effort S)+ - Impact : Compose correctness and performance bugs that lint already detects (recomposition reading StateFlow.value or scroll state directly, Locale read without observing it) go unnoticed, and regressions are never caught.+ - Correction : Add `lint { disable += setOf("MissingTranslation", "MissingQuantity"); baseline = file("lint-baseline.xml"); checkDependencies = true; abortOnError = true }`, generate the baseline once with `./gradlew :app:updateLintBaseline`, and run `:app:lintDebug` in the CI build job, uploading the HTML report on failure. Then fix the Compose items listed above (or hand them to the UI area).+- **[low] ML Kit code scanner registers an init ContentProvider and Firebase telemetry services that run for a rarely used feature** — `base/app/build.gradle.kts:115` (build-size, effort S)+ - Impact : A few ms of main-thread work on every cold start (component-registrar discovery). It is also telemetry to Google in an app whose data-saver promises no data use, though the logs are sent only after a scan.+ - Correction : Remove the provider with `<provider android:name="com.google.mlkit.common.internal.MlKitInitProvider" android:authorities="${applicationId}.mlkitinitprovider" tools:node="remove"/>` and call `com.google.mlkit.common.sdkinternal.MlKitContext.initializeIfNeeded(context)` just before `GmsBarcodeScanning.getClient`. Optionally disable the datatransport components the same way, after checking that the scan still works.+- **[low] No locale config: the per-app language list is hand-maintained and the app does not show in Android 13+ 'App languages'** — `base/app/src/main/java/com/music/spotui/data/AppLanguage.kt:14` (build-size, effort S)+ - Impact : On Android 13+ the system Settings > Apps > Myspoti > Language entry is missing, so the language can only be changed in the in-app menu. Adding a values-xx folder without editing the Kotlin list silently does nothing.+ - Correction : Add `androidResources { generateLocaleConfig = true; localeFilters += <the same 70 tags> }` and `res/resources.properties` with `unqualifiedResLocale=en-US`. Optionally build AppLanguage.AVAILABLE from `LocaleManager.getOverrideLocaleConfig`/the generated config, or keep the list and add a unit test that compares it with the res folders. localeFilters also removes library strings for locales the app does not support, which makes resources.arsc slightly smaller.+- **[low] Packaging leftovers: unused 4697x3126 album.jpeg, protobuf .proto files, kotlin_builtins, DebugProbesKt.bin, unused gql-schema.json and license files in the APK** — `base/app/src/main/res/drawable/album.jpeg:1` (build-size, effort S)+ - Impact : Small (about 100 KB compressed in release, 0.3 MB in debug), but it is free to remove.+ - Correction : Delete album.jpeg. In app/build.gradle.kts add `packaging { resources { excludes += setOf("google/protobuf/*.proto", "kotlin/**.kotlin_builtins", "DebugProbesKt.bin", "META-INF/*.version", "META-INF/**/LICENSE.txt", "spotify/gql-schema.json") } }` (the licences are already credited in THIRD_PARTY_NOTICES.md). Or move gql-schema.json out of src/main/resources into api-spotify/tools.+- **[low] Version catalog drift: unused entries, versions hard-coded outside the catalog, a beta material3 in stable releases** — `base/gradle/libs.versions.toml:15` (build-size, effort S)+ - Impact : Two sources of truth: versions drift between modules, and stale catalog entries (bouncycastle) look like real dependencies, which is how dead keep rules like proguard-rules.pro:13 survive. A pre-release Compose Material3 ships in the stable channel.+ - Correction : Move every coordinate into the catalog, delete the unused entries, and add Dependabot (gradle ecosystem) or the Renovate config. Use the BOM's material3 unless a beta API is really needed, and if so write the reason next to the pin.+- **[low] No Compose compiler stability config or metrics: collections and :api models are unstable to the compiler** — `base/app/build.gradle.kts:4` (build-size, effort S)+ - Impact : Extra recompositions of list rows when a flow re-emits equal data (library refreshes, player state ticks). Probably minor, but nobody can see it today because no metrics are produced.+ - Correction : Add `composeCompiler { stabilityConfigurationFiles.add(rootProject.layout.projectDirectory.file("compose-stability.conf")); if (providers.gradleProperty("composeReports").isPresent) { reportsDestination = layout.buildDirectory.dir("compose"); metricsDestination = layout.buildDirectory.dir("compose") } }`, with compose-stability.conf listing `kotlin.collections.*` and `app.myspoti.api.*` (immutable data classes). Then look at the *-composables.txt reports for non-skippable hot composables.+- **[low] Every process start (widget update at boot or after an update, CLI broadcasts) boots the full Web Player, extensions and downloads** — `base/app/src/main/java/com/music/spotui/di/Graph.kt:13` (cold-start, effort L)+ - Impact : A user with the home-screen widget gets a background process after every reboot and every update that loads open.spotify.com in a hidden WebView (about 150-250 MB of RAM, network, renderer CPU) and starts the extension sandboxes and download queues, with nothing on screen and nothing playing. Battery and data are wasted, and the cached process is a prime LMK target.+ - Correction : Together with the lazy-engine change: Graph.init keeps only the cheap set-up (prefs, caches, DataSaver). The engine, extensions and download resume start from an idempotent `Engine.ensure()` called by MainActivity (after the first frame), PlaybackService.onCreate/onGetRoot, MediaButtonReceiver handling and the widget's PREVIOUS/TOGGLE/NEXT actions. The widget's onUpdate only renders from the saved last-track prefs.+- **[low] Diagnostics and other small set-up work run on the main thread before the first frame** — `base/host-android/src/main/kotlin/app/myspoti/host/android/LastExit.kt:44` (cold-start, effort S)+ - Impact : Each item costs a few ms to a few tens of ms. Together they plausibly add 20-80 ms of main-thread time before the first frame, and more right after an ANR, when LastExit reads the trace.+ - Correction : Run LastExit.reportCrashFile/reportExitInfo and NetworkReport.logOnce on a background thread: install the uncaught-exception handler synchronously and post the reporting. Initialise Glide on a background thread right at start (`Executors`/Dispatchers.IO; Glide.get is synchronized, so the first image simply waits if it is not done). Read the device id and browser.json on IO, in parallel with the WebView creation. Consider merging the small prefs into one file, or read them on a background thread with a warm-up such as `getSharedPreferences(...)` from an IO thread at the top of onCreate.+- **[low] ML Kit's MlKitInitProvider runs on every process start for a rarely used QR scanner** — `base/app/build.gradle.kts:116` (cold-start, effort S)+ - Impact : ML Kit's context and Firebase-components discovery (PackageManager metadata lookup plus reflection) are paid on every cold start, including background starts, for a feature used rarely. This is a small but pure-waste item on the critical path.+ - Correction : Remove the provider with `<provider android:name="com.google.mlkit.common.internal.MlKitInitProvider" android:authorities="${applicationId}.mlkitinitprovider" tools:node="remove"/>` in the app manifest. Call `com.google.mlkit.common.sdkinternal.MlKitContext.initializeIfNeeded(context.applicationContext)` right before `GmsBarcodeScanning.getClient(...)` in PlayerSheets.kt.+- **[low] The encryption migration thread opens every downloaded file on every launch** — `base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt:109` (cold-start, effort S)+ - Impact : N file opens and reads at every cold start (N = downloads), competing for flash I/O with the WebView's cache, Glide and the screen caches during the busiest second. It also holds folderLock, which other offline operations wait on.+ - Correction : Store a 'migrated' flag (or an `encrypted` field per OfflineTrack in the index, set when a download finishes encrypted) and skip the thread entirely when everything is already encrypted. At minimum, start the thread after a delay (for example 30 s after launch).+- **[low] The profile (avatar, name, id) is not kept across launches: placeholder avatar at each cold start and waits on a me() call** — `base/app/src/main/java/com/music/spotui/data/api/ProfileCache.kt:38` (cold-start, effort S)+ - Impact : On every cold start the home header shows an orange dot instead of the user's avatar for the whole page boot plus one request (several seconds on slow phones). The cached Home is otherwise complete, so this is the visible gap. Queued likes also wait for the id.+ - Correction : Persist name, imageUrl and id (prefs or a small JSON file) when me() succeeds, and load them in ensure() before the network call so the first frame shows the avatar. Still call me() after ready to confirm, and clear the stored copy in SessionActions logout/sessionLost. The account checks (OfflineAccounts.claim, LibraryOutbox) should keep using the confirmed id only.+- **[low] Many separate OkHttpClients are created, including at startup (one of them unused)** — `base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt:31` (cold-start, effort S)+ - Impact : No connection or TLS-session reuse between components talking to the same Spotify hosts (for example the updater's and the API's open.spotify.com / *.spotify.com connections). The unused MediaProxy client adds construction cost on the main thread at startup.+ - Correction : Create one root OkHttpClient in host-android (or app) and derive the others with `root.newBuilder()...build()`, which shares the pool and dispatcher. Pass it to SpotifyApi(http = root) and GqlOpsUpdater(root). Build MediaProxy's client lazily (`by lazy`) or not at all while ENABLED is false. Keep separate clients only where isolation is intended (ControlRelay's identity-specific stack, extension SafeNet).+- **[low] `Modifier.pressable` is built from three `composed {}` modifiers and launches a coroutine per row (about 100 call sites, most list rows)** — `base/app/src/main/java/com/music/spotui/ui/components/Motion.kt:46` (compose-classic, effort M)+ - Impact : Each lazy item that scrolls into view pays for three composed materialisations, a coroutine launch, an Animatable and extra slot-table groups, even if it is never pressed. Composed modifiers are also never equal, so the modifier chain is re-applied on every recomposition of the row. This cost appears in scroll and fling frames.+ - Correction : Implement the press scale as a Compose `IndicationNodeFactory` (ScaleIndication(pressedScale)) whose node animates `scale` in draw via `drawWithContent { scale(s) { drawContent() } }` or a layer. Then use `Modifier.clickable(interactionSource = null, indication = ScaleIndication(0.96f), onClick = ...)`. Since Compose 1.7, clickable creates the indication node lazily on first press, so rows cost nothing extra until touched. Turn `pressHint` into a `Modifier.Node` (`SuspendingPointerInputModifierNode`) or a plain `pointerInput` without `composed`. Keep the `pressable(...)` signature so call sites do not change.+- **[low] Search results and other mixed lazy lists have no keys or contentType** — `base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt:332` (compose-classic, effort S)+ - Impact : When typing changes the result set, index position i often switches kind (Song to Artist). The composition at that index is thrown away and rebuilt, the Glide image at that slot cross-fades from the previous result's cover, and scroll restoration is index-based. Without contentType, the reuse pool hands heavy header or carousel slots to track rows and the other way round, so reuse fails and items are composed from scratch while scrolling.+ - Correction : Search: `items(mixed.size, key = { i -> mixed[i].key }, contentType = { i -> mixed[i]::class })`, with `SearchRow.key` such as "song:"+spotifyTrackId (handle duplicates with the existing uniqueKeys helper from HomeScreen). Do the same for recents, profiles, shows and episodes. ContextScreen: `contentType = "track"` on `itemsIndexed(listed...)` and `"rec"` on recommendations. Home: `contentType = { "carousel" }` on the carousel items.+- **[low] MeshGradientBackground reads 5 colour animations in composition and recomputes HSL tuning on every frame of a palette change** — `base/app/src/main/java/com/music/spotui/ui/look/MeshGradient.kt:126` (compose-classic, effort S)+ - Impact : For 1.4 s after each track change in the Immersive player, an extra composition every frame on top of the blurred full-screen redraw, at the same moment as the cover and title transitions.+ - Correction : Keep the `State<Color>` objects (`val anims = tuned.mapIndexed { i, c -> animateColorAsState(c, ...) }`) and read `anims[i].value` inside the Canvas `onDraw`. Draw the base colour with `drawRect(base.value)` instead of `.background(baseColor)`. Compute `tuned` with `remember(palette) { ... }`. Hoist the `anchors` and `speeds` lists out of the draw lambda as constants.+- **[low] FitText shrinks over several frames (one recomposition and layout per 10% step) and stays invisible until done** — `base/app/src/main/java/com/music/spotui/ui/components/FitText.kt:37` (compose-classic, effort S)+ - Impact : A long playlist or album name needs up to 4 shrink steps (26 to 18sp). Each step is a state write during layout, then a recomposition and text layout on the next frame. The title therefore appears 3-4 frames after the rest of the header, during the page-in transition.+ - Correction : Use Compose's single-pass auto-size: `BasicText(text, style = ..., maxLines = maxLines, overflow = TextOverflow.Ellipsis, autoSize = TextAutoSize.StepBased(minFontSize = minSize, maxFontSize = fontSize, stepSize = 1.sp))` (foundation 1.8+, available with BOM 2026.06). It measures in one layout pass with no visibility gate.+- **[low] Artist page filters the whole liked-songs cache on the main thread** — `base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt:181` (compose-classic, effort S)+ - Impact : With several thousand liked songs, each artist-page open does an O(n) scan with allocations on the UI thread, during or just after the page transition.+ - Correction : `likedByArtist = withContext(Dispatchers.Default) { all.filter { ... } }`. Optionally index LikedCache by artist id once (Map<String, List<SongsModel>>) when it loads, so every artist page is an O(1) lookup.+- **[low] Each player open makes several AudioManager binder calls and registers several device callbacks for the same audio route** — `base/app/src/main/java/com/music/spotui/ui/components/AudioRoute.kt:66` (compose-classic, effort S)+ - Impact : Opening the full player (whose first composition the overlay already budgets two frames for) adds about 4 binder round trips plus extra callbacks for one value the mini player already knows. It is small, but it lands in the player's heaviest frame.+ - Correction : Make the route an app-wide state: one `AudioRouteMonitor` object with a `mutableStateOf<AudioRoute>`, started once (app start or the first subscriber, with ref-counting), with one AudioDeviceCallback. `rememberAudioRoute()` then just returns `AudioRouteMonitor.route`.+- **[low] Bottom bar writes navigation state during composition; TabNavigation is a new object every recomposition** — `base/app/src/main/java/com/music/spotui/ui/navigation/MainBottomNavigation.kt:222` (compose-classic, effort S)+ - Impact : A backwards write on each tab change forces an extra recomposition pass. The tab row and bar recompose on every track change. Minor, but on the always-visible chrome.+ - Correction : Replace the write with `LaunchedEffect(currentRoute) { if (currentRoute in TabRoutes) selectedTab.value = currentRoute }` or a `derivedStateOf` on the back-stack entry. Use `remember(navController) { TabNavigation(navController, selectedTab) }` with currentRoute read through a State. Read `hasTrack` as `val hasTrack by remember { derivedStateOf { Graph.currentSongState.title.value.isNotBlank() } }`, so it only changes when it flips.+- **[low] Main-thread loop wakes every second for the app's lifetime, even with no extension installed** — `base/app/src/main/java/com/music/spotui/extensions/Extensions.kt:1154` (concurrency-memory, effort S)+ - Impact : 86,400 main-looper wakeups per day while the process lives, which PlaybackService keeps alive during playback and the 1-minute pause grace. A small but constant battery and CPU cost that keeps the process from going idle with the screen off.+ - Correction : Start the 1 s loop only while some runtime listens to EVENT_PLAYBACK and something plays. Drive it from a `combine(listenersFlow, SongPlayer playing state)` with `collectLatest { if (active) while (true) { delay(1000); ... } }`, so it suspends with no timer when inactive. Do the same for watchStatus: wait on a flow of 'foreground or playing' instead of polling every 60 s.+- **[low] Home-screen widget downloads covers with its own OkHttp client, past the data saver** — `base/app/src/main/java/com/music/spotui/widget/NowPlayingWidget.kt:62` (concurrency-memory, effort S)+ - Impact : With a widget on the home screen, every song change on mobile data downloads a cover even with the data saver on, breaking the promise made in Settings. The extra client also misses the shared HTTP/2 connection pool and Glide's disk cache, so the cover is fetched twice (player and widget).+ - Correction : Load the widget bitmap through Glide (`Glide.with(app).asBitmap().load(coverUrl).override(160).submit().get()` on IO), which goes through DataSaverGlide and the shared disk cache. Or skip the network when `DataSaver.active` and use only a local/cached cover. Decode with `inSampleSize` if a raw decode stays.+- **[low] Playback events are delivered to extensions one after another, so one busy or slow listener delays every other listener** — `base/app/src/main/java/com/music/spotui/extensions/Extensions.kt:1142` (extensions, effort S)+ - Impact : Scrobblers and stats extensions get start/end events late (a backlog of several seconds), and those that rely on timing can mis-attribute plays. There is also a 1 Hz main-thread wakeup even with no extensions installed.+ - Correction : Give each extension its own event channel and consumer coroutine (or launch per extension as watchTracks already does), keeping FIFO per extension. Drop the dead onFailure branches, or make emit return a Result. Suspend the polling loop on a StateFlow ('some runtime listens to playback') instead of waking every second.+- **[low] sources.race throws away a lossless download lane if it also lists a lossy fallback, and returns nothing when only lossy copies exist** — `base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt:527` (extensions, effort S)+ - Impact : Downloads in 'cd'/'hi-res' quality fail for songs a source only has as MP3/AAC, and a lane offering FLAC with an MP3 backup can lose to a slower lane.+ - Correction : Require `files.first().lossless` (the list is best-first) instead of `files.none { !it.lossless }`. Keep the best lossy answer as a fallback, and return it after all lanes have finished if no lossless one arrived. Document this in SOURCE-PIPELINES.md.+- **[low] Every storage.set rewrites the whole store file (up to 512 KB) on the script's own time; long log lines make every log line rewrite the log file** — `base/app/src/main/java/com/music/spotui/extensions/ExtensionRegistry.kt:275` (extensions, effort S)+ - Impact : Extensions that cache tokens or per-song lookups in storage spend milliseconds to tens of ms of disk I/O inside a 15 s audio budget on every request. Disk writes grow on cheap eMMC phones. Mostly invisible, but measurable per lookup.+ - Correction : FileStore: keep a running size counter, mark dirty, and write behind (coalesced, about 500 ms after the last change, flushed on runtime close and in onTrimMemory/onStop). ExtensionLog: also trim by characters (drop the oldest lines until under maxChars/2) so a rewrite happens rarely, and reuse one DateTimeFormatter.+- **[low] Audio and download answers of extensions without a `media` field may point to any public host, outside the declared network hosts** — `base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt:161` (extensions, effort S)+ - Impact : A minor exfiltration and tracking channel that bypasses the declared host list. It needs audio.source or download.source, and the fetch is a GET to a public address only.+ - Correction : Plan a deprecation: for manifests with `apiVersion` ≥ 2 (or after a date), require `media.hosts` for source answers. Meanwhile, say 'may stream from any website' in the install prompt for source extensions without `media`, and log the first answer to an undeclared host.+- **[low] http.all can hold 4 × 5 MB bodies, each copied several times across Kotlin and JS, inside one hook: an OOM risk for the whole app** — `base/extensions/src/main/kotlin/app/myspoti/extensions/Host.kt:170` (extensions, effort M)+ - Impact : About 150-200 MB of transient heap in the worst case. On a 256 MB heap phone this can crash the app instead of only turning the extension off.+ - Correction : Lower the per-response cap for http.all (for example 2 MB each, 8 MB total). Pass the body to JS as its own string argument instead of embedding it in the JSON envelope (a host function returning `{status, headers}` plus a separate `body` string). Optionally reject when the summed Content-Length of a batch is over budget.+- **[low] Docs: API.md does not mention sources.race or download/audio.transform, and SOURCE-PIPELINES.md says losing workers are interrupted when the script actually runs until its deadline** — `docs/extensions/SOURCE-PIPELINES.md:48` (extensions, effort S)+ - Impact : Extension authors find neither the race API nor the transform features in the main reference. Their mental model of lane cancellation is wrong, which matters for quota use.+ - Correction : Add sources.race and the transforms to the features table and to section 3 of API.md, linking SOURCE-PIPELINES.md. Correct the cancellation sentence, or make it true by implementing the interrupt check in observeInstructionCount (see the first finding).+- **[low] Test gaps: cancellation, archive limits, early exit and stale-probe latency are untested; the CLI's cancelAtMs simulates a timeout, not the app's cancellation** — `base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Scenario.kt:248` (extensions, effort S)+ - Impact : The regressions behind the high findings above can come back unnoticed, and extension authors cannot measure how much their script costs at startup or per race.+ - Correction : Add the JVM tests listed in each finding's how_to_measure. Make Scenario's cancelAtMs interrupt the calling thread (as runInterruptible does) and then time the next step. Print `compiled in N ms, top level in M ms` in `myspoti-ext run`/`check`.+- **[low] In-memory page caches are bounded by count, not size, or not bounded at all (ArtistCache, CanvasCache, library folders)** — `base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt:120` (network-data, effort S)+ - Impact : Browsing a few large playlists can pin tens of MB (12 × 5,000 songs × about 800 B is about 48 MB) in a process that also hosts a WebView. On 3-4 GB devices this raises GC pressure and the chance the app is killed in the background, which also kills playback. The artist and canvas maps grow for the whole session (hours with autoplay).+ - Correction : Bound `recent` by total tracks: evict the eldest while the sum of `tracks.size` is over about 5,000, or store only pages of 1,000 songs or fewer (bigger ones rely on PlaylistFresh/ScreenCache). Make ArtistCache an access-ordered LinkedHashMap with removeEldestEntry over 10 entries (synchronized), and CanvasCache over 200. Clear `folders` together with libraryRoot. Optionally implement `ComponentCallbacks2.onTrimMemory` to clear these maps.+- **[low] The whole Liked Songs list is re-serialized and rewritten on every Liked page open and twice per like/unlike, even when nothing changed** — `base/app/src/main/java/com/music/spotui/data/api/Api.kt:850` (network-data, effort S)+ - Impact : For a 5,000-song library (a JSON file of a few MB), every like or unlike and every visit to Liked Songs spends CPU on the single ScreenCache IO thread. That delays other ScreenCache writes queued behind it (home, album pages) and wears flash, all for an unchanged list most of the time.+ - Correction : Write only when the merged list differs: compare `merged.size` and the first 50 ids with `known`, or keep a hash. Skip the second mergeLikedHead when the first already contained the change (the tapped id present or absent as expected).+- **[low] The profile (name, avatar) is not persisted: avatar and owner name are blank after every cold start until the Web Player is ready** — `base/app/src/main/java/com/music/spotui/data/api/ProfileCache.kt:218` (network-data, effort S)+ - Impact : On every launch, the profile avatar in the top bar and the Liked Songs header owner stay empty for the several seconds it takes the hidden page to become ready, then pop in. The disk caches already make the rest of Home paint instantly, so this blank stands out.+ - Correction : Persist name, imageUrl and id (SharedPreferences, cleared in `clearSession()` and at logout via SessionActions). Seed them at startup and refresh in the background as today (stale-while-revalidate). The Glide disk cache already holds the avatar image.+- **[low] Regexes compiled on every call in GraphQL and home-feed hot paths, and path strings split for every JSON field read** — `base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt:298` (network-data, effort S)+ - Impact : A few ms of avoidable CPU and garbage per home feed and per large playlist mapping. Small on its own, but it adds to the main-thread parsing above.+ - Correction : Hoist both regexes into `private val` constants, or replace isMutation with a `startsWith` over a prefix set. In JsonPaths, cache split paths (`ConcurrentHashMap<String, List<String>>`) or add an `at(vararg keys)` overload for hot mappers.+- **[low] Dead data-layer code and unused dependencies: five Ktor artifacts, the LikedSongs per-key prefs, and Spotui-era Api methods with no callers** — `base/app/build.gradle.kts:154` (network-data, effort S)+ - Impact : Longer builds and a larger dependency surface. Ktor plus kotlinx-io are resolved, dexed in debug builds and must be shrunk away by R8. Several hundred lines of unmaintained data paths (getShowEpisodes duplicates getShowPage) confuse future work and audits.+ - Correction : Remove the five Ktor lines (and the proguard -dontwarn, and the 'Ktor' mention in DataSaver.interceptor's doc). Delete LikedSongPref.kt and the unused imports, and add the 'LikedSongs'/'LikedSongsFromSpotify' prefs files to the logout cleanup or a one-time delete. Delete the uncalled AppRepository/Api methods.+- **[low] README 'For developers' says the project is 'split in two' and lists 3 of 7 modules; the tools/ suite and debug receivers are undocumented in the repo** — `README.md:154` (tools-docs, effort S)+ - Impact : Contributors don't know the playback battery exists or that it is the required gate for engine changes (HANDOFF §4.6), how to run it, or which module to touch. One doc path points to a file that does not exist.+ - Correction : Rewrite the developer section as a 7-row module table (module, role, depends on). Add tools/README.md: one line per script, prerequisites (debug build app.myspoti.dev signed in, adb, a single device or ANDROID_SERIAL, the test playlist), PT_SAFE and PT_HEADLESS, and the TestControlReceiver commands (point to its KDoc). Link it from CONTRIBUTING ('engine/page changes must pass tools/playback_test.py'). Fix the CAPABILITIES.md path and add Inter to the README credits.+- **[low] qa.py --perf/--anim: renderer CPU may be another app's, and the mini-player tap uses fixed screen fractions** — `tools/qa.py:100` (tools-docs, effort S)+ - Impact : Perf numbers can be attributed to the wrong process or the wrong screen without any warning, which makes before/after comparisons unreliable, especially across the two looks.+ - Correction : Renderer: find the isolated process hosted by the app via `dumpsys activity processes` (the WebView sandboxed_process record whose hosting app is app.myspoti.dev), or list the renderer PIDs before and after the app starts. Player: add a debug TEST cmd `openplayer` (navigate to the player through the app's own nav), or set `Modifier.semantics { testTagsAsResourceId = true }` on the root and `testTag("miniPlayer")`, then tap by uiautomator lookup. Verify the screen before measuring (e.g. uitrace or a dumpsys window title check).+- **[low] cdp.py picks whichever Myspoti package appears first and relies on a stale '1280x800 virtual display' heuristic** — `tools/cdp.py:85` (tools-docs, effort S)+ - Impact : `tools/cdp.py --headers` (identity and header checks) can report the beta's traffic while you think you are inspecting the dev build. During sign-in, a second open.spotify.com page could be picked.+ - Correction : Add `--package` (default $MYSPOTI_PACKAGE or app.myspoti.dev, as myspoti-cli does) and match only that process. Drop ':engine' (no android:process is declared). Pick the engine page by something the bridge sets: evaluate `!!window.Myspoti` on each candidate, or have player-bridge.js set a recognizable `document.title` marker. Share one page_socket() between cdp.py and playback_test.py.+- **[low] playback_test.test() sends every int as --el (long), but the receiver reads crossfade/uitrace seconds with getIntExtra, so the value is silently ignored** — `tools/playback_test.py:297` (tools-docs, effort S)+ - Impact : `pt.test("crossfade", secs=6)` sets crossfade to 0, and `pt.test("uitrace", secs=120)` traces 30 s. Any new scenario that uses the generic helper gets wrong conditions without an error, which is a trap the pilot author already fell into.+ - Correction : In the receiver, read both types: `val secs = intent.extras?.get("secs")?.let { (it as? Number)?.toInt() } ?: default` (debug-only code). Alternatively let test() take explicit types, e.g. `test('crossfade', secs=('ei', 6))`. Then remove the hand-built broadcasts in pilot.py.+- **[low] Still unfixed from the 2026-10-18 audit: seek/previous scenarios don't wait out an ad first and fail spuriously** — `tools/playback_test.py:360` (tools-docs, effort S)+ - Impact : The gate shows intermittent red on free accounts when a real ad slips through, which teaches people to ignore failures.+ - Correction : Add at the start of each scenario (or once in main before fn(r, ctx)): `r.wait_out_ad(probe())`. Make probe-based expectations (`exp`, `cur`) only after that.+- **[low] About 14 GB of ignored clutter in the main checkout: 61 stale agent worktrees, APK dumps, session captures and source zips (one contains a release APK)** — `.gitignore:1` (tools-docs, effort S)+ - Impact : Disk use and slower IDE indexing and grep (rg/Studio walk ignored dirs unless configured). Logs containing session data sit inside a directory that gets zipped and shared (the two src zips show it has happened). Stale worktrees keep branches and Gradle caches alive.+ - Correction : Point tool outputs to a cache dir outside the repo (`MYSPOTI_QA_DIR`, default ~/.cache/myspoti-qa) and prune runs older than N days in qa.py and pilot.py. Run `git worktree prune` and remove the merged agent worktrees and branches (`git branch --merged main`). Delete or move the src zips (a source archive should come from `git archive`, which never includes ignored files). Run `git gc`. Move PROMPT-*.md and REDDIT-*.md to a notes folder outside the repo.+- **[low] Unreferenced 4697x3126 progressive JPEG in res/drawable (292 KB), shipped in every debug APK** — `base/app/src/main/res/drawable/album.jpeg:1` (tools-docs, effort S)+ - Impact : Dead weight in the repo and in debug APKs, and a trap if someone later reuses it as a placeholder.+ - Correction : Delete it, or if a placeholder is wanted, replace it with a 512 px WebP (drawable-nodpi). Optionally enable lint's UnusedResources check in CI to catch the next one.+- **[low] Keystore and secret patterns are ignored only under base/, not at the repo root** — `.gitignore:1` (tools-docs, effort S)+ - Impact : A keystore or .env dropped at the root (e.g. by an agent preparing a signed build or copying env vars) would show as an ordinary untracked file and could be committed with `git add -A`. Leaking the stable signing key would let anyone ship updates that install over users' apps.+ - Correction : Add to the root .gitignore: `*.jks`, `*.keystore`, `*.p12`, `*.pem`, `keystore/`, `.env`, `*.env`, `keystore.properties`. Optionally add a pre-commit or CI check that rejects these extensions.+- **[low] Extensions "activity" lines are English sentences built in Kotlin, shown untranslated in both looks** — `base/app/src/main/java/com/music/spotui/extensions/Extensions.kt:652` (ui-ux, effort M)+ - Impact : French, German and other users see "Skipped by Foo" or "Audio of <song> from <ext>" under a translated "Activity" header on the Extensions page, next to translated "Turn off" buttons.+ - Correction : Store structured entries (`ActivityEntry(area, extId, kind: enum, args: List<String>)`) instead of text. Format at display time with new string resources (e.g. extension_activity_skipped = "Skipped by %1$s", extension_activity_audio = "Audio of %1$s from %2$s") translated for the 9 complete locales. Keep the English text only for the Logbook.+- **[low] New releases: raw API release type ("Album", "Single") and ISO date, plus hard-coded "h/min" duration units** — `base/app/src/main/java/com/music/spotui/ui/screens/DiscoverScreens.kt:115` (ui-ux, effort S)+ - Impact : In the 9 fully translated locales the release subtitle stays English and shows a machine date; episode durations use Latin "min" in Russian or Chinese (e.g. Russian should be "мин").+ - Correction : Map type to R.string.album_type_* (fallback: the raw value). Format the date with `DateFormat.getDateInstance(DateFormat.MEDIUM, locale)` or DateUtils.formatDateTime. For durations use a plural/format resource or `android.icu.text.MeasureFormat` (Measure(min, MeasureUnit.MINUTE), FormatWidth.SHORT).+- **[low] Keyboard covers text fields: edge-to-edge disables adjustResize and extension settings fields have no imePadding** — `base/app/src/main/java/com/music/spotui/ui/screens/ExtensionDetail.kt:437` (ui-ux, effort S)+ - Impact : Tapping an API key or server URL field near the bottom of an extension's page opens the keyboard over the field. The scroll container still thinks it is fully visible, so it is not brought into view and the user types blind or must close the keyboard to check.+ - Correction : Add `.imePadding()` (or `windowInsetsPadding(WindowInsets.ime)`) to the scrolling column of ExtensionDetail/ImmersiveExtensionDetail and to other pages with inline fields. Alternatively add `Modifier.imeNestedScroll()` and let BringIntoView work against the reduced viewport. For lists under search fields (Search tab, Library filter) set `contentPadding` bottom = max(bars, ime).+- **[low] Back does not close the Library search filter or the Immersive "find in list"; the filter persists and the user leaves the page** — `base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt:140` (ui-ux, effort S)+ - Impact : With the keyboard closed, Back from an open Library filter leaves the Library tab (to Home), and Back from "find in playlist" leaves the playlist. Returning to Library restores the still-active filter (rememberSaveable plus tab saveState), so the library looks incomplete. Spotify and most apps close the search field first.+ - Correction : Add `BackHandler(enabled = searchActive) { searchActive = false; searchQuery = "" }` in both Library screens and `BackHandler(enabled = finding) { finding = false; find = "" }` in ImmersiveContextScreen (Classic ContextScreen's field is always visible, but it could clear a non-empty query on Back the same way).+- **[low] Immersive mini player replaces pause with a spinner while buffering, so a stalled stream cannot be paused from it** — `base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersiveMiniPlayer.kt:139` (ui-ux, effort S)+ - Impact : On a bad network (tunnel, ad break loading, extension source resolving) the user cannot stop playback from the capsule. They must open the full player or the notification, and the intent "stop now" (e.g. in a meeting) is delayed.+ - Correction : Keep the play/pause target clickable while buffering. Draw the spinner as a ring around the pause glyph (or under it) instead of replacing it. Same review for the full Immersive player's play button if it does the same.+- **[low] Immersive lyrics: a failed fetch (offline or timeout) shows "No lyrics for this track" with no retry** — `base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricsPanel.kt:180` (ui-ux, effort M)+ - Impact : Offline, or when providers time out, Immersive users are told the song has no lyrics, and the negative result is cached for a while, so reopening does not help. Classic users can force a reload.+ - Correction : Add a State.Failed (or a flag on NotFound) set when every provider failed for network reasons, and show "Couldn't load the lyrics" plus a Try again button (`vm.load(track, force = true)`) in ImmersiveLyricsPanel. Do not record a Miss for network errors.+- **[low] Accessibility: unlabeled 24dp back arrow in the "Saved in" sheet, and a few controls below 48dp that sit next to other click targets** — `base/app/src/main/java/com/music/spotui/ui/components/SavedInSheet.kt:130` (ui-ux, effort S)+ - Impact : TalkBack users cannot identify the folder back control. On the Immersive player, taps meant for Like land on More and the reverse, and the search clear X is easy to miss in favour of placing the cursor.+ - Correction : SavedInSheet: `contentDescription = stringResource(R.string.accessibility_navigate_back)` and use the existing `wideClickable(...)` helper (WideTap.kt) or `minimumInteractiveComponentSize()`. CircleGlyph: keep the 34dp disc but give the clickable a 44-48dp box (`Modifier.size(44.dp).clickable{...}` wrapping the disc) or increase the spacing to 16dp. Clear buttons and chevrons: wideClickable. Replace `contentDescription = ""` with null.+- **[low] Fixed-height text containers clip at large font sizes (Home shortcut tiles, the 'Snackbar' state bar)** — `base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt:367` (ui-ux, effort S)+ - Impact : Users with large text (a common accessibility setting) see the second line of Home shortcut titles cut in half, and error messages clipped.+ - Correction : Use `heightIn(min = 48.dp)` instead of `height(48.dp)` for the tiles (keep the 48dp cover square with `Modifier.size(48.dp)` aligned to the top, or make the row height follow the text). Same for Snackbar, or replace it as proposed in the Category finding.++### Réfuté (8)++- **[high] The hidden page boots on Spotify's home route (about 7000 nodes and 190 images) only to be parked on /preferences** — `base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt:476` (cold-start, effort S)+ - Réfuté : The code paths are as described. `load()` (WebPlayerHost.kt:429), `reload()` (l.484), `retryPlayerPage` (l.533) and `attach()` (l.701) all call `view.loadUrl(playerRoot())`, which is the learnt `/intl-xx/` home root. The bridge parks the page on `/preferences` only from `boot()` (player-bridge.js:80+- **[high] A second 'next' within 2 s of the previous skip is held until 2 s have passed: up to ~1.6 s added to the most common browsing gesture** — `base/app/src/main/java/com/music/spotui/di/SongPlayer.kt:1556` (playback, effort S)+ - Réfuté : The finding describes the code correctly but not the cost and benefit. In base/app/src/main/java/com/music/spotui/di/SongPlayer.kt:1556, a 'next' only goes out at once when `now - burstAt > SKIP_BURST_MS && sinceSent >= MIN_SKIP_GAP_MS`. Otherwise it is posted with `maxOf(SKIP_BURST_MS, MIN_SKIP_GAP+- **[medium] Liquid Glass page ticker: every glass surface re-runs blur and lens every frame for 3 s after any page attach, then once a second forever, even under the opaque full-screen player** — `base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/LayerBackdropModifier.kt:139` (compose-immersive, effort M)+ - Réfuté : I refuted the finding as a medium-severity issue. It is mostly a deliberate, documented trade-off. The one new part is real, but it costs very little.++What the code really does (LayerBackdropModifier.kt:139-151):+- `onAttach` starts a loop that bumps `moves` on every frame for SETTLE_MS = 3 s.+- Af+- **[medium] The transport lock is held while waiting for the page's state, so a pause, skip or new pick right after a pick waits for that state to arrive** — `base/app/src/main/java/com/music/spotui/di/SongPlayer.kt:993` (playback, effort M)+ - Réfuté : The mechanism described is accurate. In base/app/src/main/java/com/music/spotui/di/SongPlayer.kt, transport() (lines 901-977) holds transportLock while block() runs. The block calls playChecked() (990-999), which waits up to PLAY_CHECK_MS on `api.player.state.first { it?.item?.uri == itemUri || !isL+- **[low] Scrubber time labels recompose and re-layout 15 times a second although they change once a second** — `base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerControls.kt:149` (compose-immersive, effort S)+ - Réfuté : The mechanism is real, but the impact is too small to be worth a fix, and part of the claim is wrong.++1. What is true. `PlayerScrubber` (`base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerControls.kt:133`) uses `rememberFrameClock(..., fps = 15)`. `ScrubTimes` (lines 149-172) reads+- **[low] Relayed requests do a JSON parse and a synchronous file write on the UI thread before they are even sent** — `base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt:168` (playback, effort S)+ - Réfuté : The description of the code is accurate. exposeToPlayer (PlayerChannel.kt:20-28) registers a WebMessageListener, so onMessage runs on the main thread. ControlRelay.send() line 168 calls `devices.sent(url, body)` for every non-registration, non-DELETE relayed request. PlayerDeviceRecord.sent() (lines+- **[low] Extension streams use ExoPlayer's default start buffer (1 s, 2 s after a rebuffer), while the video player uses 0.4 s; the crossfade copy must be READY within 1.5 s** — `base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt:64` (playback, effort S)+ - Réfuté : The facts in the finding are correct, but the claimed impact is overstated by about ten times.++What checks out:+- `LocalPlayer.build()` (base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt:64-74) sets no LoadControl, so it uses Media3's DefaultLoadControl (1000 ms to start, 2000 ms after a re+- **[low] Every skip or pick while music is audible is delayed by a fixed 120 ms fade hold (owner trade-off, worth a shorter curve)** — `base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt:1469` (playback, effort S)+ - Réfuté : The code does what the finding says, but this is not a defect. It is a recent, deliberate and documented owner trade-off, and the proposed fix would undo behaviour the app relies on.++1. **The code matches the claim, but the real wait is shorter.** In base/api-spotify/src/main/kotlin/app/myspoti/spo+