diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 501855eb..04f6861e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -78,6 +78,10 @@ jobs:
- name: End-to-end suite
run: bun run test:e2e
+ - name: Dictionary backend windows (Linux)
+ if: runner.os == 'Linux'
+ run: xvfb-run -a bun run test:dictionary:electron
+
- name: Upload session logs (on failure)
if: failure()
uses: actions/upload-artifact@v4
diff --git a/.gitignore b/.gitignore
index fbba9131..af0fe6c8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -20,6 +20,8 @@ coverage/
/main-entry.js
/main-entry.js.map
+/build/hachidori/
+
# Logs
*.log
npm-debug.log*
diff --git a/.gitmodules b/.gitmodules
index 860a00c3..e8965564 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -8,3 +8,7 @@
[submodule "vendor/subminer-yomitan"]
path = vendor/subminer-yomitan
url = https://github.com/ksyasuda/subminer-yomitan
+[submodule "vendor/hachidori"]
+ path = vendor/hachidori
+ url = https://github.com/ksyasuda/hachidori.git
+ branch = subminer
diff --git a/README.md b/README.md
index d48e661d..4740f65d 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
# 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)
@@ -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.
+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.
+
@@ -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 |
| [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 |
-| [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 |
## License
diff --git a/bun.lock b/bun.lock
index 4dd16633..01b147e0 100644
--- a/bun.lock
+++ b/bun.lock
@@ -351,7 +351,7 @@
"filelist": ["filelist@1.0.6", "", { "dependencies": { "minimatch": "^5.0.1" } }, "sha512-5giy2PkLYY1cP39p17Ech+2xlpTRL9HLspOfEgm0L6CwBXBTgsK5ou0JtzYuepxkaQ/tvhCFIJ5uXo0OrM2DxA=="],
- "follow-redirects": ["follow-redirects@1.16.1", "", {}, "sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg=="],
+ "follow-redirects": ["follow-redirects@1.16.1", "", { "peerDependencies": { "debug": "*" }, "optionalPeers": ["debug"] }, "sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg=="],
"form-data": ["form-data@4.0.6", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.4", "mime-types": "^2.1.35" } }, "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ=="],
diff --git a/changes/fix-timing-review-playback-hold.md b/changes/fix-timing-review-playback-hold.md
new file mode 100644
index 00000000..96fc820a
--- /dev/null
+++ b/changes/fix-timing-review-playback-hold.md
@@ -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.
diff --git a/changes/hachidori-backend.md b/changes/hachidori-backend.md
new file mode 100644
index 00000000..34e0b727
--- /dev/null
+++ b/changes/hachidori-backend.md
@@ -0,0 +1,15 @@
+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 (kept alongside its own `hachidori` tag), 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.
+- Character dictionary imports report completion as soon as the archive is read instead of waiting out the temporary server's keep-alive timeout.
+- 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.
diff --git a/changes/hachidori-setup-docs.md b/changes/hachidori-setup-docs.md
new file mode 100644
index 00000000..30697ac0
--- /dev/null
+++ b/changes/hachidori-setup-docs.md
@@ -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.
diff --git a/changes/macos-login-shell-path.md b/changes/macos-login-shell-path.md
new file mode 100644
index 00000000..d74b8069
--- /dev/null
+++ b/changes/macos-login-shell-path.md
@@ -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.
diff --git a/changes/overlay-modal-first-open.md b/changes/overlay-modal-first-open.md
new file mode 100644
index 00000000..88adb937
--- /dev/null
+++ b/changes/overlay-modal-first-open.md
@@ -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.
diff --git a/changes/patched-electron-undici-follow-redirects.md b/changes/patched-electron-undici-follow-redirects.md
new file mode 100644
index 00000000..11954c4e
--- /dev/null
+++ b/changes/patched-electron-undici-follow-redirects.md
@@ -0,0 +1,4 @@
+type: fixed
+area: dependencies
+
+- Updated Electron to 43.8.3 and undici to 7.30.1, and pinned follow-redirects to 1.16.1, to resolve new security advisories.
diff --git a/changes/prefetch-startup-restarts.md b/changes/prefetch-startup-restarts.md
new file mode 100644
index 00000000..dc8c5d5c
--- /dev/null
+++ b/changes/prefetch-startup-restarts.md
@@ -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.
diff --git a/config.example.jsonc b/config.example.jsonc
index 2c0eecb1..e895f90d 100644
--- a/config.example.jsonc
+++ b/config.example.jsonc
@@ -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
// Select primary and secondary mpv subtitle tracks from the overlay.
diff --git a/docs-site/anki-integration.md b/docs-site/anki-integration.md
index ddc24b23..23a04cbf 100644
--- a/docs-site/anki-integration.md
+++ b/docs-site/anki-integration.md
@@ -15,9 +15,9 @@ If you changed AnkiConnect's port, set `ankiConnect.url` to match.
## 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.
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`.
- **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.
+- While the template still has Hachidori's default `hachidori` tag, the configured tags are added ahead of it so cards carry both. Tags you edit in Hachidori settings are kept as written.
+- 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
@@ -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.
+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.
`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.
+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.
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 |
| `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.
| Key | Action |
diff --git a/docs-site/configuration.md b/docs-site/configuration.md
index 3bbbe41c..3daf5c51 100644
--- a/docs-site/configuration.md
+++ b/docs-site/configuration.md
@@ -67,6 +67,12 @@ Everything else needs a restart.
## 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
Log files are named by date (`app-YYYY-MM-DD.log`, `launcher-...`, `mpv-...`). Log export writes a sanitized copy and leaves the originals alone.
diff --git a/docs-site/immersion-tracking.md b/docs-site/immersion-tracking.md
index ad9c117b..ce281114 100644
--- a/docs-site/immersion-tracking.md
+++ b/docs-site/immersion-tracking.md
@@ -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:
-- **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 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
diff --git a/docs-site/public/config.example.jsonc b/docs-site/public/config.example.jsonc
index 2c0eecb1..e895f90d 100644
--- a/docs-site/public/config.example.jsonc
+++ b/docs-site/public/config.example.jsonc
@@ -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
// Select primary and secondary mpv subtitle tracks from the overlay.
diff --git a/docs-site/shortcuts.md b/docs-site/shortcuts.md
index cefa4d68..ed0466c1 100644
--- a/docs-site/shortcuts.md
+++ b/docs-site/shortcuts.md
@@ -6,12 +6,12 @@ Shortcuts work when the overlay has focus. With the [mpv plugin](/mpv-plugin), `
## Global
-| Shortcut | Action | Config key |
-| ------------- | ---------------------- | -------------------------------------- |
-| `Alt+Shift+O` | Toggle visible overlay | `shortcuts.toggleVisibleOverlayGlobal` |
-| `Alt+Shift+Y` | Open Yomitan settings | Fixed |
+| Shortcut | Action | Config key |
+| ------------- | ------------------------------- | -------------------------------------- |
+| `Alt+Shift+O` | Toggle visible overlay | `shortcuts.toggleVisibleOverlayGlobal` |
+| `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
@@ -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.
-| Keys | Action |
-| ----- | -------------------------- |
-| `y-y` | Open the SubMiner menu |
-| `y-s` | Start the overlay |
-| `y-S` | Stop the overlay |
-| `y-t` | Toggle the visible overlay |
-| `y-o` | Open Yomitan settings |
-| `y-r` | Restart the overlay |
-| `y-c` | Show overlay status |
-| `y-h` | Open session help |
-| `v` | Cycle primary subtitle bar |
+| Keys | Action |
+| ----- | ------------------------------- |
+| `y-y` | Open the SubMiner menu |
+| `y-s` | Start the overlay |
+| `y-S` | Stop the overlay |
+| `y-t` | Toggle the visible overlay |
+| `y-o` | Open active dictionary settings |
+| `y-r` | Restart the overlay |
+| `y-c` | Show overlay status |
+| `y-h` | Open session help |
+| `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.
diff --git a/docs-site/usage.md b/docs-site/usage.md
index b1500385..06df5556 100644
--- a/docs-site/usage.md
+++ b/docs-site/usage.md
@@ -16,10 +16,41 @@ Run `subminer` with no file to pick one from the current directory instead. See
### 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.
+### 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. Subtitle annotations and lookups wait while Hachidori imports a dictionary, so large imports pause them until the import finishes.
+
+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
```bash
@@ -33,15 +64,15 @@ See [Launcher script](/launcher-script#video-picker) for picker and history deta
## Overlay basics
-| Key | Action |
-| ------------- | --------------------------------------------------------------------- |
-| `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) |
-| `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/Cmd+/` | Show every overlay and mpv keybinding for this session |
+| Key | Action |
+| ------------- | ---------------------------------------------------------------------------- |
+| `Alt+Shift+O` | Show or hide the overlay (works while the overlay or mpv has focus) |
+| `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 |
+| `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 |
-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:
diff --git a/docs/architecture/README.md b/docs/architecture/README.md
index 63be066d..0392a434 100644
--- a/docs/architecture/README.md
+++ b/docs/architecture/README.md
@@ -46,6 +46,12 @@ Update checks and startup launcher migration share a serialized update-state sto
## 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
- Composition over monoliths
- Pure helpers where possible
diff --git a/docs/workflow/verification.md b/docs/workflow/verification.md
index a6773274..f46ddc5d 100644
--- a/docs/workflow/verification.md
+++ b/docs/workflow/verification.md
@@ -66,6 +66,7 @@ bun run docs:build
Content checks run inside the electron-builder afterPack hook. See the
[release guide](../RELEASING.md#package-contents-checks) for the
installed-app verification checklist.
+- Dictionary backend windows: after a full build, run `xvfb-run -a bun run test:dictionary:electron` on headless Linux (CI runs it in the Linux E2E job). 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`
- Deep/local full gate: default handoff gate above
diff --git a/launcher/commands/playback-command.ts b/launcher/commands/playback-command.ts
index 0b6e6693..4f9691eb 100644
--- a/launcher/commands/playback-command.ts
+++ b/launcher/commands/playback-command.ts
@@ -26,7 +26,10 @@ import {
readSetupState,
} from '../../src/shared/setup-state.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_POLL_INTERVAL_MS = 500;
@@ -115,6 +118,9 @@ async function ensurePlaybackSetupReady(context: LauncherCommandContext): Promis
const configDir = getLauncherConfigDir();
const statePath = getSetupStatePath(configDir);
const ready = await ensureLauncherSetupReady({
+ dictionaryBackend: loadLauncherDictionaryBackend(),
+ isAppRunning: () => isRunningAppControlServerAvailable(args.logLevel, configDir),
+ warn: (message) => log('warn', args.logLevel, message),
readSetupState: () => readSetupState(statePath),
isExternalYomitanConfigured: () => hasLauncherExternalYomitanProfileConfig(),
hasLegacyMpvPlugin: () =>
diff --git a/launcher/config.ts b/launcher/config.ts
index 57a7f9a7..f6556447 100644
--- a/launcher/config.ts
+++ b/launcher/config.ts
@@ -1,4 +1,5 @@
import { fail } from './log.js';
+import type { DictionaryBackend } from '../src/types/config.js';
import type {
Args,
LauncherLoggingConfig,
@@ -100,6 +101,12 @@ export function loadLauncherLoggingConfig(): LauncherLoggingConfig {
};
}
+export function loadLauncherDictionaryBackend(): DictionaryBackend {
+ return readLauncherMainConfigObject()?.dictionaryBackend === 'hachidori'
+ ? 'hachidori'
+ : 'yomitan';
+}
+
export function hasLauncherExternalYomitanProfileConfig(): boolean {
return readExternalYomitanProfilePath(readLauncherMainConfigObject()) !== null;
}
diff --git a/launcher/config/args-normalizer.ts b/launcher/config/args-normalizer.ts
index 8f0d3c9f..68044530 100644
--- a/launcher/config/args-normalizer.ts
+++ b/launcher/config/args-normalizer.ts
@@ -199,6 +199,10 @@ export function applyRootOptionsToArgs(
if (options.update === true) parsed.update = true;
if (options.version === true) parsed.version = 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.texthooker === false) parsed.useTexthooker = false;
if (typeof options.args === 'string') parsed.mpvArgs = options.args;
diff --git a/launcher/config/cli-parser-builder.ts b/launcher/config/cli-parser-builder.ts
index 30989502..f6a93cbc 100644
--- a/launcher/config/cli-parser-builder.ts
+++ b/launcher/config/cli-parser-builder.ts
@@ -87,6 +87,8 @@ function applyRootOptions(program: Command): void {
.option('--log-level ', 'Log level')
.option('-v, --version', 'Show SubMiner version')
.option('--settings', 'Open settings window')
+ .option('--yomitan', 'Open Yomitan settings window')
+ .option('--hachidori', 'Open Hachidori settings window')
.option('-u, --update', 'Check for updates')
.option('-R, --rofi', 'Use rofi picker')
.option('-H, --history', 'Browse local watch history')
diff --git a/launcher/main.test.ts b/launcher/main.test.ts
index 542329e4..5d214190 100644
--- a/launcher/main.test.ts
+++ b/launcher/main.test.ts
@@ -378,6 +378,11 @@ const forwardedAppArgsCases: Array<{
argv: () => ['settings'],
expected: () => '--settings\n',
},
+ ...['--settings', '--yomitan', '--hachidori'].map((flag) => ({
+ name: `launcher ${flag} forwards the matching app settings command`,
+ argv: () => [flag],
+ expected: () => `${flag}\n`,
+ })),
{
name: 'launcher youtube command forwards the YouTube browser flag and log level',
argv: () => ['yt', '--log-level', 'debug'],
@@ -562,3 +567,43 @@ test(
});
},
);
+
+test('external Yomitan profile remains available while a running app awaits a backend switch', () => {
+ withSandbox(({ env, writeConfigFile }) => {
+ writeConfigFile('config.jsonc', {
+ dictionaryBackend: 'hachidori',
+ yomitan: { externalProfilePath: '/external/yomitan-profile' },
+ });
+ const result = spawnSync(
+ process.execPath,
+ [
+ '--eval',
+ `
+ import assert from 'node:assert/strict';
+ import { hasLauncherExternalYomitanProfileConfig } from './launcher/config.ts';
+ import { ensureLauncherSetupReady } from './launcher/setup-gate.ts';
+ import { createDefaultSetupState } from './src/shared/setup-state.ts';
+ for (const running of [true, false]) {
+ let launches = 0;
+ let tick = 0;
+ const ready = await ensureLauncherSetupReady({
+ dictionaryBackend: 'hachidori',
+ isAppRunning: async () => running,
+ readSetupState: () => ({ ...createDefaultSetupState(), dictionaryBackend: 'yomitan' }),
+ isExternalYomitanConfigured: hasLauncherExternalYomitanProfileConfig,
+ launchSetupApp: () => { launches += 1; },
+ sleep: async () => {},
+ now: () => tick++,
+ timeoutMs: 2,
+ pollIntervalMs: 1,
+ });
+ assert.equal(ready, running);
+ assert.equal(launches, running ? 0 : 1);
+ }
+ `,
+ ],
+ { cwd: process.cwd(), env, encoding: 'utf8', timeout: LAUNCHER_RUN_TIMEOUT_MS },
+ );
+ assert.equal(result.status, 0, result.stderr);
+ });
+});
diff --git a/launcher/parse-args.test.ts b/launcher/parse-args.test.ts
index bb82fca7..8d9fe82d 100644
--- a/launcher/parse-args.test.ts
+++ b/launcher/parse-args.test.ts
@@ -339,3 +339,12 @@ test('parseArgs requires an explicit logs action', () => {
assert.equal(exit.code, 1);
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);
+ });
+}
diff --git a/launcher/setup-gate.test.ts b/launcher/setup-gate.test.ts
index 489b70ec..13de6560 100644
--- a/launcher/setup-gate.test.ts
+++ b/launcher/setup-gate.test.ts
@@ -1,7 +1,11 @@
import test from 'node:test';
import assert from 'node:assert/strict';
-import { ensureLauncherSetupReady, waitForSetupCompletion } from './setup-gate';
-import type { SetupState } from '../src/shared/setup-state';
+import {
+ ensureLauncherSetupReady,
+ resolveLauncherGateBackend,
+ waitForSetupCompletion,
+} from './setup-gate';
+import { createDefaultSetupState, type SetupState } from '../src/shared/setup-state';
/** An in-progress setup state; tests override only the fields that matter. */
function makeState(overrides: Partial = {}): SetupState {
@@ -189,3 +193,101 @@ test('ensureLauncherSetupReady ignores stale cancelled state after launching set
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);
+});
diff --git a/launcher/setup-gate.ts b/launcher/setup-gate.ts
index c82ee39f..f862fd37 100644
--- a/launcher/setup-gate.ts
+++ b/launcher/setup-gate.ts
@@ -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: {
readSetupState: () => SetupState | null;
+ dictionaryBackend?: DictionaryBackend;
sleep: (ms: number) => Promise;
now: () => number;
timeoutMs: number;
@@ -13,7 +19,7 @@ export async function waitForSetupCompletion(deps: {
while (deps.now() <= deadline) {
const state = deps.readSetupState();
- if (isSetupCompleted(state)) {
+ if (isSetupCompleted(state, deps.dictionaryBackend)) {
return 'completed';
}
if (ignoringCancelled && state != null && state.status !== 'cancelled') {
@@ -34,6 +40,7 @@ export async function waitForSetupCompletion(deps: {
export async function waitForLegacyMpvPluginPromptResolution(deps: {
readSetupState: () => SetupState | null;
+ dictionaryBackend?: DictionaryBackend;
sleep: (ms: number) => Promise;
now: () => number;
timeoutMs: number;
@@ -41,13 +48,13 @@ export async function waitForLegacyMpvPluginPromptResolution(deps: {
initialState?: SetupState | null;
}): Promise<'acknowledged' | 'cancelled' | 'timeout'> {
const deadline = deps.now() + deps.timeoutMs;
- const initialCompleted = isSetupCompleted(deps.initialState);
+ const initialCompleted = isSetupCompleted(deps.initialState, deps.dictionaryBackend);
const initialCompletedAt = deps.initialState?.completedAt ?? null;
while (deps.now() <= deadline) {
const state = deps.readSetupState();
if (
- isSetupCompleted(state) &&
+ isSetupCompleted(state, deps.dictionaryBackend) &&
(!initialCompleted || state?.completedAt !== initialCompletedAt)
) {
return 'acknowledged';
@@ -62,8 +69,34 @@ export async function waitForLegacyMpvPluginPromptResolution(deps: {
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;
+ warn?: (message: string) => void;
+}): Promise {
+ 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: {
readSetupState: () => SetupState | null;
+ dictionaryBackend?: DictionaryBackend;
+ isAppRunning?: () => Promise;
+ warn?: (message: string) => void;
isExternalYomitanConfigured?: () => boolean;
hasLegacyMpvPlugin?: () => boolean;
launchSetupApp: () => void;
@@ -73,6 +106,12 @@ export async function ensureLauncherSetupReady(deps: {
pollIntervalMs: number;
}): Promise {
const initialState = deps.readSetupState();
+ const dictionaryBackend = await resolveLauncherGateBackend({
+ configuredBackend: deps.dictionaryBackend ?? 'yomitan',
+ state: initialState,
+ isAppRunning: deps.isAppRunning,
+ warn: deps.warn,
+ });
let setupLaunched = false;
const launchSetupApp = () => {
if (setupLaunched) return;
@@ -84,6 +123,7 @@ export async function ensureLauncherSetupReady(deps: {
launchSetupApp();
const result = await waitForLegacyMpvPluginPromptResolution({
readSetupState: deps.readSetupState,
+ dictionaryBackend,
sleep: deps.sleep,
now: deps.now,
timeoutMs: deps.timeoutMs,
@@ -95,17 +135,18 @@ export async function ensureLauncherSetupReady(deps: {
}
}
- if (deps.isExternalYomitanConfigured?.()) {
+ if (dictionaryBackend !== 'hachidori' && deps.isExternalYomitanConfigured?.()) {
return true;
}
const stateAfterLegacyPrompt = deps.readSetupState();
- if (isSetupCompleted(stateAfterLegacyPrompt)) {
+ if (isSetupCompleted(stateAfterLegacyPrompt, dictionaryBackend)) {
return true;
}
launchSetupApp();
const result = await waitForSetupCompletion({
...deps,
+ dictionaryBackend,
ignoreInitialCancelledState: stateAfterLegacyPrompt?.status === 'cancelled',
});
return result === 'completed';
diff --git a/package.json b/package.json
index 9b7cf1fd..ca138b9d 100644
--- a/package.json
+++ b/package.json
@@ -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: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: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",
"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",
@@ -21,7 +22,7 @@
"build:launcher": "bun run scripts/build-launcher.ts",
"build:stats": "cd stats && bun run build",
"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: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",
@@ -83,7 +84,8 @@
"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: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": {
"@xmldom/xmldom": "0.8.15",
@@ -232,6 +234,10 @@
"from": "build/yomitan",
"to": "yomitan"
},
+ {
+ "from": "build/hachidori",
+ "to": "hachidori"
+ },
{
"from": "vendor/yomitan-jlpt-vocab",
"to": "yomitan-jlpt-vocab"
diff --git a/scripts/build-hachidori.mjs b/scripts/build-hachidori.mjs
new file mode 100644
index 00000000..c6d4a388
--- /dev/null
+++ b/scripts/build-hachidori.mjs
@@ -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`);
diff --git a/scripts/build-hachidori.test.ts b/scripts/build-hachidori.test.ts
new file mode 100644
index 00000000..3332bbcb
--- /dev/null
+++ b/scripts/build-hachidori.test.ts
@@ -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');
+});
diff --git a/scripts/check-dictionary-backends.cjs b/scripts/check-dictionary-backends.cjs
new file mode 100644
index 00000000..fc189b7f
--- /dev/null
+++ b/scripts/check-dictionary-backends.cjs
@@ -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);
+});
diff --git a/scripts/check-hachidori-parser.cjs b/scripts/check-hachidori-parser.cjs
new file mode 100644
index 00000000..50c5ad34
--- /dev/null
+++ b/scripts/check-hachidori-parser.cjs
@@ -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, 'hachidori']);
+ 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);
+ });
diff --git a/scripts/hachidori-anki-audio.test.ts b/scripts/hachidori-anki-audio.test.ts
new file mode 100644
index 00000000..801feaa6
--- /dev/null
+++ b/scripts/hachidori-anki-audio.test.ts
@@ -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 = {};
+ 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);
+});
diff --git a/scripts/hachidori-host.test.ts b/scripts/hachidori-host.test.ts
new file mode 100644
index 00000000..cda320a3
--- /dev/null
+++ b/scripts/hachidori-host.test.ts
@@ -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');
+ `);
+});
diff --git a/scripts/package-audit.cjs b/scripts/package-audit.cjs
index 65b26c68..22ed41a6 100644
--- a/scripts/package-audit.cjs
+++ b/scripts/package-audit.cjs
@@ -26,6 +26,14 @@ const REQUIRED_APP_FILES = [
]),
];
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/data/fonts/kanji-stroke-orders.ttf',
'yomitan/fonts/NotoSansJP-Regular.ttf',
diff --git a/scripts/run-dictionary-settings-smoke.mjs b/scripts/run-dictionary-settings-smoke.mjs
new file mode 100644
index 00000000..c2f84db7
--- /dev/null
+++ b/scripts/run-dictionary-settings-smoke.mjs
@@ -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 });
+}
diff --git a/scripts/smoke-package.cjs b/scripts/smoke-package.cjs
index 8eb49fb4..9ffede4e 100644
--- a/scripts/smoke-package.cjs
+++ b/scripts/smoke-package.cjs
@@ -22,39 +22,6 @@ const timeout = setTimeout(() => {
app.exit(1);
}, 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() {
await app.whenReady();
const packagedRequire = createRequire(path.join(archive, 'package.json'));
@@ -83,6 +50,10 @@ async function smoke() {
{ allowFileAccess: true },
);
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 = [];
session.defaultSession.webRequest.onErrorOccurred(
{ urls: ['file://*/*', 'http://127.0.0.1/*'] },
@@ -93,9 +64,7 @@ async function smoke() {
failedRequests.push(`${details.url}: ${details.error}`);
},
);
- const statsServer = serveStatsDist(path.join(archive, 'stats', 'dist'), failedRequests);
- await once(statsServer, 'listening');
- for (const ui of ['renderer', 'settings', 'syncui', 'stats']) {
+ for (const ui of ['renderer', 'settings', 'syncui']) {
const win = new BrowserWindow({
show: false,
webPreferences: {
@@ -104,25 +73,52 @@ async function smoke() {
},
});
try {
- if (ui === 'stats') {
- await win.loadURL(`http://127.0.0.1:${statsServer.address().port}/`);
- // Let in-flight font requests settle before the window goes away.
- await win.webContents.executeJavaScript('document.fonts.ready.then(() => true)');
- } else {
- 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`);
- }
+ 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 {
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');
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.',
);
}
diff --git a/src/anki-integration.ts b/src/anki-integration.ts
index ce8001c6..cb2327c6 100644
--- a/src/anki-integration.ts
+++ b/src/anki-integration.ts
@@ -1802,6 +1802,9 @@ export class AnkiIntegration {
request: Omit,
): Promise {
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 await this.mediaTimingReviewCallback({
diff --git a/src/anki-integration/anki-connect-proxy.test.ts b/src/anki-integration/anki-connect-proxy.test.ts
index c10b1e9c..8f811fae 100644
--- a/src/anki-integration/anki-connect-proxy.test.ts
+++ b/src/anki-integration/anki-connect-proxy.test.ts
@@ -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 () => {
const processed: number[] = [];
let releaseProcessing: (() => void) | undefined;
diff --git a/src/anki-integration/anki-connect-proxy.ts b/src/anki-integration/anki-connect-proxy.ts
index 1cae5f3a..91c25c1d 100644
--- a/src/anki-integration/anki-connect-proxy.ts
+++ b/src/anki-integration/anki-connect-proxy.ts
@@ -224,6 +224,31 @@ export class AnkiConnectProxyServer {
typeof 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') {
return;
}
@@ -239,12 +264,23 @@ export class AnkiConnectProxyServer {
return;
}
- this.maybeTrackDuplicateNoteIds(requestJson, action, responseResult);
-
const noteIds =
action === 'multi'
? this.collectMultiResultIds(requestJson, 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) {
void this.enqueueMostRecentAddedNote();
return;
@@ -293,7 +329,7 @@ export class AnkiConnectProxyServer {
typeof requestJson.action === 'string'
? requestJson.action
: String(requestJson.action ?? '');
- if (action !== 'addNote') {
+ if (action !== 'addNote' && action !== 'updateNoteFields') {
return requestJson;
}
@@ -301,12 +337,17 @@ export class AnkiConnectProxyServer {
requestJson.params && typeof requestJson.params === 'object'
? (requestJson.params as Record)
: 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;
}
const nextParams = { ...params };
delete nextParams.subminerDuplicateNoteIds;
+ delete nextParams.subminerEnrich;
return {
...requestJson,
params: nextParams,
@@ -455,7 +496,7 @@ export class AnkiConnectProxyServer {
});
}
- private enqueueNotes(noteIds: number[]): void {
+ private enqueueNotes(noteIds: number[], recordAdded = true): void {
let enqueuedCount = 0;
const acceptedIds: number[] = [];
for (const noteId of noteIds) {
@@ -472,7 +513,7 @@ export class AnkiConnectProxyServer {
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.processQueue();
}
diff --git a/src/anki-integration/note-update-workflow.test.ts b/src/anki-integration/note-update-workflow.test.ts
index abd6b32e..3af34dd2 100644
--- a/src/anki-integration/note-update-workflow.test.ts
+++ b/src/anki-integration/note-update-workflow.test.ts
@@ -8,6 +8,7 @@ import {
import type { SubtitleMiningContext } from '../types/subtitle';
import type { CardKind } from '../types/anki';
import { applyCardKindFlagFields } from './card-kinds';
+import { STATS_MINING_TAG } from '../shared/anki-source';
function setCardTypeFields(
updatedFields: Record,
@@ -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 () => {
const harness = createWorkflowHarness();
diff --git a/src/anki-integration/note-update-workflow.ts b/src/anki-integration/note-update-workflow.ts
index ccb560c8..c7af3029 100644
--- a/src/anki-integration/note-update-workflow.ts
+++ b/src/anki-integration/note-update-workflow.ts
@@ -8,9 +8,11 @@ import type {
WordCardKind,
} from '../types/anki';
import { resolveWordCardKind } from './note-field-utils';
+import { STATS_MINING_TAG } from '../shared/anki-source';
export interface NoteUpdateWorkflowNoteInfo {
noteId: number;
+ tags?: string[];
fields: Record;
}
@@ -185,6 +187,10 @@ export class NoteUpdateWorkflow {
}
const noteInfo = notesInfo[0]!;
+ if (noteInfo.tags?.includes(STATS_MINING_TAG)) {
+ this.deps.appendKnownWordsFromNoteInfo(noteInfo);
+ return;
+ }
const fields = this.deps.extractFields(noteInfo.fields);
const config = this.deps.getConfig();
diff --git a/src/cli/args.test.ts b/src/cli/args.test.ts
index 1a5b03d9..4f5e6143 100644
--- a/src/cli/args.test.ts
+++ b/src/cli/args.test.ts
@@ -8,6 +8,7 @@ import {
isStandaloneTexthookerCommand,
parseArgs,
shouldRunYomitanOnlyStartup,
+ shouldRunDictionarySettingsOnlyStartup,
shouldStartApp,
} from './args';
@@ -476,3 +477,21 @@ test('hasExplicitCommand and shouldStartApp preserve command intent', () => {
assert.equal(hasExplicitCommand(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);
+});
diff --git a/src/cli/args.ts b/src/cli/args.ts
index 942c6642..da3579a2 100644
--- a/src/cli/args.ts
+++ b/src/cli/args.ts
@@ -12,6 +12,7 @@ export interface CliArgs {
toggleVisibleOverlay: boolean;
togglePrimarySubtitleBar: boolean;
yomitan: boolean;
+ hachidori: boolean;
settings: boolean;
syncWindow: boolean;
youtubeBrowser: boolean;
@@ -133,6 +134,7 @@ export function parseArgs(argv: string[]): CliArgs {
toggleVisibleOverlay: false,
togglePrimarySubtitleBar: false,
yomitan: false,
+ hachidori: false,
settings: false,
syncWindow: 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-primary-subtitle-bar') args.togglePrimarySubtitleBar = 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 === '--sync-window') args.syncWindow = true;
else if (arg === '--youtube-browser') args.youtubeBrowser = true;
@@ -563,6 +566,7 @@ export function hasExplicitCommand(args: CliArgs): boolean {
args.toggleVisibleOverlay ||
args.togglePrimarySubtitleBar ||
args.yomitan ||
+ args.hachidori ||
args.settings ||
args.syncWindow ||
args.youtubeBrowser ||
@@ -643,6 +647,7 @@ export function isStandaloneTexthookerCommand(args: CliArgs): boolean {
!args.toggleVisibleOverlay &&
!args.togglePrimarySubtitleBar &&
!args.yomitan &&
+ !args.hachidori &&
!args.settings &&
!args.syncWindow &&
!args.youtubeBrowser &&
@@ -716,6 +721,7 @@ export function shouldStartApp(args: CliArgs): boolean {
args.toggleVisibleOverlay ||
args.togglePrimarySubtitleBar ||
args.yomitan ||
+ args.hachidori ||
args.settings ||
args.syncWindow ||
args.youtubeBrowser ||
@@ -767,8 +773,12 @@ export function shouldStartApp(args: CliArgs): boolean {
}
export function shouldRunYomitanOnlyStartup(args: CliArgs): boolean {
+ return args.yomitan && !args.hachidori && shouldRunDictionarySettingsOnlyStartup(args);
+}
+
+export function shouldRunDictionarySettingsOnlyStartup(args: CliArgs): boolean {
return (
- args.yomitan &&
+ (args.yomitan || args.hachidori) &&
!args.background &&
!args.start &&
!args.stop &&
diff --git a/src/cli/help.ts b/src/cli/help.ts
index bfa39f19..b3223e76 100644
--- a/src/cli/help.ts
+++ b/src/cli/help.ts
@@ -25,6 +25,7 @@ ${B}Overlay${R}
--show-visible-overlay Show subtitle overlay
--hide-visible-overlay Hide subtitle overlay
--yomitan Open Yomitan settings window
+ --hachidori Open Hachidori settings window
--settings Open SubMiner settings window
--setup Open first-run setup window
--auto-start-overlay Auto-hide mpv subs, show overlay on connect
diff --git a/src/config/definitions.ts b/src/config/definitions.ts
index e5d9be11..7da11e6a 100644
--- a/src/config/definitions.ts
+++ b/src/config/definitions.ts
@@ -22,6 +22,7 @@ export type {
} from './definitions/shared';
const {
+ dictionaryBackend,
subtitlePosition,
keybindings,
websocket,
@@ -57,6 +58,7 @@ const { stats } = STATS_DEFAULT_CONFIG;
export const DEFAULT_CONFIG: ResolvedConfig = {
subtitleSelection: { enabled: false },
subtitleGeneration: { ...DEFAULT_SUBTITLE_GENERATION_CONFIG },
+ dictionaryBackend,
subtitlePosition,
keybindings,
websocket,
diff --git a/src/config/definitions/defaults-core.ts b/src/config/definitions/defaults-core.ts
index 5d87c82c..b92fd9c8 100644
--- a/src/config/definitions/defaults-core.ts
+++ b/src/config/definitions/defaults-core.ts
@@ -2,6 +2,7 @@ import { ResolvedConfig } from '../../types/config';
export const CORE_DEFAULT_CONFIG: Pick<
ResolvedConfig,
+ | 'dictionaryBackend'
| 'subtitlePosition'
| 'keybindings'
| 'websocket'
@@ -18,6 +19,7 @@ export const CORE_DEFAULT_CONFIG: Pick<
| 'notifications'
| 'auto_start_overlay'
> = {
+ dictionaryBackend: 'yomitan',
subtitlePosition: { yPercent: 10 },
keybindings: [],
websocket: {
diff --git a/src/config/definitions/options-core.ts b/src/config/definitions/options-core.ts
index d3a30b0d..1852f997 100644
--- a/src/config/definitions/options-core.ts
+++ b/src/config/definitions/options-core.ts
@@ -81,6 +81,13 @@ export function buildCoreConfigOptionRegistry(
] as const;
return [
+ {
+ path: 'dictionaryBackend',
+ kind: 'enum',
+ enumValues: ['yomitan', 'hachidori'],
+ defaultValue: defaultConfig.dictionaryBackend,
+ description: 'Dictionary lookup backend. Restart SubMiner after changing this setting.',
+ },
{
path: 'logging.level',
kind: 'enum',
diff --git a/src/config/definitions/template-sections.ts b/src/config/definitions/template-sections.ts
index 8d7bbe19..ee68378e 100644
--- a/src/config/definitions/template-sections.ts
+++ b/src/config/definitions/template-sections.ts
@@ -1,6 +1,14 @@
import { ConfigTemplateSection } from './shared';
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',
description: ['Select primary and secondary mpv subtitle tracks from the overlay.'],
diff --git a/src/config/resolve/core-domains.ts b/src/config/resolve/core-domains.ts
index 74ba482d..b0553031 100644
--- a/src/config/resolve/core-domains.ts
+++ b/src/config/resolve/core-domains.ts
@@ -6,6 +6,17 @@ import { asBoolean, asNumber, asString, isObject } from './shared';
export function applyCoreDomainConfig(context: ResolveContext): void {
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)) {
const enabled = asBoolean(src.subtitleSelection.enabled);
if (enabled !== undefined) resolved.subtitleSelection.enabled = enabled;
diff --git a/src/config/resolve/dictionary-backend.test.ts b/src/config/resolve/dictionary-backend.test.ts
new file mode 100644
index 00000000..b23307dc
--- /dev/null
+++ b/src/config/resolve/dictionary-backend.test.ts
@@ -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');
+ }
+});
diff --git a/src/config/settings/registry.ts b/src/config/settings/registry.ts
index f1c119df..38ffe31b 100644
--- a/src/config/settings/registry.ts
+++ b/src/config/settings/registry.ts
@@ -146,6 +146,7 @@ const SECTION_ORDER = new Map(
'Discord Rich Presence',
'Jellyfin',
'Texthooker',
+ 'Dictionary Lookup',
'Yomitan',
'Stats dashboard',
'Startup warmups',
@@ -228,8 +229,8 @@ const LABEL_OVERRIDES: Record = {
'shortcuts.openCharacterDictionaryManager': 'Open Character Dictionary Manager',
'subtitleSidebar.pauseVideoOnHover': 'Pause Video On Hover - Sidebar',
'subtitleStyle.autoPauseVideoOnHover': 'Pause Video On Hover - Subtitles',
- 'subtitleStyle.autoPauseVideoOnYomitanPopup': 'Pause Video On Yomitan Popup',
- 'subtitleStyle.primaryVisibleOnYomitanPopup': 'Keep Primary Visible On Yomitan Popup',
+ 'subtitleStyle.autoPauseVideoOnYomitanPopup': 'Pause Video On Dictionary Popup',
+ 'subtitleStyle.primaryVisibleOnYomitanPopup': 'Keep Primary Visible On Dictionary Popup',
'subtitleStyle.primaryDefaultMode': 'Primary Subtitle Visibility Mode',
'subtitleStyle.frequencyDictionary.mode': 'Frequency Mode',
'subtitleStyle.css': 'CSS Declarations',
@@ -270,7 +271,7 @@ const DESCRIPTION_OVERRIDES: Record = {
'subtitleSidebar.css':
'CSS declarations applied to the subtitle sidebar. Includes color, background-color, all font properties, and sidebar CSS variables.',
'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':
'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':
@@ -334,6 +335,9 @@ function humanizePath(path: string): string {
}
function categoryAndSection(path: string): { category: ConfigSettingsCategory; section: string } {
+ if (path === 'dictionaryBackend') {
+ return { category: 'integrations', section: 'Dictionary Lookup' };
+ }
if (
path === 'subtitleStyle.autoPauseVideoOnHover' ||
path === 'subtitleStyle.autoPauseVideoOnYomitanPopup' ||
diff --git a/src/core/services/__tests__/stats-server.test.ts b/src/core/services/__tests__/stats-server.test.ts
index 9108b92f..d76f63b9 100644
--- a/src/core/services/__tests__/stats-server.test.ts
+++ b/src/core/services/__tests__/stats-server.test.ts
@@ -1831,6 +1831,7 @@ describe('stats server API routes', () => {
});
assert.equal(status, 200, JSON.stringify(body));
+ assert.deepEqual(sentNote(env.requests, 'addNote').tags, ['SubMiner', 'SubMiner::Stats']);
assert.match(
sentNote(env.requests, 'updateNoteFields').fields.Picture ?? '',
/^$/,
diff --git a/src/core/services/anilist/cover-art-fetcher.test.ts b/src/core/services/anilist/cover-art-fetcher.test.ts
index a23ed18c..803822f8 100644
--- a/src/core/services/anilist/cover-art-fetcher.test.ts
+++ b/src/core/services/anilist/cover-art-fetcher.test.ts
@@ -6,6 +6,7 @@ import test from 'node:test';
import { createCoverArtFetcher, stripFilenameTags } from './cover-art-fetcher.js';
import { Database } from '../immersion-tracker/sqlite.js';
import {
+ applyPragmas,
ensureSchema,
getOrCreateAnimeRecord,
getOrCreateVideoRecord,
@@ -50,6 +51,7 @@ test('stripFilenameTags normalizes common media-title formats', () => {
async function backfillMissingCoverBlob(): Promise {
const dbPath = makeDbPath();
const db = new Database(dbPath);
+ applyPragmas(db);
ensureSchema(db);
const videoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-test.mkv', {
canonicalTitle: 'Cover Fetcher Test',
@@ -114,6 +116,7 @@ test(
async function reuseCachedAnimeCoverArt(): Promise {
const dbPath = makeDbPath();
const db = new Database(dbPath);
+ applyPragmas(db);
ensureSchema(db);
const firstVideoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-cache-1.mkv', {
canonicalTitle: 'Shared Cover Show',
@@ -203,6 +206,7 @@ function createJsonResponse(payload: unknown): Response {
test('fetchIfMissing uses guessit primary title and season when available', async () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
+ applyPragmas(db);
ensureSchema(db);
const videoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-season-test.mkv', {
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 () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
+ applyPragmas(db);
ensureSchema(db);
const videoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-fallback-test.mkv', {
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 () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
+ applyPragmas(db);
ensureSchema(db);
const videoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-unresolved.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 () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
+ applyPragmas(db);
ensureSchema(db);
const videoId = getOrCreateVideoRecord(db, 'local:/tmp/cover-fetcher-recovers.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 () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
+ applyPragmas(db);
ensureSchema(db);
const videoId = getOrCreateVideoRecord(db, 'local:/tmp/hanzawa-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 () => {
const dbPath = makeDbPath();
const db = new Database(dbPath);
+ applyPragmas(db);
ensureSchema(db);
const videoId = getOrCreateVideoRecord(db, 'local:/tmp/hanzawa-02.mkv', {
canonicalTitle: 'Hanzawa Naoki - 02.mkv',
diff --git a/src/core/services/app-lifecycle.test.ts b/src/core/services/app-lifecycle.test.ts
index 049a8856..e3cb65c4 100644
--- a/src/core/services/app-lifecycle.test.ts
+++ b/src/core/services/app-lifecycle.test.ts
@@ -15,6 +15,7 @@ function makeArgs(overrides: Partial = {}): CliArgs {
toggleVisibleOverlay: false,
togglePrimarySubtitleBar: false,
yomitan: false,
+ hachidori: false,
settings: false,
syncWindow: false,
youtubeBrowser: false,
diff --git a/src/core/services/cli-command.test.ts b/src/core/services/cli-command.test.ts
index 3e70dd12..f935ae4c 100644
--- a/src/core/services/cli-command.test.ts
+++ b/src/core/services/cli-command.test.ts
@@ -15,6 +15,7 @@ function makeArgs(overrides: Partial = {}): CliArgs {
toggle: false,
toggleVisibleOverlay: false,
yomitan: false,
+ hachidori: false,
settings: false,
syncWindow: false,
youtubeBrowser: false,
@@ -129,6 +130,9 @@ function createDeps(overrides: Partial = {}) {
togglePrimarySubtitleBar: () => {
calls.push('togglePrimarySubtitleBar');
},
+ openHachidoriSettingsDelayed: (delayMs) => {
+ calls.push(`openHachidoriSettingsDelayed:${delayMs}`);
+ },
openYomitanSettingsDelayed: (delayMs) => {
calls.push(`openYomitanSettingsDelayed:${delayMs}`);
},
@@ -980,3 +984,14 @@ test('handleCliCommand reports async refresh-known-words errors to OSD', async (
assert.ok(osd.some((value) => value.includes('Refresh known words failed: refresh boom')));
assert.ok(calls.includes('stopApp'));
});
+
+for (const source of ['initial', 'second-instance'] as const) {
+ test(`Hachidori settings command opens its own settings on ${source} invocation`, () => {
+ const { deps, calls } = createDeps();
+ handleCliCommand(makeArgs({ hachidori: true }), source, deps);
+ assert.ok(calls.includes('openHachidoriSettingsDelayed:1000'));
+ assert.equal(calls.includes('openYomitanSettingsDelayed:1000'), false);
+ assert.equal(calls.includes('initializeOverlayRuntime'), false);
+ assert.equal(calls.includes('connectMpvClient'), false);
+ });
+}
diff --git a/src/core/services/cli-command.ts b/src/core/services/cli-command.ts
index f89d15b1..d91e1bd9 100644
--- a/src/core/services/cli-command.ts
+++ b/src/core/services/cli-command.ts
@@ -43,6 +43,7 @@ export interface CliCommandServiceDeps {
togglePrimarySubtitleBar: () => void;
openFirstRunSetup: (force?: boolean) => void;
openYomitanSettingsDelayed: (delayMs: number) => void;
+ openHachidoriSettingsDelayed: (delayMs: number) => void;
openConfigSettingsWindow: () => void;
openSyncUiWindow: () => void;
openYoutubeBrowserWindow: () => void;
@@ -167,6 +168,7 @@ interface MiningCliRuntime {
interface UiCliRuntime {
openFirstRunSetup: (force?: boolean) => void;
openYomitanSettings: () => void;
+ openHachidoriSettings: () => void;
openConfigSettingsWindow: () => void;
openSyncUiWindow: () => void;
openYoutubeBrowserWindow: () => void;
@@ -273,6 +275,11 @@ export function createCliCommandDepsRuntime(
options.ui.openYomitanSettings();
}, delayMs);
},
+ openHachidoriSettingsDelayed: (delayMs) => {
+ options.schedule(() => {
+ options.ui.openHachidoriSettings();
+ }, delayMs);
+ },
openConfigSettingsWindow: options.ui.openConfigSettingsWindow,
openSyncUiWindow: options.ui.openSyncUiWindow,
openYoutubeBrowserWindow: options.ui.openYoutubeBrowserWindow,
@@ -424,6 +431,8 @@ export function handleCliCommand(
deps.logDebug('Opened first-run setup flow.');
} else if (args.yomitan) {
deps.openYomitanSettingsDelayed(1000);
+ } else if (args.hachidori) {
+ deps.openHachidoriSettingsDelayed(1000);
} else if (args.settings) {
deps.openConfigSettingsWindow();
} else if (args.syncWindow) {
diff --git a/src/core/services/hachidori-extension.test.ts b/src/core/services/hachidori-extension.test.ts
new file mode 100644
index 00000000..10b71887
--- /dev/null
+++ b/src/core/services/hachidori-extension.test.ts
@@ -0,0 +1,55 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { resolveHachidoriExtensionPath } from './hachidori-extension';
+import { ensureExtensionCopyAsync } from './yomitan-extension-copy';
+
+test('Hachidori resolves development and packaged artifacts without falling back to Yomitan', () => {
+ const options = { moduleDir: '/app/dist/core/services', resourcesPath: '/resources' };
+ assert.equal(
+ resolveHachidoriExtensionPath({
+ ...options,
+ exists: (p) => p === '/app/build/hachidori/manifest.json',
+ }),
+ '/app/build/hachidori',
+ );
+ assert.equal(
+ resolveHachidoriExtensionPath({
+ ...options,
+ exists: (p) => p === '/resources/hachidori/manifest.json',
+ }),
+ '/resources/hachidori',
+ );
+ assert.throws(
+ () => resolveHachidoriExtensionPath({ ...options, exists: () => false }),
+ /build:hachidori/,
+ );
+});
+
+test('Hachidori updates its own extension copy and preserves the Yomitan copy', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-backend-copy-'));
+ try {
+ const source = path.join(root, 'source');
+ const profile = path.join(root, 'profile');
+ fs.mkdirSync(source);
+ fs.writeFileSync(path.join(source, 'manifest.json'), '{"name":"Hachidori","version":"1"}');
+ fs.mkdirSync(path.join(profile, 'extensions/yomitan'), { recursive: true });
+ fs.writeFileSync(path.join(profile, 'extensions/yomitan/marker'), 'preserved');
+ const options = { extensionName: 'hachidori', platform: 'linux' } satisfies Parameters<
+ typeof ensureExtensionCopyAsync
+ >[2];
+ const copy = await ensureExtensionCopyAsync(source, profile, options);
+ assert.equal(copy.targetDir, path.join(profile, 'extensions/hachidori'));
+ assert.equal((await ensureExtensionCopyAsync(source, profile, options)).copied, false);
+ fs.writeFileSync(path.join(source, 'bridge.js'), 'updated');
+ assert.equal((await ensureExtensionCopyAsync(source, profile, options)).copied, true);
+ assert.equal(
+ fs.readFileSync(path.join(profile, 'extensions/yomitan/marker'), 'utf8'),
+ 'preserved',
+ );
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
diff --git a/src/core/services/hachidori-extension.ts b/src/core/services/hachidori-extension.ts
new file mode 100644
index 00000000..5fde9c7d
--- /dev/null
+++ b/src/core/services/hachidori-extension.ts
@@ -0,0 +1,59 @@
+import electron from 'electron';
+import type { Extension, Session } from 'electron';
+import { existsSync } from 'node:fs';
+import * as path from 'node:path';
+import { ensureExtensionCopyAsync } from './yomitan-extension-copy';
+import { HACHIDORI_SESSION_PARTITION } from './tokenizer/hachidori-parser-bridge';
+
+export function getHachidoriSession(): Session {
+ return electron.session.fromPartition(HACHIDORI_SESSION_PARTITION);
+}
+
+export function resolveHachidoriExtensionPath(options: {
+ moduleDir: string;
+ resourcesPath: string;
+ exists?: (candidate: string) => boolean;
+}): string {
+ const candidates = [
+ path.resolve(options.moduleDir, '../../../build/hachidori'),
+ path.join(options.resourcesPath, 'hachidori'),
+ ];
+ const found = candidates.find((candidate) =>
+ (options.exists ?? existsSync)(path.join(candidate, 'manifest.json')),
+ );
+ if (!found) throw new Error('Hachidori is not bundled. Run bun run build:hachidori.');
+ return found;
+}
+
+/** Separate session keeps settings-only launches from injecting into the other backend's overlay. */
+export function createHachidoriExtensionRuntime(userDataPath: string) {
+ let extension: Extension | null = null;
+ let loading: Promise | null = null;
+ return {
+ getSession: getHachidoriSession,
+ ensureLoaded(): Promise {
+ if (extension) return Promise.resolve(extension);
+ if (loading) return loading;
+ loading = (async () => {
+ const source = resolveHachidoriExtensionPath({
+ moduleDir: __dirname,
+ resourcesPath: process.resourcesPath,
+ });
+ const copy = await ensureExtensionCopyAsync(source, userDataPath, {
+ extensionName: 'hachidori',
+ });
+ const session = getHachidoriSession();
+ // Electron can reuse an old extension worker after its files change.
+ // Drop worker registrations before loading, preserving dictionaries and settings.
+ await session.clearStorageData({ storages: ['serviceworkers'] });
+ extension = await session.extensions.loadExtension(copy.targetDir, {
+ allowFileAccess: true,
+ });
+ return extension;
+ })().finally(() => {
+ loading = null;
+ });
+ return loading;
+ },
+ };
+}
diff --git a/src/core/services/startup-bootstrap.test.ts b/src/core/services/startup-bootstrap.test.ts
index ff8d8bcc..2d8e6f3e 100644
--- a/src/core/services/startup-bootstrap.test.ts
+++ b/src/core/services/startup-bootstrap.test.ts
@@ -15,6 +15,7 @@ function makeArgs(overrides: Partial = {}): CliArgs {
toggleVisibleOverlay: false,
togglePrimarySubtitleBar: false,
yomitan: false,
+ hachidori: false,
settings: false,
syncWindow: false,
youtubeBrowser: false,
diff --git a/src/core/services/stats-server/mining-routes.ts b/src/core/services/stats-server/mining-routes.ts
index bbe8353c..653125bc 100644
--- a/src/core/services/stats-server/mining-routes.ts
+++ b/src/core/services/stats-server/mining-routes.ts
@@ -7,6 +7,7 @@ import { resolveAnimatedImageLeadInSeconds } from '../../../anki-integration/ani
import { clampMediaEndTime } from '../../../anki-integration/media-duration.js';
import { MediaGenerator } from '../../../media-generator.js';
import { statsJson } from '../../../types/stats-http-contract.js';
+import { STATS_MINING_TAG } from '../../../shared/anki-source.js';
import { widenHalfwidthKana } from '../../utils/halfwidth-kana.js';
import {
resolveRetimedSecondarySubtitleTextFromSidecar,
@@ -372,7 +373,7 @@ export function registerStatsMiningRoutes(app: Hono, options?: StatsMiningRouteO
}
const model = ankiConfig.isLapis?.sentenceCardModel || 'Basic';
- const tags = ankiConfig.tags ?? ['SubMiner'];
+ const tags = [...new Set([...(ankiConfig.tags ?? ['SubMiner']), STATS_MINING_TAG])];
const addNotePromise = timeMiningPhase(
mode,
diff --git a/src/core/services/subtitle-prefetch.test.ts b/src/core/services/subtitle-prefetch.test.ts
index ad2c9f8c..c428f07d 100644
--- a/src/core/services/subtitle-prefetch.test.ts
+++ b/src/core/services/subtitle-prefetch.test.ts
@@ -300,3 +300,65 @@ test('prefetch service deduplicates repeated cue text within a run', async () =>
);
assert.ok(tokenizedTexts.includes('other'));
});
+
+test('prefetch service keeps an in-flight result from a superseded run', async () => {
+ const cues = makeCues(5);
+ const cachedTexts: string[] = [];
+ let releaseFirst!: () => void;
+ const firstGate = new Promise((resolve) => {
+ releaseFirst = resolve;
+ });
+
+ const service = createSubtitlePrefetchService({
+ cues,
+ tokenizeSubtitle: async (text) => {
+ if (text === 'line-0') await firstGate;
+ return { text, tokens: [] };
+ },
+ preCacheTokenization: (text) => {
+ cachedTexts.push(text);
+ },
+ getCacheGeneration: () => 0,
+ priorityWindowSize: 3,
+ });
+
+ service.start(0);
+ await flushMicrotasks();
+ service.stop();
+ releaseFirst();
+ await flushMicrotasks();
+
+ assert.deepEqual(cachedTexts, ['line-0']);
+});
+
+test('prefetch service drops an in-flight result after cache invalidation', async () => {
+ const cues = makeCues(5);
+ const cachedTexts: string[] = [];
+ let generation = 0;
+ let releaseFirst!: () => void;
+ const firstGate = new Promise((resolve) => {
+ releaseFirst = resolve;
+ });
+
+ const service = createSubtitlePrefetchService({
+ cues,
+ tokenizeSubtitle: async (text) => {
+ if (text === 'line-0') await firstGate;
+ return { text, tokens: [] };
+ },
+ preCacheTokenization: (text) => {
+ cachedTexts.push(text);
+ },
+ getCacheGeneration: () => generation,
+ priorityWindowSize: 3,
+ });
+
+ service.start(0);
+ await flushMicrotasks();
+ service.stop();
+ generation += 1;
+ releaseFirst();
+ await flushMicrotasks();
+
+ assert.deepEqual(cachedTexts, []);
+});
diff --git a/src/core/services/subtitle-prefetch.ts b/src/core/services/subtitle-prefetch.ts
index fd169f87..a532a9ba 100644
--- a/src/core/services/subtitle-prefetch.ts
+++ b/src/core/services/subtitle-prefetch.ts
@@ -7,6 +7,12 @@ export interface SubtitlePrefetchServiceDeps {
tokenizeSubtitle: (text: string) => Promise;
preCacheTokenization: (text: string, data: SubtitleData) => void;
hasCachedTokenization?: (text: string) => boolean;
+ /**
+ * Bumped whenever the tokenization cache is invalidated. A result is cached only if
+ * the generation is unchanged since its tokenization began; without this dep every
+ * result counts as fresh.
+ */
+ getCacheGeneration?: () => number;
priorityWindowSize?: number;
}
@@ -88,9 +94,12 @@ export function createSubtitlePrefetchService(
}
warmedKeys.add(cacheKey);
+ // Freshness follows the cache generation, not the run: a seek or restart that
+ // supersedes this run leaves the result valid, and the parser time is already spent.
+ const generation = deps.getCacheGeneration?.();
try {
const result = await deps.tokenizeSubtitle(cue.text);
- if (result && !stopped && runId === currentRunId) {
+ if (result && generation === deps.getCacheGeneration?.()) {
deps.preCacheTokenization(cue.text, result);
}
} catch {
diff --git a/src/core/services/subtitle-processing-controller.ts b/src/core/services/subtitle-processing-controller.ts
index d03d8c88..27710146 100644
--- a/src/core/services/subtitle-processing-controller.ts
+++ b/src/core/services/subtitle-processing-controller.ts
@@ -43,6 +43,8 @@ export interface SubtitleProcessingController {
*/
notePlainSubtitleEmitted: (text: string) => void;
invalidateTokenizationCache: () => void;
+ /** Incremented by invalidateTokenizationCache; lets async writers detect stale results. */
+ getCacheGeneration: () => number;
preCacheTokenization: (text: string, data: SubtitleData) => void;
consumeCachedSubtitle: (text: string) => SubtitleData | null;
hasCachedSubtitle: (text: string) => boolean;
@@ -253,6 +255,7 @@ export function createSubtitleProcessingController(
tokenizationCache.clear();
cacheGeneration += 1;
},
+ getCacheGeneration: () => cacheGeneration,
preCacheTokenization: (text: string, data: SubtitleData) => {
setCachedTokenization(text, data);
},
diff --git a/src/core/services/tokenizer.test.ts b/src/core/services/tokenizer.test.ts
index 6e24806a..081fbd9a 100644
--- a/src/core/services/tokenizer.test.ts
+++ b/src/core/services/tokenizer.test.ts
@@ -1512,6 +1512,26 @@ test('tokenizeSubtitle keeps Yomitan frequency for noun-particle-noun compounds'
assert.equal(result.tokens?.[0]?.frequencyRank, 581);
});
+test('tokenizeSubtitle skips frequency requests for ranks supplied by the scanner', async () => {
+ const deps = makeDepsFromYomitanTokens(
+ [{ surface: '猫', reading: 'ねこ', headword: '猫', frequencyRank: 42 }],
+ { getFrequencyDictionaryEnabled: () => true },
+ );
+ const parserWindow = deps.getYomitanParserWindow();
+ assert.ok(parserWindow);
+ deps.getYomitanParserWindow = () => parserWindow;
+ const scripts: string[] = [];
+ const execute = parserWindow.webContents.executeJavaScript.bind(parserWindow.webContents);
+ parserWindow.webContents.executeJavaScript = async (script) => {
+ scripts.push(script);
+ return execute(script);
+ };
+ const result = await tokenizeSubtitle('猫', deps);
+ assert.equal(result.tokens?.[0]?.frequencyRank, 42);
+ assert.ok(scripts.length > 0);
+ assert.equal(scripts.filter((script) => script.includes('getTermFrequencies')).length, 0);
+});
+
test('tokenizeSubtitle keeps frequency for ordinal prefix-noun tokens', async () => {
const result = await tokenizeSubtitle(
'第二走者',
diff --git a/src/core/services/tokenizer.ts b/src/core/services/tokenizer.ts
index 1a8e8de0..4aad3374 100644
--- a/src/core/services/tokenizer.ts
+++ b/src/core/services/tokenizer.ts
@@ -494,6 +494,7 @@ function buildYomitanFrequencyTermReadingList(
): Array<{ term: string; reading: string | null }> {
const termReadingList: Array<{ term: string; reading: string | null }> = [];
for (const token of tokens) {
+ if (normalizePositiveFrequencyRank(token.frequencyRank) !== null) continue;
const readingRaw =
token.reading && token.reading.trim().length > 0 ? token.reading.trim() : null;
for (const term of resolveYomitanFrequencyLookupTexts(token, matchMode)) {
diff --git a/src/core/services/tokenizer/hachidori-anki-settings.test.ts b/src/core/services/tokenizer/hachidori-anki-settings.test.ts
new file mode 100644
index 00000000..ab93eeae
--- /dev/null
+++ b/src/core/services/tokenizer/hachidori-anki-settings.test.ts
@@ -0,0 +1,191 @@
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+import test from 'node:test';
+import { pathToFileURL } from 'node:url';
+import vm from 'node:vm';
+import { buildHachidoriAnkiHints, HACHIDORI_ANKI_SETTINGS_SCRIPT } from './hachidori-anki-settings';
+
+const extensionPath = path.resolve(__dirname, '../../../../vendor/hachidori/extension');
+const config = {
+ tags: ['SubMiner', 'Japanese'],
+ fields: { word: 'Term', sentence: 'Context', wordAudio: 'Pronunciation', image: 'Image' },
+};
+const modelFields = ['Term', 'Reading', 'Definition', 'Context', 'Pronunciation', 'Image'];
+
+async function harness(
+ anki: unknown = {},
+ models: Record = { Japanese: modelFields },
+) {
+ const templates: unknown = await import(
+ pathToFileURL(path.join(extensionPath, 'anki-templates.js')).href
+ );
+ const setup: unknown = await import(
+ pathToFileURL(path.join(extensionPath, 'anki-setup.js')).href
+ );
+ const context = vm.createContext({
+ __templates: templates,
+ __setup: setup,
+ __initialAnki: anki,
+ __models: models,
+ structuredClone,
+ URL,
+ });
+ vm.runInContext('globalThis.window = globalThis', context);
+ vm.runInContext(await readFile(path.join(extensionPath, 'reader-options.js'), 'utf8'), context);
+ vm.runInContext(
+ `
+ let options = { ...HDReaderOptions.normaliseOptions({ anki: __initialAnki }), revision: 1 };
+ let writes = 0, online = true, race = false, proxy = null, failWrites = false;
+ const readOptions = async () => structuredClone(options);
+ globalThis.__subminerSetAnkiProxyUrl = async value => { const old = proxy; proxy = value; return old; };
+ const send = async (type, request, target) => {
+ if (type !== 'hd_options_write' || target !== 'hoshidicts-worker') throw Error('Unexpected request');
+ if (failWrites) throw Error('offline');
+ if (race) {
+ race = false;
+ options.anki.templates[0].tags = options.anki.tags = ['User edit'];
+ options.revision++;
+ }
+ if (request.baseRevision !== options.revision) throw Error('conflict');
+ options = { ...HDReaderOptions.normaliseOptions({ ...options, ...request.options }), revision: options.revision + 1 };
+ writes++;
+ };
+ const __gateway = { createAnkiGateway: () => ({ discover: async ({ model }) => ({
+ connected: online, model, models: Object.keys(__models), decks: ['Mining'],
+ fields: __models[model] || [], errors: online ? [] : ['offline'],
+ }) }) };
+ `,
+ context,
+ );
+ await vm.runInContext(
+ HACHIDORI_ANKI_SETTINGS_SCRIPT.replace("await import('./anki-templates.js')", '__templates')
+ .replace("await import('./anki-setup.js')", '__setup')
+ .replace("await import('./anki.js')", '__gateway'),
+ context,
+ );
+ const run = async (script: string): Promise =>
+ structuredClone(await vm.runInContext(script, context));
+ const sync = () =>
+ run(
+ `__subminerSyncAnkiSettings(${JSON.stringify({
+ server: 'http://127.0.0.1:8766',
+ deck: 'Mining',
+ forceOverride: true,
+ hints: buildHachidoriAnkiHints(config),
+ })})`,
+ );
+ return { run, sync };
+}
+
+test('fresh Hachidori settings inherit deck, tags, a unique model and configured fields', async () => {
+ const h = await harness();
+ assert.deepEqual(await h.sync(), { updated: true, matched: true, pending: false });
+ assert.deepEqual(
+ await h.run('[options.anki.url, options.anki.deck, options.anki.model, options.anki.tags]'),
+ ['http://127.0.0.1:8766', 'Mining', 'Japanese', [...config.tags, 'hachidori']],
+ );
+ assert.deepEqual(
+ await h.run(
+ 'Object.fromEntries(Object.entries(options.anki.fieldTemplates).map(([key, row]) => [key, row.value]))',
+ ),
+ {
+ Term: '{expression}',
+ Reading: '{reading}',
+ Definition: '{definition}',
+ Context: '{sentence}',
+ Pronunciation: '{audio}',
+ Image: '{screenshot}',
+ },
+ );
+ await h.sync();
+ assert.equal(await h.run('writes'), 1);
+});
+
+test('leaves tags edited in Hachidori settings alone', async () => {
+ const h = await harness({
+ templates: [
+ { id: 'default', name: 'Default', deck: 'Mining', model: 'Japanese', tags: ['SubMiner'] },
+ ],
+ });
+ await h.sync();
+ assert.deepEqual(await h.run('options.anki.tags'), ['SubMiner']);
+});
+
+// SubMiner's new-card polling only watches ankiConnect.deck, so the first
+// template's deck follows it the way Yomitan's term card deck does.
+test('moves the first template to the SubMiner deck and preserves the rest of custom templates', async () => {
+ const h = await harness({
+ templates: [
+ {
+ id: 'default',
+ name: 'Custom',
+ deck: 'Own deck',
+ model: 'Japanese',
+ tags: ['own'],
+ fieldTemplates: {
+ Term: { value: '{reading}', overwriteMode: 'overwrite' },
+ Context: { value: '', overwriteMode: 'coalesce' },
+ },
+ },
+ { id: 'second', name: 'Second', deck: 'Other', model: 'Other', tags: [] },
+ ],
+ });
+ const before = (await h.run('options.anki.templates')) as Array>;
+ await h.sync();
+ assert.deepEqual(await h.run('options.anki.templates'), [
+ { ...before[0], deck: 'Mining' },
+ ...before.slice(1),
+ ]);
+ assert.equal(await h.run('options.anki.deck'), 'Mining');
+});
+
+test('leaves an ambiguous model unset and retries discovery after Anki reconnects', async () => {
+ const h = await harness({}, { Japanese: modelFields, Second: modelFields });
+ await h.run('online = false');
+ assert.deepEqual(await h.sync(), { updated: true, matched: false, pending: true });
+ assert.equal(await h.run('options.anki.deck'), 'Mining');
+ await h.run('online = true');
+ await h.sync();
+ assert.equal(await h.run('options.anki.model'), '');
+ await h.run('delete __models.Second');
+ await h.sync();
+ assert.equal(await h.run('options.anki.model'), 'Japanese');
+});
+
+test('fills missing basic mappings only with fields belonging to the selected model', async () => {
+ const h = await harness(
+ { model: 'Japanese', fields: { expression: 'Reading' } },
+ { Japanese: ['Term', 'Reading', 'Context'] },
+ );
+ await h.sync();
+ assert.deepEqual(
+ await h.run(
+ '[options.anki.fields.expression, options.anki.fields.sentence, options.anki.fields.audio, options.anki.fieldTemplates]',
+ ),
+ ['Reading', 'Context', '', null],
+ );
+});
+
+test('re-reads concurrent settings edits before retrying its revisioned write', async () => {
+ const h = await harness();
+ await h.run('race = true');
+ await h.sync();
+ assert.deepEqual(await h.run('options.anki.tags'), ['User edit']);
+ assert.equal(await h.run('options.anki.model'), 'Japanese');
+});
+
+test('restores the previous proxy marker when every settings write fails', async () => {
+ const h = await harness();
+ await h.run(`proxy = 'http://127.0.0.1:9000'; failWrites = true`);
+ await assert.rejects(h.sync(), /offline/);
+ assert.equal(await h.run('proxy'), 'http://127.0.0.1:9000');
+});
+
+test('keeps sentence audio out of captured-audio settings and uses wordAudio first', () => {
+ const hints = buildHachidoriAnkiHints({
+ fields: { audio: 'SentenceAudio', wordAudio: 'WordAudio' },
+ });
+ assert.equal(hints.fields.audio, 'WordAudio');
+ assert.equal('captureAudio' in hints.fields, false);
+});
diff --git a/src/core/services/tokenizer/hachidori-anki-settings.ts b/src/core/services/tokenizer/hachidori-anki-settings.ts
new file mode 100644
index 00000000..b4f8d6c4
--- /dev/null
+++ b/src/core/services/tokenizer/hachidori-anki-settings.ts
@@ -0,0 +1,126 @@
+import type { AnkiConnectConfig } from '../../../types';
+
+// Only settings with the same meaning in both apps cross this boundary.
+export function buildHachidoriAnkiHints(config: AnkiConnectConfig) {
+ return {
+ tags: config.tags,
+ fields: {
+ expression: config.fields?.word?.trim(),
+ audio: (config.fields?.wordAudio || config.fields?.audio)?.trim(),
+ sentence: config.fields?.sentence?.trim(),
+ screenshot: config.fields?.image?.trim(),
+ },
+ model: config.isLapis?.enabled ? config.isLapis.sentenceCardModel?.trim() : undefined,
+ family: config.isLapis?.enabled
+ ? 'lapis'
+ : config.isKiku?.enabled
+ ? 'kiku'
+ : config.isSenren?.enabled
+ ? 'senren'
+ : undefined,
+ };
+}
+
+// Installed inside the hidden Hachidori settings page. Uses local option writes
+// even when dictionaries are remote or their host is offline.
+export const HACHIDORI_ANKI_SETTINGS_SCRIPT = String.raw`
+ globalThis.__subminerSyncAnkiSettings = async ({ server, deck, forceOverride, hints }) => {
+ const previousProxy = await globalThis.__subminerSetAnkiProxyUrl(forceOverride ? server : null);
+ const { applyAnkiPreset, resolveAnkiTemplates } = await import('./anki-templates.js');
+ const { ankiSetupFamily } = await import('./anki-setup.js');
+ const { createAnkiGateway } = await import('./anki.js');
+ const gateway = createAnkiGateway({ timeoutMs: 2000 });
+ const discoveries = new Map();
+ const discover = async (anki, model) => {
+ const key = JSON.stringify([anki.url, anki.apiKey, model]);
+ if (!discoveries.has(key)) discoveries.set(key, gateway.discover({ ...anki, model }));
+ return discoveries.get(key);
+ };
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ const options = await readOptions();
+ let anki = options.anki;
+ const canReplaceServer = forceOverride || !anki.url || anki.url === server
+ || anki.url === 'http://127.0.0.1:8765' || anki.url === previousProxy;
+ if (!canReplaceServer) return { updated: false, matched: false, reason: 'blocked-existing-server' };
+ anki = { ...anki, url: server };
+ const first = anki.templates[0];
+ if (!first) return { updated: false, matched: false, reason: 'no-templates' };
+ let template = { ...first, fields: { ...first.fields } };
+ // SubMiner's new-card polling only watches its configured deck, so the
+ // first template follows it like Yomitan's term card deck.
+ if (deck) template.deck = deck;
+ // SubMiner's tags join Hachidori's own so cards show which backend mined
+ // them. Only the untouched default is filled; edits in Hachidori settings win.
+ if (hints?.tags && JSON.stringify(first.tags) === JSON.stringify(['hachidori'])) {
+ template.tags = [...new Set([...hints.tags, 'hachidori'])];
+ }
+ let pending = false;
+ // Advanced templates include intentionally blank fields. Preserve them
+ // as a unit rather than replacing them with inferred mappings.
+ if (hints && first.fieldTemplates === null) {
+ let discovery = await discover(anki, template.model || hints.model || '');
+ if (!discovery.connected) {
+ pending = true;
+ } else {
+ if (!template.model) {
+ const candidates = hints.model
+ ? discovery.models.filter(model => model === hints.model)
+ : discovery.models.filter(model => !hints.family || ankiSetupFamily(model) === hints.family);
+ const anchors = [hints.fields.expression, hints.fields.sentence].filter(Boolean);
+ const matches = [];
+ // Require a configured word and sentence field for an inferred
+ // model. Never choose the first of several compatible note types.
+ if (anchors.length === 2) for (const model of candidates) {
+ const result = await discover(anki, model);
+ if (!result.connected || result.errors.length) { pending = true; break; }
+ if (anchors.every(field => result.fields.includes(field))) matches.push(result);
+ }
+ if (!pending && matches.length === 1) {
+ discovery = matches[0];
+ template.model = discovery.model;
+ }
+ }
+ if (template.model && discovery.model === template.model && discovery.fields.length) {
+ const fields = discovery.fields;
+ for (const [semantic, field] of Object.entries(hints.fields)) {
+ if (!template.fields[semantic] && field && fields.includes(field)) template.fields[semantic] = field;
+ }
+ if (Object.values(first.fields).every(value => !value)) {
+ const preset = applyAnkiPreset(template, fields, ankiSetupFamily(template.model) || 'automatic');
+ const configured = resolveAnkiTemplates(template, fields).templates;
+ const markers = new Set(Object.entries(template.fields)
+ .filter(([, value]) => value).map(([key]) => '{' + key + '}'));
+ for (const row of Object.values(preset.fieldTemplates)) {
+ for (const marker of markers) row.value = row.value.replaceAll(marker, '');
+ }
+ for (const [field, row] of Object.entries(configured)) {
+ if (row.value) preset.fieldTemplates[field] = row;
+ }
+ template = preset;
+ }
+ }
+ }
+ }
+ // Hachidori retains a compatibility projection of its first template.
+ // Updating both prevents its normalizer from restoring stale values.
+ const templateConfig = Object.fromEntries(globalThis.HDReaderOptions.ANKI_TEMPLATE_CONFIG_KEYS
+ .map(key => [key, template[key]]));
+ anki = { ...anki, ...templateConfig,
+ templates: [template, ...anki.templates.slice(1)] };
+ const changed = JSON.stringify(anki) !== JSON.stringify(options.anki);
+ try {
+ if (changed) await send('hd_options_write', {
+ baseRevision: options.revision, options: { anki },
+ }, 'hoshidicts-worker');
+ return { updated: changed, matched: !pending, pending };
+ } catch (error) {
+ if (attempt > 0) {
+ // The server was never written, so the marker must not claim it.
+ await globalThis.__subminerSetAnkiProxyUrl(previousProxy);
+ throw error;
+ }
+ // Re-read after a concurrent settings save before filling anything.
+ }
+ }
+ };
+`;
diff --git a/src/core/services/tokenizer/hachidori-dictionary-import.test.ts b/src/core/services/tokenizer/hachidori-dictionary-import.test.ts
new file mode 100644
index 00000000..7afa8fce
--- /dev/null
+++ b/src/core/services/tokenizer/hachidori-dictionary-import.test.ts
@@ -0,0 +1,87 @@
+import assert from 'node:assert/strict';
+import { mkdtemp, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+import { importYomitanDictionaryFromZip } from './yomitan-parser-runtime';
+import { createDeps } from './yomitan-scan-test-harness';
+
+// Hachidori deps whose sharing status reports `host`, recording every archive the
+// settings automation imports (locally or forwarded over the link).
+function hachidoriDeps(host: Record | null) {
+ const imported: string[] = [];
+ const runScript = async (script: string): Promise => {
+ if (script.includes('hd_sharing_status')) {
+ return {
+ ok: true,
+ sharing: {
+ client: host
+ ? { linked: true, connected: true, address: 'ws://desktop:8771/link', host }
+ : { linked: false },
+ },
+ };
+ }
+ const archiveUrl = /importDictionaryArchiveUrl\(\s*("[^"]+")/.exec(script)?.[1];
+ if (archiveUrl) imported.push(await (await fetch(JSON.parse(archiveUrl))).text());
+ return true;
+ };
+ const settingsWindow = {
+ isDestroyed: () => false,
+ destroy: () => undefined,
+ webContents: { executeJavaScript: runScript },
+ };
+ return {
+ imported,
+ deps: {
+ ...createDeps(runScript, { createYomitanExtensionWindow: async () => settingsWindow }),
+ getYomitanExt: () => ({
+ id: 'hachi',
+ name: 'Hachidori',
+ version: '1',
+ path: '',
+ url: '',
+ manifest: {},
+ }),
+ },
+ };
+}
+
+async function writeArchive(): Promise {
+ const zipPath = path.join(await mkdtemp(path.join(os.tmpdir(), 'hachi-import-')), 'merged.zip');
+ await writeFile(zipPath, 'PK-test');
+ return zipPath;
+}
+
+for (const [name, host] of [
+ ['an unlinked Hachidori imports the ZIP itself', null],
+ [
+ 'a linked host that accepts imports gets the ZIP over the link',
+ { name: 'Helium', dictionaryCount: 8, capabilities: ['linked-import-v1'] },
+ ],
+] as const) {
+ test(name, async () => {
+ const { deps, imported } = hachidoriDeps(host);
+ assert.equal(
+ await importYomitanDictionaryFromZip(await writeArchive(), deps, { error: assert.fail }),
+ true,
+ );
+ assert.deepEqual(imported, ['PK-test']);
+ });
+}
+
+test('a linked host without linked imports fails with the update or manual-import fix', async () => {
+ const { deps, imported } = hachidoriDeps({ name: 'Chrome', dictionaryCount: 8 });
+ const zipPath = await writeArchive();
+ const errors: string[] = [];
+ assert.equal(
+ await importYomitanDictionaryFromZip(zipPath, deps, {
+ error: (...parts: unknown[]) => errors.push(parts.join(' ')),
+ }),
+ false,
+ );
+ assert.deepEqual(imported, []);
+ assert.match(
+ errors[0] ?? '',
+ /Update its Hachidori to 0\.2\.3 or later, or import .*merged\.zip/,
+ );
+});
diff --git a/src/core/services/tokenizer/hachidori-parser-bridge.test.ts b/src/core/services/tokenizer/hachidori-parser-bridge.test.ts
new file mode 100644
index 00000000..d371f765
--- /dev/null
+++ b/src/core/services/tokenizer/hachidori-parser-bridge.test.ts
@@ -0,0 +1,559 @@
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+import test from 'node:test';
+import { pathToFileURL } from 'node:url';
+import * as vm from 'node:vm';
+import { HACHIDORI_PARSER_BRIDGE_SCRIPT } from './hachidori-parser-bridge';
+import {
+ requestYomitanScanTokens,
+ requestYomitanParseResults,
+ requestYomitanTermFrequencies,
+ syncYomitanDefaultAnkiServer,
+ addYomitanNoteViaSearch,
+} from './yomitan-parser-runtime';
+import { createDeps } from './yomitan-scan-test-harness';
+import { selectYomitanParseTokens } from './parser-selection-stage';
+
+const extensionPath = path.resolve(__dirname, '../../../../vendor/hachidori/extension');
+const characterDictionary = 'SubMiner Character Dictionary (AniList 1)';
+
+function lookupResult(matched: string, expression: string, reading: string, dictionary = 'JMdict') {
+ return {
+ matched,
+ deinflected: expression,
+ trace: [],
+ term: {
+ expression,
+ reading,
+ score: 0,
+ rules: 'v1',
+ glossaries: [{ dictionary, glossary: '["definition"]', termTags: '', definitionTags: '' }],
+ pitches: [],
+ frequencies: [{ dictionary: 'Frequency', frequencies: [{ value: 42, displayValue: '' }] }],
+ },
+ };
+}
+
+type UploadReply = Record;
+// The parts of vendor/hachidori/extension/linked-import.js the harness drives.
+type LinkedImportModule = {
+ createUploadHost(options: {
+ store: {
+ append(token: string, data: string): void;
+ discard(token: string): void;
+ };
+ importUpload(
+ token: string,
+ upload: { fileName: string; replace: boolean },
+ ): Promise;
+ setTimer(): number;
+ clearTimer(): void;
+ }): {
+ begin(message: UploadReply, owner: string): UploadReply;
+ chunk(message: UploadReply, owner: string): Promise;
+ commit(message: UploadReply, owner: string): Promise;
+ abort(message: UploadReply, owner: string): UploadReply;
+ };
+};
+
+async function createHarness(emptyLibrary = false) {
+ const messages: Array> = [];
+ let dictionaryRevision = 2;
+ let optionRevision = 3;
+ let anki = {
+ url: 'http://127.0.0.1:8765',
+ templates: [
+ { id: 'default', name: 'Default', deck: 'Old', model: 'Japanese', fields: {} },
+ { id: 'second', name: 'Second', deck: 'Other', model: 'Japanese', fields: {} },
+ ],
+ };
+ let dictionaries = [
+ { id: 'terms', title: 'JMdict', displayName: 'Main dictionary', enabled: true, revision: '1' },
+ { id: 'names', title: characterDictionary, enabled: true, revision: '1' },
+ {
+ id: 'frequency',
+ title: 'Frequency',
+ enabled: true,
+ revision: '1',
+ frequencyMode: 'rank-based',
+ frequencyCount: 1,
+ },
+ ];
+ let duplicate = false;
+ let proxyUrl: unknown;
+ let loadingStatusReplies = 0;
+ let busyEngineReplies = 0;
+ const uploads: Array<{ fileName: string; replace: boolean; bytes: Buffer }> = [];
+ const apiModule: unknown = await import(
+ pathToFileURL(path.join(extensionPath, 'api-host.js')).href
+ );
+ const linkedImportModule = (await import(
+ pathToFileURL(path.join(extensionPath, 'linked-import.js')).href
+ )) as LinkedImportModule;
+ // Hachidori's own upload host, with the engine import replaced by a recorder.
+ const uploadParts = new Map();
+ const uploadHost = linkedImportModule.createUploadHost({
+ store: {
+ append: (token: string, data: string) => {
+ uploadParts.set(token, [...(uploadParts.get(token) ?? []), Buffer.from(data, 'base64')]);
+ },
+ discard: (token: string) => {
+ uploadParts.delete(token);
+ },
+ },
+ importUpload: async (
+ token: string,
+ { fileName, replace }: { fileName: string; replace: boolean },
+ ) => {
+ uploads.push({ fileName, replace, bytes: Buffer.concat(uploadParts.get(token) ?? []) });
+ return { ok: true, report: { success: true } };
+ },
+ setTimer: () => 0,
+ clearTimer: () => {},
+ });
+ const context = vm.createContext({
+ __testApiModule: apiModule,
+ __testLinkedImportModule: linkedImportModule,
+ setTimeout,
+ crypto,
+ URL,
+ Blob,
+ Uint8Array,
+ atob,
+ chrome: {
+ storage: {
+ local: {
+ set: async (value: Record) => {
+ proxyUrl = value.subminerAnkiProxyUrl;
+ },
+ get: async () => ({
+ options: { anki, scanLength: 40, revision: optionRevision },
+ subminerAnkiProxyUrl: proxyUrl,
+ }),
+ },
+ },
+ runtime: {
+ getManifest: () => ({ version: 'test' }),
+ sendMessage: async (message: Record) => {
+ messages.push(structuredClone(message));
+ if (message.target === 'hachidori-linked-import') {
+ // Mirrors background.js answerUploadRequest: commit answers with the import reply.
+ try {
+ switch (message.type) {
+ case 'hd_import_begin':
+ return { ok: true, ...uploadHost.begin(message, 'local') };
+ case 'hd_import_chunk':
+ return { ok: true, ...(await uploadHost.chunk(message, 'local')) };
+ case 'hd_import_abort':
+ return { ok: true, ...uploadHost.abort(message, 'local') };
+ default:
+ return await uploadHost.commit(message, 'local');
+ }
+ } catch (error) {
+ return { ok: false, error: (error as Error).message };
+ }
+ }
+ if (message.type === 'hd_status') {
+ const loading = loadingStatusReplies > 0;
+ if (loading) loadingStatusReplies -= 1;
+ return { ok: true, ready: !loading, loading };
+ }
+ if (busyEngineReplies > 0 && message.target !== 'hachidori-anki') {
+ busyEngineReplies -= 1;
+ return { ok: false, error: 'the dictionary engine is busy mutating' };
+ }
+ switch (message.type) {
+ case 'hd_state_read':
+ return {
+ ok: true,
+ state: emptyLibrary ? null : { revision: dictionaryRevision, dictionaries },
+ };
+ case 'hd_lookup': {
+ const text = String(message.text);
+ const candidates = [
+ lookupResult('食べた', '食べる', 'たべる'),
+ lookupResult('食べる', '食べる', 'たべる'),
+ lookupResult('ミナト', 'ミナト', 'みなと', characterDictionary),
+ ];
+ return {
+ ok: true,
+ generation: 1,
+ results: candidates.filter((result) => text.startsWith(result.matched)),
+ };
+ }
+ case 'hd_options_write': {
+ if (message.baseRevision !== optionRevision) return { ok: false, error: 'conflict' };
+ const update = message.options;
+ assert.ok(update && typeof update === 'object' && 'anki' in update);
+ const value = update.anki;
+ assert.ok(
+ value &&
+ typeof value === 'object' &&
+ 'url' in value &&
+ typeof value.url === 'string',
+ );
+ assert.ok('templates' in value && Array.isArray(value.templates));
+ anki = { url: value.url, templates: value.templates };
+ optionRevision += 1;
+ return { ok: true };
+ }
+ case 'hd_apply_state': {
+ assert.equal(message.baseRevision, dictionaryRevision);
+ assert.ok(Array.isArray(message.dictionaries));
+ dictionaries = message.dictionaries;
+ dictionaryRevision += 1;
+ return { ok: true };
+ }
+ case 'hd_anki_status':
+ return { ok: true, configKey: 'configuration' };
+ case 'hd_anki_preflight':
+ return {
+ ok: true,
+ canAdd: !duplicate,
+ state: duplicate ? 'duplicate' : 'addable',
+ noteIds: duplicate ? [15] : [],
+ };
+ case 'hd_anki_submit':
+ return { ok: true, state: 'added', noteId: 19 };
+ case 'hd_remove':
+ return { ok: true };
+ default:
+ throw new Error('Unexpected native request: ' + String(message.type));
+ }
+ },
+ },
+ },
+ });
+ vm.runInContext('globalThis.window = globalThis', context);
+ vm.runInContext(await readFile(path.join(extensionPath, 'reader-options.js'), 'utf8'), context);
+ const script = HACHIDORI_PARSER_BRIDGE_SCRIPT.replace(
+ "await import('./api-host.js')",
+ '__testApiModule',
+ )
+ .replace("await import('./linked-import.js')", '__testLinkedImportModule')
+ .replace("await import('./reader-options.js')", 'Promise.resolve()');
+ await vm.runInContext(script, context);
+ const run = async (code: string): Promise =>
+ structuredClone(await vm.runInContext(code, context));
+ const invoke = (action: string, params?: unknown) =>
+ run(`new Promise((resolve, reject) => {
+ __subminerDictionarySendMessage(${JSON.stringify({ action, params })}, response => {
+ if (response.error) reject(new Error(response.error.message)); else resolve(response.result);
+ });
+ })`);
+ return {
+ deps: createDeps(run),
+ run,
+ invoke,
+ messages,
+ anki: () => anki,
+ proxyUrl: () => proxyUrl,
+ setAnkiServer: (url: string) => {
+ anki = { ...anki, url };
+ },
+ setAnkiTemplates: (templates: typeof anki.templates) => {
+ anki = { ...anki, templates };
+ },
+ dictionaries: () => dictionaries,
+ disableDictionary: (id: string) => {
+ dictionaries = dictionaries.map((entry) =>
+ entry.id === id ? { ...entry, enabled: false } : entry,
+ );
+ dictionaryRevision += 1;
+ },
+ setDuplicate: () => {
+ duplicate = true;
+ },
+ changeRevision: () => {
+ optionRevision += 1;
+ },
+ setLoadingStatusReplies: (count: number) => {
+ loadingStatusReplies = count;
+ },
+ setBusyEngineReplies: (count: number) => {
+ busyEngineReplies = count;
+ },
+ uploads: () => uploads,
+ };
+}
+
+test('Hachidori runs the shared scanner with inflected offsets, headwords, names and frequencies', async () => {
+ const harness = await createHarness();
+ const tokens = await requestYomitanScanTokens(
+ 'ミナト 食べた',
+ harness.deps,
+ { error: assert.fail },
+ {
+ includeNameMatchMetadata: true,
+ currentCharacterDictionaryMediaId: 1,
+ },
+ );
+ assert.ok(tokens);
+ assert.equal(tokens[0]?.surface, 'ミナト');
+ assert.equal(tokens[0]?.isNameMatch, true);
+ assert.equal(tokens[1]?.surface, '食べた');
+ assert.equal(tokens[1]?.headword, '食べる');
+ 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 frequencies = await requestYomitanTermFrequencies(
+ [{ term: '食べる', reading: 'たべる' }],
+ harness.deps,
+ { error: assert.fail },
+ );
+ assert.equal(frequencies[0]?.frequency, 42);
+ assert.equal(frequencies[0]?.dictionary, 'Frequency');
+});
+
+test('Hachidori frequency lookups match API headwords, readings and requested dictionaries', async () => {
+ const harness = await createHarness();
+ const query = (term: string, reading: string | null, dictionaries = ['Frequency']) =>
+ harness.invoke('getTermFrequencies', { termReadingList: [{ term, reading }], dictionaries });
+ assert.deepEqual(await query('食べる', 'たべる'), [
+ {
+ term: '食べる',
+ reading: 'たべる',
+ hasReading: false,
+ dictionary: 'Frequency',
+ frequency: 42,
+ displayValue: null,
+ displayValueParsed: false,
+ },
+ ]);
+ assert.deepEqual(await query('食べる', 'べつのよみ'), []);
+ assert.deepEqual(await query('食べる', null, ['Other frequency']), []);
+ assert.deepEqual(await query('食べるだけ', null), []);
+ assert.deepEqual(await query('頻度だけ', null), []);
+ assert.deepEqual(await query('食べる', null), await query('食べる', 'たべる'));
+});
+
+test('Hachidori syncs the Anki endpoint and every term template through revisioned writes', async () => {
+ const harness = await createHarness();
+ const synced = await syncYomitanDefaultAnkiServer(
+ 'http://127.0.0.1:8766',
+ harness.deps,
+ { error: assert.fail },
+ { deck: 'Mining' },
+ );
+ assert.equal(synced, true);
+ assert.equal(harness.anki().url, 'http://127.0.0.1:8766');
+ assert.deepEqual(
+ harness.anki().templates.map((template) => template.deck),
+ ['Mining', 'Mining'],
+ );
+ assert.equal(harness.proxyUrl(), null);
+ assert.equal(
+ await syncYomitanDefaultAnkiServer(
+ 'http://127.0.0.1:8766',
+ harness.deps,
+ { error: assert.fail },
+ { forceOverride: true },
+ ),
+ true,
+ );
+ assert.equal(harness.proxyUrl(), 'http://127.0.0.1:8766');
+ await assert.rejects(
+ harness.invoke('setAllSettings', {
+ value: {
+ hachidoriRevisions: { dictionaries: 99, options: 99 },
+ profiles: [{ options: { dictionaries: [], anki: { server: '', cardFormats: [] } } }],
+ },
+ }),
+ /settings changed/,
+ );
+});
+
+test('Hachidori applies only SubMiner changes when its settings moved on meanwhile', async () => {
+ const harness = await createHarness();
+ const projected = (await harness.invoke('optionsGetFull')) as {
+ profiles: Array<{ options: { dictionaries: Array<{ name: string; enabled: boolean }> } }>;
+ };
+ const jmdict = projected.profiles[0]!.options.dictionaries.find(
+ (entry) => entry.name === 'JMdict',
+ );
+ jmdict!.enabled = false;
+ // Hachidori changed both revisions after SubMiner read them.
+ harness.disableDictionary('names');
+ harness.setAnkiServer('http://192.168.1.10:8765');
+ harness.changeRevision();
+ assert.equal(await harness.invoke('setAllSettings', { value: projected }), true);
+ assert.deepEqual(
+ harness.dictionaries().map((entry) => [entry.id, entry.enabled]),
+ [
+ ['terms', false],
+ ['names', false],
+ ['frequency', true],
+ ],
+ );
+ assert.equal(harness.anki().url, 'http://192.168.1.10:8765');
+ assert.equal(harness.messages.filter((message) => message.type === 'hd_options_write').length, 0);
+});
+
+test('Hachidori settings writes survive an empty template list', async () => {
+ const harness = await createHarness();
+ harness.setAnkiTemplates([]);
+ assert.equal(
+ await syncYomitanDefaultAnkiServer(
+ 'http://127.0.0.1:8766',
+ harness.deps,
+ { error: assert.fail },
+ {
+ forceOverride: true,
+ },
+ ),
+ true,
+ );
+ assert.equal(harness.anki().url, 'http://127.0.0.1:8766');
+});
+
+test('Hachidori initializes an empty library before the first dictionary import', async () => {
+ const harness = await createHarness(true);
+ assert.deepEqual(await harness.invoke('getDictionaryInfo'), []);
+ assert.equal(
+ await syncYomitanDefaultAnkiServer(
+ 'http://127.0.0.1:8766',
+ harness.deps,
+ { error: assert.fail },
+ { forceOverride: true },
+ ),
+ true,
+ );
+});
+
+test('Hachidori restores direct AnkiConnect when disabling its managed proxy', async () => {
+ const harness = await createHarness();
+ const logger = { error: assert.fail };
+ assert.equal(
+ await syncYomitanDefaultAnkiServer('http://127.0.0.1:8766', harness.deps, logger, {
+ forceOverride: true,
+ }),
+ true,
+ );
+ assert.equal(harness.anki().url, 'http://127.0.0.1:8766');
+ assert.equal(
+ await syncYomitanDefaultAnkiServer('http://127.0.0.1:8765', harness.deps, logger),
+ true,
+ );
+ assert.equal(harness.anki().url, 'http://127.0.0.1:8765');
+ assert.equal(harness.proxyUrl(), null);
+});
+
+test('Hachidori preserves a custom Anki endpoint when disabling its managed proxy', async () => {
+ const harness = await createHarness();
+ const logger = { error: assert.fail };
+ assert.equal(
+ await syncYomitanDefaultAnkiServer('http://127.0.0.1:8766', harness.deps, logger, {
+ forceOverride: true,
+ }),
+ true,
+ );
+ harness.setAnkiServer('http://192.168.1.10:8765');
+ assert.equal(
+ await syncYomitanDefaultAnkiServer('http://127.0.0.1:8765', harness.deps, logger),
+ false,
+ );
+ assert.equal(harness.anki().url, 'http://192.168.1.10:8765');
+ assert.equal(harness.proxyUrl(), null);
+});
+
+test('Hachidori fallback parsing retains token boundaries, inflected readings and headwords', async () => {
+ const harness = await createHarness();
+ const parsed = await requestYomitanParseResults('ミナト 食べた', harness.deps, {
+ error: assert.fail,
+ });
+ const tokens = selectYomitanParseTokens(parsed, () => false, 'headword');
+ assert.deepEqual(
+ tokens?.map((token) => ({
+ surface: token.surface,
+ headword: token.headword,
+ reading: token.reading,
+ start: token.startPos,
+ })),
+ [
+ { surface: 'ミナト', headword: 'ミナト', reading: 'みなと', start: 0 },
+ { surface: '食べた', headword: '食べる', reading: 'たべた', start: 4 },
+ ],
+ );
+});
+
+test('Hachidori stats mining returns note IDs and prevents duplicate submissions', async () => {
+ const harness = await createHarness();
+ assert.deepEqual(await addYomitanNoteViaSearch('食べる', harness.deps, { error: assert.fail }), {
+ noteId: 19,
+ duplicateNoteIds: [],
+ });
+ harness.setDuplicate();
+ assert.deepEqual(await addYomitanNoteViaSearch('食べる', harness.deps, { error: assert.fail }), {
+ noteId: null,
+ duplicateNoteIds: [15],
+ });
+ assert.equal(harness.messages.filter((message) => message.type === 'hd_anki_submit').length, 1);
+});
+
+test('Hachidori mining requests render native dictionary aliases and frequency markers', async () => {
+ const harness = await createHarness();
+ await addYomitanNoteViaSearch('食べる', harness.deps, { error: assert.fail });
+ const request = harness.messages.find((message) => message.type === 'hd_anki_preflight')?.request;
+ assert.ok(request && typeof request === 'object');
+ assert.ok('subminerEnrich' in request && request.subminerEnrich === false);
+ const native: unknown = await import(
+ pathToFileURL(path.join(extensionPath, 'anki-values.js')).href
+ );
+ assert.ok(native && typeof native === 'object' && 'buildAnkiFields' in native);
+ assert.equal(typeof native.buildAnkiFields, 'function');
+ if (typeof native.buildAnkiFields !== 'function') assert.fail('Native renderer is unavailable');
+ const fields: unknown = await native.buildAnkiFields(
+ request,
+ {
+ Dictionary: { value: '{dictionary-alias}' },
+ Frequency: { value: '{single-frequency-frequency}' },
+ Rank: { value: '{frequency-harmonic-rank}' },
+ },
+ {},
+ );
+ assert.deepEqual(fields, {
+ Dictionary: 'Main dictionary',
+ Frequency: '
Import dictionaries through Hachidori Settings to keep them in SubMiner, or connect to an existing library below.
+
+ Use an external dictionary host
+
Connect to Hachidori in another app, browser, or Docker container to use the dictionaries already installed there. You won't need to import a second copy into SubMiner.
+
Dictionaries and their settings are shared. You still mine cards in SubMiner, using its own Anki settings, audio, and screenshots.
+
+
Browser: keep the browser and its sharing relay running. If the relay runs through Anki, keep Anki open too.
+
Desktop app: keep the app sharing your dictionaries and any required relay running.
+
Docker: keep the dictionary container running. You can close its browser management page.
+
+
If that app or container stops or loses its connection, dictionary lookups will be unavailable until it reconnects.