From 8ec1866ec483f39ce7b0c9aac21d1eddffdf5bcd Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:47:51 +0000 Subject: [PATCH 01/41] chore(comments): describe what records() returns Its doc comment only defined a session; it now names the records the function returns as well. Comments only; no code changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- app/analytics/history.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/app/analytics/history.ts b/app/analytics/history.ts index 3f68d38..62d7cd4 100644 --- a/app/analytics/history.ts +++ b/app/analytics/history.ts @@ -519,7 +519,11 @@ export interface Records { avgSessionMs: number; } -/** Sessions are runs of plays with gaps under 30 minutes. */ +/** + * Records in the range: the biggest day, the longest session, the song streamed most in one day, + * and how many sessions there were and their average length. A session is a run of plays with + * gaps under 30 minutes. + */ export function records(ds: Dataset, range: Range = {}): Records { const [s, e] = rangeIndices(ds, range.from, range.to); if (e <= s) return { biggestDay: null, longestSession: null, obsession: null, sessions: 0, avgSessionMs: 0 }; From 8382ccf7d2480dc5639e190b1490c81fe61f1f78 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:48:00 +0000 Subject: [PATCH 02/41] chore(comments): correct and tidy comments in UI components The charts' comments called the tooltip their live region; ChartStatus is, and the tooltip is aria-hidden. Comments that told how a layout once broke ("it was cut to six letters", "the row snapped 16 px") now say what the code guarantees. Comments only; no code changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- app/components/charts/Charts.tsx | 6 +++--- app/components/immersive/Immersive.tsx | 4 ++-- app/components/media/Cards.tsx | 4 ++-- app/components/media/TrackRow.tsx | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/app/components/charts/Charts.tsx b/app/components/charts/Charts.tsx index 17cbbe8..5311c5f 100644 --- a/app/components/charts/Charts.tsx +++ b/app/components/charts/Charts.tsx @@ -213,8 +213,8 @@ export function AreaChart({ const peak = points.reduce((best, p) => (p.v > best.v ? p : best), points[0] ?? { t: 0, v: 0 }); return ( - // The tooltip is the chart's live region, so it sits beside the image: an image's contents - // are hidden from screen readers, and what changes there is never read out. + // The live region (ChartStatus) sits beside the image: an image's contents are hidden from + // screen readers, and what changes there is never read out.
setActive(null)}>
= { cover: "Full-screen player", lyr /** * Song title, artists and album, sized for across the room. Under the cover (phones, and the Both - * view) it sits in the cover's shadow, which is lighter on a light scheme: at full strength it took - * the status line there under 4.5:1. + * view) it sits in the cover's shadow, which is lighter on a light scheme so the status line keeps + * 4.5:1 there. */ function TrackTitle({ track, playing, compact }: { track: Track; playing: boolean; compact?: boolean }) { const artists = track.artists.map((a) => a.name).join(", "); diff --git a/app/components/media/Cards.tsx b/app/components/media/Cards.tsx index f0fe3b5..81cad71 100644 --- a/app/components/media/Cards.tsx +++ b/app/components/media/Cards.tsx @@ -142,8 +142,8 @@ export function Shelf({ children, label }: { children: ReactNode; label: string const items = Children.toArray(children); return ( // Scroll padding as wide as the gutter: snapping lines the first card up with the page's - // edge. Without it the row snapped 16 px on loading, the first card against the screen's - // edge, and the scroll closed any menu open at the time. + // edge. Without it the row would snap 16 px on loading, putting the first card against the + // screen's edge, and that scroll would close any open menu.
) : null} - {/* Not in a phone-wide list: the title needs the room more (on a 320 px screen it was cut - to six letters). */} + {/* Not in a phone-wide list: the title needs the room more (with the length beside it, a + 320 px screen cuts the title to six letters). */} {formatDuration(track.durationMs)}
From 0b16c8a199624752a89c3bd06ca47dc2798fa2db Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:48:01 +0000 Subject: [PATCH 03/41] chore(comments): state layout reasons in pages as guarantees The Lyrics, Now Playing and Recent pages explained their layout with what an earlier layout did ("left the name under the player bar", "a phone gave it 75 px"); they now say why the layout is what it is. Comments only; no code changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- app/pages/Lyrics.tsx | 2 +- app/pages/NowPlaying.tsx | 3 ++- app/pages/Recent.tsx | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/app/pages/Lyrics.tsx b/app/pages/Lyrics.tsx index 0393336..d18c0b1 100644 --- a/app/pages/Lyrics.tsx +++ b/app/pages/Lyrics.tsx @@ -62,7 +62,7 @@ export default function Lyrics() { )} {/* One slim row in a short window (a phone on its side, 200 % zoom), where two or three rows - of header left the lyrics a line or two. */} + of header would leave the lyrics a line or two. */}
{track ? : null}
diff --git a/app/pages/NowPlaying.tsx b/app/pages/NowPlaying.tsx index 0bc75f3..8afcf7a 100644 --- a/app/pages/NowPlaying.tsx +++ b/app/pages/NowPlaying.tsx @@ -107,7 +107,8 @@ export default function NowPlaying() {
{/* As big as the window's height allows the song's name and heart to show under it - without scrolling (a laptop's 768 px left the name under the player bar). */} + without scrolling (at full size, a 768 px laptop screen hides the name under the + player bar). */}
diff --git a/app/pages/Recent.tsx b/app/pages/Recent.tsx index e835e67..e1e3228 100644 --- a/app/pages/Recent.tsx +++ b/app/pages/Recent.tsx @@ -140,7 +140,7 @@ export default function Recent() { Most recent 300 plays in your saved log - {/* The song takes the width the figures don't need: left to the table, a phone gave it 75 px. */} + {/* The song takes the width the figures don't need: left to the table, a phone gives it 75 px. */} Track From acb32e0d2496c3b7b4eb400c5ff704a770d9314a Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:48:01 +0000 Subject: [PATCH 04/41] chore(comments): say what the Lyricsfile reader avoids, and why "Not a regex with `.`" sat above a line that uses a regex; it now says the indent and body are split by search and slice instead. Comments only; no code changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- app/lyrics/lyricsfile.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/lyrics/lyricsfile.ts b/app/lyrics/lyricsfile.ts index 3283b2c..034ace5 100644 --- a/app/lyrics/lyricsfile.ts +++ b/app/lyrics/lyricsfile.ts @@ -120,7 +120,8 @@ export function parseYamlSubset(src: string): YamlValue { const lines: Line[] = []; let seenContent = false; for (const raw of src.replace(/^\uFEFF/, "").split(/\r\n|\r|\n/)) { - // Not a regex with `.`: that stops at U+2028/U+2029, which YAML 1.2 treats as ordinary text. + // Indent and body by search and slice, not a regex with `.`: that stops at U+2028/U+2029, + // which YAML 1.2 treats as ordinary text. const indent = raw.search(/[^ ]|$/); const body = raw.slice(indent).trimEnd(); if (body.startsWith("\t")) throw new Unsupported("tab indentation"); From ca8a94f1aec760bd2d31b8a5896b40e1de31fabf Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:48:01 +0000 Subject: [PATCH 05/41] chore(comments): explain the heatmap's deep steps without the history The accent engine's heatmap comment said what the steps "used to" do; it now says why they are capped as they are. Comments only; no code changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- app/settings/accent.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/settings/accent.ts b/app/settings/accent.ts index 947abcd..0c20c22 100644 --- a/app/settings/accent.ts +++ b/app/settings/accent.ts @@ -234,7 +234,7 @@ export function accentTokens(hex: string, theme: ResolvedTheme): Record= 0.74 ? accent : withLightness(accent, 0.74); const deepest = Math.min(0.48, L); const heat = light From 11b13840e28dc5b8529d1d8754e149eea32547e0 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:48:01 +0000 Subject: [PATCH 06/41] chore(comments): tighten visuals and backdrop comments AlbumBackdrop's doc repeated backdropShown's rules at length; it now points to them. The window material and the album-backdrop styles state their reasons in the present tense rather than as what once flickered or fell under 4.5:1. Comments only; no code changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- app/styles/index.css | 4 ++-- app/visuals/AlbumBackdrop.tsx | 5 +---- app/visuals/windowMaterial.ts | 4 ++-- 3 files changed, 5 insertions(+), 8 deletions(-) diff --git a/app/styles/index.css b/app/styles/index.css index a8bdae9..c8ae05d 100644 --- a/app/styles/index.css +++ b/app/styles/index.css @@ -742,7 +742,7 @@ * Opaque, text sits straight on the waves, whose lit crests reach well above the theme's canvas, * and which start from a random phase each time: the canvas keeps 55 %. Measured over the * brightest crests of many phases, muted text stays at 5.4:1 or more in every theme (Midnight is - * the lowest); at 45 % it fell to 4.5:1 and below. Subtle text takes the muted colour, since no + * the lowest); at 45 % it falls to 4.5:1 and below. Subtle text takes the muted colour, since no * veil that still shows the colours could keep it 4.5:1. Panels over the waves get both for free. */ [data-backdrop="album"]:not([data-transparent="true"]) { @@ -755,7 +755,7 @@ } /* See-through, text on the glass has the window's material (or the desktop) behind it, lightened further by the album tint: subtle text takes the muted colour there too (measured over Windows' - dark Acrylic with the tint on, subtle text fell to 4.4:1; muted keeps well above 4.5:1). */ + dark Acrylic with the tint on, subtle text falls to 4.4:1; muted keeps well above 4.5:1). */ [data-transparent="true"] { --text-subtle: var(--text-muted); } diff --git a/app/visuals/AlbumBackdrop.tsx b/app/visuals/AlbumBackdrop.tsx index 4c62582..0c7429f 100644 --- a/app/visuals/AlbumBackdrop.tsx +++ b/app/visuals/AlbumBackdrop.tsx @@ -15,10 +15,7 @@ import type { RGB } from "./palette"; * (the theme's canvas) with the playing song's colours drifting in as a soft tint (see * backdrop.ts). Without colours from the artwork, it stays neutral: never the stand-in greens, * and no flash of them while a new cover is read. - * Whether it shows at all is decided by backdropShown (backdrop.ts): whenever the window isn't - * see-through (a full-screen desktop window never is, see useSeeThrough), the opaque choice applies, - * whatever the transparency setting, and it stays under the full-screen player (still, when the - * player's own waves cover it). + * Whether it shows at all is decided by backdropShown (backdrop.ts). */ export function AlbumBackdrop() { const s = useSettings(); diff --git a/app/visuals/windowMaterial.ts b/app/visuals/windowMaterial.ts index d35709f..ea22381 100644 --- a/app/visuals/windowMaterial.ts +++ b/app/visuals/windowMaterial.ts @@ -55,8 +55,8 @@ export function pageSeeThrough(transparency: boolean, fullscreen: boolean): bool /** * The window's material and the page's see-through for the settings and the window's state. - * Focus, maximising and minimising never change it: a material that changed with them is what - * flickered. Full screen makes the page solid and keeps the material set behind it. + * Focus, maximising and minimising never change it: a material that changes with them flickers. + * Full screen makes the page solid and keeps the material set behind it. */ export function decideMaterial(settings: MaterialSettings, state: WindowState): MaterialDecision { return { From 55a6d2a525ca69bfa1daf978fd993d65670467b7 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:48:01 +0000 Subject: [PATCH 07/41] chore(comments): count the version's places in package-lock.json The version script names five files for "six places"; package-lock.json holds the version twice. Comments only; no code changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- scripts/set-version.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/set-version.mjs b/scripts/set-version.mjs index 361abaa..09e22e4 100644 --- a/scripts/set-version.mjs +++ b/scripts/set-version.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node /** - * The app's version lives in six places that must agree: package.json and package-lock.json (the - * web build), src-tauri/tauri.conf.json (what installers and the About box show), and + * The app's version lives in six places that must agree: package.json and package-lock.json (twice; + * the web build), src-tauri/tauri.conf.json (what installers and the About box show), and * src-tauri/Cargo.toml and Cargo.lock (the Rust crate). * * npm run version:set -- 1.2.0 set it everywhere From fe2a2d3767e6993878c8785440ee9baca701589e Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:49:54 +0000 Subject: [PATCH 08/41] docs(guide): organise the user guide by task, with troubleshooting Group the guide the way people use the app: playing music, their listening history (importing, the plays Statsify saves, All time and Streams, backing up and deleting), the library, lyrics, full screen, appearance, keyboard and charts, their account, and troubleshooting. New: how the import and the 50-play sync fit together, CSV export and deleting, why lyrics are missing (each message, LRCLIB, the three-day retry), the theme and album-background settings, and a table of the app's real error messages with what to do. Lyrics are on the Now playing page, not the Overview's card, and the browser player is missing from the desktop WebView on every system, not only Windows'. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- docs/GUIDE.md | 372 +++++++++++++++++++++++++++++++++----------------- 1 file changed, 243 insertions(+), 129 deletions(-) diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 3cc6ed1..960e9af 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1,7 +1,7 @@ # Statsify user guide -How to use Statsify day to day. For installing and the one-time Spotify setup, see the -[README](../README.md). +How to use Statsify day to day. For installing it and the one-time Spotify setup, see the +[README](../README.md). If something doesn't work, see [Troubleshooting](#troubleshooting). ## Playing music @@ -20,7 +20,7 @@ You don't need to open Spotify's window. In the desktop app: 3. When Spotify comes online (usually 3–10 seconds), playback moves to it and your music starts. If a song stopped partway last time, it carries on from there. -You can also start it without playing: **Devices** button (the speaker icon in the player bar) → +You can also start it without playing: the devices button (the speaker icon in the player bar) → **Start Spotify in the background**. Statsify only starts Spotify when there's nothing to play on this PC, and only for things that mean @@ -28,8 +28,8 @@ Statsify only starts Spotify when there's nothing to play on this PC, and only f and shuffle never start it. If Spotify is already running (for example signed out, or still starting), Statsify doesn't start a second copy; it waits for it instead. Pressing Play several times while it starts does one thing, not one per press. If you're listening on your phone or a -speaker, it keeps controlling that. To move music to another device at any time, use the -**Devices** button. +speaker, it keeps controlling that. To move music to another device at any time, use the devices +button. To turn this off: **Settings → Stats & playback → Start Spotify in the background**. Then Play shows "No active Spotify device" with buttons to open Spotify or choose a device instead. @@ -43,6 +43,9 @@ To turn this off: **Settings → Stats & playback → Start Spotify in the backg running if you ever open and close its window. - **Statsify in the tray too:** *Settings → Stats & playback → Keep running in the tray* lets you close Statsify's window and keep the play/pause/next controls in the tray. +- **Songs pick up where they stopped:** a song you skipped or that stopped when Spotify closed + carries on from that point the next time it plays, with a **Start over** button. Turn it off with + *Settings → Stats & playback → Resume songs where they stopped*. ### If it doesn't start @@ -50,9 +53,10 @@ To turn this off: **Settings → Stats & playback → Start Spotify in the backg | --- | --- | | "Spotify isn't installed on this PC" | Install the Spotify desktop app from [spotify.com/download](https://www.spotify.com/download/) or the Microsoft Store, sign in once, then press Play again. Or choose another device. | | "Spotify started but hasn't come online" | Spotify is probably waiting for you to sign in or update. Click **Open Spotify**, sign in, and close its window; next time it will start hidden. Also check you're online. | -| "No active Spotify device" | Background start is off, or this isn't the desktop app. Open Spotify, or use **Devices** to pick a phone or speaker. | +| "No active Spotify device" | Background start is off, or this isn't the desktop app. Open Spotify, or use the devices button to pick a phone or speaker. | | "Playback control needs Spotify Premium" | Spotify only lets Premium accounts be controlled by other apps. | -| Music plays on the wrong device | Use the **Devices** button to move it. Statsify picks this PC first when it has to choose. | +| "Can't reach Spotify. Check your connection." | Statsify can't reach Spotify's servers. Check you're online; it keeps trying. | +| Music plays on the wrong device | Use the devices button to move it. Statsify picks this PC first when it has to choose. | | A device is greyed out: "can't be controlled from here" | Spotify doesn't let other apps control some devices (some TVs, cars and speakers). Start the music on it from Spotify itself, or pick another device. | Notes: @@ -69,15 +73,52 @@ Notes: ### In a browser The browser version of Statsify can't start apps on your PC. It can play in the browser tab itself -(Chrome, Edge or Firefox): **Devices → Play in this browser**. The desktop app can't do that, because -Spotify's protected audio needs a browser component (Widevine) that Windows' app WebView doesn't -include, which is why it starts the Spotify app instead. +(Chrome, Edge or Firefox): devices button → **Play in this browser**. The desktop app can't do that, +because Spotify's protected audio needs a browser component (Widevine) that the desktop app's +WebView doesn't include, which is why it starts the Spotify app instead. Spotify's web player checks one permission the rest of Statsify doesn't use: your account's email address (Statsify never reads it). If you signed in before Statsify asked for it, **Play in this browser** offers to sign in again first. -## All time +## Your listening history + +Spotify's API only shares your last 50 plays, and not how long you listened to each. Statsify +builds your full history from your Spotify data export and the plays it saves itself, and keeps it +on this device, separately for each account. Streams, All time and most of Insights are built from +it. + +### Importing your Spotify data + +1. Open **Import history** and choose **Account privacy settings** (Spotify's privacy page). +2. Request **Extended streaming history**: every play since you joined, with skips, devices and + countries. It can take up to 30 days. **Account data** (the last year) arrives within about 5 + days. +3. Spotify emails you a link when your data is ready. Download the `.zip`. +4. Drop it on **Import history**, or use **Choose files**. The `StreamingHistory` and + `Streaming_History_Audio` `.json` files from inside it work too. + +The files are read on this device; nothing is uploaded. You can import Account data now and the +extended streaming history when it arrives: plays in both are counted once and keep the extended +history's details (album, device, skips), and importing the same file again adds nothing. +**Import complete** lists, for each file, the new plays, podcast plays, plays you already had, and +entries skipped because they had no song or episode (ads, for example). + +Importing waits until Spotify has said which account you're signed in to (the history is kept per +account); the page says so while it checks, and offers **Try again** if Spotify can't be reached. + +### Plays Statsify saves itself + +While Statsify is open or in the tray, it saves Spotify's recently played list: on start-up, when +you come back to the window, every 10 minutes and shortly after each song. **Streams** and +**Import history** show where your history is saved and when new plays were last saved; **Save new +plays now** does it at once. + +Because Spotify only shares the last 50 plays without their length, a saved play counts as the +whole song, and if Statsify is closed while you play more than 50 songs, the oldest are missed. +Your next data export fills the gaps: an exported play replaces the saved one. + +### All time, Streams and Insights Spotify's own charts stop at a year. **Top charts → All time** adds up your whole listening history (your imported Spotify export plus the plays Statsify saves): your first and latest listen, streams, @@ -90,36 +131,104 @@ Genres come from Spotify, which tags artists rather than songs: Statsify looks u most-played artists (a few at a time, remembered on this PC), so the first visit can take a few seconds to fill in. -## When something goes wrong: the developer log +- **Streams:** how much you listened in the last 24 hours, week, month, 6 months, year, all time or + any dates, with every play listed. Rank songs, artists or albums by most or fewest streams or + minutes, first or last listened, or name. A **stream** is a play of 30 seconds or more, the same + threshold Spotify uses. +- **Details:** select any song, artist or album for streams, time, rank, first and last listen and + more. +- **Insights:** **Listening history** has lifetime stats, a listening heatmap and calendar, + records, habits, discovery, least played and forgotten favourites, year-by-year totals, and + podcasts and audiobooks per show (kept apart from your music stats). **Taste profile** works + without an import, from Spotify's top lists. + +### Backing up, exporting and deleting + +- **Back up:** in the desktop app, your history is one SQLite file you can copy; + [DATABASE.md](DATABASE.md#backups-and-moving-pcs) says where it is and how. In a browser it lives + in the browser's storage for the site, so keep your Spotify export to import again. +- **Export:** **Import history → Export as CSV** saves your whole history as a spreadsheet; + **Streams → Export CSV** saves the period on screen. +- **Delete:** **Import history → Delete history** removes the imported and saved plays from this + device. **Settings → Account → Sign out and erase data** does the same and signs you out. It only + erases once the history has loaded; if Spotify can't be reached it says so and keeps you signed + in, so nothing is left behind that you think is gone. Neither changes anything in your Spotify + account. + +## Your library + +### Liked Songs and your playlists -Right-click anywhere → **Developer log**, or press Ctrl Shift L. -Error messages and error toasts also have a **Details** button that opens it. It shows, as they -happen: +- **Like a song:** the heart next to the song in the player bar (on wider screens), on the + Overview's now-playing card and on **Now playing** saves the playing song to your Liked Songs; + it's filled while the song is in them, and pressing it again removes it. For any other song, open its **⋯** menu and + choose **Save to Liked Songs** (or **Remove from Liked Songs**). **Library → Liked songs** + follows straight away. +- **Add to a playlist:** **Add to playlist** next to the heart on **Now playing**, or **⋯ → Add to + playlist…** on any song. Pick one of your playlists (yours and collaborative ones: Spotify + doesn't let anyone add to other people's), type to filter a long list (the cursor starts in the + box), or choose **New playlist** to make a private one that starts with the song. **Open** in the + message goes to the playlist. If Statsify has already loaded that playlist and the song is in it, + it asks before adding it a second time. -- **Errors:** crashes, failed requests, warnings and error messages you were shown. -- **Network:** every call to Spotify, the sign-in service and LRCLIB, with method, endpoint, - status, time taken, and the data sent and received (select an entry). Retries and rate limits - show as separate calls. -- **Desktop:** calls into the desktop app (history database, Spotify start, tray, window), each - once, with the reason when the app refused one. -- **Events:** pages visited, playback changes, settings changes (one line per change, even while - you drag a slider), history saves. -- **Console:** everything the app writes to its console. -- **System:** app version, platform, history and player state, settings: handy for bug reports - (**Copy system info**). +Statsify only adds: it never removes or reorders songs in your playlists, and never deletes one. -Filter by endpoint, status or text; **Pause** to read without new entries arriving; **Export** -saves the whole log as a JSON file you can attach to a bug report. The log lives in memory only -(it starts empty each time) and is never sent anywhere. Access tokens, sign-in codes and other -secrets are masked before anything is recorded, and the system info shows your home folder as -`~`. Signing out (or switching to the demo) empties the log, so whoever uses the device next -can't read your account's data in it. +### Pinned playlists and folders -**Developer tools** (also F12 in the desktop app) opens the real WebView inspector: -elements, console, network and performance. In a browser, use the browser's own developer tools. +Spotify doesn't let other apps see the folders you make in the Spotify app, so Statsify has its +own (kept on this PC, for your account): -Right-clicking in a text field keeps the normal menu (cut, copy, paste), and Shift + right-click -always shows it. The menu works inside open dialogs too (the shortcuts list, the developer log). +- **Folders:** **Library → Playlists → New folder**. Add playlists from a playlist's **⋯** menu → + **Add to folder…**, or **Add to folder** on its page. Open a folder to see just its playlists, and + rename, delete (its playlists stay) or pin it. +- **Pins:** up to four playlists or folders in the sidebar, under **Pinned**: **⋯ → Pin to + sidebar** on a playlist, **Pin** on its page, or **Pin to sidebar** in a folder. A pinned folder + opens in the sidebar (the arrow) to show its playlists. Hover a pin and open its **⋯** menu to + unpin it. +- **Reorder pins:** in the expanded sidebar, drag a pin up or down or choose **Move up** or + **Move down** in its **⋯** menu (no dragging needed; on touch screens the **⋯** is always shown). + Anywhere, focus a pin and press Alt ↑ / ↓. The order is + remembered. + +### Instant playlists + +Lists from your stats can become music in one click: + +- **Insights → Listening history:** *Top tracks* (for the period you picked), *Forgotten + favourites* (songs you played a lot but not in the last four months) and *Most skipped*. +- **Streams:** under *Your songs*, the first 50 in the order you chose for the period, so "top of + March" is **Streams → Custom → March 1 to 31**, sorted by *Most streams*. + +**Play** starts them now (up to 100 songs). **Save to Spotify** makes a private playlist in your +account, named after the list and period ("Top songs · March 2026"), and **Open** in the message +goes to it. Statsify only ever creates private playlists. + +## Lyrics + +Press L (or the microphone button in the player bar) to open the playing song's lyrics, +and again to go back. They're also on the **Now playing** page and in the full-screen player. Synced lyrics light up word by word as they're sung (using real word timing when the song +has it; otherwise words are spread across each line) and scroll by themselves. Click a line to jump +there. + +- **Timing:** if a song's lyrics run early or late, nudge them with **−** / **+** next to the + lyrics, 0.1 s at a time: that's saved for that song only, and the button between them resets it. + The default for every song is in **Settings → Lyrics → Default timing**. +- **Where they come from:** Spotify's API has no lyrics, so Statsify looks them up on + [LRCLIB](https://lrclib.net), a free, community-built lyrics database. The lookup sends the + song's title, artist, album and length, never anything about you. Answers are kept on this + device (lyrics for 30 days, "no lyrics" for 3). Turn lyrics off with **Settings → Lyrics → Show + lyrics**; nothing is looked up then. + +When there are no lyrics to show: + +| What you see | Why, and what to do | +| --- | --- | +| "No lyrics for this song yet" | LRCLIB doesn't have them: popular songs are well covered, less-known ones can be missing. **Add them on LRCLIB** opens the site; Statsify looks again after three days. | +| Lyrics that don't follow the music | LRCLIB only has plain lyrics (without timing) for this song, so they show as text. | +| "Instrumental" | LRCLIB lists the song as having no words. | +| "No lyrics for podcasts" | Lyrics are only looked up for songs. | +| "Couldn't load the lyrics" | LRCLIB couldn't be reached, was busy or took too long. Choose **Try again**. | +| "Lyrics are turned off" | Choose **Turn on lyrics**, or turn on **Settings → Lyrics → Show lyrics**. | ## Full screen @@ -153,11 +262,15 @@ or you're working in another one. The window material comes back when you leave **Settings → Appearance**: +- **Theme:** Midnight, OLED black, Forest, Light or High contrast, or **Match system** for Midnight + or Light following your system's dark or light mode. - **Accent colour:** nine colours (Green, Teal, Blue, Purple, Pink, Red, Orange, Yellow, Mono), or **Custom** for any colour: the colour picker, the **Hue** slider, or type a hex code or red, green and blue values. Buttons, highlights, the logo, charts and heatmaps all follow it. Text in your colour is made a little lighter or darker where needed so it stays easy to read on every theme (Settings says when). +- **Interface size:** 75 % to 150 %, or Ctrl + / − / + 0 in the desktop app (your browser's zoom does the same on the web). - **Transparent background:** the window (or, on the web, the page) turns see-through, as much as the **Transparency** slider says; panels stay more solid so text is easy to read. With **Album colours when see-through** on, the song that's playing tints the glass softly in its @@ -165,6 +278,8 @@ or you're working in another one. The window material comes back when you leave neutral. Every page is the same glass, the Lyrics page included (its blurred artwork shows when the window is solid), and so are the welcome and set-up pages before you sign in. **Frosted glass blur** blurs what shows behind the panels; turn it off for sharp glass. +- **Album colour background:** flowing waves in the playing song's colours behind the app, + **In full screen** (the default), **Always** or **Off**. It isn't used with High contrast. - **Performance mode** (**Motion & performance**): no frosted blur, no accent glow, and no decorative animation (the playing bars, the album-colour waves' motion, covers that follow your mouse), for battery and older graphics. Spinners still turn while something loads. @@ -193,61 +308,35 @@ or you're working in another one. The window material comes back when you leave battery saver turns it off, Windows shows a plain colour instead of Mica or Acrylic. macOS and Linux have no window materials, so the setting isn't shown there. -## Pinned playlists and folders - -Spotify doesn't let other apps see the folders you make in the Spotify app, so Statsify has its -own (kept on this PC, for your account): - -- **Folders:** **Library → Playlists → New folder**. Add playlists from a playlist's **⋯** menu → - **Add to folder…**, or **Add to folder** on its page. Open a folder to see just its playlists, and - rename, delete (its playlists stay) or pin it. -- **Pins:** up to four playlists or folders in the sidebar, under **Pinned**: **⋯ → Pin to - sidebar** on a playlist, **Pin** on its page, or **Pin to sidebar** in a folder. A pinned folder - opens in the sidebar (the arrow) to show its playlists. Hover a pin and open its **⋯** menu to - unpin it. -- **Reorder pins:** in the expanded sidebar, drag a pin up or down or choose **Move up** or - **Move down** in its **⋯** menu (no dragging needed; on touch screens the **⋯** is always shown). - Anywhere, focus a pin and press Alt ↑ / ↓. The order is - remembered. - -## Instant playlists - -Lists from your stats can become music in one click: - -- **Insights → Listening history:** *Top tracks* (for the period you picked), *Forgotten - favourites* (songs you played a lot but not in the last four months) and *Most skipped*. -- **Streams:** under *Your songs*, the first 50 in the order you chose for the period, so "top of - March" is **Streams → Custom → March 1 to 31**, sorted by *Most streams*. - -**Play** starts them now (up to 100 songs). **Save to Spotify** makes a private playlist in your -account, named after the list and period ("Top songs · March 2026"), and **Open** in the message -goes to it. Statsify only ever creates private playlists. - -## Liked Songs and your playlists - -- **Like a song:** the heart next to the song in the player bar (on wider screens), on the - Overview's now-playing card and on **Now playing** saves the playing song to your Liked Songs; - it's filled while the song is in them, and pressing it again removes it. For any other song, open its **⋯** menu and - choose **Save to Liked Songs** (or **Remove from Liked Songs**). **Library → Liked songs** - follows straight away. -- **Add to a playlist:** **Add to playlist** next to the heart on **Now playing**, or **⋯ → Add to - playlist…** on any song. Pick one of your playlists (yours and collaborative ones: Spotify - doesn't let anyone add to other people's), type to filter a long list (the cursor starts in the - box), or choose **New playlist** to make a private one that starts with the song. **Open** in the - message goes to the playlist. If Statsify has already loaded that playlist and the song is in it, - it asks before adding it a second time. +**Settings → Data & about → Reset appearance** goes back to Midnight with the green accent. -Statsify only adds: it never removes or reorders songs in your playlists, and never deletes one. +## Keyboard, charts and other details -## Signing in again for new features +- **Keyboard shortcuts:** press ? for the full list. If you use speech input, or keys + set things off by accident, turn off **Settings → Keyboard → Single-key shortcuts**: Space, + letters, /, ? and [ then do nothing, while Shift + ← / →, Ctrl K and Esc keep working. The + list (the keyboard button in the top bar, or **Keyboard shortcuts** in the right-click menu) + then says **Off** next to the ones that don't. +- **Charts:** most charts have a **Table** button with the same numbers. Hover a chart, or reach it + with Tab and use ← / → (Home / End for the + ends), to read each value; the heatmap and calendar also take ↑ / ↓, and + Enter on a calendar day opens its plays on **Streams**. On a phone the calendar opens + on its latest weeks; swipe it for earlier ones. +- **Song lists:** select a song's number (or double-click its row) to play it; its **⋯** menu has + the rest. On a phone-wide screen the lists leave out each song's length, so its title has room. +- **Tooltips:** rest the pointer on a button (or reach it with Tab) to see what it + does, its state (**Repeat: all**, **Lyrics: on**) and its keyboard shortcut as keys: + Shift → on Next, G then I on Insights in the sidebar. + With single-key shortcuts turned off, tooltips only show the ones that still work. A tooltip + stays while you move the pointer onto it, and Esc closes it. Touch screens don't show + them. +- **Messages:** messages in the corner wait while the pointer is over them or one of their buttons + has keyboard focus. -Statsify only asks Spotify for the permissions its features use. If you signed in before a -feature existed (saving playlists, liking songs, adding to playlists), Spotify hasn't given -Statsify that permission yet: the first time you use it you'll be asked to **Sign in again** once -and approve it. That covers every feature at once; nothing else changes and your stats stay as -they are. +## Your account -## Changing your Client ID +### Changing your Client ID Pasted the wrong Client ID, or made a new Spotify app? You can fix it before you're signed in: @@ -267,47 +356,72 @@ redirect URI* when your Spotify app's **Redirect URIs** don't include the addres screen shows, exactly. Signed in, the Client ID is also in **Settings → Account**; saving a different one there asks first, then signs you out, because your sign-in belongs to the old ID. -## Several tabs +### Signing in again for new features + +Statsify only asks Spotify for the permissions its features use. A sign-in from an older version +of Statsify may not include a permission a newer feature needs (saving playlists, liking songs, +adding to playlists, playing in the browser): the first time you use it you'll be asked to +**Sign in again** once and approve it. That covers every feature at once; nothing else changes and +your stats stay as they are. + +### Several tabs In a browser, every Statsify tab shares one sign-in. Signing out in one signs out all of them, -and signing in (or opening the demo) in one does the same in the others. **Sign out and erase -data** only erases once the history has loaded; if Spotify can't be reached it says so and keeps -you signed in, so nothing is left behind that you think is gone. - -## Other things you can do - -- **Streams:** how much you listened in the last 24 hours, week, month, 6 months, year or any dates. - Rank songs, artists or albums by most or fewest streams or minutes, first or last listened, or name. -- **Details:** select any song, artist or album for streams, time, rank, first and last listen and more. -- **Insights:** lifetime stats from your Spotify data export, a listening heatmap and calendar, and - podcasts and audiobooks per show. Import the export on the **Import history** page. You can - import Account data now and the extended streaming history when it arrives: plays in both are - counted once and keep the extended history's details (album, device, skips). Importing waits - until Spotify has said which account you're signed in to (the history is kept per account); the - page says so while it checks, and offers **Try again** if Spotify can't be reached. -- **Charts:** most charts have a **Table** button with the same numbers. Hover a chart, or reach it - with Tab and use ← / → (Home / End for the - ends), to read each value; the heatmap and calendar also take ↑ / ↓, and - Enter on a calendar day opens its plays on **Streams**. On a phone the calendar opens - on its latest weeks; swipe it for earlier ones. -- **Song lists:** select a song's number (or double-click its row) to play it; its **⋯** menu has - the rest. On a phone-wide screen the lists leave out each song's length, so its title has room. -- **Lyrics:** press L. Click a line to jump there. If a song's lyrics run early or - late, nudge them with **−** / **+** next to the lyrics: that's saved for that song only. The - default for every song is in **Settings → Lyrics → Default timing**. -- **Interface size:** *Settings → Appearance*, or Ctrl + / − / - 0. -- **Keyboard shortcuts:** press ? for the full list. If you use speech input, or keys - set things off by accident, turn off **Settings → Keyboard → Single-key shortcuts**: Space, - letters, /, ? and [ then do nothing, while Shift - ← / →, Ctrl K and Esc keep working. The - list (the keyboard button in the top bar, or **Keyboard shortcuts** in the right-click menu) - then says **Off** next to the ones that don't. -- **Tooltips:** rest the pointer on a button (or reach it with Tab) to see what it - does, its state (**Repeat: all**, **Lyrics: on**) and its keyboard shortcut as keys: - Shift → on Next, G then I on Insights in the sidebar. - With single-key shortcuts turned off, tooltips only show the ones that still work. A tooltip - stays while you move the pointer onto it, and Esc closes it. Touch screens don't show - them. -- **Messages:** messages in the corner wait while the pointer is over them or one of their buttons - has keyboard focus. +and signing in (or opening the demo) in one does the same in the others. + +## Troubleshooting + +### Common problems + +| What you see | What it means, and what to do | +| --- | --- | +| Spotify's page says *INVALID_CLIENT: Invalid client* | Spotify doesn't know the Client ID you entered. See [Changing your Client ID](#changing-your-client-id). | +| Spotify's page says *INVALID_CLIENT: Invalid redirect URI* | Your Spotify app's **Redirect URIs** must include the address on the set-up screen (and in **Settings → Account**) exactly: `http://127.0.0.1:43821/callback` for the desktop app. | +| "Spotify sign-in was cancelled." | Access wasn't approved on Spotify's page. Sign in again when you're ready. | +| "This sign-in link is invalid or has expired." | The sign-in took too long, or its link was already used. Start it again. | +| "Spotify didn't allow this" | Your Spotify account isn't listed under **User Management** in your Spotify app (add it in the [Spotify Developer Dashboard](https://developer.spotify.com/dashboard)), or the page is someone else's playlist, which Spotify doesn't share with apps in Development Mode. | +| "Session expired", or "Your Spotify session expired. Please sign in again." | Spotify ended the sign-in, for example because Statsify's access was removed on Spotify's [Manage apps](https://www.spotify.com/account/apps/) page. Sign in again. | +| "Your session ended in another Statsify tab." | You signed out in another tab: tabs share one sign-in. | +| "You're offline" | Statsify can't reach Spotify. Check your connection; pages load again when you're back online. | +| "Spotify asked us to slow down" | Spotify limits how many requests an app makes in a short time. Wait a moment, then choose **Try again**. | +| Stats or playlists look out of date | Statsify keeps Spotify's answers for a few minutes. **Settings → Data & about → Clear cache** fetches everything again (your history is kept). | +| "No streaming history files found" when importing | Choose the `.zip` from Spotify, or the `StreamingHistory` / `Streaming_History_Audio` `.json` files inside it. | +| "Damaged or incomplete zip" in the import summary | The download didn't finish. Download the file from Spotify's email again. | +| "Your listening history couldn't be opened, so new plays aren't being saved." | Statsify stops saving rather than risk overwriting your history. Choose **Try again**. If the message says the file is from a newer version of Statsify, update Statsify. | +| Play does nothing, or Spotify doesn't start | See [If it doesn't start](#if-it-doesnt-start). | +| No lyrics | See [Lyrics](#lyrics). | + +Still stuck? Open an [issue](https://github.com/Kkkermit/Spotify-Stats/issues/new/choose) and +include what the developer log shows. + +### The developer log + +Right-click anywhere → **Developer log**, or press Ctrl Shift L. +Error messages and error toasts also have a **Details** button that opens it. It shows, as they +happen: + +- **Errors:** crashes, failed requests, warnings and error messages you were shown. +- **Network:** every call to Spotify, the sign-in service and LRCLIB, with method, endpoint, + status, time taken, and the data sent and received (select an entry). Retries and rate limits + show as separate calls. +- **Desktop:** calls into the desktop app (history database, Spotify start, tray, window), each + once, with the reason when the app refused one. +- **Events:** pages visited, playback changes, settings changes (one line per change, even while + you drag a slider), history saves. +- **Console:** everything the app writes to its console. +- **System:** app version, platform, history and player state, settings: handy for bug reports + (**Copy system info**). + +Filter by endpoint, status or text; **Pause** to read without new entries arriving; **Export** +saves the whole log as a JSON file you can attach to a bug report. The log lives in memory only +(it starts empty each time) and is never sent anywhere. Access tokens, sign-in codes and other +secrets are masked before anything is recorded, and the system info shows your home folder as +`~`. Signing out (or switching to the demo) empties the log, so whoever uses the device next +can't read your account's data in it. It does contain song and playlist names, so look it over +before you share it. + +**Developer tools** (also F12 in the desktop app) opens the real WebView inspector: +elements, console, network and performance. In a browser, use the browser's own developer tools. + +Right-clicking in a text field keeps the normal menu (cut, copy, paste), and Shift + right-click +always shows it. The menu works inside open dialogs too (the shortcuts list, the developer log). From f1b98b05130007b0b4eac80ea197ac7962c2f696 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:50:00 +0000 Subject: [PATCH 09/41] docs(readme): answer what users ask, and leave developer detail to DEVELOPMENT The README now covers what Statsify does, installing it (first-launch warnings on each system, checksums, updating, uninstalling, WebView2 for the portable .exe), the one-time Spotify setup with why each person needs their own Client ID (five accounts, Premium for the owner and for playback), a wrong Client ID, importing history, where data is kept and how to back it up, delete it or revoke Statsify's access, the permissions it asks for, and a short FAQ. Corrected: the theme is "OLED black" and there's "Match system"; Spotify starts hidden when there's no device to play on, not whenever nothing is playing; macOS 15 no longer opens unsigned apps from Control-click, and "is damaged" needs xattr, not Open Anyway; the roadmap is no longer "after 1.0". Removed: the upgrade note for "Spotify Stats" (no release carried that name), and the scripts table and folder map, which DEVELOPMENT.md and AGENTS.md already have. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- README.md | 406 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 243 insertions(+), 163 deletions(-) diff --git a/README.md b/README.md index 78fdf02..7d20380 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,9 @@

Statsify

- Your Spotify, by the numbers. A fast, private desktop app for Windows, macOS and Linux that + Your Spotify, by the numbers. A free, open-source app for Windows, macOS, Linux and the web that shows every stat Spotify shares, turns your full listening history into insights, and controls - playback. + playback. No servers and no tracking: your data stays on your computer.

@@ -28,24 +28,53 @@ Overview: now playing, 30-day listening time, plays, top artist, streak, top tracks and recent plays

+Statsify works with your own Spotify account through Spotify's official Web API. You create a free +**Client ID** for it once (about two minutes, [see below](#one-time-spotify-setup-about-2-minutes)), +or click **Explore the demo** to look around with fictional data first. + ## Features -- **Stats:** top tracks, artists, albums and genres for the last 4 weeks, 6 months and year, with rank changes, release decades, explicit share and artist variety, plus **All time**: everything since your first listen (streams, time, songs, artists, albums, days, streaks, genres), built from your listening history. -- **Streams over any period:** how many streams, minutes, songs and artists in the last 24 hours, week, month, 6 months, year or any custom dates, with a chart, every play listed and CSV export. Rank your songs, artists or albums by most or fewest streams or minutes, first or last listened, or name, and filter by name. -- **Details for everything you've played:** select any song, artist or album for its streams, time listened, rank, first and last listen, days played, skip rate, streams over time, top songs and albums, and recent plays, with its cover or artist photo. -- **Your own history database:** every play is saved on your PC in a documented SQLite file ([docs/DATABASE.md](docs/DATABASE.md)): your imported Spotify history plus new plays recorded while the app is open or in the tray. -- **Minutes listened, for real:** import your Spotify data export for lifetime listening time, streaks, a weekday × hour heatmap and a day-by-day listening calendar, records, skips, devices, countries, discovery, least-played and forgotten favourites, year-by-year totals, and podcasts and audiobooks per show. New plays are logged automatically while the app runs. -- **Library:** every playlist, liked song, saved album and followed artist. Search, filter and sort; search inside a playlist; per-playlist stats; smooth even with 10,000-track playlists. Put playlists in your own folders and pin up to four playlists or folders to the sidebar (reorder by dragging, from their ⋯ menu or with Alt + arrows). -- **Player:** play, pause, skip, shuffle, repeat, seek, volume, queue and device switching (Spotify Connect), whole-playlist playback, 30-second previews, tray controls and keyboard shortcuts. Songs pick up where they stopped (after a skip or closing Spotify), with a Start over button. Spotify's window never needs to be open: press Play and the desktop app starts Spotify hidden in the tray. -- **Lyrics:** time-synced lyrics that light up word by word as they are sung, with a blurred-artwork view, auto-scroll, click-a-line-to-jump (on the Lyrics page and the Now Playing card) and a timing nudge that's remembered per song. Real word timing is used when the song has it; otherwise words are spread across each line. Press L or the microphone button. -- **Instant playlists:** play your top songs of any period ("top of March"), your forgotten favourites or your most skipped right away, or save them to Spotify as a private playlist. -- **Like and add to playlists:** a heart in the player and on Now Playing saves the song to your Liked Songs, and any song's ⋯ menu can like it or add it to one of your playlists (or a new private one). -- **Full screen:** a full-screen player with the album cover, the lyrics, or both side by side, over flowing, glossy waves in the colours of the song that's playing (F, then C / L / B to switch; it opens on the one you used last). The whole window can go full screen too (F11 in the desktop app), with the same album colours behind the app; choose "Always" in Settings to keep them on. -- **Make it yours:** five themes (Midnight, OLED, Forest, Light, High contrast), nine accent colours or any colour you pick (hue, hex or RGB; text in it is adjusted to stay readable on every theme), interface size from 75 % to 150 % (Ctrl + / − / 0), playlists that remember your sort, and a see-through window with a 0–90 % slider: the apps behind it show through (Clear), frosted (Acrylic, which stays frosted when you switch to another app) or a wallpaper tint (Mica). In see-through mode the playing song's colours add a soft, slowly drifting tint (neutral glass when nothing is playing). -- **Covers that follow your mouse:** covers lean toward the pointer in 3D with a soft sheen (Now Playing, full screen, album, playlist and artist pages, and gently in the grids); still with reduced motion or in performance mode. -- **Accessible and light:** WCAG 2.2 AA checked in CI, full keyboard support, reduced-motion support, and about 50 MB of JS heap. -- **Developer log:** right-click anywhere → **Developer log** (or Ctrl Shift L) for errors, console output, every API call (endpoint, status, timing, data), desktop calls, events and system info, with filtering and export. Tokens are masked. **Developer tools** opens the real WebView inspector in the desktop app (F12). -- **Private:** no servers and no tracking. Your data stays on your computer. (Lyrics are looked up on LRCLIB by song title, artist, album and length; turn them off in Settings.) +- **Top charts:** your top tracks, artists, albums and genres over the last 4 weeks, 6 months and + year, with rank changes, release decades, explicit share and artist variety. +- **All time:** everything since your first listen (streams, listening time, songs, artists, + albums, days, streaks, genres), built from your listening history. +- **Streams over any period:** streams, minutes, songs and artists in the last 24 hours, week, + month, 6 months, year, all time or any dates, with a chart, every play listed and CSV export. + Rank songs, artists or albums by streams, minutes, first or last listen, or name. +- **Details for everything you've played:** select a song, artist or album for its streams, time + listened, rank, first and last listen, days played, skip rate, streams over time, top songs and + albums, and recent plays. +- **Insights from your whole history:** import your Spotify data export for lifetime listening + time, streaks, a weekday × hour heatmap and a day-by-day listening calendar, records, skips, + devices, countries, discovery, least-played and forgotten favourites, year-by-year totals, and + podcasts and audiobooks per show. New plays are saved automatically while Statsify runs. +- **Your own history database:** the desktop app keeps every play in a documented SQLite file on + your computer that you can open, query and back up ([docs/DATABASE.md](docs/DATABASE.md)). +- **Library:** every playlist, liked song, saved album and followed artist, with search, filters, + sorting and per-playlist stats, smooth even with 10,000-track playlists. Group playlists in your + own folders and pin up to four playlists or folders to the sidebar. +- **Player:** play, pause, skip, shuffle, repeat, seek, volume, queue and device switching + (Spotify Connect), 30-second previews, tray controls and keyboard shortcuts. Songs pick up where + they stopped, with a **Start over** button. In the desktop app, Play starts Spotify hidden in the + tray when there's no Spotify device to play on, so you never need Spotify's window. +- **Lyrics:** time-synced lyrics that light up word by word, with auto-scroll, click-a-line-to-jump + and a timing nudge remembered per song. Press L or the microphone button. +- **Instant playlists:** play your top songs of any period, your forgotten favourites or your most + skipped, or save them to Spotify as a private playlist. +- **Liked Songs and playlists:** like a song with the heart, or add any song to one of your + playlists (or a new private one) from its ⋯ menu. +- **Full-screen player:** the cover, the lyrics or both, over flowing waves in the colours of the + song that's playing (F). +- **Make it yours:** five themes (Midnight, OLED black, Forest, Light, High contrast), or Midnight + and Light following your system; nine accent colours or any colour you pick (text in it is + adjusted to stay readable); interface size from 75 % to 150 %; and a see-through window + (0–90 %) tinted by the playing song's colours. On Windows, choose what shows through: the apps + behind the window (Clear), the same frosted (Acrylic) or a tint of your wallpaper (Mica). +- **Accessible:** WCAG 2.2 AA, checked in CI; full keyboard support, single-key shortcuts you can + turn off, reduced motion and a performance mode. +- **Developer log:** right-click anywhere → **Developer log** (or Ctrl Shift + L) for errors, every API call and system info, with tokens masked: handy for bug + reports.

Insights: lifetime listening time, plays, streaks, skip rate and listening-over-time chart @@ -54,179 +83,230 @@ ## Install -Download the file for your system from the [latest release](https://github.com/Kkkermit/Spotify-Stats/releases/latest), then follow the -[one-time Spotify setup](#one-time-spotify-setup-about-2-minutes) below, or click **Explore the -demo** to look around with fictional data first. - -| System | File | -| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------ | -| **Windows** 10 and 11 | `Statsify__x64-setup.exe`: installs for you only, no admin needed (or the `.msi`, or the portable `.exe`) | -| **macOS** (Apple silicon and Intel) | `Statsify__universal.dmg` | -| **Linux** | `Statsify__amd64.deb` (Debian, Ubuntu, Mint...) or `Statsify__amd64.AppImage` (any distribution) | - -`SHA256SUMS.txt` in the release lists every file's checksum (`sha256sum -c SHA256SUMS.txt`). The -installers aren't code-signed yet, so each system asks once: - -- **Windows:** SmartScreen says "Windows protected your PC": choose **More info → Run anyway**. -- **macOS:** open the `.dmg`, drag Statsify to Applications, then right-click it → **Open** → **Open**. - If macOS says the app "is damaged" or offers no Open button, go to **System Settings → Privacy & - Security** and choose **Open Anyway**, or run `xattr -dr com.apple.quarantine /Applications/Statsify.app`. +Download the file for your system from the +[latest release](https://github.com/Kkkermit/Spotify-Stats/releases/latest): + +| System | File | +| ----------------------------------- | -------------------------------------------------------------------------------------------------------------------- | +| **Windows** 10 and 11 | `Statsify__x64-setup.exe`: installs for you only, no admin needed (or the `.msi`, or the portable `.exe`) | +| **macOS** (Apple silicon and Intel) | `Statsify__universal.dmg` | +| **Linux** | `Statsify__amd64.deb` (Debian, Ubuntu, Mint...) or `Statsify__amd64.AppImage` (most distributions) | + +The installers aren't code-signed yet, so Windows and macOS can't verify who made them and ask +you to confirm the first time you open Statsify: + +- **Windows:** SmartScreen says "Windows protected your PC". Choose **More info → Run anyway**. +- **macOS:** open the `.dmg` and drag Statsify to Applications. Open it once; macOS says it can't + check the app. Then open **System Settings → Privacy & Security**, scroll down and choose + **Open Anyway** (on macOS 14 and earlier, Control-click the app → **Open** also works). If macOS + says Statsify "is damaged and can't be opened", it means the app isn't signed, not that it's + damaged: run `xattr -dr com.apple.quarantine /Applications/Statsify.app` in Terminal, then open + it. - **Linux:** `sudo apt install ./Statsify__amd64.deb`, or make the AppImage executable - (`chmod +x Statsify_*.AppImage`) and run it. The tray icon needs an AppIndicator-capable desktop - (on GNOME, the _AppIndicator and KStatusNotifierItem Support_ extension). - -Builds of the latest changes on `main` are under [Actions → Desktop app](https://github.com/Kkkermit/Spotify-Stats/actions/workflows/desktop.yml) -(open a run, then download `statsify-Windows`, `statsify-macOS` or `statsify-Linux`). - -**Upgrading from "Spotify Stats"** (the app's old name): install Statsify, then remove _Spotify -Stats_ in Windows Settings → Apps. Your history, settings and sign-in carry over, because both use -the same data folder, so **leave "Delete the application data" unticked** when uninstalling the -old one. + (`chmod +x Statsify_*.AppImage`) and run it. The tray icon needs a desktop with AppIndicator + support (on GNOME, the _AppIndicator and KStatusNotifierItem Support_ extension). + +Good to know: + +- **Checking the download:** `SHA256SUMS.txt` in each release lists every file's SHA-256 + checksum. Compare it with `sha256sum ` on Linux, `shasum -a 256 ` on macOS or + `Get-FileHash ` in Windows PowerShell. +- **Updating:** Statsify doesn't update itself yet. Install the new version over the old one; your + history, settings and sign-in are kept. +- **Uninstalling:** remove Statsify like any other app. Your history and settings stay on your + computer unless you delete them: the uninstaller of the Windows `-setup.exe` offers to ("Delete + the application data"); elsewhere, delete the data folder yourself + ([where it is](docs/DATABASE.md#where-it-is)). +- **The portable Windows `.exe`** needs Microsoft Edge WebView2, which Windows 11 includes. The + installers add it on Windows 10 if it's missing. +- **The latest changes on `main`:** every build is under + [Actions → Desktop app](https://github.com/Kkkermit/Spotify-Stats/actions/workflows/desktop.yml) + for 14 days. Open a run and download `statsify-Windows`, `statsify-macOS` or `statsify-Linux` + (you need to be signed in to GitHub). +- **The web version:** each release also has `Statsify__web.zip` to host yourself; see + [Production web build](docs/DEVELOPMENT.md#production-web-build). ## One-time Spotify setup (about 2 minutes) -Spotify requires each app to have its own Client ID, and because this app has no server you create a -free one. The app walks you through it: +Statsify signs in to Spotify with your own **Client ID**, a free key you create once in Spotify's +developer dashboard. Choose **Connect Spotify** and the app walks you through it: -1. Go to the [Spotify Developer Dashboard](https://developer.spotify.com/dashboard) → **Create app**. -2. Add the Redirect URI shown in the app's setup screen: +1. Open the [Spotify Developer Dashboard](https://developer.spotify.com/dashboard), sign in with your + Spotify account and choose **Create app**. Any name and description will do. +2. Under **Redirect URIs**, add the address Statsify's setup screen shows, exactly: - Desktop app: `http://127.0.0.1:43821/callback` - - Browser dev mode: `http://127.0.0.1:5173/callback` - - Hosted web build: `https:///callback` - - Spotify only accepts `https://` or loopback-IP addresses, so use `127.0.0.1`, not `localhost`. - Tick **Web API** and **Web Playback SDK**. - -3. Under **User Management**, add the Spotify account(s) that will use it (Development Mode allows up - to 5; the app owner needs Premium). -4. Paste the **Client ID** into the app. It's a public identifier; there is **no client secret** - (the app uses the PKCE flow). - -**Wrong Client ID?** Spotify answers a Client ID it doesn't know with *INVALID_CLIENT: Invalid -client* on its own page (and a Redirect URI your app doesn't list with *Invalid redirect URI*). The -welcome page shows the ID in use (first and last four characters) with **Change**, which opens the -setup screen with it filled in to correct or clear. While the desktop app waits for the browser, -**Wrong Client ID?** stops waiting and goes there too, and a failed sign-in offers **Check your -Client ID**. Once signed in, it's under **Settings → Account**. - -To get lifetime stats, request your data at -[spotify.com/account/privacy](https://www.spotify.com/account/privacy/) (choose _Extended streaming -history_), then drop the zip onto the app's **Import history** page. - -## Playing music (Spotify starts hidden) - -Statsify is a remote control: the music itself plays in the Spotify app, the only official way to -play Spotify's protected audio on a PC. You never need to open Spotify's window, though: - -- **Press Play** (player bar, Space, the tray icon or any song). If nothing is playing on this PC, - Statsify **starts Spotify hidden in the tray**, waits for it to come online (usually 3–10 seconds) - and plays there. The player bar says "Starting Spotify in the background…" meanwhile. -- **Devices button → Start Spotify in the background** does the same without playing. -- Already playing on your phone or a speaker? Statsify keeps controlling that; it only starts Spotify - when there's nothing to play on. - -It needs the Spotify desktop app installed (from [spotify.com/download](https://www.spotify.com/download/) -or the Microsoft Store) and signed in once, plus Spotify Premium for playback control. Turn it off in -**Settings → Stats & playback → Start Spotify in the background**. For the smoothest start, you can -also let Spotify open with Windows: Spotify → Settings → _Open Spotify automatically after you log -into the computer_ → **Minimized**. More in the [user guide](docs/GUIDE.md). + - `npm run dev`: `http://127.0.0.1:5173/callback` + - Your own web host: `https:///callback` + + Spotify only accepts `https://` or loopback IP addresses, so it's `127.0.0.1`, never + `localhost`. Tick **Web API** and **Web Playback SDK**, and save. + +3. Under **User Management**, add each Spotify account that will use Statsify (up to five). +4. Copy the **Client ID** from the app's **Basic Information** page, paste it into Statsify and + choose **Save and sign in**. Spotify asks you to approve access in your browser (in the desktop + app, your normal browser opens; come back to Statsify when you've approved). + +The Client ID is a public identifier, not a password. There is no client secret: Statsify signs in +with PKCE, and your password only ever goes to Spotify. + +### Why do I need my own Client ID? + +Statsify has no server, so there's no Statsify account at Spotify for everyone to share. And +Spotify's rules for apps like yours (Development Mode) are: + +- One Client ID can be used by at most **five** Spotify accounts, each added under + **User Management**. A shared one couldn't serve everyone, so each person, or a household, + creates their own. +- The account that creates the Spotify app needs **Spotify Premium**. +- **Controlling playback needs Premium** for every account: Spotify's rule for every third-party + app. Without it you still get every stat, previews and "Open in Spotify". + +### Typed the wrong Client ID? + +A sign-in with a wrong Client ID never comes back to Statsify: Spotify shows an error on its own +page instead. + +- _INVALID_CLIENT: Invalid client_ means Spotify doesn't know that Client ID. +- _INVALID_CLIENT: Invalid redirect URI_ means your Spotify app's **Redirect URIs** don't include the + address the setup screen shows, exactly. + +Back in Statsify, the welcome page shows the Client ID in use (its first and last four characters) +with **Change**, which opens the setup screen to correct or clear it. While the desktop app waits +for the browser, **Wrong Client ID?** takes you there too, and a failed sign-in offers **Check your +Client ID**. Once you're signed in, it's in **Settings → Account**. More in the +[user guide](docs/GUIDE.md#changing-your-client-id). + +### Import your full history (optional) + +Spotify's API only shares your last 50 plays, so lifetime stats come from your Spotify data +export: + +1. On [spotify.com/account/privacy](https://www.spotify.com/account/privacy/), request + **Extended streaming history**: every play since you joined. It can take up to 30 days. + **Account data** (the last year) usually arrives within about 5 days. You can import both. +2. Spotify emails you when your data is ready. Download the `.zip`. +3. Drop it on Statsify's **Import history** page. It's read on your computer; nothing is uploaded. + +From then on, Statsify adds new plays itself while it's open or in the tray. See +[Your listening history](docs/GUIDE.md#your-listening-history) in the user guide. + +## Your data and privacy + +- **No servers, no tracking, no analytics.** Statsify talks only to Spotify (sign-in, the Web API, + artwork and the preview player) and, for lyrics, to [LRCLIB](https://lrclib.net), which gets the + song's title, artist, album and length, never anything about you. Lyrics can be turned off in + **Settings → Lyrics**. +- **Where it's kept:** in the desktop app, your listening history is one SQLite file in the app's + data folder ([location on each system](docs/DATABASE.md#where-it-is)), and your settings and + sign-in are in the app's own storage on your computer. In a browser, everything stays in that + site's browser storage. +- **Backing up:** close the app and copy the database file + ([how](docs/DATABASE.md#backups-and-moving-pcs)), or export your history as CSV from + **Import history → Export as CSV** (or one period from **Streams → Export CSV**). +- **Deleting:** **Import history → Delete history** removes your imported and recorded plays from + this device; **Settings → Account → Sign out and erase data** does the same and signs you out. + Neither changes anything in your Spotify account. To take away Statsify's access to your + account, remove it on Spotify's [Manage apps](https://www.spotify.com/account/apps/) page. +- **Permissions:** Statsify asks Spotify only for what its features use: your profile, top items, + recently played, library, playlists and followed artists; seeing and controlling playback; + creating private playlists, adding songs to your own and collaborative playlists, and liking + songs. It never removes or reorders songs in a playlist, and never deletes one. The browser + version also asks for streaming and your email address, which Spotify's in-browser player + requires; Statsify never reads the address. + +More in [SECURITY.md](SECURITY.md#how-statsify-protects-your-data). + +## FAQ + +**Do I need Spotify Premium?** Stats, your library, lyrics and 30-second previews work with any +account. Controlling playback needs Premium. Spotify also requires the account that creates the +Client ID to have Premium; if yours doesn't, someone with Premium can create one and add you under +**User Management**. + +**Can friends or family use Statsify?** Yes: up to five Spotify accounts per Client ID. Add each one +under **User Management** in your Spotify app, and share the Client ID with them; each person signs +in with their own Spotify account on their own device. + +**Why are some numbers or features missing?** Under Spotify's rules for Development Mode apps +(since February 2026), the API leaves out popularity scores, follower counts, artist top tracks and +other people's profiles and playlists, among others. Statsify says where something isn't available +instead of showing zeros. + +**Why are plays missing from Streams or All time?** Spotify only shares your last 50 plays, and +not how long you listened to each. Statsify saves them while it's open or in the tray (counting +each as the song's full length); if it's closed while you play more than 50 songs, the oldest are +missed. Importing your next data export fills the gaps with the exact plays. + +**Why don't lyrics show for a song?** Spotify's API has no lyrics, so Statsify looks them up on +LRCLIB, a free, community-built database. Popular songs are well covered; less-known ones may have +plain lyrics (without timing) or none. You can add missing lyrics on LRCLIB, and Statsify looks +again after three days. If lyrics run early or late, nudge them with **−** / **+**. + +**Why does Play say "No active Spotify device" or "Spotify isn't installed on this PC"?** Statsify +is a remote control: the music plays in a Spotify app, the only official way to play Spotify's +protected audio. The desktop app needs the Spotify desktop app installed and signed in once; it +then starts it hidden for you. [If it doesn't start](docs/GUIDE.md#if-it-doesnt-start) lists each +message and what to do. + +**What does "Spotify didn't allow this" mean?** Your Spotify account probably isn't listed under +**User Management** in your Spotify app, or the page is someone else's playlist, which Spotify +doesn't share with Development Mode apps. + +More answers are in the user guide's [Troubleshooting](docs/GUIDE.md#troubleshooting). ## Build from source You need [Node.js](https://nodejs.org/) 26 or newer, and for the desktop app -[Rust](https://rustup.rs/) plus the [Tauri prerequisites](https://v2.tauri.app/start/prerequisites/) -for your system ([docs/DEVELOPMENT.md](docs/DEVELOPMENT.md#prerequisites) lists them). +[Rust](https://rustup.rs/) 1.92 or newer plus the +[Tauri prerequisites](https://v2.tauri.app/start/prerequisites/) for your system. ```bash git clone https://github.com/Kkkermit/Spotify-Stats.git cd Spotify-Stats npm ci - -npm run dev # the web app on http://127.0.0.1:5173 (use 127.0.0.1: Spotify rejects "localhost") -npm run desktop:dev # the desktop app, with hot reload -npm run desktop:build # installers for this system, in src-tauri/target/release/bundle/ +npm run dev # the web app on http://127.0.0.1:5173 +npm run desktop:dev # or the desktop app, with hot reload ``` -Optionally copy `.env.example` to `.env.local` and set `VITE_SPOTIFY_CLIENT_ID` to skip the setup -screen. Everything else (tests, debugging, the desktop shell, the project layout) is in -[docs/DEVELOPMENT.md](docs/DEVELOPMENT.md). - -### Scripts - -| Command | What it does | -| --------------------------------------- | --------------------------------------------------------------------- | -| `npm run dev` | Web dev server | -| `npm run desktop:dev` / `desktop:build` | Desktop app with hot reload / installers | -| `npm run typecheck` · `lint` · `test` | TypeScript, ESLint, Vitest | -| `npm run e2e` | Playwright end-to-end + axe accessibility (demo mode, 3 screen sizes) | -| `npm run check` | Everything except E2E | -| `npm run version:set -- 1.2.0` | Set the version everywhere before a release | - -## Project structure - -``` -app/ the React app: pages, components, Spotify client, history, analytics, player, - lyrics, visuals, settings (React 19, TypeScript, Vite, Tailwind) -src-tauri/ the desktop shell in Rust (Tauri 2): tray, sign-in listener, history database, - starting Spotify hidden -e2e/ Playwright end-to-end tests with a fake Spotify API and a fake desktop bridge -docs/ user guide, history database format -``` - -[AGENTS.md](AGENTS.md) maps every folder and explains the architecture, conventions and checks. +[docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) has the prerequisites for each system, every command, +the tests and debugging. ## Documentation -| Document | For | -| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | -| [User guide](docs/GUIDE.md) | Playing music, liking songs and adding them to playlists, All time, full screen, themes, pins and folders, instant playlists, the developer log | -| [Development](docs/DEVELOPMENT.md) | Setting up on Windows, macOS or Linux, running, testing and debugging | -| [Contributing](CONTRIBUTING.md) | Branches, commits, pull requests and code style | -| [Architecture (AGENTS.md)](AGENTS.md) | How the app works, every folder, conventions; for people and AI agents | -| [History database](docs/DATABASE.md) | The SQLite file's schema, for your own queries | -| [Releasing](docs/RELEASING.md) | Versioning, tagging and the release pipeline | -| [Security policy](SECURITY.md) | Reporting a vulnerability privately | - -## Contributing - -Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for setting up, running the -tests and opening a pull request, and please follow the [Code of Conduct](CODE_OF_CONDUCT.md). -Found a security problem? Report it privately as described in [SECURITY.md](SECURITY.md). - -## Support - -- **Questions and bugs:** open an [issue](https://github.com/Kkkermit/Spotify-Stats/issues/new/choose); the bug form asks for the - details that help (and the developer log can export them, with tokens masked). +| Document | For | +| ------------------------------------- | ------------------------------------------------------------------------------------------ | +| [User guide](docs/GUIDE.md) | Using Statsify: playing music, your history, library, lyrics, full screen, troubleshooting | +| [History database](docs/DATABASE.md) | Where your history file is, its schema and example queries, backups | +| [Security policy](SECURITY.md) | Reporting a vulnerability privately, and how Statsify protects your data | +| [Contributing](CONTRIBUTING.md) | Ways to help, branches, commits, pull requests and code style | +| [Development](docs/DEVELOPMENT.md) | Setting up on Windows, macOS or Linux, commands, testing and debugging | +| [Architecture (AGENTS.md)](AGENTS.md) | How the code works, every folder, conventions; for contributors and AI coding agents | +| [Releasing](docs/RELEASING.md) | Versions and the release pipeline, for maintainers | + +## Contributing and support + +- **Found a bug or have a question?** Open an + [issue](https://github.com/Kkkermit/Spotify-Stats/issues/new/choose). The bug form asks for the + details that help; the developer log can export them, with tokens masked. +- **Found a security problem?** Please report it privately, as [SECURITY.md](SECURITY.md) describes. +- **Want to contribute?** Contributions are welcome! Start with [CONTRIBUTING.md](CONTRIBUTING.md), + and please follow the [Code of Conduct](CODE_OF_CONDUCT.md). - **Like Statsify?** Star the repository, tell a friend, or [buy me a coffee](https://buymeacoffee.com/Kkermit). ## Roadmap -Ideas for after 1.0, roughly in order: +Ideas for future versions, roughly in order: -- Auto-updates from signed releases, tokens in the OS keychain, code-signed installers (no more - SmartScreen prompt). +- Auto-updates from signed releases, tokens in the operating system's keychain, code-signed + installers (no more SmartScreen or Gatekeeper prompts). - Global media keys, a compact always-on-top mini player, start with Windows. - Shareable "year in review" cards, comparing two periods side by side, playlist tools (find duplicates, sort and save). - Translations. -## Good to know - -- Spotify's February 2026 rules removed popularity scores, follower counts and some endpoints for - Development Mode apps. The app degrades gracefully and explains anything unavailable. -- Playback control needs Spotify Premium (a Spotify rule for every third-party app). Without it you - still get all stats, previews and "open in Spotify". -- The desktop app can't play Spotify audio by itself: Spotify's protected audio needs the Spotify app - (started hidden, see above) or a browser with Widevine, which Windows' app WebView lacks. The - browser version of Statsify can also play in the tab with **Devices → Play in this browser**. -- Lyrics come from [LRCLIB](https://lrclib.net), a free, community-built lyrics database (Spotify's - API has no lyrics). Popular songs are well covered; for less-known ones you may see plain lyrics or - none. Lyrics follow the position Spotify reports, polled every few seconds and smoothed in between; - if they run slightly early or late on your setup, nudge them with the timing control. - -## License & disclaimer - -Apache-2.0. Statsify is an independent project and is **not affiliated with, endorsed by or -sponsored by Spotify AB**. Spotify is a trademark of Spotify AB. Demo-mode artists, tracks and artwork -are fictional and generated. +## Licence and disclaimer + +Statsify is licensed under [Apache-2.0](LICENSE). It is an independent project and is **not +affiliated with, endorsed by or sponsored by Spotify AB**. Spotify is a trademark of Spotify AB. +Demo-mode artists, tracks and artwork are fictional and generated. From fa874c3dbe516970fc2c43b444c21f7f1a874558 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:50:06 +0000 Subject: [PATCH 10/41] docs: one job each for CONTRIBUTING and DEVELOPMENT CONTRIBUTING is the workflow: ways to help, where to read first, branches, commits, pull requests and code style. The command table, the Spotify account set-up, the Rust check commands and the test details it repeated now live only in DEVELOPMENT.md (which gains the command table) and AGENTS.md, linked from where they were. DEVELOPMENT.md's production build said VITE_SPOTIFY_REDIRECT_URI lets the app live below the root of a domain; the build links its files from "/", so it has to be at the root, with every unknown path answered by index.html. It now says so, with the frame-ancestors header and the release's web zip. The common problems point at the redirect list by name and add signing in on localhost. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- CONTRIBUTING.md | 100 ++++++++++++-------------------------------- docs/DEVELOPMENT.md | 64 ++++++++++++++++++++-------- 2 files changed, 72 insertions(+), 92 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0d6e2c7..9574e64 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,89 +4,35 @@ Thanks for helping make Statsify better! Bug reports, ideas, docs fixes and code - **Found a bug or have an idea?** Open an [issue](https://github.com/Kkkermit/Spotify-Stats/issues/new/choose). - **Found a security problem?** Please don't open an issue; see [SECURITY.md](SECURITY.md). -- **Want to write code?** Read on. [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) covers setting up - Windows, macOS or Linux, running, testing and debugging in detail. For a tour of the codebase - (architecture, conventions, how to add a page, a setting or a desktop command), see - [AGENTS.md](AGENTS.md). It is written for AI coding agents and new contributors alike. -- **Want to help another way?** Star the repository, answer an issue, improve the docs, or +- **Want to write code or docs?** Read on. +- **Want to help another way?** Star the repository, answer an issue, or [buy me a coffee](https://buymeacoffee.com/Kkermit). Everyone taking part is expected to follow the [Code of Conduct](CODE_OF_CONDUCT.md). -## Set up +## Before you start -You need [Node.js](https://nodejs.org/) 26 or newer and npm; for the desktop app, also -[Rust](https://rustup.rs/) 1.92 or newer and your system's Tauri prerequisites (the packages for -Windows, macOS and each Linux family are listed in -[docs/DEVELOPMENT.md](docs/DEVELOPMENT.md#prerequisites)). Then: +- [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) covers setting up Windows, macOS or Linux, every + command, running the tests and debugging. +- [AGENTS.md](AGENTS.md) is the tour of the codebase: how the app works, where things live, the + conventions, how to add a page, a setting or a desktop command, and what "done" means. It is + written for new contributors and AI coding agents alike. +- For anything bigger than a small fix, open an issue first (or comment on an existing one), so we + can agree on the approach before you spend time on it. + +The short version of the set-up, with [Node.js](https://nodejs.org/) 26 or newer: ```bash git clone https://github.com/Kkkermit/Spotify-Stats.git cd Spotify-Stats npm ci npm run dev # web app on http://127.0.0.1:5173 -npm run desktop:dev # or the desktop app, with hot reload -``` - -You don't need a Spotify account to work on most of the app: click **Explore the demo**. Demo -mode serves a fictional catalogue and three years of generated history from a local mock of the -Spotify API, so every page works offline. - -To use your own Spotify account, create a free app in the -[Spotify Developer Dashboard](https://developer.spotify.com/dashboard) as the -[README](README.md#one-time-spotify-setup-about-2-minutes) describes, with the redirect URI -`http://127.0.0.1:5173/callback` (and `http://127.0.0.1:43821/callback` for the desktop app). -Paste the Client ID into the app, or put it in a git-ignored `.env.local`: - -```bash -cp .env.example .env.local # then set VITE_SPOTIFY_CLIENT_ID ``` -The Client ID is a public identifier and there is **no client secret** (sign-in uses PKCE). Still, -keep your own ID in `.env.local` rather than in code. - -## Scripts - -| Command | What it does | -| ----------------------------------- | ------------------------------------------------------------------------- | -| `npm run dev` | Web dev server on `http://127.0.0.1:5173` (Spotify rejects `localhost`) | -| `npm run desktop:dev` | Desktop app with hot reload | -| `npm run desktop:build` | Desktop installers for your OS (`src-tauri/target/release/bundle/`) | -| `npm run typecheck` | TypeScript (`tsc -b`) | -| `npm run lint` | ESLint | -| `npm test` / `npm run test:watch` | Unit and component tests (Vitest) | -| `npm run test:coverage` | Unit tests with a coverage report in `coverage/` | -| `npm run build` / `npm run preview` | Production web build, and serving it on `http://127.0.0.1:4173` | -| `npm run e2e` | End-to-end tests with accessibility checks (Playwright) | -| `npm run check` | typecheck + lint + unit tests + build (what to run before a PR) | -| `npm run version:set -- 1.2.0` | Set the version in all six places (see [RELEASING.md](docs/RELEASING.md)) | - -Rust checks run inside `src-tauri/`. They compile the app, which embeds the built web app from -`dist/`, so build it first (`npm run build`) or create a placeholder like CI does: - -```bash -mkdir -p dist && echo 'ci' > dist/index.html -cd src-tauri -cargo fmt --check -cargo clippy --all-targets -- -D warnings -cargo test -``` - -## Tests - -- **Unit and component tests** (Vitest + Testing Library, jsdom) live next to the code as - `*.test.ts(x)`. Logic in `analytics/`, `history/`, `lyrics/`, `settings/` and `spotify/` is - pure on purpose, so test it directly. -- **End-to-end tests** (Playwright, `e2e/*.spec.ts`) run against the production build in three - sizes: desktop, tablet and phone. Install the browser once with - `npx playwright install chromium`. Most specs run on the desktop size only; put `[all sizes]` in - a test's title to run it on all three. Signed-in flows use a fake Spotify API - (`e2e/mock-spotify.ts`), desktop-only features a fake Tauri bridge (`e2e/fake-desktop.ts`), and - pages are checked with axe for WCAG 2.2 AA (`noSeriousA11y` in `e2e/helpers.ts`). -- **Rust tests** cover the history database, the sign-in listener and the Spotify launcher, and - call the commands through Tauri's IPC layer with its mock runtime (`src-tauri/tests/`). - -New behaviour needs a test; bug fixes need a test that fails without the fix. +You don't need a Spotify account for most work: click **Explore the demo**. Demo mode serves a +fictional catalogue and three years of generated history from a local mock of the Spotify API, so +every page works offline. To sign in with your own account, see +[With your own Spotify account](docs/DEVELOPMENT.md#with-your-own-spotify-account). ## Branches @@ -118,7 +64,9 @@ Before opening a pull request: - [ ] `npm run check` passes, and `npm run e2e` if the change touches the UI. - [ ] Rust changed: `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings` and `cargo test` pass in `src-tauri/`. -- [ ] New behaviour has tests. +- [ ] New behaviour has tests, and a bug fix has a test that fails without it: Vitest for logic + and components, Playwright (with an axe check) for what people see, Rust tests for the + desktop shell. [Test it](docs/DEVELOPMENT.md#test-it) shows how to run them. - [ ] UI changes work at desktop, tablet and phone sizes, by keyboard, with reduced motion, and in every theme (including Light and High contrast). - [ ] Error, empty and loading states are handled, in demo mode and with a real account. @@ -127,8 +75,9 @@ Before opening a pull request: - [ ] No secrets, tokens, Client IDs, personal data or real listening history in code, tests, fixtures, screenshots or logs. Use demo mode for screenshots. -Keep pull requests focused; a small PR gets reviewed sooner. Describe what changed and why, how -you tested it, and include screenshots for visible changes. +Keep pull requests focused; a small pull request gets reviewed sooner. Describe what changed and +why, how you tested it, and include screenshots for visible changes. The pull request template +asks for the same. **Title the pull request like a commit** (`feat(lyrics): ...`, `fix: ...`). A bot labels it from that type and from the files it changes (a maintainer labels pull requests from forks), and the @@ -143,7 +92,8 @@ release notes group changes by those labels; the maintainer may adjust them. - **CodeQL:** security scanning of the TypeScript, the Rust and the workflows. All of them must pass before merging. If an end-to-end test fails, the run's `e2e-failures` -artifact has screenshots of the failure. +artifact has screenshots of the failure. [Continuous integration](docs/DEVELOPMENT.md#continuous-integration) +lists every workflow. ## Releases @@ -158,6 +108,8 @@ everything. See [docs/RELEASING.md](docs/RELEASING.md). - Rust follows `rustfmt` and `clippy` with warnings as errors. - Comments explain **why**, not what: a Spotify API quirk, a platform difference, a security reason. See the conventions in [AGENTS.md](AGENTS.md#conventions). +- UI text uses the product name **Statsify**, plain English and British spelling ("colour", + "behaviour"). ## Licence diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 51f05d0..595d08a 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -44,6 +44,24 @@ npm ci `npm install `: `.npmrc` saves exact versions (no `^`), and the lockfile change goes in the same commit. +## Commands + +| Command | What it does | +| ----------------------------------- | -------------------------------------------------------------------------- | +| `npm run dev` | Web dev server on `http://127.0.0.1:5173` | +| `npm run desktop:dev` | Desktop app with hot reload (starts the web dev server too) | +| `npm run desktop:build` | Desktop installers for your system | +| `npm run build` / `npm run preview` | Production web build in `dist/`, and serving it on `http://127.0.0.1:4173` | +| `npm run typecheck` | TypeScript (`tsc -b`) | +| `npm run lint` | ESLint | +| `npm test` / `npm run test:watch` | Unit and component tests (Vitest) | +| `npm run test:coverage` | Unit tests with a coverage report in `coverage/` | +| `npm run e2e` | End-to-end tests with accessibility checks (Playwright) | +| `npm run check` | Typecheck, lint, unit tests and build: run it before every push | +| `npm run version:set -- 1.2.0` | Set the version in all six places (see [RELEASING.md](RELEASING.md)) | + +The Rust checks run with `cargo` inside `src-tauri/` (see [Rust checks](#rust-checks)). + ## Run it ### Web app @@ -104,9 +122,18 @@ npm run build # type-checks, then builds into dist/ npm run preview # serves dist/ on http://127.0.0.1:4173 ``` -`dist/` is a static site: any host that serves files over HTTPS works. Add -`https:///callback` as a redirect URI, and set `VITE_SPOTIFY_REDIRECT_URI` at build -time if the app doesn't live at the root of the domain. +`dist/` is a static site (each release also has it as `Statsify__web.zip`). To host it: + +- Serve it over HTTPS at the root of a domain or subdomain: its files are linked from `/`. +- Answer every path that isn't a file (such as `/callback` or `/top`) with `index.html`, as + single-page apps need. +- Add `https:///callback` as a redirect URI in your Spotify app. +- If your host can send headers, add `Content-Security-Policy: frame-ancestors 'none'` (the + page's own policy can't, so the app refuses to start inside a frame instead). + +Set `VITE_SPOTIFY_CLIENT_ID` at build time to fill in the Client ID for everyone using it (at most +five accounts, see the [README](../README.md#why-do-i-need-my-own-client-id)); leave it unset and +each person enters their own. ### Ports and settings @@ -119,11 +146,11 @@ taken, stop whatever uses it rather than picking another port. | 4173 | `npm run preview` and the end-to-end tests | | 43821 | The desktop app's sign-in listener | -| Variable | What it does | -| --------------------------- | --------------------------------------------------------------------------- | -| `VITE_SPOTIFY_CLIENT_ID` | Fills in the Client ID (in `.env.local`, or in CI as a repository variable) | -| `VITE_SPOTIFY_REDIRECT_URI` | Overrides the redirect address of a hosted web build | -| `E2E_PORT` | Runs the end-to-end tests on another port, so two runs can share a machine | +| Variable | What it does | +| --------------------------- | -------------------------------------------------------------------------------- | +| `VITE_SPOTIFY_CLIENT_ID` | Fills in the Client ID (in `.env.local`, or in CI as a repository variable) | +| `VITE_SPOTIFY_REDIRECT_URI` | Only when Spotify must send people back somewhere other than `/callback` | +| `E2E_PORT` | Runs the end-to-end tests on another port, so two runs can share a machine | ## Test it @@ -196,16 +223,17 @@ checks above cover it. Elsewhere, `rustup target add x86_64-pc-windows-msvc` and ### Common problems -| Problem | Fix | -| -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | -| Spotify says `INVALID_CLIENT: Invalid redirect URI` | Add the exact address from the table above to your Spotify app, `127.0.0.1` and all. | -| Spotify says the user isn't registered, or answers 403 | Add the account under **User Management** in the Spotify dashboard. | -| Playback buttons say Premium is required | A Spotify rule for every third-party app: playback control needs Premium. Stats, previews and the library work without it. | -| `Port 5173 is already in use` | Another dev server is running; stop it. | -| Cargo can't find `../dist` | Build the web app first, or make the placeholder (see [Rust checks](#rust-checks)). | -| Linux build can't find `webkit2gtk-4.1` or `javascriptcoregtk` | Install the Linux packages from [Prerequisites](#prerequisites). | -| Playwright says the browser executable doesn't exist | `npx playwright install chromium` | -| End-to-end tests see old behaviour | An old preview server is still on port 4173; stop it, or run with `E2E_PORT`. | +| Problem | Fix | +| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| Spotify says `INVALID_CLIENT: Invalid redirect URI` | Add the exact address from [With your own Spotify account](#with-your-own-spotify-account) to your Spotify app, `127.0.0.1` and all. | +| Sign-in fails on `http://localhost:5173` | Open `http://127.0.0.1:5173` instead: Spotify rejects `localhost`, and sign-in state is kept per address. | +| "Spotify didn't allow this", or Spotify answers 403 | Add the account under **User Management** in the Spotify dashboard. | +| Playback buttons say Premium is required | A Spotify rule for every third-party app: playback control needs Premium. Stats, previews and the library work without it. | +| `Port 5173 is already in use` | Another dev server is running; stop it. | +| Cargo can't find `../dist` | Build the web app first, or make the placeholder (see [Rust checks](#rust-checks)). | +| Linux build can't find `webkit2gtk-4.1` or `javascriptcoregtk` | Install the Linux packages from [Prerequisites](#prerequisites). | +| Playwright says the browser executable doesn't exist | `npx playwright install chromium` | +| End-to-end tests see old behaviour | An old preview server is still on port 4173; stop it, or run with `E2E_PORT`. | ## Continuous integration From b18b7a80ea13a402e5164c494d96ba287cb84db8 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:50:12 +0000 Subject: [PATCH 11/41] docs(security): list every permission and how the sign-in listener closes The policy read as if Statsify only asked to like songs and add to playlists. It now lists every permission in SCOPES, the two the browser build adds for Spotify's web player, and where to revoke access. The desktop listener closes after the first genuine callback, not only after five minutes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- SECURITY.md | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index f9d238c..8758a25 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -56,11 +56,18 @@ Out of scope: Content Security Policy allows no outside scripts and the app never renders data as HTML. Keeping them in the OS keychain instead is on the roadmap. - Sign-in uses the OAuth Authorization Code flow with PKCE only; there is no client secret. It - asks Spotify only for the permissions a feature uses: to like songs, and to add songs to your - own and collaborative playlists. Playlists it creates are private, and it never removes or - reorders anything in an existing playlist. -- The desktop sign-in listener binds the loopback interface only, accepts a single `GET /callback` - with the expected `state` and a loopback `Host` header, and closes after five minutes. + asks Spotify only for the permissions its features use (`SCOPES` in `app/spotify/auth.ts`): to + read your profile, top items, recently played, library, playlists and followed artists; to see + and control playback; and to create private playlists, add songs to your own and collaborative + playlists, and like songs. Playlists it creates are private, and it never removes or reorders + anything in an existing playlist. The browser build also asks for the two permissions Spotify's + Web Playback SDK requires (`streaming` and `user-read-email`); Statsify never reads the email + address. +- You can revoke Statsify's access at any time on Spotify's + [Manage apps](https://www.spotify.com/account/apps/) page. +- The desktop sign-in listener binds the loopback interface only, accepts nothing but + `GET /callback` with the expected `state` and a loopback `Host` header, closes after the first + such callback, and stops waiting after five minutes. - The desktop window gets least-privilege Tauri capabilities and a strict Content Security Policy; the web build ships a CSP that allows its one inline script by hash, and refuses to run inside another site's frame (clickjacking). If you host the web build, also send From 98fd8d92120f329377c92e59e553fbd4fb5b5592 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:50:12 +0000 Subject: [PATCH 12/41] docs: keep the doc index, repository map and done list in step AGENTS.md describes the README and user guide as they now are, lists every doc in docs/ and RELEASING.md in the definition of done, names lib/'s clipboard module, and says what following other tabs prevents rather than what once happened. CLAUDE.md says plainly that guidance belongs in AGENTS.md. RELEASING.md's six version places are in five files. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- AGENTS.md | 17 +++++++++-------- CLAUDE.md | 7 ++++--- docs/RELEASING.md | 2 +- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 12ce7ee..605a41a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,9 +2,9 @@ A guide to the Statsify codebase for AI coding agents and new contributors: what the app is, where things live, how data flows, the rules the code follows, and what "done" means. Read it before -changing code. Human-facing docs: [README.md](README.md) (install and setup), -[docs/GUIDE.md](docs/GUIDE.md) (user guide), [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) (setting -up, running, testing, debugging), [docs/DATABASE.md](docs/DATABASE.md) (history file format), +changing code. Human-facing docs: [README.md](README.md) (features, install, Spotify setup, FAQ), +[docs/GUIDE.md](docs/GUIDE.md) (user guide and troubleshooting), +[docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) (setting up, commands, testing, debugging), [docs/DATABASE.md](docs/DATABASE.md) (history file format), [docs/RELEASING.md](docs/RELEASING.md) (versions and the release pipeline), [CONTRIBUTING.md](CONTRIBUTING.md) (workflow), [SECURITY.md](SECURITY.md). @@ -79,7 +79,7 @@ app/ the React app (web and desktop UI) src-tauri/ the desktop shell (Rust, Tauri 2) e2e/ Playwright specs and their fakes scripts/ test set-up, repository-wide checks, the version script -docs/ user guide, database format, screenshots +docs/ user guide, development, database and release docs, README screenshots public/ static files served as-is (icons, web manifest, logo) .github/ workflows, release-notes and PR-label config, funding, CODEOWNERS, issue and PR templates, Dependabot index.html entry page; its inline script applies the saved theme before first paint @@ -99,7 +99,7 @@ index.html entry page; its inline script applies the saved theme befor | `settings/` | The persisted settings store (validated and migrated), applying settings to ``, the accent-colour token engine, per-playlist sort preferences | | `library/` | Your own playlist folders and sidebar pins (kept locally per account); liking songs (`liked.ts`) and adding them to playlists (`addToPlaylist.ts`) in your Spotify library | | `media/` | Artwork for history items (one track lookup at a time, cached) | -| `lib/` | Small shared modules: runtime config (`env`), the Tauri bridge (`platform`), the developer log, safe `localStorage` wrappers, formatting, hooks, toasts and announcements, error messages, image sizing, search matching, `cn` | +| `lib/` | Small shared modules: runtime config (`env`), the Tauri bridge (`platform`), the developer log, safe `localStorage` wrappers, formatting, hooks, toasts and announcements, error messages, image sizing, search matching, the clipboard, `cn` | | `pages/` | One lazy-loaded component per route (Overview, Top, Streams, Recent, Insights, Library, Playlist, Artist, Album, Search, Now playing, Lyrics, Import, Settings, Setup, Callback, Landing, errors) | | `components/` | `ui/` (design-system primitives: buttons, controls, dialog, menu, tooltips, layout, loading/empty/error states), `layout/` (app shell, sidebar, top bar, title bar, mobile nav, overlays, `nav.ts`), `charts/`, `media/` (artwork, cards, track lists), `player/`, `lyrics/`, `history/` (rankings, all time, detail sheet), `insights/` (the Insights page sections and their data), `library/` (folder dialogs, playlist card menu, instant playlists, the heart, "Add to playlist"), `immersive/`, `devlog/` (panel, right-click menu), `settings/` (setting groups, theme and accent pickers, account), `auth/` (signing in, the "sign in again" prompt), `brand/` | | `styles/` | `index.css`: Tailwind import, design tokens per theme, component classes, keyframes, reduced-motion rules | @@ -201,7 +201,7 @@ on the first F instead, the window would turn solid for full screen before the p - **Tabs follow each other** (`followStoredSession`, on `storage` events for `ss.auth` and `ss.demo`): a sign-out, a sign-in as someone else or the demo in one tab becomes a new session in the others; the same sign-in refreshed elsewhere (same `login` id in the tokens) only swaps the - tokens. Otherwise a tab left open wrote its tokens back after a sign-out elsewhere. + tokens. Without this, a tab left open would write its tokens back after a sign-out elsewhere. ### Spotify API client and query layer @@ -920,8 +920,9 @@ A change is done when: and phone to desktop sizes are handled; demo mode still works. - [ ] No secrets, personal data or new network hosts slipped in; anything secret-bearing is redacted in the developer log. -- [ ] Docs match the code: README (features, setup), `docs/GUIDE.md` (user-visible behaviour), - `docs/DEVELOPMENT.md` (set-up, commands, CI), `docs/DATABASE.md` (schema), and this file +- [ ] Docs match the code: README (features, install, setup, FAQ), `docs/GUIDE.md` (user-visible + behaviour and troubleshooting), `docs/DEVELOPMENT.md` (set-up, commands, CI), + `docs/DATABASE.md` (schema), `docs/RELEASING.md` (the release pipeline), and this file (architecture, commands, conventions). - [ ] Commits follow the [commit style](CONTRIBUTING.md#commits) on a `feature/` branch. diff --git a/CLAUDE.md b/CLAUDE.md index 1f4a7d4..eff6f9f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,6 +2,7 @@ @AGENTS.md -`AGENTS.md` is the guide for every coding agent and new contributor: what the app is, where things -live, the conventions, and the checks a change must pass. Keep it up to date when the architecture, -commands or conventions change; put nothing Claude-specific here that other agents would also need. +[AGENTS.md](AGENTS.md) is the guide for every coding agent and new contributor: what the app is, +where things live, the conventions, and the checks a change must pass. Keep it up to date when the +architecture, commands or conventions change. Put guidance there rather than here, so that every +agent sees it; this file only imports it for Claude Code. diff --git a/docs/RELEASING.md b/docs/RELEASING.md index cd6797d..9d4b668 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -16,7 +16,7 @@ Statsify follows [Semantic Versioning](https://semver.org/): - **Pre-release** (`1.3.0-beta.1`, `1.3.0-rc.1`): for testing before a release. Marked as a pre-release on GitHub, so it never becomes "latest". -The version is written in six places that must agree: `package.json`, `package-lock.json`, +The version is written in six places that must agree: `package.json`, `package-lock.json` (twice), `src-tauri/tauri.conf.json` (the number installers and the app show), `src-tauri/Cargo.toml` and `src-tauri/Cargo.lock`. One command sets them all: From 6b95861dac8cf3193a5a0509aa0afa28bd159cdc Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:50:16 +0000 Subject: [PATCH 13/41] docs(github): point bug reporters at troubleshooting first The issue chooser and the bug form link to the user guide's troubleshooting. The version field says where to find it in each build (the browser build shows no number in Settings), and the warning names sign-in links for what they carry. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- .github/ISSUE_TEMPLATE/bug_report.yml | 6 +++--- .github/ISSUE_TEMPLATE/config.yml | 3 +++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index e493245..f37ed9a 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -7,7 +7,7 @@ body: value: | Thanks for taking the time to report a bug. Please check the [open issues](https://github.com/Kkkermit/Spotify-Stats/issues) first, and **don't use this form for security problems**: report those privately (see [SECURITY.md](https://github.com/Kkkermit/Spotify-Stats/blob/main/SECURITY.md)). - Never paste access tokens, your Client ID's sign-in links, or your listening history here. + Never paste access tokens, sign-in links (they carry one-time codes), or your listening history here. Many problems already have an answer in the user guide's [Troubleshooting](https://github.com/Kkkermit/Spotify-Stats/blob/main/docs/GUIDE.md#troubleshooting). - type: textarea id: what-happened attributes: @@ -41,8 +41,8 @@ body: id: version attributes: label: Statsify version - description: Settings → Data & about, or right-click anywhere → Developer log → System. - placeholder: "1.0.0" + description: In the desktop app, Settings → Data & about. In a browser, the release or commit you built from. + placeholder: "1.1.1" validations: required: true - type: dropdown diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 41811ac..b1c801d 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -6,3 +6,6 @@ contact_links: - name: Help with the Spotify developer app setup url: https://github.com/Kkkermit/Spotify-Stats#one-time-spotify-setup-about-2-minutes about: Client ID, redirect URIs and user management, step by step. + - name: Troubleshooting and FAQ + url: https://github.com/Kkkermit/Spotify-Stats/blob/main/docs/GUIDE.md#troubleshooting + about: What Statsify's messages mean (sign-in, playback, lyrics, importing) and what to do. From 1d76a36ea467c980438a823c638dff00bced4039 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:52:41 +0000 Subject: [PATCH 14/41] fix(settings): describe the transparent background for the build it's in On macOS and Linux the description promised "a Windows 11 frosted backdrop", which only the Windows build has. The Windows build points to the window material below, other desktop builds just say the desktop shows through, and the browser keeps its own description. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- app/pages/Settings.test.tsx | 39 +++++++++++++++++++++++++++++++++++-- app/pages/Settings.tsx | 8 +++++++- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/app/pages/Settings.test.tsx b/app/pages/Settings.test.tsx index 4e06daf..68c8228 100644 --- a/app/pages/Settings.test.tsx +++ b/app/pages/Settings.test.tsx @@ -1,11 +1,29 @@ import { screen } from "@testing-library/react"; -import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { renderWithProviders } from "../components/testUtils"; +import type * as Platform from "../lib/platform"; import { enterDemo, signOut } from "../spotify/auth"; import Settings from "./Settings"; +/** Which build the page thinks it's in: the browser, or the desktop app with or without window materials. */ +const build = vi.hoisted(() => ({ desktop: false, materials: false })); +vi.mock("../lib/platform", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + get IS_DESKTOP() { + return build.desktop; + }, + windowMaterialsAvailable: () => build.materials, + }; +}); + beforeEach(() => enterDemo()); -afterEach(() => signOut()); +afterEach(() => { + signOut(); + build.desktop = false; + build.materials = false; +}); describe("Settings", () => { it("names every group after its heading, including titles with spaces and symbols", async () => { @@ -21,4 +39,21 @@ describe("Settings", () => { expect(screen.getByRole("slider", { name: "Interface size" })).toBeInTheDocument(); expect(screen.getByRole("radiogroup", { name: "Theme" })).toBeInTheDocument(); }); + + it("describes the transparent background for the build it's in: materials only on Windows", () => { + const description = () => screen.getByRole("switch", { name: "Transparent background" }).closest("[class]")?.parentElement?.textContent ?? ""; + const { unmount } = renderWithProviders(); + expect(description()).toContain("soft glow from your current track's artwork"); + unmount(); + + build.desktop = true; + const mac = renderWithProviders(); + expect(description()).toContain("Let your desktop show through the window."); + expect(description()).not.toMatch(/frosted|Windows/); + mac.unmount(); + + build.materials = true; + renderWithProviders(); + expect(description()).toContain("window material below"); + }); }); diff --git a/app/pages/Settings.tsx b/app/pages/Settings.tsx index 85b9f09..283c5e8 100644 --- a/app/pages/Settings.tsx +++ b/app/pages/Settings.tsx @@ -52,7 +52,13 @@ export default function Settings() { s.set("transparency", v)} /> From bd2e4c97d8ae6bab0172bb2dcbb99c1b73638ebb Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:58:49 +0000 Subject: [PATCH 15/41] fix(oauth): answer the sign-in redirect without tiny_http One request to the sign-in listener announcing a body it never sends (`Content-Length: 99999999999999`) aborted the whole app: tiny_http drains an unread body when a request is dropped, allocating a buffer of the announced size first. A smaller one left the listener blocked on the missing body for good, holding the port, so sign-in couldn't finish or be started again until a restart. The listener is now a small std::net loop that speaks only what a browser sends to a redirect URI: one request per connection, its line and headers capped at 8 KB and 10 s, answered on its own short-lived thread with `Connection: close`, and no body ever read. Slow, oversized, malformed and many concurrent connections are refused without holding up the callback. Also: - A listener whose wait had ended (timed out, or its callback answered) could still be retargeted by a sign-in started in that instant, leaving the new sign-in waiting on a closed port. Ending the wait and retargeting now decide under the same lock. - Waiting costs nothing: the threads sleep until a connection, the deadline or a cancel, instead of waking four times a second; a cancel frees the port at once. - `oauth_cancel` runs on a worker thread: on the main thread it could wait up to a second for a sign-in still binding the port. - The callback page is sent with `Cache-Control: no-store` (its address holds the sign-in code), and only `Host: 127.0.0.1:` is accepted: the listener never binds IPv6, so `[::1]` could not reach it anyway. - tiny_http, ascii, chunked_transfer and httpdate leave the build. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- AGENTS.md | 11 +- src-tauri/Cargo.lock | 31 -- src-tauri/Cargo.toml | 1 - src-tauri/src/oauth.rs | 785 +++++++++++++++++++++++++++-------- src-tauri/tests/oauth_ipc.rs | 165 ++++++++ 5 files changed, 794 insertions(+), 199 deletions(-) create mode 100644 src-tauri/tests/oauth_ipc.rs diff --git a/AGENTS.md b/AGENTS.md index 12ce7ee..08f687b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,7 +38,7 @@ with no account and no network; the end-to-end tests use it. | Imports | `fflate` (zip) in a Web Worker | | Icons, font | `lucide-react`, Figtree (bundled via `@fontsource-variable`, no network fonts) | | Charts | Hand-built SVG and a WebGL shader (album-colour waves) | -| Desktop | Tauri 2 (Rust 2021, MSRV 1.92), `rusqlite` (bundled SQLite), `tiny_http` | +| Desktop | Tauri 2 (Rust 2021, MSRV 1.92), `rusqlite` (bundled SQLite) | | Tauri plugins | `opener`, `single-instance`, `window-state` | | Tests | Vitest + Testing Library (jsdom), Playwright + `@axe-core/playwright`, `cargo test` | | CI/CD | GitHub Actions: CI, desktop installers, tagged releases, CodeQL, PR labels (see Testing) | @@ -177,9 +177,10 @@ on the first F instead, the window would turn solid for full screen before the p user's normal browser, and waits for the `oauth-callback` event. The listener only accepts `GET /callback` with the matching `state` and a loopback `Host` header (anti DNS-rebinding), answers anything else with an error page and keeps waiting, closes after the first genuine - callback, and times out after five minutes. A sign-in started while one is pending reuses the - listener with the new `state` and five minutes from then. If no browser opens, the UI shows the - link to copy. + callback, and times out after five minutes. It reads one request per connection, its headers + capped at 8 KB and 10 s and never its body, so slow or oversized requests can't stall or + crash it. A sign-in started while one is pending reuses the listener with the new `state` and + five minutes from then. If no browser opens, the UI shows the link to copy. - **A wrong Client ID** never comes back: Spotify shows *INVALID_CLIENT* on its own page. So the landing page shows the ID in use (masked, `maskClientId`) with **Change**, the desktop wait offers **Wrong Client ID?** (cancels and opens `/setup`) next to Cancel, and a failed sign-in @@ -494,7 +495,7 @@ start-up. | `app_info` | Version, OS, architecture | | | `open_devtools` | WebView inspector (release builds too) | Only shows the user their own app | | `oauth_listen` | Start or retarget the loopback sign-in listener | Async; binds 127.0.0.1 only; emits `oauth-callback` | -| `oauth_cancel` | Stop a pending listener | | +| `oauth_cancel` | Stop a pending listener | Async (waits for a sign-in still binding the port) | | `set_tray_tooltip` | Current song in the tray tooltip | Clipped to 120 UTF-16 units (Windows holds 128) | | `history_load` | Whole account history as a binary blob | Async, blocking worker; raw IPC response | | `history_apply` | Insert/delete plays and account metadata in one transaction | Async; validates everything | diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index bd8ed25..191fd28 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -47,12 +47,6 @@ version = "1.0.105" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" -[[package]] -name = "ascii" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" - [[package]] name = "async-broadcast" version = "0.7.2" @@ -465,12 +459,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "chunked_transfer" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901" - [[package]] name = "combine" version = "4.6.9" @@ -1459,12 +1447,6 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - [[package]] name = "hybrid-array" version = "0.4.15" @@ -3211,7 +3193,6 @@ dependencies = [ "tauri-plugin-opener", "tauri-plugin-single-instance", "tauri-plugin-window-state", - "tiny_http", "window-vibrancy", "windows-sys 0.61.2", ] @@ -3774,18 +3755,6 @@ dependencies = [ "time-core", ] -[[package]] -name = "tiny_http" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82" -dependencies = [ - "ascii", - "chunked_transfer", - "httpdate", - "log", -] - [[package]] name = "tinystr" version = "0.8.5" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index fff3c1a..b099970 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -25,7 +25,6 @@ tauri-plugin-single-instance = "2" tauri-plugin-window-state = "2" serde = { version = "1", features = ["derive"] } serde_json = "1" -tiny_http = "0.12" # Listening history: SQLite compiled in, so there is nothing extra to install. rusqlite = { version = "0.43", features = ["bundled"] } diff --git a/src-tauri/src/oauth.rs b/src-tauri/src/oauth.rs index 5fd49e6..8670dd2 100644 --- a/src-tauri/src/oauth.rs +++ b/src-tauri/src/oauth.rs @@ -9,30 +9,53 @@ //! - only `GET /callback` requests whose `Host` is the loopback address and whose `state` //! matches the sign-in the UI started are accepted; anything else gets an error page and the //! listener keeps waiting, so a stray or hostile request can't end a sign-in; +//! - one request per connection, its line and headers capped at `MAX_HEAD` bytes and +//! `HEAD_TIMEOUT`, and no body is ever read: a slow, oversized or endless request costs one +//! short-lived thread, never memory sized to what it claims or a wait the callback is stuck +//! behind; //! - single-use: the listener closes after the first genuine callback; //! - starting a new sign-in while one is pending reuses the running listener with the new state, //! and the new sign-in gets the full five minutes. - -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex}; +//! +//! The HTTP spoken here is only what a browser sends to a redirect URI: a request line and +//! headers, answered with a small page and `Connection: close`. Waiting costs nothing: the +//! threads sleep until a connection, the deadline or a cancel wakes them. + +use std::io::{Read, Write}; +use std::net::{Ipv4Addr, Shutdown, SocketAddr, TcpListener, TcpStream}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::thread; use std::time::{Duration, Instant}; -use tauri::{AppHandle, Emitter, Manager, Runtime, State}; +use tauri::{AppHandle, Emitter, Manager, Runtime}; const DONE_PAGE: &str = include_str!("../assets/oauth-done.html"); +const BAD_REQUEST_PAGE: &str = "Statsify

This sign-in link doesn't match the sign-in in progress. Return to Statsify and try again.

"; const LISTEN_TIMEOUT: Duration = Duration::from_secs(300); -/// How often the listener checks whether it was cancelled or timed out. -const POLL: Duration = Duration::from_millis(250); -/// A cancelled listener lets go of its port within about one `POLL`, so a sign-in started right -/// after a cancel retries the bind for this long before reporting the port as taken. +/// A stopped listener lets go of its port a moment after it is told to, so a sign-in started +/// right after a cancel retries the bind for this long before reporting the port as taken. const BIND_RETRY: Duration = Duration::from_secs(1); -const BAD_REQUEST_PAGE: &str = "Statsify

This sign-in link doesn't match the sign-in in progress. Return to Statsify and try again.

"; +/// Most bytes a request's line and headers may take. A browser's redirect, with Spotify's code +/// and the state in the address, is well under 2 KB. +const MAX_HEAD: usize = 8 * 1024; +/// How long a connection has to send them. Browsers send them at once; a connection a browser +/// opens speculatively and never uses is closed after this. +const HEAD_TIMEOUT: Duration = Duration::from_secs(10); +/// How long sending an answer, and waiting for the client to close afterwards, may take. +const CLOSE_TIMEOUT: Duration = Duration::from_secs(2); +/// Connections answered at once; more are closed straight away. A browser uses a handful. +const MAX_CONNECTIONS: usize = 64; /// The sign-in a listener waits for: its `state`, and when the wait ends. A new sign-in while one /// is pending replaces both, so the listener lasts as long as the sign-in the UI is waiting for. struct Target { state: String, deadline: Instant, + /// The callback arrived, or the wait was cancelled or timed out. Whoever sets this sends + /// the listener its `Event` before letting go of the lock. + finished: bool, } impl Target { @@ -40,14 +63,27 @@ impl Target { Self { state, deadline: Instant::now() + LISTEN_TIMEOUT, + finished: false, } } + + /// Still waiting for its callback. Checked under the target's lock together with whatever + /// acts on the answer, so a retarget can't revive a listener that is stopping. + fn open(&self) -> bool { + !self.finished && Instant::now() < self.deadline + } +} + +/// What ends a listener's wait, besides its deadline. +enum Event { + Callback(String), + Cancel, } struct Listener { port: u16, - cancel: Arc, target: Arc>, + events: Sender, } #[derive(Default)] @@ -55,11 +91,19 @@ pub struct OAuthState { active: Mutex>, } +/// What these locks guard is consistent at every step, so a panic elsewhere while one was held +/// is no reason to stop signing in. +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + impl OAuthState { fn cancel_running(&self) { - if let Ok(mut guard) = self.active.lock() { - if let Some(listener) = guard.take() { - listener.cancel.store(true, Ordering::SeqCst); + if let Some(listener) = lock(&self.active).take() { + let mut target = lock(&listener.target); + if !target.finished { + target.finished = true; + let _ = listener.events.send(Event::Cancel); } } } @@ -70,15 +114,6 @@ struct CallbackPayload { url: String, } -fn html_response(body: &str, status: u16) -> tiny_http::Response>> { - let header = - tiny_http::Header::from_bytes(&b"Content-Type"[..], &b"text/html; charset=utf-8"[..]) - .expect("static header is valid"); - tiny_http::Response::from_string(body) - .with_status_code(status) - .with_header(header) -} - fn hex_digit(byte: Option<&u8>) -> Option { byte.and_then(|b| char::from(*b).to_digit(16)) .map(|d| d as u8) @@ -121,142 +156,338 @@ fn query_param(path: &str, name: &str) -> Option { }) } -/// Is this request the genuine redirect for the sign-in in progress? -fn is_expected_callback(request: &tiny_http::Request, port: u16, expected_state: &str) -> bool { - if *request.method() != tiny_http::Method::Get { - return false; +/// What the listener looks at in a request: its request line and its `Host` header. +#[derive(Debug, PartialEq, Eq)] +struct Request<'a> { + method: &'a str, + target: &'a str, + /// None without exactly one `Host` header. + host: Option<&'a str>, +} + +/// A request's line and headers (without the blank line that ends them), or None if they +/// aren't HTTP/1.x. +fn parse_head(head: &str) -> Option> { + let mut lines = head.split("\r\n"); + let mut parts = lines.next()?.split(' '); + let (method, target, version) = (parts.next()?, parts.next()?, parts.next()?); + if parts.next().is_some() || !matches!(version, "HTTP/1.0" | "HTTP/1.1") { + return None; } - let url = request.url(); - let path_only = url.split('?').next().unwrap_or(""); - if path_only != "/callback" { - return false; + let mut hosts = Vec::new(); + for line in lines { + let (name, value) = line.split_once(':')?; + if name.eq_ignore_ascii_case("host") { + hosts.push(value.trim_matches([' ', '\t'])); + } } + Some(Request { + method, + target, + host: match hosts[..] { + [host] => Some(host), + _ => None, + }, + }) +} + +/// Is this request the genuine redirect for the sign-in in progress? +fn is_expected_callback(request: &Request, port: u16, expected_state: &str) -> bool { + let path = request.target.split('?').next().unwrap_or(""); // Block DNS-rebinding pages: the browser sends the page's own host name here. - let host_ok = request.headers().iter().any(|h| { - h.field.equiv("Host") && { - let value = h.value.as_str(); - value == format!("127.0.0.1:{port}") || value == format!("[::1]:{port}") - } - }); - host_ok + let host_ok = request.host == Some(format!("127.0.0.1:{port}").as_str()); + request.method == "GET" + && path == "/callback" + && host_ok + && request.target.bytes().all(|b| b.is_ascii_graphic()) && !expected_state.is_empty() - && query_param(url, "state").as_deref() == Some(expected_state) + && query_param(request.target, "state").as_deref() == Some(expected_state) } -fn bind(port: u16) -> Result { - let deadline = Instant::now() + BIND_RETRY; +/// Why a connection's request couldn't be read. +#[derive(Debug, PartialEq, Eq)] +enum HeadError { + /// Closed, failed or out of time before its headers ended: there is nothing to answer. + Gone, + TooLarge, + NotText, +} + +/// Read a request's line and headers, up to the blank line that ends them. Whatever follows +/// them, such as a body, is never read. +fn read_head(stream: &mut TcpStream) -> Result { + const END: &[u8] = b"\r\n\r\n"; + let deadline = Instant::now() + HEAD_TIMEOUT; + let mut head = Vec::with_capacity(1024); + let mut chunk = [0; 1024]; loop { - match tiny_http::Server::http(("127.0.0.1", port)) { - Ok(server) => return Ok(server), - Err(_) if Instant::now() < deadline => std::thread::sleep(POLL / 5), - Err(err) => { - return Err(format!( - "Could not open the sign-in listener on 127.0.0.1:{port}. Is another app using that port? ({err})" - )) + // Never more than MAX_HEAD bytes and the blank line, so a head found is small enough. + let room = (MAX_HEAD + END.len() - head.len()).min(chunk.len()); + if room == 0 { + return Err(HeadError::TooLarge); + } + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() || stream.set_read_timeout(Some(left)).is_err() { + return Err(HeadError::Gone); + } + let read = match stream.read(&mut chunk[..room]) { + Ok(0) | Err(_) => return Err(HeadError::Gone), + Ok(read) => read, + }; + // The blank line may straddle two reads. + let from = head.len().saturating_sub(END.len() - 1); + head.extend_from_slice(&chunk[..read]); + if let Some(end) = head[from..].windows(END.len()).position(|w| w == END) { + head.truncate(from + end); + return String::from_utf8(head).map_err(|_| HeadError::NotText); + } + } +} + +/// Send the answer and close the connection. +fn respond(mut stream: TcpStream, status: u16, page: &str) { + let reason = match status { + 200 => "OK", + 404 => "Not Found", + 431 => "Request Header Fields Too Large", + _ => "Bad Request", + }; + // no-store: the callback's address holds a sign-in code, which nothing should keep. + let head = format!( + "HTTP/1.1 {status} {reason}\r\nContent-Type: text/html; charset=utf-8\r\n\ + Content-Length: {}\r\nCache-Control: no-store\r\nReferrer-Policy: no-referrer\r\n\ + X-Content-Type-Options: nosniff\r\nConnection: close\r\n\r\n", + page.len() + ); + let _ = stream.set_write_timeout(Some(CLOSE_TIMEOUT)); + let sent = stream + .write_all(head.as_bytes()) + .and_then(|()| stream.write_all(page.as_bytes())) + .and_then(|()| stream.shutdown(Shutdown::Write)); + if sent.is_err() { + return; + } + // Closing a socket with unread input resets the connection, and the client may then lose + // the answer: read what is left (an unread body, say) until the client closes, for a while. + let _ = stream.set_read_timeout(Some(CLOSE_TIMEOUT)); + let deadline = Instant::now() + CLOSE_TIMEOUT; + let mut sink = [0; 1024]; + while Instant::now() < deadline && matches!(stream.read(&mut sink), Ok(n) if n > 0) {} +} + +/// Answer one connection. The genuine callback finishes the target and is sent on `events`. +fn handle(mut stream: TcpStream, port: u16, target: &Mutex, events: &Sender) { + let (status, page) = match read_head(&mut stream) { + Err(HeadError::Gone) => return, + Err(HeadError::TooLarge) => (431, BAD_REQUEST_PAGE), + Err(HeadError::NotText) => (400, BAD_REQUEST_PAGE), + Ok(head) => match parse_head(&head) { + None => (400, BAD_REQUEST_PAGE), + Some(request) => { + let mut target = lock(target); + if target.open() && is_expected_callback(&request, port, &target.state) { + target.finished = true; + let url = format!("http://127.0.0.1:{port}{}", request.target); + let _ = events.send(Event::Callback(url)); + drop(target); + (200, DONE_PAGE) + } else if request.target.starts_with("/callback") { + (400, BAD_REQUEST_PAGE) + } else { + (404, BAD_REQUEST_PAGE) + } } + }, + }; + respond(stream, status, page); +} + +/// Counts a connection being answered while it lives. +struct Slot(Arc); + +impl Slot { + fn take(busy: &Arc) -> Option { + let slot = Slot(busy.clone()); + (busy.fetch_add(1, Ordering::SeqCst) < MAX_CONNECTIONS).then_some(slot) + } +} + +impl Drop for Slot { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::SeqCst); + } +} + +/// Accept connections until `stop` is set, answering each on a thread of its own so one slow +/// client never holds up another. +fn accept( + socket: TcpListener, + port: u16, + target: Arc>, + events: Sender, + stop: Arc, +) { + let busy = Arc::new(AtomicUsize::new(0)); + for stream in socket.incoming() { + if stop.load(Ordering::SeqCst) { + break; + } + let Ok(stream) = stream else { + // Out of file handles, say: wait a little rather than spin. + thread::sleep(Duration::from_millis(50)); + continue; + }; + // Over the limit, the connection is dropped, which closes it. + let Some(slot) = Slot::take(&busy) else { + continue; + }; + let (target, events) = (target.clone(), events.clone()); + // If no thread can be started, the closure is dropped with the connection and its slot. + let _ = thread::Builder::new() + .name("sign-in request".into()) + .spawn(move || { + handle(stream, port, &target, &events); + drop(slot); + }); + } +} + +/// Wait for the callback (its URL), a cancel, or the target's deadline. +fn wait(events: &Receiver, target: &Mutex) -> Option { + loop { + let left = { + let mut target = lock(target); + if target.finished { + // Its event is already queued. + None + } else { + let left = target.deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + target.finished = true; + return None; + } + Some(left) + } + }; + let event = match left { + Some(left) => events.recv_timeout(left), + None => events.recv().map_err(|_| RecvTimeoutError::Disconnected), + }; + match event { + Ok(Event::Callback(url)) => return Some(url), + Ok(Event::Cancel) | Err(RecvTimeoutError::Disconnected) => return None, + // The deadline passed, unless a new sign-in moved it: look again. + Err(RecvTimeoutError::Timeout) => {} } } } /// Answer requests until the genuine callback arrives (its URL is returned), the listener is -/// cancelled, or the target's deadline passes. +/// cancelled, or the target's deadline passes. The port is free again when this returns. fn serve( - server: &tiny_http::Server, + socket: TcpListener, port: u16, - cancel: &AtomicBool, - target: &Mutex, + target: &Arc>, + events: (Sender, Receiver), ) -> Option { - // A poisoned lock means no sign-in can match: the listener stops. - let deadline = || { - target - .lock() - .map(|t| t.deadline) - .unwrap_or_else(|_| Instant::now()) + let (sender, receiver) = events; + let stop = Arc::new(AtomicBool::new(false)); + let acceptor = { + let (target, stop) = (target.clone(), stop.clone()); + thread::Builder::new() + .name("sign-in listener".into()) + .spawn(move || accept(socket, port, target, sender, stop)) }; - while Instant::now() < deadline() && !cancel.load(Ordering::SeqCst) { - let request = match server.recv_timeout(POLL) { - Ok(Some(request)) => request, - Ok(None) => continue, - Err(_) => return None, - }; - let current = target.lock().map(|t| t.state.clone()).unwrap_or_default(); - if is_expected_callback(&request, port, ¤t) { - let url = format!("http://127.0.0.1:{port}{}", request.url()); - let _ = request.respond(html_response(DONE_PAGE, 200)); - return Some(url); + let callback = match &acceptor { + Ok(_) => wait(&receiver, target), + Err(_) => None, + }; + // However the wait ended, this listener takes no more callbacks and can't be retargeted. + lock(target).finished = true; + let Ok(acceptor) = acceptor else { + return None; + }; + stop.store(true, Ordering::SeqCst); + // `accept` sleeps until a connection comes: make one, so it sees `stop` and closes the port. + let address = SocketAddr::from((Ipv4Addr::LOCALHOST, port)); + if TcpStream::connect_timeout(&address, CLOSE_TIMEOUT).is_ok() { + let _ = acceptor.join(); + } + callback +} + +fn bind(port: u16) -> Result { + let deadline = Instant::now() + BIND_RETRY; + loop { + match TcpListener::bind((Ipv4Addr::LOCALHOST, port)) { + Ok(socket) => return Ok(socket), + Err(_) if Instant::now() < deadline => thread::sleep(Duration::from_millis(50)), + Err(err) => { + return Err(format!( + "Could not open the sign-in listener on 127.0.0.1:{port}. Is another app using that port? ({err})" + )) + } } - let status = if request.url().starts_with("/callback") { - 400 - } else { - 404 - }; - let _ = request.respond(html_response(BAD_REQUEST_PAGE, status)); } - None } /// Point the running listener, if any, at a new sign-in (see `Target`): its port, or None when no -/// listener is still running. +/// listener is still waiting. fn retarget(active: &Option, expected_state: &str) -> Option { - let listener = active - .as_ref() - .filter(|l| !l.cancel.load(Ordering::SeqCst))?; - if let Ok(mut target) = listener.target.lock() { - *target = Target::new(expected_state.to_string()); + let listener = active.as_ref()?; + let mut target = lock(&listener.target); + if !target.open() { + return None; } + *target = Target::new(expected_state.to_string()); Some(listener.port) } fn listen(app: AppHandle, port: u16, expected_state: String) -> Result { let state = app.state::(); - // Held until the new listener is registered, so two quick sign-ins can't both bind. - let mut guard = state - .active - .lock() - .map_err(|_| "Sign-in listener is unavailable".to_string())?; + // Held until the new listener is registered, so two quick sign-ins can't both bind, and a + // cancel sent meanwhile stops the listener this starts. + let mut active = lock(&state.active); // A listener is already running (the window reloaded during a sign-in, say): retarget it. - if let Some(port) = retarget(&guard, &expected_state) { + if let Some(port) = retarget(&active, &expected_state) { return Ok(port); } - let server = bind(port)?; - let bound_port = server - .server_addr() - .to_ip() - .map(|addr| addr.port()) - .unwrap_or(port); - - let cancel = Arc::new(AtomicBool::new(false)); + let socket = bind(port)?; + let port = socket + .local_addr() + .map_err(|e| format!("Could not open the sign-in listener: {e}"))? + .port(); let target = Arc::new(Mutex::new(Target::new(expected_state))); - *guard = Some(Listener { - port: bound_port, - cancel: cancel.clone(), + let (sender, receiver) = mpsc::channel(); + let listener = Listener { + port, target: target.clone(), - }); - drop(guard); - - std::thread::spawn(move || { - let callback = serve(&server, bound_port, &cancel, &target); - cancel.store(true, Ordering::SeqCst); - // Free the port before taking the lock: a new sign-in may hold it while it binds. - drop(server); - if let Some(url) = callback { - let _ = app.emit("oauth-callback", CallbackPayload { url }); - crate::show_main_window(&app); - } - let state = app.state::(); - if let Ok(mut guard) = state.active.lock() { - if guard + events: sender.clone(), + }; + let app_handle = app.clone(); + thread::Builder::new() + .name("sign-in".into()) + .spawn(move || { + let callback = serve(socket, port, &target, (sender, receiver)); + if let Some(url) = callback { + let _ = app_handle.emit("oauth-callback", CallbackPayload { url }); + crate::show_main_window(&app_handle); + } + // Taken only once the port is free: a new sign-in may hold it while it binds. + let state = app_handle.state::(); + let mut active = lock(&state.active); + if active .as_ref() - .is_some_and(|l| Arc::ptr_eq(&l.cancel, &cancel)) + .is_some_and(|l| Arc::ptr_eq(&l.target, &target)) { - *guard = None; + *active = None; } - }; - }); - - Ok(bound_port) + }) + .map_err(|e| format!("Could not start the sign-in listener: {e}"))?; + *active = Some(listener); + Ok(port) } /// Start listening for the OAuth redirect for `expected_state`. Returns the port in use. @@ -272,17 +503,19 @@ pub async fn oauth_listen( .map_err(|e| format!("Sign-in listener failed: {e}"))? } -/// Stop a pending listener (the user cancelled sign-in). +/// Stop a pending listener (the user cancelled sign-in). On a worker thread, because it waits +/// for a sign-in that is still binding its port. #[tauri::command] -pub fn oauth_cancel(state: State<'_, OAuthState>) { - state.cancel_running(); +pub async fn oauth_cancel(app: AppHandle) { + let _ = tauri::async_runtime::spawn_blocking(move || { + app.state::().cancel_running(); + }) + .await; } #[cfg(test)] mod tests { use super::*; - use std::io::{Read, Write}; - use std::net::TcpStream; #[test] fn parses_and_decodes_query_params() { @@ -311,46 +544,95 @@ mod tests { assert_eq!(percent_decode("%é"), "%é"); } + #[test] + fn reads_the_request_line_and_the_one_host_header() { + let request = |method, target, host| Request { + method, + target, + host, + }; + assert_eq!( + parse_head("GET /callback?state=s HTTP/1.1\r\nhost: 127.0.0.1:1 \r\nAccept: */*"), + Some(request("GET", "/callback?state=s", Some("127.0.0.1:1"))) + ); + assert_eq!( + parse_head("GET / HTTP/1.0"), + Some(request("GET", "/", None)) + ); + assert_eq!( + parse_head("GET / HTTP/1.1\r\nHost: a\r\nHost: b"), + Some(request("GET", "/", None)), + "two Host headers are as good as none" + ); + for bad in [ + "", + "GET", + "GET /", + "GET / HTTP/2.0", + "GET / HTTP/1.1 extra", + "GET / HTTP/1.1", + "GET / HTTP/1.1\r\nno colon here", + ] { + assert_eq!(parse_head(bad), None, "{bad:?}"); + } + } + struct Running { port: u16, - cancel: Arc, target: Arc>, - handle: std::thread::JoinHandle>, + events: Sender, + handle: thread::JoinHandle>, + } + + impl Running { + /// The listener as `listen` registers it. + fn listener(&self) -> Listener { + Listener { + port: self.port, + target: self.target.clone(), + events: self.events.clone(), + } + } } /// A listener on a free port, serving on its own thread like `listen` does. fn start(expected_state: &str, timeout: Duration) -> Running { - let server = tiny_http::Server::http("127.0.0.1:0").unwrap(); - let port = server.server_addr().to_ip().unwrap().port(); - let cancel = Arc::new(AtomicBool::new(false)); + let socket = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = socket.local_addr().unwrap().port(); let target = Arc::new(Mutex::new(Target { state: expected_state.to_string(), deadline: Instant::now() + timeout, + finished: false, })); - let (flag, shared) = (cancel.clone(), target.clone()); - let handle = std::thread::spawn(move || serve(&server, port, &flag, &shared)); + let (sender, receiver) = mpsc::channel(); + let (shared, events) = (target.clone(), sender.clone()); + let handle = thread::spawn(move || serve(socket, port, &shared, (events, receiver))); Running { port, - cancel, target, + events: sender, handle, } } - /// Send a raw request and return the response's status code. - fn status_of(port: u16, request: &str) -> u16 { + /// Send raw bytes and return the response's status code (None if the connection was + /// closed without one). + fn answer(port: u16, request: &[u8]) -> Option { let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); stream - .set_read_timeout(Some(Duration::from_secs(5))) + .set_read_timeout(Some(Duration::from_secs(15))) .unwrap(); - stream.write_all(request.as_bytes()).unwrap(); - let mut response = String::new(); - stream.read_to_string(&mut response).unwrap(); - response + stream.write_all(request).unwrap(); + let mut response = Vec::new(); + let _ = stream.read_to_end(&mut response); + String::from_utf8_lossy(&response) .split(' ') .nth(1) .and_then(|code| code.parse().ok()) - .expect("the listener's response starts with a status line") + } + + fn status_of(port: u16, request: &str) -> u16 { + answer(port, request.as_bytes()).expect("the listener answers with a status line") } fn get(port: u16, path: &str, host: &str) -> u16 { @@ -388,40 +670,200 @@ mod tests { ); assert!(!running.handle.is_finished(), "a bad request ended sign-in"); - assert_eq!(get(port, "/callback?code=abc&state=s3cret", &host), 200); + let mut done = TcpStream::connect(("127.0.0.1", port)).unwrap(); + done.write_all( + format!("GET /callback?code=abc&state=s3cret HTTP/1.1\r\nHost: {host}\r\n\r\n") + .as_bytes(), + ) + .unwrap(); + let mut page = String::new(); + done.read_to_string(&mut page).unwrap(); + assert!(page.starts_with("HTTP/1.1 200 OK\r\n"), "{page}"); + assert!(page.contains("\r\nCache-Control: no-store\r\n"), "{page}"); + assert!(page.ends_with(DONE_PAGE)); let url = running.handle.join().unwrap(); assert_eq!( url.as_deref(), Some(format!("http://127.0.0.1:{port}/callback?code=abc&state=s3cret").as_str()) ); + // Single-use: the port is closed once the callback has arrived. + assert!(TcpStream::connect(("127.0.0.1", port)).is_err()); } #[test] - fn a_cancelled_listener_stops_and_its_port_can_be_bound_again() { + fn malformed_requests_are_refused_and_the_wait_goes_on() { let running = start("s3cret", Duration::from_secs(30)); + let port = running.port; + let good = "/callback?code=c&state=s3cret"; + let host = format!("127.0.0.1:{port}"); + let line = format!("GET {good} HTTP/1.1\r\n"); + for (request, status) in [ + (b"\r\n\r\n".to_vec(), 400), + (b"hello\r\n\r\n".to_vec(), 400), + ( + format!("GET {good} HTTP/2.0\r\nHost: {host}\r\n\r\n").into_bytes(), + 400, + ), + // No Host, two of them, the request in a proxy's form. + (format!("{line}\r\n").into_bytes(), 400), + ( + format!("{line}Host: {host}\r\nHost: {host}\r\n\r\n").into_bytes(), + 400, + ), + ( + format!("GET http://{host}{good} HTTP/1.1\r\nHost: {host}\r\n\r\n").into_bytes(), + 404, + ), + // Not text. + ( + [ + line.as_bytes(), + &b"Host: \xff"[..], + host.as_bytes(), + &b"\r\n\r\n"[..], + ] + .concat(), + 400, + ), + ( + [ + &b"GET /callback\xff?state=s3cret HTTP/1.1\r\nHost: "[..], + host.as_bytes(), + &b"\r\n\r\n"[..], + ] + .concat(), + 400, + ), + ] { + assert_eq!( + answer(port, &request), + Some(status), + "{}", + String::from_utf8_lossy(&request) + ); + } + // Header names are case-insensitive. + assert_eq!( + status_of( + port, + &format!("GET {good} HTTP/1.1\r\nhOsT: {host}\r\nConnection: close\r\n\r\n") + ), + 200 + ); + assert!(running.handle.join().unwrap().is_some()); + } + + /// A request that announces a body it never sends: the listener must neither wait for the + /// body nor reserve memory for it, and the genuine callback still gets through. + #[test] + fn a_request_announcing_a_huge_body_neither_crashes_nor_blocks_the_listener() { + let running = start("s3cret", Duration::from_secs(30)); + let port = running.port; + let host = format!("127.0.0.1:{port}"); + let mut hostile = TcpStream::connect(("127.0.0.1", port)).unwrap(); + hostile + .write_all( + format!( + "POST /callback HTTP/1.1\r\nHost: {host}\r\nContent-Length: 99999999999999\r\n\r\n" + ) + .as_bytes(), + ) + .unwrap(); + std::thread::sleep(Duration::from_millis(300)); + assert_eq!(get(port, "/callback?code=abc&state=s3cret", &host), 200); + assert!(running.handle.join().unwrap().is_some()); + drop(hostile); + } + + /// Connections that send nothing, or a byte at a time, don't hold up the callback. + #[test] + fn slow_connections_do_not_hold_up_the_callback() { + let running = start("s3cret", Duration::from_secs(30)); + let port = running.port; + let host = format!("127.0.0.1:{port}"); + let idle: Vec = (0..10) + .map(|_| TcpStream::connect(("127.0.0.1", port)).unwrap()) + .collect(); + let mut trickle = TcpStream::connect(("127.0.0.1", port)).unwrap(); + trickle.write_all(b"GET /callback?st").unwrap(); let started = Instant::now(); - running.cancel.store(true, Ordering::SeqCst); - assert_eq!(running.handle.join().unwrap(), None); + assert_eq!(get(port, "/callback?code=abc&state=s3cret", &host), 200); assert!(started.elapsed() < Duration::from_secs(2)); - // tiny_http releases the socket a moment after the server is dropped; bind waits for it. - let again = bind(running.port).expect("the port is free again"); - drop(again); + assert!(running.handle.join().unwrap().is_some()); + drop((idle, trickle)); + } + + #[test] + fn an_oversized_request_is_refused_and_the_wait_goes_on() { + let running = start("s3cret", Duration::from_secs(30)); + let port = running.port; + let host = format!("127.0.0.1:{port}"); + // The genuine callback, padded to `pad` bytes over the limit. + let padded = |pad: usize| { + let start = "GET /callback?code=abc&state=s3cret&pad="; + let end = format!(" HTTP/1.1\r\nHost: {host}"); + let fill = (MAX_HEAD + pad) - start.len() - end.len(); + format!("{start}{}{end}\r\n\r\n", "a".repeat(fill)) + }; + assert_eq!(status_of(port, &padded(1)), 431); + let endless_header = format!("GET /x HTTP/1.1\r\nX-Pad: {}", "a".repeat(64 * 1024)); + assert_eq!(status_of(port, &endless_header), 431); + assert!(!running.handle.is_finished()); + assert_eq!(status_of(port, &padded(0)), 200, "the limit itself is fine"); + assert!(running.handle.join().unwrap().is_some()); + } + + #[test] + fn many_connections_at_once_are_all_answered() { + let running = start("s3cret", Duration::from_secs(30)); + let port = running.port; + let host = format!("127.0.0.1:{port}"); + let clients: Vec<_> = (0..40) + .map(|i| { + let host = host.clone(); + thread::spawn(move || get(port, &format!("/page{i}"), &host)) + }) + .collect(); + for client in clients { + assert_eq!(client.join().unwrap(), 404); + } + assert_eq!(get(port, "/callback?code=abc&state=s3cret", &host), 200); + assert!(running.handle.join().unwrap().is_some()); + } + + #[test] + fn a_cancelled_listener_stops_at_once_and_frees_its_port() { + let running = start("s3cret", Duration::from_secs(30)); + let state = OAuthState::default(); + *lock(&state.active) = Some(running.listener()); + let started = Instant::now(); + state.cancel_running(); + assert_eq!(running.handle.join().unwrap(), None); + assert!( + started.elapsed() < Duration::from_millis(500), + "cancelling took {:?}", + started.elapsed() + ); + assert!(lock(&state.active).is_none()); + // Bound again straight away, without bind's retries. + TcpListener::bind(("127.0.0.1", running.port)).expect("the port is free again"); + // Cancelling again, or with nothing running, does nothing. + state.cancel_running(); } #[test] fn a_listener_gives_up_at_its_deadline() { let running = start("s3cret", Duration::from_millis(300)); + let started = Instant::now(); assert_eq!(running.handle.join().unwrap(), None); + assert!(started.elapsed() < Duration::from_secs(1)); + TcpListener::bind(("127.0.0.1", running.port)).expect("the port is free again"); } #[test] fn a_retargeted_listener_waits_the_full_time_for_the_new_sign_in() { let running = start("first", Duration::from_millis(300)); - let active = Some(Listener { - port: running.port, - cancel: running.cancel.clone(), - target: running.target.clone(), - }); + let active = Some(running.listener()); assert_eq!(retarget(&active, "second"), Some(running.port)); // Past the first sign-in's deadline, the listener still waits, now for the second one. std::thread::sleep(Duration::from_millis(600)); @@ -442,23 +884,42 @@ mod tests { // A cancelled listener isn't retargeted: a new one is started instead. let stopped = start("s3cret", Duration::from_secs(30)); - stopped.cancel.store(true, Ordering::SeqCst); - let active = Some(Listener { - port: stopped.port, - cancel: stopped.cancel.clone(), - target: stopped.target.clone(), - }); - assert_eq!(retarget(&active, "next"), None); + let state = OAuthState::default(); + *lock(&state.active) = Some(stopped.listener()); + let kept = Some(stopped.listener()); + state.cancel_running(); + assert_eq!(retarget(&kept, "next"), None); assert_eq!(retarget(&None, "next"), None); stopped.handle.join().unwrap(); } + /// A listener whose wait has ended is stopping, even while it is still registered (its + /// thread takes the registry's lock only after freeing the port): retargeting it would + /// leave the new sign-in waiting on a closed port. + #[test] + fn a_listener_that_stopped_waiting_is_never_retargeted() { + let timed_out = start("first", Duration::from_millis(100)); + let registered = Some(timed_out.listener()); + timed_out.handle.join().unwrap(); + assert_eq!(retarget(®istered, "second"), None); + + let answered = start("first", Duration::from_secs(30)); + let registered = Some(answered.listener()); + let host = format!("127.0.0.1:{}", answered.port); + assert_eq!( + get(answered.port, "/callback?code=c&state=first", &host), + 200 + ); + assert_eq!(retarget(®istered, "second"), None); + answered.handle.join().unwrap(); + } + #[test] fn a_port_in_use_is_a_readable_error() { - let busy = tiny_http::Server::http("127.0.0.1:0").unwrap(); - let port = busy.server_addr().to_ip().unwrap().port(); + let busy = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = busy.local_addr().unwrap().port(); let started = Instant::now(); - let err = bind(port).err().expect("the port is taken"); + let err = bind(port).expect_err("the port is taken"); assert!(err.contains("Is another app using that port?"), "{err}"); assert!(started.elapsed() >= BIND_RETRY); } diff --git a/src-tauri/tests/oauth_ipc.rs b/src-tauri/tests/oauth_ipc.rs new file mode 100644 index 0000000..6e4211a --- /dev/null +++ b/src-tauri/tests/oauth_ipc.rs @@ -0,0 +1,165 @@ +//! The sign-in listener's commands called through Tauri's IPC layer (mock runtime) with the +//! arguments `desktopOAuthListen()` in `app/lib/platform.ts` sends, and the browser's side +//! played over raw TCP: `oauth_listen` binds the loopback port, the genuine redirect becomes +//! the `oauth-callback` event, and `oauth_cancel` frees the port at once. + +mod common; + +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::sync::mpsc; +use std::time::Duration; + +use common::{invoke_request, open_main, APP_ORIGIN}; +use tauri::ipc::InvokeResponse; +use tauri::test::{get_ipc_response, mock_builder, noop_assets, MockRuntime}; +use tauri::{Listener, WebviewWindow}; + +fn app() -> (tauri::App, WebviewWindow) { + let context: tauri::Context = + tauri::generate_context!(test = true, assets = noop_assets()); + open_main(spotify_stats_lib::with_commands(mock_builder()), context) +} + +fn call( + webview: &WebviewWindow, + cmd: &str, + args: serde_json::Value, +) -> Result { + get_ipc_response(webview, invoke_request(APP_ORIGIN, cmd, args)) + .map(|body| body.deserialize().unwrap()) + .map_err(|err| err.to_string()) +} + +/// What `desktopOAuthListen(port, state)` sends; the port it answers with. +fn listen(webview: &WebviewWindow, port: u16, state: &str) -> u16 { + let answer = call( + webview, + "oauth_listen", + serde_json::json!({ "port": port, "expectedState": state }), + ); + answer.unwrap().as_u64().unwrap() as u16 +} + +/// A free port, released for the listener to take. +fn free_port() -> u16 { + TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port() +} + +/// The browser following Spotify's redirect: the response's status code. +fn redirect(port: u16, query: &str) -> u16 { + let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(10))) + .unwrap(); + let request = format!("GET /callback?{query} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n\r\n"); + stream.write_all(request.as_bytes()).unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).unwrap(); + response.split(' ').nth(1).unwrap().parse().unwrap() +} + +#[test] +fn the_genuine_redirect_reaches_the_ui_as_an_event() { + let (app, webview) = app(); + let (sender, callbacks) = mpsc::channel(); + app.listen_any("oauth-callback", move |event| { + let payload: serde_json::Value = serde_json::from_str(event.payload()).unwrap(); + sender + .send(payload["url"].as_str().unwrap().to_string()) + .unwrap(); + }); + let port = listen(&webview, free_port(), "first"); + // A sign-in started again while one is pending (a reload, say) gets the same listener. + assert_eq!(listen(&webview, port, "second"), port); + assert_eq!(redirect(port, "code=old&state=first"), 400); + assert_eq!(redirect(port, "code=abc&state=second"), 200); + assert_eq!( + callbacks.recv_timeout(Duration::from_secs(5)).unwrap(), + format!("http://127.0.0.1:{port}/callback?code=abc&state=second") + ); + // Single-use: the port is free again for the next sign-in. + assert_eq!(listen(&webview, port, "third"), port); + call(&webview, "oauth_cancel", serde_json::json!({})).unwrap(); +} + +#[test] +fn cancelling_frees_the_port_at_once() { + let (_app, webview) = app(); + let port = listen(&webview, free_port(), "s3cret"); + assert_eq!( + call(&webview, "oauth_cancel", serde_json::json!({})), + Ok(serde_json::Value::Null) + ); + // The listener closes its port promptly; a new sign-in binds it again within bind's retry. + let started = std::time::Instant::now(); + assert_eq!(listen(&webview, port, "again"), port); + assert!(started.elapsed() < Duration::from_millis(500)); + call(&webview, "oauth_cancel", serde_json::json!({})).unwrap(); + // Cancelling with nothing running is fine. + call(&webview, "oauth_cancel", serde_json::json!({})).unwrap(); +} + +#[test] +fn a_port_in_use_is_a_readable_error() { + let (_app, webview) = app(); + let busy = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = busy.local_addr().unwrap().port(); + let err = call( + &webview, + "oauth_listen", + serde_json::json!({ "port": port, "expectedState": "s" }), + ) + .unwrap_err(); + assert!(err.contains("Is another app using that port?"), "{err}"); +} + +#[test] +fn bad_arguments_are_refused() { + let (_app, webview) = app(); + for args in [ + serde_json::json!({}), + serde_json::json!({ "port": 70_000, "expectedState": "s" }), + serde_json::json!({ "port": -1, "expectedState": "s" }), + serde_json::json!({ "port": "43821", "expectedState": "s" }), + serde_json::json!({ "port": 0, "expectedState": 5 }), + ] { + assert!( + call(&webview, "oauth_listen", args.clone()).is_err(), + "{args}" + ); + } +} + +/// In the app, IPC messages arrive on the main thread, where a plain (sync) command would run. +/// Cancelling waits for a sign-in that is still binding its port, so it answers from a worker +/// thread instead of freezing the window meanwhile. +#[test] +fn the_commands_answer_off_the_calling_thread() { + let (_app, webview) = app(); + let caller = std::thread::current().id(); + let port = free_port(); + for (cmd, args) in [ + ( + "oauth_listen", + serde_json::json!({ "port": port, "expectedState": "s" }), + ), + ("oauth_cancel", serde_json::json!({})), + ] { + let (sender, answered) = mpsc::sync_channel(1); + webview.clone().on_message( + invoke_request(APP_ORIGIN, cmd, args), + Box::new(move |_webview, _cmd, response, _callback, _error| { + let ok = matches!(response, InvokeResponse::Ok(_)); + sender.send((std::thread::current().id(), ok)).unwrap(); + }), + ); + let (thread, ok) = answered.recv().expect("the command answers"); + assert!(ok, "{cmd} failed"); + assert_ne!(thread, caller, "{cmd} ran on the calling thread"); + } +} From ef1f26004285e545f01a9f7d335165ceccd27aaa Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:00:10 +0000 Subject: [PATCH 16/41] test: wait up to 5 s in Testing Library, as the demo answers slowly findBy* and waitFor gave up after 1 s. The demo API answers every request after a simulated 60-200 ms, a page can wait on a few in a row, and under load (the whole suite at once, a CI runner) Playlist.test.tsx's heading took longer than that and the test failed. A longer wait costs nothing when the element turns up. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- scripts/setupTests.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/scripts/setupTests.ts b/scripts/setupTests.ts index 699eb93..0cc5fb2 100644 --- a/scripts/setupTests.ts +++ b/scripts/setupTests.ts @@ -1,8 +1,14 @@ import "@testing-library/jest-dom/vitest"; import "fake-indexeddb/auto"; -import { cleanup } from "@testing-library/react"; +import { cleanup, configure } from "@testing-library/react"; import { afterEach, vi } from "vitest"; +// findBy* and waitFor give up after 1 s by default. The demo API answers each request after a +// simulated 60-200 ms of network, and a page can take a few of them in a row: on a busy machine +// (a CI runner, the whole suite at once) that passed 1 s. Waiting longer costs nothing when the +// element turns up, only when a test is failing anyway. +configure({ asyncUtilTimeout: 5_000 }); + afterEach(() => { cleanup(); localStorage.clear(); From f4d67c44433866a4b9fe8366cedd8d96b23a9656 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:00:18 +0000 Subject: [PATCH 17/41] test(lyrics): check the parsers' speed with room for a busy machine The crafted-input check allowed 500 ms per case, and one case takes up to about 200 ms on a quiet machine, so a loaded CI runner failed it. A parser that backtracks or rescans would take minutes on these inputs, so 3 s still catches it, and far from what a linear one needs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- app/lyrics/timeline.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/app/lyrics/timeline.test.ts b/app/lyrics/timeline.test.ts index 646f36a..fd1b3dd 100644 --- a/app/lyrics/timeline.test.ts +++ b/app/lyrics/timeline.test.ts @@ -255,7 +255,10 @@ plain: | expect(parseLyricsfile("x".repeat(600_000))).toBeNull(); }); - it("stays fast on crafted input (no catastrophic backtracking)", () => { + // Each case takes from under a millisecond to a couple of hundred (more on a busy machine, or + // while the code is still being compiled); a parser that backtracks or rescans would take + // minutes on inputs this size. The limit sits far from both, so only that fails it. + it("stays fast on crafted input (no catastrophic backtracking)", { timeout: 30_000 }, () => { const cases = [ () => parseLyricsfile(`lines:\n - text: a${" ".repeat(400_000)}b\n`), () => parseLyricsfile(`a${" ".repeat(400_000)}b`), @@ -268,7 +271,7 @@ plain: | for (const run of cases) { const started = performance.now(); expect(() => run()).not.toThrow(); - expect(performance.now() - started).toBeLessThan(500); + expect(performance.now() - started).toBeLessThan(3_000); } }); From 9831413404209277edb579c21ae55879a9f22714 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:00:23 +0000 Subject: [PATCH 18/41] ci: stop running CodeQL and the installers twice for every pull request Both ran on pushes to feature/** and again on the pull request for the same commit. They now run on pull requests and on main. Pull requests build the installers only when they change what those are built from (src-tauri/, the dependencies, vite.config.ts, the workflow): CI builds and tests the same web app, and every change to the app still builds them on main. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- .github/workflows/codeql.yml | 7 ++++--- .github/workflows/desktop.yml | 13 +++++++------ 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index d255c0e..4594394 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -1,11 +1,12 @@ name: CodeQL # GitHub's code scanning for security problems in the TypeScript app, the Rust shell and these -# workflows. Findings appear under Security → Code scanning. Runs on pushes to main and feature -# branches, on pull requests, and every week (new queries find problems in old code). +# workflows. Findings appear under Security → Code scanning. Runs on pushes to main, on pull +# requests (not on pushes to their branches as well, which would scan every commit twice), and +# every week (new queries find problems in old code). on: push: - branches: [main, "feature/**"] + branches: [main] pull_request: schedule: - cron: "27 4 * * 1" diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml index f01d1b5..d4d857b 100644 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -2,13 +2,17 @@ name: Desktop app # Builds the installable desktop app on Windows, Linux and macOS and uploads the installers as # downloadable artifacts of the run (Windows .exe/.msi and a portable .exe, Linux .deb/.AppImage, -# a macOS .dmg for both Apple silicon and Intel). Runs when the app's code changes, by hand, and -# from the release workflow, which attaches these files to the GitHub Release. +# a macOS .dmg for both Apple silicon and Intel). Runs by hand, from the release workflow, which +# attaches these files to the GitHub Release, when a change to the app reaches main, and on pull +# requests that change what the installers are built from: the Rust shell, the dependencies +# (Tauri's CLI and API among them) or the build configuration. Pull requests that change only the +# web app don't build them: CI builds and tests the same web app, and builds of main keep +# installers of the latest code to download. on: workflow_dispatch: workflow_call: push: - branches: [main, "feature/**"] + branches: [main] paths: - "app/**" - "src-tauri/**" @@ -20,10 +24,7 @@ on: - ".github/workflows/desktop.yml" pull_request: paths: - - "app/**" - "src-tauri/**" - - "public/**" - - "index.html" - "package.json" - "package-lock.json" - "vite.config.ts" From 6045afdedb5e0562832088de78eba34213cea418 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:01:30 +0000 Subject: [PATCH 19/41] test(e2e): choose each screen size's tests in the config, not by skipping Every spec called desktopOnlyUnlessAllSizes(), which skipped its tests on tablet and phone from a beforeEach: 547 of the 987 tests were queued, started and skipped on every run, and a shard would count them as work. playwright.config.ts now gives tablet and phone a grep instead (app.spec.ts, and the tests marked [all sizes]), so they are never queued: 451 tests remain, the same ones that ran before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- e2e/a11y.spec.ts | 4 +--- e2e/autostart.spec.ts | 4 +--- e2e/backgrounds.spec.ts | 4 +--- e2e/covers.spec.ts | 4 +--- e2e/devlog.spec.ts | 4 +--- e2e/fullscreen.spec.ts | 4 +--- e2e/helpers.ts | 18 ++++-------------- e2e/library-actions.spec.ts | 4 +--- e2e/lyrics.spec.ts | 4 +--- e2e/music.spec.ts | 4 +--- e2e/personalise.spec.ts | 4 +--- e2e/playlists.spec.ts | 4 +--- e2e/real.spec.ts | 4 +--- e2e/regression.spec.ts | 4 +--- e2e/security.spec.ts | 4 +--- e2e/shell.spec.ts | 4 +--- e2e/stats.spec.ts | 4 +--- e2e/streams.spec.ts | 4 +--- e2e/uplift.spec.ts | 4 +--- e2e/ux.spec.ts | 4 +--- e2e/window-material.spec.ts | 4 +--- e2e/window-states.spec.ts | 4 +--- playwright.config.ts | 16 ++++++++++++++-- 23 files changed, 39 insertions(+), 79 deletions(-) diff --git a/e2e/a11y.spec.ts b/e2e/a11y.spec.ts index b334743..4a681e3 100644 --- a/e2e/a11y.spec.ts +++ b/e2e/a11y.spec.ts @@ -1,5 +1,5 @@ import { expect, test, type Page } from "@playwright/test"; -import { desktopOnlyUnlessAllSizes, noSeriousA11y, seedDemo, settled, trackErrors } from "./helpers"; +import { noSeriousA11y, seedDemo, settled, trackErrors } from "./helpers"; import { mockSpotify } from "./mock-spotify"; /** @@ -9,8 +9,6 @@ import { mockSpotify } from "./mock-spotify"; * single-key shortcuts, tooltips). Demo mode. */ -desktopOnlyUnlessAllSizes(); - const THEMES = ["midnight", "oled", "forest", "light", "contrast"] as const; /** WCAG contrast ratio of two CSS colours (any format the browser parses), measured in the page. */ diff --git a/e2e/autostart.spec.ts b/e2e/autostart.spec.ts index ba5363c..3085984 100644 --- a/e2e/autostart.spec.ts +++ b/e2e/autostart.spec.ts @@ -1,7 +1,7 @@ import { expect, test, type Page } from "@playwright/test"; import { mockSpotify, type Scenario } from "./mock-spotify"; import { allDevices, fakeConnect, fakeDesktop, PHONE, THIS_PC, type ConnectOptions, type FakeConnect, type FakeDesktop, type LaunchBehaviour } from "./fake-desktop"; -import { desktopOnlyUnlessAllSizes, noSeriousA11y, trackErrors } from "./helpers"; +import { noSeriousA11y, trackErrors } from "./helpers"; /** * "Start Spotify hidden automatically" in the desktop app, end to end: the web build runs with @@ -9,8 +9,6 @@ import { desktopOnlyUnlessAllSizes, noSeriousA11y, trackErrors } from "./helpers * this PC's Spotify only comes online a few seconds after `spotify_launch_hidden` was called. */ -desktopOnlyUnlessAllSizes(); - interface SetupOptions { launch?: LaunchBehaviour; launchDelayMs?: number; diff --git a/e2e/backgrounds.spec.ts b/e2e/backgrounds.spec.ts index 853596d..19e6edc 100644 --- a/e2e/backgrounds.spec.ts +++ b/e2e/backgrounds.spec.ts @@ -1,6 +1,6 @@ import { expect, test, type Page } from "@playwright/test"; import { mockSpotify } from "./mock-spotify"; -import { desktopOnlyUnlessAllSizes, seedDemo, trackErrors } from "./helpers"; +import { seedDemo, trackErrors } from "./helpers"; import { colourAt, contrastBehind } from "./pixels"; /** @@ -9,8 +9,6 @@ import { colourAt, contrastBehind } from "./pixels"; * mode drops blur, glow and decorative animation. */ -desktopOnlyUnlessAllSizes(); - const backdrop = (page: Page) => page.getByTestId("album-backdrop"); /** The alpha of a computed colour, whichever syntax the browser reports it in. */ diff --git a/e2e/covers.spec.ts b/e2e/covers.spec.ts index 0e7053b..7c773f2 100644 --- a/e2e/covers.spec.ts +++ b/e2e/covers.spec.ts @@ -1,5 +1,5 @@ import { expect, test, type Locator, type Page } from "@playwright/test"; -import { desktopOnlyUnlessAllSizes, seedDemo, trackErrors } from "./helpers"; +import { seedDemo, trackErrors } from "./helpers"; /** * Covers that lean toward the pointer: on for a mouse with motion welcome, off with reduced motion @@ -7,8 +7,6 @@ import { desktopOnlyUnlessAllSizes, seedDemo, trackErrors } from "./helpers"; * (a mouse); touch screens never get it (see app/components/media/tilt.ts). */ -desktopOnlyUnlessAllSizes(); - const mainCover = (page: Page) => page .locator("#main") diff --git a/e2e/devlog.spec.ts b/e2e/devlog.spec.ts index 48a2fdf..266c61d 100644 --- a/e2e/devlog.spec.ts +++ b/e2e/devlog.spec.ts @@ -1,11 +1,9 @@ import { expect, test, type Page } from "@playwright/test"; import { mockSpotify } from "./mock-spotify"; -import { desktopOnlyUnlessAllSizes, enterDemo, noSeriousA11y } from "./helpers"; +import { enterDemo, noSeriousA11y } from "./helpers"; /** Right-click menu and the developer log (errors, network, events, system). */ -desktopOnlyUnlessAllSizes(); - const devlog = (page: Page) => page.getByRole("dialog", { name: "Developer log" }); test("right-click shows the app's menu; text fields and Shift keep the normal one", async ({ page }) => { diff --git a/e2e/fullscreen.spec.ts b/e2e/fullscreen.spec.ts index 30f7862..09ee9c3 100644 --- a/e2e/fullscreen.spec.ts +++ b/e2e/fullscreen.spec.ts @@ -1,11 +1,9 @@ import AxeBuilder from "@axe-core/playwright"; import { expect, test, type Page } from "@playwright/test"; import { mockSpotify } from "./mock-spotify"; -import { desktopOnlyUnlessAllSizes, seedDemo, settleAnimations, trackErrors, WCAG_TAGS } from "./helpers"; +import { seedDemo, settleAnimations, trackErrors, WCAG_TAGS } from "./helpers"; import { contrastBehind } from "./pixels"; -desktopOnlyUnlessAllSizes(); - const waves = (page: Page) => page.getByRole("dialog").locator("[data-renderer]"); const isFullscreen = (page: Page) => page.evaluate(() => Boolean(document.fullscreenElement)); diff --git a/e2e/helpers.ts b/e2e/helpers.ts index 388dc89..ca2f734 100644 --- a/e2e/helpers.ts +++ b/e2e/helpers.ts @@ -1,20 +1,10 @@ /** - * Helpers shared by the end-to-end specs: running a spec on the desktop project only, demo-mode - * set-up, error tracking and the axe accessibility check. + * Helpers shared by the end-to-end specs: demo-mode set-up, error tracking and the axe + * accessibility check. (Which tests run at which screen sizes is set in playwright.config.ts: + * outside app.spec.ts, the desktop project only, unless the title says "[all sizes]".) */ import AxeBuilder from "@axe-core/playwright"; -import { expect, test, type Page } from "@playwright/test"; - -/** - * Run this file's tests on the desktop project only, except tests whose title contains - * "[all sizes]", which also run on tablet and phone. Call once at the top of a spec. - */ -export function desktopOnlyUnlessAllSizes(): void { - // eslint-disable-next-line no-empty-pattern -- Playwright requires destructuring here - test.beforeEach(({}, info) => { - if (info.project.name !== "desktop" && !info.title.includes("[all sizes]")) test.skip(); - }); -} +import { expect, type Page } from "@playwright/test"; /** Open `path` in demo mode, skipping the landing page. */ export async function enterDemo(page: Page, path = "/"): Promise { diff --git a/e2e/library-actions.spec.ts b/e2e/library-actions.spec.ts index 0716b13..e1ce67a 100644 --- a/e2e/library-actions.spec.ts +++ b/e2e/library-actions.spec.ts @@ -1,11 +1,9 @@ import { expect, test, type Locator, type Page } from "@playwright/test"; -import { desktopOnlyUnlessAllSizes, noSeriousA11y, seedDemo, trackErrors } from "./helpers"; +import { noSeriousA11y, seedDemo, trackErrors } from "./helpers"; import { mockSpotify } from "./mock-spotify"; /** Liking songs (Liked Songs) and adding them to playlists: demo mode and the signed-in fake. */ -desktopOnlyUnlessAllSizes(); - const ALL_SCOPES = "user-library-read user-library-modify playlist-modify-private playlist-modify-public user-top-read"; const heartIn = (scope: Page | Locator) => scope.getByRole("button", { name: "Like", exact: true }); diff --git a/e2e/lyrics.spec.ts b/e2e/lyrics.spec.ts index 88d736e..152d3c9 100644 --- a/e2e/lyrics.spec.ts +++ b/e2e/lyrics.spec.ts @@ -1,6 +1,6 @@ import { expect, test, type Page } from "@playwright/test"; import { mockSpotify } from "./mock-spotify"; -import { desktopOnlyUnlessAllSizes, noSeriousA11y, seedDemo, trackErrors } from "./helpers"; +import { noSeriousA11y, seedDemo, trackErrors } from "./helpers"; import { contrastBehind } from "./pixels"; /** @@ -8,8 +8,6 @@ import { contrastBehind } from "./pixels"; * where the test lyrics are on "one two three" (word-synced) or "Sing it from the top". */ -desktopOnlyUnlessAllSizes(); - const FULL_MOTION = { motion: "full" }; const activeLine = (page: Page) => page.locator('.lyric-line[data-status="active"]'); /** Word states on the current line: 0 not yet, 1 being sung, 2 sung. */ diff --git a/e2e/music.spec.ts b/e2e/music.spec.ts index e6d744c..79f1d0a 100644 --- a/e2e/music.spec.ts +++ b/e2e/music.spec.ts @@ -1,5 +1,5 @@ import { expect, test, type Page } from "@playwright/test"; -import { desktopOnlyUnlessAllSizes, enterDemo, seedDemo } from "./helpers"; +import { enterDemo, seedDemo } from "./helpers"; import { mockSpotify } from "./mock-spotify"; /** @@ -8,8 +8,6 @@ import { mockSpotify } from "./mock-spotify"; * headers that read evenly, and controls that look the way they behave. */ -desktopOnlyUnlessAllSizes(); - /** The box of the first element matching `selector` inside the main pane, or null. */ const boxOf = (page: Page, selector: string) => page.evaluate((s) => { diff --git a/e2e/personalise.spec.ts b/e2e/personalise.spec.ts index 3d6334d..9a54440 100644 --- a/e2e/personalise.spec.ts +++ b/e2e/personalise.spec.ts @@ -1,14 +1,12 @@ import { expect, test, type Page } from "@playwright/test"; import { fakeDesktop } from "./fake-desktop"; -import { desktopOnlyUnlessAllSizes, noSeriousA11y, seedDemo, trackErrors } from "./helpers"; +import { noSeriousA11y, seedDemo, trackErrors } from "./helpers"; /** * Full-screen Both view, accent colours, pinned playlists and folders, the top bar, the Overview * artists row, and the desktop window's material in and out of focus and full screen. */ -desktopOnlyUnlessAllSizes(); - const cssVar = (page: Page, name: string) => page.evaluate((n) => getComputedStyle(document.documentElement).getPropertyValue(n).trim(), name); test.describe("full-screen player", () => { diff --git a/e2e/playlists.spec.ts b/e2e/playlists.spec.ts index a44bf4b..0855621 100644 --- a/e2e/playlists.spec.ts +++ b/e2e/playlists.spec.ts @@ -1,11 +1,9 @@ import { expect, test, type Page } from "@playwright/test"; -import { desktopOnlyUnlessAllSizes, noSeriousA11y, seedDemo, trackErrors } from "./helpers"; +import { noSeriousA11y, seedDemo, trackErrors } from "./helpers"; import { mockSpotify } from "./mock-spotify"; /** Instant playlists from your stats, per-song lyrics timing, and reordering sidebar pins. */ -desktopOnlyUnlessAllSizes(); - const playerTitle = (page: Page) => page.getByRole("region", { name: "Player" }).locator("p").first(); test.describe("instant playlists", () => { diff --git a/e2e/real.spec.ts b/e2e/real.spec.ts index 89def5f..e6a4e08 100644 --- a/e2e/real.spec.ts +++ b/e2e/real.spec.ts @@ -1,15 +1,13 @@ import { expect, test, type Page } from "@playwright/test"; import { fakeDesktop } from "./fake-desktop"; import { CLIENT_ID, mockSpotify } from "./mock-spotify"; -import { desktopOnlyUnlessAllSizes, enterDemo, noSeriousA11y, trackErrors } from "./helpers"; +import { enterDemo, noSeriousA11y, trackErrors } from "./helpers"; /** * Signed-in (real API) code path against a fake Spotify: empty accounts, failures, auth edge * cases, hostile data and large libraries. */ -desktopOnlyUnlessAllSizes(); - test.describe("signed in", () => { test("overview, charts, library and playlist use real API shapes", async ({ page }) => { const errors = trackErrors(page); diff --git a/e2e/regression.spec.ts b/e2e/regression.spec.ts index 67ac0e3..70a6f85 100644 --- a/e2e/regression.spec.ts +++ b/e2e/regression.spec.ts @@ -1,5 +1,5 @@ import { expect, test, type Page } from "@playwright/test"; -import { desktopOnlyUnlessAllSizes, seedDemo, trackErrors } from "./helpers"; +import { seedDemo, trackErrors } from "./helpers"; import { mockSpotify } from "./mock-spotify"; /** @@ -7,8 +7,6 @@ import { mockSpotify } from "./mock-spotify"; * going offline, and focus while a page is still arriving. */ -desktopOnlyUnlessAllSizes(); - const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); /** Open a playlist from the library, then come back, so its page code is already loaded. */ diff --git a/e2e/security.spec.ts b/e2e/security.spec.ts index 57b144c..c016044 100644 --- a/e2e/security.spec.ts +++ b/e2e/security.spec.ts @@ -2,7 +2,7 @@ import { createServer } from "node:http"; import type { AddressInfo } from "node:net"; import { expect, test, type Page } from "@playwright/test"; import { fakeDesktop } from "./fake-desktop"; -import { desktopOnlyUnlessAllSizes, trackErrors } from "./helpers"; +import { trackErrors } from "./helpers"; import { CLIENT_ID, mockSpotify } from "./mock-spotify"; /** @@ -11,8 +11,6 @@ import { CLIENT_ID, mockSpotify } from "./mock-spotify"; * another program (or a hand edit) has filled with hostile values. */ -desktopOnlyUnlessAllSizes(); - /** Nothing reaches the real internet; the tests route what they expect. Call before other routes. */ async function offline(page: Page) { await page.route(/^https?:\/\/(?!127\.0\.0\.1[:/])/, (route) => route.abort()); diff --git a/e2e/shell.spec.ts b/e2e/shell.spec.ts index 0b51e24..07cf796 100644 --- a/e2e/shell.spec.ts +++ b/e2e/shell.spec.ts @@ -1,6 +1,6 @@ import { expect, test, type Locator, type Page } from "@playwright/test"; import { fakeDesktop } from "./fake-desktop"; -import { desktopOnlyUnlessAllSizes, seedDemo } from "./helpers"; +import { seedDemo } from "./helpers"; import { CLIENT_ID, mockSpotify } from "./mock-spotify"; /** @@ -9,8 +9,6 @@ import { CLIENT_ID, mockSpotify } from "./mock-spotify"; * buttons that fit a small phone, title bar buttons whose ring and colours show. */ -desktopOnlyUnlessAllSizes(); - const box = async (locator: Locator) => { const b = await locator.boundingBox(); if (!b) throw new Error("not on screen"); diff --git a/e2e/stats.spec.ts b/e2e/stats.spec.ts index 11e754f..2330001 100644 --- a/e2e/stats.spec.ts +++ b/e2e/stats.spec.ts @@ -1,5 +1,5 @@ import { expect, test, type Locator, type Page } from "@playwright/test"; -import { desktopOnlyUnlessAllSizes, enterDemo, seedDemo, settled, trackErrors } from "./helpers"; +import { enterDemo, seedDemo, settled, trackErrors } from "./helpers"; import { mockSpotify } from "./mock-spotify"; /** @@ -8,8 +8,6 @@ import { mockSpotify } from "./mock-spotify"; * and failing requests, empty accounts. */ -desktopOnlyUnlessAllSizes(); - /** Every element matched by `selector` inside `root` shows its whole text. */ const whole = (root: Locator, selector: string) => root.evaluate( diff --git a/e2e/streams.spec.ts b/e2e/streams.spec.ts index e9fb9de..b1bc16a 100644 --- a/e2e/streams.spec.ts +++ b/e2e/streams.spec.ts @@ -1,8 +1,6 @@ import { expect, test, type Page } from "@playwright/test"; import { mockSpotify } from "./mock-spotify"; -import { desktopOnlyUnlessAllSizes, settled, trackErrors } from "./helpers"; - -desktopOnlyUnlessAllSizes(); +import { settled, trackErrors } from "./helpers"; const tile = (page: Page, label: string) => page.getByRole("region", { name: "Totals" }).locator("div.card").filter({ hasText: label }).locator("p.text-3xl"); diff --git a/e2e/uplift.spec.ts b/e2e/uplift.spec.ts index dc9f74c..9e71076 100644 --- a/e2e/uplift.spec.ts +++ b/e2e/uplift.spec.ts @@ -1,13 +1,11 @@ import { expect, test } from "@playwright/test"; -import { desktopOnlyUnlessAllSizes, enterDemo, noSeriousA11y, settled, trackErrors } from "./helpers"; +import { enterDemo, noSeriousA11y, settled, trackErrors } from "./helpers"; /** * Tooltips, interface size, the sidebar handle, remembered playlist order, the heatmap and * calendar, rankings and detail views, podcasts and the import summary. Demo mode. */ -desktopOnlyUnlessAllSizes(); - test("tooltips are themed, follow the pointer and keyboard, and hide on Escape", async ({ page }) => { await enterDemo(page); const button = page.getByRole("button", { name: "Keyboard shortcuts" }); diff --git a/e2e/ux.spec.ts b/e2e/ux.spec.ts index 141dba8..4e974b8 100644 --- a/e2e/ux.spec.ts +++ b/e2e/ux.spec.ts @@ -1,5 +1,5 @@ import { expect, test, type Locator } from "@playwright/test"; -import { desktopOnlyUnlessAllSizes, enterDemo, seedDemo, settled, trackErrors } from "./helpers"; +import { enterDemo, seedDemo, settled, trackErrors } from "./helpers"; import { mockSpotify } from "./mock-spotify"; /** @@ -7,8 +7,6 @@ import { mockSpotify } from "./mock-spotify"; * instead of clipped ones, honest loading states, the import nudge and clear wording. */ -desktopOnlyUnlessAllSizes(); - /** True when every element inside `root` shows its whole text (nothing clipped or cut short). */ const nothingClipped = (root: Locator) => root.evaluate((el) => diff --git a/e2e/window-material.spec.ts b/e2e/window-material.spec.ts index 707aa69..939b3cf 100644 --- a/e2e/window-material.spec.ts +++ b/e2e/window-material.spec.ts @@ -1,6 +1,6 @@ import { expect, test, type Page } from "@playwright/test"; import { fakeDesktop, type FakeDesktop } from "./fake-desktop"; -import { desktopOnlyUnlessAllSizes, seedDemo, trackErrors } from "./helpers"; +import { seedDemo, trackErrors } from "./helpers"; /** * The Windows material behind the see-through desktop window (visuals/windowMaterial.ts), through @@ -11,8 +11,6 @@ import { desktopOnlyUnlessAllSizes, seedDemo, trackErrors } from "./helpers"; * turns solid in full screen. */ -desktopOnlyUnlessAllSizes(); - /** How long the app waits for a burst of window events to stop, plus room for the IPC. */ const SETTLED_MS = 600; diff --git a/e2e/window-states.spec.ts b/e2e/window-states.spec.ts index 2c47461..6a19b74 100644 --- a/e2e/window-states.spec.ts +++ b/e2e/window-states.spec.ts @@ -1,6 +1,6 @@ import { expect, test, type Page } from "@playwright/test"; import { fakeDesktop, type FakeDesktop } from "./fake-desktop"; -import { desktopOnlyUnlessAllSizes, noSeriousA11y, seedDemo, trackErrors } from "./helpers"; +import { noSeriousA11y, seedDemo, trackErrors } from "./helpers"; import { backgroundFrames, clearBackgroundFrames, @@ -19,8 +19,6 @@ import { * never a bare canvas. Desktop window states come from the fake Tauri bridge (fake-desktop.ts). */ -desktopOnlyUnlessAllSizes(); - const THEMES = ["midnight", "oled", "forest", "light", "contrast"] as const; const seeThrough = async (page: Page) => (await page.locator("html").getAttribute("data-transparent")) === "true"; diff --git a/playwright.config.ts b/playwright.config.ts index 957ae98..2d256f9 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -4,6 +4,14 @@ import { defineConfig, devices } from "@playwright/test"; const port = Number(process.env.E2E_PORT) || 4173; const origin = `http://127.0.0.1:${port}`; +/** + * Tablet and phone run app.spec.ts (every page at every size) and, from the other specs, the tests + * whose title says "[all sizes]"; the rest run on the desktop project alone. They're filtered out + * here rather than skipped inside each test, so they're never queued, and CI's shards split only + * tests that run. Playwright matches these against " ". + */ +const ALL_SIZES = [/\[all sizes\]/, /(^| )app\.spec\.ts /]; + /** * End-to-end tests run against the production build in demo mode (no Spotify account or * network needed). Three form factors: laptop, tablet and phone. @@ -22,8 +30,12 @@ export default defineConfig({ }, projects: [ { name: "desktop", use: { ...devices["Desktop Chrome"], viewport: { width: 1366, height: 768 } } }, - { name: "tablet", use: { ...devices["Desktop Chrome"], viewport: { width: 820, height: 1180 }, hasTouch: true } }, - { name: "phone", use: { ...devices["Pixel 7"] } }, + { + name: "tablet", + grep: ALL_SIZES, + use: { ...devices["Desktop Chrome"], viewport: { width: 820, height: 1180 }, hasTouch: true }, + }, + { name: "phone", grep: ALL_SIZES, use: { ...devices["Pixel 7"] } }, ], webServer: { command: `npm run build && npx vite preview --host 127.0.0.1 --port ${port} --strictPort`, From 5e8eaa62f91608ae7fb960e7190d95ce2502a27f Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:01:52 +0000 Subject: [PATCH 20/41] ci: build once and run the end-to-end tests in four jobs side by side The end-to-end step took about 10.5 minutes of a 12-14 minute job, with two browsers, after building the app a second time. Now: - Build runs vite build once and uploads statsify-web; four end-to-end jobs download it and serve it (E2E_PREBUILT skips the build in Playwright's web server) beside a job for types, lint and unit tests. - e2e/shard.ts deals the tests out between the jobs in turn. Playwright's --shard cuts consecutive runs, which gave the job starting with a11y, app and autostart about twice the work of the phone's job. The script fails if Playwright doesn't pick every test it listed. - The browser step installs only the headless shell the tests run in. - "Lint, test & build" stays the required check: it needs the build, the checks and every end-to-end job, always runs (cancelled included), and fails unless each passed or wasn't needed. "Desktop shell (Rust)" keeps its name. - A "What changed" job skips the end-to-end tests for documentation (Markdown, docs/, and .github/ other than this workflow) and the Rust checks outside src-tauri/. Skipped jobs count as passed, so this is a job-level if, not on: paths, which would leave a required check pending. - CI runs on pull requests and pushes to main, no longer also on pushes to feature/**, which ran every pull request's commits twice. Start it by hand for a branch without one. - The release workflow's dry runs (pull requests that change it) call it with run: build: the pull request's own run has the checks, and a dry run only packages the build. Releases run everything, and dry runs no longer start on feature-branch pushes as well. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- .github/workflows/ci.yml | 160 +++++++++++++++++++++++++++++++--- .github/workflows/release.yml | 12 +-- e2e/shard.ts | 62 +++++++++++++ playwright.config.ts | 16 ++-- 4 files changed, 228 insertions(+), 22 deletions(-) create mode 100644 e2e/shard.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d0829a6..a3f2536 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,12 +3,30 @@ name: CI # Every check a change must pass: types, lint, unit tests, the production build, end-to-end tests # (demo mode at three screen sizes, with axe accessibility checks) and the Rust checks. The # release workflow runs it too (workflow_call), so a tag is only released from a green commit. +# +# It runs on pull requests and on pushes to main. Pushes to other branches don't run it: a pull +# request's branch would run it twice for every commit. Start it by hand (workflow_dispatch) for a +# branch without a pull request. +# +# The end-to-end tests take most of the time, so the app is built once and the tests are split +# across four jobs that run side by side. The branch rules require "Lint, test & build" and +# "Desktop shell (Rust)" by name: "Lint, test & build" collects the build, the checks and every +# end-to-end job, and fails if any of them failed. Changes that can't affect a part skip it (a +# skipped job counts as passed): documentation skips the end-to-end tests, and anything outside +# src-tauri/ skips the Rust checks. on: push: - branches: [main, "feature/**"] + branches: [main] pull_request: workflow_dispatch: workflow_call: + inputs: + run: + description: >- + "all" runs every check; "build" only builds the web app (the release workflow's dry runs: + their pull request runs every check already). + type: string + default: all permissions: contents: read @@ -20,9 +38,49 @@ concurrency: cancel-in-progress: true jobs: - web: - name: Lint, test & build + changes: + name: What changed + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + checks: ${{ steps.filter.outputs.checks }} + e2e: ${{ steps.filter.outputs.e2e }} + rust: ${{ steps.filter.outputs.rust }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - id: filter + env: + # Empty unless another workflow calls this one. + RUN: ${{ inputs.run }} + EVENT: ${{ github.event_name }} + # What the change is compared with: the pull request's base, or main before the push. + BASE: ${{ github.event.pull_request.base.sha || github.event.before }} + run: | + checks=true e2e=true rust=true + if [[ "$RUN" == build ]]; then + checks=false e2e=false rust=false + # Anything this can't work out (a run by hand or from another workflow, a new branch, a + # base it can't fetch) runs everything. + elif [[ -z "$RUN" && "$EVENT" =~ ^(push|pull_request)$ && "$BASE" =~ ^[0-9a-f]{40}$ && ! "$BASE" =~ ^0+$ ]] && + git fetch --quiet --no-tags --depth=1 origin "$BASE" && + files=$(git diff --name-only "$BASE" "$GITHUB_SHA"); then + echo "Changed files:" + echo "$files" + # Markdown, docs/, the licence and the repository's settings in .github/ can't change + # what the end-to-end tests see; this workflow can. The checks job always runs: one of + # its tests checks every file name, docs included. + code=$(grep -vE '\.md$|^docs/|^LICENSE$|^\.github/' <<< "$files" || true) + if [[ -z "$code" ]] && ! grep -qx '.github/workflows/ci.yml' <<< "$files"; then e2e=false; fi + grep -qE '^src-tauri/|^\.github/workflows/ci\.yml$' <<< "$files" || rust=false + fi + { echo "checks=$checks"; echo "e2e=$e2e"; echo "rust=$rust"; } | tee -a "$GITHUB_OUTPUT" + + build: + name: Build runs-on: ubuntu-latest + timeout-minutes: 10 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -32,10 +90,9 @@ jobs: node-version-file: .nvmrc cache: npm - run: npm ci - - run: npm run typecheck - - run: npm run lint - - run: npm test - - run: npm run build + # npm run build is tsc -b && vite build. The types are checked in the checks job, side by + # side with this one, so the end-to-end jobs get the build sooner. + - run: npx vite build - name: Upload the web build uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: @@ -43,22 +100,103 @@ jobs: path: dist/ if-no-files-found: error retention-days: 14 - - name: Install Playwright browser - run: npx playwright install --with-deps chromium + + checks: + name: Types, lint & unit tests + needs: changes + if: needs.changes.outputs.checks == 'true' + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version-file: .nvmrc + cache: npm + - run: npm ci + - run: npm run typecheck + - run: npm run lint + - run: npm test + + e2e: + name: End-to-end tests (${{ matrix.shard }}/${{ strategy.job-total }}) + needs: [changes, build] + if: needs.changes.outputs.e2e == 'true' + runs-on: ubuntu-latest + timeout-minutes: 15 + strategy: + # Every shard runs to the end, so one run reports every failing test. + fail-fast: false + matrix: + # Add a number to split the tests further. + shard: [1, 2, 3, 4] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version-file: .nvmrc + cache: npm + - run: npm ci + # Headless tests run in Chromium's headless shell, so the full browser isn't downloaded. + # Caching the download saves no time: restoring it takes about as long as fetching it. + - name: Install Playwright's browser + run: npx playwright install --with-deps --only-shell chromium + - name: Download the web build + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: statsify-web + path: dist - name: End-to-end tests (demo mode, 3 screen sizes, axe accessibility) - run: npm run e2e + env: + SHARD: ${{ matrix.shard }} + SHARDS: ${{ strategy.job-total }} + # Serve the downloaded build instead of building again. + E2E_PREBUILT: "1" + # e2e/shard.ts deals the tests out between the jobs in turn, so they take about as long + # as each other (Playwright's --shard gives one job all the slowest specs). + run: | + node e2e/shard.ts "$SHARD" "$SHARDS" "$RUNNER_TEMP/tests.txt" + npx playwright test --test-list "$RUNNER_TEMP/tests.txt" - name: Upload screenshots of failed end-to-end tests if: failure() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: e2e-failures + name: e2e-failures-${{ matrix.shard }} path: test-results/ if-no-files-found: ignore retention-days: 7 + web: + name: Lint, test & build + needs: [changes, build, checks, e2e] + # Always reports, cancelled runs included: a required check that is skipped counts as passed. + if: always() + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Every part passed, or wasn't needed for this change + env: + CHANGES: ${{ needs.changes.result }} + BUILD: ${{ needs.build.result }} + CHECKS: ${{ needs.checks.result }} + E2E: ${{ needs.e2e.result }} + run: | + echo "What changed: $CHANGES. Build: $BUILD. Types, lint & unit tests: $CHECKS. End-to-end tests: $E2E." + [[ "$CHANGES" == success && "$BUILD" == success ]] || exit 1 + for result in "$CHECKS" "$E2E"; do + [[ "$result" == success || "$result" == skipped ]] || exit 1 + done + rust: name: Desktop shell (Rust) + needs: changes + if: needs.changes.outputs.rust == 'true' runs-on: ubuntu-latest + timeout-minutes: 20 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 940e0a2..94a58b6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -11,16 +11,13 @@ name: Release # - pushing a version tag by hand (v1.2.0, or v1.2.0-beta.1 for a pre-release from any branch). # # Everything else is a dry run that builds and packages the release without creating one: pull -# requests and feature-branch pushes that change this workflow or the version script, and runs -# started by hand from a branch. (Started by hand from a tag, it releases that tag.) +# requests that change this workflow or the version script, and runs started by hand from a +# branch. (Started by hand from a tag, it releases that tag.) A dry run builds the web app without +# running CI's checks again: the pull request's own CI run has them. # docs/RELEASING.md has the whole process. on: push: tags: ["v*.*.*"] - branches: ["feature/**"] - paths: - - ".github/workflows/release.yml" - - "scripts/set-version.mjs" pull_request: paths: - ".github/workflows/release.yml" @@ -97,6 +94,9 @@ jobs: name: CI needs: version uses: ./.github/workflows/ci.yml + with: + # A release runs every check; a dry run only needs the web build to package. + run: ${{ needs.version.outputs.release == 'true' && 'all' || 'build' }} desktop: name: Desktop app diff --git a/e2e/shard.ts b/e2e/shard.ts new file mode 100644 index 0000000..8cb6279 --- /dev/null +++ b/e2e/shard.ts @@ -0,0 +1,62 @@ +/** + * Splits the end-to-end tests between CI's parallel jobs. + * + * node e2e/shard.ts 2 4 shard.txt && npx playwright test --test-list shard.txt + * + * writes the second of four lists to shard.txt and runs it. Playwright's own `--shard` cuts the + * ordered tests into consecutive runs of equal count, so the job that starts with the slowest + * specs (a11y, app, autostart) took about twice as long as the job with the phone's tests. This + * deals the tests out in turn instead, like cards, so every job gets its share of every spec and + * they finish close together. Every test lands in exactly one list. + * + * The list is checked against what Playwright then selects from it: a test it didn't recognise + * would otherwise be dropped without a word (an empty list passes). + */ +import { execFileSync } from "node:child_process"; +import { writeFileSync } from "node:fs"; + +interface JsonSuite { + title: string; + file: string; + specs?: { title: string; tests: { projectName: string }[] }[]; + suites?: JsonSuite[]; +} + +const [shard, total] = process.argv.slice(2, 4).map(Number); +const out = process.argv[4]; +if (!Number.isInteger(shard) || !Number.isInteger(total) || shard < 1 || shard > total || !out) { + console.error("Usage: node e2e/shard.ts <shard> <total> <output file>, e.g. 2 4 shard.txt"); + process.exit(2); +} + +/** Playwright's JSON listing, with or without a test list to pick from. */ +function list(...args: string[]): JsonSuite[] { + const json = execFileSync("npx", ["playwright", "test", "--list", "--reporter=json", ...args], { + encoding: "utf8", + maxBuffer: 256 * 1024 * 1024, + }); + return (JSON.parse(json) as { suites: JsonSuite[] }).suites; +} + +/** One line per test, in the --test-list format: "[project] › file › describe › title". */ +function lines(suites: JsonSuite[]): string[] { + const found: string[] = []; + const walk = (suite: JsonSuite, titles: string[]) => { + for (const spec of suite.specs ?? []) + for (const test of spec.tests) + found.push([`[${test.projectName}]`, suite.file, ...titles, spec.title].join(" › ")); + for (const child of suite.suites ?? []) walk(child, [...titles, child.title]); + }; + // The top-level suites are the files themselves, titled with their path. + for (const file of suites) walk(file, []); + return found; +} + +const mine = lines(list()).filter((_, i) => i % total === shard - 1); +writeFileSync(out, `${mine.join("\n")}\n`); +const picked = lines(list("--test-list", out)).length; +if (mine.length === 0 || picked !== mine.length) { + console.error(`Shard ${shard}/${total}: wrote ${mine.length} tests, but Playwright picks ${picked} of them.`); + process.exit(1); +} +console.log(`Shard ${shard}/${total}: ${mine.length} tests in ${out}.`); diff --git a/playwright.config.ts b/playwright.config.ts index 2d256f9..d12efb4 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -3,6 +3,7 @@ import { defineConfig, devices } from "@playwright/test"; /** E2E_PORT runs the suite on another port, so several runs can share a machine. */ const port = Number(process.env.E2E_PORT) || 4173; const origin = `http://127.0.0.1:${port}`; +const ci = Boolean(process.env.CI); /** * Tablet and phone run app.spec.ts (every page at every size) and, from the other specs, the tests @@ -21,9 +22,12 @@ export default defineConfig({ timeout: 45_000, expect: { timeout: 10_000 }, fullyParallel: true, - forbidOnly: Boolean(process.env.CI), - retries: process.env.CI ? 1 : 0, - reporter: process.env.CI ? [["github"], ["list"]] : "list", + forbidOnly: ci, + retries: ci ? 1 : 0, + // Two browsers per CI job (half of a 4-core runner): the waves render in software, and the + // timing and pixel checks need the rest of the machine. + workers: ci ? 2 : undefined, + reporter: ci ? [["github"], ["list"]] : "list", use: { baseURL: origin, screenshot: "only-on-failure", @@ -38,9 +42,11 @@ export default defineConfig({ { name: "phone", grep: ALL_SIZES, use: { ...devices["Pixel 7"] } }, ], webServer: { - command: `npm run build && npx vite preview --host 127.0.0.1 --port ${port} --strictPort`, + // CI builds once and gives every end-to-end job that dist/ (E2E_PREBUILT); otherwise the + // tests build what is checked out. + command: `${process.env.E2E_PREBUILT ? "" : "npm run build && "}npx vite preview --host 127.0.0.1 --port ${port} --strictPort`, url: origin, - reuseExistingServer: !process.env.CI, + reuseExistingServer: !ci, timeout: 180_000, }, }); From 5ab8287ea1775cacc01778a4cfc2a4036435bce8 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:30:56 +0000 Subject: [PATCH 21/41] test(e2e): drop repeated checks and waits that bought nothing About 5 % less test time (measured on the same machine at the same time as the branch point), every behaviour and past bug still covered: - a11y: each theme ran five looks in one 28 s test. 60 % see-through with Blue is gone: Blue is no extreme, and 60 % lies between opaque and the 90 % still checked. The rest run as one test per theme and look (20), so they spread across workers and CI jobs. - app: the memory check runs on desktop only (the heap doesn't depend on the window), each page no longer sleeps 400 ms before axe (it waits for aria-busy to clear), and the keyboard shortcut test is gone: a11y.spec opens help with ? and regression.spec checks G T and /. - real: the 500 error state (Try again, axe, no errors) joins devlog's [all sizes] test of the same failure; the offline message is covered by regression.spec's offline page (now also checking for errors) and stats.spec's history pages. - regression: a token refresh that never answers is cut off by the app's 20 s deadline on a fake clock instead of waiting it out (21 s to about 3). - autostart: the two "mashing Play five times" tests were one scenario; they are one test. The tray test waits for the pause request instead of expecting it the moment the button flips (it failed under load). - fullscreen: the player's axe scan repeated a11y.spec's overlays; the focus trap stays. - window-states: the date's contrast over the waves in full screen repeated backgrounds.spec, which measures it over three loads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- e2e/a11y.spec.ts | 18 ++++++++++-------- e2e/app.spec.ts | 22 +++++----------------- e2e/autostart.spec.ts | 16 +++++----------- e2e/devlog.spec.ts | 8 ++++++-- e2e/fullscreen.spec.ts | 6 ++---- e2e/real.spec.ts | 19 ------------------- e2e/regression.spec.ts | 10 ++++++++-- e2e/window-states.spec.ts | 15 +++------------ 8 files changed, 39 insertions(+), 75 deletions(-) diff --git a/e2e/a11y.spec.ts b/e2e/a11y.spec.ts index 4a681e3..e886e5f 100644 --- a/e2e/a11y.spec.ts +++ b/e2e/a11y.spec.ts @@ -36,18 +36,20 @@ async function contrastOf(page: Page, a: string, b: string): Promise<number> { } test.describe("every theme, see-through or not, with any accent", () => { + // The accents the token engine has to work hardest for: Mono (near white, with a rule of its + // own), pure yellow and black. See-through is checked at 90 %, the most see-through the + // surfaces get; levels between that and opaque fall between the two. const looks: { name: string; settings: Record<string, unknown> }[] = [ { name: "opaque", settings: {} }, - { name: "60 % see-through, Blue", settings: { transparency: true, transparencyLevel: 60, accent: "blue" } }, { name: "90 % see-through, Mono", settings: { transparency: true, transparencyLevel: 90, accent: "white" } }, { name: "custom yellow", settings: { accent: "custom", accentColor: "#ffff00" } }, { name: "custom black", settings: { accent: "custom", accentColor: "#000000" } }, ]; + // One test per theme and look, so they run side by side. for (const theme of THEMES) { - test(`${theme}: pages, menus and dialogs pass axe`, async ({ page }) => { - test.setTimeout(120_000); - const errors = trackErrors(page); - for (const look of looks) { + for (const look of looks) { + test(`${theme}, ${look.name}: pages pass axe and the focus ring stands out`, async ({ page }) => { + const errors = trackErrors(page); await page.addInitScript( ([t, s]) => { localStorage.setItem("ss.demo", "true"); @@ -92,9 +94,9 @@ test.describe("every theme, see-through or not, with any accent", () => { expect(await contrastOf(page, ring, bg), `${theme} ${look.name} focus ring on ${bg}`).toBeGreaterThanOrEqual( 3, ); - } - expect(errors).toEqual([]); - }); + expect(errors).toEqual([]); + }); + } } }); diff --git a/e2e/app.spec.ts b/e2e/app.spec.ts index 7b6311b..eb684c6 100644 --- a/e2e/app.spec.ts +++ b/e2e/app.spec.ts @@ -1,5 +1,5 @@ import { expect, test, type Page } from "@playwright/test"; -import { enterDemo, noSeriousA11y } from "./helpers"; +import { enterDemo, noSeriousA11y, settled } from "./helpers"; async function expectNoHorizontalScroll(page: Page) { // The app shell scrolls inside <main>, which can scroll sideways while the page itself doesn't. @@ -66,7 +66,7 @@ test.describe("every page", () => { await enterDemo(page, path); await expect(page.getByRole("heading", { level: 1, name: heading }).first()).toBeAttached(); await page.waitForLoadState("networkidle"); - await page.waitForTimeout(400); + await settled(page); await noSeriousA11y(page, path); await expectNoHorizontalScroll(page); expect(errors).toEqual([]); @@ -190,20 +190,6 @@ test.describe("settings & keyboard", () => { await expect(page.locator("html")).toHaveAttribute("data-theme", "light"); }); - test("keyboard shortcuts navigate and open help", async ({ page, isMobile }) => { - test.skip(isMobile, "Keyboard shortcuts are for physical keyboards"); - await enterDemo(page, "/"); - await expect(page.getByRole("heading", { level: 1 })).toBeVisible(); - await page.locator("body").press("?"); - await expect(page.getByRole("dialog", { name: "Keyboard shortcuts" })).toBeVisible(); - await page.keyboard.press("Escape"); - await page.locator("body").press("g"); - await page.locator("body").press("t"); - await expect(page).toHaveURL(/\/top\/tracks/); - await page.locator("body").press("/"); - await expect(page.locator("#global-search")).toBeFocused(); - }); - test("skip link moves focus to the main content", async ({ page, isMobile }) => { test.skip(isMobile, "Skip links are a keyboard feature"); await enterDemo(page, "/"); @@ -216,8 +202,10 @@ test.describe("settings & keyboard", () => { }); }); -test("stays light on memory after browsing every page", async ({ page, browserName }) => { +test("stays light on memory after browsing every page", async ({ page, browserName }, info) => { test.skip(browserName !== "chromium"); + // The heap doesn't depend on the window's size: once is enough. + test.skip(info.project.name !== "desktop", "Runs once, on the desktop project"); await enterDemo(page, "/"); for (const [path] of ROUTES) { await page.goto(path); diff --git a/e2e/autostart.spec.ts b/e2e/autostart.spec.ts index 3085984..3ad7a92 100644 --- a/e2e/autostart.spec.ts +++ b/e2e/autostart.spec.ts @@ -133,27 +133,20 @@ test.describe("Play with nothing to play on", () => { await expectClean(ctx); }); - test("mashing Play five times starts Spotify once", async ({ page }) => { + test("mashing Play five times starts Spotify once, then moves playback and plays once", async ({ page }) => { + // Queued presses don't each start Spotify, nor replay a transfer and a play once it's online. const ctx = await setup(page); for (let i = 0; i < 5; i++) await playButton(page).click(); await expect(launchingStatus(page)).toBeVisible(); await expect(pauseButton(page)).toBeVisible({ timeout: 15_000 }); await page.waitForTimeout(1_500); expect(ctx.desktop.launches.length).toBe(1); + expect({ transfers: ctx.connect.transfers().length, plays: ctx.connect.plays().filter((p) => p.status !== 404).length }).toEqual({ transfers: 1, plays: 1 }); await expect(pauseButton(page)).toBeVisible(); await expect(banner(page)).toHaveCount(0); await expectClean(ctx); }); - test("mashing Play five times moves playback and plays once", async ({ page }) => { - // Queued presses don't each replay a transfer and a play once Spotify is online. - const ctx = await setup(page); - for (let i = 0; i < 5; i++) await playButton(page).click(); - await expect(pauseButton(page)).toBeVisible({ timeout: 15_000 }); - await page.waitForTimeout(1_500); - expect({ transfers: ctx.connect.transfers().length, plays: ctx.connect.plays().filter((p) => p.status !== 404).length }).toEqual({ transfers: 1, plays: 1 }); - }); - test("a slow launch command keeps the status up until Spotify is online", async ({ page }) => { const ctx = await setup(page, { launch: "slow", launchDelayMs: 2_000 }); await playButton(page).click(); @@ -174,7 +167,8 @@ test.describe("Play with nothing to play on", () => { expect(ctx.desktop.launches.length).toBe(1); await ctx.desktop.emit("tray-action", "play-pause"); await expect(playButton(page)).toBeVisible(); - expect(ctx.connect.requests.some((r) => r.method === "PUT" && r.path === "/me/player/pause" && r.status === "mock")).toBe(true); + // The button flips at once; the request follows. + await expect.poll(() => ctx.connect.requests.some((r) => r.method === "PUT" && r.path === "/me/player/pause" && r.status === "mock")).toBe(true); // The tray tooltip follows the song. await expect.poll(async () => (await ctx.desktop.calls()).filter((c) => c.cmd === "set_tray_tooltip").map((c) => (c.args as { text: string }).text)).toContain("Track 1 · Artist 1"); await expectClean(ctx); diff --git a/e2e/devlog.spec.ts b/e2e/devlog.spec.ts index 266c61d..7632664 100644 --- a/e2e/devlog.spec.ts +++ b/e2e/devlog.spec.ts @@ -1,6 +1,6 @@ import { expect, test, type Page } from "@playwright/test"; import { mockSpotify } from "./mock-spotify"; -import { enterDemo, noSeriousA11y } from "./helpers"; +import { enterDemo, noSeriousA11y, trackErrors } from "./helpers"; /** Right-click menu and the developer log (errors, network, events, system). */ @@ -75,11 +75,14 @@ test("the developer log shows every API call with endpoint, status and data, and await expect(devlog(page)).toBeVisible(); }); -test("a failed request is one click from its details [all sizes]", async ({ page }) => { +test("a server error is a retryable error state, one click from its details [all sizes]", async ({ page }) => { + const errors = trackErrors(page); await mockSpotify(page, { fail: { "/me/top/tracks": 500 } }); await page.goto("/top/tracks"); const alert = page.getByRole("alert").filter({ hasText: /spotify had a problem/i }); await expect(alert).toBeVisible({ timeout: 20_000 }); + await expect(alert.getByRole("button", { name: "Try again" })).toBeVisible(); + await noSeriousA11y(page, "error state"); await alert.getByRole("button", { name: "Details" }).click(); await expect(devlog(page)).toBeVisible(); await expect(devlog(page).getByRole("radio", { name: /^Errors/ })).toHaveAttribute("aria-checked", "true"); @@ -87,6 +90,7 @@ test("a failed request is one click from its details [all sizes]", async ({ page await expect(devlog(page).getByRole("list", { name: "Log entries" }).getByText(/\/v1\/me\/top\/tracks.* → 500/).first()).toBeVisible(); const overflow = await page.evaluate(() => document.documentElement.scrollWidth - innerWidth); expect(overflow).toBeLessThanOrEqual(1); + expect(errors).toEqual([]); }); test("All time on Top charts adds up the whole history, and songs open their stats", async ({ page }) => { diff --git a/e2e/fullscreen.spec.ts b/e2e/fullscreen.spec.ts index 09ee9c3..4f1da16 100644 --- a/e2e/fullscreen.spec.ts +++ b/e2e/fullscreen.spec.ts @@ -73,7 +73,8 @@ test.describe("full-screen player", () => { await expect(page.getByRole("dialog")).toBeHidden(); }); - test("keeps keyboard focus inside and is accessible", async ({ page }) => { + // axe checks each of its views in a11y.spec.ts ("overlays"). + test("keeps keyboard focus inside", async ({ page }) => { await seedDemo(page); await page.goto("/"); await expect(page.getByRole("heading", { level: 1 })).toBeVisible(); @@ -84,9 +85,6 @@ test.describe("full-screen player", () => { await page.keyboard.press("Tab"); expect(await page.evaluate(() => Boolean(document.activeElement?.closest('[role="dialog"]')))).toBe(true); } - await settleAnimations(page); - const results = await new AxeBuilder({ page }).include('[role="dialog"]').withTags(WCAG_TAGS).analyze(); - expect(results.violations.filter((v) => v.impact === "serious" || v.impact === "critical").map((v) => `${v.id} ${v.nodes[0]?.target}`)).toEqual([]); }); test("controls fade out after a few seconds and come back on movement", async ({ page }) => { diff --git a/e2e/real.spec.ts b/e2e/real.spec.ts index e6a4e08..1f15b28 100644 --- a/e2e/real.spec.ts +++ b/e2e/real.spec.ts @@ -75,17 +75,6 @@ test.describe("signed in", () => { expect(errors).toEqual([]); }); - test("server errors show a retryable error state", async ({ page }) => { - const errors = trackErrors(page); - await mockSpotify(page, { fail: { "/me/top/tracks": 500 } }); - await page.goto("/top/tracks"); - const alert = page.getByRole("alert").filter({ hasText: /spotify had a problem/i }); - await expect(alert).toBeVisible({ timeout: 20_000 }); - await expect(alert.getByRole("button", { name: "Try again" })).toBeVisible(); - await noSeriousA11y(page, "error state"); - expect(errors).toEqual([]); - }); - test("rate limiting is retried transparently", async ({ page }) => { const log = await mockSpotify(page, { rateLimit: { "/me/top/artists": 2 } }); await page.goto("/top/artists"); @@ -93,14 +82,6 @@ test.describe("signed in", () => { expect(log.requests.filter((r) => r.path.startsWith("/me/top/artists")).length).toBeGreaterThanOrEqual(3); }); - test("offline shows an offline message, not a crash", async ({ page }) => { - const errors = trackErrors(page); - await mockSpotify(page, { offline: true }); - await page.goto("/top/tracks"); - await expect(page.getByText(/you're offline/i).first()).toBeVisible({ timeout: 20_000 }); - expect(errors).toEqual([]); - }); - test("an expired token is refreshed before use", async ({ page }) => { const log = await mockSpotify(page, { expired: true }); await page.goto("/"); diff --git a/e2e/regression.spec.ts b/e2e/regression.spec.ts index 70a6f85..8c17e50 100644 --- a/e2e/regression.spec.ts +++ b/e2e/regression.spec.ts @@ -212,7 +212,8 @@ test("the demo keeps working when the device goes offline", async ({ page }) => expect(errors).toEqual([]); }); -test("a page that couldn't load while offline loads by itself when the connection is back", async ({ page }) => { +test("a page that couldn't load while offline says so, and loads by itself when the connection is back", async ({ page }) => { + const errors = trackErrors(page); await mockSpotify(page); let offline = false; await page.route("https://api.spotify.com/**", (route) => (offline ? route.abort("internetdisconnected") : route.fallback())); @@ -228,6 +229,7 @@ test("a page that couldn't load while offline loads by itself when the connectio await page.context().setOffline(false); await expect(page.getByRole("heading", { level: 1, name: "Playlist 2" })).toBeVisible(); await expect(page.getByRole("alert").filter({ hasText: "You're offline" })).toHaveCount(0); + expect(errors).toEqual([]); }); test("pressing F quickly never leaves the window full screen with the player closed", async ({ page, isMobile }) => { @@ -311,6 +313,8 @@ test("a seek set without a pointer or keys (as a screen reader does) is sent, an }); test("a token refresh lost on a dropped connection doesn't freeze the app", async ({ page }) => { + // A fake clock (time still flows) skips the 20 s the app gives a token request to answer. + await page.clock.install(); await mockSpotify(page, { expired: true }); let refreshes = 0; await page.route("https://accounts.spotify.com/api/token", async (route) => { @@ -319,7 +323,9 @@ test("a token refresh lost on a dropped connection doesn't freeze the app", asyn await route.fallback(); }); await page.goto("/"); - await expect(page.getByRole("table", { name: "Top tracks this month" })).toBeVisible({ timeout: 35_000 }); + await expect.poll(() => refreshes).toBe(1); + await page.clock.fastForward(20_000); + await expect(page.getByRole("table", { name: "Top tracks this month" })).toBeVisible({ timeout: 15_000 }); expect(refreshes).toBe(2); }); diff --git a/e2e/window-states.spec.ts b/e2e/window-states.spec.ts index 6a19b74..130c30f 100644 --- a/e2e/window-states.spec.ts +++ b/e2e/window-states.spec.ts @@ -1,14 +1,7 @@ import { expect, test, type Page } from "@playwright/test"; import { fakeDesktop, type FakeDesktop } from "./fake-desktop"; import { noSeriousA11y, seedDemo, trackErrors } from "./helpers"; -import { - backgroundFrames, - clearBackgroundFrames, - contrastBehind, - paintedAlpha, - recordBackground, - type BackgroundFrame, -} from "./pixels"; +import { backgroundFrames, clearBackgroundFrames, paintedAlpha, recordBackground, type BackgroundFrame } from "./pixels"; /** * The page's background in every window state: in a window, maximised, full screen (F11), the @@ -206,11 +199,9 @@ test("a full-screen window that can't be see-through shows the album background await expect(backdrop.locator("[data-renderer]")).toBeVisible(); await expect(backdrop).toHaveCSS("opacity", "1"); await expectGlass(page, null, "full screen, solid"); - await page.waitForTimeout(600); - const date = page.locator("#main").getByText(/^(Mon|Tues|Wednes|Thurs|Fri|Satur|Sun)day, /); - expect(await contrastBehind(page, date)).toBeGreaterThanOrEqual(4.5); // axe can't see the waves (a canvas that ignores the pointer) and would assume white behind - // the text; the contrast over the real pixels is measured above. Give it the theme's canvas. + // the text. backgrounds.spec.ts measures the text over the waves' real pixels, drawn the same + // way in a window ("Always"); give axe the theme's canvas. const canvas = await page.addStyleTag({ content: "html { background-color: Canvas !important; }" }); await noSeriousA11y(page, "full screen over the album background"); await canvas.evaluate((el) => (el as HTMLStyleElement).remove()); From f9b9cd7731e33d88dc78b715665cc6778544c378 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:08:43 +0000 Subject: [PATCH 22/41] docs: describe the split CI jobs and how end-to-end tests pick their sizes AGENTS.md (Testing) and DEVELOPMENT.md (end-to-end tests, CI): sizes chosen in the config, e2e/shard.ts and how to run one CI job's share, the jobs CI runs and the two required checks, what each kind of change skips, and when CodeQL, the installers and the release dry run start. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- AGENTS.md | 55 ++++++++++++++++++++++++++++++++------------- docs/DEVELOPMENT.md | 54 +++++++++++++++++++++++++++++++++----------- 2 files changed, 81 insertions(+), 28 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 12ce7ee..850e58b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -714,11 +714,17 @@ modules that need context are welcome. player's autostart and resume logic (fake timers), the developer log's redaction, and key components. Prefer testing pure functions directly. - **Playwright** (`npm run e2e`): builds the app and serves it on `127.0.0.1:4173`; three projects: - `desktop` (1366 × 768), `tablet` (820 × 1180, touch) and `phone` (Pixel 7). Specs call - `desktopOnlyUnlessAllSizes()` (from `e2e/helpers.ts`) so their tests run on the desktop project - only, unless the title contains `[all sizes]`; `app.spec.ts` runs everything at every size. + `desktop` (1366 × 768), `tablet` (820 × 1180, touch) and `phone` (Pixel 7). + `playwright.config.ts` gives tablet and phone `app.spec.ts` and, from the other specs, only the + tests whose title contains `[all sizes]` (a `grep` per project, so the rest are never queued + rather than skipped). Mark a test `[all sizes]` only when its layout or input differs at those + sizes. Each test should earn its time: check a behaviour once, in the spec that owns it, and + wait with web-first assertions or `expect.poll` (a fixed `waitForTimeout` only to prove that + something does _not_ happen), or with `page.clock` for the app's own long timers. CI splits the + tests between four jobs with `e2e/shard.ts` (below). - `app.spec.ts`: demo mode end to end: every route renders without errors, axe-clean, no - horizontal scroll; player, library, import, settings, keyboard, memory, extreme sizes. + horizontal scroll, at every size; player, library, import, settings and the skip link; + memory and extreme sizes (desktop project only). - `real.spec.ts`: the signed-in code path against `mock-spotify.ts` (empty accounts, 5xx, 429, offline, expired and revoked tokens, no Premium, hostile names and links, callback replay, corrupt storage, 10,000-track playlists, fixing a wrong Client ID on the web and desktop). @@ -739,9 +745,10 @@ modules that need context are welcome. storage, going offline and back, requests that never answer, quick full-screen toggling, held shortcut keys, a seek set without pointer or keys (a screen reader), focus while a page's code is still downloading, page code prefetched once on hover and idle. - - `a11y.spec.ts`: WCAG 2.2 AA beyond plain pages: every theme opaque and see-through with - extreme accents (and the focus ring's contrast), open menus, dialogs, sheets, toasts and the - full-screen player, the phone's More sheet, and what axe can't see: focus order out of menus, + - `a11y.spec.ts`: WCAG 2.2 AA beyond plain pages: every theme opaque and 90 % see-through, + with the extreme accents (Mono, yellow, black; one test per theme and look) and the focus + ring's contrast, open menus, dialogs, sheets, toasts and the full-screen player, the phone's + More sheet, and what axe can't see: focus order out of menus, visible focus, truncated links, radio groups, single-key shortcuts, moving pins without dragging, hoverable tooltips (their state, key chips, contrast in every theme, no tips left behind by a tap), form errors. @@ -788,6 +795,11 @@ modules that need context are welcome. label)` (axe WCAG 2.2 A/AA, no serious or critical violations), `enterDemo`, `seedDemo`, `settled` (wait for `aria-busy` to clear). - Tests assert what users see, using roles and accessible names, not CSS classes. + - `e2e/shard.ts <n> <total> <file>` writes the `n`th of `total` lists of tests, dealt out in + turn (Playwright's `--shard` cuts consecutive runs, which gave one job all the slowest specs), + for `npx playwright test --test-list <file>`; it fails if Playwright doesn't pick every test + it wrote. CI's jobs serve a build made once (`E2E_PREBUILT=1` skips the build in the + config's web server) and run two workers each. - **Rust** (`cargo test` in `src-tauri/`): unit tests in each module (schema, migrations, validation, the binary format, a 200k-play history, the sign-in listener against raw HTTP requests, launch plans, window-material plans) and integration tests through the IPC layer @@ -798,11 +810,22 @@ label)` (axe WCAG 2.2 A/AA, no serious or critical violations), `enterDemo`, `se Windows SDK is available, or rely on the Windows desktop build in `desktop.yml`. - **Workflows** (`.github/workflows/`, every action pinned to a commit SHA, Dependabot keeps them current): - - `ci.yml`: typecheck, lint, unit tests, build, e2e, and the three cargo checks on every push to - `main` or `feature/**` and on pull requests; uploads the web build (`statsify-web`) and, on - failure, e2e screenshots (`e2e-failures`). Also callable (`workflow_call`). - - `desktop.yml`: installers on Windows, Linux and macOS (universal) when the app's code changes; - also callable. Pre-release versions skip the MSI (WiX accepts numeric versions only). + - `ci.yml`: on pull requests and pushes to `main` (not pushes to other branches, which would + run every pull request twice; start it by hand for a branch without one). Jobs side by side: + **Build** (`vite build` once, uploaded as `statsify-web`), **Types, lint & unit tests**, four + **End-to-end tests** jobs that download that build (`e2e/shard.ts`; screenshots of failures + as `e2e-failures-<n>`), and the three cargo checks. The branch rules require two checks by + name: **Lint, test & build**, a job that needs the others and fails unless each passed or + wasn't needed, and **Desktop shell (Rust)**; keep both names when changing the jobs. A + "What changed" job skips the end-to-end tests for changes to Markdown, `docs/` and + `.github/` (other than `ci.yml`), and the Rust checks for changes outside `src-tauri/`; + a skipped job counts as passed, so use a job-level `if`, never `on: paths`, in this + workflow (a required check that never starts blocks merging). Also callable + (`workflow_call`, `run: all` or `build`). + - `desktop.yml`: installers on Windows, Linux and macOS (universal) when the app's code reaches + `main`, and on pull requests that change `src-tauri/`, the dependencies, `vite.config.ts` or + the workflow; also callable. Pre-release versions skip the MSI (WiX accepts numeric versions + only). - `release-on-main.yml`: on every push to `main`, reads the version from `package.json` and, when `v<version>` has no tag yet, calls `release.yml` for that commit; otherwise it stops there. Releasing is setting the version (`npm run version:set`) and merging it. @@ -812,9 +835,11 @@ label)` (axe WCAG 2.2 A/AA, no serious or critical violations), `enterDemo`, `se Release with generated notes, creating the tag on the commit when it doesn't exist. The "release tags" ruleset must not restrict creating `v*` tags for that (RELEASING.md, One-time set-up: a personal repository's ruleset can't list GitHub Actions as a bypass - actor); otherwise the release is left as a draft for an admin to publish. Changes - to it run a dry run. - - `codeql.yml`: code scanning for TypeScript, Rust and the workflows. + actor); otherwise the release is left as a draft for an admin to publish. Pull requests + that change it or the version script run a dry run, which calls `ci.yml` with `run: build` + (the pull request's own CI run has the checks). + - `codeql.yml`: code scanning for TypeScript, Rust and the workflows, on pull requests, + pushes to `main` and weekly. - `labeler.yml`: labels pull requests by files (`.github/labeler.yml`) and title type; the release notes group by those labels (`.github/release.yml`). Runs on `pull_request` (GitHub blocks `pull_request_target` on public repositories by default) and skips pull requests from diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 51f05d0..9977b92 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -155,8 +155,17 @@ E2E_PORT=4801 npm run e2e # on another port ``` There are three projects: `desktop` (1366 × 768), `tablet` (820 × 1180, touch) and `phone` -(Pixel 7). Specs run on `desktop` only unless the test's title contains `[all sizes]`. To see why a -test failed, run it again with `--trace on` and open the trace with `npx playwright show-trace`. +(Pixel 7). `app.spec.ts` runs on all three; the other specs run on `desktop` only, unless the +test's title contains `[all sizes]` (`playwright.config.ts` filters them, so `--project=phone` +lists only the tests that run there). To see why a test failed, run it again with `--trace on` +and open the trace with `npx playwright show-trace`. + +CI splits the tests between four jobs. To run one job's share, as CI does: + +```bash +node e2e/shard.ts 2 4 /tmp/shard.txt # the second of four lists +npx playwright test --test-list /tmp/shard.txt +``` Outside CI, Playwright reuses a server already listening on the port. After changing code, stop an old `npm run preview` (or use `E2E_PORT`) so the tests build and serve the new code. @@ -212,14 +221,33 @@ checks above cover it. Elsewhere, `rustup target add x86_64-pc-windows-msvc` and Every workflow is in `.github/workflows/`. Actions are pinned to commit SHAs; Dependabot updates them, and npm and Cargo dependencies, every week (`.github/dependabot.yml`). -| Workflow | When | What it does | -| ------------------------------------------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | -| **CI** (`ci.yml`) | Pushes to `main` and `feature/**`, pull requests | Typecheck, lint, unit tests, build, end-to-end tests with axe, then `cargo fmt`, `clippy` and `cargo test` | -| **Desktop app** (`desktop.yml`) | Pushes and pull requests that change the app | Builds the installers on Windows, Linux and macOS and keeps them as downloadable artifacts for 14 days | -| **Release on main** (`release-on-main.yml`) | Pushes to `main` | Releases the version in `package.json` when it has no tag yet, by running **Release** on that commit | -| **Release** (`release.yml`) | Called by Release on main, version tags (`v1.2.0`); dry runs when the workflow itself changes | Checks the version, runs CI and the desktop builds, and publishes a GitHub Release ([RELEASING.md](RELEASING.md)) | -| **CodeQL** (`codeql.yml`) | Pushes to `main` and `feature/**`, pull requests, weekly | Security scanning of the TypeScript, the Rust and the workflows | -| **Label pull requests** (`labeler.yml`) | Pull requests | Labels each pull request by its files and its title's type, for the release notes | - -A failed end-to-end run uploads its screenshots as the `e2e-failures` artifact, and every CI run -keeps the web build as `statsify-web`. +| Workflow | When | What it does | +| ------------------------------------------- | ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| **CI** (`ci.yml`) | Pull requests, pushes to `main`, by hand | Typecheck, lint, unit tests, one build, end-to-end tests with axe in four jobs side by side, `cargo fmt`, `clippy` and `cargo test` | +| **Desktop app** (`desktop.yml`) | Changes to the app reaching `main`; pull requests that change `src-tauri/`, dependencies or the build | Builds the installers on Windows, Linux and macOS and keeps them as downloadable artifacts for 14 days | +| **Release on main** (`release-on-main.yml`) | Pushes to `main` | Releases the version in `package.json` when it has no tag yet, by running **Release** on that commit | +| **Release** (`release.yml`) | Called by Release on main, version tags (`v1.2.0`); dry runs when the workflow itself changes | Checks the version, runs CI and the desktop builds, and publishes a GitHub Release ([RELEASING.md](RELEASING.md)) | +| **CodeQL** (`codeql.yml`) | Pull requests, pushes to `main`, weekly | Security scanning of the TypeScript, the Rust and the workflows | +| **Label pull requests** (`labeler.yml`) | Pull requests | Labels each pull request by its files and its title's type, for the release notes | + +Pushes to other branches start nothing: open a pull request (a draft is fine), or start **CI** by +hand from the Actions tab (Run workflow) for a branch without one. + +How **CI** is laid out, and why: + +- **Build** runs `vite build` once and uploads `dist/` as `statsify-web`. The four **End-to-end + tests** jobs download it and serve it (`E2E_PREBUILT=1`), instead of each building again. +- **Types, lint & unit tests** runs beside them, so the end-to-end jobs don't wait for it. +- `e2e/shard.ts` deals the tests out between the four jobs in turn, so they take about as long + as each other (see [End-to-end tests](#end-to-end-tests-playwright)). Each job runs two + browsers, half of a 4-core runner. A failing job uploads its screenshots as `e2e-failures-<n>`; + the other jobs still run to the end. +- **What changed** decides what a change needs. Changes to Markdown, `docs/` or `.github/` (other + than `ci.yml`) skip the end-to-end tests; changes outside `src-tauri/` skip the Rust checks. + Runs by hand and releases run everything. +- The branch rules require **Lint, test & build** and **Desktop shell (Rust)**. **Lint, test & + build** waits for the build, the checks and every end-to-end job, and passes only if each passed + or wasn't needed. A skipped job counts as passed, so these skip with a job-level `if`; a workflow + filtered with `on: paths` would leave a required check waiting for ever. +- A release runs every check (`run: all`); a pull request's release dry run only builds the web + app to package (`run: build`), since the pull request's own CI run has the checks. From 8cea2f3b55facf57e6321fff1fe318feeb31ffda Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:30:00 +0000 Subject: [PATCH 23/41] test(e2e): wake the full-screen player's controls before clicking them The controls fade after 3 s without input, and Playwright waits for an element to take the click before it moves the mouse, so a click on a faded control waits until the test times out. On a busy machine an axe scan or a screenshot takes that long: "Lyrics and Both show the cover" failed so, before and after this branch's changes. wakePlayerControls() moves the pointer first, as a person would; the glass test's view switcher uses it too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- e2e/fullscreen.spec.ts | 3 ++- e2e/helpers.ts | 12 ++++++++++++ e2e/window-states.spec.ts | 4 +++- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/e2e/fullscreen.spec.ts b/e2e/fullscreen.spec.ts index 4f1da16..a3990f4 100644 --- a/e2e/fullscreen.spec.ts +++ b/e2e/fullscreen.spec.ts @@ -1,7 +1,7 @@ import AxeBuilder from "@axe-core/playwright"; import { expect, test, type Page } from "@playwright/test"; import { mockSpotify } from "./mock-spotify"; -import { seedDemo, settleAnimations, trackErrors, WCAG_TAGS } from "./helpers"; +import { seedDemo, settleAnimations, trackErrors, wakePlayerControls, WCAG_TAGS } from "./helpers"; import { contrastBehind } from "./pixels"; const waves = (page: Page) => page.getByRole("dialog").locator("[data-renderer]"); @@ -231,6 +231,7 @@ test.describe("full-screen lyrics for a song without lyrics", () => { const switcher = dialog(page).getByRole("radiogroup", { name: "Full-screen view" }); await expect(switcher.getByRole("radio", { name: "Lyrics" })).toHaveAttribute("aria-checked", "true"); await noSeriousA11yIn(page, "no lyrics, Lyrics view"); + await wakePlayerControls(page); await switcher.getByRole("radio", { name: "Both" }).click(); await expect(page.getByRole("dialog", { name: "Full-screen player and lyrics" })).toBeVisible(); await expect(note(page)).toHaveText("Lyrics aren't available for this song."); diff --git a/e2e/helpers.ts b/e2e/helpers.ts index ca2f734..fe26230 100644 --- a/e2e/helpers.ts +++ b/e2e/helpers.ts @@ -42,6 +42,18 @@ export async function settleAnimations(page: Page): Promise<void> { ); } +/** + * Move the pointer, as a person reaching for the full-screen player's controls does. They fade + * after 3 s without input, and a click can't reach them then (Playwright waits for the element + * to take the click before it moves the mouse, so it would wait for ever). Call it before + * clicking them after a slow step: axe or a screenshot can take that long on a busy machine. + */ +export async function wakePlayerControls(page: Page): Promise<void> { + await page.mouse.move(300, 300); + await page.mouse.move(320, 320); + await expect(page.getByRole("dialog", { name: /^Full-screen/ })).toHaveAttribute("data-idle", "false"); +} + /** Wait until deferred work (anything marked aria-busy) has settled. */ export async function settled(page: Page): Promise<void> { await expect(page.locator('[aria-busy="true"]')).toHaveCount(0); diff --git a/e2e/window-states.spec.ts b/e2e/window-states.spec.ts index 130c30f..b223828 100644 --- a/e2e/window-states.spec.ts +++ b/e2e/window-states.spec.ts @@ -1,6 +1,6 @@ import { expect, test, type Page } from "@playwright/test"; import { fakeDesktop, type FakeDesktop } from "./fake-desktop"; -import { noSeriousA11y, seedDemo, trackErrors } from "./helpers"; +import { noSeriousA11y, seedDemo, trackErrors, wakePlayerControls } from "./helpers"; import { backgroundFrames, clearBackgroundFrames, paintedAlpha, recordBackground, type BackgroundFrame } from "./pixels"; /** @@ -440,6 +440,8 @@ test("the full-screen player and lyrics sit on the same glass as the app, at eve const { width, height } = page.viewportSize()!; await expect.poll(() => player(page).boundingBox()).toEqual({ x: 0, y: 0, width, height }); for (const view of ["Lyrics", "Both", "Cover"]) { + // Measuring the glass can take as long as the controls stay up. + await wakePlayerControls(page); await player(page).getByRole("radio", { name: view }).click(); await expect(player(page).getByRole("radio", { name: view })).toHaveAttribute("aria-checked", "true"); await expectGlass(page, 40, view); From 4541c6216d5b66d7dfa275a174a2ecdeb594bff0 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:33:06 +0000 Subject: [PATCH 24/41] fix(history): leave nothing of erased history in the write-ahead log "Sign out and erase data" deleted the account and ran VACUUM, but the write-ahead log kept the pages that held the erased plays for as long as the app stayed open (it stays open all day in the tray): the song names were still readable in listening-history.sqlite3-wal. Erasing now ends with a TRUNCATE checkpoint, which copies the vacuumed database into the file and empties the log. Quitting now closes the database, so SQLite folds the log into the file and removes it: a backup that copies only listening-history.sqlite3 after closing the app no longer misses the latest plays. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- AGENTS.md | 8 ++++-- docs/DATABASE.md | 11 +++++--- src-tauri/src/history.rs | 60 ++++++++++++++++++++++++++++++++++++++-- src-tauri/src/lib.rs | 9 ++++-- 4 files changed, 77 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 08f687b..d904f2c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -253,8 +253,10 @@ on desktop and never touches the SQLite database. Any new endpoint the UI uses n History left in IndexedDB by older desktop versions moves into the database on first load. - **Rust side**: one connection behind a mutex, opened lazily in the app data folder, WAL mode, every save in one transaction, inputs validated (dates, lengths, text clipped to 300 bytes), - schema migrations in a transaction, files from a newer schema refused, unused songs removed, and - all work on a blocking worker thread so the window never freezes. + schema migrations in a transaction, files from a newer schema refused untouched, unused songs + removed, and all work on a blocking worker thread so the window never freezes. Erasing compacts + the file and empties the write-ahead log, and quitting closes the database, which folds the log + into the file. - **Import** (`history/parse.ts`, `history/import.worker.ts`): Spotify's Extended streaming history, Account data and video history, from JSON or zip, parsed in a Web Worker one zip entry at a time with size caps (zip-bomb safe) and count caps (a zip's directory can claim billions of @@ -499,7 +501,7 @@ start-up. | `set_tray_tooltip` | Current song in the tray tooltip | Clipped to 120 UTF-16 units (Windows holds 128) | | `history_load` | Whole account history as a binary blob | Async, blocking worker; raw IPC response | | `history_apply` | Insert/delete plays and account metadata in one transaction | Async; validates everything | -| `history_delete` | Erase an account, drop unused songs, VACUUM | Async | +| `history_delete` | Erase an account, drop unused songs, VACUUM, empty the log | Async | | `history_info` | File path, size, play and song counts | Async | | `spotify_launch_hidden` | Start Spotify minimised; `"running"` if it already runs | Async; `Err("not_installed")` or a readable message | | `window_set_material` | Mica, Acrylic or none behind the window (or `reassert` it) | Windows only, no-op elsewhere; runs on main thread | diff --git a/docs/DATABASE.md b/docs/DATABASE.md index cb0c8ee..46bf9fc 100644 --- a/docs/DATABASE.md +++ b/docs/DATABASE.md @@ -118,9 +118,11 @@ FROM plays WHERE ms_played >= 30000 GROUP BY day ORDER BY day; ## Backups and moving PCs -Close the app, then copy `listening-history.sqlite3` (and `listening-history.sqlite3-wal` if it -exists). To restore, put the files back in the same folder before starting the app. You can also -export a CSV of any period from the Streams page, or everything from the Import page. +Close the app, then copy `listening-history.sqlite3`: as it quits, the app folds its write-ahead +log into that file. If `listening-history.sqlite3-wal` is there too (the app didn't get to quit +normally), copy it as well. To restore, put the files back in the same folder before starting the +app. You can also export a CSV of any period from the Streams page, or everything from the Import +page. ## Design notes @@ -132,6 +134,7 @@ export a CSV of any period from the Streams page, or everything from the Import opened the app stops saving rather than risk overwriting it. Only the app's own window can call the history commands; content from anywhere else is rejected. - **Erasing:** Settings → "Sign out and erase data" deletes the account's plays and any songs no - longer used, then compacts the file. + longer used, then compacts the file and empties its write-ahead log, so nothing of the erased + history is left in either file. - Code: `src-tauri/src/history.rs` (database), `app/history/sqlite.ts` (UI side), `app/history/diff.ts` (what changed between saves). diff --git a/src-tauri/src/history.rs b/src-tauri/src/history.rs index 01a8d11..64358cf 100644 --- a/src-tauri/src/history.rs +++ b/src-tauri/src/history.rs @@ -553,8 +553,11 @@ fn delete(conn: &mut Connection, owner: &str) -> Result<(), String> { .map_err(|e| e.to_string())?; drop_unused_songs(&tx)?; tx.commit().map_err(|e| e.to_string())?; - // Give the space back: erased history shouldn't linger in free pages. - conn.execute_batch("VACUUM").map_err(|e| e.to_string())?; + // Give the space back and leave nothing of the erased history in the files: VACUUM + // rewrites the database without its free pages, and the checkpoint copies that into the + // file and empties the write-ahead log, which still holds the erased plays' pages. + conn.execute_batch("VACUUM; PRAGMA wal_checkpoint(TRUNCATE);") + .map_err(|e| e.to_string())?; Ok(()) } @@ -588,6 +591,13 @@ impl HistoryDb { *self.0.path.lock().unwrap_or_else(|e| e.into_inner()) = Some(path); } + /// Close the database (the app is quitting), after any command still running. SQLite then + /// folds the write-ahead log into the file and removes it, so the file alone is the whole + /// history: a backup that copies only it misses nothing. A later command opens it again. + pub fn close(&self) { + drop(self.0.conn.lock().unwrap_or_else(|e| e.into_inner()).take()); + } + fn with<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T, String>) -> Result<T, String> { let mut guard = self.0.conn.lock().unwrap_or_else(|e| e.into_inner()); if guard.is_none() { @@ -1067,6 +1077,52 @@ mod tests { std::fs::remove_dir_all(&dir).ok(); } + /// Erasing an account leaves none of its history in the database's files, the + /// write-ahead log included, while the app keeps the database open. + #[test] + fn erasing_leaves_no_trace_in_the_files() { + let dir = std::env::temp_dir().join(format!("ss-erase-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(FILE_NAME); + let mut conn = open(&path).unwrap(); + let secret = "Erase me completely"; + let plays = (0..2_000) + .map(|i| row(T0 + i, &format!("{secret} {i}"), 0)) + .collect(); + apply(&mut conn, "me", &change(true, plays, vec![])).unwrap(); + delete(&mut conn, "me").unwrap(); + for file in [path.clone(), path.with_extension("sqlite3-wal")] { + let bytes = std::fs::read(&file).unwrap_or_default(); + assert!( + !bytes.windows(secret.len()).any(|w| w == secret.as_bytes()), + "{} still holds erased plays", + file.display() + ); + } + drop(conn); + std::fs::remove_dir_all(&dir).ok(); + } + + /// Quitting closes the database, which folds the write-ahead log into the file: a backup + /// of the file alone then has every play. + #[test] + fn closing_folds_the_log_into_the_file() { + let dir = std::env::temp_dir().join(format!("ss-close-test-{}", std::process::id())); + let db = HistoryDb::new(); + db.set_path(dir.join(FILE_NAME)); + let saved = db.with(|conn| apply(conn, "me", &change(true, vec![row(T0, "a", 0)], vec![]))); + assert_eq!(saved, Ok(1)); + let log = dir.join(FILE_NAME).with_extension("sqlite3-wal"); + assert!(log.exists()); + db.close(); + assert!(!log.exists(), "the log is still there"); + // The next command opens it again. + let (_, ts, ..) = decode(&db.with(|conn| load(conn, "me")).unwrap()); + assert_eq!(ts.len(), 1); + db.close(); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn handles_a_large_history_quickly() { let mut conn = db(); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index b93c4bc..c9d20ee 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -87,6 +87,11 @@ pub fn run() { tray::create(app.handle())?; Ok(()) }) - .run(tauri::generate_context!()) - .expect("error while running Statsify"); + .build(tauri::generate_context!()) + .expect("error while building Statsify") + .run(|app, event| { + if let tauri::RunEvent::Exit = event { + app.state::<history::HistoryDb>().close(); + } + }); } From 61de68da3e13a88cded5ea85f86404f999ed3389 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:33:54 +0000 Subject: [PATCH 25/41] fix(history): leave a newer Statsify's database untouched The schema check that refuses a file from a newer version came after the file had been switched to WAL mode, which rewrites its header and creates a log next to it: the "won't write to a file from a newer version" promise was broken before the refusal. The version is now checked first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- src-tauri/src/history.rs | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src-tauri/src/history.rs b/src-tauri/src/history.rs index 64358cf..4ab4354 100644 --- a/src-tauri/src/history.rs +++ b/src-tauri/src/history.rs @@ -116,12 +116,14 @@ fn open(path: &Path) -> Result<Connection, String> { let conn = Connection::open(path).map_err(|e| e.to_string())?; conn.busy_timeout(std::time::Duration::from_secs(5)) .map_err(|e| e.to_string())?; - // WAL: fast appends, and a crash mid-write can't corrupt earlier history. + // Before anything else: a file from a newer Statsify is refused untouched. + migrate(&conn)?; + // WAL: fast appends, and a crash mid-write can't corrupt earlier history. NORMAL is as + // safe with WAL (a power cut can lose only the last save) and syncs far less often. conn.pragma_update(None, "journal_mode", "WAL") .map_err(|e| e.to_string())?; conn.pragma_update(None, "synchronous", "NORMAL") .map_err(|e| e.to_string())?; - migrate(&conn)?; Ok(conn) } @@ -888,6 +890,30 @@ mod tests { assert_eq!(version, SCHEMA_VERSION + 1, "the file is left alone"); } + /// A file from a newer Statsify is refused before anything is written to it, its journal + /// mode included. + #[test] + fn a_newer_file_is_left_untouched() { + let dir = std::env::temp_dir().join(format!("ss-newer-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(FILE_NAME); + { + let conn = Connection::open(&path).unwrap(); + conn.execute_batch(SCHEMA).unwrap(); + conn.pragma_update(None, "user_version", SCHEMA_VERSION + 1) + .unwrap(); + } + let before = std::fs::read(&path).unwrap(); + let err = open(&path).unwrap_err(); + assert!(err.contains("newer version of Statsify"), "{err}"); + assert!( + std::fs::read(&path).unwrap() == before, + "the file was changed" + ); + assert!(!path.with_extension("sqlite3-wal").exists()); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn saves_that_remove_plays_also_remove_unused_songs() { let mut conn = db(); From de1259e4c602c729cddbf8b41c6cf323e62c4691 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:34:20 +0000 Subject: [PATCH 26/41] perf(history): index plays by song (schema 3) Removing a song makes SQLite check that no play still refers to it (the plays.song_id foreign key), and without an index on song_id that meant reading every play for each song removed. A save that drops many songs crawled: rewriting a 200,000-play history whose songs had changed (what the UI does after a failed save) took 57 s of wall time and 45 s of CPU; with the index it takes about 2.3 s and 1.9 s of CPU. The index costs about 14% more file (42.6 MB to 48.6 MB for that history). Schema 3 adds it in the usual idempotent migration step. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- docs/DATABASE.md | 8 +++-- src-tauri/src/history.rs | 66 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 68 insertions(+), 6 deletions(-) diff --git a/docs/DATABASE.md b/docs/DATABASE.md index 46bf9fc..a4f6cb3 100644 --- a/docs/DATABASE.md +++ b/docs/DATABASE.md @@ -31,7 +31,7 @@ automatically the first time an account loads. Plays are de-duplicated: the same play from two sources (or imported twice) is stored once, and a play recorded live is replaced by the more detailed exported one when you import. -## Schema (version 2) +## Schema (version 3) ```sql -- One row per Spotify account. @@ -68,13 +68,15 @@ CREATE TABLE plays ( country TEXT -- two-letter code, from exports ); CREATE INDEX plays_owner_time ON plays (owner, ended_at); +CREATE INDEX plays_song ON plays (song_id); -- added in version 3 ``` `flags` is a bit set: `1` skipped, `2` shuffle, `4` offline, `8` incognito, `16` the length is an estimate (a recorded play: Spotify doesn't say how long it played, so it is the song's length), `32` played to the end. `PRAGMA user_version` holds the schema version; newer versions of the app -upgrade older files in place, in one transaction (version 1 → 2 adds `accounts.extras`). An older -version of the app won't write to a file from a newer one: it stops saving and asks you to update. +upgrade older files in place, in one transaction (version 1 → 2 adds `accounts.extras`, 2 → 3 the +`plays_song` index, which keeps removing unused songs quick). An older version of the app won't +write to a file from a newer one: it stops saving and asks you to update. Songs that no play refers to any more (after an import replaced plays, or you erased an account) are removed, so `songs` only holds songs you have played. diff --git a/src-tauri/src/history.rs b/src-tauri/src/history.rs index 4ab4354..414d732 100644 --- a/src-tauri/src/history.rs +++ b/src-tauri/src/history.rs @@ -17,7 +17,7 @@ use std::sync::{Arc, Mutex}; pub const FILE_NAME: &str = "listening-history.sqlite3"; /// Bumped when the schema changes; `migrate` upgrades older files in place. -const SCHEMA_VERSION: i32 = 2; +const SCHEMA_VERSION: i32 = 3; /// Largest `extras` JSON accepted (a heavy podcast listener's log is well under this). const MAX_EXTRAS: usize = 16 * 1024 * 1024; /// Platform/country indexes are bytes in the UI; 255 means "unknown". @@ -60,6 +60,9 @@ CREATE TABLE IF NOT EXISTS plays ( country TEXT ); CREATE INDEX IF NOT EXISTS plays_owner_time ON plays (owner, ended_at); +-- Removing a song makes SQLite check that no play refers to it (the foreign key): without this +-- index, by reading every play (v3). +CREATE INDEX IF NOT EXISTS plays_song ON plays (song_id); "#; /// One play: [endedAt, msPlayed, name, artist, album, uri, flags, platform, country, image, durationMs]. @@ -153,7 +156,8 @@ fn migrate(conn: &Connection) -> Result<(), String> { } let step = || -> rusqlite::Result<()> { let tx = Transaction::new_unchecked(conn, TransactionBehavior::Immediate)?; - // Creates whatever is missing (everything, for a new file). + // Creates whatever is missing: everything for a new file, the `plays_song` index (v3) + // for an older one. tx.execute_batch(SCHEMA)?; // v1 -> v2: per-account extras (podcast log). if !has_column(&tx, "accounts", "extras")? { @@ -831,11 +835,29 @@ mod tests { assert!(apply(&mut conn, "me", &c).is_err()); } + /// The schema before version 3: no index of plays by song. + fn schema_v2() -> String { + let index = SCHEMA.find("-- Removing a song").unwrap(); + let v2 = &SCHEMA[..index]; + assert!(!v2.contains("plays_song")); + v2.to_string() + } + + fn has_index(conn: &Connection, name: &str) -> bool { + conn.query_row( + "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = ?1", + [name], + |r| r.get::<_, i64>(0), + ) + .unwrap() + == 1 + } + #[test] fn upgrades_a_version_1_file_in_place() { let conn = Connection::open_in_memory().unwrap(); // The v1 accounts table had no extras column. - let v1 = SCHEMA + let v1 = schema_v2() .replace("NOT NULL, -- unix ms", "NOT NULL -- unix ms") .replace("\n extras TEXT NOT NULL DEFAULT '{}' -- JSON: podcast and audiobook plays per show (v2)", ""); assert!(!v1.contains("extras")); @@ -855,6 +877,7 @@ mod tests { .pragma_query_value(None, "user_version", |r| r.get(0)) .unwrap(); assert_eq!(version, SCHEMA_VERSION); + assert!(has_index(&conn, "plays_song")); let (header, ..) = decode(&load(&conn, "me").unwrap()); assert_eq!(header["podcastMs"], 9); assert_eq!(header["extras"], serde_json::json!({})); @@ -862,6 +885,43 @@ mod tests { migrate(&conn).unwrap(); } + #[test] + fn upgrades_a_version_2_file_in_place() { + let mut conn = Connection::open_in_memory().unwrap(); + conn.execute_batch(&schema_v2()).unwrap(); + conn.pragma_update(None, "user_version", 2).unwrap(); + assert!( + !has_index(&conn, "plays_song"), + "the test starts from a v2 file" + ); + let plays = vec![row(T0, "a", 0), row(T0 + 1, "b", 0)]; + apply(&mut conn, "me", &change(true, plays, vec![])).unwrap(); + migrate(&conn).unwrap(); + let version: i32 = conn + .pragma_query_value(None, "user_version", |r| r.get(0)) + .unwrap(); + assert_eq!(version, SCHEMA_VERSION); + assert!(has_index(&conn, "plays_song")); + let (_, ts, ..) = decode(&load(&conn, "me").unwrap()); + assert_eq!(ts.len(), 2); + } + + /// Removing a song makes SQLite look for plays of it (the foreign key). Without an index + /// that read every play for each song removed: a full rewrite of a 200k-play history that + /// dropped 20k songs took most of a minute. + #[test] + fn plays_of_a_song_are_found_through_an_index() { + let conn = db(); + let plan: String = conn + .query_row( + "EXPLAIN QUERY PLAN SELECT 1 FROM plays WHERE song_id = ?1", + [1], + |r| r.get(3), + ) + .unwrap(); + assert!(plan.contains("plays_song"), "{plan}"); + } + #[test] fn finishes_an_upgrade_that_was_interrupted() { // A version 1 file that already has the extras column: an upgrade that stopped between From ecce8d263b6e22b897b6b9ae761acbec5c71eecf Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:35:51 +0000 Subject: [PATCH 27/41] perf(history): lighter saves and loads, and errors in words Saving: - Plays are read in place: names, URIs and platforms are clipped as borrowed text instead of being copied for every play (seven allocations a play), and the songs a save has met are remembered by that text. - A song's artwork and length were written again for every play that carried them, one UPDATE per play; now only when they change. - Writes take the lock up front (an immediate transaction), so a database browser writing at the same time is waited for. Loading: - Each song is read once, the first time one of its plays comes up, instead of being joined to every play; platforms and countries are matched without copying them. - The header is written straight from the tables, and the stored sources and podcast log are passed on as they are, with no JSON tree built and thrown away (the podcast log alone can be 16 MB). On a 200,000-play history of 20,000 songs (tests/history_bench.rs, CPU time with this commit and the index before it, against the original): a first save 1.65-1.91 s to 1.45-1.50 s, a load 222-234 ms to 148-150 ms with its peak heap 33.0 MB to 17.8 MB, an import replacing 5,000 plays 150-170 ms to 110-140 ms. Database errors now say what happened, in a sentence the UI shows ("The history database is in use by another program", "... file is damaged", "The disk is full"), with SQLite's words after it. Lengths beyond what the UI's column holds are treated as unknown, and erasing an account that isn't there no longer vacuums the whole file. docs/DATABASE.md documents the load format. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- docs/DATABASE.md | 36 +- src-tauri/Cargo.toml | 3 +- src-tauri/src/history.rs | 1249 ++++++++++++++++++++++++++------------ 3 files changed, 907 insertions(+), 381 deletions(-) diff --git a/docs/DATABASE.md b/docs/DATABASE.md index a4f6cb3..beda6b2 100644 --- a/docs/DATABASE.md +++ b/docs/DATABASE.md @@ -126,15 +126,41 @@ normally), copy it as well. To restore, put the files back in the same folder be app. You can also export a CSV of any period from the Streams page, or everything from the Import page. +## Load format + +The app doesn't query the file play by play: `history_load` answers with an account's whole +history as one binary blob, which the UI turns straight into typed arrays +(`decodeHistory` in `app/history/sqlite.ts`). An account with no history is an empty answer. + +| Bytes | What | +| -------- | --------------------------------------------------------------------------- | +| 4 | `SSH1` | +| 4 | The header's length in bytes | +| (length) | The JSON header, padded with spaces so the columns start on a multiple of 8 | +| 8 × n | `ended_at` of each play, as 64-bit floats | +| 4 × n | `ms_played`, unsigned 32-bit | +| 4 × n | Index into `tracks`, unsigned 32-bit | +| n | `flags` | +| n | Index into `platforms`, 255 when unknown | +| n | Index into `countries`, 255 when unknown | + +Numbers are little-endian, and plays come oldest first. The header is `{ n, tracks, artists, +albums, platforms, countries, sources, podcastMs, podcastPlays, updatedAt, extras }`: each track is +`[name, artist index, album index, uri, image, length in ms]` (the last three `null` when +unknown), `platforms` and `countries` hold at most 255 names, and `sources` and `extras` are the +account's JSON as stored. + ## Design notes - **Fast and small:** SQLite in write-ahead-log mode. The app reads an account's whole history - into compact typed arrays once (200,000 plays load in about 0.2 s as a ~4 MB binary transfer) - and every chart is computed in memory from those. Saving new plays only writes the plays that - changed, in a single transaction, so a crash can't leave a half-written history. + into compact typed arrays once (200,000 plays of 20,000 songs load in about 0.15 s as a 7 MB + binary transfer, see [Load format](#load-format)) and every chart is computed in memory from + those. Saving new plays only writes the plays that changed, in a single transaction, so a crash + can't leave a half-written history. - **Safe:** writes are validated in Rust (dates, lengths, text limits), and if the file can't be - opened the app stops saving rather than risk overwriting it. Only the app's own window can call - the history commands; content from anywhere else is rejected. + opened (damaged, in use by another program, from a newer version) the app says why and stops + saving rather than risk overwriting it. Only the app's own window can call the history + commands; content from anywhere else is rejected. - **Erasing:** Settings → "Sign out and erase data" deletes the account's plays and any songs no longer used, then compacts the file and empties its write-ahead log, so nothing of the erased history is left in either file. diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index b099970..d8972ab 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -24,7 +24,8 @@ tauri-plugin-opener = "2" tauri-plugin-single-instance = "2" tauri-plugin-window-state = "2" serde = { version = "1", features = ["derive"] } -serde_json = "1" +# raw_value: the history load passes stored JSON on without parsing it (Tauri enables it too). +serde_json = { version = "1", features = ["raw_value"] } # Listening history: SQLite compiled in, so there is nothing extra to install. rusqlite = { version = "0.43", features = ["bundled"] } diff --git a/src-tauri/src/history.rs b/src-tauri/src/history.rs index 414d732..cacaa0b 100644 --- a/src-tauri/src/history.rs +++ b/src-tauri/src/history.rs @@ -1,7 +1,8 @@ //! Listening history database: one SQLite file in the app's data folder. //! //! The desktop app keeps every play here (imported history and plays recorded while it runs). -//! The schema is documented in `docs/DATABASE.md`; the file can be opened with any SQLite tool. +//! The schema and the binary format `history_load` answers with are documented in +//! `docs/DATABASE.md`; the file can be opened with any SQLite tool. //! //! The UI holds history in memory as typed arrays for fast analytics. It loads them from here //! in one binary response, and saves by sending only the plays that changed. @@ -9,25 +10,39 @@ //! The commands run on a blocking worker thread, never the main thread: a first import of a //! few hundred thousand plays, or the VACUUM after erasing, would otherwise freeze the window. -use rusqlite::{params, Connection, OptionalExtension, Transaction, TransactionBehavior}; -use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::time::Duration; + +use rusqlite::ffi::ErrorCode; +use rusqlite::{ + params, Connection, OptionalExtension, Statement, Transaction, TransactionBehavior, +}; +use serde::{Deserialize, Serialize}; +use serde_json::value::RawValue; pub const FILE_NAME: &str = "listening-history.sqlite3"; /// Bumped when the schema changes; `migrate` upgrades older files in place. const SCHEMA_VERSION: i32 = 3; /// Largest `extras` JSON accepted (a heavy podcast listener's log is well under this). const MAX_EXTRAS: usize = 16 * 1024 * 1024; +const MAX_SOURCES: usize = 100_000; /// Platform/country indexes are bytes in the UI; 255 means "unknown". const UNKNOWN: u8 = 255; +/// Longest name, URI or URL kept, in bytes. const MAX_TEXT: usize = 300; const MAX_OWNER: usize = 128; const MAX_ROWS: usize = 5_000_000; -/// Plays must fall between 2006 and a little past now (same rule as the importer). +/// Plays must fall between 2006 and a little past now (same rule as the importer), allowing +/// for clocks that differ by up to two days. const MIN_TS: i64 = 1_136_073_600_000; +const MAX_AHEAD_MS: i64 = 2 * 86_400_000; const MAGIC: &[u8; 4] = b"SSH1"; +/// Bytes per play in `load`'s columns: f64 + u32 + u32 + three u8. +const BYTES_PER_PLAY: usize = 19; +/// How long a command waits for another program (a database browser, say) to finish writing. +const BUSY_TIMEOUT: Duration = Duration::from_secs(5); const SCHEMA: &str = r#" CREATE TABLE IF NOT EXISTS accounts ( @@ -65,9 +80,10 @@ CREATE INDEX IF NOT EXISTS plays_owner_time ON plays (owner, ended_at); CREATE INDEX IF NOT EXISTS plays_song ON plays (song_id); "#; -/// One play: [endedAt, msPlayed, name, artist, album, uri, flags, platform, country, image, durationMs]. -#[derive(Debug, Deserialize)] -struct Row( +/// One play as the UI sends it (`PlayRow` in `app/history/diff.ts`): [endedAt, msPlayed, name, +/// artist, album, uri, flags, platform, country, image, durationMs]. +#[derive(Debug, Clone, Deserialize)] +struct Play( f64, f64, String, @@ -81,6 +97,79 @@ struct Row( #[serde(default)] Option<f64>, ); +/// A song's identity, as the `songs_identity` index has it: (uri, name, artist, album). +type SongKey<'a> = (&'a str, &'a str, &'a str, &'a str); + +/// `s` cut to MAX_TEXT bytes, between characters. +fn clip(s: &str) -> &str { + if s.len() <= MAX_TEXT { + return s; + } + let mut end = MAX_TEXT; + while !s.is_char_boundary(end) { + end -= 1; + } + &s[..end] +} + +/// Optional text, clipped; empty counts as missing. +fn clip_opt(s: &Option<String>) -> Option<&str> { + s.as_deref().filter(|v| !v.is_empty()).map(clip) +} + +impl Play { + fn ended_at(&self) -> i64 { + self.0 as i64 + } + + fn ms_played(&self) -> i64 { + self.1 as i64 + } + + fn song(&self) -> SongKey<'_> { + ( + clip_opt(&self.5).unwrap_or(""), + clip(&self.2), + clip(&self.3), + clip(&self.4), + ) + } + + fn flags(&self) -> u8 { + self.6 + } + + fn platform(&self) -> Option<&str> { + clip_opt(&self.7) + } + + fn country(&self) -> Option<&str> { + clip_opt(&self.8) + } + + fn image(&self) -> Option<&str> { + clip_opt(&self.9) + } + + /// The song's length, when it is a plausible one. + fn duration(&self) -> Option<i64> { + self.10 + .filter(|d| d.is_finite() && *d > 0.0 && *d <= u32::MAX as f64) + .map(|d| d as i64) + } + + /// `latest`: the latest plausible end time (a little past now, for clock differences). + fn check(&self, latest: f64) -> Result<(), String> { + if !self.0.is_finite() || self.0 < MIN_TS as f64 || self.0 > latest { + return Err("A play has an impossible date.".into()); + } + if !self.1.is_finite() || self.1 < 0.0 || self.1 > u32::MAX as f64 { + return Err("A play has an impossible length.".into()); + } + Ok(()) + } +} + #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct Meta { @@ -100,8 +189,8 @@ struct Meta { pub struct Change { /// Replace all of this account's plays (first save, or a save without a known previous state). replace: bool, - insert: Vec<Row>, - delete: Vec<Row>, + insert: Vec<Play>, + delete: Vec<Play>, meta: Meta, } @@ -115,18 +204,37 @@ pub struct Info { songs: u64, } +/// A database error as a sentence the UI can show (it ends up in "Listening history can't be +/// saved right now: ..."), with SQLite's own words for the developer log. +fn db_error(err: rusqlite::Error) -> String { + let what = match err.sqlite_error_code() { + Some(ErrorCode::DatabaseBusy | ErrorCode::DatabaseLocked) => { + "The history database is in use by another program" + } + Some(ErrorCode::DatabaseCorrupt | ErrorCode::NotADatabase) => { + "The history database file is damaged" + } + Some(ErrorCode::DiskFull) => "The disk is full", + Some(ErrorCode::ReadOnly | ErrorCode::PermissionDenied) => { + "The history database file can't be written to" + } + Some(ErrorCode::CannotOpen) => "The history database file can't be opened", + _ => "The history database failed", + }; + format!("{what} ({err}).") +} + fn open(path: &Path) -> Result<Connection, String> { - let conn = Connection::open(path).map_err(|e| e.to_string())?; - conn.busy_timeout(std::time::Duration::from_secs(5)) - .map_err(|e| e.to_string())?; + let conn = Connection::open(path).map_err(db_error)?; + conn.busy_timeout(BUSY_TIMEOUT).map_err(db_error)?; // Before anything else: a file from a newer Statsify is refused untouched. migrate(&conn)?; // WAL: fast appends, and a crash mid-write can't corrupt earlier history. NORMAL is as // safe with WAL (a power cut can lose only the last save) and syncs far less often. conn.pragma_update(None, "journal_mode", "WAL") - .map_err(|e| e.to_string())?; + .map_err(db_error)?; conn.pragma_update(None, "synchronous", "NORMAL") - .map_err(|e| e.to_string())?; + .map_err(db_error)?; Ok(conn) } @@ -140,10 +248,10 @@ fn has_column(conn: &Connection, table: &str, column: &str) -> rusqlite::Result< /// version intact; each step is also safe to repeat. fn migrate(conn: &Connection) -> Result<(), String> { conn.pragma_update(None, "foreign_keys", "ON") - .map_err(|e| e.to_string())?; + .map_err(db_error)?; let version: i32 = conn .pragma_query_value(None, "user_version", |r| r.get(0)) - .map_err(|e| e.to_string())?; + .map_err(db_error)?; if version > SCHEMA_VERSION { // Written by a newer Statsify: writing to a schema this version doesn't know could // damage it, so the UI is told and stops saving instead. @@ -166,22 +274,7 @@ fn migrate(conn: &Connection) -> Result<(), String> { tx.pragma_update(None, "user_version", SCHEMA_VERSION)?; tx.commit() }; - step().map_err(|e| e.to_string()) -} - -fn text(s: &str) -> String { - if s.len() <= MAX_TEXT { - return s.to_string(); - } - let mut end = MAX_TEXT; - while !s.is_char_boundary(end) { - end -= 1; - } - s[..end].to_string() -} - -fn opt_text(s: &Option<String>) -> Option<String> { - s.as_deref().filter(|v| !v.is_empty()).map(text) + step().map_err(db_error) } fn check_owner(owner: &str) -> Result<(), String> { @@ -191,17 +284,6 @@ fn check_owner(owner: &str) -> Result<(), String> { Ok(()) } -/// `max_ts`: the latest plausible end time (a little past now, for clock differences). -fn check_row(row: &Row, max_ts: f64) -> Result<(), String> { - if !row.0.is_finite() || row.0 < MIN_TS as f64 || row.0 > max_ts { - return Err("A play has an impossible date.".into()); - } - if !row.1.is_finite() || row.1 < 0.0 || row.1 > u32::MAX as f64 { - return Err("A play has an impossible length.".into()); - } - Ok(()) -} - /// Unix time in milliseconds. fn now_ms() -> i64 { std::time::SystemTime::now() @@ -210,83 +292,181 @@ fn now_ms() -> i64 { .unwrap_or(0) } -struct SongCache<'a> { - tx: &'a Transaction<'a>, - ids: HashMap<(String, String, String, String), i64>, +/// A song one save has looked up or written, and the artwork and length the save last wrote +/// to it. +struct KnownSong<'a> { + id: i64, + image: Option<&'a str>, + duration: Option<i64>, } -impl SongCache<'_> { - fn key(row: &Row) -> (String, String, String, String) { - ( - opt_text(&row.5).unwrap_or_default(), - text(&row.2), - text(&row.3), - text(&row.4), - ) +/// Song ids for one save. Most plays in a save are of songs it has met already, so those are +/// answered from memory, keyed by text borrowed from the save itself. +struct Songs<'c, 'a> { + find: Statement<'c>, + insert: Statement<'c>, + fill_in: Statement<'c>, + known: HashMap<SongKey<'a>, KnownSong<'a>>, +} + +impl<'c, 'a> Songs<'c, 'a> { + fn new(tx: &'c Transaction) -> rusqlite::Result<Self> { + Ok(Self { + find: tx.prepare( + "SELECT id FROM songs WHERE uri = ?1 AND name = ?2 AND artist = ?3 AND album = ?4", + )?, + insert: tx.prepare( + "INSERT INTO songs (uri, name, artist, album, image, duration_ms) VALUES (?1, ?2, ?3, ?4, ?5, ?6) + ON CONFLICT (uri, name, artist, album) DO UPDATE SET + image = COALESCE(excluded.image, songs.image), + duration_ms = COALESCE(excluded.duration_ms, songs.duration_ms) + RETURNING id", + )?, + fill_in: tx.prepare( + "UPDATE songs SET image = COALESCE(?2, image), duration_ms = COALESCE(?3, duration_ms) WHERE id = ?1", + )?, + known: HashMap::new(), + }) } - /// Existing song id, without creating one. - fn find(&mut self, row: &Row) -> rusqlite::Result<Option<i64>> { - let key = Self::key(row); - if let Some(id) = self.ids.get(&key) { - return Ok(Some(*id)); + /// The id of the song `play` is of, if it is stored. + fn find(&mut self, play: &'a Play) -> rusqlite::Result<Option<i64>> { + let key = play.song(); + if let Some(song) = self.known.get(&key) { + return Ok(Some(song.id)); } + let (uri, name, artist, album) = key; let id = self - .tx - .prepare_cached( - "SELECT id FROM songs WHERE uri = ?1 AND name = ?2 AND artist = ?3 AND album = ?4", - )? - .query_row(params![key.0, key.1, key.2, key.3], |r| r.get(0)) + .find + .query_row(params![uri, name, artist, album], |r| r.get(0)) .optional()?; if let Some(id) = id { - self.ids.insert(key, id); + let song = KnownSong { + id, + image: None, + duration: None, + }; + self.known.insert(key, song); } Ok(id) } - /// Song id, creating the song (or filling in its artwork/length) as needed. - fn upsert(&mut self, row: &Row) -> rusqlite::Result<i64> { - let key = Self::key(row); - let image = opt_text(&row.9); - let duration = row - .10 - .filter(|d| d.is_finite() && *d > 0.0) - .map(|d| d as i64); - if let Some(id) = self.ids.get(&key) { - if image.is_some() || duration.is_some() { - self.tx - .prepare_cached("UPDATE songs SET image = COALESCE(?2, image), duration_ms = COALESCE(?3, duration_ms) WHERE id = ?1")? - .execute(params![id, image, duration])?; + /// The id of the song `play` is of, storing the song or filling in its artwork and length. + fn upsert(&mut self, play: &'a Play) -> rusqlite::Result<i64> { + let key = play.song(); + let (image, duration) = (play.image(), play.duration()); + if let Some(song) = self.known.get_mut(&key) { + // Plays of one song carry the same artwork and length: write only what is new. + let new_image = image.is_some() && image != song.image; + let new_duration = duration.is_some() && duration != song.duration; + if new_image || new_duration { + self.fill_in.execute(params![song.id, image, duration])?; + song.image = image.or(song.image); + song.duration = duration.or(song.duration); } - return Ok(*id); + return Ok(song.id); } + let (uri, name, artist, album) = key; let id = self - .tx - .prepare_cached( - "INSERT INTO songs (uri, name, artist, album, image, duration_ms) VALUES (?1, ?2, ?3, ?4, ?5, ?6) - ON CONFLICT (uri, name, artist, album) DO UPDATE SET - image = COALESCE(excluded.image, songs.image), - duration_ms = COALESCE(excluded.duration_ms, songs.duration_ms) - RETURNING id", - )? - .query_row(params![key.0, key.1, key.2, key.3, image, duration], |r| r.get(0))?; - self.ids.insert(key, id); + .insert + .query_row(params![uri, name, artist, album, image, duration], |r| { + r.get(0) + })?; + let song = KnownSong { + id, + image, + duration, + }; + self.known.insert(key, song); Ok(id) } } +/// Write a checked change set; returns the account's play count. +fn write( + tx: &Transaction, + owner: &str, + change: &Change, + sources: &str, + extras: Option<&str>, +) -> rusqlite::Result<u64> { + let meta = &change.meta; + tx.execute( + "INSERT INTO accounts (owner, sources, podcast_ms, podcast_plays, updated_at, extras) VALUES (?1, ?2, ?3, ?4, ?5, COALESCE(?6, '{}')) + ON CONFLICT (owner) DO UPDATE SET sources = excluded.sources, podcast_ms = excluded.podcast_ms, + podcast_plays = excluded.podcast_plays, updated_at = excluded.updated_at, + extras = COALESCE(?6, accounts.extras)", + params![ + owner, + sources, + meta.podcast_ms.max(0.0) as i64, + meta.podcast_plays.max(0.0) as i64, + meta.updated_at as i64, + extras + ], + )?; + if change.replace { + tx.execute("DELETE FROM plays WHERE owner = ?1", [owner])?; + } + let mut songs = Songs::new(tx)?; + if !change.replace && !change.delete.is_empty() { + // One play each, even when the account holds several identical ones. + let mut delete = tx.prepare( + "DELETE FROM plays WHERE id = (SELECT id FROM plays WHERE owner = ?1 AND ended_at = ?2 + AND ms_played = ?3 AND song_id = ?4 AND flags = ?5 AND platform IS ?6 AND country IS ?7 LIMIT 1)", + )?; + for play in &change.delete { + if let Some(song) = songs.find(play)? { + delete.execute(params![ + owner, + play.ended_at(), + play.ms_played(), + song, + play.flags(), + play.platform(), + play.country() + ])?; + } + } + } + let mut insert = tx.prepare( + "INSERT INTO plays (owner, ended_at, ms_played, song_id, flags, platform, country) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + )?; + for play in &change.insert { + let song = songs.upsert(play)?; + insert.execute(params![ + owner, + play.ended_at(), + play.ms_played(), + song, + play.flags(), + play.platform(), + play.country() + ])?; + } + if change.replace || !change.delete.is_empty() { + drop_unused_songs(tx)?; + } + let plays: i64 = tx.query_row( + "SELECT COUNT(*) FROM plays WHERE owner = ?1", + [owner], + |r| r.get(0), + )?; + Ok(plays as u64) +} + /// Apply a change set in one transaction: all of it lands, or none of it. fn apply(conn: &mut Connection, owner: &str, change: &Change) -> Result<u64, String> { check_owner(owner)?; if change.insert.len() + change.delete.len() > MAX_ROWS { return Err("Too many plays in one save.".into()); } - let max_ts = (now_ms() + 2 * 86_400_000) as f64; - for row in change.insert.iter() { - check_row(row, max_ts)?; + let latest = (now_ms() + MAX_AHEAD_MS) as f64; + for play in &change.insert { + play.check(latest)?; } let sources = serde_json::to_string(&change.meta.sources).map_err(|e| e.to_string())?; - if sources.len() > 100_000 { + if sources.len() > MAX_SOURCES { return Err("Source list is too large.".into()); } let extras = match &change.meta.extras { @@ -297,284 +477,284 @@ fn apply(conn: &mut Connection, owner: &str, change: &Change) -> Result<u64, Str if extras.as_ref().is_some_and(|e| e.len() > MAX_EXTRAS) { return Err("Podcast history is too large.".into()); } - let tx = conn.transaction().map_err(|e| e.to_string())?; - tx.execute( - "INSERT INTO accounts (owner, sources, podcast_ms, podcast_plays, updated_at, extras) VALUES (?1, ?2, ?3, ?4, ?5, COALESCE(?6, '{}')) - ON CONFLICT (owner) DO UPDATE SET sources = excluded.sources, podcast_ms = excluded.podcast_ms, - podcast_plays = excluded.podcast_plays, updated_at = excluded.updated_at, - extras = COALESCE(?6, accounts.extras)", - params![ - owner, - sources, - change.meta.podcast_ms.max(0.0) as i64, - change.meta.podcast_plays.max(0.0) as i64, - change.meta.updated_at as i64, - extras - ], - ) - .map_err(|e| e.to_string())?; - if change.replace { - tx.execute("DELETE FROM plays WHERE owner = ?1", params![owner]) - .map_err(|e| e.to_string())?; + // Immediate: take the write lock now, waiting for another program to finish writing. + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .map_err(db_error)?; + let plays = write(&tx, owner, change, &sources, extras.as_deref()).map_err(db_error)?; + tx.commit().map_err(db_error)?; + Ok(plays) +} + +/// Names and their indexes in a `load` header, in order of first use. +#[derive(Default)] +struct Table { + names: Vec<String>, + index: HashMap<String, u32>, +} + +impl Table { + fn intern(&mut self, name: &str) -> u32 { + if let Some(&i) = self.index.get(name) { + return i; + } + let i = self.names.len() as u32; + self.index.insert(name.to_owned(), i); + self.names.push(name.to_owned()); + i } - { - let mut songs = SongCache { - tx: &tx, - ids: HashMap::new(), - }; - let mut delete = tx - .prepare_cached( - "DELETE FROM plays WHERE id = (SELECT id FROM plays WHERE owner = ?1 AND ended_at = ?2 AND ms_played = ?3 - AND song_id = ?4 AND flags = ?5 AND platform IS ?6 AND country IS ?7 LIMIT 1)", - ) - .map_err(|e| e.to_string())?; - if !change.replace { - for row in change.delete.iter() { - if let Some(song) = songs.find(row).map_err(|e| e.to_string())? { - delete - .execute(params![ - owner, - row.0 as i64, - row.1 as i64, - song, - row.6, - opt_text(&row.7), - opt_text(&row.8) - ]) - .map_err(|e| e.to_string())?; - } + + /// For the tables the UI indexes with a byte: UNKNOWN for no name, or no room for another. + fn intern_byte(&mut self, name: Option<&str>) -> u8 { + match name { + Some(name) if self.names.len() < UNKNOWN as usize || self.index.contains_key(name) => { + self.intern(name) as u8 } - } - let mut insert = tx - .prepare_cached( - "INSERT INTO plays (owner, ended_at, ms_played, song_id, flags, platform, country) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", - ) - .map_err(|e| e.to_string())?; - for row in change.insert.iter() { - let song = songs.upsert(row).map_err(|e| e.to_string())?; - insert - .execute(params![ - owner, - row.0 as i64, - row.1 as i64, - song, - row.6, - opt_text(&row.7), - opt_text(&row.8) - ]) - .map_err(|e| e.to_string())?; + _ => UNKNOWN, } } - if change.replace || !change.delete.is_empty() { - drop_unused_songs(&tx)?; - } - let plays: u64 = tx - .query_row( - "SELECT COUNT(*) FROM plays WHERE owner = ?1", - params![owner], - |r| r.get::<_, i64>(0), - ) - .map_err(|e| e.to_string())? as u64; - tx.commit().map_err(|e| e.to_string())?; - Ok(plays) } -fn intern(map: &mut HashMap<String, u32>, list: &mut Vec<String>, value: String) -> u32 { - if let Some(i) = map.get(&value) { - return *i; +/// A song in a `load` header: [name, artist index, album index, uri, image, duration]. +#[derive(Serialize)] +struct Track( + String, + u32, + u32, + Option<String>, + Option<String>, + Option<i64>, +); + +/// The JSON header of `load`'s answer. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct Header<'a> { + n: usize, + tracks: &'a [Track], + artists: &'a [String], + albums: &'a [String], + platforms: &'a [String], + countries: &'a [String], + sources: &'a RawValue, + podcast_ms: i64, + podcast_plays: i64, + updated_at: i64, + extras: &'a RawValue, +} + +/// JSON stored in the database, passed on as it is; `fallback` if it isn't valid JSON (the +/// file is the user's to edit). +fn stored_json<'a>(text: &'a str, fallback: &'static str) -> &'a RawValue { + serde_json::from_str(text) + .or_else(|_| serde_json::from_str(fallback)) + .expect("the fallback is valid JSON") +} + +struct Account { + sources: String, + podcast_ms: i64, + podcast_plays: i64, + updated_at: i64, + extras: String, +} + +/// An account's plays, as `load` sends them: columns, and the tables they index into. +#[derive(Default)] +struct Columns { + ts: Vec<f64>, + ms: Vec<u32>, + track: Vec<u32>, + flags: Vec<u8>, + platform: Vec<u8>, + country: Vec<u8>, + tracks: Vec<Track>, + artists: Table, + albums: Table, + platforms: Table, + countries: Table, +} + +/// Text from a column, borrowed from SQLite. +fn text<'r>(row: &'r rusqlite::Row, i: usize) -> rusqlite::Result<&'r str> { + Ok(row.get_ref(i)?.as_str()?) +} + +/// Text or NULL from a column, borrowed from SQLite. +fn text_or_null<'r>(row: &'r rusqlite::Row, i: usize) -> rusqlite::Result<Option<&'r str>> { + Ok(row.get_ref(i)?.as_str_or_null()?) +} + +/// Read an account's plays, oldest first. +fn read_plays(conn: &Connection, owner: &str) -> rusqlite::Result<Columns> { + let n: i64 = conn.query_row( + "SELECT COUNT(*) FROM plays WHERE owner = ?1", + [owner], + |r| r.get(0), + )?; + let n = n as usize; + let mut c = Columns { + ts: Vec::with_capacity(n), + ms: Vec::with_capacity(n), + track: Vec::with_capacity(n), + flags: Vec::with_capacity(n), + platform: Vec::with_capacity(n), + country: Vec::with_capacity(n), + ..Columns::default() + }; + // Each song is read once, the first time a play of it comes up, rather than joined to + // every play. + let mut track_of_song: HashMap<i64, u32> = HashMap::new(); + let mut song = conn + .prepare("SELECT name, artist, album, uri, image, duration_ms FROM songs WHERE id = ?1")?; + let mut plays = conn.prepare( + "SELECT ended_at, ms_played, song_id, flags, platform, country + FROM plays WHERE owner = ?1 ORDER BY ended_at, id", + )?; + let mut rows = plays.query([owner])?; + while let Some(r) = rows.next()? { + let song_id: i64 = r.get(2)?; + let track = match track_of_song.get(&song_id) { + Some(&t) => t, + None => { + let found = song + .query_row([song_id], |s| { + let uri: String = s.get(3)?; + Ok(Track( + s.get(0)?, + c.artists.intern(text(s, 1)?), + c.albums.intern(text(s, 2)?), + (!uri.is_empty()).then_some(uri), + s.get(4)?, + s.get(5)?, + )) + }) + .optional()?; + // A play of a song that isn't there (the file was edited by hand) is left out. + let Some(found) = found else { continue }; + let t = c.tracks.len() as u32; + c.tracks.push(found); + track_of_song.insert(song_id, t); + t + } + }; + c.ts.push(r.get::<_, i64>(0)? as f64); + c.ms.push(r.get::<_, i64>(1)?.clamp(0, u32::MAX as i64) as u32); + c.track.push(track); + c.flags.push(r.get::<_, i64>(3)?.clamp(0, 255) as u8); + c.platform + .push(c.platforms.intern_byte(text_or_null(r, 4)?)); + c.country.push(c.countries.intern_byte(text_or_null(r, 5)?)); } - let i = list.len() as u32; - map.insert(value.clone(), i); - list.push(value); - i + Ok(c) } -fn intern_byte(map: &mut HashMap<String, u8>, list: &mut Vec<String>, value: Option<String>) -> u8 { - let Some(value) = value else { return UNKNOWN }; - if let Some(i) = map.get(&value) { - return *i; +/// Lay out `load`'s answer (see `load`). +fn encode(account: &Account, c: &Columns) -> Result<Vec<u8>, String> { + let n = c.ts.len(); + let header = Header { + n, + tracks: &c.tracks, + artists: &c.artists.names, + albums: &c.albums.names, + platforms: &c.platforms.names, + countries: &c.countries.names, + sources: stored_json(&account.sources, "[]"), + podcast_ms: account.podcast_ms, + podcast_plays: account.podcast_plays, + updated_at: account.updated_at, + extras: stored_json(&account.extras, "{}"), + }; + let mut out = Vec::new(); + out.extend_from_slice(MAGIC); + out.extend_from_slice(&[0; 4]); + serde_json::to_writer(&mut out, &header).map_err(|e| e.to_string())?; + // Spaces after the JSON, so the columns start 8-byte aligned for the UI's typed arrays. + out.resize(out.len().next_multiple_of(8), b' '); + let header_len = u32::try_from(out.len() - 8).map_err(|_| "This history is too large.")?; + out[4..8].copy_from_slice(&header_len.to_le_bytes()); + out.reserve_exact(n * BYTES_PER_PLAY); + for v in &c.ts { + out.extend_from_slice(&v.to_le_bytes()); } - if list.len() >= UNKNOWN as usize { - return UNKNOWN; + for v in c.ms.iter().chain(&c.track) { + out.extend_from_slice(&v.to_le_bytes()); } - let i = list.len() as u8; - map.insert(value.clone(), i); - list.push(value); - i + out.extend_from_slice(&c.flags); + out.extend_from_slice(&c.platform); + out.extend_from_slice(&c.country); + Ok(out) } /// An account's history as one binary blob for the UI, or an empty blob when there is none. /// -/// Layout: "SSH1", u32 header length (LE), JSON header, padding to 8 bytes, then the columns: -/// f64 ended_at[n], u32 ms_played[n], u32 track[n], u8 flags[n], u8 platform[n], u8 country[n]. +/// Layout (also in docs/DATABASE.md): "SSH1", the header's length as a u32, the JSON header +/// padded with spaces to a multiple of 8 bytes, then the columns, `n` values each: f64 +/// ended_at, u32 ms_played, u32 track, u8 flags, u8 platform, u8 country. Numbers are +/// little-endian. fn load(conn: &Connection, owner: &str) -> Result<Vec<u8>, String> { check_owner(owner)?; let account = conn .query_row( "SELECT sources, podcast_ms, podcast_plays, updated_at, extras FROM accounts WHERE owner = ?1", - params![owner], + [owner], |r| { - Ok(( - r.get::<_, String>(0)?, - r.get::<_, i64>(1)?, - r.get::<_, i64>(2)?, - r.get::<_, i64>(3)?, - r.get::<_, String>(4)?, - )) + Ok(Account { + sources: r.get(0)?, + podcast_ms: r.get(1)?, + podcast_plays: r.get(2)?, + updated_at: r.get(3)?, + extras: r.get(4)?, + }) }, ) .optional() - .map_err(|e| e.to_string())?; - let Some((sources, podcast_ms, podcast_plays, updated_at, extras)) = account else { + .map_err(db_error)?; + let Some(account) = account else { return Ok(Vec::new()); }; - - let mut ts: Vec<f64> = Vec::new(); - let mut ms: Vec<u32> = Vec::new(); - let mut track: Vec<u32> = Vec::new(); - let mut flags: Vec<u8> = Vec::new(); - let mut platform: Vec<u8> = Vec::new(); - let mut country: Vec<u8> = Vec::new(); - let mut tracks: Vec<serde_json::Value> = Vec::new(); - let mut track_of_song: HashMap<i64, u32> = HashMap::new(); - let (mut artists, mut artist_map) = (Vec::new(), HashMap::new()); - let (mut albums, mut album_map) = (Vec::new(), HashMap::new()); - let (mut platforms, mut platform_map) = (Vec::new(), HashMap::new()); - let (mut countries, mut country_map) = (Vec::new(), HashMap::new()); - - let mut stmt = conn - .prepare( - "SELECT p.ended_at, p.ms_played, p.song_id, p.flags, p.platform, p.country, - s.name, s.artist, s.album, s.uri, s.image, s.duration_ms - FROM plays p JOIN songs s ON s.id = p.song_id - WHERE p.owner = ?1 ORDER BY p.ended_at, p.id", - ) - .map_err(|e| e.to_string())?; - let mut rows = stmt.query(params![owner]).map_err(|e| e.to_string())?; - while let Some(r) = rows.next().map_err(|e| e.to_string())? { - let song: i64 = r.get(2).map_err(|e| e.to_string())?; - let t = match track_of_song.get(&song) { - Some(t) => *t, - None => { - let artist = intern( - &mut artist_map, - &mut artists, - r.get(7).map_err(|e| e.to_string())?, - ); - let album = intern( - &mut album_map, - &mut albums, - r.get(8).map_err(|e| e.to_string())?, - ); - let uri: String = r.get(9).map_err(|e| e.to_string())?; - let image: Option<String> = r.get(10).map_err(|e| e.to_string())?; - let duration: Option<i64> = r.get(11).map_err(|e| e.to_string())?; - let name: String = r.get(6).map_err(|e| e.to_string())?; - let t = tracks.len() as u32; - tracks.push(serde_json::json!([ - name, - artist, - album, - if uri.is_empty() { None } else { Some(uri) }, - image, - duration - ])); - track_of_song.insert(song, t); - t - } - }; - ts.push(r.get::<_, i64>(0).map_err(|e| e.to_string())? as f64); - ms.push( - r.get::<_, i64>(1) - .map_err(|e| e.to_string())? - .clamp(0, u32::MAX as i64) as u32, - ); - track.push(t); - flags.push(r.get::<_, i64>(3).map_err(|e| e.to_string())?.clamp(0, 255) as u8); - platform.push(intern_byte( - &mut platform_map, - &mut platforms, - r.get(4).map_err(|e| e.to_string())?, - )); - country.push(intern_byte( - &mut country_map, - &mut countries, - r.get(5).map_err(|e| e.to_string())?, - )); - } - - let header = serde_json::json!({ - "n": ts.len(), - "tracks": tracks, - "artists": artists, - "albums": albums, - "platforms": platforms, - "countries": countries, - "sources": serde_json::from_str::<serde_json::Value>(&sources).unwrap_or(serde_json::json!([])), - "podcastMs": podcast_ms, - "podcastPlays": podcast_plays, - "updatedAt": updated_at, - "extras": serde_json::from_str::<serde_json::Value>(&extras).unwrap_or(serde_json::json!({})), - }); - let mut header = serde_json::to_vec(&header).map_err(|e| e.to_string())?; - while (8 + header.len()) % 8 != 0 { - header.push(b' '); - } - let n = ts.len(); - let mut out = Vec::with_capacity(8 + header.len() + n * 19); - out.extend_from_slice(MAGIC); - out.extend_from_slice(&(header.len() as u32).to_le_bytes()); - out.extend_from_slice(&header); - for v in &ts { - out.extend_from_slice(&v.to_le_bytes()); - } - for v in &ms { - out.extend_from_slice(&v.to_le_bytes()); - } - for v in &track { - out.extend_from_slice(&v.to_le_bytes()); - } - out.extend_from_slice(&flags); - out.extend_from_slice(&platform); - out.extend_from_slice(&country); - Ok(out) + let columns = read_plays(conn, owner).map_err(db_error)?; + encode(&account, &columns) } /// Remove songs no play refers to any more (the schema promises every song has a play). -fn drop_unused_songs(tx: &Transaction) -> Result<(), String> { +fn drop_unused_songs(tx: &Transaction) -> rusqlite::Result<()> { tx.execute( - "DELETE FROM songs WHERE id NOT IN (SELECT DISTINCT song_id FROM plays)", + "DELETE FROM songs WHERE id NOT IN (SELECT song_id FROM plays)", [], - ) - .map(|_| ()) - .map_err(|e| e.to_string()) + )?; + Ok(()) +} + +/// Remove an account and its plays; whether there was anything to remove. +fn erase(conn: &mut Connection, owner: &str) -> rusqlite::Result<bool> { + let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; + let plays = tx.execute("DELETE FROM plays WHERE owner = ?1", [owner])?; + let accounts = tx.execute("DELETE FROM accounts WHERE owner = ?1", [owner])?; + drop_unused_songs(&tx)?; + tx.commit()?; + Ok(plays + accounts > 0) } fn delete(conn: &mut Connection, owner: &str) -> Result<(), String> { check_owner(owner)?; - let tx = conn.transaction().map_err(|e| e.to_string())?; - tx.execute("DELETE FROM plays WHERE owner = ?1", params![owner]) - .map_err(|e| e.to_string())?; - tx.execute("DELETE FROM accounts WHERE owner = ?1", params![owner]) - .map_err(|e| e.to_string())?; - drop_unused_songs(&tx)?; - tx.commit().map_err(|e| e.to_string())?; + if !erase(conn, owner).map_err(db_error)? { + return Ok(()); + } // Give the space back and leave nothing of the erased history in the files: VACUUM // rewrites the database without its free pages, and the checkpoint copies that into the // file and empties the write-ahead log, which still holds the erased plays' pages. conn.execute_batch("VACUUM; PRAGMA wal_checkpoint(TRUNCATE);") - .map_err(|e| e.to_string())?; - Ok(()) + .map_err(db_error) } -fn counts(conn: &Connection) -> Result<(u64, u64), String> { - let plays = conn - .query_row("SELECT COUNT(*) FROM plays", [], |r| r.get::<_, i64>(0)) - .map_err(|e| e.to_string())?; - let songs = conn - .query_row("SELECT COUNT(*) FROM songs", [], |r| r.get::<_, i64>(0)) - .map_err(|e| e.to_string())?; - Ok((plays as u64, songs as u64)) +fn counts(conn: &Connection) -> rusqlite::Result<(u64, u64)> { + let count = |table: &str| { + conn.query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |r| { + r.get::<_, i64>(0) + }) + }; + Ok((count("plays")? as u64, count("songs")? as u64)) } #[derive(Default)] @@ -583,6 +763,12 @@ struct DbState { conn: Mutex<Option<Connection>>, } +/// What these locks guard is whole at every step (the connection rolls back a transaction +/// that didn't finish), so a panic elsewhere while one was held is no reason to stop. +fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + /// The open database, created on first use in the app's data folder. Cheap to clone (a shared /// handle), so a command can hand it to a worker thread. #[derive(Clone, Default)] @@ -594,36 +780,36 @@ impl HistoryDb { } pub fn set_path(&self, path: PathBuf) { - *self.0.path.lock().unwrap_or_else(|e| e.into_inner()) = Some(path); + *lock(&self.0.path) = Some(path); } /// Close the database (the app is quitting), after any command still running. SQLite then /// folds the write-ahead log into the file and removes it, so the file alone is the whole /// history: a backup that copies only it misses nothing. A later command opens it again. pub fn close(&self) { - drop(self.0.conn.lock().unwrap_or_else(|e| e.into_inner()).take()); + drop(lock(&self.0.conn).take()); } + /// Run `f` with the connection, opening the database first if it isn't open yet (if that + /// fails, the next call tries again). One call at a time. fn with<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T, String>) -> Result<T, String> { - let mut guard = self.0.conn.lock().unwrap_or_else(|e| e.into_inner()); - if guard.is_none() { - let path = self.file().ok_or("History storage isn't ready.")?; - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir) - .map_err(|e| format!("Couldn't create the history folder: {e}"))?; + let mut guard = lock(&self.0.conn); + let conn = match &mut *guard { + Some(conn) => conn, + empty => { + let path = self.file().ok_or("History storage isn't ready.")?; + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir) + .map_err(|e| format!("Couldn't create the history folder: {e}"))?; + } + empty.insert(open(&path)?) } - *guard = - Some(open(&path).map_err(|e| format!("Couldn't open the history database: {e}"))?); - } - f(guard.as_mut().expect("connection was just opened")) + }; + f(conn) } fn file(&self) -> Option<PathBuf> { - self.0 - .path - .lock() - .unwrap_or_else(|e| e.into_inner()) - .clone() + lock(&self.0.path).clone() } /// Run `f` on a blocking worker thread with the open connection. @@ -666,7 +852,7 @@ pub async fn history_delete(db: tauri::State<'_, HistoryDb>, owner: String) -> R pub async fn history_info(db: tauri::State<'_, HistoryDb>) -> Result<Info, String> { let path = db.file().unwrap_or_default(); db.run(move |conn| { - let (plays, songs) = counts(conn)?; + let (plays, songs) = counts(conn).map_err(db_error)?; let bytes = [path.clone(), path.with_extension("sqlite3-wal")] .iter() .filter_map(|p| std::fs::metadata(p).ok()) @@ -692,8 +878,8 @@ mod tests { conn } - fn row(ts: i64, name: &str, flags: u8) -> Row { - Row( + fn row(ts: i64, name: &str, flags: u8) -> Play { + Play( ts as f64, 180_000.0, name.into(), @@ -720,7 +906,7 @@ mod tests { } } - fn change(replace: bool, insert: Vec<Row>, delete: Vec<Row>) -> Change { + fn change(replace: bool, insert: Vec<Play>, delete: Vec<Play>) -> Change { Change { replace, insert, @@ -922,32 +1108,26 @@ mod tests { assert!(plan.contains("plays_song"), "{plan}"); } + /// Loading walks the (owner, time) index in order: no sorting of a whole history. #[test] - fn finishes_an_upgrade_that_was_interrupted() { - // A version 1 file that already has the extras column: an upgrade that stopped between - // adding the column and recording the new version. - let conn = Connection::open_in_memory().unwrap(); - conn.execute_batch(SCHEMA).unwrap(); - conn.pragma_update(None, "user_version", 1).unwrap(); - migrate(&conn).unwrap(); - let version: i32 = conn - .pragma_query_value(None, "user_version", |r| r.get(0)) - .unwrap(); - assert_eq!(version, SCHEMA_VERSION); - assert!(has_column(&conn, "accounts", "extras").unwrap()); - } - - #[test] - fn refuses_a_file_from_a_newer_version() { + fn plays_load_in_index_order_without_sorting() { let conn = db(); - conn.pragma_update(None, "user_version", SCHEMA_VERSION + 1) + let mut stmt = conn + .prepare( + "EXPLAIN QUERY PLAN SELECT ended_at, ms_played, song_id, flags, platform, country + FROM plays WHERE owner = ?1 ORDER BY ended_at, id", + ) .unwrap(); - let err = migrate(&conn).unwrap_err(); - assert!(err.contains("newer version of Statsify"), "{err}"); - let version: i32 = conn - .pragma_query_value(None, "user_version", |r| r.get(0)) + let plan: Vec<String> = stmt + .query_map(["me"], |r| r.get(3)) + .unwrap() + .collect::<Result<_, _>>() .unwrap(); - assert_eq!(version, SCHEMA_VERSION + 1, "the file is left alone"); + assert!( + plan.iter().any(|p| p.contains("plays_owner_time")), + "{plan:?}" + ); + assert!(!plan.iter().any(|p| p.contains("TEMP B-TREE")), "{plan:?}"); } /// A file from a newer Statsify is refused before anything is written to it, its journal @@ -974,6 +1154,54 @@ mod tests { std::fs::remove_dir_all(&dir).ok(); } + #[test] + fn database_errors_are_sentences() { + let error = |code| { + db_error(rusqlite::Error::SqliteFailure( + rusqlite::ffi::Error::new(code), + None, + )) + }; + assert!(error(rusqlite::ffi::SQLITE_BUSY).starts_with("The history database is in use")); + assert!(error(rusqlite::ffi::SQLITE_CORRUPT) + .starts_with("The history database file is damaged")); + assert!( + error(rusqlite::ffi::SQLITE_NOTADB).starts_with("The history database file is damaged") + ); + assert!(error(rusqlite::ffi::SQLITE_FULL).starts_with("The disk is full")); + assert!(error(rusqlite::ffi::SQLITE_READONLY) + .starts_with("The history database file can't be written to")); + assert!(error(rusqlite::ffi::SQLITE_IOERR).ends_with(").")); + } + + #[test] + fn finishes_an_upgrade_that_was_interrupted() { + // A version 1 file that already has the extras column: an upgrade that stopped between + // adding the column and recording the new version. + let conn = Connection::open_in_memory().unwrap(); + conn.execute_batch(SCHEMA).unwrap(); + conn.pragma_update(None, "user_version", 1).unwrap(); + migrate(&conn).unwrap(); + let version: i32 = conn + .pragma_query_value(None, "user_version", |r| r.get(0)) + .unwrap(); + assert_eq!(version, SCHEMA_VERSION); + assert!(has_column(&conn, "accounts", "extras").unwrap()); + } + + #[test] + fn refuses_a_file_from_a_newer_version() { + let conn = db(); + conn.pragma_update(None, "user_version", SCHEMA_VERSION + 1) + .unwrap(); + let err = migrate(&conn).unwrap_err(); + assert!(err.contains("newer version of Statsify"), "{err}"); + let version: i32 = conn + .pragma_query_value(None, "user_version", |r| r.get(0)) + .unwrap(); + assert_eq!(version, SCHEMA_VERSION + 1, "the file is left alone"); + } + #[test] fn saves_that_remove_plays_also_remove_unused_songs() { let mut conn = db(); @@ -1189,6 +1417,277 @@ mod tests { std::fs::remove_dir_all(&dir).ok(); } + #[test] + fn an_account_without_plays_loads_as_an_empty_history() { + let mut conn = db(); + apply(&mut conn, "me", &change(true, vec![], vec![])).unwrap(); + let blob = load(&conn, "me").unwrap(); + let (header, ts, ..) = decode(&blob); + assert_eq!((header["n"].as_u64(), ts.len()), (Some(0), 0)); + assert_eq!(header["tracks"], serde_json::json!([])); + } + + #[test] + fn columns_start_aligned_whatever_the_header_length() { + let mut lengths = std::collections::HashSet::new(); + for pad in 0..16 { + let mut conn = db(); + let mut c = change(true, vec![row(T0, "a", 0), row(T0 + 1, "b", 3)], vec![]); + c.meta.sources = serde_json::json!([{ "label": "x".repeat(pad) }]); + apply(&mut conn, "me", &c).unwrap(); + let blob = load(&conn, "me").unwrap(); + // decode checks the alignment and every length. + let (header, ts, _, tr, flags, ..) = decode(&blob); + assert_eq!(header["sources"][0]["label"], "x".repeat(pad)); + assert_eq!((ts.len(), tr, flags), (2, vec![0, 1], vec![0, 3])); + let header_len = u32::from_le_bytes(blob[4..8].try_into().unwrap()) as usize; + let json = &blob[8..8 + header_len]; + lengths.insert((json.iter().rposition(|&b| b != b' ').unwrap() + 1) % 8); + } + assert_eq!(lengths.len(), 8, "every amount of padding was tried"); + } + + #[test] + fn platform_and_country_tables_hold_at_most_255_names() { + let mut conn = db(); + let plays = (0..300) + .map(|i| { + let mut play = row(T0 + i, "a", 0); + play.7 = Some(format!("platform {i}")); + if i % 2 == 0 { + play.8 = Some(String::new()); + } + play + }) + .collect(); + apply(&mut conn, "me", &change(true, plays, vec![])).unwrap(); + let (header, _, _, _, _, platform, country) = decode(&load(&conn, "me").unwrap()); + assert_eq!(header["platforms"].as_array().unwrap().len(), 255); + assert_eq!(header["platforms"][254], "platform 254"); + assert_eq!(&platform[..3], &[0, 1, 2]); + assert!(platform[255..].iter().all(|&p| p == UNKNOWN)); + // An empty country is no country. + assert_eq!(country[0], UNKNOWN); + assert_eq!(header["countries"][country[1] as usize], "GB"); + } + + #[test] + fn json_edited_by_hand_falls_back_to_empty_values() { + let mut conn = db(); + apply( + &mut conn, + "me", + &change(true, vec![row(T0, "a", 0)], vec![]), + ) + .unwrap(); + conn.execute( + "UPDATE accounts SET sources = 'not json', extras = '{\"podcasts\":'", + [], + ) + .unwrap(); + let (header, ts, ..) = decode(&load(&conn, "me").unwrap()); + assert_eq!(header["sources"], serde_json::json!([])); + assert_eq!(header["extras"], serde_json::json!({})); + assert_eq!(ts.len(), 1); + } + + #[test] + fn plays_of_songs_that_are_gone_are_left_out() { + let mut conn = db(); + apply( + &mut conn, + "me", + &change(true, vec![row(T0, "a", 0)], vec![]), + ) + .unwrap(); + // As a database browser with foreign keys off could leave it. + conn.execute_batch( + "PRAGMA foreign_keys = OFF; + INSERT INTO plays (owner, ended_at, ms_played, song_id) VALUES ('me', 1700000000001, 5, 999);", + ) + .unwrap(); + let (header, ts, ..) = decode(&load(&conn, "me").unwrap()); + assert_eq!(ts, vec![T0 as f64]); + assert_eq!(header["n"], 1); + } + + #[test] + fn the_latest_artwork_and_length_in_a_save_win() { + let mut conn = db(); + let mut plays: Vec<Play> = (0..4).map(|i| row(T0 + i, "a", 0)).collect(); + plays[0].9 = Some("https://i.scdn.co/image/old".into()); + plays[1].10 = Some(200_000.0); + plays[2].9 = Some("https://i.scdn.co/image/new".into()); + // Unknown again, or impossible: what is known is kept. + plays[3].10 = Some(1e300); + apply(&mut conn, "me", &change(true, plays, vec![])).unwrap(); + let (header, ..) = decode(&load(&conn, "me").unwrap()); + assert_eq!(header["tracks"][0][4], "https://i.scdn.co/image/new"); + assert_eq!(header["tracks"][0][5], 200_000); + } + + /// A small deterministic random number generator (xorshift), for the round-trip test. + struct Random(u64); + + impl Random { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + } + + /// A play as `load` gives it back: (ended_at, ms, name, artist, album, uri, flags, + /// platform, country). + type Seen = ( + i64, + u32, + String, + String, + String, + Option<String>, + u8, + Option<String>, + Option<String>, + ); + + fn seen(play: &Play) -> Seen { + let (uri, name, artist, album) = play.song(); + ( + play.ended_at(), + play.ms_played() as u32, + name.into(), + artist.into(), + album.into(), + (!uri.is_empty()).then(|| uri.into()), + play.flags(), + play.platform().map(Into::into), + play.country().map(Into::into), + ) + } + + fn loaded(conn: &Connection) -> Vec<Seen> { + let (header, ts, ms, tr, flags, platform, country) = decode(&load(conn, "me").unwrap()); + let text = |v: &serde_json::Value| v.as_str().map(String::from); + let name = |table: &str, i: u8| text(&header[table][i as usize]); + (0..ts.len()) + .map(|i| { + let track = &header["tracks"][tr[i] as usize]; + ( + ts[i] as i64, + ms[i], + text(&track[0]).unwrap(), + text(&header["artists"][track[1].as_u64().unwrap() as usize]).unwrap(), + text(&header["albums"][track[2].as_u64().unwrap() as usize]).unwrap(), + text(&track[3]), + flags[i], + name("platforms", platform[i]), + name("countries", country[i]), + ) + }) + .collect() + } + + /// Random saves, as the UI makes them (a first save in chunks, then inserts and deletes, + /// sometimes a full rewrite), checked against a plain list of the plays that should be + /// stored. Names include long, multi-byte and empty ones; plays repeat. + #[test] + fn random_saves_load_back_exactly() { + let mut random = Random(0x5EED_CAFE_F00D); + let names = [ + "a", + "Ünïcödé", + "🎵 emoji 🎶", + "", + &"é".repeat(200), + &"x".repeat(299), + "same", + ]; + let make = |random: &mut Random| { + let pick = |random: &mut Random, list: &[&str]| { + list[random.below(list.len() as u64) as usize].to_string() + }; + let uri = match random.below(3) { + 0 => None, + 1 => Some(String::new()), + _ => Some(format!("spotify:track:{}", random.below(5))), + }; + let platform = ["windows", "", "ios"][random.below(3) as usize]; + Play( + (T0 + random.below(50) as i64 * 1000) as f64, + random.below(400_000) as f64, + pick(random, &names), + pick(random, &names[..3]), + pick(random, &names[3..]), + uri, + random.below(64) as u8, + (random.below(4) > 0).then(|| platform.to_string()), + (random.below(2) == 0).then(|| "SE".to_string()), + (random.below(2) == 0) + .then(|| format!("https://i.scdn.co/image/{}", random.below(3))), + (random.below(2) == 0).then(|| 1000.0 + random.below(3) as f64), + ) + }; + let mut conn = db(); + let mut model: Vec<Seen> = Vec::new(); + for round in 0..40 { + if round == 0 || random.below(10) == 0 { + // A full rewrite, in chunks like the UI's. + let plays: Vec<Play> = (0..random.below(120)).map(|_| make(&mut random)).collect(); + model = plays.iter().map(seen).collect(); + let mut chunks = plays.chunks(25).peekable(); + if chunks.peek().is_none() { + apply(&mut conn, "me", &change(true, vec![], vec![])).unwrap(); + } + let mut first = true; + for chunk in chunks { + apply(&mut conn, "me", &change(first, chunk.to_vec(), vec![])).unwrap(); + first = false; + } + } else { + let insert: Vec<Play> = (0..random.below(20)).map(|_| make(&mut random)).collect(); + // Delete some stored plays, and some that were never stored. + let mut delete = Vec::new(); + for _ in 0..random.below(15) { + if !model.is_empty() && random.below(4) > 0 { + let s = model.swap_remove(random.below(model.len() as u64) as usize); + delete.push(Play( + s.0 as f64, s.1 as f64, s.2, s.3, s.4, s.5, s.6, s.7, s.8, None, None, + )); + } else { + let mut gone = make(&mut random); + gone.0 = (T0 - 1) as f64; + delete.push(gone); + } + } + model.extend(insert.iter().map(seen)); + let stored = apply(&mut conn, "me", &change(false, insert, delete)).unwrap(); + assert_eq!(stored, model.len() as u64, "round {round}"); + } + let mut expected = model.clone(); + expected.sort(); + let got = loaded(&conn); + assert!(got.windows(2).all(|w| w[0].0 <= w[1].0), "sorted by time"); + let mut got_sorted = got.clone(); + got_sorted.sort(); + assert_eq!(got_sorted, expected, "round {round}"); + // Every stored song is a song some play refers to. + assert_eq!( + counts(&conn).unwrap().1 as usize, + got.iter() + .map(|s| (&s.5, &s.2, &s.3, &s.4)) + .collect::<std::collections::HashSet<_>>() + .len(), + "round {round}" + ); + } + } + /// Quitting closes the database, which folds the write-ahead log into the file: a backup /// of the file alone then has every play. #[test] @@ -1212,7 +1711,7 @@ mod tests { #[test] fn handles_a_large_history_quickly() { let mut conn = db(); - let rows: Vec<Row> = (0..200_000) + let rows: Vec<Play> = (0..200_000) .map(|i| { row( T0 + i * 60_000, From af990254a092df64aee0321a4242f7006c98c4ca Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:36:50 +0000 Subject: [PATCH 28/41] test(history): hostile, concurrent and damaged-file cases, and a benchmark Through the IPC layer with the arguments the UI sends: - hostile saves: megabyte names (stored clipped), impossible dates, lengths and flags, wrong shapes and account ids, refused with nothing written; - eight threads saving and loading at once, and an erase racing saves; - a file that isn't a database: refused in words and never written to; - a database cut in half: an error, not a shorter history. tests/history_bench.rs times the history commands and their heap on a 200,000-play history (ignored by default; run with --release --ignored). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- AGENTS.md | 20 +-- src-tauri/tests/history_bench.rs | 227 +++++++++++++++++++++++++++++++ src-tauri/tests/history_ipc.rs | 208 +++++++++++++++++++++++++++- 3 files changed, 446 insertions(+), 9 deletions(-) create mode 100644 src-tauri/tests/history_bench.rs diff --git a/AGENTS.md b/AGENTS.md index d904f2c..9d4bf9f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -120,7 +120,7 @@ Tests sit next to the code they test (`*.test.ts` / `*.test.tsx`). | `assets/oauth-done.html` | The page the browser shows after a successful sign-in | | `capabilities/default.json` | Permissions for the main window (least privilege) | | `tauri.conf.json` | Window, bundle targets, identifier (fixes the data folder; never change it), CSP | -| `tests/` | Integration tests through Tauri's IPC layer with the mock runtime: history commands, the launcher, launch-plan edge cases, the window material's arguments, every command refusing remote origins | +| `tests/` | Integration tests through Tauri's IPC layer with the mock runtime: history commands, the sign-in listener, the launcher, launch-plan edge cases, the window material's arguments, every command refusing remote origins; a history benchmark | ### `e2e/`, `scripts/`, `docs/` @@ -792,13 +792,17 @@ label)` (axe WCAG 2.2 A/AA, no serious or critical violations), `enterDemo`, `se `settled` (wait for `aria-busy` to clear). - Tests assert what users see, using roles and accessible names, not CSS classes. - **Rust** (`cargo test` in `src-tauri/`): unit tests in each module (schema, migrations, - validation, the binary format, a 200k-play history, the sign-in listener against raw HTTP - requests, launch plans, window-material plans) and integration tests through the IPC layer - with Tauri's mock runtime (`tests/`), including rejecting remote origins and answering off the - calling thread. Launcher tests use a fake `spotify` script and skip themselves if a real Spotify - is installed at a fixed path. Windows-only code (the window material's subclass) isn't compiled - on the Linux CI runners: check it with `cargo check --target x86_64-pc-windows-msvc` where the - Windows SDK is available, or rely on the Windows desktop build in `desktop.yml`. + validation, the binary format, random saves checked against a model, a 200k-play history, the + sign-in listener against raw, malformed, slow and oversized HTTP requests, launch plans, + window-material plans) and integration tests through the IPC layer with Tauri's mock runtime + (`tests/`), including hostile input, damaged database files, concurrent calls, rejecting remote + origins and answering off the calling thread. `tests/history_bench.rs` times the history + commands and their heap on 200k plays; run it before and after touching that code: + `cargo test --release --test history_bench -- --ignored --nocapture`. Launcher tests use a fake + `spotify` script and skip themselves if a real Spotify is installed at a fixed path. Windows-only + code (the window material's subclass) isn't compiled on the Linux CI runners: check it with + `cargo check --target x86_64-pc-windows-msvc` where the Windows SDK is available, or rely on the + Windows desktop build in `desktop.yml`. - **Workflows** (`.github/workflows/`, every action pinned to a commit SHA, Dependabot keeps them current): - `ci.yml`: typecheck, lint, unit tests, build, e2e, and the three cargo checks on every push to diff --git a/src-tauri/tests/history_bench.rs b/src-tauri/tests/history_bench.rs new file mode 100644 index 0000000..1d6b72f --- /dev/null +++ b/src-tauri/tests/history_bench.rs @@ -0,0 +1,227 @@ +//! Time and peak heap of the history commands on a large history, called through the IPC +//! layer (mock runtime) with the argument shapes the UI sends. A benchmark, not part of the +//! normal run: +//! +//! cargo test --release --test history_bench -- --ignored --nocapture +//! +//! CPU time (Linux) is the process's, all threads, so it holds up better than wall time on a +//! busy machine. The heap figures count Rust's allocations only, not SQLite's page cache. + +mod common; + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; +use std::time::Instant; + +use common::{invoke_request, open_main, APP_ORIGIN}; +use spotify_stats_lib::history::{self, HistoryDb}; +use tauri::ipc::InvokeResponseBody; +use tauri::test::{get_ipc_response, mock_builder, mock_context, noop_assets, MockRuntime}; +use tauri::webview::InvokeRequest; +use tauri::WebviewWindow; + +/// The system allocator, counting live and peak bytes. +struct Counting; +static LIVE: AtomicUsize = AtomicUsize::new(0); +static PEAK: AtomicUsize = AtomicUsize::new(0); + +fn grew(by: usize) { + let live = LIVE.fetch_add(by, Relaxed) + by; + PEAK.fetch_max(live, Relaxed); +} + +// SAFETY: every call is passed straight to the system allocator; the counters are only read. +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let p = System.alloc(layout); + if !p.is_null() { + grew(layout.size()); + } + p + } + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + let p = System.alloc_zeroed(layout); + if !p.is_null() { + grew(layout.size()); + } + p + } + unsafe fn dealloc(&self, p: *mut u8, layout: Layout) { + System.dealloc(p, layout); + LIVE.fetch_sub(layout.size(), Relaxed); + } + unsafe fn realloc(&self, p: *mut u8, layout: Layout, new: usize) -> *mut u8 { + let q = System.realloc(p, layout, new); + if !q.is_null() { + if new > layout.size() { + grew(new - layout.size()); + } else { + LIVE.fetch_sub(layout.size() - new, Relaxed); + } + } + q + } +} + +#[global_allocator] +static ALLOC: Counting = Counting; + +/// CPU time this process has used, in ms (user and system, every thread; 10 ms steps). +fn cpu_ms() -> Option<f64> { + let stat = std::fs::read_to_string("/proc/self/stat").ok()?; + let fields: Vec<&str> = stat[stat.rfind(')')? + 2..].split(' ').collect(); + let ticks: f64 = fields[11].parse::<f64>().ok()? + fields[12].parse::<f64>().ok()?; + Some(ticks * 10.0) +} + +/// Run `f` `times` times and print the time each took on average (wall and CPU) and the most +/// heap one held beyond what was live before. +fn measure<T>(label: &str, times: u32, mut f: impl FnMut() -> T) -> T { + let before = LIVE.load(Relaxed); + PEAK.store(before, Relaxed); + let cpu = cpu_ms(); + let started = Instant::now(); + let mut out = f(); + for _ in 1..times { + out = f(); + } + let wall = started.elapsed().as_secs_f64() * 1e3 / f64::from(times); + let cpu = cpu_ms() + .zip(cpu) + .map(|(after, before)| format!(" cpu {:>7.0} ms", (after - before) / f64::from(times))) + .unwrap_or_default(); + let peak = PEAK.load(Relaxed).saturating_sub(before) as f64 / 1e6; + println!("{label:<40} {wall:>8.1} ms{cpu} heap +{peak:>5.1} MB"); + out +} + +const PLAYS: usize = 200_000; +const SONGS: usize = 20_000; +const T0: f64 = 1_600_000_000_000.0; + +/// A play as `allRows` in app/history/diff.ts sends it; `variant` renames every song. +fn row(i: usize, variant: usize) -> serde_json::Value { + let s = (i * 7919) % SONGS; + let country = ["GB", "US", "DE", "FR", "SE"][i % 5]; + serde_json::json!([ + T0 + (i as f64) * 120_000.0, + (i * 37 % 240_000) as f64, + format!("Song number {s} (Remastered 2011) {variant}"), + format!("Artist {}", s % 3_000), + format!("Album {}", s % 6_000), + format!("spotify:track:{s:022}"), + (i % 64) as u8, + format!("Android OS 1{} API 3{}", i % 7, i % 5), + country, + format!("https://i.scdn.co/image/ab67616d0000b273{s:024}"), + 180_000 + (s % 60_000) as u64 + ]) +} + +fn apply_request( + replace: bool, + insert: Vec<serde_json::Value>, + delete: Vec<serde_json::Value>, +) -> InvokeRequest { + let meta = serde_json::json!({ "sources": [{ "kind": "extended", "label": "Extended streaming history", "plays": PLAYS, "importedAt": 1 }], + "podcastMs": 0, "podcastPlays": 0, "updatedAt": 1_700_000_000_000.0 }); + let body = serde_json::json!({ "owner": "me", "change": { "replace": replace, "insert": insert, "delete": delete, "meta": meta } }); + invoke_request(APP_ORIGIN, "history_apply", body) +} + +/// A whole history as the UI saves it: 50k-play chunks, the first replacing what is stored. +fn save_requests(variant: usize) -> Vec<InvokeRequest> { + let rows: Vec<serde_json::Value> = (0..PLAYS).map(|i| row(i, variant)).collect(); + rows.chunks(50_000) + .enumerate() + .map(|(k, chunk)| apply_request(k == 0, chunk.to_vec(), vec![])) + .collect() +} + +fn send(webview: &WebviewWindow<MockRuntime>, request: InvokeRequest) -> InvokeResponseBody { + get_ipc_response(webview, request).unwrap() +} + +fn load(webview: &WebviewWindow<MockRuntime>) -> usize { + let request = invoke_request( + APP_ORIGIN, + "history_load", + serde_json::json!({ "owner": "me" }), + ); + match send(webview, request) { + InvokeResponseBody::Raw(bytes) => bytes.len(), + other => panic!("expected a binary answer, got {other:?}"), + } +} + +#[test] +#[ignore = "a benchmark: run with --release --ignored --nocapture"] +fn large_history() { + let dir = std::env::temp_dir().join(format!("ss-bench-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let db = HistoryDb::new(); + db.set_path(dir.join(history::FILE_NAME)); + let (_app, webview) = open_main( + mock_builder() + .manage(db) + .invoke_handler(tauri::generate_handler![ + history::history_load, + history::history_apply, + history::history_delete, + history::history_info + ]), + mock_context(noop_assets()), + ); + + // Requests are built beforehand and handed over whole, so only the command is measured. + let mut first = Some(save_requests(0)); + measure("first save: 200k plays, 20k songs", 1, || { + for request in first.take().unwrap() { + send(&webview, request); + } + }); + let bytes = measure("load 200k plays (average of 5)", 5, || load(&webview)); + println!(" {} KB sent to the UI", bytes / 1024); + let sync: Vec<_> = (PLAYS..PLAYS + 50).map(|i| row(i, 0)).collect(); + let mut sync = Some(apply_request(false, sync, vec![])); + measure("sync: 50 new plays", 1, || { + send(&webview, sync.take().unwrap()) + }); + // An import replacing 5,000 plays with plays of other songs. + let mut import = Some(apply_request( + false, + (0..5_000).map(|i| row(i, 1)).collect(), + (0..5_000).map(|i| row(i, 0)).collect(), + )); + measure("import: 5k plays replaced", 1, || { + send(&webview, import.take().unwrap()) + }); + // What the UI does after a save failed: rewrite everything. Here every song is renamed, so + // the old ones are dropped. + let mut rewrite = Some(save_requests(2)); + measure("full rewrite of an existing history", 1, || { + for request in rewrite.take().unwrap() { + send(&webview, request); + } + }); + let info = send( + &webview, + invoke_request(APP_ORIGIN, "history_info", serde_json::json!({})), + ); + let info: serde_json::Value = info.deserialize().unwrap(); + println!( + " database and log: {} KB", + info["bytes"].as_u64().unwrap() / 1024 + ); + measure("erase the account", 1, || { + send( + &webview, + invoke_request( + APP_ORIGIN, + "history_delete", + serde_json::json!({ "owner": "me" }), + ), + ) + }); + std::fs::remove_dir_all(&dir).ok(); +} diff --git a/src-tauri/tests/history_ipc.rs b/src-tauri/tests/history_ipc.rs index 69be6e1..34b8e99 100644 --- a/src-tauri/tests/history_ipc.rs +++ b/src-tauri/tests/history_ipc.rs @@ -10,7 +10,7 @@ use spotify_stats_lib::history::{self, HistoryDb}; use tauri::ipc::{InvokeResponse, InvokeResponseBody}; use tauri::test::{get_ipc_response, mock_builder, mock_context, noop_assets, MockRuntime}; use tauri::webview::InvokeRequest; -use tauri::{App, WebviewWindow}; +use tauri::{App, Manager, WebviewWindow}; fn request(cmd: &str, body: serde_json::Value) -> InvokeRequest { invoke_request(APP_ORIGIN, cmd, body) @@ -152,3 +152,209 @@ fn history_commands_answer_off_the_calling_thread() { } std::fs::remove_dir_all(&dir).ok(); } + +/// A fresh folder for one test's database, removed afterwards. +struct TempDir(std::path::PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("ss-ipc-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + TempDir(dir) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A play as `PlayRow` in app/history/diff.ts. +fn play(ended_at: f64, name: &str) -> serde_json::Value { + serde_json::json!([ended_at, 180_000, name, "Artist", "Album", null, 0, null, null, null, null]) +} + +fn apply( + webview: &WebviewWindow<MockRuntime>, + replace: bool, + insert: Vec<serde_json::Value>, + delete: Vec<serde_json::Value>, +) -> Result<u64, String> { + let body = serde_json::json!({ "owner": "me", "change": { "replace": replace, "insert": insert, "delete": delete, + "meta": { "sources": [], "podcastMs": 0, "podcastPlays": 0, "updatedAt": 1 } } }); + get_ipc_response(webview, request("history_apply", body)) + .map(|answer| answer.deserialize::<u64>().unwrap()) + .map_err(|err| err.to_string()) +} + +fn load(webview: &WebviewWindow<MockRuntime>) -> Result<Vec<u8>, String> { + let answer = get_ipc_response( + webview, + request("history_load", serde_json::json!({ "owner": "me" })), + ); + match answer.map_err(|err| err.to_string())? { + InvokeResponseBody::Raw(bytes) => Ok(bytes), + other => panic!("expected a binary answer, got {other:?}"), + } +} + +/// The header of a `history_load` answer. +fn header(blob: &[u8]) -> serde_json::Value { + let len = u32::from_le_bytes(blob[4..8].try_into().unwrap()) as usize; + serde_json::from_slice(&blob[8..8 + len]).unwrap() +} + +const T0: f64 = 1_700_000_000_000.0; + +#[test] +fn hostile_saves_are_refused_or_clipped() { + let dir = TempDir::new("hostile"); + let (_app, webview) = history_app(&dir.0); + // A megabyte-long name is stored clipped to 300 bytes, between characters. + let long = "é".repeat(500_000); + assert_eq!(apply(&webview, true, vec![play(T0, &long)], vec![]), Ok(1)); + let stored = header(&load(&webview).unwrap())["tracks"][0][0] + .as_str() + .unwrap() + .to_string(); + assert_eq!(stored, "é".repeat(150)); + + let refused = [ + // Before 2006, far in the future, beyond what a number can be. + play(1_000.0, "old"), + play(T0 * 10.0, "future"), + play(1e300, "huge"), + play(-T0, "negative"), + // Impossible lengths and flags. + serde_json::json!([T0, -1, "s", "a", "b", null, 0, null, null, null, null]), + serde_json::json!([T0, 1e12, "s", "a", "b", null, 0, null, null, null, null]), + serde_json::json!([T0, 1, "s", "a", "b", null, 256, null, null, null, null]), + serde_json::json!([T0, 1, "s", "a", "b", null, -1, null, null, null, null]), + // Wrong shapes. + serde_json::json!([T0, 1, "s", "a"]), + serde_json::json!([T0, 1, 5, "a", "b", null, 0, null, null, null, null]), + serde_json::json!({ "endedAt": T0 }), + serde_json::json!(null), + ]; + for bad in refused { + let plays = vec![play(T0 + 1.0, "ok"), bad.clone()]; + assert!( + apply(&webview, false, plays, vec![]).is_err(), + "{bad} was accepted" + ); + } + for owner in [ + serde_json::json!(""), + serde_json::json!("x".repeat(129)), + serde_json::json!("me\u{0}"), + serde_json::json!(5), + ] { + let body = serde_json::json!({ "owner": owner }); + assert!(get_ipc_response(&webview, request("history_load", body.clone())).is_err()); + assert!(get_ipc_response(&webview, request("history_delete", body)).is_err()); + } + // Nothing of the refused saves was written. + assert_eq!(header(&load(&webview).unwrap())["n"], 1); + // Deleting plays that were never saved, even impossible ones, changes nothing. + let never = vec![play(1e300, "never"), play(-1.0, "never")]; + assert_eq!(apply(&webview, false, vec![], never), Ok(1)); +} + +/// The UI saves, loads and erases from several places at once (a sync while an import is +/// saving, say). Each command runs whole, one at a time. +#[test] +fn concurrent_commands_run_one_at_a_time() { + let dir = TempDir::new("concurrent"); + let (_app, webview) = history_app(&dir.0); + assert_eq!(apply(&webview, true, vec![], vec![]), Ok(0)); + let savers: Vec<_> = (0..8) + .map(|t| { + let webview = webview.clone(); + std::thread::spawn(move || { + for k in 0..10 { + let at = T0 + f64::from(t * 1_000 + k); + let plays = (0..10) + .map(|i| play(at + f64::from(i) * 0.1, "s")) + .collect(); + apply(&webview, false, plays, vec![]).unwrap(); + load(&webview).unwrap(); + } + }) + }) + .collect(); + for saver in savers { + saver.join().unwrap(); + } + assert_eq!(header(&load(&webview).unwrap())["n"], 800); + + // An erase racing saves: afterwards only plays saved after it remain. + let eraser = { + let webview = webview.clone(); + std::thread::spawn(move || { + get_ipc_response( + &webview, + request("history_delete", serde_json::json!({ "owner": "me" })), + ) + .unwrap(); + }) + }; + for k in 0..5 { + apply( + &webview, + false, + vec![play(T0 + f64::from(k), "late")], + vec![], + ) + .unwrap(); + } + eraser.join().unwrap(); + let left = match load(&webview).unwrap() { + blob if blob.is_empty() => 0, + blob => header(&blob)["n"].as_u64().unwrap(), + }; + assert!(left <= 5, "{left} plays survived the erase"); +} + +/// A file that isn't a database is reported in words and never written to: the UI then +/// stops saving rather than replace the user's file with a new history. +#[test] +fn a_damaged_file_is_refused_and_left_alone() { + let dir = TempDir::new("damaged"); + let path = dir.0.join(history::FILE_NAME); + let garbage = b"definitely not a database, but someone's precious file".repeat(100); + std::fs::write(&path, &garbage).unwrap(); + let (_app, webview) = history_app(&dir.0); + let err = load(&webview).unwrap_err(); + assert!( + err.contains("The history database file is damaged"), + "{err}" + ); + assert!(apply(&webview, true, vec![play(T0, "new")], vec![]).is_err()); + let erase = request("history_delete", serde_json::json!({ "owner": "me" })); + assert!(get_ipc_response(&webview, erase).is_err()); + assert_eq!(std::fs::read(&path).unwrap(), garbage); +} + +/// A database cut short (a disk that filled up mid-copy, say) fails to load in words rather +/// than loading as an empty or partial history. +#[test] +fn a_truncated_file_does_not_load_as_a_shorter_history() { + let dir = TempDir::new("truncated"); + let path = dir.0.join(history::FILE_NAME); + let (app, webview) = history_app(&dir.0); + let plays = (0..5_000) + .map(|i| play(T0 + f64::from(i), &format!("song {}", i % 500))) + .collect(); + assert_eq!(apply(&webview, true, plays, vec![]), Ok(5_000)); + // As the app quits: the log is folded into the file, which then holds everything. + app.state::<HistoryDb>().close(); + assert!(!path.with_extension("sqlite3-wal").exists()); + let bytes = std::fs::read(&path).unwrap(); + std::fs::write(&path, &bytes[..bytes.len() / 2]).unwrap(); + match load(&webview) { + Err(err) => assert!(err.contains("The history database"), "{err}"), + Ok(blob) => panic!("loaded {} from half a file", header(&blob)["n"]), + } +} From 2f8b1b2311d8ed89a0f068f4a2057df24ef1b211 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:38:28 +0000 Subject: [PATCH 29/41] fix(launcher): start Spotify once for requests close together Two requests to start Spotify at about the same time both found it not running and both started it, and so did one arriving before a just-started Spotify showed up as running (a launcher script or a sandbox can take a few seconds to start the real program). Launches now run one at a time, and an install Statsify started in the last ten seconds is reported as starting instead of being started again. A PATH holding one folder whose name isn't valid Unicode was skipped whole (std::env::var refuses the variable), so Spotify on the PATH read as not installed. The environment is now read lossily: only that folder is lost. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- src-tauri/src/spotify_app.rs | 19 ++++++++- src-tauri/tests/spotify_launch_ipc.rs | 56 +++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) diff --git a/src-tauri/src/spotify_app.rs b/src-tauri/src/spotify_app.rs index b19cedb..0388213 100644 --- a/src-tauri/src/spotify_app.rs +++ b/src-tauri/src/spotify_app.rs @@ -14,6 +14,8 @@ use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; +use std::sync::{Mutex, PoisonError}; +use std::time::{Duration, Instant}; /// How to start Spotify on this machine. #[derive(Debug, Clone, PartialEq, Eq)] @@ -284,16 +286,31 @@ pub async fn spotify_launch_hidden() -> Result<String, String> { .map_err(|e| format!("Couldn't start Spotify: {e}"))? } +/// The installs Statsify started lately, and when. Spotify can take a few seconds to show up +/// as running (a launcher script, a sandbox), so a request in that time is told it is starting +/// rather than starting a second copy, which could bring its window up. +static STARTED: Mutex<Vec<(PathBuf, Instant)>> = Mutex::new(Vec::new()); +const STARTING: Duration = Duration::from_secs(10); + fn launch_hidden() -> Result<String, String> { + // One launch at a time, so requests arriving together can't all find Spotify not running + // and each start it. Nothing else takes this lock. + let mut started = STARTED.lock().unwrap_or_else(PoisonError::into_inner); if spotify_running() { return Ok("running".into()); } - let env = |name: &str| std::env::var(name).ok(); + // Lossy: one folder named in another encoding mustn't hide the rest of the PATH. + let env = |name: &str| std::env::var_os(name).map(|v| v.to_string_lossy().into_owned()); let exists = |p: &Path| installed(p); let Some(plan) = plan(std::env::consts::OS, &env, &exists) else { return Err("not_installed".into()); }; + started.retain(|(_, at)| at.elapsed() < STARTING); + if started.iter().any(|(program, _)| *program == plan.program) { + return Ok(plan.via.into()); + } spawn(&plan).map_err(|e| format!("Couldn't start Spotify: {e}"))?; + started.push((plan.program.clone(), Instant::now())); Ok(plan.via.into()) } diff --git a/src-tauri/tests/spotify_launch_ipc.rs b/src-tauri/tests/spotify_launch_ipc.rs index 478d3fb..d997983 100644 --- a/src-tauri/tests/spotify_launch_ipc.rs +++ b/src-tauri/tests/spotify_launch_ipc.rs @@ -496,3 +496,59 @@ fn appimage_environment_does_not_leak_into_spotify() { ); } } + +/// A PATH entry that isn't valid Unicode (a folder named in another encoding) doesn't stop +/// the search through the others. +#[cfg(target_os = "linux")] +#[test] +fn a_path_entry_that_is_not_unicode_does_not_hide_the_others() { + use std::os::unix::ffi::OsStringExt; + let _lock = lock_env(); + let root = TempDir::new("nonutf8"); + let bin = root.sub("bin"); + let marker = root.0.join("started"); + fake_spotify(&bin.join("spotify"), &marker, 0); + let mut path = b"/opt/caf\xe9/bin:".to_vec(); + path.extend_from_slice(bin.as_os_str().as_encoded_bytes()); + let mut env = EnvGuard::new(); + env.sandbox(&root).set("PATH", OsString::from_vec(path)); + let (_app, webview) = launcher_app(mock_context(noop_assets())); + assert_eq!(call(&webview, APP_ORIGIN), Ok(serde_json::json!("path"))); + assert!(read_marker(&marker, Duration::from_secs(10)).is_some()); +} + +/// Requests that arrive together, or before Spotify shows up as running (a launcher script or +/// a sandbox can take a few seconds to start the real program), start it once. +#[cfg(target_os = "linux")] +#[test] +fn launches_close_together_start_spotify_once() { + use std::os::unix::fs::PermissionsExt; + let _lock = lock_env(); + let root = TempDir::new("together"); + let bin = root.sub("bin"); + let log = root.0.join("starts"); + let log_path = log.to_str().unwrap(); + assert!(!log_path.contains('\'')); + // A stand-in that notes each start and stays up for a while, as a shell script (so the + // running check never sees it as Spotify). + let script = format!("#!/bin/sh\nPATH=/usr/bin:/bin\necho start >> '{log_path}'\nsleep 3\n"); + std::fs::write(bin.join("spotify"), script).unwrap(); + std::fs::set_permissions(bin.join("spotify"), std::fs::Permissions::from_mode(0o755)).unwrap(); + let mut env = EnvGuard::new(); + env.sandbox(&root).set("PATH", bin.as_os_str()); + let (_app, webview) = launcher_app(mock_context(noop_assets())); + let together: Vec<_> = (0..4) + .map(|_| { + let webview = webview.clone(); + std::thread::spawn(move || call(&webview, APP_ORIGIN)) + }) + .collect(); + for request in together { + assert_eq!(request.join().unwrap(), Ok(serde_json::json!("path"))); + } + // And one a moment later, while it is still starting. + assert_eq!(call(&webview, APP_ORIGIN), Ok(serde_json::json!("path"))); + std::thread::sleep(Duration::from_millis(500)); + let starts = std::fs::read_to_string(&log).unwrap_or_default(); + assert_eq!(starts.lines().count(), 1, "Spotify was started {starts:?}"); +} From 34ae9f1c5e3f00afe5f560777b3e53000de03461 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:39:28 +0000 Subject: [PATCH 30/41] test(shell): tooltip clipping at the edge, and malformed command arguments The tray tooltip keeps an emoji that ends exactly on the 120-unit limit and drops one that would cross it, and counts UTF-16 units, not bytes. Every command that takes arguments refuses ones of the wrong shape with an error, and the app goes on answering. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- src-tauri/src/tray.rs | 8 ++++ src-tauri/tests/remote_origins_ipc.rs | 63 ++++++++++++++++++++++++++- 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/src-tauri/src/tray.rs b/src-tauri/src/tray.rs index 126662b..60e9226 100644 --- a/src-tauri/src/tray.rs +++ b/src-tauri/src/tray.rs @@ -100,5 +100,13 @@ mod tests { // Never half a pair: one unit short of a whole emoji leaves it out. let odd = clip_tooltip(&format!("a{}", "🎵".repeat(100))); assert_eq!(odd.encode_utf16().count(), MAX_TOOLTIP - 1); + // At the edge: an emoji that ends exactly on the limit stays, one past it goes. + let fits = format!("{}🎵", "a".repeat(MAX_TOOLTIP - 2)); + assert_eq!(clip_tooltip(&fits), fits); + let over = format!("{}🎵", "a".repeat(MAX_TOOLTIP - 1)); + assert_eq!(clip_tooltip(&over), "a".repeat(MAX_TOOLTIP - 1)); + // Units, not bytes: "€" is three bytes but one unit. + assert_eq!(clip_tooltip(&"€".repeat(200)), "€".repeat(MAX_TOOLTIP)); + assert_eq!(clip_tooltip(""), ""); } } diff --git a/src-tauri/tests/remote_origins_ipc.rs b/src-tauri/tests/remote_origins_ipc.rs index f45ab36..155954a 100644 --- a/src-tauri/tests/remote_origins_ipc.rs +++ b/src-tauri/tests/remote_origins_ipc.rs @@ -2,7 +2,8 @@ //! Tauri's IPC layer with the shipped tauri.conf.json and capabilities: only the app's own pages //! may call them. A page from anywhere else (a site the WebView were ever sent to, Spotify's own, //! a local server) is refused before the command runs, so it can't start a sign-in listener, -//! read or erase the listening history, start a program or change the window. +//! read or erase the listening history, start a program or change the window. Arguments of the +//! wrong shape are refused too, with an error rather than a crash. mod common; @@ -86,3 +87,63 @@ fn no_command_answers_a_page_from_another_origin() { ) .expect("cancelling with no sign-in running is fine"); } + +#[test] +fn arguments_of_the_wrong_shape_are_refused() { + let context: tauri::Context<MockRuntime> = + tauri::generate_context!(test = true, assets = noop_assets()); + let (_app, webview) = open_main(spotify_stats_lib::with_commands(mock_builder()), context); + let change = serde_json::json!({ "replace": true, "insert": [], "delete": [], + "meta": { "sources": [], "podcastMs": 0, "podcastPlays": 0, "updatedAt": 1 } }); + let bad: Vec<(&str, serde_json::Value)> = vec![ + ("oauth_listen", serde_json::json!({})), + ( + "oauth_listen", + serde_json::json!({ "port": "43821", "expectedState": "s" }), + ), + ( + "oauth_listen", + serde_json::json!({ "port": 65_536, "expectedState": "s" }), + ), + ( + "oauth_listen", + serde_json::json!({ "port": 43_821, "expectedState": null }), + ), + ("set_tray_tooltip", serde_json::json!({})), + ("set_tray_tooltip", serde_json::json!({ "text": 5 })), + ("set_tray_tooltip", serde_json::json!({ "text": ["Song"] })), + ("history_load", serde_json::json!({})), + ( + "history_load", + serde_json::json!({ "owner": { "id": "me" } }), + ), + ("history_delete", serde_json::json!({ "owner": null })), + ("history_apply", serde_json::json!({ "owner": "me" })), + ( + "history_apply", + serde_json::json!({ "owner": "me", "change": {} }), + ), + ( + "history_apply", + serde_json::json!({ "owner": 1, "change": change }), + ), + ( + "history_apply", + serde_json::json!({ "owner": "me", "change": { "replace": true } }), + ), + ( + "window_set_material", + serde_json::json!({ "material": "glass", "reassert": false }), + ), + ]; + for (cmd, args) in bad { + let answer = get_ipc_response(&webview, invoke_request(APP_ORIGIN, cmd, args.clone())); + assert!(answer.is_err(), "{cmd} accepted {args}"); + } + // The app goes on answering. + get_ipc_response( + &webview, + invoke_request(APP_ORIGIN, "app_info", serde_json::json!({})), + ) + .expect("the app still answers"); +} From 82c6b999c0be8196d1b7db38ce635f11c3b1b374 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:41:46 +0000 Subject: [PATCH 31/41] docs: match the faster CI in CONTRIBUTING and RELEASING CI runs on pull requests and main (not feature/** pushes), skips the end-to-end tests for docs-only changes and the Rust checks for changes outside src-tauri/, builds installers on pull requests only when they touch the desktop build, and names its failure artifacts e2e-failures-<n>. Release dry runs come from pull requests only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- CONTRIBUTING.md | 13 ++++++++----- docs/RELEASING.md | 2 +- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9574e64..a5574c5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -38,7 +38,7 @@ every page works offline. To sign in with your own account, see Work on a branch named `feature/<short-name>` in kebab-case, whatever the change is (`feature/year-in-review`, `feature/fix-tray-tooltip`, `feature/docs-database`). CI runs on every -push to `feature/**` and on every pull request. +pull request and on `main`; you can also start it by hand from the Actions tab. ## Commits @@ -86,12 +86,15 @@ release notes group changes by those labels; the maintainer may adjust them. **What CI checks.** Every pull request runs: - **CI:** typecheck, lint, unit tests, the build, the end-to-end tests at three screen sizes with - axe accessibility checks, and `cargo fmt`, `clippy` and `cargo test`. -- **Desktop app** (when the app's code changes): the installers build on Windows, Linux and macOS. - Each run's installers can be downloaded from its page, handy for testing a pull request. + axe accessibility checks (split across parallel jobs), and `cargo fmt`, `clippy` and + `cargo test`. Changes only to docs skip the end-to-end tests, and changes outside `src-tauri/` + skip the Rust checks. +- **Desktop app** (when a pull request changes `src-tauri/`, dependencies or the build): the + installers build on Windows, Linux and macOS, and can be downloaded from the run's page, handy + for testing. - **CodeQL:** security scanning of the TypeScript, the Rust and the workflows. -All of them must pass before merging. If an end-to-end test fails, the run's `e2e-failures` +All of them must pass before merging. If an end-to-end test fails, that job's `e2e-failures-<n>` artifact has screenshots of the failure. [Continuous integration](docs/DEVELOPMENT.md#continuous-integration) lists every workflow. diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 9d4b668..bf65099 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -140,7 +140,7 @@ their own, and the app asks for it on first run. ## Trying the pipeline The Release workflow does a **dry run**, building and packaging everything without releasing, -when a pull request or a push to a `feature/**` branch changes it or the version script. You can +when a pull request changes it or the version script. You can also start one from **Actions → Release → Run workflow** on any branch. The run's `release` artifact holds exactly the files a release would have. Started from a tag instead of a branch, it releases that tag. Release on main only runs on `main`; all it does itself is read the version From 5071e286674d71f319f5a779d817f139dec2a255 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:50:20 +0000 Subject: [PATCH 32/41] test(history): a database in a folder whose name isn't Unicode A home folder named in another encoding (Linux paths are bytes) still holds a database that saves and loads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- src-tauri/src/history.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src-tauri/src/history.rs b/src-tauri/src/history.rs index cacaa0b..2580924 100644 --- a/src-tauri/src/history.rs +++ b/src-tauri/src/history.rs @@ -1391,6 +1391,23 @@ mod tests { std::fs::remove_dir_all(&dir).ok(); } + /// A home folder named in another encoding still holds a working database. + #[cfg(target_os = "linux")] + #[test] + fn opens_a_file_in_a_folder_whose_name_is_not_unicode() { + use std::os::unix::ffi::OsStrExt; + let name = [b"ss-caf\xe9-", std::process::id().to_string().as_bytes()].concat(); + let dir = std::env::temp_dir().join(std::ffi::OsStr::from_bytes(&name)); + let db = HistoryDb::new(); + db.set_path(dir.join(FILE_NAME)); + let saved = db.with(|conn| apply(conn, "me", &change(true, vec![row(T0, "a", 0)], vec![]))); + assert_eq!(saved, Ok(1)); + let (_, ts, ..) = decode(&db.with(|conn| load(conn, "me")).unwrap()); + assert_eq!(ts.len(), 1); + db.close(); + std::fs::remove_dir_all(&dir).ok(); + } + /// Erasing an account leaves none of its history in the database's files, the /// write-ahead log included, while the app keeps the database open. #[test] From 00ba52ef44a5014a25eb09f3c2c3410789eeecf4 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:52:15 +0000 Subject: [PATCH 33/41] docs(agents): the desktop binary is about 6 MB with Tauri 2.13 Measured at 6.2 MB for the Linux release build after the move to Tauri 2.13 and the new GTK bindings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 0c530b2..46338dc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -971,7 +971,7 @@ Linux; check again when you touch these paths): | Full Insights on 300k plays | about 0.3 s, in a deferred render so controls stay responsive | | 10,000-track playlist | about 20 rows in the DOM (virtualised) | | Network while idle | one player poll every 5 s visible, 30 s hidden; history sync every 10 min | -| Desktop release binary | about 5 MB (LTO, `opt-level = "s"`, stripped) | +| Desktop release binary | about 6 MB on Linux with Tauri 2.13 (LTO, `opt-level = "s"`, stripped) | | Idle CPU | effectively zero once the UI settles; WebGL waves at most 24 fps, paused when hidden | ## Gotchas From 10e218a4dcedb0615250244dcb28f562db8f1a17 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:06:21 +0000 Subject: [PATCH 34/41] fix(history): finish erasing when an earlier erase stopped half-way An erase that deleted the plays but then failed to compact the file and empty the write-ahead log (a full disk, another program writing) is reported, and "Sign out and erase data" offers to try again. The retry found nothing left to delete and returned at once, so it said the history was gone while the erased plays were still readable in the file's free space and in the log. Erasing now always compacts the file and empties the log, as it did before the shortcut for accounts with nothing stored. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- src-tauri/src/history.rs | 55 +++++++++++++++++++++++++++++++--------- 1 file changed, 43 insertions(+), 12 deletions(-) diff --git a/src-tauri/src/history.rs b/src-tauri/src/history.rs index 2580924..de19d9f 100644 --- a/src-tauri/src/history.rs +++ b/src-tauri/src/history.rs @@ -738,12 +738,13 @@ fn erase(conn: &mut Connection, owner: &str) -> rusqlite::Result<bool> { fn delete(conn: &mut Connection, owner: &str) -> Result<(), String> { check_owner(owner)?; - if !erase(conn, owner).map_err(db_error)? { - return Ok(()); - } + erase(conn, owner).map_err(db_error)?; // Give the space back and leave nothing of the erased history in the files: VACUUM // rewrites the database without its free pages, and the checkpoint copies that into the - // file and empties the write-ahead log, which still holds the erased plays' pages. + // file and empties the write-ahead log, which still holds the erased plays' pages. Even + // when there was nothing left to erase: an earlier erase may have deleted the plays and + // then failed here (a full disk, another program writing), and trying again is how the + // UI finishes it. conn.execute_batch("VACUUM; PRAGMA wal_checkpoint(TRUNCATE);") .map_err(db_error) } @@ -1408,6 +1409,16 @@ mod tests { std::fs::remove_dir_all(&dir).ok(); } + /// The database file or its write-ahead log that still holds `secret`, if either does. + fn file_holding(path: &Path, secret: &str) -> Option<PathBuf> { + [path.to_path_buf(), path.with_extension("sqlite3-wal")] + .into_iter() + .find(|file| { + let bytes = std::fs::read(file).unwrap_or_default(); + bytes.windows(secret.len()).any(|w| w == secret.as_bytes()) + }) + } + /// Erasing an account leaves none of its history in the database's files, the /// write-ahead log included, while the app keeps the database open. #[test] @@ -1422,14 +1433,34 @@ mod tests { .collect(); apply(&mut conn, "me", &change(true, plays, vec![])).unwrap(); delete(&mut conn, "me").unwrap(); - for file in [path.clone(), path.with_extension("sqlite3-wal")] { - let bytes = std::fs::read(&file).unwrap_or_default(); - assert!( - !bytes.windows(secret.len()).any(|w| w == secret.as_bytes()), - "{} still holds erased plays", - file.display() - ); - } + assert_eq!(file_holding(&path, secret), None, "erased plays are left"); + drop(conn); + std::fs::remove_dir_all(&dir).ok(); + } + + /// An erase whose clean-up failed after the plays were deleted (the disk full, another + /// program writing) reports the failure, and the UI offers to try again. The retry finds + /// nothing left to delete, but must still clean up what the first one left in the files. + #[test] + fn erasing_again_cleans_up_what_a_failed_erase_left() { + let dir = std::env::temp_dir().join(format!("ss-erase-retry-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(FILE_NAME); + let mut conn = open(&path).unwrap(); + let secret = "Erase me on the second try"; + let plays = (0..2_000) + .map(|i| row(T0 + i, &format!("{secret} {i}"), 0)) + .collect(); + apply(&mut conn, "me", &change(true, plays, vec![])).unwrap(); + // The first attempt: its plays are gone, its clean-up never ran. + assert!(erase(&mut conn, "me").unwrap()); + assert!(load(&conn, "me").unwrap().is_empty()); + assert!( + file_holding(&path, secret).is_some(), + "the test starts with erased plays left in the files" + ); + delete(&mut conn, "me").unwrap(); + assert_eq!(file_holding(&path, secret), None, "erased plays are left"); drop(conn); std::fs::remove_dir_all(&dir).ok(); } From cda0c01b4585265fee68781d3fd5589124be6b74 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:07:08 +0000 Subject: [PATCH 35/41] ci: count a moved file at both of its paths when choosing the checks "What changed" listed each changed file with git diff --name-only, which reports a moved file at its new path only. Moving a file out of src-tauri/ (into docs/, say) skipped the Rust checks, and the skipped "Desktop shell (Rust)" counted as passed for a build that may no longer compile; moving one out of app/ into docs/ skipped the end-to-end tests. --no-renames lists the old path as deleted and the new one as added. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- .github/workflows/ci.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a3f2536..e62b9be 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -63,9 +63,11 @@ jobs: checks=false e2e=false rust=false # Anything this can't work out (a run by hand or from another workflow, a new branch, a # base it can't fetch) runs everything. + # --no-renames lists a moved file at both paths: a file moved out of src-tauri/ changes + # the Rust build as much as one deleted there. elif [[ -z "$RUN" && "$EVENT" =~ ^(push|pull_request)$ && "$BASE" =~ ^[0-9a-f]{40}$ && ! "$BASE" =~ ^0+$ ]] && git fetch --quiet --no-tags --depth=1 origin "$BASE" && - files=$(git diff --name-only "$BASE" "$GITHUB_SHA"); then + files=$(git diff --name-only --no-renames "$BASE" "$GITHUB_SHA"); then echo "Changed files:" echo "$files" # Markdown, docs/, the licence and the repository's settings in .github/ can't change From 0d487d4e2ff456e0839e899603f329827964ffac Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:08:25 +0000 Subject: [PATCH 36/41] test(settings): read the transparent background's description as screen readers do The test found the description by walking from the switch to its row's text, which held the label too and would follow any change to the row's markup. It now checks the switch's accessible description, the whole sentence for each build, and that the window material control shows only where its description points to it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- app/pages/Settings.test.tsx | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/app/pages/Settings.test.tsx b/app/pages/Settings.test.tsx index 68c8228..6d06916 100644 --- a/app/pages/Settings.test.tsx +++ b/app/pages/Settings.test.tsx @@ -41,19 +41,20 @@ describe("Settings", () => { }); it("describes the transparent background for the build it's in: materials only on Windows", () => { - const description = () => screen.getByRole("switch", { name: "Transparent background" }).closest("[class]")?.parentElement?.textContent ?? ""; + const toggle = () => screen.getByRole("switch", { name: "Transparent background" }); const { unmount } = renderWithProviders(<Settings />); - expect(description()).toContain("soft glow from your current track's artwork"); + expect(toggle()).toHaveAccessibleDescription("Let a soft glow from your current track's artwork show through."); unmount(); build.desktop = true; const mac = renderWithProviders(<Settings />); - expect(description()).toContain("Let your desktop show through the window."); - expect(description()).not.toMatch(/frosted|Windows/); + expect(toggle()).toHaveAccessibleDescription("Let your desktop show through the window."); + expect(screen.queryByRole("radiogroup", { name: "Window material" })).not.toBeInTheDocument(); mac.unmount(); build.materials = true; renderWithProviders(<Settings />); - expect(description()).toContain("window material below"); + expect(toggle()).toHaveAccessibleDescription(/window material below\.$/); + expect(screen.getByRole("radiogroup", { name: "Window material" })).toBeInTheDocument(); }); }); From 973052053677458fcb0c4d9ef30af4ceed4312fb Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:10:13 +0000 Subject: [PATCH 37/41] test(oauth): a callback that arrives in pieces is read whole The listener reads a request's headers in chunks and looks for the blank line that ends them across chunk boundaries. No test sent the genuine callback in pieces with that blank line split between two reads; one does now (it fails if the search drops the overlap). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- src-tauri/src/oauth.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src-tauri/src/oauth.rs b/src-tauri/src/oauth.rs index 8670dd2..292b0ff 100644 --- a/src-tauri/src/oauth.rs +++ b/src-tauri/src/oauth.rs @@ -793,6 +793,31 @@ mod tests { drop((idle, trickle)); } + /// A request that arrives in pieces, the blank line that ends it split between two of + /// them, is read whole. + #[test] + fn a_request_sent_in_pieces_is_read_whole() { + let running = start("s3cret", Duration::from_secs(30)); + let port = running.port; + let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(15))) + .unwrap(); + let request = format!( + "GET /callback?code=abc&state=s3cret HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n\r\n" + ); + let (head, last) = request.split_at(request.len() - 3); + for piece in [&head[..10], &head[10..], last] { + stream.write_all(piece.as_bytes()).unwrap(); + stream.flush().unwrap(); + std::thread::sleep(Duration::from_millis(150)); + } + let mut page = String::new(); + stream.read_to_string(&mut page).unwrap(); + assert!(page.starts_with("HTTP/1.1 200 OK\r\n"), "{page}"); + assert!(running.handle.join().unwrap().is_some()); + } + #[test] fn an_oversized_request_is_refused_and_the_wait_goes_on() { let running = start("s3cret", Duration::from_secs(30)); From 8c44e3d037519508fa60482f0651127874904891 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:10:33 +0000 Subject: [PATCH 38/41] docs(database): quit from the tray before copying the history file The backup steps said to close the app, but with "Keep running in the tray" on, closing the window only hides it: the database stays open and its latest plays can still be in the write-ahead log. They now say to quit, from the tray menu if need be. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- docs/DATABASE.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/DATABASE.md b/docs/DATABASE.md index beda6b2..a2cb500 100644 --- a/docs/DATABASE.md +++ b/docs/DATABASE.md @@ -120,8 +120,9 @@ FROM plays WHERE ms_played >= 30000 GROUP BY day ORDER BY day; ## Backups and moving PCs -Close the app, then copy `listening-history.sqlite3`: as it quits, the app folds its write-ahead -log into that file. If `listening-history.sqlite3-wal` is there too (the app didn't get to quit +Quit Statsify (with **Keep running in the tray** on, closing the window only hides it: choose +**Quit** in the tray menu), then copy `listening-history.sqlite3`: as it quits, the app folds its +write-ahead log into that file. If `listening-history.sqlite3-wal` is there too (the app didn't get to quit normally), copy it as well. To restore, put the files back in the same folder before starting the app. You can also export a CSV of any period from the Streams page, or everything from the Import page. From d6bebc60f96a70a9a1ccd11d0ee77d6c9e5036ce Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:15:35 +0000 Subject: [PATCH 39/41] docs(release): a self-upgrading history schema is a minor release Going back to an older version then needs a backup from before the upgrade; a major version is for changes people must act on when they upgrade. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- docs/RELEASING.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/RELEASING.md b/docs/RELEASING.md index bf65099..6b985ee 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -9,10 +9,12 @@ release. Statsify follows [Semantic Versioning](https://semver.org/): - **Patch** (`1.2.1`): bug fixes only. -- **Minor** (`1.3.0`): new features. Older data (history, settings) keeps working. -- **Major** (`2.0.0`): a change people must act on, such as a history database that older versions - can no longer open (they refuse a newer schema rather than damage it; see - [DATABASE.md](DATABASE.md)). +- **Minor** (`1.3.0`): new features and improvements. Older data (history, settings) keeps + working. A new history schema that upgrades itself counts here, even though older versions then + refuse the file (they never damage a newer schema; see [DATABASE.md](DATABASE.md)): going back + to an older version needs a backup from before the upgrade. +- **Major** (`2.0.0`): a change people must act on when they upgrade, such as data that doesn't + carry over or a system that's no longer supported. - **Pre-release** (`1.3.0-beta.1`, `1.3.0-rc.1`): for testing before a release. Marked as a pre-release on GitHub, so it never becomes "latest". From 2391ddb1a4ea305cc0011bd039462e96a4608901 Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:15:37 +0000 Subject: [PATCH 40/41] chore(release): 1.2.0 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- package-lock.json | 4 ++-- package.json | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index 69f4e2f..f811a4a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "statsify", - "version": "1.1.1", + "version": "1.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "statsify", - "version": "1.1.1", + "version": "1.2.0", "license": "Apache-2.0", "dependencies": { "@fontsource-variable/figtree": "5.3.0", diff --git a/package.json b/package.json index 615c1b3..1a35743 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "statsify", "private": true, - "version": "1.1.1", + "version": "1.2.0", "description": "Your Spotify listening stats, library and player in one place. Web app and Windows/macOS/Linux desktop app (Tauri).", "keywords": [ "spotify", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 191fd28..0fd9fd6 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -3183,7 +3183,7 @@ dependencies = [ [[package]] name = "spotify-stats" -version = "1.1.1" +version = "1.2.0" dependencies = [ "rusqlite", "serde", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index d8972ab..c357d2c 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "spotify-stats" -version = "1.1.1" +version = "1.2.0" description = "Statsify: your listening stats, library and player controls on the desktop." authors = ["Kkkermit"] license = "Apache-2.0" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 0b6422f..05c8b41 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Statsify", - "version": "1.1.1", + "version": "1.2.0", "identifier": "com.kkkermit.spotifystats", "build": { "beforeDevCommand": "npm run dev", From 73db7ac3d801604e18798dae9189eb156698b33c Mon Sep 17 00:00:00 2001 From: Kkkermit <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:25:07 +0000 Subject: [PATCH 41/41] test(oauth): keep the listener's responses out of assertion messages Three tests printed the HTTP response read from the socket when an assertion failed, which CodeQL reports as log injection (alerts 11-13). They now say what was wrong in their own words. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TCk6t7edJdscNtTSeFmyQN --- src-tauri/src/oauth.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src-tauri/src/oauth.rs b/src-tauri/src/oauth.rs index 292b0ff..b671ae0 100644 --- a/src-tauri/src/oauth.rs +++ b/src-tauri/src/oauth.rs @@ -678,8 +678,15 @@ mod tests { .unwrap(); let mut page = String::new(); done.read_to_string(&mut page).unwrap(); - assert!(page.starts_with("HTTP/1.1 200 OK\r\n"), "{page}"); - assert!(page.contains("\r\nCache-Control: no-store\r\n"), "{page}"); + // The messages don't echo the response: it's data from a socket, kept out of test logs. + assert!( + page.starts_with("HTTP/1.1 200 OK\r\n"), + "the callback wasn't answered with 200 OK" + ); + assert!( + page.contains("\r\nCache-Control: no-store\r\n"), + "the sign-in page can be cached" + ); assert!(page.ends_with(DONE_PAGE)); let url = running.handle.join().unwrap(); assert_eq!( @@ -814,7 +821,10 @@ mod tests { } let mut page = String::new(); stream.read_to_string(&mut page).unwrap(); - assert!(page.starts_with("HTTP/1.1 200 OK\r\n"), "{page}"); + assert!( + page.starts_with("HTTP/1.1 200 OK\r\n"), + "a callback sent in pieces wasn't answered with 200 OK" + ); assert!(running.handle.join().unwrap().is_some()); }