Compare commits

...
Author SHA1 Message Date
sudacode 4a78b946d9 fix(stats): address review findings on franchise walk and group view
- The relation walk keeps every incoming link to an entry and follows it when
  any link is accepted, so a veto on one seed no longer hides a franchise root
  reached through another (and seed order no longer changes the result).
- A stopped refresher starts no further AniList request; the in-flight result
  is dropped and the walk ends.
- An open franchise that is left with one part closes once the library has
  loaded, so a later refresh cannot reopen it on its own.
2026-11-22 14:37:03 -08:00
sudacode 55110fd592 docs(stats): note schema 27 in the immersion schema version comment 2026-11-22 02:34:05 -08:00
sudacode 2edf56541c feat(stats): group library seasons, movies and OVAs into franchise cards
The stats library now lists each anime once. Grouping is a view over
imm_anime rows computed from a cached AniList relation graph; no rows are
merged and identity keys are unchanged.

- Schema 27: imm_anilist_media + imm_anilist_relations cache every AniList
  entry reached from the library and all its anime edges. A background
  refresher walks from owned AniList ids (depth 6, 250 fetches per run,
  7-day staleness) through the shared AniList rate limiter; a failed fetch
  leaves cached rows untouched.
- FRANCHISE_RELATION_TYPES (PREQUEL, SEQUEL, PARENT, SIDE_STORY, SUMMARY,
  COMPILATION, CONTAINS) joins entries; an entry that names the other only
  through an excluded type (a spin-off's original) vetoes the join.
- GET /api/stats/anime/groups returns cards with summed totals, the root
  entry's title, and parts in release order. Entries without cached
  relations stay single cards identical to before.
- imm_anime.group_override (NULL = AniList, 0 = on its own, positive =
  join the franchise containing that AniList id) with
  PUT /api/stats/anime/:id/group and Move to Another Anime / Show On Its
  Own / Put Back Where AniList Has It on the title page.
- SSH sync merges the override last-writer-wins on
  group_override_updated_at and skips the rebuildable relation cache.
2026-11-22 02:33:44 -08:00
sudacode 0ae70b4ab2 fix(overlay): keep forwarding mpv keys after a Yomitan popup closes (#332)
Decide whether the Yomitan popup is open from the popup host in the DOM
instead of the cached yomitanPopupVisible flag, which can lag a close and
kept input.conf keys from reaching mpv.

Keep the imported mpv key list in place while a refresh is in flight, so a
key pressed right after the overlay regains focus is not dropped. A failed
reload still clears the list.

At --log-level debug, log why the overlay kept an mpv-bound key
(config-loading, modal, lookup-popup, interactive-target or
no-imported-bindings) over a validated IPC channel.

Refs #331
2026-11-20 18:27:11 -08:00
sudacode 0c1865f4a6 chore(release): prepare v0.22.1-beta.1 2026-11-06 19:07:54 -08:00
sudacode 6fd55053d4 fix(overlay): identify Windows mpv windows through IPC PID (#330) 2026-11-06 18:37:44 -08:00
74 changed files with 3609 additions and 477 deletions

No files matched your search

+3
View File
@@ -32,6 +32,9 @@ jobs:
- name: Verify native mpv process launch
run: bun test src/main/runtime/mpv-process.test.ts
- name: Verify mpv PID lookup and Windows tracker
run: bun test src/window-trackers/mpv-process-id.test.ts src/window-trackers/windows-tracker.test.ts
- name: Verify POSIX launcher bootstrap
run: bun test src/main/runtime/posix-launcher-bootstrap.test.ts
+5
View File
@@ -0,0 +1,5 @@
type: added
area: stats
- Library lists each anime once: seasons, movies, and OVAs that AniList links as sequels, prequels, side stories, summaries, or compilations share one card, named after the first TV series. Opening it lists the parts in release order with their own stats. Spin-offs and alternative versions keep their own cards.
- A title's page has **Move to Another Anime…**, **Show On Its Own**, and **Put Back Where AniList Has It** to correct the grouping. `subminer sync` keeps the most recent choice.
+6
View File
@@ -0,0 +1,6 @@
type: fixed
area: overlay
- mpv keys from `input.conf` (for example arrow keys bound to `sub-seek`) are no longer sent to a Yomitan popup that has already closed. The overlay decided whether the popup was open from a cached flag that could lag behind a close.
- mpv keys no longer get dropped while the overlay reloads mpv's bindings after it regains focus.
- With `--log-level debug`, the log names why the overlay kept an mpv-bound key instead of forwarding it.
@@ -0,0 +1,4 @@
type: docs
area: overlay
- Explain how to collect and interpret Windows overlay attachment and readiness warnings without enabling debug logging.
@@ -0,0 +1,6 @@
type: fixed
area: overlay
- Windows overlay attachment now identifies mpv through its IPC process ID, removing the dependency on PowerShell command-line lookups and allowing the IPC socket to be configured in `mpv.conf`.
- Revalidate cached Windows mpv process IDs and expire them after sustained IPC failures so PID reuse cannot keep the overlay attached to an unrelated window.
- Diagnose stalled Windows overlays at the default warn log level, including tracking/PID state, renderer readiness, opacity, native binding errors, and recovery, with repeated warnings rate limited.
+6 -2
View File
@@ -50,11 +50,15 @@ Deleting a session or session group refreshes the Overview totals, charts, calen
Your shows as cover-art cards with search, sorting, per-series progress, and an episode list linking to mined cards. The **All Titles** / **Anime** / **Live Action** / **YouTube** selector filters the grid. YouTube videos are grouped by channel.
Seasons get separate cards when a season number is detected. Live-action titles that AniList cannot match are looked up on [TMDB](/configuration#tmdb). If a title gets no match, open it and use **Link to TMDB** to pick one by hand.
Seasons, movies, and OVAs of one anime share a card. SubMiner follows AniList's sequel, prequel, parent, side-story, summary, and compilation links, including through entries you have not watched, so two films can meet at a TV series you never played. Spin-offs and alternative versions keep their own cards. A shared card is named after the anime's first TV series, shows the cover of the earliest part you have, and opens to a list of its parts in release order. Relations come from AniList in the background and refresh weekly, so a newly linked show can take a minute to join its card.
If a part lands on the wrong card, open it and choose **Move to Another Anime…** (the target must be linked to AniList) or **Show On Its Own**. **Put Back Where AniList Has It** undoes either. This only changes how the library is listed; duplicate entries for the same season still need a merge.
Live-action titles that AniList cannot match are looked up on [TMDB](/configuration#tmdb). If a title gets no match, open it and use **Link to TMDB** to pick one by hand.
The same show can end up on several cards when release names disagree. To fix that:
- Merge: click **Select**, tick the duplicate cards, choose **Merge Selected**, and pick the entry to keep. Sessions, cards, and watch time move over, and future episodes with those names join the kept entry.
- Merge: click **Select** (the grid then lists every entry on its own), tick the duplicate cards, choose **Merge Selected**, and pick the entry to keep. Sessions, cards, and watch time move over, and future episodes with those names join the kept entry.
- Move one episode: hover its row in the episode list and click **→** to assign it to another entry. SubMiner remembers the correction.
- Suggested merges appear as **Possible duplicate** above the grid. Choose **Review merge** or **Not duplicates**.
+1 -1
View File
@@ -145,7 +145,7 @@ subminer sync macbook --remote-cmd ~/Apps/SubMiner.AppImage # SubMiner in a cu
subminer sync --ui # open the sync window
```
Syncing only adds data. It never overwrites or double-counts, so you can run it as often as you like. `--push` and `--pull` do not delete anything on the receiving side.
Syncing only adds data. It never overwrites or double-counts, so you can run it as often as you like. The one setting it carries is a library title's anime card choice (**Move to Another Anime…**), where the most recent change wins. `--push` and `--pull` do not delete anything on the receiving side.
Before a command-line sync, close SubMiner on both machines and stop the stats server with `subminer stats -s`, or pass `--force`. The sync window does not need this. It syncs while SubMiner and playback are running, and skips the session in progress until it finishes.
+15
View File
@@ -51,6 +51,17 @@ When `connect ENOENT /tmp/subminer-socket` follows a cast in the app log, SubMin
- Confirm SubMiner is running (`SubMiner.AppImage --start`, or check for the process).
- Linux: Hyprland and Sway work natively. Any other compositor needs mpv and SubMiner under X11 or Xwayland, with `xdotool`, `xprop`, and `xwininfo` installed. See [KDE Plasma and other Wayland compositors](#kde-plasma-and-other-wayland-compositors).
- macOS: grant Accessibility permission. See [macOS](#macos).
- Windows: leave the affected mpv window open for at least five seconds, then collect the daily
app log from the directory above. No debug setting is required: a stalled overlay logs
`Windows overlay is not visible after startup or tracking loss` with its PID, native window
handle, tracking state, geometry, opacity, and renderer readiness. The `reason` distinguishes
a missing mpv window, an unready renderer, a hidden window, and a transparent window.
This warning waits until mpv has answered on its IPC socket, so a requested overlay with no
mpv running stays quiet. PID lookup failures and native ownership or transparency errors also
appear at `warn`, and a PID lookup failure is the only trace if mpv never answers.
Repeated visibility/native-operation warnings are limited to one every 30 seconds; recovery
is recorded too. These logs diagnose attachment and readiness, but cannot prove that pixels
were drawn correctly by the graphics driver.
## Overlay is on the wrong monitor or position
@@ -179,6 +190,10 @@ Another app or your desktop already uses `Alt+Shift+Y` (Yomitan settings). Free
Overlay shortcuts only work while the overlay has focus. Click the overlay, or press `Alt+Shift+O` with mpv or the overlay focused.
## An mpv key does nothing over the overlay
Keys from `input.conf` reach mpv through the overlay only in some cases (see [automatic mpv bindings](/shortcuts#automatic-mpv-bindings)). Run with `--log-level debug` and press the key: an `Overlay kept an mpv-bound key` line names the reason. To make a key work everywhere, add it to [`keybindings`](/configuration#keybindings) instead.
## Update checks
**"Update check failed"**: GitHub could not be reached. Check your connection and retry from the tray menu or with `subminer -u`.
+12
View File
@@ -27,6 +27,16 @@ Read when: you need to find the owner module for a behavior or test surface
subtitle suppression while the overlay shows, and the overlay-window IPC handlers (modal
open/close, pointer interaction, content measurement): `src/main/assemblies/overlay.ts`
Overlay-hosted modal openers: `src/main/assemblies/overlay-modals.ts`
Windows window tracking: `src/window-trackers/windows-tracker.ts` queries the target mpv IPC
socket for its PID through `mpv-process-id.ts`, then `win32.ts` matches native windows by PID.
Visible matches are revalidated every 10 seconds; a PID expires after 30 seconds without a
successful IPC response. Missing windows retry at one-second intervals. Custom executable
names remain supported because matching uses the IPC PID.
`src/core/services/overlay-visibility-diagnostics.ts` watches requested Windows overlays:
after five seconds hidden or transparent it logs a warn-level snapshot, repeating at most
every 30 seconds. Intentional hiding, minimization and having no mpv answer on the socket
yet suppress these warnings; an identified mpv whose window never matches does not. PID lookup
failures and native ownership/transparency failures also log at warn, including recovery.
- MPV runtime and protocol: `src/core/services/mpv*.ts`
mpv client creation, mpv event wiring, AniSkip, the autoplay-ready gate that releases mpv's
startup pause, managed local subtitle selection, subtitle prefetch, and subtitle sidebar state:
@@ -54,8 +64,10 @@ Read when: you need to find the owner module for a behavior or test surface
the stats overlay window options, and the `--stats` command are assembled by `src/main/assemblies/stats.ts`
Includes stats storage/query schema such as `imm_videos`, `imm_media_art`, and `imm_youtube_videos` for per-video and YouTube-specific library metadata.
Library-entry identity aliases and merge recommendations are persisted alongside this schema; the stats HTTP and SPA layers only expose and present those domain decisions.
Franchise grouping is a view over `imm_anime`, never a merge: `query-library-groups.ts` groups library rows by union-find over the AniList relation cache (`imm_anilist_media` + `imm_anilist_relations`, written by `anilist-relation-cache.ts`; pure graph and walk in `anilist/franchise-graph.ts`, where `FRANCHISE_RELATION_TYPES` is the joining set). `franchise-relation-refresher.ts` walks from owned AniList ids (bounded depth and fetches per run, 7-day staleness, shared AniList rate limiter) when the grouped library is read, after cover art links an id, and after manual AniList or group changes; a failed fetch leaves cached rows untouched. `imm_anime.group_override` (NULL = AniList, 0 = on its own, positive = join the franchise containing that AniList id) is the only user state; `/api/stats/anime/groups` and `PUT /api/stats/anime/:id/group` expose it.
`delete-maintenance-scheduler.ts` coalesces and serializes stats deletes; the expensive work runs in `delete-maintenance-worker-thread.ts` while the tracker queues playback writes. Each batch uses one transaction, lexical update, rollup refresh, and incremental lifetime subtraction (`planLifetimeRemovals`/`applyLifetimeRemovals` in `lifetime.ts`). Merges, moves, AniList reassignments, and `stats cleanup -l` use `repairLifetimeSummariesFromMedia` (recompute from the per-video media ledger). The full lifetime rebuild survives only as the empty-table bootstrap; anywhere else it would collapse lifetime totals to the session retention window.
- Immersion sync: `src/core/services/stats-sync/`, bound by `src/main/sync-cli.ts`. The sync window and auto-sync scheduler live in `src/main/assemblies/sync.ts`.
`imm_anime.group_override` merges last-writer-wins on `group_override_updated_at` (clears carry a timestamp too); its values are AniList ids, so no id remapping. The AniList relation cache is not merged: each machine rebuilds it, and stale or partial remote cache rows would otherwise outlive the 7-day refresh.
`snapshot-transfer.ts` selects compressed rsync or scp. `transfer-cache.ts` atomically retains the last successfully received snapshot per hashed peer/database identity under the config directory's `sync-transfer-cache/`. Cache copies seed isolated transfer directories; rsync verifies reconstructed files before the existing merge engine runs. The `--make-temp` / `--remove-temp` helpers accept an internal `--transfer-cache` key, with a fallback for older peers that do not recognize it.
- AniList tracking + character dictionary: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*` (called by `src/main/assemblies/anilist.ts`), `src/main/character-dictionary-runtime.ts`, `src/main/character-dictionary-runtime/`, assembled by `src/main/assemblies/character-dictionary.ts`
- TMDB live-action metadata: `src/core/services/tmdb/` (client + exact-title resolver), `src/core/services/immersion-tracker/live-action-link.ts` (links an entry to a TMDB title and merges other holders of the same title). The AniList cover-art fetcher calls the resolver as its fallback; `imm_anime.media_kind` marks the result and keeps the entry out of AniList season repair.
+39
View File
@@ -114,6 +114,45 @@ test(
},
);
// The other tests read the renderer over CDP, which works even if the window never appears.
// Windows keeps the overlay hidden until the tracker identifies mpv's window.
// Bun's node:test ignores the `skip` option, so this picks `test.skip` instead.
const testOnWindows = process.platform === 'win32' ? test : test.skip;
testOnWindows('visible overlay window appears over mpv', { timeout: TEST_TIMEOUT_MS }, async () => {
const { session } = await useSession();
await session.runAppCommand('--show-visible-overlay');
const mpvPid = await session.mpv.command('get_property', 'pid');
assert.equal(typeof mpvPid, 'number');
const main = await session.mainProcess();
await waitUntil(
() =>
main.evaluate<boolean>(
`(() => {
const electron = process.mainModule.require('electron');
const overlay = electron.BrowserWindow.getAllWindows().find(
(w) => w.webContents.getURL().includes(${JSON.stringify(OVERLAY_PAGE)}));
if (!overlay?.isVisible() || overlay.getOpacity() !== 1 ||
overlay.__subminerOverlayContentReady !== true) return false;
// The inspector's mainModule can be Electron's bootstrap module. Resolve app
// dependencies from the repository instead of that module's search paths.
const appRequire = process.mainModule.require('node:module').createRequire(
process.mainModule.require('node:path').resolve('package.json'));
const koffi = appRequire('koffi');
const getWindow = koffi.load('user32.dll').func(
'intptr __stdcall GetWindow(intptr hwnd, uint uCmd)');
const handle = overlay.getNativeWindowHandle();
const hwnd = handle.length >= 8 ? Number(handle.readBigUInt64LE(0)) : handle.readUInt32LE(0);
const owner = getWindow(hwnd, 4); // GW_OWNER
const win32 = appRequire(
process.mainModule.require('node:path').resolve('dist/window-trackers/win32.js'));
return win32.findMpvWindows(${JSON.stringify(mpvPid)}).matches.some(
(match) => match.hwnd === owner);
})()`,
),
{ description: 'the visible overlay to be fully revealed and owned by the target mpv window' },
);
});
test(
'seeking to another cue replaces the line and deinflects verbs to their headword',
{ timeout: TEST_TIMEOUT_MS },
+3 -1
View File
@@ -25,7 +25,9 @@ export const IMMERSION_DB_FIXTURE_DDL = `
tmdb_type TEXT,
metadata_json TEXT,
CREATED_DATE TEXT,
LAST_UPDATE_DATE TEXT
LAST_UPDATE_DATE TEXT,
group_override INTEGER,
group_override_updated_at TEXT
);
CREATE UNIQUE INDEX idx_anime_namespace_title ON imm_anime((media_kind = 'youtube'), normalized_title_key);
CREATE TABLE imm_videos(
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "subminer",
"productName": "SubMiner",
"desktopName": "SubMiner.desktop",
"version": "0.22.0",
"version": "0.22.1-beta.1",
"description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration",
"packageManager": "bun@1.3.5",
"main": "dist/main-entry.js",
+8 -75
View File
@@ -1,88 +1,21 @@
> This is a prerelease build for testing. Stable changelog and docs-site updates remain pending until the final stable release.
<!-- prerelease-version: 0.20.1-beta.2; since: v0.20.1-beta.1 -->
## Changes since v0.20.1-beta.1
- Upgraded the desktop runtime to Electron 43.7.7.
- SubMiner now refuses to start on an unsupported Electron runtime, or after an Electron major or minor downgrade, so your Yomitan profile data stays safe; patch downgrades are still allowed.
- Automatic character-dictionary updates now stop if a Yomitan profile that had dictionaries suddenly reports none.
- Development launches now use a separate `SubMiner-dev` profile unless you explicitly ask for the production profile.
- Sentence mining (single and multi-line) no longer counts each card twice in session and lifetime stats.
- Deleting sessions now updates word and kanji "first seen" and "last seen" dates correctly, and retention pruning keeps historical discovery dates and counts.
- Words hidden by the vocabulary filter are no longer counted in the new-words charts, so the charts now match the vocabulary summary.
- A one-time background repair on next launch fixes stale "last seen" dates and existing chart mismatches.
- Overview totals, charts, the activity calendar, and the vocabulary summary now refresh after you delete sessions, and a failed refresh keeps the dashboard visible with a retry option.
- Subtitle generation now works during Windows YouTube playback and loads the generated subtitles into the playing video.
- On Windows, moving on to a video queued from the YouTube browser window no longer drops the rest of mpv's queue.
- The stats docs now cover the automatic Overview refresh after deletions and how discovery dates are kept through retention pruning.
<!-- prerelease-version: 0.22.1-beta.1 -->
## Highlights
### Added
- **YouTube Browser Window**:
- Open it with `subminer youtube` (or `subminer yt`), or pick **Browse YouTube** from the tray. It stays logged in across restarts.
- Clicking a video plays it in mpv. Middle-click, Shift-click, Ctrl-click, or the right-click menu adds it to mpv's playlist.
- Queued videos get the same Japanese subtitle setup when they start.
- Closing the window quits SubMiner if you started it with `subminer youtube`. If a video is still playing, SubMiner waits until mpv closes.
- **Whisper Subtitles for YouTube**:
- Set `youtube.subtitleSource` to `whisper` to make subtitles with Whisper instead of downloading YouTube's captions.
- The video stays paused while Whisper works, and progress shows in the subtitle generation modal. You can close the modal to keep watching, or cancel.
- The subtitle generation modal (`Ctrl+Shift+G`) now works on YouTube videos, including on Windows.
- **Mouse and Scroll Wheel Bindings**:
- You can now use scroll wheel keys (`WHEEL_UP`, `WHEEL_DOWN`, `WHEEL_LEFT`, `WHEEL_RIGHT`) in `keybindings` and record them in the settings key editor.
- mpv's mouse button and wheel bindings now work while the cursor is over the overlay. This matters most on Hyprland, where these bindings did nothing before.
- When a binding conflicts, SubMiner's own bindings and right-click pause take priority over mpv's.
- **Session Help Commands**: During playback, press `Enter` or double-click a row in session help to run that command. Hovering over a row makes it the target for `Enter`.
### Changed
- **Release Assets**: Releases no longer include package-size JSON reports.
### Fixed
- **Jellyfin Subtitles**:
- The Japanese track is selected, and annotations start, as soon as it downloads. SubMiner no longer waits for the other tracks.
- Japanese and English tracks are now picked automatically on episodes with image-based subtitles (PGS, DVD, DVB).
- If one track fails to download, the other tracks are still selected.
- **Jellyfin Audio Track**: On direct-play streams, timing review previews and mined card audio now use the audio track you're playing.
- **Media Timing Review**:
- Trim handles are now thin lines centered on the clip edges.
- Original subtitle boundaries are now plain orange bars with no labels.
- The preview cursor no longer stutters on macOS with Bluetooth headphones such as AirPods.
- **Hyprland Fullscreen**: The overlay stays visible when mpv enters or leaves fullscreen. With `mpv.backend: x11`, subtitles and the sidebar stay clickable after going fullscreen.
- **mpv Key Bindings in the Overlay**: mpv key bindings, such as `9`/`0` for volume, now work while the overlay has focus, even when the overlay loaded before mpv connected.
- **YouTube Japanese Subtitles**: Some videos also list a machine-translated Japanese track. On those, Japanese subtitles no longer fail with "HTTP 429". If YouTube refuses a direct download, SubMiner retries with yt-dlp.
- **Stats Accuracy**:
- Sentence mining no longer counts each card twice in session and lifetime stats.
- Overview totals, charts, the activity calendar, and the vocabulary summary now update after you delete sessions.
- Word and kanji dates stay correct after deleting sessions. New-word charts now match the vocabulary summary.
- **Dictionary Safety**: Automatic character dictionary changes now stop if a Yomitan profile that had dictionaries suddenly reports none. SubMiner also refuses to load Yomitan data after a downgrade to an older Electron version.
- **AppImage in Sandboxes**: The AppImage now opens its window in sandboxes that mount the image themselves, such as `firejail --appimage`.
- **Ctrl+C Crash**: Stopping the terminal command that started SubMiner with Ctrl+C no longer crashes it with a "write EPIPE" error.
- **Security Updates**: Electron is updated to 43.7.7 and undici to 7.29.1, which fixes known security advisories.
- **Windows Overlay**:
- The overlay now finds mpv more reliably, without relying on PowerShell lookups.
- You can now configure the IPC socket in `mpv.conf`.
- The overlay no longer stays attached to an unrelated window after mpv's process ID is reused.
- Stalled overlays now log diagnostic warnings without debug logging enabled.
### Docs
- **Docs Site Rewrite**: Pages are shorter and easier to scan. The configuration reference now has a short explanation and a table of keys and defaults for each config block. Pages that no longer matched current behavior are fixed.
- **Arch Linux Install**: The MeCab install command now uses the AUR package `mecab-git`. The README now matches the installation guide.
- **Stats**: The docs now cover the Overview refreshing after you delete sessions, and how first-seen dates are kept when old sessions are cleaned up.
- **Windows Overlay Troubleshooting**: Added a guide to collecting and interpreting overlay attachment and readiness warnings without debug logging.
## What's Changed
- fix(storage): protect Yomitan profiles across Electron runtime changes by @ksyasuda in #211
- fix(jellyfin): select subtitles faster and survive failed track downloads by @ksyasuda in #270
- fix(jellyfin): use the current audio track for media generation by @ksyasuda in #271
- feat(youtube): add YouTube browser window and Whisper subtitle source by @ksyasuda in #273
- fix(overlay): thin centered trim handles and label-free subtitle boundaries in timing review by @ksyasuda in #274
- feat(overlay): run session help commands with Enter or double-click by @ksyasuda in #275
- fix(overlay): keep overlay mapped during Hyprland/Sway fullscreen by @ksyasuda in #276
- fix(linux): skip AppImage mount keepalive on sandbox squashfs mounts by @ksyasuda in #277
- fix(overlay): reload imported mpv keys after mpv connects by @ksyasuda in #278
- feat(overlay): forward mpv mouse button and wheel bindings by @ksyasuda in #279
- fix(stats): count mined cards once and keep lexical stats exact after deletes by @ksyasuda in #280
- fix(youtube): keep mpv queue when advancing to a queued video on Windows by @ksyasuda in #281
- fix(subtitles): allow Whisper generation during Windows YouTube stream playback by @ksyasuda in #282
- fix(overlay): identify Windows mpv windows through IPC PID by @ksyasuda in #330
## Installation
@@ -338,6 +338,7 @@ function createMockTracker(
hasAnime: async (animeId: number) => animeId === 1,
getAnimeEpisodes: async () => ANIME_EPISODES,
getAnimeAnilistEntries: async () => [],
getAnimeGroupPlacement: async () => null,
getAnimeWords: async () => ANIME_WORDS,
getAnimeDailyRollups: async () => DAILY_ROLLUPS,
getEpisodesPerDay: async () => EPISODES_PER_DAY,
@@ -712,7 +713,7 @@ const MALFORMED_IDS = [
/** Every route that takes a positive resource id; `:id` is replaced per request. */
const ID_ROUTES: Array<{
method: 'GET' | 'DELETE' | 'PATCH' | 'POST';
method: 'GET' | 'DELETE' | 'PATCH' | 'POST' | 'PUT';
path: string;
body?: unknown;
}> = [
@@ -739,6 +740,7 @@ const ID_ROUTES: Array<{
{ method: 'PATCH', path: '/api/stats/anime/:id/anilist', body: { anilistId: 21858 } },
{ method: 'PATCH', path: '/api/stats/anime/:id/tmdb', body: { tmdbId: 12, tmdbType: 'tv' } },
{ method: 'POST', path: '/api/stats/anime/:id/merge', body: { sourceAnimeIds: [8] } },
{ method: 'PUT', path: '/api/stats/anime/:id/group', body: { mode: 'standalone' } },
{ method: 'POST', path: '/api/stats/anki/browse?noteId=:id' },
];
@@ -2429,6 +2431,50 @@ describe('stats server API routes', () => {
assert.equal(mergeCalls, 0);
});
it('PUT /api/stats/anime/:animeId/group validates the body and maps refusals', async () => {
const calls: unknown[] = [];
const app = createStatsApp(
createMockTracker({
setAnimeGroupOverride: async (animeId, target) => {
calls.push([animeId, target]);
if (target.mode === 'join' && target.targetAnimeId === 9) {
return { ok: false, reason: 'target-not-grouped' };
}
if (animeId === 404) return { ok: false, reason: 'not-found' };
return { ok: true };
},
}),
);
const put = (path: string, body: unknown) =>
app.request(path, { method: 'PUT', headers: JSON_HEADERS, body: JSON.stringify(body) });
for (const body of [
{},
{ mode: 'join' },
{ mode: 'join', targetAnimeId: 0 },
{ mode: 'join', targetAnimeId: '8' },
{ mode: 'join', targetAnimeId: 3 },
{ mode: 'reset' },
]) {
assert.equal((await put('/api/stats/anime/3/group', body)).status, 400, JSON.stringify(body));
}
assert.deepEqual(calls, []);
assert.equal(
(await put('/api/stats/anime/3/group', { mode: 'join', targetAnimeId: 8 })).status,
200,
);
assert.equal((await put('/api/stats/anime/3/group', { mode: 'anilist' })).status, 200);
assert.equal((await put('/api/stats/anime/404/group', { mode: 'standalone' })).status, 404);
const refused = await put('/api/stats/anime/3/group', { mode: 'join', targetAnimeId: 9 });
assert.equal(refused.status, 409);
assert.match((await refused.json()).error, /no AniList entry/);
assert.deepEqual(calls.slice(0, 2), [
[3, { mode: 'join', targetAnimeId: 8 }],
[3, { mode: 'anilist' }],
]);
});
it('PATCH /api/stats/media/:videoId/anime moves the episode to another entry', async () => {
let moved: { videoId: number; animeId: number } | null = null;
const app = createStatsApp(
@@ -0,0 +1,49 @@
import type { AnilistRateLimiter } from './rate-limiter';
const ANILIST_GRAPHQL_URL = 'https://graphql.anilist.co';
export class AnilistRateLimitedError extends Error {
constructor() {
super('Anilist rate limit reached');
this.name = 'AnilistRateLimitedError';
}
}
/**
* Runs one anonymous AniList GraphQL query through the shared rate limiter.
* Throws AnilistRateLimitedError on HTTP 429 (the limiter has already recorded
* the retry window) and a plain Error for other HTTP or GraphQL failures.
*/
export async function executeAnilistQuery<T>(
rateLimiter: AnilistRateLimiter,
query: string,
variables: Record<string, unknown>,
): Promise<T> {
await rateLimiter.acquire();
const res = await fetch(ANILIST_GRAPHQL_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ query, variables }),
});
rateLimiter.recordResponse(res.headers);
if (res.status === 429) {
throw new AnilistRateLimitedError();
}
if (!res.ok) {
throw new Error(`Anilist search failed: ${res.status} ${res.statusText}`);
}
const json = (await res.json()) as { data?: T; errors?: Array<{ message?: string }> };
const firstError = json.errors?.find((entry) => Boolean(entry?.message));
if (firstError?.message) {
throw new Error(firstError.message);
}
if (!json.data) {
throw new Error('Anilist response missing data');
}
return json.data;
}
+1 -42
View File
@@ -1,4 +1,5 @@
import type { AnilistRateLimiter } from './rate-limiter';
import { AnilistRateLimitedError, executeAnilistQuery } from './anilist-graphql';
import type { DatabaseSync } from '../immersion-tracker/sqlite';
import {
getAnimeCoverArt,
@@ -20,7 +21,6 @@ import { getVideoTmdbLink, linkAnimeToTmdbTitle } from '../immersion-tracker/liv
import type { LiveActionMetadataResolver } from '../tmdb/live-action-resolver';
import type { TmdbTitleDetails } from '../tmdb/tmdb-client';
const ANILIST_GRAPHQL_URL = 'https://graphql.anilist.co';
const NO_MATCH_RETRY_MS = 5 * 60 * 1000;
export interface CoverArtFetcher {
@@ -76,47 +76,6 @@ export function stripFilenameTags(raw: string): string {
return title.trim().replace(/\s{2,}/g, ' ');
}
class AnilistRateLimitedError extends Error {
constructor() {
super('Anilist rate limit reached');
this.name = 'AnilistRateLimitedError';
}
}
async function executeAnilistQuery<T>(
rateLimiter: AnilistRateLimiter,
query: string,
variables: Record<string, unknown>,
): Promise<T> {
await rateLimiter.acquire();
const res = await fetch(ANILIST_GRAPHQL_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ query, variables }),
});
rateLimiter.recordResponse(res.headers);
if (res.status === 429) {
throw new AnilistRateLimitedError();
}
if (!res.ok) {
throw new Error(`Anilist search failed: ${res.status} ${res.statusText}`);
}
const json = (await res.json()) as { data?: T; errors?: Array<{ message?: string }> };
const firstError = json.errors?.find((entry) => Boolean(entry?.message));
if (firstError?.message) {
throw new Error(firstError.message);
}
if (!json.data) {
throw new Error('Anilist response missing data');
}
return json.data;
}
async function downloadImage(url: string): Promise<Buffer | null> {
try {
const res = await fetch(url);
@@ -0,0 +1,261 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
buildFranchiseGraph,
walkFranchiseRelations,
type AnilistMediaNode,
type FranchiseWalkOptions,
} from './franchise-graph';
function entry(
anilistId: number,
format: string | null,
startDate: number | null,
relations: Array<[string, number]> = [],
): AnilistMediaNode {
return {
anilistId,
format,
titleRomaji: `romaji ${anilistId}`,
titleEnglish: null,
titleNative: null,
startDate,
episodes: null,
relations: relations.map(([relationType, targetId]) => ({ relationType, targetId })),
fetchedAtMs: 0,
};
}
// Overlord: two recap films sit between seasons one and two; Isekai Quartet only shares characters.
const overlord = [
entry(20832, 'TV', 20150707, [
['SEQUEL', 98437],
['SUMMARY', 98873],
['CHARACTER', 104454],
]),
entry(98873, 'MOVIE', 20170225, [
['PARENT', 20832],
['SEQUEL', 98874],
]),
entry(98874, 'MOVIE', 20170311, [
['PREQUEL', 98873],
['SEQUEL', 98437],
]),
entry(98437, 'TV', 20180109, [
['PREQUEL', 20832],
['PREQUEL', 98874],
]),
entry(104454, 'TV_SHORT', 20190410, [['CHARACTER', 20832]]),
];
test('seasons, films and recaps share a root named after the first TV series', () => {
const graph = buildFranchiseGraph(overlord);
for (const id of [20832, 98873, 98874, 98437]) assert.equal(graph.rootOf(id), 20832);
assert.equal(graph.rootOf(104454), 104454);
assert.equal(graph.rootOf(1), undefined);
});
test('excluded relation types keep franchises apart even when the other end says PARENT', () => {
const graph = buildFranchiseGraph([
entry(1, 'TV', 20060101, [
['SPIN_OFF', 2],
['ALTERNATIVE', 3],
['ADAPTATION', 4],
['OTHER', 5],
]),
// A spin-off pointing back at its original as PARENT.
entry(2, 'TV', 20130101, [['PARENT', 1]]),
entry(3, 'TV', 20140101, [['ALTERNATIVE', 1]]),
]);
assert.deepEqual(
[1, 2, 3, 4, 5].map((id) => graph.rootOf(id)),
[1, 2, 3, undefined, undefined],
);
});
test('root falls back to episodic formats, then earliest entry, then lowest id', () => {
const ona = buildFranchiseGraph([
entry(10, 'MOVIE', 20000101, [['SEQUEL', 11]]),
entry(11, 'ONA', 20050101, [['PREQUEL', 10]]),
]);
assert.equal(ona.rootOf(10), 11);
const films = buildFranchiseGraph([
entry(20, 'MOVIE', 20100101, [['PREQUEL', 21]]),
entry(21, 'MOVIE', 20090101, [['SEQUEL', 20]]),
entry(22, 'OVA', null, [['PARENT', 20]]),
]);
assert.equal(films.rootOf(22), 21);
});
test('owned films join through an unowned, uncached TV entry they both point at', () => {
const graph = buildFranchiseGraph([
entry(528, 'MOVIE', 19980718, [['PARENT', 527]]),
entry(1526, 'MOVIE', 20050716, [['PARENT', 527]]),
]);
assert.equal(graph.rootOf(528), graph.rootOf(1526));
});
test('relation cycles terminate and form one franchise', () => {
const graph = buildFranchiseGraph([
entry(1, 'TV', 20000101, [['SEQUEL', 2]]),
entry(2, 'TV', 20010101, [['SEQUEL', 3]]),
entry(3, 'TV', 20020101, [['SEQUEL', 1]]),
]);
assert.deepEqual(
[1, 2, 3].map((id) => graph.rootOf(id)),
[1, 1, 1],
);
});
function walkHarness(all: AnilistMediaNode[], overrides: Partial<FranchiseWalkOptions> = {}) {
const asked: number[][] = [];
const known = new Map<number, AnilistMediaNode>();
const options: FranchiseWalkOptions = {
seeds: [],
known,
isFresh: () => true,
fetchNodes: async (ids) => {
asked.push([...ids].sort((a, b) => a - b));
return all.filter((node) => ids.includes(node.anilistId));
},
onBatch: () => {},
now: () => 5,
maxDepth: 6,
maxFetch: 500,
...overrides,
};
return { asked, known, options };
}
test('walk follows franchise links through entries the user does not own', async () => {
const pokemon = [
entry(528, 'MOVIE', 19980718, [['PARENT', 527]]),
entry(527, 'TV', 19970401, [
['SIDE_STORY', 528],
['SEQUEL', 1564],
]),
entry(1564, 'TV', 20021121, [
['PREQUEL', 527],
['SIDE_STORY', 1526],
['OTHER', 9],
]),
entry(1526, 'MOVIE', 20050716, [['PARENT', 1564]]),
entry(9, 'TV', 20000101),
];
const { asked, known, options } = walkHarness(pokemon, { seeds: [528, 1526, 404] });
await walkFranchiseRelations(options);
assert.deepEqual(asked, [
[404, 528, 1526],
[527, 1564],
]);
const graph = buildFranchiseGraph(known.values());
assert.equal(graph.rootOf(528), 527);
assert.equal(graph.rootOf(1526), 527);
// Missing ids are remembered so they are not asked about again; OTHER links are not followed.
assert.equal(known.get(404)?.format, null);
assert.equal(known.has(9), false);
});
test('walk does not follow the links of an entry that vetoes how it was reached', async () => {
const { asked, options } = walkHarness(
[
entry(2, 'TV', 20130101, [['PARENT', 1]]),
entry(1, 'TV', 20060101, [
['SPIN_OFF', 2],
['SEQUEL', 3],
]),
entry(3, 'TV', 20070101),
],
{ seeds: [2] },
);
await walkFranchiseRelations(options);
assert.deepEqual(asked, [[2], [1]]);
});
test('walk follows an entry reached through any link it accepts, whatever the seed order', async () => {
const nodes = [
entry(1, 'TV', 20100101, [['SEQUEL', 3]]),
entry(2, 'TV', 20110101, [['SEQUEL', 3]]),
// Rejects seed 1 but accepts seed 2, so its own links are still followed.
entry(3, 'TV', 20120101, [
['SPIN_OFF', 1],
['PREQUEL', 2],
['PARENT', 4],
]),
entry(4, 'TV', 20000101),
];
for (const seeds of [
[1, 2],
[2, 1],
]) {
const { asked, options } = walkHarness(nodes, { seeds });
await walkFranchiseRelations(options);
assert.deepEqual(asked, [[1, 2], [3], [4]]);
}
});
test('a cancelled walk starts no further request and drops the in-flight result', async () => {
const seeds = Array.from({ length: 51 }, (_, index) => index + 1);
let cancelled = false;
const batches: number[] = [];
const { asked, known, options } = walkHarness(
seeds.map((id) => entry(id, 'TV', 20200101)),
{
seeds,
isFresh: () => false,
onBatch: (nodes) => batches.push(nodes.length),
isCancelled: () => cancelled,
},
);
const fetchNodes = options.fetchNodes;
options.fetchNodes = async (ids) => {
cancelled = true;
return fetchNodes(ids);
};
const result = await walkFranchiseRelations(options);
assert.equal(asked.length, 1);
assert.deepEqual(batches, []);
assert.equal(known.size, 0);
assert.equal(result.truncated, true);
});
test('walk respects the depth and fetch bounds', async () => {
const chain = Array.from({ length: 10 }, (_, i) =>
entry(i + 1, 'TV', 20000101 + i, i < 9 ? [['SEQUEL', i + 2]] : []),
);
const deep = walkHarness(chain, { seeds: [1], maxDepth: 3 });
await walkFranchiseRelations(deep.options);
assert.deepEqual([...deep.known.keys()], [1, 2, 3, 4]);
const budget = walkHarness(chain, { seeds: [1], maxFetch: 2 });
const result = await walkFranchiseRelations(budget.options);
assert.deepEqual(result, { fetched: 2, truncated: true });
assert.deepEqual([...budget.known.keys()], [1, 2]);
});
test('walk follows fresh cached entries without asking and keeps old data on a failed fetch', async () => {
const cached = entry(1, 'TV', 20000101, [['SEQUEL', 2]]);
const stale = { ...entry(2, 'TV', 20010101, [['PREQUEL', 1]]), fetchedAtMs: -1 };
const { known, options } = walkHarness([], {
seeds: [1],
isFresh: (node) => node.fetchedAtMs >= 0,
fetchNodes: async () => {
throw new Error('AniList unavailable');
},
});
known.set(1, cached);
known.set(2, stale);
await assert.rejects(walkFranchiseRelations(options), /AniList unavailable/);
assert.deepEqual(known.get(2), stale);
});
test('an entry AniList stops returning keeps its cached links', async () => {
const previous = { ...entry(2, 'TV', 20010101, [['PREQUEL', 1]]), fetchedAtMs: -1 };
const { known, options } = walkHarness([], {
seeds: [2],
isFresh: (node) => node.fetchedAtMs >= 0,
});
known.set(2, previous);
await walkFranchiseRelations(options);
assert.deepEqual(known.get(2), { ...previous, fetchedAtMs: 5 });
});
@@ -0,0 +1,250 @@
/**
* Franchise grouping over AniList's relation graph. AniList keeps every
* season, movie and OVA as its own entry and says how entries relate; the
* stats library lists a franchise once by following those links, including
* through entries the user does not own (two movies meet at a TV series that
* is not in the library). Nothing here touches the database or the network.
*/
/**
* Relation types that make two entries parts of one franchise. SPIN_OFF,
* ALTERNATIVE, CHARACTER, OTHER, ADAPTATION and SOURCE are left out on purpose:
* following them collapses Gundam or Fate into a single card.
*/
export const FRANCHISE_RELATION_TYPES: ReadonlySet<string> = new Set([
'PREQUEL',
'SEQUEL',
'PARENT',
'SIDE_STORY',
'SUMMARY',
'COMPILATION',
'CONTAINS',
]);
export interface AnilistRelationEdge {
relationType: string;
targetId: number;
}
/** One cached AniList entry and its links to other anime entries. */
export interface AnilistMediaNode {
anilistId: number;
/** TV, MOVIE, OVA...; null when AniList did not return the entry. */
format: string | null;
titleRomaji: string | null;
titleEnglish: string | null;
titleNative: string | null;
/** First air date as yyyymmdd (month/day 0 when unknown); null when AniList has no year. */
startDate: number | null;
episodes: number | null;
relations: AnilistRelationEdge[];
fetchedAtMs: number;
}
export interface FranchiseGraph {
node(anilistId: number): AnilistMediaNode | undefined;
/** AniList id the franchise containing `anilistId` is named after; undefined when unknown. */
rootOf(anilistId: number): number | undefined;
}
export function anilistNodeTitle(node: AnilistMediaNode): string | null {
return node.titleEnglish ?? node.titleRomaji ?? node.titleNative;
}
/**
* True when `node` names `targetId` only through relations that do not join a
* franchise. AniList records most links from both ends; a spin-off can point
* back at its original as PARENT, so the original's SPIN_OFF edge has to veto
* the join or excluding SPIN_OFF would not keep the two apart.
*/
function vetoes(node: AnilistMediaNode, targetId: number): boolean {
const edges = node.relations.filter((edge) => edge.targetId === targetId);
return edges.length > 0 && !edges.some((edge) => FRANCHISE_RELATION_TYPES.has(edge.relationType));
}
function franchiseTargets(node: AnilistMediaNode): number[] {
return node.relations
.filter((edge) => FRANCHISE_RELATION_TYPES.has(edge.relationType))
.map((edge) => edge.targetId);
}
// TV first, then other episodic formats, then films/OVAs/specials, then entries with no data.
function formatRank(format: string | null): number {
if (format === 'TV') return 0;
if (format === 'TV_SHORT' || format === 'ONA') return 1;
return format === null ? 3 : 2;
}
export function buildFranchiseGraph(nodes: Iterable<AnilistMediaNode>): FranchiseGraph {
const byId = new Map<number, AnilistMediaNode>();
for (const node of nodes) byId.set(node.anilistId, node);
const parent = new Map<number, number>();
const find = (id: number): number => {
let top = parent.get(id) ?? id;
if (!parent.has(id)) parent.set(id, id);
while (parent.get(top) !== top) top = parent.get(top)!;
// Path compression keeps long sequel chains cheap.
let at = id;
while (at !== top) {
const next = parent.get(at)!;
parent.set(at, top);
at = next;
}
return top;
};
for (const node of byId.values()) {
find(node.anilistId);
for (const targetId of franchiseTargets(node)) {
const target = byId.get(targetId);
if (target && vetoes(target, node.anilistId)) continue;
const a = find(node.anilistId);
const b = find(targetId);
if (a !== b) parent.set(b, a);
}
}
const members = new Map<number, number[]>();
for (const id of parent.keys()) {
const top = find(id);
const list = members.get(top);
if (list) list.push(id);
else members.set(top, [id]);
}
// A franchise is named after its first TV series, else its first episodic
// entry, else its earliest entry; ties go to the lower id.
const compareRoots = (a: number, b: number): number => {
const left = byId.get(a);
const right = byId.get(b);
return (
formatRank(left?.format ?? null) - formatRank(right?.format ?? null) ||
(left?.startDate ?? Number.MAX_SAFE_INTEGER) -
(right?.startDate ?? Number.MAX_SAFE_INTEGER) ||
a - b
);
};
const roots = new Map<number, number>();
for (const ids of members.values()) {
const root = [...ids].sort(compareRoots)[0]!;
for (const id of ids) roots.set(id, root);
}
return {
node: (anilistId) => byId.get(anilistId),
rootOf: (anilistId) => roots.get(anilistId),
};
}
const FETCH_CHUNK_SIZE = 50;
export interface FranchiseWalkOptions {
/** AniList ids the walk starts from (the library's own entries). */
seeds: readonly number[];
/** Cached entries; updated in place with everything fetched. */
known: Map<number, AnilistMediaNode>;
isFresh: (node: AnilistMediaNode) => boolean;
/** Entries AniList returned for `ids` (at most 50). Throws on transport or API failure. */
fetchNodes: (ids: number[]) => Promise<AnilistMediaNode[]>;
/** Called once per fetched batch so progress survives a later failure. */
onBatch: (nodes: AnilistMediaNode[]) => void;
now: () => number;
/** Hops from a seed; entries at this depth are fetched but not followed. */
maxDepth: number;
/** Most entries fetched in one walk; the rest wait for the next walk. */
maxFetch: number;
/** When true, the walk starts no further request and drops an in-flight result. */
isCancelled?: () => boolean;
}
export interface FranchiseWalkResult {
fetched: number;
/** True when the fetch budget ran out before every stale entry was refreshed. */
truncated: boolean;
}
/**
* Breadth-first walk from the seeds along franchise relations, fetching
* entries that are missing or stale. Fresh cached entries are followed without
* a request. An entry AniList does not return keeps its previous data (or gets
* an empty placeholder) so it is not asked about again until it goes stale; a
* thrown fetch error stops the walk and leaves the cache as it was.
*/
export async function walkFranchiseRelations(
options: FranchiseWalkOptions,
): Promise<FranchiseWalkResult> {
const { known } = options;
const visited = new Set<number>();
// `from` lists every entry the walk reached this one through at this depth
// (empty for a seed), so the order seeds are given in cannot change the result.
let frontier: Array<{ id: number; from: number[] }> = [...new Set(options.seeds)].map((id) => ({
id,
from: [],
}));
let fetched = 0;
let truncated = false;
for (let depth = 0; frontier.length > 0; depth += 1) {
for (const step of frontier) visited.add(step.id);
const stale = frontier
.map((step) => step.id)
.filter((id) => {
const node = known.get(id);
return !node || !options.isFresh(node);
});
const allowed = stale.slice(0, Math.max(0, options.maxFetch - fetched));
if (allowed.length < stale.length) truncated = true;
for (let start = 0; start < allowed.length; start += FETCH_CHUNK_SIZE) {
if (options.isCancelled?.()) return { fetched, truncated: true };
const chunk = allowed.slice(start, start + FETCH_CHUNK_SIZE);
const fetchedNodes = await options.fetchNodes(chunk);
if (options.isCancelled?.()) return { fetched, truncated: true };
const found = new Map(fetchedNodes.map((node) => [node.anilistId, node] as const));
const fetchedAtMs = options.now();
const batch = chunk.map((id): AnilistMediaNode => {
const node = found.get(id);
if (node) return node;
const previous = known.get(id);
if (previous) return { ...previous, fetchedAtMs };
return {
anilistId: id,
format: null,
titleRomaji: null,
titleEnglish: null,
titleNative: null,
startDate: null,
episodes: null,
relations: [],
fetchedAtMs,
};
});
for (const node of batch) known.set(node.anilistId, node);
options.onBatch(batch);
fetched += chunk.length;
}
if (depth >= options.maxDepth) break;
const next = new Map<number, number[]>();
for (const step of frontier) {
const node = known.get(step.id);
if (!node) continue;
// Reached only through links the entry itself rejects (a spin-off's
// original): it is not part of the franchise, so its own links are not
// followed. One accepted incoming link is enough.
if (step.from.length > 0 && step.from.every((fromId) => vetoes(node, fromId))) continue;
for (const targetId of franchiseTargets(node)) {
if (visited.has(targetId)) continue;
const from = next.get(targetId);
if (from) from.push(node.anilistId);
else next.set(targetId, [node.anilistId]);
}
}
frontier = [...next].map(([id, from]) => ({ id, from }));
}
return { fetched, truncated };
}
@@ -0,0 +1,83 @@
import { executeAnilistQuery } from './anilist-graphql';
import type { AnilistMediaNode, AnilistRelationEdge } from './franchise-graph';
import type { AnilistRateLimiter } from './rate-limiter';
/** Loads AniList entries with their relations, for the library's franchise grouping. */
export interface AnilistRelationFetcher {
/** Entries AniList returned for `ids` (at most 50); ids it does not know are absent. */
fetchMedia(ids: number[]): Promise<AnilistMediaNode[]>;
}
const RELATIONS_QUERY = `
query ($ids: [Int], $perPage: Int) {
Page(page: 1, perPage: $perPage) {
media(id_in: $ids, type: ANIME) {
id
format
episodes
title { romaji english native }
startDate { year month day }
relations { edges { relationType(version: 2) node { id type } } }
}
}
}`;
interface RelationsMedia {
id: number;
format: string | null;
episodes: number | null;
title: { romaji: string | null; english: string | null; native: string | null } | null;
startDate: { year: number | null; month: number | null; day: number | null } | null;
relations: {
edges: Array<{
relationType: string | null;
node: { id: number; type: string | null } | null;
} | null> | null;
} | null;
}
interface RelationsResponse {
Page: { media: Array<RelationsMedia | null> | null } | null;
}
export function toAnilistMediaNode(media: RelationsMedia, fetchedAtMs: number): AnilistMediaNode {
const start = media.startDate;
const relations: AnilistRelationEdge[] = [];
for (const edge of media.relations?.edges ?? []) {
// Manga and novels are not part of a watch library.
if (!edge?.relationType || edge.node?.type !== 'ANIME') continue;
relations.push({ relationType: edge.relationType, targetId: edge.node.id });
}
return {
anilistId: media.id,
format: media.format,
titleRomaji: media.title?.romaji ?? null,
titleEnglish: media.title?.english ?? null,
titleNative: media.title?.native ?? null,
startDate: start?.year
? start.year * 10_000 + (start.month ?? 0) * 100 + (start.day ?? 0)
: null,
episodes: media.episodes,
relations,
fetchedAtMs,
};
}
export function createAnilistRelationFetcher(
rateLimiter: AnilistRateLimiter,
now: () => number = Date.now,
): AnilistRelationFetcher {
return {
async fetchMedia(ids) {
if (ids.length === 0) return [];
const data = await executeAnilistQuery<RelationsResponse>(rateLimiter, RELATIONS_QUERY, {
ids,
perPage: ids.length,
});
const fetchedAtMs = now();
return (data.Page?.media ?? [])
.filter((media): media is RelationsMedia => media !== null)
.map((media) => toAnilistMediaNode(media, fetchedAtMs));
},
};
}
@@ -4,6 +4,18 @@ import { createLogger } from '../../logger';
import { sanitizeMediaTitle, toMediaIdentityPath } from '../../shared/media-identity';
import { MediaGenerator } from '../../media-generator';
import type { CoverArtFetcher } from './anilist/cover-art-fetcher';
import type { AnilistRelationFetcher } from './anilist/franchise-relation-fetcher';
import {
createFranchiseRelationRefresher,
type FranchiseRelationRefresher,
} from './immersion-tracker/franchise-relation-refresher';
import {
getAnimeGroupPlacement,
getAnimeLibraryGroups,
setAnimeGroupOverride,
type AnimeGroupOverrideResult,
type AnimeGroupOverrideTarget,
} from './immersion-tracker/query-library-groups';
import { getLocalVideoMetadata, guessAnimeVideoMetadata } from './immersion-tracker/metadata';
import {
pruneRawRetention,
@@ -61,6 +73,7 @@ import type {
StatsTrendGroupBy,
StatsTrendRange,
} from '../../types/stats-http-contract';
import type { AnimeGroupPlacement, AnimeLibraryGroup } from '../../types/stats-wire';
import {
getKanjiAnimeAppearances,
getKanjiDetail,
@@ -452,6 +465,7 @@ export class ImmersionTrackerService {
private readonly mediaGenerator = new MediaGenerator();
private readonly preparedStatements: TrackerPreparedStatements;
private coverArtFetcher: CoverArtFetcher | null = null;
private franchiseRelations: FranchiseRelationRefresher | null = null;
private readonly pendingCoverFetches = new Map<number, Promise<boolean>>();
private readonly pendingYoutubeMetadataFetches = new Map<number, Promise<void>>();
private readonly recordedSubtitleKeys = new Set<string>();
@@ -621,6 +635,7 @@ export class ImmersionTrackerService {
}
this.finalizeActiveSession();
this.isDestroyed = true;
this.franchiseRelations?.stop();
this.deleteMaintenanceScheduler.destroy();
this.destroyDeleteMaintenanceRunner();
this.destroyVocabularySummaryRunner();
@@ -833,6 +848,27 @@ export class ImmersionTrackerService {
return getAnimeLibrary(this.db);
}
/** The library as franchise cards; also schedules a background AniList relation refresh. */
async getAnimeLibraryGroups(): Promise<AnimeLibraryGroup[]> {
this.relinkYoutubeAnimeLibrary();
const groups = getAnimeLibraryGroups(this.db);
this.franchiseRelations?.requestRefresh();
return groups;
}
async getAnimeGroupPlacement(animeId: number): Promise<AnimeGroupPlacement | null> {
return getAnimeGroupPlacement(this.db, animeId);
}
async setAnimeGroupOverride(
animeId: number,
target: AnimeGroupOverrideTarget,
): Promise<AnimeGroupOverrideResult> {
const result = setAnimeGroupOverride(this.db, animeId, target);
if (result.ok) this.franchiseRelations?.requestRefresh({ force: true });
return result;
}
async getAnimeMergeRecommendations(): Promise<AnimeMergeRecommendation[]> {
return getAnimeMergeRecommendations(this.db);
}
@@ -1122,6 +1158,7 @@ export class ImmersionTrackerService {
this.db.exec('ROLLBACK');
throw error;
}
this.franchiseRelations?.requestRefresh({ force: true });
}
/**
@@ -1248,6 +1285,19 @@ export class ImmersionTrackerService {
this.coverArtFetcher = fetcher;
}
/** Enables franchise grouping refreshes; null disables them (tests, offline runs). */
setAnilistRelationFetcher(fetcher: AnilistRelationFetcher | null): void {
this.franchiseRelations?.stop();
this.franchiseRelations = fetcher
? createFranchiseRelationRefresher({
db: this.db,
fetcher,
logger: createLogger('immersion-tracker:franchise-relations'),
})
: null;
this.franchiseRelations?.requestRefresh();
}
async ensureAnimeCoverArt(animeId: number): Promise<boolean> {
const existing = await this.getAnimeCoverArt(animeId);
if (existing?.coverBlob) {
@@ -1300,6 +1350,8 @@ export class ImmersionTrackerService {
if (!fetched) {
return false;
}
// A fresh AniList link may join this entry to a franchise card.
this.franchiseRelations?.requestRefresh({ force: true });
const cover = await this.getCoverArt(videoId);
return cover?.coverBlob != null;
})();
@@ -0,0 +1,126 @@
import type { AnilistMediaNode } from '../anilist/franchise-graph';
import type { DatabaseSync } from './sqlite';
import { fromDbTimestamp, toDbTimestamp } from './query-shared';
/**
* Franchise grouping state. `imm_anilist_media` and `imm_anilist_relations`
* cache AniList entries (owned or reached through relations) and every
* anime-to-anime edge, whatever its type, so the grouping rule can change
* without a refetch. The cache is rebuildable from AniList and is not synced.
*
* `imm_anime.group_override` is the user's choice for one library entry:
* NULL follows AniList, 0 keeps the entry on its own, and a positive value is
* an AniList id whose franchise the entry joins. `group_override_updated_at`
* records when it was set (or cleared) so sync can keep the newer choice.
*/
export function ensureAnimeGroupingSchema(db: DatabaseSync): void {
db.exec(`
CREATE TABLE IF NOT EXISTS imm_anilist_media(
anilist_id INTEGER PRIMARY KEY,
format TEXT,
title_romaji TEXT,
title_english TEXT,
title_native TEXT,
start_date INTEGER,
episodes INTEGER,
fetched_at_ms TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS imm_anilist_relations(
anilist_id INTEGER NOT NULL,
relation_type TEXT NOT NULL,
target_anilist_id INTEGER NOT NULL,
PRIMARY KEY(anilist_id, relation_type, target_anilist_id),
FOREIGN KEY(anilist_id) REFERENCES imm_anilist_media(anilist_id) ON DELETE CASCADE
);
`);
const columns = new Set(
(db.prepare('PRAGMA table_info(imm_anime)').all() as Array<{ name: string }>).map(
(column) => column.name,
),
);
if (!columns.has('group_override')) {
db.exec('ALTER TABLE imm_anime ADD COLUMN group_override INTEGER');
}
if (!columns.has('group_override_updated_at')) {
db.exec('ALTER TABLE imm_anime ADD COLUMN group_override_updated_at TEXT');
}
}
export function readAnilistRelationCache(db: DatabaseSync): Map<number, AnilistMediaNode> {
const nodes = new Map<number, AnilistMediaNode>();
const mediaRows = db
.prepare(
`SELECT anilist_id AS anilistId, format, title_romaji AS titleRomaji,
title_english AS titleEnglish, title_native AS titleNative,
start_date AS startDate, episodes, fetched_at_ms AS fetchedAtMs
FROM imm_anilist_media`,
)
.all() as Array<Omit<AnilistMediaNode, 'relations' | 'fetchedAtMs'> & { fetchedAtMs: string }>;
for (const row of mediaRows) {
nodes.set(row.anilistId, {
...row,
relations: [],
fetchedAtMs: fromDbTimestamp(row.fetchedAtMs) ?? 0,
});
}
const edgeRows = db
.prepare(
`SELECT anilist_id AS anilistId, relation_type AS relationType, target_anilist_id AS targetId
FROM imm_anilist_relations
ORDER BY anilist_id, relation_type, target_anilist_id`,
)
.all() as Array<{ anilistId: number; relationType: string; targetId: number }>;
for (const edge of edgeRows) {
nodes.get(edge.anilistId)?.relations.push({
relationType: edge.relationType,
targetId: edge.targetId,
});
}
return nodes;
}
/** Replaces each node's cached row and edges in one transaction. */
export function writeAnilistRelationNodes(db: DatabaseSync, nodes: AnilistMediaNode[]): void {
if (nodes.length === 0) return;
const upsertMedia = db.prepare(`
INSERT INTO imm_anilist_media(anilist_id, format, title_romaji, title_english, title_native,
start_date, episodes, fetched_at_ms)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(anilist_id) DO UPDATE SET
format = excluded.format,
title_romaji = excluded.title_romaji,
title_english = excluded.title_english,
title_native = excluded.title_native,
start_date = excluded.start_date,
episodes = excluded.episodes,
fetched_at_ms = excluded.fetched_at_ms
`);
const deleteEdges = db.prepare('DELETE FROM imm_anilist_relations WHERE anilist_id = ?');
const insertEdge = db.prepare(`
INSERT OR IGNORE INTO imm_anilist_relations(anilist_id, relation_type, target_anilist_id)
VALUES (?, ?, ?)
`);
db.exec('BEGIN IMMEDIATE');
try {
for (const node of nodes) {
upsertMedia.run(
node.anilistId,
node.format,
node.titleRomaji,
node.titleEnglish,
node.titleNative,
node.startDate,
node.episodes,
toDbTimestamp(node.fetchedAtMs),
);
deleteEdges.run(node.anilistId);
for (const edge of node.relations) {
insertEdge.run(node.anilistId, edge.relationType, edge.targetId);
}
}
db.exec('COMMIT');
} catch (error) {
db.exec('ROLLBACK');
throw error;
}
}
@@ -0,0 +1,75 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import type { AnilistMediaNode } from '../anilist/franchise-graph';
import { readAnilistRelationCache } from './anilist-relation-cache';
import {
createFranchiseRelationRefresher,
FRANCHISE_RELATION_STALE_MS,
} from './franchise-relation-refresher';
import { Database } from './sqlite';
import { ensureSchema } from './storage';
const silent = { info: () => {}, warn: () => {} };
function media(anilistId: number, relations: Array<[string, number]>, fetchedAtMs: number) {
return {
anilistId,
format: 'TV',
titleRomaji: null,
titleEnglish: null,
titleNative: null,
startDate: null,
episodes: null,
relations: relations.map(([relationType, targetId]) => ({ relationType, targetId })),
fetchedAtMs,
} satisfies AnilistMediaNode;
}
test('refresh walks from linked entries and override targets, then keeps the cache on failure', async () => {
const db = new Database(':memory:');
try {
ensureSchema(db);
db.exec(`INSERT INTO imm_anime(normalized_title_key, canonical_title, anilist_id, media_kind)
VALUES ('a', 'A', 1, 'anime'), ('c', 'C', 77, 'youtube');
INSERT INTO imm_anime(normalized_title_key, canonical_title, group_override)
VALUES ('b', 'B', 50)`);
let clock = 1_000;
let failing = false;
const asked: number[][] = [];
const refresher = createFranchiseRelationRefresher({
db,
logger: silent,
now: () => clock,
fetcher: {
fetchMedia: async (ids) => {
if (failing) throw new Error('AniList down');
asked.push([...ids].sort((a, b) => a - b));
return ids.map((id) => media(id, id === 1 ? [['SEQUEL', 2]] : [], clock));
},
},
});
refresher.requestRefresh();
await refresher.whenIdle();
assert.deepEqual(asked, [[1, 50], [2]]);
assert.deepEqual(
[...readAnilistRelationCache(db).keys()].sort((a, b) => a - b),
[1, 2, 50],
);
// Throttled until forced; everything is fresh, so a forced run asks nothing.
refresher.requestRefresh({ force: true });
await refresher.whenIdle();
assert.equal(asked.length, 2);
clock += FRANCHISE_RELATION_STALE_MS;
failing = true;
refresher.requestRefresh({ force: true });
await refresher.whenIdle();
assert.deepEqual(readAnilistRelationCache(db).get(1)?.relations, [
{ relationType: 'SEQUEL', targetId: 2 },
]);
} finally {
db.close();
}
});
@@ -0,0 +1,121 @@
import { walkFranchiseRelations } from '../anilist/franchise-graph';
import type { AnilistRelationFetcher } from '../anilist/franchise-relation-fetcher';
import { readAnilistRelationCache, writeAnilistRelationNodes } from './anilist-relation-cache';
import type { DatabaseSync } from './sqlite';
/** Cached AniList entries are asked about again after a week. */
export const FRANCHISE_RELATION_STALE_MS = 7 * 24 * 60 * 60 * 1000;
/** Hops followed from a library entry; keeps long-running franchises bounded. */
export const FRANCHISE_WALK_MAX_DEPTH = 6;
/** Entries fetched per refresh (five AniList requests); the rest wait for the next refresh. */
export const FRANCHISE_WALK_MAX_FETCH = 250;
/** Unforced refreshes (library polls) run at most this often. */
const MIN_INTERVAL_MS = 10 * 60 * 1000;
interface RefresherLogger {
info(message: string, ...args: unknown[]): void;
warn(message: string, ...args: unknown[]): void;
}
export interface FranchiseRelationRefresherDeps {
db: DatabaseSync;
fetcher: AnilistRelationFetcher;
logger: RefresherLogger;
now?: () => number;
}
export interface FranchiseRelationRefresher {
/**
* Starts a background refresh unless one ran recently. `force` skips that
* throttle, for when an entry has just been linked to AniList.
*/
requestRefresh(options?: { force?: boolean }): void;
/** Resolves once no refresh is running; for tests and shutdown. */
whenIdle(): Promise<void>;
/** Stops writing; a running refresh finishes its request and discards the result. */
stop(): void;
}
function readSeeds(db: DatabaseSync): number[] {
return (
db
.prepare(
`SELECT anilist_id AS id FROM imm_anime WHERE media_kind = 'anime' AND anilist_id IS NOT NULL
UNION
SELECT group_override AS id FROM imm_anime WHERE group_override > 0`,
)
.all() as Array<{ id: number }>
).map((row) => row.id);
}
export function createFranchiseRelationRefresher(
deps: FranchiseRelationRefresherDeps,
): FranchiseRelationRefresher {
const now = deps.now ?? Date.now;
let running: Promise<void> | null = null;
let pending = false;
let stopped = false;
let lastStartedAtMs: number | null = null;
const refreshOnce = async (): Promise<void> => {
const known = readAnilistRelationCache(deps.db);
const result = await walkFranchiseRelations({
seeds: readSeeds(deps.db),
known,
isFresh: (node) => now() - node.fetchedAtMs < FRANCHISE_RELATION_STALE_MS,
fetchNodes: (ids) => deps.fetcher.fetchMedia(ids),
onBatch: (nodes) => writeAnilistRelationNodes(deps.db, nodes),
isCancelled: () => stopped,
now,
maxDepth: FRANCHISE_WALK_MAX_DEPTH,
maxFetch: FRANCHISE_WALK_MAX_FETCH,
});
if (result.fetched > 0) {
deps.logger.info(
'franchise-relations: refreshed %d AniList entries%s',
result.fetched,
result.truncated ? ' (more next time)' : '',
);
}
};
const run = (): void => {
lastStartedAtMs = now();
running = (async () => {
try {
do {
pending = false;
await refreshOnce();
} while (pending && !stopped);
} catch (error) {
// Cached rows stay as they were; the next request (after the throttle) retries.
deps.logger.warn(
'franchise-relations: refresh failed: %s',
error instanceof Error ? error.message : String(error),
);
} finally {
running = null;
}
})();
};
return {
requestRefresh(options = {}) {
if (stopped) return;
if (running) {
if (options.force) pending = true;
return;
}
if (!options.force && lastStartedAtMs !== null && now() - lastStartedAtMs < MIN_INTERVAL_MS) {
return;
}
run();
},
async whenIdle() {
while (running) await running;
},
stop() {
stopped = true;
},
};
}
@@ -0,0 +1,226 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { buildFranchiseGraph, type AnilistMediaNode } from '../anilist/franchise-graph';
import { readAnilistRelationCache, writeAnilistRelationNodes } from './anilist-relation-cache';
import {
getAnimeGroupPlacement,
getAnimeLibraryGroups,
groupAnimeLibrary,
setAnimeGroupOverride,
type GroupableLibraryRow,
} from './query-library-groups';
import { Database, type DatabaseSync } from './sqlite';
import { ensureSchema } from './storage';
import { SCHEMA_VERSION } from './types';
function node(
anilistId: number,
format: string,
startDate: number,
relations: Array<[string, number]>,
titleEnglish: string | null = null,
): AnilistMediaNode {
return {
anilistId,
format,
titleRomaji: `romaji ${anilistId}`,
titleEnglish,
titleNative: null,
startDate,
episodes: null,
relations: relations.map(([relationType, targetId]) => ({ relationType, targetId })),
fetchedAtMs: 1,
};
}
// Owned: season 2 and a film. The first season (the root) is not in the library.
const overlordNodes = [
node(
20832,
'TV',
20150707,
[
['SEQUEL', 98437],
['SUMMARY', 98873],
],
'Overlord',
),
node(98873, 'MOVIE', 20170225, [['PARENT', 20832]]),
node(98437, 'TV', 20180109, [['PREQUEL', 20832]]),
];
function row(
animeId: number,
anilistId: number | null,
overrides: Partial<GroupableLibraryRow> = {},
): GroupableLibraryRow {
return {
mediaKind: 'anime',
animeId,
canonicalTitle: `Entry ${animeId}`,
anilistId,
tmdbId: null,
tmdbType: null,
totalSessions: 1,
totalActiveMs: 1000 * animeId,
totalCards: animeId,
totalTokensSeen: 10,
episodeCount: 2,
episodesTotal: null,
lastWatchedMs: 100 * animeId,
groupOverride: null,
...overrides,
};
}
test('owned parts join under the unowned root, in release order, with summed totals', () => {
const graph = buildFranchiseGraph(overlordNodes);
const groups = groupAnimeLibrary([row(1, 98437), row(2, 98873), row(3, null)], graph);
assert.equal(groups.length, 2);
const overlord = groups.find((group) => group.groupKey === 20832)!;
assert.equal(overlord.title, 'Overlord');
assert.deepEqual(
overlord.parts.map((part) => [part.animeId, part.format, part.startDate]),
[
[2, 'MOVIE', 20170225],
[1, 'TV', 20180109],
],
);
assert.equal(overlord.coverAnimeId, 2);
assert.deepEqual(
[overlord.totalActiveMs, overlord.totalCards, overlord.episodeCount, overlord.lastWatchedMs],
[3000, 3, 4, 200],
);
});
test('entries without AniList data stay single cards that look like the entry', () => {
const graph = buildFranchiseGraph([]);
const lone = row(7, 555, { canonicalTitle: 'Bocchi the Rock!' });
const [linked, unlinked, channel] = groupAnimeLibrary(
[lone, row(3, null), row(2, null, { mediaKind: 'youtube', groupOverride: 555 })],
graph,
);
assert.deepEqual(
[linked!.groupKey, linked!.title, linked!.coverAnimeId, linked!.parts.length],
[555, 'Bocchi the Rock!', 7, 1],
);
const { groupOverride: _override, ...item } = lone;
assert.deepEqual(linked!.parts[0], { ...item, format: null, startDate: null });
assert.equal(unlinked!.groupKey, -3);
// Overrides never apply to YouTube or live-action entries.
assert.equal(channel!.groupKey, -2);
});
test('overrides move an entry to another franchise or keep it on its own', () => {
const graph = buildFranchiseGraph(overlordNodes);
const groups = groupAnimeLibrary(
[
row(1, 98437),
row(2, 98873, { groupOverride: 0 }),
// Unlinked specials moved in by the user, pointing at any part of the franchise.
row(3, null, { groupOverride: 98437 }),
],
graph,
);
assert.deepEqual(
groups
.map((group) => [group.groupKey, group.parts.map((part) => part.animeId)] as const)
.sort((a, b) => a[0] - b[0]),
[
[-2, [2]],
[20832, [1, 3]],
],
);
});
function seed(db: DatabaseSync, title: string, anilistId: number | null): number {
const animeId = Number(
db
.prepare(
`INSERT INTO imm_anime(normalized_title_key, canonical_title, anilist_id) VALUES (?, ?, ?)`,
)
.run(title.toLowerCase(), title, anilistId).lastInsertRowid,
);
db.prepare(
`INSERT INTO imm_videos(video_key, anime_id, canonical_title, source_type, duration_ms)
VALUES (?, ?, ?, 1, 0)`,
).run(`key:${title}`, animeId, title);
db.prepare(
'INSERT INTO imm_lifetime_anime(anime_id, total_active_ms, total_cards) VALUES (?, 60000, 1)',
).run(animeId);
return animeId;
}
test('library groups and overrides round-trip through the database', () => {
const db = new Database(':memory:');
try {
ensureSchema(db);
const season2 = seed(db, 'Overlord II', 98437);
const film = seed(db, 'The Undead King', 98873);
const specials = seed(db, 'Overlord specials', null);
const other = seed(db, 'Bocchi the Rock!', 130003);
// No cached relations yet: every entry is its own card.
assert.equal(getAnimeLibraryGroups(db).length, 4);
writeAnilistRelationNodes(db, overlordNodes);
assert.deepEqual(readAnilistRelationCache(db).get(20832), overlordNodes[0]);
assert.deepEqual(getAnimeGroupPlacement(db, film), {
groupKey: 20832,
title: 'Overlord',
partCount: 2,
overrideMode: 'anilist',
});
assert.deepEqual(
setAnimeGroupOverride(db, specials, { mode: 'join', targetAnimeId: season2 }),
{
ok: true,
},
);
assert.deepEqual(setAnimeGroupOverride(db, film, { mode: 'standalone' }), { ok: true });
assert.deepEqual(setAnimeGroupOverride(db, other, { mode: 'join', targetAnimeId: film }), {
ok: false,
reason: 'target-not-grouped',
});
assert.deepEqual(setAnimeGroupOverride(db, 999, { mode: 'standalone' }), {
ok: false,
reason: 'not-found',
});
const stored = db
.prepare('SELECT group_override AS value FROM imm_anime WHERE anime_id = ?')
.get(specials) as { value: number };
assert.equal(stored.value, 20832);
assert.deepEqual(getAnimeGroupPlacement(db, specials), {
groupKey: 20832,
title: 'Overlord',
partCount: 2,
overrideMode: 'joined',
});
assert.equal(getAnimeGroupPlacement(db, film)?.overrideMode, 'standalone');
setAnimeGroupOverride(db, film, { mode: 'anilist' });
assert.equal(getAnimeGroupPlacement(db, film)?.partCount, 3);
} finally {
db.close();
}
});
test('schema 27 upgrade adds the relation cache and override columns', () => {
const db = new Database(':memory:');
try {
ensureSchema(db);
db.exec(`DROP TABLE imm_anilist_relations; DROP TABLE imm_anilist_media;
ALTER TABLE imm_anime DROP COLUMN group_override;
ALTER TABLE imm_anime DROP COLUMN group_override_updated_at;`);
db.prepare('UPDATE imm_schema_version SET schema_version = ?').run(SCHEMA_VERSION - 1);
ensureSchema(db);
const columns = (db.prepare('PRAGMA table_info(imm_anime)').all() as Array<{ name: string }>)
.map((column) => column.name)
.filter((name) => name.startsWith('group_override'));
assert.deepEqual(columns, ['group_override', 'group_override_updated_at']);
assert.equal(readAnilistRelationCache(db).size, 0);
} finally {
db.close();
}
});
@@ -0,0 +1,192 @@
import type {
AnimeGroupOverrideMode,
AnimeGroupPlacement,
AnimeLibraryGroup,
AnimeLibraryGroupPart,
} from '../../../types/stats-wire';
import {
anilistNodeTitle,
buildFranchiseGraph,
type FranchiseGraph,
} from '../anilist/franchise-graph';
import { readAnilistRelationCache } from './anilist-relation-cache';
import { toDbTimestamp } from './query-shared';
import { getAnimeLibrary } from './query-library';
import type { DatabaseSync } from './sqlite';
import { nowMs } from './time';
import type { AnimeLibraryRow } from './types';
/** `imm_anime.group_override` value that keeps an entry on its own. */
export const GROUP_OVERRIDE_STANDALONE = 0;
export interface GroupableLibraryRow extends AnimeLibraryRow {
groupOverride: number | null;
}
function overrideMode(row: GroupableLibraryRow): AnimeGroupOverrideMode {
if (row.mediaKind !== 'anime' || row.groupOverride === null || row.groupOverride < 0) {
return 'anilist';
}
return row.groupOverride === GROUP_OVERRIDE_STANDALONE ? 'standalone' : 'joined';
}
/**
* The card an entry belongs to: positive keys are AniList ids (the franchise
* root once its relations are cached, the entry's own id until then), negative
* keys are `-animeId` for entries listed on their own. Overrides only apply to
* anime entries; live-action and YouTube rows always stand alone.
*/
function groupKeyFor(row: GroupableLibraryRow, graph: FranchiseGraph): number {
const mode = overrideMode(row);
if (mode === 'standalone') return -row.animeId;
if (mode === 'joined') return graph.rootOf(row.groupOverride!) ?? row.groupOverride!;
if (row.mediaKind === 'anime' && row.anilistId !== null) {
return graph.rootOf(row.anilistId) ?? row.anilistId;
}
return -row.animeId;
}
function toPart(row: GroupableLibraryRow, graph: FranchiseGraph): AnimeLibraryGroupPart {
const { groupOverride: _groupOverride, ...item } = row;
const node =
row.mediaKind === 'anime' && row.anilistId !== null ? graph.node(row.anilistId) : undefined;
return { ...item, format: node?.format ?? null, startDate: node?.startDate ?? null };
}
// Release order; entries AniList has no date for go last, in library order.
function compareParts(a: AnimeLibraryGroupPart, b: AnimeLibraryGroupPart): number {
return (
(a.startDate ?? Number.MAX_SAFE_INTEGER) - (b.startDate ?? Number.MAX_SAFE_INTEGER) ||
a.animeId - b.animeId
);
}
/**
* Groups library rows into franchise cards. A card with one part keeps that
* entry's own title, so ungrouped entries render exactly as before; a card with
* several parts is named after the franchise root, even when the root itself
* is not in the library.
*/
export function groupAnimeLibrary(
rows: GroupableLibraryRow[],
graph: FranchiseGraph,
): AnimeLibraryGroup[] {
const byKey = new Map<number, GroupableLibraryRow[]>();
for (const row of rows) {
const key = groupKeyFor(row, graph);
const members = byKey.get(key);
if (members) members.push(row);
else byKey.set(key, [row]);
}
const groups: AnimeLibraryGroup[] = [];
for (const [groupKey, members] of byKey) {
const parts = members.map((row) => toPart(row, graph)).sort(compareParts);
const first = parts[0]!;
const rootNode = groupKey > 0 ? graph.node(groupKey) : undefined;
const title =
parts.length === 1
? first.canonicalTitle
: ((rootNode ? anilistNodeTitle(rootNode) : null) ??
parts.find((part) => part.anilistId === groupKey)?.canonicalTitle ??
first.canonicalTitle);
groups.push({
groupKey,
title,
mediaKind: first.mediaKind,
coverAnimeId: first.animeId,
totalSessions: parts.reduce((sum, part) => sum + part.totalSessions, 0),
totalActiveMs: parts.reduce((sum, part) => sum + part.totalActiveMs, 0),
totalCards: parts.reduce((sum, part) => sum + part.totalCards, 0),
totalTokensSeen: parts.reduce((sum, part) => sum + part.totalTokensSeen, 0),
episodeCount: parts.reduce((sum, part) => sum + part.episodeCount, 0),
lastWatchedMs: Math.max(...parts.map((part) => part.lastWatchedMs)),
parts,
});
}
return groups.sort((a, b) => b.totalActiveMs - a.totalActiveMs || a.groupKey - b.groupKey);
}
function readGroupableLibrary(db: DatabaseSync): GroupableLibraryRow[] {
const overrides = new Map(
(
db
.prepare(
'SELECT anime_id AS animeId, group_override AS groupOverride FROM imm_anime WHERE group_override IS NOT NULL',
)
.all() as Array<{ animeId: number; groupOverride: number }>
).map((row) => [row.animeId, row.groupOverride] as const),
);
return getAnimeLibrary(db).map((row) => ({
...row,
groupOverride: overrides.get(row.animeId) ?? null,
}));
}
export function getAnimeLibraryGroups(db: DatabaseSync): AnimeLibraryGroup[] {
return groupAnimeLibrary(
readGroupableLibrary(db),
buildFranchiseGraph(readAnilistRelationCache(db).values()),
);
}
/** The card an entry is listed under, or null when the entry is not in the library list. */
export function getAnimeGroupPlacement(
db: DatabaseSync,
animeId: number,
): AnimeGroupPlacement | null {
const rows = readGroupableLibrary(db);
const row = rows.find((candidate) => candidate.animeId === animeId);
if (!row) return null;
const group = groupAnimeLibrary(
rows,
buildFranchiseGraph(readAnilistRelationCache(db).values()),
).find((candidate) => candidate.parts.some((part) => part.animeId === animeId));
if (!group) return null;
return {
groupKey: group.groupKey,
title: group.title,
partCount: group.parts.length,
overrideMode: overrideMode(row),
};
}
/** Where to put an entry: with another entry's franchise, on its own, or where AniList has it. */
export type AnimeGroupOverrideTarget =
| { mode: 'join'; targetAnimeId: number }
| { mode: 'standalone' }
| { mode: 'anilist' };
export type AnimeGroupOverrideResult =
| { ok: true }
| { ok: false; reason: 'not-found' | 'unsupported-kind' | 'target-not-grouped' };
/**
* Stores the user's grouping choice for one anime entry. Joining stores the
* target's current card key, which is always an AniList id: entries without
* one cannot be joined (merge them instead).
*/
export function setAnimeGroupOverride(
db: DatabaseSync,
animeId: number,
target: AnimeGroupOverrideTarget,
): AnimeGroupOverrideResult {
const row = db
.prepare('SELECT media_kind AS mediaKind FROM imm_anime WHERE anime_id = ?')
.get(animeId) as { mediaKind: string } | undefined;
if (!row) return { ok: false, reason: 'not-found' };
if (row.mediaKind !== 'anime') return { ok: false, reason: 'unsupported-kind' };
let value: number | null = null;
if (target.mode === 'standalone') value = GROUP_OVERRIDE_STANDALONE;
if (target.mode === 'join') {
const placement = getAnimeGroupPlacement(db, target.targetAnimeId);
if (!placement) return { ok: false, reason: 'not-found' };
if (placement.groupKey <= 0) return { ok: false, reason: 'target-not-grouped' };
value = placement.groupKey;
}
db.prepare(
'UPDATE imm_anime SET group_override = ?, group_override_updated_at = ? WHERE anime_id = ?',
).run(value, toDbTimestamp(nowMs()), animeId);
return { ok: true };
}
@@ -10,6 +10,7 @@ import { isVocabularyStatsRowVisible, type VocabularyVisibilityRow } from './voc
import { SCHEMA_VERSION } from './types';
import type { QueuedWrite, VideoMetadata, YoutubeVideoMetadata } from './types';
import { toDbTimestamp } from './query-shared';
import { ensureAnimeGroupingSchema } from './anilist-relation-cache';
export interface TrackerPreparedStatements {
telemetryInsertStmt: ReturnType<DatabaseSync['prepare']>;
@@ -998,6 +999,7 @@ export function ensureSchema(db: DatabaseSync): void {
ensureLifetimeSummaryTables(db);
ensureStatsExcludedWordsTable(db);
ensureAnimeMergeTables(db);
ensureAnimeGroupingSchema(db);
ensureSubtitleLineEventIndex(db);
return;
}
@@ -1064,6 +1066,8 @@ export function ensureSchema(db: DatabaseSync): void {
'INTEGER NOT NULL DEFAULT 0 CHECK(anime_assignment_locked IN (0, 1))',
);
ensureAnimeMergeTables(db);
// Schema 27: franchise grouping (AniList relation cache + per-entry override).
ensureAnimeGroupingSchema(db);
db.exec(`
CREATE TABLE IF NOT EXISTS imm_sessions(
session_id INTEGER PRIMARY KEY AUTOINCREMENT,
+2 -1
View File
@@ -1,7 +1,8 @@
import type { MediaKind, TmdbMediaType } from '../../../shared/media-kind';
// 26: live-action entries (TMDB link) and YouTube channels share the media_kind column.
export const SCHEMA_VERSION = 26;
// 27: AniList relation cache and imm_anime.group_override for franchise grouping.
export const SCHEMA_VERSION = 27;
export const DEFAULT_QUEUE_CAP = 1_000;
export const DEFAULT_BATCH_SIZE = 25;
export const DEFAULT_FLUSH_INTERVAL_MS = 500;
+10
View File
@@ -40,10 +40,14 @@ import {
parseSessionActionDispatchRequest,
parseSubtitlePosition,
parseSubsyncManualRunRequest,
parseUnforwardedMpvKeyReport,
parseYoutubePickerResolveRequest,
} from '../../shared/ipc/validators';
import { createLogger } from '../../logger';
import { applyOverlayClickThrough } from './overlay-click-through';
const overlayInputLogger = createLogger('overlay:input');
const { ipcMain } = electron;
export interface IpcServiceDeps {
@@ -640,6 +644,12 @@ export function registerIpcHandlers(deps: IpcServiceDeps, ipc: IpcMainRegistrar
},
);
// Shows, at --log-level debug, why an mpv input.conf key never reached mpv.
ipc.on(IPC_CHANNELS.command.reportUnforwardedMpvKey, (_event: unknown, payload: unknown) => {
const report = parseUnforwardedMpvKeyReport(payload);
if (report) overlayInputLogger.debug('Overlay kept an mpv-bound key', report);
});
ipc.on(IPC_CHANNELS.command.recordYomitanLookup, (_event: unknown, payload: unknown) => {
try {
deps.recordSubtitleMiningContext?.(parseSubtitleMiningContext(payload));
@@ -0,0 +1,176 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
createOverlayVisibilityDiagnostics,
readOverlayVisibilitySnapshot,
type OverlayVisibilitySnapshot,
} from './overlay-visibility-diagnostics';
type SnapshotArgs = Parameters<typeof readOverlayVisibilitySnapshot>[0];
function snapshotFor(
options: {
tracking?: boolean;
targetPid?: number | null;
minimized?: boolean;
window?: Record<string, unknown>;
noTracker?: boolean;
} & Pick<SnapshotArgs, 'modalActive' | 'suspendVisibleOverlay'> & {
visibleOverlayVisible?: boolean;
} = {},
) {
const tracker = {
isTracking: () => options.tracking ?? false,
getGeometry: () => null,
isTargetWindowFocused: () => false,
isTargetWindowMinimized: () => options.minimized ?? false,
getDiagnosticState: () => ({ targetPid: options.targetPid ?? null, socketPath: '/tmp/mpv' }),
};
return readOverlayVisibilitySnapshot({
mainWindow: {
isDestroyed: () => false,
isVisible: () => false,
getOpacity: () => 0,
...options.window,
} as unknown as SnapshotArgs['mainWindow'],
windowTracker: options.noTracker ? null : (tracker as unknown as SnapshotArgs['windowTracker']),
visibleOverlayVisible: options.visibleOverlayVisible ?? true,
modalActive: options.modalActive,
suspendVisibleOverlay: options.suspendVisibleOverlay,
});
}
function harness() {
let now = 0;
let callback: (() => void) | null = null;
let delay = 0;
const warnings: Array<{ message: string; details: Record<string, unknown> }> = [];
let snapshot: OverlayVisibilitySnapshot | null = {
expectedVisible: true,
visible: false,
opacity: 0,
contentReady: false,
tracking: false,
targetPid: 4242,
pidLookupPending: false,
};
const diagnostics = createOverlayVisibilityDiagnostics({
now: () => now,
warn: (message, details) => warnings.push({ message, details }),
schedule: (fn, ms) => {
callback = fn;
delay = ms;
return { unref() {} } as ReturnType<typeof setTimeout>;
},
cancel: () => {
callback = null;
},
});
const update = () => diagnostics.update(() => snapshot);
return {
warnings,
update,
setSnapshot: (value: typeof snapshot) => {
snapshot = value;
},
tick: () => {
assert.ok(callback, 'watchdog must be scheduled');
now += delay;
callback();
},
scheduled: () => callback !== null,
};
}
test('visibility watchdog warns without more events and rate limits repeated polls', () => {
const h = harness();
h.update();
assert.equal(h.warnings.length, 0);
for (let i = 0; i < 100; i += 1) h.update();
h.tick();
assert.equal(h.warnings.length, 1);
assert.equal(h.warnings[0]?.details.reason, 'mpv-window-not-tracked');
assert.equal(h.warnings[0]?.details.targetPid, 4242);
assert.equal(h.warnings[0]?.details.elapsedMs, 5_000);
for (let i = 0; i < 100; i += 1) h.update();
assert.equal(h.warnings.length, 1);
h.tick();
assert.equal(h.warnings[1]?.details.elapsedMs, 35_000);
});
test('visibility watchdog distinguishes renderer readiness, hidden windows and opacity', () => {
for (const [contentReady, visible, opacity, reason] of [
[false, false, 0, 'renderer-not-ready'],
[true, false, 0, 'window-hidden'],
[true, true, 0, 'window-transparent'],
] as const) {
const h = harness();
h.setSnapshot({ expectedVisible: true, tracking: true, contentReady, visible, opacity });
h.update();
h.tick();
assert.equal(h.warnings[0]?.details.reason, reason);
}
});
test('visibility watchdog reports recovery only after warning and stops', () => {
const h = harness();
h.update();
h.tick();
h.setSnapshot({
expectedVisible: true,
visible: true,
opacity: 1,
contentReady: true,
tracking: true,
});
h.tick();
assert.match(h.warnings[1]!.message, /recovered/);
assert.equal(h.scheduled(), false);
h.update();
assert.equal(h.warnings.length, 2);
});
test('visibility watchdog stays quiet after fast startup, intentional hide or window destruction', () => {
for (const snapshot of [
{ expectedVisible: true, visible: true, opacity: 1, contentReady: true, tracking: true },
{ expectedVisible: false, visible: false, opacity: 0, contentReady: false, tracking: false },
null,
]) {
const h = harness();
h.update();
h.setSnapshot(snapshot);
h.tick();
assert.deepEqual(h.warnings, []);
assert.equal(h.scheduled(), false);
}
});
test('overlay snapshot expects visibility only once an mpv has been identified', () => {
// Requested before any mpv exists: auto_start_overlay, tray or --show-visible-overlay.
assert.equal(snapshotFor()?.expectedVisible, false);
assert.equal(snapshotFor({ noTracker: true })?.expectedVisible, false);
// mpv answered on the socket but its window never matched, so tracking never started.
assert.equal(snapshotFor({ targetPid: 4242 })?.expectedVisible, true);
// A tracker with no target socket matches windows without ever learning a PID.
assert.equal(snapshotFor({ tracking: true })?.expectedVisible, true);
});
test('overlay snapshot does not expect an intentionally hidden overlay', () => {
const identified = { targetPid: 4242, tracking: true };
assert.equal(snapshotFor(identified)?.expectedVisible, true);
assert.equal(snapshotFor({ ...identified, modalActive: true })?.expectedVisible, false);
assert.equal(snapshotFor({ ...identified, suspendVisibleOverlay: true })?.expectedVisible, false);
assert.equal(snapshotFor({ ...identified, minimized: true })?.expectedVisible, false);
assert.equal(
snapshotFor({ ...identified, visibleOverlayVisible: false })?.expectedVisible,
false,
);
});
test('overlay snapshot carries tracker state, defaults opacity and ends with the window', () => {
const snapshot = snapshotFor({ targetPid: 4242, window: { getOpacity: undefined } });
assert.equal(snapshot?.targetPid, 4242);
assert.equal(snapshot?.socketPath, '/tmp/mpv');
assert.equal(snapshot?.opacity, 1);
assert.equal(snapshotFor({ window: { isDestroyed: () => true } }), null);
});
@@ -0,0 +1,153 @@
import type { BrowserWindow } from 'electron';
import type { BaseWindowTracker } from '../../window-trackers';
import { createLogger } from '../../logger';
import {
OVERLAY_WINDOW_CONTENT_READY_FLAG,
OVERLAY_WINDOW_DOCUMENT_LOADED_FLAG,
} from './overlay-window-flags';
const log = createLogger('overlay:visibility');
export type OverlayVisibilitySnapshot = {
expectedVisible: boolean;
visible: boolean;
opacity: number;
contentReady: boolean;
tracking: boolean;
[key: string]: unknown;
};
// One watchdog per window, independent of further visibility events: a renderer
// that never becomes ready must still leave evidence at the default warn level.
export function createOverlayVisibilityDiagnostics(deps: {
warn: (message: string, details: Record<string, unknown>) => void;
now: () => number;
schedule: (callback: () => void, delayMs: number) => ReturnType<typeof setTimeout>;
cancel: (timer: ReturnType<typeof setTimeout>) => void;
}) {
let timer: ReturnType<typeof setTimeout> | null = null;
let readSnapshot: () => OverlayVisibilitySnapshot | null = () => null;
let stalledAtMs: number | null = null;
let warned = false;
let lastWarningAtMs = 0;
const check = () => {
if (timer !== null) deps.cancel(timer);
timer = null;
const snapshot = readSnapshot();
if (!snapshot?.expectedVisible) {
stalledAtMs = null;
warned = false;
return;
}
if (snapshot.visible && snapshot.opacity > 0 && snapshot.contentReady) {
if (warned) {
deps.warn('Windows overlay visibility recovered', {
...snapshot,
elapsedMs: deps.now() - stalledAtMs!,
});
}
stalledAtMs = null;
warned = false;
return;
}
stalledAtMs ??= deps.now();
const elapsedMs = deps.now() - stalledAtMs;
if (elapsedMs >= 5_000 && (!warned || deps.now() - lastWarningAtMs >= 30_000)) {
const reason = !snapshot.tracking
? 'mpv-window-not-tracked'
: !snapshot.contentReady
? 'renderer-not-ready'
: !snapshot.visible
? 'window-hidden'
: 'window-transparent';
deps.warn('Windows overlay is not visible after startup or tracking loss', {
...snapshot,
reason,
elapsedMs,
});
warned = true;
lastWarningAtMs = deps.now();
}
timer = deps.schedule(
check,
warned ? 30_000 - (deps.now() - lastWarningAtMs) : 5_000 - elapsedMs,
);
timer.unref?.();
};
return {
update(reader: () => OverlayVisibilitySnapshot | null) {
readSnapshot = reader;
// Frequent polls must not postpone a warning or bypass its rate limit.
check();
},
};
}
const diagnosticsByWindow = new WeakMap<
BrowserWindow,
ReturnType<typeof createOverlayVisibilityDiagnostics>
>();
type OverlayVisibilityWatchArgs = {
mainWindow: BrowserWindow;
windowTracker: BaseWindowTracker | null;
visibleOverlayVisible: boolean;
modalActive?: boolean;
suspendVisibleOverlay?: boolean;
};
export function readOverlayVisibilitySnapshot(
args: OverlayVisibilityWatchArgs,
): OverlayVisibilitySnapshot | null {
const window = args.mainWindow;
if (window.isDestroyed()) return null;
const tracker = args.windowTracker as
| (BaseWindowTracker & {
getDiagnosticState?: () => { targetPid?: number | null } & Record<string, unknown>;
})
| null;
const trackerState = tracker?.getDiagnosticState?.();
const flags = window as unknown as Record<string, unknown>;
const minimized = tracker?.isTargetWindowMinimized?.() ?? false;
const tracking = tracker?.isTracking() ?? false;
// The overlay may be requested with no mpv to attach to (auto_start_overlay, tray,
// --show-visible-overlay), so it only counts as stalled once an mpv has answered on the
// socket. That still covers an mpv whose window never matches, which never starts tracking.
const mpvIdentified = tracking || (trackerState?.targetPid ?? null) !== null;
return {
...trackerState,
expectedVisible:
args.visibleOverlayVisible &&
mpvIdentified &&
!args.modalActive &&
!args.suspendVisibleOverlay &&
!minimized,
visible: window.isVisible(),
opacity: window.getOpacity?.() ?? 1,
contentReady: flags[OVERLAY_WINDOW_CONTENT_READY_FLAG] === true,
documentLoaded: flags[OVERLAY_WINDOW_DOCUMENT_LOADED_FLAG] === true,
rendererLoading: window.webContents?.isLoading?.() ?? null,
tracking,
trackerInitialized: tracker !== null,
geometry: tracker?.getGeometry() ?? null,
focused: tracker?.isTargetWindowFocused?.() ?? false,
minimized,
};
}
export function watchWindowsOverlayVisibility(args: OverlayVisibilityWatchArgs): void {
const window = args.mainWindow;
let diagnostics = diagnosticsByWindow.get(window);
if (!diagnostics) {
diagnostics = createOverlayVisibilityDiagnostics({
warn: (message, details) => log.warn(message, details),
now: Date.now,
schedule: setTimeout,
cancel: clearTimeout,
});
diagnosticsByWindow.set(window, diagnostics);
}
diagnostics.update(() => readOverlayVisibilitySnapshot(args));
}
@@ -589,6 +589,34 @@ runScenarios([
},
]);
test('only a live Windows overlay reads visibility diagnostics', () => {
const diagnosticReads = (platform: Platform, overrides: Partial<VisibilityArgs> = {}): number => {
let reads = 0;
createHarness({ platform, tracker: tracked() }).run({
windowTracker: {
isTracking: () => true,
getGeometry: () => GEOMETRY,
getDiagnosticState: () => {
reads += 1;
return { targetPid: 4242 };
},
} as unknown as VisibilityArgs['windowTracker'],
...overrides,
});
return reads;
};
assert.equal(diagnosticReads('windows'), 1);
assert.equal(diagnosticReads('linux'), 0);
assert.equal(diagnosticReads('macos'), 0);
assert.equal(
diagnosticReads('windows', {
mainWindow: { isDestroyed: () => true } as unknown as VisibilityArgs['mainWindow'],
}),
0,
);
});
test('Windows visible overlay restores opacity and rebinds after the deferred reveal delay', async () => {
const h = createHarness({ platform: 'windows', tracker: tracked() });
assertOutcome(h.run(), { opacity: 0, zOrderSyncs: 1 });
+11 -1
View File
@@ -3,6 +3,7 @@ import { BaseWindowTracker } from '../../window-trackers';
import { WindowGeometry } from '../../types';
import { applyOverlayClickThrough } from './overlay-click-through';
import { OVERLAY_WINDOW_CONTENT_READY_FLAG } from './overlay-window-flags';
import { watchWindowsOverlayVisibility } from './overlay-visibility-diagnostics';
const WINDOWS_OVERLAY_REVEAL_DELAY_MS = 48;
const pendingWindowsOverlayRevealTimeoutByWindow = new WeakMap<
@@ -65,7 +66,7 @@ function isOverlayWindowContentReady(window: BrowserWindow): boolean {
);
}
export function updateVisibleOverlayVisibility(args: {
function applyVisibleOverlayVisibility(args: {
visibleOverlayVisible: boolean;
modalActive?: boolean;
forceMousePassthrough?: boolean;
@@ -453,6 +454,15 @@ export function updateVisibleOverlayVisibility(args: {
args.syncOverlayShortcuts();
}
export function updateVisibleOverlayVisibility(
args: Parameters<typeof applyVisibleOverlayVisibility>[0],
): void {
applyVisibleOverlayVisibility(args);
if (args.isWindowsPlatform && args.mainWindow && !args.mainWindow.isDestroyed()) {
watchWindowsOverlayVisibility({ ...args, mainWindow: args.mainWindow });
}
}
export function setVisibleOverlayVisible(options: {
visible: boolean;
setVisibleOverlayVisibleState: (visible: boolean) => void;
@@ -11,6 +11,7 @@ import {
enrichSessionsWithKnownWordMetrics,
isPositiveSafeInteger,
loadKnownWordsSet,
parseAnimeGroupOverrideBody,
parseBooleanQuery,
parseDuplicateLineCleanupBody,
parseExcludedWordsBody,
@@ -190,6 +191,11 @@ export function registerStatsLibraryRoutes(
return c.json(statsJson('animeLibrary', rows));
});
// Registered before `/api/stats/anime/:animeId` so `groups` is not read as an id.
app.get('/api/stats/anime/groups', async (c) => {
return c.json(statsJson('animeLibraryGroups', await tracker.getAnimeLibraryGroups()));
});
app.get('/api/stats/anime/merge-recommendations', async (c) => {
const recommendations = await tracker.getAnimeMergeRecommendations();
return c.json(statsJson('animeMergeRecommendations', { recommendations }));
@@ -208,11 +214,12 @@ export function registerStatsLibraryRoutes(
if (animeId === null) return c.body(null, 400);
const detail = await tracker.getAnimeDetail(animeId);
if (!detail) return c.body(null, 404);
const [episodes, anilistEntries] = await Promise.all([
const [episodes, anilistEntries, group] = await Promise.all([
tracker.getAnimeEpisodes(animeId),
tracker.getAnimeAnilistEntries(animeId),
tracker.getAnimeGroupPlacement(animeId),
]);
return c.json(statsJson('animeDetail', { detail, episodes, anilistEntries }));
return c.json(statsJson('animeDetail', { detail, episodes, anilistEntries, group }));
});
app.get('/api/stats/anime/:animeId/words', async (c) => {
@@ -267,6 +274,22 @@ export function registerStatsLibraryRoutes(
return c.json(statsJson('deleteAnime', { ok: true }));
});
app.put('/api/stats/anime/:animeId/group', async (c) => {
const animeId = parsePositiveId(c.req.param('animeId'));
if (animeId === null) return c.body(null, 400);
const request = parseAnimeGroupOverrideBody(await c.req.json().catch(() => null));
if (!request) return c.body(null, 400);
if (request.mode === 'join' && request.targetAnimeId === animeId) return c.body(null, 400);
const result = await tracker.setAnimeGroupOverride(animeId, request);
if (result.ok) return c.json(statsJson('setAnimeGroupOverride', { ok: true }));
if (result.reason === 'not-found') return c.body(null, 404);
const error =
result.reason === 'unsupported-kind'
? 'Only anime entries can be grouped.'
: 'That title has no AniList entry to group with. Link it to AniList or merge the entries instead.';
return c.json(statsJson('error', { error }), 409);
});
app.post('/api/stats/anime/:animeId/merge', async (c) => {
const animeId = parsePositiveId(c.req.param('animeId'));
if (animeId === null) return c.body(null, 400);
@@ -13,6 +13,7 @@ import {
import { createLogger } from '../../../logger.js';
import type { AnkiConnectConfig } from '../../../types.js';
import type {
StatsAnimeGroupOverrideRequest,
StatsDayRange,
StatsDictionaryWordQuery,
StatsDictionaryWordSort,
@@ -59,6 +60,15 @@ export function isPositiveSafeInteger(value: unknown): value is number {
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
}
/** Validates a `PUT /api/stats/anime/:animeId/group` body; null for anything malformed. */
export function parseAnimeGroupOverrideBody(body: unknown): StatsAnimeGroupOverrideRequest | null {
if (!body || typeof body !== 'object') return null;
const { mode, targetAnimeId } = body as Record<string, unknown>;
if (mode === 'standalone' || mode === 'anilist') return { mode };
if (mode === 'join' && isPositiveSafeInteger(targetAnimeId)) return { mode, targetAnimeId };
return null;
}
export function parsePositiveId(raw: string | undefined): number | null {
if (raw === undefined) return null;
const value = Number(raw);
@@ -58,3 +58,78 @@ for (const [localKind, remoteKind, sameEntry] of [
}
});
}
test('franchise override follows whichever side set or cleared it last', () => {
const adapt = (db: DatabaseSync) => ({
query: (sql: string) => db.prepare(sql),
exec: (sql: string) => {
db.exec(sql);
},
close: () => {
db.close();
},
});
const cases: Array<{
name: string;
local: [number | null, string | null];
remote: [number | null, string | null];
expected: number | null;
}> = [
{
name: 'newer remote join wins',
local: [null, null],
remote: [20832, '2000'],
expected: 20832,
},
{ name: 'newer remote clear wins', local: [0, '1000'], remote: [null, '2000'], expected: null },
{ name: 'older remote loses', local: [0, '3000'], remote: [20832, '2000'], expected: 0 },
{ name: 'untouched remote keeps local', local: [0, '1000'], remote: [null, null], expected: 0 },
];
for (const c of cases) {
const local = new Database(':memory:');
const remote = new Database(':memory:');
try {
for (const [db, [override, updatedAt]] of [
[local, c.local],
[remote, c.remote],
] as const) {
ensureSchema(db);
db.prepare(
`INSERT INTO imm_anime(normalized_title_key, canonical_title, anilist_id, group_override, group_override_updated_at)
VALUES ('overlord ii', 'Overlord II', 98437, ?, ?)`,
).run(override, updatedAt);
}
mergeAnime(adapt(local), adapt(remote), createEmptyMergeSummary());
const row = local.prepare('SELECT group_override AS value FROM imm_anime').get() as {
value: number | null;
};
assert.equal(row.value, c.expected, c.name);
} finally {
local.close();
remote.close();
}
}
const local = new Database(':memory:');
const remote = new Database(':memory:');
try {
ensureSchema(local);
ensureSchema(remote);
remote
.prepare(
`INSERT INTO imm_anime(normalized_title_key, canonical_title, group_override, group_override_updated_at)
VALUES ('specials', 'Specials', 20832, '1000')`,
)
.run();
mergeAnime(adapt(local), adapt(remote), createEmptyMergeSummary());
const row = local
.prepare(
'SELECT group_override AS value, group_override_updated_at AS updatedAt FROM imm_anime',
)
.get() as { value: number | null; updatedAt: string | null };
assert.deepEqual([row.value, row.updatedAt], [20832, '1000']);
} finally {
local.close();
remote.close();
}
});
@@ -15,6 +15,8 @@ const ANIME_COPY_COLUMNS = [
'tmdb_id',
'tmdb_type',
'metadata_json',
'group_override',
'group_override_updated_at',
'CREATED_DATE',
'LAST_UPDATE_DATE',
] as const;
@@ -146,6 +148,13 @@ export function mergeAnime(
END
WHERE anime_id = ?`,
);
// The franchise override holds AniList ids (or 0 / NULL), so it needs no id
// remapping. The side that set or cleared it last wins.
const takeNewerGroupOverride = local.query(
`UPDATE imm_anime SET group_override = ?, group_override_updated_at = ?
WHERE anime_id = ? AND (group_override_updated_at IS NULL
OR CAST(group_override_updated_at AS INTEGER) < CAST(? AS INTEGER))`,
);
for (const row of selectAll(
remote,
@@ -195,6 +204,14 @@ export function mergeAnime(
row.media_kind,
localId,
);
if (row.group_override_updated_at !== null) {
takeNewerGroupOverride.run(
row.group_override,
row.group_override_updated_at,
localId,
row.group_override_updated_at,
);
}
continue;
}
// Conflicting providers can share a title, but the stored title key is
+5
View File
@@ -20,6 +20,11 @@ export type { SyncMergeSummary } from './shared';
* are updated incrementally so history older than the session retention
* window is preserved on both sides. Idempotent: re-merging the same
* snapshot is a no-op.
*
* A library entry's franchise override (`group_override`) is last-writer-wins
* by `group_override_updated_at`. The AniList relation cache
* (`imm_anilist_media`, `imm_anilist_relations`) is not merged: each machine
* rebuilds it from AniList.
*/
export function mergeSnapshotIntoDb(localDbPath: string, snapshotPath: string): SyncMergeSummary {
if (!fs.existsSync(localDbPath)) {
+4
View File
@@ -1,6 +1,7 @@
import path from 'node:path';
import { ImmersionTrackerService } from '../../core/services';
import { createCoverArtFetcher } from '../../core/services/anilist/cover-art-fetcher';
import { createAnilistRelationFetcher } from '../../core/services/anilist/franchise-relation-fetcher';
import type { createAnilistRateLimiter } from '../../core/services/anilist/rate-limiter';
import { resolveLegacyVocabularyPosFromTokens } from '../../core/services/immersion-tracker/legacy-vocabulary-pos';
import type { StatsWindowOptions } from '../../core/services/stats-window';
@@ -172,6 +173,8 @@ export function createStatsAssembly(deps: StatsAssemblyDeps) {
},
);
const anilistRelationFetcher = createAnilistRelationFetcher(deps.anilistRateLimiter);
// One options object serves the overlay's IPC toggle and the session-action toggle.
const statsOverlayOptions: StatsWindowOptions = {
preloadPath: path.join(deps.mainDirname, 'preload-stats.js'),
@@ -235,6 +238,7 @@ export function createStatsAssembly(deps: StatsAssemblyDeps) {
appState.immersionTracker = tracker as ImmersionTrackerService | null;
appState.immersionTracker?.setCoverArtFetcher(coverArtFetcher);
appState.immersionTracker?.setAnilistRelationFetcher(anilistRelationFetcher);
if (tracker) {
// Start HTTP stats server
if (!appState.statsServer) {
+5
View File
@@ -19,6 +19,7 @@
import { clipboard, contextBridge, ipcRenderer, IpcRendererEvent, webUtils } from 'electron';
import { resolveOverlayLayerFromArgv } from './preload-args';
import { createIpcListenerFactories } from './preload-ipc-listeners';
import type { UnforwardedMpvKeyReport } from './types/session-bindings';
import {
DICTIONARY_EXTERNAL_LINK_CHANNEL,
parseDictionaryExternalUrl,
@@ -329,6 +330,10 @@ const electronAPI: ElectronAPI = {
ipcRenderer.send(IPC_CHANNELS.command.recordYomitanLookup, context ?? null);
},
reportUnforwardedMpvKey: (report: UnforwardedMpvKeyReport) => {
ipcRenderer.send(IPC_CHANNELS.command.reportUnforwardedMpvKey, report);
},
getSubtitlePosition: (): Promise<SubtitlePosition | null> =>
ipcRenderer.invoke(IPC_CHANNELS.request.getSubtitlePosition),
saveSubtitlePosition: (position: SubtitlePosition) => {
+26
View File
@@ -150,6 +150,7 @@ function installKeyboardTestGlobals() {
let markActiveVideoWatchedCalls = 0;
let statsToggleOverlayCalls = 0;
const openedModalNotifications: string[] = [];
const unforwardedMpvKeys: Array<{ key: string; reason: string }> = [];
let selectionClearCount = 0;
let selectionAddCount = 0;
let mutationRecordsTaken = 0;
@@ -252,6 +253,9 @@ function installKeyboardTestGlobals() {
sendMpvCommand: (command: Array<string | number>) => {
mpvCommands.push(command);
},
reportUnforwardedMpvKey: (report: { key: string; reason: string }) => {
unforwardedMpvKeys.push(report);
},
dispatchSessionAction: async (actionId: string, payload?: unknown) => {
sessionActions.push({ actionId, payload });
},
@@ -518,6 +522,7 @@ function installKeyboardTestGlobals() {
markActiveVideoWatchedCalls: () => markActiveVideoWatchedCalls,
statsToggleOverlayCalls: () => statsToggleOverlayCalls,
openedModalNotifications,
unforwardedMpvKeys,
getPlaybackPaused: async () => playbackPausedResponse,
setPlaybackPausedResponse: (value: boolean | null) => {
playbackPausedResponse = value;
@@ -2570,6 +2575,27 @@ test('discovered mpv keys only run after SubMiner controls and stay out of sessi
}
});
test('imported mpv keys forward once the popup closes, even if the cached popup flag lags', async () => {
const { handlers, testGlobals, ctx } = createKeyboardHandlerHarness();
try {
testGlobals.setGetMpvInputBindings(async () => ({ keys: ['r'], blockedKeys: [] }));
await handlers.setupMpvInputForwarding();
await wait(0);
testGlobals.setPopupVisible(true);
testGlobals.dispatchKeydown({ key: 'r', code: 'KeyR' });
assert.deepEqual(testGlobals.mpvCommands, []);
assert.deepEqual(testGlobals.unforwardedMpvKeys, [{ key: 'r', reason: 'lookup-popup' }]);
// #331: the popup closed, but a late popup event left the cached flag set.
testGlobals.setPopupVisible(false);
ctx.state.yomitanPopupVisible = true;
testGlobals.dispatchKeydown({ key: 'r', code: 'KeyR' });
assert.deepEqual(testGlobals.mpvCommands, [['keydown', 'r']]);
} finally {
testGlobals.restore();
}
});
test('stalled mpv discovery does not delay configured overlay controls', async () => {
const { handlers, testGlobals } = createKeyboardHandlerHarness();
try {
+26 -8
View File
@@ -1,4 +1,5 @@
import type { CompiledSessionBinding, PrimarySubMode, ShortcutsConfig } from '../../types';
import type { MpvKeyForwardBlock } from '../../types/session-bindings';
import type { RendererContext } from '../context';
import { createMpvInputForwarding } from './mpv-input-forwarding';
import { MPV_MOUSE_BUTTON_BY_BUTTON, wheelEventToMpvWheel } from '../../shared/mpv-input-bindings';
@@ -141,14 +142,24 @@ export function createKeyboardHandlers(
// Imported mpv bindings only run when no SubMiner UI could be the input's target.
// The subtitle sidebar is a side panel over playback, so only input inside it (a
// `.modal` target) stays with SubMiner.
// Why imported mpv input must stay in the overlay right now, or null when it may forward.
// SubMiner's own keybindings never pass through here.
function getMpvForwardBlock(target: EventTarget | null): MpvKeyForwardBlock | null {
if (!keyboardConfigLoaded) return 'config-loading';
if (ctx.state.playlistBrowserModalOpen || ctx.state.youtubePickerModalOpen) return 'modal';
if (isLookupPopupOpen(ctx.state, document)) return 'lookup-popup';
if (isInteractiveTarget(target)) return 'interactive-target';
return null;
}
function canForwardToMpv(target: EventTarget | null): boolean {
return (
keyboardConfigLoaded &&
!ctx.state.playlistBrowserModalOpen &&
!ctx.state.youtubePickerModalOpen &&
!isLookupPopupOpen(ctx.state, document) &&
!isInteractiveTarget(target)
);
return getMpvForwardBlock(target) === null;
}
// Debug breadcrumb for "my mpv key does nothing": the main process logs it at debug level.
function reportUnforwardedMpvKey(e: KeyboardEvent, reason: MpvKeyForwardBlock): void {
const report = importedMpvBindings.unforwardedReport(e, reason);
if (report) window.electronAPI.reportUnforwardedMpvKey(report);
}
// Scrolling over subtitles still reaches mpv; only scrollable overlay UI keeps the wheel.
@@ -1403,6 +1414,7 @@ export function createKeyboardHandlers(
if (isLookupPopupOpen(ctx.state, document)) {
if (handleYomitanPopupKeybind(e)) {
reportUnforwardedMpvKey(e, 'lookup-popup');
e.preventDefault();
return;
}
@@ -1469,7 +1481,13 @@ export function createKeyboardHandlers(
e.preventDefault();
return;
}
if (canForwardToMpv(e.target)) importedMpvBindings.keydown(e);
const forwardBlock = getMpvForwardBlock(e.target);
if (forwardBlock) {
reportUnforwardedMpvKey(e, forwardBlock);
} else if (!importedMpvBindings.keydown(e)) {
// Reports only while nothing is imported; an unbound key is not worth a line.
reportUnforwardedMpvKey(e, 'no-imported-bindings');
}
});
document.addEventListener('mousedown', (e: MouseEvent) => {
@@ -175,3 +175,50 @@ test('focus loss releases held keys and failed refresh clears stale bindings', a
await forwarding.refresh();
assert.equal(forwarding.keydown(keyEvent()), false);
});
test('a reload keeps forwarding the current keys until it settles', async () => {
let resolveReload: (snapshot: MpvInputBindingsSnapshot) => void = () => {};
let loads = 0;
const forwarding = createMpvInputForwarding({
load: () => {
loads += 1;
if (loads === 1) return Promise.resolve({ keys: ['r'], blockedKeys: [] });
return new Promise((resolve) => {
resolveReload = resolve;
});
},
send: () => {},
});
await forwarding.refresh();
const reload = forwarding.refresh();
assert.equal(forwarding.keydown(keyEvent()), true);
forwarding.keyup(keyEvent());
resolveReload({ keys: ['t'], blockedKeys: [] });
await reload;
assert.equal(forwarding.keydown(keyEvent()), false);
assert.equal(forwarding.keydown(keyEvent({ key: 't', code: 'KeyT' })), true);
});
test('unforwarded reports name keys mpv binds, or any key while nothing is imported', async () => {
let snapshot: MpvInputBindingsSnapshot = { keys: [], blockedKeys: [] };
const forwarding = createMpvInputForwarding({ load: async () => snapshot, send: () => {} });
await forwarding.refresh();
assert.deepEqual(forwarding.unforwardedReport(keyEvent(), 'lookup-popup'), {
key: 'r',
reason: 'no-imported-bindings',
});
assert.equal(
forwarding.unforwardedReport(keyEvent({ key: 'Shift', code: 'ShiftLeft' }), 'lookup-popup'),
null,
);
snapshot = { keys: ['r', 't'], blockedKeys: [{ code: 'KeyT', modifiers: [] }] };
await forwarding.refresh();
assert.deepEqual(forwarding.unforwardedReport(keyEvent(), 'interactive-target'), {
key: 'r',
reason: 'interactive-target',
});
assert.equal(forwarding.unforwardedReport(keyEvent(), 'no-imported-bindings'), null);
assert.equal(forwarding.unforwardedReport(keyEvent({ key: 't', code: 'KeyT' }), 'modal'), null);
assert.equal(forwarding.unforwardedReport(keyEvent({ key: 'z', code: 'KeyZ' }), 'modal'), null);
});
+44 -10
View File
@@ -4,7 +4,13 @@ import {
normalizeMpvInputKey,
wheelEventToMpvWheel,
} from '../../shared/mpv-input-bindings';
import type { MpvInputBindingsSnapshot } from '../../types/session-bindings';
import type {
MpvInputBindingsSnapshot,
MpvKeyForwardBlock,
UnforwardedMpvKeyReport,
} from '../../types/session-bindings';
const MODIFIER_ONLY_KEYS = new Set(['Shift', 'Control', 'Alt', 'Meta', 'AltGraph']);
type ModifierState = Pick<KeyboardEvent, 'ctrlKey' | 'altKey' | 'shiftKey' | 'metaKey'>;
type ForwardedKeyEvent = Parameters<typeof keyboardEventToMpvKey>[0] &
@@ -31,25 +37,26 @@ export function createMpvInputForwarding(deps: {
heldKeys.clear();
}
// Every window focus refreshes, so the current list keeps forwarding until the reload
// settles; a key pressed mid-reload would otherwise be dropped.
function refresh(): Promise<void> {
if (disposed) return Promise.resolve();
generation += 1;
keys.clear();
blockedKeys = [];
releaseAll();
if (pending) return pending;
pending = (async () => {
let requestedGeneration: number;
do {
requestedGeneration = generation;
let snapshot: MpvInputBindingsSnapshot | null = null;
try {
const snapshot = await deps.load();
if (!disposed && requestedGeneration === generation) {
keys = new Set(snapshot.keys);
blockedKeys = snapshot.blockedKeys;
}
snapshot = await deps.load();
} catch {
// Discovery is optional. Keep the existing overlay controls available.
// Discovery is optional: SubMiner's own bindings keep working without it.
}
if (!disposed && requestedGeneration === generation) {
keys = new Set(snapshot?.keys ?? []);
blockedKeys = snapshot?.blockedKeys ?? [];
}
} while (!disposed && requestedGeneration !== generation);
})().finally(() => {
@@ -98,6 +105,23 @@ export function createMpvInputForwarding(deps: {
return true;
}
/**
* The debug report for a key the overlay kept from mpv, or null when mpv does not bind
* it. With nothing imported yet, every nameable key is reported as such.
*/
function unforwardedReport(
event: ForwardedKeyEvent,
reason: MpvKeyForwardBlock,
): UnforwardedMpvKeyReport | null {
if (disposed || event.repeat || MODIFIER_ONLY_KEYS.has(event.key)) return null;
const key = keyboardEventToMpvKey(event);
if (!key) return null;
if (keys.size === 0) return { key, reason: 'no-imported-bindings' };
if (reason === 'no-imported-bindings') return null;
if (isBlocked(event.code, event) || !keys.has(key)) return null;
return { key, reason };
}
function keyup(event: Pick<KeyboardEvent, 'code' | 'preventDefault'>): void {
const key = heldKeys.get(event.code);
if (!key) return;
@@ -154,5 +178,15 @@ export function createMpvInputForwarding(deps: {
releaseAll();
}
return { refresh, keydown, keyup, wheel, mousedown, mouseup, releaseAll, dispose };
return {
refresh,
keydown,
keyup,
wheel,
mousedown,
mouseup,
releaseAll,
dispose,
unforwardedReport,
};
}
+4 -2
View File
@@ -125,11 +125,13 @@ export function isHachidoriPopupOpen(root: ParentNode | null | undefined = docum
* (the shown event and the host's visible marker) also covers a plain press.
*/
export function isLookupPopupOpen(
state: { yomitanPopupVisible: boolean; hachidoriReaderSeen: boolean },
state: { hachidoriReaderSeen: boolean },
root: ParentNode | null | undefined = document,
): boolean {
if (state.hachidoriReaderSeen) return isHachidoriPopupOpen(root);
return state.yomitanPopupVisible || isYomitanPopupVisible(root);
// The fork marks the host before it fires the shown event, so the DOM is authoritative.
// The cached yomitanPopupVisible flag can lag a close (#331) and would keep stealing keys.
return isYomitanPopupVisible(root);
}
export function isYomitanPopupVisible(root: ParentNode | null | undefined = document): boolean {
+1
View File
@@ -27,6 +27,7 @@ export const IPC_CHANNELS = {
setIgnoreMouseEvents: 'set-ignore-mouse-events',
overlayModalClosed: 'overlay:modal-closed',
recordYomitanLookup: 'record-yomitan-lookup',
reportUnforwardedMpvKey: 'overlay:unforwarded-mpv-key',
youtubePickerResolve: 'youtube:picker-resolve',
toggleDevTools: 'toggle-dev-tools',
saveSubtitlePosition: 'save-subtitle-position',
+11 -1
View File
@@ -4,7 +4,7 @@ import test from 'node:test';
import { DEFAULT_CONFIG, DEFAULT_KEYBINDINGS } from '../../config/definitions';
import { compileSessionBindings } from '../../core/services/session-bindings';
import { resolveConfiguredShortcuts } from '../../core/utils/shortcut-config';
import { parseSessionActionDispatchRequest } from './validators';
import { parseSessionActionDispatchRequest, parseUnforwardedMpvKeyReport } from './validators';
// Regression guard: SESSION_ACTION_IDS in validators.ts is a hand-maintained mirror of the
// SessionActionId union. If a new shortcut-backed action is added to the union/defaults but not to
@@ -36,3 +36,13 @@ test('every default session-action binding is accepted by parseSessionActionDisp
);
}
});
test('unforwarded mpv key reports accept known reasons only', () => {
assert.deepEqual(parseUnforwardedMpvKeyReport({ key: 'LEFT', reason: 'lookup-popup' }), {
key: 'LEFT',
reason: 'lookup-popup',
});
assert.equal(parseUnforwardedMpvKeyReport({ key: 'LEFT', reason: 'toString' }), null);
assert.equal(parseUnforwardedMpvKeyReport({ key: '', reason: 'modal' }), null);
assert.equal(parseUnforwardedMpvKeyReport(null), null);
});
+26 -1
View File
@@ -14,7 +14,12 @@ import type {
SubsyncManualRunRequest,
} from '../../types/runtime';
import type { RuntimeOptionId, RuntimeOptionValue } from '../../types/runtime-options';
import type { SessionActionId, SessionActionPayload } from '../../types/session-bindings';
import type {
MpvKeyForwardBlock,
SessionActionId,
SessionActionPayload,
UnforwardedMpvKeyReport,
} from '../../types/session-bindings';
import type { SubtitlePosition } from '../../types/subtitle';
import { OVERLAY_HOSTED_MODALS, type OverlayHostedModal } from './contracts';
import { isControllerFaceButtonLabels, parseControllerDiscreteBinding } from '../controller-review';
@@ -365,6 +370,26 @@ export function parseMpvCommand(value: unknown): Array<string | number> | null {
: null;
}
// A Record so a new MpvKeyForwardBlock member fails typecheck until it is listed here.
const MPV_KEY_FORWARD_BLOCKS: Record<MpvKeyForwardBlock, true> = {
'config-loading': true,
modal: true,
'lookup-popup': true,
'interactive-target': true,
'no-imported-bindings': true,
};
function isMpvKeyForwardBlock(value: unknown): value is MpvKeyForwardBlock {
return typeof value === 'string' && Object.hasOwn(MPV_KEY_FORWARD_BLOCKS, value);
}
export function parseUnforwardedMpvKeyReport(value: unknown): UnforwardedMpvKeyReport | null {
if (!isObject(value)) return null;
const { key, reason } = value;
if (typeof key !== 'string' || key.length === 0 || key.length > 64) return null;
return isMpvKeyForwardBlock(reason) ? { key, reason } : null;
}
export function parseOptionalForwardingOptions(value: unknown): {
forward?: boolean;
} {
+5 -1
View File
@@ -6,6 +6,7 @@ import { ConfigService } from './config/service';
import { createLogger, setLogLevel } from './logger';
import { ImmersionTrackerService } from './core/services/immersion-tracker-service';
import { createCoverArtFetcher } from './core/services/anilist/cover-art-fetcher';
import { createAnilistRelationFetcher } from './core/services/anilist/franchise-relation-fetcher';
import { createAnilistRateLimiter } from './core/services/anilist/rate-limiter';
import { createLiveActionMetadataResolver } from './core/services/tmdb/live-action-resolver';
import { createTmdbClient, createTmdbApiKeyResolver } from './core/services/tmdb/tmdb-client';
@@ -212,11 +213,14 @@ async function main(): Promise<void> {
() => bundledTmdbApiKey,
),
});
// Cover art and franchise relations share one AniList request budget.
const anilistRateLimiter = createAnilistRateLimiter();
tracker.setCoverArtFetcher(
createCoverArtFetcher(createAnilistRateLimiter(), createLogger('stats-daemon:cover-art'), {
createCoverArtFetcher(anilistRateLimiter, createLogger('stats-daemon:cover-art'), {
liveAction: createLiveActionMetadataResolver(tmdbClient, createLogger('stats-daemon:tmdb')),
}),
);
tracker.setAnilistRelationFetcher(createAnilistRelationFetcher(anilistRateLimiter));
statsServer = await startStatsServer({
port: config.stats.serverPort,
+3 -1
View File
@@ -1,4 +1,4 @@
import type { MpvInputBindingsSnapshot } from './session-bindings';
import type { MpvInputBindingsSnapshot, UnforwardedMpvKeyReport } from './session-bindings';
import type {
KikuFieldGroupingChoice,
KikuFieldGroupingRequestData,
@@ -600,6 +600,8 @@ export interface ElectronAPI {
setIgnoreMouseEvents: (ignore: boolean, options?: { forward?: boolean }) => void;
reportOverlayInteractive: (interactive: boolean) => void;
recordYomitanLookup: (context?: SubtitleMiningContext | null) => void;
/** Debug-only: the overlay kept a key that mpv binds. */
reportUnforwardedMpvKey: (report: UnforwardedMpvKeyReport) => void;
getSubtitlePosition: () => Promise<SubtitlePosition | null>;
saveSubtitlePosition: (position: SubtitlePosition) => void;
sendMpvCommand: (command: (string | number)[]) => void;
+14
View File
@@ -13,6 +13,20 @@ export interface MpvInputBindingsSnapshot {
blockedKeys: SessionKeySpec[];
}
/** Why the overlay kept a key that mpv binds instead of forwarding it. */
export type MpvKeyForwardBlock =
| 'config-loading'
| 'modal'
| 'lookup-popup'
| 'interactive-target'
| 'no-imported-bindings';
/** Debug report the overlay sends when it does not forward an mpv-bound key. */
export interface UnforwardedMpvKeyReport {
key: string;
reason: MpvKeyForwardBlock;
}
export interface SessionBindingWarning {
kind: 'unsupported' | 'conflict' | 'deprecated-config';
path: string;
+18
View File
@@ -1,5 +1,6 @@
import type {
AnimeDetailData,
AnimeLibraryGroup,
AnimeLibraryItem,
AnimeWord,
DailyRollup,
@@ -187,6 +188,16 @@ export interface StatsMoveVideoRequest {
animeId: number;
}
/**
* Body of `PUT /api/stats/anime/:animeId/group`: list the entry with another
* entry's franchise (`join`), on its own (`standalone`), or where AniList's
* relations put it (`anilist`, which clears the override).
*/
export type StatsAnimeGroupOverrideRequest =
| { mode: 'join'; targetAnimeId: number }
| { mode: 'standalone' }
| { mode: 'anilist' };
export interface StatsAnimeMergeRecommendation {
recommendationId: number;
animeIds: [number, number];
@@ -251,6 +262,7 @@ export interface StatsJsonResponseMap {
mediaLibrary: MediaLibraryItem[];
mediaDetail: MediaDetailData;
animeLibrary: AnimeLibraryItem[];
animeLibraryGroups: AnimeLibraryGroup[];
animeMergeRecommendations: StatsAnimeMergeRecommendationsResponse;
animeDetail: AnimeDetailData;
animeWords: AnimeWord[];
@@ -262,6 +274,7 @@ export interface StatsJsonResponseMap {
deleteAnime: StatsOkResponse;
mergeAnime: StatsMergeAnimeResponse;
moveVideoToAnime: StatsMoveVideoResponse;
setAnimeGroupOverride: StatsOkResponse;
dismissAnimeMergeRecommendation: StatsOkResponse;
anilistSearch: StatsAnilistSearchResult[];
tmdbSearch: StatsTmdbSearchResult[];
@@ -330,6 +343,7 @@ export interface StatsHttpClient {
getMediaLibrary: () => Promise<MediaLibraryItem[]>;
getMediaDetail: (videoId: number) => Promise<MediaDetailData>;
getAnimeLibrary: () => Promise<AnimeLibraryItem[]>;
getAnimeLibraryGroups: () => Promise<AnimeLibraryGroup[]>;
getAnimeMergeRecommendations: () => Promise<StatsAnimeMergeRecommendationsResponse>;
getAnimeDetail: (animeId: number) => Promise<AnimeDetailData>;
getAnimeWords: (animeId: number, limit?: number) => Promise<AnimeWord[]>;
@@ -356,6 +370,10 @@ export interface StatsHttpClient {
deleteAnime: (animeId: number) => Promise<void>;
mergeAnime: (targetAnimeId: number, sourceAnimeIds: number[]) => Promise<StatsMergeAnimeResponse>;
moveVideoToAnime: (videoId: number, animeId: number) => Promise<StatsMoveVideoResponse>;
setAnimeGroupOverride: (
animeId: number,
request: StatsAnimeGroupOverrideRequest,
) => Promise<void>;
dismissAnimeMergeRecommendation: (recommendationId: number) => Promise<void>;
getKnownWords: () => Promise<string[]>;
getKnownWordsSummary: () => Promise<StatsKnownWordsSummary>;
+42
View File
@@ -306,6 +306,46 @@ export interface AnimeLibraryItem {
lastWatchedMs: number;
}
/** One library entry inside a franchise group, with its AniList format and start date when cached. */
export interface AnimeLibraryGroupPart extends AnimeLibraryItem {
/** AniList format (TV, MOVIE, OVA...); null without a cached AniList entry. */
format: string | null;
/** AniList start date as yyyymmdd (month/day 0 when unknown); null when unknown. */
startDate: number | null;
}
/**
* A library card: one franchise (seasons, movies and OVAs that AniList links
* together) or a single entry. Totals add up the parts; `lastWatchedMs` is the
* latest part's. Parts are in AniList release order.
*/
export interface AnimeLibraryGroup {
/** AniList id the franchise is named after, or minus the entry's animeId for a card of its own. */
groupKey: number;
title: string;
mediaKind: MediaKind;
/** Entry whose cover the card shows: the first part by release date. */
coverAnimeId: number;
totalSessions: number;
totalActiveMs: number;
totalCards: number;
totalTokensSeen: number;
episodeCount: number;
lastWatchedMs: number;
parts: AnimeLibraryGroupPart[];
}
/** How a library entry's franchise was chosen: by AniList, moved by the user, or kept on its own. */
export type AnimeGroupOverrideMode = 'anilist' | 'joined' | 'standalone';
/** Where one library entry sits in the grouped library. */
export interface AnimeGroupPlacement {
groupKey: number;
title: string;
partCount: number;
overrideMode: AnimeGroupOverrideMode;
}
export interface AnilistEntry {
anilistId: number;
titleRomaji: string | null;
@@ -338,6 +378,8 @@ export interface AnimeDetailData {
};
episodes: AnimeEpisode[];
anilistEntries: AnilistEntry[];
/** Null when the entry has no watch history to list in the library. */
group: AnimeGroupPlacement | null;
}
export interface AnimeEpisode {
@@ -0,0 +1,93 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import net from 'node:net';
import os from 'node:os';
import path from 'node:path';
import { queryMpvProcessId } from './mpv-process-id';
// Runs a stand-in mpv IPC server that hands each request line to `onRequest`.
async function withFakeMpv(
onRequest: (socket: net.Socket, request: string) => void,
run: (socketPath: string) => Promise<void>,
): Promise<void> {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mpv-pid-'));
const socketPath =
process.platform === 'win32'
? path.win32.join(String.raw`\\.\pipe`, path.basename(dir))
: path.join(dir, 'mpv.sock');
const server = net.createServer((socket) => {
socket.once('data', (data) => onRequest(socket, data.toString()));
});
try {
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(socketPath, resolve);
});
await run(socketPath);
} finally {
await new Promise((resolve) => server.close(resolve));
fs.rmSync(dir, { recursive: true, force: true });
}
}
test('queryMpvProcessId asks mpv for pid and returns the answer', async () => {
let request = '';
await withFakeMpv(
(socket, line) => {
request = line;
socket.write('{"data":4242,"request_id":1,"error":"success"}\n');
},
async (socketPath) => {
assert.equal(await queryMpvProcessId(socketPath), 4242);
},
);
assert.deepEqual(JSON.parse(request), { command: ['get_property', 'pid'], request_id: 1 });
});
test('queryMpvProcessId skips events and malformed lines, across split chunks', async () => {
await withFakeMpv(
(socket) => {
socket.write('{"event":"idle"}\nnot json\n{"data":42');
setTimeout(() => socket.write('42,"request_id":1,"error":"success"}\n'), 10);
},
async (socketPath) => {
assert.equal(await queryMpvProcessId(socketPath), 4242);
},
);
});
test('queryMpvProcessId rejects when mpv refuses the property', async () => {
await withFakeMpv(
(socket) => socket.write('{"request_id":1,"error":"property unavailable"}\n'),
async (socketPath) => {
await assert.rejects(queryMpvProcessId(socketPath), /no process ID/);
},
);
});
test('queryMpvProcessId rejects when nothing is listening', async () => {
const missing =
process.platform === 'win32'
? path.win32.join(String.raw`\\.\pipe`, `mpv-pid-missing-${process.pid}`)
: path.join(os.tmpdir(), `mpv-pid-missing-${process.pid}.sock`);
await assert.rejects(queryMpvProcessId(missing));
});
test('queryMpvProcessId rejects when mpv hangs up or never answers', async () => {
await withFakeMpv(
(socket) => socket.end(),
async (socketPath) => {
await assert.rejects(queryMpvProcessId(socketPath), /closed before mpv answered/);
},
);
const held: net.Socket[] = [];
await withFakeMpv(
(socket) => held.push(socket),
async (socketPath) => {
await assert.rejects(queryMpvProcessId(socketPath, 20), /no answer within 20ms/);
held.forEach((socket) => socket.destroy());
},
);
});
+67
View File
@@ -0,0 +1,67 @@
import net from 'node:net';
const PID_REQUEST_ID = 1;
const PID_QUERY_TIMEOUT_MS = 5_000;
// This runs inside a socket callback, where a parse error would be an uncaught exception.
function parseIpcLine(line: string): unknown {
try {
return JSON.parse(line);
} catch {
return null;
}
}
// Asks the mpv listening on `socketPath` for its process ID over a short-lived IPC connection.
export function queryMpvProcessId(
socketPath: string,
timeoutMs = PID_QUERY_TIMEOUT_MS,
): Promise<number> {
return new Promise((resolve, reject) => {
const socket = net.createConnection(socketPath);
let buffered = '';
const fail = (message: string): void => {
socket.destroy();
reject(new Error(message));
};
socket.setEncoding('utf8');
socket.setTimeout(timeoutMs, () => fail(`no answer within ${timeoutMs}ms`));
socket.once('error', (error) => fail(error.message));
socket.once('close', () => fail('connection closed before mpv answered'));
socket.once('connect', () => {
socket.write(
`${JSON.stringify({ command: ['get_property', 'pid'], request_id: PID_REQUEST_ID })}\n`,
);
});
socket.on('data', (chunk: string) => {
buffered += chunk;
const lines = buffered.split('\n');
buffered = lines.pop() ?? '';
// mpv also streams events on this connection, so skip to the line answering the request.
for (const line of lines) {
const message = parseIpcLine(line);
if (
typeof message !== 'object' ||
message === null ||
!('request_id' in message) ||
message.request_id !== PID_REQUEST_ID
) {
continue;
}
const pid = 'data' in message ? message.data : undefined;
if (typeof pid === 'number') {
socket.destroy();
resolve(pid);
} else {
fail(`mpv returned no process ID: ${line}`);
}
return;
}
});
});
}
@@ -1,72 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
filterMpvPollResultBySocketPath,
matchesMpvSocketPathInCommandLine,
} from './mpv-socket-match';
import type { MpvPollResult } from './win32';
function createPollResult(commandLines: Array<string | null>): MpvPollResult {
return {
matches: commandLines.map((commandLine, index) => ({
hwnd: index + 1,
bounds: { x: index * 10, y: 0, width: 1280, height: 720 },
area: 1280 * 720,
isForeground: index === 0,
commandLine,
})),
focusState: true,
windowState: 'visible',
};
}
test('matchesMpvSocketPathInCommandLine accepts equals and space-delimited socket flags', () => {
assert.equal(
matchesMpvSocketPathInCommandLine(
'mpv.exe --input-ipc-server=\\\\.\\pipe\\subminer-a video.mkv',
'\\\\.\\pipe\\subminer-a',
),
true,
);
assert.equal(
matchesMpvSocketPathInCommandLine(
'mpv.exe --input-ipc-server "\\\\.\\pipe\\subminer-b" video.mkv',
'\\\\.\\pipe\\subminer-b',
),
true,
);
assert.equal(
matchesMpvSocketPathInCommandLine(
'mpv.exe --input-ipc-server=\\\\.\\pipe\\subminer-a video.mkv',
'\\\\.\\pipe\\subminer-b',
),
false,
);
});
test('filterMpvPollResultBySocketPath keeps only matches for the requested socket path', () => {
const result = filterMpvPollResultBySocketPath(
createPollResult([
'mpv.exe --input-ipc-server=\\\\.\\pipe\\subminer-a video-a.mkv',
'mpv.exe --input-ipc-server=\\\\.\\pipe\\subminer-b video-b.mkv',
null,
]),
'\\\\.\\pipe\\subminer-b',
);
assert.deepEqual(
result.matches.map((match) => match.hwnd),
[2],
);
assert.equal(result.windowState, 'visible');
});
test('matchesMpvSocketPathInCommandLine rejects socket-path prefix matches', () => {
assert.equal(
matchesMpvSocketPathInCommandLine(
'mpv.exe --input-ipc-server=\\\\.\\pipe\\subminer-10 video.mkv',
'\\\\.\\pipe\\subminer-1',
),
false,
);
});
-41
View File
@@ -1,41 +0,0 @@
import type { MpvPollResult } from './win32';
function escapeRegex(text: string): string {
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
export function matchesMpvSocketPathInCommandLine(
commandLine: string,
targetSocketPath: string,
): boolean {
if (!commandLine || !targetSocketPath) {
return false;
}
const escapedSocketPath = escapeRegex(targetSocketPath);
return new RegExp(
`(?:^|\\s)--input-ipc-server(?:=|\\s+)(?:"${escapedSocketPath}"|${escapedSocketPath})(?=\\s|$)`,
'i',
).test(commandLine);
}
export function filterMpvPollResultBySocketPath(
result: MpvPollResult,
targetSocketPath?: string | null,
): MpvPollResult {
if (!targetSocketPath) {
return result;
}
const matches = result.matches.filter(
(match) =>
typeof match.commandLine === 'string' &&
matchesMpvSocketPathInCommandLine(match.commandLine, targetSocketPath),
);
return {
matches,
focusState: matches.some((match) => match.isForeground),
windowState: matches.length > 0 ? 'visible' : 'not-found',
};
}
+7 -109
View File
@@ -1,6 +1,4 @@
import { execFile } from 'node:child_process';
import koffi from 'koffi';
import { matchesMpvSocketPathInCommandLine } from './mpv-socket-match';
const user32 = koffi.load('user32.dll');
const dwmapi = koffi.load('dwmapi.dll');
@@ -129,7 +127,6 @@ export interface MpvWindowMatch {
bounds: WindowBounds;
area: number;
isForeground: boolean;
commandLine?: string | null;
}
export interface MpvPollResult {
@@ -200,102 +197,9 @@ function pruneExpiredProcessNames(nowMs: number): void {
}
}
type ProcessCommandLineCacheEntry =
| { state: 'resolved'; commandLine: string; expiresAtMs: number; refreshInFlight: boolean }
| { state: 'pending' }
| { state: 'failed'; retryAtMs: number; backoffMs: number };
const COMMAND_LINE_RETRY_INITIAL_BACKOFF_MS = 2_000;
const COMMAND_LINE_RETRY_MAX_BACKOFF_MS = 30_000;
// A process command line never changes, so a resolved entry only has to expire to survive
// Windows PID reuse (a dead mpv's PID handed to a new instance, whose stale socket path would
// otherwise match the wrong window forever). Longer than the process-name TTL because each
// refresh costs a PowerShell spawn, and the cached value keeps being served while the refresh
// runs, so expiry never interrupts window matching.
const COMMAND_LINE_CACHE_TTL_MS = 60_000;
const processCommandLineCache = new Map<number, ProcessCommandLineCacheEntry>();
function queryProcessCommandLine(
pid: number,
onResult: (commandLine: string | null) => void,
): void {
execFile(
'powershell.exe',
[
'-NoProfile',
'-NonInteractive',
'-ExecutionPolicy',
'Bypass',
'-Command',
`$process = Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}"; if ($process -and $process.CommandLine) { [Console]::Out.Write($process.CommandLine) }`,
],
{
encoding: 'utf8',
windowsHide: true,
timeout: 1500,
},
(error, stdout) => {
const output = error ? '' : stdout.trim();
onResult(output.length > 0 ? output : null);
},
);
}
// Resolves a process command line via a background PowerShell lookup. Returns null until the
// first lookup completes; the caller's next poll picks up the cached result. Failures are
// negative-cached with exponential backoff: the synchronous version of this lookup could
// block the main thread for its full 1.5s timeout on every 250ms poll, which (combined with
// the forward:true mouse hook) stalled mouse input system-wide.
function getProcessCommandLineByPid(pid: number): string | null {
const entry = processCommandLineCache.get(pid);
const nowMs = Date.now();
if (entry?.state === 'resolved') {
if (nowMs >= entry.expiresAtMs && !entry.refreshInFlight) {
entry.refreshInFlight = true;
queryProcessCommandLine(pid, (commandLine) => {
processCommandLineCache.set(pid, {
state: 'resolved',
// A failed refresh is usually a transient query error rather than a dead process
// (a gone process owns no window, so it is never looked up again). Keep the last
// known command line and re-check after the next TTL.
commandLine: commandLine ?? entry.commandLine,
expiresAtMs: Date.now() + COMMAND_LINE_CACHE_TTL_MS,
refreshInFlight: false,
});
});
}
return entry.commandLine;
}
if (entry?.state === 'pending') return null;
if (entry?.state === 'failed' && nowMs < entry.retryAtMs) return null;
const nextBackoffMs =
entry?.state === 'failed'
? Math.min(entry.backoffMs * 2, COMMAND_LINE_RETRY_MAX_BACKOFF_MS)
: COMMAND_LINE_RETRY_INITIAL_BACKOFF_MS;
processCommandLineCache.set(pid, { state: 'pending' });
queryProcessCommandLine(pid, (commandLine) => {
if (commandLine !== null) {
processCommandLineCache.set(pid, {
state: 'resolved',
commandLine,
expiresAtMs: Date.now() + COMMAND_LINE_CACHE_TTL_MS,
refreshInFlight: false,
});
} else {
processCommandLineCache.set(pid, {
state: 'failed',
retryAtMs: Date.now() + nextBackoffMs,
backoffMs: nextBackoffMs,
});
}
});
return null;
}
export function findMpvWindows(targetSocketPath?: string | null): MpvPollResult {
// With a target PID only that process's windows match, whatever its executable is named.
// Without one, any process named mpv matches.
export function findMpvWindows(targetPid?: number | null): MpvPollResult {
const foregroundHwnd = GetForegroundWindow();
const matches: MpvWindowMatch[] = [];
let hasMinimized = false;
@@ -310,15 +214,10 @@ export function findMpvWindows(targetSocketPath?: string | null): MpvPollResult
const pidValue = pid[0]!;
if (pidValue === 0) return true;
const processName = getCachedProcessNameByPid(pidValue);
if (!processName || processName.toLowerCase() !== 'mpv') return true;
let commandLine: string | null = null;
if (targetSocketPath) {
commandLine = getProcessCommandLineByPid(pidValue);
if (!commandLine || !matchesMpvSocketPathInCommandLine(commandLine, targetSocketPath)) {
return true;
}
if (targetPid != null) {
if (pidValue !== targetPid) return true;
} else if (getCachedProcessNameByPid(pidValue)?.toLowerCase() !== 'mpv') {
return true;
}
if (IsIconic(hwnd)) {
@@ -337,7 +236,6 @@ export function findMpvWindows(targetSocketPath?: string | null): MpvPollResult
bounds,
area: bounds.width * bounds.height,
isForeground,
commandLine,
});
return true;
+73 -1
View File
@@ -1,8 +1,80 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { findWindowsMpvTargetWindowHandle } from './windows-helper';
import { createWindowsOverlayOperations, findWindowsMpvTargetWindowHandle } from './windows-helper';
import type { MpvPollResult } from './win32';
function overlayOperationsHarness() {
let nowMs = 0;
let failing = true;
const warnings: Array<{ message: string; operation: unknown }> = [];
const nativeCall = () => {
if (failing) throw new Error('native failure');
};
const operations = createWindowsOverlayOperations({
loadWin32: () => ({
setOverlayOwner: nativeCall,
ensureOverlayTransparency: nativeCall,
bindOverlayAboveMpv: nativeCall,
clearOverlayOwner: nativeCall,
}),
warn: (message, details) => warnings.push({ message, operation: details.operation }),
now: () => nowMs,
});
return {
operations,
warnings,
setNow: (value: number) => {
nowMs = value;
},
setFailing: (value: boolean) => {
failing = value;
},
};
}
for (const [operation, call] of [
['set-owner', (ops) => ops.setOwner(1, 2)],
['transparency', (ops) => ops.ensureTransparency(1)],
['bind-above-mpv', (ops) => ops.bindAboveMpv(1, 2)],
['clear-owner', (ops) => ops.clearOwner(1)],
] as const satisfies ReadonlyArray<
readonly [string, (ops: ReturnType<typeof createWindowsOverlayOperations>) => boolean]
>) {
test(`${operation} reports failure, rate limits warnings and records recovery`, () => {
const h = overlayOperationsHarness();
const failed = { message: 'Windows native overlay operation failed', operation };
assert.equal(call(h.operations), false);
assert.deepEqual(h.warnings, [failed]);
h.setNow(29_999);
assert.equal(call(h.operations), false);
assert.deepEqual(h.warnings, [failed]);
h.setNow(30_000);
assert.equal(call(h.operations), false);
assert.deepEqual(h.warnings, [failed, failed]);
h.setFailing(false);
const recovered = { message: 'Windows native overlay operation recovered', operation };
assert.equal(call(h.operations), true);
assert.deepEqual(h.warnings, [failed, failed, recovered]);
assert.equal(call(h.operations), true);
assert.equal(h.warnings.length, 3);
});
}
test('native overlay operations rate limit independently', () => {
const h = overlayOperationsHarness();
h.operations.setOwner(1, 2);
h.operations.clearOwner(1);
assert.deepEqual(
h.warnings.map((warning) => warning.operation),
['set-owner', 'clear-owner'],
);
});
test('findWindowsMpvTargetWindowHandle prefers the focused mpv window', () => {
const result: MpvPollResult = {
matches: [
+74 -38
View File
@@ -17,11 +17,85 @@
*/
import type { MpvPollResult } from './win32';
import { createLogger } from '../logger';
const log = createLogger('overlay:windows');
type OverlayWin32 = Pick<
typeof import('./win32'),
'setOverlayOwner' | 'ensureOverlayTransparency' | 'bindOverlayAboveMpv' | 'clearOverlayOwner'
>;
// These run on every visibility update, so each operation warns at most every 30 seconds
// while it keeps failing, and once more when it recovers.
export function createWindowsOverlayOperations(deps: {
loadWin32: () => OverlayWin32;
warn: (message: string, details: Record<string, unknown>) => void;
now: () => number;
}) {
const failures = new Map<string, number>();
const run = (
operation: string,
handles: { overlayHwnd: number; mpvHwnd?: number },
action: (win32: OverlayWin32) => void,
): boolean => {
try {
action(deps.loadWin32());
if (failures.delete(operation)) {
deps.warn('Windows native overlay operation recovered', { operation, ...handles });
}
return true;
} catch (error) {
const lastWarning = failures.get(operation);
if (lastWarning === undefined || deps.now() - lastWarning >= 30_000) {
deps.warn('Windows native overlay operation failed', {
operation,
...handles,
error: error instanceof Error ? error.message : String(error),
});
failures.set(operation, deps.now());
}
return false;
}
};
return {
setOwner: (overlayHwnd: number, mpvHwnd: number): boolean =>
run('set-owner', { overlayHwnd, mpvHwnd }, (win32) => {
win32.setOverlayOwner(overlayHwnd, mpvHwnd);
}),
ensureTransparency: (overlayHwnd: number): boolean =>
run('transparency', { overlayHwnd }, (win32) => {
win32.ensureOverlayTransparency(overlayHwnd);
}),
bindAboveMpv: (overlayHwnd: number, mpvHwnd: number): boolean =>
run('bind-above-mpv', { overlayHwnd, mpvHwnd }, (win32) => {
win32.bindOverlayAboveMpv(overlayHwnd, mpvHwnd);
win32.ensureOverlayTransparency(overlayHwnd);
}),
clearOwner: (overlayHwnd: number): boolean =>
run('clear-owner', { overlayHwnd }, (win32) => {
win32.clearOverlayOwner(overlayHwnd);
}),
};
}
function loadWin32(): typeof import('./win32') {
return require('./win32') as typeof import('./win32');
}
const overlayOperations = createWindowsOverlayOperations({
loadWin32,
warn: (message, details) => log.warn(message, details),
now: Date.now,
});
export const setWindowsOverlayOwner = overlayOperations.setOwner;
export const ensureWindowsOverlayTransparency = overlayOperations.ensureTransparency;
export const bindWindowsOverlayAboveMpv = overlayOperations.bindAboveMpv;
export const clearWindowsOverlayOwner = overlayOperations.clearOwner;
export function findWindowsMpvTargetWindowHandle(result?: MpvPollResult): number | null {
const poll = result ?? loadWin32().findMpvWindows();
const focused = poll.matches.find((match) => match.isForeground);
@@ -31,44 +105,6 @@ export function findWindowsMpvTargetWindowHandle(result?: MpvPollResult): number
return best?.hwnd ?? null;
}
export function setWindowsOverlayOwner(overlayHwnd: number, mpvHwnd: number): boolean {
try {
loadWin32().setOverlayOwner(overlayHwnd, mpvHwnd);
return true;
} catch {
return false;
}
}
export function ensureWindowsOverlayTransparency(overlayHwnd: number): boolean {
try {
loadWin32().ensureOverlayTransparency(overlayHwnd);
return true;
} catch {
return false;
}
}
export function bindWindowsOverlayAboveMpv(overlayHwnd: number, mpvHwnd: number): boolean {
try {
const win32 = loadWin32();
win32.bindOverlayAboveMpv(overlayHwnd, mpvHwnd);
win32.ensureOverlayTransparency(overlayHwnd);
return true;
} catch {
return false;
}
}
export function clearWindowsOverlayOwner(overlayHwnd: number): boolean {
try {
loadWin32().clearOverlayOwner(overlayHwnd);
return true;
} catch {
return false;
}
}
export function getWindowsForegroundProcessName(): string | null {
try {
return loadWin32().getForegroundProcessName();
+186
View File
@@ -265,3 +265,189 @@ test('WindowsWindowTracker keeps tracking through repeated transient minimized r
assert.equal(tracker.isTargetWindowMinimized(), false);
assert.deepEqual(tracker.getGeometry(), { x: 10, y: 20, width: 1280, height: 720 });
});
const SOCKET_PATH = String.raw`\\.\pipe\subminer-socket`;
const flushPromises = () => new Promise((resolve) => setImmediate(resolve));
function pollOnce(tracker: WindowsWindowTracker): void {
(tracker as unknown as { pollGeometry: () => void }).pollGeometry();
}
test('WindowsWindowTracker follows the process that answers on the target socket', async () => {
const queriedSockets: string[] = [];
const polledPids: Array<number | null> = [];
const tracker = new WindowsWindowTracker(SOCKET_PATH, {
queryMpvProcessId: async (socketPath) => {
queriedSockets.push(socketPath);
return 4242;
},
pollMpvWindows: (targetPid) => {
polledPids.push(targetPid);
return mpvVisible();
},
});
pollOnce(tracker);
assert.equal(tracker.isTracking(), false);
await flushPromises();
pollOnce(tracker);
assert.equal(tracker.isTracking(), true);
assert.deepEqual(queriedSockets, [SOCKET_PATH]);
assert.deepEqual(polledPids, [4242]);
});
test('WindowsWindowTracker keeps polling while a process lookup is pending', async () => {
let queries = 0;
let answer: (pid: number) => void = () => {};
let now = 1_000;
const tracker = new WindowsWindowTracker(SOCKET_PATH, {
now: () => now,
queryMpvProcessId: () => {
queries += 1;
return new Promise((resolve) => {
answer = resolve;
});
},
pollMpvWindows: () => mpvVisible(),
});
for (let poll = 0; poll < 120; poll += 1) {
pollOnce(tracker);
now += 250;
}
assert.equal(tracker.isTracking(), false);
assert.equal(queries, 1);
answer(4242);
await flushPromises();
pollOnce(tracker);
assert.equal(tracker.isTracking(), true);
});
test('WindowsWindowTracker retries a failed lookup at a limited rate', async () => {
let queries = 0;
let now = 1_000;
const tracker = new WindowsWindowTracker(SOCKET_PATH, {
now: () => now,
queryMpvProcessId: async () => {
queries += 1;
if (queries === 1) throw new Error('connect ENOENT');
return 4242;
},
pollMpvWindows: () => mpvVisible(),
});
pollOnce(tracker);
await flushPromises();
now += 250;
pollOnce(tracker);
await flushPromises();
assert.equal(queries, 1);
now += 1_000;
pollOnce(tracker);
await flushPromises();
pollOnce(tracker);
assert.equal(queries, 2);
assert.equal(tracker.isTracking(), true);
});
test('WindowsWindowTracker moves to the new process when mpv restarts on the same socket', async () => {
let currentPid = 1111;
let now = 1_000;
let queries = 0;
const polledPids: Array<number | null> = [];
const tracker = new WindowsWindowTracker(SOCKET_PATH, {
now: () => now,
queryMpvProcessId: async () => {
queries += 1;
return currentPid;
},
// Only the live process still owns a window.
pollMpvWindows: (targetPid) => {
polledPids.push(targetPid);
return targetPid === currentPid ? mpvVisible() : mpvNotFound;
},
});
pollOnce(tracker);
await flushPromises();
pollOnce(tracker);
assert.equal(tracker.isTracking(), true);
currentPid = 2222;
now += 2_000;
pollOnce(tracker);
await flushPromises();
pollOnce(tracker);
assert.equal(tracker.isTracking(), true);
assert.deepEqual(tracker.getGeometry(), { x: 0, y: 0, width: 1280, height: 720 });
assert.equal(polledPids.at(-1), 2222);
assert.equal(queries, 2);
});
test('WindowsWindowTracker revalidates a PID even while its window remains visible', async () => {
let currentPid = 1111;
let now = 0;
const polledPids: Array<number | null> = [];
const tracker = new WindowsWindowTracker(SOCKET_PATH, {
now: () => now,
queryMpvProcessId: async () => currentPid,
// Simulates PID reuse: the old PID still has a visible, unrelated window.
pollMpvWindows: (pid) => {
polledPids.push(pid);
return mpvVisible();
},
});
pollOnce(tracker);
await flushPromises();
pollOnce(tracker);
currentPid = 2222;
now = 10_000;
pollOnce(tracker);
await flushPromises();
pollOnce(tracker);
assert.equal(polledPids.at(-1), 2222);
});
test('WindowsWindowTracker expires an unvalidated PID and recovers after IPC returns', async () => {
let available = true;
let now = 0;
const polledPids: Array<number | null> = [];
const tracker = new WindowsWindowTracker(SOCKET_PATH, {
now: () => now,
queryMpvProcessId: async () => {
if (!available) throw new Error('IPC unavailable');
return 4242;
},
pollMpvWindows: (pid) => {
polledPids.push(pid);
return mpvVisible();
},
trackingLossGraceMs: 0,
maxConsecutiveMisses: 1,
});
pollOnce(tracker);
await flushPromises();
pollOnce(tracker);
assert.equal(tracker.isTracking(), true);
available = false;
now = 10_000;
pollOnce(tracker);
await flushPromises();
assert.equal(tracker.isTracking(), true);
polledPids.length = 0;
now = 30_000;
pollOnce(tracker);
await flushPromises();
assert.equal(tracker.isTracking(), false);
assert.deepEqual(polledPids, []);
available = true;
now += 1_000;
pollOnce(tracker);
await flushPromises();
pollOnce(tracker);
assert.equal(tracker.isTracking(), true);
assert.equal(polledPids.at(-1), 4242);
});
+97 -7
View File
@@ -19,27 +19,35 @@
import { BaseWindowTracker } from './base-tracker';
import type { WindowGeometry } from '../types';
import type { MpvPollResult } from './win32';
import { queryMpvProcessId } from './mpv-process-id';
import { createLogger } from '../logger';
const log = createLogger('tracker').child('windows');
const MPV_PID_LOOKUP_INTERVAL_MS = 1_000;
const MPV_PID_REVALIDATE_INTERVAL_MS = 10_000;
const MPV_PID_MAX_AGE_MS = 30_000;
const NO_MPV_WINDOW: MpvPollResult = { matches: [], focusState: false, windowState: 'not-found' };
type WindowsTrackerDeps = {
pollMpvWindows?: () => MpvPollResult;
pollMpvWindows?: (targetPid: number | null) => MpvPollResult;
queryMpvProcessId?: (socketPath: string) => Promise<number>;
maxConsecutiveMisses?: number;
trackingLossGraceMs?: number;
minimizedTrackingLossGraceMs?: number;
now?: () => number;
};
function defaultPollMpvWindows(_targetMpvSocketPath?: string | null): MpvPollResult {
function defaultPollMpvWindows(targetPid: number | null): MpvPollResult {
const win32 = require('./win32') as typeof import('./win32');
return win32.findMpvWindows(_targetMpvSocketPath);
return win32.findMpvWindows(targetPid);
}
export class WindowsWindowTracker extends BaseWindowTracker {
private pollInterval: ReturnType<typeof setInterval> | null = null;
private pollInFlight = false;
private readonly pollMpvWindows: () => MpvPollResult;
private readonly pollMpvWindows: (targetPid: number | null) => MpvPollResult;
private readonly queryMpvProcessId: (socketPath: string) => Promise<number>;
private readonly maxConsecutiveMisses: number;
private readonly trackingLossGraceMs: number;
private readonly minimizedTrackingLossGraceMs: number;
@@ -51,12 +59,17 @@ export class WindowsWindowTracker extends BaseWindowTracker {
private targetWindowMinimized = false;
private readonly targetMpvSocketPath: string | null;
private currentTargetWindowHwnd: number | null = null;
private targetMpvPid: number | null = null;
private pidLookupInFlight = false;
private lastPidLookupAtMs: number | null = null;
private lastPidConfirmedAtMs: number | null = null;
private pidLookupFailureLogged = false;
constructor(_targetMpvSocketPath?: string, deps: WindowsTrackerDeps = {}) {
super();
this.targetMpvSocketPath = _targetMpvSocketPath?.trim() || null;
this.pollMpvWindows =
deps.pollMpvWindows ?? (() => defaultPollMpvWindows(this.targetMpvSocketPath));
this.pollMpvWindows = deps.pollMpvWindows ?? defaultPollMpvWindows;
this.queryMpvProcessId = deps.queryMpvProcessId ?? queryMpvProcessId;
this.maxConsecutiveMisses = Math.max(1, Math.floor(deps.maxConsecutiveMisses ?? 2));
this.trackingLossGraceMs = Math.max(0, Math.floor(deps.trackingLossGraceMs ?? 1_500));
this.minimizedTrackingLossGraceMs = Math.max(
@@ -86,6 +99,16 @@ export class WindowsWindowTracker extends BaseWindowTracker {
return this.currentTargetWindowHwnd;
}
getDiagnosticState() {
return {
socketPath: this.targetMpvSocketPath,
targetPid: this.targetMpvPid,
targetHwnd: this.currentTargetWindowHwnd,
pidLookupPending: this.pidLookupInFlight,
pidAgeMs: this.lastPidConfirmedAtMs === null ? null : this.now() - this.lastPidConfirmedAtMs,
};
}
private maybeLogPollError(error: Error): void {
const now = Date.now();
const fingerprint = error.message;
@@ -142,12 +165,79 @@ export class WindowsWindowTracker extends BaseWindowTracker {
};
}
// Asks the mpv on the target socket which process it is. Runs in the background so a slow
// answer never stalls the poll, which shares the main thread with the mouse hook.
private refreshTargetMpvPid(socketPath: string, intervalMs = MPV_PID_LOOKUP_INTERVAL_MS): void {
const nowMs = this.now();
if (
this.pidLookupInFlight ||
(this.lastPidLookupAtMs !== null && nowMs - this.lastPidLookupAtMs < intervalMs)
) {
return;
}
this.pidLookupInFlight = true;
this.lastPidLookupAtMs = nowMs;
this.queryMpvProcessId(socketPath)
.then(
(pid) => {
this.targetMpvPid = pid;
this.lastPidConfirmedAtMs = this.now();
if (this.pidLookupFailureLogged) {
log.warn('Windows mpv PID lookup recovered', this.getDiagnosticState());
}
this.pidLookupFailureLogged = false;
},
(error: unknown) => {
// The overlay stays hidden until mpv is identified, so leave a trace of why it isn't.
if (this.pidLookupFailureLogged) return;
this.pidLookupFailureLogged = true;
log.warn('Windows mpv PID lookup failed; overlay attachment may be unavailable', {
...this.getDiagnosticState(),
error: error instanceof Error ? error.message : String(error),
});
},
)
.finally(() => {
this.pidLookupInFlight = false;
});
}
private pollTargetWindows(): MpvPollResult {
const socketPath = this.targetMpvSocketPath;
if (!socketPath) return this.pollMpvWindows(null);
// Windows can reuse a PID for an unrelated visible window. A cached match must
// remain tied to the process answering on our socket, even while it is visible.
if (
this.lastPidConfirmedAtMs !== null &&
this.now() - this.lastPidConfirmedAtMs >= MPV_PID_MAX_AGE_MS
) {
this.targetMpvPid = null;
}
if (this.targetMpvPid === null) {
this.refreshTargetMpvPid(socketPath);
return NO_MPV_WINDOW;
}
const result = this.pollMpvWindows(this.targetMpvPid);
// A new mpv may have taken over the socket after the known process exited.
this.refreshTargetMpvPid(
socketPath,
result.windowState === 'not-found'
? MPV_PID_LOOKUP_INTERVAL_MS
: MPV_PID_REVALIDATE_INTERVAL_MS,
);
return result;
}
private pollGeometry(): void {
if (this.pollInFlight) return;
this.pollInFlight = true;
try {
const result = this.pollMpvWindows();
const result = this.pollTargetWindows();
const best = this.selectBestMatch(result);
if (best) {
+9 -3
View File
@@ -1,9 +1,9 @@
import { AnimeCoverImage } from './AnimeCoverImage';
import { formatDuration, formatNumber } from '../../lib/formatters';
import type { AnimeLibraryItem } from '../../types/stats';
import type { AnimeCardData } from '../../lib/anime-groups';
interface AnimeCardProps {
anime: AnimeLibraryItem;
anime: AnimeCardData;
onClick: () => void;
/** While selecting, clicking the card toggles it instead of opening it. */
selectable?: boolean;
@@ -16,6 +16,7 @@ export function AnimeCard({
selectable = false,
selected = false,
}: AnimeCardProps) {
const unit = anime.mediaKind === 'youtube' ? 'video' : 'episode';
return (
<button
type="button"
@@ -44,11 +45,16 @@ export function AnimeCard({
{'✓'}
</span>
)}
{anime.partCount ? (
<span className="absolute top-2 right-2 px-1.5 py-0.5 rounded text-[10px] font-medium bg-ctp-crust/80 text-ctp-text border border-ctp-surface2">
{anime.partCount} parts
</span>
) : null}
</div>
<div className="p-3">
<div className="text-sm font-medium text-ctp-text truncate">{anime.canonicalTitle}</div>
<div className="text-xs text-ctp-overlay2 mt-1">
{anime.episodeCount} {anime.mediaKind === 'youtube' ? 'video' : 'episode'}
{anime.episodeCount} {unit}
{anime.episodeCount !== 1 ? 's' : ''}
</div>
<div className="text-xs text-ctp-overlay2">
+70 -3
View File
@@ -9,13 +9,16 @@ import { AnimeWordList } from './AnimeWordList';
import { AnilistSelector } from './AnilistSelector';
import { TmdbSelector } from './TmdbSelector';
import { AnimeOverviewStats } from './AnimeOverviewStats';
import { LibraryEntryPicker } from './LibraryEntryPicker';
import { CHART_THEME } from '../../lib/chart-theme';
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts';
import type { DailyRollup } from '../../types/stats';
import type { DailyRollup, StatsAnimeGroupOverrideRequest } from '../../types/stats';
interface AnimeDetailViewProps {
animeId: number;
onBack: () => void;
/** Defaults to "Back to Library"; a part opened from a franchise card returns there. */
backLabel?: string;
onNavigateToWord?: (wordId: number) => void;
onOpenEpisodeDetail?: (videoId: number) => void;
/** Called after the whole library entry is deleted, so the caller can refresh. */
@@ -28,6 +31,23 @@ interface AnimeDetailViewProps {
onProviderRelinked?: () => void;
/** Called after an episode is reassigned to another entry. */
onEpisodeMoved?: () => void;
/** Called after the entry is moved to another franchise card or back. */
onGroupChanged?: () => void;
}
/** The server explains a refused move (409) in its JSON body; show that text. */
function describeGroupError(err: unknown): string {
const message = err instanceof Error ? err.message : '';
const refused = /^Stats API error: 409 (.*)$/s.exec(message);
if (refused) {
try {
const body = JSON.parse(refused[1]!) as { error?: unknown };
if (typeof body.error === 'string') return body.error;
} catch {
// Fall through to the raw message.
}
}
return message || 'Failed to move this title.';
}
type Range = 14 | 30 | 90;
@@ -149,11 +169,13 @@ function useAnimeKnownWords(animeId: number) {
export function AnimeDetailView({
animeId,
onBack,
backLabel = 'Back to Library',
onNavigateToWord,
onOpenEpisodeDetail,
onAnimeDeleted,
onProviderRelinked,
onEpisodeMoved,
onGroupChanged,
}: AnimeDetailViewProps) {
const { data, loading, error, reload } = useAnimeDetail(animeId);
const [showAnilistSelector, setShowAnilistSelector] = useState(false);
@@ -162,6 +184,9 @@ export function AnimeDetailView({
const [isDeletingAnime, setIsDeletingAnime] = useState(false);
const [deleteError, setDeleteError] = useState<string | null>(null);
const isDeletingAnimeRef = useRef(false);
const [showGroupPicker, setShowGroupPicker] = useState(false);
const [groupBusyTargetId, setGroupBusyTargetId] = useState<number | null>(null);
const [groupError, setGroupError] = useState<string | null>(null);
const knownWordsSummary = useAnimeKnownWords(animeId);
useEffect(() => {
@@ -172,7 +197,23 @@ export function AnimeDetailView({
if (error) return <div className="text-ctp-red p-4">Error: {error}</div>;
if (!data?.detail) return <div className="text-ctp-overlay2 p-4">Library entry not found</div>;
const { detail, episodes, anilistEntries } = data;
const { detail, episodes, anilistEntries, group } = data;
// `busyId` marks which picker row shows progress; the entry's own id for header actions.
const applyGroupOverride = async (request: StatsAnimeGroupOverrideRequest, busyId: number) => {
setGroupBusyTargetId(busyId);
setGroupError(null);
try {
await getStatsClient().setAnimeGroupOverride(animeId, request);
setShowGroupPicker(false);
reload();
onGroupChanged?.();
} catch (err) {
setGroupError(describeGroupError(err));
} finally {
setGroupBusyTargetId(null);
}
};
const handleDeleteAnime = async () => {
if (isDeletingAnimeRef.current) return;
@@ -214,11 +255,18 @@ export function AnimeDetailView({
onClick={onBack}
className="text-sm text-ctp-blue hover:text-ctp-sapphire transition-colors"
>
&larr; Back to Library
&larr; {backLabel}
</button>
<AnimeHeader
detail={detail}
anilistEntries={anilistEntries ?? []}
group={group}
groupBusy={groupBusyTargetId !== null}
onMoveToGroup={() => {
setGroupError(null);
setShowGroupPicker(true);
}}
onSetGroupMode={(mode) => void applyGroupOverride({ mode }, animeId)}
coverRetryToken={coverRetryToken}
onChangeAnilist={() => setShowAnilistSelector(true)}
onChangeTmdb={() => setShowTmdbSelector(true)}
@@ -226,6 +274,25 @@ export function AnimeDetailView({
isDeletingAnime={isDeletingAnime}
/>
{deleteError ? <div className="text-sm text-ctp-red">{deleteError}</div> : null}
{groupError && !showGroupPicker ? (
<div role="alert" className="text-sm text-ctp-red">
{groupError}
</div>
) : null}
{showGroupPicker && (
<LibraryEntryPicker
heading="Move to another anime"
mediaKind="anime"
excludeAnimeIds={[animeId]}
filter={(entry) => entry.anilistId !== null}
busyAnimeId={groupBusyTargetId}
error={groupError}
onSelect={(entry) =>
void applyGroupOverride({ mode: 'join', targetAnimeId: entry.animeId }, entry.animeId)
}
onClose={() => setShowGroupPicker(false)}
/>
)}
<AnimeOverviewStats detail={detail} knownWordsSummary={knownWordsSummary} />
<EpisodeList
episodes={episodes}
@@ -0,0 +1,87 @@
import { describeAnimePart } from '../../lib/anime-groups';
import { formatDuration, formatNumber, formatRelativeDate } from '../../lib/formatters';
import type { AnimeLibraryGroup } from '../../types/stats';
import { AnimeCoverImage } from './AnimeCoverImage';
interface AnimeGroupViewProps {
group: AnimeLibraryGroup;
onBack: () => void;
onOpenPart: (animeId: number) => void;
}
/** A franchise card opened: its library entries in release order, each opening its own page. */
export function AnimeGroupView({ group, onBack, onOpenPart }: AnimeGroupViewProps) {
const cover = group.parts.find((part) => part.animeId === group.coverAnimeId) ?? group.parts[0]!;
return (
<div className="space-y-4">
<button
type="button"
onClick={onBack}
className="text-sm text-ctp-blue hover:text-ctp-sapphire transition-colors"
>
&larr; Back to Library
</button>
<div className="flex gap-4">
<AnimeCoverImage
animeId={cover.animeId}
title={group.title}
coverRetryToken={cover.anilistId ?? 0}
className="w-32 h-44 rounded-lg shrink-0"
/>
<div className="flex-1 min-w-0">
<h2 className="text-lg font-bold text-ctp-text truncate">{group.title}</h2>
<div className="text-sm text-ctp-subtext0 mt-2">
{group.parts.length} parts · {group.episodeCount} episode
{group.episodeCount !== 1 ? 's' : ''}
</div>
<div className="text-xs text-ctp-overlay2 mt-1">
{formatDuration(group.totalActiveMs)} · {formatNumber(group.totalCards)} cards
{group.lastWatchedMs > 0
? ` · last watched ${formatRelativeDate(group.lastWatchedMs)}`
: ''}
</div>
<p className="text-xs text-ctp-overlay2 mt-3 leading-relaxed">
Grouped by AniList&apos;s season, movie and side-story links. Open a part to move it to
another anime or show it on its own.
</p>
</div>
</div>
<div className="bg-ctp-surface0 border border-ctp-surface1 rounded-lg p-4">
<h3 className="text-sm font-semibold text-ctp-text mb-3">Seasons and Movies</h3>
<ul className="space-y-1">
{group.parts.map((part) => {
const kind = describeAnimePart(part.format, part.startDate);
return (
<li key={part.animeId}>
<button
type="button"
onClick={() => onOpenPart(part.animeId)}
className="w-full flex items-center gap-3 p-2.5 rounded-lg hover:bg-ctp-surface1 transition-colors text-left"
>
<AnimeCoverImage
animeId={part.animeId}
title={part.canonicalTitle}
coverRetryToken={part.anilistId ?? part.tmdbId ?? 0}
className="w-10 h-14 rounded shrink-0"
/>
<div className="min-w-0 flex-1">
<div className="text-sm text-ctp-text truncate">{part.canonicalTitle}</div>
<div className="text-xs text-ctp-overlay2 mt-0.5">
{kind ? `${kind} · ` : ''}
{part.episodeCount} episode{part.episodeCount !== 1 ? 's' : ''}
</div>
</div>
<div className="text-xs text-ctp-overlay2 text-right shrink-0">
<div>{formatDuration(part.totalActiveMs)}</div>
<div>{formatNumber(part.totalCards)} cards</div>
</div>
</button>
</li>
);
})}
</ul>
</div>
</div>
);
}
@@ -0,0 +1,178 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { apiClient } from '../../lib/api-client';
import type {
AnimeDetailData,
AnimeLibraryGroup,
AnimeLibraryGroupPart,
StatsAnimeGroupOverrideRequest,
} from '../../types/stats';
import { AnimeTab } from './AnimeTab';
import { installDom } from '../../test-utils/dom';
function part(
animeId: number,
title: string,
format: string,
startDate: number,
): AnimeLibraryGroupPart {
return {
mediaKind: 'anime',
animeId,
canonicalTitle: title,
anilistId: animeId * 100,
tmdbId: null,
tmdbType: null,
totalSessions: 1,
totalActiveMs: 60_000,
totalCards: 2,
totalTokensSeen: 0,
episodeCount: format === 'MOVIE' ? 1 : 13,
episodesTotal: null,
lastWatchedMs: animeId,
format,
startDate,
};
}
const overlord: AnimeLibraryGroup = {
groupKey: 20832,
title: 'Overlord',
mediaKind: 'anime',
coverAnimeId: 2,
totalSessions: 2,
totalActiveMs: 120_000,
totalCards: 4,
totalTokensSeen: 0,
episodeCount: 14,
lastWatchedMs: 2,
parts: [part(2, 'The Undead King', 'MOVIE', 20170225), part(1, 'Overlord II', 'TV', 20180109)],
};
function detailData(): AnimeDetailData {
const {
format: _format,
startDate: _startDate,
episodesTotal: _total,
...item
} = part(1, 'Overlord II', 'TV', 20180109);
return {
detail: {
...item,
titleRomaji: null,
titleEnglish: null,
titleNative: null,
description: null,
totalLinesSeen: 0,
totalLookupCount: 0,
totalLookupHits: 0,
totalYomitanLookupCount: 0,
},
episodes: [],
anilistEntries: [],
group: { groupKey: 20832, title: 'Overlord', partCount: 2, overrideMode: 'anilist' },
};
}
function findButton(container: Element, label: string): HTMLElement {
const match = [...container.querySelectorAll('button')].find((button) =>
(button.textContent ?? '').includes(label),
);
assert.ok(match, `expected a "${label}" button`);
return match as unknown as HTMLElement;
}
test('a franchise card opens its parts in release order, and a part can stand alone', async () => {
const uninstallDom = installDom();
const original = { ...apiClient };
const overrides: Array<[number, StatsAnimeGroupOverrideRequest]> = [];
let libraryFetches = 0;
apiClient.getAnimeLibraryGroups = async () => {
libraryFetches += 1;
return [overlord];
};
apiClient.getAnimeMergeRecommendations = async () => ({ recommendations: [] });
apiClient.getAnimeDetail = async () => detailData();
apiClient.getAnimeWords = async () => [];
apiClient.getAnimeRollups = async () => [];
apiClient.getAnimeKnownWordsSummary = async () => ({ totalUniqueWords: 0, knownWordCount: 0 });
apiClient.setAnimeGroupOverride = async (animeId, request) => {
overrides.push([animeId, request]);
};
const container = document.createElement('div');
document.body.append(container);
const root = createRoot(container);
try {
await act(async () => root.render(<AnimeTab />));
// One card for the franchise, counted once, with the first-released part's cover.
assert.match(container.textContent ?? '', /1 title/);
assert.match(findButton(container, 'Overlord').textContent ?? '', /2 parts/);
assert.match(container.querySelector('img')?.getAttribute('src') ?? '', /anime\/2\/cover/);
await act(async () => findButton(container, 'Overlord').click());
const rows = [...container.querySelectorAll('li button')].map((row) => row.textContent ?? '');
assert.equal(rows.length, 2);
assert.match(rows[0]!, /The Undead King.*Movie · 2017/);
assert.match(rows[1]!, /Overlord II.*TV · 2018/);
await act(async () => findButton(container, 'Overlord II').click());
assert.match(container.textContent ?? '', /Listed under Overlord with 1 other part/);
await act(async () => findButton(container, 'Show On Its Own').click());
assert.deepEqual(overrides, [[1, { mode: 'standalone' }]]);
assert.equal(libraryFetches, 2);
await act(async () => findButton(container, 'Back to Overlord').click());
assert.match(container.textContent ?? '', /Seasons and Movies/);
} finally {
await act(async () => root.unmount());
Object.assign(apiClient, original);
uninstallDom();
}
});
test('a franchise left with one part closes and does not reopen on a later refresh', async () => {
const uninstallDom = installDom();
const original = { ...apiClient };
const [movie, season] = overlord.parts as [AnimeLibraryGroupPart, AnimeLibraryGroupPart];
const split: AnimeLibraryGroup[] = [
{ ...overlord, parts: [movie], coverAnimeId: movie.animeId },
{ ...overlord, groupKey: 1, title: season.canonicalTitle, parts: [season], coverAnimeId: 1 },
];
let library: AnimeLibraryGroup[] = [overlord];
apiClient.getAnimeLibraryGroups = async () => library;
apiClient.getAnimeMergeRecommendations = async () => ({ recommendations: [] });
apiClient.getAnimeDetail = async () => detailData();
apiClient.getAnimeWords = async () => [];
apiClient.getAnimeRollups = async () => [];
apiClient.getAnimeKnownWordsSummary = async () => ({ totalUniqueWords: 0, knownWordCount: 0 });
apiClient.setAnimeGroupOverride = async () => {
library = split;
};
const container = document.createElement('div');
document.body.append(container);
const root = createRoot(container);
try {
await act(async () => root.render(<AnimeTab />));
await act(async () => findButton(container, 'Overlord').click());
await act(async () => findButton(container, 'Overlord II').click());
await act(async () => findButton(container, 'Show On Its Own').click());
await act(async () => findButton(container, 'Back to Overlord').click());
assert.doesNotMatch(container.textContent ?? '', /Seasons and Movies/);
// The franchise gets its second part back; the library must stay where it is.
library = [overlord];
await act(async () => {
window.dispatchEvent(new window.Event('focus'));
});
assert.match(findButton(container, 'Overlord').textContent ?? '', /2 parts/);
assert.doesNotMatch(container.textContent ?? '', /Seasons and Movies/);
} finally {
await act(async () => root.unmount());
Object.assign(apiClient, original);
uninstallDom();
}
});
+57 -1
View File
@@ -1,9 +1,17 @@
import { AnimeCoverImage } from './AnimeCoverImage';
import type { AnimeDetailData, AnilistEntry } from '../../types/stats';
import type { AnimeDetailData, AnimeGroupPlacement, AnilistEntry } from '../../types/stats';
const SECONDARY_BUTTON_CLASS =
'inline-flex items-center gap-1 px-2 py-1 text-xs rounded bg-ctp-surface1 text-ctp-overlay2 hover:bg-ctp-surface2 hover:text-ctp-subtext0 transition-colors disabled:opacity-50 disabled:cursor-not-allowed';
interface AnimeHeaderProps {
detail: AnimeDetailData['detail'];
anilistEntries: AnilistEntry[];
/** The franchise card this entry is listed under; null hides the grouping actions. */
group?: AnimeGroupPlacement | null;
onMoveToGroup?: () => void;
onSetGroupMode?: (mode: 'standalone' | 'anilist') => void;
groupBusy?: boolean;
coverRetryToken?: number;
onChangeAnilist?: () => void;
onChangeTmdb?: () => void;
@@ -33,6 +41,10 @@ function AnilistButton({ entry }: { entry: AnilistEntry }) {
export function AnimeHeader({
detail,
anilistEntries,
group = null,
onMoveToGroup,
onSetGroupMode,
groupBusy = false,
coverRetryToken = 0,
onChangeAnilist,
onChangeTmdb,
@@ -52,6 +64,9 @@ export function AnimeHeader({
? `https://www.themoviedb.org/${detail.tmdbType}/${detail.tmdbId}`
: null;
const coverCacheToken = (detail.anilistId ?? detail.tmdbId ?? 0) * 1_000_000 + coverRetryToken;
// Only anime entries are grouped by AniList relations.
const placement = detail.mediaKind === 'anime' ? group : null;
const otherParts = placement ? placement.partCount - 1 : 0;
return (
<div className="flex gap-4">
@@ -80,6 +95,11 @@ export function AnimeHeader({
</span>
)}
</div>
{placement && otherParts > 0 && (
<div className="text-xs text-ctp-overlay2 mt-1">
Listed under {placement.title} with {otherParts} other part{otherParts !== 1 ? 's' : ''}
</div>
)}
<div className="flex flex-wrap gap-1.5 mt-2">
{tmdbUrl && (
<a
@@ -138,6 +158,42 @@ export function AnimeHeader({
{tmdbUrl ? 'Change TMDB Title' : 'Link to TMDB'}
</button>
)}
{placement && onMoveToGroup && (
<button
type="button"
onClick={onMoveToGroup}
disabled={groupBusy}
title="List this entry with another anime's seasons and movies"
className={SECONDARY_BUTTON_CLASS}
>
{'Move to Another Anime\u2026'}
</button>
)}
{placement && onSetGroupMode && placement.overrideMode !== 'anilist' && (
<button
type="button"
onClick={() => onSetGroupMode('anilist')}
disabled={groupBusy}
title="Undo a manual move and group this entry by its AniList relations"
className={SECONDARY_BUTTON_CLASS}
>
Put Back Where AniList Has It
</button>
)}
{placement &&
onSetGroupMode &&
placement.overrideMode === 'anilist' &&
otherParts > 0 && (
<button
type="button"
onClick={() => onSetGroupMode('standalone')}
disabled={groupBusy}
title="List this entry as its own card instead of with its franchise"
className={SECONDARY_BUTTON_CLASS}
>
Show On Its Own
</button>
)}
{onDeleteAnime && (
<button
type="button"
@@ -7,6 +7,7 @@ import type { AnimeLibraryItem, StatsMergeAnimeResponse } from '../../types/stat
import { AnimeMergeDialog } from './AnimeMergeDialog';
import { AnimeTab } from './AnimeTab';
import { installDom } from '../../test-utils/dom';
import { singleGroupLibrary } from '../../test-utils/library';
function libraryItem(animeId: number, title: string, episodeCount: number): AnimeLibraryItem {
return {
@@ -52,7 +53,7 @@ function mergeButton(container: Element): HTMLButtonElement {
test('AnimeTab merges the selected duplicate entries into the chosen keeper', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
mergeAnime: apiClient.mergeAnime,
};
@@ -61,10 +62,10 @@ test('AnimeTab merges the selected duplicate entries into the chosen keeper', as
let libraryFetches = 0;
let mergeCall: { targetAnimeId: number; sourceAnimeIds: number[] } | null = null;
apiClient.getAnimeLibrary = (async () => {
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
libraryFetches += 1;
return entries;
}) as typeof apiClient.getAnimeLibrary;
});
apiClient.mergeAnime = (async (targetAnimeId: number, sourceAnimeIds: number[]) => {
mergeCall = { targetAnimeId, sourceAnimeIds };
entries = [libraryItem(1, 'Show', 3)];
@@ -181,7 +182,7 @@ test('AnimeMergeDialog refuses to merge an AniList entry with a TMDB entry', asy
test('AnimeTab keeps a suggested duplicate visible until it is reviewed and merged', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
mergeAnime: apiClient.mergeAnime,
@@ -191,7 +192,7 @@ test('AnimeTab keeps a suggested duplicate visible until it is reviewed and merg
let recommendations = [{ recommendationId: 41, animeIds: [1, 2] }];
let mergeCall: { targetAnimeId: number; sourceAnimeIds: number[] } | null = null;
apiClient.getAnimeLibrary = (async () => entries) as typeof apiClient.getAnimeLibrary;
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => entries);
apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations,
})) as typeof apiClient.getAnimeMergeRecommendations;
@@ -252,16 +253,16 @@ test('AnimeTab keeps a suggested duplicate visible until it is reviewed and merg
test('AnimeTab dismisses a false-positive duplicate recommendation', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
};
let dismissedId: number | null = null;
apiClient.getAnimeLibrary = (async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2),
libraryItem(2, 'Different Show', 1),
]) as typeof apiClient.getAnimeLibrary;
]);
apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations: [{ recommendationId: 73, animeIds: [1, 2] }],
})) as typeof apiClient.getAnimeMergeRecommendations;
@@ -291,16 +292,16 @@ test('AnimeTab dismisses a false-positive duplicate recommendation', async () =>
test('AnimeTab refreshes the library and recommendations when the window regains focus', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
};
let entries = [libraryItem(1, 'Show', 2), libraryItem(2, 'Show Season 1', 1)];
let libraryFetches = 0;
let recommendationFetches = 0;
apiClient.getAnimeLibrary = (async () => {
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
libraryFetches += 1;
return entries;
}) as typeof apiClient.getAnimeLibrary;
});
apiClient.getAnimeMergeRecommendations = (async () => {
recommendationFetches += 1;
return { recommendations: [] };
@@ -330,14 +331,14 @@ test('AnimeTab refreshes the library and recommendations when the window regains
test('AnimeTab keeps a recommendation visible through a transient refresh failure', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
};
let failRecommendations = false;
apiClient.getAnimeLibrary = (async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2),
libraryItem(2, 'Show Season 1', 1),
]) as typeof apiClient.getAnimeLibrary;
]);
apiClient.getAnimeMergeRecommendations = (async () => {
if (failRecommendations) throw new Error('temporary failure');
return { recommendations: [{ recommendationId: 41, animeIds: [1, 2] }] };
@@ -364,14 +365,14 @@ test('AnimeTab keeps a recommendation visible through a transient refresh failur
test('AnimeTab retains a recommendation and reports a failed dismissal', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
};
apiClient.getAnimeLibrary = (async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2),
libraryItem(2, 'Show Season 1', 1),
]) as typeof apiClient.getAnimeLibrary;
]);
apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations: [{ recommendationId: 41, animeIds: [1, 2] }],
})) as typeof apiClient.getAnimeMergeRecommendations;
@@ -399,14 +400,14 @@ test('AnimeTab retains a recommendation and reports a failed dismissal', async (
test('AnimeTab keeps an open recommendation review stable during background refresh', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
};
let recommendations = [{ recommendationId: 41, animeIds: [1, 2] as [number, number] }];
apiClient.getAnimeLibrary = (async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2),
libraryItem(2, 'Show Season 1', 1),
]) as typeof apiClient.getAnimeLibrary;
]);
apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations,
})) as typeof apiClient.getAnimeMergeRecommendations;
@@ -434,14 +435,14 @@ test('AnimeTab keeps an open recommendation review stable during background refr
test('AnimeTab keeps the library visible through a transient background refresh failure', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
};
let failLibrary = false;
apiClient.getAnimeLibrary = (async () => {
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
if (failLibrary) throw new Error('temporary failure');
return [libraryItem(1, 'Show', 2), libraryItem(2, 'Show Season 1', 1)];
}) as typeof apiClient.getAnimeLibrary;
});
apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations: [],
})) as typeof apiClient.getAnimeMergeRecommendations;
@@ -470,7 +471,7 @@ test('AnimeTab keeps the library visible through a transient background refresh
test('AnimeTab does not resurrect a dismissed recommendation from a stale in-flight refresh', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
};
@@ -479,10 +480,10 @@ test('AnimeTab does not resurrect a dismissed recommendation from a stale in-fli
};
let holdNextFetch = false;
let releaseHeldFetch: (() => void) | null = null;
apiClient.getAnimeLibrary = (async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2),
libraryItem(2, 'Show Season 1', 1),
]) as typeof apiClient.getAnimeLibrary;
]);
apiClient.getAnimeMergeRecommendations = ((): Promise<typeof payload> => {
if (!holdNextFetch) return Promise.resolve(payload);
holdNextFetch = false;
+12 -10
View File
@@ -6,6 +6,7 @@ import { apiClient } from '../../lib/api-client';
import type { AnimeDetailData, AnimeLibraryItem } from '../../types/stats';
import { AnimeTab } from './AnimeTab';
import { installDom } from '../../test-utils/dom';
import { singleGroupLibrary } from '../../test-utils/library';
function libraryItem(anilistId: number | null): AnimeLibraryItem {
return {
@@ -51,6 +52,7 @@ function detailData(anilistId: number | null): AnimeDetailData {
},
episodes: [],
anilistEntries: [],
group: null,
};
}
@@ -65,7 +67,7 @@ function findButton(container: Element, label: string): HTMLElement {
test('AnimeTab refetches the library after the AniList entry is relinked', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeDetail: apiClient.getAnimeDetail,
getAnimeWords: apiClient.getAnimeWords,
getAnimeRollups: apiClient.getAnimeRollups,
@@ -79,10 +81,10 @@ test('AnimeTab refetches the library after the AniList entry is relinked', async
let anilistId: number | null = 14813;
let libraryFetches = 0;
apiClient.getAnimeLibrary = (async () => {
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
libraryFetches += 1;
return [libraryItem(anilistId)];
}) as typeof apiClient.getAnimeLibrary;
});
apiClient.getAnimeDetail = (async () => detailData(anilistId)) as typeof apiClient.getAnimeDetail;
apiClient.getAnimeWords = (async () => []) as typeof apiClient.getAnimeWords;
apiClient.getAnimeRollups = (async () => []) as typeof apiClient.getAnimeRollups;
@@ -150,8 +152,8 @@ test('AnimeTab refetches the library after the AniList entry is relinked', async
test('AnimeTab watch time follows the displayed kind filter', async () => {
const uninstallDom = installDom();
const original = apiClient.getAnimeLibrary;
apiClient.getAnimeLibrary = async () => [
const original = apiClient.getAnimeLibraryGroups;
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
{ ...libraryItem(42), totalActiveMs: 3600000 },
{
...libraryItem(null),
@@ -162,7 +164,7 @@ test('AnimeTab watch time follows the displayed kind filter', async () => {
tmdbType: 'tv',
totalActiveMs: 7200000,
},
];
]);
const container = document.createElement('div');
document.body.append(container);
const root = createRoot(container);
@@ -180,7 +182,7 @@ test('AnimeTab watch time follows the displayed kind filter', async () => {
await act(async () => {
root.unmount();
});
apiClient.getAnimeLibrary = original;
apiClient.getAnimeLibraryGroups = original;
uninstallDom();
}
});
@@ -188,10 +190,10 @@ test('AnimeTab watch time follows the displayed kind filter', async () => {
test('Library kind filter separates YouTube channels from anime and updates totals', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
};
apiClient.getAnimeLibrary = async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
{ ...libraryItem(null), totalActiveMs: 60_000 },
{
...libraryItem(null),
@@ -200,7 +202,7 @@ test('Library kind filter separates YouTube channels from anime and updates tota
canonicalTitle: 'Language Channel',
totalActiveMs: 120_000,
},
];
]);
apiClient.getAnimeMergeRecommendations = async () => ({ recommendations: [] });
const container = document.createElement('div');
document.body.append(container);
+72 -9
View File
@@ -5,6 +5,7 @@ import {
} from '../../../../src/shared/media-kind';
import { useState, useMemo, useEffect } from 'react';
import { useAnimeLibrary } from '../../hooks/useAnimeLibrary';
import { groupCardData, groupMatchesSearch } from '../../lib/anime-groups';
import { formatDuration } from '../../lib/formatters';
import {
getLibraryCardSizeStorage,
@@ -14,6 +15,7 @@ import {
} from '../../lib/library-card-size';
import { AnimeCard } from './AnimeCard';
import { AnimeDetailView } from './AnimeDetailView';
import { AnimeGroupView } from './AnimeGroupView';
import { AnimeMergeDialog } from './AnimeMergeDialog';
import { DuplicateReviewStrip } from './DuplicateReviewStrip';
@@ -39,7 +41,14 @@ const SORT_OPTIONS: { key: SortKey; label: string }[] = [
{ key: 'episodes', label: 'Episodes' },
];
function sortAnime(list: ReturnType<typeof useAnimeLibrary>['anime'], key: SortKey) {
interface SortableEntry {
lastWatchedMs: number;
totalActiveMs: number;
totalCards: number;
episodeCount: number;
}
function sortAnime<T extends SortableEntry>(list: T[], key: SortKey): T[] {
return [...list].sort((a, b) => {
switch (key) {
case 'lastWatched':
@@ -68,6 +77,7 @@ export function AnimeTab({
onOpenEpisodeDetail,
}: AnimeTabProps) {
const {
groups,
anime,
loading,
error,
@@ -87,6 +97,8 @@ export function AnimeTab({
),
);
const [selectedAnimeId, setSelectedAnimeId] = useState<number | null>(null);
// Franchise card that is open, and stays the back target while one of its parts is open.
const [selectedGroupKey, setSelectedGroupKey] = useState<number | null>(null);
const [selectionMode, setSelectionMode] = useState(false);
const [checkedAnimeIds, setCheckedAnimeIds] = useState<number[]>([]);
const [showMergeDialog, setShowMergeDialog] = useState(false);
@@ -115,11 +127,14 @@ export function AnimeTab({
useEffect(() => {
if (initialAnimeId != null) {
setSelectedGroupKey(null);
setSelectedAnimeId(initialAnimeId);
onClearInitialAnime?.();
}
}, [initialAnimeId, onClearInitialAnime]);
// Merging works on individual entries, so selection mode lists every entry
// on its own; browsing lists one card per franchise.
const filtered = useMemo(() => {
const entries = anime.filter((entry) => mediaKind === 'all' || entry.mediaKind === mediaKind);
const base = search.trim()
@@ -127,8 +142,32 @@ export function AnimeTab({
: entries;
return sortAnime(base, sortKey);
}, [anime, search, sortKey, mediaKind]);
const filteredGroups = useMemo(
() =>
sortAnime(
groups.filter(
(group) =>
(mediaKind === 'all' || group.mediaKind === mediaKind) &&
groupMatchesSearch(group, search),
),
sortKey,
),
[groups, search, sortKey, mediaKind],
);
const shownCount = selectionMode ? filtered.length : filteredGroups.length;
const totalMs = filtered.reduce((sum, a) => sum + a.totalActiveMs, 0);
const totalMs = (selectionMode ? filtered : filteredGroups).reduce(
(sum, entry) => sum + entry.totalActiveMs,
0,
);
const selectedGroup = groups.find((group) => group.groupKey === selectedGroupKey) ?? null;
// A franchise that no longer has several parts closes, so a later refresh
// cannot reopen it on its own. Only loaded results count; while a part is
// open, the franchise stays its back target.
useEffect(() => {
if (loading || selectedGroupKey === null || selectedAnimeId !== null) return;
if (!selectedGroup || selectedGroup.parts.length < 2) setSelectedGroupKey(null);
}, [loading, selectedGroupKey, selectedAnimeId, selectedGroup]);
const checkedEntries = checkedAnimeIds
.map((animeId) => anime.find((entry) => entry.animeId === animeId))
.filter((entry): entry is (typeof anime)[number] => entry !== undefined);
@@ -160,6 +199,7 @@ export function AnimeTab({
return (
<AnimeDetailView
animeId={selectedAnimeId}
backLabel={selectedGroup ? `Back to ${selectedGroup.title}` : undefined}
onBack={() => setSelectedAnimeId(null)}
onNavigateToWord={onNavigateToWord}
onOpenEpisodeDetail={
@@ -170,6 +210,17 @@ export function AnimeTab({
onAnimeDeleted={reload}
onProviderRelinked={reload}
onEpisodeMoved={reload}
onGroupChanged={reload}
/>
);
}
if (selectedGroup && selectedGroup.parts.length > 1) {
return (
<AnimeGroupView
group={selectedGroup}
onBack={() => setSelectedGroupKey(null)}
onOpenPart={setSelectedAnimeId}
/>
);
}
@@ -250,12 +301,12 @@ export function AnimeTab({
{selectionMode ? 'Cancel' : 'Select'}
</button>
<div className="text-xs text-ctp-overlay2 shrink-0">
{filtered.length}{' '}
{shownCount}{' '}
{mediaKind === 'youtube'
? filtered.length === 1
? shownCount === 1
? 'channel'
: 'channels'
: filtered.length === 1
: shownCount === 1
? 'title'
: 'titles'}{' '}
· {formatDuration(totalMs)}
@@ -298,18 +349,30 @@ export function AnimeTab({
</div>
)}
{filtered.length === 0 ? (
{shownCount === 0 ? (
<div className="text-sm text-ctp-overlay2 p-4">No titles found</div>
) : (
) : selectionMode ? (
<div className={`grid ${GRID_CLASSES[cardSize]} gap-4`}>
{filtered.map((item) => (
<AnimeCard
key={item.animeId}
anime={item}
selectable={selectionMode}
selectable
selected={checkedAnimeIds.includes(item.animeId)}
onClick={() => toggleChecked(item.animeId)}
/>
))}
</div>
) : (
<div className={`grid ${GRID_CLASSES[cardSize]} gap-4`}>
{filteredGroups.map((group) => (
<AnimeCard
key={group.groupKey}
anime={groupCardData(group)}
onClick={() =>
selectionMode ? toggleChecked(item.animeId) : setSelectedAnimeId(item.animeId)
group.parts.length > 1
? setSelectedGroupKey(group.groupKey)
: setSelectedAnimeId(group.parts[0]!.animeId)
}
/>
))}
@@ -12,6 +12,8 @@ interface LibraryEntryPickerProps {
excludeAnimeIds?: number[];
/** When set, only entries of this kind are offered. */
mediaKind?: MediaKind;
/** Further narrows the entries offered. */
filter?: (entry: AnimeLibraryItem) => boolean;
initialQuery?: string;
busyAnimeId?: number | null;
error?: string | null;
@@ -23,6 +25,7 @@ export function LibraryEntryPicker({
heading,
excludeAnimeIds = [],
mediaKind,
filter,
initialQuery = '',
busyAnimeId = null,
error = null,
@@ -74,9 +77,10 @@ export function LibraryEntryPicker({
return (entries ?? [])
.filter((entry) => !excluded.has(entry.animeId))
.filter((entry) => mediaKind === undefined || shareTitleNamespace(entry.mediaKind, mediaKind))
.filter((entry) => filter === undefined || filter(entry))
.filter((entry) => !term || entry.canonicalTitle.toLowerCase().includes(term))
.sort((a, b) => b.lastWatchedMs - a.lastWatchedMs);
}, [entries, excluded, mediaKind, query]);
}, [entries, excluded, mediaKind, filter, query]);
return (
<div
+11 -5
View File
@@ -1,11 +1,16 @@
import { useCallback, useState, useEffect, useRef } from 'react';
import { useCallback, useMemo, useState, useEffect, useRef } from 'react';
import { getStatsClient } from './useStatsApi';
import type { AnimeLibraryItem, StatsAnimeMergeRecommendation } from '../types/stats';
import type { AnimeLibraryGroup, StatsAnimeMergeRecommendation } from '../types/stats';
const BACKGROUND_REFRESH_MS = 30_000;
/**
* The library as franchise cards (`groups`) plus every entry on its own
* (`anime`), which merging and duplicate review work on.
*/
export function useAnimeLibrary() {
const [anime, setAnime] = useState<AnimeLibraryItem[]>([]);
const [groups, setGroups] = useState<AnimeLibraryGroup[]>([]);
const anime = useMemo(() => groups.flatMap((group) => group.parts), [groups]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [recommendations, setRecommendations] = useState<StatsAnimeMergeRecommendation[]>([]);
@@ -29,11 +34,11 @@ export function useAnimeLibrary() {
let cancelled = false;
const client = getStatsClient();
client
.getAnimeLibrary()
.getAnimeLibraryGroups()
.then((data) => {
if (!cancelled) {
hasLoadedRef.current = true;
setAnime(data);
setGroups(data);
setError(null);
}
})
@@ -103,6 +108,7 @@ export function useAnimeLibrary() {
}, []);
return {
groups,
anime,
loading,
error,
+62
View File
@@ -0,0 +1,62 @@
import type { AnimeLibraryGroup, AnimeLibraryItem } from '../types/stats';
/** What a library card shows; a single entry or a whole franchise. */
export type AnimeCardData = Pick<
AnimeLibraryItem,
| 'animeId'
| 'canonicalTitle'
| 'anilistId'
| 'tmdbId'
| 'mediaKind'
| 'episodeCount'
| 'totalActiveMs'
| 'totalCards'
> & {
/** Set for franchise cards with more than one part. */
partCount?: number;
};
/** A one-part card is exactly that entry; a franchise card shows the first part's cover. */
export function groupCardData(group: AnimeLibraryGroup): AnimeCardData {
const cover = group.parts.find((part) => part.animeId === group.coverAnimeId) ?? group.parts[0]!;
if (group.parts.length === 1) return cover;
return {
animeId: cover.animeId,
canonicalTitle: group.title,
anilistId: cover.anilistId,
tmdbId: cover.tmdbId,
mediaKind: group.mediaKind,
episodeCount: group.episodeCount,
totalActiveMs: group.totalActiveMs,
totalCards: group.totalCards,
partCount: group.parts.length,
};
}
/** Matches the franchise name or any part's title, so "Undead King" finds Overlord. */
export function groupMatchesSearch(group: AnimeLibraryGroup, search: string): boolean {
const term = search.trim().toLowerCase();
if (!term) return true;
return (
group.title.toLowerCase().includes(term) ||
group.parts.some((part) => part.canonicalTitle.toLowerCase().includes(term))
);
}
const FORMAT_LABELS: Record<string, string> = {
TV: 'TV',
TV_SHORT: 'TV Short',
MOVIE: 'Movie',
SPECIAL: 'Special',
OVA: 'OVA',
ONA: 'ONA',
MUSIC: 'Music',
};
/** "Movie · 2017" from AniList's format and yyyymmdd start date; null when neither is known. */
export function describeAnimePart(format: string | null, startDate: number | null): string | null {
const label = format ? (FORMAT_LABELS[format] ?? format) : null;
const year = startDate ? String(Math.floor(startDate / 10_000)) : null;
const parts = [label, year].filter((value): value is string => value !== null);
return parts.length > 0 ? parts.join(' · ') : null;
}
+12
View File
@@ -3,6 +3,7 @@ import type {
StatsExcludedWord,
StatsCoverImagesData,
StatsAnilistAssignment,
StatsAnimeGroupOverrideRequest,
StatsAnkiNotesInfoRequest,
StatsCoverImagesRequest,
StatsDeleteSessionsRequest,
@@ -163,6 +164,7 @@ export const apiClient = {
getMediaLibrary: () => fetchJson('mediaLibrary', '/api/stats/media'),
getMediaDetail: (videoId: number) => fetchJson('mediaDetail', `/api/stats/media/${videoId}`),
getAnimeLibrary: () => fetchJson('animeLibrary', '/api/stats/anime'),
getAnimeLibraryGroups: () => fetchJson('animeLibraryGroups', '/api/stats/anime/groups'),
getAnimeMergeRecommendations: () =>
fetchJson('animeMergeRecommendations', '/api/stats/anime/merge-recommendations'),
getAnimeDetail: (animeId: number) => fetchJson('animeDetail', `/api/stats/anime/${animeId}`),
@@ -268,6 +270,16 @@ export const apiClient = {
});
return res.json() as Promise<StatsMoveVideoResponse>;
},
setAnimeGroupOverride: async (
animeId: number,
request: StatsAnimeGroupOverrideRequest,
): Promise<void> => {
await fetchResponse(`/api/stats/anime/${animeId}/group`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request satisfies StatsAnimeGroupOverrideRequest),
});
},
dismissAnimeMergeRecommendation: async (recommendationId: number): Promise<void> => {
await fetchResponse(`/api/stats/anime/merge-recommendations/${recommendationId}`, {
method: 'DELETE',
+26
View File
@@ -0,0 +1,26 @@
import type { apiClient } from '../lib/api-client';
import type { AnimeLibraryGroup, AnimeLibraryItem } from '../types/stats';
/** Wraps each entry in a one-part card, as the server does for entries without AniList relations. */
export function asSingleGroups(items: AnimeLibraryItem[]): AnimeLibraryGroup[] {
return items.map((item) => ({
groupKey: -item.animeId,
title: item.canonicalTitle,
mediaKind: item.mediaKind,
coverAnimeId: item.animeId,
totalSessions: item.totalSessions,
totalActiveMs: item.totalActiveMs,
totalCards: item.totalCards,
totalTokensSeen: item.totalTokensSeen,
episodeCount: item.episodeCount,
lastWatchedMs: item.lastWatchedMs,
parts: [{ ...item, format: null, startDate: null }],
}));
}
/** A `getAnimeLibraryGroups` mock serving `load()`'s entries as one-part cards. */
export function singleGroupLibrary(
load: () => Promise<AnimeLibraryItem[]>,
): typeof apiClient.getAnimeLibraryGroups {
return async () => asSingleGroups(await load());
}