mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-04-10 04:19:25 -07:00
Compare commits
30 Commits
v0.7.1
...
b7e0026d48
| Author | SHA1 | Date | |
|---|---|---|---|
|
b7e0026d48
|
|||
|
207151dba3
|
|||
|
c6e6aeebbe
|
|||
|
e9fc6bf8ec
|
|||
|
2e43d95396
|
|||
|
3e7615b3bd
|
|||
|
1f48ff000c
|
|||
|
ba9bae63e4
|
|||
|
415c758840
|
|||
|
ff72976bae
|
|||
|
0def04b09c
|
|||
|
6bf148514e
|
|||
|
07b91f8704
|
|||
|
d8a7ae77b0
|
|||
|
809b57af44
|
|||
|
ef716b82c7
|
|||
|
d65575c80d
|
|||
|
8da3a26855
|
|||
|
8928bfdf7e
|
|||
|
16f7b2507b
|
|||
|
7d8d2ae7a7
|
|||
|
3fb33af116
|
|||
|
8ddace5536
|
|||
|
e7242d006f
|
|||
|
7666a094f4
|
|||
| 0317c7f011 | |||
|
13797b5005
|
|||
|
b24d9d7487
|
|||
| 3a01cffc6b | |||
|
eddf6f0456
|
26
CHANGELOG.md
26
CHANGELOG.md
@@ -1,5 +1,31 @@
|
||||
# Changelog
|
||||
|
||||
## v0.9.0 (2026-03-22)
|
||||
|
||||
### Changed
|
||||
- Subtitle Sidebar: Added subtitle sidebar state and behavior updates, including startup-auto-open controls and resume positioning improvements.
|
||||
- Subtitle Sidebar: Fixed subtitle prefetch and embedded overlay passthrough sync between sidebar and overlay subtitle rendering.
|
||||
- Launcher: Added an app-owned YouTube subtitle picker flow that boots mpv paused, opens an overlay track picker, and downloads selected subtitles into external files.
|
||||
- Launcher: Added explicit `download` and `generate` YouTube subtitle modes with `download` as the default path.
|
||||
- Launcher: Disabled mpv native YouTube subtitle auto-loading for the app-owned flow so external subtitle files stay authoritative.
|
||||
- Launcher: Added OSD status messages for YouTube playback startup, subtitle acquisition, and subtitle loading so the flow stays visible before and during the picker.
|
||||
|
||||
## v0.8.0 (2026-03-22)
|
||||
|
||||
### Added
|
||||
- Overlay: Added the subtitle sidebar feature with a new `subtitleSidebar` configuration surface and rendered sidebar modal with cue list rendering, click-to-seek, active-cue highlighting, and embedded layout support.
|
||||
- IPC: Added sidebar snapshot plumbing between renderer and main process for overlay/sidebar synchronization.
|
||||
|
||||
### Changed
|
||||
- Config: Added hot-reloadable sidebar options for enablement, layout, visibility, typography, opacity, sizing, and interaction behavior (`autoOpen`, `pauseOnHover`, `autoScroll`, toggle key).
|
||||
- Docs: Added full `subtitleSidebar` documentation coverage, including sample config, option table, and toggle shortcut notes.
|
||||
- Runtime: Improved subtitle prefetch/rendering flow so sidebar and overlay subtitle states stay in sync across media transitions.
|
||||
|
||||
### Fixed
|
||||
- Overlay: Kept sidebar cue tracking stable across playback transitions and timing edge cases.
|
||||
- Overlay: Improved sidebar resume/start behavior to jump directly to the first resolved active cue.
|
||||
- Overlay: Stopped stale subtitle refreshes from regressing active-cue and text state.
|
||||
|
||||
## v0.7.0 (2026-03-19)
|
||||
|
||||
### Added
|
||||
|
||||
220
README.md
220
README.md
@@ -1,60 +1,163 @@
|
||||
<div align="center">
|
||||
<img src="assets/SubMiner.png" width="140" alt="SubMiner logo">
|
||||
|
||||
<img src="assets/SubMiner.png" width="160" alt="SubMiner logo">
|
||||
|
||||
# SubMiner
|
||||
|
||||
**Sentence-mine from mpv — look up words, one-key Anki export, immersion tracking.**
|
||||
## Turn mpv into a sentence-mining workstation.
|
||||
|
||||
[](https://www.gnu.org/licenses/gpl-3.0)
|
||||
[](https://github.com/ksyasuda/SubMiner)
|
||||
[](https://docs.subminer.moe)
|
||||
[](https://aur.archlinux.org/packages/subminer-bin)
|
||||
Look up words with Yomitan, export to Anki in one key, track your immersion — all without leaving mpv.
|
||||
|
||||
[](https://www.gnu.org/licenses/gpl-3.0)
|
||||
[](https://github.com/ksyasuda/SubMiner)
|
||||
[](https://docs.subminer.moe)
|
||||
[](https://aur.archlinux.org/packages/subminer-bin)
|
||||
|
||||
[](./assets/minecard.mp4)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
## How It Works
|
||||
|
||||
SubMiner is an Electron overlay for [mpv](https://mpv.io) that turns video into a sentence-mining workstation. Look up any word with [Yomitan](https://github.com/yomidevs/yomitan), mine it to Anki with one key, and track your immersion over time.
|
||||
|
||||
<div align="center">
|
||||
|
||||
[](./assets/minecard.mp4)
|
||||
|
||||
</div>
|
||||
SubMiner runs as an invisible Electron overlay on top of mpv. Subtitles render as an interactive layer. Move your cursor over any word and trigger a [Yomitan](https://github.com/yomidevs/yomitan) lookup. Press one key to snapshot the sentence, audio, and screenshot into Anki via AnkiConnect.
|
||||
|
||||
## Features
|
||||
|
||||
**Dictionary lookups** — Yomitan runs inside the overlay. Hover or navigate to any word for full dictionary popups without leaving mpv.
|
||||
### Dictionary Lookups
|
||||
|
||||
**One-key Anki mining** — Press one key to create a card with the sentence, audio clip, screenshot, and machine translation from the exact playback moment.
|
||||
Yomitan runs inside the overlay. Trigger a lookup on any word for full dictionary popups — definitions, pitch accent, frequency data — without ever leaving mpv.
|
||||
|
||||
<div align="center">
|
||||
<img src="docs-site/public/screenshots/yomitan-lookup.png" width="800" alt="Yomitan popup with dictionary entry and mine button over annotated subtitles in mpv">
|
||||
<img src="docs-site/public/screenshots/yomitan-lookup.png" width="800" alt="Yomitan dictionary popup over annotated subtitles in mpv">
|
||||
</div>
|
||||
|
||||
**Reading annotations** — Real-time subtitle annotations with N+1 targeting, frequency highlighting, JLPT tags, and a character name dictionary. Grammar-only tokens render as plain text.
|
||||
<br>
|
||||
|
||||
### Instant Anki Mining
|
||||
|
||||
Create an Anki card with the sentence, audio clip, screenshot, and machine translation from the exact playback moment with one key press, click, or controller input.
|
||||
|
||||
<div align="center">
|
||||
<img src="docs-site/public/screenshots/annotations.png" width="800" alt="Annotated subtitles with frequency highlighting, JLPT underlines, known words, and N+1 targets">
|
||||
<img src="docs-site/public/screenshots/one-key-mining.png" width="800" alt="Anki card created from SubMiner with sentence, audio, and screenshot">
|
||||
</div>
|
||||
|
||||
**Immersion dashboard** — Local stats dashboard with watch time, anime progress, vocabulary growth, mining throughput, and session history.
|
||||
<br>
|
||||
|
||||
### Reading Annotations
|
||||
|
||||
Real-time subtitle annotations with frequency highlighting, JLPT tags, N+1 targeting, and a character name dictionary. Known words fade back; new words stand out. Grammar-only tokens render as plain text so you focus on what matters.
|
||||
|
||||
<div align="center">
|
||||
<img src="docs-site/public/screenshots/stats-overview.png" width="800" alt="Stats dashboard with watch time, cards mined, streaks, and tracking snapshot">
|
||||
<img src="docs-site/public/screenshots/annotations.png" width="800" alt="Annotated subtitles with frequency coloring, JLPT underlines, and N+1 targets">
|
||||
</div>
|
||||
|
||||
**Integrations** — AniList episode tracking, Jellyfin remote playback, Jimaku subtitle downloads, alass/ffsubsync, and an annotated websocket feed for external clients.
|
||||
<br>
|
||||
|
||||
### Immersion Dashboard
|
||||
|
||||
Local stats dashboard — watch time, anime library, vocabulary growth, mining throughput, session history, and trends. All stored locally, no third-party tracking.
|
||||
|
||||
<div align="center">
|
||||
<img src="docs-site/public/screenshots/texthooker.png" width="800" alt="Texthooker page with annotated subtitle lines and frequency highlighting">
|
||||
<img src="docs-site/public/screenshots/stats-overview.png" width="800" alt="Stats dashboard showing watch time, cards mined, streaks, and tracking data">
|
||||
</div>
|
||||
|
||||
<br>
|
||||
|
||||
### Integrations
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td><b>YouTube</b></td>
|
||||
<td>App-owned subtitle picker with downloaded/native track selection and local fallback generation</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><b>AniList</b></td>
|
||||
<td>Automatic episode tracking and progress sync</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><b>Jellyfin</b></td>
|
||||
<td>Browse and launch media from your Jellyfin server</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><b>Jimaku</b></td>
|
||||
<td>Search and download Japanese subtitles</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><b>alass / ffsubsync</b></td>
|
||||
<td>Automatic subtitle retiming</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><b>WebSocket</b></td>
|
||||
<td>Annotated subtitle feed for external clients (texthooker pages, custom tools)</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<div align="center">
|
||||
<img src="docs-site/public/screenshots/texthooker.png" width="800" alt="Texthooker page receiving annotated subtitle lines via WebSocket">
|
||||
</div>
|
||||
|
||||
<br>
|
||||
|
||||
---
|
||||
|
||||
## Requirements
|
||||
|
||||
| | Required | Optional |
|
||||
| -------------- | --------------------------------------- | -------------------------------------- |
|
||||
| **Player** | [`mpv`](https://mpv.io) with IPC socket | — |
|
||||
| **Processing** | `ffmpeg`, `mecab` + `mecab-ipadic` | `guessit` (AniSkip) |
|
||||
| **Media** | — | `yt-dlp`, `chafa`, `ffmpegthumbnailer` |
|
||||
| **Selection** | — | `fzf` / `rofi` |
|
||||
|
||||
> [!NOTE]
|
||||
> [`bun`](https://bun.sh) is required if building from source or using the CLI wrapper: `subminer`. Pre-built releases (AppImage, DMG, installer) do not require it.
|
||||
|
||||
**Platform-specific:**
|
||||
|
||||
| Linux | macOS | Windows |
|
||||
| ----------------------------------- | ------------------------ | ------------- |
|
||||
| `hyprctl` or `xdotool` + `xwininfo` | Accessibility permission | No extra deps |
|
||||
|
||||
<details>
|
||||
<summary><b>Arch Linux</b></summary>
|
||||
|
||||
```bash
|
||||
paru -S --needed mpv ffmpeg mecab-git mecab-ipadic
|
||||
# Optional
|
||||
paru -S --needed yt-dlp fzf rofi chafa ffmpegthumbnailer xdotool xorg-xwininfo
|
||||
# X11 / XWAYLAND
|
||||
paru -S --needed xdotool xorg-xwininfo
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>macOS</b></summary>
|
||||
|
||||
```bash
|
||||
brew install mpv ffmpeg mecab mecab-ipadic
|
||||
# Optional
|
||||
brew install yt-dlp fzf rofi chafa ffmpegthumbnailer
|
||||
```
|
||||
|
||||
Grant Accessibility permission to SubMiner in **System Settings > Privacy & Security > Accessibility**.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Windows</b></summary>
|
||||
|
||||
Install [`mpv`](https://mpv.io/installation/) and [`ffmpeg`](https://ffmpeg.org/download.html) and ensure both are on your `PATH`.
|
||||
|
||||
For MeCab, install [MeCab for Windows](https://taku910.github.io/mecab/#download) with the UTF-8 dictionary.
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Install
|
||||
### 1. Install
|
||||
|
||||
<details>
|
||||
<summary><b>Arch Linux (AUR)</b></summary>
|
||||
@@ -88,53 +191,62 @@ wget https://github.com/ksyasuda/SubMiner/releases/latest/download/subminer -O ~
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>macOS / Windows / From source</b></summary>
|
||||
<summary><b>macOS</b></summary>
|
||||
|
||||
**macOS** — Download the latest DMG/ZIP from [GitHub Releases](https://github.com/ksyasuda/SubMiner/releases/latest) and drag `SubMiner.app` into `/Applications`.
|
||||
|
||||
**Windows** — Download the latest installer or portable `.zip` from [GitHub Releases](https://github.com/ksyasuda/SubMiner/releases/latest). Keep `mpv` on `PATH`.
|
||||
|
||||
**From source** — See [docs.subminer.moe/installation#from-source](https://docs.subminer.moe/installation#from-source).
|
||||
Download the latest DMG or ZIP from [GitHub Releases](https://github.com/ksyasuda/SubMiner/releases/latest) and drag `SubMiner.app` into `/Applications`.
|
||||
|
||||
</details>
|
||||
|
||||
### First Launch
|
||||
<details>
|
||||
<summary><b>Windows</b></summary>
|
||||
|
||||
Run `SubMiner.AppImage` (Linux), `SubMiner.app` (macOS), or `SubMiner.exe` (Windows). On first launch, SubMiner starts in the tray, creates a default config, and opens a setup popup where you can install the mpv plugin and configure Yomitan dictionaries.
|
||||
Download the latest installer or portable `.zip` from [GitHub Releases](https://github.com/ksyasuda/SubMiner/releases/latest). Make sure `mpv` is on your `PATH`.
|
||||
|
||||
### Mine
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>From source</b></summary>
|
||||
|
||||
See the [build-from-source guide](https://docs.subminer.moe/installation#from-source).
|
||||
|
||||
</details>
|
||||
|
||||
### 2. First Launch
|
||||
|
||||
Run the app. On first launch SubMiner starts in the system tray, creates a default config, and opens a setup popup to install the mpv plugin and configure Yomitan dictionaries.
|
||||
|
||||
### 3. Mine
|
||||
|
||||
```bash
|
||||
subminer video.mkv # auto-starts overlay + resumes playback
|
||||
subminer --start video.mkv # explicit overlay start (if plugin auto_start=no)
|
||||
subminer stats # open the immersion dashboard
|
||||
subminer stats -b # keep the stats daemon running in background
|
||||
subminer stats -s # stop the dedicated stats daemon
|
||||
subminer stats cleanup # repair/prune stored stats vocabulary rows
|
||||
subminer video.mkv # play video with overlay
|
||||
subminer --start video.mkv # explicit overlay start
|
||||
subminer stats # open immersion dashboard
|
||||
subminer stats -b # stats daemon in background
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Requirements
|
||||
|
||||
| Required | Optional |
|
||||
| ------------------------------------------------------ | ----------------------------- |
|
||||
| [`mpv`](https://mpv.io) with IPC socket | `yt-dlp` |
|
||||
| `ffmpeg` | `guessit` (AniSkip detection) |
|
||||
| `mecab` + `mecab-ipadic` | `fzf` / `rofi` |
|
||||
| [`bun`](https://bun.sh) (source builds, Linux wrapper) | `chafa`, `ffmpegthumbnailer` |
|
||||
| Linux: `hyprctl` or `xdotool` + `xwininfo` | |
|
||||
| macOS: Accessibility permission | |
|
||||
|
||||
Windows uses native window tracking and does not need the Linux compositor tools.
|
||||
|
||||
## Documentation
|
||||
|
||||
Full guides on configuration, Anki, Jellyfin, immersion tracking, and more at **[docs.subminer.moe](https://docs.subminer.moe)**.
|
||||
Full guides on configuration, Anki setup, Jellyfin, immersion tracking, and more: **[docs.subminer.moe](https://docs.subminer.moe)**
|
||||
|
||||
---
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
Built on [GameSentenceMiner](https://github.com/bpwhelan/GameSentenceMiner), [Renji's Texthooker Page](https://github.com/Renji-XD/texthooker-ui), [Anacreon-Script](https://github.com/friedrich-de/Anacreon-Script), and [Bee's Character Dictionary](https://github.com/bee-san/Japanese_Character_Name_Dictionary). Subtitles from [Jimaku.cc](https://jimaku.cc). Lookups via [Yomitan](https://github.com/yomidevs/yomitan). JLPT tags from [yomitan-jlpt-vocab](https://github.com/stephenmk/yomitan-jlpt-vocab).
|
||||
SubMiner builds on the work of these open-source projects:
|
||||
|
||||
| Project | Role |
|
||||
| ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
|
||||
| [Anacreon-Script](https://github.com/friedrich-de/Anacreon-Script) | Inspiration for the mining workflow |
|
||||
| [asbplayer](https://github.com/killergerbah/asbplayer) | Inspiration for subtitle sidebar and logic for YouTube subtitle parsing |
|
||||
| [Bee's Character Dictionary](https://github.com/bee-san/Japanese_Character_Name_Dictionary) | Character name recognition in subtitles |
|
||||
| [GameSentenceMiner](https://github.com/bpwhelan/GameSentenceMiner) | Inspiration for Electron overlay with Yomitan integration |
|
||||
| [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-jlpt-vocab](https://github.com/stephenmk/yomitan-jlpt-vocab) | JLPT level tags for vocabulary |
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
---
|
||||
id: TASK-143
|
||||
title: Keep character dictionary auto-sync non-blocking during startup
|
||||
status: In Progress
|
||||
status: Done
|
||||
assignee:
|
||||
- codex
|
||||
created_date: '2026-03-09 01:45'
|
||||
updated_date: '2026-03-20 09:22'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- dictionary
|
||||
- startup
|
||||
@@ -18,7 +18,7 @@ references:
|
||||
- >-
|
||||
/home/sudacode/projects/japanese/SubMiner/src/main/runtime/current-media-tokenization-gate.ts
|
||||
priority: high
|
||||
ordinal: 38500
|
||||
ordinal: 144500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -5,7 +5,7 @@ status: Done
|
||||
assignee:
|
||||
- '@codex'
|
||||
created_date: '2026-03-19 17:46'
|
||||
updated_date: '2026-03-19 17:54'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- stats
|
||||
- immersion-tracking
|
||||
@@ -19,6 +19,7 @@ references:
|
||||
- src/core/services/stats-server.ts
|
||||
parent_task_id: TASK-177
|
||||
priority: medium
|
||||
ordinal: 132500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -5,7 +5,7 @@ status: Done
|
||||
assignee:
|
||||
- '@codex'
|
||||
created_date: '2026-03-19 19:38'
|
||||
updated_date: '2026-03-19 19:40'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- stats
|
||||
- immersion-tracking
|
||||
@@ -17,6 +17,7 @@ references:
|
||||
- stats/src/lib/dashboard-data.ts
|
||||
parent_task_id: TASK-177
|
||||
priority: medium
|
||||
ordinal: 130500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -5,7 +5,7 @@ status: Done
|
||||
assignee:
|
||||
- '@codex'
|
||||
created_date: '2026-03-19 20:15'
|
||||
updated_date: '2026-03-19 20:17'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- launcher
|
||||
- stats
|
||||
@@ -19,6 +19,7 @@ references:
|
||||
- src/main/runtime/stats-cli-command.test.ts
|
||||
parent_task_id: TASK-177
|
||||
priority: medium
|
||||
ordinal: 129500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -5,7 +5,7 @@ status: Done
|
||||
assignee:
|
||||
- codex
|
||||
created_date: '2026-03-19 20:31'
|
||||
updated_date: '2026-03-19 20:52'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- bug
|
||||
- stats
|
||||
@@ -17,6 +17,7 @@ references:
|
||||
- >-
|
||||
/Users/sudacode/projects/japanese/SubMiner/stats/src/lib/session-detail.test.tsx
|
||||
parent_task_id: TASK-182
|
||||
ordinal: 128500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -5,7 +5,7 @@ status: Done
|
||||
assignee:
|
||||
- codex
|
||||
created_date: '2026-03-18 00:29'
|
||||
updated_date: '2026-03-18 00:55'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- stats
|
||||
- performance
|
||||
@@ -22,6 +22,7 @@ references:
|
||||
- stats/src/types/stats.ts
|
||||
- stats/src/lib/dashboard-data.ts
|
||||
priority: medium
|
||||
ordinal: 138500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -5,7 +5,7 @@ status: Done
|
||||
assignee:
|
||||
- codex
|
||||
created_date: '2026-03-17 23:15'
|
||||
updated_date: '2026-03-17 23:18'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- pr-review
|
||||
- stats
|
||||
@@ -16,6 +16,7 @@ references:
|
||||
- src/core/services/immersion-tracker-service.ts
|
||||
- src/core/services/immersion-tracker-service.test.ts
|
||||
priority: medium
|
||||
ordinal: 139500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
---
|
||||
id: TASK-192
|
||||
title: 'Assess remaining PR #19 review batch'
|
||||
status: Done
|
||||
assignee:
|
||||
- codex
|
||||
created_date: '2026-03-17 23:24'
|
||||
updated_date: '2026-03-17 23:42'
|
||||
labels:
|
||||
- pr-review
|
||||
- stats
|
||||
- docs
|
||||
milestone: m-1
|
||||
dependencies: []
|
||||
references:
|
||||
- docs/superpowers/plans/2026-03-12-immersion-stats-page.md
|
||||
- src/core/services/immersion-tracker/__tests__/query.test.ts
|
||||
- src/core/services/ipc.ts
|
||||
- src/core/services/stats-server.ts
|
||||
- src/main.ts
|
||||
- src/renderer/handlers/keyboard.ts
|
||||
- stats/src
|
||||
priority: medium
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
<!-- SECTION:DESCRIPTION:BEGIN -->
|
||||
Validate the remaining PR #19 automated review findings against the current branch, implement only the technically correct fixes, and document which comments are stale, already addressed, or not warranted.
|
||||
<!-- SECTION:DESCRIPTION:END -->
|
||||
|
||||
## Acceptance Criteria
|
||||
<!-- AC:BEGIN -->
|
||||
- [x] #1 Each remaining review comment is classified as actionable, already fixed, stale, or not warranted
|
||||
- [x] #2 Confirmed bugs or correctness issues are fixed with focused regression coverage where it fits
|
||||
- [x] #3 Final notes record which comments were intentionally not applied and why
|
||||
<!-- AC:END -->
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
<!-- SECTION:PLAN:BEGIN -->
|
||||
1. Inspect the referenced files in batches and compare each comment against current branch behavior.
|
||||
2. Separate correctness/security regressions from stylistic nitpicks and already-fixed items.
|
||||
3. Add tests first for confirmed behavior bugs where practical, apply the smallest safe fixes, and rerun targeted verification.
|
||||
<!-- SECTION:PLAN:END -->
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
<!-- SECTION:NOTES:BEGIN -->
|
||||
Swept the pasted PR #19 review batch against the current branch.
|
||||
|
||||
Classification:
|
||||
- Already fixed on current branch: `src/core/services/immersion-tracker/__tests__/query.test.ts` cleanup rethrow, `src/core/services/ipc.ts` limit validation, `src/core/services/stats-server.ts` max-limit parsing and CORS removal, `src/main.ts` quit-path TDZ issue, `src/renderer/handlers/keyboard.ts` stats-toggle shortcut ordering/config usage, `stats/src/components/vocabulary/WordList.tsx`, `stats/src/hooks/useSessions.ts`, `stats/src/hooks/useTrends.ts` stale-error reset, `src/core/services/__tests__/stats-server.test.ts` kanji endpoint/readability notes, `src/core/services/stats-window.ts`, `stats/src/App.tsx`, `stats/src/components/layout/TabBar.tsx`, `stats/src/components/overview/QuickStats.tsx`, `stats/src/components/overview/WatchTimeChart.tsx`, `stats/src/components/sessions/SessionDetail.tsx`, `stats/src/components/sessions/SessionRow.tsx`, `stats/src/components/trends/DateRangeSelector.tsx`, `stats/src/components/vocabulary/KanjiBreakdown.tsx`, `stats/src/components/vocabulary/VocabularyTab.tsx`, `stats/src/hooks/useVocabulary.ts`, `stats/src/lib/api-client.ts`, `stats/src/types/stats.ts`.
|
||||
- Stale / obsolete against current architecture: `docs/superpowers/plans/2026-03-12-immersion-stats-page.md` path does not exist on this branch; `stats/src/components/trends/TrendsTab.tsx` / monthly-range comments describe older client-side aggregation code that is no longer present because trends now come from `getTrendsDashboard`.
|
||||
- Not warranted as written: `stats/src/lib/formatters.ts` no longer emits negative `Xd ago`; current code short-circuits future timestamps to `just now`, so the reported bug condition is gone even though the suggested wording differs.
|
||||
- Actionable and fixed now: `src/core/services/ipc.ts` no-tracker `statsGetOverview` fallback omitted required hint fields (`totalLookupCount`, `totalLookupHits`, `newWordsToday`, `newWordsThisWeek`). Added the missing fields in the fallback object and updated IPC tests to assert the full shape.
|
||||
|
||||
Verification:
|
||||
- `bun test src/core/services/ipc.test.ts`
|
||||
- `bun test src/core/services/ipc.test.ts --test-name-pattern "empty stats overview shape without a tracker|validates and clamps stats request limits"`
|
||||
- `bash .agents/skills/subminer-change-verification/scripts/classify_subminer_diff.sh src/core/services/ipc.ts src/core/services/ipc.test.ts`
|
||||
|
||||
Repo verifier note:
|
||||
- `bash .agents/skills/subminer-change-verification/scripts/verify_subminer_change.sh --lane core src/core/services/ipc.ts src/core/services/ipc.test.ts`
|
||||
- That verifier run captured a temporary `bun run typecheck` failure in `src/anki-integration.test.ts` and `src/core/services/__tests__/stats-server.test.ts`, but a fresh rerun after the follow-up validation no longer reproduces those diagnostics.
|
||||
- Fresh verification: `bun run typecheck` passes locally.
|
||||
- artifact dir from the earlier failed verifier snapshot: `.tmp/skill-verification/subminer-verify-20260317-234027-i6QJ3n`
|
||||
<!-- SECTION:NOTES:END -->
|
||||
|
||||
## Final Summary
|
||||
|
||||
<!-- SECTION:FINAL_SUMMARY:BEGIN -->
|
||||
The larger pasted PR #19 review batch was not mostly new work on the current branch. After verifying each item against the live code, almost all were already fixed or stale. One additional item was still actionable: the no-tracker fallback returned by `statsGetOverview` in `src/core/services/ipc.ts` omitted required hint fields, which made the fallback shape inconsistent with the normal overview payload. That fallback is now fixed and covered by IPC tests.
|
||||
|
||||
Count-wise: the earlier open CodeRabbit service comments contributed 2 actionable fixes, and this larger pasted batch contributed 1 additional actionable fix on top of those.
|
||||
<!-- SECTION:FINAL_SUMMARY:END -->
|
||||
@@ -5,7 +5,7 @@ status: Done
|
||||
assignee:
|
||||
- codex
|
||||
created_date: '2026-03-20 00:12'
|
||||
updated_date: '2026-03-20 00:14'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- stats
|
||||
- immersion-tracker
|
||||
@@ -17,6 +17,7 @@ references:
|
||||
- src/core/services/immersion-tracker/query.ts
|
||||
- src/core/services/immersion-tracker-service.test.ts
|
||||
priority: medium
|
||||
ordinal: 127500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
id: TASK-194
|
||||
title: App-owned YouTube subtitle picker flow
|
||||
status: Done
|
||||
assignee: []
|
||||
created_date: '2026-03-18 07:52'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels: []
|
||||
dependencies: []
|
||||
references:
|
||||
- /home/sudacode/projects/japanese/SubMiner/launcher/youtube/orchestrator.ts
|
||||
- /home/sudacode/projects/japanese/SubMiner/launcher/youtube/manual-subs.ts
|
||||
- /home/sudacode/projects/japanese/SubMiner/src/core/services/tokenizer.ts
|
||||
documentation:
|
||||
- /home/sudacode/projects/japanese/SubMiner/youtube.md
|
||||
priority: medium
|
||||
ordinal: 137500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
<!-- SECTION:DESCRIPTION:BEGIN -->
|
||||
Replace the YouTube subtitle-generation-first flow with an app-owned picker flow that boots mpv paused, opens an overlay track picker, downloads selected subtitles into external subtitle files, and preserves generation as an explicit mode. Keep the existing SubMiner tokenization and annotation pipeline as the downstream consumer of downloaded subtitle files.
|
||||
<!-- SECTION:DESCRIPTION:END -->
|
||||
|
||||
## Acceptance Criteria
|
||||
<!-- AC:BEGIN -->
|
||||
- [x] #1 Launcher and app expose YouTube subtitle acquisition modes `download` and `generate`, with `download` as the default.
|
||||
- [x] #2 YouTube playback boots mpv paused and presents an overlay selection UI for primary and secondary subtitle choices.
|
||||
- [x] #3 Selected YouTube subtitle tracks are downloaded to external subtitle files and loaded into mpv before playback resumes.
|
||||
- [x] #4 `generate` mode preserves the existing subtitle generation path as an explicit opt-in behavior.
|
||||
- [x] #5 Downloaded YouTube subtitle files integrate with the existing SubMiner subtitle/tokenization/annotation pipeline without regressing current overlay behavior.
|
||||
- [x] #6 Tests cover mode selection, subtitle-track enumeration/selection flow, and the paused bootstrap plus app handoff path.
|
||||
- [x] #7 User-facing config and launcher docs are updated to describe the new modes and default behavior.
|
||||
<!-- AC:END -->
|
||||
@@ -1,34 +0,0 @@
|
||||
---
|
||||
id: TASK-194
|
||||
title: Redesign YouTube subtitle acquisition around download-first track selection
|
||||
status: To Do
|
||||
assignee: []
|
||||
created_date: '2026-03-18 07:52'
|
||||
labels: []
|
||||
dependencies: []
|
||||
references:
|
||||
- /home/sudacode/projects/japanese/SubMiner/launcher/youtube/orchestrator.ts
|
||||
- /home/sudacode/projects/japanese/SubMiner/launcher/youtube/manual-subs.ts
|
||||
- /home/sudacode/projects/japanese/SubMiner/src/core/services/tokenizer.ts
|
||||
documentation:
|
||||
- /home/sudacode/projects/japanese/SubMiner/youtube.md
|
||||
priority: medium
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
<!-- SECTION:DESCRIPTION:BEGIN -->
|
||||
Replace the current YouTube subtitle-generation-first flow with a download-first flow that enumerates available YouTube subtitle tracks, prompts for primary and secondary track selection before playback, downloads selected tracks into external subtitle files for mpv, and preserves generation as an explicit mode and as fallback behavior in auto mode. Keep the existing SubMiner tokenization and annotation pipeline as the downstream consumer of downloaded subtitle files.
|
||||
<!-- SECTION:DESCRIPTION:END -->
|
||||
|
||||
## Acceptance Criteria
|
||||
<!-- AC:BEGIN -->
|
||||
- [ ] #1 Launcher and config expose YouTube subtitle acquisition modes `download`, `generate`, and `auto`, with `download` as the default for launcher YouTube playback.
|
||||
- [ ] #2 YouTube playback enumerates available subtitle tracks before mpv launch and presents a selection UI that supports primary and secondary subtitle choices.
|
||||
- [ ] #3 Selected YouTube subtitle tracks are downloaded to external subtitle files and loaded into mpv before playback starts when download mode succeeds.
|
||||
- [ ] #4 `auto` mode attempts download-first for the selected tracks and falls back to generation only when required tracks cannot be downloaded or download fails.
|
||||
- [ ] #5 `generate` mode preserves the existing whisper/AI generation path as an explicit opt-in behavior.
|
||||
- [ ] #6 Downloaded YouTube subtitle files integrate with the existing SubMiner subtitle/tokenization/annotation pipeline without regressing current overlay behavior.
|
||||
- [ ] #7 Tests cover mode selection, subtitle-track enumeration/selection flow, download-first success path, and fallback behavior for auto mode.
|
||||
- [ ] #8 User-facing config and launcher docs are updated to describe the new modes and default behavior.
|
||||
<!-- AC:END -->
|
||||
@@ -4,13 +4,16 @@ title: Fix subtitle prefetch cache-key mismatch and active-cue window
|
||||
status: Done
|
||||
assignee: []
|
||||
created_date: '2026-03-18 16:05'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels: []
|
||||
dependencies: []
|
||||
references:
|
||||
- /home/sudacode/projects/japanese/SubMiner/src/core/services/subtitle-processing-controller.ts
|
||||
- /home/sudacode/projects/japanese/SubMiner/src/core/services/subtitle-prefetch.ts
|
||||
documentation: []
|
||||
- >-
|
||||
/home/sudacode/projects/japanese/SubMiner/src/core/services/subtitle-processing-controller.ts
|
||||
- >-
|
||||
/home/sudacode/projects/japanese/SubMiner/src/core/services/subtitle-prefetch.ts
|
||||
priority: high
|
||||
ordinal: 136500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -4,15 +4,19 @@ title: Eliminate per-line plain subtitle flash on prefetch cache hit
|
||||
status: Done
|
||||
assignee: []
|
||||
created_date: '2026-03-18 16:28'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels: []
|
||||
dependencies:
|
||||
- TASK-196
|
||||
references:
|
||||
- /home/sudacode/projects/japanese/SubMiner/src/core/services/subtitle-processing-controller.ts
|
||||
- /home/sudacode/projects/japanese/SubMiner/src/main/runtime/mpv-main-event-actions.ts
|
||||
- /home/sudacode/projects/japanese/SubMiner/src/main/runtime/mpv-main-event-main-deps.ts
|
||||
documentation: []
|
||||
- >-
|
||||
/home/sudacode/projects/japanese/SubMiner/src/core/services/subtitle-processing-controller.ts
|
||||
- >-
|
||||
/home/sudacode/projects/japanese/SubMiner/src/main/runtime/mpv-main-event-actions.ts
|
||||
- >-
|
||||
/home/sudacode/projects/japanese/SubMiner/src/main/runtime/mpv-main-event-main-deps.ts
|
||||
priority: high
|
||||
ordinal: 135500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -4,6 +4,7 @@ title: Forward launcher log level into mpv plugin script opts
|
||||
status: Done
|
||||
assignee: []
|
||||
created_date: '2026-03-18 21:16'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels: []
|
||||
dependencies:
|
||||
- TASK-198
|
||||
@@ -12,8 +13,8 @@ references:
|
||||
- /home/sudacode/projects/japanese/SubMiner/launcher/mpv.ts
|
||||
- /home/sudacode/projects/japanese/SubMiner/launcher/main.test.ts
|
||||
- /home/sudacode/projects/japanese/SubMiner/launcher/aniskip-metadata.test.ts
|
||||
documentation: []
|
||||
priority: medium
|
||||
ordinal: 134500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -5,7 +5,7 @@ status: Done
|
||||
assignee:
|
||||
- '@codex'
|
||||
created_date: '2026-03-19 07:18'
|
||||
updated_date: '2026-03-19 07:28'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- pr-review
|
||||
- anki-integration
|
||||
@@ -19,6 +19,7 @@ references:
|
||||
- src/anki-integration/runtime.ts
|
||||
- src/anki-integration/known-word-cache.ts
|
||||
priority: medium
|
||||
ordinal: 133500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -5,7 +5,7 @@ status: Done
|
||||
assignee:
|
||||
- '@codex'
|
||||
created_date: '2026-03-19 18:47'
|
||||
updated_date: '2026-03-19 19:01'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- bug
|
||||
- macos
|
||||
@@ -20,6 +20,7 @@ references:
|
||||
- >-
|
||||
/Users/sudacode/projects/japanese/SubMiner/src/core/services/overlay-visibility.test.ts
|
||||
priority: high
|
||||
ordinal: 131500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -5,7 +5,7 @@ status: Done
|
||||
assignee:
|
||||
- '@Codex'
|
||||
created_date: '2026-03-20 02:52'
|
||||
updated_date: '2026-03-20 03:02'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- anki
|
||||
- cache
|
||||
@@ -17,6 +17,7 @@ references:
|
||||
- docs/plans/2026-03-19-known-word-cache-incremental-sync-design.md
|
||||
parent_task_id: TASK-204
|
||||
priority: high
|
||||
ordinal: 124500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -5,7 +5,7 @@ status: Done
|
||||
assignee:
|
||||
- codex
|
||||
created_date: '2026-03-20 02:41'
|
||||
updated_date: '2026-03-20 02:46'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels: []
|
||||
milestone: m-1
|
||||
dependencies: []
|
||||
@@ -14,6 +14,7 @@ references:
|
||||
- stats/src/hooks/useSessions.ts
|
||||
- stats/src/hooks/useTrends.ts
|
||||
priority: medium
|
||||
ordinal: 126500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -5,7 +5,7 @@ status: Done
|
||||
assignee:
|
||||
- '@codex'
|
||||
created_date: '2026-03-20 02:51'
|
||||
updated_date: '2026-03-20 02:59'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- pr-review
|
||||
- launcher
|
||||
@@ -22,6 +22,7 @@ references:
|
||||
- src/anki-integration.ts
|
||||
- src/anki-integration/known-word-cache.ts
|
||||
priority: medium
|
||||
ordinal: 125500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -5,7 +5,7 @@ status: Done
|
||||
assignee:
|
||||
- '@codex'
|
||||
created_date: '2026-03-20 03:03'
|
||||
updated_date: '2026-03-20 03:04'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- pr-review
|
||||
- anki-integration
|
||||
@@ -15,6 +15,7 @@ dependencies: []
|
||||
references:
|
||||
- src/anki-integration/anki-connect-proxy.test.ts
|
||||
priority: medium
|
||||
ordinal: 123500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -5,7 +5,7 @@ status: Done
|
||||
assignee:
|
||||
- '@codex'
|
||||
created_date: '2026-03-20 03:37'
|
||||
updated_date: '2026-03-20 03:47'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- pr-review
|
||||
- launcher
|
||||
@@ -17,6 +17,7 @@ references:
|
||||
- launcher/mpv.ts
|
||||
- src/anki-integration.ts
|
||||
priority: medium
|
||||
ordinal: 122500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -5,7 +5,7 @@ status: Done
|
||||
assignee:
|
||||
- codex
|
||||
created_date: '2026-03-20 04:06'
|
||||
updated_date: '2026-03-20 04:33'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- bug
|
||||
- tokenizer
|
||||
@@ -18,6 +18,7 @@ references:
|
||||
- >-
|
||||
/Users/sudacode/projects/japanese/SubMiner/src/core/services/tokenizer.test.ts
|
||||
priority: high
|
||||
ordinal: 120500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -5,7 +5,7 @@ status: Done
|
||||
assignee:
|
||||
- '@Codex'
|
||||
created_date: '2026-03-20 04:09'
|
||||
updated_date: '2026-03-20 04:25'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- stats
|
||||
- bug
|
||||
@@ -17,6 +17,7 @@ references:
|
||||
- src/core/services/immersion-tracker/query.ts
|
||||
- src/core/services/immersion-tracker/session.ts
|
||||
- src/core/services/immersion-tracker-service.ts
|
||||
ordinal: 121500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
---
|
||||
id: TASK-211
|
||||
title: Recover anime episode progress from subtitle timing when checkpoints are missing
|
||||
title: >-
|
||||
Recover anime episode progress from subtitle timing when checkpoints are
|
||||
missing
|
||||
status: Done
|
||||
assignee:
|
||||
- '@Codex'
|
||||
created_date: '2026-03-20 10:15'
|
||||
updated_date: '2026-03-20 10:22'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- stats
|
||||
- bug
|
||||
@@ -14,20 +16,26 @@ dependencies: []
|
||||
references:
|
||||
- src/core/services/immersion-tracker/query.ts
|
||||
- src/core/services/immersion-tracker/__tests__/query.test.ts
|
||||
ordinal: 119500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
<!-- SECTION:DESCRIPTION:BEGIN -->
|
||||
Anime episode progress can still show `0%` for older sessions that have watch-time and subtitle timing but no persisted `ended_media_ms` checkpoint. Recover progress from the latest retained subtitle/event segment end so already-recorded sessions render a useful progress percentage.
|
||||
<!-- SECTION:DESCRIPTION:END -->
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [x] `getAnimeEpisodes` returns the latest known session position even when `ended_media_ms` is null but subtitle/event timing exists.
|
||||
- [x] Existing ended-session metrics and aggregation totals do not regress.
|
||||
- [x] Regression coverage locks the fallback behavior.
|
||||
<!-- AC:BEGIN -->
|
||||
- [x] #1 `getAnimeEpisodes` returns the latest known session position even when `ended_media_ms` is null but subtitle/event timing exists.
|
||||
- [x] #2 Existing ended-session metrics and aggregation totals do not regress.
|
||||
- [x] #3 Regression coverage locks the fallback behavior.
|
||||
<!-- AC:END -->
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
<!-- SECTION:NOTES:BEGIN -->
|
||||
Added a query-side fallback for anime episode progress: when the newest session for a video has no persisted `ended_media_ms`, `getAnimeEpisodes` now uses the latest retained subtitle-line or session-event `segment_end_ms` from that same session. This recovers useful progress for already-recorded sessions that have timing data but predate or missed checkpoint persistence.
|
||||
|
||||
Verification: `bun test src/core/services/immersion-tracker/__tests__/query.test.ts` passed. `bun run typecheck` passed.
|
||||
<!-- SECTION:NOTES:END -->
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
---
|
||||
id: TASK-212
|
||||
title: Fix mac texthooker helper startup blocking mpv launch
|
||||
status: In Progress
|
||||
status: Done
|
||||
assignee: []
|
||||
created_date: '2026-03-20 08:27'
|
||||
updated_date: '2026-03-20 08:45'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- bug
|
||||
- macos
|
||||
@@ -15,6 +15,7 @@ references:
|
||||
- /Users/sudacode/projects/japanese/SubMiner/src/main.ts
|
||||
- /Users/sudacode/projects/japanese/SubMiner/plugin/subminer/process.lua
|
||||
priority: high
|
||||
ordinal: 140500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
---
|
||||
id: TASK-213
|
||||
title: Show character dictionary progress during paused startup waits
|
||||
status: In Progress
|
||||
status: Done
|
||||
assignee: []
|
||||
created_date: '2026-03-20 08:59'
|
||||
updated_date: '2026-03-20 09:22'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- bug
|
||||
- ux
|
||||
@@ -18,6 +18,7 @@ references:
|
||||
/Users/sudacode/projects/japanese/SubMiner/src/main/runtime/character-dictionary-auto-sync-notifications.ts
|
||||
- /Users/sudacode/projects/japanese/SubMiner/src/main.ts
|
||||
priority: medium
|
||||
ordinal: 141500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
id: TASK-214
|
||||
title: Jump subtitle sidebar directly to resume position on first resolved cue
|
||||
status: Done
|
||||
assignee: []
|
||||
created_date: '2026-03-21 11:15'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- bug
|
||||
- ux
|
||||
- overlay
|
||||
- subtitles
|
||||
dependencies: []
|
||||
references:
|
||||
- >-
|
||||
/Users/sudacode/projects/japanese/SubMiner/src/renderer/modals/subtitle-sidebar.ts
|
||||
- >-
|
||||
/Users/sudacode/projects/japanese/SubMiner/src/renderer/modals/subtitle-sidebar.test.ts
|
||||
priority: medium
|
||||
ordinal: 142500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
<!-- SECTION:DESCRIPTION:BEGIN -->
|
||||
When playback starts from a resumed timestamp while the subtitle sidebar is open, the sidebar currently smooth-scrolls from the top of the cue list to the resumed cue. Change the first resolved active-cue positioning to jump immediately to the resume location while preserving smooth auto-follow for later playback-driven cue advances.
|
||||
<!-- SECTION:DESCRIPTION:END -->
|
||||
|
||||
## Acceptance Criteria
|
||||
<!-- AC:BEGIN -->
|
||||
- [x] #1 The first active cue resolved after open/resume uses an instant jump instead of smooth-scrolling through the list.
|
||||
- [x] #2 Normal subtitle-sidebar auto-follow remains smooth after the first active cue has been positioned.
|
||||
- [x] #3 Regression coverage distinguishes the initial jump behavior from later smooth auto-follow updates.
|
||||
<!-- AC:END -->
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
<!-- SECTION:NOTES:BEGIN -->
|
||||
2026-03-21: Fixed by treating the first auto-scroll from `previousActiveCueIndex < 0` as `behavior: 'auto'` in the subtitle sidebar scroll helper. Added renderer regression coverage for initial jump plus later smooth follow.
|
||||
<!-- SECTION:NOTES:END -->
|
||||
@@ -0,0 +1,44 @@
|
||||
---
|
||||
id: TASK-215
|
||||
title: Add startup auto-open option for subtitle sidebar
|
||||
status: Done
|
||||
assignee: []
|
||||
created_date: '2026-03-21 11:35'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- feature
|
||||
- ux
|
||||
- overlay
|
||||
- subtitles
|
||||
dependencies: []
|
||||
references:
|
||||
- /Users/sudacode/projects/japanese/SubMiner/src/types.ts
|
||||
- >-
|
||||
/Users/sudacode/projects/japanese/SubMiner/src/config/definitions/defaults-subtitle.ts
|
||||
- >-
|
||||
/Users/sudacode/projects/japanese/SubMiner/src/config/resolve/subtitle-domains.ts
|
||||
- >-
|
||||
/Users/sudacode/projects/japanese/SubMiner/src/renderer/modals/subtitle-sidebar.ts
|
||||
- /Users/sudacode/projects/japanese/SubMiner/src/renderer/renderer.ts
|
||||
priority: medium
|
||||
ordinal: 143500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
<!-- SECTION:DESCRIPTION:BEGIN -->
|
||||
Add a subtitle sidebar config option that auto-opens the sidebar once during overlay startup. The option should default to `false`, only apply when the sidebar feature is enabled, and should not force the sidebar back open later in the same session after manual close or later visibility changes.
|
||||
<!-- SECTION:DESCRIPTION:END -->
|
||||
|
||||
## Acceptance Criteria
|
||||
<!-- AC:BEGIN -->
|
||||
- [x] #1 `subtitleSidebar.autoOpen` is available in config with default `false`.
|
||||
- [x] #2 When enabled, overlay startup opens the subtitle sidebar once after initial sidebar config/snapshot load.
|
||||
- [x] #3 Regression coverage covers config resolution and startup-only auto-open behavior.
|
||||
<!-- AC:END -->
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
<!-- SECTION:NOTES:BEGIN -->
|
||||
2026-03-21: Added `subtitleSidebar.autoOpen` to types/defaults/config registry and resolver. Renderer bootstrap now calls a startup-only subtitle sidebar helper after the initial snapshot refresh. Modal regression coverage verifies startup auto-open requires both `enabled` and `autoOpen`.
|
||||
<!-- SECTION:NOTES:END -->
|
||||
@@ -0,0 +1,79 @@
|
||||
---
|
||||
id: TASK-216
|
||||
title: 'Address PR #28 CodeRabbit follow-ups on subtitle sidebar'
|
||||
status: Completed
|
||||
assignee:
|
||||
- '@codex'
|
||||
created_date: '2026-03-21 00:00'
|
||||
updated_date: '2026-03-21 00:00'
|
||||
labels:
|
||||
- pr-review
|
||||
- subtitle-sidebar
|
||||
- renderer
|
||||
dependencies: []
|
||||
references:
|
||||
- src/main/runtime/subtitle-prefetch-init.ts
|
||||
- src/main/runtime/subtitle-prefetch-init.test.ts
|
||||
- src/renderer/handlers/mouse.ts
|
||||
- src/renderer/handlers/mouse.test.ts
|
||||
- src/renderer/modals/subtitle-sidebar.ts
|
||||
- src/renderer/modals/subtitle-sidebar.test.ts
|
||||
- src/renderer/style.css
|
||||
priority: medium
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
<!-- SECTION:DESCRIPTION:BEGIN -->
|
||||
Validate the CodeRabbit follow-ups on PR #28 for the subtitle sidebar workstream, implement the confirmed fixes, and verify the touched runtime and renderer paths.
|
||||
<!-- SECTION:DESCRIPTION:END -->
|
||||
|
||||
## Acceptance Criteria
|
||||
<!-- AC:BEGIN -->
|
||||
- [x] #1 Review comments that described real regressions are fixed in code
|
||||
- [x] #2 Focused regression coverage exists for the fixed behaviors
|
||||
- [x] #3 Targeted typecheck and runtime-compat verification pass
|
||||
<!-- AC:END -->
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
<!-- SECTION:NOTES:BEGIN -->
|
||||
Completed follow-up fixes for PR #28:
|
||||
- Cleared parsed subtitle cues on subtitle prefetch init failure so stale snapshot cache entries do not survive a failed refresh.
|
||||
- Treated primary and secondary subtitle containers as one hover region so moving between them does not resume playback mid-transition.
|
||||
- Kept the subtitle sidebar closed when disabled, serialized snapshot polling with timeouts, made cue rows keyboard-activatable, resolved stale cue selection fallback, and resumed hover-paused playback when the modal closes.
|
||||
|
||||
Regression coverage added:
|
||||
- `src/main/runtime/subtitle-prefetch-init.test.ts`
|
||||
- `src/renderer/handlers/mouse.test.ts`
|
||||
- `src/renderer/modals/subtitle-sidebar.test.ts`
|
||||
|
||||
Verification:
|
||||
- `bun test src/main/runtime/subtitle-prefetch-init.test.ts`
|
||||
- `bun test src/renderer/handlers/mouse.test.ts`
|
||||
- `bun test src/renderer/modals/subtitle-sidebar.test.ts`
|
||||
- `bun run typecheck`
|
||||
- `bun run test:runtime:compat`
|
||||
|
||||
2026-03-21: Reopened to assess a newer CodeRabbit review pass on PR #28 and address any remaining valid action items before push/reply.
|
||||
|
||||
2026-03-21: Addressed the latest CodeRabbit follow-up pass in commit d70c6448 after rebasing onto the updated remote branch tip.
|
||||
|
||||
2026-03-21: Reopened for the latest CodeRabbit round on commit d70c6448; current actionable item is the invalid ctx.state.isOverSubtitleSidebar assignment in subtitle-sidebar.ts.
|
||||
|
||||
2026-03-22: Addressed the live hover-state and startup mouse-ignore follow-ups from the latest CodeRabbit pass. `handleMouseLeave()` now clears `isOverSubtitle` and drops `secondary-sub-hover-active` when leaving the secondary subtitle container toward the primary container, and renderer startup now calls `syncOverlayMouseIgnoreState(ctx)` instead of forcing `setIgnoreMouseEvents(true, { forward: true })`. The sidebar IPC hover catch and CSS spacing comments were already satisfied in the current tree.
|
||||
|
||||
2026-03-22: Regenerated `bun.lock` from a clean install so the `electron-builder-squirrel-windows` override now resolves at `26.8.2` in the lockfile alongside `app-builder-lib@26.8.2`.
|
||||
|
||||
2026-03-21: Finished the remaining cleanup pass from the latest review. `subtitleSidebar.layout` now uses enum validation, `SubtitleCue` is re-exported from `src/types.ts` as the single public type path, and the subtitle sidebar resize listener now has unload cleanup wired through the renderer.
|
||||
<!-- SECTION:NOTES:END -->
|
||||
|
||||
## Final Summary
|
||||
|
||||
<!-- SECTION:FINAL_SUMMARY:BEGIN -->
|
||||
Implemented the confirmed PR #28 CodeRabbit follow-ups for subtitle sidebar behavior and added regression coverage plus verification for the touched renderer and runtime paths.
|
||||
|
||||
Handled the latest CodeRabbit review pass for PR #28: accepted zero sidebar opacity, closed/inerted the sidebar when refresh sees config disabled, moved poll rescheduling out of finally, caught hover pause IPC failures, and fixed the stylelint spacing issue.
|
||||
|
||||
Verification: bun test src/config/resolve/subtitle-sidebar.test.ts; bun test src/renderer/modals/subtitle-sidebar.test.ts; bun test src/renderer/handlers/mouse.test.ts; bun run typecheck; bun run test:fast; bun run test:env; bun run build; SubMiner verifier lanes config + runtime-compat (including test:runtime:compat and test:smoke:dist).
|
||||
<!-- SECTION:FINAL_SUMMARY:END -->
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: TASK-217
|
||||
title: Fix embedded overlay passthrough sync between subtitle and sidebar
|
||||
status: Done
|
||||
assignee:
|
||||
- codex
|
||||
created_date: '2026-03-21 23:16'
|
||||
updated_date: '2026-03-23 03:22'
|
||||
labels:
|
||||
- bug
|
||||
- overlay
|
||||
- macos
|
||||
dependencies: []
|
||||
references:
|
||||
- src/renderer/handlers/mouse.ts
|
||||
- src/renderer/modals/subtitle-sidebar.ts
|
||||
- src/renderer/renderer.ts
|
||||
documentation:
|
||||
- docs/workflow/verification.md
|
||||
priority: high
|
||||
ordinal: 118500
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
<!-- SECTION:DESCRIPTION:BEGIN -->
|
||||
On macOS, when both the subtitle overlay and embedded subtitle sidebar are visible, mouse passthrough to mpv can remain stale until the user hovers the sidebar. After closing the sidebar, passthrough can likewise remain stale until the user hovers the subtitle again. Fix the overlay input-state synchronization so passthrough reflects the current hover/open state immediately instead of relying on the last hover target.
|
||||
<!-- SECTION:DESCRIPTION:END -->
|
||||
|
||||
## Acceptance Criteria
|
||||
<!-- AC:BEGIN -->
|
||||
- [x] #1 When the embedded subtitle sidebar is open and the pointer is not over subtitle or sidebar content, the overlay returns to mouse passthrough immediately without requiring a sidebar hover cycle.
|
||||
- [x] #2 When transitioning between subtitle hover and sidebar hover states on macOS embedded sidebar mode, mouse ignore state stays in sync with the currently interactive region.
|
||||
- [x] #3 Closing the embedded subtitle sidebar restores the correct passthrough state based on remaining subtitle hover/modal state without requiring an additional hover.
|
||||
- [x] #4 Regression tests cover the passthrough synchronization behavior.
|
||||
<!-- AC:END -->
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
<!-- SECTION:PLAN:BEGIN -->
|
||||
1. Add a shared renderer-side passthrough sync helper that derives whether the overlay should ignore mouse events from subtitle hover, embedded sidebar visibility/hover, popup visibility, and modal state.
|
||||
2. Replace direct embedded-sidebar passthrough toggles in subtitle hover/sidebar handlers with calls to the shared sync helper so state is recomputed on every transition.
|
||||
3. Add regression tests for macOS embedded sidebar mode covering sidebar-open idle passthrough, subtitle-to-sidebar transitions, and sidebar-close restore behavior.
|
||||
4. Run targeted renderer tests for mouse/sidebar passthrough coverage, then summarize any residual risk.
|
||||
<!-- SECTION:PLAN:END -->
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
<!-- SECTION:NOTES:BEGIN -->
|
||||
Added shared renderer overlay mouse-ignore recompute so subtitle hover, embedded sidebar hover/open/close, and popup idle transitions all derive passthrough from current state instead of last hover target.
|
||||
|
||||
Added regression coverage for embedded sidebar idle passthrough on subtitle leave and for sidebar-close recompute behavior.
|
||||
|
||||
Verification: `bun run typecheck` passed; `bun test src/renderer/handlers/mouse.test.ts` passed; `bun test src/renderer/modals/subtitle-sidebar.test.ts` passed; core verification wrapper artifact at `.tmp/skill-verification/subminer-verify-20260321-162743-XhSBxw` hit an unrelated `bun run test:fast` failure in `scripts/update-aur-package.test.ts` because macOS system bash lacks `mapfile`.
|
||||
<!-- SECTION:NOTES:END -->
|
||||
|
||||
## Final Summary
|
||||
|
||||
<!-- SECTION:FINAL_SUMMARY:BEGIN -->
|
||||
Fixed stale embedded-sidebar passthrough sync on macOS by introducing a shared renderer mouse-ignore recompute path and tracking sidebar-hover state separately from subtitle hover. Subtitle hover leave, sidebar hover enter/leave, sidebar open, and sidebar close now all recompute passthrough from the current overlay state instead of waiting for a later hover event to repair it. Added regression tests covering subtitle-leave passthrough while the embedded sidebar is open but idle, plus sidebar-close restore behavior based on remaining subtitle hover state.
|
||||
|
||||
Tests run:
|
||||
- `bun run typecheck`
|
||||
- `bun test src/renderer/handlers/mouse.test.ts`
|
||||
- `bun test src/renderer/modals/subtitle-sidebar.test.ts`
|
||||
- `bash .agents/skills/subminer-change-verification/scripts/classify_subminer_diff.sh src/renderer/state.ts src/renderer/overlay-mouse-ignore.ts src/renderer/handlers/mouse.ts src/renderer/handlers/mouse.test.ts src/renderer/modals/subtitle-sidebar.ts src/renderer/modals/subtitle-sidebar.test.ts`
|
||||
- `bash .agents/skills/subminer-change-verification/scripts/verify_subminer_change.sh --lane core src/renderer/state.ts src/renderer/overlay-mouse-ignore.ts src/renderer/handlers/mouse.ts src/renderer/handlers/mouse.test.ts src/renderer/modals/subtitle-sidebar.ts src/renderer/modals/subtitle-sidebar.test.ts` (typecheck passed; `test:fast` blocked by unrelated `scripts/update-aur-package.test.ts` failure on macOS Bash 3.2 lacking `mapfile`)
|
||||
|
||||
Risk: the classifier flagged this as a real-runtime candidate, so actual Electron/mpv macOS pointer behavior was not exercised in a live runtime during this turn.
|
||||
<!-- SECTION:FINAL_SUMMARY:END -->
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
id: TASK-218
|
||||
title: 'Delete zero-session media from stats library and trends'
|
||||
status: Done
|
||||
assignee:
|
||||
- codex
|
||||
created_date: '2026-03-22 16:20'
|
||||
updated_date: '2026-03-22 21:10'
|
||||
labels:
|
||||
- stats
|
||||
- immersion-tracker
|
||||
priority: medium
|
||||
dependencies: []
|
||||
references:
|
||||
- /Users/sudacode/projects/japanese/SubMiner/src/core/services/immersion-tracker/query.ts
|
||||
- /Users/sudacode/projects/japanese/SubMiner/src/core/services/immersion-tracker/lifetime.ts
|
||||
- /Users/sudacode/projects/japanese/SubMiner/src/core/services/immersion-tracker/maintenance.ts
|
||||
- /Users/sudacode/projects/japanese/SubMiner/src/core/services/immersion-tracker/__tests__/query.test.ts
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
<!-- SECTION:DESCRIPTION:BEGIN -->
|
||||
Deleting the last retained session for a video still left stale lifetime media rows and trend rollups behind, so the stats dashboard could continue showing ghost entries in Library and Trends after all sessions were gone.
|
||||
<!-- SECTION:DESCRIPTION:END -->
|
||||
|
||||
## Acceptance Criteria
|
||||
<!-- AC:BEGIN -->
|
||||
- [x] #1 Deleting the final session for a video removes that media from Library queries and detail reads
|
||||
- [x] #2 Deleting the final session for a video removes stale daily/monthly trend rollups for that media
|
||||
- [x] #3 Regression coverage proves zero-session media disappears from affected stats surfaces after deletion
|
||||
<!-- AC:END -->
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
<!-- SECTION:PLAN:BEGIN -->
|
||||
1. Add a failing regression around deleting the only retained session for a video while preexisting lifetime and rollup rows exist.
|
||||
2. Patch the deletion path to rebuild lifetime and rollup state from retained sessions inside the same transaction.
|
||||
3. Run focused immersion-tracker tests plus the repo-native verifier core lane and record results.
|
||||
<!-- SECTION:PLAN:END -->
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
<!-- SECTION:NOTES:BEGIN -->
|
||||
Added a query regression that seeds a finished session plus stale lifetime media/anime rows and daily/monthly rollups, deletes that only session, and asserts Library, Anime detail, and Trends all drop the media immediately.
|
||||
|
||||
Refactored lifetime rebuild logic so it can run inside an existing delete transaction, then reused that helper from `deleteSession`, `deleteSessions`, and `deleteVideo`.
|
||||
|
||||
Added a rollup rebuild helper that clears existing daily/monthly rollups and reconstructs them from retained telemetry inside the current transaction so deleted sessions cannot leave ghost trend points behind.
|
||||
|
||||
Verification passed:
|
||||
- `bun test src/core/services/immersion-tracker/__tests__/query.test.ts`
|
||||
- `bun test src/core/services/immersion-tracker-service.test.ts`
|
||||
- `bash .agents/skills/subminer-change-verification/scripts/classify_subminer_diff.sh src/core/services/immersion-tracker/query.ts src/core/services/immersion-tracker/lifetime.ts src/core/services/immersion-tracker/maintenance.ts src/core/services/immersion-tracker/__tests__/query.test.ts`
|
||||
- `bash .agents/skills/subminer-change-verification/scripts/verify_subminer_change.sh --lane core src/core/services/immersion-tracker/query.ts src/core/services/immersion-tracker/lifetime.ts src/core/services/immersion-tracker/maintenance.ts src/core/services/immersion-tracker/__tests__/query.test.ts`
|
||||
|
||||
Verifier artifact dir: `.tmp/skill-verification/subminer-verify-20260322-210718-n6sGL8`
|
||||
<!-- SECTION:NOTES:END -->
|
||||
|
||||
## Final Summary
|
||||
|
||||
<!-- SECTION:FINAL_SUMMARY:BEGIN -->
|
||||
Delete paths now rebuild lifetime summaries and trend rollups after removing sessions, so when the last session for a video disappears the stats database also drops that media from Library, related detail reads, and chart data. Added a regression proving a video with only stale lifetime/rollup rows vanishes after its final session is deleted, and verified the change with focused immersion-tracker tests plus the SubMiner core verification lane.
|
||||
<!-- SECTION:FINAL_SUMMARY:END -->
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
id: TASK-219
|
||||
title: 'Restore streamed video progress in anime episodes'
|
||||
status: In Progress
|
||||
assignee:
|
||||
- codex
|
||||
created_date: '2026-03-22 21:25'
|
||||
updated_date: '2026-03-22 21:25'
|
||||
labels:
|
||||
- stats
|
||||
- immersion-tracker
|
||||
- youtube
|
||||
priority: medium
|
||||
dependencies: []
|
||||
references:
|
||||
- /Users/sudacode/projects/japanese/SubMiner/src/core/services/immersion-tracker/query.ts
|
||||
- /Users/sudacode/projects/japanese/SubMiner/src/core/services/immersion-tracker-service.ts
|
||||
- /Users/sudacode/projects/japanese/SubMiner/src/core/services/immersion-tracker/__tests__/query.test.ts
|
||||
- /Users/sudacode/projects/japanese/SubMiner/src/core/services/immersion-tracker-service.test.ts
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
<!-- SECTION:DESCRIPTION:BEGIN -->
|
||||
Episode progress for streamed media can stay at `0%` because some remote sessions persist `ended_media_ms = 0` even when subtitle timing and watch activity clearly advanced, and the anime episode query currently treats `0` as a valid progress checkpoint.
|
||||
<!-- SECTION:DESCRIPTION:END -->
|
||||
|
||||
## Acceptance Criteria
|
||||
<!-- AC:BEGIN -->
|
||||
- [ ] #1 Anime episode progress ignores zero-valued session checkpoints and falls back to subtitle/event timing
|
||||
- [ ] #2 New streamed sessions persist meaningful progress even when playback-position updates are missing or sparse
|
||||
- [ ] #3 Regression tests cover the zero-checkpoint remote-session case
|
||||
<!-- AC:END -->
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
id: TASK-220
|
||||
title: Restore YouTube overlay mpv keybindings after picker routing
|
||||
status: Done
|
||||
assignee:
|
||||
- codex
|
||||
created_date: '2026-03-22 00:00'
|
||||
updated_date: '2026-03-22 23:49'
|
||||
labels:
|
||||
- bug
|
||||
- overlay
|
||||
- youtube
|
||||
- keyboard
|
||||
dependencies: []
|
||||
references:
|
||||
- src/renderer/handlers/keyboard.ts
|
||||
- src/renderer/modals/youtube-track-picker.ts
|
||||
- src/renderer/handlers/keyboard.test.ts
|
||||
- src/renderer/modals/youtube-track-picker.test.ts
|
||||
documentation:
|
||||
- docs/workflow/verification.md
|
||||
priority: high
|
||||
ordinal: 118800
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
<!-- SECTION:DESCRIPTION:BEGIN -->
|
||||
Regression: after adding the YouTube subtitle picker modal path, visible-overlay keydown handling can stop before reaching the shared mpv keybinding dispatch path. Result: default overlay mpv bindings like `Space` pause/play and `q` quit stop working while the overlay owns focus during YouTube playback.
|
||||
<!-- SECTION:DESCRIPTION:END -->
|
||||
|
||||
## Acceptance Criteria
|
||||
<!-- AC:BEGIN -->
|
||||
- [x] #1 Unhandled keys while the YouTube track picker state is active still fall through to the shared overlay mpv keybinding dispatcher.
|
||||
- [x] #2 The YouTube picker continues to consume `Enter` and `Escape` for its own actions.
|
||||
- [x] #3 Renderer regression tests cover both the picker modal key contract and the shared keyboard dispatch fallback.
|
||||
<!-- AC:END -->
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
<!-- SECTION:PLAN:BEGIN -->
|
||||
1. Add a failing renderer keyboard regression test covering YouTube picker state plus shared mpv keybinding fallback.
|
||||
2. Update the global keyboard handler to return early only when the YouTube picker actually handles the key event.
|
||||
3. Update the picker modal handler to return false for unhandled keys while preserving `Enter`/`Escape`.
|
||||
4. Run the cheap renderer verification lane and record results.
|
||||
<!-- SECTION:PLAN:END -->
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
<!-- SECTION:NOTES:BEGIN -->
|
||||
Fixed the regression by making the global renderer keyboard handler stop early for the YouTube picker only when the picker actually consumes the key. The picker modal now returns `false` for unrelated keys, so shared overlay mpv bindings like `Space` and `KeyQ` still dispatch while the visible overlay has focus.
|
||||
|
||||
Added regression coverage in the keyboard handler suite for mpv keybinding fallback during YouTube picker state, plus a picker-modal contract test that keeps `Escape` handled but leaves unrelated keys unclaimed.
|
||||
|
||||
Verification:
|
||||
- `bun test src/renderer/handlers/keyboard.test.ts src/renderer/modals/youtube-track-picker.test.ts`
|
||||
- `bash .agents/skills/subminer-change-verification/scripts/classify_subminer_diff.sh src/renderer/handlers/keyboard.ts src/renderer/handlers/keyboard.test.ts src/renderer/modals/youtube-track-picker.ts src/renderer/modals/youtube-track-picker.test.ts`
|
||||
- `bash .agents/skills/subminer-change-verification/scripts/verify_subminer_change.sh --lane core src/renderer/handlers/keyboard.ts src/renderer/handlers/keyboard.test.ts src/renderer/modals/youtube-track-picker.ts src/renderer/modals/youtube-track-picker.test.ts`
|
||||
- verifier artifact: `.tmp/skill-verification/subminer-verify-20260322-234831-b2m6nJ`
|
||||
<!-- SECTION:NOTES:END -->
|
||||
|
||||
## Final Summary
|
||||
|
||||
<!-- SECTION:FINAL_SUMMARY:BEGIN -->
|
||||
Restored YouTube-session overlay mpv keybindings by removing an unconditional early return added to the renderer keyboard path for the YouTube subtitle picker modal. Unhandled keys now fall through to the shared mpv keybinding dispatcher, while handled picker keys (`Enter`, `Escape`) still stay local to the picker. Added renderer regression tests for both the keyboard fallback path and the picker modal key-consumption contract.
|
||||
<!-- SECTION:FINAL_SUMMARY:END -->
|
||||
@@ -1,4 +0,0 @@
|
||||
type: fixed
|
||||
area: anki
|
||||
|
||||
- Known-word cache refreshes now reconcile Anki changes incrementally instead of wiping and rebuilding on startup, mined cards can append their word into the cache immediately through a new default-enabled config flag, and explicit refreshes now run through `subminer doctor --refresh-known-words`.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: fixed
|
||||
area: subtitle
|
||||
|
||||
- Restored known-word coloring and JLPT underlines for subtitle tokens like `大体` when the subtitle token is kanji but the known-word cache only matches the kana reading.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: fixed
|
||||
area: stats
|
||||
|
||||
- Episode progress in the anime page now uses the last ended playback position instead of cumulative active watch time, avoiding distorted percentages after rewatches or repeated sessions.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: fixed
|
||||
area: stats
|
||||
|
||||
- Anime episode progress now keeps the latest known playback position through active-session checkpoints and stale-session recovery, so recently watched episodes no longer lose their progress percentage.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: changed
|
||||
area: docs
|
||||
|
||||
- Refreshed the vendored Texthooker docs/index.html bundle to match the latest local build artifacts.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: fixed
|
||||
area: stats
|
||||
|
||||
- Anime episode progress now falls back to the latest retained subtitle/event timing when a session is missing a persisted playback-position checkpoint, so older watch sessions no longer get stuck at `0%` progress.
|
||||
5
changes/2026-03-22-websocket-texthooker-docs.md
Normal file
5
changes/2026-03-22-websocket-texthooker-docs.md
Normal file
@@ -0,0 +1,5 @@
|
||||
type: docs
|
||||
area: docs
|
||||
|
||||
- Added a new WebSocket / Texthooker API and integration guide covering websocket payloads, custom client patterns, mpv plugin automation, and webhook-style relay examples.
|
||||
- Linked the new integration guide from configuration and mining workflow docs for easier discovery.
|
||||
7
changes/2026-03-23-immersion-youtube.md
Normal file
7
changes/2026-03-23-immersion-youtube.md
Normal file
@@ -0,0 +1,7 @@
|
||||
type: changed
|
||||
area: launcher
|
||||
|
||||
- Added an app-owned YouTube subtitle flow that pauses mpv, lets the overlay picker choose tracks, and injects downloaded subtitle files before playback resumes.
|
||||
- Added absPlayer-style YouTube timedtext parsing/conversion so downloaded subtitle tracks load as parsed cues for the sidebar, tokenization, and mining flows.
|
||||
- Added yt-dlp metadata probing so YouTube playback and immersion tracking keep canonical video and channel metadata.
|
||||
- Hardened the YouTube picker against duplicate submissions and tightened YouTube URL detection so follow-up runtime flows only treat real YouTube hosts as YouTube playback.
|
||||
5
changes/2026-03-23-youtube-cookie-override.md
Normal file
5
changes/2026-03-23-youtube-cookie-override.md
Normal file
@@ -0,0 +1,5 @@
|
||||
type: changed
|
||||
area: launcher
|
||||
|
||||
- Stopped forcing `--ytdl-raw-options=` before user-provided MPV options during YouTube playback so existing YouTube cookie integrations in user configs are no longer clobbered.
|
||||
- Reordered launcher argument application so user `--args` are appended after SubMiner’s internal YouTube defaults, preserving explicit runtime overrides for `--ytdl-raw-options-*`.
|
||||
@@ -284,6 +284,30 @@
|
||||
} // Secondary setting.
|
||||
}, // Primary and secondary subtitle styling.
|
||||
|
||||
// ==========================================
|
||||
// Subtitle Sidebar
|
||||
// Parsed-subtitle sidebar cue list styling, behavior, and toggle key.
|
||||
// Hot-reload: subtitle sidebar changes apply live without restarting SubMiner.
|
||||
// ==========================================
|
||||
"subtitleSidebar": {
|
||||
"enabled": false, // Enable the subtitle sidebar feature for parsed subtitle sources. Values: true | false
|
||||
"autoOpen": false, // Automatically open the subtitle sidebar once during overlay startup. Values: true | false
|
||||
"layout": "overlay", // Render the subtitle sidebar as a floating overlay or reserve space inside mpv. Values: overlay | embedded
|
||||
"toggleKey": "Backslash", // KeyboardEvent.code used to toggle the subtitle sidebar open and closed.
|
||||
"pauseVideoOnHover": false, // Pause mpv while hovering the subtitle sidebar, then resume on leave. Values: true | false
|
||||
"autoScroll": true, // Auto-scroll the active subtitle cue into view while playback advances. Values: true | false
|
||||
"maxWidth": 420, // Maximum sidebar width in CSS pixels.
|
||||
"opacity": 0.95, // Base opacity applied to the sidebar shell.
|
||||
"backgroundColor": "rgba(73, 77, 100, 0.9)", // Background color for the subtitle sidebar shell.
|
||||
"textColor": "#cad3f5", // Default cue text color in the subtitle sidebar.
|
||||
"fontFamily": "\"M PLUS 1\", \"Noto Sans CJK JP\", sans-serif", // Font family used for subtitle sidebar cue text.
|
||||
"fontSize": 16, // Base font size for subtitle sidebar cue text in CSS pixels.
|
||||
"timestampColor": "#a5adcb", // Timestamp color in the subtitle sidebar.
|
||||
"activeLineColor": "#f5bde6", // Text color for the active subtitle cue.
|
||||
"activeLineBackgroundColor": "rgba(138, 173, 244, 0.22)", // Background color for the active subtitle cue.
|
||||
"hoverLineBackgroundColor": "rgba(54, 58, 79, 0.84)" // Background color for hovered subtitle cues.
|
||||
}, // Parsed-subtitle sidebar cue list styling, behavior, and toggle key.
|
||||
|
||||
// ==========================================
|
||||
// Shared AI Provider
|
||||
// Canonical OpenAI-compatible provider transport settings shared by Anki and YouTube subtitle fixing.
|
||||
|
||||
@@ -95,6 +95,7 @@ export default {
|
||||
{ text: 'Building & Testing', link: '/development' },
|
||||
{ text: 'Architecture', link: '/architecture' },
|
||||
{ text: 'IPC + Runtime Contracts', link: '/ipc-contracts' },
|
||||
{ text: 'WebSocket + Texthooker API', link: '/websocket-texthooker-api' },
|
||||
{ text: 'Changelog', link: '/changelog' },
|
||||
],
|
||||
},
|
||||
|
||||
@@ -29,7 +29,8 @@ In both modes, the enrichment workflow is the same:
|
||||
4. Fills the translation field from the secondary subtitle or AI.
|
||||
5. Writes metadata to the miscInfo field.
|
||||
|
||||
Polling mode uses the query `"deck:<your-deck>" added:1` to find recently added cards. If no deck is configured, it searches all decks.
|
||||
Polling mode uses the query `"deck:<ankiConnect.deck>" added:1` to find recently added cards. If no deck is configured, it searches all decks.
|
||||
Known-word sync scope is controlled by `ankiConnect.knownWords.decks` (object map), with `ankiConnect.deck` used as legacy fallback.
|
||||
|
||||
### Proxy Mode Setup (Yomitan / Texthooker)
|
||||
|
||||
|
||||
@@ -1,5 +1,23 @@
|
||||
# Changelog
|
||||
|
||||
## v0.9.0 (2026-03-22)
|
||||
- Added an app-owned YouTube subtitle picker flow that boots mpv paused, opens an overlay picker, and downloads selected subtitles into external files before playback resumes.
|
||||
- Added explicit launcher/app YouTube subtitle modes `download` and `generate`, with `download` as the default path.
|
||||
- Disabled mpv native YouTube subtitle auto-loading for the app-owned flow so injected external subtitle files stay authoritative.
|
||||
- Added OSD status updates covering YouTube playback startup, subtitle acquisition, and subtitle loading.
|
||||
- Improved sidebar startup/resume behavior and overlay/sidebar subtitle synchronization.
|
||||
|
||||
## v0.8.0 (2026-03-22)
|
||||
- Added a configurable subtitle sidebar feature (`subtitleSidebar`) with overlay/embedded rendering, click-to-seek cue list, and hot-reloadable visibility and behavior controls.
|
||||
- Added a rendered sidebar modal with cue list display, click-to-seek, active-cue highlighting, and embedded layout support.
|
||||
- Added sidebar snapshot plumbing between main and renderer for overlay/sidebar synchronization.
|
||||
- Added sidebar configuration options for visibility and behavior (enabled, layout, toggle key, autoOpen, pauseOnHover, autoScroll) plus typography and sizing controls.
|
||||
- Documented `subtitleSidebar` configuration and behavior in user-facing docs (configuration.md, shortcuts.md, config.example.jsonc).
|
||||
- Updated subtitle prefetch/rendering flow to keep overlay and sidebar state in sync through media transitions.
|
||||
- Kept sidebar cue tracking stable across playback transitions and timing edge cases.
|
||||
- Fixed sidebar startup/resume positioning to jump directly to the first resolved active cue.
|
||||
- Prevented stale subtitle refreshes from regressing active-cue state.
|
||||
|
||||
## v0.7.0 (2026-03-19)
|
||||
- Added a full local immersion dashboard release line with Overview, Library, Trends, Vocabulary, and Sessions drill-down views backed by SQLite tracking data.
|
||||
- Added browser-first stats workflows: `subminer stats`, background stats daemon controls (`-b` / `-s`), stats cleanup, and dashboard-side mining actions with media enrichment.
|
||||
|
||||
@@ -17,6 +17,11 @@ For most users, start with this minimal configuration:
|
||||
"ankiConnect": {
|
||||
"enabled": true,
|
||||
"deck": "YourDeckName",
|
||||
"knownWords": {
|
||||
"decks": {
|
||||
"YourDeckName": ["Word", "Word Reading", "Expression"]
|
||||
}
|
||||
},
|
||||
"fields": {
|
||||
"sentence": "Sentence",
|
||||
"audio": "Audio",
|
||||
@@ -26,6 +31,8 @@ For most users, start with this minimal configuration:
|
||||
}
|
||||
```
|
||||
|
||||
`ankiConnect.deck` is still accepted for backward-compatible polling scope and legacy known-word fallback behavior. For known-word cache scope, prefer `ankiConnect.knownWords.decks` with deck-to-fields mapping.
|
||||
|
||||
Then customize as needed using the sections below.
|
||||
|
||||
## Configuration File
|
||||
@@ -59,6 +66,7 @@ SubMiner watches the active config file (`config.jsonc` or `config.json`) while
|
||||
Hot-reloadable fields:
|
||||
|
||||
- `subtitleStyle`
|
||||
- `subtitleSidebar`
|
||||
- `keybindings`
|
||||
- `shortcuts`
|
||||
- `secondarySub.defaultMode`
|
||||
@@ -88,6 +96,7 @@ The configuration file includes several main sections:
|
||||
**Subtitle Display**
|
||||
|
||||
- [**Subtitle Style**](#subtitle-style) - Appearance customization
|
||||
- [**Subtitle Sidebar**](#subtitle-sidebar) - Parsed cue list sidebar modal
|
||||
- [**Subtitle Position**](#subtitle-position) - Overlay vertical positioning
|
||||
- [**Secondary Subtitles**](#secondary-subtitles) - Dual subtitle track support
|
||||
|
||||
@@ -193,6 +202,8 @@ Defaults warm everything (`true` for all toggles, `lowPowerMode: false`). Settin
|
||||
|
||||
The overlay includes a built-in WebSocket server that broadcasts subtitle text to connected clients (such as texthooker-ui) for external processing.
|
||||
|
||||
For endpoint details, payload examples, and client patterns, see [WebSocket / Texthooker API & Integration](/websocket-texthooker-api).
|
||||
|
||||
By default, the server uses "auto" mode: it starts automatically unless [mpv_websocket](https://github.com/kuroahna/mpv_websocket) is detected at `~/.config/mpv/mpv_websocket`. If you have mpv_websocket installed, the built-in server is skipped to avoid conflicts.
|
||||
|
||||
See `config.example.jsonc` for detailed configuration options.
|
||||
@@ -337,6 +348,48 @@ Secondary subtitle defaults: `fontFamily: "Inter, Noto Sans, Helvetica Neue, san
|
||||
|
||||
**See `config.example.jsonc`** for the complete list of subtitle style configuration options.
|
||||
|
||||
### Subtitle Sidebar
|
||||
|
||||
Configure the parsed-subtitle sidebar modal.
|
||||
|
||||
```json
|
||||
{
|
||||
"subtitleSidebar": {
|
||||
"enabled": false,
|
||||
"autoOpen": false,
|
||||
"layout": "overlay",
|
||||
"toggleKey": "Backslash",
|
||||
"pauseVideoOnHover": false,
|
||||
"autoScroll": true,
|
||||
"fontFamily": "\"M PLUS 1\", \"Noto Sans CJK JP\", sans-serif",
|
||||
"fontSize": 16
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Option | Values | Description |
|
||||
| --------------------------- | ---------------- | -------------------------------------------------------------------------------- |
|
||||
| `enabled` | boolean | Enable subtitle sidebar support (`false` by default) |
|
||||
| `autoOpen` | boolean | Open sidebar automatically on overlay startup (`false` by default) |
|
||||
| `layout` | string | `"overlay"` floats over mpv; `"embedded"` reserves right-side player space to mimic browser-like layout |
|
||||
| `toggleKey` | string | `KeyboardEvent.code` used to open/close the sidebar (default: `"Backslash"`) |
|
||||
| `pauseVideoOnHover` | boolean | Pause playback while hovering the sidebar cue list |
|
||||
| `autoScroll` | boolean | Keep the active cue in view while playback advances |
|
||||
| `maxWidth` | number | Maximum sidebar width in CSS pixels (default: `420`) |
|
||||
| `opacity` | number | Sidebar opacity between `0` and `1` (default: `0.95`) |
|
||||
| `backgroundColor` | string | Sidebar shell background color |
|
||||
| `textColor` | hex color | Default cue text color |
|
||||
| `fontFamily` | string | CSS `font-family` value applied to sidebar cue text |
|
||||
| `fontSize` | number | Base sidebar cue font size in CSS pixels (default: `16`) |
|
||||
| `timestampColor` | hex color | Cue timestamp color |
|
||||
| `activeLineColor` | hex color | Active cue text color |
|
||||
| `activeLineBackgroundColor` | string | Active cue background color |
|
||||
| `hoverLineBackgroundColor` | string | Hovered cue background color |
|
||||
|
||||
The sidebar is only available when the active subtitle source has been parsed into a cue list. Default colors use Catppuccin Macchiato with a semi-transparent shell so the panel stays readable without feeling like an opaque settings dialog.
|
||||
|
||||
`embedded` layout is intended to act like a split-pane view: it reserves player space with a right-side video margin and keeps interaction in both the player area and sidebar. If you see unexpected offset behavior in your environment, switch back to `overlay` to isolate sidebar placement.
|
||||
|
||||
`jlptColors` keys are:
|
||||
|
||||
| Key | Default | Description |
|
||||
@@ -707,6 +760,8 @@ Anki and YouTube subtitle cleanup both read this provider, then apply feature-lo
|
||||
| `apiKey` | string | Static API key for the shared provider |
|
||||
| `apiKeyCommand` | string | Shell command used to resolve the API key |
|
||||
| `baseUrl` | string (URL) | OpenAI-compatible base URL |
|
||||
| `model` | string | Optional model override for shared provider workflows |
|
||||
| `systemPrompt` | string | Optional system prompt override for shared provider workflows |
|
||||
| `requestTimeoutMs` | integer milliseconds | Shared request timeout (default: `15000`) |
|
||||
|
||||
SubMiner uses the shared provider in two places:
|
||||
@@ -796,8 +851,8 @@ This example is intentionally compact. The option table below documents availabl
|
||||
| `proxy.port` | number | Bind port for local AnkiConnect proxy (default: `8766`) |
|
||||
| `proxy.upstreamUrl` | string (URL) | Upstream AnkiConnect URL that proxy forwards to (default: `http://127.0.0.1:8765`) |
|
||||
| `tags` | array of strings | Tags automatically added to cards mined/updated by SubMiner (default: `['SubMiner']`; set `[]` to disable automatic tagging). |
|
||||
| `deck` | string | Anki deck to monitor for new cards |
|
||||
| `ankiConnect.knownWords.decks` | array of strings | Decks used for known-word cache lookups. When omitted/empty, falls back to `ankiConnect.deck`. |
|
||||
| `ankiConnect.deck` | string | Legacy Anki polling/compatibility scope. Newer known-word cache scoping should use `ankiConnect.knownWords.decks`. |
|
||||
| `ankiConnect.knownWords.decks` | object | Deck→fields mapping for known-word cache queries (for example `{ "Kaishi 1.5k": ["Word", "Word Reading"] }`). |
|
||||
| `fields.word` | string | Card field for mined word / expression text (default: `Expression`) |
|
||||
| `fields.audio` | string | Card field for audio files (default: `ExpressionAudio`) |
|
||||
| `fields.image` | string | Card field for images (default: `Picture`) |
|
||||
@@ -818,6 +873,7 @@ This example is intentionally compact. The option table below documents availabl
|
||||
| `media.animatedMaxWidth` | number (px) | Max width for animated AVIF (default: `640`) |
|
||||
| `media.animatedMaxHeight` | number (px) | Optional max height for animated AVIF. Unset keeps source aspect-constrained height. |
|
||||
| `media.animatedCrf` | number (0-63) | CRF quality for AVIF; lower = higher quality (default: `35`) |
|
||||
| `media.syncAnimatedImageToWordAudio` | `true`, `false` | Whether animated AVIF includes an opening frame synced to sentence word-audio timing (default: `true`). |
|
||||
| `media.audioPadding` | number (seconds) | Padding around audio clip timing (default: `0.5`) |
|
||||
| `media.fallbackDuration` | number (seconds) | Default duration if timing unavailable (default: `3.0`) |
|
||||
| `media.maxMediaDuration` | number (seconds) | Max duration for generated media from multi-line copy (default: `30`, `0` to disable) |
|
||||
@@ -826,10 +882,11 @@ This example is intentionally compact. The option table below documents availabl
|
||||
| `behavior.mediaInsertMode` | `"append"`, `"prepend"` | Where to insert new media when overwrite is off (default: `"append"`) |
|
||||
| `behavior.highlightWord` | `true`, `false` | Highlight the word in sentence context (default: `true`) |
|
||||
| `ankiConnect.knownWords.highlightEnabled` | `true`, `false` | Enable fast local highlighting for words already known in Anki (default: `false`) |
|
||||
| `ankiConnect.knownWords.addMinedWordsImmediately` | `true`, `false` | Add words from successful mines into the local known-word cache immediately (default: `true`) |
|
||||
| `ankiConnect.knownWords.color` | hex color string | Text color for tokens already found in the local known-word cache (default: `"#a6da95"`). |
|
||||
| `ankiConnect.knownWords.matchMode` | `"headword"`, `"surface"` | Matching strategy for known-word highlighting (default: `"headword"`). `headword` uses token headwords; `surface` uses visible subtitle text. |
|
||||
| `ankiConnect.knownWords.refreshMinutes` | number | Minutes between known-word cache refreshes (default: `1440`) |
|
||||
| `ankiConnect.knownWords.decks` | array of strings | Decks used by known-word cache refresh. Leave empty for compatibility with legacy `deck` scope. |
|
||||
| `ankiConnect.knownWords.decks` | object | Deck→fields mapping used for known-word cache query scope (e.g. `{ "Kaishi 1.5k": ["Word", "Word Reading"] }`). |
|
||||
| `ankiConnect.nPlusOne.nPlusOne` | hex color string | Text color for the single target token to study when exactly one unknown candidate exists in a sentence (default: `"#c6a0f6"`). |
|
||||
| `ankiConnect.nPlusOne.minSentenceWords` | number | Minimum number of words required in a sentence before single unknown-word N+1 highlighting can trigger (default: `3`). |
|
||||
| `behavior.notificationType` | `"osd"`, `"system"`, `"both"`, `"none"` | Notification type on card update (default: `"osd"`) |
|
||||
@@ -875,7 +932,7 @@ Known-word cache policy:
|
||||
- `ankiConnect.nPlusOne.nPlusOne` sets the color for the single target token when exactly one eligible unknown word exists.
|
||||
- `ankiConnect.nPlusOne.minSentenceWords` sets the minimum token count required in a sentence for N+1 highlighting (default: `3`).
|
||||
- `ankiConnect.knownWords.color` sets the known-word highlight color for tokens already in Anki.
|
||||
- `ankiConnect.knownWords.decks` accepts one or more decks. If empty, it uses the legacy single `ankiConnect.deck` value as scope.
|
||||
- `ankiConnect.knownWords.decks` accepts an object keyed by deck name. If omitted or empty, it falls back to the legacy `ankiConnect.deck` single-deck scope.
|
||||
- Cache state is persisted to `known-words-cache.json` under the app `userData` directory.
|
||||
- The cache is automatically invalidated when the configured scope changes (for example, when deck changes).
|
||||
- Cache lookups are in-memory. By default, token headwords are matched against cached `Expression` / `Word` values; set `ankiConnect.knownWords.matchMode` to `"surface"` for raw subtitle text matching.
|
||||
@@ -1219,6 +1276,14 @@ Enable or disable local immersion analytics stored in SQLite for mined subtitles
|
||||
| `retention.monthlyRollupsDays` | integer (`0`-`36500`) | Monthly rollup retention window. Default `0` (keep all). |
|
||||
| `retention.vacuumIntervalDays` | integer (`0`-`3650`) | Minimum spacing between `VACUUM` passes. `0` disables vacuum. Default `0` (disabled). |
|
||||
|
||||
You can also disable immersion tracking for a single session using:
|
||||
|
||||
```bash
|
||||
SUBMINER_DISABLE_IMMERSION_TRACKING=1 subminer
|
||||
```
|
||||
|
||||
When this is set, SubMiner skips immersion-tracker startup and does not initialize or read the immersion SQLite database for that session.
|
||||
|
||||
Default behavior keeps raw events, telemetry, sessions, and rollups forever while still maintaining lifetime summary tables and daily/monthly rollups for faster reads. If you later want bounded retention, switch `retentionMode` or set explicit `retention.*` values.
|
||||
|
||||
When `dbPath` is blank or omitted, SubMiner writes telemetry and session summaries to the default app-data location:
|
||||
@@ -1239,7 +1304,7 @@ Configure the local stats UI served from SubMiner and the in-app stats overlay t
|
||||
{
|
||||
"stats": {
|
||||
"toggleKey": "Backquote",
|
||||
"serverPort": 5175,
|
||||
"serverPort": 6969,
|
||||
"autoStartServer": true,
|
||||
"autoOpenBrowser": true
|
||||
}
|
||||
@@ -1249,7 +1314,7 @@ Configure the local stats UI served from SubMiner and the in-app stats overlay t
|
||||
| Option | Values | Description |
|
||||
| ----------------- | ----------------- | --------------------------------------------------------------------------- |
|
||||
| `toggleKey` | Electron key code | Overlay-local key code used to toggle the stats overlay. Default `Backquote`. |
|
||||
| `serverPort` | integer | Localhost port for the browser stats UI. Default `5175`. |
|
||||
| `serverPort` | integer | Localhost port for the browser stats UI. Default `6969`. |
|
||||
| `autoStartServer` | `true`, `false` | Start the local stats HTTP server automatically once immersion tracking is active. Default `true`. |
|
||||
| `autoOpenBrowser` | `true`, `false` | When `subminer stats` starts the server on demand, also open the dashboard in your default browser. Default `true`. |
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ The same immersion data powers the stats dashboard.
|
||||
- Launcher command: run `subminer stats` to start the local stats server on demand and open the dashboard in your browser.
|
||||
- Background server: run `subminer stats -b` to start or reuse a dedicated background stats daemon without keeping the launcher attached, and `subminer stats -s` to stop that daemon.
|
||||
- Maintenance command: run `subminer stats cleanup` or `subminer stats cleanup -v` to backfill/repair vocabulary metadata (`headword`, `reading`, POS) and purge stale or excluded rows from `imm_words` on demand.
|
||||
- Browser page: open `http://127.0.0.1:5175` directly if the local stats server is already running.
|
||||
- Browser page: open `http://127.0.0.1:6969` directly if the local stats server is already running.
|
||||
|
||||
### Dashboard Tabs
|
||||
|
||||
@@ -42,6 +42,8 @@ Recent sessions, streak calendar, watch-time history, and a tracking snapshot wi
|
||||
|
||||
Cover-art library with search and sorting, per-series progress, episode drill-down, and direct links into mined cards.
|
||||
|
||||
When YouTube channel metadata is available, the Library tab groups videos by creator/channel and treats each tracked video as an episode-like entry inside that channel section.
|
||||
|
||||

|
||||
|
||||
#### Trends
|
||||
@@ -68,7 +70,7 @@ Stats server config lives under `stats`:
|
||||
{
|
||||
"stats": {
|
||||
"toggleKey": "Backquote",
|
||||
"serverPort": 5175,
|
||||
"serverPort": 6969,
|
||||
"autoStartServer": true,
|
||||
"autoOpenBrowser": true
|
||||
}
|
||||
|
||||
@@ -6,11 +6,28 @@ This guide walks through the sentence mining loop — from watching a video to c
|
||||
|
||||
SubMiner runs as a transparent overlay on top of mpv. As subtitles play, the overlay displays them as interactive text. You hover a word, trigger Yomitan lookup with your configured lookup key/modifier, then create an Anki card with a single action. SubMiner automatically attaches the sentence, audio clip, and screenshot.
|
||||
|
||||
```text
|
||||
Watch video → See subtitle → Hover word + trigger lookup → Yomitan popup → Add to Anki
|
||||
↓
|
||||
SubMiner auto-fills:
|
||||
sentence, audio, image, translation
|
||||
```mermaid
|
||||
flowchart LR
|
||||
classDef step fill:#c6a0f6,stroke:#494d64,color:#24273a,stroke-width:1.5px
|
||||
classDef action fill:#8aadf4,stroke:#494d64,color:#24273a,stroke-width:1.5px
|
||||
classDef result fill:#a6da95,stroke:#494d64,color:#24273a,stroke-width:1.5px
|
||||
classDef enrich fill:#8bd5ca,stroke:#494d64,color:#24273a,stroke-width:1.5px
|
||||
|
||||
Watch["Watch Video"]:::step
|
||||
Sub["Subtitle Appears"]:::step
|
||||
Hover["Hover Word"]:::action
|
||||
Lookup["Trigger Lookup"]:::action
|
||||
Yomi["Yomitan Popup"]:::result
|
||||
Add["Add to Anki"]:::result
|
||||
|
||||
Watch --> Sub --> Hover --> Lookup --> Yomi --> Add
|
||||
|
||||
Add --> Enrich["SubMiner Enriches"]:::enrich
|
||||
|
||||
Enrich --> S["Sentence"]:::enrich
|
||||
Enrich --> A["Audio Clip"]:::enrich
|
||||
Enrich --> I["Screenshot"]:::enrich
|
||||
Enrich --> T["Translation"]:::enrich
|
||||
```
|
||||
|
||||
## Subtitle Delivery Path (Startup + Runtime)
|
||||
@@ -176,6 +193,8 @@ SubMiner runs a local HTTP server at `http://127.0.0.1:5174` (configurable port)
|
||||
|
||||
The texthooker page displays the current subtitle and updates as new lines arrive. This is useful if you prefer to do lookups in a browser rather than through the overlay's built-in Yomitan.
|
||||
|
||||
If you want to build your own browser client, websocket consumer, or automation relay, see [WebSocket / Texthooker API & Integration](/websocket-texthooker-api).
|
||||
|
||||
## Subtitle Sync (Subsync)
|
||||
|
||||
If your subtitle file is out of sync with the audio, SubMiner can resynchronize it using [alass](https://github.com/kaegi/alass) or [ffsubsync](https://github.com/smacke/ffsubsync).
|
||||
@@ -206,7 +225,7 @@ Enable it in your config:
|
||||
}
|
||||
```
|
||||
|
||||
Open the dashboard in the overlay with `stats.toggleKey` (default: `` ` ``), launch it in a browser with `subminer stats`, keep a dedicated background server alive with `subminer stats -b`, stop that background server with `subminer stats -s`, or visit `http://127.0.0.1:5175` directly if the local stats server is already running. The dashboard covers overview totals, anime progress, session detail, and vocabulary drill-down from the same local immersion database.
|
||||
Open the dashboard in the overlay with `stats.toggleKey` (default: `` ` ``), launch it in a browser with `subminer stats`, keep a dedicated background server alive with `subminer stats -b`, stop that background server with `subminer stats -s`, or visit `http://127.0.0.1:6969` directly if the local stats server is already running. The dashboard covers overview totals, anime progress, session detail, and vocabulary drill-down from the same local immersion database.
|
||||
|
||||
See [Immersion Tracking](/immersion-tracking) for dashboard details, schema, and retention settings.
|
||||
|
||||
|
||||
@@ -284,6 +284,30 @@
|
||||
} // Secondary setting.
|
||||
}, // Primary and secondary subtitle styling.
|
||||
|
||||
// ==========================================
|
||||
// Subtitle Sidebar
|
||||
// Parsed-subtitle sidebar cue list styling, behavior, and toggle key.
|
||||
// Hot-reload: subtitle sidebar changes apply live without restarting SubMiner.
|
||||
// ==========================================
|
||||
"subtitleSidebar": {
|
||||
"enabled": false, // Enable the subtitle sidebar feature for parsed subtitle sources. Values: true | false
|
||||
"autoOpen": false, // Automatically open the subtitle sidebar once during overlay startup. Values: true | false
|
||||
"layout": "overlay", // Render the subtitle sidebar as a floating overlay or reserve space inside mpv. Values: overlay | embedded
|
||||
"toggleKey": "Backslash", // KeyboardEvent.code used to toggle the subtitle sidebar open and closed.
|
||||
"pauseVideoOnHover": false, // Pause mpv while hovering the subtitle sidebar, then resume on leave. Values: true | false
|
||||
"autoScroll": true, // Auto-scroll the active subtitle cue into view while playback advances. Values: true | false
|
||||
"maxWidth": 420, // Maximum sidebar width in CSS pixels.
|
||||
"opacity": 0.95, // Base opacity applied to the sidebar shell.
|
||||
"backgroundColor": "rgba(73, 77, 100, 0.9)", // Background color for the subtitle sidebar shell.
|
||||
"textColor": "#cad3f5", // Default cue text color in the subtitle sidebar.
|
||||
"fontFamily": "\"M PLUS 1\", \"Noto Sans CJK JP\", sans-serif", // Font family used for subtitle sidebar cue text.
|
||||
"fontSize": 16, // Base font size for subtitle sidebar cue text in CSS pixels.
|
||||
"timestampColor": "#a5adcb", // Timestamp color in the subtitle sidebar.
|
||||
"activeLineColor": "#f5bde6", // Text color for the active subtitle cue.
|
||||
"activeLineBackgroundColor": "rgba(138, 173, 244, 0.22)", // Background color for the active subtitle cue.
|
||||
"hoverLineBackgroundColor": "rgba(54, 58, 79, 0.84)" // Background color for hovered subtitle cues.
|
||||
}, // Parsed-subtitle sidebar cue list styling, behavior, and toggle key.
|
||||
|
||||
// ==========================================
|
||||
// Shared AI Provider
|
||||
// Canonical OpenAI-compatible provider transport settings shared by Anki and YouTube subtitle fixing.
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 52 KiB |
BIN
docs-site/public/screenshots/one-key-mining.png
Normal file
BIN
docs-site/public/screenshots/one-key-mining.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 614 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1.4 MiB After Width: | Height: | Size: 1.4 MiB |
@@ -68,10 +68,13 @@ Mouse-hover playback behavior is configured separately from shortcuts: `subtitle
|
||||
| `Ctrl/Cmd+Shift+O` | Open runtime options palette | `shortcuts.openRuntimeOptions` |
|
||||
| `Ctrl+Shift+J` | Open Jimaku subtitle search modal | `shortcuts.openJimaku` |
|
||||
| `Ctrl+Alt+S` | Open subtitle sync (subsync) modal | `shortcuts.triggerSubsync` |
|
||||
| `\` | Toggle subtitle sidebar | `subtitleSidebar.toggleKey` |
|
||||
| `` ` `` | Toggle stats overlay | `stats.toggleKey` |
|
||||
|
||||
The stats toggle is handled inside the focused visible overlay window. It is configurable through the top-level `stats.toggleKey` setting and defaults to `Backquote`.
|
||||
|
||||
The subtitle sidebar toggle is overlay-local and only opens when SubMiner has a parsed cue list for the active subtitle source.
|
||||
|
||||
## Controller Shortcuts
|
||||
|
||||
These overlay-local shortcuts are fixed and open controller utilities for the Chrome Gamepad API integration.
|
||||
@@ -133,4 +136,4 @@ The `keybindings` array overrides or extends the overlay's built-in key handling
|
||||
}
|
||||
```
|
||||
|
||||
Both `shortcuts` and `keybindings` are [hot-reloadable](/configuration#hot-reload-behavior) — changes take effect without restarting SubMiner.
|
||||
Both `shortcuts`, `keybindings`, and `subtitleSidebar` are [hot-reloadable](/configuration#hot-reload-behavior) — changes take effect without restarting SubMiner.
|
||||
|
||||
@@ -24,7 +24,7 @@ N+1 highlighting identifies sentences where you know every word except one, maki
|
||||
| --- | --- | --- |
|
||||
| `ankiConnect.knownWords.highlightEnabled` | `false` | Enable known-word cache lookups used by N+1 highlighting |
|
||||
| `ankiConnect.knownWords.refreshMinutes` | `1440` | Minutes between Anki cache refreshes |
|
||||
| `ankiConnect.knownWords.decks` | `[]` | Decks to query (falls back to `ankiConnect.deck`) |
|
||||
| `ankiConnect.knownWords.decks` | `{}` | Deck→fields map for known-word cache queries (legacy fallback: `ankiConnect.deck`) |
|
||||
| `ankiConnect.knownWords.matchMode` | `"headword"` | `"headword"` (dictionary form) or `"surface"` (raw text) |
|
||||
| `ankiConnect.nPlusOne.minSentenceWords` | `3` | Minimum tokens in a sentence for N+1 to trigger |
|
||||
| `ankiConnect.nPlusOne.nPlusOne` | `#c6a0f6` | Color for the single unknown target word |
|
||||
|
||||
@@ -228,12 +228,13 @@ If you also use Yomitan in a browser, configure that browser profile separately;
|
||||
### YouTube Playback
|
||||
|
||||
`subminer` accepts direct URLs (for example, YouTube links) and `ytsearch:` targets.
|
||||
For YouTube playback, SubMiner now generates or downloads subtitle tracks before mpv starts, then launches mpv with the resolved subtitle files attached.
|
||||
For YouTube playback, SubMiner now resolves subtitle tracks before mpv starts playback: it pauses at startup, opens an overlay subtitle picker, resolves the selected tracks, then resumes with the downloaded subtitle files attached.
|
||||
|
||||
Notes:
|
||||
|
||||
- Install `yt-dlp` so mpv can resolve YouTube streams and subtitle tracks reliably.
|
||||
- For YouTube URLs, `subminer` now generates any missing subtitles before mpv launch.
|
||||
- For YouTube URLs, the overlay picker lets you choose the primary and optional secondary subtitle tracks before playback resumes.
|
||||
- For YouTube URLs, `subminer` generates only the missing tracks after probing YouTube's native/manual subtitle inventory.
|
||||
- It probes manual/native YouTube subtitle tracks first, then falls back to local `whisper.cpp` only for missing tracks.
|
||||
- Primary subtitle target languages come from `youtubeSubgen.primarySubLanguages` (defaults to `["ja","jpn"]`).
|
||||
- Secondary target languages come from `secondarySub.secondarySubLanguages` (defaults to English if unset).
|
||||
|
||||
357
docs-site/websocket-texthooker-api.md
Normal file
357
docs-site/websocket-texthooker-api.md
Normal file
@@ -0,0 +1,357 @@
|
||||
# WebSocket / Texthooker API & Integration
|
||||
|
||||
SubMiner exposes a small set of local integration surfaces for browser tools, automation helpers, and mpv-driven workflows:
|
||||
|
||||
- **Subtitle WebSocket** at `ws://127.0.0.1:6677` by default for plain subtitle pushes.
|
||||
- **Annotation WebSocket** at `ws://127.0.0.1:6678` by default for token-aware clients.
|
||||
- **Texthooker HTTP UI** at `http://127.0.0.1:5174` by default for browser-based subtitle consumption.
|
||||
- **mpv plugin script messages** for in-player automation and extension.
|
||||
|
||||
This page documents those integration points and shows how to build custom consumers around them.
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Surface | Default | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `websocket` | `ws://127.0.0.1:6677` | Basic subtitle broadcast stream |
|
||||
| `annotationWebsocket` | `ws://127.0.0.1:6678` | Structured stream with token metadata |
|
||||
| `texthooker` | `http://127.0.0.1:5174` | Local texthooker UI with injected websocket config |
|
||||
| mpv plugin | `script-message subminer-*` | Start/stop/toggle/status automation inside mpv |
|
||||
|
||||
## Enable and Configure the Services
|
||||
|
||||
SubMiner's integration ports are configured in `config.jsonc`.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"websocket": {
|
||||
"enabled": "auto",
|
||||
"port": 6677
|
||||
},
|
||||
"annotationWebsocket": {
|
||||
"enabled": true,
|
||||
"port": 6678
|
||||
},
|
||||
"texthooker": {
|
||||
"launchAtStartup": true,
|
||||
"openBrowser": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### How startup behaves
|
||||
|
||||
- `websocket.enabled: "auto"` starts the basic subtitle websocket unless SubMiner detects the external `mpv_websocket` plugin.
|
||||
- `annotationWebsocket` is independent from `websocket` and stays enabled unless you explicitly disable it.
|
||||
- `texthooker.launchAtStartup` starts the local HTTP UI automatically.
|
||||
- `texthooker.openBrowser` controls whether SubMiner opens the texthooker page in your browser when it starts.
|
||||
|
||||
If you use the [mpv plugin](/mpv-plugin), it can also start a texthooker-only helper process and override the texthooker port in `subminer.conf`.
|
||||
|
||||
## Developer API Documentation
|
||||
|
||||
### 1. Subtitle WebSocket
|
||||
|
||||
Use the basic subtitle websocket when you only need the current subtitle line and a ready-to-render HTML sentence string.
|
||||
|
||||
- **Default URL:** `ws://127.0.0.1:6677`
|
||||
- **Transport:** local WebSocket server bound to `127.0.0.1`
|
||||
- **Direction:** server push only
|
||||
- **Client auth:** none
|
||||
- **Reconnects:** client-managed
|
||||
|
||||
When a client connects, SubMiner immediately sends the latest subtitle payload if one is available. After that, it pushes a new message each time the current subtitle changes.
|
||||
|
||||
#### Message shape
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"text": "無事",
|
||||
"sentence": "<span class=\"word word-known word-jlpt-n2\" data-reading=\"ぶじ\" data-headword=\"無事\" data-frequency-rank=\"745\" data-jlpt-level=\"N2\">無事</span>",
|
||||
"tokens": [
|
||||
{
|
||||
"surface": "無事",
|
||||
"reading": "ぶじ",
|
||||
"headword": "無事",
|
||||
"startPos": 0,
|
||||
"endPos": 2,
|
||||
"partOfSpeech": "other",
|
||||
"isMerged": false,
|
||||
"isKnown": true,
|
||||
"isNPlusOneTarget": false,
|
||||
"isNameMatch": false,
|
||||
"jlptLevel": "N2",
|
||||
"frequencyRank": 745,
|
||||
"className": "word word-known word-jlpt-n2",
|
||||
"frequencyRankLabel": "745",
|
||||
"jlptLevelLabel": "N2"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### Field reference
|
||||
|
||||
| Field | Type | Notes |
|
||||
| --- | --- | --- |
|
||||
| `version` | number | Current websocket payload version. Today this is `1`. |
|
||||
| `text` | string | Raw subtitle text. |
|
||||
| `sentence` | string | HTML string with `<span>` wrappers and `data-*` attributes for client rendering. |
|
||||
| `tokens` | array | Token metadata; empty when the subtitle is not tokenized yet. |
|
||||
|
||||
Each token may include:
|
||||
|
||||
| Token field | Type | Notes |
|
||||
| --- | --- | --- |
|
||||
| `surface` | string | Display text for the token |
|
||||
| `reading` | string | Kana reading when available |
|
||||
| `headword` | string | Dictionary headword when available |
|
||||
| `startPos` / `endPos` | number | Character offsets in the subtitle text |
|
||||
| `partOfSpeech` | string | SubMiner token POS label |
|
||||
| `isMerged` | boolean | Whether this token represents merged content |
|
||||
| `isKnown` | boolean | Marked known by SubMiner's known-word logic |
|
||||
| `isNPlusOneTarget` | boolean | True when the token is the sentence's N+1 target |
|
||||
| `isNameMatch` | boolean | True for prioritized character-name matches |
|
||||
| `frequencyRank` | number | Frequency rank when available |
|
||||
| `jlptLevel` | string | JLPT level when available |
|
||||
| `className` | string | CSS-ready class list derived from token state |
|
||||
| `frequencyRankLabel` | string or `null` | Preformatted rank label for UIs |
|
||||
| `jlptLevelLabel` | string or `null` | Preformatted JLPT label for UIs |
|
||||
|
||||
### 2. Annotation WebSocket
|
||||
|
||||
Use the annotation websocket for custom clients that want the same structured token payload the bundled texthooker UI consumes.
|
||||
|
||||
- **Default URL:** `ws://127.0.0.1:6678`
|
||||
- **Payload shape:** same JSON contract as the basic subtitle websocket
|
||||
- **Primary difference:** this stream is intended to stay on even when the basic websocket auto-disables because `mpv_websocket` is installed
|
||||
|
||||
In practice, if you are building a new client, prefer `annotationWebsocket` unless you specifically need compatibility with an existing `websocket` consumer.
|
||||
|
||||
### 3. HTML markup conventions
|
||||
|
||||
The `sentence` field is pre-rendered HTML generated by SubMiner. Depending on token state, it can include classes such as:
|
||||
|
||||
- `word`
|
||||
- `word-known`
|
||||
- `word-n-plus-one`
|
||||
- `word-name-match`
|
||||
- `word-jlpt-n1` through `word-jlpt-n5`
|
||||
- `word-frequency-single`
|
||||
- `word-frequency-band-1` through `word-frequency-band-5`
|
||||
|
||||
SubMiner also adds tooltip-friendly data attributes when available:
|
||||
|
||||
- `data-reading`
|
||||
- `data-headword`
|
||||
- `data-frequency-rank`
|
||||
- `data-jlpt-level`
|
||||
|
||||
If you need a fully custom UI, ignore `sentence` and render from `tokens` instead.
|
||||
|
||||
## Texthooker Integration Guide
|
||||
|
||||
### When to use the bundled texthooker page
|
||||
|
||||
Use texthooker when you want a browser tab that:
|
||||
|
||||
- updates live from current subtitles
|
||||
- works well with browser-based Yomitan setups
|
||||
- inherits SubMiner's coloring preferences and websocket URL automatically
|
||||
|
||||
Start it with either:
|
||||
|
||||
```bash
|
||||
subminer texthooker
|
||||
```
|
||||
|
||||
or by leaving `texthooker.launchAtStartup` enabled.
|
||||
|
||||
### What SubMiner injects into the page
|
||||
|
||||
When SubMiner serves the local texthooker UI, it injects bootstrap values into `window.localStorage`, including:
|
||||
|
||||
- `bannou-texthooker-websocketUrl`
|
||||
- coloring toggles for known/N+1/name/frequency/JLPT styling
|
||||
- CSS custom properties for SubMiner's token colors
|
||||
|
||||
That means the bundled page already knows which websocket to connect to and which color palette to use.
|
||||
|
||||
### Build a custom websocket client
|
||||
|
||||
Here is a minimal browser client for the annotation stream:
|
||||
|
||||
```html
|
||||
<!doctype html>
|
||||
<meta charset="utf-8" />
|
||||
<title>SubMiner client</title>
|
||||
<div id="subtitle">Waiting for subtitles...</div>
|
||||
<script>
|
||||
const subtitle = document.getElementById('subtitle');
|
||||
const ws = new WebSocket('ws://127.0.0.1:6678');
|
||||
|
||||
ws.addEventListener('message', (event) => {
|
||||
const payload = JSON.parse(event.data);
|
||||
subtitle.innerHTML = payload.sentence || payload.text;
|
||||
});
|
||||
|
||||
ws.addEventListener('close', () => {
|
||||
subtitle.textContent = 'Connection closed; reload or reconnect.';
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
### Build a custom Node client
|
||||
|
||||
```js
|
||||
import WebSocket from 'ws';
|
||||
|
||||
const ws = new WebSocket('ws://127.0.0.1:6678');
|
||||
|
||||
ws.on('message', (raw) => {
|
||||
const payload = JSON.parse(String(raw));
|
||||
console.log({
|
||||
text: payload.text,
|
||||
tokens: payload.tokens.length,
|
||||
firstToken: payload.tokens[0]?.surface ?? null,
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Integration tips
|
||||
|
||||
- Bind only to `127.0.0.1`; these services are local-only by design.
|
||||
- Handle empty `tokens` arrays gracefully because subtitle text can arrive before tokenization completes.
|
||||
- Reconnect on disconnect; SubMiner does not manage client reconnects for you.
|
||||
- Prefer `payload.text` for logging/automation and `payload.sentence` or `payload.tokens` for UI rendering.
|
||||
|
||||
## Plugin Development
|
||||
|
||||
SubMiner does **not** currently expose a general-purpose third-party plugin SDK inside the app itself. Today, the supported extension surfaces are:
|
||||
|
||||
1. the local websocket streams
|
||||
2. the local texthooker UI
|
||||
3. the mpv Lua plugin's script-message API
|
||||
4. the launcher CLI
|
||||
|
||||
### mpv script messages
|
||||
|
||||
The mpv plugin accepts these script messages:
|
||||
|
||||
```text
|
||||
script-message subminer-start
|
||||
script-message subminer-stop
|
||||
script-message subminer-toggle
|
||||
script-message subminer-menu
|
||||
script-message subminer-options
|
||||
script-message subminer-restart
|
||||
script-message subminer-status
|
||||
script-message subminer-autoplay-ready
|
||||
script-message subminer-aniskip-refresh
|
||||
script-message subminer-skip-intro
|
||||
```
|
||||
|
||||
The start command also accepts inline overrides:
|
||||
|
||||
```text
|
||||
script-message subminer-start backend=hyprland socket=/custom/path texthooker=no log-level=debug
|
||||
```
|
||||
|
||||
### Practical extension patterns
|
||||
|
||||
#### Add another mpv script that coordinates with SubMiner
|
||||
|
||||
Examples:
|
||||
|
||||
- send `subminer-start` after your own media-selection script chooses a file
|
||||
- send `subminer-status` before running follow-up automation
|
||||
- send `subminer-aniskip-refresh` after you update title/episode metadata
|
||||
|
||||
#### Build a launcher wrapper
|
||||
|
||||
Examples:
|
||||
|
||||
- open a media picker, then call `subminer /path/to/file.mkv`
|
||||
- launch browser-only subtitle tooling with `subminer texthooker`
|
||||
- disable the helper UI for a session with `subminer --no-texthooker video.mkv`
|
||||
|
||||
#### Build an overlay-adjacent client
|
||||
|
||||
Examples:
|
||||
|
||||
- browser widget showing current subtitle + token breakdown
|
||||
- local vocabulary capture helper that writes interesting lines to a file
|
||||
- bridge service that forwards websocket events into your own workflow engine
|
||||
|
||||
## Webhook Examples
|
||||
|
||||
SubMiner does **not** currently send outbound webhooks by itself. The supported pattern is to consume the websocket locally and relay events into another system.
|
||||
|
||||
That still makes webhook-style automation straightforward.
|
||||
|
||||
### Example: forward subtitle lines to a local webhook receiver
|
||||
|
||||
```js
|
||||
import WebSocket from 'ws';
|
||||
|
||||
const ws = new WebSocket('ws://127.0.0.1:6678');
|
||||
|
||||
ws.on('message', async (raw) => {
|
||||
const payload = JSON.parse(String(raw));
|
||||
|
||||
await fetch('http://127.0.0.1:5678/subminer/subtitle', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
text: payload.text,
|
||||
tokens: payload.tokens,
|
||||
receivedAt: new Date().toISOString(),
|
||||
}),
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Automation ideas
|
||||
|
||||
- **n8n / Make / Zapier relay:** send each subtitle line into an automation workflow for logging, translation, or summarization.
|
||||
- **Discord / Slack notifier:** post only lines that contain unknown words or N+1 targets.
|
||||
- **Obsidian / Markdown capture:** append subtitle lines plus token metadata to a daily immersion note.
|
||||
- **Local LLM pipeline:** trigger a glossary, translation, or sentence-mining workflow whenever a new line arrives.
|
||||
|
||||
### Filtering example: only forward N+1 lines
|
||||
|
||||
```js
|
||||
import WebSocket from 'ws';
|
||||
|
||||
const ws = new WebSocket('ws://127.0.0.1:6678');
|
||||
|
||||
ws.on('message', async (raw) => {
|
||||
const payload = JSON.parse(String(raw));
|
||||
const hasNPlusOne = payload.tokens.some((token) => token.isNPlusOneTarget);
|
||||
|
||||
if (!hasNPlusOne) return;
|
||||
|
||||
await fetch('http://127.0.0.1:5678/subminer/n-plus-one', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ text: payload.text, tokens: payload.tokens }),
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Recommended Integration Combinations
|
||||
|
||||
- **Browser Yomitan client:** `texthooker` + `annotationWebsocket`
|
||||
- **Custom dashboard:** `annotationWebsocket` only
|
||||
- **Lightweight subtitle mirror:** `websocket` only
|
||||
- **mpv-side automation:** mpv plugin script messages + optional websocket relay
|
||||
- **Webhook-style workflows:** `annotationWebsocket` + your own local relay service
|
||||
|
||||
## Related Pages
|
||||
|
||||
- [Configuration](/configuration#websocket-server)
|
||||
- [Mining Workflow — Texthooker](/mining-workflow#texthooker)
|
||||
- [MPV Plugin](/mpv-plugin)
|
||||
- [Launcher Script](/launcher-script)
|
||||
- [Anki Integration](/anki-integration#proxy-mode-setup-yomitan--texthooker)
|
||||
@@ -8,6 +8,7 @@
|
||||
4. Bump `package.json` to the release version.
|
||||
5. Build release metadata before tagging:
|
||||
`bun run changelog:build --version <version> --date <yyyy-mm-dd>`
|
||||
- Release CI now also auto-runs this step when releasing directly from a tag and `changes/*.md` fragments remain.
|
||||
6. Review `CHANGELOG.md` and `release/release-notes.md`.
|
||||
7. Run release gate locally:
|
||||
`bun run changelog:check --version <version>`
|
||||
@@ -29,6 +30,8 @@ Notes:
|
||||
- Pass `--date` explicitly when you want the release stamped with the local cut date; otherwise the generator uses the current ISO date, which can roll over to the next UTC day late at night.
|
||||
- `changelog:check` now rejects tag/package version mismatches.
|
||||
- `changelog:build` generates `CHANGELOG.md` + `release/release-notes.md` and removes the released `changes/*.md` fragments.
|
||||
- In the same way, the release workflow now auto-runs `changelog:build` when it detects unreleased `changes/*.md` on a tag-based run, then verifies and publishes.
|
||||
- Do not tag while `changes/*.md` fragments still exist.
|
||||
- If you need to repair a published release body (for example, a prior version’s section was omitted), regenerate notes from `CHANGELOG.md` and re-edit the release with `gh release edit --notes-file`.
|
||||
- Tagged release workflow now also attempts to update `subminer-bin` on the AUR after GitHub Release publication.
|
||||
- Required GitHub Actions secret: `AUR_SSH_PRIVATE_KEY`. Add the matching public key to your AUR account before relying on the automation.
|
||||
|
||||
@@ -22,6 +22,7 @@ Read when: you need to find the owner module for a behavior or test surface
|
||||
- Subtitle/token pipeline: `src/core/services/tokenizer*`, `src/subtitle/`, `src/tokenizers/`
|
||||
- Anki workflow: `src/anki-integration/`, `src/core/services/anki-jimaku*.ts`
|
||||
- Immersion tracking: `src/core/services/immersion-tracker/`
|
||||
Includes stats storage/query schema such as `imm_videos`, `imm_media_art`, and `imm_youtube_videos` for per-video and YouTube-specific library metadata.
|
||||
- AniList tracking: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*`
|
||||
- Jellyfin integration: `src/core/services/jellyfin*.ts`, `src/main/runtime/composers/jellyfin-*`
|
||||
- Window trackers: `src/window-trackers/`
|
||||
|
||||
@@ -553,10 +553,12 @@ export function buildSubminerScriptOpts(
|
||||
socketPath: string,
|
||||
aniSkipMetadata: AniSkipMetadata | null,
|
||||
logLevel: LogLevel = 'info',
|
||||
extraParts: string[] = [],
|
||||
): string {
|
||||
const parts = [
|
||||
`subminer-binary_path=${sanitizeScriptOptValue(appPath)}`,
|
||||
`subminer-socket_path=${sanitizeScriptOptValue(socketPath)}`,
|
||||
...extraParts.map(sanitizeScriptOptValue),
|
||||
];
|
||||
if (logLevel !== 'info') {
|
||||
parts.push(`subminer-log_level=${sanitizeScriptOptValue(logLevel)}`);
|
||||
|
||||
@@ -149,20 +149,16 @@ test('doctor command forwards refresh-known-words to app binary', () => {
|
||||
context.args.doctorRefreshKnownWords = true;
|
||||
const forwarded: string[][] = [];
|
||||
|
||||
assert.throws(
|
||||
() =>
|
||||
runDoctorCommand(context, {
|
||||
commandExists: () => false,
|
||||
configExists: () => true,
|
||||
resolveMainConfigPath: () => '/tmp/SubMiner/config.jsonc',
|
||||
runAppCommandWithInherit: (_appPath, appArgs) => {
|
||||
forwarded.push(appArgs);
|
||||
throw new ExitSignal(0);
|
||||
},
|
||||
}),
|
||||
(error: unknown) => error instanceof ExitSignal && error.code === 0,
|
||||
);
|
||||
const handled = runDoctorCommand(context, {
|
||||
commandExists: () => false,
|
||||
configExists: () => true,
|
||||
resolveMainConfigPath: () => '/tmp/SubMiner/config.jsonc',
|
||||
runAppCommandWithInherit: (_appPath, appArgs) => {
|
||||
forwarded.push(appArgs);
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(handled, true);
|
||||
assert.deepEqual(forwarded, [['--refresh-known-words']]);
|
||||
});
|
||||
|
||||
@@ -187,31 +183,25 @@ test('dictionary command forwards --dictionary and target path to app binary', (
|
||||
context.args.dictionaryTarget = '/tmp/anime';
|
||||
const forwarded: string[][] = [];
|
||||
|
||||
assert.throws(
|
||||
() =>
|
||||
runDictionaryCommand(context, {
|
||||
runAppCommandWithInherit: (_appPath, appArgs) => {
|
||||
forwarded.push(appArgs);
|
||||
throw new ExitSignal(0);
|
||||
},
|
||||
}),
|
||||
(error: unknown) => error instanceof ExitSignal && error.code === 0,
|
||||
);
|
||||
const handled = runDictionaryCommand(context, {
|
||||
runAppCommandWithInherit: (_appPath, appArgs) => {
|
||||
forwarded.push(appArgs);
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(handled, true);
|
||||
assert.deepEqual(forwarded, [['--dictionary', '--dictionary-target', '/tmp/anime']]);
|
||||
});
|
||||
|
||||
test('dictionary command throws if app handoff unexpectedly returns', () => {
|
||||
test('dictionary command returns after app handoff starts', () => {
|
||||
const context = createContext();
|
||||
context.args.dictionary = true;
|
||||
|
||||
assert.throws(
|
||||
() =>
|
||||
runDictionaryCommand(context, {
|
||||
runAppCommandWithInherit: () => undefined as never,
|
||||
}),
|
||||
/unexpectedly returned/,
|
||||
);
|
||||
const handled = runDictionaryCommand(context, {
|
||||
runAppCommandWithInherit: () => undefined,
|
||||
});
|
||||
|
||||
assert.equal(handled, true);
|
||||
});
|
||||
|
||||
test('stats command launches attached app command with response path', async () => {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { runAppCommandWithInherit } from '../mpv.js';
|
||||
import type { LauncherCommandContext } from './context.js';
|
||||
|
||||
interface DictionaryCommandDeps {
|
||||
runAppCommandWithInherit: (appPath: string, appArgs: string[]) => never;
|
||||
runAppCommandWithInherit: (appPath: string, appArgs: string[]) => void;
|
||||
}
|
||||
|
||||
const defaultDeps: DictionaryCommandDeps = {
|
||||
@@ -27,5 +27,5 @@ export function runDictionaryCommand(
|
||||
}
|
||||
|
||||
deps.runAppCommandWithInherit(appPath, forwarded);
|
||||
throw new Error('Dictionary command app handoff unexpectedly returned.');
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ interface DoctorCommandDeps {
|
||||
commandExists(command: string): boolean;
|
||||
configExists(path: string): boolean;
|
||||
resolveMainConfigPath(): string;
|
||||
runAppCommandWithInherit(appPath: string, appArgs: string[]): never;
|
||||
runAppCommandWithInherit(appPath: string, appArgs: string[]): void;
|
||||
}
|
||||
|
||||
const defaultDeps: DoctorCommandDeps = {
|
||||
@@ -85,6 +85,7 @@ export function runDoctorCommand(
|
||||
return true;
|
||||
}
|
||||
deps.runAppCommandWithInherit(appPath, ['--refresh-known-words']);
|
||||
return true;
|
||||
}
|
||||
|
||||
const hasHardFailure = checks.some((entry) =>
|
||||
|
||||
@@ -21,6 +21,7 @@ export async function runJellyfinCommand(context: LauncherCommandContext): Promi
|
||||
if (args.logLevel !== 'info') forwarded.push('--log-level', args.logLevel);
|
||||
appendPasswordStore(forwarded);
|
||||
runAppCommandWithInherit(appPath, forwarded);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (args.jellyfinLogin) {
|
||||
@@ -44,6 +45,7 @@ export async function runJellyfinCommand(context: LauncherCommandContext): Promi
|
||||
if (args.logLevel !== 'info') forwarded.push('--log-level', args.logLevel);
|
||||
appendPasswordStore(forwarded);
|
||||
runAppCommandWithInherit(appPath, forwarded);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (args.jellyfinLogout) {
|
||||
@@ -51,6 +53,7 @@ export async function runJellyfinCommand(context: LauncherCommandContext): Promi
|
||||
if (args.logLevel !== 'info') forwarded.push('--log-level', args.logLevel);
|
||||
appendPasswordStore(forwarded);
|
||||
runAppCommandWithInherit(appPath, forwarded);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (args.jellyfinPlay) {
|
||||
@@ -69,13 +72,8 @@ export async function runJellyfinCommand(context: LauncherCommandContext): Promi
|
||||
if (args.logLevel !== 'info') forwarded.push('--log-level', args.logLevel);
|
||||
appendPasswordStore(forwarded);
|
||||
runAppCommandWithInherit(appPath, forwarded);
|
||||
return true;
|
||||
}
|
||||
|
||||
return Boolean(
|
||||
args.jellyfin ||
|
||||
args.jellyfinLogin ||
|
||||
args.jellyfinLogout ||
|
||||
args.jellyfinPlay ||
|
||||
args.jellyfinDiscovery,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
113
launcher/commands/playback-command.test.ts
Normal file
113
launcher/commands/playback-command.test.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import type { LauncherCommandContext } from './context.js';
|
||||
import { runPlaybackCommandWithDeps } from './playback-command.js';
|
||||
|
||||
function createContext(): LauncherCommandContext {
|
||||
return {
|
||||
args: {
|
||||
backend: 'auto',
|
||||
directory: '.',
|
||||
recursive: false,
|
||||
profile: '',
|
||||
startOverlay: false,
|
||||
youtubeMode: 'download',
|
||||
whisperBin: '',
|
||||
whisperModel: '',
|
||||
whisperVadModel: '',
|
||||
whisperThreads: 0,
|
||||
youtubeSubgenOutDir: '',
|
||||
youtubeSubgenAudioFormat: '',
|
||||
youtubeSubgenKeepTemp: false,
|
||||
youtubeFixWithAi: false,
|
||||
youtubePrimarySubLangs: [],
|
||||
youtubeSecondarySubLangs: [],
|
||||
youtubeAudioLangs: [],
|
||||
youtubeWhisperSourceLanguage: '',
|
||||
aiConfig: {},
|
||||
useTexthooker: false,
|
||||
autoStartOverlay: false,
|
||||
texthookerOnly: false,
|
||||
useRofi: false,
|
||||
logLevel: 'info',
|
||||
passwordStore: '',
|
||||
target: 'https://www.youtube.com/watch?v=65Ovd7t8sNw',
|
||||
targetKind: 'url',
|
||||
jimakuApiKey: '',
|
||||
jimakuApiKeyCommand: '',
|
||||
jimakuApiBaseUrl: '',
|
||||
jimakuLanguagePreference: 'ja',
|
||||
jimakuMaxEntryResults: 20,
|
||||
jellyfin: false,
|
||||
jellyfinLogin: false,
|
||||
jellyfinLogout: false,
|
||||
jellyfinPlay: false,
|
||||
jellyfinDiscovery: false,
|
||||
dictionary: false,
|
||||
stats: false,
|
||||
doctor: false,
|
||||
doctorRefreshKnownWords: false,
|
||||
configPath: false,
|
||||
configShow: false,
|
||||
mpvIdle: false,
|
||||
mpvSocket: false,
|
||||
mpvStatus: false,
|
||||
mpvArgs: '',
|
||||
appPassthrough: false,
|
||||
appArgs: [],
|
||||
jellyfinServer: '',
|
||||
jellyfinUsername: '',
|
||||
jellyfinPassword: '',
|
||||
},
|
||||
scriptPath: '/tmp/subminer',
|
||||
scriptName: 'subminer',
|
||||
mpvSocketPath: '/tmp/subminer.sock',
|
||||
pluginRuntimeConfig: {
|
||||
socketPath: '/tmp/subminer.sock',
|
||||
autoStart: true,
|
||||
autoStartVisibleOverlay: true,
|
||||
autoStartPauseUntilReady: true,
|
||||
},
|
||||
appPath: '/tmp/SubMiner.AppImage',
|
||||
launcherJellyfinConfig: {},
|
||||
processAdapter: {
|
||||
platform: () => 'linux',
|
||||
onSignal: () => {},
|
||||
writeStdout: () => {},
|
||||
exit: (_code: number): never => {
|
||||
throw new Error('unexpected exit');
|
||||
},
|
||||
setExitCode: () => {},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('youtube playback launches overlay with youtube-play args in the primary app start', async () => {
|
||||
const calls: string[] = [];
|
||||
const context = createContext();
|
||||
|
||||
await runPlaybackCommandWithDeps(context, {
|
||||
ensurePlaybackSetupReady: async () => {},
|
||||
chooseTarget: async (_args, _scriptPath) => ({ target: context.args.target, kind: 'url' }),
|
||||
checkDependencies: () => {},
|
||||
registerCleanup: () => {},
|
||||
startMpv: async () => {
|
||||
calls.push('startMpv');
|
||||
},
|
||||
waitForUnixSocketReady: async () => true,
|
||||
startOverlay: async (_appPath, _args, _socketPath, extraAppArgs = []) => {
|
||||
calls.push(`startOverlay:${extraAppArgs.join(' ')}`);
|
||||
},
|
||||
launchAppCommandDetached: (_appPath: string, appArgs: string[]) => {
|
||||
calls.push(`launch:${appArgs.join(' ')}`);
|
||||
},
|
||||
log: () => {},
|
||||
cleanupPlaybackSession: async () => {},
|
||||
getMpvProc: () => null,
|
||||
});
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
'startMpv',
|
||||
'startOverlay:--youtube-play https://www.youtube.com/watch?v=65Ovd7t8sNw --youtube-mode download',
|
||||
]);
|
||||
});
|
||||
@@ -6,13 +6,13 @@ import { commandExists, isYoutubeTarget, realpathMaybe, resolvePathMaybe } from
|
||||
import { collectVideos, showFzfMenu, showRofiMenu } from '../picker.js';
|
||||
import {
|
||||
cleanupPlaybackSession,
|
||||
launchAppCommandDetached,
|
||||
startMpv,
|
||||
startOverlay,
|
||||
state,
|
||||
stopOverlay,
|
||||
waitForUnixSocketReady,
|
||||
} from '../mpv.js';
|
||||
import { generateYoutubeSubtitles } from '../youtube.js';
|
||||
import type { Args } from '../types.js';
|
||||
import type { LauncherCommandContext } from './context.js';
|
||||
import { ensureLauncherSetupReady } from '../setup-gate.js';
|
||||
@@ -31,11 +31,12 @@ function checkDependencies(args: Args): void {
|
||||
|
||||
if (!commandExists('mpv')) missing.push('mpv');
|
||||
|
||||
if (args.targetKind === 'url' && isYoutubeTarget(args.target) && !commandExists('yt-dlp')) {
|
||||
const isYoutubeUrl = args.targetKind === 'url' && isYoutubeTarget(args.target);
|
||||
if (args.targetKind === 'url' && !isYoutubeUrl && !commandExists('yt-dlp')) {
|
||||
missing.push('yt-dlp');
|
||||
}
|
||||
|
||||
if (args.targetKind === 'url' && isYoutubeTarget(args.target) && !commandExists('ffmpeg')) {
|
||||
if (args.targetKind === 'url' && !isYoutubeUrl && !commandExists('ffmpeg')) {
|
||||
missing.push('ffmpeg');
|
||||
}
|
||||
|
||||
@@ -126,30 +127,66 @@ async function ensurePlaybackSetupReady(context: LauncherCommandContext): Promis
|
||||
}
|
||||
|
||||
export async function runPlaybackCommand(context: LauncherCommandContext): Promise<void> {
|
||||
return runPlaybackCommandWithDeps(context, {
|
||||
ensurePlaybackSetupReady,
|
||||
chooseTarget,
|
||||
checkDependencies,
|
||||
registerCleanup,
|
||||
startMpv,
|
||||
waitForUnixSocketReady,
|
||||
startOverlay,
|
||||
launchAppCommandDetached,
|
||||
log,
|
||||
cleanupPlaybackSession,
|
||||
getMpvProc: () => state.mpvProc,
|
||||
});
|
||||
}
|
||||
|
||||
type PlaybackCommandDeps = {
|
||||
ensurePlaybackSetupReady: (context: LauncherCommandContext) => Promise<void>;
|
||||
chooseTarget: (
|
||||
args: Args,
|
||||
scriptPath: string,
|
||||
) => Promise<{ target: string; kind: 'file' | 'url' } | null>;
|
||||
checkDependencies: (args: Args) => void;
|
||||
registerCleanup: (context: LauncherCommandContext) => void;
|
||||
startMpv: typeof startMpv;
|
||||
waitForUnixSocketReady: typeof waitForUnixSocketReady;
|
||||
startOverlay: typeof startOverlay;
|
||||
launchAppCommandDetached: typeof launchAppCommandDetached;
|
||||
log: typeof log;
|
||||
cleanupPlaybackSession: typeof cleanupPlaybackSession;
|
||||
getMpvProc: () => typeof state.mpvProc;
|
||||
};
|
||||
|
||||
export async function runPlaybackCommandWithDeps(
|
||||
context: LauncherCommandContext,
|
||||
deps: PlaybackCommandDeps,
|
||||
): Promise<void> {
|
||||
const { args, appPath, scriptPath, mpvSocketPath, pluginRuntimeConfig, processAdapter } = context;
|
||||
if (!appPath) {
|
||||
fail('SubMiner AppImage not found. Install to ~/.local/bin/ or set SUBMINER_APPIMAGE_PATH.');
|
||||
}
|
||||
|
||||
await ensurePlaybackSetupReady(context);
|
||||
await deps.ensurePlaybackSetupReady(context);
|
||||
|
||||
if (!args.target) {
|
||||
checkPickerDependencies(args);
|
||||
}
|
||||
|
||||
const targetChoice = await chooseTarget(args, scriptPath);
|
||||
const targetChoice = await deps.chooseTarget(args, scriptPath);
|
||||
if (!targetChoice) {
|
||||
log('info', args.logLevel, 'No video selected, exiting');
|
||||
deps.log('info', args.logLevel, 'No video selected, exiting');
|
||||
processAdapter.exit(0);
|
||||
}
|
||||
|
||||
checkDependencies({
|
||||
deps.checkDependencies({
|
||||
...args,
|
||||
target: targetChoice ? targetChoice.target : args.target,
|
||||
targetKind: targetChoice ? targetChoice.kind : 'url',
|
||||
});
|
||||
|
||||
registerCleanup(context);
|
||||
deps.registerCleanup(context);
|
||||
|
||||
const selectedTarget = targetChoice
|
||||
? {
|
||||
@@ -159,30 +196,11 @@ export async function runPlaybackCommand(context: LauncherCommandContext): Promi
|
||||
: { target: args.target, kind: 'url' as const };
|
||||
|
||||
const isYoutubeUrl = selectedTarget.kind === 'url' && isYoutubeTarget(selectedTarget.target);
|
||||
let preloadedSubtitles: { primaryPath?: string; secondaryPath?: string } | undefined;
|
||||
const isAppOwnedYoutubeFlow = isYoutubeUrl;
|
||||
const youtubeMode = args.youtubeMode ?? 'download';
|
||||
|
||||
if (isYoutubeUrl) {
|
||||
log('info', args.logLevel, 'YouTube subtitle generation: preload before mpv');
|
||||
const generated = await generateYoutubeSubtitles(selectedTarget.target, args);
|
||||
preloadedSubtitles = {
|
||||
primaryPath: generated.primaryPath,
|
||||
secondaryPath: generated.secondaryPath,
|
||||
};
|
||||
const primaryStatus = generated.primaryPath
|
||||
? 'ready'
|
||||
: generated.primaryNative
|
||||
? 'native'
|
||||
: 'missing';
|
||||
const secondaryStatus = generated.secondaryPath
|
||||
? 'ready'
|
||||
: generated.secondaryNative
|
||||
? 'native'
|
||||
: 'missing';
|
||||
log(
|
||||
'info',
|
||||
args.logLevel,
|
||||
`YouTube subtitle result: primary=${primaryStatus}, secondary=${secondaryStatus}`,
|
||||
);
|
||||
deps.log('info', args.logLevel, 'YouTube subtitle flow: app-owned picker after mpv bootstrap');
|
||||
}
|
||||
|
||||
const shouldPauseUntilOverlayReady =
|
||||
@@ -191,47 +209,57 @@ export async function runPlaybackCommand(context: LauncherCommandContext): Promi
|
||||
pluginRuntimeConfig.autoStartPauseUntilReady;
|
||||
|
||||
if (shouldPauseUntilOverlayReady) {
|
||||
log('info', args.logLevel, 'Configured to pause mpv until overlay and tokenization are ready');
|
||||
deps.log('info', args.logLevel, 'Configured to pause mpv until overlay and tokenization are ready');
|
||||
}
|
||||
|
||||
await startMpv(
|
||||
await deps.startMpv(
|
||||
selectedTarget.target,
|
||||
selectedTarget.kind,
|
||||
args,
|
||||
mpvSocketPath,
|
||||
appPath,
|
||||
preloadedSubtitles,
|
||||
{ startPaused: shouldPauseUntilOverlayReady },
|
||||
undefined,
|
||||
{
|
||||
startPaused: shouldPauseUntilOverlayReady || isAppOwnedYoutubeFlow,
|
||||
disableYoutubeSubtitleAutoLoad: isAppOwnedYoutubeFlow,
|
||||
},
|
||||
);
|
||||
|
||||
const ready = await waitForUnixSocketReady(mpvSocketPath, 10000);
|
||||
const ready = await deps.waitForUnixSocketReady(mpvSocketPath, 10000);
|
||||
const pluginAutoStartEnabled = pluginRuntimeConfig.autoStart;
|
||||
const shouldStartOverlay = args.startOverlay || args.autoStartOverlay;
|
||||
const shouldStartOverlay = args.startOverlay || args.autoStartOverlay || isAppOwnedYoutubeFlow;
|
||||
if (shouldStartOverlay) {
|
||||
if (ready) {
|
||||
log('info', args.logLevel, 'MPV IPC socket ready, starting SubMiner overlay');
|
||||
deps.log('info', args.logLevel, 'MPV IPC socket ready, starting SubMiner overlay');
|
||||
} else {
|
||||
log(
|
||||
deps.log(
|
||||
'info',
|
||||
args.logLevel,
|
||||
'MPV IPC socket not ready after timeout, starting SubMiner overlay anyway',
|
||||
);
|
||||
}
|
||||
await startOverlay(appPath, args, mpvSocketPath);
|
||||
await deps.startOverlay(
|
||||
appPath,
|
||||
args,
|
||||
mpvSocketPath,
|
||||
isAppOwnedYoutubeFlow
|
||||
? ['--youtube-play', selectedTarget.target, '--youtube-mode', youtubeMode]
|
||||
: [],
|
||||
);
|
||||
} else if (pluginAutoStartEnabled) {
|
||||
if (ready) {
|
||||
log('info', args.logLevel, 'MPV IPC socket ready, relying on mpv plugin auto-start');
|
||||
deps.log('info', args.logLevel, 'MPV IPC socket ready, relying on mpv plugin auto-start');
|
||||
} else {
|
||||
log('info', args.logLevel, 'MPV IPC socket not ready yet, relying on mpv plugin auto-start');
|
||||
deps.log('info', args.logLevel, 'MPV IPC socket not ready yet, relying on mpv plugin auto-start');
|
||||
}
|
||||
} else if (ready) {
|
||||
log(
|
||||
deps.log(
|
||||
'info',
|
||||
args.logLevel,
|
||||
'MPV IPC socket ready, overlay auto-start disabled (use y-s to start)',
|
||||
);
|
||||
} else {
|
||||
log(
|
||||
deps.log(
|
||||
'info',
|
||||
args.logLevel,
|
||||
'MPV IPC socket not ready yet, overlay auto-start disabled (use y-s to start)',
|
||||
@@ -239,7 +267,7 @@ export async function runPlaybackCommand(context: LauncherCommandContext): Promi
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
const mpvProc = state.mpvProc;
|
||||
const mpvProc = deps.getMpvProc();
|
||||
if (!mpvProc) {
|
||||
stopOverlay(args);
|
||||
resolve();
|
||||
@@ -247,7 +275,7 @@ export async function runPlaybackCommand(context: LauncherCommandContext): Promi
|
||||
}
|
||||
|
||||
const finalize = (code: number | null | undefined) => {
|
||||
void cleanupPlaybackSession(args).finally(() => {
|
||||
void deps.cleanupPlaybackSession(args).finally(() => {
|
||||
processAdapter.setExitCode(code ?? 0);
|
||||
resolve();
|
||||
});
|
||||
|
||||
@@ -111,6 +111,7 @@ export function createDefaultArgs(launcherConfig: LauncherYoutubeSubgenConfig):
|
||||
youtubeSubgenAudioFormat: process.env.SUBMINER_YT_SUBGEN_AUDIO_FORMAT || 'm4a',
|
||||
youtubeSubgenKeepTemp: process.env.SUBMINER_YT_SUBGEN_KEEP_TEMP === '1',
|
||||
youtubeFixWithAi: launcherConfig.fixWithAi === true,
|
||||
youtubeMode: undefined,
|
||||
jimakuApiKey: process.env.SUBMINER_JIMAKU_API_KEY || '',
|
||||
jimakuApiKeyCommand: process.env.SUBMINER_JIMAKU_API_KEY_COMMAND || '',
|
||||
jimakuApiBaseUrl: process.env.SUBMINER_JIMAKU_API_BASE_URL || DEFAULT_JIMAKU_API_BASE_URL,
|
||||
@@ -250,6 +251,9 @@ export function applyInvocationsToArgs(parsed: Args, invocations: CliInvocations
|
||||
}
|
||||
|
||||
if (invocations.ytInvocation) {
|
||||
if (invocations.ytInvocation.mode) {
|
||||
parsed.youtubeMode = invocations.ytInvocation.mode;
|
||||
}
|
||||
if (invocations.ytInvocation.logLevel)
|
||||
parsed.logLevel = parseLogLevel(invocations.ytInvocation.logLevel);
|
||||
if (invocations.ytInvocation.outDir)
|
||||
|
||||
@@ -16,6 +16,7 @@ export interface JellyfinInvocation {
|
||||
|
||||
export interface YtInvocation {
|
||||
target?: string;
|
||||
mode?: 'download' | 'generate';
|
||||
outDir?: string;
|
||||
keepTemp?: boolean;
|
||||
whisperBin?: string;
|
||||
@@ -222,6 +223,7 @@ export function parseCliPrograms(
|
||||
.alias('youtube')
|
||||
.description('YouTube workflows')
|
||||
.argument('[target]', 'YouTube URL or ytsearch: query')
|
||||
.option('--mode <mode>', 'YouTube subtitle acquisition mode')
|
||||
.option('-o, --out-dir <dir>', 'Subtitle output dir')
|
||||
.option('--keep-temp', 'Keep temp files')
|
||||
.option('--whisper-bin <path>', 'whisper.cpp CLI path')
|
||||
@@ -233,6 +235,10 @@ export function parseCliPrograms(
|
||||
.action((target: string | undefined, options: Record<string, unknown>) => {
|
||||
ytInvocation = {
|
||||
target,
|
||||
mode:
|
||||
typeof options.mode === 'string' && (options.mode === 'download' || options.mode === 'generate')
|
||||
? options.mode
|
||||
: undefined,
|
||||
outDir: typeof options.outDir === 'string' ? options.outDir : undefined,
|
||||
keepTemp: options.keepTemp === true,
|
||||
whisperBin: typeof options.whisperBin === 'string' ? options.whisperBin : undefined,
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import path from 'node:path';
|
||||
import { getDefaultMpvLogFile } from './types.js';
|
||||
import { getDefaultLauncherLogFile, getDefaultMpvLogFile } from './types.js';
|
||||
|
||||
test('getDefaultMpvLogFile uses APPDATA on windows', () => {
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const resolved = getDefaultMpvLogFile({
|
||||
platform: 'win32',
|
||||
homeDir: 'C:\\Users\\tester',
|
||||
@@ -17,8 +18,27 @@ test('getDefaultMpvLogFile uses APPDATA on windows', () => {
|
||||
'C:\\Users\\tester\\AppData\\Roaming',
|
||||
'SubMiner',
|
||||
'logs',
|
||||
`SubMiner-${new Date().toISOString().slice(0, 10)}.log`,
|
||||
`mpv-${today}.log`,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('getDefaultLauncherLogFile uses launcher prefix', () => {
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const resolved = getDefaultLauncherLogFile({
|
||||
platform: 'linux',
|
||||
homeDir: '/home/tester',
|
||||
});
|
||||
|
||||
assert.equal(
|
||||
resolved,
|
||||
path.join(
|
||||
'/home/tester',
|
||||
'.config',
|
||||
'SubMiner',
|
||||
'logs',
|
||||
`launcher-${today}.log`,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { LogLevel } from './types.js';
|
||||
import { DEFAULT_MPV_LOG_FILE } from './types.js';
|
||||
import { DEFAULT_MPV_LOG_FILE, getDefaultLauncherLogFile } from './types.js';
|
||||
import { appendLogLine, resolveDefaultLogFilePath } from '../src/shared/log-files.js';
|
||||
|
||||
export const COLORS = {
|
||||
red: '\x1b[0;31m',
|
||||
@@ -28,14 +27,32 @@ export function getMpvLogPath(): string {
|
||||
return DEFAULT_MPV_LOG_FILE;
|
||||
}
|
||||
|
||||
export function getLauncherLogPath(): string {
|
||||
const envPath = process.env.SUBMINER_LAUNCHER_LOG?.trim();
|
||||
if (envPath) return envPath;
|
||||
return getDefaultLauncherLogFile();
|
||||
}
|
||||
|
||||
export function getAppLogPath(): string {
|
||||
const envPath = process.env.SUBMINER_APP_LOG?.trim();
|
||||
if (envPath) return envPath;
|
||||
return resolveDefaultLogFilePath('app');
|
||||
}
|
||||
|
||||
function appendTimestampedLog(logPath: string, message: string): void {
|
||||
appendLogLine(logPath, `[${new Date().toISOString()}] ${message}`);
|
||||
}
|
||||
|
||||
export function appendToMpvLog(message: string): void {
|
||||
const logPath = getMpvLogPath();
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(logPath), { recursive: true });
|
||||
fs.appendFileSync(logPath, `[${new Date().toISOString()}] ${message}\n`, { encoding: 'utf8' });
|
||||
} catch {
|
||||
// ignore logging failures
|
||||
}
|
||||
appendTimestampedLog(getMpvLogPath(), message);
|
||||
}
|
||||
|
||||
export function appendToLauncherLog(message: string): void {
|
||||
appendTimestampedLog(getLauncherLogPath(), message);
|
||||
}
|
||||
|
||||
export function appendToAppLog(message: string): void {
|
||||
appendTimestampedLog(getAppLogPath(), message);
|
||||
}
|
||||
|
||||
export function log(level: LogLevel, configured: LogLevel, message: string): void {
|
||||
@@ -49,11 +66,11 @@ export function log(level: LogLevel, configured: LogLevel, message: string): voi
|
||||
? COLORS.red
|
||||
: COLORS.cyan;
|
||||
process.stdout.write(`${color}[${level.toUpperCase()}]${COLORS.reset} ${message}\n`);
|
||||
appendToMpvLog(`[${level.toUpperCase()}] ${message}`);
|
||||
appendToLauncherLog(`[${level.toUpperCase()}] ${message}`);
|
||||
}
|
||||
|
||||
export function fail(message: string): never {
|
||||
process.stderr.write(`${COLORS.red}[ERROR]${COLORS.reset} ${message}\n`);
|
||||
appendToMpvLog(`[ERROR] ${message}`);
|
||||
appendToLauncherLog(`[ERROR] ${message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
@@ -205,136 +205,6 @@ test('doctor refresh-known-words forwards app refresh command without requiring
|
||||
});
|
||||
});
|
||||
|
||||
test('youtube command rejects removed --mode option', () => {
|
||||
withTempDir((root) => {
|
||||
const homeDir = path.join(root, 'home');
|
||||
const xdgConfigHome = path.join(root, 'xdg');
|
||||
const appPath = path.join(root, 'fake-subminer.sh');
|
||||
fs.writeFileSync(appPath, '#!/bin/sh\nexit 0\n');
|
||||
fs.chmodSync(appPath, 0o755);
|
||||
|
||||
const env = {
|
||||
...makeTestEnv(homeDir, xdgConfigHome),
|
||||
SUBMINER_APPIMAGE_PATH: appPath,
|
||||
};
|
||||
const result = runLauncher(
|
||||
['youtube', 'https://www.youtube.com/watch?v=test123', '--mode', 'automatic'],
|
||||
env,
|
||||
);
|
||||
|
||||
assert.equal(result.status, 1);
|
||||
assert.match(result.stderr, /unknown option '--mode'/i);
|
||||
});
|
||||
});
|
||||
|
||||
test('youtube playback generates subtitles before mpv launch', { timeout: 15000 }, () => {
|
||||
withTempDir((root) => {
|
||||
const homeDir = path.join(root, 'home');
|
||||
const xdgConfigHome = path.join(root, 'xdg');
|
||||
const binDir = path.join(root, 'bin');
|
||||
const appPath = path.join(root, 'fake-subminer.sh');
|
||||
const ytdlpLogPath = path.join(root, 'yt-dlp.log');
|
||||
const mpvCapturePath = path.join(root, 'mpv-order.txt');
|
||||
const mpvArgsPath = path.join(root, 'mpv-args.txt');
|
||||
const socketPath = path.join(root, 'mpv.sock');
|
||||
const bunBinary = JSON.stringify(process.execPath.replace(/\\/g, '/'));
|
||||
|
||||
fs.mkdirSync(binDir, { recursive: true });
|
||||
fs.mkdirSync(path.join(xdgConfigHome, 'SubMiner'), { recursive: true });
|
||||
fs.mkdirSync(path.join(xdgConfigHome, 'mpv', 'script-opts'), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(xdgConfigHome, 'SubMiner', 'setup-state.json'),
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
status: 'completed',
|
||||
completedAt: '2026-03-08T00:00:00.000Z',
|
||||
completionSource: 'user',
|
||||
lastSeenYomitanDictionaryCount: 0,
|
||||
pluginInstallStatus: 'installed',
|
||||
pluginInstallPathSummary: null,
|
||||
}),
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(xdgConfigHome, 'mpv', 'script-opts', 'subminer.conf'),
|
||||
`socket_path=${socketPath}\nauto_start=no\nauto_start_visible_overlay=no\nauto_start_pause_until_ready=no\n`,
|
||||
);
|
||||
fs.writeFileSync(appPath, '#!/bin/sh\nexit 0\n');
|
||||
fs.chmodSync(appPath, 0o755);
|
||||
|
||||
fs.writeFileSync(
|
||||
path.join(binDir, 'yt-dlp'),
|
||||
`#!/bin/sh
|
||||
set -eu
|
||||
printf '%s\\n' "$*" >> "$SUBMINER_TEST_YTDLP_LOG"
|
||||
if printf '%s\\n' "$*" | grep -q -- '--dump-single-json'; then
|
||||
printf '{"id":"video123"}\\n'
|
||||
exit 0
|
||||
fi
|
||||
out_dir=""
|
||||
prev=""
|
||||
for arg in "$@"; do
|
||||
if [ "$prev" = "-o" ]; then
|
||||
out_dir=$(dirname "$arg")
|
||||
break
|
||||
fi
|
||||
prev="$arg"
|
||||
done
|
||||
mkdir -p "$out_dir"
|
||||
printf '1\\n00:00:00,000 --> 00:00:01,000\\nこんにちは\\n' > "$out_dir/video123.ja.srt"
|
||||
printf '1\\n00:00:00,000 --> 00:00:01,000\\nhello\\n' > "$out_dir/video123.en.srt"
|
||||
`,
|
||||
'utf8',
|
||||
);
|
||||
fs.chmodSync(path.join(binDir, 'yt-dlp'), 0o755);
|
||||
|
||||
fs.writeFileSync(path.join(binDir, 'ffmpeg'), '#!/bin/sh\nexit 0\n', 'utf8');
|
||||
fs.chmodSync(path.join(binDir, 'ffmpeg'), 0o755);
|
||||
|
||||
fs.writeFileSync(
|
||||
path.join(binDir, 'mpv'),
|
||||
`#!/bin/sh
|
||||
set -eu
|
||||
if [ -s "$SUBMINER_TEST_YTDLP_LOG" ]; then
|
||||
printf 'generated-before-mpv\\n' > "$SUBMINER_TEST_MPV_ORDER"
|
||||
else
|
||||
printf 'mpv-before-generation\\n' > "$SUBMINER_TEST_MPV_ORDER"
|
||||
fi
|
||||
printf '%s\\n' "$@" > "$SUBMINER_TEST_MPV_ARGS"
|
||||
socket_path=""
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--input-ipc-server=*)
|
||||
socket_path="\${arg#--input-ipc-server=}"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
${bunBinary} -e "const net=require('node:net'); const fs=require('node:fs'); const path=require('node:path'); const socket=process.argv[1]||''; try{ if(socket) fs.mkdirSync(path.dirname(socket),{recursive:true}); }catch{} try{ if(socket) fs.rmSync(socket,{force:true}); }catch{} const server=net.createServer((c)=>c.end()); server.on('error',()=>process.exit(0)); if(!socket) process.exit(0); try{ server.listen(socket,()=>setTimeout(()=>server.close(()=>process.exit(0)),250)); } catch { process.exit(0); }" "$socket_path"
|
||||
`,
|
||||
'utf8',
|
||||
);
|
||||
fs.chmodSync(path.join(binDir, 'mpv'), 0o755);
|
||||
|
||||
const env = {
|
||||
...makeTestEnv(homeDir, xdgConfigHome),
|
||||
PATH: `${binDir}${path.delimiter}${process.env.Path || process.env.PATH || ''}`,
|
||||
Path: `${binDir}${path.delimiter}${process.env.Path || process.env.PATH || ''}`,
|
||||
SUBMINER_APPIMAGE_PATH: appPath,
|
||||
SUBMINER_TEST_YTDLP_LOG: ytdlpLogPath,
|
||||
SUBMINER_TEST_MPV_ORDER: mpvCapturePath,
|
||||
SUBMINER_TEST_MPV_ARGS: mpvArgsPath,
|
||||
};
|
||||
const result = runLauncher(['youtube', 'https://www.youtube.com/watch?v=test123'], env);
|
||||
|
||||
assert.equal(result.status, 0, `stdout:\n${result.stdout}\nstderr:\n${result.stderr}`);
|
||||
assert.equal(fs.readFileSync(mpvCapturePath, 'utf8').trim(), 'generated-before-mpv');
|
||||
assert.match(
|
||||
fs.readFileSync(mpvArgsPath, 'utf8'),
|
||||
/https:\/\/www\.youtube\.com\/watch\?v=test123/,
|
||||
);
|
||||
assert.match(fs.readFileSync(ytdlpLogPath, 'utf8'), /--dump-single-json/);
|
||||
});
|
||||
});
|
||||
|
||||
test('launcher forwards --args to mpv as parsed tokens', { timeout: 15000 }, () => {
|
||||
withTempDir((root) => {
|
||||
const homeDir = path.join(root, 'home');
|
||||
@@ -387,6 +257,10 @@ ${bunBinary} -e "const net=require('node:net'); const fs=require('node:fs'); con
|
||||
'utf8',
|
||||
);
|
||||
fs.chmodSync(path.join(binDir, 'mpv'), 0o755);
|
||||
fs.writeFileSync(path.join(binDir, 'yt-dlp'), '#!/bin/sh\nexit 0\n', 'utf8');
|
||||
fs.writeFileSync(path.join(binDir, 'ffmpeg'), '#!/bin/sh\nexit 0\n', 'utf8');
|
||||
fs.chmodSync(path.join(binDir, 'yt-dlp'), 0o755);
|
||||
fs.chmodSync(path.join(binDir, 'ffmpeg'), 0o755);
|
||||
|
||||
const env = {
|
||||
...makeTestEnv(homeDir, xdgConfigHome),
|
||||
@@ -466,6 +340,10 @@ ${bunBinary} -e "const net=require('node:net'); const fs=require('node:fs'); con
|
||||
'utf8',
|
||||
);
|
||||
fs.chmodSync(path.join(binDir, 'mpv'), 0o755);
|
||||
fs.writeFileSync(path.join(binDir, 'yt-dlp'), '#!/bin/sh\nexit 0\n', 'utf8');
|
||||
fs.writeFileSync(path.join(binDir, 'ffmpeg'), '#!/bin/sh\nexit 0\n', 'utf8');
|
||||
fs.chmodSync(path.join(binDir, 'yt-dlp'), 0o755);
|
||||
fs.chmodSync(path.join(binDir, 'ffmpeg'), 0o755);
|
||||
|
||||
const env = {
|
||||
...makeTestEnv(homeDir, xdgConfigHome),
|
||||
@@ -484,6 +362,84 @@ ${bunBinary} -e "const net=require('node:net'); const fs=require('node:fs'); con
|
||||
});
|
||||
});
|
||||
|
||||
test('launcher disables plugin startup pause gate for app-owned youtube flow', { timeout: 15000 }, () => {
|
||||
withTempDir((root) => {
|
||||
const homeDir = path.join(root, 'home');
|
||||
const xdgConfigHome = path.join(root, 'xdg');
|
||||
const binDir = path.join(root, 'bin');
|
||||
const appPath = path.join(root, 'fake-subminer.sh');
|
||||
const mpvArgsPath = path.join(root, 'mpv-args.txt');
|
||||
const socketPath = path.join(root, 'mpv.sock');
|
||||
const bunBinary = JSON.stringify(process.execPath.replace(/\\/g, '/'));
|
||||
|
||||
fs.mkdirSync(binDir, { recursive: true });
|
||||
fs.mkdirSync(path.join(xdgConfigHome, 'SubMiner'), { recursive: true });
|
||||
fs.mkdirSync(path.join(xdgConfigHome, 'mpv', 'script-opts'), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(xdgConfigHome, 'SubMiner', 'setup-state.json'),
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
status: 'completed',
|
||||
completedAt: '2026-03-08T00:00:00.000Z',
|
||||
completionSource: 'user',
|
||||
lastSeenYomitanDictionaryCount: 0,
|
||||
pluginInstallStatus: 'installed',
|
||||
pluginInstallPathSummary: null,
|
||||
}),
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(xdgConfigHome, 'mpv', 'script-opts', 'subminer.conf'),
|
||||
`socket_path=${socketPath}\nauto_start=yes\nauto_start_visible_overlay=yes\nauto_start_pause_until_ready=yes\n`,
|
||||
);
|
||||
fs.writeFileSync(
|
||||
appPath,
|
||||
'#!/bin/sh\nif [ -n "$SUBMINER_TEST_CAPTURE" ]; then printf "%s\\n" "$@" > "$SUBMINER_TEST_CAPTURE"; fi\nexit 0\n',
|
||||
);
|
||||
fs.chmodSync(appPath, 0o755);
|
||||
|
||||
fs.writeFileSync(
|
||||
path.join(binDir, 'mpv'),
|
||||
`#!/bin/sh
|
||||
set -eu
|
||||
printf '%s\\n' "$@" > "$SUBMINER_TEST_MPV_ARGS"
|
||||
socket_path=""
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--input-ipc-server=*)
|
||||
socket_path="\${arg#--input-ipc-server=}"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
${bunBinary} -e "const net=require('node:net'); const fs=require('node:fs'); const path=require('node:path'); const socket=process.argv[1]||''; try{ if (socket) fs.mkdirSync(path.dirname(socket),{recursive:true}); }catch{} try{ if (socket) fs.rmSync(socket,{force:true}); }catch{} if(!socket) process.exit(0); const server=net.createServer((c)=>c.end()); server.on('error',()=>process.exit(0)); try{ server.listen(socket,()=>setTimeout(()=>server.close(()=>process.exit(0)),250)); } catch { process.exit(0); }" "$socket_path"
|
||||
`,
|
||||
'utf8',
|
||||
);
|
||||
fs.chmodSync(path.join(binDir, 'mpv'), 0o755);
|
||||
fs.writeFileSync(path.join(binDir, 'yt-dlp'), '#!/bin/sh\nexit 0\n', 'utf8');
|
||||
fs.writeFileSync(path.join(binDir, 'ffmpeg'), '#!/bin/sh\nexit 0\n', 'utf8');
|
||||
fs.chmodSync(path.join(binDir, 'yt-dlp'), 0o755);
|
||||
fs.chmodSync(path.join(binDir, 'ffmpeg'), 0o755);
|
||||
|
||||
const env = {
|
||||
...makeTestEnv(homeDir, xdgConfigHome),
|
||||
PATH: `${binDir}${path.delimiter}${process.env.Path || process.env.PATH || ''}`,
|
||||
Path: `${binDir}${path.delimiter}${process.env.Path || process.env.PATH || ''}`,
|
||||
DISPLAY: ':99',
|
||||
XDG_SESSION_TYPE: 'x11',
|
||||
SUBMINER_APPIMAGE_PATH: appPath,
|
||||
SUBMINER_TEST_MPV_ARGS: mpvArgsPath,
|
||||
SUBMINER_TEST_CAPTURE: path.join(root, 'captured-args.txt'),
|
||||
};
|
||||
const result = runLauncher(['yt', 'https://www.youtube.com/watch?v=abc123'], env);
|
||||
|
||||
assert.equal(result.status, 0, `stdout:\n${result.stdout}\nstderr:\n${result.stderr}`);
|
||||
assert.match(
|
||||
fs.readFileSync(mpvArgsPath, 'utf8'),
|
||||
/--script-opts=.*subminer-auto_start_pause_until_ready=no/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('dictionary command forwards --dictionary and --dictionary-target to app command path', () => {
|
||||
withTempDir((root) => {
|
||||
const homeDir = path.join(root, 'home');
|
||||
|
||||
@@ -302,7 +302,47 @@ test('startOverlay resolves without fixed 2s sleep when readiness signals arrive
|
||||
}
|
||||
});
|
||||
|
||||
test('cleanupPlaybackSession preserves background app while stopping mpv-owned children', async () => {
|
||||
test('startOverlay captures app stdout and stderr into app log', async () => {
|
||||
const { dir, socketPath } = createTempSocketPath();
|
||||
const appPath = path.join(dir, 'fake-subminer.sh');
|
||||
const appLogPath = path.join(dir, 'app.log');
|
||||
const originalAppLog = process.env.SUBMINER_APP_LOG;
|
||||
fs.writeFileSync(
|
||||
appPath,
|
||||
'#!/bin/sh\nprintf "hello from stdout\\n"\nprintf "hello from stderr\\n" >&2\nexit 0\n',
|
||||
);
|
||||
fs.chmodSync(appPath, 0o755);
|
||||
fs.writeFileSync(socketPath, '');
|
||||
const originalCreateConnection = net.createConnection;
|
||||
try {
|
||||
process.env.SUBMINER_APP_LOG = appLogPath;
|
||||
net.createConnection = (() => {
|
||||
const socket = new EventEmitter() as net.Socket;
|
||||
socket.destroy = (() => socket) as net.Socket['destroy'];
|
||||
socket.setTimeout = (() => socket) as net.Socket['setTimeout'];
|
||||
setTimeout(() => socket.emit('connect'), 10);
|
||||
return socket;
|
||||
}) as typeof net.createConnection;
|
||||
|
||||
await startOverlay(appPath, makeArgs(), socketPath);
|
||||
|
||||
const logText = fs.readFileSync(appLogPath, 'utf8');
|
||||
assert.match(logText, /\[STDOUT\] hello from stdout/);
|
||||
assert.match(logText, /\[STDERR\] hello from stderr/);
|
||||
} finally {
|
||||
net.createConnection = originalCreateConnection;
|
||||
state.overlayProc = null;
|
||||
state.overlayManagedByLauncher = false;
|
||||
if (originalAppLog === undefined) {
|
||||
delete process.env.SUBMINER_APP_LOG;
|
||||
} else {
|
||||
process.env.SUBMINER_APP_LOG = originalAppLog;
|
||||
}
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('cleanupPlaybackSession stops launcher-managed overlay app and mpv-owned children', async () => {
|
||||
const { dir } = createTempSocketPath();
|
||||
const appPath = path.join(dir, 'fake-subminer.sh');
|
||||
const appInvocationsPath = path.join(dir, 'app-invocations.log');
|
||||
@@ -345,8 +385,8 @@ test('cleanupPlaybackSession preserves background app while stopping mpv-owned c
|
||||
try {
|
||||
await cleanupPlaybackSession(makeArgs());
|
||||
|
||||
assert.deepEqual(calls, ['mpv-kill', 'helper-kill']);
|
||||
assert.equal(fs.existsSync(appInvocationsPath), false);
|
||||
assert.deepEqual(calls, ['overlay-kill', 'mpv-kill', 'helper-kill']);
|
||||
assert.match(fs.readFileSync(appInvocationsPath, 'utf8'), /--stop/);
|
||||
} finally {
|
||||
state.overlayProc = null;
|
||||
state.mpvProc = null;
|
||||
|
||||
243
launcher/mpv.ts
243
launcher/mpv.ts
@@ -5,7 +5,7 @@ import net from 'node:net';
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import type { LogLevel, Backend, Args, MpvTrack } from './types.js';
|
||||
import { DEFAULT_MPV_SUBMINER_ARGS, DEFAULT_YOUTUBE_YTDL_FORMAT } from './types.js';
|
||||
import { log, fail, getMpvLogPath } from './log.js';
|
||||
import { appendToAppLog, getAppLogPath, log, fail, getMpvLogPath } from './log.js';
|
||||
import { buildSubminerScriptOpts, resolveAniSkipMetadataForFile } from './aniskip-metadata.js';
|
||||
import {
|
||||
commandExists,
|
||||
@@ -542,7 +542,7 @@ export async function startMpv(
|
||||
socketPath: string,
|
||||
appPath: string,
|
||||
preloadedSubtitles?: { primaryPath?: string; secondaryPath?: string },
|
||||
options?: { startPaused?: boolean },
|
||||
options?: { startPaused?: boolean; disableYoutubeSubtitleAutoLoad?: boolean },
|
||||
): Promise<void> {
|
||||
if (targetKind === 'file' && (!fs.existsSync(target) || !fs.statSync(target).isFile())) {
|
||||
fail(`Video file not found: ${target}`);
|
||||
@@ -557,13 +557,9 @@ export async function startMpv(
|
||||
const mpvArgs: string[] = [];
|
||||
if (args.profile) mpvArgs.push(`--profile=${args.profile}`);
|
||||
mpvArgs.push(...DEFAULT_MPV_SUBMINER_ARGS);
|
||||
if (args.mpvArgs) {
|
||||
mpvArgs.push(...parseMpvArgString(args.mpvArgs));
|
||||
}
|
||||
|
||||
if (targetKind === 'url' && isYoutubeTarget(target)) {
|
||||
log('info', args.logLevel, 'Applying URL playback options');
|
||||
mpvArgs.push('--ytdl=yes', '--ytdl-raw-options=');
|
||||
mpvArgs.push('--ytdl=yes');
|
||||
|
||||
if (isYoutubeTarget(target)) {
|
||||
const subtitleLangs = uniqueNormalizedLangCodes([
|
||||
@@ -575,15 +571,22 @@ export async function startMpv(
|
||||
log('debug', args.logLevel, `YouTube subtitle langs: ${subtitleLangs}`);
|
||||
log('debug', args.logLevel, `YouTube audio langs: ${audioLangs}`);
|
||||
mpvArgs.push(`--ytdl-format=${DEFAULT_YOUTUBE_YTDL_FORMAT}`, `--alang=${audioLangs}`);
|
||||
mpvArgs.push(
|
||||
'--sub-auto=fuzzy',
|
||||
`--slang=${subtitleLangs}`,
|
||||
'--ytdl-raw-options-append=write-subs=',
|
||||
'--ytdl-raw-options-append=sub-format=vtt/best',
|
||||
`--ytdl-raw-options-append=sub-langs=${subtitleLangs}`,
|
||||
);
|
||||
if (options?.disableYoutubeSubtitleAutoLoad !== true) {
|
||||
mpvArgs.push(
|
||||
'--sub-auto=fuzzy',
|
||||
`--slang=${subtitleLangs}`,
|
||||
'--ytdl-raw-options-append=write-subs=',
|
||||
'--ytdl-raw-options-append=sub-format=vtt/best',
|
||||
`--ytdl-raw-options-append=sub-langs=${subtitleLangs}`,
|
||||
);
|
||||
} else {
|
||||
mpvArgs.push('--sub-auto=no');
|
||||
}
|
||||
}
|
||||
}
|
||||
if (args.mpvArgs) {
|
||||
mpvArgs.push(...parseMpvArgString(args.mpvArgs));
|
||||
}
|
||||
|
||||
if (preloadedSubtitles?.primaryPath) {
|
||||
mpvArgs.push(`--sub-file=${preloadedSubtitles.primaryPath}`);
|
||||
@@ -597,7 +600,17 @@ export async function startMpv(
|
||||
const aniSkipMetadata = shouldResolveAniSkipMetadata(target, targetKind, preloadedSubtitles)
|
||||
? await resolveAniSkipMetadataForFile(target)
|
||||
: null;
|
||||
const scriptOpts = buildSubminerScriptOpts(appPath, socketPath, aniSkipMetadata, args.logLevel);
|
||||
const extraScriptOpts =
|
||||
targetKind === 'url' && isYoutubeTarget(target) && options?.disableYoutubeSubtitleAutoLoad === true
|
||||
? ['subminer-auto_start_pause_until_ready=no']
|
||||
: [];
|
||||
const scriptOpts = buildSubminerScriptOpts(
|
||||
appPath,
|
||||
socketPath,
|
||||
aniSkipMetadata,
|
||||
args.logLevel,
|
||||
extraScriptOpts,
|
||||
);
|
||||
if (aniSkipMetadata) {
|
||||
log(
|
||||
'debug',
|
||||
@@ -661,19 +674,25 @@ async function waitForOverlayStartCommandSettled(
|
||||
});
|
||||
}
|
||||
|
||||
export async function startOverlay(appPath: string, args: Args, socketPath: string): Promise<void> {
|
||||
export async function startOverlay(
|
||||
appPath: string,
|
||||
args: Args,
|
||||
socketPath: string,
|
||||
extraAppArgs: string[] = [],
|
||||
): Promise<void> {
|
||||
const backend = detectBackend(args.backend);
|
||||
log('info', args.logLevel, `Starting SubMiner overlay (backend: ${backend})...`);
|
||||
|
||||
const overlayArgs = ['--start', '--backend', backend, '--socket', socketPath];
|
||||
const overlayArgs = ['--start', '--backend', backend, '--socket', socketPath, ...extraAppArgs];
|
||||
if (args.logLevel !== 'info') overlayArgs.push('--log-level', args.logLevel);
|
||||
if (args.useTexthooker) overlayArgs.push('--texthooker');
|
||||
|
||||
const target = resolveAppSpawnTarget(appPath, overlayArgs);
|
||||
state.overlayProc = spawn(target.command, target.args, {
|
||||
stdio: 'inherit',
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: buildAppEnv(),
|
||||
});
|
||||
attachAppProcessLogging(state.overlayProc);
|
||||
state.overlayManagedByLauncher = true;
|
||||
|
||||
const [socketReady] = await Promise.all([
|
||||
@@ -699,10 +718,7 @@ export function launchTexthookerOnly(appPath: string, args: Args): never {
|
||||
if (args.logLevel !== 'info') overlayArgs.push('--log-level', args.logLevel);
|
||||
|
||||
log('info', args.logLevel, 'Launching texthooker mode...');
|
||||
const result = spawnSync(appPath, overlayArgs, {
|
||||
stdio: 'inherit',
|
||||
env: buildAppEnv(),
|
||||
});
|
||||
const result = runSyncAppCommand(appPath, overlayArgs, true);
|
||||
if (result.error) {
|
||||
fail(`Failed to launch texthooker mode: ${result.error.message}`);
|
||||
}
|
||||
@@ -713,30 +729,7 @@ export function stopOverlay(args: Args): void {
|
||||
if (state.stopRequested) return;
|
||||
state.stopRequested = true;
|
||||
|
||||
if (state.overlayManagedByLauncher && state.appPath) {
|
||||
log('info', args.logLevel, 'Stopping SubMiner overlay...');
|
||||
|
||||
const stopArgs = ['--stop'];
|
||||
if (args.logLevel !== 'info') stopArgs.push('--log-level', args.logLevel);
|
||||
|
||||
const result = spawnSync(state.appPath, stopArgs, {
|
||||
stdio: 'ignore',
|
||||
env: buildAppEnv(),
|
||||
});
|
||||
if (result.error) {
|
||||
log('warn', args.logLevel, `Failed to stop SubMiner overlay: ${result.error.message}`);
|
||||
} else if (typeof result.status === 'number' && result.status !== 0) {
|
||||
log('warn', args.logLevel, `SubMiner overlay stop command exited with status ${result.status}`);
|
||||
}
|
||||
|
||||
if (state.overlayProc && !state.overlayProc.killed) {
|
||||
try {
|
||||
state.overlayProc.kill('SIGTERM');
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
stopManagedOverlayApp(args);
|
||||
|
||||
if (state.mpvProc && !state.mpvProc.killed) {
|
||||
try {
|
||||
@@ -761,6 +754,8 @@ export function stopOverlay(args: Args): void {
|
||||
}
|
||||
|
||||
export async function cleanupPlaybackSession(args: Args): Promise<void> {
|
||||
stopManagedOverlayApp(args);
|
||||
|
||||
if (state.mpvProc && !state.mpvProc.killed) {
|
||||
try {
|
||||
state.mpvProc.kill('SIGTERM');
|
||||
@@ -783,9 +778,40 @@ export async function cleanupPlaybackSession(args: Args): Promise<void> {
|
||||
await terminateTrackedDetachedMpv(args.logLevel);
|
||||
}
|
||||
|
||||
function stopManagedOverlayApp(args: Args): void {
|
||||
if (!(state.overlayManagedByLauncher && state.appPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
log('info', args.logLevel, 'Stopping SubMiner overlay...');
|
||||
|
||||
const stopArgs = ['--stop'];
|
||||
if (args.logLevel !== 'info') stopArgs.push('--log-level', args.logLevel);
|
||||
|
||||
const target = resolveAppSpawnTarget(state.appPath, stopArgs);
|
||||
const result = spawnSync(target.command, target.args, {
|
||||
stdio: 'ignore',
|
||||
env: buildAppEnv(),
|
||||
});
|
||||
if (result.error) {
|
||||
log('warn', args.logLevel, `Failed to stop SubMiner overlay: ${result.error.message}`);
|
||||
} else if (typeof result.status === 'number' && result.status !== 0) {
|
||||
log('warn', args.logLevel, `SubMiner overlay stop command exited with status ${result.status}`);
|
||||
}
|
||||
|
||||
if (state.overlayProc && !state.overlayProc.killed) {
|
||||
try {
|
||||
state.overlayProc.kill('SIGTERM');
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function buildAppEnv(): NodeJS.ProcessEnv {
|
||||
const env: Record<string, string | undefined> = {
|
||||
...process.env,
|
||||
SUBMINER_APP_LOG: getAppLogPath(),
|
||||
SUBMINER_MPV_LOG: getMpvLogPath(),
|
||||
};
|
||||
delete env.ELECTRON_RUN_AS_NODE;
|
||||
@@ -804,6 +830,64 @@ function buildAppEnv(): NodeJS.ProcessEnv {
|
||||
return env;
|
||||
}
|
||||
|
||||
function appendCapturedAppOutput(kind: 'STDOUT' | 'STDERR', chunk: string): void {
|
||||
const normalized = chunk.replace(/\r\n/g, '\n');
|
||||
for (const line of normalized.split('\n')) {
|
||||
if (!line) continue;
|
||||
appendToAppLog(`[${kind}] ${line}`);
|
||||
}
|
||||
}
|
||||
|
||||
function attachAppProcessLogging(
|
||||
proc: ReturnType<typeof spawn>,
|
||||
options?: {
|
||||
mirrorStdout?: boolean;
|
||||
mirrorStderr?: boolean;
|
||||
},
|
||||
): void {
|
||||
proc.stdout?.setEncoding('utf8');
|
||||
proc.stderr?.setEncoding('utf8');
|
||||
proc.stdout?.on('data', (chunk: string) => {
|
||||
appendCapturedAppOutput('STDOUT', chunk);
|
||||
if (options?.mirrorStdout) process.stdout.write(chunk);
|
||||
});
|
||||
proc.stderr?.on('data', (chunk: string) => {
|
||||
appendCapturedAppOutput('STDERR', chunk);
|
||||
if (options?.mirrorStderr) process.stderr.write(chunk);
|
||||
});
|
||||
}
|
||||
|
||||
function runSyncAppCommand(
|
||||
appPath: string,
|
||||
appArgs: string[],
|
||||
mirrorOutput: boolean,
|
||||
): {
|
||||
status: number;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
error?: Error;
|
||||
} {
|
||||
const target = resolveAppSpawnTarget(appPath, appArgs);
|
||||
const result = spawnSync(target.command, target.args, {
|
||||
env: buildAppEnv(),
|
||||
encoding: 'utf8',
|
||||
});
|
||||
if (result.stdout) {
|
||||
appendCapturedAppOutput('STDOUT', result.stdout);
|
||||
if (mirrorOutput) process.stdout.write(result.stdout);
|
||||
}
|
||||
if (result.stderr) {
|
||||
appendCapturedAppOutput('STDERR', result.stderr);
|
||||
if (mirrorOutput) process.stderr.write(result.stderr);
|
||||
}
|
||||
return {
|
||||
status: result.status ?? 1,
|
||||
stdout: result.stdout ?? '',
|
||||
stderr: result.stderr ?? '',
|
||||
error: result.error ?? undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function maybeCaptureAppArgs(appArgs: string[]): boolean {
|
||||
const capturePath = process.env.SUBMINER_TEST_CAPTURE?.trim();
|
||||
if (!capturePath) {
|
||||
@@ -821,20 +905,23 @@ function resolveAppSpawnTarget(appPath: string, appArgs: string[]): SpawnTarget
|
||||
return resolveCommandInvocation(appPath, appArgs);
|
||||
}
|
||||
|
||||
export function runAppCommandWithInherit(appPath: string, appArgs: string[]): never {
|
||||
export function runAppCommandWithInherit(appPath: string, appArgs: string[]): void {
|
||||
if (maybeCaptureAppArgs(appArgs)) {
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const target = resolveAppSpawnTarget(appPath, appArgs);
|
||||
const result = spawnSync(target.command, target.args, {
|
||||
stdio: 'inherit',
|
||||
const proc = spawn(target.command, target.args, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: buildAppEnv(),
|
||||
});
|
||||
if (result.error) {
|
||||
fail(`Failed to run app command: ${result.error.message}`);
|
||||
}
|
||||
process.exit(result.status ?? 0);
|
||||
attachAppProcessLogging(proc, { mirrorStdout: true, mirrorStderr: true });
|
||||
proc.once('error', (error) => {
|
||||
fail(`Failed to run app command: ${error.message}`);
|
||||
});
|
||||
proc.once('close', (code) => {
|
||||
process.exit(code ?? 0);
|
||||
});
|
||||
}
|
||||
|
||||
export function runAppCommandCaptureOutput(
|
||||
@@ -854,18 +941,7 @@ export function runAppCommandCaptureOutput(
|
||||
};
|
||||
}
|
||||
|
||||
const target = resolveAppSpawnTarget(appPath, appArgs);
|
||||
const result = spawnSync(target.command, target.args, {
|
||||
env: buildAppEnv(),
|
||||
encoding: 'utf8',
|
||||
});
|
||||
|
||||
return {
|
||||
status: result.status ?? 1,
|
||||
stdout: result.stdout ?? '',
|
||||
stderr: result.stderr ?? '',
|
||||
error: result.error ?? undefined,
|
||||
};
|
||||
return runSyncAppCommand(appPath, appArgs, false);
|
||||
}
|
||||
|
||||
export function runAppCommandAttached(
|
||||
@@ -887,13 +963,14 @@ export function runAppCommandAttached(
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const proc = spawn(target.command, target.args, {
|
||||
stdio: 'inherit',
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: buildAppEnv(),
|
||||
});
|
||||
attachAppProcessLogging(proc, { mirrorStdout: true, mirrorStderr: true });
|
||||
proc.once('error', (error) => {
|
||||
reject(error);
|
||||
});
|
||||
proc.once('exit', (code, signal) => {
|
||||
proc.once('close', (code, signal) => {
|
||||
if (code !== null) {
|
||||
resolve(code);
|
||||
} else if (signal) {
|
||||
@@ -921,10 +998,7 @@ export function runAppCommandWithInheritLogged(
|
||||
logLevel,
|
||||
`${label}: launching app with args: ${[target.command, ...target.args].join(' ')}`,
|
||||
);
|
||||
const result = spawnSync(target.command, target.args, {
|
||||
stdio: 'inherit',
|
||||
env: buildAppEnv(),
|
||||
});
|
||||
const result = runSyncAppCommand(appPath, appArgs, true);
|
||||
if (result.error) {
|
||||
fail(`Failed to run app command: ${result.error.message}`);
|
||||
}
|
||||
@@ -953,15 +1027,24 @@ export function launchAppCommandDetached(
|
||||
logLevel,
|
||||
`${label}: launching detached app with args: ${[target.command, ...target.args].join(' ')}`,
|
||||
);
|
||||
const proc = spawn(target.command, target.args, {
|
||||
stdio: 'ignore',
|
||||
detached: true,
|
||||
env: buildAppEnv(),
|
||||
});
|
||||
proc.once('error', (error) => {
|
||||
log('warn', logLevel, `${label}: failed to launch detached app: ${error.message}`);
|
||||
});
|
||||
proc.unref();
|
||||
const appLogPath = getAppLogPath();
|
||||
fs.mkdirSync(path.dirname(appLogPath), { recursive: true });
|
||||
const stdoutFd = fs.openSync(appLogPath, 'a');
|
||||
const stderrFd = fs.openSync(appLogPath, 'a');
|
||||
try {
|
||||
const proc = spawn(target.command, target.args, {
|
||||
stdio: ['ignore', stdoutFd, stderrFd],
|
||||
detached: true,
|
||||
env: buildAppEnv(),
|
||||
});
|
||||
proc.once('error', (error) => {
|
||||
log('warn', logLevel, `${label}: failed to launch detached app: ${error.message}`);
|
||||
});
|
||||
proc.unref();
|
||||
} finally {
|
||||
fs.closeSync(stdoutFd);
|
||||
fs.closeSync(stderrFd);
|
||||
}
|
||||
}
|
||||
|
||||
export function launchMpvIdleDetached(
|
||||
|
||||
@@ -85,6 +85,13 @@ test('parseArgs maps mpv idle action', () => {
|
||||
assert.equal(parsed.mpvStatus, false);
|
||||
});
|
||||
|
||||
test('parseArgs captures youtube mode forwarding', () => {
|
||||
const parsed = parseArgs(['youtube', 'https://example.com', '--mode', 'generate'], 'subminer', {});
|
||||
|
||||
assert.equal(parsed.target, 'https://example.com');
|
||||
assert.equal(parsed.youtubeMode, 'generate');
|
||||
});
|
||||
|
||||
test('parseArgs maps dictionary command and log-level override', () => {
|
||||
const parsed = parseArgs(['dictionary', '.', '--log-level', 'debug'], 'subminer', {});
|
||||
|
||||
|
||||
@@ -310,6 +310,7 @@ test(
|
||||
const appStartPath = path.join(smokeCase.artifactsDir, 'fake-app-start.log');
|
||||
const appStopPath = path.join(smokeCase.artifactsDir, 'fake-app-stop.log');
|
||||
await waitForJsonLines(appStartPath, 1);
|
||||
await waitForJsonLines(appStopPath, 1);
|
||||
|
||||
const appStartEntries = readJsonLines(appStartPath);
|
||||
const appStopEntries = readJsonLines(appStopPath);
|
||||
@@ -324,7 +325,7 @@ test(
|
||||
assert.match(result.stdout, /Starting SubMiner overlay/i);
|
||||
|
||||
assert.equal(appStartEntries.length, 1);
|
||||
assert.equal(appStopEntries.length, 0);
|
||||
assert.equal(appStopEntries.length, 1);
|
||||
assert.equal(mpvEntries.length >= 1, true);
|
||||
|
||||
const appStartArgs = appStartEntries[0]?.argv;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import { resolveDefaultLogFilePath } from '../src/shared/log-files.js';
|
||||
export { VIDEO_EXTENSIONS } from '../src/shared/video-extensions.js';
|
||||
|
||||
export const ROFI_THEME_FILE = 'subminer.rasi';
|
||||
@@ -29,21 +30,28 @@ export const DEFAULT_YOUTUBE_SUBGEN_OUT_DIR = path.join(
|
||||
'subminer',
|
||||
'youtube-subs',
|
||||
);
|
||||
export function getDefaultLauncherLogFile(options?: {
|
||||
platform?: NodeJS.Platform;
|
||||
homeDir?: string;
|
||||
appDataDir?: string;
|
||||
}): string {
|
||||
return resolveDefaultLogFilePath('launcher', {
|
||||
platform: options?.platform ?? process.platform,
|
||||
homeDir: options?.homeDir ?? os.homedir(),
|
||||
appDataDir: options?.appDataDir,
|
||||
});
|
||||
}
|
||||
|
||||
export function getDefaultMpvLogFile(options?: {
|
||||
platform?: NodeJS.Platform;
|
||||
homeDir?: string;
|
||||
appDataDir?: string;
|
||||
}): string {
|
||||
const platform = options?.platform ?? process.platform;
|
||||
const homeDir = options?.homeDir ?? os.homedir();
|
||||
const baseDir =
|
||||
platform === 'win32'
|
||||
? path.join(
|
||||
options?.appDataDir?.trim() || path.join(homeDir, 'AppData', 'Roaming'),
|
||||
'SubMiner',
|
||||
)
|
||||
: path.join(homeDir, '.config', 'SubMiner');
|
||||
return path.join(baseDir, 'logs', `SubMiner-${new Date().toISOString().slice(0, 10)}.log`);
|
||||
return resolveDefaultLogFilePath('mpv', {
|
||||
platform: options?.platform ?? process.platform,
|
||||
homeDir: options?.homeDir ?? os.homedir(),
|
||||
appDataDir: options?.appDataDir,
|
||||
});
|
||||
}
|
||||
|
||||
export const DEFAULT_MPV_LOG_FILE = getDefaultMpvLogFile();
|
||||
@@ -79,6 +87,7 @@ export interface Args {
|
||||
recursive: boolean;
|
||||
profile: string;
|
||||
startOverlay: boolean;
|
||||
youtubeMode?: 'download' | 'generate';
|
||||
whisperBin: string;
|
||||
whisperModel: string;
|
||||
whisperVadModel: string;
|
||||
|
||||
31
package.json
31
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "subminer",
|
||||
"version": "0.7.1",
|
||||
"version": "0.9.0",
|
||||
"description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration",
|
||||
"packageManager": "bun@1.3.5",
|
||||
"main": "dist/main-entry.js",
|
||||
@@ -77,6 +77,12 @@
|
||||
"build:win": "bun run build && electron-builder --win nsis zip --publish never",
|
||||
"build:win:unsigned": "bun run build && node scripts/build-win-unsigned.mjs"
|
||||
},
|
||||
"overrides": {
|
||||
"app-builder-lib": "26.8.2",
|
||||
"electron-builder-squirrel-windows": "26.8.2",
|
||||
"minimatch": "10.2.3",
|
||||
"tar": "7.5.11"
|
||||
},
|
||||
"keywords": [
|
||||
"anki",
|
||||
"ankiconnect",
|
||||
@@ -105,7 +111,7 @@
|
||||
"@types/node": "^25.3.0",
|
||||
"@types/ws": "^8.18.1",
|
||||
"electron": "^37.10.3",
|
||||
"electron-builder": "^26.8.1",
|
||||
"electron-builder": "26.8.2",
|
||||
"esbuild": "^0.25.12",
|
||||
"prettier": "^3.8.1",
|
||||
"typescript": "^5.9.3"
|
||||
@@ -159,12 +165,21 @@
|
||||
"include": "build/installer.nsh"
|
||||
},
|
||||
"files": [
|
||||
"dist/**/*",
|
||||
"stats/dist/**/*",
|
||||
"vendor/texthooker-ui/docs/**/*",
|
||||
"vendor/texthooker-ui/package.json",
|
||||
"package.json",
|
||||
"scripts/get-mpv-window-macos.swift"
|
||||
"**/*",
|
||||
"!src{,/**/*}",
|
||||
"!launcher{,/**/*}",
|
||||
"!stats/src{,/**/*}",
|
||||
"!stats/index.html",
|
||||
"!docs-site{,/**/*}",
|
||||
"!changes{,/**/*}",
|
||||
"!backlog{,/**/*}",
|
||||
"!.tmp{,/**/*}",
|
||||
"!release-*{,/**/*}",
|
||||
"!vendor/subminer-yomitan{,/**/*}",
|
||||
"!vendor/texthooker-ui/src{,/**/*}",
|
||||
"!vendor/texthooker-ui/node_modules{,/**/*}",
|
||||
"!vendor/texthooker-ui/.svelte-kit{,/**/*}",
|
||||
"!vendor/texthooker-ui/package-lock.json"
|
||||
],
|
||||
"extraResources": [
|
||||
{
|
||||
|
||||
@@ -33,6 +33,7 @@ function M.load(options_lib, default_socket_path)
|
||||
auto_start = true,
|
||||
auto_start_visible_overlay = true,
|
||||
auto_start_pause_until_ready = true,
|
||||
auto_start_pause_until_ready_timeout_seconds = 15,
|
||||
osd_messages = true,
|
||||
log_level = "info",
|
||||
aniskip_enabled = true,
|
||||
|
||||
@@ -2,9 +2,9 @@ local M = {}
|
||||
|
||||
local OVERLAY_START_RETRY_DELAY_SECONDS = 0.2
|
||||
local OVERLAY_START_MAX_ATTEMPTS = 6
|
||||
local AUTO_PLAY_READY_TIMEOUT_SECONDS = 15
|
||||
local AUTO_PLAY_READY_LOADING_OSD = "Loading subtitle tokenization..."
|
||||
local AUTO_PLAY_READY_READY_OSD = "Subtitle tokenization ready"
|
||||
local DEFAULT_AUTO_PLAY_READY_TIMEOUT_SECONDS = 15
|
||||
|
||||
function M.create(ctx)
|
||||
local mp = ctx.mp
|
||||
@@ -34,6 +34,23 @@ function M.create(ctx)
|
||||
return options_helper.coerce_bool(raw_pause_until_ready, false)
|
||||
end
|
||||
|
||||
local function resolve_pause_until_ready_timeout_seconds()
|
||||
local raw_timeout_seconds = opts.auto_start_pause_until_ready_timeout_seconds
|
||||
if raw_timeout_seconds == nil then
|
||||
raw_timeout_seconds = opts["auto-start-pause-until-ready-timeout-seconds"]
|
||||
end
|
||||
if type(raw_timeout_seconds) == "number" then
|
||||
return raw_timeout_seconds
|
||||
end
|
||||
if type(raw_timeout_seconds) == "string" then
|
||||
local parsed = tonumber(raw_timeout_seconds)
|
||||
if parsed ~= nil then
|
||||
return parsed
|
||||
end
|
||||
end
|
||||
return DEFAULT_AUTO_PLAY_READY_TIMEOUT_SECONDS
|
||||
end
|
||||
|
||||
local function normalize_socket_path(path)
|
||||
if type(path) ~= "string" then
|
||||
return nil
|
||||
@@ -118,17 +135,20 @@ function M.create(ctx)
|
||||
end)
|
||||
end
|
||||
subminer_log("info", "process", "Pausing playback until SubMiner overlay/tokenization readiness signal")
|
||||
state.auto_play_ready_timeout = mp.add_timeout(AUTO_PLAY_READY_TIMEOUT_SECONDS, function()
|
||||
if not state.auto_play_ready_gate_armed then
|
||||
return
|
||||
end
|
||||
subminer_log(
|
||||
"warn",
|
||||
"process",
|
||||
"Startup readiness signal timed out; resuming playback to avoid stalled pause"
|
||||
)
|
||||
release_auto_play_ready_gate("timeout")
|
||||
end)
|
||||
local timeout_seconds = resolve_pause_until_ready_timeout_seconds()
|
||||
if timeout_seconds and timeout_seconds > 0 then
|
||||
state.auto_play_ready_timeout = mp.add_timeout(timeout_seconds, function()
|
||||
if not state.auto_play_ready_gate_armed then
|
||||
return
|
||||
end
|
||||
subminer_log(
|
||||
"warn",
|
||||
"process",
|
||||
"Startup readiness signal timed out; resuming playback to avoid stalled pause"
|
||||
)
|
||||
release_auto_play_ready_gate("timeout")
|
||||
end)
|
||||
end
|
||||
end
|
||||
|
||||
local function notify_auto_play_ready()
|
||||
|
||||
@@ -95,6 +95,43 @@ test('writeChangelogArtifacts ignores README, groups fragments by type, writes r
|
||||
}
|
||||
});
|
||||
|
||||
test('writeChangelogArtifacts skips changelog prepend when release section already exists', async () => {
|
||||
const { writeChangelogArtifacts } = await loadModule();
|
||||
const workspace = createWorkspace('write-artifacts-existing-version');
|
||||
const projectRoot = path.join(workspace, 'SubMiner');
|
||||
const existingChangelog = [
|
||||
'# Changelog',
|
||||
'',
|
||||
'## v0.4.1 (2026-03-07)',
|
||||
'### Added',
|
||||
'- Existing release bullet.',
|
||||
'',
|
||||
].join('\n');
|
||||
|
||||
fs.mkdirSync(projectRoot, { recursive: true });
|
||||
fs.mkdirSync(path.join(projectRoot, 'changes'), { recursive: true });
|
||||
fs.writeFileSync(path.join(projectRoot, 'CHANGELOG.md'), existingChangelog, 'utf8');
|
||||
fs.writeFileSync(path.join(projectRoot, 'changes', '001.md'), ['type: added', 'area: overlay', '', '- Stale release fragment.'].join('\n'), 'utf8');
|
||||
|
||||
try {
|
||||
const result = writeChangelogArtifacts({
|
||||
cwd: projectRoot,
|
||||
version: '0.4.1',
|
||||
date: '2026-03-08',
|
||||
});
|
||||
|
||||
assert.deepEqual(result.deletedFragmentPaths, [path.join(projectRoot, 'changes', '001.md')]);
|
||||
assert.equal(fs.existsSync(path.join(projectRoot, 'changes', '001.md')), false);
|
||||
|
||||
const changelog = fs.readFileSync(path.join(projectRoot, 'CHANGELOG.md'), 'utf8');
|
||||
assert.equal(changelog, existingChangelog);
|
||||
const releaseNotes = fs.readFileSync(path.join(projectRoot, 'release', 'release-notes.md'), 'utf8');
|
||||
assert.match(releaseNotes, /## Highlights\n### Added\n- Existing release bullet\./);
|
||||
} finally {
|
||||
fs.rmSync(workspace, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('verifyChangelogReadyForRelease ignores README but rejects pending fragments and missing version sections', async () => {
|
||||
const { verifyChangelogReadyForRelease } = await loadModule();
|
||||
const workspace = createWorkspace('verify-release');
|
||||
|
||||
@@ -341,12 +341,34 @@ export function writeChangelogArtifacts(options?: ChangelogOptions): {
|
||||
const version = resolveVersion(options ?? {});
|
||||
const date = resolveDate(options?.date);
|
||||
const fragments = readChangeFragments(cwd, options?.deps);
|
||||
const releaseSection = buildReleaseSection(version, date, fragments);
|
||||
const existingChangelogPath = path.join(cwd, 'CHANGELOG.md');
|
||||
const existingChangelog = existsSync(existingChangelogPath)
|
||||
? readFileSync(existingChangelogPath, 'utf8')
|
||||
: '';
|
||||
const outputPaths = resolveChangelogOutputPaths({ cwd });
|
||||
const existingReleaseSection = extractReleaseSectionBody(existingChangelog, version);
|
||||
if (existingReleaseSection !== null) {
|
||||
log(`Existing section found for v${version}; skipping changelog prepend.`);
|
||||
for (const fragment of fragments) {
|
||||
rmSync(fragment.path);
|
||||
log(`Removed ${fragment.path}`);
|
||||
}
|
||||
|
||||
const releaseNotesPath = writeReleaseNotesFile(
|
||||
cwd,
|
||||
existingReleaseSection,
|
||||
options?.deps,
|
||||
);
|
||||
log(`Generated ${releaseNotesPath}`);
|
||||
|
||||
return {
|
||||
deletedFragmentPaths: fragments.map((fragment) => fragment.path),
|
||||
outputPaths,
|
||||
releaseNotesPath,
|
||||
};
|
||||
}
|
||||
|
||||
const releaseSection = buildReleaseSection(version, date, fragments);
|
||||
const nextChangelog = prependReleaseSection(existingChangelog, releaseSection, version);
|
||||
|
||||
for (const outputPath of outputPaths) {
|
||||
|
||||
157
scripts/patch-modernz.sh
Executable file
157
scripts/patch-modernz.sh
Executable file
@@ -0,0 +1,157 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
TARGET="${HOME}/.config/mpv/scripts/modernz.lua"
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
Usage: patch-modernz.sh [--target /path/to/modernz.lua]
|
||||
|
||||
Applies the local ModernZ OSC sidebar-resize patch to an existing modernz.lua.
|
||||
If the target file does not exist, the script exits without changing anything.
|
||||
EOF
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--target)
|
||||
if [[ $# -lt 2 || -z "${2:-}" || "$2" == -* ]]; then
|
||||
echo "patch-modernz: --target requires a non-empty file path" >&2
|
||||
usage >&2
|
||||
exit 1
|
||||
fi
|
||||
TARGET="$2"
|
||||
shift 2
|
||||
;;
|
||||
--help|-h)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "Unknown argument: $1" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ ! -f "$TARGET" ]]; then
|
||||
echo "patch-modernz: target missing, skipped: $TARGET"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if grep -q 'get_external_video_margin_ratio' "$TARGET" \
|
||||
&& grep -q 'observe_cached("video-margin-ratio-right"' "$TARGET"; then
|
||||
echo "patch-modernz: already patched: $TARGET"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ! patch --forward --quiet "$TARGET" <<'PATCH'
|
||||
--- a/modernz.lua
|
||||
+++ b/modernz.lua
|
||||
@@ -931,6 +931,26 @@ local function reset_margins()
|
||||
set_margin_offset("osd-margin-y", 0)
|
||||
end
|
||||
|
||||
+local function get_external_video_margin_ratio(prop)
|
||||
+ local value = mp.get_property_number(prop, 0) or 0
|
||||
+ if value < 0 then return 0 end
|
||||
+ if value > 0.95 then return 0.95 end
|
||||
+ return value
|
||||
+end
|
||||
+
|
||||
+local function get_layout_horizontal_bounds()
|
||||
+ local margin_l = get_external_video_margin_ratio("video-margin-ratio-left")
|
||||
+ local margin_r = get_external_video_margin_ratio("video-margin-ratio-right")
|
||||
+ local width_ratio = math.max(0.05, 1 - margin_l - margin_r)
|
||||
+ local pos_x = osc_param.playresx * margin_l
|
||||
+ local width = osc_param.playresx * width_ratio
|
||||
+
|
||||
+ osc_param.video_margins.l = margin_l
|
||||
+ osc_param.video_margins.r = margin_r
|
||||
+
|
||||
+ return pos_x, width
|
||||
+end
|
||||
+
|
||||
local function update_margins()
|
||||
local use_margins = get_hidetimeout() < 0 or user_opts.dynamic_margins
|
||||
local top_vis = state.wc_visible
|
||||
@@ -1965,8 +1985,9 @@ layouts["modern"] = function ()
|
||||
local chapter_index = user_opts.show_chapter_title and mp.get_property_number("chapter", -1) >= 0
|
||||
local osc_height_offset = (no_title and user_opts.notitle_osc_h_offset or 0) + ((no_chapter or not chapter_index) and user_opts.nochapter_osc_h_offset or 0)
|
||||
|
||||
+ local posX, layout_width = get_layout_horizontal_bounds()
|
||||
local osc_geo = {
|
||||
- w = osc_param.playresx,
|
||||
+ w = layout_width,
|
||||
h = user_opts.osc_height - osc_height_offset
|
||||
}
|
||||
|
||||
@@ -1974,7 +1995,6 @@ layouts["modern"] = function ()
|
||||
osc_param.video_margins.b = math.max(user_opts.osc_height, user_opts.fade_alpha) / osc_param.playresy
|
||||
|
||||
-- origin of the controllers, left/bottom corner
|
||||
- local posX = 0
|
||||
local posY = osc_param.playresy
|
||||
|
||||
osc_param.areas = {} -- delete areas
|
||||
@@ -2191,8 +2211,9 @@ layouts["modern-compact"] = function ()
|
||||
((user_opts.title_mbtn_left_command == "" and user_opts.title_mbtn_right_command == "") and 25 or 0) +
|
||||
(((user_opts.chapter_title_mbtn_left_command == "" and user_opts.chapter_title_mbtn_right_command == "") or not chapter_index) and 10 or 0)
|
||||
|
||||
+ local posX, layout_width = get_layout_horizontal_bounds()
|
||||
local osc_geo = {
|
||||
- w = osc_param.playresx,
|
||||
+ w = layout_width,
|
||||
h = 145 - osc_height_offset
|
||||
}
|
||||
|
||||
@@ -2200,7 +2221,6 @@ layouts["modern-compact"] = function ()
|
||||
osc_param.video_margins.b = math.max(osc_geo.h, user_opts.fade_alpha) / osc_param.playresy
|
||||
|
||||
-- origin of the controllers, left/bottom corner
|
||||
- local posX = 0
|
||||
local posY = osc_param.playresy
|
||||
|
||||
osc_param.areas = {} -- delete areas
|
||||
@@ -2370,8 +2390,9 @@ layouts["modern-compact"] = function ()
|
||||
end
|
||||
|
||||
layouts["modern-image"] = function ()
|
||||
+ local posX, layout_width = get_layout_horizontal_bounds()
|
||||
local osc_geo = {
|
||||
- w = osc_param.playresx,
|
||||
+ w = layout_width,
|
||||
h = 50
|
||||
}
|
||||
|
||||
@@ -2379,7 +2400,6 @@ layouts["modern-image"] = function ()
|
||||
osc_param.video_margins.b = math.max(50, user_opts.fade_alpha) / osc_param.playresy
|
||||
|
||||
-- origin of the controllers, left/bottom corner
|
||||
- local posX = 0
|
||||
local posY = osc_param.playresy
|
||||
|
||||
osc_param.areas = {} -- delete areas
|
||||
@@ -3718,6 +3738,14 @@ observe_cached("border", request_init_resize)
|
||||
observe_cached("title-bar", request_init_resize)
|
||||
observe_cached("window-maximized", request_init_resize)
|
||||
observe_cached("idle-active", request_tick)
|
||||
+observe_cached("video-margin-ratio-left", function ()
|
||||
+ state.marginsREQ = true
|
||||
+ request_init_resize()
|
||||
+end)
|
||||
+observe_cached("video-margin-ratio-right", function ()
|
||||
+ state.marginsREQ = true
|
||||
+ request_init_resize()
|
||||
+end)
|
||||
mp.observe_property("user-data/mpv/console/open", "bool", function(_, val)
|
||||
if val and user_opts.visibility == "auto" and not user_opts.showonselect then
|
||||
osc_visible(false)
|
||||
PATCH
|
||||
then
|
||||
echo "patch-modernz: failed to apply patch to $TARGET" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "patch-modernz: patched $TARGET"
|
||||
76
scripts/patch-modernz.test.ts
Normal file
76
scripts/patch-modernz.test.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import test from 'node:test';
|
||||
|
||||
function withTempDir<T>(fn: (dir: string) => T): T {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-patch-modernz-test-'));
|
||||
try {
|
||||
return fn(dir);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function writeExecutable(filePath: string, contents: string): void {
|
||||
fs.writeFileSync(filePath, contents, 'utf8');
|
||||
fs.chmodSync(filePath, 0o755);
|
||||
}
|
||||
|
||||
test('patch-modernz rejects a missing --target value', () => {
|
||||
withTempDir((root) => {
|
||||
const result = spawnSync('bash', ['scripts/patch-modernz.sh', '--target'], {
|
||||
cwd: process.cwd(),
|
||||
encoding: 'utf8',
|
||||
env: {
|
||||
...process.env,
|
||||
HOME: path.join(root, 'home'),
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result.status, 1, result.stderr || result.stdout);
|
||||
assert.match(result.stderr, /--target requires a non-empty file path/);
|
||||
assert.match(result.stderr, /Usage: patch-modernz\.sh/);
|
||||
});
|
||||
});
|
||||
|
||||
test('patch-modernz reports patch failures explicitly', () => {
|
||||
withTempDir((root) => {
|
||||
const binDir = path.join(root, 'bin');
|
||||
const target = path.join(root, 'modernz.lua');
|
||||
const patchLog = path.join(root, 'patch.log');
|
||||
|
||||
fs.mkdirSync(binDir, { recursive: true });
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
fs.writeFileSync(target, 'original', 'utf8');
|
||||
|
||||
writeExecutable(
|
||||
path.join(binDir, 'patch'),
|
||||
`#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cat > "${patchLog}"
|
||||
exit 1
|
||||
`,
|
||||
);
|
||||
|
||||
const result = spawnSync(
|
||||
'bash',
|
||||
['scripts/patch-modernz.sh', '--target', target],
|
||||
{
|
||||
cwd: process.cwd(),
|
||||
encoding: 'utf8',
|
||||
env: {
|
||||
...process.env,
|
||||
HOME: path.join(root, 'home'),
|
||||
PATH: `${binDir}:${process.env.PATH || ''}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
assert.equal(result.status, 1, result.stderr || result.stdout);
|
||||
assert.match(result.stderr, /failed to apply patch to/);
|
||||
assert.equal(fs.readFileSync(patchLog, 'utf8').includes('modernz.lua'), true);
|
||||
});
|
||||
});
|
||||
@@ -58,6 +58,7 @@ import { NoteUpdateWorkflow } from './anki-integration/note-update-workflow';
|
||||
import { FieldGroupingWorkflow } from './anki-integration/field-grouping-workflow';
|
||||
import { resolveAnimatedImageLeadInSeconds } from './anki-integration/animated-image-sync';
|
||||
import { AnkiIntegrationRuntime, normalizeAnkiIntegrationConfig } from './anki-integration/runtime';
|
||||
import { resolveMediaGenerationInputPath } from './anki-integration/media-source';
|
||||
|
||||
const log = createLogger('anki').child('integration');
|
||||
|
||||
@@ -597,6 +598,10 @@ export class AnkiIntegration {
|
||||
this.runtime.start();
|
||||
}
|
||||
|
||||
waitUntilReady(): Promise<void> {
|
||||
return this.runtime.waitUntilReady();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.runtime.stop();
|
||||
}
|
||||
@@ -647,7 +652,10 @@ export class AnkiIntegration {
|
||||
return null;
|
||||
}
|
||||
|
||||
const videoPath = mpvClient.currentVideoPath;
|
||||
const videoPath = await resolveMediaGenerationInputPath(mpvClient, 'audio');
|
||||
if (!videoPath) {
|
||||
return null;
|
||||
}
|
||||
let startTime = mpvClient.currentSubStart;
|
||||
let endTime = mpvClient.currentSubEnd;
|
||||
|
||||
@@ -672,7 +680,10 @@ export class AnkiIntegration {
|
||||
return null;
|
||||
}
|
||||
|
||||
const videoPath = this.mpvClient.currentVideoPath;
|
||||
const videoPath = await resolveMediaGenerationInputPath(this.mpvClient, 'video');
|
||||
if (!videoPath) {
|
||||
return null;
|
||||
}
|
||||
const timestamp = this.mpvClient.currentTimePos || 0;
|
||||
|
||||
if (this.config.media?.imageType === 'avif') {
|
||||
@@ -946,8 +957,15 @@ export class AnkiIntegration {
|
||||
if (this.mpvClient && this.mpvClient.currentVideoPath) {
|
||||
try {
|
||||
const timestamp = this.mpvClient.currentTimePos || 0;
|
||||
const notificationIconSource = await resolveMediaGenerationInputPath(
|
||||
this.mpvClient,
|
||||
'video',
|
||||
);
|
||||
if (!notificationIconSource) {
|
||||
throw new Error('No media source available for notification icon');
|
||||
}
|
||||
const iconBuffer = await this.mediaGenerator.generateNotificationIcon(
|
||||
this.mpvClient.currentVideoPath,
|
||||
notificationIconSource,
|
||||
timestamp,
|
||||
);
|
||||
if (iconBuffer && iconBuffer.length > 0) {
|
||||
|
||||
@@ -35,6 +35,9 @@ export class AnkiConnectProxyServer {
|
||||
private pendingNoteIdSet = new Set<number>();
|
||||
private inFlightNoteIds = new Set<number>();
|
||||
private processingQueue = false;
|
||||
private readyPromise: Promise<void> | null = null;
|
||||
private resolveReady: (() => void) | null = null;
|
||||
private rejectReady: ((error: Error) => void) | null = null;
|
||||
|
||||
constructor(private readonly deps: AnkiConnectProxyServerDeps) {
|
||||
this.client = axios.create({
|
||||
@@ -48,6 +51,13 @@ export class AnkiConnectProxyServer {
|
||||
return this.server !== null;
|
||||
}
|
||||
|
||||
waitUntilReady(): Promise<void> {
|
||||
if (!this.server || this.server.listening) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
return this.readyPromise ?? Promise.resolve();
|
||||
}
|
||||
|
||||
start(options: StartProxyOptions): void {
|
||||
this.stop();
|
||||
|
||||
@@ -58,15 +68,26 @@ export class AnkiConnectProxyServer {
|
||||
return;
|
||||
}
|
||||
|
||||
this.readyPromise = new Promise<void>((resolve, reject) => {
|
||||
this.resolveReady = resolve;
|
||||
this.rejectReady = reject;
|
||||
});
|
||||
|
||||
this.server = http.createServer((req, res) => {
|
||||
void this.handleRequest(req, res, options.upstreamUrl);
|
||||
});
|
||||
|
||||
this.server.on('error', (error) => {
|
||||
this.rejectReady?.(error as Error);
|
||||
this.resolveReady = null;
|
||||
this.rejectReady = null;
|
||||
this.deps.logError('[anki-proxy] Server error:', (error as Error).message);
|
||||
});
|
||||
|
||||
this.server.listen(options.port, options.host, () => {
|
||||
this.resolveReady?.();
|
||||
this.resolveReady = null;
|
||||
this.rejectReady = null;
|
||||
this.deps.logInfo(
|
||||
`[anki-proxy] Listening on http://${options.host}:${options.port} -> ${options.upstreamUrl}`,
|
||||
);
|
||||
@@ -79,6 +100,10 @@ export class AnkiConnectProxyServer {
|
||||
this.server = null;
|
||||
this.deps.logInfo('[anki-proxy] Stopped');
|
||||
}
|
||||
this.rejectReady?.(new Error('AnkiConnect proxy stopped before becoming ready'));
|
||||
this.readyPromise = null;
|
||||
this.resolveReady = null;
|
||||
this.rejectReady = null;
|
||||
this.pendingNoteIds = [];
|
||||
this.pendingNoteIdSet.clear();
|
||||
this.inFlightNoteIds.clear();
|
||||
|
||||
@@ -283,3 +283,117 @@ test('CardCreationService keeps updating after recordCardsMinedCallback throws',
|
||||
assert.equal(calls.notesInfo, 1);
|
||||
assert.equal(calls.updateNoteFields, 1);
|
||||
});
|
||||
|
||||
test('CardCreationService uses stream-open-filename for remote media generation', async () => {
|
||||
const audioPaths: string[] = [];
|
||||
const imagePaths: string[] = [];
|
||||
const edlSource = [
|
||||
'edl://!new_stream;!no_clip;!no_chapters;%70%https://audio.example/videoplayback?mime=audio%2Fwebm',
|
||||
'!new_stream;!no_clip;!no_chapters;%69%https://video.example/videoplayback?mime=video%2Fmp4',
|
||||
'!global_tags,title=test',
|
||||
].join(';');
|
||||
|
||||
const service = new CardCreationService({
|
||||
getConfig: () =>
|
||||
({
|
||||
deck: 'Mining',
|
||||
fields: {
|
||||
sentence: 'Sentence',
|
||||
audio: 'SentenceAudio',
|
||||
image: 'Picture',
|
||||
},
|
||||
media: {
|
||||
generateAudio: true,
|
||||
generateImage: true,
|
||||
imageFormat: 'jpg',
|
||||
},
|
||||
behavior: {},
|
||||
ai: false,
|
||||
}) as AnkiConnectConfig,
|
||||
getAiConfig: () => ({}),
|
||||
getTimingTracker: () => ({}) as never,
|
||||
getMpvClient: () =>
|
||||
({
|
||||
currentVideoPath: 'https://www.youtube.com/watch?v=abc123',
|
||||
currentSubText: '字幕',
|
||||
currentSubStart: 1,
|
||||
currentSubEnd: 2,
|
||||
currentTimePos: 1.5,
|
||||
currentAudioStreamIndex: 0,
|
||||
requestProperty: async (name: string) => {
|
||||
assert.equal(name, 'stream-open-filename');
|
||||
return edlSource;
|
||||
},
|
||||
}) as never,
|
||||
client: {
|
||||
addNote: async () => 42,
|
||||
addTags: async () => undefined,
|
||||
notesInfo: async () => [
|
||||
{
|
||||
noteId: 42,
|
||||
fields: {
|
||||
Sentence: { value: '' },
|
||||
SentenceAudio: { value: '' },
|
||||
Picture: { value: '' },
|
||||
},
|
||||
},
|
||||
],
|
||||
updateNoteFields: async () => undefined,
|
||||
storeMediaFile: async () => undefined,
|
||||
findNotes: async () => [],
|
||||
retrieveMediaFile: async () => '',
|
||||
},
|
||||
mediaGenerator: {
|
||||
generateAudio: async (path) => {
|
||||
audioPaths.push(path);
|
||||
return Buffer.from('audio');
|
||||
},
|
||||
generateScreenshot: async (path) => {
|
||||
imagePaths.push(path);
|
||||
return Buffer.from('image');
|
||||
},
|
||||
generateAnimatedImage: async () => null,
|
||||
},
|
||||
showOsdNotification: () => undefined,
|
||||
showUpdateResult: () => undefined,
|
||||
showStatusNotification: () => undefined,
|
||||
showNotification: async () => undefined,
|
||||
beginUpdateProgress: () => undefined,
|
||||
endUpdateProgress: () => undefined,
|
||||
withUpdateProgress: async (_message, action) => action(),
|
||||
resolveConfiguredFieldName: (noteInfo, preferredName) => {
|
||||
if (!preferredName) return null;
|
||||
return Object.keys(noteInfo.fields).find((field) => field === preferredName) ?? null;
|
||||
},
|
||||
resolveNoteFieldName: (noteInfo, preferredName) => {
|
||||
if (!preferredName) return null;
|
||||
return Object.keys(noteInfo.fields).find((field) => field === preferredName) ?? null;
|
||||
},
|
||||
getAnimatedImageLeadInSeconds: async () => 0,
|
||||
extractFields: () => ({}),
|
||||
processSentence: (sentence) => sentence,
|
||||
setCardTypeFields: () => undefined,
|
||||
mergeFieldValue: (_existing, newValue) => newValue,
|
||||
formatMiscInfoPattern: () => '',
|
||||
getEffectiveSentenceCardConfig: () => ({
|
||||
model: 'Sentence',
|
||||
sentenceField: 'Sentence',
|
||||
audioField: 'SentenceAudio',
|
||||
lapisEnabled: false,
|
||||
kikuEnabled: false,
|
||||
kikuFieldGrouping: 'disabled',
|
||||
kikuDeleteDuplicateInAuto: false,
|
||||
}),
|
||||
getFallbackDurationSeconds: () => 10,
|
||||
appendKnownWordsFromNoteInfo: () => undefined,
|
||||
isUpdateInProgress: () => false,
|
||||
setUpdateInProgress: () => undefined,
|
||||
trackLastAddedNoteId: () => undefined,
|
||||
});
|
||||
|
||||
const created = await service.createSentenceCard('テスト', 0, 1);
|
||||
|
||||
assert.equal(created, true);
|
||||
assert.deepEqual(audioPaths, ['https://audio.example/videoplayback?mime=audio%2Fwebm']);
|
||||
assert.deepEqual(imagePaths, ['https://video.example/videoplayback?mime=video%2Fmp4']);
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ import { createLogger } from '../logger';
|
||||
import { SubtitleTimingTracker } from '../subtitle-timing-tracker';
|
||||
import { MpvClient } from '../types';
|
||||
import { resolveSentenceBackText } from './ai';
|
||||
import { resolveMediaGenerationInputPath } from './media-source';
|
||||
|
||||
const log = createLogger('anki').child('integration.card-creation');
|
||||
|
||||
@@ -501,7 +502,12 @@ export class CardCreationService {
|
||||
this.deps.showOsdNotification('Creating sentence card...');
|
||||
try {
|
||||
return await this.deps.withUpdateProgress('Creating sentence card', async () => {
|
||||
const videoPath = mpvClient.currentVideoPath;
|
||||
const videoPath = await resolveMediaGenerationInputPath(mpvClient, 'video');
|
||||
const audioSourcePath = await resolveMediaGenerationInputPath(mpvClient, 'audio');
|
||||
if (!videoPath) {
|
||||
this.deps.showOsdNotification('No video loaded');
|
||||
return false;
|
||||
}
|
||||
const fields: Record<string, string> = {};
|
||||
const errors: string[] = [];
|
||||
let miscInfoFilename: string | null = null;
|
||||
@@ -605,7 +611,9 @@ export class CardCreationService {
|
||||
|
||||
try {
|
||||
const audioFilename = this.generateAudioFilename();
|
||||
const audioBuffer = await this.mediaGenerateAudio(videoPath, startTime, endTime);
|
||||
const audioBuffer = audioSourcePath
|
||||
? await this.mediaGenerateAudio(audioSourcePath, startTime, endTime)
|
||||
: null;
|
||||
|
||||
if (audioBuffer) {
|
||||
await this.deps.client.storeMediaFile(audioFilename, audioBuffer);
|
||||
|
||||
64
src/anki-integration/media-source.test.ts
Normal file
64
src/anki-integration/media-source.test.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { resolveMediaGenerationInputPath } from './media-source';
|
||||
|
||||
test('resolveMediaGenerationInputPath keeps local file paths', async () => {
|
||||
const result = await resolveMediaGenerationInputPath({
|
||||
currentVideoPath: '/tmp/video.mkv',
|
||||
});
|
||||
|
||||
assert.equal(result, '/tmp/video.mkv');
|
||||
});
|
||||
|
||||
test('resolveMediaGenerationInputPath prefers stream-open-filename for remote media', async () => {
|
||||
const requests: string[] = [];
|
||||
|
||||
const result = await resolveMediaGenerationInputPath({
|
||||
currentVideoPath: 'https://www.youtube.com/watch?v=abc123',
|
||||
requestProperty: async (name: string) => {
|
||||
requests.push(name);
|
||||
return 'https://rr1---sn.example.googlevideo.com/videoplayback?id=123';
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result, 'https://rr1---sn.example.googlevideo.com/videoplayback?id=123');
|
||||
assert.deepEqual(requests, ['stream-open-filename']);
|
||||
});
|
||||
|
||||
test('resolveMediaGenerationInputPath unwraps mpv edl source for audio and video', async () => {
|
||||
const edlSource = [
|
||||
'edl://!new_stream;!no_clip;!no_chapters;%70%https://audio.example/videoplayback?mime=audio%2Fwebm',
|
||||
'!new_stream;!no_clip;!no_chapters;%69%https://video.example/videoplayback?mime=video%2Fmp4',
|
||||
'!global_tags,title=test',
|
||||
].join(';');
|
||||
|
||||
const audioResult = await resolveMediaGenerationInputPath(
|
||||
{
|
||||
currentVideoPath: 'https://www.youtube.com/watch?v=abc123',
|
||||
requestProperty: async () => edlSource,
|
||||
},
|
||||
'audio',
|
||||
);
|
||||
const videoResult = await resolveMediaGenerationInputPath(
|
||||
{
|
||||
currentVideoPath: 'https://www.youtube.com/watch?v=abc123',
|
||||
requestProperty: async () => edlSource,
|
||||
},
|
||||
'video',
|
||||
);
|
||||
|
||||
assert.equal(audioResult, 'https://audio.example/videoplayback?mime=audio%2Fwebm');
|
||||
assert.equal(videoResult, 'https://video.example/videoplayback?mime=video%2Fmp4');
|
||||
});
|
||||
|
||||
test('resolveMediaGenerationInputPath falls back to currentVideoPath when stream-open-filename fails', async () => {
|
||||
const result = await resolveMediaGenerationInputPath({
|
||||
currentVideoPath: 'https://www.youtube.com/watch?v=abc123',
|
||||
requestProperty: async () => {
|
||||
throw new Error('property unavailable');
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result, 'https://www.youtube.com/watch?v=abc123');
|
||||
});
|
||||
84
src/anki-integration/media-source.ts
Normal file
84
src/anki-integration/media-source.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import { isRemoteMediaPath } from '../jimaku/utils';
|
||||
import type { MpvClient } from '../types';
|
||||
|
||||
export type MediaGenerationKind = 'audio' | 'video';
|
||||
|
||||
function trimToNonEmptyString(value: unknown): string | null {
|
||||
if (typeof value !== 'string') {
|
||||
return null;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function extractUrlsFromMpvEdlSource(source: string): string[] {
|
||||
const matches = source.matchAll(/%\d+%(https?:\/\/.*?)(?=;!new_stream|;!global_tags|$)/gms);
|
||||
return [...matches]
|
||||
.map((match) => trimToNonEmptyString(match[1]))
|
||||
.filter((value): value is string => value !== null);
|
||||
}
|
||||
|
||||
function classifyMediaUrl(url: string): MediaGenerationKind | null {
|
||||
try {
|
||||
const mime = new URL(url).searchParams.get('mime')?.toLowerCase() ?? '';
|
||||
if (mime.startsWith('audio/')) {
|
||||
return 'audio';
|
||||
}
|
||||
if (mime.startsWith('video/')) {
|
||||
return 'video';
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed URLs and fall back to stream order.
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolvePreferredUrlFromMpvEdlSource(
|
||||
source: string,
|
||||
kind: MediaGenerationKind,
|
||||
): string | null {
|
||||
const urls = extractUrlsFromMpvEdlSource(source);
|
||||
if (urls.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const typedMatch = urls.find((url) => classifyMediaUrl(url) === kind);
|
||||
if (typedMatch) {
|
||||
return typedMatch;
|
||||
}
|
||||
|
||||
// mpv EDL sources usually list audio streams first and video streams last, so
|
||||
// when classifyMediaUrl cannot identify a typed URL we fall back to stream order.
|
||||
return kind === 'audio' ? urls[0] ?? null : urls[urls.length - 1] ?? null;
|
||||
}
|
||||
|
||||
export async function resolveMediaGenerationInputPath(
|
||||
mpvClient: Pick<MpvClient, 'currentVideoPath' | 'requestProperty'> | null | undefined,
|
||||
kind: MediaGenerationKind = 'video',
|
||||
): Promise<string | null> {
|
||||
const currentVideoPath = trimToNonEmptyString(mpvClient?.currentVideoPath);
|
||||
if (!currentVideoPath) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!isRemoteMediaPath(currentVideoPath) || !mpvClient?.requestProperty) {
|
||||
return currentVideoPath;
|
||||
}
|
||||
|
||||
try {
|
||||
const streamOpenFilename = trimToNonEmptyString(
|
||||
await mpvClient.requestProperty('stream-open-filename'),
|
||||
);
|
||||
if (streamOpenFilename?.startsWith('edl://')) {
|
||||
return resolvePreferredUrlFromMpvEdlSource(streamOpenFilename, kind) ?? streamOpenFilename;
|
||||
}
|
||||
if (streamOpenFilename) {
|
||||
return streamOpenFilename;
|
||||
}
|
||||
} catch {
|
||||
// Fall back to the current path when mpv does not expose a resolved stream URL.
|
||||
}
|
||||
|
||||
return currentVideoPath;
|
||||
}
|
||||
@@ -26,6 +26,7 @@ function createRuntime(
|
||||
start: ({ host, port, upstreamUrl }) =>
|
||||
calls.push(`proxy:start:${host}:${port}:${upstreamUrl}`),
|
||||
stop: () => calls.push('proxy:stop'),
|
||||
waitUntilReady: async () => undefined,
|
||||
}),
|
||||
logInfo: () => undefined,
|
||||
logWarn: () => undefined,
|
||||
@@ -80,6 +81,44 @@ test('AnkiIntegrationRuntime starts proxy transport when proxy mode is enabled',
|
||||
assert.deepEqual(calls, ['known:start', 'proxy:start:127.0.0.1:9999:http://upstream:8765']);
|
||||
});
|
||||
|
||||
test('AnkiIntegrationRuntime waits for proxy readiness when proxy mode is enabled', async () => {
|
||||
let releaseReady!: () => void;
|
||||
const waitUntilReadyCalls: string[] = [];
|
||||
const readyPromise = new Promise<void>((resolve) => {
|
||||
releaseReady = resolve;
|
||||
});
|
||||
const { runtime } = createRuntime(
|
||||
{
|
||||
proxy: {
|
||||
enabled: true,
|
||||
host: '127.0.0.1',
|
||||
port: 9999,
|
||||
upstreamUrl: 'http://upstream:8765',
|
||||
},
|
||||
},
|
||||
{
|
||||
proxyServerFactory: () => ({
|
||||
start: () => undefined,
|
||||
stop: () => undefined,
|
||||
waitUntilReady: async () => {
|
||||
waitUntilReadyCalls.push('proxy:wait-until-ready');
|
||||
await readyPromise;
|
||||
},
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
runtime.start();
|
||||
const waitPromise = runtime.waitUntilReady().then(() => {
|
||||
waitUntilReadyCalls.push('proxy:ready');
|
||||
});
|
||||
|
||||
assert.deepEqual(waitUntilReadyCalls, ['proxy:wait-until-ready']);
|
||||
releaseReady();
|
||||
await waitPromise;
|
||||
assert.deepEqual(waitUntilReadyCalls, ['proxy:wait-until-ready', 'proxy:ready']);
|
||||
});
|
||||
|
||||
test('AnkiIntegrationRuntime switches transports and clears known words when runtime patch disables highlighting', () => {
|
||||
const { runtime, calls } = createRuntime({
|
||||
knownWords: {
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
export interface AnkiIntegrationRuntimeProxyServer {
|
||||
start(options: { host: string; port: number; upstreamUrl: string }): void;
|
||||
stop(): void;
|
||||
waitUntilReady(): Promise<void>;
|
||||
}
|
||||
|
||||
interface AnkiIntegrationRuntimeDeps {
|
||||
@@ -131,6 +132,13 @@ export class AnkiIntegrationRuntime {
|
||||
return this.config;
|
||||
}
|
||||
|
||||
waitUntilReady(): Promise<void> {
|
||||
if (!this.started || !this.isProxyTransportEnabled()) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
return this.getOrCreateProxyServer().waitUntilReady();
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this.started) {
|
||||
this.stop();
|
||||
|
||||
@@ -56,6 +56,15 @@ test('parseArgs captures launch-mpv targets and keeps it out of app startup', ()
|
||||
assert.equal(shouldStartApp(args), false);
|
||||
});
|
||||
|
||||
test('parseArgs captures youtube playback commands and mode', () => {
|
||||
const args = parseArgs(['--youtube-play', 'https://youtube.com/watch?v=abc', '--youtube-mode', 'generate']);
|
||||
|
||||
assert.equal(args.youtubePlay, 'https://youtube.com/watch?v=abc');
|
||||
assert.equal(args.youtubeMode, 'generate');
|
||||
assert.equal(hasExplicitCommand(args), true);
|
||||
assert.equal(shouldStartApp(args), true);
|
||||
});
|
||||
|
||||
test('parseArgs handles jellyfin item listing controls', () => {
|
||||
const args = parseArgs([
|
||||
'--jellyfin-items',
|
||||
|
||||
@@ -3,6 +3,8 @@ export interface CliArgs {
|
||||
start: boolean;
|
||||
launchMpv: boolean;
|
||||
launchMpvTargets: string[];
|
||||
youtubePlay?: string;
|
||||
youtubeMode?: 'download' | 'generate';
|
||||
stop: boolean;
|
||||
toggle: boolean;
|
||||
toggleVisibleOverlay: boolean;
|
||||
@@ -79,6 +81,8 @@ export function parseArgs(argv: string[]): CliArgs {
|
||||
start: false,
|
||||
launchMpv: false,
|
||||
launchMpvTargets: [],
|
||||
youtubePlay: undefined,
|
||||
youtubeMode: undefined,
|
||||
stop: false,
|
||||
toggle: false,
|
||||
toggleVisibleOverlay: false,
|
||||
@@ -140,7 +144,19 @@ export function parseArgs(argv: string[]): CliArgs {
|
||||
|
||||
if (arg === '--background') args.background = true;
|
||||
else if (arg === '--start') args.start = true;
|
||||
else if (arg === '--launch-mpv') {
|
||||
else if (arg.startsWith('--youtube-play=')) {
|
||||
const value = arg.split('=', 2)[1];
|
||||
if (value) args.youtubePlay = value;
|
||||
} else if (arg === '--youtube-play') {
|
||||
const value = readValue(argv[i + 1]);
|
||||
if (value) args.youtubePlay = value;
|
||||
} else if (arg.startsWith('--youtube-mode=')) {
|
||||
const value = arg.split('=', 2)[1];
|
||||
if (value === 'download' || value === 'generate') args.youtubeMode = value;
|
||||
} else if (arg === '--youtube-mode') {
|
||||
const value = readValue(argv[i + 1]);
|
||||
if (value === 'download' || value === 'generate') args.youtubeMode = value;
|
||||
} else if (arg === '--launch-mpv') {
|
||||
args.launchMpv = true;
|
||||
args.launchMpvTargets = argv.slice(i + 1).filter((value) => value && !value.startsWith('--'));
|
||||
break;
|
||||
@@ -334,6 +350,7 @@ export function hasExplicitCommand(args: CliArgs): boolean {
|
||||
return (
|
||||
args.background ||
|
||||
args.start ||
|
||||
Boolean(args.youtubePlay) ||
|
||||
args.launchMpv ||
|
||||
args.stop ||
|
||||
args.toggle ||
|
||||
@@ -385,6 +402,7 @@ export function shouldStartApp(args: CliArgs): boolean {
|
||||
if (
|
||||
args.background ||
|
||||
args.start ||
|
||||
Boolean(args.youtubePlay) ||
|
||||
args.launchMpv ||
|
||||
args.toggle ||
|
||||
args.toggleVisibleOverlay ||
|
||||
@@ -452,6 +470,7 @@ export function shouldRunSettingsOnlyStartup(args: CliArgs): boolean {
|
||||
!args.jellyfinItems &&
|
||||
!args.jellyfinSubtitles &&
|
||||
!args.jellyfinPlay &&
|
||||
!args.youtubePlay &&
|
||||
!args.jellyfinRemoteAnnounce &&
|
||||
!args.jellyfinPreviewAuth &&
|
||||
!args.texthooker &&
|
||||
@@ -481,5 +500,6 @@ export function commandNeedsOverlayRuntime(args: CliArgs): boolean {
|
||||
args.triggerSubsync ||
|
||||
args.markAudioCard ||
|
||||
args.openRuntimeOptions
|
||||
|| Boolean(args.youtubePlay)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ ${B}Session${R}
|
||||
--background Start in tray/background mode
|
||||
--start Connect to mpv and launch overlay
|
||||
--launch-mpv ${D}[targets...]${R} Launch mpv with the SubMiner mpv profile and exit
|
||||
--youtube-play ${D}URL${R} Open YouTube subtitle picker flow for a URL
|
||||
--youtube-mode ${D}download|generate${R} Subtitle acquisition mode for YouTube flow
|
||||
--stop Stop the running instance
|
||||
--stats Open the stats dashboard in your browser
|
||||
--texthooker Start texthooker server only ${D}(no overlay)${R}
|
||||
|
||||
@@ -36,7 +36,7 @@ const {
|
||||
} = CORE_DEFAULT_CONFIG;
|
||||
const { ankiConnect, jimaku, anilist, yomitan, jellyfin, discordPresence, ai, youtubeSubgen } =
|
||||
INTEGRATIONS_DEFAULT_CONFIG;
|
||||
const { subtitleStyle } = SUBTITLE_DEFAULT_CONFIG;
|
||||
const { subtitleStyle, subtitleSidebar } = SUBTITLE_DEFAULT_CONFIG;
|
||||
const { immersionTracking } = IMMERSION_DEFAULT_CONFIG;
|
||||
const { stats } = STATS_DEFAULT_CONFIG;
|
||||
|
||||
@@ -54,6 +54,7 @@ export const DEFAULT_CONFIG: ResolvedConfig = {
|
||||
subsync,
|
||||
startupWarmups,
|
||||
subtitleStyle,
|
||||
subtitleSidebar,
|
||||
auto_start_overlay,
|
||||
jimaku,
|
||||
anilist,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ResolvedConfig } from '../../types';
|
||||
|
||||
export const SUBTITLE_DEFAULT_CONFIG: Pick<ResolvedConfig, 'subtitleStyle'> = {
|
||||
export const SUBTITLE_DEFAULT_CONFIG: Pick<ResolvedConfig, 'subtitleStyle' | 'subtitleSidebar'> = {
|
||||
subtitleStyle: {
|
||||
enableJlpt: false,
|
||||
preserveLineBreaks: false,
|
||||
@@ -57,4 +57,22 @@ export const SUBTITLE_DEFAULT_CONFIG: Pick<ResolvedConfig, 'subtitleStyle'> = {
|
||||
fontStyle: 'normal',
|
||||
},
|
||||
},
|
||||
subtitleSidebar: {
|
||||
enabled: false,
|
||||
autoOpen: false,
|
||||
layout: 'overlay',
|
||||
toggleKey: 'Backslash',
|
||||
pauseVideoOnHover: false,
|
||||
autoScroll: true,
|
||||
maxWidth: 420,
|
||||
opacity: 0.95,
|
||||
backgroundColor: 'rgba(73, 77, 100, 0.9)',
|
||||
textColor: '#cad3f5',
|
||||
fontFamily: '"M PLUS 1", "Noto Sans CJK JP", sans-serif',
|
||||
fontSize: 16,
|
||||
timestampColor: '#a5adcb',
|
||||
activeLineColor: '#f5bde6',
|
||||
activeLineBackgroundColor: 'rgba(138, 173, 244, 0.22)',
|
||||
hoverLineBackgroundColor: 'rgba(54, 58, 79, 0.84)',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -110,5 +110,102 @@ export function buildSubtitleConfigOptionRegistry(
|
||||
description:
|
||||
'Five colors used for rank bands when mode is `banded` (from most common to least within topX).',
|
||||
},
|
||||
{
|
||||
path: 'subtitleSidebar.enabled',
|
||||
kind: 'boolean',
|
||||
defaultValue: defaultConfig.subtitleSidebar.enabled,
|
||||
description: 'Enable the subtitle sidebar feature for parsed subtitle sources.',
|
||||
},
|
||||
{
|
||||
path: 'subtitleSidebar.autoOpen',
|
||||
kind: 'boolean',
|
||||
defaultValue: defaultConfig.subtitleSidebar.autoOpen,
|
||||
description: 'Automatically open the subtitle sidebar once during overlay startup.',
|
||||
},
|
||||
{
|
||||
path: 'subtitleSidebar.layout',
|
||||
kind: 'enum',
|
||||
enumValues: ['overlay', 'embedded'],
|
||||
defaultValue: defaultConfig.subtitleSidebar.layout,
|
||||
description: 'Render the subtitle sidebar as a floating overlay or reserve space inside mpv.',
|
||||
},
|
||||
{
|
||||
path: 'subtitleSidebar.toggleKey',
|
||||
kind: 'string',
|
||||
defaultValue: defaultConfig.subtitleSidebar.toggleKey,
|
||||
description: 'KeyboardEvent.code used to toggle the subtitle sidebar open and closed.',
|
||||
},
|
||||
{
|
||||
path: 'subtitleSidebar.pauseVideoOnHover',
|
||||
kind: 'boolean',
|
||||
defaultValue: defaultConfig.subtitleSidebar.pauseVideoOnHover,
|
||||
description: 'Pause mpv while hovering the subtitle sidebar, then resume on leave.',
|
||||
},
|
||||
{
|
||||
path: 'subtitleSidebar.autoScroll',
|
||||
kind: 'boolean',
|
||||
defaultValue: defaultConfig.subtitleSidebar.autoScroll,
|
||||
description: 'Auto-scroll the active subtitle cue into view while playback advances.',
|
||||
},
|
||||
{
|
||||
path: 'subtitleSidebar.maxWidth',
|
||||
kind: 'number',
|
||||
defaultValue: defaultConfig.subtitleSidebar.maxWidth,
|
||||
description: 'Maximum sidebar width in CSS pixels.',
|
||||
},
|
||||
{
|
||||
path: 'subtitleSidebar.opacity',
|
||||
kind: 'number',
|
||||
defaultValue: defaultConfig.subtitleSidebar.opacity,
|
||||
description: 'Base opacity applied to the sidebar shell.',
|
||||
},
|
||||
{
|
||||
path: 'subtitleSidebar.backgroundColor',
|
||||
kind: 'string',
|
||||
defaultValue: defaultConfig.subtitleSidebar.backgroundColor,
|
||||
description: 'Background color for the subtitle sidebar shell.',
|
||||
},
|
||||
{
|
||||
path: 'subtitleSidebar.textColor',
|
||||
kind: 'string',
|
||||
defaultValue: defaultConfig.subtitleSidebar.textColor,
|
||||
description: 'Default cue text color in the subtitle sidebar.',
|
||||
},
|
||||
{
|
||||
path: 'subtitleSidebar.fontFamily',
|
||||
kind: 'string',
|
||||
defaultValue: defaultConfig.subtitleSidebar.fontFamily,
|
||||
description: 'Font family used for subtitle sidebar cue text.',
|
||||
},
|
||||
{
|
||||
path: 'subtitleSidebar.fontSize',
|
||||
kind: 'number',
|
||||
defaultValue: defaultConfig.subtitleSidebar.fontSize,
|
||||
description: 'Base font size for subtitle sidebar cue text in CSS pixels.',
|
||||
},
|
||||
{
|
||||
path: 'subtitleSidebar.timestampColor',
|
||||
kind: 'string',
|
||||
defaultValue: defaultConfig.subtitleSidebar.timestampColor,
|
||||
description: 'Timestamp color in the subtitle sidebar.',
|
||||
},
|
||||
{
|
||||
path: 'subtitleSidebar.activeLineColor',
|
||||
kind: 'string',
|
||||
defaultValue: defaultConfig.subtitleSidebar.activeLineColor,
|
||||
description: 'Text color for the active subtitle cue.',
|
||||
},
|
||||
{
|
||||
path: 'subtitleSidebar.activeLineBackgroundColor',
|
||||
kind: 'string',
|
||||
defaultValue: defaultConfig.subtitleSidebar.activeLineBackgroundColor,
|
||||
description: 'Background color for the active subtitle cue.',
|
||||
},
|
||||
{
|
||||
path: 'subtitleSidebar.hoverLineBackgroundColor',
|
||||
kind: 'string',
|
||||
defaultValue: defaultConfig.subtitleSidebar.hoverLineBackgroundColor,
|
||||
description: 'Background color for hovered subtitle cues.',
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user