Compare commits

..
Author SHA1 Message Date
sudacode 4ed878270f fix(stats): accept legacy lexical rollup state schemas 2026-08-18 02:24:49 -07:00
sudacode 1d1b0c7bb6 fix(subtitles): collapse duplicate primary ASS style layers
- Use parsed cues when they fully explain mpv live text
- Preserve unmatched overlapping dialogue and signs
2026-08-18 01:51:19 -07:00
sudacode db61ce358d fix(stats): preserve session rollups across schema upgrades
- Stop deleting imm_daily_rollups/imm_monthly_rollups on unrelated schema version bumps; their source session/telemetry rows may already be pruned, so deleted buckets could not be rebuilt
- Run startup session-rollup maintenance before the lexical rollup backfill takes the write lock, so recovery no longer races playback writes
- Update the vocabulary summary totals changelog fragment to reflect that watch-time, activity, efficiency, and library charts are no longer cleared during rebuilds
2026-08-18 01:12:58 -07:00
sudacode e9778a945a fix(overlay): deduplicate secondary subtitle rendering (#208) 2026-08-18 00:44:02 -07:00
sudacode 7de73e16a1 fix(stats): report complete vocabulary totals and new-word history (#202) 2026-08-18 00:42:46 -07:00
sudacode 273652f781 fix(subtitles): recover canonical lines from ASS animation (#207) 2026-08-18 00:30:48 -07:00
sudacode 14c0086520 chore(stats): reword duplicates popup 2026-08-17 18:42:58 -07:00
sudacode ff0bc0af6d fix(dictionary): prevent freezes and restore AppImage notifications (#205) 2026-08-17 18:41:03 -07:00
sudacode 00b1b79bf4 fix(mpv): recover from stalled IPC connects (#204) 2026-08-16 22:58:28 -07:00
sudacode e11a5fea0d chore(release): prepare v0.19.4-beta.1 2026-08-16 02:00:32 -07:00
sudacode f73fe179d0 fix(docs): keep versioned pages out of search indexes
- Add self-canonical noindex signals and headers for archived docs
- Restore sitemap lastmod dates from the tracked checkout
2026-08-16 01:45:08 -07:00
sudacode 2938e7a32a fix(overlay): prevent Windows mouse lag during click-through tracking (#201) 2026-08-16 01:34:51 -07:00
sudacode 82f6b4705a fix(overlay): recycle Windows modal windows after close
- Refresh the hidden modal renderer between Windows sessions
- Add regression coverage and stabilize launcher completion testing
2026-08-16 01:10:07 -07:00
sudacode a02c33dac4 fix(overlay): keep macOS modal windows on fullscreen Spaces (#200) 2026-08-15 21:43:26 -07:00
191 changed files with 7783 additions and 5002 deletions
+5
View File
@@ -0,0 +1,5 @@
type: fixed
area: subtitles
- Typeset ASS karaoke and animated signs no longer flood the primary overlay, subtitle sidebar, immersion history, or sentence mining with repeated glyph fragments or full-line color phases. Matching timed comments and full-line boundary events recover the complete authored line without merging ordinary repeated dialogue or separately positioned signs, and dialogue spoken while a song's animation is on screen is kept intact instead of being replaced by the lyric. Entrance and exit frames that run past the authored line timing still resolve to the clean line during lyric transitions, and dialogue spoken while a song's animation is on screen enters immersion and subtitle history without the fragment lines beside it.
- The secondary subtitle overlay drops layered duplicate lines from animated tracks, so a short stack of repeated words collapses to its distinct lines even when the full karaoke heuristic does not apply.
@@ -0,0 +1,5 @@
type: fixed
area: dictionary
- Character dictionary generation, merged rebuilds, and imports no longer freeze the app (and trigger the compositor's "application not responding" dialog) on large dictionaries; snapshot reads/writes, archive building, and the character image/name lookup caches now do their heavy work off the UI's critical path.
- Desktop progress notifications now update in place on Linux AppImage installs too: the AppImage's bundled libraries broke the system notify-send helper, which silently forced the flickering close-and-reopen notification fallback.
+5
View File
@@ -0,0 +1,5 @@
type: internal
area: docs
- Excluded the `/main/` and `/v/<version>/` docs trees from search indexing with a self-referential canonical, `noindex,follow`, and a matching `X-Robots-Tag` header, so crawlers spend their budget on the current docs instead of ~30 archived copies of every page.
- Restored `<lastmod>` dates in the docs sitemap, which were silently dropped because production builds render from an untracked release snapshot.
@@ -0,0 +1,5 @@
type: fixed
area: overlay
- Dedicated overlay modals are prewarmed on macOS and Windows so shortcuts open them promptly on the first press. Windows now refreshes the hidden modal renderer between sessions to keep later modals interactive. On macOS, reused modals and the in-app stats window also open above fullscreen mpv on its current Space instead of appearing on another desktop or forcing a Space change.
- Updated subtitle ASS observation to mpv's current `sub-text/ass` property, removing its deprecation warning.
+4
View File
@@ -0,0 +1,4 @@
type: fixed
area: overlay
- Fixed the overlay getting stuck on "Overlay loading" forever when startup stalls: mpv IPC connection attempts now time out and retry, switching sockets aborts obsolete attempts, and the plugin replaces its spinner with an actionable error if overlay content is still not ready after 30 seconds.
@@ -0,0 +1,4 @@
type: fixed
area: subtitles
- Primary ASS subtitles now use the active parsed cue when it fully accounts for mpv's live text, preventing fill, border, blur, and shadow copies of the same full-span lyric from appearing repeatedly while preserving unmatched overlapping dialogue and signs.
@@ -0,0 +1,4 @@
type: fixed
area: overlay
- Secondary subtitles now parse the selected ASS/SRT/VTT source with the primary subtitle deduplication pipeline, preventing layered animation text from appearing several times in the overlay, mined cards, and statistics. Live mpv text remains the fallback for unreadable tracks.
+4
View File
@@ -0,0 +1,4 @@
type: fixed
area: overlay
- Fixed system-wide mouse lag on Windows while SubMiner is running: the overlay no longer installs Electron's global mouse hook for click-through forwarding, and the mpv window tracker no longer blocks the app on repeated PowerShell command-line lookups.
-4
View File
@@ -1,4 +0,0 @@
type: added
area: mining
- Added optional pre-generation timing review for word, sentence, and audio cards with a compact speech-weighted waveform, clearly labeled mined-line boundaries, drag and keyboard adjustments, audio preview with a sweeping playhead, exact screenshot and AVIF timing, cancellation choices that include keeping a card without media, and a session-only runtime toggle.
@@ -0,0 +1,8 @@
type: fixed
area: stats
- Fixed Vocabulary totals and charts counting only the first browsing page instead of all tracked vocabulary, without delaying the rest of the page.
- New-word history now uses permanent daily lexical rollups that apply the same vocabulary filters as the totals and normalize legacy second/millisecond timestamps; versioned background rebuilds repair existing history across legacy rollup-state schemas without dropping playback writes or clearing watch-time, activity, efficiency, and library charts.
- Calendar-day chart labels now preserve the recorded local date in time zones west of UTC.
- Vocabulary summary cards and charts refresh automatically after the word exclusion list changes, and failed or unfinished loads use bounded retries before showing an inline error with a Retry control.
- Rapid exclusion edits no longer race each other; writes are sent in order so a slower earlier save cannot overwrite a newer list.
+1 -2
View File
@@ -523,7 +523,7 @@
// ========================================== // ==========================================
// AnkiConnect Integration // AnkiConnect Integration
// Automatic Anki updates and media generation options. // Automatic Anki updates and media generation options.
// Hot-reload: ankiConnect.ai.enabled, media.normalizeAudio/mirrorMpvVolume/reviewTiming, knownWords, nPlusOne, fields.word/audio/image/sentence/miscInfo, behavior.autoUpdateNewCards, isLapis.sentenceCardModel, isKiku.fieldGrouping, and lapisKiku.wordCardKind update live while SubMiner is running. // Hot-reload: ankiConnect.ai.enabled, media.normalizeAudio/mirrorMpvVolume, knownWords, nPlusOne, fields.word/audio/image/sentence/miscInfo, behavior.autoUpdateNewCards, isLapis.sentenceCardModel, isKiku.fieldGrouping, and lapisKiku.wordCardKind update live while SubMiner is running.
// Shared AI provider transport settings are read from top-level ai and typically require restart. // Shared AI provider transport settings are read from top-level ai and typically require restart.
// Most other AnkiConnect settings still require restart. // Most other AnkiConnect settings still require restart.
// ========================================== // ==========================================
@@ -569,7 +569,6 @@
"syncAnimatedImageToWordAudio": true, // For animated AVIF images, prepend a frozen first frame matching the existing word-audio duration so motion starts with sentence audio. Values: true | false "syncAnimatedImageToWordAudio": true, // For animated AVIF images, prepend a frozen first frame matching the existing word-audio duration so motion starts with sentence audio. Values: true | false
"normalizeAudio": true, // Normalize generated sentence audio loudness during media extraction. Changes apply live. Values: true | false "normalizeAudio": true, // Normalize generated sentence audio loudness during media extraction. Changes apply live. Values: true | false
"mirrorMpvVolume": true, // Apply mpv's current software volume curve to generated sentence audio. Changes apply live. Values: true | false "mirrorMpvVolume": true, // Apply mpv's current software volume curve to generated sentence audio. Changes apply live. Values: true | false
"reviewTiming": false, // Review and preview subtitle media timing before SubMiner creates or enriches a mined card. Values: true | false
"audioPadding": 0, // Seconds of padding appended to both ends of generated sentence audio and animated AVIF clips. "audioPadding": 0, // Seconds of padding appended to both ends of generated sentence audio and animated AVIF clips.
"fallbackDuration": 3, // Fallback clip duration in seconds when subtitle timing data is unavailable. "fallbackDuration": 3, // Fallback clip duration in seconds when subtitle timing data is unavailable.
"maxMediaDuration": 30 // Maximum allowed media clip duration in seconds. "maxMediaDuration": 30 // Maximum allowed media clip duration in seconds.
+49 -14
View File
@@ -1,3 +1,4 @@
import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync, statSync } from 'node:fs'; import { existsSync, readFileSync, statSync } from 'node:fs';
import { extname, join, posix, resolve, sep } from 'node:path'; import { extname, join, posix, resolve, sep } from 'node:path';
import type { DefaultTheme, HeadConfig, TransformContext, UserConfig } from 'vitepress'; import type { DefaultTheme, HeadConfig, TransformContext, UserConfig } from 'vitepress';
@@ -26,6 +27,9 @@ function optionalEnv(value: string | undefined): string | undefined {
const base = normalizeBase(optionalEnv(process.env.SUBMINER_DOCS_BASE) ?? '/'); const base = normalizeBase(optionalEnv(process.env.SUBMINER_DOCS_BASE) ?? '/');
const outDir = optionalEnv(process.env.SUBMINER_DOCS_OUT_DIR); const outDir = optionalEnv(process.env.SUBMINER_DOCS_OUT_DIR);
const docsSourceDir = optionalEnv(process.env.SUBMINER_DOCS_SOURCE_DIR) ?? process.cwd(); const docsSourceDir = optionalEnv(process.env.SUBMINER_DOCS_SOURCE_DIR) ?? process.cwd();
// The tracked `docs-site/` checkout, which stays a git working tree even when
// `docsSourceDir` points at an untracked release snapshot. Used for git lookups only.
const repoDocsDir = optionalEnv(process.env.SUBMINER_DOCS_REPO_DIR) ?? process.cwd();
const channel = normalizeChannel(optionalEnv(process.env.SUBMINER_DOCS_CHANNEL)); const channel = normalizeChannel(optionalEnv(process.env.SUBMINER_DOCS_CHANNEL));
const docsVersion = optionalEnv(process.env.SUBMINER_DOCS_VERSION); const docsVersion = optionalEnv(process.env.SUBMINER_DOCS_VERSION);
const latestStable = optionalEnv(process.env.SUBMINER_DOCS_LATEST_STABLE) ?? 'v0.18.0'; const latestStable = optionalEnv(process.env.SUBMINER_DOCS_LATEST_STABLE) ?? 'v0.18.0';
@@ -82,15 +86,18 @@ function pageToRoute(page: string): string | null {
return route ? `/${route}` : '/'; return route ? `/${route}` : '/';
} }
// Only the root channel is indexable. `main` and every /v/<version>/ archive are
// near-verbatim copies of it, so they own their URL via a self-referential canonical
// and are excluded from the index instead of being consolidated onto root. Uniform
// self-canonical plus noindex avoids mixing noindex with a cross-page canonical,
// which Google treats as a conflicting signal.
const isIndexableChannel = channel === 'stable-root';
function pageToCanonicalHref(page: string): string | null { function pageToCanonicalHref(page: string): string | null {
const route = pageToRoute(page); const route = pageToRoute(page);
if (!route) return null; if (!route) return null;
if (channel === 'main') { if (!isIndexableChannel) {
return `${DOCS_HOSTNAME}${canonicalRouteWithBase(route)}`;
}
if (channel === 'stable-archive' && docsVersion !== latestStable) {
return `${DOCS_HOSTNAME}${canonicalRouteWithBase(route)}`; return `${DOCS_HOSTNAME}${canonicalRouteWithBase(route)}`;
} }
@@ -106,7 +113,9 @@ function transformPageHead({ page }: TransformContext): HeadConfig[] {
const href = pageToCanonicalHref(page); const href = pageToCanonicalHref(page);
const head: HeadConfig[] = href ? [['link', { rel: 'canonical', href }]] : []; const head: HeadConfig[] = href ? [['link', { rel: 'canonical', href }]] : [];
if (channel === 'main') { // Crawlable so links still pass through, but out of the index: ~30 archived copies
// of every page otherwise soak up the crawl budget the current docs need.
if (!isIndexableChannel) {
head.push(['meta', { name: 'robots', content: 'noindex,follow' }]); head.push(['meta', { name: 'robots', content: 'noindex,follow' }]);
} }
@@ -287,6 +296,39 @@ const versionItems = [
})), })),
]; ];
function sitemapUrlToPage(url: string): string {
const route = url.replace(/\.html$/, '').replace(/^\/+|\/+$/g, '');
return route ? `${route}.md` : 'index.md';
}
// VitePress derives <lastmod> by running `git log` inside its source dir. Production
// builds point that at an untracked snapshot of the release tag, so the lookup comes
// back empty and the sitemap ships with no dates at all. Resolve it from the tracked
// checkout at the ref being built instead.
function lastModifiedFor(url: string): string | undefined {
const ref = docsVersion && docsVersion !== 'main' ? docsVersion : 'HEAD';
const result = spawnSync('git', ['log', '-1', '--format=%cI', ref, '--', sitemapUrlToPage(url)], {
cwd: repoDocsDir,
encoding: 'utf8',
});
return (result.status === 0 && result.stdout.trim()) || undefined;
}
// Only the root channel publishes a sitemap. Archived and `main` builds would emit
// their own copies listing the same canonical URLs, which just advertises the
// duplicate trees we are trying to keep out of the index.
const sitemap: UserConfig['sitemap'] = isIndexableChannel
? {
hostname: DOCS_HOSTNAME,
transformItems(items) {
return items
.filter((item) => item.url !== 'README' && item.url !== `${DOCS_HOSTNAME}/README`)
.map((item) => ({ ...item, lastmod: item.lastmod ?? lastModifiedFor(item.url) }));
},
}
: undefined;
const nav: DefaultTheme.NavItem[] = [ const nav: DefaultTheme.NavItem[] = [
{ text: 'Home', link: '/' }, { text: 'Home', link: '/' },
{ text: 'Get Started', link: '/installation' }, { text: 'Get Started', link: '/installation' },
@@ -419,14 +461,7 @@ const config: UserConfig = {
appearance: 'dark', appearance: 'dark',
cleanUrls: true, cleanUrls: true,
metaChunk: true, metaChunk: true,
sitemap: { sitemap,
hostname: DOCS_HOSTNAME,
transformItems(items) {
return items.filter(
(item) => item.url !== 'README' && item.url !== `${DOCS_HOSTNAME}/README`,
);
},
},
transformHead: transformPageHead, transformHead: transformPageHead,
lastUpdated: true, lastUpdated: true,
srcExclude: ['subagents/**', 'README.md'], srcExclude: ['subagents/**', 'README.md'],
+3 -1
View File
@@ -38,8 +38,10 @@ bun run docs:dev
The public docs root is stable-only: The public docs root is stable-only:
- `/` serves the latest stable release docs. - `/` serves the latest stable release docs.
- `/main/` serves development docs from `main` and is marked `noindex,follow`. - `/main/` serves development docs from `main`.
- `/v/<version>/` serves stable release archives. - `/v/<version>/` serves stable release archives.
- Prerelease tags do not update the docs site. - Prerelease tags do not update the docs site.
Only `/` is indexable. `/main/` and every `/v/<version>/` page carries a self-referential canonical plus `noindex,follow`, and the generated `_headers` file repeats that as an `X-Robots-Tag`. They stay crawlable so their links still resolve, but ~30 archived copies of every page would otherwise consume the crawl budget the current docs need. Only the root build emits `sitemap.xml`, and its `<lastmod>` dates come from `git log` against the tracked checkout at the released tag, because the build renders from an untracked snapshot that VitePress cannot date itself.
Keep Cloudflare Git auto-deploy disabled. The production deploy is `.github/workflows/docs-pages.yml`, which uploads `.tmp/docs-versioned-site` with `--branch main` so tag-triggered runs update Production instead of creating preview deployments. Keep Cloudflare Git auto-deploy disabled. The production deploy is `.github/workflows/docs-pages.yml`, which uploads `.tmp/docs-versioned-site` with `--branch main` so tag-triggered runs update Production instead of creating preview deployments.
-5
View File
@@ -166,7 +166,6 @@ Audio is extracted from the video file using the subtitle's start and end timest
"generateAudio": true, "generateAudio": true,
"normalizeAudio": true, // normalize generated clip loudness "normalizeAudio": true, // normalize generated clip loudness
"mirrorMpvVolume": true, // apply the current mpv volume level "mirrorMpvVolume": true, // apply the current mpv volume level
"reviewTiming": false, // review and adjust timing before media generation
"audioPadding": 0, // optional seconds before and after subtitle timing "audioPadding": 0, // optional seconds before and after subtitle timing
"maxMediaDuration": 30 // cap total duration in seconds "maxMediaDuration": 30 // cap total duration in seconds
} }
@@ -179,10 +178,6 @@ Output format: MP3 at 44100 Hz. If the video has multiple audio streams, SubMine
The audio is uploaded to Anki's media folder and inserted as `[sound:audio_<timestamp>.mp3]`. The audio is uploaded to Anki's media folder and inserted as `[sound:audio_<timestamp>.mp3]`.
Set `media.reviewTiming` to `true` to pause playback and review each word, sentence, or audio card before its media is generated. The review opens with the subtitle range plus configured audio padding. Drag either edge of the clip to trim it, drag the middle to slide it without changing its length, or press anywhere else on the waveform to snap the nearer edge there. A focused edge also moves with the arrow keys, by 100 ms alone or 500 ms with Shift, and the 100 ms buttons do the same. Space previews the selection with a playhead that sweeps the clip, Enter confirms, and Escape cancels. The Earlier and Later buttons reveal another two seconds of available timeline without moving the selected clip. A speech-weighted waveform shows the mined subtitle as a tinted band with labeled line-start and line-end rails, making adjacent dialogue easier to distinguish. SubMiner uses a center channel when one carries dialogue, then falls back to a speech-band mono mix. Waveform analysis failure leaves the timing controls available. The confirmed range is exact: SubMiner does not apply audio padding a second time. Static screenshots use its midpoint, and animated AVIF clips use the full confirmed range.
Canceling the review lets you keep editing, finish with the original timing, keep or create the card without audio or an image, or discard the card. Discard deletes an existing Yomitan or audio card and skips creation for a direct sentence card. Clipboard updates and stats-dashboard mining do not open timing review. Audio preview failure does not block confirmation or card creation. The option is disabled by default and hot-reloads. You can also toggle **Review Media Timing** for the current session from the runtime options palette (`Ctrl/Cmd+Shift+O`).
### Screenshots (Static) ### Screenshots (Static)
A single frame is captured at the current playback position. A single frame is captured at the current playback position.
+3 -6
View File
@@ -873,10 +873,9 @@ When config hot-reload updates shortcut/keybinding/style values, close and reope
Use the runtime options palette to toggle settings live while SubMiner is running. These changes are session-only and reset on restart. Use the runtime options palette to toggle settings live while SubMiner is running. These changes are session-only and reset on restart.
Current runtime options cover automatic card updates, media timing review, Current runtime options cover automatic card updates, known-word highlighting,
known-word highlighting, known-word maturity coloring, N+1 annotation, JLPT known-word maturity coloring, N+1 annotation, JLPT underlines, frequency
underlines, frequency highlighting, known-word match mode, and Kiku field highlighting, known-word match mode, and Kiku field grouping mode.
grouping mode.
Annotation toggles only apply to new subtitle lines after the toggle. The currently displayed line is not re-tokenized in place. Annotation toggles only apply to new subtitle lines after the toggle. The currently displayed line is not re-tokenized in place.
@@ -968,7 +967,6 @@ Enable automatic Anki card creation and updates with media generation:
"animatedCrf": 35, "animatedCrf": 35,
"normalizeAudio": true, "normalizeAudio": true,
"mirrorMpvVolume": true, "mirrorMpvVolume": true,
"reviewTiming": false,
"audioPadding": 0, "audioPadding": 0,
"fallbackDuration": 3, "fallbackDuration": 3,
"maxMediaDuration": 30 "maxMediaDuration": 30
@@ -1021,7 +1019,6 @@ This example is intentionally compact. The option table below documents availabl
| `media.generateAudio` | `true`, `false` | Generate audio clips from video (default: `true`) | | `media.generateAudio` | `true`, `false` | Generate audio clips from video (default: `true`) |
| `media.normalizeAudio` | `true`, `false` | Normalize generated sentence-audio loudness during media extraction (default: `true`). Set to `false` to keep raw source loudness. Changes apply live. | | `media.normalizeAudio` | `true`, `false` | Normalize generated sentence-audio loudness during media extraction (default: `true`). Set to `false` to keep raw source loudness. Changes apply live. |
| `media.mirrorMpvVolume` | `true`, `false` | Apply mpv's cubic software-volume curve to each generated sentence-audio clip (default: `true`). This ignores mpv's separate mute state, falls back to unity scaling if volume cannot be read, and applies changes live. | | `media.mirrorMpvVolume` | `true`, `false` | Apply mpv's cubic software-volume curve to each generated sentence-audio clip (default: `true`). This ignores mpv's separate mute state, falls back to unity scaling if volume cannot be read, and applies changes live. |
| `media.reviewTiming` | `true`, `false` | Pause playback and review word, sentence, and audio card timing before media generation (default: `false`). Clipboard updates and stats-dashboard mining do not open the review. |
| `media.generateImage` | `true`, `false` | Generate image/animation screenshots (default: `true`) | | `media.generateImage` | `true`, `false` | Generate image/animation screenshots (default: `true`) |
| `media.imageType` | `"static"`, `"avif"` | Image type: static screenshot or animated AVIF (default: `"static"`) | | `media.imageType` | `"static"`, `"avif"` | Image type: static screenshot or animated AVIF (default: `"static"`) |
| `media.imageFormat` | `"jpg"`, `"png"`, `"webp"` | Image format (default: `"jpg"`) | | `media.imageFormat` | `"jpg"`, `"png"`, `"webp"` | Image format (default: `"jpg"`) |
+5 -1
View File
@@ -82,7 +82,7 @@ Expandable session history with new-word activity, cumulative totals, and pause/
#### Vocabulary #### Vocabulary
Top repeated words (click a bar to open the word), new-word timeline, cross-title and frequency rank tables with Hide Known / Hide Kana filters, kanji breakdown, word exclusion list, and click-through occurrence drilldown with Mine Word / Mine Sentence / Mine Audio buttons. The summary cards show all unique vocabulary and kanji recorded in the local tracking database; **New This Week** is the only weekly figure and uses a rolling seven-day window. The word and kanji tables load first while those complete totals calculate separately. Top Repeated Words and New Words by Day use complete tracking history rather than the table's browsing page. New-word history is maintained as a permanent daily lexical rollup using the same token-visibility rules as the totals, including normalization of older timestamps stored in either seconds or milliseconds and retroactive corrections when tracked material is removed or reprocessed. On the first launch after an applicable upgrade, that history is version-rebuilt in the background and the chart refreshes when it is ready; if it remains unavailable, polling stops and an inline Retry control appears. The cards and charts also refresh automatically after the word exclusion list changes. The rest of the tab includes cross-title and frequency rank tables with Hide Known / Hide Kana filters, kanji breakdown, word exclusion list, and click-through occurrence drilldown with Mine Word / Mine Sentence / Mine Audio buttons.
![Stats Vocabulary](/screenshots/stats-vocabulary.png) ![Stats Vocabulary](/screenshots/stats-vocabulary.png)
@@ -138,6 +138,8 @@ Karaoke openings and animated signs are authored as one subtitle event per anima
Recording now collapses those runs as they happen, matching what the subtitle sidebar shows: Recording now collapses those runs as they happen, matching what the subtitle sidebar shows:
- When a typeset ASS file stores a clean lyric or sign in a timed authoring comment, or in full-line events surrounding generated fragments, the matching complete line is recorded once. The repeated glyph or clip-animation frames are not recorded. Dialogue spoken while such an animation is on screen records as itself, without the fragment lines beside it.
- When karaoke styling redraws the same complete lyric across consecutive color or highlight phases, those phases are combined into one line with their full timing. Repeated ordinary dialogue remains separate.
- When the active subtitle source has been parsed, its cue list has already had duplicate events and animation bursts merged. A line landing inside a surviving cue but after that cue's start is a frame the sidebar merged away, and is not recorded. - When the active subtitle source has been parsed, its cue list has already had duplicate events and animation bursts merged. A line landing inside a surviving cue but after that cue's start is a frame the sidebar merged away, and is not recorded.
- When no parsed cue covers the live timing, including while a subtitle source is changing or shifted, the strict metadata-free rule applies: a run of identical, contiguous lines each shorter than 0.1s stops being recorded after a few frames. Runs are tracked per line of text, so dual-line karaoke (a kanji and a romaji line frame-flipped together) collapses both lines. Ordinary repeated dialogue, and lines held for a normal beat, always record. - When no parsed cue covers the live timing, including while a subtitle source is changing or shifted, the strict metadata-free rule applies: a run of identical, contiguous lines each shorter than 0.1s stops being recorded after a few frames. Runs are tracked per line of text, so dual-line karaoke (a kanji and a romaji line frame-flipped together) collapses both lines. Ordinary repeated dialogue, and lines held for a normal beat, always record.
@@ -180,6 +182,7 @@ In practice:
- Anime and episode pages keep lifetime totals from summary tables while session drill-down still reads retained sessions directly. With the current defaults, both are kept forever. - Anime and episode pages keep lifetime totals from summary tables while session drill-down still reads retained sessions directly. With the current defaults, both are kept forever.
- Trends can read the full available history because daily/monthly rollups are also kept forever by default. - Trends can read the full available history because daily/monthly rollups are also kept forever by default.
- Vocabulary and kanji totals are cumulative and not bounded by the raw session retention knobs. - Vocabulary and kanji totals are cumulative and not bounded by the raw session retention knobs.
- New-word charts use their own permanent lexical daily rollups, which are not pruned by activity-rollup retention.
## Storage / Performance Model ## Storage / Performance Model
@@ -349,6 +352,7 @@ Rollup tables:
- `imm_daily_rollups` - `imm_daily_rollups`
- `imm_monthly_rollups` - `imm_monthly_rollups`
- `imm_lexical_daily_rollups` - permanent first-discovery counts for vocabulary and kanji chart history
- `imm_rollup_state` - incremental rollup progress bookkeeping - `imm_rollup_state` - incremental rollup progress bookkeeping
Vocabulary tables: Vocabulary tables:
+1 -2
View File
@@ -523,7 +523,7 @@
// ========================================== // ==========================================
// AnkiConnect Integration // AnkiConnect Integration
// Automatic Anki updates and media generation options. // Automatic Anki updates and media generation options.
// Hot-reload: ankiConnect.ai.enabled, media.normalizeAudio/mirrorMpvVolume/reviewTiming, knownWords, nPlusOne, fields.word/audio/image/sentence/miscInfo, behavior.autoUpdateNewCards, isLapis.sentenceCardModel, isKiku.fieldGrouping, and lapisKiku.wordCardKind update live while SubMiner is running. // Hot-reload: ankiConnect.ai.enabled, media.normalizeAudio/mirrorMpvVolume, knownWords, nPlusOne, fields.word/audio/image/sentence/miscInfo, behavior.autoUpdateNewCards, isLapis.sentenceCardModel, isKiku.fieldGrouping, and lapisKiku.wordCardKind update live while SubMiner is running.
// Shared AI provider transport settings are read from top-level ai and typically require restart. // Shared AI provider transport settings are read from top-level ai and typically require restart.
// Most other AnkiConnect settings still require restart. // Most other AnkiConnect settings still require restart.
// ========================================== // ==========================================
@@ -569,7 +569,6 @@
"syncAnimatedImageToWordAudio": true, // For animated AVIF images, prepend a frozen first frame matching the existing word-audio duration so motion starts with sentence audio. Values: true | false "syncAnimatedImageToWordAudio": true, // For animated AVIF images, prepend a frozen first frame matching the existing word-audio duration so motion starts with sentence audio. Values: true | false
"normalizeAudio": true, // Normalize generated sentence audio loudness during media extraction. Changes apply live. Values: true | false "normalizeAudio": true, // Normalize generated sentence audio loudness during media extraction. Changes apply live. Values: true | false
"mirrorMpvVolume": true, // Apply mpv's current software volume curve to generated sentence audio. Changes apply live. Values: true | false "mirrorMpvVolume": true, // Apply mpv's current software volume curve to generated sentence audio. Changes apply live. Values: true | false
"reviewTiming": false, // Review and preview subtitle media timing before SubMiner creates or enriches a mined card. Values: true | false
"audioPadding": 0, // Seconds of padding appended to both ends of generated sentence audio and animated AVIF clips. "audioPadding": 0, // Seconds of padding appended to both ends of generated sentence audio and animated AVIF clips.
"fallbackDuration": 3, // Fallback clip duration in seconds when subtitle timing data is unavailable. "fallbackDuration": 3, // Fallback clip duration in seconds when subtitle timing data is unavailable.
"maxMediaDuration": 30 // Maximum allowed media clip duration in seconds. "maxMediaDuration": 30 // Maximum allowed media clip duration in seconds.
+49 -21
View File
@@ -56,34 +56,43 @@ test('main docs canonical uses /main/ and emits noindex', async () => {
{ rel: 'canonical', href: 'https://docs.subminer.moe/main/' }, { rel: 'canonical', href: 'https://docs.subminer.moe/main/' },
]); ]);
expect(head).toContainEqual(['meta', { name: 'robots', content: 'noindex,follow' }]); expect(head).toContainEqual(['meta', { name: 'robots', content: 'noindex,follow' }]);
expect(mainDocsConfig.sitemap).toBeUndefined();
process.env.SUBMINER_DOCS_CHANNEL = previousChannel; process.env.SUBMINER_DOCS_CHANNEL = previousChannel;
process.env.SUBMINER_DOCS_BASE = previousBase; process.env.SUBMINER_DOCS_BASE = previousBase;
}); });
test('latest stable archive canonical points to root equivalent', async () => { test.each([
const previousChannel = process.env.SUBMINER_DOCS_CHANNEL; ['latest stable', 'v0.14.0', '/v/0.14.0/', 'https://docs.subminer.moe/v/0.14.0/usage'],
const previousBase = process.env.SUBMINER_DOCS_BASE; ['superseded', 'v0.12.0', '/v/0.12.0/', 'https://docs.subminer.moe/v/0.12.0/usage'],
const previousVersion = process.env.SUBMINER_DOCS_VERSION; ])(
const previousLatest = process.env.SUBMINER_DOCS_LATEST_STABLE; '%s archive keeps a self-referential canonical and stays out of the index',
process.env.SUBMINER_DOCS_CHANNEL = 'stable-archive'; async (_label, version, base, expectedCanonical) => {
process.env.SUBMINER_DOCS_BASE = '/v/0.14.0/'; const previousChannel = process.env.SUBMINER_DOCS_CHANNEL;
process.env.SUBMINER_DOCS_VERSION = 'v0.14.0'; const previousBase = process.env.SUBMINER_DOCS_BASE;
process.env.SUBMINER_DOCS_LATEST_STABLE = 'v0.14.0'; const previousVersion = process.env.SUBMINER_DOCS_VERSION;
const { default: latestArchiveConfig } = await import('./.vitepress/config?latest-archive'); const previousLatest = process.env.SUBMINER_DOCS_LATEST_STABLE;
process.env.SUBMINER_DOCS_CHANNEL = 'stable-archive';
process.env.SUBMINER_DOCS_BASE = base;
process.env.SUBMINER_DOCS_VERSION = version;
process.env.SUBMINER_DOCS_LATEST_STABLE = 'v0.14.0';
try {
const { default: archiveConfig } = await import(`./.vitepress/config?archive-${version}`);
const head = await latestArchiveConfig.transformHead?.(makeTransformContext('usage.md')); const head = await archiveConfig.transformHead?.(makeTransformContext('usage.md'));
expect(head).toContainEqual([ expect(head).toContainEqual(['link', { rel: 'canonical', href: expectedCanonical }]);
'link', expect(head).toContainEqual(['meta', { name: 'robots', content: 'noindex,follow' }]);
{ rel: 'canonical', href: 'https://docs.subminer.moe/usage' }, // A sitemap here would advertise the archive tree we just excluded.
]); expect(archiveConfig.sitemap).toBeUndefined();
} finally {
process.env.SUBMINER_DOCS_CHANNEL = previousChannel; process.env.SUBMINER_DOCS_CHANNEL = previousChannel;
process.env.SUBMINER_DOCS_BASE = previousBase; process.env.SUBMINER_DOCS_BASE = previousBase;
process.env.SUBMINER_DOCS_VERSION = previousVersion; process.env.SUBMINER_DOCS_VERSION = previousVersion;
process.env.SUBMINER_DOCS_LATEST_STABLE = previousLatest; process.env.SUBMINER_DOCS_LATEST_STABLE = previousLatest;
}); }
},
);
test('stable archive theme links stay on the selected version', async () => { test('stable archive theme links stay on the selected version', async () => {
const previousCwd = process.cwd(); const previousCwd = process.cwd();
@@ -433,3 +442,22 @@ test('docs sitemap excludes duplicate README page from indexable URLs', async ()
expect(transformedItems?.map((item) => item.url)).toEqual(['', 'usage']); expect(transformedItems?.map((item) => item.url)).toEqual(['', 'usage']);
}); });
test('docs sitemap dates every URL from the tracked checkout', async () => {
const previousRepoDir = process.env.SUBMINER_DOCS_REPO_DIR;
// Production builds render from an untracked snapshot, so the date has to come from
// the real checkout rather than VitePress's own srcDir git lookup.
process.env.SUBMINER_DOCS_REPO_DIR = docsSiteDir;
try {
const { default: sitemapConfig } = await import('./.vitepress/config?sitemap-lastmod');
const items = await sitemapConfig.sitemap?.transformItems?.([{ url: '' }, { url: 'usage' }]);
expect(items).toHaveLength(2);
for (const item of items ?? []) {
expect(item.lastmod).toMatch(/^\d{4}-\d{2}-\d{2}T/);
}
} finally {
process.env.SUBMINER_DOCS_REPO_DIR = previousRepoDir;
}
});
+2
View File
@@ -12,6 +12,8 @@ When SubMiner parses the active subtitle source into a cue list, the sidebar bec
- Clicking any cue seeks mpv to that timestamp. - Clicking any cue seeks mpv to that timestamp.
- The sidebar stays synchronized with the overlay - media transitions and subtitle source changes update both simultaneously. - The sidebar stays synchronized with the overlay - media transitions and subtitle source changes update both simultaneously.
For typeset ASS karaoke and animated signs, SubMiner collapses generated animation frames and repeated full-line color phases before they reach the sidebar. It recovers a clean complete line from a matching timed authoring comment or from full-line events surrounding generated fragments. Ordinary ASS comments, editor notes, alternate lines, repeated dialogue, and separately positioned signs remain distinct.
The sidebar only appears when a parsed cue list is available. External subtitle sources that SubMiner cannot parse (for example, embedded ASS tracks rendered directly by mpv) will not populate the sidebar. The sidebar only appears when a parsed cue list is available. External subtitle sources that SubMiner cannot parse (for example, embedded ASS tracks rendered directly by mpv) will not populate the sidebar.
## Layout Modes ## Layout Modes
@@ -70,18 +70,25 @@ interface SubtitleCue {
startTime: number; // seconds startTime: number; // seconds
endTime: number; // seconds endTime: number; // seconds
text: string; // plain text, decoded from the source format text: string; // plain text, decoded from the source format
source?: 'canonical-ass'; // recovered authored text for generated ASS animation
animationStartTime?: number; // full generated-frame envelope; entrance/exit frames
animationEndTime?: number; // run past the authored timing, live matching uses this
} }
``` ```
**Supported formats:** **Supported formats:**
- SRT/VTT: Regex-based parsing of timing lines + text content between timing blocks. - SRT/VTT: Regex-based parsing of timing lines + text content between timing blocks.
- ASS: Parse `[Events]` section, extract `Dialogue:` lines, read the field order from the `Format:` row, and take everything after the Text field index as the text (Text can itself contain commas). - ASS: Parse the `[Events]` section, read the field order from the `Format:` row, and extract timed `Dialogue:` lines. Timed `Comment:` lines are normally ignored, but can supply canonical authored text when they match a nearby generated animation from the same style and actor. Text can itself contain commas.
**ASS decoding.** The parser is where ASS text is decoded, once, via `assToPlainText()` in `src/core/services/ass-text.ts`. That decoder mirrors mpv's `ass_to_plaintext` so a cue read from a file reads identically to the same line arriving live on `sub-text`: `{...}` override blocks are markup, `\pN … \p0` vector drawing runs are dropped rather than shown as text, `\N`/`\n`/`\h` are the only escapes (`\{`, `\}` and `\\` are not), and an unclosed `{` is rendered verbatim. Every layer downstream — renderer, timing tracker, tokenizer, tokenization cache keys — receives plain text and uses `normalizePlainSubtitleText()` for whitespace only, so nothing decodes the same string twice and one authored line always maps to one cache key. **ASS decoding.** The parser is where ASS text is decoded, once, via `assToPlainText()` in `src/core/services/ass-text.ts`. That decoder mirrors mpv's `ass_to_plaintext` so a cue read from a file reads identically to the same line arriving live on `sub-text`: `{...}` override blocks are markup, `\pN … \p0` vector drawing runs are dropped rather than shown as text, `\N`/`\n`/`\h` are the only escapes (`\{`, `\}` and `\\` are not), and an unclosed `{` is rendered verbatim. Every layer downstream — renderer, timing tracker, tokenizer, tokenization cache keys — receives plain text and uses `normalizePlainSubtitleText()` for whitespace only, so nothing decodes the same string twice and one authored line always maps to one cache key.
**Duplicate collapsing.** Typeset scripts emit one `Dialogue:` event per animation frame, plus layered copies of the same line. The parser collapses identical text over an identical span unconditionally, and collapses contiguous same-text runs of at least three events when the run looks like an animation. For ASS that means shared style and actor plus authoring evidence: a temporal tag (`\t`, `\move`, `\k`/`\kf`/`\ko`/`\K`, or anything wrapped in `\t(...)`), an animated `Effect` column (`Karaoke`, `Banner`, `Scroll`), or override values that change across the run. Static tags shared by every event (`\pos`, an identical `\clip`) are not evidence. SRT/VTT carry no such metadata, so there collapsing needs at least five contiguous events all under 0.1s — the frame timing left behind by ASS-to-SRT conversion. The parser keeps this authoring metadata (style, actor, layer, `Effect`, parsed override commands, source order) private; `parseSubtitleCues()` returns only `SubtitleCue`. **Duplicate collapsing.** Typeset scripts emit one `Dialogue:` event per animation frame, plus layered copies of the same line. The parser collapses identical text over an identical span unconditionally, and collapses contiguous same-text runs of at least three events when the run looks like an animation. For ASS that means shared style and actor plus authoring evidence: a temporal tag (`\t`, `\move`, `\k`/`\kf`/`\ko`/`\K`, or anything wrapped in `\t(...)`), an animated `Effect` column (`Karaoke`, `Banner`, `Scroll`), or override values that change across the run. Static tags shared by every event (`\pos`, an identical `\clip`) are not evidence. SRT/VTT carry no such metadata, so there collapsing needs at least five contiguous events all under 0.1s — the frame timing left behind by ASS-to-SRT conversion. The parser keeps this authoring metadata (style, actor, layer, `Effect`, parsed override commands, source order) private; `parseSubtitleCues()` returns only `SubtitleCue`.
ASS scripts can also redraw one complete lyric for two or more long color/highlight phases. Those flush-timed phases collapse separately from short animation frames when they share text, style, actor, and layer and carry direct animation evidence, such as temporal tags or changing non-spatial overrides. Spatial command changes do not prove a phase, so separately positioned signs remain distinct.
**Canonical animation recovery.** Some ASS producers keep the readable lyric or sign as a timed `Comment:` and generate hundreds of `Dialogue:` frames containing repeated glyphs or changing clip regions. Others retain the complete line as brief `Dialogue:` events around the generated fragments. A complete event is promoted only when nearby dialogue from the same style and actor forms a proven animation cluster and reconstructs its entire text in source order. The generated frames are then replaced by one cue marked `source: 'canonical-ass'`. This source marker lets the live primary-subtitle path prefer the clean authored text and timing for display, sidebar history, immersion recording, and mining, while unmatched editor notes and alternative translations remain ignored.
#### Prefetch Service Lifecycle #### Prefetch Service Lifecycle
1. **Activation trigger:** When a subtitle track is activated (or changes), check if it's external via MPV's `track-list` property. If `external === true`, read the file via `external-filename` using the existing `loadSubtitleSourceText` infrastructure. 1. **Activation trigger:** When a subtitle track is activated (or changes), check if it's external via MPV's `track-list` property. If `external === true`, read the file via `external-filename` using the existing `loadSubtitleSourceText` infrastructure.
+3 -1
View File
@@ -23,7 +23,9 @@ Trend charts now consume one chart-oriented backend payload from `/api/stats/tre
- lookup rate trends - lookup rate trends
- watch-time by day-of-week/hour - watch-time by day-of-week/hour
- vocabulary-backed: - vocabulary-backed:
- new-words trend - new-words trend reads permanent daily lexical rollups
- rollup rows count only vocabulary-visible tokens and normalize mixed legacy timestamp units
- a persisted rollup version invalidates stale materializations and triggers an atomic background rebuild
## Metric Semantics ## Metric Semantics
+32 -4
View File
@@ -3,7 +3,7 @@
# Subtitle Overlay Priming # Subtitle Overlay Priming
Status: active Status: active
Last verified: 2026-08-04 Last verified: 2026-08-18
Owner: Kyle Yasuda Owner: Kyle Yasuda
Read when: debugging subtitle state or blank Linux/X11 overlay windows when the visible overlay is shown or recreated Read when: debugging subtitle state or blank Linux/X11 overlay windows when the visible overlay is shown or recreated
@@ -69,6 +69,11 @@ coming and prefetching would otherwise idle for the rest of the cue.
## Live Cue Delivery ## Live Cue Delivery
- Primary live text first resolves recovered canonical ASS animations. Otherwise, when
every live mpv line matches an active parsed cue, it uses the parsed cue text so exact
full-span style layers appear once instead of repeating for fill, border, blur, and
shadow events. Any unmatched live line keeps the complete live stack, preserving
dialogue or signs that overlap a lyric.
- A tokenization cache miss emits the plain cue synchronously. Tokenization remains serialized so - A tokenization cache miss emits the plain cue synchronously. Tokenization remains serialized so
live work does not contend for Yomitan state. live work does not contend for Yomitan state.
- If a newer cue arrives while an older line is still tokenizing, the newer plain cue or empty - If a newer cue arrives while an older line is still tokenizing, the newer plain cue or empty
@@ -77,6 +82,25 @@ coming and prefetching would otherwise idle for the rest of the cue.
- The current cue upgrades in place when its tokens and annotations are ready. This can reflow text - The current cue upgrades in place when its tokens and annotations are ready. This can reflow text
or character images, but cue visibility does not wait for that work. or character images, but cue visibility does not wait for that work.
## Secondary Subtitle Flow
- `secondary-sub-text` remains the immediate fallback, so unreadable and remote subtitle sources
still appear without waiting for file resolution.
- `secondary-subtitle-track.ts` resolves `secondary-sid` against mpv's track list. External tracks
are read directly; supported embedded text tracks are extracted through the same ffmpeg-backed
source resolver used by primary subtitle prefetching.
- The selected source is parsed with `parseSubtitleCues()`, including metadata-aware ASS duplicate
and animation collapse. Playback `time-pos` selects the active parsed cue after applying
`secondary-sub-delay`.
- The resolved text is stored in `mpvClient.currentSecondarySubText` before it is broadcast. The
overlay, mining, timing tracker, and immersion statistics therefore consume the same secondary
text when a readable source is available.
- Media and `secondary-sid` changes clear the previous parsed state before refreshing the source;
track-list changes refresh without discarding an unchanged source. Observed
`secondary-sub-delay` changes retime the active parsed cue without rereading the file. If loading,
extraction, or parsing fails, the controller returns to live mpv text and the renderer's
conservative short stack heuristic remains the final display fallback.
## Emitted State ## Emitted State
- `emitSubtitle(payload)` maps to `emitSubtitlePayload(payload)`. Overlay windows and annotation - `emitSubtitle(payload)` maps to `emitSubtitlePayload(payload)`. Overlay windows and annotation
@@ -84,8 +108,8 @@ coming and prefetching would otherwise idle for the rest of the cue.
- The basic subtitle websocket receives the immediate plain cue only. Because its serialized - The basic subtitle websocket receives the immediate plain cue only. Because its serialized
payload discards annotations, the later upgrade would be an identical duplicate and is skipped payload discards annotations, the later upgrade would be an identical duplicate and is skipped
when text and cue timing match. when text and cue timing match.
- Secondary priming reads mpv `secondary-sub-text`, stores it in - Secondary priming reads mpv `secondary-sub-text` and routes it through the secondary track
`mpvClient.currentSecondarySubText`, and broadcasts `secondary-subtitle:set` to overlay windows. controller. A parsed active cue replaces the live text when the selected source is readable.
- If secondary `requestProperty` fails, the primary flow stays complete and only a debug line is - If secondary `requestProperty` fails, the primary flow stays complete and only a debug line is
written. written.
@@ -129,7 +153,11 @@ coming and prefetching would otherwise idle for the rest of the cue.
path, empty or stale bounding shapes produced invisible or clipped subtitles even though the path, empty or stale bounding shapes produced invisible or clipped subtitles even though the
overlay window remained mapped above mpv. overlay window remained mapped above mpv.
- Pointer pass-through should continue to use `setIgnoreMouseEvents(true, { forward: true })` and - Pointer pass-through should continue to use `setIgnoreMouseEvents(true, { forward: true })` and
the Linux cursor-poll fallback, not bounding-shape clipping. the Linux cursor-poll fallback, not bounding-shape clipping. Note that on Windows click-through
must go through `applyOverlayClickThrough()` (`src/core/services/overlay-click-through.ts`),
which omits `forward: true` there: Electron implements forwarding with a global low-level mouse
hook that lags mouse input system-wide whenever the main thread stalls; the Windows cursor poll
handles overlay wake-up instead.
- Visible-overlay show/reset marks Linux pointer passthrough state dirty even when the logical - Visible-overlay show/reset marks Linux pointer passthrough state dirty even when the logical
interaction state is already inactive. The next cursor-poll tick must still reapply interaction state is already inactive. The next cursor-poll tick must still reapply
`setIgnoreMouseEvents(true, { forward: true })`; otherwise a newly shown Electron overlay can keep `setIgnoreMouseEvents(true, { forward: true })`; otherwise a newly shown Electron overlay can keep
@@ -18,6 +18,9 @@ export function createImmersionDbFixture(dbPath: string): void {
db.prepare( db.prepare(
`INSERT INTO imm_rollup_state(state_key, state_value) VALUES ('last_rollup_sample_ms', 0)`, `INSERT INTO imm_rollup_state(state_key, state_value) VALUES ('last_rollup_sample_ms', 0)`,
).run(); ).run();
db.prepare(
`INSERT INTO imm_rollup_state(state_key, state_value) VALUES ('lexical_daily_rollups_version', 0)`,
).run();
db.prepare( db.prepare(
`INSERT INTO imm_lifetime_global(global_id, CREATED_DATE, LAST_UPDATE_DATE) VALUES (1, ?, ?)`, `INSERT INTO imm_lifetime_global(global_id, CREATED_DATE, LAST_UPDATE_DATE) VALUES (1, ?, ?)`,
).run(String(Date.now()), String(Date.now())); ).run(String(Date.now()), String(Date.now()));
@@ -108,6 +108,36 @@ test('fixture schema stays aligned with production sync-touched tables and index
} }
}); });
test('fixture leaves lexical rollups pending when their table is absent', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-fixture-rollup-state-'));
const fixturePath = path.join(dir, 'fixture.sqlite');
try {
createImmersionDbFixture(fixturePath);
const db = new BunDatabase(fixturePath, { readonly: true });
try {
const state = db
.query<{ state_value: string }>(
`SELECT state_value FROM imm_rollup_state
WHERE state_key = 'lexical_daily_rollups_version'`,
)
.get();
const rollupTable = db
.query<{ name: string }>(
`SELECT name FROM sqlite_schema
WHERE type = 'table' AND name = 'imm_lexical_daily_rollups'`,
)
.get();
assert.equal(state?.state_value, '0');
assert.equal(rollupTable, null);
} finally {
db.close();
}
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('fixture session inserts enforce foreign keys', () => { test('fixture session inserts enforce foreign keys', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-fixture-foreign-keys-')); const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-fixture-foreign-keys-'));
const fixturePath = path.join(dir, 'fixture.sqlite'); const fixturePath = path.join(dir, 'fixture.sqlite');
@@ -154,6 +154,7 @@ export const IMMERSION_DB_FIXTURE_DDL = `
last_seen REAL, last_seen REAL,
frequency INTEGER, frequency INTEGER,
frequency_rank INTEGER, frequency_rank INTEGER,
vocabulary_visible INTEGER NOT NULL DEFAULT 1 CHECK(vocabulary_visible IN (0, 1)),
UNIQUE(headword, word, reading) UNIQUE(headword, word, reading)
); );
CREATE TABLE imm_kanji( CREATE TABLE imm_kanji(
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "subminer", "name": "subminer",
"productName": "SubMiner", "productName": "SubMiner",
"desktopName": "SubMiner.desktop", "desktopName": "SubMiner.desktop",
"version": "0.19.3", "version": "0.19.4-beta.1",
"description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration", "description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration",
"packageManager": "bun@1.3.5", "packageManager": "bun@1.3.5",
"main": "dist/main-entry.js", "main": "dist/main-entry.js",
+5 -2
View File
@@ -106,8 +106,11 @@ function M.create(ctx)
local function get_subtitle_ass_property() local function get_subtitle_ass_property()
local ass_text = mp.get_property("sub-text/ass") local ass_text = mp.get_property("sub-text/ass")
if type(ass_text) == "string" and ass_text ~= "" then if ass_text ~= nil then
return ass_text if type(ass_text) == "string" and ass_text ~= "" then
return ass_text
end
return nil
end end
ass_text = mp.get_property("sub-text-ass") ass_text = mp.get_property("sub-text-ass")
if type(ass_text) == "string" and ass_text ~= "" then if type(ass_text) == "string" and ass_text ~= "" then
+26
View File
@@ -7,6 +7,8 @@ local OVERLAY_RESTART_PING_MAX_ATTEMPTS = 20
local OVERLAY_LOADING_OSD_PREFIX = "Overlay loading " local OVERLAY_LOADING_OSD_PREFIX = "Overlay loading "
local OVERLAY_LOADING_OSD_FRAMES = { "|", "/", "-", "\\" } local OVERLAY_LOADING_OSD_FRAMES = { "|", "/", "-", "\\" }
local OVERLAY_LOADING_OSD_REFRESH_SECONDS = 0.18 local OVERLAY_LOADING_OSD_REFRESH_SECONDS = 0.18
local OVERLAY_LOADING_OSD_DEADLINE_SECONDS = 30
local OVERLAY_LOADING_OSD_TIMEOUT_MESSAGE = "Overlay did not become ready; check SubMiner logs"
local AUTO_PLAY_READY_LOADING_OSD = "Loading subtitle tokenization..." local AUTO_PLAY_READY_LOADING_OSD = "Loading subtitle tokenization..."
local AUTO_PLAY_READY_READY_OSD = "Subtitle tokenization ready" local AUTO_PLAY_READY_READY_OSD = "Subtitle tokenization ready"
local DEFAULT_AUTO_PLAY_READY_TIMEOUT_SECONDS = 30 local DEFAULT_AUTO_PLAY_READY_TIMEOUT_SECONDS = 30
@@ -265,10 +267,19 @@ function M.create(ctx)
state.overlay_loading_osd_timer = nil state.overlay_loading_osd_timer = nil
end end
local function clear_overlay_loading_osd_deadline()
local timeout = state.overlay_loading_osd_deadline
if timeout and timeout.kill then
timeout:kill()
end
state.overlay_loading_osd_deadline = nil
end
local function stop_overlay_loading_osd() local function stop_overlay_loading_osd()
state.overlay_loading_osd_active = false state.overlay_loading_osd_active = false
state.overlay_loading_osd_frame = 1 state.overlay_loading_osd_frame = 1
clear_overlay_loading_osd_timer() clear_overlay_loading_osd_timer()
clear_overlay_loading_osd_deadline()
end end
local function start_overlay_loading_osd() local function start_overlay_loading_osd()
@@ -291,6 +302,21 @@ function M.create(ctx)
end end
end) end)
end end
if type(mp.add_timeout) == "function" then
state.overlay_loading_osd_deadline = mp.add_timeout(OVERLAY_LOADING_OSD_DEADLINE_SECONDS, function()
if not state.overlay_loading_osd_active then
return
end
state.overlay_loading_osd_deadline = nil
stop_overlay_loading_osd()
subminer_log(
"warn",
"process",
"Overlay loading deadline expired before the app reported content ready"
)
show_osd(OVERLAY_LOADING_OSD_TIMEOUT_MESSAGE, { force = true })
end)
end
end end
local function disarm_auto_play_ready_gate(options) local function disarm_auto_play_ready_gate(options)
+3 -3
View File
@@ -232,7 +232,7 @@ function M.create(ctx)
elseif action_id == "triggerFieldGrouping" then elseif action_id == "triggerFieldGrouping" then
return { "--trigger-field-grouping" } return { "--trigger-field-grouping" }
elseif action_id == "triggerSubsync" then elseif action_id == "triggerSubsync" then
return { "--trigger-subsync" } return { "--session-action", '{"actionId":"triggerSubsync"}' }
elseif action_id == "mineSentence" then elseif action_id == "mineSentence" then
return { "--mine-sentence" } return { "--mine-sentence" }
elseif action_id == "mineSentenceMultiple" then elseif action_id == "mineSentenceMultiple" then
@@ -251,7 +251,7 @@ function M.create(ctx)
elseif action_id == "markWatched" then elseif action_id == "markWatched" then
return { "--mark-watched" } return { "--mark-watched" }
elseif action_id == "openRuntimeOptions" then elseif action_id == "openRuntimeOptions" then
return { "--open-runtime-options" } return { "--session-action", '{"actionId":"openRuntimeOptions"}' }
elseif action_id == "openJimaku" then elseif action_id == "openJimaku" then
return { "--open-jimaku" } return { "--open-jimaku" }
elseif action_id == "openTsukihime" or action_id == "openAnimetosho" then elseif action_id == "openTsukihime" or action_id == "openAnimetosho" then
@@ -259,7 +259,7 @@ function M.create(ctx)
elseif action_id == "openYoutubePicker" then elseif action_id == "openYoutubePicker" then
return { "--open-youtube-picker" } return { "--open-youtube-picker" }
elseif action_id == "openSessionHelp" then elseif action_id == "openSessionHelp" then
return { "--open-session-help" } return { "--session-action", '{"actionId":"openSessionHelp"}' }
elseif action_id == "openCharacterDictionaryManager" then elseif action_id == "openCharacterDictionaryManager" then
return { "--session-action", '{"actionId":"openCharacterDictionaryManager"}' } return { "--session-action", '{"actionId":"openCharacterDictionaryManager"}' }
elseif action_id == "openControllerSelect" then elseif action_id == "openControllerSelect" then
+1
View File
@@ -26,6 +26,7 @@ function M.new()
auto_play_ready_initial_pause_ownership_consumed = false, auto_play_ready_initial_pause_ownership_consumed = false,
overlay_loading_osd_active = false, overlay_loading_osd_active = false,
overlay_loading_osd_timer = nil, overlay_loading_osd_timer = nil,
overlay_loading_osd_deadline = nil,
overlay_loading_osd_frame = 1, overlay_loading_osd_frame = 1,
pending_visible_overlay_hide_timer = nil, pending_visible_overlay_hide_timer = nil,
pending_visible_overlay_hide_generation = 0, pending_visible_overlay_hide_generation = 0,
+13 -1
View File
@@ -4,6 +4,7 @@ function M.create(ctx)
local mp = ctx.mp local mp = ctx.mp
local input = ctx.input local input = ctx.input
local process = ctx.process local process = ctx.process
local state = ctx.state
local subminer_log = ctx.log.subminer_log local subminer_log = ctx.log.subminer_log
local show_osd = ctx.log.show_osd local show_osd = ctx.log.show_osd
@@ -93,7 +94,18 @@ function M.create(ctx)
if not ensure_binary_for_menu() then if not ensure_binary_for_menu() then
return return
end end
process.run_control_command_async("open-session-help") process.run_binary_command_async({
state.binary_path,
"--session-action",
'{"actionId":"openSessionHelp"}',
}, function(ok, result, error)
if ok then
return
end
local reason = error or (result and result.stderr) or "unknown error"
subminer_log("warn", "session-bindings", "Session action failed: " .. tostring(reason))
show_osd("Session action failed")
end)
end) end)
end end
+38 -66
View File
@@ -1,80 +1,52 @@
> This is a prerelease build for testing. Stable changelog and docs-site updates remain pending until the final stable release. > This is a prerelease build for testing. Stable changelog and docs-site updates remain pending until the final stable release.
<!-- prerelease-base-version: 0.19.0 --> <!-- prerelease-base-version: 0.19.4 -->
## Highlights ## Highlights
### Added ### Added
- **Library Merge and Move**
- **Sync Stats & History** - Duplicate library cards for the same show can now be combined: select cards in the library grid, choose "Merge Selected," and pick which entry to keep. Sessions, mined cards, and watch time move over, and future episodes stay matched to the merged card.
- New **Sync Stats & History** window (tray menu) and `subminer sync <host>` command keep mining stats and watch history in sync between machines over SSH, with saved devices, per-host sync direction, and live stage-by-stage progress. - Episodes can be reassigned to a different library entry with a "→" button on the episode row, fixing cases where a file lands under the wrong title. Manual assignments survive later filename parsing, Jellyfin refreshes, and season repair.
- Merges are safe to repeat: data combines without duplicates, and hosts with auto-sync enabled sync automatically in the background on a schedule, reporting results as overlay notifications. - Exact AniList matches with compatible seasons now merge automatically, while fuzzy matches show up as a dismissible "Possible duplicate" prompt instead of merging without confirmation.
- Manual snapshot tools (create, merge, reveal, delete) and connection testing cover one-off transfers; Windows machines running the built-in OpenSSH Server work as sync remotes too, with no setup needed beyond SSH access. Power users can script transfers directly with `--push`/`--pull`, `--check`, `--snapshot`/`--merge`, and `--json` flags.
- **TsukiHime Subtitle Downloads**
- Download Japanese and secondary-language subtitles for the current video directly from TsukiHime, mirroring the existing Jimaku flow.
- Press `Ctrl+Shift+T` to search by tabs for the primary and secondary languages; the matching release is found automatically from the video filename and loads straight into mpv, no API key required.
- **Post-Playback History Menu**
- After a watch-history episode ends or mpv closes, the fzf/rofi launcher returns to that series with options to play the previous or next episode, rewatch, pick another episode, or quit SubMiner.
- Previous/Next continue across season directories, so you can binge a show without manually browsing folders.
- The menu shown right after picking a series from `subminer -H` now offers the previous episode too, matching the post-playback menu.
- **Known-Word Highlighting by Anki Maturity**
- Subtitle highlights for known words can now be colored by Anki card maturity (new, learning, young, mature), similar to asbplayer. Enable it with `ankiConnect.knownWords.maturityEnabled`, or toggle it live during a session.
- The mature-interval threshold and the four tier colors are configurable, and the in-session help legend shows the active tier colors while maturity highlighting is on.
- Tiers follow Anki's own card state: a lapsed card correctly shows as learning rather than young, and a note is treated as mature if any of its cards are mature. Stats and other known-word tools stay accurate with this new data.
- **Stats Library Entry Deletion**
- Added a "Delete Entry" action in the stats Library detail view that removes an entire title in one step: every episode, session, subtitle line, rollup, cover, and vocabulary count derived from it. Previously a mistaken entry had to be cleared episode by episode and still lingered in the Library.
- Delete progress (session, session group, episode, or full entry) now shows app-wide as a progress bar plus a status toast, staying visible across tabs and windows instead of disappearing when you switch away.
- Deletes are dramatically faster on large libraries, and opening the Vocabulary tab no longer stalls; the first launch after upgrading migrates the stats database in place to support this.
### Changed
- **Clipboard-Video Shortcut**
- The "append clipboard video to queue" shortcut is now configurable via `shortcuts.appendClipboardVideoToQueue` instead of being fixed.
### Fixed ### Fixed
- **Anki Audio Generation on Network Drives**
- Fixed sentence-audio generation timing out on slow network-mounted video files with many subtitle and font-attachment streams.
- Extraction now uses bounded probing and a two-minute budget, and failures show a clear error instead of a cryptic one.
- **Duplicate Subtitle Line Stats**
- Fixed karaoke openings and animated signs (which record one subtitle event per animation frame) inflating word and kanji counts and skewing "Top Repeated Words." Ordinary repeated dialogue and rewatches are unaffected.
- Already-inflated stats can be cleaned up with the new "Duplicates" button in the Vocabulary tab, or `subminer stats cleanup --duplicate-lines` (supports `--dry-run` and `--lookback-days`). Only the affected subtitle lines and vocabulary counts are touched; watch time and lines-seen totals are untouched.
- **Overlay Modals on macOS and Windows**
- Fixed overlay modals and the stats window opening on the wrong macOS Space, or forcing a Space switch, when mpv is fullscreen. They now open above fullscreen mpv on its current Space.
- Modals are now prewarmed on macOS and Windows so shortcuts open them promptly, and Windows keeps the hidden modal responsive between sessions.
- **Wayland File Drag-and-Drop**
- Fixed dragging subtitle and video files from file managers like Thunar onto the overlay on native Wayland; dropped files are now resolved and sent to mpv.
- **Windows Mouse Lag**
- Fixed system-wide mouse lag while SubMiner is running on Windows, caused by a global mouse hook and blocking window lookups during click-through tracking.
- **Mining Clip Accuracy**
- Fixed mined audio and animated image clips sometimes capturing the wrong subtitle line when audio extraction was slow. The clip range is now locked in at the moment of lookup, so audio and image clips always match.
- **Linux Notifications**
- Character dictionary progress notifications on Linux now update in place instead of flickering off and back on with every status change.
- **Stats Delete Performance**
- Fixed stats deletes freezing the dashboard; deletes now reliably run off the main thread, with automatic retry if the delete worker crashes.
- Deletes, library merges/moves, and AniList reassignments are now much faster because totals are updated incrementally instead of rebuilt from scratch, and no longer erase lifetime totals older than the recent session history.
- Session deletes on large libraries dropped from minutes to milliseconds.
- **Word Highlighting Accuracy** ### Docs
- Fixed several incorrect word highlighting and annotation cases: inconsistent part-of-speech exclusions on merged quote-particle tokens, missing annotations for rare kanji, katakana punctuation wrongly treated as non-kana noise, and certain kanji vocabulary skipped for next-level ("N+1") highlighting. - **Feature Demos Page**
- Hidden the unfinished feature demos page from the documentation sidebar; it's still reachable by direct URL.
- **AniList Season Resolution**
- Season 2 and later episodes now resolve to the correct AniList entry by walking sequel relations instead of guessing from the title, so watch progress, the character dictionary, and cover art for later seasons no longer silently fall back to season 1.
- Manual AniList overrides now stay in effect for every episode in the same season (by folder and detected season), and setting an override now fixes both the character dictionary and AniList watch progress together instead of needing separate corrections.
- **Startup Playback Pausing Too Early**
- Fixed playback resuming before subtitle processing finished warming up, which could briefly show untranslated subtitles right after opening a video.
- Most noticeable when resuming mid-episode or when a subtitle cue starts within the first couple of seconds.
- **Linux AppImage Crash Notification on Quit**
- Fixed a spurious "Service Crash" desktop notification appearing after closing a video when running the Linux AppImage.
- If needed, the mount-keepalive behavior behind this fix can be disabled with `SUBMINER_NO_APPIMAGE_MOUNT_KEEPALIVE=1`.
- **AnkiConnect Proxy Port Conflict**
- Fixed video playback failing to start when another process already held the configured AnkiConnect proxy port; SubMiner now shows a notification explaining how to resolve the conflict instead of crashing.
- **Stats & Settings Reliability**
- Fixed session stats reporting zero known words after the known-word cache gained maturity tiers.
- Hardened the stats server against malformed requests, stalled AniList lookups, media mismatches during word mining, and missing Yomitan connections.
- AnkiConnect settings validation now preserves valid custom configurations while safely falling back on invalid values instead of failing.
- **Stats Library Cover After Relink**
- Relinking a title to a different AniList entry now updates its cover art in the stats Library grid, not just the detail view, so unrelated titles no longer end up sharing the wrong cover.
- **Rofi Menu Prompt Spacing**
- Rofi menu prompts now keep a space between the prompt label and the input field instead of crowding the search placeholder text.
## What's Changed ## What's Changed
- feat(shortcuts): make clipboard-video-append shortcut configurable by @ksyasuda in #158 - feat(stats): add library entry merge and episode move by @ksyasuda in #190
- refactor(tokenizer): extract subtitle annotation filter into rule table by @ksyasuda in #162 - fix(stats): stop counting duplicate typeset subtitle lines by @ksyasuda in #191
- refactor(tsukihime): swap Animetosho backend for TsukiHime API by @ksyasuda in #165 - fix(media): tolerate slow MKV audio extraction by @ksyasuda in #195
- refactor: split anki-connect and stats-server resolvers into modules by @ksyasuda in #169 - fix(stats): subtract lifetime totals incrementally on delete by @ksyasuda in #196
- feat(launcher): add post-playback history menu with previous episode by @ksyasuda in #170 - fix(anki): snapshot mining media clip timing by @ksyasuda in #197
- Anki maturity-based known-word highlighting by @ksyasuda in #172 - fix(notifications): replace Linux progress updates in place by @ksyasuda in #198
- fix(anilist): resolve later seasons via sequel relations, not title guessing by @ksyasuda in #173 - fix(overlay): support native Wayland file drag-and-drop by @ksyasuda in #199
- feat(stats): add library entry deletion and app-wide delete progress by @ksyasuda in #174 - fix(overlay): keep macOS modal windows on fullscreen Spaces by @ksyasuda in #200
- fix(overlay): prevent Windows mouse lag during click-through tracking by @ksyasuda in #201
## Installation ## Installation
+13
View File
@@ -35,6 +35,17 @@ const archiveCacheRoot = join(repoRoot, '.tmp/docs-versioned-archive-cache');
const maxCloudflareFiles = 20_000; const maxCloudflareFiles = 20_000;
const maxCloudflareFileBytes = 25 * 1024 * 1024; const maxCloudflareFileBytes = 25 * 1024 * 1024;
// Cloudflare Pages header rules for the whole deployment. Mirrors the `noindex,follow`
// meta tag the non-root channels emit, so the duplicate trees stay out of the index
// even for responses a crawler takes without parsing the HTML.
const deployHeaders = `# Generated by scripts/build-versioned-docs.ts. Do not edit by hand.
/main/*
X-Robots-Tag: noindex, follow
/v/*
X-Robots-Tag: noindex, follow
`;
function run( function run(
command: string, command: string,
args: string[], args: string[],
@@ -173,6 +184,7 @@ function buildDocs(options: {
SUBMINER_DOCS_BASE: options.base, SUBMINER_DOCS_BASE: options.base,
SUBMINER_DOCS_OUT_DIR: options.outDir, SUBMINER_DOCS_OUT_DIR: options.outDir,
SUBMINER_DOCS_SOURCE_DIR: options.snapshotDocsSite, SUBMINER_DOCS_SOURCE_DIR: options.snapshotDocsSite,
SUBMINER_DOCS_REPO_DIR: currentDocsSite,
SUBMINER_DOCS_CHANNEL: options.channel, SUBMINER_DOCS_CHANNEL: options.channel,
SUBMINER_DOCS_VERSION: options.version ?? '', SUBMINER_DOCS_VERSION: options.version ?? '',
SUBMINER_DOCS_LATEST_STABLE: options.latestStable, SUBMINER_DOCS_LATEST_STABLE: options.latestStable,
@@ -378,6 +390,7 @@ function main() {
}); });
writeFileSync(join(aggregateOutDir, 'versions.json'), `${JSON.stringify(manifest, null, 2)}\n`); writeFileSync(join(aggregateOutDir, 'versions.json'), `${JSON.stringify(manifest, null, 2)}\n`);
writeFileSync(join(aggregateOutDir, '_headers'), deployHeaders);
assertCloudflarePagesLimits(aggregateOutDir); assertCloudflarePagesLimits(aggregateOutDir);
const prunedArchives = pruneArchiveCacheGenerations({ const prunedArchives = pruneArchiveCacheGenerations({
cacheRoot: archiveCacheRoot, cacheRoot: archiveCacheRoot,
+53 -1
View File
@@ -130,7 +130,9 @@ local function run_plugin_scenario(config)
function mp.add_timeout(seconds, callback) function mp.add_timeout(seconds, callback)
recorded.timeouts[#recorded.timeouts + 1] = seconds recorded.timeouts[#recorded.timeouts + 1] = seconds
local delay = tonumber(seconds) or 0
local timeout = { local timeout = {
seconds = delay,
killed = false, killed = false,
callback = callback, callback = callback,
} }
@@ -138,7 +140,6 @@ local function run_plugin_scenario(config)
self.killed = true self.killed = true
end end
local delay = tonumber(seconds) or 0
if callback and delay < 5 and not config.defer_timeouts then if callback and delay < 5 and not config.defer_timeouts then
callback() callback()
end end
@@ -514,6 +515,15 @@ local function has_timeout(timeouts, target)
return false return false
end end
local function find_timeout_handle(recorded, target)
for _, timeout in ipairs(recorded.timeout_handles) do
if math.abs(timeout.seconds - target) < 0.0001 then
return timeout
end
end
return nil
end
local function env_has(call, target) local function env_has(call, target)
local env = (call and call.env) or {} local env = (call and call.env) or {}
for _, value in ipairs(env) do for _, value in ipairs(env) do
@@ -1636,6 +1646,8 @@ do
#recorded.periodic_timers == 1, #recorded.periodic_timers == 1,
"auto-start visible overlay should refresh the early overlay loading OSD" "auto-start visible overlay should refresh the early overlay loading OSD"
) )
local overlay_loading_deadline = find_timeout_handle(recorded, 30)
assert_true(overlay_loading_deadline ~= nil, "overlay loading OSD should have a bounded deadline")
local overlay_loading_timer = recorded.periodic_timers[1] local overlay_loading_timer = recorded.periodic_timers[1]
recorded.periodic_timers[1].callback() recorded.periodic_timers[1].callback()
assert_true( assert_true(
@@ -1670,6 +1682,46 @@ do
recorded.periodic_timers[1].killed == true, recorded.periodic_timers[1].killed == true,
"overlay loading ready should stop the early overlay loading OSD refresher" "overlay loading ready should stop the early overlay loading OSD refresher"
) )
assert_true(
overlay_loading_deadline.killed == true,
"overlay loading ready should cancel the bounded loading deadline"
)
end
do
local recorded, err = run_plugin_scenario({
defer_timeouts = true,
process_list = "",
option_overrides = {
binary_path = binary_path,
auto_start = "yes",
auto_start_visible_overlay = "yes",
osd_messages = false,
socket_path = "/tmp/subminer-socket",
},
input_ipc_server = "/tmp/subminer-socket",
media_title = "Random Movie",
files = {
[binary_path] = true,
},
})
assert_true(recorded ~= nil, "plugin failed to load for overlay loading deadline scenario: " .. tostring(err))
fire_event(recorded, "start-file")
local overlay_loading_deadline = find_timeout_handle(recorded, 30)
assert_true(overlay_loading_deadline ~= nil, "overlay loading deadline should be scheduled")
overlay_loading_deadline.callback()
assert_true(
recorded.periodic_timers[1].killed == true,
"overlay loading deadline should stop the loading spinner"
)
assert_true(
has_osd_message(recorded.osd, "SubMiner: Overlay did not become ready; check SubMiner logs"),
"overlay loading deadline should replace the spinner with actionable feedback"
)
assert_true(
has_log_containing(recorded.logs, "Overlay loading deadline expired"),
"overlay loading deadline should leave a diagnostic log entry"
)
end end
do do
+2 -38
View File
@@ -28,8 +28,6 @@ import {
KikuMergePreviewResponse, KikuMergePreviewResponse,
NotificationOptions, NotificationOptions,
type WordCardKind, type WordCardKind,
type MediaTimingReviewDecision,
type MediaTimingReviewRequest,
} from './types/anki'; } from './types/anki';
import { AiConfig } from './types/integrations'; import { AiConfig } from './types/integrations';
import type { KnownWordMaturityTier } from './types/subtitle'; import type { KnownWordMaturityTier } from './types/subtitle';
@@ -240,9 +238,6 @@ export class AnkiIntegration {
private recordCardsMinedCallback: ((count: number, noteIds?: number[]) => void) | null = null; private recordCardsMinedCallback: ((count: number, noteIds?: number[]) => void) | null = null;
private knownWordCacheUpdatedCallback: (() => void) | null = null; private knownWordCacheUpdatedCallback: (() => void) | null = null;
private consumeSubtitleMiningContextCallback: (() => SubtitleMiningContext | null) | null = null; private consumeSubtitleMiningContextCallback: (() => SubtitleMiningContext | null) | null = null;
private mediaTimingReviewCallback:
| ((request: MediaTimingReviewRequest) => Promise<MediaTimingReviewDecision>)
| null = null;
private noteIdRedirects = new Map<number, number>(); private noteIdRedirects = new Map<number, number>();
private trackedDuplicateNoteIds = new Map<number, number[]>(); private trackedDuplicateNoteIds = new Map<number, number[]>();
private getCachedMediaPath: MediaGenerationInputResolverOptions['getCachedMediaPath'] | null = private getCachedMediaPath: MediaGenerationInputResolverOptions['getCachedMediaPath'] | null =
@@ -514,7 +509,6 @@ export class AnkiIntegration {
findNotes: async (query, options) => findNotes: async (query, options) =>
(await this.client.findNotes(query, options)) as number[], (await this.client.findNotes(query, options)) as number[],
retrieveMediaFile: (filename) => this.client.retrieveMediaFile(filename), retrieveMediaFile: (filename) => this.client.retrieveMediaFile(filename),
deleteNotes: (noteIds) => this.client.deleteNotes(noteIds),
}, },
mediaGenerator: { mediaGenerator: {
generateAudio: ( generateAudio: (
@@ -572,7 +566,6 @@ export class AnkiIntegration {
getEffectiveSentenceCardConfig: () => this.getEffectiveSentenceCardConfig(), getEffectiveSentenceCardConfig: () => this.getEffectiveSentenceCardConfig(),
getFallbackDurationSeconds: () => this.getFallbackDurationSeconds(), getFallbackDurationSeconds: () => this.getFallbackDurationSeconds(),
appendKnownWordsFromNoteInfo: (noteInfo) => this.appendKnownWordsFromNoteInfo(noteInfo), appendKnownWordsFromNoteInfo: (noteInfo) => this.appendKnownWordsFromNoteInfo(noteInfo),
removeKnownWordNote: (noteId) => this.removeKnownWordNote(noteId),
isUpdateInProgress: () => this.updateInProgress, isUpdateInProgress: () => this.updateInProgress,
setUpdateInProgress: (value) => { setUpdateInProgress: (value) => {
this.updateInProgress = value; this.updateInProgress = value;
@@ -588,7 +581,6 @@ export class AnkiIntegration {
recordCardsMinedCallback: (count, noteIds) => { recordCardsMinedCallback: (count, noteIds) => {
this.recordCardsMinedSafely(count, noteIds, 'card creation'); this.recordCardsMinedSafely(count, noteIds, 'card creation');
}, },
reviewMediaTiming: (request) => this.reviewMediaTiming(request),
}); });
} }
@@ -645,14 +637,12 @@ export class AnkiIntegration {
notesInfo: async (noteIds) => (await this.client.notesInfo(noteIds)) as unknown, notesInfo: async (noteIds) => (await this.client.notesInfo(noteIds)) as unknown,
updateNoteFields: (noteId, fields) => this.client.updateNoteFields(noteId, fields), updateNoteFields: (noteId, fields) => this.client.updateNoteFields(noteId, fields),
storeMediaFile: (filename, data) => this.client.storeMediaFile(filename, data), storeMediaFile: (filename, data) => this.client.storeMediaFile(filename, data),
deleteNotes: (noteIds) => this.client.deleteNotes(noteIds),
}, },
getConfig: () => this.config, getConfig: () => this.config,
getCurrentSubtitleText: () => this.mpvClient.currentSubText, getCurrentSubtitleText: () => this.mpvClient.currentSubText,
getCurrentSubtitleStart: () => this.mpvClient.currentSubStart, getCurrentSubtitleStart: () => this.mpvClient.currentSubStart,
getEffectiveSentenceCardConfig: () => this.getEffectiveSentenceCardConfig(), getEffectiveSentenceCardConfig: () => this.getEffectiveSentenceCardConfig(),
appendKnownWordsFromNoteInfo: (noteInfo) => this.appendKnownWordsFromNoteInfo(noteInfo), appendKnownWordsFromNoteInfo: (noteInfo) => this.appendKnownWordsFromNoteInfo(noteInfo),
removeKnownWordNote: (noteId) => this.removeKnownWordNote(noteId),
extractFields: (fields) => this.extractFields(fields), extractFields: (fields) => this.extractFields(fields),
findDuplicateNote: (expression, excludeNoteId, noteInfo) => findDuplicateNote: (expression, excludeNoteId, noteInfo) =>
this.findDuplicateNote(expression, excludeNoteId, noteInfo), this.findDuplicateNote(expression, excludeNoteId, noteInfo),
@@ -690,7 +680,6 @@ export class AnkiIntegration {
logWarn: (...args) => log.warn(args[0] as string, ...args.slice(1)), logWarn: (...args) => log.warn(args[0] as string, ...args.slice(1)),
logInfo: (...args) => log.info(args[0] as string, ...args.slice(1)), logInfo: (...args) => log.info(args[0] as string, ...args.slice(1)),
logError: (...args) => log.error(args[0] as string, ...args.slice(1)), logError: (...args) => log.error(args[0] as string, ...args.slice(1)),
reviewMediaTiming: (request) => this.reviewMediaTiming(request),
}); });
} }
@@ -810,12 +799,6 @@ export class AnkiIntegration {
} }
} }
private removeKnownWordNote(noteId: number): void {
if (this.knownWordCache.removeNote(noteId)) {
this.notifyKnownWordCacheUpdated();
}
}
private notifyKnownWordCacheUpdated(): void { private notifyKnownWordCacheUpdated(): void {
if (!this.knownWordCacheUpdatedCallback) { if (!this.knownWordCacheUpdatedCallback) {
return; return;
@@ -1056,7 +1039,7 @@ export class AnkiIntegration {
videoPath, videoPath,
startTime, startTime,
endTime, endTime,
context?.mediaPaddingSeconds ?? this.config.media?.audioPadding, this.config.media?.audioPadding,
resolveAudioStreamIndexForMediaGeneration(videoPath, this.mpvClient.currentAudioStreamIndex), resolveAudioStreamIndexForMediaGeneration(videoPath, this.mpvClient.currentAudioStreamIndex),
this.config.media?.normalizeAudio !== false, this.config.media?.normalizeAudio !== false,
await this.getMpvVolumeScale(), await this.getMpvVolumeScale(),
@@ -1089,7 +1072,7 @@ export class AnkiIntegration {
videoPath, videoPath,
mediaRange.startTime, mediaRange.startTime,
mediaRange.endTime, mediaRange.endTime,
context?.mediaPaddingSeconds ?? this.config.media?.audioPadding, this.config.media?.audioPadding,
{ {
fps: this.config.media?.animatedFps, fps: this.config.media?.animatedFps,
maxWidth: this.config.media?.animatedMaxWidth, maxWidth: this.config.media?.animatedMaxWidth,
@@ -1740,25 +1723,6 @@ export class AnkiIntegration {
this.consumeSubtitleMiningContextCallback = callback; this.consumeSubtitleMiningContextCallback = callback;
} }
setMediaTimingReviewCallback(
callback: ((request: MediaTimingReviewRequest) => Promise<MediaTimingReviewDecision>) | null,
): void {
this.mediaTimingReviewCallback = callback;
}
private async reviewMediaTiming(
request: Omit<MediaTimingReviewRequest, 'audioPadding' | 'maxMediaDuration'>,
): Promise<MediaTimingReviewDecision> {
if (this.config.media?.reviewTiming !== true || !this.mediaTimingReviewCallback) {
return { action: 'use-original' };
}
return await this.mediaTimingReviewCallback({
...request,
audioPadding: Math.max(0, this.config.media.audioPadding ?? 0),
maxMediaDuration: Math.max(0, this.config.media.maxMediaDuration ?? 30),
});
}
resolveCurrentNoteId(noteId: number): number { resolveCurrentNoteId(noteId: number): number {
let resolved = noteId; let resolved = noteId;
const seen = new Set<number>(); const seen = new Set<number>();
@@ -85,7 +85,6 @@ function createManualUpdateService(overrides: Partial<CardCreationDeps> = {}): {
}, },
findNotes: async () => [42], findNotes: async () => [42],
retrieveMediaFile: async () => '', retrieveMediaFile: async () => '',
deleteNotes: async () => undefined,
}, },
mediaGenerator: { mediaGenerator: {
generateAudio: async () => Buffer.from('audio'), generateAudio: async () => Buffer.from('audio'),
@@ -130,7 +129,6 @@ function createManualUpdateService(overrides: Partial<CardCreationDeps> = {}): {
}), }),
getFallbackDurationSeconds: () => 10, getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined, appendKnownWordsFromNoteInfo: () => undefined,
removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false, isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined, setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined, trackLastAddedNoteId: () => undefined,
@@ -203,7 +201,6 @@ test('manual clipboard subtitle update marks Kiku word cards as word-and-sentenc
storeMediaFile: async () => undefined, storeMediaFile: async () => undefined,
findNotes: async () => [42], findNotes: async () => [42],
retrieveMediaFile: async () => '', retrieveMediaFile: async () => '',
deleteNotes: async () => undefined,
}, },
getEffectiveSentenceCardConfig: () => ({ getEffectiveSentenceCardConfig: () => ({
model: 'Sentence', model: 'Sentence',
@@ -251,7 +248,6 @@ test('manual clipboard subtitle update skips audio when sentence audio field is
}, },
findNotes: async () => [42], findNotes: async () => [42],
retrieveMediaFile: async () => '', retrieveMediaFile: async () => '',
deleteNotes: async () => undefined,
}, },
}); });
@@ -339,7 +335,6 @@ test('manual clipboard subtitle update uses resolved mpv stream URLs for remote
}, },
findNotes: async () => [42], findNotes: async () => [42],
retrieveMediaFile: async () => '', retrieveMediaFile: async () => '',
deleteNotes: async () => undefined,
}, },
mediaGenerator: { mediaGenerator: {
generateAudio: async (path) => { generateAudio: async (path) => {
@@ -388,98 +383,3 @@ test('createSentenceCard relies on Anki progress notification without standalone
assert.deepEqual(progressMessages, ['Creating sentence card']); assert.deepEqual(progressMessages, ['Creating sentence card']);
assert.deepEqual(statusMessages, []); assert.deepEqual(statusMessages, []);
}); });
test('discarding an audio-card timing review deletes the note before evicting its cache entry', async () => {
const events: string[] = [];
const statusMessages: string[] = [];
const { service } = createManualUpdateService({
getMpvClient: () =>
({
currentVideoPath: '/video.mp4',
currentSubText: '字幕',
currentSubStart: 4,
currentSubEnd: 6,
currentTimePos: 5,
}) as never,
client: {
addNote: async () => 0,
addTags: async () => undefined,
notesInfo: async () => [
{
noteId: 42,
fields: { Expression: { value: '単語' } },
},
],
updateNoteFields: async () => undefined,
storeMediaFile: async () => undefined,
findNotes: async () => [42],
retrieveMediaFile: async () => '',
deleteNotes: async (noteIds) => {
events.push(`delete:${noteIds.join(',')}`);
},
},
reviewMediaTiming: async () => ({ action: 'discard' }),
removeKnownWordNote: (noteId) => {
events.push(`cache:${noteId}`);
},
showStatusNotification: (message) => {
statusMessages.push(message);
},
});
await service.markLastCardAsAudioCard();
assert.deepEqual(events, ['delete:42', 'cache:42']);
assert.deepEqual(statusMessages, ['Card deleted.']);
});
test('keeping an audio card without media skips generation and preserves the note', async () => {
let generatedAudio = false;
let deleted = false;
const updates: Array<{ noteId: number; fields: Record<string, string> }> = [];
const { service, storedMedia } = createManualUpdateService({
getMpvClient: () =>
({
currentVideoPath: '/video.mp4',
currentSubText: '字幕',
currentSubStart: 4,
currentSubEnd: 6,
currentTimePos: 5,
}) as never,
client: {
addNote: async () => 0,
addTags: async () => undefined,
notesInfo: async () => [
{
noteId: 42,
fields: { Expression: { value: '単語' }, Sentence: { value: '' } },
},
],
updateNoteFields: async (noteId, fields) => {
updates.push({ noteId, fields });
},
storeMediaFile: async () => undefined,
findNotes: async () => [42],
retrieveMediaFile: async () => '',
deleteNotes: async () => {
deleted = true;
},
},
mediaGenerator: {
generateAudio: async () => {
generatedAudio = true;
return Buffer.from('audio');
},
generateScreenshot: async () => null,
generateAnimatedImage: async () => null,
},
reviewMediaTiming: async () => ({ action: 'skip-media' }),
});
await service.markLastCardAsAudioCard();
assert.equal(generatedAudio, false);
assert.equal(deleted, false);
assert.deepEqual(storedMedia, []);
assert.deepEqual(updates, [{ noteId: 42, fields: { Sentence: '字幕' } }]);
});
@@ -12,7 +12,6 @@ test('sentence card writes generated audio only to sentence audio field', async
const storedMedia: string[] = []; const storedMedia: string[] = [];
const requestedProperties: string[] = []; const requestedProperties: string[] = [];
const audioVolumeScales: Array<number | undefined> = []; const audioVolumeScales: Array<number | undefined> = [];
const audioRanges: Array<{ start: number; end: number; padding: number | undefined }> = [];
const deps: CardCreationDeps = { const deps: CardCreationDeps = {
getConfig: () => getConfig: () =>
@@ -74,19 +73,17 @@ test('sentence card writes generated audio only to sentence audio field', async
}, },
findNotes: async () => [], findNotes: async () => [],
retrieveMediaFile: async () => '', retrieveMediaFile: async () => '',
deleteNotes: async () => undefined,
}, },
mediaGenerator: { mediaGenerator: {
generateAudio: async ( generateAudio: async (
_path, _path,
startTime, _startTime,
endTime, _endTime,
audioPadding, _audioPadding,
_audioStreamIndex, _audioStreamIndex,
_normalizeAudio, _normalizeAudio,
volumeScale, volumeScale,
) => { ) => {
audioRanges.push({ start: startTime, end: endTime, padding: audioPadding });
audioVolumeScales.push(volumeScale); audioVolumeScales.push(volumeScale);
return Buffer.from('audio'); return Buffer.from('audio');
}, },
@@ -125,15 +122,17 @@ test('sentence card writes generated audio only to sentence audio field', async
}), }),
getFallbackDurationSeconds: () => 10, getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined, appendKnownWordsFromNoteInfo: () => undefined,
removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false, isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined, setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined, trackLastAddedNoteId: () => undefined,
reviewMediaTiming: async () => ({ action: 'confirm', startTime: 11.4, endTime: 14.2 }),
}; };
const service = new CardCreationService(deps); const created = await new CardCreationService(deps).createSentenceCard(
const created = await service.createSentenceCard('字幕', 12, 14, 'Subtitle'); '字幕',
12,
14,
'Subtitle',
);
assert.equal(created, true); assert.equal(created, true);
assert.deepEqual(addedFields[0], { assert.deepEqual(addedFields[0], {
@@ -145,19 +144,7 @@ test('sentence card writes generated audio only to sentence audio field', async
assert.equal(storedMedia.length, 1); assert.equal(storedMedia.length, 1);
assert.deepEqual(requestedProperties, ['volume']); assert.deepEqual(requestedProperties, ['volume']);
assert.deepEqual(audioVolumeScales, [0.4 ** 3]); assert.deepEqual(audioVolumeScales, [0.4 ** 3]);
assert.deepEqual(audioRanges, [{ start: 11.4, end: 14.2, padding: 0 }]);
const mediaUpdate = updatedFields.find((fields) => 'SentenceAudio' in fields); const mediaUpdate = updatedFields.find((fields) => 'SentenceAudio' in fields);
assert.equal(mediaUpdate?.SentenceAudio, `[sound:${storedMedia[0]}]`); assert.equal(mediaUpdate?.SentenceAudio, `[sound:${storedMedia[0]}]`);
assert.equal('ExpressionAudio' in mediaUpdate!, false); assert.equal('ExpressionAudio' in mediaUpdate!, false);
deps.reviewMediaTiming = async () => ({ action: 'discard' });
assert.equal(await service.createSentenceCard('作らない', 20, 22), false);
assert.equal(addedFields.length, 1);
deps.reviewMediaTiming = async () => ({ action: 'skip-media' });
assert.equal(await service.createSentenceCard('メディアなし', 30, 32), true);
assert.equal(addedFields.length, 2);
assert.equal(storedMedia.length, 1);
assert.deepEqual(audioRanges, [{ start: 11.4, end: 14.2, padding: 0 }]);
assert.deepEqual(requestedProperties, ['volume']);
}); });
@@ -42,7 +42,6 @@ test('CardCreationService counts locally created sentence cards', async () => {
storeMediaFile: async () => undefined, storeMediaFile: async () => undefined,
findNotes: async () => [], findNotes: async () => [],
retrieveMediaFile: async () => '', retrieveMediaFile: async () => '',
deleteNotes: async () => undefined,
}, },
mediaGenerator: { mediaGenerator: {
generateAudio: async () => null, generateAudio: async () => null,
@@ -75,7 +74,6 @@ test('CardCreationService counts locally created sentence cards', async () => {
}), }),
getFallbackDurationSeconds: () => 10, getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined, appendKnownWordsFromNoteInfo: () => undefined,
removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false, isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined, setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined, trackLastAddedNoteId: () => undefined,
@@ -141,7 +139,6 @@ test('CardCreationService keeps updating after trackLastAddedNoteId throws', asy
storeMediaFile: async () => undefined, storeMediaFile: async () => undefined,
findNotes: async () => [], findNotes: async () => [],
retrieveMediaFile: async () => '', retrieveMediaFile: async () => '',
deleteNotes: async () => undefined,
}, },
mediaGenerator: { mediaGenerator: {
generateAudio: async () => null, generateAudio: async () => null,
@@ -176,7 +173,6 @@ test('CardCreationService keeps updating after trackLastAddedNoteId throws', asy
}), }),
getFallbackDurationSeconds: () => 10, getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined, appendKnownWordsFromNoteInfo: () => undefined,
removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false, isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined, setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => { trackLastAddedNoteId: () => {
@@ -242,7 +238,6 @@ test('CardCreationService keeps updating after recordCardsMinedCallback throws',
storeMediaFile: async () => undefined, storeMediaFile: async () => undefined,
findNotes: async () => [], findNotes: async () => [],
retrieveMediaFile: async () => '', retrieveMediaFile: async () => '',
deleteNotes: async () => undefined,
}, },
mediaGenerator: { mediaGenerator: {
generateAudio: async () => null, generateAudio: async () => null,
@@ -277,7 +272,6 @@ test('CardCreationService keeps updating after recordCardsMinedCallback throws',
}), }),
getFallbackDurationSeconds: () => 10, getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined, appendKnownWordsFromNoteInfo: () => undefined,
removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false, isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined, setUpdateInProgress: () => undefined,
recordCardsMinedCallback: () => { recordCardsMinedCallback: () => {
@@ -354,7 +348,6 @@ test('CardCreationService uses stream-open-filename for remote media generation'
storeMediaFile: async () => undefined, storeMediaFile: async () => undefined,
findNotes: async () => [], findNotes: async () => [],
retrieveMediaFile: async () => '', retrieveMediaFile: async () => '',
deleteNotes: async () => undefined,
}, },
mediaGenerator: { mediaGenerator: {
generateAudio: async (path) => { generateAudio: async (path) => {
@@ -399,7 +392,6 @@ test('CardCreationService uses stream-open-filename for remote media generation'
}), }),
getFallbackDurationSeconds: () => 10, getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined, appendKnownWordsFromNoteInfo: () => undefined,
removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false, isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined, setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined, trackLastAddedNoteId: () => undefined,
@@ -462,7 +454,6 @@ test('CardCreationService does not use mpv stream indexes for ready cached YouTu
storeMediaFile: async () => undefined, storeMediaFile: async () => undefined,
findNotes: async () => [], findNotes: async () => [],
retrieveMediaFile: async () => '', retrieveMediaFile: async () => '',
deleteNotes: async () => undefined,
}, },
mediaGenerator: { mediaGenerator: {
generateAudio: async (path, _startTime, _endTime, _padding, audioStreamIndex) => { generateAudio: async (path, _startTime, _endTime, _padding, audioStreamIndex) => {
@@ -504,7 +495,6 @@ test('CardCreationService does not use mpv stream indexes for ready cached YouTu
}), }),
getFallbackDurationSeconds: () => 10, getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined, appendKnownWordsFromNoteInfo: () => undefined,
removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false, isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined, setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined, trackLastAddedNoteId: () => undefined,
@@ -600,7 +590,6 @@ test('CardCreationService queues YouTube media when required cache is not ready'
storeMediaFile: async () => undefined, storeMediaFile: async () => undefined,
findNotes: async () => [], findNotes: async () => [],
retrieveMediaFile: async () => '', retrieveMediaFile: async () => '',
deleteNotes: async () => undefined,
}, },
mediaGenerator: { mediaGenerator: {
generateAudio: async () => { generateAudio: async () => {
@@ -645,7 +634,6 @@ test('CardCreationService queues YouTube media when required cache is not ready'
}), }),
getFallbackDurationSeconds: () => 10, getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined, appendKnownWordsFromNoteInfo: () => undefined,
removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false, isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined, setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined, trackLastAddedNoteId: () => undefined,
@@ -713,7 +701,6 @@ test('CardCreationService tracks pre-add duplicate note ids for kiku sentence ca
storeMediaFile: async () => undefined, storeMediaFile: async () => undefined,
findNotes: async () => [], findNotes: async () => [],
retrieveMediaFile: async () => '', retrieveMediaFile: async () => '',
deleteNotes: async () => undefined,
}, },
mediaGenerator: { mediaGenerator: {
generateAudio: async () => null, generateAudio: async () => null,
@@ -746,7 +733,6 @@ test('CardCreationService tracks pre-add duplicate note ids for kiku sentence ca
}), }),
getFallbackDurationSeconds: () => 10, getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined, appendKnownWordsFromNoteInfo: () => undefined,
removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false, isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined, setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined, trackLastAddedNoteId: () => undefined,
@@ -804,7 +790,6 @@ test('CardCreationService does not track duplicate ids when pre-add lookup retur
storeMediaFile: async () => undefined, storeMediaFile: async () => undefined,
findNotes: async () => [], findNotes: async () => [],
retrieveMediaFile: async () => '', retrieveMediaFile: async () => '',
deleteNotes: async () => undefined,
}, },
mediaGenerator: { mediaGenerator: {
generateAudio: async () => null, generateAudio: async () => null,
@@ -837,7 +822,6 @@ test('CardCreationService does not track duplicate ids when pre-add lookup retur
}), }),
getFallbackDurationSeconds: () => 10, getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined, appendKnownWordsFromNoteInfo: () => undefined,
removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false, isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined, setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined, trackLastAddedNoteId: () => undefined,
+23 -96
View File
@@ -3,13 +3,7 @@ import {
getConfiguredWordFieldName, getConfiguredWordFieldName,
getPreferredWordValueFromExtractedFields, getPreferredWordValueFromExtractedFields,
} from '../anki-field-config'; } from '../anki-field-config';
import { import { AnkiConnectConfig, type CardKind, type WordCardKind } from '../types/anki';
AnkiConnectConfig,
type CardKind,
type MediaTimingReviewDecision,
type MediaTimingReviewRequest,
type WordCardKind,
} from '../types/anki';
import { createLogger } from '../logger'; import { createLogger } from '../logger';
import type { MediaInput } from '../media-input'; import type { MediaInput } from '../media-input';
import { SubtitleTimingTracker } from '../subtitle-timing-tracker'; import { SubtitleTimingTracker } from '../subtitle-timing-tracker';
@@ -61,7 +55,6 @@ interface CardCreationClient {
storeMediaFile(filename: string, data: Buffer): Promise<void>; storeMediaFile(filename: string, data: Buffer): Promise<void>;
findNotes(query: string, options?: { maxRetries?: number }): Promise<number[]>; findNotes(query: string, options?: { maxRetries?: number }): Promise<number[]>;
retrieveMediaFile(filename: string): Promise<string>; retrieveMediaFile(filename: string): Promise<string>;
deleteNotes(noteIds: number[]): Promise<void>;
} }
interface CardCreationMediaGenerator { interface CardCreationMediaGenerator {
@@ -145,16 +138,12 @@ interface CardCreationDeps {
}; };
getFallbackDurationSeconds: () => number; getFallbackDurationSeconds: () => number;
appendKnownWordsFromNoteInfo: (noteInfo: CardCreationNoteInfo) => void; appendKnownWordsFromNoteInfo: (noteInfo: CardCreationNoteInfo) => void;
removeKnownWordNote: (noteId: number) => void;
isUpdateInProgress: () => boolean; isUpdateInProgress: () => boolean;
setUpdateInProgress: (value: boolean) => void; setUpdateInProgress: (value: boolean) => void;
trackLastAddedNoteId?: (noteId: number) => void; trackLastAddedNoteId?: (noteId: number) => void;
trackLastAddedDuplicateNoteIds?: (noteId: number, duplicateNoteIds: number[]) => void; trackLastAddedDuplicateNoteIds?: (noteId: number, duplicateNoteIds: number[]) => void;
findDuplicateNoteIds?: (expression: string, noteInfo: CardCreationNoteInfo) => Promise<number[]>; findDuplicateNoteIds?: (expression: string, noteInfo: CardCreationNoteInfo) => Promise<number[]>;
recordCardsMinedCallback?: (count: number, noteIds?: number[]) => void; recordCardsMinedCallback?: (count: number, noteIds?: number[]) => void;
reviewMediaTiming?: (
request: Omit<MediaTimingReviewRequest, 'audioPadding' | 'maxMediaDuration'>,
) => Promise<MediaTimingReviewDecision>;
} }
export class CardCreationService { export class CardCreationService {
@@ -271,7 +260,6 @@ export class CardCreationService {
fields, fields,
this.deps.getConfig(), this.deps.getConfig(),
); );
const sentenceAudioField = this.getResolvedSentenceOnlyAudioFieldName(noteInfo); const sentenceAudioField = this.getResolvedSentenceOnlyAudioFieldName(noteInfo);
const sentenceCardConfig = this.deps.getEffectiveSentenceCardConfig(); const sentenceCardConfig = this.deps.getEffectiveSentenceCardConfig();
const sentenceField = sentenceCardConfig.sentenceField; const sentenceField = sentenceCardConfig.sentenceField;
@@ -463,28 +451,6 @@ export class CardCreationService {
this.deps.getConfig(), this.deps.getConfig(),
); );
const timingDecision = this.deps.reviewMediaTiming
? await this.deps.reviewMediaTiming({
kind: 'audio',
text: mpvClient.currentSubText,
startTime,
endTime,
noteId,
})
: ({ action: 'use-original' } as const);
if (timingDecision.action === 'discard') {
await this.deps.client.deleteNotes([noteId]);
this.deps.removeKnownWordNote(noteId);
this.deps.showStatusNotification('Card deleted.');
return;
}
const skipMedia = timingDecision.action === 'skip-media';
const exactReviewedRange = timingDecision.action === 'confirm';
if (timingDecision.action === 'confirm') {
startTime = timingDecision.startTime;
endTime = timingDecision.endTime;
}
const updatedFields: Record<string, string> = {}; const updatedFields: Record<string, string> = {};
const errors: string[] = []; const errors: string[] = [];
let miscInfoFilename: string | null = null; let miscInfoFilename: string | null = null;
@@ -499,28 +465,25 @@ export class CardCreationService {
const sentenceCardConfig = this.deps.getEffectiveSentenceCardConfig(); const sentenceCardConfig = this.deps.getEffectiveSentenceCardConfig();
const audioFieldName = sentenceCardConfig.audioField; const audioFieldName = sentenceCardConfig.audioField;
if (!skipMedia) { try {
try { const audioFilename = this.generateAudioFilename();
const audioFilename = this.generateAudioFilename(); const audioBuffer = await this.mediaGenerateAudio(
const audioBuffer = await this.mediaGenerateAudio( mpvClient.currentVideoPath,
mpvClient.currentVideoPath, startTime,
startTime, endTime,
endTime, );
exactReviewedRange ? 0 : undefined,
);
if (audioBuffer) { if (audioBuffer) {
await this.deps.client.storeMediaFile(audioFilename, audioBuffer); await this.deps.client.storeMediaFile(audioFilename, audioBuffer);
updatedFields[audioFieldName] = `[sound:${audioFilename}]`; updatedFields[audioFieldName] = `[sound:${audioFilename}]`;
miscInfoFilename = audioFilename; miscInfoFilename = audioFilename;
}
} catch (error) {
log.error('Failed to generate audio for audio card:', (error as Error).message);
errors.push('audio');
} }
} catch (error) {
log.error('Failed to generate audio for audio card:', (error as Error).message);
errors.push('audio');
} }
if (!skipMedia && shouldGenerateImage(this.deps.getConfig())) { if (shouldGenerateImage(this.deps.getConfig())) {
try { try {
const animatedLeadInSeconds = await this.deps.getAnimatedImageLeadInSeconds(noteInfo); const animatedLeadInSeconds = await this.deps.getAnimatedImageLeadInSeconds(noteInfo);
const imageFilename = this.generateImageFilename(); const imageFilename = this.generateImageFilename();
@@ -529,7 +492,6 @@ export class CardCreationService {
startTime, startTime,
endTime, endTime,
animatedLeadInSeconds, animatedLeadInSeconds,
exactReviewedRange,
); );
const imageField = this.deps.getConfig().fields?.image; const imageField = this.deps.getConfig().fields?.image;
@@ -602,28 +564,9 @@ export class CardCreationService {
try { try {
return await this.deps.withUpdateProgress('Creating sentence card', async () => { return await this.deps.withUpdateProgress('Creating sentence card', async () => {
const timingDecision = this.deps.reviewMediaTiming
? await this.deps.reviewMediaTiming({
kind: 'sentence',
text: sentence,
startTime,
endTime,
})
: ({ action: 'use-original' } as const);
if (timingDecision.action === 'discard') {
this.deps.showStatusNotification('Card creation cancelled.');
return false;
}
const skipMedia = timingDecision.action === 'skip-media';
const exactReviewedRange = timingDecision.action === 'confirm';
if (timingDecision.action === 'confirm') {
startTime = timingDecision.startTime;
endTime = timingDecision.endTime;
}
const config = this.deps.getConfig(); const config = this.deps.getConfig();
const generateAudio = !skipMedia && shouldGenerateAudio(config); const generateAudio = shouldGenerateAudio(config);
const generateImage = !skipMedia && shouldGenerateImage(config); const generateImage = shouldGenerateImage(config);
const mediaResolverOptions = this.getMediaResolverOptions(); const mediaResolverOptions = this.getMediaResolverOptions();
const videoPath = generateImage const videoPath = generateImage
? await resolveMediaGenerationInput(mpvClient, 'video', mediaResolverOptions) ? await resolveMediaGenerationInput(mpvClient, 'video', mediaResolverOptions)
@@ -789,7 +732,6 @@ export class CardCreationService {
generateAudio, generateAudio,
generateImage, generateImage,
volumeScale, volumeScale,
...(exactReviewedRange ? { mediaPaddingSeconds: 0 } : {}),
}); });
await this.deps.showNotification(noteId, label, 'media queued'); await this.deps.showNotification(noteId, label, 'media queued');
return true; return true;
@@ -805,12 +747,7 @@ export class CardCreationService {
try { try {
const audioFilename = this.generateAudioFilename(); const audioFilename = this.generateAudioFilename();
const audioBuffer = audioSourcePath const audioBuffer = audioSourcePath
? await this.mediaGenerateAudio( ? await this.mediaGenerateAudio(audioSourcePath, startTime, endTime)
audioSourcePath,
startTime,
endTime,
exactReviewedRange ? 0 : undefined,
)
: null; : null;
if (audioBuffer) { if (audioBuffer) {
@@ -828,13 +765,7 @@ export class CardCreationService {
if (generateImage) { if (generateImage) {
try { try {
const imageFilename = this.generateImageFilename(); const imageFilename = this.generateImageFilename();
const imageBuffer = await this.generateImageBuffer( const imageBuffer = await this.generateImageBuffer(videoPath!, startTime, endTime);
videoPath!,
startTime,
endTime,
0,
exactReviewedRange,
);
const imageField = config.fields?.image; const imageField = config.fields?.image;
if (imageBuffer && imageField) { if (imageBuffer && imageField) {
@@ -902,7 +833,6 @@ export class CardCreationService {
videoPath: MediaInput, videoPath: MediaInput,
startTime: number, startTime: number,
endTime: number, endTime: number,
audioPaddingOverride?: number,
): Promise<Buffer | null> { ): Promise<Buffer | null> {
const mpvClient = this.deps.getMpvClient(); const mpvClient = this.deps.getMpvClient();
if (!mpvClient) { if (!mpvClient) {
@@ -913,7 +843,7 @@ export class CardCreationService {
videoPath, videoPath,
startTime, startTime,
endTime, endTime,
audioPaddingOverride ?? this.deps.getConfig().media?.audioPadding, this.deps.getConfig().media?.audioPadding,
resolveAudioStreamIndexForMediaGeneration( resolveAudioStreamIndexForMediaGeneration(
videoPath, videoPath,
mpvClient.currentAudioStreamIndex ?? undefined, mpvClient.currentAudioStreamIndex ?? undefined,
@@ -931,16 +861,13 @@ export class CardCreationService {
startTime: number, startTime: number,
endTime: number, endTime: number,
animatedLeadInSeconds = 0, animatedLeadInSeconds = 0,
exactReviewedRange = false,
): Promise<Buffer | null> { ): Promise<Buffer | null> {
const mpvClient = this.deps.getMpvClient(); const mpvClient = this.deps.getMpvClient();
if (!mpvClient) { if (!mpvClient) {
return null; return null;
} }
const timestamp = exactReviewedRange const timestamp = mpvClient.currentTimePos || 0;
? startTime + (endTime - startTime) / 2
: mpvClient.currentTimePos || 0;
if (this.deps.getConfig().media?.imageType === 'avif') { if (this.deps.getConfig().media?.imageType === 'avif') {
let imageStart = startTime; let imageStart = startTime;
@@ -956,7 +883,7 @@ export class CardCreationService {
videoPath, videoPath,
imageStart, imageStart,
imageEnd, imageEnd,
exactReviewedRange ? 0 : this.deps.getConfig().media?.audioPadding, this.deps.getConfig().media?.audioPadding,
{ {
fps: this.deps.getConfig().media?.animatedFps, fps: this.deps.getConfig().media?.animatedFps,
maxWidth: this.deps.getConfig().media?.animatedMaxWidth, maxWidth: this.deps.getConfig().media?.animatedMaxWidth,
@@ -261,32 +261,6 @@ test('KnownWordCacheManager invalidates persisted cache when fields.word changes
} }
}); });
test('KnownWordCacheManager removes a deleted note from memory and persisted state', () => {
const config: AnkiConnectConfig = {
fields: { word: 'Word' },
knownWords: { highlightEnabled: true },
};
const { manager, statePath, cleanup } = createKnownWordCacheHarness(config);
try {
manager.appendFromNoteInfo({
noteId: 42,
fields: { Word: { value: '猫' } },
});
assert.equal(manager.removeNote(42), true);
assert.equal(manager.removeNote(42), false);
assert.equal(manager.isKnownWord('猫'), false);
const persisted = JSON.parse(fs.readFileSync(statePath, 'utf-8')) as {
notes?: Record<string, unknown>;
};
assert.deepEqual(persisted.notes, {});
} finally {
cleanup();
}
});
test('KnownWordCacheManager refresh incrementally reconciles deleted and edited note words', async () => { test('KnownWordCacheManager refresh incrementally reconciles deleted and edited note words', async () => {
const config: AnkiConnectConfig = { const config: AnkiConnectConfig = {
fields: { fields: {
-11
View File
@@ -350,17 +350,6 @@ export class KnownWordCacheManager {
return true; return true;
} }
removeNote(noteId: number): boolean {
if (!this.noteEntriesById.has(noteId)) {
return false;
}
this.removeNoteSnapshot(noteId);
this.persistKnownWordCacheState();
log.info('Known-word cache removed deleted note', `noteId=${noteId}`);
return true;
}
clearKnownWordCacheState(): void { clearKnownWordCacheState(): void {
this.clearInMemoryState(); this.clearInMemoryState();
this.knownWordsStateKey = this.getKnownWordCacheStateKey(); this.knownWordsStateKey = this.getKnownWordCacheStateKey();
@@ -44,7 +44,6 @@ function createWorkflowHarness() {
updates.push({ noteId, fields }); updates.push({ noteId, fields });
}, },
storeMediaFile: async () => undefined, storeMediaFile: async () => undefined,
deleteNotes: async () => undefined,
}, },
getConfig: () => ({ getConfig: () => ({
fields: { fields: {
@@ -62,7 +61,6 @@ function createWorkflowHarness() {
kikuFieldGrouping: 'disabled' as const, kikuFieldGrouping: 'disabled' as const,
}), }),
appendKnownWordsFromNoteInfo: (_noteInfo: NoteUpdateWorkflowNoteInfo) => undefined, appendKnownWordsFromNoteInfo: (_noteInfo: NoteUpdateWorkflowNoteInfo) => undefined,
removeKnownWordNote: (_noteId: number) => undefined,
extractFields: (fields: Record<string, { value: string }>) => { extractFields: (fields: Record<string, { value: string }>) => {
const out: Record<string, string> = {}; const out: Record<string, string> = {};
for (const [key, value] of Object.entries(fields)) { for (const [key, value] of Object.entries(fields)) {
@@ -594,104 +592,3 @@ test('NoteUpdateWorkflow queues media updates when YouTube cache is pending', as
assert.equal(queuedUpdates[0]?.context, undefined); assert.equal(queuedUpdates[0]?.context, undefined);
assert.deepEqual(harness.updates, [{ noteId: 42, fields: { Sentence: 'subtitle-text' } }]); assert.deepEqual(harness.updates, [{ noteId: 42, fields: { Sentence: 'subtitle-text' } }]);
}); });
test('NoteUpdateWorkflow deletes an existing word card when timing review discards it', async () => {
const harness = createWorkflowHarness();
const deletedNoteIds: number[][] = [];
const removedKnownWordNoteIds: number[] = [];
let appendedKnownWords = false;
harness.deps.captureSubtitleMediaContext = () => ({
source: 'overlay',
text: 'subtitle-text',
startTime: 4,
endTime: 6,
});
harness.deps.client.deleteNotes = async (noteIds) => {
deletedNoteIds.push(noteIds);
};
harness.deps.appendKnownWordsFromNoteInfo = () => {
appendedKnownWords = true;
};
harness.deps.removeKnownWordNote = (noteId) => {
removedKnownWordNoteIds.push(noteId);
};
harness.deps.reviewMediaTiming = async () => ({ action: 'discard' });
await harness.workflow.execute(42);
assert.deepEqual(deletedNoteIds, [[42]]);
assert.deepEqual(removedKnownWordNoteIds, [42]);
assert.equal(appendedKnownWords, false);
assert.deepEqual(harness.updates, []);
assert.deepEqual(harness.notifications, []);
});
test('NoteUpdateWorkflow keeps the word card but skips media after timing review', async () => {
const harness = createWorkflowHarness();
const mediaCalls: string[] = [];
const deletedNoteIds: number[][] = [];
const queuedUpdates: unknown[] = [];
harness.deps.captureSubtitleMediaContext = () => ({
source: 'overlay',
text: 'subtitle-text',
startTime: 4,
endTime: 6,
});
harness.deps.getConfig = () => ({
fields: { sentence: 'Sentence', image: 'Picture' },
media: { generateAudio: true, generateImage: true },
behavior: {},
});
harness.deps.reviewMediaTiming = async () => ({ action: 'skip-media' });
harness.deps.generateAudio = async () => {
mediaCalls.push('audio');
return Buffer.from('audio');
};
harness.deps.generateImage = async () => {
mediaCalls.push('image');
return Buffer.from('image');
};
harness.deps.queuePendingYoutubeMediaUpdate = async (update) => {
queuedUpdates.push(update);
return true;
};
harness.deps.client.deleteNotes = async (noteIds) => {
deletedNoteIds.push(noteIds);
};
await harness.workflow.execute(42);
assert.deepEqual(mediaCalls, []);
assert.deepEqual(queuedUpdates, []);
assert.deepEqual(deletedNoteIds, []);
assert.deepEqual(harness.updates, [{ noteId: 42, fields: { Sentence: 'subtitle-text' } }]);
assert.deepEqual(harness.notifications, [{ noteId: 42, label: 'taberu' }]);
});
test('NoteUpdateWorkflow keeps cache unchanged and reports when deletion fails', async () => {
const harness = createWorkflowHarness();
const statusMessages: string[] = [];
let removedKnownWord = false;
harness.deps.captureSubtitleMediaContext = () => ({
source: 'overlay',
text: 'subtitle-text',
startTime: 4,
endTime: 6,
});
harness.deps.client.deleteNotes = async () => {
throw new Error('delete failed');
};
harness.deps.removeKnownWordNote = () => {
removedKnownWord = true;
};
harness.deps.showOsdNotification = (message) => {
statusMessages.push(message);
};
harness.deps.reviewMediaTiming = async () => ({ action: 'discard' });
await harness.workflow.execute(42);
assert.equal(removedKnownWord, false);
assert.deepEqual(statusMessages, ['Card deletion failed: delete failed']);
assert.ok(harness.warnings.length === 0);
});
+5 -52
View File
@@ -1,12 +1,7 @@
import { DEFAULT_ANKI_CONNECT_CONFIG } from '../config'; import { DEFAULT_ANKI_CONNECT_CONFIG } from '../config';
import { getPreferredWordValueFromExtractedFields } from '../anki-field-config'; import { getPreferredWordValueFromExtractedFields } from '../anki-field-config';
import type { SubtitleMiningContext } from '../types/subtitle'; import type { SubtitleMiningContext } from '../types/subtitle';
import type { import type { CardKind, WordCardKind } from '../types/anki';
CardKind,
MediaTimingReviewDecision,
MediaTimingReviewRequest,
WordCardKind,
} from '../types/anki';
import { resolveWordCardKind } from './note-field-utils'; import { resolveWordCardKind } from './note-field-utils';
export interface NoteUpdateWorkflowNoteInfo { export interface NoteUpdateWorkflowNoteInfo {
@@ -19,7 +14,6 @@ export interface NoteUpdateWorkflowDeps {
notesInfo(noteIds: number[]): Promise<unknown>; notesInfo(noteIds: number[]): Promise<unknown>;
updateNoteFields(noteId: number, fields: Record<string, string>): Promise<void>; updateNoteFields(noteId: number, fields: Record<string, string>): Promise<void>;
storeMediaFile(filename: string, data: Buffer): Promise<void>; storeMediaFile(filename: string, data: Buffer): Promise<void>;
deleteNotes(noteIds: number[]): Promise<void>;
}; };
getConfig: () => { getConfig: () => {
fields?: { fields?: {
@@ -49,7 +43,6 @@ export interface NoteUpdateWorkflowDeps {
wordCardKind?: WordCardKind; wordCardKind?: WordCardKind;
}; };
appendKnownWordsFromNoteInfo: (noteInfo: NoteUpdateWorkflowNoteInfo) => void; appendKnownWordsFromNoteInfo: (noteInfo: NoteUpdateWorkflowNoteInfo) => void;
removeKnownWordNote: (noteId: number) => void;
extractFields: (fields: Record<string, { value: string }>) => Record<string, string>; extractFields: (fields: Record<string, { value: string }>) => Record<string, string>;
findDuplicateNote: ( findDuplicateNote: (
expression: string, expression: string,
@@ -109,9 +102,6 @@ export interface NoteUpdateWorkflowDeps {
logWarn: (message: string, ...args: unknown[]) => void; logWarn: (message: string, ...args: unknown[]) => void;
logInfo: (message: string, ...args: unknown[]) => void; logInfo: (message: string, ...args: unknown[]) => void;
logError: (message: string, ...args: unknown[]) => void; logError: (message: string, ...args: unknown[]) => void;
reviewMediaTiming?: (
request: Omit<MediaTimingReviewRequest, 'audioPadding' | 'maxMediaDuration'>,
) => Promise<MediaTimingReviewDecision>;
} }
function normalizeSubtitleContextText(text: string): string { function normalizeSubtitleContextText(text: string): string {
@@ -181,6 +171,7 @@ export class NoteUpdateWorkflow {
} }
const noteInfo = notesInfo[0]!; const noteInfo = notesInfo[0]!;
this.deps.appendKnownWordsFromNoteInfo(noteInfo);
const fields = this.deps.extractFields(noteInfo.fields); const fields = this.deps.extractFields(noteInfo.fields);
const config = this.deps.getConfig(); const config = this.deps.getConfig();
@@ -216,48 +207,10 @@ export class NoteUpdateWorkflow {
// Audio and image generation run sequentially and audio extraction can take tens of // Audio and image generation run sequentially and audio extraction can take tens of
// seconds, so resolve the clip range exactly once up front; reading live mpv sub // seconds, so resolve the clip range exactly once up front; reading live mpv sub
// timings per generator clips whichever line is on screen when each one starts. // timings per generator clips whichever line is on screen when each one starts.
let mediaTimingContext = const mediaTimingContext =
subtitleMiningContext ?? this.deps.captureSubtitleMediaContext?.() ?? null; subtitleMiningContext ?? this.deps.captureSubtitleMediaContext?.() ?? null;
let skipMedia = false;
const noteLabel = hasExpressionText ? expressionText : noteId; const noteLabel = hasExpressionText ? expressionText : noteId;
if (mediaTimingContext) {
const timingDecision = this.deps.reviewMediaTiming
? await this.deps.reviewMediaTiming({
kind: 'word',
text: mediaTimingContext.text,
startTime: mediaTimingContext.startTime,
endTime: mediaTimingContext.endTime,
noteId,
})
: ({ action: 'use-original' } as const);
if (timingDecision.action === 'discard') {
try {
await this.deps.client.deleteNotes([noteId]);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.deps.logError('Failed to delete discarded card:', message);
this.deps.showOsdNotification(`Card deletion failed: ${message}`);
return;
}
this.deps.removeKnownWordNote(noteId);
this.deps.showOsdNotification('Card deleted.');
return;
}
if (timingDecision.action === 'confirm') {
mediaTimingContext = {
...mediaTimingContext,
startTime: timingDecision.startTime,
endTime: timingDecision.endTime,
mediaPaddingSeconds: 0,
};
} else if (timingDecision.action === 'skip-media') {
skipMedia = true;
}
}
this.deps.appendKnownWordsFromNoteInfo(noteInfo);
const currentSubtitleText = subtitleMiningContext?.text ?? this.deps.getCurrentSubtitleText(); const currentSubtitleText = subtitleMiningContext?.text ?? this.deps.getCurrentSubtitleText();
if (sentenceField && currentSubtitleText) { if (sentenceField && currentSubtitleText) {
const processedSentence = this.deps.processSentence(currentSubtitleText, fields); const processedSentence = this.deps.processSentence(currentSubtitleText, fields);
@@ -286,8 +239,8 @@ export class NoteUpdateWorkflow {
} }
} }
const generateAudio = !skipMedia && config.media?.generateAudio !== false; const generateAudio = config.media?.generateAudio !== false;
const generateImage = !skipMedia && config.media?.generateImage !== false; const generateImage = config.media?.generateImage !== false;
const mediaCacheQueued = const mediaCacheQueued =
(generateAudio || generateImage) && this.deps.queuePendingYoutubeMediaUpdate (generateAudio || generateImage) && this.deps.queuePendingYoutubeMediaUpdate
? await this.deps.queuePendingYoutubeMediaUpdate({ ? await this.deps.queuePendingYoutubeMediaUpdate({
@@ -148,9 +148,6 @@ export class PendingYoutubeMediaQueue {
generateAudio: shouldGenerateAudio(config), generateAudio: shouldGenerateAudio(config),
generateImage: shouldGenerateImage(config), generateImage: shouldGenerateImage(config),
volumeScale, volumeScale,
...(job.context?.mediaPaddingSeconds !== undefined
? { mediaPaddingSeconds: job.context.mediaPaddingSeconds }
: {}),
}); });
return true; return true;
} }
@@ -278,7 +275,7 @@ export class PendingYoutubeMediaQueue {
cachedMediaInput, cachedMediaInput,
job.startTime, job.startTime,
job.endTime, job.endTime,
job.mediaPaddingSeconds ?? config.media?.audioPadding, config.media?.audioPadding,
undefined, undefined,
config.media?.normalizeAudio !== false, config.media?.normalizeAudio !== false,
job.volumeScale, job.volumeScale,
@@ -312,7 +309,6 @@ export class PendingYoutubeMediaQueue {
job.startTime, job.startTime,
job.endTime, job.endTime,
animatedLeadInSeconds, animatedLeadInSeconds,
job.mediaPaddingSeconds,
); );
if (imageBuffer) { if (imageBuffer) {
await this.deps.client.storeMediaFile(imageFilename, imageBuffer); await this.deps.client.storeMediaFile(imageFilename, imageBuffer);
@@ -373,7 +369,6 @@ export class PendingYoutubeMediaQueue {
startTime: number, startTime: number,
endTime: number, endTime: number,
animatedLeadInSeconds = 0, animatedLeadInSeconds = 0,
mediaPaddingSeconds?: number,
): Promise<Buffer | null> { ): Promise<Buffer | null> {
const config = this.deps.getConfig(); const config = this.deps.getConfig();
if (config.media?.imageType === 'avif') { if (config.media?.imageType === 'avif') {
@@ -381,7 +376,7 @@ export class PendingYoutubeMediaQueue {
videoPath, videoPath,
startTime, startTime,
endTime, endTime,
mediaPaddingSeconds ?? config.media?.audioPadding, config.media?.audioPadding,
{ {
fps: config.media?.animatedFps, fps: config.media?.animatedFps,
maxWidth: config.media?.animatedMaxWidth, maxWidth: config.media?.animatedMaxWidth,
@@ -10,7 +10,6 @@ export interface PendingYoutubeMediaUpdate {
generateAudio: boolean; generateAudio: boolean;
generateImage: boolean; generateImage: boolean;
volumeScale?: number; volumeScale?: number;
mediaPaddingSeconds?: number;
} }
function trimToNonEmptyString(value: unknown): string | null { function trimToNonEmptyString(value: unknown): string | null {
-1
View File
@@ -2181,7 +2181,6 @@ test('runtime options registry is centralized', () => {
const ids = RUNTIME_OPTION_REGISTRY.map((entry) => entry.id); const ids = RUNTIME_OPTION_REGISTRY.map((entry) => entry.id);
assert.deepEqual(ids, [ assert.deepEqual(ids, [
'anki.autoUpdateNewCards', 'anki.autoUpdateNewCards',
'anki.mediaReviewTiming',
'subtitle.annotation.knownWords.highlightEnabled', 'subtitle.annotation.knownWords.highlightEnabled',
'subtitle.annotation.knownWords.maturityEnabled', 'subtitle.annotation.knownWords.maturityEnabled',
'subtitle.annotation.nPlusOne', 'subtitle.annotation.nPlusOne',
@@ -54,7 +54,6 @@ export const INTEGRATIONS_DEFAULT_CONFIG: Pick<
syncAnimatedImageToWordAudio: true, syncAnimatedImageToWordAudio: true,
normalizeAudio: true, normalizeAudio: true,
mirrorMpvVolume: true, mirrorMpvVolume: true,
reviewTiming: false,
audioPadding: 0, audioPadding: 0,
fallbackDuration: 3.0, fallbackDuration: 3.0,
maxMediaDuration: 30, maxMediaDuration: 30,
@@ -196,14 +196,6 @@ export function buildIntegrationConfigOptionRegistry(
description: description:
"Apply mpv's current software volume curve to generated sentence audio. Changes apply live.", "Apply mpv's current software volume curve to generated sentence audio. Changes apply live.",
}, },
{
path: 'ankiConnect.media.reviewTiming',
kind: 'boolean',
defaultValue: defaultConfig.ankiConnect.media.reviewTiming,
description:
'Review and preview subtitle media timing before SubMiner creates or enriches a mined card.',
runtime: runtimeOptionById.get('anki.mediaReviewTiming'),
},
{ {
path: 'ankiConnect.media.generateImage', path: 'ankiConnect.media.generateImage',
kind: 'boolean', kind: 'boolean',
-14
View File
@@ -19,20 +19,6 @@ export function buildRuntimeOptionRegistry(
behavior: { autoUpdateNewCards: value === true }, behavior: { autoUpdateNewCards: value === true },
}), }),
}, },
{
id: 'anki.mediaReviewTiming',
path: 'ankiConnect.media.reviewTiming',
label: 'Review Media Timing',
scope: 'ankiConnect',
valueType: 'boolean',
allowedValues: [true, false],
defaultValue: defaultConfig.ankiConnect.media.reviewTiming,
requiresRestart: false,
formatValueForOsd: (value) => (value === true ? 'On' : 'Off'),
toAnkiPatch: (value) => ({
media: { reviewTiming: value === true },
}),
},
{ {
id: 'subtitle.annotation.knownWords.highlightEnabled', id: 'subtitle.annotation.knownWords.highlightEnabled',
path: 'ankiConnect.knownWords.highlightEnabled', path: 'ankiConnect.knownWords.highlightEnabled',
+1 -1
View File
@@ -135,7 +135,7 @@ const INTEGRATION_TEMPLATE_SECTIONS: ConfigTemplateSection[] = [
title: 'AnkiConnect Integration', title: 'AnkiConnect Integration',
description: ['Automatic Anki updates and media generation options.'], description: ['Automatic Anki updates and media generation options.'],
notes: [ notes: [
'Hot-reload: ankiConnect.ai.enabled, media.normalizeAudio/mirrorMpvVolume/reviewTiming, knownWords, nPlusOne, fields.word/audio/image/sentence/miscInfo, behavior.autoUpdateNewCards, isLapis.sentenceCardModel, isKiku.fieldGrouping, and lapisKiku.wordCardKind update live while SubMiner is running.', 'Hot-reload: ankiConnect.ai.enabled, media.normalizeAudio/mirrorMpvVolume, knownWords, nPlusOne, fields.word/audio/image/sentence/miscInfo, behavior.autoUpdateNewCards, isLapis.sentenceCardModel, isKiku.fieldGrouping, and lapisKiku.wordCardKind update live while SubMiner is running.',
'Shared AI provider transport settings are read from top-level ai and typically require restart.', 'Shared AI provider transport settings are read from top-level ai and typically require restart.',
'Most other AnkiConnect settings still require restart.', 'Most other AnkiConnect settings still require restart.',
], ],
-28
View File
@@ -21,34 +21,6 @@ function makeContext(ankiConnect: unknown): {
return { context, warnings }; return { context, warnings };
} }
test('media timing review is disabled by default and accepts a boolean override', () => {
const defaultContext = makeContext({});
applyAnkiConnectResolution(defaultContext.context);
assert.equal(defaultContext.context.resolved.ankiConnect.media.reviewTiming, false);
const enabledContext = makeContext({ media: { reviewTiming: true } });
applyAnkiConnectResolution(enabledContext.context);
assert.equal(enabledContext.context.resolved.ankiConnect.media.reviewTiming, true);
assert.deepEqual(enabledContext.warnings, []);
});
test('modern media duration accepts zero as the disabled cap sentinel', () => {
const disabledCap = makeContext({ media: { maxMediaDuration: 0 } });
applyAnkiConnectResolution(disabledCap.context);
assert.equal(disabledCap.context.resolved.ankiConnect.media.maxMediaDuration, 0);
assert.deepEqual(disabledCap.warnings, []);
const invalidCap = makeContext({ media: { maxMediaDuration: -1 } });
applyAnkiConnectResolution(invalidCap.context);
assert.equal(
invalidCap.context.resolved.ankiConnect.media.maxMediaDuration,
DEFAULT_CONFIG.ankiConnect.media.maxMediaDuration,
);
assert.ok(
invalidCap.warnings.some((warning) => warning.path === 'ankiConnect.media.maxMediaDuration'),
);
});
test('modern invalid knownWords.highlightEnabled warns modern key and does not fallback to legacy', () => { test('modern invalid knownWords.highlightEnabled warns modern key and does not fallback to legacy', () => {
const { context, warnings } = makeContext({ const { context, warnings } = makeContext({
nPlusOne: { highlightEnabled: true }, nPlusOne: { highlightEnabled: true },
+14 -25
View File
@@ -19,7 +19,6 @@ export function applyModernMediaResolution(
'syncAnimatedImageToWordAudio', 'syncAnimatedImageToWordAudio',
'normalizeAudio', 'normalizeAudio',
'mirrorMpvVolume', 'mirrorMpvVolume',
'reviewTiming',
] as const) { ] as const) {
applyModernValue( applyModernValue(
context, context,
@@ -129,28 +128,18 @@ export function applyModernMediaResolution(
'Expected non-negative number.', 'Expected non-negative number.',
); );
applyModernValue( for (const key of ['fallbackDuration', 'maxMediaDuration'] as const) {
context, applyModernValue(
media, context,
'fallbackDuration', media,
'ankiConnect.media.fallbackDuration', key,
asPositiveNumber, `ankiConnect.media.${key}`,
DEFAULT_CONFIG.ankiConnect.media.fallbackDuration, asPositiveNumber,
(value) => { DEFAULT_CONFIG.ankiConnect.media[key],
context.resolved.ankiConnect.media.fallbackDuration = value; (value) => {
}, context.resolved.ankiConnect.media[key] = value;
'Expected positive number.', },
); 'Expected positive number.',
applyModernValue( );
context, }
media,
'maxMediaDuration',
'ankiConnect.media.maxMediaDuration',
asNonNegativeNumber,
DEFAULT_CONFIG.ankiConnect.media.maxMediaDuration,
(value) => {
context.resolved.ankiConnect.media.maxMediaDuration = value;
},
'Expected non-negative number.',
);
} }
-1
View File
@@ -352,7 +352,6 @@ test('settings registry marks safe live config paths as hot-reloadable', () => {
'ankiConnect.deck', 'ankiConnect.deck',
'ankiConnect.media.normalizeAudio', 'ankiConnect.media.normalizeAudio',
'ankiConnect.media.mirrorMpvVolume', 'ankiConnect.media.mirrorMpvVolume',
'ankiConnect.media.reviewTiming',
'ankiConnect.knownWords.highlightEnabled', 'ankiConnect.knownWords.highlightEnabled',
'ankiConnect.knownWords.refreshMinutes', 'ankiConnect.knownWords.refreshMinutes',
'ankiConnect.knownWords.addMinedWordsImmediately', 'ankiConnect.knownWords.addMinedWordsImmediately',
-2
View File
@@ -244,7 +244,6 @@ const LABEL_OVERRIDES: Record<string, string> = {
'mpv.aniskipEnabled': 'Enable AniSkip', 'mpv.aniskipEnabled': 'Enable AniSkip',
'mpv.aniskipButtonKey': 'AniSkip Button Key', 'mpv.aniskipButtonKey': 'AniSkip Button Key',
'ankiConnect.media.mirrorMpvVolume': 'Mirror mpv Volume', 'ankiConnect.media.mirrorMpvVolume': 'Mirror mpv Volume',
'ankiConnect.media.reviewTiming': 'Review Media Timing',
'discordPresence.updateIntervalMs': 'Update Interval (ms)', 'discordPresence.updateIntervalMs': 'Update Interval (ms)',
}; };
@@ -695,7 +694,6 @@ function restartBehaviorForPath(path: string): ConfigSettingsRestartBehavior {
path === 'ankiConnect.ai.enabled' || path === 'ankiConnect.ai.enabled' ||
path === 'ankiConnect.media.normalizeAudio' || path === 'ankiConnect.media.normalizeAudio' ||
path === 'ankiConnect.media.mirrorMpvVolume' || path === 'ankiConnect.media.mirrorMpvVolume' ||
path === 'ankiConnect.media.reviewTiming' ||
path === 'ankiConnect.behavior.autoUpdateNewCards' || path === 'ankiConnect.behavior.autoUpdateNewCards' ||
path === 'ankiConnect.knownWords.highlightEnabled' || path === 'ankiConnect.knownWords.highlightEnabled' ||
path === 'ankiConnect.knownWords.refreshMinutes' || path === 'ankiConnect.knownWords.refreshMinutes' ||
@@ -284,6 +284,22 @@ function createMockTracker(
getSessionTimeline: async () => [], getSessionTimeline: async () => [],
getSessionEvents: async () => [], getSessionEvents: async () => [],
getVocabularyStats: async () => VOCABULARY_STATS, getVocabularyStats: async () => VOCABULARY_STATS,
getVocabularySummary: async () => ({
uniqueWords: 501,
uniqueWordsWithoutNames: 500,
uniqueKanji: 201,
newThisWeek: 7,
newThisWeekWithoutNames: 6,
knownWordCount: 250,
knownWordCountWithoutNames: 249,
}),
getVocabularyChartData: async () => ({
ready: true,
topWords: [{ wordId: 1, headword: 'する', frequency: 50 }],
topWordsWithoutNames: [{ wordId: 1, headword: 'する', frequency: 50 }],
newWordsTimeline: [{ epochDay: 20_000, wordCount: 3 }],
newWordsTimelineWithoutNames: [{ epochDay: 20_000, wordCount: 3 }],
}),
getStatsExcludedWords: async () => [], getStatsExcludedWords: async () => [],
replaceStatsExcludedWords: async () => {}, replaceStatsExcludedWords: async () => {},
getKanjiStats: async () => KANJI_STATS, getKanjiStats: async () => KANJI_STATS,
@@ -711,6 +727,38 @@ describe('stats server API routes', () => {
assert.equal(body[0].headword, 'する'); assert.equal(body[0].headword, 'する');
}); });
it('GET /api/stats/vocabulary/summary returns database-wide card totals', async () => {
const app = createStatsApp(createMockTracker());
const res = await app.request('/api/stats/vocabulary/summary');
assert.equal(res.status, 200);
assert.deepEqual(await res.json(), {
uniqueWords: 501,
uniqueWordsWithoutNames: 500,
uniqueKanji: 201,
newThisWeek: 7,
newThisWeekWithoutNames: 6,
knownWordCount: 250,
knownWordCountWithoutNames: 249,
});
});
it('GET /api/stats/vocabulary/charts returns complete chart datasets', async () => {
const app = createStatsApp(createMockTracker());
const res = await app.request('/api/stats/vocabulary/charts');
assert.equal(res.status, 200);
assert.deepEqual(await res.json(), {
ready: true,
topWords: [{ wordId: 1, headword: 'する', frequency: 50 }],
topWordsWithoutNames: [{ wordId: 1, headword: 'する', frequency: 50 }],
newWordsTimeline: [{ epochDay: 20_000, wordCount: 3 }],
newWordsTimelineWithoutNames: [{ epochDay: 20_000, wordCount: 3 }],
});
});
it('GET /api/stats/kanji returns kanji frequency data', async () => { it('GET /api/stats/kanji returns kanji frequency data', async () => {
const app = createStatsApp(createMockTracker()); const app = createStatsApp(createMockTracker());
const res = await app.request('/api/stats/kanji'); const res = await app.request('/api/stats/kanji');
@@ -33,7 +33,6 @@ test('classifyConfigHotReloadDiff treats safe nested config paths as hot-reloada
next.ankiConnect.deck = 'Mining'; next.ankiConnect.deck = 'Mining';
next.ankiConnect.media.normalizeAudio = !prev.ankiConnect.media.normalizeAudio; next.ankiConnect.media.normalizeAudio = !prev.ankiConnect.media.normalizeAudio;
next.ankiConnect.media.mirrorMpvVolume = !prev.ankiConnect.media.mirrorMpvVolume; next.ankiConnect.media.mirrorMpvVolume = !prev.ankiConnect.media.mirrorMpvVolume;
next.ankiConnect.media.reviewTiming = !prev.ankiConnect.media.reviewTiming;
next.ankiConnect.behavior.autoUpdateNewCards = !prev.ankiConnect.behavior.autoUpdateNewCards; next.ankiConnect.behavior.autoUpdateNewCards = !prev.ankiConnect.behavior.autoUpdateNewCards;
next.ankiConnect.knownWords.highlightEnabled = !prev.ankiConnect.knownWords.highlightEnabled; next.ankiConnect.knownWords.highlightEnabled = !prev.ankiConnect.knownWords.highlightEnabled;
next.ankiConnect.knownWords.refreshMinutes = prev.ankiConnect.knownWords.refreshMinutes + 5; next.ankiConnect.knownWords.refreshMinutes = prev.ankiConnect.knownWords.refreshMinutes + 5;
@@ -70,7 +69,6 @@ test('classifyConfigHotReloadDiff treats safe nested config paths as hot-reloada
'ankiConnect.deck', 'ankiConnect.deck',
'ankiConnect.media.normalizeAudio', 'ankiConnect.media.normalizeAudio',
'ankiConnect.media.mirrorMpvVolume', 'ankiConnect.media.mirrorMpvVolume',
'ankiConnect.media.reviewTiming',
'ankiConnect.behavior.autoUpdateNewCards', 'ankiConnect.behavior.autoUpdateNewCards',
'ankiConnect.knownWords.highlightEnabled', 'ankiConnect.knownWords.highlightEnabled',
'ankiConnect.knownWords.refreshMinutes', 'ankiConnect.knownWords.refreshMinutes',
-1
View File
@@ -70,7 +70,6 @@ const HOT_RELOAD_EXACT_OR_PREFIX_PATHS = [
'ankiConnect.deck', 'ankiConnect.deck',
'ankiConnect.media.normalizeAudio', 'ankiConnect.media.normalizeAudio',
'ankiConnect.media.mirrorMpvVolume', 'ankiConnect.media.mirrorMpvVolume',
'ankiConnect.media.reviewTiming',
'ankiConnect.behavior.autoUpdateNewCards', 'ankiConnect.behavior.autoUpdateNewCards',
'ankiConnect.knownWords.highlightEnabled', 'ankiConnect.knownWords.highlightEnabled',
'ankiConnect.knownWords.refreshMinutes', 'ankiConnect.knownWords.refreshMinutes',
@@ -559,6 +559,241 @@ test('fresh tracker DB creates lifetime summary tables', async () => {
} }
}); });
test('fresh tracker DB skips lexical rollup backfill work', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
let backfillRuns = 0;
try {
const Ctor = await loadTrackerCtor();
tracker = new Ctor({ dbPath }, {
runLexicalRollupBackfillTask: async () => {
backfillRuns += 1;
},
} as never);
assert.equal(backfillRuns, 0);
} finally {
tracker?.destroy();
cleanupDbPath(dbPath);
}
});
test('tracker starts the injected lexical rollup backfill when it is pending', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
let backfillRuns = 0;
try {
const setupDb = new Database(dbPath);
const { ensureSchema } = await import('./immersion-tracker/storage');
ensureSchema(setupDb);
setupDb
.prepare(
`UPDATE imm_rollup_state SET state_value = '0' WHERE state_key = 'lexical_daily_rollups_version'`,
)
.run();
setupDb.close();
const Ctor = await loadTrackerCtor();
tracker = new Ctor({ dbPath }, {
runLexicalRollupBackfillTask: async () => {
backfillRuns += 1;
},
} as never);
assert.equal(backfillRuns, 1);
await waitForCondition(
() => !(tracker as unknown as { writeLock: { locked: boolean } }).writeLock.locked,
);
assert.equal(
(tracker as unknown as { preserveWriteQueueUntilDrained: boolean })
.preserveWriteQueueUntilDrained,
false,
);
} finally {
tracker?.destroy();
cleanupDbPath(dbPath);
}
});
test('tracker runs startup session-rollup maintenance before lexical backfill locks writes', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
let releaseBackfill = (): void => {};
const heldBackfill = new Promise<void>((resolve) => {
releaseBackfill = resolve;
});
try {
const startedAtMs = trackerNowMs() - 60_000;
const endedAtMs = trackerNowMs();
const setupDb = new Database(dbPath);
const { ensureSchema } = await import('./immersion-tracker/storage');
ensureSchema(setupDb);
setupDb.exec(`
INSERT INTO imm_videos (
video_id, video_key, canonical_title, source_type, duration_ms, CREATED_DATE, LAST_UPDATE_DATE
) VALUES (1, 'local:/tmp/rollup-recovery.mkv', 'Rollup Recovery', 1, 0, '1', '1');
INSERT INTO imm_sessions (
session_id, session_uuid, video_id, started_at_ms, ended_at_ms, status,
active_watched_ms, lines_seen, tokens_seen, cards_mined, CREATED_DATE, LAST_UPDATE_DATE
) VALUES (
1, 'rollup-recovery', 1, '${startedAtMs}', '${endedAtMs}', 2,
60000, 10, 20, 2, '${startedAtMs}', '${endedAtMs}'
);
INSERT INTO imm_session_telemetry (
session_id, sample_ms, total_watched_ms, active_watched_ms, lines_seen,
tokens_seen, cards_mined, lookup_count, lookup_hits, CREATED_DATE, LAST_UPDATE_DATE
) VALUES (
1, '${endedAtMs}', 60000, 60000, 10, 20, 2, 0, 0,
'${endedAtMs}', '${endedAtMs}'
);
DELETE FROM imm_daily_rollups;
DELETE FROM imm_monthly_rollups;
UPDATE imm_rollup_state SET state_value = '0';
`);
setupDb.close();
const Ctor = await loadTrackerCtor();
tracker = new Ctor({ dbPath }, {
runLexicalRollupBackfillTask: async () => heldBackfill,
} as never);
const privateApi = tracker as unknown as {
db: DatabaseSync;
writeLock: { locked: boolean };
};
assert.equal(privateApi.writeLock.locked, true);
assert.equal(
(
privateApi.db.prepare('SELECT COUNT(*) AS total FROM imm_daily_rollups').get() as {
total: number;
}
).total,
1,
);
assert.equal(
(
privateApi.db.prepare('SELECT COUNT(*) AS total FROM imm_monthly_rollups').get() as {
total: number;
}
).total,
1,
);
} finally {
releaseBackfill();
if (tracker) {
await waitForCondition(
() => !(tracker as unknown as { writeLock: { locked: boolean } }).writeLock.locked,
);
}
tracker?.destroy();
cleanupDbPath(dbPath);
}
});
test('tracker queues playback writes until lexical rollup backfill settles', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
let startBackfill = (): void => {};
let releaseBackfill = (): void => {};
let markBackfillStarted = (): void => {};
const backfillStartGate = new Promise<void>((resolve) => {
startBackfill = resolve;
});
const heldBackfill = new Promise<void>((resolve) => {
releaseBackfill = resolve;
});
const backfillStarted = new Promise<void>((resolve) => {
markBackfillStarted = resolve;
});
try {
const setupDb = new Database(dbPath);
const { ensureSchema } = await import('./immersion-tracker/storage');
ensureSchema(setupDb);
setupDb
.prepare(
`UPDATE imm_rollup_state SET state_value = '0' WHERE state_key = 'lexical_daily_rollups_version'`,
)
.run();
setupDb.close();
const Ctor = await loadTrackerCtor();
tracker = new Ctor(
{ dbPath, policy: { queueCap: 100 } },
{
runLexicalRollupBackfillTask: async (workerDbPath) => {
await backfillStartGate;
const workerDb = new Database(workerDbPath);
try {
workerDb.exec('BEGIN IMMEDIATE');
markBackfillStarted();
await heldBackfill;
workerDb.exec('COMMIT');
} catch (error) {
try {
workerDb.exec('ROLLBACK');
} catch {
// Preserve the original worker failure.
}
throw error;
} finally {
workerDb.close();
}
},
},
);
tracker.handleMediaChange('https://example.com/backfill-test.mp4', 'Backfill Test');
startBackfill();
await backfillStarted;
for (let index = 0; index < 125; index += 1) tracker.recordCardsMined(1);
const privateApi = tracker as unknown as {
db: DatabaseSync;
queue: unknown[];
droppedWriteCount: number;
flushNow: () => void;
writeLock: { locked: boolean };
};
assert.equal(privateApi.writeLock.locked, true);
privateApi.flushNow();
assert.ok(privateApi.queue.length > 100, 'the protected queue may grow past its normal cap');
assert.equal(privateApi.droppedWriteCount, 0, 'backfill must not discard playback writes');
assert.equal(
(
privateApi.db.prepare('SELECT COUNT(*) AS total FROM imm_session_events').get() as {
total: number;
}
).total,
0,
);
releaseBackfill();
await waitForCondition(() => privateApi.queue.length === 0, 5_000);
assert.equal(
(
privateApi.db.prepare('SELECT COUNT(*) AS total FROM imm_session_events').get() as {
total: number;
}
).total,
125,
);
} finally {
releaseBackfill();
if (tracker) {
await waitForCondition(
() => !(tracker as unknown as { writeLock: { locked: boolean } }).writeLock.locked,
5_000,
);
}
tracker?.destroy();
cleanupDbPath(dbPath);
}
});
test('startup backfills lifetime summaries when retained sessions exist but summary tables are empty', async () => { test('startup backfills lifetime summaries when retained sessions exist but summary tables are empty', async () => {
const dbPath = makeDbPath(); const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null; let tracker: ImmersionTrackerService | null = null;
@@ -4909,3 +5144,149 @@ test('ensureAnimeCoverArt fetches art via the latest video of the anime', async
cleanupDbPath(dbPath); cleanupDbPath(dbPath);
} }
}); });
test('getVocabularySummary coalesces concurrent requests into one worker task', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
let taskRuns = 0;
let releaseTask: (() => void) | null = null;
const seenKnownWords: Array<ReadonlySet<string> | null> = [];
const summary = {
uniqueWords: 1,
uniqueWordsWithoutNames: 1,
uniqueKanji: 0,
newThisWeek: 0,
newThisWeekWithoutNames: 0,
knownWordCount: null,
knownWordCountWithoutNames: null,
};
try {
const Ctor = await loadTrackerCtor();
tracker = new Ctor(
{ dbPath },
{
runVocabularySummaryTask: async (_dbPath, knownWords) => {
taskRuns += 1;
seenKnownWords.push(knownWords);
await new Promise<void>((resolve) => {
releaseTask = resolve;
});
return summary;
},
destroyVocabularySummaryRunner: () => {},
},
);
const knownWordsSnapshot = new Set(['猫']);
const first = tracker.getVocabularySummary(knownWordsSnapshot);
const second = tracker.getVocabularySummary(knownWordsSnapshot);
await waitForCondition(() => releaseTask !== null);
let release = releaseTask as (() => void) | null;
assert.ok(release);
release();
assert.deepEqual(await first, summary);
assert.equal(await second, await first);
assert.equal(taskRuns, 1);
assert.deepEqual(seenKnownWords, [knownWordsSnapshot]);
releaseTask = null;
const third = tracker.getVocabularySummary(null);
await waitForCondition(() => releaseTask !== null);
release = releaseTask as (() => void) | null;
assert.ok(release);
release();
assert.deepEqual(await third, summary);
assert.equal(taskRuns, 2);
} finally {
tracker?.destroy();
cleanupDbPath(dbPath);
}
});
test('getVocabularySummary coalesces equivalent known-word snapshots by value', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
let taskRuns = 0;
const releases: Array<() => void> = [];
try {
const Ctor = await loadTrackerCtor();
tracker = new Ctor(
{ dbPath },
{
runVocabularySummaryTask: async () => {
taskRuns += 1;
await new Promise<void>((resolve) => releases.push(resolve));
return {
uniqueWords: 2,
uniqueWordsWithoutNames: 2,
uniqueKanji: 2,
newThisWeek: 0,
newThisWeekWithoutNames: 0,
knownWordCount: 2,
knownWordCountWithoutNames: 2,
};
},
destroyVocabularySummaryRunner: () => {},
},
);
const first = tracker.getVocabularySummary(new Set(['猫', '犬']));
const second = tracker.getVocabularySummary(new Set(['犬', '猫']));
await waitForCondition(() => releases.length > 0);
const observedTaskRuns = taskRuns;
for (const release of releases) release();
await Promise.all([first, second]);
assert.equal(observedTaskRuns, 1);
const third = tracker.getVocabularySummary(new Set(['猫', '犬']));
await waitForCondition(() => releases.length === 2);
releases[1]!();
await third;
assert.equal(taskRuns, 2, 'a settled snapshot must be evicted from the in-flight map');
} finally {
tracker?.destroy();
cleanupDbPath(dbPath);
}
});
test('getVocabularySummary keeps different known-word snapshots independent', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
const releases: Array<() => void> = [];
try {
const Ctor = await loadTrackerCtor();
tracker = new Ctor(
{ dbPath },
{
runVocabularySummaryTask: async (_dbPath, knownWords) => {
await new Promise<void>((resolve) => releases.push(resolve));
return {
uniqueWords: 1,
uniqueWordsWithoutNames: 1,
uniqueKanji: 0,
newThisWeek: 0,
newThisWeekWithoutNames: 0,
knownWordCount: knownWords?.size ?? null,
knownWordCountWithoutNames: knownWords?.size ?? null,
};
},
destroyVocabularySummaryRunner: () => {},
},
);
const withoutKnownWords = tracker.getVocabularySummary(null);
const withKnownWords = tracker.getVocabularySummary(new Set(['猫']));
await waitForCondition(() => releases.length === 2);
for (const release of releases) release();
assert.equal((await withoutKnownWords).knownWordCount, null);
assert.equal((await withKnownWords).knownWordCount, 1);
} finally {
tracker?.destroy();
cleanupDbPath(dbPath);
}
});
+106 -6
View File
@@ -58,6 +58,7 @@ import {
getSessionEvents, getSessionEvents,
getSimilarWords, getSimilarWords,
getStatsExcludedWords, getStatsExcludedWords,
getVocabularyChartData,
getVocabularyStats, getVocabularyStats,
replaceStatsExcludedWords, replaceStatsExcludedWords,
searchSubtitleSentences, searchSubtitleSentences,
@@ -96,6 +97,12 @@ import {
DeleteMaintenanceWorkerRuntime, DeleteMaintenanceWorkerRuntime,
type RunDeleteMaintenanceTask, type RunDeleteMaintenanceTask,
} from './immersion-tracker/delete-maintenance-worker-runtime'; } from './immersion-tracker/delete-maintenance-worker-runtime';
import {
VocabularySummaryWorkerRuntime,
type RunVocabularySummaryTask,
} from './immersion-tracker/vocabulary-summary-worker-runtime';
import { LexicalRollupWorkerRuntime } from './immersion-tracker/lexical-rollup-worker-runtime';
import { areLexicalDailyRollupsReady } from './immersion-tracker/lexical-rollups';
import { DeleteMaintenanceScheduler } from './immersion-tracker/delete-maintenance-scheduler'; import { DeleteMaintenanceScheduler } from './immersion-tracker/delete-maintenance-scheduler';
import { import {
cleanupDuplicateSubtitleLines, cleanupDuplicateSubtitleLines,
@@ -185,6 +192,7 @@ import {
type StatsExcludedWordRow, type StatsExcludedWordRow,
type StreakCalendarRow, type StreakCalendarRow,
type VocabularyCleanupSummary, type VocabularyCleanupSummary,
type VocabularyStatsSummary,
type WatchTimePerAnimeRow, type WatchTimePerAnimeRow,
type WordAnimeAppearanceRow, type WordAnimeAppearanceRow,
type WordDetailRow, type WordDetailRow,
@@ -405,13 +413,24 @@ export class ImmersionTrackerService {
private readonly monthlyRollupRetentionMs: number; private readonly monthlyRollupRetentionMs: number;
private readonly vacuumIntervalMs: number; private readonly vacuumIntervalMs: number;
private readonly dbPath: string; private readonly dbPath: string;
private readonly writeLock = { locked: false }; private readonly writeLock = {
locked: false,
reasons: new Set<'flush' | 'delete-maintenance' | 'lexical-rollup-backfill'>(),
};
private readonly destroyDeleteMaintenanceRunner: () => void; private readonly destroyDeleteMaintenanceRunner: () => void;
private readonly runVocabularySummaryTask: (
knownWords: ReadonlySet<string> | null,
) => Promise<VocabularyStatsSummary>;
private readonly vocabularySummariesInFlight = new Map<string, Promise<VocabularyStatsSummary>>();
private readonly destroyVocabularySummaryRunner: () => void;
private readonly runLexicalRollupBackfillTask: () => Promise<void>;
private readonly destroyLexicalRollupBackfillRunner: () => void;
private readonly deleteMaintenanceScheduler: DeleteMaintenanceScheduler; private readonly deleteMaintenanceScheduler: DeleteMaintenanceScheduler;
private flushTimer: ReturnType<typeof setTimeout> | null = null; private flushTimer: ReturnType<typeof setTimeout> | null = null;
private maintenanceTimer: ReturnType<typeof setInterval> | null = null; private maintenanceTimer: ReturnType<typeof setInterval> | null = null;
private flushScheduled = false; private flushScheduled = false;
private droppedWriteCount = 0; private droppedWriteCount = 0;
private preserveWriteQueueUntilDrained = false;
private lastVacuumMs = 0; private lastVacuumMs = 0;
private isDestroyed = false; private isDestroyed = false;
private sessionState: SessionState | null = null; private sessionState: SessionState | null = null;
@@ -434,6 +453,10 @@ export class ImmersionTrackerService {
dependencies: { dependencies: {
runDeleteMaintenanceTask?: RunDeleteMaintenanceTask; runDeleteMaintenanceTask?: RunDeleteMaintenanceTask;
destroyDeleteMaintenanceRunner?: () => void; destroyDeleteMaintenanceRunner?: () => void;
runVocabularySummaryTask?: RunVocabularySummaryTask;
destroyVocabularySummaryRunner?: () => void;
runLexicalRollupBackfillTask?: (dbPath: string) => Promise<void>;
destroyLexicalRollupBackfillRunner?: () => void;
} = {}, } = {},
) { ) {
this.dbPath = options.dbPath; this.dbPath = options.dbPath;
@@ -453,13 +476,34 @@ export class ImmersionTrackerService {
runTask: (task) => runDeleteMaintenanceTask(this.dbPath, task), runTask: (task) => runDeleteMaintenanceTask(this.dbPath, task),
onBusy: () => { onBusy: () => {
this.requireWriteQueueDrained('delete maintenance'); this.requireWriteQueueDrained('delete maintenance');
this.writeLock.locked = true; this.setWriteLock('delete-maintenance', true);
}, },
onIdle: () => { onIdle: () => {
this.writeLock.locked = false; this.setWriteLock('delete-maintenance', false);
if (!this.isDestroyed && this.queue.length > 0) this.scheduleFlush(0); if (!this.isDestroyed && this.queue.length > 0) this.scheduleFlush(0);
}, },
}); });
if (dependencies.runVocabularySummaryTask) {
this.runVocabularySummaryTask = (knownWords) =>
dependencies.runVocabularySummaryTask!(this.dbPath, knownWords);
this.destroyVocabularySummaryRunner =
dependencies.destroyVocabularySummaryRunner ?? (() => {});
} else {
const vocabularySummaryRuntime = new VocabularySummaryWorkerRuntime();
this.runVocabularySummaryTask = (knownWords) =>
vocabularySummaryRuntime.run(this.dbPath, knownWords);
this.destroyVocabularySummaryRunner = () => vocabularySummaryRuntime.destroy();
}
if (dependencies.runLexicalRollupBackfillTask) {
this.runLexicalRollupBackfillTask = () =>
dependencies.runLexicalRollupBackfillTask!(this.dbPath);
this.destroyLexicalRollupBackfillRunner =
dependencies.destroyLexicalRollupBackfillRunner ?? (() => {});
} else {
const lexicalRollupRuntime = new LexicalRollupWorkerRuntime();
this.runLexicalRollupBackfillTask = () => lexicalRollupRuntime.run(this.dbPath);
this.destroyLexicalRollupBackfillRunner = () => lexicalRollupRuntime.destroy();
}
const parentDir = path.dirname(this.dbPath); const parentDir = path.dirname(this.dbPath);
if (!fs.existsSync(parentDir)) { if (!fs.existsSync(parentDir)) {
fs.mkdirSync(parentDir, { recursive: true }); fs.mkdirSync(parentDir, { recursive: true });
@@ -548,6 +592,7 @@ export class ImmersionTrackerService {
} }
this.preparedStatements = createTrackerPreparedStatements(this.db); this.preparedStatements = createTrackerPreparedStatements(this.db);
this.scheduleMaintenance(); this.scheduleMaintenance();
if (!areLexicalDailyRollupsReady(this.db)) this.startLexicalRollupBackfill();
this.scheduleFlush(); this.scheduleFlush();
} }
@@ -565,6 +610,8 @@ export class ImmersionTrackerService {
this.isDestroyed = true; this.isDestroyed = true;
this.deleteMaintenanceScheduler.destroy(); this.deleteMaintenanceScheduler.destroy();
this.destroyDeleteMaintenanceRunner(); this.destroyDeleteMaintenanceRunner();
this.destroyVocabularySummaryRunner();
this.destroyLexicalRollupBackfillRunner();
this.db.close(); this.db.close();
} }
@@ -634,6 +681,25 @@ export class ImmersionTrackerService {
return getVocabularyStats(this.db, limit, excludePos); return getVocabularyStats(this.db, limit, excludePos);
} }
async getVocabularySummary(knownWords: ReadonlySet<string> | null) {
const key = knownWords ? JSON.stringify([...knownWords].sort()) : 'null';
const inFlight = this.vocabularySummariesInFlight.get(key);
if (inFlight) return inFlight;
const task = this.runVocabularySummaryTask(knownWords);
this.vocabularySummariesInFlight.set(key, task);
try {
return await task;
} finally {
if (this.vocabularySummariesInFlight.get(key) === task) {
this.vocabularySummariesInFlight.delete(key);
}
}
}
async getVocabularyChartData() {
return getVocabularyChartData(this.db);
}
async getStatsExcludedWords(): Promise<StatsExcludedWordRow[]> { async getStatsExcludedWords(): Promise<StatsExcludedWordRow[]> {
return getStatsExcludedWords(this.db); return getStatsExcludedWords(this.db);
} }
@@ -910,6 +976,33 @@ export class ImmersionTrackerService {
} }
} }
private setWriteLock(
reason: 'flush' | 'delete-maintenance' | 'lexical-rollup-backfill',
active: boolean,
): void {
if (active) this.writeLock.reasons.add(reason);
else this.writeLock.reasons.delete(reason);
this.writeLock.locked = this.writeLock.reasons.size > 0;
}
private startLexicalRollupBackfill(): void {
this.requireWriteQueueDrained('lexical rollup backfill');
this.preserveWriteQueueUntilDrained = true;
this.setWriteLock('lexical-rollup-backfill', true);
void this.runLexicalRollupBackfillTask()
.catch((error: unknown) => {
this.logger.warn(
'Lexical daily rollup backfill failed; it will retry on next startup',
error,
);
})
.finally(() => {
this.setWriteLock('lexical-rollup-backfill', false);
if (this.queue.length === 0) this.preserveWriteQueueUntilDrained = false;
else if (!this.isDestroyed) this.scheduleFlush(0);
});
}
async reassignAnimeAnilist( async reassignAnimeAnilist(
animeId: number, animeId: number,
info: { info: {
@@ -1906,7 +1999,12 @@ export class ImmersionTrackerService {
private recordWrite(write: QueuedWrite): void { private recordWrite(write: QueuedWrite): void {
if (this.isDestroyed) return; if (this.isDestroyed) return;
const { dropped } = enqueueWrite(this.queue, write, this.queueCap); // A lexical migration owns the database write lock, so dropping the oldest
// entry cannot relieve pressure: nothing can flush until the worker exits.
// Preserve that finite startup burst and drain it as soon as the lock lifts.
const { dropped } = this.preserveWriteQueueUntilDrained
? (this.queue.push(write), { dropped: 0 })
: enqueueWrite(this.queue, write, this.queueCap);
if (dropped > 0) { if (dropped > 0) {
this.droppedWriteCount += dropped; this.droppedWriteCount += dropped;
this.logger.warn(`Immersion tracker queue overflow; dropped ${dropped} oldest writes`); this.logger.warn(`Immersion tracker queue overflow; dropped ${dropped} oldest writes`);
@@ -1954,6 +2052,7 @@ export class ImmersionTrackerService {
private flushNow(): void { private flushNow(): void {
if (this.writeLock.locked || this.isDestroyed) return; if (this.writeLock.locked || this.isDestroyed) return;
if (this.queue.length === 0) { if (this.queue.length === 0) {
this.preserveWriteQueueUntilDrained = false;
this.flushScheduled = false; this.flushScheduled = false;
return; return;
} }
@@ -1965,7 +2064,7 @@ export class ImmersionTrackerService {
} }
const batch = this.queue.splice(0, Math.min(this.batchSize, this.queue.length)); const batch = this.queue.splice(0, Math.min(this.batchSize, this.queue.length));
this.writeLock.locked = true; this.setWriteLock('flush', true);
try { try {
this.db.exec('BEGIN IMMEDIATE'); this.db.exec('BEGIN IMMEDIATE');
for (const write of batch) { for (const write of batch) {
@@ -1977,8 +2076,9 @@ export class ImmersionTrackerService {
this.queue.unshift(...batch); this.queue.unshift(...batch);
this.logger.warn('Immersion tracker flush failed, retrying later', error as Error); this.logger.warn('Immersion tracker flush failed, retrying later', error as Error);
} finally { } finally {
this.writeLock.locked = false; this.setWriteLock('flush', false);
this.flushScheduled = false; this.flushScheduled = false;
if (this.queue.length === 0) this.preserveWriteQueueUntilDrained = false;
if (this.queue.length > 0) { if (this.queue.length > 0) {
this.scheduleFlush(this.flushIntervalMs); this.scheduleFlush(this.flushIntervalMs);
} }
@@ -1,7 +1,4 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test'; import test from 'node:test';
import { Database } from '../sqlite.js'; import { Database } from '../sqlite.js';
import type { DatabaseSync } from '../sqlite.js'; import type { DatabaseSync } from '../sqlite.js';
@@ -21,17 +18,6 @@ interface SeedLine {
createdMs?: number; createdMs?: number;
} }
function makeDbPath(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-duplicate-line-test-'));
return path.join(dir, 'immersion.sqlite');
}
function cleanupDbPath(dbPath: string): void {
const dir = path.dirname(dbPath);
if (!fs.existsSync(dir)) return;
fs.rmSync(dir, { recursive: true, force: true });
}
/** One episode, two sessions of it, and one word occurrence per seeded line. */ /** One episode, two sessions of it, and one word occurrence per seeded line. */
function seed(db: DatabaseSync, lines: SeedLine[]): void { function seed(db: DatabaseSync, lines: SeedLine[]): void {
db.exec(` db.exec(`
@@ -82,12 +68,16 @@ function seed(db: DatabaseSync, lines: SeedLine[]): void {
`); `);
} }
function createDb(lines: SeedLine[]): { db: DatabaseSync; dbPath: string } { /**
const dbPath = makeDbPath(); * These tests exercise the cleanup SQL, not durability. A fresh on-disk database per
const db = new Database(dbPath); * test pays a schema-creation fsync that is cheap on a local NVMe but slow enough on CI
* runners to blow the 5s per-test timeout, so the database stays in memory.
*/
function createDb(lines: SeedLine[]): { db: DatabaseSync } {
const db = new Database(':memory:');
ensureSchema(db); ensureSchema(db);
seed(db, lines); seed(db, lines);
return { db, dbPath }; return { db };
} }
/** A typeset line mpv reported once per animation frame. */ /** A typeset line mpv reported once per animation frame. */
@@ -119,7 +109,7 @@ function wordFrequency(db: DatabaseSync): number {
} }
test('a karaoke burst collapses to one line and gives back its word counts', () => { test('a karaoke burst collapses to one line and gives back its word counts', () => {
const { db, dbPath } = createDb([ const { db } = createDb([
...karaokeFrames(1, '飛び上がる', 10_000, 40, 40), ...karaokeFrames(1, '飛び上がる', 10_000, 40, 40),
{ session: 1, text: 'おはよう', startMs: 20_000, endMs: 22_000 }, { session: 1, text: 'おはよう', startMs: 20_000, endMs: 22_000 },
]); ]);
@@ -148,7 +138,6 @@ test('a karaoke burst collapses to one line and gives back its word counts', ()
assert.equal(summary.samples[0]!.videoTitle, 'Ep 1'); assert.equal(summary.samples[0]!.videoTitle, 'Ep 1');
} finally { } finally {
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
@@ -160,7 +149,7 @@ test('ordinary repeated dialogue survives', () => {
startMs: 5_000 + index * 800, startMs: 5_000 + index * 800,
endMs: 5_000 + (index + 1) * 800, endMs: 5_000 + (index + 1) * 800,
})); }));
const { db, dbPath } = createDb(lines); const { db } = createDb(lines);
try { try {
const summary = cleanupDuplicateSubtitleLines(db); const summary = cleanupDuplicateSubtitleLines(db);
@@ -171,14 +160,13 @@ test('ordinary repeated dialogue survives', () => {
assert.equal(wordFrequency(db), 6); assert.equal(wordFrequency(db), 6);
} finally { } finally {
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
test('a long run of quarter-second frames is still a burst', () => { test('a long run of quarter-second frames is still a burst', () => {
// Between the timing-only bound (0.1s) and the animation-frame bound (0.3s): heavier // Between the timing-only bound (0.1s) and the animation-frame bound (0.3s): heavier
// typesetting lands here, and the run length is what makes it conclusive. // typesetting lands here, and the run length is what makes it conclusive.
const { db, dbPath } = createDb(karaokeFrames(1, '飛び上がる', 10_000, 6, 250)); const { db } = createDb(karaokeFrames(1, '飛び上がる', 10_000, 6, 250));
try { try {
const summary = cleanupDuplicateSubtitleLines(db); const summary = cleanupDuplicateSubtitleLines(db);
@@ -189,12 +177,11 @@ test('a long run of quarter-second frames is still a burst', () => {
assert.equal(wordFrequency(db), 1); assert.equal(wordFrequency(db), 1);
} finally { } finally {
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
test('a qualifying short-frame burst may end with one long hold frame', () => { test('a qualifying short-frame burst may end with one long hold frame', () => {
const { db, dbPath } = createDb([ const { db } = createDb([
...karaokeFrames(1, '飛び上がる', 10_000, 8, 40), ...karaokeFrames(1, '飛び上がる', 10_000, 8, 40),
{ session: 1, text: '飛び上がる', startMs: 10_320, endMs: 12_320 }, { session: 1, text: '飛び上がる', startMs: 10_320, endMs: 12_320 },
]); ]);
@@ -208,12 +195,11 @@ test('a qualifying short-frame burst may end with one long hold frame', () => {
assert.equal(wordFrequency(db), 1); assert.equal(wordFrequency(db), 1);
} finally { } finally {
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
test('a long event before the final frame prevents burst cleanup', () => { test('a long event before the final frame prevents burst cleanup', () => {
const { db, dbPath } = createDb([ const { db } = createDb([
...karaokeFrames(1, '飛び上がる', 10_000, 5, 40), ...karaokeFrames(1, '飛び上がる', 10_000, 5, 40),
{ session: 1, text: '飛び上がる', startMs: 10_200, endMs: 12_200 }, { session: 1, text: '飛び上がる', startMs: 10_200, endMs: 12_200 },
{ session: 1, text: '飛び上がる', startMs: 12_200, endMs: 12_240 }, { session: 1, text: '飛び上がる', startMs: 12_200, endMs: 12_240 },
@@ -226,12 +212,11 @@ test('a long event before the final frame prevents burst cleanup', () => {
assert.equal(countLines(db), 7); assert.equal(countLines(db), 7);
} finally { } finally {
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
test('a run of frames longer than the animation bound survives', () => { test('a run of frames longer than the animation bound survives', () => {
const { db, dbPath } = createDb(karaokeFrames(1, '飛び上がる', 10_000, 6, 400)); const { db } = createDb(karaokeFrames(1, '飛び上がる', 10_000, 6, 400));
try { try {
const summary = cleanupDuplicateSubtitleLines(db); const summary = cleanupDuplicateSubtitleLines(db);
@@ -240,7 +225,6 @@ test('a run of frames longer than the animation bound survives', () => {
assert.equal(countLines(db), 6); assert.equal(countLines(db), 6);
} finally { } finally {
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
@@ -248,7 +232,7 @@ test('the four-frame residue the live gate stores is cleaned up', () => {
// The streaming gate records the first four frames of a burst before the run is long // The streaming gate records the first four frames of a burst before the run is long
// enough to recognise. Four contiguous identical events under the strict timing-only // enough to recognise. Four contiguous identical events under the strict timing-only
// bound are that residue, and no real dialogue. // bound are that residue, and no real dialogue.
const { db, dbPath } = createDb(karaokeFrames(1, '飛び上がる', 1_000, 4, 40)); const { db } = createDb(karaokeFrames(1, '飛び上がる', 1_000, 4, 40));
try { try {
const summary = cleanupDuplicateSubtitleLines(db); const summary = cleanupDuplicateSubtitleLines(db);
@@ -259,14 +243,13 @@ test('the four-frame residue the live gate stores is cleaned up', () => {
assert.equal(wordFrequency(db), 1); assert.equal(wordFrequency(db), 1);
} finally { } finally {
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
test('a four-frame run above the strict frame bound survives', () => { test('a four-frame run above the strict frame bound survives', () => {
// Long enough per event to be plausible dialogue; only a five-event run may use the // Long enough per event to be plausible dialogue; only a five-event run may use the
// looser animation-frame bound. // looser animation-frame bound.
const { db, dbPath } = createDb(karaokeFrames(1, '飛び上がる', 1_000, 4, 250)); const { db } = createDb(karaokeFrames(1, '飛び上がる', 1_000, 4, 250));
try { try {
const summary = cleanupDuplicateSubtitleLines(db); const summary = cleanupDuplicateSubtitleLines(db);
@@ -275,14 +258,13 @@ test('a four-frame run above the strict frame bound survives', () => {
assert.equal(countLines(db), 4); assert.equal(countLines(db), 4);
} finally { } finally {
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
test('an explicit minRunLength raises the bar', () => { test('an explicit minRunLength raises the bar', () => {
// Five quarter-second frames qualify under the defaults; a cautious run asking for six // Five quarter-second frames qualify under the defaults; a cautious run asking for six
// leaves them alone. Above the strict bound, so the residue rule stays out of it. // leaves them alone. Above the strict bound, so the residue rule stays out of it.
const { db, dbPath } = createDb(karaokeFrames(1, '飛び上がる', 10_000, 5, 250)); const { db } = createDb(karaokeFrames(1, '飛び上がる', 10_000, 5, 250));
try { try {
const preview = cleanupDuplicateSubtitleLines(db, { dryRun: true }); const preview = cleanupDuplicateSubtitleLines(db, { dryRun: true });
@@ -293,12 +275,11 @@ test('an explicit minRunLength raises the bar', () => {
assert.equal(countLines(db), 5); assert.equal(countLines(db), 5);
} finally { } finally {
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
test('an explicit maxFrameSeconds tightens the frame bound', () => { test('an explicit maxFrameSeconds tightens the frame bound', () => {
const { db, dbPath } = createDb(karaokeFrames(1, '飛び上がる', 10_000, 6, 250)); const { db } = createDb(karaokeFrames(1, '飛び上がる', 10_000, 6, 250));
try { try {
const summary = cleanupDuplicateSubtitleLines(db, { maxFrameSeconds: 0.2 }); const summary = cleanupDuplicateSubtitleLines(db, { maxFrameSeconds: 0.2 });
@@ -307,13 +288,12 @@ test('an explicit maxFrameSeconds tightens the frame bound', () => {
assert.equal(countLines(db), 6); assert.equal(countLines(db), 6);
} finally { } finally {
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
test('a non-finite maxFrameSeconds falls back to the default bound', () => { test('a non-finite maxFrameSeconds falls back to the default bound', () => {
// Six normal-beat lines: Infinity must not turn every event into a "short frame". // Six normal-beat lines: Infinity must not turn every event into a "short frame".
const { db, dbPath } = createDb(karaokeFrames(1, '飛び上がる', 10_000, 6, 800)); const { db } = createDb(karaokeFrames(1, '飛び上がる', 10_000, 6, 800));
try { try {
const summary = cleanupDuplicateSubtitleLines(db, { maxFrameSeconds: Infinity }); const summary = cleanupDuplicateSubtitleLines(db, { maxFrameSeconds: Infinity });
@@ -322,12 +302,11 @@ test('a non-finite maxFrameSeconds falls back to the default bound', () => {
assert.equal(countLines(db), 6); assert.equal(countLines(db), 6);
} finally { } finally {
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
test('sampleLimit zero removes bursts but reports no samples', () => { test('sampleLimit zero removes bursts but reports no samples', () => {
const { db, dbPath } = createDb(karaokeFrames(1, '飛び上がる', 10_000, 40, 40)); const { db } = createDb(karaokeFrames(1, '飛び上がる', 10_000, 40, 40));
try { try {
const summary = cleanupDuplicateSubtitleLines(db, { sampleLimit: 0 }); const summary = cleanupDuplicateSubtitleLines(db, { sampleLimit: 0 });
@@ -337,12 +316,11 @@ test('sampleLimit zero removes bursts but reports no samples', () => {
assert.equal(countLines(db), 1); assert.equal(countLines(db), 1);
} finally { } finally {
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
test('a short run below every threshold survives', () => { test('a short run below every threshold survives', () => {
const { db, dbPath } = createDb(karaokeFrames(1, '飛び上がる', 1_000, 3, 40)); const { db } = createDb(karaokeFrames(1, '飛び上がる', 1_000, 3, 40));
try { try {
const summary = cleanupDuplicateSubtitleLines(db); const summary = cleanupDuplicateSubtitleLines(db);
@@ -351,7 +329,6 @@ test('a short run below every threshold survives', () => {
assert.equal(countLines(db), 3); assert.equal(countLines(db), 3);
} finally { } finally {
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
@@ -361,7 +338,7 @@ test('interleaved dual-line karaoke collapses each line to one row', () => {
const kanji = karaokeFrames(1, '飛び上がる', 10_000, 20, 60); const kanji = karaokeFrames(1, '飛び上がる', 10_000, 20, 60);
const romaji = karaokeFrames(1, 'tobiagaru', 10_001, 20, 60); const romaji = karaokeFrames(1, 'tobiagaru', 10_001, 20, 60);
const interleaved = [...kanji, ...romaji].sort((a, b) => a.startMs - b.startMs); const interleaved = [...kanji, ...romaji].sort((a, b) => a.startMs - b.startMs);
const { db, dbPath } = createDb(interleaved); const { db } = createDb(interleaved);
try { try {
const summary = cleanupDuplicateSubtitleLines(db); const summary = cleanupDuplicateSubtitleLines(db);
@@ -372,12 +349,11 @@ test('interleaved dual-line karaoke collapses each line to one row', () => {
assert.equal(wordFrequency(db), 2); assert.equal(wordFrequency(db), 2);
} finally { } finally {
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
test('the same line in a rewatch session is never merged into the first watch', () => { test('the same line in a rewatch session is never merged into the first watch', () => {
const { db, dbPath } = createDb([ const { db } = createDb([
...karaokeFrames(1, '飛び上がる', 10_000, 6, 40), ...karaokeFrames(1, '飛び上がる', 10_000, 6, 40),
...karaokeFrames(2, '飛び上がる', 10_000, 6, 40), ...karaokeFrames(2, '飛び上がる', 10_000, 6, 40),
]); ]);
@@ -392,12 +368,11 @@ test('the same line in a rewatch session is never merged into the first watch',
assert.equal(wordFrequency(db), 2); assert.equal(wordFrequency(db), 2);
} finally { } finally {
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
test('a gap between runs splits them', () => { test('a gap between runs splits them', () => {
const { db, dbPath } = createDb([ const { db } = createDb([
...karaokeFrames(1, '飛び上がる', 10_000, 6, 40), ...karaokeFrames(1, '飛び上がる', 10_000, 6, 40),
...karaokeFrames(1, '飛び上がる', 60_000, 6, 40), ...karaokeFrames(1, '飛び上がる', 60_000, 6, 40),
]); ]);
@@ -409,12 +384,11 @@ test('a gap between runs splits them', () => {
assert.equal(countLines(db), 2); assert.equal(countLines(db), 2);
} finally { } finally {
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
test('a dry run reports what an apply would do and writes nothing', () => { test('a dry run reports what an apply would do and writes nothing', () => {
const { db, dbPath } = createDb(karaokeFrames(1, '飛び上がる', 10_000, 40, 40)); const { db } = createDb(karaokeFrames(1, '飛び上がる', 10_000, 40, 40));
try { try {
const preview = cleanupDuplicateSubtitleLines(db, { dryRun: true }); const preview = cleanupDuplicateSubtitleLines(db, { dryRun: true });
@@ -430,14 +404,13 @@ test('a dry run reports what an apply would do and writes nothing', () => {
assert.equal(countLines(db), 1); assert.equal(countLines(db), 1);
} finally { } finally {
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
test('the lookback window leaves older bursts alone', () => { test('the lookback window leaves older bursts alone', () => {
const recentMs = BASE_MS; const recentMs = BASE_MS;
const oldMs = BASE_MS - 40 * DAY_MS; const oldMs = BASE_MS - 40 * DAY_MS;
const { db, dbPath } = createDb([ const { db } = createDb([
...karaokeFrames(1, '飛び上がる', 10_000, 6, 40).map((line) => ({ ...karaokeFrames(1, '飛び上がる', 10_000, 6, 40).map((line) => ({
...line, ...line,
createdMs: oldMs, createdMs: oldMs,
@@ -462,6 +435,5 @@ test('the lookback window leaves older bursts alone', () => {
} finally { } finally {
globalThis.__subminerTestNowMs = undefined; globalThis.__subminerTestNowMs = undefined;
db.close(); db.close();
cleanupDbPath(dbPath);
} }
}); });
@@ -31,6 +31,7 @@ import {
getKanjiOccurrences, getKanjiOccurrences,
getSessionSummaries, getSessionSummaries,
getVocabularyStats, getVocabularyStats,
getVocabularySummary,
getKanjiStats, getKanjiStats,
getSessionEvents, getSessionEvents,
getSessionTimeline, getSessionTimeline,
@@ -1875,6 +1876,115 @@ test('getVocabularyStats returns rows ordered by frequency descending', () => {
} }
}); });
test('getVocabularySummary counts every tracked vocabulary row instead of a display page', () => {
const dbPath = makeDbPath();
const db = openTestDb(dbPath);
try {
ensureSchema(db);
const nowSec = Math.floor(Date.now() / 1000);
const insertWord = db.prepare(`
INSERT INTO imm_words (
headword, word, reading, part_of_speech, pos1, pos2, pos3,
first_seen, last_seen, frequency
) VALUES (?, ?, '', 'noun', '名詞', '一般', '', ?, ?, 1)
`);
const insertKanji = db.prepare(`
INSERT INTO imm_kanji (kanji, first_seen, last_seen, frequency)
VALUES (?, ?, ?, 1)
`);
for (let index = 0; index < 501; index += 1) {
insertWord.run(`単語${index}`, `単語${index}`, nowSec - 8 * 86_400, nowSec - 8 * 86_400);
}
for (let index = 0; index < 201; index += 1) {
insertKanji.run(
String.fromCodePoint(0x4e00 + index),
nowSec - 8 * 86_400,
nowSec - 8 * 86_400,
);
}
insertWord.run('今週', '今週', nowSec - 86_400, nowSec - 86_400);
assert.deepEqual(getVocabularySummary(db, new Set(['単語0', '今週']), nowSec * 1000), {
uniqueWords: 502,
uniqueWordsWithoutNames: 502,
uniqueKanji: 201,
newThisWeek: 1,
newThisWeekWithoutNames: 1,
knownWordCount: 2,
knownWordCountWithoutNames: 2,
});
} finally {
db.close();
cleanupDbPath(dbPath);
}
});
test('getVocabularySummary applies vocabulary exclusions and Hide Names totals', () => {
const dbPath = makeDbPath();
const db = openTestDb(dbPath);
try {
ensureSchema(db);
const insertWord = db.prepare(`
INSERT INTO imm_words (
headword, word, reading, part_of_speech, pos1, pos2, pos3,
first_seen, last_seen, frequency
) VALUES (?, ?, '', 'noun', '名詞', ?, '', 1, 1, 1)
`);
insertWord.run('猫', '猫', '一般');
insertWord.run('太郎', '太郎', '固有名詞');
insertWord.run('東京', '東京都', '一般');
db.prepare(
`
INSERT INTO imm_stats_excluded_words (headword, word, reading)
VALUES ('東京', '東京', '')
`,
).run();
assert.deepEqual(getVocabularySummary(db, new Set(['猫', '太郎', '東京']), 9 * 86_400_000), {
uniqueWords: 2,
uniqueWordsWithoutNames: 1,
uniqueKanji: 0,
newThisWeek: 0,
newThisWeekWithoutNames: 0,
knownWordCount: 2,
knownWordCountWithoutNames: 1,
});
} finally {
db.close();
cleanupDbPath(dbPath);
}
});
test('getVocabularySummary counts identically across id-keyed scan batches', () => {
const dbPath = makeDbPath();
const db = openTestDb(dbPath);
try {
ensureSchema(db);
const insertWord = db.prepare(`
INSERT INTO imm_words (
headword, word, reading, part_of_speech, pos1, pos2, pos3,
first_seen, last_seen, frequency
) VALUES (?, ?, '', 'noun', '名詞', '一般', '', 1, 1, 1)
`);
for (let index = 0; index < 5; index += 1) {
insertWord.run(`単語${index}`, `単語${index}`);
}
const fullScan = getVocabularySummary(db, new Set(['単語0']), 9 * 86_400_000);
const batchedScan = getVocabularySummary(db, new Set(['単語0']), 9 * 86_400_000, 2);
assert.equal(fullScan.uniqueWords, 5);
assert.deepEqual(batchedScan, fullScan);
} finally {
db.close();
cleanupDbPath(dbPath);
}
});
test('getVocabularyStats filters rows that fail tokenizer vocabulary rules', () => { test('getVocabularyStats filters rows that fail tokenizer vocabulary rules', () => {
const dbPath = makeDbPath(); const dbPath = makeDbPath();
const db = openTestDb(dbPath); const db = openTestDb(dbPath);
@@ -0,0 +1,136 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import {
LexicalRollupWorkerRuntime,
resolveLexicalRollupWorkerPath,
} from './lexical-rollup-worker-runtime';
import { areLexicalDailyRollupsReady } from './lexical-rollups';
import { Database } from './sqlite';
import { applyPragmas, ensureSchema } from './storage';
test('lexical rollup worker backfills without using the tracker connection', async () => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-lexical-rollup-runtime-'));
const dbPath = path.join(directory, 'immersion.sqlite');
const runtime = new LexicalRollupWorkerRuntime();
const db = new Database(dbPath);
try {
applyPragmas(db);
ensureSchema(db);
db.prepare(
`INSERT INTO imm_words(headword, word, reading, first_seen, last_seen, frequency)
VALUES ('鳥', '鳥', 'とり', 1700000000, 1700000000, 1)`,
).run();
db.exec('DELETE FROM imm_lexical_daily_rollups');
db.prepare(`UPDATE imm_rollup_state SET state_value = '0' WHERE state_key = ?`).run(
'lexical_daily_rollups_version',
);
db.close();
await runtime.run(dbPath);
const checkDb = new Database(dbPath);
try {
assert.equal(areLexicalDailyRollupsReady(checkDb), true);
} finally {
checkDb.close();
}
} finally {
runtime.destroy();
try {
db.close();
} catch {
// Closed before the worker starts.
}
fs.rmSync(directory, { recursive: true, force: true });
}
});
test('lexical rollup worker module resolves in the current layout', () => {
const workerPath = resolveLexicalRollupWorkerPath();
assert.ok(workerPath, 'expected the lexical rollup worker module to resolve');
assert.ok(workerPath.endsWith(__filename.endsWith('.ts') ? '.ts' : '.js'));
});
test('lexical rollup worker leaves a backfill pending when no worker can start', async () => {
const runtime = new LexicalRollupWorkerRuntime({
resolveWorkerPath: () => null,
warn: () => {},
} as never);
try {
await assert.doesNotReject(runtime.run('/tmp/not-used.sqlite'));
} finally {
runtime.destroy();
}
});
test('lexical rollup worker absorbs termination failures after settling', async () => {
let sendMessage: ((message: { ok: boolean }) => void) | null = null;
const runtime = new LexicalRollupWorkerRuntime({
resolveWorkerPath: () => '/tmp/fake-worker.js',
createWorker: async () => ({
once(event: string, listener: (value: never) => void) {
if (event === 'message') sendMessage = listener as (message: { ok: boolean }) => void;
return this;
},
terminate: async () => {
throw new Error('termination failed');
},
}),
warn: () => {},
} as never);
const unhandled: unknown[] = [];
const captureUnhandled = (reason: unknown) => unhandled.push(reason);
process.on('unhandledRejection', captureUnhandled);
try {
const task = runtime.run('/tmp/not-used.sqlite');
await new Promise((resolve) => setImmediate(resolve));
const notify = sendMessage as ((message: { ok: boolean }) => void) | null;
assert.ok(notify);
notify({ ok: true });
await task;
await new Promise((resolve) => setImmediate(resolve));
assert.deepEqual(unhandled, []);
} finally {
process.off('unhandledRejection', captureUnhandled);
runtime.destroy();
}
});
test('lexical rollup worker times out when it never responds', async () => {
let terminated = false;
const runtime = new LexicalRollupWorkerRuntime({
resolveWorkerPath: () => '/tmp/fake-worker.js',
createWorker: async () => ({
once() {
return this;
},
terminate: async () => {
terminated = true;
return 0;
},
}),
timeoutMs: 1,
warn: () => {},
} as never);
try {
const outcome = await Promise.race([
runtime.run('/tmp/not-used.sqlite').then(
() => 'resolved',
(error: unknown) => String(error),
),
new Promise<string>((resolve) => setTimeout(() => resolve('still pending'), 50)),
]);
assert.match(outcome, /timed out/);
assert.equal(terminated, true);
} finally {
runtime.destroy();
}
});
@@ -0,0 +1,117 @@
import fs from 'node:fs';
import path from 'node:path';
import { createLogger } from '../../../logger';
interface WorkerResponse {
ok?: boolean;
error?: unknown;
}
interface WorkerHandle {
once(event: 'message', listener: (message: WorkerResponse) => void): this;
once(event: 'error', listener: (error: Error) => void): this;
once(event: 'exit', listener: (code: number) => void): this;
terminate(): Promise<number>;
}
interface LexicalRollupWorkerRuntimeOptions {
resolveWorkerPath?: () => string | null;
createWorker?: (workerPath: string, workerData: { dbPath: string }) => Promise<WorkerHandle>;
timeoutMs?: number;
warn?: (message: string, ...meta: unknown[]) => void;
}
const logger = createLogger('main:immersion-tracker:lexical-rollup-worker');
const DEFAULT_WORKER_TIMEOUT_MS = 5 * 60 * 1_000;
export function resolveLexicalRollupWorkerPath(): string | null {
const fileName = __filename.endsWith('.ts')
? 'lexical-rollup-worker-thread.ts'
: 'lexical-rollup-worker-thread.js';
const workerPath = path.join(__dirname, fileName);
return fs.existsSync(workerPath) ? workerPath : null;
}
export class LexicalRollupWorkerRuntime {
private readonly activeWorkers = new Set<WorkerHandle>();
private destroyed = false;
constructor(private readonly options: LexicalRollupWorkerRuntimeOptions = {}) {}
async run(dbPath: string): Promise<void> {
if (this.destroyed) throw new Error('Lexical rollup worker is shut down');
let worker: WorkerHandle;
try {
const workerPath = (this.options.resolveWorkerPath ?? resolveLexicalRollupWorkerPath)();
if (!workerPath) throw new Error('Emitted lexical rollup worker module was not found');
const createWorker =
this.options.createWorker ??
(async (resolvedPath, workerData) => {
const { Worker } = await import('node:worker_threads');
return new Worker(resolvedPath, { workerData });
});
worker = await createWorker(workerPath, { dbPath });
} catch (error) {
if (this.destroyed) throw new Error('Lexical rollup worker is shut down');
(this.options.warn ?? logger.warn)(
'Lexical rollup worker unavailable; leaving backfill pending for a later startup',
error,
);
return;
}
if (this.destroyed) {
await worker.terminate().catch(() => undefined);
throw new Error('Lexical rollup worker is shut down');
}
return new Promise<void>((resolve, reject) => {
let settled = false;
let timeout: ReturnType<typeof setTimeout> | null = null;
this.activeWorkers.add(worker);
const settle = (error?: Error) => {
if (settled) return;
settled = true;
if (timeout) clearTimeout(timeout);
this.activeWorkers.delete(worker);
void worker.terminate().catch(() => undefined);
if (error) reject(error);
else resolve();
};
timeout = setTimeout(
() => settle(new Error('Lexical rollup worker timed out')),
this.options.timeoutMs ?? DEFAULT_WORKER_TIMEOUT_MS,
);
worker.once('message', (message) => {
if (message.ok) settle();
else
settle(
new Error(
`Lexical rollup backfill failed: ${String(message.error ?? 'unknown error')}`,
),
);
});
worker.once('error', (error) => settle(error));
worker.once('exit', (code) => {
if (!settled) {
settle(
new Error(
code === 0
? 'Lexical rollup worker exited without a response'
: `Lexical rollup worker exited with code ${code}`,
),
);
}
});
});
}
destroy(): void {
if (this.destroyed) return;
this.destroyed = true;
for (const worker of this.activeWorkers) {
void worker.terminate().catch(() => undefined);
}
this.activeWorkers.clear();
}
}
@@ -0,0 +1,11 @@
import { parentPort, workerData } from 'node:worker_threads';
import { executeLexicalRollupBackfillTask } from './lexical-rollup-worker';
if (!parentPort) throw new Error('lexical rollup worker missing parent port');
try {
executeLexicalRollupBackfillTask((workerData as { dbPath: string }).dbPath);
parentPort.postMessage({ ok: true });
} catch (error) {
parentPort.postMessage({ error: error instanceof Error ? error.message : String(error) });
}
@@ -0,0 +1,35 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { areLexicalDailyRollupsReady, getLexicalDailyRollups } from './lexical-rollups';
import { executeLexicalRollupBackfillTask } from './lexical-rollup-worker';
import { Database } from './sqlite';
import { ensureSchema } from './storage';
test('lexical rollup backfill materializes pre-existing vocabulary off the caller DB connection', () => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-lexical-rollup-worker-'));
const dbPath = path.join(directory, 'immersion.sqlite');
const db = new Database(dbPath);
try {
ensureSchema(db);
db.prepare(
`INSERT INTO imm_words(headword, word, reading, first_seen, last_seen, frequency)
VALUES (?, ?, ?, ?, ?, 1)`,
).run('犬', '犬', 'いぬ', 1_700_000_000, 1_700_000_000);
db.exec('DELETE FROM imm_lexical_daily_rollups');
db.prepare(`UPDATE imm_rollup_state SET state_value = '0' WHERE state_key = ?`).run(
'lexical_daily_rollups_version',
);
executeLexicalRollupBackfillTask(dbPath);
assert.equal(areLexicalDailyRollupsReady(db), true);
assert.equal(getLexicalDailyRollups(db)[0]?.wordCount, 1);
} finally {
db.close();
fs.rmSync(directory, { recursive: true, force: true });
}
});
@@ -0,0 +1,15 @@
import { areLexicalDailyRollupsReady, rebuildLexicalDailyRollups } from './lexical-rollups';
import { Database } from './sqlite';
import { applyPragmas } from './storage';
export function executeLexicalRollupBackfillTask(dbPath: string): void {
const db = new Database(dbPath);
try {
applyPragmas(db);
if (!areLexicalDailyRollupsReady(db)) {
rebuildLexicalDailyRollups(db);
}
} finally {
db.close();
}
}
@@ -0,0 +1,421 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import {
areLexicalDailyRollupsReady,
getLexicalDailyRollups,
rebuildLexicalDailyRollups,
} from './lexical-rollups';
import { getTrendsDashboard } from './query-trends';
import {
getVocabularyChartData,
getVocabularySummary,
replaceStatsExcludedWords,
} from './query-lexical';
import { Database } from './sqlite';
import type { DatabaseSync } from './sqlite';
import { ensureSchema } from './storage';
function makeDbPath(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-lexical-rollups-'));
return path.join(dir, 'immersion.sqlite');
}
test('lexical daily rollups follow first-seen corrections and deletions', () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
try {
ensureSchema(db);
const firstDay = 19_500;
const correctedDay = firstDay + 2;
const firstSeen = firstDay * 86_400 + 43_200;
const correctedSeen = correctedDay * 86_400 + 43_200;
db.prepare(
`INSERT INTO imm_words(headword, word, reading, first_seen, last_seen, frequency)
VALUES (?, ?, ?, ?, ?, 1)`,
).run('猫', '猫', 'ねこ', firstSeen, firstSeen);
db.prepare(
`INSERT INTO imm_kanji(kanji, first_seen, last_seen, frequency)
VALUES (?, ?, ?, 1)`,
).run('猫', firstSeen, firstSeen);
assert.deepEqual(getLexicalDailyRollups(db), [
{ epochDay: firstDay, wordCount: 1, wordCountWithoutNames: 1, kanjiCount: 1 },
]);
db.prepare(`UPDATE imm_words SET first_seen = ? WHERE headword = ?`).run(correctedSeen, '猫');
db.prepare(`DELETE FROM imm_kanji WHERE kanji = ?`).run('猫');
assert.deepEqual(getLexicalDailyRollups(db), [
{ epochDay: correctedDay, wordCount: 1, wordCountWithoutNames: 1, kanjiCount: 0 },
]);
} finally {
db.close();
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
}
});
test('lexical daily rollups normalize second and millisecond timestamps', () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
try {
ensureSchema(db);
const epochDay = 19_500;
const timestampSeconds = epochDay * 86_400 + 43_200;
const timestampMilliseconds = timestampSeconds * 1_000;
db.prepare(
`INSERT INTO imm_words(headword, word, reading, first_seen, last_seen, frequency)
VALUES (?, ?, ?, ?, ?, 1)`,
).run('猫', '猫', 'ねこ', timestampSeconds, timestampSeconds);
db.prepare(
`INSERT INTO imm_words(headword, word, reading, first_seen, last_seen, frequency)
VALUES (?, ?, ?, ?, ?, 1)`,
).run('犬', '犬', 'いぬ', timestampMilliseconds, timestampMilliseconds);
db.prepare(
`INSERT INTO imm_kanji(kanji, first_seen, last_seen, frequency)
VALUES (?, ?, ?, 1)`,
).run('猫', timestampSeconds, timestampSeconds);
db.prepare(
`INSERT INTO imm_kanji(kanji, first_seen, last_seen, frequency)
VALUES (?, ?, ?, 1)`,
).run('犬', timestampMilliseconds, timestampMilliseconds);
assert.deepEqual(getLexicalDailyRollups(db), [
{ epochDay, wordCount: 2, wordCountWithoutNames: 2, kanjiCount: 2 },
]);
} finally {
db.close();
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
}
});
test('lexical rollup rebuild excludes rows hidden by vocabulary persistence rules', () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
try {
ensureSchema(db);
const epochDay = 19_500;
const firstSeen = epochDay * 86_400 + 43_200;
db.prepare(
`INSERT INTO imm_words(
headword, word, reading, part_of_speech, first_seen, last_seen, frequency
) VALUES (?, ?, ?, ?, ?, ?, 1)`,
).run('猫', '猫', 'ねこ', 'noun', firstSeen, firstSeen);
db.prepare(
`INSERT INTO imm_words(
headword, word, reading, part_of_speech, first_seen, last_seen, frequency
) VALUES (?, ?, ?, ?, ?, ?, 1)`,
).run('は', 'は', 'は', 'particle', firstSeen, firstSeen);
rebuildLexicalDailyRollups(db);
assert.deepEqual(getLexicalDailyRollups(db), [
{ epochDay, wordCount: 1, wordCountWithoutNames: 1, kanjiCount: 0 },
]);
} finally {
db.close();
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
}
});
test('lexical rollup rebuild tolerates nullable legacy vocabulary text', () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
try {
ensureSchema(db);
db.prepare(
`INSERT INTO imm_words(headword, word, reading, first_seen, last_seen, frequency)
VALUES (NULL, NULL, NULL, 1700000000, 1700000000, 1)`,
).run();
db.prepare(
`INSERT INTO imm_words(headword, word, reading, first_seen, last_seen, frequency)
VALUES (NULL, '猫', 'ねこ', 1700000000, 1700000000, 1)`,
).run();
assert.doesNotThrow(() => rebuildLexicalDailyRollups(db));
assert.equal(areLexicalDailyRollupsReady(db), true);
assert.equal(getVocabularySummary(db, null).uniqueWords, 1);
assert.equal(getVocabularySummary(db, new Set(['猫'])).knownWordCount, 1);
assert.equal(getVocabularyChartData(db).topWords[0]?.headword, '猫');
} finally {
db.close();
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
}
});
test('lexical rollup rebuild scans vocabulary visibility in bounded id batches', () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
const expectedBatchSize = 5_000;
try {
ensureSchema(db);
const insertWord = db.prepare(
`INSERT INTO imm_words(headword, word, reading, first_seen, last_seen, frequency)
VALUES (?, ?, '', 1700000000, 1700000000, 1)`,
);
db.exec('BEGIN');
for (let index = 0; index <= expectedBatchSize; index += 1) {
insertWord.run(`${index}`, `${index}`);
}
db.exec('COMMIT');
const scanPageSizes: number[] = [];
const instrumentedDb: DatabaseSync = {
prepare(source) {
const statement = db.prepare(source);
if (!source.includes('WHERE id > ?') || !source.includes('ORDER BY id')) {
return statement;
}
return {
run: (...params) => statement.run(...params),
get: (...params) => statement.get(...params),
all: (...params) => {
const rows = statement.all(...params);
scanPageSizes.push(rows.length);
return rows;
},
};
},
exec(source) {
db.exec(source);
return instrumentedDb;
},
close() {
return instrumentedDb;
},
};
rebuildLexicalDailyRollups(instrumentedDb);
assert.deepEqual(scanPageSizes, [expectedBatchSize, 1]);
assert.equal(getVocabularySummary(db, null).uniqueWords, expectedBatchSize + 1);
} finally {
db.close();
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
}
});
test('chart exclusions do not subtract vocabulary rows already hidden from the rollup', () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
try {
ensureSchema(db);
const epochDay = 19_500;
const firstSeen = epochDay * 86_400 + 43_200;
db.prepare(
`INSERT INTO imm_words(
headword, word, reading, part_of_speech, first_seen, last_seen, frequency
) VALUES (?, ?, ?, ?, ?, ?, 1)`,
).run('猫', '猫', 'ねこ', 'noun', firstSeen, firstSeen);
db.prepare(
`INSERT INTO imm_words(
headword, word, reading, part_of_speech, first_seen, last_seen, frequency
) VALUES (?, ?, ?, ?, ?, ?, 1)`,
).run('は', 'は', 'は', 'particle', firstSeen, firstSeen);
rebuildLexicalDailyRollups(db);
replaceStatsExcludedWords(db, [{ headword: 'は', word: 'は', reading: 'は' }]);
const charts = getVocabularyChartData(db);
assert.deepEqual(charts.newWordsTimeline, [{ epochDay, wordCount: 1 }]);
assert.deepEqual(charts.newWordsTimelineWithoutNames, [{ epochDay, wordCount: 1 }]);
} finally {
db.close();
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
}
});
test('legacy lexical rollup readiness does not satisfy the current rollup version', () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
try {
ensureSchema(db);
db.prepare(
`INSERT INTO imm_rollup_state(state_key, state_value)
VALUES ('lexical_daily_rollups_ready', '1')
ON CONFLICT(state_key) DO UPDATE SET state_value = excluded.state_value`,
).run();
db.prepare(
`DELETE FROM imm_rollup_state WHERE state_key = 'lexical_daily_rollups_version'`,
).run();
assert.equal(areLexicalDailyRollupsReady(db), false);
} finally {
db.close();
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
}
});
test('current lexical rollup readiness accepts legacy integer state storage', () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
try {
db.exec(`
CREATE TABLE imm_rollup_state(
state_key TEXT PRIMARY KEY,
state_value INTEGER NOT NULL
);
INSERT INTO imm_rollup_state(state_key, state_value)
VALUES ('lexical_daily_rollups_version', 2);
`);
assert.equal(areLexicalDailyRollupsReady(db), true);
} finally {
db.close();
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
}
});
test('imm_words persists vocabulary visibility for rollup maintenance', () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
try {
ensureSchema(db);
const columns = db.prepare(`PRAGMA table_info(imm_words)`).all() as Array<{ name: string }>;
assert.equal(
columns.some((column) => column.name === 'vocabulary_visible'),
true,
);
} finally {
db.close();
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
}
});
test('vocabulary charts use complete top-word and lexical rollup data', () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
try {
ensureSchema(db);
const insertWord = db.prepare(
`INSERT INTO imm_words(headword, word, reading, first_seen, last_seen, frequency)
VALUES (?, ?, '', 1700000000, 1700000000, ?)`,
);
for (let index = 0; index < 501; index += 1) {
insertWord.run(`${index}`, `${index}`, index === 500 ? 10_000 : 1);
}
const charts = getVocabularyChartData(db);
assert.equal(charts.topWords[0]?.headword, '語500');
assert.equal(charts.topWords[0]?.frequency, 10_000);
assert.equal(charts.newWordsTimeline[0]?.wordCount, 501);
} finally {
db.close();
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
}
});
test('vocabulary charts find full top-word sets beyond excluded and name rows', () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
try {
ensureSchema(db);
const insertWord = db.prepare(
`INSERT INTO imm_words(headword, word, reading, pos2, first_seen, last_seen, frequency)
VALUES (?, ?, '', ?, 1700000000, 1700000000, ?)`,
);
const exclusions = [];
for (let index = 0; index < 100; index += 1) {
const headword = `${index}`;
insertWord.run(
headword,
headword,
index < 80 && index >= 60 ? '固有名詞' : '一般',
100 - index,
);
if (index < 60) exclusions.push({ headword, word: headword, reading: '' });
}
replaceStatsExcludedWords(db, exclusions);
const charts = getVocabularyChartData(db);
assert.equal(charts.topWords.length, 12);
assert.equal(charts.topWords[0]?.headword, '語60');
assert.equal(charts.topWordsWithoutNames.length, 12);
assert.equal(charts.topWordsWithoutNames[0]?.headword, '語80');
} finally {
db.close();
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
}
});
test('vocabulary charts handle exclusion lists above one SQLite variable batch', () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
try {
ensureSchema(db);
db.prepare(
`INSERT INTO imm_words(headword, word, reading, first_seen, last_seen, frequency)
VALUES ('語0', '語0', '', 1700000000, 1700000000, 1)`,
).run();
const exclusions = Array.from({ length: 10_923 }, (_, index) => ({
headword: `${index}`,
word: `${index}`,
reading: '',
}));
replaceStatsExcludedWords(db, exclusions);
const charts = getVocabularyChartData(db);
assert.deepEqual(charts.topWords, []);
assert.deepEqual(charts.newWordsTimeline, []);
} finally {
db.close();
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
}
});
test('lexical rollup rebuild preserves the original error when rollback also fails', () => {
const originalError = new Error('rebuild failed');
const db = {
exec(sql: string) {
if (sql === 'BEGIN IMMEDIATE') return;
if (sql === 'ROLLBACK') throw new Error('rollback failed');
throw originalError;
},
prepare() {
return { all: () => [], run: () => undefined };
},
} as unknown as DatabaseSync;
assert.throws(() => rebuildLexicalDailyRollups(db), originalError);
});
test('trends read historical new-word buckets from lexical rollups', () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
try {
ensureSchema(db);
db.prepare(
`INSERT INTO imm_words(headword, word, reading, first_seen, last_seen, frequency)
VALUES ('海', '海', 'うみ', 1700000000, 1700000000, 1)`,
).run();
db.prepare(`UPDATE imm_lexical_daily_rollups SET word_count = 9`).run();
const dashboard = getTrendsDashboard(db, 'all', 'day', false);
assert.equal(dashboard.progress.newWords[0]?.value, 9);
} finally {
db.close();
fs.rmSync(path.dirname(dbPath), { recursive: true, force: true });
}
});
@@ -0,0 +1,229 @@
import type { DatabaseSync } from './sqlite';
import { isVocabularyStatsRowVisible, type VocabularyVisibilityRow } from './vocabulary-visibility';
export interface LexicalDailyRollup {
epochDay: number;
wordCount: number;
wordCountWithoutNames: number;
kanjiCount: number;
}
const LOCAL_EPOCH_DAY_SQL = `
CAST(julianday(
CASE
WHEN ABS(CAST(%VALUE% AS REAL)) >= 10000000000 THEN CAST(%VALUE% AS REAL) / 1000
ELSE CAST(%VALUE% AS REAL)
END,
'unixepoch', 'localtime'
) - 2440587.5 AS INTEGER)
`;
const LEXICAL_DAILY_ROLLUP_VERSION = '2';
const LEXICAL_DAILY_ROLLUP_VERSION_KEY = 'lexical_daily_rollups_version';
const VOCABULARY_VISIBILITY_SCAN_BATCH_SIZE = 5_000;
export function localEpochDaySql(value: string): string {
return LOCAL_EPOCH_DAY_SQL.replaceAll('%VALUE%', value);
}
function createWordRollupTriggers(db: DatabaseSync): void {
const dayForNew = localEpochDaySql('NEW.first_seen');
const dayForOld = localEpochDaySql('OLD.first_seen');
db.exec(`
DROP TRIGGER IF EXISTS imm_words_lexical_rollup_insert;
DROP TRIGGER IF EXISTS imm_words_lexical_rollup_delete;
DROP TRIGGER IF EXISTS imm_words_lexical_rollup_first_seen_update;
CREATE TRIGGER imm_words_lexical_rollup_insert
AFTER INSERT ON imm_words
WHEN NEW.first_seen IS NOT NULL AND NEW.vocabulary_visible = 1
BEGIN
INSERT INTO imm_lexical_daily_rollups(epoch_day, word_count, word_count_without_names, kanji_count)
VALUES (${dayForNew}, 1, CASE WHEN NEW.pos2 = '固有名詞' THEN 0 ELSE 1 END, 0)
ON CONFLICT(epoch_day) DO UPDATE SET
word_count = word_count + 1,
word_count_without_names = word_count_without_names + excluded.word_count_without_names;
END;
CREATE TRIGGER imm_words_lexical_rollup_delete
AFTER DELETE ON imm_words
WHEN OLD.first_seen IS NOT NULL AND OLD.vocabulary_visible = 1
BEGIN
INSERT INTO imm_lexical_daily_rollups(epoch_day, word_count, word_count_without_names, kanji_count)
VALUES (${dayForOld}, -1, CASE WHEN OLD.pos2 = '固有名詞' THEN 0 ELSE -1 END, 0)
ON CONFLICT(epoch_day) DO UPDATE SET
word_count = word_count - 1,
word_count_without_names = word_count_without_names + excluded.word_count_without_names;
DELETE FROM imm_lexical_daily_rollups
WHERE epoch_day = ${dayForOld} AND word_count = 0 AND kanji_count = 0;
END;
CREATE TRIGGER imm_words_lexical_rollup_first_seen_update
AFTER UPDATE OF first_seen, pos2, vocabulary_visible ON imm_words
WHEN OLD.first_seen IS NOT NEW.first_seen
OR OLD.pos2 IS NOT NEW.pos2
OR OLD.vocabulary_visible IS NOT NEW.vocabulary_visible
BEGIN
INSERT INTO imm_lexical_daily_rollups(epoch_day, word_count, word_count_without_names, kanji_count)
SELECT ${dayForOld}, -1, CASE WHEN OLD.pos2 = '固有名詞' THEN 0 ELSE -1 END, 0
WHERE OLD.first_seen IS NOT NULL AND OLD.vocabulary_visible = 1
ON CONFLICT(epoch_day) DO UPDATE SET
word_count = word_count - 1,
word_count_without_names = word_count_without_names + excluded.word_count_without_names;
INSERT INTO imm_lexical_daily_rollups(epoch_day, word_count, word_count_without_names, kanji_count)
SELECT ${dayForNew}, 1, CASE WHEN NEW.pos2 = '固有名詞' THEN 0 ELSE 1 END, 0
WHERE NEW.first_seen IS NOT NULL AND NEW.vocabulary_visible = 1
ON CONFLICT(epoch_day) DO UPDATE SET
word_count = word_count + 1,
word_count_without_names = word_count_without_names + excluded.word_count_without_names;
DELETE FROM imm_lexical_daily_rollups
WHERE word_count = 0 AND kanji_count = 0;
END;
`);
}
function createKanjiRollupTriggers(db: DatabaseSync): void {
const dayForNew = localEpochDaySql('NEW.first_seen');
const dayForOld = localEpochDaySql('OLD.first_seen');
db.exec(`
DROP TRIGGER IF EXISTS imm_kanji_lexical_rollup_insert;
DROP TRIGGER IF EXISTS imm_kanji_lexical_rollup_delete;
DROP TRIGGER IF EXISTS imm_kanji_lexical_rollup_first_seen_update;
CREATE TRIGGER imm_kanji_lexical_rollup_insert
AFTER INSERT ON imm_kanji WHEN NEW.first_seen IS NOT NULL
BEGIN
INSERT INTO imm_lexical_daily_rollups(epoch_day, word_count, word_count_without_names, kanji_count)
VALUES (${dayForNew}, 0, 0, 1)
ON CONFLICT(epoch_day) DO UPDATE SET kanji_count = kanji_count + 1;
END;
CREATE TRIGGER imm_kanji_lexical_rollup_delete
AFTER DELETE ON imm_kanji WHEN OLD.first_seen IS NOT NULL
BEGIN
INSERT INTO imm_lexical_daily_rollups(epoch_day, word_count, word_count_without_names, kanji_count)
VALUES (${dayForOld}, 0, 0, -1)
ON CONFLICT(epoch_day) DO UPDATE SET kanji_count = kanji_count - 1;
DELETE FROM imm_lexical_daily_rollups
WHERE epoch_day = ${dayForOld} AND word_count = 0 AND kanji_count = 0;
END;
CREATE TRIGGER imm_kanji_lexical_rollup_first_seen_update
AFTER UPDATE OF first_seen ON imm_kanji WHEN OLD.first_seen IS NOT NEW.first_seen
BEGIN
INSERT INTO imm_lexical_daily_rollups(epoch_day, word_count, word_count_without_names, kanji_count)
SELECT ${dayForOld}, 0, 0, -1 WHERE OLD.first_seen IS NOT NULL
ON CONFLICT(epoch_day) DO UPDATE SET kanji_count = kanji_count - 1;
INSERT INTO imm_lexical_daily_rollups(epoch_day, word_count, word_count_without_names, kanji_count)
SELECT ${dayForNew}, 0, 0, 1 WHERE NEW.first_seen IS NOT NULL
ON CONFLICT(epoch_day) DO UPDATE SET kanji_count = kanji_count + 1;
DELETE FROM imm_lexical_daily_rollups WHERE word_count = 0 AND kanji_count = 0;
END;
`);
}
export function ensureLexicalDailyRollupTables(db: DatabaseSync): void {
db.exec(`
CREATE TABLE IF NOT EXISTS imm_lexical_daily_rollups(
epoch_day INTEGER PRIMARY KEY,
word_count INTEGER NOT NULL DEFAULT 0,
word_count_without_names INTEGER NOT NULL DEFAULT 0,
kanji_count INTEGER NOT NULL DEFAULT 0
);
INSERT INTO imm_rollup_state(state_key, state_value)
VALUES ('${LEXICAL_DAILY_ROLLUP_VERSION_KEY}', '0')
ON CONFLICT(state_key) DO NOTHING;
`);
createWordRollupTriggers(db);
createKanjiRollupTriggers(db);
}
export function areLexicalDailyRollupsReady(db: DatabaseSync): boolean {
const row = db
.prepare(`SELECT state_value AS value FROM imm_rollup_state WHERE state_key = ?`)
.get(LEXICAL_DAILY_ROLLUP_VERSION_KEY) as { value: string | number } | undefined;
// Older databases created this column with INTEGER affinity, while current
// databases use TEXT. SQLite returns the same persisted version with a
// different JS type depending on that legacy schema.
return row !== undefined && String(row.value) === LEXICAL_DAILY_ROLLUP_VERSION;
}
export function markLexicalDailyRollupsReady(db: DatabaseSync): void {
db.prepare(
`INSERT INTO imm_rollup_state(state_key, state_value)
VALUES (?, ?)
ON CONFLICT(state_key) DO UPDATE SET state_value = excluded.state_value`,
).run(LEXICAL_DAILY_ROLLUP_VERSION_KEY, LEXICAL_DAILY_ROLLUP_VERSION);
}
/** Rebuild from the first-seen source of truth; run off the UI/main DB thread. */
export function rebuildLexicalDailyRollups(db: DatabaseSync): void {
let transactionStarted = false;
try {
db.exec('BEGIN IMMEDIATE');
transactionStarted = true;
const scanVocabulary = db.prepare(
`SELECT id, word, headword, reading, part_of_speech AS partOfSpeech,
pos1, pos2, pos3, frequency_rank AS frequencyRank
FROM imm_words
WHERE id > ?
ORDER BY id
LIMIT ?`,
);
const updateVisibility = db.prepare(
`UPDATE imm_words SET vocabulary_visible = ? WHERE id = ? AND vocabulary_visible IS NOT ?`,
);
let lastId = Number.MIN_SAFE_INTEGER;
for (;;) {
const vocabularyRows = scanVocabulary.all(
lastId,
VOCABULARY_VISIBILITY_SCAN_BATCH_SIZE,
) as Array<VocabularyVisibilityRow & { id: number }>;
if (vocabularyRows.length === 0) break;
for (const row of vocabularyRows) {
const visible = isVocabularyStatsRowVisible(row) ? 1 : 0;
updateVisibility.run(visible, row.id, visible);
}
lastId = vocabularyRows[vocabularyRows.length - 1]!.id;
if (vocabularyRows.length < VOCABULARY_VISIBILITY_SCAN_BATCH_SIZE) break;
}
db.exec('DELETE FROM imm_lexical_daily_rollups');
db.exec(`
INSERT INTO imm_lexical_daily_rollups(epoch_day, word_count, word_count_without_names, kanji_count)
SELECT ${localEpochDaySql('first_seen')}, COUNT(*),
SUM(CASE WHEN pos2 = '固有名詞' THEN 0 ELSE 1 END), 0
FROM imm_words
WHERE first_seen IS NOT NULL AND vocabulary_visible = 1
GROUP BY ${localEpochDaySql('first_seen')};
INSERT INTO imm_lexical_daily_rollups(epoch_day, word_count, word_count_without_names, kanji_count)
SELECT ${localEpochDaySql('first_seen')}, 0, 0, COUNT(*)
FROM imm_kanji
WHERE first_seen IS NOT NULL
GROUP BY ${localEpochDaySql('first_seen')}
ON CONFLICT(epoch_day) DO UPDATE SET kanji_count = kanji_count + excluded.kanji_count;
`);
markLexicalDailyRollupsReady(db);
db.exec('COMMIT');
} catch (error) {
if (transactionStarted) {
try {
db.exec('ROLLBACK');
} catch {
// Preserve the rebuild failure; it is the actionable cause.
}
}
throw error;
}
}
export function getLexicalDailyRollups(db: DatabaseSync): LexicalDailyRollup[] {
return db
.prepare(
`
SELECT epoch_day AS epochDay, word_count AS wordCount,
word_count_without_names AS wordCountWithoutNames, kanji_count AS kanjiCount
FROM imm_lexical_daily_rollups
ORDER BY epoch_day ASC
`,
)
.all() as LexicalDailyRollup[];
}
@@ -1,6 +1,4 @@
import type { DatabaseSync } from './sqlite'; import type { DatabaseSync } from './sqlite';
import { PartOfSpeech, type MergedToken } from '../../../types';
import { shouldExcludeTokenFromVocabularyPersistence } from '../tokenizer/annotation-stage';
import type { import type {
KanjiAnimeAppearanceRow, KanjiAnimeAppearanceRow,
KanjiDetailRow, KanjiDetailRow,
@@ -13,19 +11,38 @@ import type {
SimilarWordRow, SimilarWordRow,
StatsExcludedWordRow, StatsExcludedWordRow,
VocabularyStatsRow, VocabularyStatsRow,
VocabularyStatsSummary,
WordAnimeAppearanceRow, WordAnimeAppearanceRow,
WordDetailRow, WordDetailRow,
WordOccurrenceRow, WordOccurrenceRow,
} from './types'; } from './types';
import { fromDbTimestamp, toDbTimestamp } from './query-shared'; import { fromDbTimestamp, toDbTimestamp } from './query-shared';
import { nowMs } from './time'; import { nowMs } from './time';
import {
areLexicalDailyRollupsReady,
getLexicalDailyRollups,
localEpochDaySql,
} from './lexical-rollups';
import { isVocabularyStatsRowVisible } from './vocabulary-visibility';
const VOCABULARY_STATS_FILTER_OVERSAMPLE_FACTOR = 4; const VOCABULARY_STATS_FILTER_OVERSAMPLE_FACTOR = 4;
const VOCABULARY_STATS_FILTER_OVERSAMPLE_MIN = 100; const VOCABULARY_STATS_FILTER_OVERSAMPLE_MIN = 100;
const VOCABULARY_CHART_LIMIT = 12;
const VOCABULARY_CHART_PAGE_SIZE = 100;
const EXCLUSION_ALIAS_BATCH_SIZE = 300;
const VOCABULARY_SUMMARY_SCAN_BATCH_SIZE = 5_000;
const SENTENCE_SEARCH_DEFAULT_LIMIT = 50; const SENTENCE_SEARCH_DEFAULT_LIMIT = 50;
const SENTENCE_SEARCH_MAX_LIMIT = 100; const SENTENCE_SEARCH_MAX_LIMIT = 100;
const KANJI_PATTERN = /\p{Script=Han}/gu; const KANJI_PATTERN = /\p{Script=Han}/gu;
export interface VocabularyChartData {
ready: boolean;
topWords: Array<{ wordId: number; headword: string; frequency: number }>;
topWordsWithoutNames: Array<{ wordId: number; headword: string; frequency: number }>;
newWordsTimeline: Array<{ epochDay: number; wordCount: number }>;
newWordsTimelineWithoutNames: Array<{ epochDay: number; wordCount: number }>;
}
function resolveSentenceSearchLimit(limit: number): number { function resolveSentenceSearchLimit(limit: number): number {
if (!Number.isFinite(limit)) return SENTENCE_SEARCH_DEFAULT_LIMIT; if (!Number.isFinite(limit)) return SENTENCE_SEARCH_DEFAULT_LIMIT;
const normalized = Math.floor(limit); const normalized = Math.floor(limit);
@@ -73,33 +90,6 @@ function uniqueKanji(text: string): string[] {
return Array.from(new Set(text.match(KANJI_PATTERN) ?? [])); return Array.from(new Set(text.match(KANJI_PATTERN) ?? []));
} }
function toVocabularyToken(row: VocabularyStatsRow): MergedToken {
const partOfSpeech =
row.partOfSpeech && Object.values(PartOfSpeech).includes(row.partOfSpeech as PartOfSpeech)
? (row.partOfSpeech as PartOfSpeech)
: PartOfSpeech.other;
return {
surface: row.word,
reading: row.reading ?? '',
headword: row.headword,
startPos: 0,
endPos: row.word.length,
partOfSpeech,
pos1: row.pos1 ?? '',
pos2: row.pos2 ?? '',
pos3: row.pos3 ?? '',
frequencyRank: row.frequencyRank ?? undefined,
isMerged: false,
isKnown: false,
isNPlusOneTarget: false,
};
}
function isVocabularyStatsRowVisible(row: VocabularyStatsRow): boolean {
return !shouldExcludeTokenFromVocabularyPersistence(toVocabularyToken(row));
}
export function getVocabularyStats( export function getVocabularyStats(
db: DatabaseSync, db: DatabaseSync,
limit = 100, limit = 100,
@@ -153,6 +143,198 @@ export function getVocabularyStats(
return visibleRows.slice(0, limit); return visibleRows.slice(0, limit);
} }
/**
* Chart data is intentionally independent of the paginated vocabulary tables.
* Top words use the frequency index; new-word history reads permanent daily
* lexical rollups rather than loading every vocabulary row into the dashboard.
*/
export function getVocabularyChartData(db: DatabaseSync): VocabularyChartData {
const ready = areLexicalDailyRollupsReady(db);
const excludedAliases = new Set(
getStatsExcludedWords(db).flatMap((word) => excludedVocabularyAliases(word)),
);
const isExcluded = (word: Pick<VocabularyStatsRow, 'headword' | 'word' | 'reading'>): boolean =>
excludedVocabularyAliases(word).some((alias) => excludedAliases.has(alias));
const topWords = getTopVocabularyChartWords(db, isExcluded);
const rollups = ready ? getLexicalDailyRollups(db) : [];
const timeline = new Map(rollups.map((row) => [row.epochDay, { ...row }]));
if (excludedAliases.size > 0 && ready) {
const aliases = [...excludedAliases];
const excludedRows = new Map<
number,
Pick<VocabularyStatsRow, 'headword' | 'word' | 'reading' | 'pos2'> & {
wordId: number;
epochDay: number;
}
>();
for (let offset = 0; offset < aliases.length; offset += EXCLUSION_ALIAS_BATCH_SIZE) {
const batch = aliases.slice(offset, offset + EXCLUSION_ALIAS_BATCH_SIZE);
const placeholders = batch.map(() => '?').join(', ');
const rows = db
.prepare(
`
SELECT id AS wordId, headword, word, reading, pos2,
${localEpochDaySql('first_seen')} AS epochDay
FROM imm_words
WHERE vocabulary_visible = 1
AND (headword IN (${placeholders}) OR word IN (${placeholders}) OR reading IN (${placeholders}))
`,
)
.all(...batch, ...batch, ...batch) as Array<
Pick<VocabularyStatsRow, 'headword' | 'word' | 'reading' | 'pos2'> & {
wordId: number;
epochDay: number;
}
>;
for (const row of rows) excludedRows.set(row.wordId, row);
}
for (const word of excludedRows.values()) {
if (!isExcluded(word)) continue;
const rollup = timeline.get(word.epochDay);
if (!rollup) continue;
rollup.wordCount -= 1;
if (word.pos2 !== '固有名詞') rollup.wordCountWithoutNames -= 1;
}
}
return {
ready,
topWords: topWords.all.map((word) => ({
wordId: word.wordId,
headword: vocabularyDisplayHeadword(word),
frequency: word.frequency,
})),
topWordsWithoutNames: topWords.withoutNames.map((word) => ({
wordId: word.wordId,
headword: vocabularyDisplayHeadword(word),
frequency: word.frequency,
})),
newWordsTimeline: [...timeline.values()]
.filter((row) => row.wordCount > 0)
.map((row) => ({ epochDay: row.epochDay, wordCount: row.wordCount })),
newWordsTimelineWithoutNames: [...timeline.values()]
.filter((row) => row.wordCountWithoutNames > 0)
.map((row) => ({ epochDay: row.epochDay, wordCount: row.wordCountWithoutNames })),
};
}
function getTopVocabularyChartWords(
db: DatabaseSync,
isExcluded: (word: Pick<VocabularyStatsRow, 'headword' | 'word' | 'reading'>) => boolean,
): { all: VocabularyStatsRow[]; withoutNames: VocabularyStatsRow[] } {
const stmt = db.prepare(`
SELECT id AS wordId, headword, word, reading,
part_of_speech AS partOfSpeech, pos1, pos2, pos3,
frequency, frequency_rank AS frequencyRank,
first_seen AS firstSeen, last_seen AS lastSeen,
0 AS animeCount
FROM imm_words
ORDER BY frequency DESC, id
LIMIT ? OFFSET ?
`);
const all: VocabularyStatsRow[] = [];
const withoutNames: VocabularyStatsRow[] = [];
let offset = 0;
while (all.length < VOCABULARY_CHART_LIMIT || withoutNames.length < VOCABULARY_CHART_LIMIT) {
const page = stmt.all(VOCABULARY_CHART_PAGE_SIZE, offset) as VocabularyStatsRow[];
if (page.length === 0) break;
for (const word of page) {
if (!isVocabularyStatsRowVisible(word) || isExcluded(word)) continue;
if (all.length < VOCABULARY_CHART_LIMIT) all.push(word);
if (word.pos2 !== '固有名詞' && withoutNames.length < VOCABULARY_CHART_LIMIT) {
withoutNames.push(word);
}
}
offset += page.length;
}
return { all, withoutNames };
}
function excludedVocabularyAliases(
word: Pick<VocabularyStatsRow, 'headword' | 'word' | 'reading'>,
): string[] {
const aliases = [word.headword?.trim() ?? '', word.word?.trim() ?? ''].filter(Boolean);
if (aliases.length === 0) aliases.push(word.reading?.trim() ?? '');
return [...new Set(aliases)];
}
function vocabularyDisplayHeadword(
word: Pick<VocabularyStatsRow, 'headword' | 'word' | 'reading'>,
): string {
return word.headword?.trim() || word.word?.trim() || word.reading?.trim() || '';
}
function timestampSeconds(timestamp: number): number {
return timestamp < 10_000_000_000 ? timestamp : Math.floor(timestamp / 1000);
}
export function getVocabularySummary(
db: DatabaseSync,
knownWords: ReadonlySet<string> | null,
nowMs: number = Date.now(),
scanBatchSize: number = VOCABULARY_SUMMARY_SCAN_BATCH_SIZE,
): VocabularyStatsSummary {
// Visibility and exclusion rules live in JS, so rows are scanned in id-keyed
// batches to keep memory bounded on large vocabularies.
const scanStmt = db.prepare(`
SELECT id AS wordId, headword, word, reading,
part_of_speech AS partOfSpeech, pos1, pos2, pos3,
frequency, frequency_rank AS frequencyRank,
first_seen AS firstSeen, last_seen AS lastSeen,
0 AS animeCount
FROM imm_words
WHERE id > ?
ORDER BY id
LIMIT ?
`);
const excludedAliases = new Set(
getStatsExcludedWords(db).flatMap((word) => excludedVocabularyAliases(word)),
);
const weekAgoSec = nowMs / 1000 - 7 * 86_400;
const summary: VocabularyStatsSummary = {
uniqueWords: 0,
uniqueWordsWithoutNames: 0,
uniqueKanji: (db.prepare('SELECT COUNT(*) AS count FROM imm_kanji').get() as { count: number })
.count,
newThisWeek: 0,
newThisWeekWithoutNames: 0,
knownWordCount: knownWords ? 0 : null,
knownWordCountWithoutNames: knownWords ? 0 : null,
};
let lastId = Number.MIN_SAFE_INTEGER;
for (;;) {
const words = scanStmt.all(lastId, scanBatchSize) as VocabularyStatsRow[];
if (words.length === 0) break;
lastId = words[words.length - 1]!.wordId;
for (const word of words) {
if (
!isVocabularyStatsRowVisible(word) ||
excludedVocabularyAliases(word).some((alias) => excludedAliases.has(alias))
) {
continue;
}
const isName = word.pos2 === '固有名詞';
const isNewThisWeek = timestampSeconds(fromDbTimestamp(word.firstSeen) ?? 0) >= weekAgoSec;
const isKnown = knownWords?.has(vocabularyDisplayHeadword(word)) ?? false;
summary.uniqueWords += 1;
if (!isName) summary.uniqueWordsWithoutNames += 1;
if (isNewThisWeek) {
summary.newThisWeek += 1;
if (!isName) summary.newThisWeekWithoutNames += 1;
}
if (isKnown) {
summary.knownWordCount! += 1;
if (!isName) summary.knownWordCountWithoutNames! += 1;
}
}
if (words.length < scanBatchSize) break;
}
return summary;
}
export function getStatsExcludedWords(db: DatabaseSync): StatsExcludedWordRow[] { export function getStatsExcludedWords(db: DatabaseSync): StatsExcludedWordRow[] {
return db return db
.prepare( .prepare(
@@ -13,6 +13,7 @@ import {
toDbTimestamp, toDbTimestamp,
} from './query-shared'; } from './query-shared';
import { getDailyRollups, getMonthlyRollups } from './query-sessions'; import { getDailyRollups, getMonthlyRollups } from './query-sessions';
import { areLexicalDailyRollupsReady, getLexicalDailyRollups } from './lexical-rollups';
type TrendRange = '7d' | '30d' | '90d' | '365d' | 'all'; type TrendRange = '7d' | '30d' | '90d' | '365d' | 'all';
type TrendGroupBy = 'day' | 'month'; type TrendGroupBy = 'day' | 'month';
@@ -660,6 +661,16 @@ function buildNewWordsPerDay(
cutoffMs: string | null, cutoffMs: string | null,
axis: number[] | null, axis: number[] | null,
): TrendChartPoint[] { ): TrendChartPoint[] {
if (areLexicalDailyRollupsReady(db)) {
// A trend range is defined in calendar buckets, so the rollup includes the
// complete local cutoff day rather than applying a time-of-day boundary.
const cutoffDay = cutoffMs === null ? null : getLocalEpochDay(db, cutoffMs);
const rows = getLexicalDailyRollups(db).filter(
(row) => cutoffDay === null || row.epochDay >= cutoffDay,
);
return fillAxisPoints(axis, new Map(rows.map((row) => [row.epochDay, row.wordCount])));
}
const whereClause = cutoffMs === null ? '' : 'AND first_seen >= ?'; const whereClause = cutoffMs === null ? '' : 'AND first_seen >= ?';
const prepared = db.prepare(` const prepared = db.prepare(`
SELECT SELECT
@@ -691,6 +702,18 @@ function buildNewWordsPerMonth(
cutoffMs: string | null, cutoffMs: string | null,
axis: number[] | null, axis: number[] | null,
): TrendChartPoint[] { ): TrendChartPoint[] {
if (areLexicalDailyRollupsReady(db)) {
const cutoffDay = cutoffMs === null ? null : getLocalEpochDay(db, cutoffMs);
const byMonth = new Map<number, number>();
for (const row of getLexicalDailyRollups(db)) {
if (cutoffDay !== null && row.epochDay < cutoffDay) continue;
const { year, month } = dayPartsFromEpochDay(row.epochDay);
const monthKey = year * 100 + month;
byMonth.set(monthKey, (byMonth.get(monthKey) ?? 0) + row.wordCount);
}
return fillAxisPoints(axis, byMonth);
}
const whereClause = cutoffMs === null ? '' : 'AND first_seen >= ?'; const whereClause = cutoffMs === null ? '' : 'AND first_seen >= ?';
const prepared = db.prepare(` const prepared = db.prepare(`
SELECT SELECT
@@ -184,6 +184,51 @@ test('ensureSchema adds manual assignment locks when upgrading the previous sche
} }
}); });
test('ensureSchema preserves durable session rollups across unrelated schema upgrades', () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
try {
ensureSchema(db);
db.exec(`
INSERT INTO imm_videos (
video_id, video_key, canonical_title, source_type, duration_ms, CREATED_DATE, LAST_UPDATE_DATE
) VALUES (1, 'local:/tmp/preserved.mkv', 'Preserved', 1, 0, '1', '1');
INSERT INTO imm_daily_rollups (
rollup_day, video_id, total_sessions, total_active_min, total_lines_seen,
total_tokens_seen, total_cards
) VALUES (20000, 1, 2, 30, 40, 50, 3);
INSERT INTO imm_monthly_rollups (
rollup_month, video_id, total_sessions, total_active_min, total_lines_seen,
total_tokens_seen, total_cards
) VALUES (202410, 1, 2, 30, 40, 50, 3);
UPDATE imm_rollup_state
SET state_value = '123'
WHERE state_key = 'last_rollup_sample_ms';
UPDATE imm_schema_version SET schema_version = 21;
`);
ensureSchema(db);
const daily = db
.prepare('SELECT total_sessions AS totalSessions FROM imm_daily_rollups')
.get() as { totalSessions: number } | null;
const monthly = db
.prepare('SELECT total_sessions AS totalSessions FROM imm_monthly_rollups')
.get() as { totalSessions: number } | null;
const rollupState = db
.prepare(`SELECT state_value AS value FROM imm_rollup_state WHERE state_key = ?`)
.get('last_rollup_sample_ms') as { value: string } | null;
assert.equal(daily?.totalSessions, 2);
assert.equal(monthly?.totalSessions, 2);
assert.equal(rollupState?.value, '123');
} finally {
db.close();
cleanupDbPath(dbPath);
}
});
test('stats excluded words are replaced and read from sqlite storage', () => { test('stats excluded words are replaced and read from sqlite storage', () => {
const dbPath = makeDbPath(); const dbPath = makeDbPath();
const db = new Database(dbPath); const db = new Database(dbPath);
+26 -10
View File
@@ -4,6 +4,7 @@ import { parseMediaInfo } from '../../../jimaku/utils';
import { normalizeTitleIdentity } from '../../utils/title-normalization'; import { normalizeTitleIdentity } from '../../utils/title-normalization';
import type { DatabaseSync } from './sqlite'; import type { DatabaseSync } from './sqlite';
import { nowMs } from './time'; import { nowMs } from './time';
import { ensureLexicalDailyRollupTables, markLexicalDailyRollupsReady } from './lexical-rollups';
import { SCHEMA_VERSION } from './types'; import { SCHEMA_VERSION } from './types';
import type { QueuedWrite, VideoMetadata, YoutubeVideoMetadata } from './types'; import type { QueuedWrite, VideoMetadata, YoutubeVideoMetadata } from './types';
import { toDbMs, toDbTimestamp } from './query-shared'; import { toDbMs, toDbTimestamp } from './query-shared';
@@ -890,11 +891,11 @@ export function ensureSchema(db: DatabaseSync): void {
VALUES ('last_rollup_sample_ms', 0) VALUES ('last_rollup_sample_ms', 0)
ON CONFLICT(state_key) DO NOTHING ON CONFLICT(state_key) DO NOTHING
`); `);
const currentVersion = db const currentVersion = db
.prepare('SELECT schema_version FROM imm_schema_version ORDER BY schema_version DESC LIMIT 1') .prepare('SELECT schema_version FROM imm_schema_version ORDER BY schema_version DESC LIMIT 1')
.get() as { schema_version: number } | null; .get() as { schema_version: number } | null;
if (currentVersion?.schema_version === SCHEMA_VERSION) { if (currentVersion?.schema_version === SCHEMA_VERSION) {
ensureLexicalDailyRollupTables(db);
ensureLifetimeSummaryTables(db); ensureLifetimeSummaryTables(db);
ensureStatsExcludedWordsTable(db); ensureStatsExcludedWordsTable(db);
ensureAnimeMergeTables(db); ensureAnimeMergeTables(db);
@@ -1068,6 +1069,7 @@ export function ensureSchema(db: DatabaseSync): void {
last_seen REAL, last_seen REAL,
frequency INTEGER, frequency INTEGER,
frequency_rank INTEGER, frequency_rank INTEGER,
vocabulary_visible INTEGER NOT NULL DEFAULT 1 CHECK(vocabulary_visible IN (0, 1)),
UNIQUE(headword, word, reading) UNIQUE(headword, word, reading)
); );
`); `);
@@ -1451,8 +1453,18 @@ export function ensureSchema(db: DatabaseSync): void {
addColumnIfMissing(db, 'imm_sessions', 'ended_media_ms', 'INTEGER'); addColumnIfMissing(db, 'imm_sessions', 'ended_media_ms', 'INTEGER');
} }
if (currentVersion?.schema_version && currentVersion.schema_version < 23) {
addColumnIfMissing(
db,
'imm_words',
'vocabulary_visible',
'INTEGER NOT NULL DEFAULT 1 CHECK(vocabulary_visible IN (0, 1))',
);
}
migrateSessionEventTimestampsToText(db); migrateSessionEventTimestampsToText(db);
ensureLexicalDailyRollupTables(db);
ensureLifetimeSummaryTables(db); ensureLifetimeSummaryTables(db);
ensureStatsExcludedWordsTable(db); ensureStatsExcludedWordsTable(db);
@@ -1572,19 +1584,21 @@ export function ensureSchema(db: DatabaseSync): void {
ON imm_youtube_videos(youtube_video_id) ON imm_youtube_videos(youtube_video_id)
`); `);
if (currentVersion?.schema_version && currentVersion.schema_version < SCHEMA_VERSION) { // Session rollups intentionally outlive raw session and telemetry retention.
db.exec('DELETE FROM imm_daily_rollups'); // Preserve them across unrelated schema upgrades because deleted historical
db.exec('DELETE FROM imm_monthly_rollups'); // buckets cannot be rebuilt after their source rows have been pruned.
db.exec(
`UPDATE imm_rollup_state SET state_value = 0 WHERE state_key = 'last_rollup_sample_ms'`,
);
}
db.exec(` db.exec(`
INSERT INTO imm_schema_version(schema_version, applied_at_ms) INSERT INTO imm_schema_version(schema_version, applied_at_ms)
VALUES (${SCHEMA_VERSION}, ${toDbTimestamp(nowMs())}) VALUES (${SCHEMA_VERSION}, ${toDbTimestamp(nowMs())})
ON CONFLICT DO NOTHING ON CONFLICT DO NOTHING
`); `);
// A new database has no history to materialize. Upgrades are populated by the
// background worker so startup never scans the existing vocabulary table.
if (!currentVersion) {
markLexicalDailyRollupsReady(db);
}
} }
export function createTrackerPreparedStatements(db: DatabaseSync): TrackerPreparedStatements { export function createTrackerPreparedStatements(db: DatabaseSync): TrackerPreparedStatements {
@@ -1617,9 +1631,10 @@ export function createTrackerPreparedStatements(db: DatabaseSync): TrackerPrepar
`), `),
wordUpsertStmt: db.prepare(` wordUpsertStmt: db.prepare(`
INSERT INTO imm_words ( INSERT INTO imm_words (
headword, word, reading, part_of_speech, pos1, pos2, pos3, first_seen, last_seen, frequency, frequency_rank headword, word, reading, part_of_speech, pos1, pos2, pos3, first_seen, last_seen,
frequency, frequency_rank, vocabulary_visible
) VALUES ( ) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ? ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, 1
) )
ON CONFLICT(headword, word, reading) DO UPDATE SET ON CONFLICT(headword, word, reading) DO UPDATE SET
frequency = COALESCE(frequency, 0) + 1, frequency = COALESCE(frequency, 0) + 1,
@@ -1632,6 +1647,7 @@ export function createTrackerPreparedStatements(db: DatabaseSync): TrackerPrepar
pos1 = COALESCE(NULLIF(imm_words.pos1, ''), excluded.pos1), pos1 = COALESCE(NULLIF(imm_words.pos1, ''), excluded.pos1),
pos2 = COALESCE(NULLIF(imm_words.pos2, ''), excluded.pos2), pos2 = COALESCE(NULLIF(imm_words.pos2, ''), excluded.pos2),
pos3 = COALESCE(NULLIF(imm_words.pos3, ''), excluded.pos3), pos3 = COALESCE(NULLIF(imm_words.pos3, ''), excluded.pos3),
vocabulary_visible = 1,
first_seen = MIN(COALESCE(first_seen, excluded.first_seen), excluded.first_seen), first_seen = MIN(COALESCE(first_seen, excluded.first_seen), excluded.first_seen),
last_seen = MAX(COALESCE(last_seen, excluded.last_seen), excluded.last_seen), last_seen = MAX(COALESCE(last_seen, excluded.last_seen), excluded.last_seen),
frequency_rank = CASE frequency_rank = CASE
+11 -1
View File
@@ -1,4 +1,4 @@
export const SCHEMA_VERSION = 21; export const SCHEMA_VERSION = 23;
export const DEFAULT_QUEUE_CAP = 1_000; export const DEFAULT_QUEUE_CAP = 1_000;
export const DEFAULT_BATCH_SIZE = 25; export const DEFAULT_BATCH_SIZE = 25;
export const DEFAULT_FLUSH_INTERVAL_MS = 500; export const DEFAULT_FLUSH_INTERVAL_MS = 500;
@@ -306,6 +306,16 @@ export interface VocabularyStatsRow {
lastSeen: number; lastSeen: number;
} }
export interface VocabularyStatsSummary {
uniqueWords: number;
uniqueWordsWithoutNames: number;
uniqueKanji: number;
newThisWeek: number;
newThisWeekWithoutNames: number;
knownWordCount: number | null;
knownWordCountWithoutNames: number | null;
}
export interface StatsExcludedWordRow { export interface StatsExcludedWordRow {
headword: string; headword: string;
word: string; word: string;
@@ -0,0 +1,100 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import {
resolveVocabularySummaryWorkerPath,
VocabularySummaryWorkerRuntime,
} from './vocabulary-summary-worker-runtime';
import { Database } from './sqlite';
import { applyPragmas, ensureSchema } from './storage';
test('vocabulary summary worker reads the database from a separate connection', async () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-vocabulary-summary-worker-'));
const dbPath = path.join(tempDir, 'immersion.sqlite');
const runtime = new VocabularySummaryWorkerRuntime();
const db = new Database(dbPath);
try {
applyPragmas(db);
ensureSchema(db);
db.prepare(
`
INSERT INTO imm_words (
headword, word, reading, part_of_speech, pos1, pos2, pos3,
first_seen, last_seen, frequency
) VALUES ('猫', '猫', 'ねこ', 'noun', '名詞', '一般', '', 1, 1, 1)
`,
).run();
db.close();
const summary = await runtime.run(dbPath, new Set(['猫']));
assert.equal(summary.uniqueWords, 1);
assert.equal(summary.knownWordCount, 1);
} finally {
runtime.destroy();
try {
db.close();
} catch {
// The worker needs the setup connection closed before it starts.
}
fs.rmSync(tempDir, { recursive: true, force: true });
}
});
test('vocabulary summary worker module resolves in the current layout', () => {
const workerPath = resolveVocabularySummaryWorkerPath();
assert.ok(workerPath, 'expected the vocabulary summary worker module to resolve');
assert.ok(workerPath.endsWith(__filename.endsWith('.ts') ? '.ts' : '.js'));
});
test('vocabulary summary worker never falls back to the caller thread', async () => {
const runtime = new VocabularySummaryWorkerRuntime({
resolveWorkerPath: () => null,
warn: () => {},
});
try {
await assert.rejects(
runtime.run('/tmp/subminer-summary-worker-not-used.sqlite', null),
/worker unavailable/i,
);
} finally {
runtime.destroy();
}
});
test('vocabulary summary worker times out when it never responds', async () => {
let terminated = false;
const runtime = new VocabularySummaryWorkerRuntime({
resolveWorkerPath: () => '/tmp/fake-worker.js',
createWorker: async () => ({
once() {
return this;
},
terminate: async () => {
terminated = true;
return 0;
},
}),
timeoutMs: 1,
warn: () => {},
} as never);
try {
const outcome = await Promise.race([
runtime.run('/tmp/not-used.sqlite', null).then(
() => 'resolved',
(error: unknown) => String(error),
),
new Promise<string>((resolve) => setTimeout(() => resolve('still pending'), 50)),
]);
assert.match(outcome, /timed out/);
assert.equal(terminated, true);
} finally {
runtime.destroy();
}
});
@@ -0,0 +1,133 @@
import fs from 'node:fs';
import path from 'node:path';
import { createLogger } from '../../../logger';
import type { VocabularyStatsSummary } from './types';
interface VocabularySummaryWorkerResponse {
summary?: VocabularyStatsSummary;
error?: unknown;
}
interface VocabularySummaryWorkerHandle {
once(event: 'message', listener: (message: VocabularySummaryWorkerResponse) => void): this;
once(event: 'error', listener: (error: Error) => void): this;
once(event: 'exit', listener: (code: number) => void): this;
terminate(): Promise<number>;
}
interface VocabularySummaryWorkerRuntimeOptions {
resolveWorkerPath?: () => string | null;
createWorker?: (
workerPath: string,
workerData: { dbPath: string; knownWords: string[] | null },
) => Promise<VocabularySummaryWorkerHandle>;
timeoutMs?: number;
warn?: (message: string, ...meta: unknown[]) => void;
}
export type RunVocabularySummaryTask = (
dbPath: string,
knownWords: ReadonlySet<string> | null,
) => Promise<VocabularyStatsSummary>;
export function resolveVocabularySummaryWorkerPath(): string | null {
const fileName = __filename.endsWith('.ts')
? 'vocabulary-summary-worker-thread.ts'
: 'vocabulary-summary-worker-thread.js';
const workerPath = path.join(__dirname, fileName);
return fs.existsSync(workerPath) ? workerPath : null;
}
const logger = createLogger('main:immersion-tracker:vocabulary-summary-worker');
const DEFAULT_WORKER_TIMEOUT_MS = 5 * 60 * 1_000;
export class VocabularySummaryWorkerRuntime {
private readonly activeWorkers = new Set<VocabularySummaryWorkerHandle>();
private destroyed = false;
constructor(private readonly options: VocabularySummaryWorkerRuntimeOptions = {}) {}
async run(
dbPath: string,
knownWords: ReadonlySet<string> | null,
): Promise<VocabularyStatsSummary> {
if (this.destroyed) throw new Error('Vocabulary summary worker is shut down');
const workerData = { dbPath, knownWords: knownWords ? [...knownWords] : null };
let worker: VocabularySummaryWorkerHandle;
try {
const workerPath = (this.options.resolveWorkerPath ?? resolveVocabularySummaryWorkerPath)();
if (!workerPath) throw new Error('Emitted vocabulary summary worker module was not found');
const createWorker =
this.options.createWorker ??
(async (resolvedPath, data) => {
const { Worker } = await import('node:worker_threads');
return new Worker(resolvedPath, { workerData: data });
});
worker = await createWorker(workerPath, workerData);
} catch (error) {
if (this.destroyed) throw new Error('Vocabulary summary worker is shut down');
(this.options.warn ?? logger.warn)(
'Vocabulary summary worker unavailable; refusing to scan vocabulary on the current thread',
error,
);
throw new Error('Vocabulary summary worker unavailable');
}
if (this.destroyed) {
await worker.terminate().catch(() => undefined);
throw new Error('Vocabulary summary worker is shut down');
}
return new Promise<VocabularyStatsSummary>((resolve, reject) => {
let settled = false;
let timeout: ReturnType<typeof setTimeout> | null = null;
this.activeWorkers.add(worker);
const settle = (result: VocabularyStatsSummary | Error) => {
if (settled) return;
settled = true;
if (timeout) clearTimeout(timeout);
this.activeWorkers.delete(worker);
void worker.terminate().catch(() => undefined);
if (result instanceof Error) reject(result);
else resolve(result);
};
timeout = setTimeout(
() => settle(new Error('Vocabulary summary worker timed out')),
this.options.timeoutMs ?? DEFAULT_WORKER_TIMEOUT_MS,
);
worker.once('message', (message) => {
if (message.summary) {
settle(message.summary);
return;
}
settle(
new Error(
`Vocabulary summary failed: ${String(message.error ?? 'unknown worker error')}`,
),
);
});
worker.once('error', (error) => settle(error));
worker.once('exit', (code) => {
if (!settled) {
settle(
new Error(
code === 0
? 'Vocabulary summary worker exited without a response'
: `Vocabulary summary worker exited with code ${code}`,
),
);
}
});
});
}
destroy(): void {
if (this.destroyed) return;
this.destroyed = true;
for (const worker of this.activeWorkers) {
void worker.terminate().catch(() => undefined);
}
this.activeWorkers.clear();
}
}
@@ -0,0 +1,19 @@
import { parentPort, workerData } from 'node:worker_threads';
import { executeVocabularySummaryTask } from './vocabulary-summary-worker';
interface VocabularySummaryWorkerData {
dbPath: string;
knownWords: string[] | null;
}
if (!parentPort) throw new Error('vocabulary summary worker missing parent port');
const request = workerData as VocabularySummaryWorkerData;
try {
parentPort.postMessage({
summary: executeVocabularySummaryTask(request.dbPath, request.knownWords),
});
} catch (error) {
parentPort.postMessage({ error: error instanceof Error ? error.message : String(error) });
}
@@ -0,0 +1,17 @@
import { getVocabularySummary } from './query-lexical';
import { Database } from './sqlite';
import { applyPragmas } from './storage';
import type { VocabularyStatsSummary } from './types';
export function executeVocabularySummaryTask(
dbPath: string,
knownWords: string[] | null,
): VocabularyStatsSummary {
const db = new Database(dbPath);
try {
applyPragmas(db);
return getVocabularySummary(db, knownWords ? new Set(knownWords) : null);
} finally {
db.close();
}
}
@@ -0,0 +1,43 @@
import { PartOfSpeech, type MergedToken } from '../../../types';
import { shouldExcludeTokenFromVocabularyPersistence } from '../tokenizer/annotation-stage';
export interface VocabularyVisibilityRow {
word: string | null;
headword: string | null;
reading?: string | null;
partOfSpeech?: string | null;
pos1?: string | null;
pos2?: string | null;
pos3?: string | null;
frequencyRank?: number | null;
}
function toVocabularyToken(row: VocabularyVisibilityRow): MergedToken {
const word = row.word ?? '';
const headword = row.headword ?? word;
const partOfSpeech =
row.partOfSpeech && Object.values(PartOfSpeech).includes(row.partOfSpeech as PartOfSpeech)
? (row.partOfSpeech as PartOfSpeech)
: PartOfSpeech.other;
return {
surface: word,
reading: row.reading ?? '',
headword,
startPos: 0,
endPos: word.length,
partOfSpeech,
pos1: row.pos1 ?? '',
pos2: row.pos2 ?? '',
pos3: row.pos3 ?? '',
frequencyRank: row.frequencyRank ?? undefined,
isMerged: false,
isKnown: false,
isNPlusOneTarget: false,
};
}
export function isVocabularyStatsRowVisible(row: VocabularyVisibilityRow): boolean {
if (!(row.word?.trim() || row.headword?.trim())) return false;
return !shouldExcludeTokenFromVocabularyPersistence(toVocabularyToken(row));
}
-22
View File
@@ -648,28 +648,6 @@ test('registerIpcHandlers exposes playback window activation request', async ()
assert.deepEqual(calls, ['activate']); assert.deepEqual(calls, ['activate']);
}); });
test('registerIpcHandlers accepts the keep-without-media timing decision', async () => {
const { registrar, handlers } = createFakeIpcRegistrar();
const requests: unknown[] = [];
registerIpcHandlers(
createRegisterIpcDeps({
resolveMediaTimingReview: async (request) => {
requests.push(request);
return { ok: true };
},
}),
registrar,
);
const handler = handlers.handle.get(IPC_CHANNELS.request.mediaTimingReviewResolve);
assert.ok(handler);
assert.deepEqual(
await handler!({}, { reviewId: 'review-1', decision: { action: 'skip-media' } }),
{ ok: true },
);
assert.deepEqual(requests, [{ reviewId: 'review-1', decision: { action: 'skip-media' } }]);
});
test('registerIpcHandlers forwards yomitan lookup tracking commands to immersion tracker', () => { test('registerIpcHandlers forwards yomitan lookup tracking commands to immersion tracker', () => {
const { registrar, handlers } = createFakeIpcRegistrar(); const { registrar, handlers } = createFakeIpcRegistrar();
const calls: string[] = []; const calls: string[] = [];
+8 -129
View File
@@ -19,13 +19,6 @@ import type {
YoutubePickerResolveRequest, YoutubePickerResolveRequest,
YoutubePickerResolveResult, YoutubePickerResolveResult,
} from '../../types'; } from '../../types';
import type {
MediaTimingReviewActionResult,
MediaTimingReviewPreviewRequest,
MediaTimingReviewResolveRequest,
MediaTimingReviewWaveformRequest,
MediaTimingReviewWaveformResult,
} from '../../types/anki';
import { IPC_CHANNELS, type OverlayHostedModal } from '../../shared/ipc/contracts'; import { IPC_CHANNELS, type OverlayHostedModal } from '../../shared/ipc/contracts';
import { import {
parseMpvCommand, parseMpvCommand,
@@ -41,6 +34,7 @@ import {
parseSubsyncManualRunRequest, parseSubsyncManualRunRequest,
parseYoutubePickerResolveRequest, parseYoutubePickerResolveRequest,
} from '../../shared/ipc/validators'; } from '../../shared/ipc/validators';
import { applyOverlayClickThrough } from './overlay-click-through';
const { ipcMain } = electron; const { ipcMain } = electron;
@@ -105,16 +99,6 @@ export interface IpcServiceDeps {
onYoutubePickerResolve: ( onYoutubePickerResolve: (
request: YoutubePickerResolveRequest, request: YoutubePickerResolveRequest,
) => Promise<YoutubePickerResolveResult>; ) => Promise<YoutubePickerResolveResult>;
previewMediaTimingReview?: (
request: MediaTimingReviewPreviewRequest,
) => Promise<MediaTimingReviewActionResult>;
getMediaTimingReviewWaveform?: (
request: MediaTimingReviewWaveformRequest,
) => Promise<MediaTimingReviewWaveformResult>;
stopMediaTimingReviewPreview?: (reviewId: string) => Promise<MediaTimingReviewActionResult>;
resolveMediaTimingReview?: (
request: MediaTimingReviewResolveRequest,
) => MediaTimingReviewActionResult | Promise<MediaTimingReviewActionResult>;
getAnkiConnectStatus: () => boolean; getAnkiConnectStatus: () => boolean;
getRuntimeOptions: () => unknown; getRuntimeOptions: () => unknown;
setRuntimeOption: (id: RuntimeOptionId, value: RuntimeOptionValue) => unknown; setRuntimeOption: (id: RuntimeOptionId, value: RuntimeOptionValue) => unknown;
@@ -238,69 +222,6 @@ function parseOverlayNotificationActionPayload(
return { notificationId, actionId, ...(typeof noteId === 'number' ? { noteId } : {}) }; return { notificationId, actionId, ...(typeof noteId === 'number' ? { noteId } : {}) };
} }
function parseMediaTimingReviewPreviewRequest(
payload: unknown,
): MediaTimingReviewPreviewRequest | null {
if (!payload || typeof payload !== 'object') return null;
const record = payload as Record<string, unknown>;
if (
typeof record.reviewId !== 'string' ||
!record.reviewId ||
typeof record.startTime !== 'number' ||
!Number.isFinite(record.startTime) ||
typeof record.endTime !== 'number' ||
!Number.isFinite(record.endTime)
) {
return null;
}
return {
reviewId: record.reviewId,
startTime: record.startTime,
endTime: record.endTime,
};
}
function parseMediaTimingReviewWaveformRequest(
payload: unknown,
): MediaTimingReviewWaveformRequest | null {
return parseMediaTimingReviewPreviewRequest(payload);
}
function parseMediaTimingReviewResolveRequest(
payload: unknown,
): MediaTimingReviewResolveRequest | null {
if (!payload || typeof payload !== 'object') return null;
const record = payload as Record<string, unknown>;
if (typeof record.reviewId !== 'string' || !record.reviewId) return null;
const decision = record.decision;
if (!decision || typeof decision !== 'object') return null;
const decisionRecord = decision as Record<string, unknown>;
if (
decisionRecord.action === 'use-original' ||
decisionRecord.action === 'skip-media' ||
decisionRecord.action === 'discard'
) {
return { reviewId: record.reviewId, decision: { action: decisionRecord.action } };
}
if (
decisionRecord.action === 'confirm' &&
typeof decisionRecord.startTime === 'number' &&
Number.isFinite(decisionRecord.startTime) &&
typeof decisionRecord.endTime === 'number' &&
Number.isFinite(decisionRecord.endTime)
) {
return {
reviewId: record.reviewId,
decision: {
action: 'confirm',
startTime: decisionRecord.startTime,
endTime: decisionRecord.endTime,
},
};
}
return null;
}
export interface IpcDepsRuntimeOptions { export interface IpcDepsRuntimeOptions {
getMainWindow: () => WindowLike | null; getMainWindow: () => WindowLike | null;
getVisibleOverlayVisibility: () => boolean; getVisibleOverlayVisibility: () => boolean;
@@ -357,10 +278,6 @@ export interface IpcDepsRuntimeOptions {
onYoutubePickerResolve: ( onYoutubePickerResolve: (
request: YoutubePickerResolveRequest, request: YoutubePickerResolveRequest,
) => Promise<YoutubePickerResolveResult>; ) => Promise<YoutubePickerResolveResult>;
previewMediaTimingReview?: IpcServiceDeps['previewMediaTimingReview'];
getMediaTimingReviewWaveform?: IpcServiceDeps['getMediaTimingReviewWaveform'];
stopMediaTimingReviewPreview?: IpcServiceDeps['stopMediaTimingReviewPreview'];
resolveMediaTimingReview?: IpcServiceDeps['resolveMediaTimingReview'];
getAnkiConnectStatus: () => boolean; getAnkiConnectStatus: () => boolean;
getRuntimeOptions: () => unknown; getRuntimeOptions: () => unknown;
setRuntimeOption: (id: RuntimeOptionId, value: RuntimeOptionValue) => unknown; setRuntimeOption: (id: RuntimeOptionId, value: RuntimeOptionValue) => unknown;
@@ -454,10 +371,6 @@ export function createIpcDepsRuntime(options: IpcDepsRuntimeOptions): IpcService
options.activatePlaybackWindowForOverlayInteraction ?? (() => false), options.activatePlaybackWindowForOverlayInteraction ?? (() => false),
runSubsyncManual: options.runSubsyncManual, runSubsyncManual: options.runSubsyncManual,
onYoutubePickerResolve: options.onYoutubePickerResolve, onYoutubePickerResolve: options.onYoutubePickerResolve,
previewMediaTimingReview: options.previewMediaTimingReview,
getMediaTimingReviewWaveform: options.getMediaTimingReviewWaveform,
stopMediaTimingReviewPreview: options.stopMediaTimingReviewPreview,
resolveMediaTimingReview: options.resolveMediaTimingReview,
getAnkiConnectStatus: options.getAnkiConnectStatus, getAnkiConnectStatus: options.getAnkiConnectStatus,
getRuntimeOptions: options.getRuntimeOptions, getRuntimeOptions: options.getRuntimeOptions,
setRuntimeOption: options.setRuntimeOption, setRuntimeOption: options.setRuntimeOption,
@@ -530,7 +443,13 @@ export function registerIpcHandlers(deps: IpcServiceDeps, ipc: IpcMainRegistrar
const senderWindow = const senderWindow =
electron.BrowserWindow?.fromWebContents((event as IpcMainEvent).sender) ?? null; electron.BrowserWindow?.fromWebContents((event as IpcMainEvent).sender) ?? null;
if (senderWindow && !senderWindow.isDestroyed()) { if (senderWindow && !senderWindow.isDestroyed()) {
senderWindow.setIgnoreMouseEvents(ignore, parsedOptions); // Route forwarding requests through the platform-aware helper so Windows never
// installs Electron's global mouse hook (see overlay-click-through.ts).
if (ignore && parsedOptions?.forward) {
applyOverlayClickThrough(senderWindow);
} else {
senderWindow.setIgnoreMouseEvents(ignore, parsedOptions);
}
} }
deps.onOverlayMouseInteractionChanged?.(!ignore, senderWindow); deps.onOverlayMouseInteractionChanged?.(!ignore, senderWindow);
}, },
@@ -579,46 +498,6 @@ export function registerIpcHandlers(deps: IpcServiceDeps, ipc: IpcMainRegistrar
}, },
); );
ipc.handle(
IPC_CHANNELS.request.mediaTimingReviewPreview,
async (_event: unknown, payload: unknown) => {
const request = parseMediaTimingReviewPreviewRequest(payload);
if (!request || !deps.previewMediaTimingReview) {
return { ok: false, message: 'Timing preview is unavailable.' };
}
return await deps.previewMediaTimingReview(request);
},
);
ipc.handle(
IPC_CHANNELS.request.mediaTimingReviewWaveform,
async (_event: unknown, payload: unknown) => {
const request = parseMediaTimingReviewWaveformRequest(payload);
if (!request || !deps.getMediaTimingReviewWaveform) {
return { ok: false, message: 'Timing waveform is unavailable.' };
}
return await deps.getMediaTimingReviewWaveform(request);
},
);
ipc.handle(
IPC_CHANNELS.request.mediaTimingReviewStopPreview,
async (_event: unknown, reviewId: unknown) => {
if (typeof reviewId !== 'string' || !reviewId || !deps.stopMediaTimingReviewPreview) {
return { ok: false, message: 'Timing preview is unavailable.' };
}
return await deps.stopMediaTimingReviewPreview(reviewId);
},
);
ipc.handle(
IPC_CHANNELS.request.mediaTimingReviewResolve,
async (_event: unknown, payload: unknown) => {
const request = parseMediaTimingReviewResolveRequest(payload);
if (!request || !deps.resolveMediaTimingReview) {
return { ok: false, message: 'Timing review is unavailable.' };
}
return await deps.resolveMediaTimingReview(request);
},
);
ipc.on(IPC_CHANNELS.command.openYomitanSettings, () => { ipc.on(IPC_CHANNELS.command.openYomitanSettings, () => {
deps.openYomitanSettings(); deps.openYomitanSettings();
}); });
@@ -1,191 +0,0 @@
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import net from 'node:net';
import { describe, test } from 'node:test';
import { buildMediaTimingPreviewArgs, MediaTimingPreviewSession } from './media-timing-preview';
describe('buildMediaTimingPreviewArgs', () => {
test('creates a hidden audio-only reusable mpv session', () => {
const args = buildMediaTimingPreviewArgs('/tmp/review.sock', {
mediaPath: '/video/show.mkv',
audioTrackId: 3,
volume: 55,
});
assert.ok(args.includes('--no-video'));
assert.ok(args.includes('--force-window=no'));
assert.ok(args.includes('--idle=yes'));
assert.ok(args.includes('--pause=yes'));
assert.ok(args.includes('--input-ipc-server=/tmp/review.sock'));
assert.ok(args.includes('--aid=3'));
assert.ok(args.includes('--volume=55'));
assert.equal(args.at(-2), '--');
assert.equal(args.at(-1), '/video/show.mkv');
});
test('separates an option-like media path without adding optional audio arguments', () => {
const args = buildMediaTimingPreviewArgs('/tmp/review.sock', {
mediaPath: '--fullscreen',
});
assert.equal(args.at(-2), '--');
assert.equal(args.at(-1), '--fullscreen');
assert.equal(
args.some((arg) => arg.startsWith('--aid=')),
false,
);
assert.equal(
args.some((arg) => arg.startsWith('--volume=')),
false,
);
});
});
test('preview session handles socket errors after connecting', async () => {
const socket = new net.Socket();
const child = new EventEmitter() as EventEmitter & { kill: () => boolean };
child.kill = () => true;
const session = new MediaTimingPreviewSession({
platform: 'linux',
spawnProcess: () => child as never,
connectSocket: () => {
queueMicrotask(() => socket.emit('connect'));
return socket;
},
removeSocketFile: () => undefined,
createSocketPath: () => '/tmp/review.sock',
});
await session.start({ mediaPath: '/video/show.mkv' });
assert.doesNotThrow(() => socket.emit('error', new Error('pipe closed')));
await assert.rejects(session.play(1, 2), /not ready/);
session.dispose();
});
test('preview session keeps failed connection errors handled through destruction', async () => {
const socket = new EventEmitter() as EventEmitter & {
destroy: () => void;
};
socket.destroy = () => {
socket.emit('error', new Error('socket failed again while closing'));
};
const child = new EventEmitter() as EventEmitter & { kill: () => boolean };
child.kill = () => true;
const times = [0, 0, 0, 6_000];
const session = new MediaTimingPreviewSession({
platform: 'linux',
spawnProcess: () => child as never,
connectSocket: () => {
queueMicrotask(() => socket.emit('error', new Error('connection failed')));
return socket as never;
},
now: () => times.shift() ?? 6_000,
removeSocketFile: () => undefined,
createSocketPath: () => '/tmp/review.sock',
});
await assert.rejects(session.start({ mediaPath: '/video/show.mkv' }), /Timed out starting/);
});
test('preview session rejects a connection that finishes after disposal', async () => {
const socket = new net.Socket();
const child = new EventEmitter() as EventEmitter & { kill: () => boolean };
child.kill = () => true;
const session = new MediaTimingPreviewSession({
platform: 'linux',
spawnProcess: () => child as never,
connectSocket: () => socket,
removeSocketFile: () => undefined,
createSocketPath: () => '/tmp/review.sock',
});
const pendingStart = session.start({ mediaPath: '-playlist' });
session.dispose();
socket.emit('connect');
await assert.rejects(pendingStart, /closed/);
assert.equal(socket.destroyed, true);
});
test('preview session shares one startup across concurrent start calls', async () => {
const socket = new net.Socket();
const child = new EventEmitter() as EventEmitter & { kill: () => boolean };
child.kill = () => true;
let spawnCount = 0;
const session = new MediaTimingPreviewSession({
platform: 'linux',
spawnProcess: () => {
spawnCount += 1;
return child as never;
},
connectSocket: () => socket,
removeSocketFile: () => undefined,
createSocketPath: () => '/tmp/review.sock',
});
const firstStart = session.start({ mediaPath: '/video/show.mkv' });
const secondStart = session.start({ mediaPath: '/video/show.mkv' });
socket.emit('connect');
await Promise.all([firstStart, secondStart]);
assert.equal(spawnCount, 1);
session.dispose();
});
test('preview session can start again after a startup failure', async () => {
const socket = new net.Socket();
const child = new EventEmitter() as EventEmitter & { kill: () => boolean };
child.kill = () => true;
let spawnCount = 0;
const session = new MediaTimingPreviewSession({
platform: 'linux',
spawnProcess: () => {
spawnCount += 1;
if (spawnCount === 1) throw new Error('spawn failed');
return child as never;
},
connectSocket: () => {
queueMicrotask(() => socket.emit('connect'));
return socket;
},
removeSocketFile: () => undefined,
createSocketPath: () => '/tmp/review.sock',
});
await assert.rejects(session.start({ mediaPath: '/video/show.mkv' }), /spawn failed/);
await session.start({ mediaPath: '/video/show.mkv' });
assert.equal(spawnCount, 2);
session.dispose();
});
test('preview session bounds a connection attempt that never settles', async () => {
const child = new EventEmitter() as EventEmitter & { kill: () => boolean };
child.kill = () => true;
let nowMs = 0;
let connectAttempts = 0;
const session = new MediaTimingPreviewSession({
platform: 'linux',
spawnProcess: () => child as never,
connectSocket: () => {
connectAttempts += 1;
const socket = new net.Socket();
socket.destroy = (() => {
socket.emit('error', new Error('socket failed while timing out'));
return socket;
}) as typeof socket.destroy;
return socket;
},
now: () => {
const current = nowMs;
nowMs += 1_000;
return current;
},
schedule: (callback) => setTimeout(callback, 0),
cancelSchedule: (timeout) => clearTimeout(timeout),
removeSocketFile: () => undefined,
createSocketPath: () => '/tmp/review.sock',
});
await assert.rejects(session.start({ mediaPath: '/video/show.mkv' }), /Timed out starting/);
assert.equal(connectAttempts, 1);
});
-311
View File
@@ -1,311 +0,0 @@
import { spawn, type ChildProcess } from 'child_process';
import fs from 'fs';
import net, { type Socket } from 'net';
import os from 'os';
import path from 'path';
import { randomUUID } from 'crypto';
const CONNECT_TIMEOUT_MS = 5_000;
const CONNECT_ATTEMPT_TIMEOUT_MS = 500;
const CONNECT_RETRY_MS = 40;
export interface MediaTimingPreviewStartOptions {
mediaPath: string;
executablePath?: string;
audioTrackId?: number;
volume?: number;
}
type PreviewProcess = Pick<ChildProcess, 'kill' | 'once'>;
interface MediaTimingPreviewDeps {
platform: NodeJS.Platform;
spawnProcess: (command: string, args: string[]) => PreviewProcess;
connectSocket: (socketPath: string) => Socket;
now: () => number;
schedule: (callback: () => void, delayMs: number) => ReturnType<typeof setTimeout>;
cancelSchedule: (timeout: ReturnType<typeof setTimeout>) => void;
removeSocketFile: (socketPath: string) => void;
createSocketPath: () => string;
}
export function buildMediaTimingPreviewArgs(
socketPath: string,
options: MediaTimingPreviewStartOptions,
): string[] {
const args = [
'--no-config',
'--no-video',
'--audio-display=no',
'--force-window=no',
'--idle=yes',
'--keep-open=yes',
'--pause=yes',
'--terminal=no',
'--msg-level=all=warn',
`--input-ipc-server=${socketPath}`,
];
if (typeof options.audioTrackId === 'number' && Number.isInteger(options.audioTrackId)) {
args.push(`--aid=${options.audioTrackId}`);
}
if (typeof options.volume === 'number' && Number.isFinite(options.volume)) {
args.push(`--volume=${Math.max(0, options.volume)}`);
}
args.push('--', options.mediaPath);
return args;
}
function createDefaultSocketPath(): string {
const suffix = `${process.pid}-${randomUUID()}`;
return process.platform === 'win32'
? `\\\\.\\pipe\\subminer-timing-preview-${suffix}`
: path.join(os.tmpdir(), `subminer-timing-preview-${suffix}.sock`);
}
function removePosixSocketFile(socketPath: string): void {
if (process.platform === 'win32') return;
try {
fs.unlinkSync(socketPath);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
throw error;
}
}
}
export class MediaTimingPreviewSession {
private readonly deps: MediaTimingPreviewDeps;
private socketPath: string | null = null;
private socket: Socket | null = null;
private process: PreviewProcess | null = null;
private startupError: Error | null = null;
private startPromise: Promise<void> | null = null;
private retryWait: {
timeout: ReturnType<typeof setTimeout>;
resolve: () => void;
} | null = null;
private disposed = false;
constructor(deps: Partial<MediaTimingPreviewDeps> = {}) {
this.deps = {
platform: process.platform,
spawnProcess: (command, args) => spawn(command, args, { stdio: 'ignore' }),
connectSocket: (socketPath) => net.createConnection(socketPath),
now: Date.now,
schedule: (callback, delayMs) => setTimeout(callback, delayMs),
cancelSchedule: (timeout) => clearTimeout(timeout),
removeSocketFile: removePosixSocketFile,
createSocketPath: createDefaultSocketPath,
...deps,
};
}
async start(options: MediaTimingPreviewStartOptions): Promise<void> {
if (this.disposed) throw new Error('Preview session is closed');
if (this.socket) return;
if (this.startPromise) return await this.startPromise;
const startPromise = this.startOnce(options);
this.startPromise = startPromise;
try {
await startPromise;
} catch (error) {
this.releaseResources();
throw error;
} finally {
if (this.startPromise === startPromise) this.startPromise = null;
}
}
private async startOnce(options: MediaTimingPreviewStartOptions): Promise<void> {
const mediaPath = options.mediaPath.trim();
if (!mediaPath) throw new Error('No media source is available for preview');
const socketPath = this.deps.createSocketPath();
this.socketPath = socketPath;
if (this.deps.platform !== 'win32') {
this.deps.removeSocketFile(socketPath);
}
const command = options.executablePath?.trim() || 'mpv';
this.startupError = null;
const child = this.deps.spawnProcess(
command,
buildMediaTimingPreviewArgs(socketPath, { ...options, mediaPath }),
);
this.process = child;
child.once('error', (error) => {
if (this.process !== child) return;
this.startupError = error;
});
child.once('exit', () => {
if (this.process !== child) return;
if (!this.socket && !this.disposed && !this.startupError) {
this.startupError = new Error('The hidden mpv preview player exited during startup');
}
this.socket?.destroy();
this.socket = null;
this.process = null;
});
await this.connectWithRetry(socketPath);
}
async play(startTime: number, endTime: number): Promise<void> {
if (!this.socket || this.socket.destroyed) {
throw new Error('Preview player is not ready');
}
if (!Number.isFinite(startTime) || !Number.isFinite(endTime) || endTime <= startTime) {
throw new Error('Preview timing is invalid');
}
this.send(['set_property', 'pause', true]);
this.send(['set_property', 'ab-loop-a', startTime]);
this.send(['set_property', 'ab-loop-b', endTime]);
this.send(['seek', startTime, 'absolute+exact']);
this.send(['set_property', 'pause', false]);
}
async stop(): Promise<void> {
if (!this.socket || this.socket.destroyed) return;
this.send(['set_property', 'pause', true]);
}
dispose(): void {
if (this.disposed) return;
this.disposed = true;
this.releaseResources();
}
private releaseResources(): void {
this.cancelRetryWait();
try {
this.send(['quit']);
} catch {
// The process may already have exited.
}
this.socket?.end();
this.socket?.destroy();
this.socket = null;
const child = this.process;
this.process = null;
child?.kill();
if (this.socketPath && this.deps.platform !== 'win32') {
try {
this.deps.removeSocketFile(this.socketPath);
} catch {
// mpv may still be releasing the socket. The OS temp directory owns cleanup.
}
}
this.socketPath = null;
}
private send(command: Array<string | number | boolean>): void {
if (!this.socket || this.socket.destroyed) {
throw new Error('Preview player is not connected');
}
this.socket.write(`${JSON.stringify({ command })}\n`);
}
private async connectWithRetry(socketPath: string): Promise<void> {
const deadline = this.deps.now() + CONNECT_TIMEOUT_MS;
while (!this.disposed && this.deps.now() < deadline) {
if (this.startupError) {
throw this.startupError;
}
try {
const remainingMs = deadline - this.deps.now();
if (remainingMs <= 0) break;
const socket = await this.connectOnce(
socketPath,
Math.min(CONNECT_ATTEMPT_TIMEOUT_MS, remainingMs),
);
if (this.disposed) {
socket.destroy();
throw new Error('Preview session is closed');
}
this.socket = socket;
return;
} catch {
if (this.disposed) {
throw new Error('Preview session is closed');
}
const remainingMs = deadline - this.deps.now();
if (remainingMs <= 0) break;
await this.waitForRetry(Math.min(CONNECT_RETRY_MS, remainingMs));
}
}
if (this.startupError) {
throw this.startupError;
}
if (this.disposed) {
throw new Error('Preview session is closed');
}
throw new Error('Timed out starting the hidden mpv preview player');
}
private waitForRetry(delayMs: number): Promise<void> {
return new Promise<void>((resolve) => {
const timeout = this.deps.schedule(() => {
if (this.retryWait?.timeout === timeout) this.retryWait = null;
resolve();
}, delayMs);
this.retryWait = { timeout, resolve };
});
}
private cancelRetryWait(): void {
const pending = this.retryWait;
this.retryWait = null;
if (!pending) return;
this.deps.cancelSchedule(pending.timeout);
pending.resolve();
}
private connectOnce(socketPath: string, timeoutMs: number): Promise<Socket> {
return new Promise<Socket>((resolve, reject) => {
let timeout: ReturnType<typeof setTimeout> | null = null;
let settled = false;
const clearAttemptTimeout = (): void => {
if (timeout !== null) this.deps.cancelSchedule(timeout);
timeout = null;
};
const socket = this.deps.connectSocket(socketPath);
const onConnect = (): void => {
if (settled) return;
settled = true;
clearAttemptTimeout();
socket.off('error', onError);
socket.on('error', () => {
socket.destroy();
if (this.socket === socket) this.socket = null;
});
socket.once('close', () => {
if (this.socket === socket) this.socket = null;
});
resolve(socket);
};
const onError = (error: Error): void => {
if (settled) return;
settled = true;
clearAttemptTimeout();
socket.off('connect', onConnect);
socket.on('error', () => {});
socket.destroy();
reject(error);
};
socket.once('connect', onConnect);
socket.once('error', onError);
timeout = this.deps.schedule(() => {
if (settled) return;
settled = true;
timeout = null;
socket.off('connect', onConnect);
socket.off('error', onError);
socket.on('error', () => {});
socket.destroy();
reject(new Error('Timed out connecting to the hidden mpv preview player'));
}, timeoutMs);
});
}
}
@@ -1,74 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
buildSpeechWaveformArgs,
computeWaveformPeaks,
generateSpeechWaveform,
} from './media-timing-waveform';
function pcm(samples: number[]): Buffer {
const result = Buffer.alloc(samples.length * 2);
samples.forEach((sample, index) => result.writeInt16LE(sample, index * 2));
return result;
}
test('speech waveform maps the selected FFmpeg stream and visible range', () => {
const args = buildSpeechWaveformArgs(
{
mediaPath: '/video/show.mkv',
startTime: 8,
endTime: 15,
audioStreamIndex: 3,
},
'center',
);
assert.deepEqual(args.slice(args.indexOf('-ss'), args.indexOf('-t') + 2), [
'-ss',
'8',
'-i',
'/video/show.mkv',
'-t',
'7',
]);
assert.deepEqual(args.slice(args.indexOf('-map'), args.indexOf('-map') + 2), ['-map', '0:3']);
assert.match(args[args.indexOf('-af') + 1] ?? '', /c0=FC/);
});
test('waveform peaks are normalized without flattening quieter sections', () => {
const peaks = computeWaveformPeaks(pcm([0, 1_000, -2_000, 4_000, -8_000, 16_000]), 3);
assert.equal(peaks.length, 3);
assert.ok((peaks[0] ?? 0) > 0);
assert.ok((peaks[0] ?? 0) < (peaks[1] ?? 0));
assert.ok((peaks[1] ?? 0) < (peaks[2] ?? 0));
assert.equal(peaks[2], 1);
});
test('speech waveform uses a mono downmix when the source has no center activity', async () => {
const calls: string[][] = [];
const peaks = await generateSpeechWaveform(
{ mediaPath: '/video/show.mkv', startTime: 0, endTime: 2 },
async (args) => {
calls.push(args);
return calls.length === 1 ? pcm([0, 0, 0, 0]) : pcm([0, 4_000, -8_000, 16_000]);
},
);
assert.equal(calls.length, 2);
assert.match(calls[1]?.[calls[1].indexOf('-af') + 1] ?? '', /channel_layouts=mono/);
assert.equal(Math.max(...peaks), 1);
});
test('speech waveform keeps an active center channel without doing a second decode', async () => {
let calls = 0;
await generateSpeechWaveform(
{ mediaPath: '/video/show.mkv', startTime: 0, endTime: 2 },
async () => {
calls += 1;
return pcm([0, 4_000, -8_000, 16_000]);
},
);
assert.equal(calls, 1);
});
-158
View File
@@ -1,158 +0,0 @@
import { spawn } from 'node:child_process';
const WAVEFORM_SAMPLE_RATE = 8_000;
const WAVEFORM_POINT_COUNT = 480;
const WAVEFORM_TIMEOUT_MS = 15_000;
const MAX_WAVEFORM_BYTES = 16 * 1024 * 1024;
const SPEECH_FILTER = 'highpass=f=120,lowpass=f=4000';
const CENTER_CHANNEL_FILTER = `pan=mono|c0=FC,${SPEECH_FILTER}`;
const DOWNMIX_FILTER = `aformat=channel_layouts=mono,${SPEECH_FILTER}`;
export interface SpeechWaveformOptions {
mediaPath: string;
startTime: number;
endTime: number;
audioStreamIndex?: number;
}
type RunFfmpeg = (args: string[]) => Promise<Buffer>;
export function buildSpeechWaveformArgs(
options: SpeechWaveformOptions,
mode: 'center' | 'downmix',
): string[] {
const duration = options.endTime - options.startTime;
const args = [
'-hide_banner',
'-nostdin',
'-loglevel',
'error',
'-ss',
String(options.startTime),
'-i',
options.mediaPath,
'-t',
String(duration),
];
if (
options.audioStreamIndex !== undefined &&
Number.isInteger(options.audioStreamIndex) &&
options.audioStreamIndex >= 0
) {
args.push('-map', `0:${options.audioStreamIndex}`);
}
args.push(
'-vn',
'-sn',
'-dn',
'-af',
mode === 'center' ? CENTER_CHANNEL_FILTER : DOWNMIX_FILTER,
'-ac',
'1',
'-ar',
String(WAVEFORM_SAMPLE_RATE),
'-f',
's16le',
'pipe:1',
);
return args;
}
function runFfmpeg(args: string[]): Promise<Buffer> {
return new Promise((resolve, reject) => {
const child = spawn('ffmpeg', args, { stdio: ['ignore', 'pipe', 'pipe'] });
const chunks: Buffer[] = [];
let byteLength = 0;
let stderr = '';
let settled = false;
const timeout = setTimeout(() => {
if (settled) return;
settled = true;
child.kill('SIGKILL');
reject(new Error(`FFmpeg waveform analysis timed out after ${WAVEFORM_TIMEOUT_MS}ms`));
}, WAVEFORM_TIMEOUT_MS);
const settle = (callback: () => void): void => {
if (settled) return;
settled = true;
clearTimeout(timeout);
callback();
};
child.stdout.on('data', (chunk: Buffer) => {
if (settled) return;
byteLength += chunk.byteLength;
if (byteLength > MAX_WAVEFORM_BYTES) {
settle(() => {
child.kill('SIGKILL');
reject(new Error('The visible waveform range is too large to analyze.'));
});
return;
}
chunks.push(chunk);
});
child.stderr.setEncoding('utf8');
child.stderr.on('data', (chunk) => {
if (stderr.length < 4_000) stderr += String(chunk);
});
child.once('error', (error) => settle(() => reject(error)));
child.once('close', (code) => {
settle(() => {
if (code === 0) {
resolve(Buffer.concat(chunks, byteLength));
return;
}
reject(new Error(stderr.trim() || `FFmpeg exited with status ${code ?? 'unknown'}`));
});
});
});
}
export function computeWaveformPeaks(pcm: Buffer, pointCount = WAVEFORM_POINT_COUNT): number[] {
const sampleCount = Math.floor(pcm.byteLength / 2);
if (sampleCount === 0 || pointCount <= 0) return [];
const resolvedPointCount = Math.min(pointCount, sampleCount);
const peaks = Array.from({ length: resolvedPointCount }, () => 0);
for (let point = 0; point < resolvedPointCount; point += 1) {
const sampleStart = Math.floor((point * sampleCount) / resolvedPointCount);
const sampleEnd = Math.max(
sampleStart + 1,
Math.floor(((point + 1) * sampleCount) / resolvedPointCount),
);
let peak = 0;
for (let sample = sampleStart; sample < sampleEnd; sample += 1) {
peak = Math.max(peak, Math.abs(pcm.readInt16LE(sample * 2)) / 32_768);
}
peaks[point] = peak;
}
const sortedPeaks = [...peaks].sort((left, right) => left - right);
const referenceIndex = Math.min(sortedPeaks.length - 1, Math.floor(sortedPeaks.length * 0.95));
const referencePeak = Math.max(sortedPeaks[referenceIndex] ?? 0, 0.01);
return peaks.map(
(peak) => Math.round(Math.sqrt(Math.min(1, peak / referencePeak)) * 1_000) / 1_000,
);
}
function hasAudibleSamples(pcm: Buffer): boolean {
for (let offset = 0; offset + 1 < pcm.byteLength; offset += 2) {
if (Math.abs(pcm.readInt16LE(offset)) >= 164) return true;
}
return false;
}
export async function generateSpeechWaveform(
options: SpeechWaveformOptions,
execute: RunFfmpeg = runFfmpeg,
): Promise<number[]> {
try {
const centerPcm = await execute(buildSpeechWaveformArgs(options, 'center'));
if (hasAudibleSamples(centerPcm)) return computeWaveformPeaks(centerPcm);
} catch {
// Sources without a named center channel can reject the center-only filter.
}
const downmixPcm = await execute(buildSpeechWaveformArgs(options, 'downmix'));
return computeWaveformPeaks(downmixPcm);
}
+76 -39
View File
@@ -125,9 +125,83 @@ test('mineSentenceCard creates sentence card from mpv subtitle state', async ()
]); ]);
}); });
test('mineSentenceCard refreshes secondary subtitle text before creating card', async () => { test('mineSentenceCard prefers a canonical primary subtitle snapshot', async () => {
const created: Array<{
sentence: string;
startTime: number;
endTime: number;
secondarySub?: string;
}> = [];
await mineSentenceCard({
ankiIntegration: {
updateLastAddedFromClipboard: async () => {},
triggerFieldGroupingForLastAddedCard: async () => {},
markLastCardAsAudioCard: async () => {},
createSentenceCard: async (sentence, startTime, endTime, secondarySub) => {
created.push({ sentence, startTime, endTime, secondarySub });
return true;
},
},
mpvClient: {
connected: true,
currentSubText: '今今今手手手',
currentSubStart: 11.4,
currentSubEnd: 11.8,
currentSecondarySubText: 'English subtitle',
},
primarySubtitle: {
text: '今 手にある物差しでは',
startTime: 11.13,
endTime: 13.83,
},
showMpvOsd: () => {},
});
assert.deepEqual(created, [
{
sentence: '今 手にある物差しでは',
startTime: 11.13,
endTime: 13.83,
secondarySub: 'English subtitle',
},
]);
});
test('mineSentenceCard uses normalized secondary subtitle state instead of raw mpv text', async () => {
const created: Array<{ sentence: string; secondarySub?: string }> = [];
let requestedRawSecondaryText = false;
await mineSentenceCard({
ankiIntegration: {
updateLastAddedFromClipboard: async () => {},
triggerFieldGroupingForLastAddedCard: async () => {},
markLastCardAsAudioCard: async () => {},
createSentenceCard: async (sentence, _startTime, _endTime, secondarySub) => {
created.push({ sentence, secondarySub });
return true;
},
},
mpvClient: {
connected: true,
currentSubText: '日本語字幕',
currentSubStart: 10,
currentSubEnd: 12,
currentSecondarySubText: 'Your\nmosaic',
requestProperty: async () => {
requestedRawSecondaryText = true;
return 'Your\nYour\nYour\nYour\nmosaic';
},
},
showMpvOsd: () => {},
});
assert.equal(requestedRawSecondaryText, false);
assert.deepEqual(created, [{ sentence: '日本語字幕', secondarySub: 'Your\nmosaic' }]);
});
test('mineSentenceCard omits normalized secondary text that matches the primary subtitle', async () => {
const created: Array<{ sentence: string; secondarySub?: string }> = []; const created: Array<{ sentence: string; secondarySub?: string }> = [];
const requestedProperties: string[] = [];
await mineSentenceCard({ await mineSentenceCard({
ankiIntegration: { ankiIntegration: {
@@ -145,43 +219,6 @@ test('mineSentenceCard refreshes secondary subtitle text before creating card',
currentSubStart: 10, currentSubStart: 10,
currentSubEnd: 12, currentSubEnd: 12,
currentSecondarySubText: '日本語字幕', currentSecondarySubText: '日本語字幕',
requestProperty: async (name: string) => {
requestedProperties.push(name);
return name === 'secondary-sub-text' ? 'English subtitle' : null;
},
},
showMpvOsd: () => {},
});
assert.deepEqual(requestedProperties, ['secondary-sub-text']);
assert.deepEqual(created, [{ sentence: '日本語字幕', secondarySub: 'English subtitle' }]);
});
test('mineSentenceCard does not fall back to stale cached secondary subtitle after successful refresh', async () => {
const created: Array<{ sentence: string; secondarySub?: string }> = [];
await mineSentenceCard({
ankiIntegration: {
updateLastAddedFromClipboard: async () => {},
triggerFieldGroupingForLastAddedCard: async () => {},
markLastCardAsAudioCard: async () => {},
createSentenceCard: async (sentence, _startTime, _endTime, secondarySub) => {
created.push({ sentence, secondarySub });
return true;
},
},
mpvClient: {
connected: true,
currentSubText: '日本語字幕',
currentSubStart: 10,
currentSubEnd: 12,
currentSecondarySubText: 'stale cached subtitle',
requestProperty: async (name: string) => {
if (name === 'secondary-sub-text') {
return '';
}
return null;
},
}, },
showMpvOsd: () => {}, showMpvOsd: () => {},
}); });
+10 -16
View File
@@ -129,18 +129,10 @@ function normalizeSecondarySubText(text: unknown, primaryText: string): string |
return trimmed; return trimmed;
} }
async function getCurrentSecondarySubTextForSentenceCard( function getCurrentSecondarySubTextForSentenceCard(
mpvClient: MpvClientLike, mpvClient: MpvClientLike,
): Promise<string | undefined> { primaryText: string,
const primaryText = mpvClient.currentSubText; ): string | undefined {
if (mpvClient.requestProperty) {
try {
const latestSecondaryText = await mpvClient.requestProperty('secondary-sub-text');
return normalizeSecondarySubText(latestSecondaryText, primaryText);
} catch {
// Fall back to the cached secondary subtitle below.
}
}
return normalizeSecondarySubText(mpvClient.currentSecondarySubText, primaryText); return normalizeSecondarySubText(mpvClient.currentSecondarySubText, primaryText);
} }
@@ -175,6 +167,7 @@ export async function markLastCardAsAudioCard(deps: {
export async function mineSentenceCard(deps: { export async function mineSentenceCard(deps: {
ankiIntegration: AnkiIntegrationLike | null; ankiIntegration: AnkiIntegrationLike | null;
mpvClient: MpvClientLike | null; mpvClient: MpvClientLike | null;
primarySubtitle?: Pick<SubtitleMiningContext, 'text' | 'startTime' | 'endTime'>;
showMpvOsd: (text: string) => void; showMpvOsd: (text: string) => void;
}): Promise<boolean> { }): Promise<boolean> {
const anki = requireAnkiIntegration(deps.ankiIntegration, deps.showMpvOsd); const anki = requireAnkiIntegration(deps.ankiIntegration, deps.showMpvOsd);
@@ -185,16 +178,17 @@ export async function mineSentenceCard(deps: {
deps.showMpvOsd('MPV not connected'); deps.showMpvOsd('MPV not connected');
return false; return false;
} }
if (!mpvClient.currentSubText) { const primaryText = deps.primarySubtitle?.text ?? mpvClient.currentSubText;
if (!primaryText) {
deps.showMpvOsd('No current subtitle'); deps.showMpvOsd('No current subtitle');
return false; return false;
} }
const secondarySubText = await getCurrentSecondarySubTextForSentenceCard(mpvClient); const secondarySubText = getCurrentSecondarySubTextForSentenceCard(mpvClient, primaryText);
return await anki.createSentenceCard( return await anki.createSentenceCard(
mpvClient.currentSubText, primaryText,
mpvClient.currentSubStart, deps.primarySubtitle?.startTime ?? mpvClient.currentSubStart,
mpvClient.currentSubEnd, deps.primarySubtitle?.endTime ?? mpvClient.currentSubEnd,
secondarySubText, secondarySubText,
); );
} }
+4 -2
View File
@@ -53,7 +53,7 @@ const MPV_SUBTITLE_PROPERTY_OBSERVATIONS: string[] = [
'sub-scale-by-window', 'sub-scale-by-window',
'osd-height', 'osd-height',
'osd-dimensions', 'osd-dimensions',
'sub-text-ass', 'sub-text/ass',
'sub-border-size', 'sub-border-size',
'sub-shadow-offset', 'sub-shadow-offset',
'sub-ass-override', 'sub-ass-override',
@@ -65,6 +65,8 @@ const MPV_SUBTITLE_PROPERTY_OBSERVATIONS: string[] = [
'secondary-sub-visibility', 'secondary-sub-visibility',
'sub-visibility', 'sub-visibility',
'sid', 'sid',
'secondary-sid',
'secondary-sub-delay',
'track-list', 'track-list',
]; ];
@@ -74,7 +76,7 @@ const MPV_INITIAL_PROPERTY_REQUESTS: Array<MpvProtocolCommand> = [
request_id: MPV_REQUEST_ID_SUBTEXT, request_id: MPV_REQUEST_ID_SUBTEXT,
}, },
{ {
command: ['get_property', 'sub-text-ass'], command: ['get_property', 'sub-text/ass'],
request_id: MPV_REQUEST_ID_SUBTEXT_ASS, request_id: MPV_REQUEST_ID_SUBTEXT_ASS,
}, },
{ {
+55 -1
View File
@@ -63,6 +63,8 @@ function createDeps(overrides: Partial<MpvProtocolHandleMessageDeps> = {}): {
emitSubtitleTiming: (payload) => state.events.push(payload), emitSubtitleTiming: (payload) => state.events.push(payload),
emitSecondarySubtitleChange: (payload) => state.events.push(payload), emitSecondarySubtitleChange: (payload) => state.events.push(payload),
emitSubtitleTrackChange: (payload) => state.events.push(payload), emitSubtitleTrackChange: (payload) => state.events.push(payload),
emitSecondarySubtitleTrackChange: (payload) => state.events.push(payload),
emitSecondarySubtitleDelayChange: (payload) => state.events.push(payload),
emitSubtitleTrackListChange: (payload) => state.events.push(payload), emitSubtitleTrackListChange: (payload) => state.events.push(payload),
getCurrentSubText: () => state.subText, getCurrentSubText: () => state.subText,
setCurrentSubText: (text) => { setCurrentSubText: (text) => {
@@ -129,6 +131,28 @@ test('dispatchMpvProtocolMessage emits subtitle text on property change', async
assert.deepEqual(state.events, [{ text: '字幕', isOverlayVisible: false }]); assert.deepEqual(state.events, [{ text: '字幕', isOverlayVisible: false }]);
}); });
test('dispatchMpvProtocolMessage emits ASS subtitle text from the current mpv property', async () => {
const { deps, state } = createDeps();
await dispatchMpvProtocolMessage(
{ event: 'property-change', name: 'sub-text/ass', data: '{\\b1}字幕' },
deps,
);
assert.deepEqual(state.events, [{ text: '{\\b1}字幕' }]);
});
test('dispatchMpvProtocolMessage emits ASS subtitle text from the legacy mpv property', async () => {
const { deps, state } = createDeps();
await dispatchMpvProtocolMessage(
{ event: 'property-change', name: 'sub-text-ass', data: '{\\b1}字幕' },
deps,
);
assert.deepEqual(state.events, [{ text: '{\\b1}字幕' }]);
});
test('dispatchMpvProtocolMessage emits subtitle track changes', async () => { test('dispatchMpvProtocolMessage emits subtitle track changes', async () => {
const { deps, state } = createDeps({ const { deps, state } = createDeps({
emitSubtitleTrackChange: (payload) => state.events.push(payload), emitSubtitleTrackChange: (payload) => state.events.push(payload),
@@ -136,12 +160,42 @@ test('dispatchMpvProtocolMessage emits subtitle track changes', async () => {
}); });
await dispatchMpvProtocolMessage({ event: 'property-change', name: 'sid', data: '3' }, deps); await dispatchMpvProtocolMessage({ event: 'property-change', name: 'sid', data: '3' }, deps);
await dispatchMpvProtocolMessage(
{ event: 'property-change', name: 'secondary-sid', data: '4' },
deps,
);
await dispatchMpvProtocolMessage(
{ event: 'property-change', name: 'secondary-sub-delay', data: '0.5' },
deps,
);
await dispatchMpvProtocolMessage( await dispatchMpvProtocolMessage(
{ event: 'property-change', name: 'track-list', data: [{ type: 'sub', id: 3 }] }, { event: 'property-change', name: 'track-list', data: [{ type: 'sub', id: 3 }] },
deps, deps,
); );
assert.deepEqual(state.events, [{ sid: 3 }, { trackList: [{ type: 'sub', id: 3 }] }]); assert.deepEqual(state.events, [
{ sid: 3 },
{ sid: 4 },
{ delay: 0.5 },
{ trackList: [{ type: 'sub', id: 3 }] },
]);
});
test('dispatchMpvProtocolMessage rejects decimal subtitle track IDs', async () => {
const { deps, state } = createDeps();
await dispatchMpvProtocolMessage({ event: 'property-change', name: 'sid', data: '4.5' }, deps);
await dispatchMpvProtocolMessage(
{ event: 'property-change', name: 'secondary-sid', data: '4.5' },
deps,
);
await dispatchMpvProtocolMessage({ event: 'property-change', name: 'sid', data: 4.5 }, deps);
await dispatchMpvProtocolMessage(
{ event: 'property-change', name: 'secondary-sid', data: 4.5 },
deps,
);
assert.deepEqual(state.events, [{ sid: null }, { sid: null }, { sid: null }, { sid: null }]);
}); });
test('dispatchMpvProtocolMessage enforces sub-visibility hidden when overlay suppression is enabled', async () => { test('dispatchMpvProtocolMessage enforces sub-visibility hidden when overlay suppression is enabled', async () => {
+22 -2
View File
@@ -54,6 +54,8 @@ export interface MpvProtocolHandleMessageDeps {
emitSubtitleTiming: (payload: { text: string; start: number; end: number }) => void; emitSubtitleTiming: (payload: { text: string; start: number; end: number }) => void;
emitSecondarySubtitleChange: (payload: { text: string }) => void; emitSecondarySubtitleChange: (payload: { text: string }) => void;
emitSubtitleTrackChange: (payload: { sid: number | null }) => void; emitSubtitleTrackChange: (payload: { sid: number | null }) => void;
emitSecondarySubtitleTrackChange: (payload: { sid: number | null }) => void;
emitSecondarySubtitleDelayChange: (payload: { delay: number }) => void;
emitSubtitleTrackListChange: (payload: { trackList: unknown[] | null }) => void; emitSubtitleTrackListChange: (payload: { trackList: unknown[] | null }) => void;
getCurrentSubText: () => string; getCurrentSubText: () => string;
setCurrentSubText: (text: string) => void; setCurrentSubText: (text: string) => void;
@@ -248,7 +250,7 @@ export async function dispatchMpvProtocolMessage(
isOverlayVisible: overlayVisible, isOverlayVisible: overlayVisible,
}); });
deps.setCurrentSubText(nextSubText); deps.setCurrentSubText(nextSubText);
} else if (msg.name === 'sub-text-ass') { } else if (msg.name === 'sub-text/ass' || msg.name === 'sub-text-ass') {
deps.emitSubtitleAssChange({ text: (msg.data as string) || '' }); deps.emitSubtitleAssChange({ text: (msg.data as string) || '' });
} else if (msg.name === 'sub-start') { } else if (msg.name === 'sub-start') {
deps.setCurrentSubStart((msg.data as number) || 0); deps.setCurrentSubStart((msg.data as number) || 0);
@@ -281,7 +283,25 @@ export async function dispatchMpvProtocolMessage(
: typeof msg.data === 'string' : typeof msg.data === 'string'
? Number(msg.data) ? Number(msg.data)
: null; : null;
deps.emitSubtitleTrackChange({ sid: sid !== null && Number.isFinite(sid) ? sid : null }); deps.emitSubtitleTrackChange({ sid: sid !== null && Number.isInteger(sid) ? sid : null });
} else if (msg.name === 'secondary-sid') {
const sid =
typeof msg.data === 'number'
? msg.data
: typeof msg.data === 'string'
? Number(msg.data)
: null;
deps.emitSecondarySubtitleTrackChange({
sid: sid !== null && Number.isInteger(sid) ? sid : null,
});
} else if (msg.name === 'secondary-sub-delay') {
const delay =
typeof msg.data === 'number'
? msg.data
: typeof msg.data === 'string'
? Number(msg.data)
: 0;
deps.emitSecondarySubtitleDelayChange({ delay: Number.isFinite(delay) ? delay : 0 });
} else if (msg.name === 'track-list') { } else if (msg.name === 'track-list') {
deps.emitSubtitleTrackListChange({ deps.emitSubtitleTrackListChange({
trackList: Array.isArray(msg.data) ? (msg.data as unknown[]) : null, trackList: Array.isArray(msg.data) ? (msg.data as unknown[]) : null,
+78 -1
View File
@@ -38,7 +38,15 @@ class ManualCloseSocket extends FakeSocket {
} }
} }
const wait = () => new Promise((resolve) => setTimeout(resolve, 0)); class HangingSocket extends FakeSocket {
override connect(path: string): void {
this.connectedPaths.push(path);
// Never emits 'connect', 'error', or 'close' on its own: models a named
// pipe dial that stalls indefinitely.
}
}
const wait = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));
test('getMpvReconnectDelay follows existing reconnect ramp', () => { test('getMpvReconnectDelay follows existing reconnect ramp', () => {
assert.equal(getMpvReconnectDelay(0, true), 1000); assert.equal(getMpvReconnectDelay(0, true), 1000);
@@ -232,6 +240,75 @@ test('MpvSocketTransport.shutdown clears socket and lifecycle flags', async () =
assert.deepEqual(events, []); assert.deepEqual(events, []);
}); });
test('MpvSocketTransport aborts a hung connect after the timeout and allows a fresh dial', async () => {
const events: string[] = [];
const errors: Error[] = [];
const sockets: HangingSocket[] = [];
const transport = new MpvSocketTransport({
socketPath: '/tmp/mpv.sock',
connectTimeoutMs: 5,
onConnect: () => {
events.push('connect');
},
onData: () => {},
onError: (error) => {
events.push('error');
errors.push(error);
},
onClose: () => {
events.push('close');
},
socketFactory: () => {
const socket = new HangingSocket();
sockets.push(socket);
return socket as unknown as net.Socket;
},
});
transport.connect();
assert.equal(transport.isConnecting, true);
await wait(20);
assert.deepEqual(events, ['error', 'close']);
assert.match(errors[0]!.message, /connect timed out/);
assert.equal(sockets[0]!.destroyed, true);
assert.equal(transport.isConnecting, false);
assert.equal(transport.isConnected, false);
transport.connect();
assert.equal(transport.isConnecting, true);
assert.equal(sockets.length, 2);
assert.equal(sockets[1]!.connectedPaths.at(0), '/tmp/mpv.sock');
transport.shutdown();
});
test('MpvSocketTransport does not fire the connect timeout after a successful connect', async () => {
const events: string[] = [];
const transport = new MpvSocketTransport({
socketPath: '/tmp/mpv.sock',
connectTimeoutMs: 5,
onConnect: () => {
events.push('connect');
},
onData: () => {},
onError: () => {
events.push('error');
},
onClose: () => {
events.push('close');
},
socketFactory: () => new FakeSocket() as unknown as net.Socket,
});
transport.connect();
await wait(20);
assert.deepEqual(events, ['connect']);
assert.equal(transport.isConnected, true);
});
test('MpvSocketTransport ignores stale socket events after shutdown and reconnect', async () => { test('MpvSocketTransport ignores stale socket events after shutdown and reconnect', async () => {
const events: string[] = []; const events: string[] = [];
const sockets: ManualCloseSocket[] = []; const sockets: ManualCloseSocket[] = [];
+36
View File
@@ -62,6 +62,8 @@ interface MpvSocketTransportEvents {
onClose: () => void; onClose: () => void;
} }
export const MPV_CONNECT_TIMEOUT_MS = 5000;
export interface MpvSocketTransportOptions { export interface MpvSocketTransportOptions {
socketPath: string; socketPath: string;
onConnect: () => void; onConnect: () => void;
@@ -69,13 +71,16 @@ export interface MpvSocketTransportOptions {
onError: (error: Error) => void; onError: (error: Error) => void;
onClose: () => void; onClose: () => void;
socketFactory?: () => net.Socket; socketFactory?: () => net.Socket;
connectTimeoutMs?: number;
} }
export class MpvSocketTransport { export class MpvSocketTransport {
private socketPath: string; private socketPath: string;
private readonly callbacks: MpvSocketTransportEvents; private readonly callbacks: MpvSocketTransportEvents;
private readonly socketFactory: () => net.Socket; private readonly socketFactory: () => net.Socket;
private readonly connectTimeoutMs: number;
private socketRef: net.Socket | null = null; private socketRef: net.Socket | null = null;
private connectTimer: ReturnType<typeof setTimeout> | null = null;
public socket: net.Socket | null = null; public socket: net.Socket | null = null;
public connected = false; public connected = false;
public connecting = false; public connecting = false;
@@ -83,6 +88,7 @@ export class MpvSocketTransport {
constructor(options: MpvSocketTransportOptions) { constructor(options: MpvSocketTransportOptions) {
this.socketPath = options.socketPath; this.socketPath = options.socketPath;
this.socketFactory = options.socketFactory ?? (() => new net.Socket()); this.socketFactory = options.socketFactory ?? (() => new net.Socket());
this.connectTimeoutMs = options.connectTimeoutMs ?? MPV_CONNECT_TIMEOUT_MS;
this.callbacks = { this.callbacks = {
onConnect: options.onConnect, onConnect: options.onConnect,
onData: options.onData, onData: options.onData,
@@ -91,6 +97,31 @@ export class MpvSocketTransport {
}; };
} }
private clearConnectTimeout(): void {
if (this.connectTimer) {
clearTimeout(this.connectTimer);
this.connectTimer = null;
}
}
// A named-pipe/socket dial that neither connects nor errors would otherwise
// latch `connecting` forever and silently block every future connect().
private armConnectTimeout(socket: net.Socket): void {
this.clearConnectTimeout();
this.connectTimer = setTimeout(() => {
this.connectTimer = null;
if (this.socketRef !== socket || this.connected) return;
this.connecting = false;
this.callbacks.onError(
new Error(`MPV IPC connect timed out after ${this.connectTimeoutMs}ms: ${this.socketPath}`),
);
// Destroying the socket emits 'close', which drives the normal
// disconnect path (including reconnect scheduling) upstream.
socket.destroy();
}, this.connectTimeoutMs);
this.connectTimer.unref?.();
}
setSocketPath(socketPath: string): void { setSocketPath(socketPath: string): void {
this.socketPath = socketPath; this.socketPath = socketPath;
} }
@@ -111,6 +142,7 @@ export class MpvSocketTransport {
socket.on('connect', () => { socket.on('connect', () => {
if (this.socketRef !== socket) return; if (this.socketRef !== socket) return;
this.clearConnectTimeout();
this.connected = true; this.connected = true;
this.connecting = false; this.connecting = false;
this.callbacks.onConnect(); this.callbacks.onConnect();
@@ -123,6 +155,7 @@ export class MpvSocketTransport {
socket.on('error', (error: Error) => { socket.on('error', (error: Error) => {
if (this.socketRef !== socket) return; if (this.socketRef !== socket) return;
this.clearConnectTimeout();
this.connected = false; this.connected = false;
this.connecting = false; this.connecting = false;
this.callbacks.onError(error); this.callbacks.onError(error);
@@ -130,12 +163,14 @@ export class MpvSocketTransport {
socket.on('close', () => { socket.on('close', () => {
if (this.socketRef !== socket) return; if (this.socketRef !== socket) return;
this.clearConnectTimeout();
this.connected = false; this.connected = false;
this.connecting = false; this.connecting = false;
this.callbacks.onClose(); this.callbacks.onClose();
}); });
socket.connect(this.socketPath); socket.connect(this.socketPath);
this.armConnectTimeout(socket);
} }
send(payload: MpvSocketMessagePayload): boolean { send(payload: MpvSocketMessagePayload): boolean {
@@ -149,6 +184,7 @@ export class MpvSocketTransport {
} }
shutdown(): void { shutdown(): void {
this.clearConnectTimeout();
const socket = this.socketRef; const socket = this.socketRef;
this.socketRef = null; this.socketRef = null;
this.socket = null; this.socket = null;
+140
View File
@@ -1,5 +1,6 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import { import {
MpvIpcClient, MpvIpcClient,
MpvIpcClientDeps, MpvIpcClientDeps,
@@ -23,6 +24,18 @@ function makeDeps(overrides: Partial<MpvIpcClientProtocolDeps> = {}): MpvIpcClie
}; };
} }
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
async function waitFor(predicate: () => boolean, timeoutMs = 2000): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (!predicate()) {
if (Date.now() >= deadline) {
throw new Error('Timed out waiting for MPV retry connection');
}
await wait(10);
}
}
function captureWarnLogs(run: () => void): string[] { function captureWarnLogs(run: () => void): string[] {
const originalWarn = console.warn; const originalWarn = console.warn;
const originalLogLevel = process.env.SUBMINER_LOG_LEVEL; const originalLogLevel = process.env.SUBMINER_LOG_LEVEL;
@@ -505,6 +518,17 @@ test('MpvIpcClient reconnect replays property subscriptions and initial state re
(command as { command: unknown[] }).command[1] === 1 && (command as { command: unknown[] }).command[1] === 1 &&
(command as { command: unknown[] }).command[2] === 'sub-text', (command as { command: unknown[] }).command[2] === 'sub-text',
); );
const hasAssSubtitleSubscription = commands.some(
(command) =>
Array.isArray((command as { command: unknown[] }).command) &&
(command as { command: unknown[] }).command[0] === 'observe_property' &&
(command as { command: unknown[] }).command[2] === 'sub-text/ass',
);
const hasDeprecatedAssSubtitleProperty = commands.some(
(command) =>
Array.isArray((command as { command: unknown[] }).command) &&
(command as { command: unknown[] }).command.includes('sub-text-ass'),
);
const hasPathRequest = commands.some( const hasPathRequest = commands.some(
(command) => (command) =>
Array.isArray((command as { command: unknown[] }).command) && Array.isArray((command as { command: unknown[] }).command) &&
@@ -514,6 +538,8 @@ test('MpvIpcClient reconnect replays property subscriptions and initial state re
assert.equal(hasSecondaryVisibilityReset, true); assert.equal(hasSecondaryVisibilityReset, true);
assert.equal(hasTrackSubscription, true); assert.equal(hasTrackSubscription, true);
assert.equal(hasAssSubtitleSubscription, true);
assert.equal(hasDeprecatedAssSubtitleProperty, false);
assert.equal(hasPathRequest, true); assert.equal(hasPathRequest, true);
}); });
@@ -743,3 +769,117 @@ test('MpvIpcClient playNextSubtitle still auto-pauses at end while already playi
assert.equal((client as any).pendingPauseAtSubEnd, true); assert.equal((client as any).pendingPauseAtSubEnd, true);
assert.deepEqual(commands, [{ command: ['sub-seek', 1] }]); assert.deepEqual(commands, [{ command: ['sub-seek', 1] }]);
}); });
class HangingTestSocket extends EventEmitter {
public connectedPaths: string[] = [];
public destroyed = false;
connect(path: string): void {
this.connectedPaths.push(path);
// Never resolves: models a stalled named-pipe dial.
}
write(): boolean {
return true;
}
destroy(): void {
this.destroyed = true;
}
}
class RetryTestSocket extends EventEmitter {
public connectedPaths: string[] = [];
public destroyed = false;
constructor(private readonly shouldConnect: boolean) {
super();
}
connect(path: string): void {
this.connectedPaths.push(path);
if (this.shouldConnect) {
setTimeout(() => this.emit('connect'), 0);
}
}
write(): boolean {
return true;
}
destroy(): void {
if (this.destroyed) return;
this.destroyed = true;
this.emit('close');
}
}
test('MpvIpcClient automatically retries the same socket path after a connect timeout', async () => {
const sockets: RetryTestSocket[] = [];
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
const originalLogLevel = process.env.SUBMINER_LOG_LEVEL;
const client = new MpvIpcClient(
'/tmp/mpv.sock',
makeDeps({
connectTimeoutMs: 5,
getReconnectTimer: () => reconnectTimer,
setReconnectTimer: (timer) => {
reconnectTimer = timer;
},
socketFactory: () => {
const socket = new RetryTestSocket(sockets.length > 0);
sockets.push(socket);
return socket as unknown as import('node:net').Socket;
},
}),
);
process.env.SUBMINER_LOG_LEVEL = 'error';
try {
client.connect();
await waitFor(() => client.connected);
assert.equal(sockets.length, 2);
assert.equal(sockets[0]!.destroyed, true);
assert.equal(sockets[0]!.connectedPaths.at(0), '/tmp/mpv.sock');
assert.equal(sockets[1]!.connectedPaths.at(0), '/tmp/mpv.sock');
assert.equal(client.connected, true);
} finally {
if (originalLogLevel === undefined) {
delete process.env.SUBMINER_LOG_LEVEL;
} else {
process.env.SUBMINER_LOG_LEVEL = originalLogLevel;
}
if (reconnectTimer) clearTimeout(reconnectTimer);
(client as any).transport.shutdown();
}
});
test('MpvIpcClient.setSocketPath aborts an in-flight connect so the next dial targets the new path', () => {
const sockets: HangingTestSocket[] = [];
const client = new MpvIpcClient(
'/tmp/mpv-old.sock',
makeDeps({
socketFactory: () => {
const socket = new HangingTestSocket();
sockets.push(socket);
return socket as unknown as import('node:net').Socket;
},
}),
);
client.connect();
assert.equal(sockets.length, 1);
assert.equal(sockets[0]!.connectedPaths.at(0), '/tmp/mpv-old.sock');
assert.equal((client as any).connecting, true);
client.setSocketPath('/tmp/mpv-new.sock');
assert.equal((client as any).connecting, false);
assert.equal(sockets[0]!.destroyed, true);
client.connect();
assert.equal(sockets.length, 2);
assert.equal(sockets[1]!.connectedPaths.at(0), '/tmp/mpv-new.sock');
(client as any).transport.shutdown();
});
+25 -1
View File
@@ -9,7 +9,11 @@ import {
splitMpvMessagesFromBuffer, splitMpvMessagesFromBuffer,
} from './mpv-protocol'; } from './mpv-protocol';
import { requestMpvInitialState, subscribeToMpvProperties } from './mpv-properties'; import { requestMpvInitialState, subscribeToMpvProperties } from './mpv-properties';
import { scheduleMpvReconnect, MpvSocketTransport } from './mpv-transport'; import {
scheduleMpvReconnect,
MpvSocketTransport,
MpvSocketTransportOptions,
} from './mpv-transport';
import { createLogger } from '../../logger'; import { createLogger } from '../../logger';
const logger = createLogger('main:mpv'); const logger = createLogger('main:mpv');
@@ -110,6 +114,8 @@ export interface MpvIpcClientProtocolDeps {
shouldAutoLoadSecondarySubTrack?: (path: string) => boolean; shouldAutoLoadSecondarySubTrack?: (path: string) => boolean;
shouldQuitOnMpvShutdown?: () => boolean; shouldQuitOnMpvShutdown?: () => boolean;
requestAppQuit?: () => void; requestAppQuit?: () => void;
socketFactory?: MpvSocketTransportOptions['socketFactory'];
connectTimeoutMs?: number;
} }
export interface MpvIpcClientDeps extends MpvIpcClientProtocolDeps {} export interface MpvIpcClientDeps extends MpvIpcClientProtocolDeps {}
@@ -125,6 +131,8 @@ export interface MpvIpcClientEventMap {
'fullscreen-change': { fullscreen: boolean }; 'fullscreen-change': { fullscreen: boolean };
'secondary-subtitle-change': { text: string }; 'secondary-subtitle-change': { text: string };
'subtitle-track-change': { sid: number | null }; 'subtitle-track-change': { sid: number | null };
'secondary-subtitle-track-change': { sid: number | null };
'secondary-subtitle-delay-change': { delay: number };
'subtitle-track-list-change': { trackList: unknown[] | null }; 'subtitle-track-list-change': { trackList: unknown[] | null };
'media-path-change': { path: string }; 'media-path-change': { path: string };
'media-title-change': { title: string | null }; 'media-title-change': { title: string | null };
@@ -188,6 +196,8 @@ export class MpvIpcClient implements MpvClient {
this.transport = new MpvSocketTransport({ this.transport = new MpvSocketTransport({
socketPath, socketPath,
socketFactory: deps.socketFactory,
connectTimeoutMs: deps.connectTimeoutMs,
onConnect: () => { onConnect: () => {
this.connected = true; this.connected = true;
this.connecting = false; this.connecting = false;
@@ -289,6 +299,14 @@ export class MpvIpcClient implements MpvClient {
previousSocketPath: this.socketPath, previousSocketPath: this.socketPath,
socketPath, socketPath,
}); });
if (this.connecting && !this.connected) {
// Abort the in-flight dial to the old path; otherwise the connecting
// latch turns every later connect() into a no-op while we hang on a
// stale socket.
logger.debug('Aborting in-flight MPV IPC connect for socket path change.');
this.transport.shutdown();
this.connecting = false;
}
} }
this.socketPath = socketPath; this.socketPath = socketPath;
this.transport.setSocketPath(socketPath); this.transport.setSocketPath(socketPath);
@@ -422,6 +440,12 @@ export class MpvIpcClient implements MpvClient {
emitSubtitleTrackChange: (payload) => { emitSubtitleTrackChange: (payload) => {
this.emit('subtitle-track-change', payload); this.emit('subtitle-track-change', payload);
}, },
emitSecondarySubtitleTrackChange: (payload) => {
this.emit('secondary-subtitle-track-change', payload);
},
emitSecondarySubtitleDelayChange: (payload) => {
this.emit('secondary-subtitle-delay-change', payload);
},
emitSubtitleTrackListChange: (payload) => { emitSubtitleTrackListChange: (payload) => {
this.emit('subtitle-track-list-change', payload); this.emit('subtitle-track-list-change', payload);
}, },
@@ -0,0 +1,21 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { applyOverlayClickThrough } from './overlay-click-through';
test('applyOverlayClickThrough requests forwarding only off Windows', () => {
const calls: Array<{ ignore: boolean; forward: boolean }> = [];
const window = {
setIgnoreMouseEvents: (ignore: boolean, options?: { forward?: boolean }) => {
calls.push({ ignore, forward: options?.forward === true });
},
};
applyOverlayClickThrough(window, true);
applyOverlayClickThrough(window, false);
assert.deepEqual(calls, [
{ ignore: true, forward: false },
{ ignore: true, forward: true },
]);
});
@@ -0,0 +1,27 @@
type ClickThroughWindow = {
setIgnoreMouseEvents: (ignore: boolean, options?: { forward?: boolean }) => void;
};
/**
* Puts an overlay window into click-through mode. Forwarded mouse-move ({ forward: true }) is
* what lets renderer hover tracking wake a click-through overlay, but on Windows Electron
* implements it with a global WH_MOUSE_LL hook whose callback runs on the main-process message
* loop, so any main-thread stall delays mouse input system-wide (electron/electron#10183).
* Windows instead wakes the overlay via the main-process cursor poll
* (tickWindowsOverlayPointerInteraction), so no forwarding is requested there. macOS still
* needs forwarding for renderer hover tracking; Linux ignores the flag entirely
* (electron/electron#16777).
*
* Pass isWindowsPlatform when the caller already carries a platform flag (tests simulate
* platforms through it); otherwise the real process.platform decides.
*/
export function applyOverlayClickThrough(
window: ClickThroughWindow,
isWindowsPlatform?: boolean,
): void {
if (isWindowsPlatform ?? process.platform === 'win32') {
window.setIgnoreMouseEvents(true);
} else {
window.setIgnoreMouseEvents(true, { forward: true });
}
}
+7 -7
View File
@@ -848,7 +848,7 @@ test('Windows visible overlay stays click-through and binds to mpv while tracked
} as never); } as never);
assert.ok(calls.includes('opacity:0')); assert.ok(calls.includes('opacity:0'));
assert.ok(calls.includes('mouse-ignore:true:forward')); assert.ok(calls.includes('mouse-ignore:true:plain'));
assert.ok(calls.includes('show-inactive')); assert.ok(calls.includes('show-inactive'));
assert.ok(calls.includes('sync-windows-z-order')); assert.ok(calls.includes('sync-windows-z-order'));
assert.ok(!calls.includes('move-top')); assert.ok(!calls.includes('move-top'));
@@ -1060,7 +1060,7 @@ test('tracked Windows overlay refresh rebinds while already visible', () => {
isWindowsPlatform: true, isWindowsPlatform: true,
} as never); } as never);
assert.ok(calls.includes('mouse-ignore:true:forward')); assert.ok(calls.includes('mouse-ignore:true:plain'));
assert.ok(calls.includes('sync-windows-z-order')); assert.ok(calls.includes('sync-windows-z-order'));
assert.ok(!calls.includes('move-top')); assert.ok(!calls.includes('move-top'));
assert.ok(!calls.includes('show')); assert.ok(!calls.includes('show'));
@@ -1134,7 +1134,7 @@ test('forced passthrough still reapplies while visible on Windows', () => {
forceMousePassthrough: true, forceMousePassthrough: true,
} as never); } as never);
assert.ok(calls.includes('mouse-ignore:true:forward')); assert.ok(calls.includes('mouse-ignore:true:plain'));
assert.ok(!calls.includes('always-on-top:false')); assert.ok(!calls.includes('always-on-top:false'));
assert.ok(!calls.includes('move-top')); assert.ok(!calls.includes('move-top'));
assert.ok(calls.includes('sync-windows-z-order')); assert.ok(calls.includes('sync-windows-z-order'));
@@ -1339,7 +1339,7 @@ test('tracked Windows overlay rebinds without hiding when tracker focus changes'
assert.ok(!calls.includes('always-on-top:false')); assert.ok(!calls.includes('always-on-top:false'));
assert.ok(!calls.includes('move-top')); assert.ok(!calls.includes('move-top'));
assert.ok(calls.includes('mouse-ignore:true:forward')); assert.ok(calls.includes('mouse-ignore:true:plain'));
assert.ok(calls.includes('sync-windows-z-order')); assert.ok(calls.includes('sync-windows-z-order'));
assert.ok(!calls.includes('ensure-level')); assert.ok(!calls.includes('ensure-level'));
assert.ok(!calls.includes('enforce-order')); assert.ok(!calls.includes('enforce-order'));
@@ -1489,7 +1489,7 @@ test('tracked Windows overlay reshows click-through even if focus state is stale
isWindowsPlatform: true, isWindowsPlatform: true,
} as never); } as never);
assert.ok(calls.includes('mouse-ignore:true:forward')); assert.ok(calls.includes('mouse-ignore:true:plain'));
assert.ok(calls.includes('show-inactive')); assert.ok(calls.includes('show-inactive'));
assert.ok(!calls.includes('show')); assert.ok(!calls.includes('show'));
}); });
@@ -1532,7 +1532,7 @@ test('tracked Windows overlay binds above mpv even when tracker focus lags', ()
assert.ok(!calls.includes('always-on-top:false')); assert.ok(!calls.includes('always-on-top:false'));
assert.ok(!calls.includes('move-top')); assert.ok(!calls.includes('move-top'));
assert.ok(calls.includes('mouse-ignore:true:forward')); assert.ok(calls.includes('mouse-ignore:true:plain'));
assert.ok(calls.includes('sync-windows-z-order')); assert.ok(calls.includes('sync-windows-z-order'));
assert.ok(!calls.includes('ensure-level')); assert.ok(!calls.includes('ensure-level'));
}); });
@@ -2193,7 +2193,7 @@ test('Windows preserves visible overlay and rebinds to mpv while tracker transie
assert.ok(!calls.includes('show')); assert.ok(!calls.includes('show'));
assert.ok(!calls.includes('always-on-top:false')); assert.ok(!calls.includes('always-on-top:false'));
assert.ok(!calls.includes('move-top')); assert.ok(!calls.includes('move-top'));
assert.ok(calls.includes('mouse-ignore:true:forward')); assert.ok(calls.includes('mouse-ignore:true:plain'));
assert.ok(calls.includes('sync-windows-z-order')); assert.ok(calls.includes('sync-windows-z-order'));
assert.ok(!calls.includes('ensure-level')); assert.ok(!calls.includes('ensure-level'));
assert.ok(calls.includes('sync-shortcuts')); assert.ok(calls.includes('sync-shortcuts'));
+5 -4
View File
@@ -1,6 +1,7 @@
import type { BrowserWindow } from 'electron'; import type { BrowserWindow } from 'electron';
import { BaseWindowTracker } from '../../window-trackers'; import { BaseWindowTracker } from '../../window-trackers';
import { WindowGeometry } from '../../types'; import { WindowGeometry } from '../../types';
import { applyOverlayClickThrough } from './overlay-click-through';
import { OVERLAY_WINDOW_CONTENT_READY_FLAG } from './overlay-window-flags'; import { OVERLAY_WINDOW_CONTENT_READY_FLAG } from './overlay-window-flags';
const WINDOWS_OVERLAY_REVEAL_DELAY_MS = 48; const WINDOWS_OVERLAY_REVEAL_DELAY_MS = 48;
@@ -117,7 +118,7 @@ export function updateVisibleOverlayVisibility(args: {
clearPendingWindowsOverlayReveal(mainWindow); clearPendingWindowsOverlayReveal(mainWindow);
setOverlayWindowOpacity(mainWindow, 0); setOverlayWindowOpacity(mainWindow, 0);
} }
mainWindow.setIgnoreMouseEvents(true, { forward: true }); applyOverlayClickThrough(mainWindow, args.isWindowsPlatform);
releaseOverlayWindowLevel(mainWindow); releaseOverlayWindowLevel(mainWindow);
mainWindow.hide(); mainWindow.hide();
args.syncOverlayShortcuts(); args.syncOverlayShortcuts();
@@ -215,7 +216,7 @@ export function updateVisibleOverlayVisibility(args: {
shouldPreserveWindowsOverlayDuringFocusHandoff || shouldPreserveWindowsOverlayDuringFocusHandoff ||
(hasWindowsForegroundProcessSignal && windowsForegroundProcessName === 'mpv'); (hasWindowsForegroundProcessSignal && windowsForegroundProcessName === 'mpv');
if (shouldIgnoreMouseEvents) { if (shouldIgnoreMouseEvents) {
mainWindow.setIgnoreMouseEvents(true, { forward: true }); applyOverlayClickThrough(mainWindow, args.isWindowsPlatform);
} else { } else {
mainWindow.setIgnoreMouseEvents(false); mainWindow.setIgnoreMouseEvents(false);
} }
@@ -263,7 +264,7 @@ export function updateVisibleOverlayVisibility(args: {
if (hasNonNativeInputRegion) { if (hasNonNativeInputRegion) {
mainWindow.setIgnoreMouseEvents(false); mainWindow.setIgnoreMouseEvents(false);
} else { } else {
mainWindow.setIgnoreMouseEvents(true, { forward: true }); applyOverlayClickThrough(mainWindow, args.isWindowsPlatform);
} }
if (args.isWindowsPlatform) { if (args.isWindowsPlatform) {
scheduleWindowsOverlayReveal( scheduleWindowsOverlayReveal(
@@ -424,7 +425,7 @@ export function updateVisibleOverlayVisibility(args: {
return; return;
} }
args.setTrackerNotReadyWarningShown(false); args.setTrackerNotReadyWarningShown(false);
mainWindow.setIgnoreMouseEvents(true, { forward: true }); applyOverlayClickThrough(mainWindow, args.isWindowsPlatform);
releaseOverlayWindowLevel(mainWindow); releaseOverlayWindowLevel(mainWindow);
mainWindow.hide(); mainWindow.hide();
args.syncOverlayShortcuts(); args.syncOverlayShortcuts();
@@ -15,6 +15,32 @@ test('overlay window config explicitly disables renderer sandbox for preload com
assert.equal(options.webPreferences?.backgroundThrottling, false); assert.equal(options.webPreferences?.backgroundThrottling, false);
}); });
test('macOS modal overlay uses a fullscreen auxiliary panel without changing the passive overlay', () => {
const visibleOptions = buildOverlayWindowOptions('visible', {
isDev: false,
platform: 'darwin',
yomitanSession: null,
});
const modalOptions = buildOverlayWindowOptions('modal', {
isDev: false,
platform: 'darwin',
yomitanSession: null,
});
assert.equal(visibleOptions.type, undefined);
assert.equal(modalOptions.type, 'panel');
});
test('non-macOS modal overlay remains a regular window', () => {
const options = buildOverlayWindowOptions('modal', {
isDev: false,
platform: 'linux',
yomitanSession: null,
});
assert.equal(options.type, undefined);
});
test('Linux visible overlay window allows compositor resize for mpv-sized placement', () => { test('Linux visible overlay window allows compositor resize for mpv-sized placement', () => {
const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform'); const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
@@ -1 +1,2 @@
export const OVERLAY_WINDOW_CONTENT_READY_FLAG = '__subminerOverlayContentReady'; export const OVERLAY_WINDOW_CONTENT_READY_FLAG = '__subminerOverlayContentReady';
export const OVERLAY_WINDOW_DOCUMENT_LOADED_FLAG = '__subminerOverlayDocumentLoaded';
+9 -4
View File
@@ -12,15 +12,17 @@ export function buildOverlayWindowOptions(
options: { options: {
isDev: boolean; isDev: boolean;
linuxX11FullscreenOverlay?: boolean; linuxX11FullscreenOverlay?: boolean;
platform?: NodeJS.Platform;
yomitanSession?: Session | null; yomitanSession?: Session | null;
}, },
): BrowserWindowConstructorOptions { ): BrowserWindowConstructorOptions {
const showNativeDebugFrame = process.platform === 'win32' && options.isDev; const platform = options.platform ?? process.platform;
const isLinuxVisibleOverlay = process.platform === 'linux' && kind === 'visible'; const showNativeDebugFrame = platform === 'win32' && options.isDev;
const isLinuxVisibleOverlay = platform === 'linux' && kind === 'visible';
const isLinuxFullscreenOverlay = const isLinuxFullscreenOverlay =
isLinuxVisibleOverlay && options.linuxX11FullscreenOverlay === true; isLinuxVisibleOverlay && options.linuxX11FullscreenOverlay === true;
const shouldStartAlwaysOnTop = const shouldStartAlwaysOnTop =
!(process.platform === 'win32' && kind === 'visible') && !(platform === 'win32' && kind === 'visible') &&
(!isLinuxVisibleOverlay || isLinuxFullscreenOverlay); (!isLinuxVisibleOverlay || isLinuxFullscreenOverlay);
const shouldAllowCompositorResize = isLinuxVisibleOverlay && !isLinuxFullscreenOverlay; const shouldAllowCompositorResize = isLinuxVisibleOverlay && !isLinuxFullscreenOverlay;
@@ -41,7 +43,10 @@ export function buildOverlayWindowOptions(
hasShadow: false, hasShadow: false,
focusable: !isLinuxFullscreenOverlay, focusable: !isLinuxFullscreenOverlay,
acceptFirstMouse: true, acceptFirstMouse: true,
...(process.platform === 'win32' ? { thickFrame: showNativeDebugFrame } : {}), // A macOS panel is a fullscreen auxiliary window, so modal surfaces stay on the
// active mpv Space instead of opening on SubMiner's last regular desktop.
...(platform === 'darwin' && kind === 'modal' ? { type: 'panel' as const } : {}),
...(platform === 'win32' ? { thickFrame: showNativeDebugFrame } : {}),
webPreferences: { webPreferences: {
preload: path.join(__dirname, '..', '..', 'preload.js'), preload: path.join(__dirname, '..', '..', 'preload.js'),
contextIsolation: true, contextIsolation: true,

Some files were not shown because too many files have changed in this diff Show More