Compare commits

...
58 Commits
Author SHA1 Message Date
sudacode 4d1adebf11 refactor(hachidori): drop the Docker management upload for character dictionaries
Every supported host now takes dictionary ZIPs over the link, so remove
the port 8780 upload, its hachidori.externalHostManagementUrl override and
the hachidori config section. A linked host without linked-import-v1 now
reports the update or manual-import fix.
2026-10-05 09:50:52 -07:00
sudacode e1c4d6ca94 feat(hachidori): send character dictionaries over the link to Hachidori hosts
Hachidori 0.2.3 accepts dictionary ZIPs as chunked upload requests: an
unlinked install imports them itself and a linked one forwards them to its
host. The parser bridge now imports through that path with replace, retrying
a busy commit with the same upload. Linked hosts without linked-import-v1
(hachidori-docker, older Hachidori) keep the management API upload.
2026-10-05 09:10:33 -07:00
sudacode e25d472d82 build(hachidori): bump fork to upstream 0.2.3 (991c48c) 2026-10-05 09:03:39 -07:00
sudacode 20f151482a Merge remote-tracking branch 'origin/main' into add-hachidori-backend
# Conflicts:
#	launcher/main.test.ts
#	src/cli/help.test.ts
#	src/core/services/__tests__/stats-server.test.ts
#	src/core/services/cli-command.test.ts
#	src/core/services/tokenizer/yomitan-parser-runtime.test.ts
#	src/main/overlay-runtime.test.ts
#	src/main/runtime/character-dictionary-auto-sync.test.ts
#	src/main/runtime/cli-command-context-deps.test.ts
#	src/main/runtime/cli-command-context-factory.test.ts
#	src/main/runtime/cli-command-context-main-deps.test.ts
#	src/main/runtime/composers/cli-startup-composer.test.ts
#	src/main/runtime/stats-server-runtime.test.ts
#	src/main/runtime/tray-main-actions.test.ts
#	src/main/runtime/tray-main-deps.test.ts
#	src/main/runtime/tray-runtime-handlers.test.ts
#	src/main/runtime/tray-runtime.test.ts
#	src/main/runtime/yomitan-anki-server-sync.test.ts
#	src/preload.ts
#	src/renderer/handlers/mouse.test.ts
#	src/renderer/yomitan-popup.test.ts
2026-10-05 09:01:11 -07:00
sudacode b48083ddd8 test: cut low-value tests, rewrite the rest around behavior, parallelize lanes (#285) 2026-10-05 00:07:44 -07:00
sudacode 4b6842d034 fix(setup): label missing launcher "Not set up" instead of "Not installed" (#284) 2026-10-04 17:13:10 -07:00
sudacode 170dbbb74c fix(overlay): treat Hachidori popup host as a lookup target for keys
- Match the Hachidori shadow-root host alongside the Yomitan popup host when routing keyboard events
- Update the keyboard test stub to use HACHIDORI_HOST_SELECTOR
2026-10-04 00:59:04 -07:00
sudacode 37d3f5e03e build(hachidori): bump fork to upstream 9e1dfa3 2026-10-04 00:22:41 -07:00
sudacode 55c751830e build(hachidori): bump fork to upstream 0.2.2 (2a063cd) 2026-10-04 00:04:31 -07:00
sudacode 3091d7b2a7 fix(overlay): forward imported mpv input while Hachidori only claims attention
Hachidori's popup-shown event also fires for any press that may start a
selection, so treating it as an open popup blocked imported mpv mouse
buttons and routed every key to the popup keybind handler. Once Hachidori
is the reader, forwarding, popup key routing and the controller lookup
state now require an unhidden popup pane. Wheel events over an in-document
dictionary popup stay with the popup.

Bump vendor/hachidori so presses outside a text box no longer start a
glyph drag that prevented the press.
2026-10-01 23:56:14 -07:00
sudacode 4423dd56af Merge remote-tracking branch 'origin/main' into add-hachidori-backend 2026-10-01 21:48:59 -07:00
sudacode a6df21bdc2 feat(overlay): forward mpv mouse and wheel bindings through overlay
- Accept WHEEL_UP/DOWN/LEFT/RIGHT (with modifiers) in keybindings, the plugin, and the settings key editor
- Forward mpv's MBTN_* and WHEEL_* bindings from the overlay so double-click fullscreen, wheel volume, and similar inputs work on Hyprland; SubMiner bindings and right-click pause still win
- Notify the overlay via mpv-input-bindings:changed when mpv's key set changes, fixing dead imported keys when the overlay loads before mpv connects
- Sync README requirements/quick start with the installation guide and fix the Arch MeCab install command (AUR mecab-git)
2026-10-01 01:16:44 -07:00
sudacode e5a6e3b178 Merge remote-tracking branch 'origin/main' into add-hachidori-backend 2026-09-30 20:52:27 -07:00
sudacode 152d2c0626 Merge remote-tracking branch 'origin/main' into add-hachidori-backend 2026-09-30 19:50:36 -07:00
sudacode bbb0e9b6a5 Merge remote-tracking branch 'origin/main' into add-hachidori-backend 2026-09-30 01:37:19 -07:00
sudacode e09a416422 Merge remote-tracking branch 'origin/main' into add-hachidori-backend 2026-09-29 23:00:07 -07:00
sudacode 42f86b0748 perf(subtitle-prefetch): sweep overlap spans instead of rescanning cues
- Track active cues with a single sorted start/end sweep across boundaries
- Join simultaneous cues in cue-list order to match mpv
- Skip empty or inverted cues
- Add test for multi-cue overlap spans with unsorted cue input
2026-09-29 22:17:10 -07:00
sudacode e69cd5ea06 Merge remote-tracking branch 'origin/main' into add-hachidori-backend 2026-09-29 20:31:17 -07:00
sudacode 0cff52f8e4 Merge remote-tracking branch 'origin/main' into add-hachidori-backend 2026-09-29 20:27:55 -07:00
sudacode b52692d826 feat(hachidori): derive Docker management URL from the linked host
- Default character dictionary uploads to the linked host on port 8780; externalHostManagementUrl is now an optional override
- Warn when the override points at a different machine than the link
- Browser/app hosts report where to import the merged ZIP manually
- Name the management origin when the upload request cannot connect
- Update config descriptions, generated examples, docs, and changelog fragment
2026-09-29 20:22:07 -07:00
sudacode 4ab5e37bc5 build(hachidori): bump fork to 32e5346 2026-09-29 19:03:07 -07:00
sudacode f00b830054 Merge remote-tracking branch 'origin/main' into add-hachidori-backend 2026-09-29 18:49:49 -07:00
sudacode ec73157f37 build(deps): revert fast-uri override to 3.1.7
- Pin the fast-uri override in package.json and bun.lock back to 3.1.7 from 3.1.8
2026-09-28 22:37:29 -07:00
sudacode 45212c7659 build(hachidori): bump fork to upstream 6faca95
Upstream dropped Firefox, so the overlay copy now turns off custom JavaScript
from its plain capability flag. The Anki audio fixture follows the removal of
media capture options.
2026-09-28 21:42:37 -07:00
sudacode b710822db2 build(deps): bump fast-uri override to 3.1.8 for audit advisories 2026-09-28 21:18:38 -07:00
sudacode b347fdf21a feat(youtube): add YouTube browser window and Whisper subtitle source
- Add `subminer youtube`/`yt` and tray "Browse YouTube" window that plays or queues picked videos in mpv
- Add `youtube.subtitleSource` (`youtube` | `whisper`) to transcribe YouTube audio via subtitle generation
- Allow the subtitle generation modal on YouTube videos
- Pick the real Japanese track over machine-translated ones and fall back to yt-dlp on HTTP 429
- Remove legacy launcher youtubeSubgen/whisper/AI args and `--youtube-mode`
- Fix EPIPE crash when the launching terminal is closed with Ctrl+C
- Thin media timing review handles with orange original-boundary bars
- Update docs and change fragments
2026-09-28 20:46:11 -07:00
sudacode a4325740b7 fix(subtitle-prefetch): reuse startup runs and prefetch overlap lines
- Warm combined text for overlapping subtitle cues.
- Preserve valid in-flight tokenization across startup restarts while rejecting invalidated cache results.
2026-09-28 01:17:59 -07:00
sudacode 4648c5e5a1 chore(hachidori): update submodule to upstream 1a12326
Merge 8 upstream Hachidori commits into the subminer fork, including the
Google Docs experimental lookup, monochrome image palette colours and Anki
deferred-audio fixes.
2026-09-25 23:02:23 -07:00
sudacode 72d0b19d94 Merge remote-tracking branch 'origin/main' into add-hachidori-backend 2026-09-24 21:33:27 -07:00
sudacode c627095e6e Merge remote-tracking branch 'origin/main' into add-hachidori-backend 2026-09-24 20:43:02 -07:00
sudacode dea1136170 Merge remote-tracking branch 'origin/main' into add-hachidori-backend
# Conflicts:
#	docs-site/anki-integration.md
#	docs-site/immersion-tracking.md
#	docs-site/shortcuts.md
#	docs-site/usage.md
2026-09-24 17:26:30 -07:00
sudacode 874d2c9f1a fix(hachidori): preserve setup completion while host connects
- Reopen setup only when a reachable host has no dictionaries
2026-09-24 14:02:27 -07:00
sudacode 52fc1b63e9 fix(launcher): validate login shell paths before execution
- Fall back to absolute default shells when configured values are relative
- Reject invalid shells before spawning them
2026-09-24 01:31:27 -07:00
sudacode da5074761f fix(launcher): load macOS login shell PATH for GUI launches 2026-09-24 01:10:15 -07:00
sudacode f7230db90c chore(release): prepare v0.20.0
- Build v0.20.0 changelog and release notes from changes/ fragments
- Remove package-size JSON reports and previous-release size comparisons from CI
- Download AUR release assets via curl with retries and skip publish on failure
- Update release docs, verification lanes, and workflow tests to match
2026-09-24 00:01:03 -07:00
sudacode 92ef305e8c chore(hachidori): update submodule to fork subminer 441971b
Pull in the fork fix that looks up popup definition text only when the
pointer is on a glyph, so hovering beside a short glossary row no longer
opens a nested popup for the next row's word.
2026-09-23 22:59:10 -07:00
sudacode 504faa51e0 fix(anki): honor overlay pause that races timing review setup
- Track overlay pauses per review request so a pause arriving while setup reads mpv's pause state still cancels the playback restore
- Ignore cancelPlaybackResume when no review request is in flight
- Add a test covering the pause-read race and reset between requests
2026-09-23 20:08:01 -07:00
sudacode c10174f9cd fix(dictionary): pin Hachidori extension ID with a static manifest key
Electron derives an unpacked extension's ID from its directory, so a changed
userData path gave Hachidori a new storage origin and an empty library. The
staged copy now carries a fixed key, like the bundled Yomitan.
2026-09-23 09:15:33 -07:00
sudacode 33e694bc61 fix(anki): keep playback paused after overlay pause during timing review
- Treat overlay pause requests during an open media timing review as final: drop held resumes and the review's own playback restore
- Add cancelPlaybackResume to the media timing review runtime
- Test both paused and playing starting states
2026-09-23 01:36:11 -07:00
sudacode 430120cc63 fix(anki): hold playback paused while media timing review is open
- Defer overlay resume requests (popup closed, hover left) during an active review and apply them when the review closes
- Add deferPlaybackResume to the media timing review runtime and gate sendRendererMpvCommand on it
- Document the paused-playback behavior and add a changelog fragment
2026-09-23 00:32:35 -07:00
sudacode 294e3a777e chore(hachidori): update submodule to upstream d68089e
Merge 104 upstream Hachidori commits into the subminer fork, including
rebuilt engine artifacts and upstream glyph hover hit-testing.
2026-09-22 22:42:05 -07:00
sudacode c673b71053 fix(dictionary): restore Anki proxy marker when Hachidori sync fails
- Revert the proxy marker to its previous value when every settings write attempt fails, so it no longer claims a server that was never written
- Add a test for the all-writes-fail path
- Retry Windows managed runtime cleanup in the test while bun.exe stays locked after exit
2026-09-22 22:08:51 -07:00
sudacode d31a28c54f fix(dictionary): handle Hachidori extension load failures gracefully
- Catch errors from the Hachidori extension runtime and log them
- Clear the extension and session state and return null instead of rejecting
2026-09-22 21:54:49 -07:00
sudacode d100789232 fix(anki): regenerate sentence furigana when mined context changes
- Regenerate SentenceFurigana from the final sentence after timing-review expansion or stats-dashboard word mining
- Add a Yomitan parseText-based generator with a 10s timeout and escaped, highlighted output
- Clear stale furigana on failure so templates fall back to Sentence
- Keep existing furigana formatting when the sentence is unchanged
- Document the behavior in the anki-integration and immersion-tracking docs
2026-09-22 21:46:06 -07:00
sudacode 9a5fb02cbd fix(dictionary): sync Hachidori deck to ankiConnect.deck for polling
- Always set the first Hachidori Anki template deck to ankiConnect.deck so polling mode enriches Hachidori cards; other custom template settings stay intact
- Treat right-clicks retargeted to the Hachidori popup shadow host as overlay interactions so they no longer raise mpv or toggle pause
- Update anki-integration docs and changelog fragment
2026-09-22 21:43:53 -07:00
sudacode 2ba820f41a fix(dictionary): keep Hachidori lookup highlight on in SubMiner builds
Hachidori's overlay-mode first-install options turn off "Highlight the
word on the page" because GSM-style hosts screenshot the see-through
viewport. SubMiner captures media from mpv, and without the highlight
the subtitle sidebar gave no sign of which word was looked up or where
the match ended. The staged copy now seeds the highlight on; the fork
source is unchanged.
2026-09-22 21:06:19 -07:00
sudacode c39dbb5a8d fix(overlay): keep Hachidori attention from pausing playback
Hachidori's hachidori-popup-shown/hidden pair means "the reader needs
mouse events", which includes a left press anywhere on the overlay that
may start a selection. SubMiner treated it as popup visibility, so a
click paused and resumed mpv, and holding the button kept it paused.
The host element only exists after the first lookup, so the first
attempt (gate on an open popup pane when a host exists) still paused
on clicks before any lookup.

Once a Hachidori event has been seen, popup auto-pause now requires an
unhidden popup pane in the host's shadow root, and rechecks after each
successful lookup so drag-select popups still pause.
2026-09-22 21:06:19 -07:00
sudacode 2958591ec9 fix(dictionary): open Hachidori hover popups only over subtitle glyphs
Pin the Hachidori fork fix that stops the caret snapping into the line box
from looking up a subtitle's first word when the pointer is beside the line,
which kept the popup open and playback paused.
2026-09-22 20:39:35 -07:00
sudacode c9880efee3 test(anilist): apply sqlite pragmas in cover art fetcher tests
- Call applyPragmas before ensureSchema so test databases match the production setup
2026-09-22 19:30:31 -07:00
sudacode f225ac3c89 fix(dictionary): block --yomitan when an external profile is configured
- Keep read-only external-profile mode while Hachidori is active by checking the configured externalProfilePath
- Hachidori settings remain available
- Smoke check asserts the external-profile block, with a --bundled-yomitan path for the bundled case
- Update usage docs and changelog fragment
2026-09-22 19:03:39 -07:00
sudacode cacaa2b371 feat(overlay): add subtitle selection modal and Jellyfin 12 fixes
- Add an optional subtitle selection modal for primary/secondary mpv tracks (subtitleSelection.enabled, g-s sequence shortcut) with key-sequence conflict handling
- Authenticate Jellyfin URLs with the ApiKey query, answer remote keep-alives, clear now-playing on stop, and restore episode titles in Anki misc info
- Honor the configured mpv executable when Jellyfin starts playback via a shared mpv-process launcher
- Bump electron-builder to 26.16.1
- Condense and reconcile changelog fragments; update config example and docs
2026-09-22 18:51:59 -07:00
sudacode 9fe4c7eb33 fix(anki): preserve managed proxy state when settings sync fails 2026-09-22 15:49:24 -07:00
sudacode ab5e50adac fix(dictionary): complete Hachidori imports and mining integration 2026-09-22 15:01:23 -07:00
sudacode 15c74ef502 fix(dictionary): update Hachidori overlay sharing and test fixes 2026-09-22 14:26:32 -07:00
sudacode f0d3c95b4c fix(dictionary): pin Hachidori stats mining fix 2026-09-22 14:04:09 -07:00
sudacode d7e1d7edc6 refactor: configure Hachidori in the SubMiner build 2026-09-22 12:26:37 -07:00
sudacode 5354fdf7b9 refactor(dictionary): use Hachidori fork submodule and upstream API 2026-09-22 01:22:14 -07:00
sudacode d9fdc7ef6d feat(dictionary): add Hachidori backend support
- Add backend selection, setup gating, Anki integration, and external host support
- Add launcher flags, documentation, packaging, and focused tests
- Open on-demand overlay modals on the first attempt
2026-09-22 00:21:19 -07:00
481 changed files with 23544 additions and 60601 deletions

No files matched your search

+2
View File
@@ -20,6 +20,8 @@ coverage/
/main-entry.js /main-entry.js
/main-entry.js.map /main-entry.js.map
/build/hachidori/
# Logs # Logs
*.log *.log
npm-debug.log* npm-debug.log*
+4
View File
@@ -8,3 +8,7 @@
[submodule "vendor/subminer-yomitan"] [submodule "vendor/subminer-yomitan"]
path = vendor/subminer-yomitan path = vendor/subminer-yomitan
url = https://github.com/ksyasuda/subminer-yomitan url = https://github.com/ksyasuda/subminer-yomitan
[submodule "vendor/hachidori"]
path = vendor/hachidori
url = https://github.com/ksyasuda/hachidori.git
branch = subminer
+2 -1
View File
@@ -8,6 +8,7 @@ Start here, then leave this file.
- Architecture map: [`docs/architecture/README.md`](./docs/architecture/README.md) - Architecture map: [`docs/architecture/README.md`](./docs/architecture/README.md)
- Workflow map: [`docs/workflow/README.md`](./docs/workflow/README.md) - Workflow map: [`docs/workflow/README.md`](./docs/workflow/README.md)
- Verification lanes: [`docs/workflow/verification.md`](./docs/workflow/verification.md) - Verification lanes: [`docs/workflow/verification.md`](./docs/workflow/verification.md)
- Testing guidelines: [`docs/workflow/testing.md`](./docs/workflow/testing.md)
- Knowledge-base rules: [`docs/knowledge-base/README.md`](./docs/knowledge-base/README.md) - Knowledge-base rules: [`docs/knowledge-base/README.md`](./docs/knowledge-base/README.md)
- Release guide: [`docs/RELEASING.md`](./docs/RELEASING.md) - Release guide: [`docs/RELEASING.md`](./docs/RELEASING.md)
@@ -47,7 +48,7 @@ Start here, then leave this file.
- Build/release scripts (`scripts/**`): `bun run test:scripts` - Build/release scripts (`scripts/**`): `bun run test:scripts`
- Internal docs, `AGENTS.md`, or repo skills: `bun run test:docs:kb` - Internal docs, `AGENTS.md`, or repo skills: `bun run test:docs:kb`
- User-facing `docs-site/`: `bun run docs:test`, then `bun run docs:build` - User-facing `docs-site/`: `bun run docs:test`, then `bun run docs:build`
- macOS mpv window helper: `bun test scripts/get-mpv-window-macos.test.ts` - macOS mpv window helper (`scripts/get-mpv-window-macos.swift`): compile it on macOS with `bun run build`
- Test lanes are directory-discovered via `scripts/test-lanes.ts`; never hand-list test files in `package.json` - Test lanes are directory-discovered via `scripts/test-lanes.ts`; never hand-list test files in `package.json`
## Docs Upkeep ## Docs Upkeep
+5 -2
View File
@@ -4,7 +4,7 @@
# SubMiner # SubMiner
Look up words with Yomitan, mine them to Anki, and track your immersion without leaving mpv Look up words with Yomitan or Hachidori, mine them to Anki, and track your immersion without leaving mpv
[Installation](#quick-start) · [Requirements](#requirements) · [Usage](https://docs.subminer.moe/usage) · [Documentation](https://docs.subminer.moe) [Installation](#quick-start) · [Requirements](#requirements) · [Usage](https://docs.subminer.moe/usage) · [Documentation](https://docs.subminer.moe)
@@ -25,6 +25,8 @@ Look up words with Yomitan, mine them to Anki, and track your immersion without
Hover over any word in the subtitles to open the full Yomitan popup with definitions, pitch accent, and frequency data. SubMiner bundles its own Yomitan, separate from any browser install. Hover over any word in the subtitles to open the full Yomitan popup with definitions, pitch accent, and frequency data. SubMiner bundles its own Yomitan, separate from any browser install.
Yomitan remains the default. Select the bundled Hachidori backend with `dictionaryBackend: "hachidori"` and restart SubMiner. The tray opens the selected backend's settings. See [dictionary setup](https://docs.subminer.moe/usage#hachidori-setup) for importing dictionaries, linking an external Hachidori host, and configuring Anki.
<div align="center"> <div align="center">
<img src="docs-site/public/screenshots/yomitan-lookup.png" width="800" alt="Yomitan dictionary popup over annotated subtitles in mpv"> <img src="docs-site/public/screenshots/yomitan-lookup.png" width="800" alt="Yomitan dictionary popup over annotated subtitles in mpv">
</div> </div>
@@ -265,7 +267,8 @@ SubMiner builds on the work of these open-source projects:
| [jellyfin-mpv-shim](https://github.com/jellyfin/jellyfin-mpv-shim) | Jellyfin integration | | [jellyfin-mpv-shim](https://github.com/jellyfin/jellyfin-mpv-shim) | Jellyfin integration |
| [Jimaku.cc](https://jimaku.cc) | Japanese subtitle search and downloads | | [Jimaku.cc](https://jimaku.cc) | Japanese subtitle search and downloads |
| [Renji's Texthooker Page](https://github.com/Renji-XD/texthooker-ui) | Base for the WebSocket texthooker integration | | [Renji's Texthooker Page](https://github.com/Renji-XD/texthooker-ui) | Base for the WebSocket texthooker integration |
| [Yomitan](https://github.com/yomidevs/yomitan) | Dictionary engine powering all lookups and the morphological parser | | [Yomitan](https://github.com/yomidevs/yomitan) | Default dictionary engine and morphological parser |
| [Hachidori](https://github.com/bee-san/hachidori) | Alternative dictionary backend, powered by HoshiDicts |
| [yomitan-jlpt-vocab](https://github.com/stephenmk/yomitan-jlpt-vocab) | JLPT level tags for vocabulary | | [yomitan-jlpt-vocab](https://github.com/stephenmk/yomitan-jlpt-vocab) | JLPT level tags for vocabulary |
## License ## License
@@ -0,0 +1,4 @@
type: fixed
area: anki
- Media timing review now keeps playback paused while it is open when the dictionary popup or subtitle hover pause ends, as with Hachidori popups closing when the review appears. Playback resumes after the review closes unless a dictionary popup is still open.
+14
View File
@@ -0,0 +1,14 @@
type: added
area: dictionary
- Added a bundled Hachidori dictionary backend alongside the default Yomitan backend. Select it with `dictionaryBackend` and restart SubMiner.
- The tray and dictionary-settings shortcut follow the selected backend. `--hachidori` opens Hachidori settings, while `--yomitan` opens Yomitan settings unless a read-only external Yomitan profile is configured. This restriction also applies with Hachidori active, without blocking Hachidori settings.
- Hachidori integrates with subtitle scanning, popup controls, lookup tracking, character dictionaries, and Anki media enrichment, with separate dictionaries and settings for each backend. Character dictionaries reach a linked host over the link (Hachidori 0.2.3 or later, or a current Docker host), retry busy imports, and replace the previous dictionary only after a successful import. Older hosts report where to import the dictionary manually.
- Hachidori auto-populates its first Anki template from SubMiner's deck, tags, and field mappings, detects an unambiguous matching note type, and preserves existing custom templates apart from the deck, which follows `ankiConnect.deck` so polling mode enriches Hachidori cards. Anki discovery retries after an unavailable connection.
- Hachidori saves downloadable word audio before sending a note through SubMiner's Anki proxy, so freshly mined animated cards include the word-audio delay.
- Both bundled dictionary backends reload their background code on startup so extension updates take effect while preserving installed dictionaries and settings. Failed Yomitan connection-setting updates can be retried without manually resetting the managed Anki endpoint.
- First-run setup remembers each backend that finished it, including when reopened for legacy plugin cleanup, so switching back does not repeat setup, and the launcher gates playback on the backend the running app started with. Current incomplete or cancelled setup takes precedence over stale completion history. A running Yomitan session keeps using its external profile until it restarts into Hachidori.
- Stats dashboard mining and deck lookup use the selected backend, with the Anki proxy enabled or disabled. Dashboard cards retain the selected history line and media instead of being processed again with the current mpv subtitle, with both Yomitan and Hachidori. Stats cards carry a `SubMiner::Stats` tag so polling also preserves their context. Hachidori word mining supplies dictionary aliases, IDs, and frequency metadata to its native Anki renderer. Settings labels for popup pause and the dictionary deck no longer name Yomitan, and the backend selector sits with the other dictionary settings.
- Hachidori scans, dictionary counts, and settings reads wait for the dictionary engine to finish loading or importing instead of caching empty results.
- First-run setup can link an external Hachidori dictionary host in an app, browser, or Docker container, verify its library, and unlink back to local dictionaries. The optional host controls are collapsed by default and explain which apps or containers must stay running. Unresponsive connection checks time out so setup remains usable. Anki mining, media enrichment, and custom toolbar buttons stay in SubMiner, including when editing buttons while linked.
- Hachidori frequency highlighting reuses dictionary-entry ranks and fills missing ranks through its existing API. Entries without a matching definition may remain unranked. The bundled integration is maintained in a pinned fork submodule using upstream HoshiDicts and WASM binaries.
+4
View File
@@ -0,0 +1,4 @@
type: docs
area: dictionary
- Documented backend selection, separate Hachidori dictionary and Anki setup, the settings flags and shortcuts, and external host linking with local Anki mining and the running requirements for each host type.
+4
View File
@@ -0,0 +1,4 @@
type: fixed
area: setup
- Fixed the command-line launcher showing "Not on PATH" on macOS when SubMiner was opened from Finder or the Dock, even though the launcher directory was already on your terminal PATH.
+4
View File
@@ -0,0 +1,4 @@
type: fixed
area: overlay
- Overlay modals such as the media timing review open on the first attempt when their dedicated window is created on demand, instead of after a four-second retry.
+5
View File
@@ -0,0 +1,5 @@
type: fixed
area: annotations
- Subtitle lines shown while two cues overlap (common in Jimaku and Jellyfin SRTs, and usually the long lines) are now prefetched, so their annotations appear immediately instead of after a delay.
- Subtitle prefetching no longer restarts each time the same subtitle file is re-selected during startup, and a line tokenized before a restart or seek is kept instead of discarded.
+4
View File
@@ -0,0 +1,4 @@
type: fixed
area: setup
- First-run setup now labels a missing command-line launcher "Not set up" instead of "Not installed", so the AppImage catalog test no longer reads the setup window as an error screen.
+7
View File
@@ -6,6 +6,13 @@
*/ */
{ {
// ==========================================
// Dictionary Backend
// Select the dictionary lookup backend: yomitan or hachidori.
// Restart SubMiner after changing the backend. Each backend keeps separate settings and dictionaries.
// ==========================================
"dictionaryBackend": "yomitan", // Dictionary lookup backend. Restart SubMiner after changing this setting. Values: yomitan | hachidori
// ========================================== // ==========================================
// Subtitle Selection // Subtitle Selection
// Select primary and secondary mpv subtitle tracks from the overlay. // Select primary and secondary mpv subtitle tracks from the overlay.
+22 -2
View File
@@ -15,9 +15,9 @@ If you changed AnkiConnect's port, set `ankiConnect.url` to match.
## How cards get filled ## How cards get filled
When Yomitan adds a note, SubMiner fills the sentence, audio, image, and MiscInfo fields. It finds new notes in one of two ways: When Yomitan or Hachidori adds a note, SubMiner fills the sentence, audio, image, and MiscInfo fields. It finds new notes in one of two ways:
- **Proxy (default).** SubMiner runs a local AnkiConnect-compatible server. Yomitan sends notes through it, and SubMiner fills each one right after Anki accepts it. - **Proxy (default).** SubMiner runs a local AnkiConnect-compatible server. The dictionary sends notes through it, and SubMiner fills each one right after Anki accepts it.
- **Polling.** With `ankiConnect.proxy.enabled` set to `false`, SubMiner asks AnkiConnect for recently added notes every `ankiConnect.pollingRate` milliseconds. - **Polling.** With `ankiConnect.proxy.enabled` set to `false`, SubMiner asks AnkiConnect for recently added notes every `ankiConnect.pollingRate` milliseconds.
Set `ankiConnect.behavior.autoUpdateNewCards` to `false` to stop automatic filling and update cards by hand with `Ctrl/Cmd+V` instead. Set `ankiConnect.behavior.autoUpdateNewCards` to `false` to stop automatic filling and update cards by hand with `Ctrl/Cmd+V` instead.
@@ -42,6 +42,20 @@ Clients must send notes to the proxy (`http://127.0.0.1:8766` here), not to Anki
- **Bundled Yomitan.** SubMiner sets the active Yomitan profile's Anki server for you. With the proxy on, it always points the profile at the proxy. With the proxy off, it sets `ankiConnect.url`, but only if the profile's server is blank or the stock `http://127.0.0.1:8765`. - **Bundled Yomitan.** SubMiner sets the active Yomitan profile's Anki server for you. With the proxy on, it always points the profile at the proxy. With the proxy off, it sets `ankiConnect.url`, but only if the profile's server is blank or the stock `http://127.0.0.1:8765`.
- **Browser Yomitan or other clients.** Set the Anki server to the proxy URL yourself. To leave your main profile alone, create a separate Yomitan profile for SubMiner, set its Anki server (Settings, Anki) to the proxy URL, and make it active while you mine. - **Browser Yomitan or other clients.** Set the Anki server to the proxy URL yourself. To leave your main profile alone, create a separate Yomitan profile for SubMiner, set its Anki server (Settings, Anki) to the proxy URL, and make it active while you mine.
- **Hachidori.** SubMiner routes Hachidori to the proxy while it is active. Keep the proxy on for screenshots and sentence audio.
### Hachidori settings from SubMiner
With the [Hachidori backend](/usage#hachidori-setup), SubMiner fills Hachidori's first Anki template from your `ankiConnect` settings on startup and whenever you open Hachidori Settings:
- The deck always follows `ankiConnect.deck`, because polling only looks for new cards in that deck.
- Configured tags go into untouched defaults.
- Missing word, sentence, pronunciation-audio, and picture mappings are filled with fields that exist in Anki. Pronunciation uses `fields.wordAudio`, or `fields.audio` when no word-audio field is set.
- If the note type is unset, SubMiner picks the one note type that has your word and sentence fields. Enabled Lapis, Kiku, or Senren narrows the search. A fresh mapping also gets Hachidori's matching preset for readings, definitions, and other known fields.
Apart from the deck, SubMiner only fills missing settings. Custom tags, field mappings, advanced templates, and extra templates stay as you set them. If several note types match, pick one in Hachidori Settings. If Anki was closed, start it and open Hachidori Settings again to retry.
Sentence audio, image timing, translation, metadata, and field grouping stay under SubMiner's control. Pronunciation sources are set in Hachidori. Linking an external dictionary host does not change any of this.
### Proxy troubleshooting ### Proxy troubleshooting
@@ -87,6 +101,8 @@ If cards are not getting filled:
Field names are matched case-insensitively. A mapped field that is missing from the note type is skipped. Field names are matched case-insensitively. A mapped field that is missing from the note type is skipped.
Hachidori prepares downloadable word audio before it saves a note through the proxy, so the animated image delay works on the first mine. Set a downloadable pronunciation source in Hachidori's Audio settings. Browser speech cannot be saved to Anki. Without word audio, Hachidori shows a warning and the card gets no word-audio hold.
`fields.audio` gets sentence audio, not word audio. Yomitan writes its own dictionary audio into your note, so point `fields.audio` at a separate field such as `SentenceAudio`. The default, `ExpressionAudio`, is the field many note types use for Yomitan's word audio, so leaving it would overwrite that audio. `fields.audio` gets sentence audio, not word audio. Yomitan writes its own dictionary audio into your note, so point `fields.audio` at a separate field such as `SentenceAudio`. The default, `ExpressionAudio`, is the field many note types use for Yomitan's word audio, so leaving it would overwrite that audio.
`ankiConnect.tags` adds tags to every mined or updated card. Set it to `[]` to add none. `ankiConnect.tags` adds tags to every mined or updated card. Set it to `[]` to add none.
@@ -122,6 +138,8 @@ Media settings apply to the next card without a restart.
With `media.reviewTiming` on, SubMiner pauses before making media for word, sentence, and audio cards and opens a review dialog. You can also toggle it for the current session with **Review Media Timing** in the runtime options palette (`Ctrl/Cmd+Shift+O`). Clipboard updates and stats-dashboard mining skip the review. With `media.reviewTiming` on, SubMiner pauses before making media for word, sentence, and audio cards and opens a review dialog. You can also toggle it for the current session with **Review Media Timing** in the runtime options palette (`Ctrl/Cmd+Shift+O`). Clipboard updates and stats-dashboard mining skip the review.
Playback stays paused while the dialog is open, even if the popup or hover that paused it goes away. When the dialog closes, playback resumes if it was playing before, or if the popup closed in the meantime. A popup that is still open keeps it paused.
The dialog shows the clip over a speech waveform. When the waveform loads, an untouched clip end moves back to just after the last speech in the line. The orange bars still mark the subtitle's original start and end. The dialog shows the clip over a speech waveform. When the waveform loads, an untouched clip end moves back to just after the last speech in the line. The orange bars still mark the subtitle's original start and end.
During preview, the yellow cursor follows the audio player's position through the selected range and stays at the end when playback finishes. Buffering pauses the cursor too. If the player stops reporting progress for 15 seconds, the preview stops so you can retry. During preview, the yellow cursor follows the audio player's position through the selected range and stays at the end when playback finishes. Buffering pauses the cursor too. If the player stops reporting progress for 15 seconds, the preview stops so you can retry.
@@ -208,6 +226,8 @@ For Senren, use the same keys under `isSenren`.
| `auto` | Merge into the existing card. With `deleteDuplicateInAuto`, delete the new card | | `auto` | Merge into the existing card. With `deleteDuplicateInAuto`, delete the new card |
| `manual` | Show both cards, let you choose which to keep and preview the merge | | `manual` | Show both cards, let you choose which to keep and preview the merge |
Grouping runs when a new note is added while duplicates exist. With Hachidori, that is the popup's **Add anyway** choice. **Overwrite** updates the existing note in place and only gets media.
The manual dialog cancels itself after 90 seconds. Identical entries are not deduplicated. Press `Ctrl/Cmd+G` to run the duplicate check on the last card yourself. The manual dialog cancels itself after 90 seconds. Identical entries are not deduplicated. Press `Ctrl/Cmd+G` to run the duplicate check on the last card yourself.
| Key | Action | | Key | Action |
+6
View File
@@ -67,6 +67,12 @@ Everything else needs a restart.
## Core settings ## Core settings
### Dictionary backend
`dictionaryBackend` accepts `"yomitan"` or `"hachidori"`. The default is defined in the [generated configuration example](/config.example.jsonc). Restart SubMiner after changing it. The tray shows the selected backend's settings, and the global dictionary-settings shortcut follows the same selection.
Each backend stores its own dictionaries and mining settings. `yomitan.externalProfilePath` applies only to Yomitan. See [Hachidori setup](./usage.md#hachidori-setup) before switching an existing installation.
### Logging ### Logging
Log files are named by date (`app-YYYY-MM-DD.log`, `launcher-...`, `mpv-...`). Log export writes a sanitized copy and leaves the originals alone. Log files are named by date (`app-YYYY-MM-DD.log`, `launcher-...`, `mpv-...`). Log export writes a sanitized copy and leaves the originals alone.
+4 -2
View File
@@ -91,11 +91,13 @@ Searches the primary subtitle lines and titles in your history. **Search by head
Search results and the Vocabulary word panel can create cards from past lines, as long as the source video file is still available: Search results and the Vocabulary word panel can create cards from past lines, as long as the source video file is still available:
- **Mine Word**: full Yomitan lookup for the word, plus sentence, audio, and image. - **Mine Word**: looks up the word with the selected dictionary backend (Yomitan or Hachidori), plus sentence, audio, and image. The history line you picked is the card's sentence, even while mpv plays another line. Hachidori uses its own Anki template, dictionary aliases, and frequency data.
- **Mine Sentence**: a sentence card with `IsSentenceCard` set, for Lapis and Kiku note types. - **Mine Sentence**: a sentence card with `IsSentenceCard` set, for Lapis and Kiku note types.
- **Mine Audio**: an audio card with `IsAudioCard` set. - **Mine Audio**: an audio card with `IsAudioCard` set.
Word and audio mining appear only when the word occurs in the sentence. All three use your `ankiConnect` deck, note type, fields, and media settings. Anki must be running, and Mine Word needs Yomitan dictionaries. Word and audio mining appear only when the word occurs in the sentence. All three use your `ankiConnect` deck, note type, fields, and media settings. Anki must be running, and Mine Word needs dictionaries in the selected backend.
Dashboard cards also get the `SubMiner::Stats` tag. With the Anki proxy off, SubMiner uses it to keep the chosen history line when polling picks up the card.
## Repeated lines ## Repeated lines
+7
View File
@@ -6,6 +6,13 @@
*/ */
{ {
// ==========================================
// Dictionary Backend
// Select the dictionary lookup backend: yomitan or hachidori.
// Restart SubMiner after changing the backend. Each backend keeps separate settings and dictionaries.
// ==========================================
"dictionaryBackend": "yomitan", // Dictionary lookup backend. Restart SubMiner after changing this setting. Values: yomitan | hachidori
// ========================================== // ==========================================
// Subtitle Selection // Subtitle Selection
// Select primary and secondary mpv subtitle tracks from the overlay. // Select primary and secondary mpv subtitle tracks from the overlay.
+16 -16
View File
@@ -6,12 +6,12 @@ Shortcuts work when the overlay has focus. With the [mpv plugin](/mpv-plugin), `
## Global ## Global
| Shortcut | Action | Config key | | Shortcut | Action | Config key |
| ------------- | ---------------------- | -------------------------------------- | | ------------- | ------------------------------- | -------------------------------------- |
| `Alt+Shift+O` | Toggle visible overlay | `shortcuts.toggleVisibleOverlayGlobal` | | `Alt+Shift+O` | Toggle visible overlay | `shortcuts.toggleVisibleOverlayGlobal` |
| `Alt+Shift+Y` | Open Yomitan settings | Fixed | | `Alt+Shift+Y` | Open active dictionary settings | Fixed |
`Alt+Shift+Y` is registered with the OS and works from any app. If another app already uses it, SubMiner cannot take it and you cannot rebind it. `Alt+Shift+Y` opens Yomitan or Hachidori settings, whichever backend is running. It is registered with the OS and works from any app. If another app already uses it, SubMiner cannot take it and you cannot rebind it.
## Mining ## Mining
@@ -98,17 +98,17 @@ The subtitle picker (`g` then `s`) is off until you turn it on in **Settings, Be
Press `y`, then the second key. Press `y`, then the second key.
| Keys | Action | | Keys | Action |
| ----- | -------------------------- | | ----- | ------------------------------- |
| `y-y` | Open the SubMiner menu | | `y-y` | Open the SubMiner menu |
| `y-s` | Start the overlay | | `y-s` | Start the overlay |
| `y-S` | Stop the overlay | | `y-S` | Stop the overlay |
| `y-t` | Toggle the visible overlay | | `y-t` | Toggle the visible overlay |
| `y-o` | Open Yomitan settings | | `y-o` | Open active dictionary settings |
| `y-r` | Restart the overlay | | `y-r` | Restart the overlay |
| `y-c` | Show overlay status | | `y-c` | Show overlay status |
| `y-h` | Open session help | | `y-h` | Open session help |
| `v` | Cycle primary subtitle bar | | `v` | Cycle primary subtitle bar |
The plugin's `v` replaces mpv's own subtitle visibility toggle. When the overlay has focus, `y` then `d` toggles DevTools. The plugin's `v` replaces mpv's own subtitle visibility toggle. When the overlay has focus, `y` then `d` toggles DevTools.
+40 -9
View File
@@ -16,10 +16,41 @@ Run `subminer` with no file to pick one from the current directory instead. See
### Yomitan setup ### Yomitan setup
Lookups need at least one dictionary in SubMiner's bundled Yomitan. First-run setup asks you to import one. To add more later, open Yomitan settings with `Alt+Shift+Y` or `subminer app --yomitan`. Lookups need at least one dictionary in SubMiner's bundled Yomitan (or in Hachidori, if you [switched backends](#hachidori-setup)). First-run setup asks you to import one. To add more later, open Yomitan settings with `Alt+Shift+Y` or `subminer app --yomitan`.
The bundled Yomitan is separate from any Yomitan in your browser. It has its own dictionaries and settings. The bundled Yomitan is separate from any Yomitan in your browser. It has its own dictionaries and settings.
### Hachidori setup
Hachidori is an alternative lookup backend. Set `dictionaryBackend` to `"hachidori"` in settings or `config.jsonc`, then restart SubMiner. Set it back to `"yomitan"` and restart to switch back.
Open Hachidori settings with `Alt+Shift+Y`, the tray's **Open Hachidori Settings**, or `subminer app --hachidori`. Import dictionary ZIPs or use Hachidori's recommended dictionary installer, then set up its Anki template (SubMiner [fills in what it can](/anki-integration#hachidori-settings-from-subminer)). Yomitan and Hachidori keep separate dictionaries and settings. Yomitan profiles, custom Handlebars templates, and `yomitan.externalProfilePath` do not carry over.
Hachidori uses SubMiner's subtitle scanning, popup pause, controller commands, character dictionaries, and Anki media. Keep the [Anki proxy](/anki-integration#proxy-mode-setup-yomitan-texthooker) on for screenshots and sentence audio. Hachidori's own screen recorder and screenshot capture are off inside SubMiner. `startupWarmups.yomitanExtension` and `subtitleStyle.autoPauseVideoOnYomitanPopup` apply to whichever backend is selected.
Switching backends:
- First-run setup asks for dictionaries the first time you switch to a backend. Switching back to a backend that already finished setup skips it.
- Until you restart, SubMiner keeps running the backend it started with. The launcher waits for that backend before playback and logs a restart reminder.
- `--yomitan` and `--hachidori` both work whichever backend is selected. Opening settings does not switch backends.
- When `yomitan.externalProfilePath` is set, `--yomitan` is disabled to keep the external profile read-only. Hachidori settings still open.
#### External dictionary host
First-run setup can link a Hachidori host instead of using local dictionaries: **Dictionary source → Use an external dictionary host → Link host**. Turn on sharing in the other Hachidori app or browser, or start a compatible Docker host, then enter its sharing address, for example `127.0.0.1:8771` or `ws://host:8771/link`. Use the WebSocket sharing port, not the management page or HTTP API port.
| Host | Must be running |
| -------- | ------------------------------------------- |
| Browser | The browser, the Hachidori extension, relay |
| Electron | The host app and any relay it needs |
| Docker | The container only |
Setup checks the connection and the host's dictionaries before **Finish** unlocks, so import at least one dictionary on the host and refresh. The link survives restarts. **Unlink and use local dictionaries** goes back to local.
While linked, dictionaries and dictionary settings come from the host. Anki templates, pronunciation sources, custom buttons, and SubMiner's audio and image processing stay local. Frequency annotations use ranks returned with dictionary entries, and SubMiner asks the host for missing ones. Words with no matching definition entry may stay unranked even if a frequency dictionary lists them.
SubMiner sends [character dictionaries](/character-dictionary) to the linked host over the link and replaces the previous one once the import succeeds, retrying while the host is busy. The host needs Hachidori 0.2.3 or later, or a current Docker host. With an older host, sync reports where the merged ZIP is so you can import it from that host's Hachidori settings.
## Picking files ## Picking files
```bash ```bash
@@ -33,15 +64,15 @@ See [Launcher script](/launcher-script#video-picker) for picker and history deta
## Overlay basics ## Overlay basics
| Key | Action | | Key | Action |
| ------------- | --------------------------------------------------------------------- | | ------------- | ---------------------------------------------------------------------------- |
| `Alt+Shift+O` | Show or hide the overlay (works while the overlay or mpv has focus) | | `Alt+Shift+O` | Show or hide the overlay (works while the overlay or mpv has focus) |
| `Alt+Shift+Y` | Open Yomitan settings (works from any window, not configurable) | | `Alt+Shift+Y` | Open Yomitan or Hachidori settings (works from any window, not configurable) |
| `V` | Cycle the subtitle bar through hidden, visible, and hover-only | | `V` | Cycle the subtitle bar through hidden, visible, and hover-only |
| `Ctrl+Alt+P` | Open the playlist browser to queue, reorder, or jump between episodes | | `Ctrl+Alt+P` | Open the playlist browser to queue, reorder, or jump between episodes |
| `Ctrl/Cmd+/` | Show every overlay and mpv keybinding for this session | | `Ctrl/Cmd+/` | Show every overlay and mpv keybinding for this session |
Hovering subtitle text pauses mpv, and moving away resumes it. An open Yomitan popup also keeps playback paused. Turn these off with `subtitleStyle.autoPauseVideoOnHover` and `subtitleStyle.autoPauseVideoOnYomitanPopup`. Hovering subtitle text pauses mpv, and moving away resumes it. An open dictionary popup also keeps playback paused. Turn these off with `subtitleStyle.autoPauseVideoOnHover` and `subtitleStyle.autoPauseVideoOnYomitanPopup`.
You can drop files onto the overlay: You can drop files onto the overlay:
+6
View File
@@ -46,6 +46,12 @@ Update checks and startup launcher migration share a serialized update-state sto
## Architecture Intent ## Architecture Intent
The dictionary backend is selected once at startup by `dictionaryBackend`. Yomitan keeps its existing session and external-profile policy. Hachidori uses `persist:hachidori`; overlay windows select that session before extension loading, including deferred startup. Named settings flags can open either backend without injecting a second reader into the active overlay. The detached stats word helper reads the same config key so dashboard mining uses the active backend.
`setup-state.json` records one backend's status at a time plus `completedDictionaryBackends`, the backends that finished setup before. The app projects the file onto its active backend on startup and stamps that backend into the file. The launcher gates playback on the stamped backend when an app is already running, since a config edit takes effect only after restart.
`vendor/hachidori/` is a submodule of `ksyasuda/hachidori`, tracking the `subminer` branch and pinned to a tested commit. Its nested HoshiDicts submodule and WASM binaries remain upstream versions. Initialize sources with `git submodule update --init --recursive`; merge upstream updates in the fork, test them, then update SubMiner's submodule commit. `SOURCE.json` records the upstream base and artifact checksums; the submodule commit identifies the integrated version. `build:hachidori` verifies recorded artifact checksums and stages the extension for development and packaging. It enables overlay mode, disables custom JavaScript, keeps the lookup highlight on in the overlay first-install options (SubMiner captures media from mpv, not the overlay viewport), removes the unsupported `userScripts` permission, and sets a fixed manifest `key` so the extension ID (and the storage origin holding its dictionaries and settings) does not depend on the userData path, only in that staged copy; the fork keeps upstream browser defaults. Before loading the extension, its session clears service worker registrations so Electron uses the current bundled code; dictionary databases and settings remain intact. First-run setup uses Hachidori sharing messages to link or unlink external dictionary hosts and checks their live inventory. Dictionary imports go through Hachidori's chunked upload requests (`hachidori-linked-import`): an unlinked install imports the ZIP itself and a linked one forwards it to its host. Linked hosts that do not advertise `linked-import-v1` (Hachidori before 0.2.3) cannot receive uploads, and the import reports where to import the ZIP by hand. Linked dictionaries and dictionary edits use the host, while Anki configuration, pronunciation sources, custom buttons, and mining stay local to SubMiner. The parser bridge adapts its runtime messages to the existing subtitle scanner and dictionary automation. Scanning retains term-entry frequencies, and only tokens without ranks need further frequency lookups through the existing term-entry API. This requires a matching definition entry and does not preserve the frequency source's reading provenance. SubMiner consumes native `hachidori-popup-shown` and `hachidori-popup-hidden` attention events for mouse handling, keyboard focus, and the subtitle sidebar. Attention also covers a left press anywhere on the overlay that may start a selection, and the host element only exists after the first lookup, so once a Hachidori event has been seen, popup auto-pause, popup key routing, controller lookup state, and the gate on imported mpv keys and mouse buttons require an unhidden popup pane in the host's shadow root. Auto-pause rechecks after each successful lookup. Hachidori's popup lives in the overlay document rather than an iframe, so wheel events over its host scroll the popup instead of forwarding to mpv. The fork retains host attributes, hover and successful-lookup notifications, and commands that need private reader state. The Anki proxy strips local duplicate/overwrite metadata before forwarding requests and enriches only confirmed writes.
- Small units, explicit boundaries - Small units, explicit boundaries
- Composition over monoliths - Composition over monoliths
- Pure helpers where possible - Pure helpers where possible
+1
View File
@@ -21,6 +21,7 @@ Read when: finding internal docs or checking verification status
| Planning guide | `docs/workflow/planning.md` | active | 2026-05-23 | lightweight vs execution plans | | Planning guide | `docs/workflow/planning.md` | active | 2026-05-23 | lightweight vs execution plans |
| Agent skills | `docs/workflow/agent-skills.md` | active | 2026-08-23 | repo-local workflow skill ownership | | Agent skills | `docs/workflow/agent-skills.md` | active | 2026-08-23 | repo-local workflow skill ownership |
| Verification guide | `docs/workflow/verification.md` | active | 2026-08-13 | maintained verification lanes | | Verification guide | `docs/workflow/verification.md` | active | 2026-08-13 | maintained verification lanes |
| Testing guidelines | `docs/workflow/testing.md` | active | 2026-10-04 | test style and anti-patterns |
| Release guide | `docs/RELEASING.md` | active | 2026-05-23 | release checklist | | Release guide | `docs/RELEASING.md` | active | 2026-05-23 | release checklist |
## Update Rules ## Update Rules
+1
View File
@@ -13,6 +13,7 @@ This section is the internal workflow map for contributors and agents.
- [Planning](./planning.md) - when to write a lightweight plan vs a full execution plan - [Planning](./planning.md) - when to write a lightweight plan vs a full execution plan
- [Verification](./verification.md) - maintained test/build lanes and handoff gate - [Verification](./verification.md) - maintained test/build lanes and handoff gate
- [Testing](./testing.md) - what a good test looks like and what not to write
- [Agent Skills](./agent-skills.md) - repo-local workflow skill ownership - [Agent Skills](./agent-skills.md) - repo-local workflow skill ownership
- [Release Guide](../RELEASING.md) - tagged release workflow - [Release Guide](../RELEASING.md) - tagged release workflow
+49
View File
@@ -0,0 +1,49 @@
<!-- read_when: writing, reviewing, or deleting tests -->
# Testing Guidelines
Status: active
Last verified: 2026-10-04
Owner: Kyle Yasuda
Read when: adding or changing tests
Which lanes to run lives in [Verification](./verification.md). This page covers what a
good test looks like here.
## Test Behavior, Not Wiring
- Exercise a module through its public interface and assert outcomes: return values,
resulting state, files written, rows in sqlite, messages sent to a fake process.
- Prefer real collaborators that are cheap: tmp dirs, in-memory or tmp sqlite, fake
executables, pure parsers. Fake only the edges (Electron, mpv socket, network).
- Assert call order only when order is the behavior (startup sequencing, ABA races),
and then assert relative order, not the whole call log.
## Do Not Write
- Pass-through tests: a builder or handler that only forwards deps (`*-main-deps.ts`,
`*-runtime-handlers.ts`) needs no test. TypeScript already checks the shape.
- Source-text tests: reading `.ts`, `.css`, `.html`, `.lua`, `.swift`, or workflow YAML
and asserting with regexes. If the invariant matters, extract the logic and run it
(see `src/preload-ipc-listeners.ts`). Policy lints over workflow YAML are the
exception and belong in one parsed-YAML check.
- "Stays deleted" tests for removed modules, flags, or selectors. `tsc` and review
catch reintroduction.
- Tests that restate constants, defaults, labels, or window options.
- The same rule at several layers. Test a rule once where it lives; keep one
end-to-end case (for the tokenizer, the golden corpus) for integration.
## Keep Tests Small
- Shared setup goes in a `makeDeps(overrides)` helper or a `*-test-harness.ts` file, not
pasted into every test.
- Near-identical cases become a table: `for (const c of cases) test(c.name, ...)`.
- Inject timers, clocks, and loggers instead of patching globals or private members.
- A bug fix gets a regression test for the behavior that broke, named after the
behavior, not the ticket.
## Known Debt
- `src/main/main-wiring.test.ts` and `src/renderer/renderer-init-order.test.ts` still
regex `main.ts` / `renderer.ts` to guard startup ordering. Replace each test with a
behavioral one as the logic moves out of `main.ts` closures.
+5 -3
View File
@@ -14,8 +14,9 @@ Read when: selecting the right verification lane for a change
files in `package.json`. files in `package.json`.
- `scripts/run-test-lane.mjs` runs each test file in its own `bun test` process - `scripts/run-test-lane.mjs` runs each test file in its own `bun test` process
(per-file isolation with a wall timeout) so a hanging test or leaked global in (per-file isolation with a wall timeout) so a hanging test or leaked global in
one file cannot cascade into the rest of the lane. `--jobs N` parallelizes; one file cannot cascade into the rest of the lane. Files run in parallel, one
`--single-process` restores the shared-process mode for debugging. worker per CPU by default; `--jobs 1` runs serially and `--single-process`
restores the shared-process mode for debugging.
- `bun run test:fast` is the full source gate: discovered `src/**`, launcher - `bun run test:fast` is the full source gate: discovered `src/**`, launcher
unit, and `scripts/**`. unit, and `scripts/**`.
- `.github/workflows/quality-gate.yml` is the reusable `workflow_call` gate for - `.github/workflows/quality-gate.yml` is the reusable `workflow_call` gate for
@@ -63,6 +64,7 @@ bun run docs:build
Content checks run inside the electron-builder afterPack hook. See the Content checks run inside the electron-builder afterPack hook. See the
[release guide](../RELEASING.md#package-contents-checks) for the [release guide](../RELEASING.md#package-contents-checks) for the
installed-app verification checklist. installed-app verification checklist.
- Dictionary backend windows: after a full build, run `xvfb-run -a bun run test:dictionary:electron` on headless Linux. It uses temporary profiles to check both named settings commands, backend session isolation, the overlay's external-link bridge, and Hachidori's native dictionary parser.
- Coverage for the maintained source lane: `bun run test:coverage:src` - Coverage for the maintained source lane: `bun run test:coverage:src`
- Deep/local full gate: default handoff gate above - Deep/local full gate: default handoff gate above
@@ -70,7 +72,7 @@ bun run docs:build
- `bun run test:coverage:src` runs the same discovered `bun-src-full` membership as - `bun run test:coverage:src` runs the same discovered `bun-src-full` membership as
`test:src` through a sharded coverage runner: one Bun coverage process per test `test:src` through a sharded coverage runner: one Bun coverage process per test
file, then merged LCOV output. file (parallel, one per CPU unless `--jobs N`), then merged LCOV output.
- A failing coverage shard stops the runner with a nonzero status. Coverage is a - A failing coverage shard stops the runner with a nonzero status. Coverage is a
source test gate, not a report-only step. source test gate, not a report-only step.
- Machine-readable output lands at `coverage/test-src/lcov.info`. - Machine-readable output lands at `coverage/test-src/lcov.info`.
+35 -216
View File
@@ -150,74 +150,7 @@ test('doctor command exits non-zero for missing hard dependencies', () => {
); );
}); });
test('doctor command forwards refresh-known-words to app binary', () => { test('app command starts default background app detached from launcher app detached from launcher', () => {
const context = createContext();
context.args.doctor = true;
context.args.doctorRefreshKnownWords = true;
const forwarded: string[][] = [];
const handled = runDoctorCommand(context, {
commandExists: () => false,
configExists: () => true,
resolveMainConfigPath: () => '/tmp/SubMiner/config.jsonc',
runAppCommandWithInherit: (_appPath, appArgs) => {
forwarded.push(appArgs);
},
});
assert.equal(handled, true);
assert.deepEqual(forwarded, [['--refresh-known-words']]);
});
test('logs command exports logs and writes archive path', () => {
const writes: string[] = [];
const context = createContext();
context.args.logsExport = true;
context.processAdapter = {
...context.processAdapter,
writeStdout: (text) => writes.push(text),
};
const handled = runLogsCommand(context, {
exportLogsArchive: () => ({
zipPath: '/tmp/subminer-logs.zip',
exportedFiles: ['/tmp/app.log'],
mode: 'current-day',
}),
});
assert.equal(handled, true);
assert.deepEqual(writes, ['/tmp/subminer-logs.zip\n']);
});
test('logs command ignores unrelated launcher commands', () => {
const context = createContext();
assert.equal(runLogsCommand(context), false);
});
test('app command starts default macOS background app detached from launcher', () => {
const context = createContext();
context.args.appPassthrough = true;
context.args.appArgs = [];
const calls: string[] = [];
const handled = runAppPassthroughCommand(context, {
runAppCommandWithInherit: () => {
calls.push('attached');
},
launchSyncUiDetached: () => calls.push('sync-ui'),
launchYoutubeBrowserDetached: () => calls.push('youtube'),
launchAppBackgroundDetached: (appPath, logLevel) => {
calls.push(`detached:${appPath}:${logLevel}`);
},
});
assert.equal(handled, true);
assert.deepEqual(calls, ['detached:/tmp/subminer.app:warn']);
});
test('app command starts default Linux background app detached from launcher', () => {
const context = createContext(); const context = createContext();
context.args.appPassthrough = true; context.args.appPassthrough = true;
context.args.appArgs = []; context.args.appArgs = [];
@@ -389,49 +322,6 @@ test('dictionary command forwards candidate and selection modes to app binary',
]); ]);
}); });
test('dictionary command returns after app handoff starts', () => {
const context = createContext();
context.args.dictionary = true;
const handled = runDictionaryCommand(context, {
runAppCommandWithInherit: () => undefined,
});
assert.equal(handled, true);
});
test('update command runs direct Linux release update without launching Electron', async () => {
const context = createContext();
context.args.update = true;
const calls: string[] = [];
const handled = await runUpdateCommand(context, {
runAppCommandCaptureOutput: () => {
throw new Error('unexpected Electron launch');
},
runDirectReleaseUpdate: async (request) => {
calls.push(`direct:${request.appPath}:${request.launcherPath}:${request.channel}`);
return {
appImage: { status: 'not-found' },
launcher: { status: 'updated' },
supportAssets: [{ status: 'skipped' }],
};
},
readMainConfig: () => null,
log: (level, _configured, message) => {
calls.push(`${level}:${message}`);
},
});
assert.equal(handled, true);
assert.deepEqual(calls, [
'direct:/tmp/subminer.app:/tmp/subminer:stable',
'info:AppImage update: not-found',
'info:Launcher update: updated',
'info:Support assets update: skipped',
]);
});
test('stats command launches attached app command with response path', async () => { test('stats command launches attached app command with response path', async () => {
const harness = createStatsTestHarness({ stats: true, logLevel: 'debug' }); const harness = createStatsTestHarness({ stats: true, logLevel: 'debug' });
const handled = await runStatsCommand(harness.context, harness.commandDeps); const handled = await runStatsCommand(harness.context, harness.commandDeps);
@@ -449,16 +339,41 @@ test('stats command launches attached app command with response path', async ()
assert.equal(harness.removedPaths.length, 1); assert.equal(harness.removedPaths.length, 1);
}); });
test('stats background command launches attached daemon control command with response path', async () => { const STATS_RESPONSE_ARGS = ['--stats-response-path', '/tmp/subminer-stats-test/response.json'];
const harness = createStatsTestHarness({ stats: true, statsBackground: true });
const handled = await runStatsCommand(harness.context, harness.commandDeps);
assert.equal(handled, true); const statsForwardingCases = [
assert.deepEqual(harness.forwarded, [ {
['--stats-daemon-start', '--stats-response-path', '/tmp/subminer-stats-test/response.json'], name: 'stats background command launches the daemon start command',
]); overrides: { statsBackground: true },
assert.equal(harness.removedPaths.length, 1); expected: ['--stats-daemon-start', ...STATS_RESPONSE_ARGS],
}); },
{
name: 'stats stop command forwards the daemon stop flag',
overrides: { statsStop: true },
expected: ['--stats-daemon-stop', ...STATS_RESPONSE_ARGS],
},
{
name: 'stats cleanup command forwards cleanup vocab flags',
overrides: { statsCleanup: true, statsCleanupVocab: true },
expected: ['--stats', ...STATS_RESPONSE_ARGS, '--stats-cleanup', '--stats-cleanup-vocab'],
},
{
name: 'stats cleanup command forwards the lifetime rebuild flag',
overrides: { statsCleanup: true, statsCleanupLifetime: true },
expected: ['--stats', ...STATS_RESPONSE_ARGS, '--stats-cleanup', '--stats-cleanup-lifetime'],
},
];
for (const c of statsForwardingCases) {
test(`${c.name} to the app`, async () => {
const harness = createStatsTestHarness({ stats: true, ...c.overrides });
const handled = await runStatsCommand(harness.context, harness.commandDeps);
assert.equal(handled, true);
assert.deepEqual(harness.forwarded, [c.expected]);
assert.equal(harness.removedPaths.length, 1);
});
}
test('stats command waits for attached app exit after startup response', async () => { test('stats command waits for attached app exit after startup response', async () => {
const harness = createStatsTestHarness({ stats: true }); const harness = createStatsTestHarness({ stats: true });
@@ -503,45 +418,6 @@ test('stats command throws when attached app exits non-zero after startup respon
assert.equal(harness.removedPaths.length, 1); assert.equal(harness.removedPaths.length, 1);
}); });
test('stats cleanup command forwards cleanup vocab flags to the app', async () => {
const harness = createStatsTestHarness({
stats: true,
statsCleanup: true,
statsCleanupVocab: true,
});
const handled = await runStatsCommand(harness.context, {
...harness.commandDeps,
waitForStatsResponse: async () => ({ ok: true }),
});
assert.equal(handled, true);
assert.deepEqual(harness.forwarded, [
[
'--stats',
'--stats-response-path',
'/tmp/subminer-stats-test/response.json',
'--stats-cleanup',
'--stats-cleanup-vocab',
],
]);
assert.equal(harness.removedPaths.length, 1);
});
test('stats stop command forwards stop flag to the app', async () => {
const harness = createStatsTestHarness({ stats: true, statsStop: true });
const handled = await runStatsCommand(harness.context, {
...harness.commandDeps,
waitForStatsResponse: async () => ({ ok: true }),
});
assert.equal(handled, true);
assert.deepEqual(harness.forwarded, [
['--stats-daemon-stop', '--stats-response-path', '/tmp/subminer-stats-test/response.json'],
]);
assert.equal(harness.removedPaths.length, 1);
});
test('stats stop command exits on process exit without waiting for startup response', async () => { test('stats stop command exits on process exit without waiting for startup response', async () => {
const harness = createStatsTestHarness({ stats: true, statsStop: true }); const harness = createStatsTestHarness({ stats: true, statsStop: true });
let waitedForResponse = false; let waitedForResponse = false;
@@ -563,30 +439,6 @@ test('stats stop command exits on process exit without waiting for startup respo
assert.equal(harness.removedPaths.length, 1); assert.equal(harness.removedPaths.length, 1);
}); });
test('stats cleanup command forwards lifetime rebuild flag to the app', async () => {
const harness = createStatsTestHarness({
stats: true,
statsCleanup: true,
statsCleanupLifetime: true,
});
const handled = await runStatsCommand(harness.context, {
...harness.commandDeps,
waitForStatsResponse: async () => ({ ok: true }),
});
assert.equal(handled, true);
assert.deepEqual(harness.forwarded, [
[
'--stats',
'--stats-response-path',
'/tmp/subminer-stats-test/response.json',
'--stats-cleanup',
'--stats-cleanup-lifetime',
],
]);
assert.equal(harness.removedPaths.length, 1);
});
test('stats command throws when stats response reports an error', async () => { test('stats command throws when stats response reports an error', async () => {
const harness = createStatsTestHarness({ stats: true }); const harness = createStatsTestHarness({ stats: true });
@@ -692,36 +544,3 @@ test('stats command aborts pending response wait when attached app fails to spaw
assert.equal(aborted, true); assert.equal(aborted, true);
assert.equal(harness.removedPaths.length, 1); assert.equal(harness.removedPaths.length, 1);
}); });
test('stats cleanup command aborts pending response wait when app exits before startup response', async () => {
const harness = createStatsTestHarness({
stats: true,
statsCleanup: true,
statsCleanupVocab: true,
});
let aborted = false;
await assert.rejects(async () => {
await runStatsCommand(harness.context, {
...harness.commandDeps,
runAppCommandAttached: async (...args) => {
await harness.runAppCommandAttachedStub(...args);
return 2;
},
waitForStatsResponse: async (_responsePath, signal) =>
await new Promise((resolve) => {
signal?.addEventListener(
'abort',
() => {
aborted = true;
resolve({ ok: false, error: 'aborted' });
},
{ once: true },
);
}),
});
}, /Stats app exited before startup response \(status 2\)\./);
assert.equal(aborted, true);
assert.equal(harness.removedPaths.length, 1);
});
+182 -401
View File
@@ -4,81 +4,53 @@ import { EventEmitter } from 'node:events';
import fs from 'node:fs'; import fs from 'node:fs';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import type { Args } from '../types.js';
import type { LauncherCommandContext } from './context.js'; import type { LauncherCommandContext } from './context.js';
import { registerCleanup, runPlaybackCommandWithDeps } from './playback-command.js'; import { registerCleanup, runPlaybackCommandWithDeps } from './playback-command.js';
import { state } from '../mpv.js'; import { state, type startMpv } from '../mpv.js';
import { makeLauncherArgs } from '../test-support/args.js';
import { withEnv } from '../test-support/env.js';
function createContext(): LauncherCommandContext { type PlaybackDeps = Parameters<typeof runPlaybackCommandWithDeps>[1];
type StartMpvOptions = NonNullable<Parameters<typeof startMpv>[6]>;
const YOUTUBE_URL = 'https://www.youtube.com/watch?v=65Ovd7t8sNw';
function makePluginConfig(
overrides: Partial<LauncherCommandContext['pluginRuntimeConfig']> = {},
): LauncherCommandContext['pluginRuntimeConfig'] {
return { return {
args: { socketPath: '/tmp/subminer.sock',
backend: 'auto', binaryPath: '',
directory: '.', backend: 'auto',
recursive: false, autoStart: true,
profile: '', autoStartVisibleOverlay: true,
startOverlay: false, autoStartPauseUntilReady: true,
youtubePrimarySubLangs: [], osdMessages: false,
youtubeSecondarySubLangs: [], texthookerEnabled: false,
youtubeAudioLangs: [], ...overrides,
useTexthooker: false, };
autoStartOverlay: false, }
texthookerOnly: false,
texthookerOpenBrowser: false, /** A context for a YouTube URL target with logging at info and CLI texthooker off. */
useRofi: false, function createContext(
history: false, options: {
sync: false, args?: Partial<Args>;
syncCliTokens: [], plugin?: Partial<LauncherCommandContext['pluginRuntimeConfig']>;
syncUi: false, } = {},
logLevel: 'info', ): LauncherCommandContext {
logRotation: 7, return {
passwordStore: '', args: makeLauncherArgs({
target: 'https://www.youtube.com/watch?v=65Ovd7t8sNw', target: YOUTUBE_URL,
targetKind: 'url', targetKind: 'url',
jimakuApiKey: '', logLevel: 'info',
jimakuApiKeyCommand: '', useTexthooker: false,
jimakuApiBaseUrl: '', ...options.args,
jimakuLanguagePreference: 'ja', }),
jimakuMaxEntryResults: 20,
jellyfin: false,
jellyfinLogin: false,
jellyfinLogout: false,
jellyfinPlay: false,
jellyfinDiscovery: false,
dictionary: false,
dictionaryCandidates: false,
dictionarySelect: false,
stats: false,
doctor: false,
doctorRefreshKnownWords: false,
logsExport: false,
version: false,
settings: false,
youtubeBrowser: false,
configPath: false,
configShow: false,
mpvIdle: false,
mpvSocket: false,
mpvStatus: false,
mpvArgs: '',
appPassthrough: false,
appArgs: [],
jellyfinServer: '',
jellyfinUsername: '',
jellyfinPassword: '',
launchMode: 'normal',
},
scriptPath: '/tmp/subminer', scriptPath: '/tmp/subminer',
scriptName: 'subminer', scriptName: 'subminer',
mpvSocketPath: '/tmp/subminer.sock', mpvSocketPath: '/tmp/subminer.sock',
pluginRuntimeConfig: { pluginRuntimeConfig: makePluginConfig(options.plugin),
socketPath: '/tmp/subminer.sock',
binaryPath: '',
backend: 'auto',
autoStart: true,
autoStartVisibleOverlay: true,
autoStartPauseUntilReady: true,
osdMessages: false,
texthookerEnabled: false,
},
appPath: '/tmp/SubMiner.AppImage', appPath: '/tmp/SubMiner.AppImage',
launcherJellyfinConfig: {}, launcherJellyfinConfig: {},
processAdapter: { processAdapter: {
@@ -93,8 +65,70 @@ function createContext(): LauncherCommandContext {
}; };
} }
const FILE_TARGET = { target: '/tmp/movie.mkv', targetKind: 'file' } as const;
/**
* Playback harness. Deps are inert by default and record what the tests assert on: the
* options mpv was started with, the overlay launches, and an `events` log for the few cases
* where relative order is the behavior.
*/
function makeHarness(
options: {
context?: LauncherCommandContext;
deps?: Partial<PlaybackDeps>;
events?: string[];
} = {},
) {
const context = options.context ?? createContext();
const events = options.events ?? [];
const startMpvOptions: StartMpvOptions[] = [];
const overlayCalls: Array<{ extraAppArgs: string[]; configDir?: string }> = [];
const deps: PlaybackDeps = {
ensurePlaybackSetupReady: async () => {},
ensureRuntimePluginReady: async () => {
events.push('plugin');
},
chooseTarget: async () => ({
target: context.args.target,
kind: context.args.targetKind === 'file' ? 'file' : 'url',
}),
checkDependencies: () => {},
registerCleanup: () => {},
startMpv: async (_target, _kind, _args, _socket, _appPath, _subtitles, startOptions) => {
events.push('startMpv');
if (startOptions) startMpvOptions.push(startOptions);
},
waitForUnixSocketReady: async () => true,
startOverlay: async (_appPath, _args, _socket, extraAppArgs = [], configDir) => {
events.push('startOverlay');
overlayCalls.push({ extraAppArgs, configDir });
},
launchAppCommandDetached: () => {},
log: () => {},
cleanupPlaybackSession: async () => {},
getMpvProc: () => null,
...options.deps,
};
return {
context,
events,
startMpvOptions,
overlayCalls,
run: () => runPlaybackCommandWithDeps(context, deps),
};
}
function assertRanInOrder(events: string[], ...expected: string[]): void {
const positions = expected.map((event) => events.indexOf(event));
assert.ok(
positions.every(
(position, index) => position >= 0 && (index === 0 || position > positions[index - 1]!),
),
`expected ${expected.join(' -> ')} in order, got ${events.join(', ')}`,
);
}
test('playback cleanup signal handlers are registered once across repeated sessions', () => { test('playback cleanup signal handlers are registered once across repeated sessions', () => {
assert.equal(typeof registerCleanup, 'function', 'cleanup registration is not exported');
const context = createContext(); const context = createContext();
const registeredSignals: NodeJS.Signals[] = []; const registeredSignals: NodeJS.Signals[] = [];
context.processAdapter.onSignal = (signal) => { context.processAdapter.onSignal = (signal) => {
@@ -108,121 +142,41 @@ test('playback cleanup signal handlers are registered once across repeated sessi
}); });
test('youtube playback launches overlay with app-owned youtube flow args', async () => { test('youtube playback launches overlay with app-owned youtube flow args', async () => {
const calls: string[] = []; const harness = makeHarness({
const context = createContext(); context: createContext({
context.pluginRuntimeConfig = { plugin: {
...context.pluginRuntimeConfig, autoStart: false,
autoStart: false, autoStartVisibleOverlay: false,
autoStartVisibleOverlay: false, autoStartPauseUntilReady: false,
autoStartPauseUntilReady: false, },
}; }),
const receivedStartMpvOptions: Record<string, unknown>[] = [];
await runPlaybackCommandWithDeps(context, {
ensurePlaybackSetupReady: async () => {},
ensureRuntimePluginReady: async () => {},
chooseTarget: async (_args, _scriptPath) => ({ target: context.args.target, kind: 'url' }),
checkDependencies: () => {},
registerCleanup: () => {},
startMpv: async (
_target,
_targetKind,
_args,
_socketPath,
_appPath,
_preloadedSubtitles,
options,
) => {
if (options) {
receivedStartMpvOptions.push(options as Record<string, unknown>);
}
calls.push('startMpv');
},
waitForUnixSocketReady: async () => true,
startOverlay: async (_appPath, _args, _socketPath, extraAppArgs = []) => {
calls.push(`startOverlay:${extraAppArgs.join(' ')}`);
},
launchAppCommandDetached: (_appPath: string, appArgs: string[]) => {
calls.push(`launch:${appArgs.join(' ')}`);
},
log: () => {},
cleanupPlaybackSession: async () => {},
getMpvProc: () => null,
}); });
assert.deepEqual(calls, [ await harness.run();
'startMpv',
'startOverlay:--youtube-play https://www.youtube.com/watch?v=65Ovd7t8sNw', assertRanInOrder(harness.events, 'startMpv', 'startOverlay');
]); assert.deepEqual(harness.overlayCalls[0]?.extraAppArgs, ['--youtube-play', YOUTUBE_URL]);
assert.equal(receivedStartMpvOptions[0]?.startPaused, true); assert.equal(harness.startMpvOptions[0]?.startPaused, true);
assert.equal(receivedStartMpvOptions[0]?.disableYoutubeSubtitleAutoLoad, true); assert.equal(harness.startMpvOptions[0]?.disableYoutubeSubtitleAutoLoad, true);
}); });
test('youtube app-owned playback disables mpv plugin auto-start', async () => { test('youtube app-owned playback disables mpv plugin auto-start', async () => {
const context = createContext(); const harness = makeHarness();
context.pluginRuntimeConfig = {
...context.pluginRuntimeConfig,
autoStart: true,
autoStartVisibleOverlay: true,
autoStartPauseUntilReady: true,
};
const receivedStartMpvOptions: Record<string, unknown>[] = [];
await runPlaybackCommandWithDeps(context, { await harness.run();
ensurePlaybackSetupReady: async () => {},
ensureRuntimePluginReady: async () => {},
chooseTarget: async () => ({ target: context.args.target, kind: 'url' }),
checkDependencies: () => {},
registerCleanup: () => {},
startMpv: async (
_target,
_targetKind,
_args,
_socketPath,
_appPath,
_preloadedSubtitles,
options,
) => {
if (options) {
receivedStartMpvOptions.push(options as Record<string, unknown>);
}
},
waitForUnixSocketReady: async () => true,
startOverlay: async () => {},
launchAppCommandDetached: () => {},
log: () => {},
cleanupPlaybackSession: async () => {},
getMpvProc: () => null,
});
const runtimeConfig = receivedStartMpvOptions[0]?.runtimePluginConfig as const runtimeConfig = harness.startMpvOptions[0]?.runtimePluginConfig;
| { autoStart?: boolean; autoStartVisibleOverlay?: boolean; autoStartPauseUntilReady?: boolean }
| undefined;
assert.equal(runtimeConfig?.autoStart, false); assert.equal(runtimeConfig?.autoStart, false);
assert.equal(runtimeConfig?.autoStartVisibleOverlay, false); assert.equal(runtimeConfig?.autoStartVisibleOverlay, false);
assert.equal(runtimeConfig?.autoStartPauseUntilReady, false); assert.equal(runtimeConfig?.autoStartPauseUntilReady, false);
}); });
test('plugin auto-start playback leaves app lifetime to managed-playback owner', async () => { test('plugin auto-start playback leaves app lifetime to managed-playback owner', async () => {
const context = createContext(); const context = createContext({
context.args = { args: { ...FILE_TARGET, useTexthooker: true },
...context.args, plugin: { autoStartVisibleOverlay: false, autoStartPauseUntilReady: false },
target: '/tmp/movie.mkv', });
targetKind: 'file', state.appPath = context.appPath ?? '';
useTexthooker: true,
};
context.pluginRuntimeConfig = {
socketPath: '/tmp/subminer.sock',
binaryPath: '',
backend: 'auto',
autoStart: true,
autoStartVisibleOverlay: false,
autoStartPauseUntilReady: false,
osdMessages: false,
texthookerEnabled: false,
};
const appPath = context.appPath ?? '';
state.appPath = appPath;
state.overlayManagedByLauncher = false; state.overlayManagedByLauncher = false;
const mpvProc = new EventEmitter() as EventEmitter & { const mpvProc = new EventEmitter() as EventEmitter & {
exitCode: number | null; exitCode: number | null;
@@ -233,31 +187,27 @@ test('plugin auto-start playback leaves app lifetime to managed-playback owner',
mpvProc.killed = false; mpvProc.killed = false;
mpvProc.kill = () => true; mpvProc.kill = () => true;
let cleanupSawManagedOverlay = true; let cleanupSawManagedOverlay = true;
const harness = makeHarness({
try { context,
await runPlaybackCommandWithDeps(context, { deps: {
ensurePlaybackSetupReady: async () => {},
ensureRuntimePluginReady: async () => {},
chooseTarget: async () => ({ target: context.args.target, kind: 'file' }),
checkDependencies: () => {},
registerCleanup: () => {},
startMpv: async () => { startMpv: async () => {
setTimeout(() => { setTimeout(() => {
mpvProc.exitCode = 0; mpvProc.exitCode = 0;
mpvProc.emit('exit', 0); mpvProc.emit('exit', 0);
}, 5); }, 5);
}, },
waitForUnixSocketReady: async () => true,
startOverlay: async () => { startOverlay: async () => {
throw new Error('startOverlay should not run when plugin auto-start is used'); throw new Error('startOverlay should not run when plugin auto-start is used');
}, },
launchAppCommandDetached: () => {},
log: () => {},
cleanupPlaybackSession: async () => { cleanupPlaybackSession: async () => {
cleanupSawManagedOverlay = state.overlayManagedByLauncher; cleanupSawManagedOverlay = state.overlayManagedByLauncher;
}, },
getMpvProc: () => mpvProc as NonNullable<typeof state.mpvProc>, getMpvProc: () => mpvProc as NonNullable<typeof state.mpvProc>,
}); },
});
try {
await harness.run();
assert.equal(cleanupSawManagedOverlay, false); assert.equal(cleanupSawManagedOverlay, false);
} finally { } finally {
@@ -267,258 +217,89 @@ test('plugin auto-start playback leaves app lifetime to managed-playback owner',
}); });
test('plugin auto-start playback attaches a warm background app through the launcher', async () => { test('plugin auto-start playback attaches a warm background app through the launcher', async () => {
const context = createContext(); const harness = makeHarness({
context.args = { context: createContext({
...context.args, args: { ...FILE_TARGET, useTexthooker: true },
target: '/tmp/movie.mkv', plugin: { texthookerEnabled: true },
targetKind: 'file', }),
useTexthooker: true, deps: { isAppControlServerAvailable: async () => true },
};
context.pluginRuntimeConfig = {
socketPath: '/tmp/subminer.sock',
binaryPath: '',
backend: 'auto',
autoStart: true,
autoStartVisibleOverlay: true,
autoStartPauseUntilReady: true,
osdMessages: false,
texthookerEnabled: true,
};
const calls: string[] = [];
const receivedStartMpvOptions: Record<string, unknown>[] = [];
await runPlaybackCommandWithDeps(context, {
ensurePlaybackSetupReady: async () => {},
ensureRuntimePluginReady: async () => {},
chooseTarget: async () => ({ target: context.args.target, kind: 'file' }),
checkDependencies: () => {},
registerCleanup: () => {},
startMpv: async (
_target,
_targetKind,
_args,
_socketPath,
_appPath,
_preloadedSubtitles,
options,
) => {
calls.push('startMpv');
if (options) {
receivedStartMpvOptions.push(options as Record<string, unknown>);
}
},
waitForUnixSocketReady: async () => true,
startOverlay: async (_appPath, _args, _socketPath, extraAppArgs = []) => {
calls.push(`startOverlay:${extraAppArgs.join(' ')}`);
},
launchAppCommandDetached: () => {},
log: () => {},
cleanupPlaybackSession: async () => {},
getMpvProc: () => null,
isAppControlServerAvailable: async () => true,
} as Parameters<typeof runPlaybackCommandWithDeps>[1] & {
isAppControlServerAvailable: () => Promise<boolean>;
}); });
assert.deepEqual(calls, ['startMpv', 'startOverlay:--show-visible-overlay --texthooker']); await harness.run();
assert.equal(receivedStartMpvOptions[0]?.startPaused, true);
assert.equal( assertRanInOrder(harness.events, 'startMpv', 'startOverlay');
(receivedStartMpvOptions[0]?.runtimePluginConfig as { autoStart?: boolean } | undefined) assert.deepEqual(harness.overlayCalls[0]?.extraAppArgs, [
?.autoStart, '--show-visible-overlay',
false, '--texthooker',
); ]);
assert.equal(harness.startMpvOptions[0]?.startPaused, true);
assert.equal(harness.startMpvOptions[0]?.runtimePluginConfig?.autoStart, false);
}); });
test('plugin auto-start attach mode reuses launcher-resolved config dir for app control', async () => { test('plugin auto-start attach mode reuses launcher-resolved config dir for app control', async () => {
const context = createContext();
const originalXdgConfigHome = process.env.XDG_CONFIG_HOME;
const originalAppData = process.env.APPDATA;
const xdgConfigHome = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-test-xdg-')); const xdgConfigHome = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-test-xdg-'));
const expectedConfigDir = path.join(xdgConfigHome, 'SubMiner'); const expectedConfigDir = path.join(xdgConfigHome, 'SubMiner');
fs.mkdirSync(expectedConfigDir, { recursive: true }); fs.mkdirSync(expectedConfigDir, { recursive: true });
fs.writeFileSync(path.join(expectedConfigDir, 'config.jsonc'), '{}'); fs.writeFileSync(path.join(expectedConfigDir, 'config.jsonc'), '{}');
context.args = {
...context.args,
target: '/tmp/movie.mkv',
targetKind: 'file',
useTexthooker: true,
};
context.pluginRuntimeConfig = {
socketPath: '/tmp/subminer.sock',
binaryPath: '',
backend: 'auto',
autoStart: true,
autoStartVisibleOverlay: true,
autoStartPauseUntilReady: true,
osdMessages: false,
texthookerEnabled: true,
};
let availabilityConfigDir: string | undefined; let availabilityConfigDir: string | undefined;
let overlayConfigDir: string | undefined; const harness = makeHarness({
let overlayLoadingOsd: boolean | undefined; context: createContext({
args: { ...FILE_TARGET, useTexthooker: true },
try { plugin: { texthookerEnabled: true },
process.env.XDG_CONFIG_HOME = xdgConfigHome; }),
process.env.APPDATA = xdgConfigHome; deps: {
await runPlaybackCommandWithDeps(context, {
ensurePlaybackSetupReady: async () => {},
ensureRuntimePluginReady: async () => {},
chooseTarget: async () => ({ target: context.args.target, kind: 'file' }),
checkDependencies: () => {},
registerCleanup: () => {},
startMpv: async (
_target,
_targetKind,
_args,
_socketPath,
_appPath,
_preloadedSubtitles,
options,
) => {
overlayLoadingOsd = (
options?.runtimePluginConfig as { overlayLoadingOsd?: boolean } | undefined
)?.overlayLoadingOsd;
},
waitForUnixSocketReady: async () => true,
startOverlay: async (_appPath, _args, _socketPath, _extraAppArgs = [], configDir) => {
overlayConfigDir = configDir;
},
launchAppCommandDetached: () => {},
log: () => {},
cleanupPlaybackSession: async () => {},
getMpvProc: () => null,
isAppControlServerAvailable: async (_logLevel, configDir) => { isAppControlServerAvailable: async (_logLevel, configDir) => {
availabilityConfigDir = configDir; availabilityConfigDir = configDir;
return true; return true;
}, },
}); },
});
try {
await withEnv({ XDG_CONFIG_HOME: xdgConfigHome, APPDATA: xdgConfigHome }, () => harness.run());
assert.equal(availabilityConfigDir, expectedConfigDir); assert.equal(availabilityConfigDir, expectedConfigDir);
assert.equal(overlayConfigDir, expectedConfigDir); assert.equal(harness.overlayCalls[0]?.configDir, expectedConfigDir);
assert.equal(overlayLoadingOsd, true); assert.equal(harness.startMpvOptions[0]?.runtimePluginConfig?.overlayLoadingOsd, true);
} finally { } finally {
if (originalXdgConfigHome === undefined) {
delete process.env.XDG_CONFIG_HOME;
} else {
process.env.XDG_CONFIG_HOME = originalXdgConfigHome;
}
if (originalAppData === undefined) {
delete process.env.APPDATA;
} else {
process.env.APPDATA = originalAppData;
}
fs.rmSync(xdgConfigHome, { recursive: true, force: true }); fs.rmSync(xdgConfigHome, { recursive: true, force: true });
} }
}); });
test('plugin auto-start attach mode omits texthooker flag when CLI texthooker is disabled', async () => { test('plugin auto-start attach mode omits texthooker flag when CLI texthooker is disabled', async () => {
const context = createContext(); const harness = makeHarness({
context.args = { context: createContext({ args: FILE_TARGET, plugin: { texthookerEnabled: true } }),
...context.args, deps: { isAppControlServerAvailable: async () => true },
target: '/tmp/movie.mkv',
targetKind: 'file',
};
context.pluginRuntimeConfig = {
socketPath: '/tmp/subminer.sock',
binaryPath: '',
backend: 'auto',
autoStart: true,
autoStartVisibleOverlay: true,
autoStartPauseUntilReady: true,
osdMessages: false,
texthookerEnabled: true,
};
const calls: string[] = [];
await runPlaybackCommandWithDeps(context, {
ensurePlaybackSetupReady: async () => {},
ensureRuntimePluginReady: async () => {},
chooseTarget: async () => ({ target: context.args.target, kind: 'file' }),
checkDependencies: () => {},
registerCleanup: () => {},
startMpv: async () => {
calls.push('startMpv');
},
waitForUnixSocketReady: async () => true,
startOverlay: async (_appPath, _args, _socketPath, extraAppArgs = []) => {
calls.push(`startOverlay:${extraAppArgs.join(' ')}`);
},
launchAppCommandDetached: () => {},
log: () => {},
cleanupPlaybackSession: async () => {},
getMpvProc: () => null,
isAppControlServerAvailable: async () => true,
} as Parameters<typeof runPlaybackCommandWithDeps>[1] & {
isAppControlServerAvailable: () => Promise<boolean>;
}); });
assert.deepEqual(calls, ['startMpv', 'startOverlay:--show-visible-overlay']); await harness.run();
assert.deepEqual(harness.overlayCalls[0]?.extraAppArgs, ['--show-visible-overlay']);
}); });
test('playback command ensures Linux runtime plugin before mpv launch', async () => { test('playback command ensures Linux runtime plugin before mpv launch', async () => {
const context = createContext(); const harness = makeHarness({ context: createContext({ args: FILE_TARGET }) });
context.args = {
...context.args,
target: '/tmp/movie.mkv',
targetKind: 'file',
};
const calls: string[] = [];
await runPlaybackCommandWithDeps(context, { await harness.run();
ensurePlaybackSetupReady: async () => {},
ensureRuntimePluginReady: async () => {
calls.push('plugin');
},
chooseTarget: async () => ({ target: context.args.target, kind: 'file' }),
checkDependencies: () => {},
registerCleanup: () => {},
startMpv: async () => {
calls.push('startMpv');
},
waitForUnixSocketReady: async () => true,
startOverlay: async () => {},
launchAppCommandDetached: () => {},
log: () => {},
cleanupPlaybackSession: async () => {},
getMpvProc: () => null,
});
assert.deepEqual(calls, ['plugin', 'startMpv']); assertRanInOrder(harness.events, 'plugin', 'startMpv');
}); });
test('rofi playback repairs support assets before opening the picker', async () => { test('rofi playback repairs support assets before opening the picker', async () => {
const context = createContext(); const events: string[] = [];
context.args = { const harness = makeHarness({
...context.args, events,
target: '', context: createContext({ args: { target: '', targetKind: '', useRofi: true } }),
targetKind: '', deps: {
useRofi: true, chooseTarget: async () => {
}; events.push('picker');
const calls: string[] = []; return { target: '/tmp/movie.mkv', kind: 'file' };
},
await runPlaybackCommandWithDeps(context, { checkPickerDependencies: () => {},
ensurePlaybackSetupReady: async () => {},
ensureRuntimePluginReady: async () => {
calls.push('assets');
}, },
chooseTarget: async () => {
calls.push('picker');
return { target: '/tmp/movie.mkv', kind: 'file' };
},
checkPickerDependencies: () => {},
checkDependencies: () => {},
registerCleanup: () => {},
startMpv: async () => {
calls.push('startMpv');
},
waitForUnixSocketReady: async () => true,
startOverlay: async () => {},
launchAppCommandDetached: () => {},
log: () => {},
cleanupPlaybackSession: async () => {},
getMpvProc: () => null,
}); });
assert.deepEqual(calls, ['assets', 'picker', 'startMpv']); await harness.run();
assertRanInOrder(events, 'plugin', 'picker', 'startMpv');
}); });
+7 -1
View File
@@ -26,7 +26,10 @@ import {
readSetupState, readSetupState,
} from '../../src/shared/setup-state.js'; } from '../../src/shared/setup-state.js';
import { detectInstalledFirstRunPluginCandidates } from '../../src/main/runtime/first-run-setup-plugin.js'; import { detectInstalledFirstRunPluginCandidates } from '../../src/main/runtime/first-run-setup-plugin.js';
import { hasLauncherExternalYomitanProfileConfig } from '../config.js'; import {
hasLauncherExternalYomitanProfileConfig,
loadLauncherDictionaryBackend,
} from '../config.js';
const SETUP_WAIT_TIMEOUT_MS = 10 * 60 * 1000; const SETUP_WAIT_TIMEOUT_MS = 10 * 60 * 1000;
const SETUP_POLL_INTERVAL_MS = 500; const SETUP_POLL_INTERVAL_MS = 500;
@@ -115,6 +118,9 @@ async function ensurePlaybackSetupReady(context: LauncherCommandContext): Promis
const configDir = getLauncherConfigDir(); const configDir = getLauncherConfigDir();
const statePath = getSetupStatePath(configDir); const statePath = getSetupStatePath(configDir);
const ready = await ensureLauncherSetupReady({ const ready = await ensureLauncherSetupReady({
dictionaryBackend: loadLauncherDictionaryBackend(),
isAppRunning: () => isRunningAppControlServerAvailable(args.logLevel, configDir),
warn: (message) => log('warn', args.logLevel, message),
readSetupState: () => readSetupState(statePath), readSetupState: () => readSetupState(statePath),
isExternalYomitanConfigured: () => hasLauncherExternalYomitanProfileConfig(), isExternalYomitanConfigured: () => hasLauncherExternalYomitanProfileConfig(),
hasLegacyMpvPlugin: () => hasLegacyMpvPlugin: () =>
-43
View File
@@ -48,49 +48,6 @@ test('runSyncCommand proxies sync argv to the app in --sync-cli mode', async ()
assert.equal(spawned.length, 1); assert.equal(spawned.length, 1);
}); });
test('runSyncCommand forwards tokens verbatim and appends the effective log level', async () => {
const spawned: string[][] = [];
const deps: Partial<SyncCommandDeps> = {
runAppCommand: (_appPath, appArgs) => {
spawned.push(appArgs);
},
};
await runSyncCommand(
makeContext({
syncCliTokens: [
'media-box',
'--pull',
'--remote-cmd',
'/opt/SubMiner.AppImage',
'--db',
'/tmp/db.sqlite',
'--force',
'--json',
],
logLevel: 'debug',
}),
deps,
);
assert.deepEqual(spawned, [
[
'--sync-cli',
'sync',
'media-box',
'--pull',
'--remote-cmd',
'/opt/SubMiner.AppImage',
'--db',
'/tmp/db.sqlite',
'--force',
'--json',
'--log-level',
'debug',
],
]);
});
test('runSyncCommand fails with a clear message when the app binary is missing', async () => { test('runSyncCommand fails with a clear message when the app binary is missing', async () => {
const deps: Partial<SyncCommandDeps> = { const deps: Partial<SyncCommandDeps> = {
runAppCommand: () => { runAppCommand: () => {
-5
View File
@@ -8,7 +8,6 @@ import {
buildPluginRuntimeScriptOptParts, buildPluginRuntimeScriptOptParts,
parsePluginRuntimeConfigFromMainConfig, parsePluginRuntimeConfigFromMainConfig,
} from './config/plugin-runtime-config.js'; } from './config/plugin-runtime-config.js';
import { getDefaultSocketPath } from './types.js';
test('parseLauncherYoutubeSubgenConfig keeps only valid typed values', () => { test('parseLauncherYoutubeSubgenConfig keeps only valid typed values', () => {
const parsed = parseLauncherYoutubeSubgenConfig({ const parsed = parseLauncherYoutubeSubgenConfig({
@@ -207,10 +206,6 @@ test('buildPluginRuntimeScriptOptParts strips script-option delimiters from stri
); );
}); });
test('getDefaultSocketPath returns Windows named pipe default', () => {
assert.equal(getDefaultSocketPath('win32'), '\\\\.\\pipe\\subminer-socket');
});
test('parseLauncherMpvConfig reads configured mpv profile', () => { test('parseLauncherMpvConfig reads configured mpv profile', () => {
assert.deepEqual( assert.deepEqual(
parseLauncherMpvConfig({ parseLauncherMpvConfig({
-20
View File
@@ -1,20 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import path from 'node:path';
test('launcher root help lists subcommands', () => {
const output = execFileSync('bun', ['run', path.join(process.cwd(), 'launcher/main.ts'), '-h'], {
encoding: 'utf8',
});
assert.match(output, /Commands:/);
assert.match(output, /jellyfin\|jf/);
assert.match(output, /doctor/);
assert.match(output, /config/);
assert.match(output, /mpv/);
assert.match(output, /logs/);
assert.match(output, /dictionary\|dict/);
assert.match(output, /texthooker/);
assert.match(output, /app\|bin/);
});
+7
View File
@@ -1,4 +1,5 @@
import { fail } from './log.js'; import { fail } from './log.js';
import type { DictionaryBackend } from '../src/types/config.js';
import type { import type {
Args, Args,
LauncherLoggingConfig, LauncherLoggingConfig,
@@ -100,6 +101,12 @@ export function loadLauncherLoggingConfig(): LauncherLoggingConfig {
}; };
} }
export function loadLauncherDictionaryBackend(): DictionaryBackend {
return readLauncherMainConfigObject()?.dictionaryBackend === 'hachidori'
? 'hachidori'
: 'yomitan';
}
export function hasLauncherExternalYomitanProfileConfig(): boolean { export function hasLauncherExternalYomitanProfileConfig(): boolean {
return readExternalYomitanProfilePath(readLauncherMainConfigObject()) !== null; return readExternalYomitanProfilePath(readLauncherMainConfigObject()) !== null;
} }
+83 -162
View File
@@ -9,6 +9,7 @@ import {
applyRootOptionsToArgs, applyRootOptionsToArgs,
createDefaultArgs, createDefaultArgs,
} from './args-normalizer.js'; } from './args-normalizer.js';
import type { CliInvocations } from './cli-parser-builder.js';
function withTempDir<T>(fn: (dir: string) => T): T { function withTempDir<T>(fn: (dir: string) => T): T {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-launcher-args-')); const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-launcher-args-'));
@@ -19,6 +20,48 @@ function withTempDir<T>(fn: (dir: string) => T): T {
} }
} }
/** An invocations bag with nothing triggered; tests pass only the fields under test. */
function emptyInvocations(overrides: Partial<CliInvocations> = {}): CliInvocations {
return {
jellyfinInvocation: null,
configInvocation: null,
settingsInvocation: null,
youtubeBrowserInvocation: null,
mpvInvocation: null,
appInvocation: null,
dictionaryTriggered: false,
dictionaryTarget: null,
dictionaryLogLevel: null,
dictionaryCandidates: false,
dictionarySelect: false,
dictionaryAnilistId: null,
statsTriggered: false,
statsBackground: false,
statsStop: false,
statsCleanup: false,
statsCleanupVocab: false,
statsCleanupLifetime: false,
statsCleanupDuplicateLines: false,
statsCleanupDryRun: false,
statsCleanupLookbackDays: null,
statsLogLevel: null,
syncTriggered: false,
syncCliTokens: [],
syncLogLevel: null,
syncUiTriggered: false,
syncUiLogLevel: null,
doctorTriggered: false,
doctorLogLevel: null,
doctorRefreshKnownWords: false,
logsTriggered: false,
logsExport: false,
texthookerTriggered: false,
texthookerLogLevel: null,
texthookerOpenBrowser: false,
...overrides,
};
}
test('createDefaultArgs normalizes configured language codes', () => { test('createDefaultArgs normalizes configured language codes', () => {
const parsed = createDefaultArgs({ const parsed = createDefaultArgs({
primarySubLanguages: [' JA ', 'jpn', 'ja'], primarySubLanguages: [' JA ', 'jpn', 'ja'],
@@ -92,53 +135,23 @@ test('applyRootOptionsToArgs rejects unsupported targets', () => {
test('applyInvocationsToArgs maps config and jellyfin invocation state', () => { test('applyInvocationsToArgs maps config and jellyfin invocation state', () => {
const parsed = createDefaultArgs({}); const parsed = createDefaultArgs({});
applyInvocationsToArgs(parsed, { applyInvocationsToArgs(
jellyfinInvocation: { parsed,
action: 'play', emptyInvocations({
play: true, jellyfinInvocation: {
server: 'https://jf.example', action: 'play',
username: 'alice', play: true,
password: 'secret', server: 'https://jf.example',
logLevel: 'debug', username: 'alice',
}, password: 'secret',
configInvocation: { logLevel: 'debug',
action: 'show', },
logLevel: 'warn', configInvocation: {
}, action: 'show',
settingsInvocation: null, logLevel: 'warn',
youtubeBrowserInvocation: null, },
mpvInvocation: null, }),
appInvocation: null, );
dictionaryTriggered: false,
dictionaryTarget: null,
dictionaryLogLevel: null,
dictionaryCandidates: false,
dictionarySelect: false,
dictionaryAnilistId: null,
statsTriggered: false,
statsBackground: false,
statsStop: false,
statsCleanup: false,
statsCleanupVocab: false,
statsCleanupLifetime: false,
statsCleanupDuplicateLines: false,
statsCleanupDryRun: false,
statsCleanupLookbackDays: null,
statsLogLevel: null,
syncTriggered: false,
syncCliTokens: [],
syncLogLevel: null,
syncUiTriggered: false,
syncUiLogLevel: null,
doctorTriggered: false,
doctorLogLevel: null,
doctorRefreshKnownWords: false,
logsTriggered: false,
logsExport: false,
texthookerTriggered: false,
texthookerLogLevel: null,
texthookerOpenBrowser: false,
});
assert.equal(parsed.jellyfin, false); assert.equal(parsed.jellyfin, false);
assert.equal(parsed.jellyfinPlay, true); assert.equal(parsed.jellyfinPlay, true);
@@ -155,45 +168,14 @@ test('applyInvocationsToArgs maps config and jellyfin invocation state', () => {
test('applyInvocationsToArgs maps settings invocation to settings window', () => { test('applyInvocationsToArgs maps settings invocation to settings window', () => {
const parsed = createDefaultArgs({}); const parsed = createDefaultArgs({});
applyInvocationsToArgs(parsed, { applyInvocationsToArgs(
jellyfinInvocation: null, parsed,
configInvocation: null, emptyInvocations({
settingsInvocation: { settingsInvocation: {
logLevel: undefined, logLevel: undefined,
}, },
youtubeBrowserInvocation: null, }),
mpvInvocation: null, );
appInvocation: null,
dictionaryTriggered: false,
dictionaryTarget: null,
dictionaryLogLevel: null,
dictionaryCandidates: false,
dictionarySelect: false,
dictionaryAnilistId: null,
statsTriggered: false,
statsBackground: false,
statsStop: false,
statsCleanup: false,
statsCleanupVocab: false,
statsCleanupLifetime: false,
statsCleanupDuplicateLines: false,
statsCleanupDryRun: false,
statsCleanupLookbackDays: null,
statsLogLevel: null,
syncTriggered: false,
syncCliTokens: [],
syncLogLevel: null,
syncUiTriggered: false,
syncUiLogLevel: null,
doctorTriggered: false,
doctorLogLevel: null,
doctorRefreshKnownWords: false,
logsTriggered: false,
logsExport: false,
texthookerTriggered: false,
texthookerLogLevel: null,
texthookerOpenBrowser: false,
});
assert.equal(parsed.settings, true); assert.equal(parsed.settings, true);
assert.equal(parsed.configPath, false); assert.equal(parsed.configPath, false);
@@ -203,45 +185,14 @@ test('applyInvocationsToArgs fails when config invocation has no action', () =>
const parsed = createDefaultArgs({}); const parsed = createDefaultArgs({});
const error = withProcessExitIntercept(() => { const error = withProcessExitIntercept(() => {
applyInvocationsToArgs(parsed, { applyInvocationsToArgs(
jellyfinInvocation: null, parsed,
configInvocation: { emptyInvocations({
action: undefined, configInvocation: {
}, action: undefined,
settingsInvocation: null, },
youtubeBrowserInvocation: null, }),
mpvInvocation: null, );
appInvocation: null,
dictionaryTriggered: false,
dictionaryTarget: null,
dictionaryLogLevel: null,
dictionaryCandidates: false,
dictionarySelect: false,
dictionaryAnilistId: null,
statsTriggered: false,
statsBackground: false,
statsStop: false,
statsCleanup: false,
statsCleanupVocab: false,
statsCleanupLifetime: false,
statsCleanupDuplicateLines: false,
statsCleanupDryRun: false,
statsCleanupLookbackDays: null,
statsLogLevel: null,
syncTriggered: false,
syncCliTokens: [],
syncLogLevel: null,
syncUiTriggered: false,
syncUiLogLevel: null,
doctorTriggered: false,
doctorLogLevel: null,
doctorRefreshKnownWords: false,
logsTriggered: false,
logsExport: false,
texthookerTriggered: false,
texthookerLogLevel: null,
texthookerOpenBrowser: false,
});
}); });
assert.equal(error.code, 1); assert.equal(error.code, 1);
@@ -251,43 +202,13 @@ test('applyInvocationsToArgs fails when config invocation has no action', () =>
test('applyInvocationsToArgs maps texthooker browser-open request', () => { test('applyInvocationsToArgs maps texthooker browser-open request', () => {
const parsed = createDefaultArgs({}); const parsed = createDefaultArgs({});
applyInvocationsToArgs(parsed, { applyInvocationsToArgs(
jellyfinInvocation: null, parsed,
configInvocation: null, emptyInvocations({
settingsInvocation: null, texthookerTriggered: true,
youtubeBrowserInvocation: null, texthookerOpenBrowser: true,
mpvInvocation: null, }),
appInvocation: null, );
dictionaryTriggered: false,
dictionaryTarget: null,
dictionaryLogLevel: null,
dictionaryCandidates: false,
dictionarySelect: false,
dictionaryAnilistId: null,
statsTriggered: false,
statsBackground: false,
statsStop: false,
statsCleanup: false,
statsCleanupVocab: false,
statsCleanupLifetime: false,
statsCleanupDuplicateLines: false,
statsCleanupDryRun: false,
statsCleanupLookbackDays: null,
statsLogLevel: null,
syncTriggered: false,
syncCliTokens: [],
syncLogLevel: null,
syncUiTriggered: false,
syncUiLogLevel: null,
doctorTriggered: false,
doctorLogLevel: null,
doctorRefreshKnownWords: false,
logsTriggered: false,
logsExport: false,
texthookerTriggered: true,
texthookerLogLevel: null,
texthookerOpenBrowser: true,
});
assert.equal(parsed.texthookerOnly, true); assert.equal(parsed.texthookerOnly, true);
assert.equal(parsed.texthookerOpenBrowser, true); assert.equal(parsed.texthookerOpenBrowser, true);
+4
View File
@@ -214,6 +214,10 @@ export function applyRootOptionsToArgs(
if (options.update === true) parsed.update = true; if (options.update === true) parsed.update = true;
if (options.version === true) parsed.version = true; if (options.version === true) parsed.version = true;
if (options.settings === true) parsed.settings = true; if (options.settings === true) parsed.settings = true;
if (options.yomitan === true || options.hachidori === true) {
parsed.appPassthrough = true;
parsed.appArgs = [options.yomitan === true ? '--yomitan' : '--hachidori'];
}
if (options.startOverlay === true) parsed.autoStartOverlay = true; if (options.startOverlay === true) parsed.autoStartOverlay = true;
if (options.texthooker === false) parsed.useTexthooker = false; if (options.texthooker === false) parsed.useTexthooker = false;
if (typeof options.args === 'string') parsed.mpvArgs = options.args; if (typeof options.args === 'string') parsed.mpvArgs = options.args;
+2
View File
@@ -87,6 +87,8 @@ function applyRootOptions(program: Command): void {
.option('--log-level <level>', 'Log level') .option('--log-level <level>', 'Log level')
.option('-v, --version', 'Show SubMiner version') .option('-v, --version', 'Show SubMiner version')
.option('--settings', 'Open settings window') .option('--settings', 'Open settings window')
.option('--yomitan', 'Open Yomitan settings window')
.option('--hachidori', 'Open Hachidori settings window')
.option('-u, --update', 'Check for updates') .option('-u, --update', 'Check for updates')
.option('-R, --rofi', 'Use rofi picker') .option('-R, --rofi', 'Use rofi picker')
.option('-H, --history', 'Browse local watch history') .option('-H, --history', 'Browse local watch history')
+297 -120
View File
@@ -1,128 +1,305 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import type { Args } from './types.js'; import fs from 'node:fs';
import { runJellyfinPlayMenuWithDeps } from './jellyfin.js'; import os from 'node:os';
import path from 'node:path';
import {
buildForwardedJellyfinAppArgs,
buildRootSearchGroups,
classifyJellyfinChildSelection,
deriveJellyfinTokenStorePath,
hasStoredJellyfinSession,
parseEpisodePathFromDisplay,
parseJellyfinErrorFromAppOutput,
parseJellyfinItemsFromAppOutput,
parseJellyfinLibrariesFromAppOutput,
parseJellyfinPreviewAuthResponse,
readUtf8FileAppendedSince,
runJellyfinPlayMenuWithDeps,
shouldRetryWithStartForNoRunningInstance,
} from './jellyfin.js';
import { makeLauncherArgs } from './test-support/args.js';
import { withEnv } from './test-support/env.js';
function createArgs(): Args { function withTempDir<T>(fn: (dir: string) => T): T {
return { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-jellyfin-test-'));
backend: 'auto', try {
directory: '.', return fn(dir);
recursive: false, } finally {
profile: '', fs.rmSync(dir, { recursive: true, force: true });
startOverlay: false, }
youtubePrimarySubLangs: [],
youtubeSecondarySubLangs: [],
youtubeAudioLangs: [],
useTexthooker: false,
autoStartOverlay: false,
texthookerOnly: false,
texthookerOpenBrowser: false,
useRofi: false,
history: false,
sync: false,
syncCliTokens: [],
syncUi: false,
logLevel: 'info',
logRotation: 7,
passwordStore: '',
target: '',
targetKind: '',
jimakuApiKey: '',
jimakuApiKeyCommand: '',
jimakuApiBaseUrl: '',
jimakuLanguagePreference: 'ja',
jimakuMaxEntryResults: 20,
jellyfin: false,
jellyfinLogin: false,
jellyfinLogout: false,
jellyfinPlay: false,
jellyfinDiscovery: false,
dictionary: false,
dictionaryCandidates: false,
dictionarySelect: false,
stats: false,
doctor: false,
doctorRefreshKnownWords: false,
logsExport: false,
version: false,
settings: false,
youtubeBrowser: false,
configPath: false,
configShow: false,
mpvIdle: false,
mpvSocket: false,
mpvStatus: false,
mpvArgs: '',
appPassthrough: false,
appArgs: [],
jellyfinServer: 'https://jellyfin.example.test',
jellyfinUsername: '',
jellyfinPassword: '',
launchMode: 'normal',
};
} }
test('Jellyfin playback ensures Linux runtime plugin before detached idle mpv bootstrap', async () => { class HandoffComplete extends Error {}
const originalAccessToken = process.env.SUBMINER_JELLYFIN_ACCESS_TOKEN;
const originalUserId = process.env.SUBMINER_JELLYFIN_USER_ID;
process.env.SUBMINER_JELLYFIN_ACCESS_TOKEN = 'token';
process.env.SUBMINER_JELLYFIN_USER_ID = 'user';
const calls: string[] = [];
try { type PlayMenuDeps = NonNullable<Parameters<typeof runJellyfinPlayMenuWithDeps>[4]>;
await assert.rejects(
() =>
runJellyfinPlayMenuWithDeps(
'/tmp/SubMiner.AppImage',
createArgs(),
'/tmp/subminer',
'/tmp/subminer.sock',
{
loadLauncherJellyfinConfig: () => ({}),
findRofiTheme: () => null,
resolveJellyfinSelection: async () => 'item-123',
resolveJellyfinSelectionViaApp: async () => {
throw new Error('unexpected app-based selection');
},
hasStoredJellyfinSession: () => true,
requestJellyfinPreviewAuthFromApp: async () => null,
resolveLauncherMainConfigPath: () => '/tmp/SubMiner/config.jsonc',
pathExists: () => false,
ensureRuntimePluginReady: async () => {
calls.push('plugin');
},
waitForUnixSocketReady: async () => {
calls.push('wait');
return true;
},
launchMpvIdleDetached: async () => {
calls.push('launch');
},
resolveLauncherRuntimePluginPath: () => {
calls.push('resolve');
return '/tmp/plugin/main.lua';
},
runAppCommandWithInheritLogged: () => {
calls.push('handoff');
throw new Error('stop after handoff');
},
log: () => {},
},
),
/stop after handoff/,
);
assert.deepEqual(calls, ['plugin', 'resolve', 'launch', 'wait', 'handoff']); /**
} finally { * Runs the play menu with fake deps and a direct env session. The app handoff never returns in
if (originalAccessToken === undefined) { * production, so the fake throws `HandoffComplete` after recording its args into `handoff`.
delete process.env.SUBMINER_JELLYFIN_ACCESS_TOKEN; */
} else { async function runPlayMenu(options: {
process.env.SUBMINER_JELLYFIN_ACCESS_TOKEN = originalAccessToken; socketReady?: boolean;
} overrides?: Partial<PlayMenuDeps>;
if (originalUserId === undefined) { args?: Parameters<typeof makeLauncherArgs>[0];
delete process.env.SUBMINER_JELLYFIN_USER_ID; }) {
} else { const launches: string[] = [];
process.env.SUBMINER_JELLYFIN_USER_ID = originalUserId; const handoff: { appArgs: string[] | null } = { appArgs: null };
} const deps: PlayMenuDeps = {
} loadLauncherJellyfinConfig: () => ({}),
findRofiTheme: () => null,
resolveJellyfinSelection: async () => 'item-123',
resolveJellyfinSelectionViaApp: async () => {
throw new Error('unexpected app-based selection');
},
hasStoredJellyfinSession: () => true,
requestJellyfinPreviewAuthFromApp: async () => null,
resolveLauncherMainConfigPath: () => '/tmp/SubMiner/config.jsonc',
pathExists: () => options.socketReady ?? false,
ensureRuntimePluginReady: async () => {
launches.push('plugin');
},
waitForUnixSocketReady: async () => true,
launchMpvIdleDetached: async () => {
launches.push('launch');
},
resolveLauncherRuntimePluginPath: () => '/tmp/plugin/main.lua',
runAppCommandWithInheritLogged: (_appPath, appArgs) => {
handoff.appArgs = appArgs;
throw new HandoffComplete();
},
log: () => {},
...options.overrides,
};
await withEnv(
{ SUBMINER_JELLYFIN_ACCESS_TOKEN: 'token', SUBMINER_JELLYFIN_USER_ID: 'user' },
() =>
assert.rejects(
() =>
runJellyfinPlayMenuWithDeps(
'/tmp/SubMiner.AppImage',
makeLauncherArgs({ jellyfinServer: 'https://jellyfin.example.test', ...options.args }),
'/tmp/subminer',
'/tmp/subminer.sock',
deps,
),
HandoffComplete,
),
);
return { launches, appArgs: handoff.appArgs };
}
test('Jellyfin playback launches the idle mpv with the runtime plugin, then hands the item to the app', async () => {
const { launches, appArgs } = await runPlayMenu({});
assert.deepEqual(launches, ['plugin', 'launch']);
assert.deepEqual(appArgs, ['--start', '--jellyfin-play', '--jellyfin-item-id=item-123']);
});
test('Jellyfin playback reuses a ready mpv socket instead of launching idle mpv', async () => {
const { launches, appArgs } = await runPlayMenu({ socketReady: true });
assert.deepEqual(launches, []);
assert.deepEqual(appArgs, ['--start', '--jellyfin-play', '--jellyfin-item-id=item-123']);
});
test('parseJellyfinLibrariesFromAppOutput parses prefixed library lines', () => {
const parsed = parseJellyfinLibrariesFromAppOutput(`
[subminer] - 2026-03-01 13:10:34 - INFO - [main] Jellyfin library: Anime [lib1] (tvshows)
[subminer] - 2026-03-01 13:10:35 - INFO - [main] Jellyfin library: Movies [lib2] (movies)
`);
assert.deepEqual(parsed, [
{ id: 'lib1', name: 'Anime', kind: 'tvshows' },
{ id: 'lib2', name: 'Movies', kind: 'movies' },
]);
});
test('parseJellyfinItemsFromAppOutput parses item title/id/type tuples', () => {
const parsed = parseJellyfinItemsFromAppOutput(`
[subminer] - 2026-03-01 13:10:34 - INFO - [main] Jellyfin item: Solo Leveling S01E10 [item-10] (Episode)
[subminer] - 2026-03-01 13:10:35 - INFO - [main] Jellyfin item: Movie [Alt] [movie-1] (Movie)
`);
assert.deepEqual(parsed, [
{
id: 'item-10',
name: 'Solo Leveling S01E10',
type: 'Episode',
display: 'Solo Leveling S01E10',
},
{
id: 'movie-1',
name: 'Movie [Alt]',
type: 'Movie',
display: 'Movie [Alt]',
},
]);
});
test('buildForwardedJellyfinAppArgs forces app log level for parseable list output', () => {
const forwarded = buildForwardedJellyfinAppArgs(
{
jellyfinServer: 'https://jf.example.test/',
passwordStore: 'gnome-libsecret',
logLevel: 'info',
} as never,
['--jellyfin-libraries'],
);
assert.deepEqual(forwarded, [
'--jellyfin-libraries',
'--jellyfin-server',
'https://jf.example.test',
'--password-store',
'gnome-libsecret',
'--log-level',
'info',
]);
});
test('parseJellyfinErrorFromAppOutput extracts bracketed error lines', () => {
const parsed = parseJellyfinErrorFromAppOutput(`
[subminer] - 2026-03-01 13:10:34 - WARN - [main] test warning
[2026-03-01T21:11:28.821Z] [ERROR] Missing Jellyfin session. Set SUBMINER_JELLYFIN_ACCESS_TOKEN and SUBMINER_JELLYFIN_USER_ID, then retry.
`);
assert.equal(
parsed,
'Missing Jellyfin session. Set SUBMINER_JELLYFIN_ACCESS_TOKEN and SUBMINER_JELLYFIN_USER_ID, then retry.',
);
});
test('parseJellyfinErrorFromAppOutput extracts main runtime error lines', () => {
const parsed = parseJellyfinErrorFromAppOutput(`
[subminer] - 2026-03-01 13:10:34 - ERROR - [main] runJellyfinCommand failed: {"message":"Missing Jellyfin password."}
`);
assert.equal(
parsed,
'[main] runJellyfinCommand failed: {"message":"Missing Jellyfin password."}',
);
});
test('parseJellyfinPreviewAuthResponse parses valid structured response payload', () => {
const parsed = parseJellyfinPreviewAuthResponse(
JSON.stringify({
serverUrl: 'http://pve-main:8096/',
accessToken: 'token-123',
userId: 'user-1',
}),
);
assert.deepEqual(parsed, {
serverUrl: 'http://pve-main:8096',
accessToken: 'token-123',
userId: 'user-1',
});
});
test('parseJellyfinPreviewAuthResponse returns null for invalid payloads', () => {
assert.equal(parseJellyfinPreviewAuthResponse(''), null);
assert.equal(parseJellyfinPreviewAuthResponse('{not json}'), null);
assert.equal(
parseJellyfinPreviewAuthResponse(
JSON.stringify({
serverUrl: 'http://pve-main:8096',
accessToken: '',
userId: 'user-1',
}),
),
null,
);
});
test('hasStoredJellyfinSession checks token-store existence', () => {
const configPath = path.join('/home/test', '.config', 'SubMiner', 'config.jsonc');
const tokenPath = deriveJellyfinTokenStorePath(configPath);
const exists = (candidate: string): boolean => candidate === tokenPath;
assert.equal(hasStoredJellyfinSession(configPath, exists), true);
assert.equal(
hasStoredJellyfinSession(path.join('/home/test', '.config', 'Other', 'alt.jsonc'), exists),
false,
);
});
test('shouldRetryWithStartForNoRunningInstance matches expected app lifecycle error', () => {
assert.equal(
shouldRetryWithStartForNoRunningInstance('No running instance. Use --start to launch the app.'),
true,
);
assert.equal(
shouldRetryWithStartForNoRunningInstance(
'Missing Jellyfin session. Run --jellyfin-login first.',
),
false,
);
});
test('readUtf8FileAppendedSince treats offset as bytes and survives multibyte logs', () => {
withTempDir((root) => {
const logPath = path.join(root, 'SubMiner.log');
const prefix = '[subminer] こんにちは\n';
const suffix = '[subminer] Jellyfin library: Movies [lib2] (movies)\n';
fs.writeFileSync(logPath, `${prefix}${suffix}`, 'utf8');
const byteOffset = Buffer.byteLength(prefix, 'utf8');
const fromByteOffset = readUtf8FileAppendedSince(logPath, byteOffset);
assert.match(fromByteOffset, /Jellyfin library: Movies \[lib2\] \(movies\)/);
const fromBeyondEnd = readUtf8FileAppendedSince(logPath, byteOffset + 9999);
assert.match(fromBeyondEnd, /Jellyfin library: Movies \[lib2\] \(movies\)/);
});
});
test('parseEpisodePathFromDisplay extracts series and season from episode display titles', () => {
assert.deepEqual(
parseEpisodePathFromDisplay('KONOSUBA S01E03 A Panty Treasure in This Right Hand!'),
{
seriesName: 'KONOSUBA',
seasonNumber: 1,
},
);
assert.deepEqual(parseEpisodePathFromDisplay('Frieren S2E10 Something'), {
seriesName: 'Frieren',
seasonNumber: 2,
});
});
test('parseEpisodePathFromDisplay returns null for non-episode displays', () => {
assert.equal(parseEpisodePathFromDisplay('Movie Title (Movie)'), null);
assert.equal(parseEpisodePathFromDisplay('Just A Name'), null);
});
test('buildRootSearchGroups excludes episodes and keeps containers/movies', () => {
const groups = buildRootSearchGroups([
{ id: 'series-1', name: 'The Eminence in Shadow', type: 'Series', display: 'x' },
{ id: 'movie-1', name: 'Spirited Away', type: 'Movie', display: 'x' },
{ id: 'episode-1', name: 'The Eminence in Shadow S01E01', type: 'Episode', display: 'x' },
]);
assert.deepEqual(groups, [
{
id: 'series-1',
name: 'The Eminence in Shadow',
type: 'Series',
display: 'The Eminence in Shadow (Series)',
},
{
id: 'movie-1',
name: 'Spirited Away',
type: 'Movie',
display: 'Spirited Away (Movie)',
},
]);
});
test('classifyJellyfinChildSelection keeps container drilldown state instead of flattening', () => {
const next = classifyJellyfinChildSelection({ id: 'season-2', type: 'Season' });
assert.deepEqual(next, {
kind: 'container',
id: 'season-2',
});
}); });
+364 -888
View File
File diff suppressed because it is too large. Load diff
+523 -964
View File
File diff suppressed because it is too large. Load diff
+9 -14
View File
@@ -30,12 +30,6 @@ test('parseArgs captures mpv args string', () => {
assert.equal(parsed.mpvArgs, '--pause=yes --title="movie night"'); assert.equal(parsed.mpvArgs, '--pause=yes --title="movie night"');
}); });
test('parseArgs appends CLI mpv profile to configured mpv profile', () => {
const parsed = parseArgs(['--profile', 'hdr'], 'subminer', {}, { profile: 'anime' });
assert.equal(parsed.profile, 'anime,hdr');
});
test('parseArgs maps root settings window option', () => { test('parseArgs maps root settings window option', () => {
const parsed = parseArgs(['--settings'], 'subminer', {}); const parsed = parseArgs(['--settings'], 'subminer', {});
@@ -224,14 +218,6 @@ test('parseArgs maps stats cleanup to vocab mode by default', () => {
assert.equal(parsed.statsCleanupVocab, true); assert.equal(parsed.statsCleanupVocab, true);
}); });
test('parseArgs maps explicit stats cleanup vocab flag', () => {
const parsed = parseArgs(['stats', 'cleanup', '-v'], 'subminer', {});
assert.equal(parsed.stats, true);
assert.equal(parsed.statsCleanup, true);
assert.equal(parsed.statsCleanupVocab, true);
});
test('parseArgs maps lifetime stats cleanup flag', () => { test('parseArgs maps lifetime stats cleanup flag', () => {
const parsed = parseArgs(['stats', 'cleanup', '--lifetime'], 'subminer', {}); const parsed = parseArgs(['stats', 'cleanup', '--lifetime'], 'subminer', {});
@@ -353,3 +339,12 @@ test('parseArgs requires an explicit logs action', () => {
assert.equal(exit.code, 1); assert.equal(exit.code, 1);
assert.match(exit.stderr, /Logs command requires -e or --export/); assert.match(exit.stderr, /Logs command requires -e or --export/);
}); });
for (const flag of ['--yomitan', '--hachidori']) {
test(`parseArgs forwards ${flag} to the app`, () => {
const parsed = parseArgs([flag], 'subminer', {});
assert.equal(parsed.appPassthrough, true);
assert.deepEqual(parsed.appArgs, [flag]);
assert.equal(parsed.settings, false);
});
}
+144 -258
View File
@@ -8,282 +8,168 @@ import {
installManagedPluginAssetsViaApp, installManagedPluginAssetsViaApp,
} from './runtime-plugin-preflight'; } from './runtime-plugin-preflight';
test('ensureLinuxRuntimePluginAvailable is a no-op on non-Linux platforms', async () => { type EnsureOptions = Parameters<typeof ensureLinuxRuntimePluginAvailable>[0];
const calls: string[] = [];
await ensureLinuxRuntimePluginAvailable({ /**
platform: 'darwin', * Linux preflight harness: by default every managed asset resolves, so tests override only
detectInstalledPlugin: () => { * the probes that should report something missing. Counts installs and collects log messages.
calls.push('detect'); */
return false; function makeEnsureHarness(overrides: Partial<EnsureOptions> = {}) {
}, const state = { installs: 0, logs: [] as string[] };
resolveRuntimePluginPath: () => { const options: EnsureOptions = {
calls.push('resolve');
return null;
},
installManagedPluginAssets: async () => {
calls.push('install');
return { ok: true, status: 'installed', path: '/tmp/plugin/main.lua' };
},
log: () => {
calls.push('log');
},
});
assert.deepEqual(calls, []);
});
test('ensureLinuxRuntimePluginAvailable skips install when plugin, theme, and thumbnailer exist', async () => {
const calls: string[] = [];
await ensureLinuxRuntimePluginAvailable({
platform: 'linux',
detectInstalledPlugin: () => {
calls.push('detect');
return true;
},
resolveRuntimePluginPath: () => {
calls.push('resolve');
return null;
},
installManagedPluginAssets: async () => {
calls.push('install');
return { ok: true, status: 'installed', path: '/tmp/plugin/main.lua' };
},
isManagedThemeAvailable: () => {
calls.push('theme');
return true;
},
isManagedThumbnailerAvailable: () => {
calls.push('thumbnailer');
return true;
},
log: () => {},
});
assert.deepEqual(calls, ['detect', 'theme', 'thumbnailer']);
});
test('ensureLinuxRuntimePluginAvailable skips install when all managed assets resolve', async () => {
const calls: string[] = [];
await ensureLinuxRuntimePluginAvailable({
platform: 'linux',
xdgDataHome: '/tmp/xdg-data',
detectInstalledPlugin: () => {
calls.push('detect');
return false;
},
resolveRuntimePluginPath: () => {
calls.push('resolve');
return '/tmp/plugin/main.lua';
},
installManagedPluginAssets: async () => {
calls.push('install');
return { ok: true, status: 'installed', path: '/tmp/plugin/main.lua' };
},
isManagedThemeAvailable: () => {
calls.push('theme');
return true;
},
isManagedThumbnailerAvailable: () => {
calls.push('thumbnailer');
return true;
},
log: () => {},
});
assert.deepEqual(calls, ['detect', 'resolve', 'theme', 'thumbnailer']);
});
test('ensureLinuxRuntimePluginAvailable installs managed assets when rofi theme is missing', async () => {
const calls: string[] = [];
let themeAvailable = false;
await ensureLinuxRuntimePluginAvailable({
platform: 'linux',
xdgDataHome: '/tmp/xdg-data',
detectInstalledPlugin: () => {
calls.push('detect');
return false;
},
resolveRuntimePluginPath: () => {
calls.push('resolve');
return '/tmp/plugin/main.lua';
},
isManagedThemeAvailable: () => {
calls.push('theme');
return themeAvailable;
},
isManagedThumbnailerAvailable: () => {
calls.push('thumbnailer');
return true;
},
installManagedPluginAssets: async () => {
calls.push('install');
themeAvailable = true;
return { ok: true, status: 'installed', path: '/tmp/plugin/main.lua' };
},
log: (level, _configured, message) => {
calls.push(`${level}:${message}`);
},
});
assert.deepEqual(calls, [
'detect',
'resolve',
'theme',
'info:Linux runtime support assets missing; installing managed plugin/theme/thumbnailer assets.',
'install',
'info:Managed Linux runtime support assets installed: plugin=/tmp/plugin/main.lua theme=/tmp/xdg-data/SubMiner/themes/subminer.rasi thumbnailer=/tmp/xdg-data/SubMiner/thumbnailers/subminer-ffmpegthumbnailer.thumbnailer',
'resolve',
'theme',
'thumbnailer',
]);
});
test('ensureLinuxRuntimePluginAvailable installs managed assets when thumbnailer is missing', async () => {
const calls: string[] = [];
let thumbnailerAvailable = false;
await ensureLinuxRuntimePluginAvailable({
platform: 'linux',
xdgDataHome: '/tmp/xdg-data',
detectInstalledPlugin: () => true,
resolveRuntimePluginPath: () => '/tmp/plugin/main.lua',
isManagedThemeAvailable: () => true,
isManagedThumbnailerAvailable: () => thumbnailerAvailable,
installManagedPluginAssets: async () => {
calls.push('install');
thumbnailerAvailable = true;
return { ok: true, status: 'installed', path: '/tmp/plugin/main.lua' };
},
log: (_level, _configured, message) => {
calls.push(message);
},
});
assert.deepEqual(calls, [
'Linux runtime support assets missing; installing managed plugin/theme/thumbnailer assets.',
'install',
'Managed Linux runtime support assets installed: plugin=/tmp/plugin/main.lua theme=/tmp/xdg-data/SubMiner/themes/subminer.rasi thumbnailer=/tmp/xdg-data/SubMiner/thumbnailers/subminer-ffmpegthumbnailer.thumbnailer',
]);
});
test('ensureLinuxRuntimePluginAvailable retains an installed plugin after installing support assets', async () => {
const calls: string[] = [];
let thumbnailerAvailable = false;
await ensureLinuxRuntimePluginAvailable({
platform: 'linux',
xdgDataHome: '/tmp/xdg-data',
detectInstalledPlugin: () => true,
resolveRuntimePluginPath: () => {
calls.push('resolve');
return null;
},
isManagedThemeAvailable: () => true,
isManagedThumbnailerAvailable: () => thumbnailerAvailable,
installManagedPluginAssets: async () => {
calls.push('install');
thumbnailerAvailable = true;
return { ok: true, status: 'installed', path: '/tmp/plugin/main.lua' };
},
log: () => {},
});
assert.deepEqual(calls, ['install']);
});
test('ensureLinuxRuntimePluginAvailable installs managed assets and re-resolves plugin path', async () => {
const calls: string[] = [];
let resolveCount = 0;
await ensureLinuxRuntimePluginAvailable({
platform: 'linux', platform: 'linux',
xdgDataHome: '/tmp/xdg-data', xdgDataHome: '/tmp/xdg-data',
detectInstalledPlugin: () => false, detectInstalledPlugin: () => false,
resolveRuntimePluginPath: () => { resolveRuntimePluginPath: () => '/tmp/plugin/main.lua',
resolveCount += 1;
calls.push(`resolve:${resolveCount}`);
return resolveCount === 1 ? null : '/tmp/plugin/main.lua';
},
isManagedThemeAvailable: () => true, isManagedThemeAvailable: () => true,
isManagedThumbnailerAvailable: () => true, isManagedThumbnailerAvailable: () => true,
installManagedPluginAssets: async () => { installManagedPluginAssets: async () => {
calls.push('install'); state.installs += 1;
return { ok: true, status: 'installed', path: '/tmp/plugin/main.lua' }; return { ok: true, status: 'installed', path: '/tmp/plugin/main.lua' };
}, },
log: (level, _configured, message) => { log: (_level, _configured, message) => {
calls.push(`${level}:${message}`); state.logs.push(message);
},
...overrides,
};
return { state, run: () => ensureLinuxRuntimePluginAvailable(options) };
}
test('ensureLinuxRuntimePluginAvailable is a no-op on non-Linux platforms', async () => {
const unexpected = () => {
throw new Error('probed on a non-Linux platform');
};
const harness = makeEnsureHarness({
platform: 'darwin',
detectInstalledPlugin: unexpected,
resolveRuntimePluginPath: unexpected,
isManagedThemeAvailable: unexpected,
isManagedThumbnailerAvailable: unexpected,
});
await harness.run();
assert.equal(harness.state.installs, 0);
assert.deepEqual(harness.state.logs, []);
});
const skipInstallCases: Array<{ name: string; overrides: Partial<EnsureOptions> }> = [
{
name: 'plugin, theme, and thumbnailer exist',
overrides: { detectInstalledPlugin: () => true, resolveRuntimePluginPath: () => null },
},
{ name: 'all managed assets resolve', overrides: {} },
];
for (const c of skipInstallCases) {
test(`ensureLinuxRuntimePluginAvailable skips install when ${c.name}`, async () => {
const harness = makeEnsureHarness(c.overrides);
await harness.run();
assert.equal(harness.state.installs, 0);
assert.deepEqual(harness.state.logs, []);
});
}
const installWhenMissingCases: Array<{ name: string; missing: 'theme' | 'thumbnailer' }> = [
{ name: 'rofi theme is missing', missing: 'theme' },
{ name: 'thumbnailer is missing', missing: 'thumbnailer' },
];
for (const c of installWhenMissingCases) {
test(`ensureLinuxRuntimePluginAvailable installs managed assets when ${c.name}`, async () => {
let available = false;
const probe = {
[c.missing === 'theme' ? 'isManagedThemeAvailable' : 'isManagedThumbnailerAvailable']: () =>
available,
};
const harness = makeEnsureHarness({
...probe,
installManagedPluginAssets: async () => {
harness.state.installs += 1;
available = true;
return { ok: true, status: 'installed', path: '/tmp/plugin/main.lua' };
},
});
await harness.run();
assert.equal(harness.state.installs, 1);
assert.equal(harness.state.logs.length, 2);
assert.match(harness.state.logs[0]!, /support assets missing; installing/);
assert.match(
harness.state.logs[1]!,
/installed: plugin=\/tmp\/plugin\/main\.lua theme=.*subminer\.rasi thumbnailer=.*\.thumbnailer/,
);
});
}
test('ensureLinuxRuntimePluginAvailable retains an installed plugin after installing support assets', async () => {
let thumbnailerAvailable = false;
const harness = makeEnsureHarness({
detectInstalledPlugin: () => true,
// An installed plugin means the bundled path is never needed, even after the install.
resolveRuntimePluginPath: () => null,
isManagedThumbnailerAvailable: () => thumbnailerAvailable,
installManagedPluginAssets: async () => {
harness.state.installs += 1;
thumbnailerAvailable = true;
return { ok: true, status: 'installed', path: '/tmp/plugin/main.lua' };
}, },
}); });
assert.deepEqual(calls, [ await harness.run();
'resolve:1',
'info:Linux runtime support assets missing; installing managed plugin/theme/thumbnailer assets.', assert.equal(harness.state.installs, 1);
'install',
'info:Managed Linux runtime support assets installed: plugin=/tmp/plugin/main.lua theme=/tmp/xdg-data/SubMiner/themes/subminer.rasi thumbnailer=/tmp/xdg-data/SubMiner/thumbnailers/subminer-ffmpegthumbnailer.thumbnailer',
'resolve:2',
]);
}); });
test('ensureLinuxRuntimePluginAvailable fails when install result is not ok', async () => { test('ensureLinuxRuntimePluginAvailable installs managed assets and re-resolves plugin path', async () => {
await assert.rejects( let installed = false;
() => const harness = makeEnsureHarness({
ensureLinuxRuntimePluginAvailable({ resolveRuntimePluginPath: () => (installed ? '/tmp/plugin/main.lua' : null),
platform: 'linux', installManagedPluginAssets: async () => {
detectInstalledPlugin: () => false, harness.state.installs += 1;
resolveRuntimePluginPath: () => null, installed = true;
installManagedPluginAssets: async () => ({ return { ok: true, status: 'installed', path: '/tmp/plugin/main.lua' };
ok: false, },
status: 'failed', });
error: 'copy failed',
}), await harness.run();
log: () => {},
}), assert.equal(harness.state.installs, 1);
/copy failed/,
);
}); });
test('ensureLinuxRuntimePluginAvailable fails when runtime path remains unresolved after install', async () => { const failureCases: Array<{ name: string; overrides: Partial<EnsureOptions>; error: RegExp }> = [
await assert.rejects( {
() => name: 'install result is not ok',
ensureLinuxRuntimePluginAvailable({ overrides: {
platform: 'linux', resolveRuntimePluginPath: () => null,
detectInstalledPlugin: () => false, installManagedPluginAssets: async () => ({
resolveRuntimePluginPath: () => null, ok: false,
installManagedPluginAssets: async () => ({ status: 'failed',
ok: true, error: 'copy failed',
status: 'installed',
path: '/tmp/plugin/main.lua',
}),
log: () => {},
}), }),
/managed runtime plugin assets could not be installed/i, },
); error: /copy failed/,
}); },
{
name: 'runtime path remains unresolved after install',
overrides: { resolveRuntimePluginPath: () => null },
error: /managed runtime plugin assets could not be installed/i,
},
{
name: 'thumbnailer remains missing after install',
overrides: { detectInstalledPlugin: () => true, isManagedThumbnailerAvailable: () => false },
error: /thumbnailer=.*subminer-ffmpegthumbnailer\.thumbnailer/i,
},
];
test('ensureLinuxRuntimePluginAvailable fails when thumbnailer remains missing after install', async () => { for (const c of failureCases) {
await assert.rejects( test(`ensureLinuxRuntimePluginAvailable fails when ${c.name}`, async () => {
() => await assert.rejects(() => makeEnsureHarness(c.overrides).run(), c.error);
ensureLinuxRuntimePluginAvailable({ });
platform: 'linux', }
xdgDataHome: '/tmp/xdg-data',
detectInstalledPlugin: () => true,
resolveRuntimePluginPath: () => '/tmp/plugin/main.lua',
isManagedThemeAvailable: () => true,
isManagedThumbnailerAvailable: () => false,
installManagedPluginAssets: async () => ({
ok: true,
status: 'installed',
path: '/tmp/plugin/main.lua',
}),
log: () => {},
}),
/thumbnailer=.*subminer-ffmpegthumbnailer\.thumbnailer/i,
);
});
test('ensureLinuxRuntimePluginAvailable rejects a thumbnailer directory before and after install', async () => { test('ensureLinuxRuntimePluginAvailable rejects a thumbnailer directory before and after install', async () => {
const xdgDataHome = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-thumbnailer-directory-')); const xdgDataHome = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-thumbnailer-directory-'));
+209 -213
View File
@@ -1,106 +1,96 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { ensureLauncherSetupReady, waitForSetupCompletion } from './setup-gate'; import {
import type { SetupState } from '../src/shared/setup-state'; ensureLauncherSetupReady,
resolveLauncherGateBackend,
waitForSetupCompletion,
} from './setup-gate';
import { createDefaultSetupState, type SetupState } from '../src/shared/setup-state';
const commandLineSetupDefaults = { /** An in-progress setup state; tests override only the fields that matter. */
bunInstallStatus: 'unknown', function makeState(overrides: Partial<SetupState> = {}): SetupState {
launcherInstallStatus: 'unknown', return {
launcherInstallPath: null, version: 4,
} satisfies Pick<SetupState, 'bunInstallStatus' | 'launcherInstallStatus' | 'launcherInstallPath'>; status: 'in_progress',
completedAt: null,
completionSource: null,
yomitanSetupMode: null,
lastSeenYomitanDictionaryCount: 0,
pluginInstallStatus: 'unknown',
pluginInstallPathSummary: null,
windowsMpvShortcutPreferences: { startMenuEnabled: true, desktopEnabled: true },
windowsMpvShortcutLastStatus: 'unknown',
bunInstallStatus: 'unknown',
launcherInstallStatus: 'unknown',
launcherInstallPath: null,
...overrides,
};
}
test('waitForSetupCompletion resolves completed and cancelled states', async () => { function completedState(overrides: Partial<SetupState> = {}): SetupState {
const sequence: Array<SetupState | null> = [ return makeState({
null, status: 'completed',
{ completedAt: '2026-03-07T00:00:00.000Z',
version: 4, completionSource: 'user',
status: 'in_progress', yomitanSetupMode: 'internal',
completedAt: null, lastSeenYomitanDictionaryCount: 1,
completionSource: null, ...overrides,
yomitanSetupMode: null, });
lastSeenYomitanDictionaryCount: 0, }
pluginInstallStatus: 'unknown',
pluginInstallPathSummary: null,
windowsMpvShortcutPreferences: { startMenuEnabled: true, desktopEnabled: true },
windowsMpvShortcutLastStatus: 'unknown',
...commandLineSetupDefaults,
},
{
version: 4,
status: 'completed',
completedAt: '2026-03-07T00:00:00.000Z',
completionSource: 'user',
yomitanSetupMode: 'internal',
lastSeenYomitanDictionaryCount: 1,
pluginInstallStatus: 'skipped',
pluginInstallPathSummary: null,
windowsMpvShortcutPreferences: { startMenuEnabled: true, desktopEnabled: true },
windowsMpvShortcutLastStatus: 'skipped',
...commandLineSetupDefaults,
},
];
const result = await waitForSetupCompletion({ const cancelledState = () => makeState({ status: 'cancelled' });
readSetupState: () => sequence.shift() ?? null,
/** Deterministic clock: every `now()` advances 100ms and `sleep` returns immediately. */
function fakeClock() {
let value = 0;
return {
sleep: async () => undefined, sleep: async () => undefined,
now: (() => { now: () => (value += 100),
let value = 0;
return () => (value += 100);
})(),
timeoutMs: 5_000, timeoutMs: 5_000,
pollIntervalMs: 100, pollIntervalMs: 100,
}); };
}
assert.equal(result, 'completed'); /** Reader that serves `states` in order, then repeats the last one; counts its reads. */
}); function sequenceReader(states: Array<SetupState | null>) {
const reader = {
reads: 0,
read: (): SetupState | null => states[Math.min(reader.reads++, states.length - 1)] ?? null,
};
return reader;
}
for (const c of [
{ name: 'completed', last: completedState(), expected: 'completed' },
{ name: 'cancelled', last: cancelledState(), expected: 'cancelled' },
] as const) {
test(`waitForSetupCompletion resolves ${c.name} state after polling through earlier states`, async () => {
const reader = sequenceReader([null, makeState(), c.last]);
const result = await waitForSetupCompletion({
readSetupState: reader.read,
...fakeClock(),
});
assert.equal(result, c.expected);
assert.equal(reader.reads, 3);
});
}
test('ensureLauncherSetupReady launches setup app and resumes only after completion', async () => { test('ensureLauncherSetupReady launches setup app and resumes only after completion', async () => {
const calls: string[] = []; const calls: string[] = [];
let reads = 0; const reader = sequenceReader([
null,
makeState(),
completedState({ pluginInstallStatus: 'installed', pluginInstallPathSummary: '/tmp/mpv' }),
]);
const ready = await ensureLauncherSetupReady({ const ready = await ensureLauncherSetupReady({
readSetupState: () => { readSetupState: reader.read,
reads += 1;
if (reads === 1) return null;
if (reads === 2) {
return {
version: 4,
status: 'in_progress',
completedAt: null,
completionSource: null,
yomitanSetupMode: null,
lastSeenYomitanDictionaryCount: 0,
pluginInstallStatus: 'unknown',
pluginInstallPathSummary: null,
windowsMpvShortcutPreferences: { startMenuEnabled: true, desktopEnabled: true },
windowsMpvShortcutLastStatus: 'unknown',
...commandLineSetupDefaults,
};
}
return {
version: 4,
status: 'completed',
completedAt: '2026-03-07T00:00:00.000Z',
completionSource: 'user',
yomitanSetupMode: 'internal',
lastSeenYomitanDictionaryCount: 1,
pluginInstallStatus: 'installed',
pluginInstallPathSummary: '/tmp/mpv',
windowsMpvShortcutPreferences: { startMenuEnabled: true, desktopEnabled: true },
windowsMpvShortcutLastStatus: 'installed',
...commandLineSetupDefaults,
};
},
launchSetupApp: () => { launchSetupApp: () => {
calls.push('launch'); calls.push('launch');
}, },
sleep: async () => undefined, ...fakeClock(),
now: (() => {
let value = 0;
return () => (value += 100);
})(),
timeoutMs: 5_000,
pollIntervalMs: 100,
}); });
assert.equal(ready, true); assert.equal(ready, true);
@@ -116,10 +106,7 @@ test('ensureLauncherSetupReady bypasses setup gate when external yomitan is conf
launchSetupApp: () => { launchSetupApp: () => {
calls.push('launch'); calls.push('launch');
}, },
sleep: async () => undefined, ...fakeClock(),
now: () => 0,
timeoutMs: 5_000,
pollIntervalMs: 100,
}); });
assert.equal(ready, true); assert.equal(ready, true);
@@ -129,76 +116,47 @@ test('ensureLauncherSetupReady bypasses setup gate when external yomitan is conf
test('ensureLauncherSetupReady waits for finish after legacy mpv plugin removal', async () => { test('ensureLauncherSetupReady waits for finish after legacy mpv plugin removal', async () => {
const calls: string[] = []; const calls: string[] = [];
let legacyPluginInstalled = true; let legacyPluginInstalled = true;
let reads = 0; // The completion timestamp moves forward once the setup app has finished.
const reader = sequenceReader([
completedState({ yomitanSetupMode: null, lastSeenYomitanDictionaryCount: 0 }),
completedState({ yomitanSetupMode: null, lastSeenYomitanDictionaryCount: 0 }),
completedState({
completedAt: '2026-05-12T14:40:00.000Z',
yomitanSetupMode: null,
lastSeenYomitanDictionaryCount: 0,
}),
]);
const ready = await ensureLauncherSetupReady({ const ready = await ensureLauncherSetupReady({
readSetupState: () => { readSetupState: reader.read,
reads += 1;
return {
version: 4,
status: 'completed',
completedAt: reads < 3 ? '2026-03-07T00:00:00.000Z' : '2026-05-12T14:40:00.000Z',
completionSource: 'user',
yomitanSetupMode: null,
lastSeenYomitanDictionaryCount: 0,
pluginInstallStatus: 'unknown',
pluginInstallPathSummary: null,
windowsMpvShortcutPreferences: { startMenuEnabled: true, desktopEnabled: true },
windowsMpvShortcutLastStatus: 'unknown',
...commandLineSetupDefaults,
};
},
hasLegacyMpvPlugin: () => legacyPluginInstalled, hasLegacyMpvPlugin: () => legacyPluginInstalled,
launchSetupApp: () => { launchSetupApp: () => {
calls.push('launch'); calls.push('launch');
legacyPluginInstalled = false; legacyPluginInstalled = false;
}, },
sleep: async () => undefined, ...fakeClock(),
now: (() => {
let value = 0;
return () => (value += 100);
})(),
timeoutMs: 5_000,
pollIntervalMs: 100,
}); });
assert.equal(ready, true); assert.equal(ready, true);
assert.deepEqual(calls, ['launch']); assert.deepEqual(calls, ['launch']);
assert.equal(reads >= 3, true); assert.equal(reader.reads >= 3, true);
}); });
test('ensureLauncherSetupReady lets users continue without removing a legacy mpv plugin', async () => { test('ensureLauncherSetupReady lets users continue without removing a legacy mpv plugin', async () => {
const calls: string[] = []; const calls: string[] = [];
let reads = 0; const reader = sequenceReader([
completedState({ lastSeenYomitanDictionaryCount: 2 }),
completedState({ lastSeenYomitanDictionaryCount: 2 }),
completedState({ completedAt: '2026-05-12T14:30:00.000Z', lastSeenYomitanDictionaryCount: 2 }),
]);
const ready = await ensureLauncherSetupReady({ const ready = await ensureLauncherSetupReady({
readSetupState: () => { readSetupState: reader.read,
reads += 1;
return {
version: 4,
status: 'completed',
completedAt: reads < 3 ? '2026-03-07T00:00:00.000Z' : '2026-05-12T14:30:00.000Z',
completionSource: 'user',
yomitanSetupMode: 'internal',
lastSeenYomitanDictionaryCount: 2,
pluginInstallStatus: 'unknown',
pluginInstallPathSummary: null,
windowsMpvShortcutPreferences: { startMenuEnabled: true, desktopEnabled: true },
windowsMpvShortcutLastStatus: 'unknown',
...commandLineSetupDefaults,
};
},
hasLegacyMpvPlugin: () => true, hasLegacyMpvPlugin: () => true,
launchSetupApp: () => { launchSetupApp: () => {
calls.push('launch'); calls.push('launch');
}, },
sleep: async () => undefined, ...fakeClock(),
now: (() => {
let value = 0;
return () => (value += 100);
})(),
timeoutMs: 5_000,
pollIntervalMs: 100,
}); });
assert.equal(ready, true); assert.equal(ready, true);
@@ -207,91 +165,129 @@ test('ensureLauncherSetupReady lets users continue without removing a legacy mpv
test('ensureLauncherSetupReady fails on timeout/cancelled state', async () => { test('ensureLauncherSetupReady fails on timeout/cancelled state', async () => {
const result = await ensureLauncherSetupReady({ const result = await ensureLauncherSetupReady({
readSetupState: () => ({ readSetupState: cancelledState,
version: 4,
status: 'cancelled',
completedAt: null,
completionSource: null,
yomitanSetupMode: null,
lastSeenYomitanDictionaryCount: 0,
pluginInstallStatus: 'unknown',
pluginInstallPathSummary: null,
windowsMpvShortcutPreferences: { startMenuEnabled: true, desktopEnabled: true },
windowsMpvShortcutLastStatus: 'unknown',
...commandLineSetupDefaults,
}),
launchSetupApp: () => undefined, launchSetupApp: () => undefined,
sleep: async () => undefined, ...fakeClock(),
now: (() => {
let value = 0;
return () => (value += 100);
})(),
timeoutMs: 5_000,
pollIntervalMs: 100,
}); });
assert.equal(result, false); assert.equal(result, false);
}); });
test('ensureLauncherSetupReady ignores stale cancelled state after launching setup app', async () => { test('ensureLauncherSetupReady ignores stale cancelled state after launching setup app', async () => {
let reads = 0; const reader = sequenceReader([
cancelledState(),
cancelledState(),
makeState(),
completedState({
completionSource: 'legacy_auto_detected',
pluginInstallStatus: 'installed',
pluginInstallPathSummary: '/tmp/mpv',
}),
]);
const result = await ensureLauncherSetupReady({ const result = await ensureLauncherSetupReady({
readSetupState: () => { readSetupState: reader.read,
reads += 1;
if (reads <= 2) {
return {
version: 4,
status: 'cancelled',
completedAt: null,
completionSource: null,
yomitanSetupMode: null,
lastSeenYomitanDictionaryCount: 0,
pluginInstallStatus: 'unknown',
pluginInstallPathSummary: null,
windowsMpvShortcutPreferences: { startMenuEnabled: true, desktopEnabled: true },
windowsMpvShortcutLastStatus: 'unknown',
...commandLineSetupDefaults,
};
}
if (reads === 3) {
return {
version: 4,
status: 'in_progress',
completedAt: null,
completionSource: null,
yomitanSetupMode: null,
lastSeenYomitanDictionaryCount: 0,
pluginInstallStatus: 'unknown',
pluginInstallPathSummary: null,
windowsMpvShortcutPreferences: { startMenuEnabled: true, desktopEnabled: true },
windowsMpvShortcutLastStatus: 'unknown',
...commandLineSetupDefaults,
};
}
return {
version: 4,
status: 'completed',
completedAt: '2026-03-07T00:00:00.000Z',
completionSource: 'legacy_auto_detected',
yomitanSetupMode: 'internal',
lastSeenYomitanDictionaryCount: 1,
pluginInstallStatus: 'installed',
pluginInstallPathSummary: '/tmp/mpv',
windowsMpvShortcutPreferences: { startMenuEnabled: true, desktopEnabled: true },
windowsMpvShortcutLastStatus: 'unknown',
...commandLineSetupDefaults,
};
},
launchSetupApp: () => undefined, launchSetupApp: () => undefined,
sleep: async () => undefined, ...fakeClock(),
now: (() => {
let value = 0;
return () => (value += 100);
})(),
timeoutMs: 5_000,
pollIntervalMs: 100,
}); });
assert.equal(result, true); assert.equal(result, true);
}); });
test('Hachidori setup ignores completed Yomitan state and external Yomitan profiles', async () => {
let state: SetupState = { ...createDefaultSetupState(), status: 'completed' };
let launched = 0;
let polls = 0;
const ready = await ensureLauncherSetupReady({
dictionaryBackend: 'hachidori',
readSetupState: () => state,
isExternalYomitanConfigured: () => true,
launchSetupApp: () => {
launched += 1;
},
sleep: async () => {
polls += 1;
state = { ...state, dictionaryBackend: 'hachidori', lastSeenYomitanDictionaryCount: 1 };
},
now: () => polls,
timeoutMs: 5,
pollIntervalMs: 1,
});
assert.equal(ready, true);
assert.equal(launched, 1);
assert.equal(polls, 1);
});
test('matching Hachidori completion resumes playback without launching setup', async () => {
const ready = await ensureLauncherSetupReady({
dictionaryBackend: 'hachidori',
readSetupState: () => ({
...createDefaultSetupState(),
dictionaryBackend: 'hachidori',
status: 'completed',
lastSeenYomitanDictionaryCount: 1,
}),
launchSetupApp: () => assert.fail('setup should not open'),
sleep: async () => undefined,
now: () => 0,
timeoutMs: 5,
pollIntervalMs: 1,
});
assert.equal(ready, true);
});
test('a backend that finished setup earlier passes the gate after switching back', async () => {
const ready = await ensureLauncherSetupReady({
dictionaryBackend: 'yomitan',
readSetupState: () => ({
...createDefaultSetupState(),
dictionaryBackend: 'hachidori',
status: 'incomplete',
completedDictionaryBackends: ['yomitan'],
}),
launchSetupApp: () => assert.fail('setup should not open'),
sleep: async () => undefined,
now: () => 0,
timeoutMs: 5,
pollIntervalMs: 1,
});
assert.equal(ready, true);
});
test('gate follows the running app backend until it restarts into the configured one', async () => {
const warnings: string[] = [];
const state = {
...createDefaultSetupState(),
dictionaryBackend: 'yomitan' as const,
status: 'completed' as const,
};
assert.equal(
await resolveLauncherGateBackend({
configuredBackend: 'hachidori',
state,
isAppRunning: async () => true,
warn: (message) => warnings.push(message),
}),
'yomitan',
);
assert.match(warnings[0] ?? '', /restart it to switch to hachidori/);
assert.equal(
await resolveLauncherGateBackend({
configuredBackend: 'hachidori',
state,
isAppRunning: async () => false,
}),
'hachidori',
);
const ready = await ensureLauncherSetupReady({
dictionaryBackend: 'hachidori',
isAppRunning: async () => true,
readSetupState: () => state,
launchSetupApp: () => assert.fail('the running Yomitan app already completed setup'),
sleep: async () => undefined,
now: () => 0,
timeoutMs: 5,
pollIntervalMs: 1,
});
assert.equal(ready, true);
});
+47 -6
View File
@@ -1,7 +1,13 @@
import { isSetupCompleted, type SetupState } from '../src/shared/setup-state.js'; import type { DictionaryBackend } from '../src/types/config.js';
import {
getSetupStateDictionaryBackend,
isSetupCompleted,
type SetupState,
} from '../src/shared/setup-state.js';
export async function waitForSetupCompletion(deps: { export async function waitForSetupCompletion(deps: {
readSetupState: () => SetupState | null; readSetupState: () => SetupState | null;
dictionaryBackend?: DictionaryBackend;
sleep: (ms: number) => Promise<void>; sleep: (ms: number) => Promise<void>;
now: () => number; now: () => number;
timeoutMs: number; timeoutMs: number;
@@ -13,7 +19,7 @@ export async function waitForSetupCompletion(deps: {
while (deps.now() <= deadline) { while (deps.now() <= deadline) {
const state = deps.readSetupState(); const state = deps.readSetupState();
if (isSetupCompleted(state)) { if (isSetupCompleted(state, deps.dictionaryBackend)) {
return 'completed'; return 'completed';
} }
if (ignoringCancelled && state != null && state.status !== 'cancelled') { if (ignoringCancelled && state != null && state.status !== 'cancelled') {
@@ -34,6 +40,7 @@ export async function waitForSetupCompletion(deps: {
export async function waitForLegacyMpvPluginPromptResolution(deps: { export async function waitForLegacyMpvPluginPromptResolution(deps: {
readSetupState: () => SetupState | null; readSetupState: () => SetupState | null;
dictionaryBackend?: DictionaryBackend;
sleep: (ms: number) => Promise<void>; sleep: (ms: number) => Promise<void>;
now: () => number; now: () => number;
timeoutMs: number; timeoutMs: number;
@@ -41,13 +48,13 @@ export async function waitForLegacyMpvPluginPromptResolution(deps: {
initialState?: SetupState | null; initialState?: SetupState | null;
}): Promise<'acknowledged' | 'cancelled' | 'timeout'> { }): Promise<'acknowledged' | 'cancelled' | 'timeout'> {
const deadline = deps.now() + deps.timeoutMs; const deadline = deps.now() + deps.timeoutMs;
const initialCompleted = isSetupCompleted(deps.initialState); const initialCompleted = isSetupCompleted(deps.initialState, deps.dictionaryBackend);
const initialCompletedAt = deps.initialState?.completedAt ?? null; const initialCompletedAt = deps.initialState?.completedAt ?? null;
while (deps.now() <= deadline) { while (deps.now() <= deadline) {
const state = deps.readSetupState(); const state = deps.readSetupState();
if ( if (
isSetupCompleted(state) && isSetupCompleted(state, deps.dictionaryBackend) &&
(!initialCompleted || state?.completedAt !== initialCompletedAt) (!initialCompleted || state?.completedAt !== initialCompletedAt)
) { ) {
return 'acknowledged'; return 'acknowledged';
@@ -62,8 +69,34 @@ export async function waitForLegacyMpvPluginPromptResolution(deps: {
return 'timeout'; return 'timeout';
} }
/**
* The app pins its dictionary backend at startup while the config file can change
* underneath it. When an app is already running, gate on the backend it recorded
* in the setup state rather than the config value it has not restarted into.
*/
export async function resolveLauncherGateBackend(deps: {
configuredBackend: DictionaryBackend;
state: SetupState | null;
isAppRunning?: () => Promise<boolean>;
warn?: (message: string) => void;
}): Promise<DictionaryBackend> {
const runningBackend = deps.state
? getSetupStateDictionaryBackend(deps.state)
: deps.configuredBackend;
if (runningBackend === deps.configuredBackend || !(await deps.isAppRunning?.())) {
return deps.configuredBackend;
}
deps.warn?.(
`SubMiner is running with the ${runningBackend} dictionary backend; restart it to switch to ${deps.configuredBackend}.`,
);
return runningBackend;
}
export async function ensureLauncherSetupReady(deps: { export async function ensureLauncherSetupReady(deps: {
readSetupState: () => SetupState | null; readSetupState: () => SetupState | null;
dictionaryBackend?: DictionaryBackend;
isAppRunning?: () => Promise<boolean>;
warn?: (message: string) => void;
isExternalYomitanConfigured?: () => boolean; isExternalYomitanConfigured?: () => boolean;
hasLegacyMpvPlugin?: () => boolean; hasLegacyMpvPlugin?: () => boolean;
launchSetupApp: () => void; launchSetupApp: () => void;
@@ -73,6 +106,12 @@ export async function ensureLauncherSetupReady(deps: {
pollIntervalMs: number; pollIntervalMs: number;
}): Promise<boolean> { }): Promise<boolean> {
const initialState = deps.readSetupState(); const initialState = deps.readSetupState();
const dictionaryBackend = await resolveLauncherGateBackend({
configuredBackend: deps.dictionaryBackend ?? 'yomitan',
state: initialState,
isAppRunning: deps.isAppRunning,
warn: deps.warn,
});
let setupLaunched = false; let setupLaunched = false;
const launchSetupApp = () => { const launchSetupApp = () => {
if (setupLaunched) return; if (setupLaunched) return;
@@ -84,6 +123,7 @@ export async function ensureLauncherSetupReady(deps: {
launchSetupApp(); launchSetupApp();
const result = await waitForLegacyMpvPluginPromptResolution({ const result = await waitForLegacyMpvPluginPromptResolution({
readSetupState: deps.readSetupState, readSetupState: deps.readSetupState,
dictionaryBackend,
sleep: deps.sleep, sleep: deps.sleep,
now: deps.now, now: deps.now,
timeoutMs: deps.timeoutMs, timeoutMs: deps.timeoutMs,
@@ -95,17 +135,18 @@ export async function ensureLauncherSetupReady(deps: {
} }
} }
if (deps.isExternalYomitanConfigured?.()) { if (dictionaryBackend !== 'hachidori' && deps.isExternalYomitanConfigured?.()) {
return true; return true;
} }
const stateAfterLegacyPrompt = deps.readSetupState(); const stateAfterLegacyPrompt = deps.readSetupState();
if (isSetupCompleted(stateAfterLegacyPrompt)) { if (isSetupCompleted(stateAfterLegacyPrompt, dictionaryBackend)) {
return true; return true;
} }
launchSetupApp(); launchSetupApp();
const result = await waitForSetupCompletion({ const result = await waitForSetupCompletion({
...deps, ...deps,
dictionaryBackend,
ignoreInitialCancelledState: stateAfterLegacyPrompt?.status === 'cancelled', ignoreInitialCancelledState: stateAfterLegacyPrompt?.status === 'cancelled',
}); });
return result === 'completed'; return result === 'completed';
+51 -67
View File
@@ -9,7 +9,6 @@ import {
createDefaultSetupState, createDefaultSetupState,
getDefaultConfigDir, getDefaultConfigDir,
getSetupStatePath, getSetupStatePath,
readSetupState,
writeSetupState, writeSetupState,
} from '../src/shared/setup-state.js'; } from '../src/shared/setup-state.js';
@@ -407,65 +406,65 @@ setInterval(() => {}, 1000);
}; };
} }
test('launcher smoke fixture seeds completed setup state', () => { /**
const smokeCase = createSmokeCase('setup-state'); * Some sandboxes forbid binding unix sockets (EPERM). The fake mpv needs one, so these tests
* cannot pass there; probe once and skip them instead of weakening every assertion.
*/
function unixSocketsDenied(): boolean {
if (process.platform === 'win32') return false;
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-sock-probe-'));
try { try {
const configDir = getDefaultConfigDir({ const probe = spawnSync(
xdgConfigHome: smokeCase.xdgConfigHome, process.execPath,
homeDir: smokeCase.homeDir, [
}); '-e',
const statePath = getSetupStatePath(configDir); `require('node:net').createServer().on('error', (e) => { process.stderr.write(String(e)); process.exit(1); }).listen(${JSON.stringify(path.join(dir, 's.sock'))}, function () { this.close(() => process.exit(0)); });`,
],
assert.equal(readSetupState(statePath)?.status, 'completed'); { encoding: 'utf8', timeout: 5000 },
);
return probe.status !== 0 && /eperm|operation not permitted/i.test(probe.stderr);
} finally { } finally {
fs.rmSync(smokeCase.root, { recursive: true, force: true }); fs.rmSync(dir, { recursive: true, force: true });
fs.rmSync(smokeCase.socketDir, { recursive: true, force: true });
} }
}); }
test('launcher mpv status returns ready when socket is connectable', async () => { const skipWithoutUnixSockets = unixSocketsDenied() ? 'sandbox denies unix socket binding' : false;
await withSmokeCase('mpv-status', async (smokeCase) => {
const env = makeTestEnv(smokeCase);
const fakeMpv = spawn(smokeCase.fakeMpvPath, [`--input-ipc-server=${smokeCase.socketPath}`], {
env,
stdio: 'ignore',
});
try { test(
await waitForSocketReady(smokeCase.socketPath); 'launcher mpv status returns ready when socket is connectable',
const result = runLauncher( { skip: skipWithoutUnixSockets },
smokeCase, async () => {
['mpv', 'status', '--log-level', 'debug'], await withSmokeCase('mpv-status', async (smokeCase) => {
const env = makeTestEnv(smokeCase);
const fakeMpv = spawn(smokeCase.fakeMpvPath, [`--input-ipc-server=${smokeCase.socketPath}`], {
env, env,
'mpv-status', stdio: 'ignore',
); });
const fakeMpvEntries = readJsonLines(path.join(smokeCase.artifactsDir, 'fake-mpv.log'));
const fakeMpvError = fakeMpvEntries.find(
(entry): entry is { error: string } => typeof entry.error === 'string',
)?.error;
const unixSocketDenied =
typeof fakeMpvError === 'string' && /eperm|operation not permitted/i.test(fakeMpvError);
if (unixSocketDenied) { try {
assert.equal(result.status, 1); await waitForSocketReady(smokeCase.socketPath);
assert.match(result.stdout, /socket not ready/i); const result = runLauncher(
} else { smokeCase,
['mpv', 'status', '--log-level', 'debug'],
env,
'mpv-status',
);
assert.equal(result.status, 0); assert.equal(result.status, 0);
assert.match(result.stdout, /socket ready/i); assert.match(result.stdout, /socket ready/i);
} finally {
if (fakeMpv.exitCode === null) {
await new Promise<void>((resolve) => {
fakeMpv.once('close', () => resolve());
});
}
} }
} finally { });
if (fakeMpv.exitCode === null) { },
await new Promise<void>((resolve) => { );
fakeMpv.once('close', () => resolve());
});
}
}
});
});
test( test(
'launcher start-overlay run forwards socket/backend and stops owned background app after mpv exits', 'launcher start-overlay run forwards socket/backend and stops owned background app after mpv exits',
{ timeout: LONG_SMOKE_TEST_TIMEOUT_MS }, { timeout: LONG_SMOKE_TEST_TIMEOUT_MS, skip: skipWithoutUnixSockets },
async () => { async () => {
await withSmokeCase('overlay-start-stop', async (smokeCase) => { await withSmokeCase('overlay-start-stop', async (smokeCase) => {
const env = makeTestEnv(smokeCase); const env = makeTestEnv(smokeCase);
@@ -484,13 +483,8 @@ test(
const appStartEntries = readJsonLines(appStartPath); const appStartEntries = readJsonLines(appStartPath);
const appStopEntries = readJsonLines(appStopPath); const appStopEntries = readJsonLines(appStopPath);
const mpvEntries = readJsonLines(path.join(smokeCase.artifactsDir, 'fake-mpv.log')); const mpvEntries = readJsonLines(path.join(smokeCase.artifactsDir, 'fake-mpv.log'));
const mpvError = mpvEntries.find(
(entry): entry is { error: string } => typeof entry.error === 'string',
)?.error;
const unixSocketDenied =
typeof mpvError === 'string' && /eperm|operation not permitted/i.test(mpvError);
assert.equal(result.status, unixSocketDenied ? 3 : 0); assert.equal(result.status, 0);
assert.match(result.stdout, /Starting SubMiner overlay/i); assert.match(result.stdout, /Starting SubMiner overlay/i);
assert.equal(appStartEntries.length, 1); assert.equal(appStartEntries.length, 1);
@@ -523,7 +517,7 @@ test(
test( test(
'launcher start-overlay attaches to a running background app without spawning another app start command', 'launcher start-overlay attaches to a running background app without spawning another app start command',
{ timeout: LONG_SMOKE_TEST_TIMEOUT_MS }, { timeout: LONG_SMOKE_TEST_TIMEOUT_MS, skip: skipWithoutUnixSockets },
async () => { async () => {
await withSmokeCase('overlay-borrow-background', async (smokeCase) => { await withSmokeCase('overlay-borrow-background', async (smokeCase) => {
const controlServer = await startFakeControlServer(smokeCase); const controlServer = await startFakeControlServer(smokeCase);
@@ -550,13 +544,8 @@ test(
const appStopEntries = readJsonLines(appStopPath); const appStopEntries = readJsonLines(appStopPath);
const controlEntries = readJsonLines(controlServer.logPath); const controlEntries = readJsonLines(controlServer.logPath);
const mpvEntries = readJsonLines(path.join(smokeCase.artifactsDir, 'fake-mpv.log')); const mpvEntries = readJsonLines(path.join(smokeCase.artifactsDir, 'fake-mpv.log'));
const mpvError = mpvEntries.find(
(entry): entry is { error: string } => typeof entry.error === 'string',
)?.error;
const unixSocketDenied =
typeof mpvError === 'string' && /eperm|operation not permitted/i.test(mpvError);
assert.equal(result.status, unixSocketDenied ? 3 : 0); assert.equal(result.status, 0);
if (process.platform === 'linux') { if (process.platform === 'linux') {
assert.equal(appEntries.length > 0, true); assert.equal(appEntries.length > 0, true);
assert.equal( assert.equal(
@@ -583,7 +572,7 @@ test(
test( test(
'launcher starts mpv paused when plugin auto-start visible overlay gate is enabled', 'launcher starts mpv paused when plugin auto-start visible overlay gate is enabled',
{ timeout: LONG_SMOKE_TEST_TIMEOUT_MS }, { timeout: LONG_SMOKE_TEST_TIMEOUT_MS, skip: skipWithoutUnixSockets },
async () => { async () => {
await withSmokeCase('autoplay-ready-gate', async (smokeCase) => { await withSmokeCase('autoplay-ready-gate', async (smokeCase) => {
fs.writeFileSync( fs.writeFileSync(
@@ -607,14 +596,9 @@ test(
); );
const mpvEntries = readJsonLines(path.join(smokeCase.artifactsDir, 'fake-mpv.log')); const mpvEntries = readJsonLines(path.join(smokeCase.artifactsDir, 'fake-mpv.log'));
const mpvError = mpvEntries.find(
(entry): entry is { error: string } => typeof entry.error === 'string',
)?.error;
const unixSocketDenied =
typeof mpvError === 'string' && /eperm|operation not permitted/i.test(mpvError);
const mpvFirstArgs = mpvEntries[0]?.argv; const mpvFirstArgs = mpvEntries[0]?.argv;
assert.equal(result.status, unixSocketDenied ? 3 : 0); assert.equal(result.status, 0);
assert.equal(Array.isArray(mpvFirstArgs), true); assert.equal(Array.isArray(mpvFirstArgs), true);
assert.equal((mpvFirstArgs as string[]).includes('--pause=yes'), true); assert.equal((mpvFirstArgs as string[]).includes('--pause=yes'), true);
assert.match( assert.match(
+7
View File
@@ -0,0 +1,7 @@
import { parseArgs } from '../config.js';
import type { Args } from '../types.js';
/** Default launcher `Args` (as if run with no CLI input), with `overrides` applied. */
export function makeLauncherArgs(overrides: Partial<Args> = {}): Args {
return { ...parseArgs([], 'subminer', {}), ...overrides };
}
+25
View File
@@ -0,0 +1,25 @@
/**
* Runs `run` with the given process env values (`undefined` deletes a key) and restores the
* originals afterwards, even if `run` throws or rejects.
*/
export async function withEnv<T>(
overrides: Record<string, string | undefined>,
run: () => T | Promise<T>,
): Promise<T> {
const originals = Object.fromEntries(
Object.keys(overrides).map((key) => [key, process.env[key]]),
);
const apply = (values: Record<string, string | undefined>): void => {
for (const [key, value] of Object.entries(values)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
};
apply(overrides);
try {
return await run();
} finally {
apply(originals);
}
}
@@ -5,7 +5,7 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { Database as BunDatabase } from 'bun:sqlite'; import { Database as BunDatabase } from 'bun:sqlite';
import { ensureSchema } from '../../src/core/services/immersion-tracker/storage.js'; import { ensureSchema } from '../../src/core/services/immersion-tracker/storage.js';
import { createImmersionDbFixture, insertFixtureSession } from './immersion-db-fixture.js'; import { createImmersionDbFixture } from './immersion-db-fixture.js';
type SchemaRow = { type: string; name: string; tbl_name: string; sql: string | null }; type SchemaRow = { type: string; name: string; tbl_name: string; sql: string | null };
@@ -108,65 +108,3 @@ test('fixture schema stays aligned with production sync-touched tables and index
fs.rmSync(dir, { recursive: true, force: true }); fs.rmSync(dir, { recursive: true, force: true });
} }
}); });
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', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-fixture-foreign-keys-'));
const fixturePath = path.join(dir, 'fixture.sqlite');
try {
createImmersionDbFixture(fixturePath);
const db = new BunDatabase(fixturePath, { readwrite: true });
try {
db.run(`
CREATE TRIGGER remove_fixture_video
BEFORE INSERT ON imm_sessions
BEGIN
DELETE FROM imm_videos WHERE video_id = NEW.video_id;
END
`);
} finally {
db.close();
}
assert.throws(
() =>
insertFixtureSession(fixturePath, {
uuid: 'foreign-key-check',
videoKey: 'foreign-key-check',
startedAtMs: Date.UTC(2026, 6, 9),
}),
/FOREIGN KEY constraint failed/,
);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
+8 -2
View File
@@ -12,6 +12,7 @@
"get-frequency": "bun run scripts/get_frequency.ts --pretty --color-top-x 10000 --yomitan-user-data ~/.config/SubMiner --colorized-line", "get-frequency": "bun run scripts/get_frequency.ts --pretty --color-top-x 10000 --yomitan-user-data ~/.config/SubMiner --colorized-line",
"get-frequency:electron": "bun run build:yomitan && bun build scripts/get_frequency.ts --format=cjs --target=node --outfile dist/scripts/get_frequency.js --external electron && env -u ELECTRON_RUN_AS_NODE electron dist/scripts/get_frequency.js --pretty --color-top-x 10000 --yomitan-user-data ~/.config/SubMiner --colorized-line", "get-frequency:electron": "bun run build:yomitan && bun build scripts/get_frequency.ts --format=cjs --target=node --outfile dist/scripts/get_frequency.js --external electron && env -u ELECTRON_RUN_AS_NODE electron dist/scripts/get_frequency.js --pretty --color-top-x 10000 --yomitan-user-data ~/.config/SubMiner --colorized-line",
"test-yomitan-parser": "bun run scripts/test-yomitan-parser.ts", "test-yomitan-parser": "bun run scripts/test-yomitan-parser.ts",
"test:dictionary:electron": "bun scripts/run-dictionary-settings-smoke.mjs && bun scripts/run-dictionary-settings-smoke.mjs --backend=yomitan && env -u ELECTRON_RUN_AS_NODE electron --no-sandbox --ozone-platform=x11 scripts/check-hachidori-parser.cjs",
"test-yomitan-parser:electron": "bun run build:yomitan && bun build scripts/test-yomitan-parser.ts --format=cjs --target=node --outfile dist/scripts/test-yomitan-parser.js --external electron && env -u ELECTRON_RUN_AS_NODE electron dist/scripts/test-yomitan-parser.js", "test-yomitan-parser:electron": "bun run build:yomitan && bun build scripts/test-yomitan-parser.ts --format=cjs --target=node --outfile dist/scripts/test-yomitan-parser.js --external electron && env -u ELECTRON_RUN_AS_NODE electron dist/scripts/test-yomitan-parser.js",
"verify-known-word-highlights:electron": "bun run build:yomitan && bun build scripts/verify-known-word-highlights.ts --format=cjs --target=node --outfile dist/scripts/verify-known-word-highlights.js --packages=external && env -u ELECTRON_RUN_AS_NODE electron dist/scripts/verify-known-word-highlights.js", "verify-known-word-highlights:electron": "bun run build:yomitan && bun build scripts/verify-known-word-highlights.ts --format=cjs --target=node --outfile dist/scripts/verify-known-word-highlights.js --packages=external && env -u ELECTRON_RUN_AS_NODE electron dist/scripts/verify-known-word-highlights.js",
"record-tokenizer-fixture:electron": "bun run build:yomitan && bun build scripts/record-tokenizer-fixture.ts --format=cjs --target=node --outfile dist/scripts/record-tokenizer-fixture.js --external electron && env -u ELECTRON_RUN_AS_NODE electron dist/scripts/record-tokenizer-fixture.js", "record-tokenizer-fixture:electron": "bun run build:yomitan && bun build scripts/record-tokenizer-fixture.ts --format=cjs --target=node --outfile dist/scripts/record-tokenizer-fixture.js --external electron && env -u ELECTRON_RUN_AS_NODE electron dist/scripts/record-tokenizer-fixture.js",
@@ -21,7 +22,7 @@
"build:launcher": "bun run scripts/build-launcher.ts", "build:launcher": "bun run scripts/build-launcher.ts",
"build:stats": "cd stats && bun run build", "build:stats": "cd stats && bun run build",
"dev:stats": "cd stats && bun run dev", "dev:stats": "cd stats && bun run dev",
"build": "bun run build:yomitan && bun run build:stats && tsc -p tsconfig.json && bun run build:renderer && bun run build:settings && bun run build:syncui && bun run build:launcher && bun run build:assets", "build": "bun run build:yomitan && bun run build:hachidori && bun run build:stats && tsc -p tsconfig.json && bun run build:renderer && bun run build:settings && bun run build:syncui && bun run build:launcher && bun run build:assets",
"build:renderer": "esbuild src/renderer/renderer.ts --bundle --platform=browser --format=esm --target=es2022 --outfile=dist/renderer/renderer.js --sourcemap", "build:renderer": "esbuild src/renderer/renderer.ts --bundle --platform=browser --format=esm --target=es2022 --outfile=dist/renderer/renderer.js --sourcemap",
"build:settings": "esbuild src/settings/settings.ts --bundle --platform=browser --format=esm --target=es2022 --outfile=dist/settings/settings.js --sourcemap", "build:settings": "esbuild src/settings/settings.ts --bundle --platform=browser --format=esm --target=es2022 --outfile=dist/settings/settings.js --sourcemap",
"build:syncui": "esbuild src/syncui/syncui.ts --bundle --platform=browser --format=esm --target=es2022 --outfile=dist/syncui/syncui.js --sourcemap && esbuild src/preload-syncui.ts --bundle --platform=node --format=cjs --target=node20 --external:electron --outfile=dist/preload-syncui.js --sourcemap", "build:syncui": "esbuild src/syncui/syncui.ts --bundle --platform=browser --format=esm --target=es2022 --outfile=dist/syncui/syncui.js --sourcemap && esbuild src/preload-syncui.ts --bundle --platform=node --format=cjs --target=node20 --external:electron --outfile=dist/preload-syncui.js --sourcemap",
@@ -81,7 +82,8 @@
"build:mac:zip": "bun run build && electron-builder --mac zip --publish never", "build:mac:zip": "bun run build && electron-builder --mac zip --publish never",
"build:win": "bun run build && electron-builder --win nsis zip --publish never", "build:win": "bun run build && electron-builder --win nsis zip --publish never",
"build:win:unsigned": "bun run build && node scripts/build-win-unsigned.mjs", "build:win:unsigned": "bun run build && node scripts/build-win-unsigned.mjs",
"test:package": "bun scripts/run-package-smoke.mjs" "test:package": "bun scripts/run-package-smoke.mjs",
"build:hachidori": "bun scripts/build-hachidori.mjs"
}, },
"overrides": { "overrides": {
"@xmldom/xmldom": "0.8.15", "@xmldom/xmldom": "0.8.15",
@@ -232,6 +234,10 @@
"from": "build/yomitan", "from": "build/yomitan",
"to": "yomitan" "to": "yomitan"
}, },
{
"from": "build/hachidori",
"to": "hachidori"
},
{ {
"from": "vendor/yomitan-jlpt-vocab", "from": "vendor/yomitan-jlpt-vocab",
"to": "yomitan-jlpt-vocab" "to": "yomitan-jlpt-vocab"
File diff suppressed because it is too large. Load diff
+69
View File
@@ -0,0 +1,69 @@
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const source = path.join(repoRoot, 'vendor', 'hachidori');
const output = path.join(repoRoot, 'build', 'hachidori');
const provenance = JSON.parse(fs.readFileSync(path.join(source, 'SOURCE.json'), 'utf8'));
// Upstream commits the engine binaries. Verify the pinned bytes before staging
// so ordinary app builds need neither Emscripten nor network access.
for (const [file, expected] of Object.entries(provenance.artifacts)) {
const actual = createHash('sha256')
.update(fs.readFileSync(path.join(source, file)))
.digest('hex');
if (actual !== expected) throw new Error(`Hachidori artifact checksum mismatch: ${file}`);
}
const extension = path.join(source, 'extension');
const manifest = JSON.parse(fs.readFileSync(path.join(extension, 'manifest.json'), 'utf8'));
for (const file of [
manifest.options_page,
manifest.background.service_worker,
'offscreen.html',
...manifest.content_scripts.flatMap(({ js, css }) => [...js, ...css]),
]) {
if (!fs.existsSync(path.join(extension, file)))
throw new Error(`Missing Hachidori asset: ${file}`);
}
fs.rmSync(output, { recursive: true, force: true });
fs.mkdirSync(output, { recursive: true });
fs.cpSync(extension, output, { recursive: true });
// Host configuration belongs in the staged copy, leaving the fork usable in Chrome.
const hostConfiguration = {
'overlay-mode.js': [
['export const OVERLAY_MODE = false;', 'export const OVERLAY_MODE = true;'],
['customJavaScript: true,', 'customJavaScript: false,'],
],
// Overlay hosts seed the lookup highlight off because their Anki screenshot is
// the see-through viewport. SubMiner captures media from mpv, and without the
// highlight the sidebar shows nothing for the word being looked up.
'setup-state.js': [
[
'lookupMode: "hover",\n sourceHighlightEnabled: false,',
'lookupMode: "hover",\n sourceHighlightEnabled: true,',
],
],
};
for (const [file, replacements] of Object.entries(hostConfiguration)) {
const filePath = path.join(output, file);
let text = fs.readFileSync(filePath, 'utf8');
for (const [original, replacement] of replacements) {
if (!text.includes(original))
throw new Error(`Hachidori host configuration changed upstream: ${original}`);
text = text.replace(original, replacement);
}
fs.writeFileSync(filePath, text);
}
manifest.permissions = manifest.permissions.filter((permission) => permission !== 'userScripts');
// A fixed key pins the extension ID, so Hachidori's storage origin (dictionaries,
// settings, setup state) survives userData path changes. Electron otherwise
// derives the ID from the unpacked directory path.
manifest.key =
'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA40zTTbhCbrKnDOqj17tosDChP60VXuuMjR0tFFR/kAet21jrYn0JKPzqqNpXMGaJsx1chnuMOgaP0zuOT+gv9DNVV83wGLhQL7cC4LCoGN648WqnE2jYqBPj6hdD5A/N3uPeKFRAHkiC9HKoj2Et6sYZFTqag79QqQkkUz17X2VpjuTGmTP3lvhyEwhJWQKzOU0k6dTn6fKB2ZSqTebpw/JS2G8jf58vHlQOcfLhIiolKCG9DfMuo11aoG1s3AsFmQmw9VVyp4wgyQ80UI4lyBdqboanJxEiZ211+HKWPEgtG6VML1+Uo59qWS3uBU1apxE1+7E51UBEHaTsxajFIQIDAQAB';
fs.writeFileSync(path.join(output, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n');
for (const file of ['LICENSE', 'SOURCE.json', 'README.md']) {
fs.copyFileSync(path.join(source, file), path.join(output, file));
}
process.stdout.write(`Hachidori ${provenance.revision} staged in ${output}\n`);
+53
View File
@@ -0,0 +1,53 @@
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import test from 'node:test';
test('Hachidori staging configures Electron without changing the fork source', async () => {
const files = ['overlay-mode.js', 'setup-state.js', 'manifest.json'];
const source = (file: string) =>
new URL(`../vendor/hachidori/extension/${file}`, import.meta.url);
const before = files.map((file) => readFileSync(source(file), 'utf8'));
execFileSync(process.execPath, [
fileURLToPath(new URL('./build-hachidori.mjs', import.meta.url)),
]);
assert.deepEqual(
files.map((file) => readFileSync(source(file), 'utf8')),
before,
);
const staged = await import(new URL('../build/hachidori/overlay-mode.js', import.meta.url).href);
assert.equal(staged.OVERLAY_MODE, true);
assert.equal(staged.HOST_CAPABILITIES.customJavaScript, false);
const original = await import(source('overlay-mode.js').href);
assert.equal(original.OVERLAY_MODE, false);
assert.equal(original.HOST_CAPABILITIES.customJavaScript, true);
// SubMiner mines media from mpv, not the overlay viewport, so the lookup
// highlight stays on for a first install.
const stagedSetup = await import(
new URL('../build/hachidori/setup-state.js', import.meta.url).href
);
assert.equal(stagedSetup.OVERLAY_MODE_OPTIONS.sourceHighlightEnabled, true);
const originalSetup = await import(source('setup-state.js').href);
assert.equal(originalSetup.OVERLAY_MODE_OPTIONS.sourceHighlightEnabled, false);
const manifest = JSON.parse(
readFileSync(new URL('../build/hachidori/manifest.json', import.meta.url), 'utf8'),
);
const originalManifest = JSON.parse(readFileSync(source('manifest.json'), 'utf8'));
assert.deepEqual(manifest, {
...originalManifest,
permissions: originalManifest.permissions.filter(
(permission: string) => permission !== 'userScripts',
),
key: manifest.key,
});
// The ID keys Hachidori's stored dictionaries and settings; changing the key orphans them.
const digest = createHash('sha256').update(Buffer.from(manifest.key, 'base64')).digest('hex');
const extensionId = [...digest.slice(0, 32)]
.map((digit) => String.fromCharCode(97 + parseInt(digit, 16)))
.join('');
assert.equal(extensionId, 'jpfgmfknblendgepdejlfhocdcnjjelj');
});
+139
View File
@@ -0,0 +1,139 @@
// Exercises the real entry point with disposable Linux config and data directories.
const { app, BrowserWindow, session, shell } = require('electron');
const fs = require('node:fs');
const path = require('node:path');
const assert = require('node:assert/strict');
if (process.platform !== 'linux')
throw new Error('This app-entry smoke requires Linux XDG isolation.');
const root = process.cwd();
const backend = process.argv.includes('--backend=yomitan') ? 'yomitan' : 'hachidori';
const externalYomitanProfile =
backend === 'hachidori' && !process.argv.includes('--bundled-yomitan');
const profile = process.env.SUBMINER_DICTIONARY_SMOKE_DATA;
assert(
profile && fs.existsSync(profile),
'Use bun run test:dictionary:electron for profile isolation',
);
process.env.XDG_CONFIG_HOME = profile;
process.env.XDG_DATA_HOME = path.join(profile, 'data');
fs.mkdirSync(path.join(profile, 'SubMiner'));
fs.writeFileSync(
path.join(profile, 'SubMiner', 'config.json'),
JSON.stringify({
dictionaryBackend: backend,
// External Yomitan profiles must not block Hachidori settings.
yomitan: {
externalProfilePath: externalYomitanProfile ? path.join(profile, 'external-yomitan') : '',
},
mpv: { socketPath: path.join(profile, 'missing-mpv.sock') },
ankiConnect: { enabled: false },
startupWarmups: { lowPowerMode: true },
discordPresence: { enabled: false },
updates: { enabled: false },
}),
);
const openedLinks = [];
shell.openExternal = async (url) => {
openedLinks.push(url);
};
app.setAppPath(root);
app.getVersion = () => require(path.join(root, 'package.json')).version;
process.env.SUBMINER_APP_LOG = path.join(profile, 'app.log');
app.commandLine.appendSwitch('ozone-platform', 'x11');
app.commandLine.appendSwitch('disable-gpu');
app.commandLine.appendSwitch('disable-dev-shm-usage');
process.argv = [process.execPath, root, '--hachidori', '--log-level', 'debug'];
require(path.join(root, 'dist/main-entry.js'));
const deadline = setTimeout(() => {
console.error(
'FAIL timeout',
BrowserWindow.getAllWindows().map((w) => w.webContents.getURL()),
);
finish(1);
}, 60000);
function finish(exitCode) {
clearTimeout(deadline);
app.exit(exitCode);
}
(async () => {
await app.whenReady();
let window;
for (let i = 0; i < 300; i++) {
window = BrowserWindow.getAllWindows().find(
(w) => w.getTitle().includes('Hachidori') && w.isVisible(),
);
if (window) break;
await new Promise((r) => setTimeout(r, 100));
}
assert.ok(window, 'Hachidori settings window opens from actual app flag');
assert.equal(window.webContents.session, session.fromPartition('persist:hachidori'));
assert.match(window.webContents.getURL(), /settings.html/);
const status = await window.webContents.executeJavaScript(
`chrome.runtime.sendMessage({target:'hoshidicts-offscreen',type:'hd_status',requestId:'app-settings-smoke'})`,
);
assert.equal(status.ok, true);
assert.equal(status.ready, true);
console.log(
'PASS actual --hachidori startup, visible settings, isolated backend session, native engine ready',
);
app.emit('second-instance', {}, [process.execPath, root, '--yomitan'], root);
if (externalYomitanProfile) {
const blockedMessage =
'Yomitan settings unavailable while using read-only external-profile mode.';
for (let i = 0; i < 100; i++) {
if (fs.readFileSync(process.env.SUBMINER_APP_LOG, 'utf8').includes(blockedMessage)) break;
await new Promise((r) => setTimeout(r, 100));
}
assert.ok(
fs.readFileSync(process.env.SUBMINER_APP_LOG, 'utf8').includes(blockedMessage),
'--yomitan is rejected when an external Yomitan profile is configured',
);
assert.equal(session.defaultSession.extensions.getAllExtensions().length, 0);
assert.ok(!BrowserWindow.getAllWindows().some((w) => w.getTitle().includes('Yomitan')));
console.log('PASS external Yomitan settings blocked while Hachidori settings remain available');
} else {
let yomi;
for (let i = 0; i < 200; i++) {
yomi = BrowserWindow.getAllWindows().find(
(w) => w.getTitle().includes('Yomitan') && w.isVisible(),
);
if (yomi) break;
await new Promise((r) => setTimeout(r, 100));
}
assert.ok(yomi, 'inactive --yomitan settings opens');
assert.equal(yomi.webContents.session, session.defaultSession);
}
assert.equal(window.webContents.session, session.fromPartition('persist:hachidori'));
app.emit('second-instance', {}, [process.execPath, root, '--toggle-visible-overlay'], root);
let overlay;
for (let i = 0; i < 200; i++) {
overlay = BrowserWindow.getAllWindows().find((w) =>
w.webContents.getURL().includes('/renderer/index.html?'),
);
if (overlay && !overlay.webContents.isLoading()) break;
await new Promise((r) => setTimeout(r, 100));
}
assert.ok(overlay, 'actual overlay initialized');
assert.equal(
overlay.webContents.session,
backend === 'hachidori' ? session.fromPartition('persist:hachidori') : session.defaultSession,
);
const requestLink = (url) =>
overlay.webContents.executeJavaScript(`new Promise((resolve,reject)=>{
const timer=setTimeout(()=>reject(Error('No external link acknowledgment')),3000);
window.addEventListener('hachidori-open-external-result',e=>{clearTimeout(timer);resolve(e.detail);},{once:true});
window.dispatchEvent(new CustomEvent('hachidori-open-external',{detail:{requestId:'smoke-link',url:${JSON.stringify(url)}}}));
})`);
assert.equal((await requestLink('file:///tmp/private')).ok, false);
assert.equal((await requestLink('https://example.com/word')).ok, backend === 'hachidori');
assert.deepEqual(openedLinks, backend === 'hachidori' ? ['https://example.com/word'] : []);
console.log(
`PASS ${backend} overlay session, independent settings windows, real preload external link bridge`,
);
finish(0);
})().catch((error) => {
console.error(error);
finish(1);
});
+239
View File
@@ -0,0 +1,239 @@
// Run after bun run build. This uses a temporary profile and small local ZIPs.
const { app, BrowserWindow, protocol, session } = require('electron');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const http = require('node:http');
const root = path.resolve(__dirname, '..');
const parser = require(path.join(root, 'dist/core/services/tokenizer/yomitan-parser-runtime.js'));
const { writeStoredZip } = require(path.join(root, 'dist/shared/stored-zip.js'));
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-hachidori-parser-'));
protocol.registerSchemesAsPrivileged([
{
scheme: 'chrome-extension',
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
bypassCSP: true,
},
},
]);
app.setPath('userData', profile);
app.setAppPath(root);
app.disableHardwareAcceleration();
app.on('window-all-closed', () => {});
const deadline = setTimeout(() => {
console.error('Hachidori parser verification timed out', profile);
app.exit(1);
}, 120_000);
function fixture(name, title, bankName, entries, frequencyMode = 'rank-based') {
const zipPath = path.join(profile, name + '.zip');
writeStoredZip(zipPath, [
{
name: 'index.json',
data: Buffer.from(JSON.stringify({ title, revision: '1', format: 3, frequencyMode })),
},
{ name: bankName, data: Buffer.from(JSON.stringify(entries)) },
]);
return zipPath;
}
app
.whenReady()
.then(async () => {
const targetSession = session.fromPartition('persist:hachidori-check');
const extension = await targetSession.extensions.loadExtension(
path.join(root, 'build/hachidori'),
{ allowFileAccess: true },
);
// Keep a host window alive while the dictionary importer opens/closes its
// temporary settings windows, matching the running app's window lifecycle.
const host = new BrowserWindow({
show: false,
webPreferences: { session: targetSession, contextIsolation: true, nodeIntegration: false },
});
await host.loadURL(`chrome-extension://${extension.id}/settings.html`);
let parserWindow = null;
let readyPromise = null;
let initPromise = null;
const deps = {
getYomitanExt: () => extension,
getYomitanSession: () => targetSession,
getYomitanParserWindow: () => parserWindow,
setYomitanParserWindow: (value) => {
parserWindow = value;
},
getYomitanParserReadyPromise: () => readyPromise,
setYomitanParserReadyPromise: (value) => {
readyPromise = value;
},
getYomitanParserInitPromise: () => initPromise,
setYomitanParserInitPromise: (value) => {
initPromise = value;
},
};
const errors = [];
const logger = {
error: (...args) => {
errors.push(args);
console.error(...args);
},
};
assert.deepEqual(await parser.getYomitanDictionaryInfo(deps, logger), []);
assert.equal(
await parser.syncYomitanDefaultAnkiServer('http://127.0.0.1:18766', deps, logger, {
forceOverride: true,
deck: 'Test Mining',
}),
true,
);
// Exercise discovery and revisioned options writes in the real extension,
// without creating a note or changing the user's Anki collection.
const fields = ['Term', 'Reading', 'Definition', 'Context', 'Pronunciation', 'Image'];
const metadataServer = http.createServer((request, response) => {
let body = '';
request.on('data', (chunk) => {
body += chunk;
});
request.on('end', () => {
const message = JSON.parse(body);
assert.equal(message.action, 'multi');
const result = message.params.actions.map(({ action }) => ({
result:
action === 'deckNames'
? ['Test Mining']
: action === 'modelNames'
? ['Custom Japanese']
: fields,
error: null,
}));
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify({ result, error: null }));
});
});
await new Promise((resolve) => metadataServer.listen(0, '127.0.0.1', resolve));
try {
const url = `http://127.0.0.1:${metadataServer.address().port}`;
const ankiConfig = {
tags: ['SubMiner', 'Autofill'],
fields: {
word: 'Term',
sentence: 'Context',
wordAudio: 'Pronunciation',
image: 'Image',
},
};
assert.equal(
await parser.syncYomitanDefaultAnkiServer(url, deps, logger, {
forceOverride: true,
deck: 'Test Mining',
ankiConfig,
}),
true,
);
const anki = await parserWindow.webContents.executeJavaScript(
`(async () => (await chrome.storage.local.get('options')).options.anki)()`,
);
assert.equal(anki.model, 'Custom Japanese');
assert.equal(anki.deck, 'Test Mining');
assert.deepEqual(anki.tags, ankiConfig.tags);
assert.equal(anki.fieldTemplates.Term.value, '{expression}');
assert.equal(anki.fieldTemplates.Pronunciation.value, '{audio}');
assert.equal(anki.fieldTemplates.Context.value, '{sentence}');
assert.deepEqual(anki.templates[0].fieldTemplates, anki.fieldTemplates);
console.log('Hachidori Anki auto-population passed with an empty dictionary library');
} finally {
await new Promise((resolve) => metadataServer.close(resolve));
}
const archives = [
fixture('terms', 'SubMiner Test Terms', 'term_bank_1.json', [
['食べる', 'たべる', '', 'v1', 0, ['to eat'], 1, ''],
]),
fixture('names', 'SubMiner Character Dictionary (AniList 1)', 'term_bank_1.json', [
['ミナト', 'みなと', '', 'n', 0, ['name'], 1, ''],
]),
fixture('frequency', 'SubMiner Test Frequency', 'term_meta_bank_1.json', [
['食べる', 'freq', { reading: 'たべる', frequency: 42 }],
['頻度だけ', 'freq', { reading: 'ひんどだけ', frequency: 120 }],
['頻度だけ', 'freq', { reading: 'べつのよみ', frequency: 250 }],
['頻度だけ', 'freq', 17],
]),
fixture(
'occurrences',
'SubMiner Test Occurrences',
'term_meta_bank_1.json',
[['頻度だけ', 'freq', 9000]],
'occurrence-based',
),
];
for (const archive of archives)
assert.equal(await parser.importYomitanDictionaryFromZip(archive, deps, logger), true);
const dictionaries = await parser.getYomitanDictionaryInfo(deps, logger);
assert.equal(dictionaries.length, 4);
parser.clearYomitanParserCachesForWindow(parserWindow);
const tokens = await parser.requestYomitanScanTokens('ミナト 食べた', deps, logger, {
includeNameMatchMetadata: true,
currentCharacterDictionaryMediaId: 1,
});
assert.equal(tokens[0].isNameMatch, true);
assert.equal(tokens[1].headword, '食べる');
assert.equal(tokens[1].reading, 'たべた');
assert.equal(tokens[1].startPos, 4);
assert.equal(tokens[1].endPos, 7);
assert.equal(tokens[1].frequencyRank, 42);
assert.deepEqual(tokens[1].wordClasses, ['v1']);
const exact = await parser.requestYomitanTermFrequencies(
[{ term: '食べる', reading: 'たべる' }],
deps,
logger,
);
assert.equal(exact.length, 1);
assert.equal(exact[0].frequency, 42);
assert.equal(exact[0].reading, 'たべる');
assert.equal(exact[0].hasReading, false);
const otherReading = await parser.requestYomitanTermFrequencies(
[{ term: '食べる', reading: 'べつのよみ' }],
deps,
logger,
);
// The shared frequency pipeline retries a missing reading as a term-only query.
assert.equal(otherReading[0]?.frequency, 42);
const unmatched = await parser.requestYomitanTermFrequencies(
[{ term: '頻度だけ', reading: null }],
deps,
logger,
);
assert.deepEqual(unmatched, []);
assert.equal(await parser.getYomitanCurrentAnkiDeckName(deps, logger), 'Test Mining');
assert.equal((await targetSession.extensions.getAllExtensions()).length, 1);
assert.equal(
await parser.syncYomitanDefaultAnkiServer('http://127.0.0.1:8765', deps, logger),
true,
);
const directSettings = await parser.getYomitanSettingsFull(deps, logger);
assert.equal(directSettings.profiles[0].options.anki.server, 'http://127.0.0.1:8765');
const proxyState = await host.webContents.executeJavaScript(
"chrome.storage.local.get('subminerAnkiProxyUrl')",
);
assert.equal(proxyState.subminerAnkiProxyUrl, null);
for (const entry of await parser.getYomitanDictionaryInfo(deps, logger)) {
assert.equal(await parser.deleteYomitanDictionaryByTitle(entry.title, deps, logger), true);
}
assert.deepEqual(await parser.getYomitanDictionaryInfo(deps, logger), []);
assert.equal(errors.length, 0);
console.log(
'PASS Hachidori native import, scanner, character names, term-entry API frequencies, settings and removal',
);
clearTimeout(deadline);
app.exit(0);
})
.catch((error) => {
console.error(error);
clearTimeout(deadline);
app.exit(1);
});
-26
View File
@@ -1,26 +0,0 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
const source = readFileSync('scripts/compare-yomitan-api.ts', 'utf8');
test('creates the configured Yomitan user-data directory before Electron uses it', () => {
const setPathIndex = source.indexOf(
"electronModule.app.setPath('userData', options.yomitanUserDataPath)",
);
assert.notEqual(setPathIndex, -1);
const mkdirIndex = source.lastIndexOf(
'fs.mkdirSync(options.yomitanUserDataPath, { recursive: true })',
setPathIndex,
);
assert.ok(mkdirIndex > -1, 'must create the user-data directory');
assert.ok(mkdirIndex < setPathIndex, 'must create the directory before app.setPath');
});
test('lets output drain by using exitCode in the top-level completion handlers', () => {
const completionHandlers = source.slice(source.lastIndexOf('\nmain()'));
assert.match(completionHandlers, /process\.exitCode = process\.exitCode \?\? 0/);
assert.match(completionHandlers, /process\.exitCode = 1/);
assert.doesNotMatch(completionHandlers, /process\.exit\(/);
});
+1
View File
@@ -21,6 +21,7 @@ const requiredDocs = [
'docs/workflow/README.md', 'docs/workflow/README.md',
'docs/workflow/agent-skills.md', 'docs/workflow/agent-skills.md',
'docs/workflow/planning.md', 'docs/workflow/planning.md',
'docs/workflow/testing.md',
'docs/workflow/verification.md', 'docs/workflow/verification.md',
] as const; ] as const;
-94
View File
@@ -1,94 +0,0 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
const source = readFileSync('scripts/get-mpv-window-macos.swift', 'utf8');
test('minimized Accessibility windows are validated by PID and socket before reporting minimized', () => {
const minimizedAssignmentIndex = source.indexOf('foundMinimizedTargetWindow = true');
assert.notEqual(minimizedAssignmentIndex, -1);
const loopStartIndex = source.lastIndexOf('for window in windows', minimizedAssignmentIndex);
assert.notEqual(loopStartIndex, -1);
const pidExtractionIndex = source.indexOf(
'AXUIElementGetPid(window, &windowPid)',
loopStartIndex,
);
const appPidMatchIndex = source.indexOf('windowPid != app.processIdentifier', loopStartIndex);
const socketCheckIndex = source.indexOf('if !windowHasTargetSocket(windowPid)', loopStartIndex);
assert.ok(
pidExtractionIndex > loopStartIndex && pidExtractionIndex < minimizedAssignmentIndex,
'window PID must be extracted before accepting a minimized window',
);
assert.ok(
appPidMatchIndex > pidExtractionIndex && appPidMatchIndex < minimizedAssignmentIndex,
'window PID must match the owning app before accepting a minimized window',
);
assert.ok(
socketCheckIndex > appPidMatchIndex && socketCheckIndex < minimizedAssignmentIndex,
'target socket must be validated before accepting a minimized window',
);
});
test('focused mpv window follows the frontmost mpv app signal', () => {
const focusHelperIndex = source.indexOf('private func isFocusedMpvWindow');
assert.notEqual(focusHelperIndex, -1);
const nextFunctionIndex = source.indexOf('\nprivate func ', focusHelperIndex + 1);
const focusHelperBody = source.slice(focusHelperIndex, nextFunctionIndex);
assert.ok(
focusHelperBody.includes('frontmost.pid == ownerPid'),
'matching frontmost PID should mark the mpv window focused',
);
assert.ok(
focusHelperBody.includes('frontmost.isMpv && windowHasTargetSocket(ownerPid)'),
'frontmost mpv app should mark the target mpv window focused even when PIDs differ',
);
assert.ok(
source.includes('focused: isFocusedMpvWindow(ownerPid: windowPid, frontmost: frontmost)'),
'Accessibility path should use the shared focused mpv helper',
);
assert.ok(
source.includes('focused: isFocusedMpvWindow(ownerPid: ownerPid, frontmost: frontmost)'),
'CoreGraphics path should use the shared focused mpv helper',
);
});
test('frontmost mpv app emits active state when geometry lookup misses', () => {
assert.ok(
/case\s+\.active:/.test(source),
'helper should expose an active state without window geometry',
);
assert.ok(
source.includes('if windowHasTargetSocket(frontmost.pid)'),
'active state should still accept a matching target socket when available',
);
assert.ok(
source.includes('return targetMpvSocketPath != nil'),
'active state should preserve frontmost mpv even if command-line socket detection fails',
);
assert.ok(
source.includes('return .active'),
'lookup should preserve active mpv state after geometry lookup misses',
);
assert.ok(source.includes('print("active")'), 'active state should be printed for the tracker');
});
test('frontmost non-mpv app emits inactive state when geometry lookup misses', () => {
assert.ok(
/case\s+\.inactive:/.test(source),
'helper should expose an inactive state without window geometry',
);
assert.ok(
source.includes('if frontmost != nil'),
'helper should distinguish a known non-mpv frontmost app from an unknown miss',
);
assert.ok(source.includes('return .inactive'), 'known non-mpv focus should return inactive');
assert.ok(
source.includes('print("inactive")'),
'inactive state should be printed for the tracker',
);
});
-45
View File
@@ -1,45 +0,0 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import { spawnSync } from 'node:child_process';
function createWorkspace(name: string): string {
const baseDir = path.join(process.cwd(), '.tmp', 'get-frequency-typecheck-test');
fs.mkdirSync(baseDir, { recursive: true });
return fs.mkdtempSync(path.join(baseDir, `${name}-`));
}
test('scripts/get_frequency.ts typechecks in isolation', () => {
const workspace = createWorkspace('isolated-script');
const tsconfigPath = path.join(workspace, 'tsconfig.json');
fs.writeFileSync(
tsconfigPath,
JSON.stringify(
{
extends: '../../../tsconfig.typecheck.json',
include: ['../../../scripts/get_frequency.ts'],
exclude: [],
},
null,
2,
),
'utf8',
);
try {
const result = spawnSync('bunx', ['tsc', '--noEmit', '-p', tsconfigPath], {
cwd: process.cwd(),
encoding: 'utf8',
});
assert.equal(
result.status,
0,
`expected scripts/get_frequency.ts to typecheck\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`,
);
} finally {
fs.rmSync(workspace, { recursive: true, force: true });
}
});
+137
View File
@@ -0,0 +1,137 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import '../vendor/hachidori/extension/reader-options.js';
import { createAnkiGateway } from '../vendor/hachidori/extension/anki.js';
import { createAnkiWorkerService } from '../vendor/hachidori/extension/anki-worker.js';
async function mine({ proxy = true, audioFails = false } = {}) {
const events: string[] = [];
const filename = `hachidori_${'a'.repeat(64)}.mp3`;
let fields: Record<string, string> = {};
let initialAudio = '';
let stored = false;
const gateway = createAnkiGateway({
readSubminerProxyUrl: async () => (proxy ? 'http://127.0.0.1:8766' : null),
fetch: async (_url: string, options: RequestInit) => {
const { action, params } = JSON.parse(String(options.body));
events.push(action);
let result: unknown;
switch (action) {
case 'multi':
result = [
{ result: ['Default'], error: null },
{ result: ['Basic'], error: null },
{ result: ['Expression', 'ExpressionAudio'], error: null },
];
break;
case 'canAddNotes':
result = [true];
break;
case 'canAddNotesWithErrorDetail':
result = [{ canAdd: true, error: null }];
break;
case 'getMediaFilesNames':
result = stored ? [filename] : [];
break;
case 'storeMediaFile':
stored = true;
result = filename;
break;
case 'addNote':
fields = { ...params.note.fields };
initialAudio = fields.ExpressionAudio ?? '';
if (initialAudio) assert.ok(stored, 'audio must exist before the note references it');
result = 123;
break;
case 'notesInfo':
result = [
{
noteId: 123,
fields: Object.fromEntries(
Object.entries(fields).map(([key, value]) => [key, { value }]),
),
},
];
break;
case 'updateNoteFields':
Object.assign(fields, params.note.fields);
result = null;
break;
default:
throw new Error(`Unexpected action: ${action}`);
}
return Response.json({ result, error: null });
},
});
const service = createAnkiWorkerService({
gateway,
readOptions: async () => ({
anki: {
url: 'http://127.0.0.1:8766',
apiKey: '',
templates: [
{
id: 'default',
name: 'Default',
deck: 'Default',
model: 'Basic',
tags: [],
fields: {},
duplicateScope: 'model',
duplicateBehavior: 'prevent',
captureScreenshot: false,
fieldTemplates: {
Expression: { value: '{expression}', overwriteMode: 'overwrite' },
ExpressionAudio: { value: '{audio}', overwriteMode: 'overwrite' },
},
},
],
},
audioSources: [
{ id: 'test', enabled: true, type: 'custom', url: 'https://example.test/{term}' },
],
experimental: {},
}),
readDictionaries: async () => [],
engine: async () => ({ ready: true, loading: false, generation: 1 }),
offscreen: async (message: { type: string; audio?: string }) => {
if (message.type === 'hd_anki_audio') {
events.push('pronunciation');
if (audioFails) throw new Error('No pronunciation available');
return { filename, data: 'YXVkaW8=' };
}
return { fields: { Expression: '猫', ExpressionAudio: message.audio ?? '' }, media: [] };
},
duplicateIndex: { source: async () => null, recordWrite: async () => {} },
});
const status = await service.status();
assert.equal(status.available, true, status.error);
const result = await service.submit({
configKey: status.configKey,
generation: 1,
term: { expression: '猫', reading: 'ねこ' },
});
return { result, initialAudio, fields, events, filename };
}
test('SubMiner receives pronunciation in the initial Hachidori note, before enrichment starts', async () => {
const value = await mine();
assert.equal(value.result.state, 'added');
assert.equal(value.initialAudio, `[sound:${value.filename}]`);
assert.equal(value.events.filter((event) => event === 'pronunciation').length, 1);
});
test('direct Hachidori keeps deferred pronunciation', async () => {
const value = await mine({ proxy: false });
assert.equal(value.initialAudio, '');
assert.equal(value.fields.ExpressionAudio, `[sound:${value.filename}]`);
});
test('unavailable pronunciation remains a warning without a late audio write', async () => {
const value = await mine({ audioFails: true });
assert.equal(value.result.state, 'added');
assert.match(value.result.warnings.join(' '), /No pronunciation available/);
assert.equal(value.initialAudio, '');
assert.equal(value.events.filter((event) => event === 'pronunciation').length, 1);
assert.equal(value.events.includes('updateNoteFields'), false);
});
+132
View File
@@ -0,0 +1,132 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { runInNewContext } from 'node:vm';
import test from 'node:test';
import { CHARACTER_DICTIONARY_TITLE_PREFIX } from '../src/core/services/tokenizer/character-dictionary-title';
import { createAnkiGateway } from '../vendor/hachidori/extension/anki.js';
const bridge = readFileSync(
new URL('../vendor/hachidori/extension/subminer-host.js', import.meta.url),
'utf8',
);
function run(code: string) {
runInNewContext(`${bridge}\n${code}`, {
window: new EventTarget(),
EventTarget,
CustomEvent,
assert,
characterPrefix: CHARACTER_DICTIONARY_TITLE_PREFIX,
KeyboardEvent: class {
constructor(_type: string, options: KeyboardEventInit = {}) {
Object.assign(this, options);
}
},
});
}
test('Hachidori marks popup state independently from successful lookups', () => {
run(`
const events = [];
for (const name of ['yomitan-popup-shown', 'yomitan-popup-hidden', 'subminer-yomitan-lookup']) {
window.addEventListener(name, () => events.push(name));
}
const attributes = new Map();
const host = { setAttribute: (name, value) => attributes.set(name, value) };
SubMinerHachidori.markHost(host, true);
assert.equal(attributes.get('data-subminer-yomitan-popup-visible'), 'true');
assert.equal(events.join(','), '');
SubMinerHachidori.lookup();
SubMinerHachidori.markHost(host, false);
assert.equal(attributes.get('data-subminer-yomitan-popup-visible'), 'false');
assert.equal(events.join(','), 'subminer-yomitan-lookup');
`);
});
test('Hachidori promotes character glossaries and results without overriding linguistic rank', () => {
run(`
const result = (id, matched, dictionary, options = {}) => ({
matched, deinflected: matched, trace: [], preprocessorSteps: 0,
term: { expression: matched, reading: 'reading', glossaries: [{ dictionary }] }, ...options, id,
});
const character = characterPrefix + ' - Current show';
const longer = result('longer', '花子さん', 'General');
const normal = result('normal', '花子', 'General');
const person = result('person', '花子', character);
const shorter = result('shorter', '花', character);
const output = SubMinerHachidori.prioritizeCharacterResults([longer, normal, person, shorter]);
assert.equal(output.map(entry => entry.id).join(','), 'longer,person,normal,shorter');
const merged = result('merged', '花子', 'General');
merged.term.glossaries.push({ dictionary: character }, { dictionary: 'Second general' });
const [promoted] = SubMinerHachidori.prioritizeCharacterResults([merged]);
assert.equal(promoted.term.glossaries.map(g => g.dictionary).join(','), character + ',General,Second general');
assert.equal(merged.term.glossaries[0].dictionary, 'General');
for (const change of [{ preprocessorSteps: 1 }, { trace: [{}] }, { deinflected: '別の語' }]) {
const transformed = { ...person, ...change };
assert.equal(SubMinerHachidori.prioritizeCharacterResults([normal, transformed])[0].id, 'normal');
}
const preferredReading = { ...normal, term: { ...normal.term, reading: 'preferred' } };
assert.equal(SubMinerHachidori.prioritizeCharacterResults([person, preferredReading], {primaryReading: 'preferred'})[0].id, 'normal');
const aliased = result('aliased', '花子', 'Imported character data');
assert.equal(SubMinerHachidori.prioritizeCharacterResults([normal, aliased], {}, [{title: 'Imported character data', displayName: character}])[0].id, 'aliased');
`);
});
test('Hachidori sends private mining metadata only to the configured SubMiner proxy', async () => {
const requests: Array<{ url: string; body: string }> = [];
const proxy = 'http://127.0.0.1:8766';
const gateway = createAnkiGateway({
readSubminerProxyUrl: async () => proxy,
fetch: async (url: string, options: RequestInit) => {
assert.equal(typeof options.body, 'string');
requests.push({ url, body: String(options.body) });
return Response.json({ result: 123, error: null });
},
});
const params = {
note: { fields: { Expression: '花子' } },
subminerDuplicateNoteIds: [456],
subminerEnrich: true,
};
await gateway.invoke('addNote', params, '', 1000, proxy);
await gateway.invoke('addNote', params, '', 1000, 'http://127.0.0.1:8765');
assert.deepEqual(
requests.map((request) => JSON.parse(request.body).params),
[params, { note: params.note }],
);
assert.equal(params.subminerEnrich, true);
const direct = createAnkiGateway({
readSubminerProxyUrl: async () => null,
fetch: async (_url: string, options: RequestInit) => {
assert.deepEqual(JSON.parse(String(options.body)).params, { note: params.note });
return Response.json({ result: null, error: null });
},
});
await direct.invoke('updateNoteFields', params, '', 1000, proxy);
});
test('Hachidori routes host commands, validates keyboard input and disconnects', () => {
run(`
const calls = [];
const disconnect = SubMinerHachidori.connect({
hide: () => calls.push('hide'), clear: () => calls.push('clear'),
action: name => calls.push(name), cycleAudio: direction => calls.push(direction),
scroll: (x, y) => calls.push(x + ':' + y),
keydown: event => calls.push(event.key + ':' + event.ctrlKey + ':' + event.shiftKey),
});
const send = detail => window.dispatchEvent(new CustomEvent('subminer-yomitan-popup-command', {detail}));
send(null);
send({ type: 'forwardKeyDown', key: 12, modifiers: [] });
send({ type: 'mineSelected' });
send({ type: 'playCurrentAudio' });
send({ type: 'scanSelectedText' });
send({ type: 'cycleAudioSource', direction: -1 });
send({ type: 'scrollBy', deltaX: Infinity, deltaY: 40 });
send({ type: 'forwardKeyDown', key: 'j', code: 'KeyJ', modifiers: ['ctrl', 'shift'] });
send({ type: 'setVisible', visible: false });
send({ type: 'clearActiveTextSource' });
disconnect();
send({ type: 'mineSelected' });
assert.equal(calls.join(','), 'addNote,playAudio,scanSelectedText,-1,0:40,j:true:true,hide,clear');
`);
});
+8
View File
@@ -26,6 +26,14 @@ const REQUIRED_APP_FILES = [
]), ]),
]; ];
const REQUIRED_RESOURCES = [ const REQUIRED_RESOURCES = [
'hachidori/manifest.json',
'hachidori/settings.html',
'hachidori/subminer-host.js',
'hachidori/vendor/hoshidicts.wasm',
'hachidori/vendor/hoshidicts-threaded.wasm',
'hachidori/vendor/hoshidicts-threaded-idbfs.wasm',
'hachidori/LICENSE',
'hachidori/SOURCE.json',
'yomitan/manifest.json', 'yomitan/manifest.json',
'yomitan/data/fonts/kanji-stroke-orders.ttf', 'yomitan/data/fonts/kanji-stroke-orders.ttf',
'yomitan/fonts/NotoSansJP-Regular.ttf', 'yomitan/fonts/NotoSansJP-Regular.ttf',
-18
View File
@@ -39,24 +39,6 @@ describe('Bun corresponding-source manifest', () => {
} }
}); });
test('pins the source to the revision reported by the distributed binary', async () => {
const manifest = parseSourceManifest(
JSON.parse(
await fs.readFile(path.join(projectRoot, 'build/bun-source-manifest.json'), 'utf8'),
),
);
expect(manifest.version).toBe('1.3.5');
expect(manifest.bunRevision).toBe('1e86cebd74a5723e818b5c0555276b646bcf0e4c');
expect(manifest.releaseTagCommit).toBe('fa5a5bbe556a4bda5bde77b4013aa6c3bb4ec9ab');
expect(manifest.sources.find((source) => source.name === 'WebKit')?.revision).toBe(
'6d0f3aac0b817cc01a846b3754b21271adedac12',
);
expect(manifest.sources.find((source) => source.name === 'tinycc')?.revision).toBe(
'29985a3b59898861442fa3b43f663fc1af2591d7',
);
});
test('parses commit and tag registrations from Bun CMake', () => { test('parses commit and tag registrations from Bun CMake', () => {
const registrations = parseRegisteredRepositories(` const registrations = parseRegisteredRepositories(`
register_repository( register_repository(
-16
View File
@@ -1,16 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
test('build:syncui bundles the sandboxed preload and keeps Electron external', () => {
const packageJson = JSON.parse(
fs.readFileSync(path.join(import.meta.dir, '..', 'package.json'), 'utf8'),
) as { scripts: Record<string, string> };
const command = packageJson.scripts['build:syncui'] ?? '';
assert.match(command, /src\/preload-syncui\.ts/);
assert.match(command, /--bundle/);
assert.match(command, /--external:electron/);
assert.match(command, /--outfile=dist\/preload-syncui\.js/);
});
-27
View File
@@ -1,27 +0,0 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
const source = readFileSync('scripts/prepare-build-assets.mjs', 'utf8');
test('macOS helper build creates dist scripts directory before swiftc output', () => {
const buildFunctionIndex = source.indexOf('function buildMacosHelper()');
assert.notEqual(buildFunctionIndex, -1);
const swiftcIndex = source.indexOf("'swiftc'", buildFunctionIndex);
assert.notEqual(swiftcIndex, -1);
const ensureDirIndex = source.lastIndexOf('ensureDir(scriptsOutputDir)', swiftcIndex);
assert.ok(
ensureDirIndex > buildFunctionIndex,
'buildMacosHelper must create dist/scripts before swiftc writes the helper binary',
);
});
// Regression guard for #213: an untargeted swiftc stamps the build machine's OS
// version as the helper's minimum, so released builds refuse to load on older macOS.
test('macOS helper is compiled with an explicit deployment target', () => {
assert.match(source, /-target/);
assert.match(source, /apple-macos\$\{MACOS_HELPER_DEPLOYMENT_TARGET\}/);
});
+3 -3
View File
@@ -75,7 +75,7 @@ test('resolveCoverageDir keeps coverage output inside the repository', () => {
assert.throws(() => resolveCoverageDir(repoRoot, ['--coverage-dir', '/tmp/escape'])); assert.throws(() => resolveCoverageDir(repoRoot, ['--coverage-dir', '/tmp/escape']));
}); });
test('runCoverageLane returns a failure when a discovered test fails', () => { test('runCoverageLane returns a failure when a discovered test fails', async () => {
const repoRoot = mkdtempSync(join(tmpdir(), 'subminer-coverage-failure-')); const repoRoot = mkdtempSync(join(tmpdir(), 'subminer-coverage-failure-'));
try { try {
mkdirSync(join(repoRoot, 'src')); mkdirSync(join(repoRoot, 'src'));
@@ -93,10 +93,10 @@ test('runCoverageLane returns a failure when a discovered test fails', () => {
); );
assert.notEqual( assert.notEqual(
runCoverageLane({ await runCoverageLane({
repoRootDir: repoRoot, repoRootDir: repoRoot,
argv: ['bun-src-full', '--coverage-dir', 'coverage/test-src'], argv: ['bun-src-full', '--coverage-dir', 'coverage/test-src'],
stdio: 'pipe', quiet: true,
}), }),
0, 0,
); );
+69 -33
View File
@@ -1,5 +1,6 @@
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { spawnSync } from 'node:child_process'; import { spawn } from 'node:child_process';
import { availableParallelism } from 'node:os';
import { isAbsolute, join, relative, resolve } from 'node:path'; import { isAbsolute, join, relative, resolve } from 'node:path';
import { collectLaneFiles } from './test-lanes'; import { collectLaneFiles } from './test-lanes';
@@ -201,9 +202,40 @@ export function mergeLcovReports(reports: string[]): string {
return chunks.length > 0 ? `${chunks.join('\n')}\n` : ''; return chunks.length > 0 ? `${chunks.join('\n')}\n` : '';
} }
export function runCoverageLane( type ShardResult = { status: number; output: string; lcov: string | null };
options: { repoRootDir?: string; argv?: string[]; stdio?: 'inherit' | 'pipe' } = {},
): number { // Runs one test file under coverage into its own shard directory, buffering
// output so parallel shards do not interleave on the terminal.
function runShard(repoRootDir: string, file: string, shardDir: string): Promise<ShardResult> {
return new Promise((resolveShard) => {
const child = spawn(
'bun',
['test', '--coverage', '--coverage-reporter=lcov', '--coverage-dir', shardDir, `./${file}`],
{ cwd: repoRootDir },
);
let output = '';
child.stdout.on('data', (chunk) => (output += chunk));
child.stderr.on('data', (chunk) => (output += chunk));
child.on('error', (error) => resolveShard({ status: 1, output: String(error), lcov: null }));
child.on('close', (code) => {
const lcovPath = join(shardDir, 'lcov.info');
const lcov = existsSync(lcovPath) ? readFileSync(lcovPath, 'utf8') : null;
resolveShard({ status: code ?? 1, output, lcov });
});
});
}
function parseJobsArg(argv: string[]): number {
const index = argv.indexOf('--jobs');
if (index === -1) return availableParallelism();
return Math.max(1, Number(argv[index + 1]) || 1);
}
// Shards run in parallel (one per CPU unless --jobs N). The first failing shard
// stops scheduling new shards and its exit status becomes the lane result.
export async function runCoverageLane(
options: { repoRootDir?: string; argv?: string[]; quiet?: boolean } = {},
): Promise<number> {
const repoRootDir = options.repoRootDir ?? repoRoot; const repoRootDir = options.repoRootDir ?? repoRoot;
const argv = options.argv ?? process.argv.slice(2); const argv = options.argv ?? process.argv.slice(2);
const laneName = argv[0]; const laneName = argv[0];
@@ -225,40 +257,44 @@ export function runCoverageLane(
process.stderr.write(`${error instanceof Error ? error.message : error}\n`); process.stderr.write(`${error instanceof Error ? error.message : error}\n`);
return 1; return 1;
} }
const reports: string[] = [];
const reports: Array<string | null> = new Array(files.length).fill(null);
const failures: Array<{ file: string; result: ShardResult }> = [];
let nextIndex = 0;
const worker = async (): Promise<void> => {
while (failures.length === 0 && nextIndex < files.length) {
const index = nextIndex++;
const file = files[index]!;
const shardDir = join(shardRoot, String(index + 1).padStart(3, '0'));
const result = await runShard(repoRootDir, file, shardDir);
if (result.status !== 0) {
failures.push({ file, result });
return;
}
if (result.lcov === null && !options.quiet) {
process.stdout.write(`Skipping empty coverage shard for ${file}\n`);
}
reports[index] = result.lcov;
}
};
try { try {
for (const [index, file] of files.entries()) { const jobs = Math.min(parseJobsArg(argv), files.length);
const shardDir = join(shardRoot, `${String(index + 1).padStart(3, '0')}`); await Promise.all(Array.from({ length: jobs }, worker));
const result = spawnSync(
'bun',
['test', '--coverage', '--coverage-reporter=lcov', '--coverage-dir', shardDir, `./${file}`],
{
cwd: repoRootDir,
stdio: options.stdio ?? 'inherit',
},
);
if (result.error) { const [failure] = failures;
throw result.error; if (failure !== undefined) {
const { file, result } = failure;
if (!options.quiet) {
process.stderr.write(`${result.output}\nCoverage shard failed: ${file}\n`);
} }
if ((result.status ?? 1) !== 0) { return result.status;
return result.status ?? 1;
}
const lcovPath = join(shardDir, 'lcov.info');
if (!existsSync(lcovPath)) {
process.stdout.write(`Skipping empty coverage shard for ${file}\n`);
continue;
}
reports.push(readFileSync(lcovPath, 'utf8'));
} }
writeFileSync(join(coverageDir, 'lcov.info'), mergeLcovReports(reports), 'utf8'); const lcovPath = join(coverageDir, 'lcov.info');
process.stdout.write( writeFileSync(lcovPath, mergeLcovReports(reports.filter((r) => r !== null)), 'utf8');
`Merged LCOV written to ${relative(repoRootDir, join(coverageDir, 'lcov.info'))}\n`, process.stdout.write(`Merged LCOV written to ${relative(repoRootDir, lcovPath)}\n`);
);
return 0; return 0;
} finally { } finally {
rmSync(shardRoot, { recursive: true, force: true }); rmSync(shardRoot, { recursive: true, force: true });
@@ -267,5 +303,5 @@ export function runCoverageLane(
// @ts-ignore Bun entrypoint detection; TS config for scripts still targets CommonJS. // @ts-ignore Bun entrypoint detection; TS config for scripts still targets CommonJS.
if (import.meta.main) { if (import.meta.main) {
process.exit(runCoverageLane()); runCoverageLane().then((status) => process.exit(status));
} }
+26
View File
@@ -0,0 +1,26 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-hachi-settings-'));
const env = { ...process.env, SUBMINER_DICTIONARY_SMOKE_DATA: profile };
delete env.ELECTRON_RUN_AS_NODE;
try {
const result = spawnSync(
require('electron'),
[
'--no-sandbox',
fileURLToPath(new URL('./check-dictionary-backends.cjs', import.meta.url)),
...process.argv.slice(2),
],
{ env, stdio: 'inherit', timeout: 75_000 },
);
if (result.error) throw result.error;
process.exitCode = result.status ?? 1;
} finally {
fs.rmSync(profile, { recursive: true, force: true, maxRetries: 3 });
}
+9 -1
View File
@@ -1,5 +1,6 @@
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { resolve } from 'node:path'; import { resolve } from 'node:path';
import { availableParallelism } from 'node:os';
import { spawn, spawnSync } from 'node:child_process'; import { spawn, spawnSync } from 'node:child_process';
import { collectLaneFiles } from './test-lanes.ts'; import { collectLaneFiles } from './test-lanes.ts';
@@ -7,6 +8,8 @@ import { collectLaneFiles } from './test-lanes.ts';
// test file so a hanging test or leaked global in one file cannot poison the // test file so a hanging test or leaked global in one file cannot poison the
// rest of the lane. Use --single-process for the old all-in-one-process mode. // rest of the lane. Use --single-process for the old all-in-one-process mode.
// //
// Files run in parallel, one worker per CPU by default; --jobs 1 runs serially.
//
// Usage: bun scripts/run-test-lane.mjs <lane> [--jobs N] [--timeout-secs N] [--single-process] // Usage: bun scripts/run-test-lane.mjs <lane> [--jobs N] [--timeout-secs N] [--single-process]
const repoRoot = resolve(fileURLToPath(new URL('..', import.meta.url))); const repoRoot = resolve(fileURLToPath(new URL('..', import.meta.url)));
@@ -34,7 +37,12 @@ for (const signal of ['SIGINT', 'SIGTERM']) {
} }
function parseArgs(argv) { function parseArgs(argv) {
const options = { lane: undefined, jobs: 1, timeoutSecs: 300, singleProcess: false }; const options = {
lane: undefined,
jobs: availableParallelism(),
timeoutSecs: 300,
singleProcess: false,
};
for (let index = 0; index < argv.length; index += 1) { for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index]; const arg = argv[index];
if (arg === '--jobs') { if (arg === '--jobs') {
+45 -49
View File
@@ -22,39 +22,6 @@ const timeout = setTimeout(() => {
app.exit(1); app.exit(1);
}, 60_000); }, 60_000);
const STATIC_TYPES = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.json': 'application/json',
};
// The stats dashboard is served by the stats HTTP server in the app, so load it
// over loopback HTTP from the packaged stats/dist and treat missing static
// assets as failures. API routes are not part of this smoke and may 404.
function serveStatsDist(root, failedRequests) {
const server = http.createServer((req, res) => {
const pathname = new URL(req.url, 'http://127.0.0.1').pathname;
const relative = pathname === '/' ? 'index.html' : pathname.slice(1);
try {
const body = fs.readFileSync(path.join(root, relative));
res.writeHead(200, {
'Content-Type': STATIC_TYPES[path.extname(relative)] ?? 'application/octet-stream',
});
res.end(body);
} catch {
if (!pathname.startsWith('/api/')) failedRequests.push(`${req.url}: missing static asset`);
res.writeHead(404).end();
}
});
server.listen(0, '127.0.0.1');
return server;
}
async function smoke() { async function smoke() {
await app.whenReady(); await app.whenReady();
const packagedRequire = createRequire(path.join(archive, 'package.json')); const packagedRequire = createRequire(path.join(archive, 'package.json'));
@@ -83,6 +50,10 @@ async function smoke() {
{ allowFileAccess: true }, { allowFileAccess: true },
); );
assert(extension.id, 'Yomitan extension failed to load'); assert(extension.id, 'Yomitan extension failed to load');
const hachidori = await session
.fromPartition('persist:hachidori')
.extensions.loadExtension(path.join(resources, 'hachidori'), { allowFileAccess: true });
assert(hachidori.id, 'Hachidori extension failed to load');
const failedRequests = []; const failedRequests = [];
session.defaultSession.webRequest.onErrorOccurred( session.defaultSession.webRequest.onErrorOccurred(
{ urls: ['file://*/*', 'http://127.0.0.1/*'] }, { urls: ['file://*/*', 'http://127.0.0.1/*'] },
@@ -93,9 +64,7 @@ async function smoke() {
failedRequests.push(`${details.url}: ${details.error}`); failedRequests.push(`${details.url}: ${details.error}`);
}, },
); );
const statsServer = serveStatsDist(path.join(archive, 'stats', 'dist'), failedRequests); for (const ui of ['renderer', 'settings', 'syncui']) {
await once(statsServer, 'listening');
for (const ui of ['renderer', 'settings', 'syncui', 'stats']) {
const win = new BrowserWindow({ const win = new BrowserWindow({
show: false, show: false,
webPreferences: { webPreferences: {
@@ -104,25 +73,52 @@ async function smoke() {
}, },
}); });
try { try {
if (ui === 'stats') { await win.loadFile(path.join(archive, `dist/${ui}/index.html`));
await win.loadURL(`http://127.0.0.1:${statsServer.address().port}/`); const loaded = await win.webContents.executeJavaScript(
// Let in-flight font requests settle before the window goes away. `document.fonts.load('400 16px "M PLUS 1"', '日本語').then(fonts => fonts.length > 0 && fonts.every(font => font.status === 'loaded'))`,
await win.webContents.executeJavaScript('document.fonts.ready.then(() => true)'); );
} else { assert(loaded, `${ui}: shared Japanese font failed to load`);
await win.loadFile(path.join(archive, `dist/${ui}/index.html`));
const loaded = await win.webContents.executeJavaScript(
`document.fonts.load('400 16px "M PLUS 1"', '日本語').then(fonts => fonts.length > 0 && fonts.every(font => font.status === 'loaded'))`,
);
assert(loaded, `${ui}: shared Japanese font failed to load`);
}
} finally { } finally {
win.destroy(); win.destroy();
} }
} }
statsServer.close(); // The stats dashboard uses HTTP for both assets and API requests in the app.
const { ImmersionTrackerService } = packagedRequire(
'./dist/core/services/immersion-tracker-service.js',
);
const { createStatsApp, startNodeHttpServer } = packagedRequire(
'./dist/core/services/stats-server.js',
);
const tracker = new ImmersionTrackerService({ dbPath: path.join(isolatedData, 'stats.db') });
const statsConfig = { port: 0, staticDir: path.join(archive, 'stats/dist'), tracker };
let statsHttp;
const statsServer = await startNodeHttpServer(
createStatsApp(tracker, statsConfig),
statsConfig,
(listener) => (statsHttp = http.createServer(listener)),
);
const statsWindow = new BrowserWindow({ show: false });
try {
const url = `http://127.0.0.1:${statsHttp.address().port}`;
session.defaultSession.webRequest.onCompleted({ urls: [`${url}/*`] }, (details) => {
if (details.statusCode >= 400) failedRequests.push(`${details.url}: ${details.statusCode}`);
});
await statsWindow.loadURL(url);
// Let in-flight font requests settle before the window goes away.
await statsWindow.webContents.executeJavaScript('document.fonts.ready.then(() => true)');
for (const endpoint of ['overview', 'sessions']) {
const response = await fetch(`${url}/api/stats/${endpoint}`);
assert.equal(response.status, 200, `Stats ${endpoint} request failed`);
await response.json();
}
} finally {
statsWindow.destroy();
await statsServer.close();
tracker.destroy();
}
assert.deepEqual(failedRequests, [], 'Packaged UI resources failed to load'); assert.deepEqual(failedRequests, [], 'Packaged UI resources failed to load');
console.log( console.log(
'Package smoke passed: SQLite, platform FFI, texthooker, Yomitan loading, UI pages, shared Japanese font.', 'Package smoke passed: SQLite, platform FFI, texthooker, both dictionary extensions, UI pages, stats HTTP, shared Japanese font.',
); );
} }
-9
View File
@@ -61,15 +61,6 @@ test('normalizeTarget maps each supported electron-builder target without using
assert.throws(() => normalizeTarget('linux', 0), /Unsupported Bun runtime target architecture/); assert.throws(() => normalizeTarget('linux', 0), /Unsupported Bun runtime target architecture/);
}); });
test('resolveArtifact chooses baseline x64 builds and standard arm64 builds', () => {
const config = runtimeConfig();
assert.equal(resolveArtifact(config, 'linux', 'x64').file, 'bun-linux-x64-baseline.zip');
assert.equal(resolveArtifact(config, 'darwin', 'x64').file, 'bun-darwin-x64-baseline.zip');
assert.equal(resolveArtifact(config, 'win32', 'x64').file, 'bun-windows-x64-baseline.zip');
assert.equal(resolveArtifact(config, 'linux', 'arm64').file, 'bun-linux-aarch64.zip');
assert.equal(resolveArtifact(config, 'darwin', 'arm64').file, 'bun-darwin-aarch64.zip');
});
test('tracked runtime manifest covers every supported target at the packageManager version', async () => { test('tracked runtime manifest covers every supported target at the packageManager version', async () => {
const config = await loadRuntimeConfig(); const config = await loadRuntimeConfig();
assert.equal(config.version, '1.3.5'); assert.equal(config.version, '1.3.5');
-14
View File
@@ -3,20 +3,6 @@ import assert from 'node:assert/strict';
import { AnkiConnectClient } from './anki-connect'; import { AnkiConnectClient } from './anki-connect';
import { setLogLevel } from './logger'; import { setLogLevel } from './logger';
test('AnkiConnectClient disables keep-alive agents to avoid stale socket retries', () => {
const client = new AnkiConnectClient('http://127.0.0.1:8765') as unknown as {
client: {
defaults: {
httpAgent?: { options?: { keepAlive?: boolean } };
httpsAgent?: { options?: { keepAlive?: boolean } };
};
};
};
assert.equal(client.client.defaults.httpAgent?.options?.keepAlive, false);
assert.equal(client.client.defaults.httpsAgent?.options?.keepAlive, false);
});
test('AnkiConnectClient includes action name in retry logs', async () => { test('AnkiConnectClient includes action name in retry logs', async () => {
const client = new AnkiConnectClient('http://127.0.0.1:8765') as unknown as { const client = new AnkiConnectClient('http://127.0.0.1:8765') as unknown as {
client: { post: (url: string, body: unknown, options: unknown) => Promise<unknown> }; client: { post: (url: string, body: unknown, options: unknown) => Promise<unknown> };
+612 -1235
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -1807,6 +1807,9 @@ export class AnkiIntegration {
request: Omit<MediaTimingReviewRequest, 'audioPadding' | 'maxMediaDuration'>, request: Omit<MediaTimingReviewRequest, 'audioPadding' | 'maxMediaDuration'>,
): Promise<MediaTimingReviewDecision> { ): Promise<MediaTimingReviewDecision> {
if (this.config.media?.reviewTiming !== true || !this.mediaTimingReviewCallback) { if (this.config.media?.reviewTiming !== true || !this.mediaTimingReviewCallback) {
log.debug(
`[media-timing] review skipped: reviewTiming=${String(this.config.media?.reviewTiming)} callback=${this.mediaTimingReviewCallback ? 'set' : 'missing'}`,
);
return { action: 'use-original' }; return { action: 'use-original' };
} }
return await this.mediaTimingReviewCallback({ return await this.mediaTimingReviewCallback({
@@ -441,6 +441,127 @@ test('proxy strips SubMiner duplicate metadata before forwarding upstream addNot
} }
}); });
test('proxy enriches confirmed Hachidori overwrites without counting a new card or forwarding metadata', async () => {
const received: unknown[] = [];
let upstreamError: string | null = null;
const upstream = http.createServer(async (req, res) => {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(Buffer.from(chunk));
received.push(JSON.parse(Buffer.concat(chunks).toString()));
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ result: null, error: upstreamError }));
});
upstream.listen(0, '127.0.0.1');
await once(upstream, 'listening');
const address = upstream.address();
assert.ok(address && typeof address === 'object');
const processed: number[] = [];
const added: number[] = [];
const proxy = new AnkiConnectProxyServer({
shouldAutoUpdateNewCards: () => true,
processNewCard: async (id) => {
processed.push(id);
},
recordCardsAdded: (count) => {
added.push(count);
},
logInfo: () => {},
logWarn: () => {},
logError: () => {},
});
try {
proxy.start({ host: '127.0.0.1', port: 0, upstreamUrl: `http://127.0.0.1:${address.port}` });
await proxy.waitUntilReady();
const server: unknown = Reflect.get(proxy, 'server');
assert.ok(server instanceof http.Server);
const bound = server.address();
assert.ok(bound && typeof bound === 'object');
for (const [id, marked, error] of [
[51, true, null],
[52, false, null],
[53, true, 'failed'],
] satisfies Array<[number, boolean, string | null]>) {
upstreamError = error;
await fetch(`http://127.0.0.1:${bound.port}`, {
method: 'POST',
body: JSON.stringify({
action: 'updateNoteFields',
version: 6,
params: {
note: { id, fields: { Expression: '猫' } },
...(marked ? { subminerEnrich: true } : {}),
},
}),
});
}
await waitForCondition(() => processed.length > 0);
assert.deepEqual(processed, [51]);
assert.deepEqual(added, []);
assert.equal(JSON.stringify(received).includes('subminerEnrich'), false);
} finally {
proxy.stop();
upstream.close();
await once(upstream, 'close');
}
});
test('stats-owned notes bypass overlay enrichment while popup notes still enqueue', async () => {
const processed: number[] = [];
const added: number[] = [];
const received: unknown[] = [];
let noteId = 70;
const upstream = http.createServer(async (req, res) => {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(Buffer.from(chunk));
received.push(JSON.parse(Buffer.concat(chunks).toString()));
res.end(JSON.stringify({ result: ++noteId, error: null }));
});
upstream.listen(0, '127.0.0.1');
await once(upstream, 'listening');
const address = upstream.address();
assert.ok(address && typeof address === 'object');
const proxy = new AnkiConnectProxyServer({
shouldAutoUpdateNewCards: () => true,
processNewCard: async (id) => {
processed.push(id);
},
recordCardsAdded: (_count, ids) => {
added.push(...ids);
},
logInfo: () => {},
logWarn: () => {},
logError: () => {},
});
try {
proxy.start({ host: '127.0.0.1', port: 0, upstreamUrl: `http://127.0.0.1:${address.port}` });
await proxy.waitUntilReady();
const server: unknown = Reflect.get(proxy, 'server');
assert.ok(server instanceof http.Server);
const bound = server.address();
assert.ok(bound && typeof bound === 'object');
for (const metadata of [{ subminerEnrich: false }, {}]) {
const response: Response = await fetch(`http://127.0.0.1:${bound.port}`, {
method: 'POST',
body: JSON.stringify({
action: 'addNote',
version: 6,
params: { note: { fields: { Expression: '猫' } }, ...metadata },
}),
});
assert.equal(response.status, 200);
await response.json();
}
await waitForCondition(() => processed.includes(72));
assert.deepEqual(processed, [72]);
assert.deepEqual(added, [71, 72]);
assert.equal(JSON.stringify(received).includes('subminerEnrich'), false);
} finally {
proxy.stop();
upstream.close();
await once(upstream, 'close');
}
});
test('proxy returns addNote response without waiting for background enrichment', async () => { test('proxy returns addNote response without waiting for background enrichment', async () => {
const processed: number[] = []; const processed: number[] = [];
let releaseProcessing: (() => void) | undefined; let releaseProcessing: (() => void) | undefined;
+47 -6
View File
@@ -224,6 +224,31 @@ export class AnkiConnectProxyServer {
typeof requestJson.action === 'string' typeof requestJson.action === 'string'
? requestJson.action ? requestJson.action
: String(requestJson.action ?? ''); : String(requestJson.action ?? '');
if (action === 'updateNoteFields') {
const params = requestJson.params;
if (
!params ||
typeof params !== 'object' ||
!('subminerEnrich' in params) ||
params.subminerEnrich !== true
)
return;
const note = 'note' in params ? params.note : null;
if (!note || typeof note !== 'object' || !('id' in note)) return;
const response = this.tryParseJsonValue(responseBody);
// AnkiConnect confirms updates with {result:null,error:null}; failures must never enrich.
if (
!response ||
typeof response !== 'object' ||
!('error' in response) ||
response.error !== null ||
!('result' in response) ||
response.result !== null
)
return;
this.enqueueNotes(this.collectSingleResultId(note.id), false);
return;
}
if (action !== 'addNote' && action !== 'addNotes' && action !== 'multi') { if (action !== 'addNote' && action !== 'addNotes' && action !== 'multi') {
return; return;
} }
@@ -239,12 +264,23 @@ export class AnkiConnectProxyServer {
return; return;
} }
this.maybeTrackDuplicateNoteIds(requestJson, action, responseResult);
const noteIds = const noteIds =
action === 'multi' action === 'multi'
? this.collectMultiResultIds(requestJson, responseResult) ? this.collectMultiResultIds(requestJson, responseResult)
: this.collectNoteIdsForAction(action, responseResult); : this.collectNoteIdsForAction(action, responseResult);
const params = requestJson.params;
if (
action === 'addNote' &&
params &&
typeof params === 'object' &&
'subminerEnrich' in params &&
params.subminerEnrich === false
) {
// Stats owns the saved sentence and media; the live mpv context is unrelated.
if (noteIds.length > 0) this.deps.recordCardsAdded?.(noteIds.length, noteIds);
return;
}
this.maybeTrackDuplicateNoteIds(requestJson, action, responseResult);
if (noteIds.length === 0 && shouldFallbackToLatestAdded) { if (noteIds.length === 0 && shouldFallbackToLatestAdded) {
void this.enqueueMostRecentAddedNote(); void this.enqueueMostRecentAddedNote();
return; return;
@@ -293,7 +329,7 @@ export class AnkiConnectProxyServer {
typeof requestJson.action === 'string' typeof requestJson.action === 'string'
? requestJson.action ? requestJson.action
: String(requestJson.action ?? ''); : String(requestJson.action ?? '');
if (action !== 'addNote') { if (action !== 'addNote' && action !== 'updateNoteFields') {
return requestJson; return requestJson;
} }
@@ -301,12 +337,17 @@ export class AnkiConnectProxyServer {
requestJson.params && typeof requestJson.params === 'object' requestJson.params && typeof requestJson.params === 'object'
? (requestJson.params as Record<string, unknown>) ? (requestJson.params as Record<string, unknown>)
: null; : null;
if (!params || !Object.prototype.hasOwnProperty.call(params, 'subminerDuplicateNoteIds')) { if (
!params ||
(!Object.prototype.hasOwnProperty.call(params, 'subminerDuplicateNoteIds') &&
!Object.prototype.hasOwnProperty.call(params, 'subminerEnrich'))
) {
return requestJson; return requestJson;
} }
const nextParams = { ...params }; const nextParams = { ...params };
delete nextParams.subminerDuplicateNoteIds; delete nextParams.subminerDuplicateNoteIds;
delete nextParams.subminerEnrich;
return { return {
...requestJson, ...requestJson,
params: nextParams, params: nextParams,
@@ -455,7 +496,7 @@ export class AnkiConnectProxyServer {
}); });
} }
private enqueueNotes(noteIds: number[]): void { private enqueueNotes(noteIds: number[], recordAdded = true): void {
let enqueuedCount = 0; let enqueuedCount = 0;
const acceptedIds: number[] = []; const acceptedIds: number[] = [];
for (const noteId of noteIds) { for (const noteId of noteIds) {
@@ -472,7 +513,7 @@ export class AnkiConnectProxyServer {
return; return;
} }
this.deps.recordCardsAdded?.(enqueuedCount, acceptedIds); if (recordAdded) this.deps.recordCardsAdded?.(enqueuedCount, acceptedIds);
this.deps.logInfo(`[anki-proxy] Enqueued ${enqueuedCount} note(s) for enrichment`); this.deps.logInfo(`[anki-proxy] Enqueued ${enqueuedCount} note(s) for enrichment`);
this.processQueue(); this.processQueue();
} }
@@ -2,9 +2,13 @@ import assert from 'node:assert/strict';
import test from 'node:test'; import test from 'node:test';
import { CardCreationService } from './card-creation'; import { CardCreationService } from './card-creation';
import type { AnkiConnectConfig } from '../types/anki'; import {
type CardCreationDeps,
type CardCreationDeps = ConstructorParameters<typeof CardCreationService>[0]; createAnkiConfig,
createCardCreationDeps,
createFakeClient,
createFakeMediaGenerator,
} from './card-creation-test-utils';
test('sentence card writes generated audio only to sentence audio field', async () => { test('sentence card writes generated audio only to sentence audio field', async () => {
const addedFields: Record<string, string>[] = []; const addedFields: Record<string, string>[] = [];
@@ -13,128 +17,88 @@ test('sentence card writes generated audio only to sentence audio field', async
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 audioRanges: Array<{ start: number; end: number; padding: number | undefined }> = [];
let review: Awaited<ReturnType<NonNullable<CardCreationDeps['reviewMediaTiming']>>> = {
const deps: CardCreationDeps = { action: 'confirm',
getConfig: () => startTime: 11.4,
({ endTime: 14.2,
deck: 'Mining',
fields: {
word: 'Expression',
sentence: 'Sentence',
audio: 'ExpressionAudio',
translation: 'SelectionText',
},
media: {
generateAudio: true,
generateImage: false,
mirrorMpvVolume: true,
maxMediaDuration: 30,
},
behavior: {},
ai: false,
}) as AnkiConnectConfig,
getAiConfig: () => ({}),
getTimingTracker: () => ({}) as never,
getMpvClient: () =>
({
currentVideoPath: '/video.mp4',
currentSubText: '字幕',
currentSubStart: 12,
currentSubEnd: 14,
currentTimePos: 13,
currentAudioStreamIndex: 0,
requestProperty: async (name: string) => {
requestedProperties.push(name);
return 40;
},
}) as never,
client: {
addNote: async (_deck, _modelName, fields) => {
addedFields.push(fields);
return 42;
},
addTags: async () => undefined,
notesInfo: async () => [
{
noteId: 42,
fields: {
Expression: { value: '字幕' },
Sentence: { value: '字幕' },
SelectionText: { value: 'Subtitle' },
ExpressionAudio: { value: '' },
SentenceAudio: { value: '' },
},
},
],
updateNoteFields: async (_noteId, fields) => {
updatedFields.push(fields);
},
storeMediaFile: async (filename) => {
storedMedia.push(filename);
},
findNotes: async () => [],
retrieveMediaFile: async () => '',
deleteNotes: async () => undefined,
},
mediaGenerator: {
generateAudio: async (
_path,
startTime,
endTime,
audioPadding,
_audioStreamIndex,
_normalizeAudio,
volumeScale,
) => {
audioRanges.push({ start: startTime, end: endTime, padding: audioPadding });
audioVolumeScales.push(volumeScale);
return Buffer.from('audio');
},
generateScreenshot: async () => null,
generateAnimatedImage: async () => null,
},
showOsdNotification: () => undefined,
showUpdateResult: () => undefined,
showStatusNotification: () => undefined,
showNotification: async () => undefined,
beginUpdateProgress: () => undefined,
endUpdateProgress: () => undefined,
withUpdateProgress: async (_message, action) => action(),
resolveConfiguredFieldName: (noteInfo, ...preferredNames) => {
for (const preferredName of preferredNames) {
if (preferredName && preferredName in noteInfo.fields) return preferredName;
}
return null;
},
resolveNoteFieldName: (noteInfo, preferredName) =>
preferredName && preferredName in noteInfo.fields ? preferredName : null,
getAnimatedImageLeadInSeconds: async () => 0,
extractFields: () => ({}),
processSentence: (sentence) => sentence,
setCardTypeFields: () => undefined,
mergeFieldValue: (_existing, newValue) => newValue,
formatMiscInfoPattern: () => '',
getEffectiveSentenceCardConfig: () => ({
model: 'Sentence',
sentenceField: 'Sentence',
audioField: 'SentenceAudio',
lapisEnabled: true,
kikuEnabled: false,
fieldGroupingMode: 'disabled',
}),
getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined,
removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined,
reviewMediaTiming: async () => ({ action: 'confirm', startTime: 11.4, endTime: 14.2 }),
}; };
const service = new CardCreationService(deps); const service = new CardCreationService(
const created = await service.createSentenceCard('字幕', 12, 14, 'Subtitle'); createCardCreationDeps({
getConfig: () =>
createAnkiConfig({
fields: {
word: 'Expression',
audio: 'ExpressionAudio',
translation: 'SelectionText',
},
media: { generateAudio: true, mirrorMpvVolume: true, maxMediaDuration: 30 },
}),
getMpvClient: () =>
({
currentVideoPath: '/video.mp4',
currentSubText: '字幕',
currentSubStart: 12,
currentSubEnd: 14,
currentTimePos: 13,
currentAudioStreamIndex: 0,
requestProperty: async (name: string) => {
requestedProperties.push(name);
return 40;
},
}) as never,
client: createFakeClient({
addNote: async (_deck, _modelName, fields) => {
addedFields.push(fields);
return 42;
},
notesInfo: async () => [
{
noteId: 42,
fields: {
Expression: { value: '字幕' },
Sentence: { value: '字幕' },
SelectionText: { value: 'Subtitle' },
ExpressionAudio: { value: '' },
SentenceAudio: { value: '' },
},
},
],
updateNoteFields: async (_noteId, fields) => {
updatedFields.push(fields);
},
storeMediaFile: async (filename) => {
storedMedia.push(filename);
},
}),
mediaGenerator: createFakeMediaGenerator({
generateAudio: async (
_path,
startTime,
endTime,
audioPadding,
_audioStreamIndex,
_normalizeAudio,
volumeScale,
) => {
audioRanges.push({ start: startTime, end: endTime, padding: audioPadding });
audioVolumeScales.push(volumeScale);
return Buffer.from('audio');
},
}),
getEffectiveSentenceCardConfig: () => ({
model: 'Sentence',
sentenceField: 'Sentence',
audioField: 'SentenceAudio',
lapisEnabled: true,
kikuEnabled: false,
fieldGroupingMode: 'disabled',
}),
reviewMediaTiming: async () => review,
}),
);
assert.equal(created, true); assert.equal(await service.createSentenceCard('字幕', 12, 14, 'Subtitle'), true);
assert.deepEqual(addedFields[0], { assert.deepEqual(addedFields[0], {
Sentence: '字幕', Sentence: '字幕',
SelectionText: 'Subtitle', SelectionText: 'Subtitle',
@@ -149,11 +113,11 @@ test('sentence card writes generated audio only to sentence audio field', async
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' }); review = { action: 'discard' };
assert.equal(await service.createSentenceCard('作らない', 20, 22), false); assert.equal(await service.createSentenceCard('作らない', 20, 22), false);
assert.equal(addedFields.length, 1); assert.equal(addedFields.length, 1);
deps.reviewMediaTiming = async () => ({ action: 'skip-media' }); review = { action: 'skip-media' };
assert.equal(await service.createSentenceCard('メディアなし', 30, 32), true); assert.equal(await service.createSentenceCard('メディアなし', 30, 32), true);
assert.equal(addedFields.length, 2); assert.equal(addedFields.length, 2);
assert.equal(storedMedia.length, 1); assert.equal(storedMedia.length, 1);
@@ -0,0 +1,107 @@
import { CardCreationService } from './card-creation';
import type { AnkiConnectConfig } from '../types/anki';
export type CardCreationDeps = ConstructorParameters<typeof CardCreationService>[0];
/** Builds the minimal config the service reads; pass only the sections a test cares about. */
export function createAnkiConfig(
overrides: {
fields?: Record<string, string>;
media?: Record<string, unknown>;
} = {},
): AnkiConnectConfig {
return {
deck: 'Mining',
fields: { sentence: 'Sentence', audio: 'SentenceAudio', ...overrides.fields },
media: { generateAudio: false, generateImage: false, ...overrides.media },
behavior: {},
ai: false,
} as AnkiConnectConfig;
}
/**
* Fake CardCreationService dependencies: a bare mpv session, a client that adds note 42, no media,
* and field resolvers that match exact field names. Override only what the test exercises.
*/
export function createCardCreationDeps(
overrides: Partial<CardCreationDeps> = {},
): CardCreationDeps {
return {
getConfig: () => createAnkiConfig(),
getAiConfig: () => ({}),
getTimingTracker: () => ({}) as never,
getMpvClient: () =>
({
currentVideoPath: '/video.mp4',
currentSubText: '字幕',
currentSubStart: 1,
currentSubEnd: 2,
currentTimePos: 1.5,
currentAudioStreamIndex: 0,
}) as never,
client: {
addNote: async () => 42,
addTags: async () => undefined,
notesInfo: async () => [],
updateNoteFields: async () => undefined,
storeMediaFile: async () => undefined,
findNotes: async () => [],
retrieveMediaFile: async () => '',
deleteNotes: async () => undefined,
},
mediaGenerator: {
generateAudio: async () => null,
generateScreenshot: async () => null,
generateAnimatedImage: async () => null,
},
showOsdNotification: () => undefined,
showUpdateResult: () => undefined,
showStatusNotification: () => undefined,
showNotification: async () => undefined,
beginUpdateProgress: () => undefined,
endUpdateProgress: () => undefined,
withUpdateProgress: async (_message, action) => action(),
resolveConfiguredFieldName: (noteInfo, ...preferredNames) => {
for (const preferredName of preferredNames) {
if (preferredName && preferredName in noteInfo.fields) return preferredName;
}
return null;
},
resolveNoteFieldName: (noteInfo, preferredName) =>
preferredName && preferredName in noteInfo.fields ? preferredName : null,
getAnimatedImageLeadInSeconds: async () => 0,
extractFields: () => ({}),
processSentence: (sentence) => sentence,
setCardTypeFields: () => undefined,
mergeFieldValue: (_existing, newValue) => newValue,
formatMiscInfoPattern: () => '',
getEffectiveSentenceCardConfig: () => ({
model: 'Sentence',
sentenceField: 'Sentence',
audioField: 'SentenceAudio',
lapisEnabled: false,
kikuEnabled: false,
fieldGroupingMode: 'disabled',
}),
getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined,
removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined,
...overrides,
};
}
/** Anki client overrides, kept separate so a test can swap one method without redeclaring the rest. */
export function createFakeClient(
overrides: Partial<CardCreationDeps['client']> = {},
): CardCreationDeps['client'] {
return { ...createCardCreationDeps().client, ...overrides };
}
export function createFakeMediaGenerator(
overrides: Partial<CardCreationDeps['mediaGenerator']> = {},
): CardCreationDeps['mediaGenerator'] {
return { ...createCardCreationDeps().mediaGenerator, ...overrides };
}
File diff suppressed because it is too large. Load diff
@@ -500,3 +500,38 @@ test('Senren merge keeps duplicate SentenceFurigana when the kept field is empty
assert.equal(merged.SentenceFurigana, '<span class="group">duplicate furigana</span>'); assert.equal(merged.SentenceFurigana, '<span class="group">duplicate furigana</span>');
}); });
test('computeFieldGroupingMergedFields keeps independent groups for identical sentence, audio, and image values', async () => {
const { collaborator } = createCollaborator();
const merged = await collaborator.computeFieldGroupingMergedFields(
202,
101,
makeNote(202, {
Sentence: 'same sentence',
SentenceAudio: '[sound:same.mp3]',
Picture: '<img src="same.png">',
ExpressionAudio: '[sound:same.mp3]',
}),
makeNote(101, {
Sentence: 'same sentence',
SentenceAudio: '[sound:same.mp3]',
Picture: '<img src="same.png">',
}),
false,
);
assert.equal(
merged.Sentence,
'<span data-group-id="202">same sentence</span><span data-group-id="101">same sentence</span>',
);
assert.equal(
merged.SentenceAudio,
'<span data-group-id="202">[sound:same.mp3]</span><span data-group-id="101">[sound:same.mp3]</span>',
);
assert.equal(
merged.Picture,
'<img data-group-id="202" src="same.png"><img data-group-id="101" src="same.png">',
);
assert.equal('ExpressionAudio' in merged, false);
});
@@ -127,18 +127,6 @@ test('lifecycle config key is unchanged when maturity is disabled', () => {
); );
}); });
test('a cache built under the old tier rules is invalidated', () => {
const config: AnkiConnectConfig = {
knownWords: { highlightEnabled: true, maturityEnabled: true, refreshMinutes: 60 },
};
// v1 rules put lapsed cards in young because the interval queries did not
// exclude is:learn; those persisted tiers must not be served under v2.
assert.notEqual(
getKnownWordCacheLifecycleConfig(config),
'{"refreshMinutes":60,"scope":"all","fieldsWord":"","maturity":21}',
);
});
test('refresh fetches tier sets and getKnownWordTier classifies notes', async () => { test('refresh fetches tier sets and getKnownWordTier classifies notes', async () => {
const { manager, calls, clientState, cleanup } = createMaturityHarness(maturityConfig()); const { manager, calls, clientState, cleanup } = createMaturityHarness(maturityConfig());
+22 -121
View File
@@ -8,6 +8,7 @@ import {
import type { SubtitleMiningContext } from '../types/subtitle'; import type { SubtitleMiningContext } from '../types/subtitle';
import type { CardKind } from '../types/anki'; import type { CardKind } from '../types/anki';
import { applyCardKindFlagFields } from './card-kinds'; import { applyCardKindFlagFields } from './card-kinds';
import { STATS_MINING_TAG } from '../shared/anki-source';
function setCardTypeFields( function setCardTypeFields(
updatedFields: Record<string, string>, updatedFields: Record<string, string>,
@@ -110,6 +111,27 @@ function createWorkflowHarness() {
}; };
} }
test('NoteUpdateWorkflow preserves stats cards discovered by polling', async () => {
const { workflow, deps, updates } = createWorkflowHarness();
const note = {
noteId: 42,
tags: [STATS_MINING_TAG],
fields: { Expression: { value: '猫' }, Sentence: { value: '猫がいる。' } },
};
deps.client.notesInfo = async () => [note];
deps.captureSubtitleMediaContext = () => assert.fail('Must not capture current playback');
deps.findDuplicateNote = async () => assert.fail('Must not regroup a stats card');
let cachedNote: NoteUpdateWorkflowNoteInfo | undefined;
deps.appendKnownWordsFromNoteInfo = (value) => {
cachedNote = value;
};
await workflow.execute(42);
assert.deepEqual(updates, []);
assert.equal(cachedNote, note);
});
test('NoteUpdateWorkflow updates sentence field and emits notification', async () => { test('NoteUpdateWorkflow updates sentence field and emits notification', async () => {
const harness = createWorkflowHarness(); const harness = createWorkflowHarness();
@@ -223,127 +245,6 @@ test('NoteUpdateWorkflow marks enriched Kiku word cards as word-and-sentence car
}); });
}); });
test('NoteUpdateWorkflow marks the configured word card kind instead of word-and-sentence', async () => {
const harness = createWorkflowHarness();
harness.deps.getEffectiveSentenceCardConfig = () => ({
sentenceField: 'Sentence',
lapisEnabled: false,
kikuEnabled: true,
fieldGroupingMode: 'manual',
wordCardKind: 'click',
});
harness.deps.client.notesInfo = async () =>
[
{
noteId: 42,
fields: {
Expression: { value: 'taberu' },
Sentence: { value: '' },
IsWordAndSentenceCard: { value: 'x' },
IsClickCard: { value: '' },
IsSentenceCard: { value: '' },
IsAudioCard: { value: '' },
},
},
] satisfies NoteUpdateWorkflowNoteInfo[];
await harness.workflow.execute(42);
assert.equal(harness.updates.length, 1);
assert.deepEqual(harness.updates[0]?.fields, {
Sentence: 'subtitle-text',
IsClickCard: 'x',
IsWordAndSentenceCard: '',
IsSentenceCard: '',
IsAudioCard: '',
});
});
test('NoteUpdateWorkflow leaves card type flags alone when the word card kind is none', async () => {
const harness = createWorkflowHarness();
harness.deps.getEffectiveSentenceCardConfig = () => ({
sentenceField: 'Sentence',
lapisEnabled: false,
kikuEnabled: true,
fieldGroupingMode: 'manual',
wordCardKind: 'none',
});
harness.deps.client.notesInfo = async () =>
[
{
noteId: 42,
fields: {
Expression: { value: 'taberu' },
Sentence: { value: '' },
IsWordAndSentenceCard: { value: '' },
IsSentenceCard: { value: '' },
IsAudioCard: { value: '' },
},
},
] satisfies NoteUpdateWorkflowNoteInfo[];
await harness.workflow.execute(42);
assert.equal(harness.updates.length, 1);
assert.deepEqual(harness.updates[0]?.fields, {
Sentence: 'subtitle-text',
});
});
test('NoteUpdateWorkflow does not set Kiku card flags when Lapis and Kiku are disabled', async () => {
const harness = createWorkflowHarness();
harness.deps.client.notesInfo = async () =>
[
{
noteId: 42,
fields: {
Expression: { value: 'taberu' },
Sentence: { value: '' },
IsWordAndSentenceCard: { value: '' },
IsSentenceCard: { value: '' },
IsAudioCard: { value: '' },
},
},
] satisfies NoteUpdateWorkflowNoteInfo[];
await harness.workflow.execute(42);
assert.equal(harness.updates.length, 1);
assert.deepEqual(harness.updates[0]?.fields, {
Sentence: 'subtitle-text',
});
});
test('NoteUpdateWorkflow preserves explicit sentence card type during sentence enrichment', async () => {
const harness = createWorkflowHarness();
harness.deps.getEffectiveSentenceCardConfig = () => ({
sentenceField: 'Sentence',
lapisEnabled: true,
kikuEnabled: false,
fieldGroupingMode: 'disabled',
});
harness.deps.client.notesInfo = async () =>
[
{
noteId: 42,
fields: {
Expression: { value: 'sentence expression' },
Sentence: { value: '' },
IsWordAndSentenceCard: { value: '' },
IsSentenceCard: { value: 'x' },
IsAudioCard: { value: '' },
},
},
] satisfies NoteUpdateWorkflowNoteInfo[];
await harness.workflow.execute(42);
assert.equal(harness.updates.length, 1);
assert.deepEqual(harness.updates[0]?.fields, {
Sentence: 'subtitle-text',
});
});
test('NoteUpdateWorkflow no-ops when note info is missing', async () => { test('NoteUpdateWorkflow no-ops when note info is missing', async () => {
const harness = createWorkflowHarness(); const harness = createWorkflowHarness();
harness.deps.client.notesInfo = async () => []; harness.deps.client.notesInfo = async () => [];
@@ -8,9 +8,11 @@ import type {
WordCardKind, WordCardKind,
} from '../types/anki'; } from '../types/anki';
import { resolveWordCardKind } from './note-field-utils'; import { resolveWordCardKind } from './note-field-utils';
import { STATS_MINING_TAG } from '../shared/anki-source';
export interface NoteUpdateWorkflowNoteInfo { export interface NoteUpdateWorkflowNoteInfo {
noteId: number; noteId: number;
tags?: string[];
fields: Record<string, { value: string }>; fields: Record<string, { value: string }>;
} }
@@ -185,6 +187,10 @@ export class NoteUpdateWorkflow {
} }
const noteInfo = notesInfo[0]!; const noteInfo = notesInfo[0]!;
if (noteInfo.tags?.includes(STATS_MINING_TAG)) {
this.deps.appendKnownWordsFromNoteInfo(noteInfo);
return;
}
const fields = this.deps.extractFields(noteInfo.fields); const fields = this.deps.extractFields(noteInfo.fields);
const config = this.deps.getConfig(); const config = this.deps.getConfig();
-74
View File
@@ -1,74 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
const ciWorkflowPath = resolve(__dirname, '../.github/workflows/ci.yml');
const ciWorkflow = readFileSync(ciWorkflowPath, 'utf8');
const docsPagesWorkflowPath = resolve(__dirname, '../.github/workflows/docs-pages.yml');
const docsPagesWorkflow = readFileSync(docsPagesWorkflowPath, 'utf8');
const packageJsonPath = resolve(__dirname, '../package.json');
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8')) as {
scripts: Record<string, string>;
};
test('package scripts expose a sharded maintained source coverage lane with lcov output', () => {
assert.equal(
packageJson.scripts['test:coverage:src'],
'bun run build:yomitan && bun run scripts/run-coverage-lane.ts bun-src-full --coverage-dir coverage/test-src',
);
});
test('source and coverage scripts discover the same maintained source lane', () => {
const sourceLane = packageJson.scripts['test:src']?.match(/run-test-lane\.mjs\s+([^\s]+)/)?.[1];
const coverageLane = packageJson.scripts['test:coverage:src']?.match(
/run-coverage-lane\.ts\s+([^\s]+)/,
)?.[1];
assert.equal(sourceLane, 'bun-src-full');
assert.equal(coverageLane, sourceLane);
});
test('environment suite owns launcher smoke execution', () => {
assert.match(
packageJson.scripts['test:env'] ?? '',
/^bun run test:launcher:smoke:src && bun run test:plugin:src && bun run test:immersion:sqlite:src$/,
);
});
test('ci delegates its gate instead of duplicating quality steps', () => {
assert.match(
ciWorkflow,
/build-test-audit:\s*\n\s*uses: \.\/\.github\/workflows\/quality-gate\.yml/,
);
assert.doesNotMatch(ciWorkflow, /oven-sh\/setup-bun/);
assert.doesNotMatch(ciWorkflow, /bun run test:coverage:src/);
assert.doesNotMatch(ciWorkflow, /bun run test:env/);
});
test('main docs deploy exists, serializes deploys, and uses Cloudflare credentials', () => {
assert.match(docsPagesWorkflow, /name: Docs Pages/);
assert.match(docsPagesWorkflow, /branches:\s*\n\s*-\s*main/);
assert.match(docsPagesWorkflow, /group:\s*docs-pages-production/);
assert.match(docsPagesWorkflow, /CLOUDFLARE_API_TOKEN/);
assert.match(docsPagesWorkflow, /CLOUDFLARE_ACCOUNT_ID/);
assert.match(docsPagesWorkflow, /CLOUDFLARE_PAGES_PROJECT_NAME/);
assert.match(docsPagesWorkflow, /pages deploy \.\.\/\.tmp\/docs-versioned-site/);
assert.match(docsPagesWorkflow, /--branch main/);
});
test('docs deploy syncs frozen archives to R2 and ships the archive Pages Function', () => {
assert.doesNotMatch(docsPagesWorkflow, /actions\/cache@/);
assert.match(docsPagesWorkflow, /DOCS_ARCHIVE_R2_ACCESS_KEY_ID/);
assert.match(docsPagesWorkflow, /DOCS_ARCHIVE_R2_SECRET_ACCESS_KEY/);
assert.match(docsPagesWorkflow, /--require-archives/);
assert.match(docsPagesWorkflow, /--rebuild-archives=\$\{REBUILD_ARCHIVES\}/);
assert.match(docsPagesWorkflow, /workingDirectory: docs-site/);
});
test('docs deploy skips invalid release tags without failing the workflow', () => {
assert.match(docsPagesWorkflow, /id:\s*tag_guard/);
assert.match(docsPagesWorkflow, /stable_tag=false/);
assert.doesNotMatch(docsPagesWorkflow, /exit 78/);
assert.match(docsPagesWorkflow, /if:\s*steps\.tag_guard\.outputs\.stable_tag != 'false'/);
});
+19
View File
@@ -8,6 +8,7 @@ import {
isStandaloneTexthookerCommand, isStandaloneTexthookerCommand,
parseArgs, parseArgs,
shouldRunYomitanOnlyStartup, shouldRunYomitanOnlyStartup,
shouldRunDictionarySettingsOnlyStartup,
shouldStartApp, shouldStartApp,
} from './args'; } from './args';
@@ -476,3 +477,21 @@ test('hasExplicitCommand and shouldStartApp preserve command intent', () => {
assert.equal(hasExplicitCommand(setup), true); assert.equal(hasExplicitCommand(setup), true);
assert.equal(shouldStartApp(setup), true); assert.equal(shouldStartApp(setup), true);
}); });
test('Hachidori settings starts the app without overlay or mpv prerequisites', () => {
const args = parseArgs(['--hachidori']);
assert.equal(args.hachidori, true);
assert.equal(args.yomitan, false);
assert.equal(hasExplicitCommand(args), true);
assert.equal(shouldStartApp(args), true);
assert.equal(shouldRunDictionarySettingsOnlyStartup(args), true);
assert.equal(shouldRunYomitanOnlyStartup(args), false);
assert.equal(commandNeedsOverlayRuntime(args), false);
assert.equal(commandNeedsOverlayStartupPrereqs(args), false);
assert.equal(isStandaloneTexthookerCommand(parseArgs(['--texthooker', '--hachidori'])), false);
assert.equal(
shouldRunDictionarySettingsOnlyStartup(parseArgs(['--hachidori', '--start'])),
false,
);
assert.equal(shouldRunDictionarySettingsOnlyStartup(parseArgs(['--yomitan'])), true);
});
+11 -1
View File
@@ -12,6 +12,7 @@ export interface CliArgs {
toggleVisibleOverlay: boolean; toggleVisibleOverlay: boolean;
togglePrimarySubtitleBar: boolean; togglePrimarySubtitleBar: boolean;
yomitan: boolean; yomitan: boolean;
hachidori: boolean;
settings: boolean; settings: boolean;
syncWindow: boolean; syncWindow: boolean;
youtubeBrowser: boolean; youtubeBrowser: boolean;
@@ -133,6 +134,7 @@ export function parseArgs(argv: string[]): CliArgs {
toggleVisibleOverlay: false, toggleVisibleOverlay: false,
togglePrimarySubtitleBar: false, togglePrimarySubtitleBar: false,
yomitan: false, yomitan: false,
hachidori: false,
settings: false, settings: false,
syncWindow: false, syncWindow: false,
youtubeBrowser: false, youtubeBrowser: false,
@@ -279,6 +281,7 @@ export function parseArgs(argv: string[]): CliArgs {
else if (arg === '--toggle-visible-overlay') args.toggleVisibleOverlay = true; else if (arg === '--toggle-visible-overlay') args.toggleVisibleOverlay = true;
else if (arg === '--toggle-primary-subtitle-bar') args.togglePrimarySubtitleBar = true; else if (arg === '--toggle-primary-subtitle-bar') args.togglePrimarySubtitleBar = true;
else if (arg === '--yomitan') args.yomitan = true; else if (arg === '--yomitan') args.yomitan = true;
else if (arg === '--hachidori') args.hachidori = true;
else if (arg === '--settings') args.settings = true; else if (arg === '--settings') args.settings = true;
else if (arg === '--sync-window') args.syncWindow = true; else if (arg === '--sync-window') args.syncWindow = true;
else if (arg === '--youtube-browser') args.youtubeBrowser = true; else if (arg === '--youtube-browser') args.youtubeBrowser = true;
@@ -563,6 +566,7 @@ export function hasExplicitCommand(args: CliArgs): boolean {
args.toggleVisibleOverlay || args.toggleVisibleOverlay ||
args.togglePrimarySubtitleBar || args.togglePrimarySubtitleBar ||
args.yomitan || args.yomitan ||
args.hachidori ||
args.settings || args.settings ||
args.syncWindow || args.syncWindow ||
args.youtubeBrowser || args.youtubeBrowser ||
@@ -643,6 +647,7 @@ export function isStandaloneTexthookerCommand(args: CliArgs): boolean {
!args.toggleVisibleOverlay && !args.toggleVisibleOverlay &&
!args.togglePrimarySubtitleBar && !args.togglePrimarySubtitleBar &&
!args.yomitan && !args.yomitan &&
!args.hachidori &&
!args.settings && !args.settings &&
!args.syncWindow && !args.syncWindow &&
!args.youtubeBrowser && !args.youtubeBrowser &&
@@ -716,6 +721,7 @@ export function shouldStartApp(args: CliArgs): boolean {
args.toggleVisibleOverlay || args.toggleVisibleOverlay ||
args.togglePrimarySubtitleBar || args.togglePrimarySubtitleBar ||
args.yomitan || args.yomitan ||
args.hachidori ||
args.settings || args.settings ||
args.syncWindow || args.syncWindow ||
args.youtubeBrowser || args.youtubeBrowser ||
@@ -767,8 +773,12 @@ export function shouldStartApp(args: CliArgs): boolean {
} }
export function shouldRunYomitanOnlyStartup(args: CliArgs): boolean { export function shouldRunYomitanOnlyStartup(args: CliArgs): boolean {
return args.yomitan && !args.hachidori && shouldRunDictionarySettingsOnlyStartup(args);
}
export function shouldRunDictionarySettingsOnlyStartup(args: CliArgs): boolean {
return ( return (
args.yomitan && (args.yomitan || args.hachidori) &&
!args.background && !args.background &&
!args.start && !args.start &&
!args.stop && !args.stop &&
-36
View File
@@ -1,36 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { printHelp } from './help';
test('printHelp includes configured texthooker port', () => {
const original = console.log;
let output = '';
console.log = (value?: unknown) => {
output += String(value);
};
try {
printHelp(7777);
} finally {
console.log = original;
}
assert.match(output, /--help\s+Show this help/);
assert.match(output, /default: 7777/);
assert.match(output, /--launch-mpv.*Launch mpv with SubMiner defaults and exit/);
assert.match(output, /--stats\s+Open the stats dashboard in your browser/);
assert.match(output, /--open-browser\s+Open texthooker in your default browser/);
assert.doesNotMatch(output, /--refresh-known-words/);
assert.match(output, /--setup\s+Open first-run setup window/);
assert.match(output, /--settings\s+Open SubMiner settings window/);
assert.match(output, /--yomitan\s+Open Yomitan settings window/);
assert.match(output, /--mark-watched\s+Mark current video watched and advance playlist/);
assert.match(output, /--anilist-status/);
assert.match(output, /--anilist-retry-queue/);
assert.match(output, /--dictionary/);
assert.match(output, /--dictionary-target/);
assert.match(output, /--jellyfin\s+Open Jellyfin setup window/);
assert.match(output, /--jellyfin-login/);
assert.match(output, /--jellyfin-subtitles/);
assert.match(output, /--jellyfin-play/);
});
+1
View File
@@ -25,6 +25,7 @@ ${B}Overlay${R}
--show-visible-overlay Show subtitle overlay --show-visible-overlay Show subtitle overlay
--hide-visible-overlay Hide subtitle overlay --hide-visible-overlay Hide subtitle overlay
--yomitan Open Yomitan settings window --yomitan Open Yomitan settings window
--hachidori Open Hachidori settings window
--settings Open SubMiner settings window --settings Open SubMiner settings window
--setup Open first-run setup window --setup Open first-run setup window
--auto-start-overlay Auto-hide mpv subs, show overlay on connect --auto-start-overlay Auto-hide mpv subs, show overlay on connect
+103 -1004
View File
File diff suppressed because it is too large. Load diff
+2
View File
@@ -22,6 +22,7 @@ export type {
} from './definitions/shared'; } from './definitions/shared';
const { const {
dictionaryBackend,
subtitlePosition, subtitlePosition,
keybindings, keybindings,
websocket, websocket,
@@ -57,6 +58,7 @@ const { stats } = STATS_DEFAULT_CONFIG;
export const DEFAULT_CONFIG: ResolvedConfig = { export const DEFAULT_CONFIG: ResolvedConfig = {
subtitleSelection: { enabled: false }, subtitleSelection: { enabled: false },
subtitleGeneration: { ...DEFAULT_SUBTITLE_GENERATION_CONFIG }, subtitleGeneration: { ...DEFAULT_SUBTITLE_GENERATION_CONFIG },
dictionaryBackend,
subtitlePosition, subtitlePosition,
keybindings, keybindings,
websocket, websocket,
+2
View File
@@ -2,6 +2,7 @@ import { ResolvedConfig } from '../../types/config';
export const CORE_DEFAULT_CONFIG: Pick< export const CORE_DEFAULT_CONFIG: Pick<
ResolvedConfig, ResolvedConfig,
| 'dictionaryBackend'
| 'subtitlePosition' | 'subtitlePosition'
| 'keybindings' | 'keybindings'
| 'websocket' | 'websocket'
@@ -18,6 +19,7 @@ export const CORE_DEFAULT_CONFIG: Pick<
| 'notifications' | 'notifications'
| 'auto_start_overlay' | 'auto_start_overlay'
> = { > = {
dictionaryBackend: 'yomitan',
subtitlePosition: { yPercent: 10 }, subtitlePosition: { yPercent: 10 },
keybindings: [], keybindings: [],
websocket: { websocket: {
+5 -134
View File
@@ -2,17 +2,7 @@ import assert from 'node:assert/strict';
import test from 'node:test'; import test from 'node:test';
import { ResolvedConfig } from '../../types/config'; import { ResolvedConfig } from '../../types/config';
import { import { CONFIG_OPTION_REGISTRY, CONFIG_TEMPLATE_SECTIONS, DEFAULT_CONFIG } from '../definitions';
CONFIG_OPTION_REGISTRY,
CONFIG_TEMPLATE_SECTIONS,
DEFAULT_CONFIG,
DEFAULT_KEYBINDINGS,
RUNTIME_OPTION_REGISTRY,
} from '../definitions';
import { buildCoreConfigOptionRegistry } from './options-core';
import { buildImmersionConfigOptionRegistry } from './options-immersion';
import { buildIntegrationConfigOptionRegistry } from './options-integrations';
import { buildSubtitleConfigOptionRegistry } from './options-subtitle';
function collectConfigLeafPaths(config: ResolvedConfig): string[] { function collectConfigLeafPaths(config: ResolvedConfig): string[] {
const leaves: string[] = []; const leaves: string[] = [];
@@ -87,58 +77,6 @@ const UNDOCUMENTED_LEAVES: ReadonlySet<string> = new Set([
'subtitleStyle.wordSpacing', 'subtitleStyle.wordSpacing',
]); ]);
test('config option registry includes critical paths and has unique entries', () => {
const paths = CONFIG_OPTION_REGISTRY.map((entry) => entry.path);
for (const requiredPath of [
'logging.level',
'logging.files.mpv',
'annotationWebsocket.enabled',
'controller.enabled',
'controller.scrollPixelsPerSecond',
'startupWarmups.lowPowerMode',
'updates.channel',
'youtube.primarySubLanguages',
'subtitleStyle.enableJlpt',
'subtitleStyle.autoPauseVideoOnYomitanPopup',
'ankiConnect.enabled',
'subtitleStyle.nameMatchEnabled',
'ankiConnect.media.normalizeAudio',
'ankiConnect.media.mirrorMpvVolume',
'anilist.characterDictionary.collapsibleSections.description',
'mpv.executablePath',
'mpv.launchMode',
'mpv.profile',
'mpv.socketPath',
'mpv.backend',
'mpv.autoStartSubMiner',
'mpv.pauseUntilOverlayReady',
'mpv.subminerBinaryPath',
'mpv.aniskipEnabled',
'mpv.aniskipButtonKey',
'yomitan.externalProfilePath',
'immersionTracking.enabled',
]) {
assert.ok(paths.includes(requiredPath), `missing config path: ${requiredPath}`);
}
assert.equal(new Set(paths).size, paths.length);
});
test('known-word annotation color has one public config path', () => {
const leaves = collectConfigLeafPaths(DEFAULT_CONFIG);
assert.ok(leaves.includes('subtitleStyle.knownWordColor'));
assert.ok(!leaves.includes('ankiConnect.knownWords.color'));
});
test('n+1 annotation color has one public config path', () => {
const leaves = collectConfigLeafPaths(DEFAULT_CONFIG);
assert.ok(leaves.includes('subtitleStyle.nPlusOneColor'));
assert.ok(!leaves.includes('ankiConnect.nPlusOne.color'));
});
test('every DEFAULT_CONFIG leaf is in CONFIG_OPTION_REGISTRY or UNDOCUMENTED_LEAVES', () => { test('every DEFAULT_CONFIG leaf is in CONFIG_OPTION_REGISTRY or UNDOCUMENTED_LEAVES', () => {
const registryPaths = new Set(CONFIG_OPTION_REGISTRY.map((entry) => entry.path)); const registryPaths = new Set(CONFIG_OPTION_REGISTRY.map((entry) => entry.path));
const leaves = collectConfigLeafPaths(DEFAULT_CONFIG); const leaves = collectConfigLeafPaths(DEFAULT_CONFIG);
@@ -168,77 +106,10 @@ test('every DEFAULT_CONFIG leaf is in CONFIG_OPTION_REGISTRY or UNDOCUMENTED_LEA
); );
}); });
test('config template sections include expected domains and unique keys', () => { test('config option paths and template section keys are unique', () => {
const paths = CONFIG_OPTION_REGISTRY.map((entry) => entry.path);
assert.equal(new Set(paths).size, paths.length);
const keys = CONFIG_TEMPLATE_SECTIONS.map((section) => section.key); const keys = CONFIG_TEMPLATE_SECTIONS.map((section) => section.key);
const requiredKeys: (typeof keys)[number][] = [
'websocket',
'annotationWebsocket',
'controller',
'startupWarmups',
'youtube',
'subtitleStyle',
'ankiConnect',
'yomitan',
'mpv',
'immersionTracking',
];
for (const requiredKey of requiredKeys) {
assert.ok(keys.includes(requiredKey), `missing template section key: ${requiredKey}`);
}
assert.equal(new Set(keys).size, keys.length); assert.equal(new Set(keys).size, keys.length);
}); });
test('domain registry builders each contribute entries to composed registry', () => {
const domainEntries = [
buildCoreConfigOptionRegistry(DEFAULT_CONFIG),
buildSubtitleConfigOptionRegistry(DEFAULT_CONFIG),
buildIntegrationConfigOptionRegistry(DEFAULT_CONFIG, RUNTIME_OPTION_REGISTRY),
buildImmersionConfigOptionRegistry(DEFAULT_CONFIG),
];
const composedPaths = new Set(CONFIG_OPTION_REGISTRY.map((entry) => entry.path));
for (const entries of domainEntries) {
assert.ok(entries.length > 0);
assert.ok(entries.some((entry) => composedPaths.has(entry.path)));
}
});
test('default keybindings include primary and secondary subtitle track cycling on J keys', () => {
const keybindingMap = new Map(
DEFAULT_KEYBINDINGS.map((binding) => [binding.key, binding.command]),
);
assert.deepEqual(keybindingMap.get('KeyJ'), ['cycle', 'sid']);
assert.deepEqual(keybindingMap.get('Shift+KeyJ'), ['cycle', 'secondary-sid']);
assert.deepEqual(keybindingMap.get('Ctrl+Alt+KeyC'), ['__youtube-picker-open']);
assert.deepEqual(keybindingMap.get('Ctrl+Alt+KeyP'), ['__playlist-browser-open']);
});
test('default keybindings include fullscreen on F', () => {
const keybindingMap = new Map(
DEFAULT_KEYBINDINGS.map((binding) => [binding.key, binding.command]),
);
assert.deepEqual(keybindingMap.get('KeyF'), ['cycle', 'fullscreen']);
});
test('default keybindings include replay and next subtitle controls', () => {
const keybindingMap = new Map(
DEFAULT_KEYBINDINGS.map((binding) => [binding.key, binding.command]),
);
assert.deepEqual(keybindingMap.get('Ctrl+Shift+KeyH'), ['__replay-subtitle']);
assert.deepEqual(keybindingMap.get('Ctrl+Shift+KeyL'), ['__play-next-subtitle']);
});
test('default keybindings mirror mpv subtitle delay and sub-step keys', () => {
const keybindingMap = new Map(
DEFAULT_KEYBINDINGS.map((binding) => [binding.key, binding.command]),
);
assert.deepEqual(keybindingMap.get('KeyZ'), ['add', 'sub-delay', -0.1]);
assert.deepEqual(keybindingMap.get('Shift+KeyZ'), ['add', 'sub-delay', 0.1]);
assert.deepEqual(keybindingMap.get('KeyX'), ['add', 'sub-delay', 0.1]);
assert.deepEqual(keybindingMap.get('Ctrl+Shift+ArrowLeft'), ['sub-step', -1]);
assert.deepEqual(keybindingMap.get('Ctrl+Shift+ArrowRight'), ['sub-step', 1]);
assert.equal(keybindingMap.has('Shift+BracketLeft'), false);
assert.equal(keybindingMap.has('Shift+BracketRight'), false);
});
+7
View File
@@ -81,6 +81,13 @@ export function buildCoreConfigOptionRegistry(
] as const; ] as const;
return [ return [
{
path: 'dictionaryBackend',
kind: 'enum',
enumValues: ['yomitan', 'hachidori'],
defaultValue: defaultConfig.dictionaryBackend,
description: 'Dictionary lookup backend. Restart SubMiner after changing this setting.',
},
{ {
path: 'logging.level', path: 'logging.level',
kind: 'enum', kind: 'enum',
@@ -1,6 +1,14 @@
import { ConfigTemplateSection } from './shared'; import { ConfigTemplateSection } from './shared';
const CORE_TEMPLATE_SECTIONS: ConfigTemplateSection[] = [ const CORE_TEMPLATE_SECTIONS: ConfigTemplateSection[] = [
{
title: 'Dictionary Backend',
description: ['Select the dictionary lookup backend: yomitan or hachidori.'],
notes: [
'Restart SubMiner after changing the backend. Each backend keeps separate settings and dictionaries.',
],
key: 'dictionaryBackend',
},
{ {
title: 'Subtitle Selection', title: 'Subtitle Selection',
description: ['Select primary and secondary mpv subtitle tracks from the overlay.'], description: ['Select primary and secondary mpv subtitle tracks from the overlay.'],
+11
View File
@@ -6,6 +6,17 @@ import { asBoolean, asNumber, asString, isObject } from './shared';
export function applyCoreDomainConfig(context: ResolveContext): void { export function applyCoreDomainConfig(context: ResolveContext): void {
const { src, resolved, warn } = context; const { src, resolved, warn } = context;
if (src.dictionaryBackend === 'yomitan' || src.dictionaryBackend === 'hachidori') {
resolved.dictionaryBackend = src.dictionaryBackend;
} else if (src.dictionaryBackend !== undefined) {
warn(
'dictionaryBackend',
src.dictionaryBackend,
resolved.dictionaryBackend,
"Expected 'yomitan' or 'hachidori'.",
);
}
if (isObject(src.subtitleSelection)) { if (isObject(src.subtitleSelection)) {
const enabled = asBoolean(src.subtitleSelection.enabled); const enabled = asBoolean(src.subtitleSelection.enabled);
if (enabled !== undefined) resolved.subtitleSelection.enabled = enabled; if (enabled !== undefined) resolved.subtitleSelection.enabled = enabled;
@@ -0,0 +1,30 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { resolveConfig } from '../resolve';
import { buildConfigSettingsRegistry } from '../settings/registry';
import { createResolveContext } from './context';
import { applyCoreDomainConfig } from './core-domains';
test('dictionary backend defaults to Yomitan and accepts Hachidori', () => {
assert.equal(resolveConfig({}).resolved.dictionaryBackend, 'yomitan');
const { resolved, warnings } = resolveConfig({ dictionaryBackend: 'hachidori' });
assert.equal(resolved.dictionaryBackend, 'hachidori');
assert.deepEqual(warnings, []);
const field = buildConfigSettingsRegistry(resolved).find(
(entry) => entry.configPath === 'dictionaryBackend',
);
assert.equal(field?.restartBehavior, 'restart');
assert.deepEqual(field?.enumValues, ['yomitan', 'hachidori']);
assert.equal(field?.category, 'integrations');
});
test('unknown dictionary backend values warn and preserve the default', () => {
for (const dictionaryBackend of ['unknown', '', null, true, {}]) {
const { context, warnings } = createResolveContext({});
context.src.dictionaryBackend = dictionaryBackend;
applyCoreDomainConfig(context);
assert.equal(context.resolved.dictionaryBackend, 'yomitan');
assert.equal(warnings.length, 1);
assert.equal(warnings[0]?.path, 'dictionaryBackend');
}
});
-301
View File
@@ -11,209 +11,6 @@ function field(path: string) {
return match; return match;
} }
test('settings registry splits viewing into appearance and behavior categories', () => {
assert.equal(field('subtitleStyle.fontSize').category, 'appearance');
assert.equal(field('subtitleStyle.primaryDefaultMode').category, 'behavior');
assert.equal(field('subtitleStyle.primaryDefaultMode').section, 'Subtitle Behavior');
assert.equal(field('subtitleStyle.primaryVisibleOnYomitanPopup').category, 'behavior');
assert.equal(field('subtitleStyle.primaryVisibleOnYomitanPopup').section, 'Subtitle Behavior');
assert.equal(field('secondarySub.defaultMode').category, 'behavior');
assert.equal(field('subtitlePosition.yPercent').label, 'Subtitle Position');
assert.equal(field('subtitleStyle.frequencyDictionary.mode').label, 'Frequency Mode');
assert.equal(field('auto_start_overlay').category, 'behavior');
assert.equal(field('auto_start_overlay').section, 'Playback Behavior');
assert.equal(field('youtube.primarySubLanguages').category, 'behavior');
assert.equal(field('youtube.primarySubLanguages').section, 'YouTube Playback Settings');
assert.equal(field('mpv.launchMode').category, 'behavior');
assert.equal(field('mpv.launchMode').section, 'mpv Playback');
assert.equal(field('mpv.profile').category, 'behavior');
assert.equal(field('mpv.profile').section, 'mpv Playback');
assert.ok(
fields.findIndex((candidate) => candidate.configPath === 'subtitleStyle.primaryDefaultMode') <
fields.findIndex(
(candidate) => candidate.configPath === 'subtitleStyle.primaryVisibleOnYomitanPopup',
),
);
assert.ok(
fields.findIndex(
(candidate) => candidate.configPath === 'subtitleStyle.primaryVisibleOnYomitanPopup',
) < fields.findIndex((candidate) => candidate.configPath === 'secondarySub.defaultMode'),
);
});
test('settings registry groups playback startup controls under playback behavior', () => {
for (const path of [
'subtitleStyle.autoPauseVideoOnHover',
'subtitleStyle.autoPauseVideoOnYomitanPopup',
'subtitleSidebar.pauseVideoOnHover',
'mpv.autoStartSubMiner',
'auto_start_overlay',
'mpv.pauseUntilOverlayReady',
]) {
assert.equal(field(path).category, 'behavior', path);
assert.equal(field(path).section, 'Playback Behavior', path);
}
});
test('settings registry moves AniSkip button key into input shortcuts and hot reload', () => {
assert.equal(field('mpv.aniskipButtonKey').category, 'input');
assert.equal(field('mpv.aniskipButtonKey').section, 'Overlay Shortcuts');
assert.equal(field('mpv.aniskipButtonKey').subsection, 'Playback');
assert.equal(field('mpv.aniskipButtonKey').control, 'mpv-key');
assert.equal(field('mpv.aniskipButtonKey').restartBehavior, 'hot-reload');
});
test('settings registry exposes character dictionary panel shortcuts dynamically', () => {
assert.equal(
field('shortcuts.openCharacterDictionaryManager').label,
'Open Character Dictionary Manager',
);
assert.equal(field('shortcuts.openCharacterDictionaryManager').subsection, 'Open Panels');
});
test('settings registry hides removed modal-only fields', () => {
for (const path of [
'shortcuts.multiCopyTimeoutMs',
'anilist.characterDictionary.profileScope',
'jellyfin.directPlayContainers',
]) {
assert.equal(
fields.some((candidate) => candidate.configPath === path),
false,
path,
);
}
});
test('settings registry orders websocket server immediately after annotation websocket', () => {
const integrationSections = [
...new Set(
fields
.filter((candidate) => candidate.category === 'integrations')
.map((candidate) => candidate.section),
),
];
const annotationIndex = integrationSections.indexOf('Annotation WebSocket');
assert.equal(integrationSections[annotationIndex + 1], 'WebSocket server');
});
test('settings registry explains websocket auto mode and keeps it disabled by default', () => {
assert.equal(field('websocket.enabled').defaultValue, false);
assert.equal(
field('websocket.enabled').description,
'Built-in subtitle WebSocket server mode. Auto starts the built-in server only when mpv_websocket is not detected; otherwise it defers to the plugin.',
);
});
test('settings registry places immersion tracking after other tracking and app sections', () => {
const trackingSections = [
...new Set(
fields
.filter((candidate) => candidate.category === 'tracking-app')
.map((candidate) => candidate.section),
),
];
assert.equal(trackingSections.at(-1), 'Immersion tracking');
});
test('settings registry groups annotation display fields by config group', () => {
assert.equal(field('ankiConnect.knownWords.highlightEnabled').section, 'Annotation Display');
assert.equal(field('ankiConnect.knownWords.highlightEnabled').subsection, 'Known Words');
assert.equal(field('subtitleStyle.knownWordColor').subsection, 'Known Words');
assert.equal(field('subtitleStyle.nPlusOneColor').subsection, 'N+1');
assert.equal(field('subtitleStyle.enableJlpt').subsection, 'JLPT');
assert.equal(field('subtitleStyle.jlptColors.N1').control, 'color');
});
test('settings registry groups maturity settings under Known Words with color controls', () => {
assert.equal(field('ankiConnect.knownWords.maturityEnabled').subsection, 'Known Words');
assert.equal(field('ankiConnect.knownWords.matureThresholdDays').subsection, 'Known Words');
for (const tier of ['new', 'learning', 'young', 'mature']) {
const tierField = field(`subtitleStyle.knownWordMaturityColors.${tier}`);
assert.equal(tierField.subsection, 'Known Words');
assert.equal(tierField.control, 'color');
}
});
test('settings registry orders maturity colors from least mature to mature', () => {
const knownWordsPaths = fields
.filter((candidate) => candidate.subsection === 'Known Words')
.map((candidate) => candidate.configPath);
assert.deepEqual(knownWordsPaths, [
'ankiConnect.knownWords.highlightEnabled',
'ankiConnect.knownWords.maturityEnabled',
'subtitleStyle.knownWordColor',
'ankiConnect.knownWords.matureThresholdDays',
'subtitleStyle.knownWordMaturityColors.new',
'subtitleStyle.knownWordMaturityColors.learning',
'subtitleStyle.knownWordMaturityColors.young',
'subtitleStyle.knownWordMaturityColors.mature',
]);
});
test('settings registry routes known words sync, n+1, and frequency config to behavior', () => {
assert.equal(field('ankiConnect.knownWords.addMinedWordsImmediately').category, 'behavior');
assert.equal(field('ankiConnect.knownWords.addMinedWordsImmediately').section, 'Known Words');
assert.equal(field('ankiConnect.knownWords.decks').category, 'behavior');
assert.equal(field('ankiConnect.knownWords.decks').section, 'Known Words');
assert.equal(field('ankiConnect.knownWords.matchMode').category, 'behavior');
assert.equal(field('ankiConnect.knownWords.matchMode').section, 'Known Words');
assert.equal(field('ankiConnect.knownWords.refreshMinutes').category, 'behavior');
assert.equal(field('ankiConnect.knownWords.refreshMinutes').section, 'Known Words');
assert.equal(field('ankiConnect.nPlusOne.minSentenceWords').category, 'behavior');
assert.equal(field('ankiConnect.nPlusOne.minSentenceWords').section, 'N+1');
assert.equal(field('subtitleStyle.frequencyDictionary.sourcePath').category, 'behavior');
assert.equal(
field('subtitleStyle.frequencyDictionary.sourcePath').section,
'Frequency Highlighting',
);
assert.equal(field('subtitleStyle.frequencyDictionary.mode').category, 'behavior');
assert.equal(field('subtitleStyle.frequencyDictionary.matchMode').category, 'behavior');
assert.equal(field('subtitleStyle.frequencyDictionary.topX').category, 'behavior');
});
test('settings registry exposes mpv aniskip button as an mpv key learn control', () => {
assert.equal(field('mpv.aniskipButtonKey').control, 'mpv-key');
});
test('settings registry exposes specialized controls for config-assisted inputs', () => {
assert.equal(field('ankiConnect.deck').control, 'anki-deck');
assert.equal(field('ankiConnect.knownWords.decks').control, 'known-words-decks');
assert.equal(field('ankiConnect.isLapis.sentenceCardModel').control, 'anki-note-type');
assert.equal(field('ankiConnect.fields.word').control, 'anki-field');
assert.equal(field('keybindings').control, 'mpv-keybindings');
assert.equal(field('subtitleStyle.css').control, 'css-declarations');
assert.equal(field('subtitleStyle.secondary.css').control, 'css-declarations');
assert.equal(field('shortcuts.copySubtitle').control, 'keyboard-shortcut');
assert.equal(field('mpv.aniskipButtonKey').control, 'mpv-key');
assert.equal(field('subtitleSidebar.css').control, 'css-declarations');
assert.equal(field('stats.toggleKey').control, 'key-code');
assert.equal(field('discordPresence.presenceStyle').control, 'select');
});
test('settings registry exposes mpv volume mirroring as a mining toggle', () => {
const volumeField = field('ankiConnect.media.mirrorMpvVolume');
assert.equal(volumeField.category, 'mining-anki');
assert.equal(volumeField.section, 'Media Capture');
assert.equal(volumeField.control, 'boolean');
assert.equal(volumeField.defaultValue, true);
});
test('settings registry exposes YouTube media cache mode as a labeled select', () => {
const mediaCacheMode = field('youtube.mediaCache.mode');
const mediaCacheMaxHeight = field('youtube.mediaCache.maxHeight');
assert.equal(mediaCacheMode.control, 'select');
assert.deepEqual(mediaCacheMode.enumValues, ['direct', 'background']);
assert.deepEqual(mediaCacheMode.enumLabels, {
direct: 'Direct stream extraction',
background: 'Background media cache',
});
assert.equal(mediaCacheMaxHeight.control, 'number');
assert.equal(mediaCacheMaxHeight.defaultValue, 720);
});
test('settings registry exposes css declaration editor for primary and secondary subtitle appearance', () => { test('settings registry exposes css declaration editor for primary and secondary subtitle appearance', () => {
const primaryVisible = fields const primaryVisible = fields
.filter( .filter(
@@ -268,18 +65,6 @@ test('settings registry exposes css declaration editor for subtitle sidebar appe
assert.equal(field('subtitleSidebar.layout').settingsHidden, false); assert.equal(field('subtitleSidebar.layout').settingsHidden, false);
}); });
test('settings registry routes playback-related integrations into integrations', () => {
assert.equal(field('jimaku.apiBaseUrl').category, 'integrations');
assert.equal(field('jimaku.apiBaseUrl').section, 'Jimaku');
assert.equal(field('subsync.replace').category, 'integrations');
assert.equal(field('subsync.replace').section, 'Subtitle Sync');
assert.equal(field('tsukihime.apiBaseUrl').category, 'integrations');
assert.equal(field('tsukihime.apiBaseUrl').section, 'TsukiHime');
assert.equal(field('tmdb.apiKey').category, 'integrations');
assert.equal(field('tmdb.apiKey').section, 'TMDB');
assert.equal(field('tmdb.apiKey').secret, true);
});
test('settings registry puts feature toggles first, then other toggles alphabetically', () => { test('settings registry puts feature toggles first, then other toggles alphabetically', () => {
const ankiConnect = fields.filter((candidate) => candidate.section === 'AnkiConnect'); const ankiConnect = fields.filter((candidate) => candidate.section === 'AnkiConnect');
assert.equal(ankiConnect[0]?.configPath, 'ankiConnect.enabled'); assert.equal(ankiConnect[0]?.configPath, 'ankiConnect.enabled');
@@ -309,89 +94,3 @@ test('settings registry puts feature toggles first, then other toggles alphabeti
['ankiConnect.isLapis.enabled', 'ankiConnect.isKiku.enabled', 'ankiConnect.isSenren.enabled'], ['ankiConnect.isLapis.enabled', 'ankiConnect.isKiku.enabled', 'ankiConnect.isSenren.enabled'],
); );
}); });
test('settings registry hides app-managed and inactive config surfaces', () => {
const paths = new Set(fields.map((candidate) => candidate.configPath));
for (const hiddenPath of [
'ai.enabled',
'ai.apiKey',
'ai.apiKeyCommand',
'ai.model',
'ai.baseUrl',
'ai.systemPrompt',
'ai.requestTimeoutMs',
'ankiConnect.ai.enabled',
'ankiConnect.ai.model',
'ankiConnect.ai.systemPrompt',
'ankiConnect.fields.translation',
'controller.bindings',
'controller.preferredGamepadId',
'controller.preferredGamepadLabel',
'controller.profiles',
'jellyfin.defaultLibraryId',
'subtitleSidebar.toggleKey',
'jellyfin.recentServers',
]) {
assert.equal(paths.has(hiddenPath), false, `${hiddenPath} should be hidden`);
}
assert.equal(paths.has('anilist.characterDictionary.enabled'), false);
});
test('settings registry marks safe live config paths as hot-reloadable', () => {
for (const path of [
'mpv.aniskipButtonKey',
'stats.toggleKey',
'stats.markWatchedKey',
'logging.level',
'logging.rotation',
'logging.files.app',
'logging.files.launcher',
'logging.files.mpv',
'youtube.primarySubLanguages',
'jimaku.apiBaseUrl',
'jimaku.languagePreference',
'jimaku.maxEntryResults',
'subsync.replace',
'ankiConnect.behavior.autoUpdateNewCards',
'ankiConnect.deck',
'ankiConnect.media.normalizeAudio',
'ankiConnect.media.mirrorMpvVolume',
'ankiConnect.media.reviewTiming',
'ankiConnect.knownWords.highlightEnabled',
'ankiConnect.knownWords.refreshMinutes',
'ankiConnect.knownWords.addMinedWordsImmediately',
'ankiConnect.knownWords.matchMode',
'ankiConnect.knownWords.decks',
'ankiConnect.nPlusOne.enabled',
'ankiConnect.nPlusOne.minSentenceWords',
'ankiConnect.fields.word',
'ankiConnect.fields.audio',
'ankiConnect.fields.wordAudio',
'ankiConnect.fields.image',
'ankiConnect.fields.sentence',
'ankiConnect.fields.miscInfo',
'ankiConnect.isLapis.sentenceCardModel',
'ankiConnect.isKiku.fieldGrouping',
'ankiConnect.isSenren.fieldGrouping',
]) {
assert.equal(field(path).restartBehavior, 'hot-reload', path);
}
});
test('settings registry does not expose removed subsync mode option', () => {
const paths = new Set(fields.map((candidate) => candidate.configPath));
assert.equal(paths.has('subsync.defaultMode'), false);
});
test('settings registry keeps unsafe config siblings restart-required', () => {
for (const path of [
'stats.serverPort',
'ankiConnect.url',
'ankiConnect.proxy.enabled',
'mpv.socketPath',
'mpv.profile',
'websocket.port',
]) {
assert.equal(field(path).restartBehavior, 'restart', path);
}
});
+7 -3
View File
@@ -146,6 +146,7 @@ const SECTION_ORDER = new Map<string, number>(
'Discord Rich Presence', 'Discord Rich Presence',
'Jellyfin', 'Jellyfin',
'Texthooker', 'Texthooker',
'Dictionary Lookup',
'Yomitan', 'Yomitan',
'Stats dashboard', 'Stats dashboard',
'Startup warmups', 'Startup warmups',
@@ -228,8 +229,8 @@ const LABEL_OVERRIDES: Record<string, string> = {
'shortcuts.openCharacterDictionaryManager': 'Open Character Dictionary Manager', 'shortcuts.openCharacterDictionaryManager': 'Open Character Dictionary Manager',
'subtitleSidebar.pauseVideoOnHover': 'Pause Video On Hover - Sidebar', 'subtitleSidebar.pauseVideoOnHover': 'Pause Video On Hover - Sidebar',
'subtitleStyle.autoPauseVideoOnHover': 'Pause Video On Hover - Subtitles', 'subtitleStyle.autoPauseVideoOnHover': 'Pause Video On Hover - Subtitles',
'subtitleStyle.autoPauseVideoOnYomitanPopup': 'Pause Video On Yomitan Popup', 'subtitleStyle.autoPauseVideoOnYomitanPopup': 'Pause Video On Dictionary Popup',
'subtitleStyle.primaryVisibleOnYomitanPopup': 'Keep Primary Visible On Yomitan Popup', 'subtitleStyle.primaryVisibleOnYomitanPopup': 'Keep Primary Visible On Dictionary Popup',
'subtitleStyle.primaryDefaultMode': 'Primary Subtitle Visibility Mode', 'subtitleStyle.primaryDefaultMode': 'Primary Subtitle Visibility Mode',
'subtitleStyle.frequencyDictionary.mode': 'Frequency Mode', 'subtitleStyle.frequencyDictionary.mode': 'Frequency Mode',
'subtitleStyle.css': 'CSS Declarations', 'subtitleStyle.css': 'CSS Declarations',
@@ -270,7 +271,7 @@ const DESCRIPTION_OVERRIDES: Record<string, string> = {
'subtitleSidebar.css': 'subtitleSidebar.css':
'CSS declarations applied to the subtitle sidebar. Includes color, background-color, all font properties, and sidebar CSS variables.', 'CSS declarations applied to the subtitle sidebar. Includes color, background-color, all font properties, and sidebar CSS variables.',
'subtitleStyle.primaryVisibleOnYomitanPopup': 'subtitleStyle.primaryVisibleOnYomitanPopup':
'When primary subtitles are in hover mode, keep the primary subtitle bar visible while a Yomitan popup is open.', 'When primary subtitles are in hover mode, keep the primary subtitle bar visible while a dictionary popup is open.',
'websocket.enabled': 'websocket.enabled':
'Built-in subtitle WebSocket server mode. Auto starts the built-in server only when mpv_websocket is not detected; otherwise it defers to the plugin.', 'Built-in subtitle WebSocket server mode. Auto starts the built-in server only when mpv_websocket is not detected; otherwise it defers to the plugin.',
'discordPresence.updateIntervalMs': 'discordPresence.updateIntervalMs':
@@ -334,6 +335,9 @@ function humanizePath(path: string): string {
} }
function categoryAndSection(path: string): { category: ConfigSettingsCategory; section: string } { function categoryAndSection(path: string): { category: ConfigSettingsCategory; section: string } {
if (path === 'dictionaryBackend' || path.startsWith('hachidori.')) {
return { category: 'integrations', section: 'Dictionary Lookup' };
}
if ( if (
path === 'subtitleStyle.autoPauseVideoOnHover' || path === 'subtitleStyle.autoPauseVideoOnHover' ||
path === 'subtitleStyle.autoPauseVideoOnYomitanPopup' || path === 'subtitleStyle.autoPauseVideoOnYomitanPopup' ||
@@ -5,30 +5,6 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import type { DatabaseSync } from '../immersion-tracker/sqlite'; import type { DatabaseSync } from '../immersion-tracker/sqlite';
type ImmersionTrackerService = import('../immersion-tracker-service').ImmersionTrackerService;
type ImmersionTrackerServiceCtor =
typeof import('../immersion-tracker-service').ImmersionTrackerService;
let trackerCtor: ImmersionTrackerServiceCtor | null = null;
async function loadTrackerCtor(): Promise<ImmersionTrackerServiceCtor> {
if (trackerCtor) return trackerCtor;
const mod = await import('../immersion-tracker-service');
trackerCtor = mod.ImmersionTrackerService;
return trackerCtor;
}
function makeDbPath(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-write-queue-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 });
}
interface TrackerInternals { interface TrackerInternals {
db: DatabaseSync; db: DatabaseSync;
queue: unknown[]; queue: unknown[];
@@ -42,155 +18,38 @@ interface TrackerInternals {
writeLock: { locked: boolean }; writeLock: { locked: boolean };
} }
test('delete maintenance fails closed when queued writes cannot drain', async () => { interface TrackerHarness {
const dbPath = makeDbPath(); tracker: TrackerInternals;
let tracker: ImmersionTrackerService | null = null; deleteRunnerCalls: () => number;
}
/** Runs `fn` against a fresh tracker (batchSize 2) seeded with two library entries. */
async function withTracker(fn: (harness: TrackerHarness) => Promise<void>): Promise<void> {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-write-queue-test-'));
const { ImmersionTrackerService } = await import('../immersion-tracker-service');
let deleteRunnerCalls = 0; let deleteRunnerCalls = 0;
const service = new ImmersionTrackerService(
try { { dbPath: path.join(dir, 'immersion.sqlite'), policy: { batchSize: 2 } },
const Ctor = await loadTrackerCtor(); {
tracker = new Ctor( runDeleteMaintenanceTask: async () => {
{ dbPath, policy: { batchSize: 2 } }, deleteRunnerCalls += 1;
{
runDeleteMaintenanceTask: async () => {
deleteRunnerCalls += 1;
},
}, },
); },
const internals = tracker as unknown as TrackerInternals; );
seedTwoEntries(internals.db);
queueSubtitleLines(internals, 1);
let flushCalls = 0;
internals.flushNow = () => {
flushCalls += 1;
if (flushCalls > 1) throw new Error('bounded no-progress sentinel');
};
await assert.rejects(internals.deleteSession(1), /queue did not drain/i);
assert.equal(flushCalls, 1);
assert.equal(deleteRunnerCalls, 0);
assert.equal(internals.writeLock.locked, false);
} finally {
tracker?.destroy();
cleanupDbPath(dbPath);
}
});
test('reassignAnimeAnilist fails closed before resolving a conflict when writes cannot drain', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
try { try {
const Ctor = await loadTrackerCtor(); const tracker = service as unknown as TrackerInternals;
tracker = new Ctor({ dbPath, policy: { batchSize: 2 } }); seedTwoEntries(tracker.db);
const internals = tracker as unknown as TrackerInternals; await fn({ tracker, deleteRunnerCalls: () => deleteRunnerCalls });
seedTwoEntries(internals.db);
internals.db.prepare('UPDATE imm_anime SET anilist_id = 123 WHERE anime_id = 2').run();
queueSubtitleLines(internals, 1);
internals.flushNow = () => {};
await assert.rejects(
internals.reassignAnimeAnilist(1, { anilistId: 123 }),
/queue did not drain/i,
);
assert.deepEqual(
internals.db
.prepare(
'SELECT anime_id AS animeId, anilist_id AS anilistId FROM imm_anime ORDER BY anime_id',
)
.all(),
[
{ animeId: 1, anilistId: null },
{ animeId: 2, anilistId: 123 },
],
);
} finally { } finally {
tracker?.destroy(); service.destroy();
cleanupDbPath(dbPath); fs.rmSync(dir, { recursive: true, force: true });
} }
}); }
test('mergeAnime fails closed when queued writes cannot drain', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
try {
const Ctor = await loadTrackerCtor();
tracker = new Ctor({ dbPath, policy: { batchSize: 2 } });
const internals = tracker as unknown as TrackerInternals;
seedTwoEntries(internals.db);
queueSubtitleLines(internals, 1);
internals.flushNow = () => {};
await assert.rejects(internals.mergeAnime(1, [2]), /queue did not drain/i);
assert.deepEqual(
internals.db
.prepare('SELECT anime_id AS animeId FROM imm_anime ORDER BY anime_id')
.all()
.map((row) => (row as { animeId: number }).animeId),
[1, 2],
);
} finally {
tracker?.destroy();
cleanupDbPath(dbPath);
}
});
test('moveVideoToAnime fails closed when queued writes cannot drain', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
try {
const Ctor = await loadTrackerCtor();
tracker = new Ctor({ dbPath, policy: { batchSize: 2 } });
const internals = tracker as unknown as TrackerInternals;
seedTwoEntries(internals.db);
queueSubtitleLines(internals, 1);
internals.flushNow = () => {};
await assert.rejects(internals.moveVideoToAnime(2, 1), /queue did not drain/i);
assert.equal(
(
internals.db
.prepare('SELECT anime_id AS animeId FROM imm_videos WHERE video_id = 2')
.get() as {
animeId: number;
}
).animeId,
2,
);
} finally {
tracker?.destroy();
cleanupDbPath(dbPath);
}
});
test('rebuildLifetimeSummaries fails closed when queued writes cannot drain', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
try {
const Ctor = await loadTrackerCtor();
tracker = new Ctor({ dbPath, policy: { batchSize: 2 } });
const internals = tracker as unknown as TrackerInternals;
seedTwoEntries(internals.db);
queueSubtitleLines(internals, 1);
internals.flushNow = () => {};
await assert.rejects(internals.rebuildLifetimeSummaries(), /queue did not drain/i);
} finally {
tracker?.destroy();
cleanupDbPath(dbPath);
}
});
function seedTwoEntries(db: DatabaseSync): void { function seedTwoEntries(db: DatabaseSync): void {
db.exec(` db.exec(`
INSERT INTO imm_anime (anime_id, normalized_title_key, canonical_title, CREATED_DATE, LAST_UPDATE_DATE) INSERT INTO imm_anime (anime_id, normalized_title_key, canonical_title, anilist_id, CREATED_DATE, LAST_UPDATE_DATE)
VALUES (1, 'show', 'Show', 1000, 1000), (2, 'show season 1', 'Show Season 1', 1000, 1000); VALUES (1, 'show', 'Show', NULL, 1000, 1000), (2, 'show season 1', 'Show Season 1', 123, 1000, 1000);
INSERT INTO imm_videos (video_id, video_key, canonical_title, anime_id, source_type, watched, duration_ms, CREATED_DATE, LAST_UPDATE_DATE) INSERT INTO imm_videos (video_id, video_key, canonical_title, anime_id, source_type, watched, duration_ms, CREATED_DATE, LAST_UPDATE_DATE)
VALUES (1, 'local:/tmp/a.mkv', 'A', 1, 1, 0, 1440000, 1000, 1000), VALUES (1, 'local:/tmp/a.mkv', 'A', 1, 1, 0, 1440000, 1000, 1000),
(2, 'local:/tmp/b.mkv', 'B', 2, 1, 0, 1440000, 1000, 1000); (2, 'local:/tmp/b.mkv', 'B', 2, 1, 0, 1440000, 1000, 1000);
@@ -244,25 +103,53 @@ function queueTelemetry(tracker: TrackerInternals, linesSeen: number): void {
}); });
} }
/** The queued telemetry sample only exists in the database once the queue drained fully. */ const SNAPSHOT_TABLES = [
function latestTelemetryLinesSeen(db: DatabaseSync, sessionId: number): number | null { 'imm_anime',
const row = db 'imm_videos',
.prepare( 'imm_sessions',
`SELECT lines_seen AS linesSeen 'imm_subtitle_lines',
FROM imm_session_telemetry 'imm_session_telemetry',
WHERE session_id = ? 'imm_lifetime_global',
ORDER BY sample_ms DESC, telemetry_id DESC 'imm_lifetime_anime',
LIMIT 1`, 'imm_lifetime_media',
) 'imm_lifetime_applied_sessions',
.get(sessionId) as { linesSeen: number } | undefined; ];
return row ? Number(row.linesSeen) : null;
function snapshotDb(db: DatabaseSync): Record<string, unknown[]> {
return Object.fromEntries(
SNAPSHOT_TABLES.map((table) => [table, db.prepare(`SELECT * FROM ${table} ORDER BY 1`).all()]),
);
} }
function countLinesForAnime(db: DatabaseSync, animeId: number): number { const guardedOperations: Array<{
const row = db name: string;
.prepare('SELECT COUNT(*) AS total FROM imm_subtitle_lines WHERE anime_id = ?') run: (tracker: TrackerInternals) => Promise<unknown>;
.get(animeId) as { total: number }; }> = [
return Number(row.total); { name: 'deleteSession', run: (tracker) => tracker.deleteSession(1) },
{ name: 'mergeAnime', run: (tracker) => tracker.mergeAnime(1, [2]) },
{ name: 'moveVideoToAnime', run: (tracker) => tracker.moveVideoToAnime(2, 1) },
{ name: 'rebuildLifetimeSummaries', run: (tracker) => tracker.rebuildLifetimeSummaries() },
{
// Anime 2 already owns AniList id 123, so this would otherwise resolve a conflict.
name: 'reassignAnimeAnilist',
run: (tracker) => tracker.reassignAnimeAnilist(1, { anilistId: 123 }),
},
];
for (const operation of guardedOperations) {
test(`${operation.name} fails closed without touching the database when queued writes cannot drain`, async () => {
await withTracker(async ({ tracker, deleteRunnerCalls }) => {
queueSubtitleLines(tracker, 1);
tracker.flushNow = () => {};
const before = snapshotDb(tracker.db);
await assert.rejects(operation.run(tracker), /queue did not drain/i);
assert.deepEqual(snapshotDb(tracker.db), before);
assert.equal(deleteRunnerCalls(), 0);
assert.equal(tracker.writeLock.locked, false);
});
});
} }
/** /**
@@ -271,52 +158,36 @@ function countLinesForAnime(db: DatabaseSync, animeId: number): number {
* queue, so anything past `batchSize` would still be unwritten when the merge * queue, so anything past `batchSize` would still be unwritten when the merge
* repoints rows. * repoints rows.
*/ */
test('mergeAnime drains a queue larger than one batch before repointing rows', async () => { const repointingOperations: Array<{
const dbPath = makeDbPath(); name: string;
let tracker: ImmersionTrackerService | null = null; run: (tracker: TrackerInternals) => Promise<unknown>;
}> = [
{ name: 'mergeAnime', run: (tracker) => tracker.mergeAnime(1, [2]) },
{ name: 'moveVideoToAnime', run: (tracker) => tracker.moveVideoToAnime(2, 1) },
];
try { for (const operation of repointingOperations) {
const Ctor = await loadTrackerCtor(); test(`${operation.name} drains a queue larger than one batch before repointing rows`, async () => {
tracker = new Ctor({ dbPath, policy: { batchSize: 2 } }); await withTracker(async ({ tracker }) => {
const internals = tracker as unknown as TrackerInternals; queueSubtitleLines(tracker, 8);
queueTelemetry(tracker, 8);
assert.ok(tracker.queue.length > 2, 'expected more queued writes than one batch');
seedTwoEntries(internals.db); await operation.run(tracker);
queueSubtitleLines(internals, 8);
queueTelemetry(internals, 8);
assert.ok(internals.queue.length > 2, 'expected more queued writes than one batch');
await internals.mergeAnime(1, [2]); assert.equal(tracker.queue.length, 0);
// Every queued line and the trailing telemetry sample landed on the surviving entry.
assert.equal(internals.queue.length, 0); const lines = tracker.db
// Every queued line landed, attributed to the surviving entry. .prepare('SELECT COUNT(*) AS total FROM imm_subtitle_lines WHERE anime_id = 1')
assert.equal(countLinesForAnime(internals.db, 1), 8); .get() as { total: number };
assert.equal(latestTelemetryLinesSeen(internals.db, 1), 8); assert.equal(Number(lines.total), 8);
} finally { const telemetry = tracker.db
tracker?.destroy(); .prepare(
cleanupDbPath(dbPath); `SELECT lines_seen AS linesSeen FROM imm_session_telemetry
} WHERE session_id = 1 ORDER BY sample_ms DESC, telemetry_id DESC LIMIT 1`,
}); )
.get() as { linesSeen: number } | undefined;
test('moveVideoToAnime drains a queue larger than one batch before repointing rows', async () => { assert.equal(Number(telemetry?.linesSeen), 8);
const dbPath = makeDbPath(); });
let tracker: ImmersionTrackerService | null = null; });
}
try {
const Ctor = await loadTrackerCtor();
tracker = new Ctor({ dbPath, policy: { batchSize: 2 } });
const internals = tracker as unknown as TrackerInternals;
seedTwoEntries(internals.db);
queueSubtitleLines(internals, 8);
queueTelemetry(internals, 8);
await internals.moveVideoToAnime(2, 1);
assert.equal(internals.queue.length, 0);
assert.equal(countLinesForAnime(internals.db, 1), 8);
assert.equal(latestTelemetryLinesSeen(internals.db, 1), 8);
} finally {
tracker?.destroy();
cleanupDbPath(dbPath);
}
});
@@ -1,23 +0,0 @@
import assert from 'node:assert/strict';
import { describe, test } from 'node:test';
import {
registerStatsAnalyticsRoutes,
registerStatsIntegrationRoutes,
registerStatsLibraryRoutes,
registerStatsMiningRoutes,
registerStatsStaticRoutes,
} from '../stats-server/routes.js';
describe('stats server route groups', () => {
test('exposes focused registrars for createStatsApp composition', () => {
for (const registrar of [
registerStatsAnalyticsRoutes,
registerStatsLibraryRoutes,
registerStatsIntegrationRoutes,
registerStatsMiningRoutes,
registerStatsStaticRoutes,
]) {
assert.equal(typeof registrar, 'function');
}
});
});
File diff suppressed because it is too large. Load diff
@@ -6,6 +6,7 @@ import test from 'node:test';
import { createCoverArtFetcher, stripFilenameTags } from './cover-art-fetcher.js'; import { createCoverArtFetcher, stripFilenameTags } from './cover-art-fetcher.js';
import { Database } from '../immersion-tracker/sqlite.js'; import { Database } from '../immersion-tracker/sqlite.js';
import { import {
applyPragmas,
ensureSchema, ensureSchema,
getOrCreateAnimeRecord, getOrCreateAnimeRecord,
getOrCreateVideoRecord, getOrCreateVideoRecord,
@@ -50,6 +51,7 @@ test('stripFilenameTags normalizes common media-title formats', () => {
async function backfillMissingCoverBlob(): Promise<void> { async function backfillMissingCoverBlob(): Promise<void> {
const dbPath = makeDbPath(); const dbPath = makeDbPath();
const db = new Database(dbPath); const db = new Database(dbPath);
applyPragmas(db);
ensureSchema(db); ensureSchema(db);
const videoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-test.mkv', { const videoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-test.mkv', {
canonicalTitle: 'Cover Fetcher Test', canonicalTitle: 'Cover Fetcher Test',
@@ -114,6 +116,7 @@ test(
async function reuseCachedAnimeCoverArt(): Promise<void> { async function reuseCachedAnimeCoverArt(): Promise<void> {
const dbPath = makeDbPath(); const dbPath = makeDbPath();
const db = new Database(dbPath); const db = new Database(dbPath);
applyPragmas(db);
ensureSchema(db); ensureSchema(db);
const firstVideoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-cache-1.mkv', { const firstVideoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-cache-1.mkv', {
canonicalTitle: 'Shared Cover Show', canonicalTitle: 'Shared Cover Show',
@@ -203,6 +206,7 @@ function createJsonResponse(payload: unknown): Response {
test('fetchIfMissing uses guessit primary title and season when available', async () => { test('fetchIfMissing uses guessit primary title and season when available', async () => {
const dbPath = makeDbPath(); const dbPath = makeDbPath();
const db = new Database(dbPath); const db = new Database(dbPath);
applyPragmas(db);
ensureSchema(db); ensureSchema(db);
const videoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-season-test.mkv', { const videoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-season-test.mkv', {
canonicalTitle: canonicalTitle:
@@ -308,6 +312,7 @@ test('fetchIfMissing uses guessit primary title and season when available', asyn
test('fetchIfMissing falls back to internal parser when guessit throws', async () => { test('fetchIfMissing falls back to internal parser when guessit throws', async () => {
const dbPath = makeDbPath(); const dbPath = makeDbPath();
const db = new Database(dbPath); const db = new Database(dbPath);
applyPragmas(db);
ensureSchema(db); ensureSchema(db);
const videoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-fallback-test.mkv', { const videoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-fallback-test.mkv', {
canonicalTitle: 'School Vlog S01E01', canonicalTitle: 'School Vlog S01E01',
@@ -372,6 +377,7 @@ test('fetchIfMissing falls back to internal parser when guessit throws', async (
test('fetchIfMissing caches a no-match when the season cannot be resolved', async () => { test('fetchIfMissing caches a no-match when the season cannot be resolved', async () => {
const dbPath = makeDbPath(); const dbPath = makeDbPath();
const db = new Database(dbPath); const db = new Database(dbPath);
applyPragmas(db);
ensureSchema(db); ensureSchema(db);
const videoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-unresolved.mkv', { const videoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-unresolved.mkv', {
canonicalTitle: 'Unresolved Show (2013) - S03E01 - Something [1080p].mkv', canonicalTitle: 'Unresolved Show (2013) - S03E01 - Something [1080p].mkv',
@@ -450,6 +456,7 @@ test('fetchIfMissing caches a no-match when the season cannot be resolved', asyn
test('fetchIfMissing re-resolves an unresolved season once AniList publishes the relation', async () => { test('fetchIfMissing re-resolves an unresolved season once AniList publishes the relation', async () => {
const dbPath = makeDbPath(); const dbPath = makeDbPath();
const db = new Database(dbPath); const db = new Database(dbPath);
applyPragmas(db);
ensureSchema(db); ensureSchema(db);
const videoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-recovers.mkv', { const videoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-recovers.mkv', {
canonicalTitle: 'Recovering Show (2013) - S02E01 - Something [1080p].mkv', canonicalTitle: 'Recovering Show (2013) - S02E01 - Something [1080p].mkv',
@@ -557,6 +564,7 @@ for (const linkedToAnilist of [false, true]) {
test(`TMDB fallback preserves AniList identity when linked=${linkedToAnilist}`, async () => { test(`TMDB fallback preserves AniList identity when linked=${linkedToAnilist}`, async () => {
const dbPath = makeDbPath(); const dbPath = makeDbPath();
const db = new Database(dbPath); const db = new Database(dbPath);
applyPragmas(db);
ensureSchema(db); ensureSchema(db);
const videoId = getOrCreateVideoRecord(db, 'local:/tmp/hanzawa-01.mkv', { const videoId = getOrCreateVideoRecord(db, 'local:/tmp/hanzawa-01.mkv', {
canonicalTitle: 'Hanzawa Naoki - 01.mkv', canonicalTitle: 'Hanzawa Naoki - 01.mkv',
@@ -674,6 +682,7 @@ for (const linkedToAnilist of [false, true]) {
test('fetchIfMissing skips AniList for an entry already linked to TMDB', async () => { test('fetchIfMissing skips AniList for an entry already linked to TMDB', async () => {
const dbPath = makeDbPath(); const dbPath = makeDbPath();
const db = new Database(dbPath); const db = new Database(dbPath);
applyPragmas(db);
ensureSchema(db); ensureSchema(db);
const videoId = getOrCreateVideoRecord(db, 'local:/tmp/hanzawa-02.mkv', { const videoId = getOrCreateVideoRecord(db, 'local:/tmp/hanzawa-02.mkv', {
canonicalTitle: 'Hanzawa Naoki - 02.mkv', canonicalTitle: 'Hanzawa Naoki - 02.mkv',
-65
View File
@@ -158,33 +158,6 @@ function createHarness(): RuntimeHarness {
return { options, registered, state }; return { options, registered, state };
} }
test('registerAnkiJimakuIpcRuntime provides full handler surface', () => {
const { registered } = createHarness();
const expected = [
'setAnkiConnectEnabled',
'clearAnkiHistory',
'refreshKnownWords',
'respondFieldGrouping',
'buildKikuMergePreview',
'getJimakuMediaInfo',
'searchJimakuEntries',
'listJimakuFiles',
'resolveJimakuApiKey',
'getCurrentMediaPath',
'isRemoteMediaPath',
'downloadToFile',
'onDownloadedSubtitle',
'searchTsukihimeEntries',
'listTsukihimeFiles',
'downloadTsukihimeSubtitle',
'onDownloadedSecondarySubtitle',
];
for (const key of expected) {
assert.equal(typeof registered[key], 'function', `missing handler: ${key}`);
}
});
test('refreshKnownWords throws when integration is unavailable', async () => { test('refreshKnownWords throws when integration is unavailable', async () => {
const { registered } = createHarness(); const { registered } = createHarness();
@@ -196,20 +169,6 @@ test('refreshKnownWords throws when integration is unavailable', async () => {
); );
}); });
test('refreshKnownWords delegates to integration', async () => {
const { registered, state } = createHarness();
let refreshed = 0;
state.ankiIntegration = {
refreshKnownWordCache: async () => {
refreshed += 1;
},
};
await registered.refreshKnownWords!();
assert.equal(refreshed, 1);
});
test('setAnkiConnectEnabled disables active integration and broadcasts changes', () => { test('setAnkiConnectEnabled disables active integration and broadcasts changes', () => {
const { registered, state } = createHarness(); const { registered, state } = createHarness();
let destroyed = 0; let destroyed = 0;
@@ -274,30 +233,6 @@ test('buildKikuMergePreview returns guard error when integration is missing', as
}); });
}); });
test('buildKikuMergePreview delegates to integration when available', async () => {
const { registered, state } = createHarness();
const calls: unknown[] = [];
state.ankiIntegration = {
buildFieldGroupingPreview: async (
keepNoteId: number,
deleteNoteId: number,
deleteDuplicate: boolean,
) => {
calls.push([keepNoteId, deleteNoteId, deleteDuplicate]);
return { ok: true };
},
};
const result = await registered.buildKikuMergePreview!({
keepNoteId: 3,
deleteNoteId: 4,
deleteDuplicate: true,
});
assert.deepEqual(calls, [[3, 4, true]]);
assert.deepEqual(result, { ok: true });
});
test('searchJimakuEntries caps results and onDownloadedSubtitle sends sub-add to mpv', async () => { test('searchJimakuEntries caps results and onDownloadedSubtitle sends sub-add to mpv', async () => {
const { registered, state } = createHarness(); const { registered, state } = createHarness();
+1
View File
@@ -15,6 +15,7 @@ function makeArgs(overrides: Partial<CliArgs> = {}): CliArgs {
toggleVisibleOverlay: false, toggleVisibleOverlay: false,
togglePrimarySubtitleBar: false, togglePrimarySubtitleBar: false,
yomitan: false, yomitan: false,
hachidori: false,
settings: false, settings: false,
syncWindow: false, syncWindow: false,
youtubeBrowser: false, youtubeBrowser: false,
-27
View File
@@ -103,17 +103,6 @@ test('runAppReadyRuntime starts texthooker on startup when enabled in config', a
); );
}); });
test('runAppReadyRuntime creates immersion tracker during heavy startup', async () => {
const { deps, calls } = makeDeps({
shouldAutoInitializeOverlayRuntimeFromConfig: () => false,
});
await runAppReadyRuntime(deps);
assert.equal(calls.includes('createImmersionTracker'), false);
assert.ok(calls.includes('log:Runtime ready: immersion tracker startup requested.'));
});
test('runAppReadyRuntime keeps annotation websocket enabled when regular websocket auto-skips', async () => { test('runAppReadyRuntime keeps annotation websocket enabled when regular websocket auto-skips', async () => {
const { deps, calls } = makeDeps({ const { deps, calls } = makeDeps({
getResolvedConfig: () => ({ getResolvedConfig: () => ({
@@ -226,22 +215,6 @@ test('runAppReadyRuntime skips Jellyfin remote startup when dependency is not wi
); );
}); });
test('runAppReadyRuntime logs when createImmersionTracker dependency is missing', async () => {
const { deps, calls } = makeDeps({
createImmersionTracker: undefined,
});
await runAppReadyRuntime(deps);
assert.ok(calls.includes('log:Runtime ready: immersion tracker dependency is missing.'));
});
test('runAppReadyRuntime logs defer message when overlay not auto-started', async () => {
const { deps, calls } = makeDeps({
shouldAutoInitializeOverlayRuntimeFromConfig: () => false,
});
await runAppReadyRuntime(deps);
assert.ok(calls.includes('log:Overlay runtime deferred: waiting for explicit overlay command.'));
});
test('runAppReadyRuntime applies config logging level during app-ready', async () => { test('runAppReadyRuntime applies config logging level during app-ready', async () => {
const { deps, calls } = makeDeps({ const { deps, calls } = makeDeps({
getResolvedConfig: () => ({ getResolvedConfig: () => ({
Loaded 100 of 481 files, more files were not shown because too many files have changed in this diff. Show more