diff --git a/.github/workflows/package-release.yml b/.github/workflows/package-release.yml
new file mode 100644
index 00000000..b3ce8b14
--- /dev/null
+++ b/.github/workflows/package-release.yml
@@ -0,0 +1,266 @@
+name: Package release
+
+on:
+ workflow_call:
+ secrets:
+ CSC_LINK:
+ required: true
+ CSC_KEY_PASSWORD:
+ required: true
+ APPLE_ID:
+ required: true
+ APPLE_APP_SPECIFIC_PASSWORD:
+ required: true
+ APPLE_TEAM_ID:
+ required: true
+
+permissions:
+ contents: read
+
+jobs:
+ build-linux:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ submodules: true
+ persist-credentials: false
+
+ - name: Setup Bun
+ uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: 1.3.5
+
+ - name: Cache dependencies
+ uses: actions/cache@v4
+ with:
+ path: |
+ ~/.bun/install/cache
+ node_modules
+ stats/node_modules
+ vendor/texthooker-ui/node_modules
+ vendor/subminer-yomitan/node_modules
+ key: ${{ runner.os }}-${{ runner.arch }}-bun-${{ hashFiles('bun.lock', 'stats/bun.lock', 'vendor/texthooker-ui/bun.lock', 'vendor/subminer-yomitan/package-lock.json') }}
+ restore-keys: |
+ ${{ runner.os }}-${{ runner.arch }}-bun-
+
+ - name: Install dependencies
+ run: |
+ bun install --frozen-lockfile
+ cd stats && bun install --frozen-lockfile
+
+ - name: Build texthooker-ui
+ run: |
+ cd vendor/texthooker-ui
+ bun install --frozen-lockfile
+ bun run build
+
+ - name: Download previous package size reports
+ shell: bash
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: |
+ mkdir -p .tmp/package-baseline
+ previous=$(gh api "repos/$GITHUB_REPOSITORY/releases" --jq '[.[] | select(.draft == false and .tag_name != env.GITHUB_REF_NAME)] | sort_by(.published_at) | last | .tag_name // empty')
+ if [ -n "$previous" ]; then
+ gh release download "$previous" --pattern 'package-size-*.json' --dir .tmp/package-baseline || echo 'Previous release has no package size reports; size comparison will be skipped.'
+ fi
+
+ - name: Build AppImage
+ run: bun run build:appimage
+
+ - name: Build unversioned AppImage
+ run: |
+ shopt -s nullglob
+ appimages=(release/SubMiner-*.AppImage)
+ if [ "${#appimages[@]}" -eq 0 ]; then
+ echo "No versioned AppImage found to create unversioned artifact."
+ ls -la release
+ exit 1
+ fi
+ cp "${appimages[0]}" release/SubMiner.AppImage
+
+ - name: Smoke packaged runtime assets
+ shell: bash
+ run: xvfb-run -a bun run test:package "release/linux-unpacked/resources"
+
+ - name: Upload AppImage artifact
+ uses: actions/upload-artifact@v4
+ with:
+ name: appimage
+ path: |
+ release/*.AppImage
+ release/latest*.yml
+ release/*.blockmap
+ release/package-size-*.json
+ if-no-files-found: error
+
+ build-macos:
+ runs-on: macos-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ submodules: true
+ persist-credentials: false
+
+ - name: Setup Bun
+ uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: 1.3.5
+
+ - name: Cache dependencies
+ uses: actions/cache@v4
+ with:
+ path: |
+ ~/.bun/install/cache
+ node_modules
+ stats/node_modules
+ vendor/texthooker-ui/node_modules
+ vendor/subminer-yomitan/node_modules
+ key: ${{ runner.os }}-${{ runner.arch }}-bun-${{ hashFiles('bun.lock', 'stats/bun.lock', 'vendor/texthooker-ui/bun.lock', 'vendor/subminer-yomitan/package-lock.json') }}
+ restore-keys: |
+ ${{ runner.os }}-${{ runner.arch }}-bun-
+
+ - name: Validate macOS signing/notarization secrets
+ run: |
+ missing=0
+ for name in CSC_LINK CSC_KEY_PASSWORD APPLE_ID APPLE_APP_SPECIFIC_PASSWORD APPLE_TEAM_ID; do
+ if [ -z "${!name}" ]; then
+ echo "Missing required secret: $name"
+ missing=1
+ fi
+ done
+ if [ "$missing" -ne 0 ]; then
+ echo "Set all required macOS signing/notarization secrets and rerun."
+ exit 1
+ fi
+ env:
+ CSC_LINK: ${{ secrets.CSC_LINK }}
+ CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
+ APPLE_ID: ${{ secrets.APPLE_ID }}
+ APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+
+ - name: Install dependencies
+ run: |
+ bun install --frozen-lockfile
+ cd stats && bun install --frozen-lockfile
+
+ - name: Build texthooker-ui
+ run: |
+ cd vendor/texthooker-ui
+ bun install --frozen-lockfile
+ bun run build
+
+ - name: Download previous package size reports
+ shell: bash
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: |
+ mkdir -p .tmp/package-baseline
+ previous=$(gh api "repos/$GITHUB_REPOSITORY/releases" --jq '[.[] | select(.draft == false and .tag_name != env.GITHUB_REF_NAME)] | sort_by(.published_at) | last | .tag_name // empty')
+ if [ -n "$previous" ]; then
+ gh release download "$previous" --pattern 'package-size-*.json' --dir .tmp/package-baseline || echo 'Previous release has no package size reports; size comparison will be skipped.'
+ fi
+
+ - name: Build signed + notarized macOS artifacts
+ run: bun run build:mac
+ env:
+ CSC_LINK: ${{ secrets.CSC_LINK }}
+ CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
+ APPLE_ID: ${{ secrets.APPLE_ID }}
+ APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+
+ - name: Smoke packaged runtime assets
+ shell: bash
+ run: bun run test:package "release/mac-arm64/SubMiner.app/Contents/Resources"
+
+ - name: Upload macOS artifacts
+ uses: actions/upload-artifact@v4
+ with:
+ name: macos
+ path: |
+ release/*.dmg
+ release/*.zip
+ release/latest*.yml
+ release/*.blockmap
+ release/package-size-*.json
+ if-no-files-found: error
+
+ build-windows:
+ runs-on: windows-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ submodules: true
+ persist-credentials: false
+
+ - name: Setup Bun
+ uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: 1.3.5
+
+ - name: Cache dependencies
+ uses: actions/cache@v4
+ with:
+ path: |
+ ~/.bun/install/cache
+ node_modules
+ stats/node_modules
+ vendor/texthooker-ui/node_modules
+ vendor/subminer-yomitan/node_modules
+ key: ${{ runner.os }}-${{ runner.arch }}-bun-${{ hashFiles('bun.lock', 'stats/bun.lock', 'vendor/texthooker-ui/bun.lock', 'vendor/subminer-yomitan/package-lock.json') }}
+ restore-keys: |
+ ${{ runner.os }}-${{ runner.arch }}-bun-
+
+ - name: Install dependencies
+ run: |
+ bun install --frozen-lockfile
+ cd stats && bun install --frozen-lockfile
+
+ - name: Build texthooker-ui
+ shell: powershell
+ run: |
+ Set-Location vendor/texthooker-ui
+ bun install --frozen-lockfile
+ bun run build
+
+ - name: Download previous package size reports
+ shell: bash
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: |
+ mkdir -p .tmp/package-baseline
+ previous=$(gh api "repos/$GITHUB_REPOSITORY/releases" --jq '[.[] | select(.draft == false and .tag_name != env.GITHUB_REF_NAME)] | sort_by(.published_at) | last | .tag_name // empty')
+ if [ -n "$previous" ]; then
+ gh release download "$previous" --pattern 'package-size-*.json' --dir .tmp/package-baseline || echo 'Previous release has no package size reports; size comparison will be skipped.'
+ fi
+
+ - name: Verify managed Windows launcher
+ run: bun test src/main/runtime/managed-launcher.test.ts
+
+ - name: Verify Windows launcher bootstrap
+ run: bun test src/main/runtime/windows-launcher-bootstrap.test.ts
+
+ - name: Build unsigned Windows artifacts
+ run: bun run build:win:unsigned
+
+ - name: Smoke packaged runtime assets
+ shell: bash
+ run: bun run test:package "release/win-unpacked/resources"
+
+ - name: Upload Windows artifacts
+ uses: actions/upload-artifact@v4
+ with:
+ name: windows
+ path: |
+ release/*.exe
+ release/*.zip
+ release/latest*.yml
+ release/*.blockmap
+ release/package-size-*.json
+ if-no-files-found: error
diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml
index 759456e4..485a83d3 100644
--- a/.github/workflows/prerelease.yml
+++ b/.github/workflows/prerelease.yml
@@ -16,201 +16,20 @@ jobs:
contents: read
uses: ./.github/workflows/quality-gate.yml
- build-linux:
+ package:
needs: [quality-gate]
- runs-on: ubuntu-latest
- steps:
- - name: Checkout
- uses: actions/checkout@v4
- with:
- submodules: true
-
- - name: Setup Bun
- uses: oven-sh/setup-bun@v2
- with:
- bun-version: 1.3.5
-
- - name: Cache dependencies
- uses: actions/cache@v4
- with:
- path: |
- ~/.bun/install/cache
- node_modules
- stats/node_modules
- vendor/texthooker-ui/node_modules
- vendor/subminer-yomitan/node_modules
- key: ${{ runner.os }}-${{ runner.arch }}-bun-${{ hashFiles('bun.lock', 'stats/bun.lock', 'vendor/texthooker-ui/package.json', 'vendor/subminer-yomitan/package-lock.json') }}
- restore-keys: |
- ${{ runner.os }}-${{ runner.arch }}-bun-
-
- - name: Install dependencies
- run: |
- bun install --frozen-lockfile
- cd stats && bun install --frozen-lockfile
-
- - name: Build texthooker-ui
- run: |
- cd vendor/texthooker-ui
- bun install
- bun run build
-
- - name: Build AppImage
- run: bun run build:appimage
-
- - name: Build unversioned AppImage
- run: |
- shopt -s nullglob
- appimages=(release/SubMiner-*.AppImage)
- if [ "${#appimages[@]}" -eq 0 ]; then
- echo "No versioned AppImage found to create unversioned artifact."
- ls -la release
- exit 1
- fi
- cp "${appimages[0]}" release/SubMiner.AppImage
-
- - name: Upload AppImage artifact
- uses: actions/upload-artifact@v4
- with:
- name: appimage
- path: |
- release/*.AppImage
- release/latest*.yml
- release/*.blockmap
- if-no-files-found: error
-
- build-macos:
- needs: [quality-gate]
- runs-on: macos-latest
- steps:
- - name: Checkout
- uses: actions/checkout@v4
- with:
- submodules: true
-
- - name: Setup Bun
- uses: oven-sh/setup-bun@v2
- with:
- bun-version: 1.3.5
-
- - name: Cache dependencies
- uses: actions/cache@v4
- with:
- path: |
- ~/.bun/install/cache
- node_modules
- stats/node_modules
- vendor/texthooker-ui/node_modules
- vendor/subminer-yomitan/node_modules
- key: ${{ runner.os }}-${{ runner.arch }}-bun-${{ hashFiles('bun.lock', 'stats/bun.lock', 'vendor/texthooker-ui/package.json', 'vendor/subminer-yomitan/package-lock.json') }}
- restore-keys: |
- ${{ runner.os }}-${{ runner.arch }}-bun-
-
- - name: Validate macOS signing/notarization secrets
- run: |
- missing=0
- for name in CSC_LINK CSC_KEY_PASSWORD APPLE_ID APPLE_APP_SPECIFIC_PASSWORD APPLE_TEAM_ID; do
- if [ -z "${!name}" ]; then
- echo "Missing required secret: $name"
- missing=1
- fi
- done
- if [ "$missing" -ne 0 ]; then
- echo "Set all required macOS signing/notarization secrets and rerun."
- exit 1
- fi
- env:
- CSC_LINK: ${{ secrets.CSC_LINK }}
- CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
- APPLE_ID: ${{ secrets.APPLE_ID }}
- APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
- APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
-
- - name: Install dependencies
- run: |
- bun install --frozen-lockfile
- cd stats && bun install --frozen-lockfile
-
- - name: Build texthooker-ui
- run: |
- cd vendor/texthooker-ui
- bun install
- bun run build
-
- - name: Build signed + notarized macOS artifacts
- run: bun run build:mac
- env:
- CSC_LINK: ${{ secrets.CSC_LINK }}
- CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
- APPLE_ID: ${{ secrets.APPLE_ID }}
- APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
- APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
-
- - name: Upload macOS artifacts
- uses: actions/upload-artifact@v4
- with:
- name: macos
- path: |
- release/*.dmg
- release/*.zip
- release/latest*.yml
- release/*.blockmap
- if-no-files-found: error
-
- build-windows:
- needs: [quality-gate]
- runs-on: windows-latest
- steps:
- - name: Checkout
- uses: actions/checkout@v4
- with:
- submodules: true
-
- - name: Setup Bun
- uses: oven-sh/setup-bun@v2
- with:
- bun-version: 1.3.5
-
- - name: Cache dependencies
- uses: actions/cache@v4
- with:
- path: |
- ~/.bun/install/cache
- node_modules
- stats/node_modules
- vendor/texthooker-ui/node_modules
- vendor/subminer-yomitan/node_modules
- key: ${{ runner.os }}-${{ runner.arch }}-bun-${{ hashFiles('bun.lock', 'stats/bun.lock', 'vendor/texthooker-ui/package.json', 'vendor/subminer-yomitan/package-lock.json') }}
- restore-keys: |
- ${{ runner.os }}-${{ runner.arch }}-bun-
-
- - name: Install dependencies
- run: |
- bun install --frozen-lockfile
- cd stats && bun install --frozen-lockfile
-
- - name: Build texthooker-ui
- shell: powershell
- run: |
- Set-Location vendor/texthooker-ui
- bun install
- bun run build
-
- - name: Build unsigned Windows artifacts
- run: bun run build:win:unsigned
-
- - name: Upload Windows artifacts
- uses: actions/upload-artifact@v4
- with:
- name: windows
- path: |
- release/*.exe
- release/*.zip
- release/latest*.yml
- release/*.blockmap
- if-no-files-found: error
+ permissions:
+ contents: read
+ uses: ./.github/workflows/package-release.yml
+ secrets:
+ CSC_LINK: ${{ secrets.CSC_LINK }}
+ CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
+ APPLE_ID: ${{ secrets.APPLE_ID }}
+ APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
release:
- needs: [build-linux, build-macos, build-windows]
+ needs: [package]
runs-on: ubuntu-latest
permissions:
contents: write
@@ -256,11 +75,11 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- - name: Build Bun subminer wrapper
+ - name: Build launcher runtime artifacts
run: make build-launcher
- - name: Verify Bun subminer wrapper
- run: dist/launcher/subminer --help >/dev/null
+ - name: Smoke launcher bundle
+ run: bun dist/launcher/subminer.js --help >/dev/null
- name: Enforce generated launcher workflow
run: bash scripts/verify-generated-launcher.sh
@@ -275,12 +94,17 @@ jobs:
plugin/subminer \
plugin/subminer.conf \
assets/themes/subminer.rasi \
- assets/thumbnailers/subminer-ffmpegthumbnailer.thumbnailer
+ assets/thumbnailers/subminer-ffmpegthumbnailer.thumbnailer \
+ resources/bun/licenses
+
+ - name: Package Bun corresponding source
+ run: bun scripts/package-bun-source.mjs
- name: Generate checksums
run: |
shopt -s nullglob
- files=(release/*.AppImage release/*.dmg release/*.exe release/*.zip release/*.tar.gz release/latest*.yml release/*.blockmap dist/launcher/subminer)
+ files=(release/*.AppImage release/*.dmg release/*.exe release/*.zip release/*.tar.gz release/latest*.yml release/*.blockmap dist/launcher/subminer dist/launcher/subminer.cmd)
+ files+=(release/package-size-*.json)
if [ "${#files[@]}" -eq 0 ]; then
echo "No release artifacts found for checksum generation."
exit 1
@@ -323,10 +147,13 @@ jobs:
release/*.exe
release/*.zip
release/*.tar.gz
+ release/*.tar.gz.sha256
release/latest*.yml
release/*.blockmap
release/SHA256SUMS.txt
+ release/package-size-*.json
dist/launcher/subminer
+ dist/launcher/subminer.cmd
)
if [ "${#artifacts[@]}" -eq 0 ]; then
diff --git a/.github/workflows/quality-gate.yml b/.github/workflows/quality-gate.yml
index bb5c0d1d..50c69c3e 100644
--- a/.github/workflows/quality-gate.yml
+++ b/.github/workflows/quality-gate.yml
@@ -7,6 +7,31 @@ permissions:
contents: read
jobs:
+ launcher-runtime:
+ strategy:
+ matrix:
+ os: [windows-latest, macos-latest]
+ runs-on: ${{ matrix.os }}
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ persist-credentials: false
+
+ - name: Setup Bun
+ uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: 1.3.5
+
+ - name: Verify native runtime staging
+ run: bun test src/main/runtime/managed-launcher.test.ts
+
+ - name: Verify Windows launcher bootstrap
+ run: bun test src/main/runtime/windows-launcher-bootstrap.test.ts
+
+ - name: Verify POSIX launcher bootstrap
+ run: bun test src/main/runtime/posix-launcher-bootstrap.test.ts
+
quality-gate:
runs-on: ubuntu-latest
steps:
@@ -60,8 +85,11 @@ jobs:
- name: Install Lua
run: |
- sudo apt-get update
- sudo apt-get install -y lua5.4
+ # Lua needs only Ubuntu sources; unrelated runner repositories can be unavailable.
+ test -f /etc/apt/sources.list.d/ubuntu.sources
+ apt_sources=(-o Dir::Etc::sourcelist=sources.list.d/ubuntu.sources -o Dir::Etc::sourceparts=-)
+ sudo apt-get "${apt_sources[@]}" update
+ sudo apt-get "${apt_sources[@]}" install -y lua5.4
sudo ln -sf /usr/bin/lua5.4 /usr/local/bin/lua
lua -v
@@ -107,11 +135,11 @@ jobs:
- name: Security audit
run: bun audit --audit-level high
- - name: Build Bun subminer wrapper
+ - name: Build launcher runtime artifacts
run: make build-launcher
- - name: Verify Bun subminer wrapper
- run: dist/launcher/subminer --help >/dev/null
+ - name: Smoke launcher bundle
+ run: bun dist/launcher/subminer.js --help >/dev/null
- name: Enforce generated launcher workflow
run: bash scripts/verify-generated-launcher.sh
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 86ba2ce7..09a1cd57 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -17,199 +17,20 @@ jobs:
contents: read
uses: ./.github/workflows/quality-gate.yml
- build-linux:
+ package:
needs: [quality-gate]
- runs-on: ubuntu-latest
- steps:
- - name: Checkout
- uses: actions/checkout@v4
- with:
- submodules: true
-
- - name: Setup Bun
- uses: oven-sh/setup-bun@v2
- with:
- bun-version: 1.3.5
-
- - name: Cache dependencies
- uses: actions/cache@v4
- with:
- path: |
- ~/.bun/install/cache
- node_modules
- stats/node_modules
- vendor/texthooker-ui/node_modules
- vendor/subminer-yomitan/node_modules
- key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock', 'stats/bun.lock', 'vendor/texthooker-ui/package.json', 'vendor/subminer-yomitan/package-lock.json') }}
- restore-keys: |
- ${{ runner.os }}-bun-
-
- - name: Install dependencies
- run: |
- bun install --frozen-lockfile
- cd stats && bun install --frozen-lockfile
-
- - name: Build texthooker-ui
- run: |
- cd vendor/texthooker-ui
- bun install
- bun run build
-
- - name: Build AppImage
- run: bun run build:appimage
-
- - name: Build unversioned AppImage
- run: |
- shopt -s nullglob
- appimages=(release/SubMiner-*.AppImage)
- if [ "${#appimages[@]}" -eq 0 ]; then
- echo "No versioned AppImage found to create unversioned artifact."
- ls -la release
- exit 1
- fi
- cp "${appimages[0]}" release/SubMiner.AppImage
-
- - name: Upload AppImage artifact
- uses: actions/upload-artifact@v4
- with:
- name: appimage
- path: |
- release/*.AppImage
- release/latest*.yml
- release/*.blockmap
-
- build-macos:
- needs: [quality-gate]
- runs-on: macos-latest
- steps:
- - name: Checkout
- uses: actions/checkout@v4
- with:
- submodules: true
-
- - name: Setup Bun
- uses: oven-sh/setup-bun@v2
- with:
- bun-version: 1.3.5
-
- - name: Cache dependencies
- uses: actions/cache@v4
- with:
- path: |
- ~/.bun/install/cache
- node_modules
- stats/node_modules
- vendor/texthooker-ui/node_modules
- vendor/subminer-yomitan/node_modules
- key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock', 'stats/bun.lock', 'vendor/texthooker-ui/package.json', 'vendor/subminer-yomitan/package-lock.json') }}
- restore-keys: |
- ${{ runner.os }}-bun-
-
- - name: Validate macOS signing/notarization secrets
- run: |
- missing=0
- for name in CSC_LINK CSC_KEY_PASSWORD APPLE_ID APPLE_APP_SPECIFIC_PASSWORD APPLE_TEAM_ID; do
- if [ -z "${!name}" ]; then
- echo "Missing required secret: $name"
- missing=1
- fi
- done
- if [ "$missing" -ne 0 ]; then
- echo "Set all required macOS signing/notarization secrets and rerun."
- exit 1
- fi
- env:
- CSC_LINK: ${{ secrets.CSC_LINK }}
- CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
- APPLE_ID: ${{ secrets.APPLE_ID }}
- APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
- APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
-
- - name: Install dependencies
- run: |
- bun install --frozen-lockfile
- cd stats && bun install --frozen-lockfile
-
- - name: Build texthooker-ui
- run: |
- cd vendor/texthooker-ui
- bun install
- bun run build
-
- - name: Build signed + notarized macOS artifacts
- run: bun run build:mac
- env:
- CSC_LINK: ${{ secrets.CSC_LINK }}
- CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
- APPLE_ID: ${{ secrets.APPLE_ID }}
- APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
- APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
-
- - name: Upload macOS artifacts
- uses: actions/upload-artifact@v4
- with:
- name: macos
- path: |
- release/*.dmg
- release/*.zip
- release/latest*.yml
- release/*.blockmap
-
- build-windows:
- needs: [quality-gate]
- runs-on: windows-latest
- steps:
- - name: Checkout
- uses: actions/checkout@v4
- with:
- submodules: true
-
- - name: Setup Bun
- uses: oven-sh/setup-bun@v2
- with:
- bun-version: 1.3.5
-
- - name: Cache dependencies
- uses: actions/cache@v4
- with:
- path: |
- ~/.bun/install/cache
- node_modules
- stats/node_modules
- vendor/texthooker-ui/node_modules
- vendor/subminer-yomitan/node_modules
- key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock', 'stats/bun.lock', 'vendor/texthooker-ui/package.json', 'vendor/subminer-yomitan/package-lock.json') }}
- restore-keys: |
- ${{ runner.os }}-bun-
-
- - name: Install dependencies
- run: |
- bun install --frozen-lockfile
- cd stats && bun install --frozen-lockfile
-
- - name: Build texthooker-ui
- shell: powershell
- run: |
- Set-Location vendor/texthooker-ui
- bun install
- bun run build
-
- - name: Build unsigned Windows artifacts
- run: bun run build:win:unsigned
-
- - name: Upload Windows artifacts
- uses: actions/upload-artifact@v4
- with:
- name: windows
- path: |
- release/*.exe
- release/*.zip
- release/latest*.yml
- release/*.blockmap
- if-no-files-found: error
+ permissions:
+ contents: read
+ uses: ./.github/workflows/package-release.yml
+ secrets:
+ CSC_LINK: ${{ secrets.CSC_LINK }}
+ CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
+ APPLE_ID: ${{ secrets.APPLE_ID }}
+ APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
release:
- needs: [build-linux, build-macos, build-windows]
+ needs: [package]
runs-on: ubuntu-latest
permissions:
contents: write
@@ -255,11 +76,11 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- - name: Build Bun subminer wrapper
+ - name: Build launcher runtime artifacts
run: make build-launcher
- - name: Verify Bun subminer wrapper
- run: dist/launcher/subminer --help >/dev/null
+ - name: Smoke launcher bundle
+ run: bun dist/launcher/subminer.js --help >/dev/null
- name: Enforce generated launcher workflow
run: bash scripts/verify-generated-launcher.sh
@@ -274,12 +95,17 @@ jobs:
plugin/subminer \
plugin/subminer.conf \
assets/themes/subminer.rasi \
- assets/thumbnailers/subminer-ffmpegthumbnailer.thumbnailer
+ assets/thumbnailers/subminer-ffmpegthumbnailer.thumbnailer \
+ resources/bun/licenses
+
+ - name: Package Bun corresponding source
+ run: bun scripts/package-bun-source.mjs
- name: Generate checksums
run: |
shopt -s nullglob
- files=(release/*.AppImage release/*.dmg release/*.exe release/*.zip release/*.tar.gz release/latest*.yml release/*.blockmap dist/launcher/subminer)
+ files=(release/*.AppImage release/*.dmg release/*.exe release/*.zip release/*.tar.gz release/latest*.yml release/*.blockmap dist/launcher/subminer dist/launcher/subminer.cmd)
+ files+=(release/package-size-*.json)
if [ "${#files[@]}" -eq 0 ]; then
echo "No release artifacts found for checksum generation."
exit 1
@@ -340,10 +166,13 @@ jobs:
release/*.exe
release/*.zip
release/*.tar.gz
+ release/*.tar.gz.sha256
release/latest*.yml
release/*.blockmap
release/SHA256SUMS.txt
+ release/package-size-*.json
dist/launcher/subminer
+ dist/launcher/subminer.cmd
)
if [ "${#artifacts[@]}" -eq 0 ]; then
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 293fb563..84b75bec 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,36 @@
# Changelog
+## v0.19.6 (2026-09-04)
+
+### Added
+
+- **Card Timing Review**:
+ - Optional pre-generation timing review for word, sentence, and audio cards, with a speech-weighted waveform that flattens background noise so dialogue edges stand out clearly.
+ - The clip end automatically snaps back to where the line's dialogue actually ends once the waveform loads, with drag and keyboard adjustments available.
+ - Audio preview includes a sweeping playhead that plays the clip to its true end, even on high-latency outputs like Bluetooth headphones.
+ - Previous and next subtitle lines can be pulled onto the card with `P`/`N` (or the Prev/Next steppers) and removed with Shift; the sentence preview and waveform markers update automatically.
+ - Cancelling lets you keep a card without media, and the review can be toggled on or off for the session.
+- **Senren Field Grouping**:
+ - Enable `ankiConnect.isSenren` to merge duplicate mined cards using Senren's scene-switching markup, grouping sentence, furigana, audio, picture, and misc-info fields.
+ - Supports the same auto/manual/disabled modes as Kiku, including the manual merge modal; only one of Senren or Kiku can be enabled at a time.
+
+### Changed
+
+- **Remote Stream Mining Performance**: Mining a card from a remote stream (Jellyfin and other HTTP sources) now downloads the clip window once and reuses it for the timing review waveform, audio preview, audio extraction, and screenshot, instead of re-fetching the stream at each step; the temporary file is cleaned up after ten minutes of inactivity or on exit.
+- **TsukiHime Release Filtering**: The TsukiHime modal's Japanese and secondary-language tabs now filter the release list by the subtitle languages each release actually carries, and report when no release has subtitles for the active tab.
+
+### Fixed
+
+- **Subtitle & Mining Accuracy**:
+ - Broadcast-style captions that split one sentence across two on-screen rows (e.g. Crunchyroll Japanese subs) now merge into a single line for the sidebar and mined cards, while separate speakers, sound effects, and labeled turns still stay on their own lines.
+ - Mining from the overlay no longer pulls in a lingering row from the previous caption; the mined sentence and clip timing now match what's actually on screen.
+ - Multi-line copy and mining now select lines backward in timeline order after seeking, instead of in playback encounter order.
+ - Copying a subtitle, mining a sentence, or recording immersion stats no longer includes the separate furigana line that broadcast ASS captions place above a word.
+- **Card Update Notifications**: Dismissed lingering overlay card-update progress when notification settings switch to OSD before an update finishes.
+- **Overlay Stability on Hyprland**: Opening a modal window (timing review, Jimaku, session help, and others) while mpv is fullscreen no longer causes the overlay to flicker while the modal loads; the overlay now stays on screen untouched until the modal is ready.
+- **Jellyfin Subtitle Sync**: Jellyfin subtitle files now load with zero mpv delay instead of inferring and saving an offset from Japanese and English cue timelines.
+- **Secondary Subtitle Visibility**: Native mpv secondary subtitles stay hidden when switching secondary subtitle tracks during playback.
+
## v0.19.5 (2026-08-30)
### Fixed
diff --git a/Makefile b/Makefile
index 09533805..59adc5e3 100644
--- a/Makefile
+++ b/Makefile
@@ -160,14 +160,8 @@ build-macos-unsigned: deps
@bun run build:mac:unsigned
build-launcher:
- @printf '%s\n' "[INFO] Bundling launcher script"
- @install -d "$(dir $(LAUNCHER_OUT))"
- @bun build ./launcher/main.ts --target=bun --packages=bundle --outfile="$(LAUNCHER_OUT)"
- @if ! head -1 "$(LAUNCHER_OUT)" | grep -q '^#!/usr/bin/env bun'; then \
- { printf '#!/usr/bin/env bun\n'; cat "$(LAUNCHER_OUT)"; } > "$(LAUNCHER_OUT).tmp" && mv "$(LAUNCHER_OUT).tmp" "$(LAUNCHER_OUT)"; \
- fi
- @chmod +x "$(LAUNCHER_OUT)"
- @printf '%s\n' "[INFO] Launcher artifact: $(LAUNCHER_OUT)"
+ @printf '%s\n' "[INFO] Building launcher runtime artifacts"
+ @bun run build:launcher
clean:
@printf '%s\n' "[INFO] Removing build artifacts"
diff --git a/README.md b/README.md
index 35bd811c..0a05f018 100644
--- a/README.md
+++ b/README.md
@@ -94,6 +94,10 @@ Browse sibling episode files and the active mpv queue in one overlay modal. Open
Jimaku
Search and download Japanese subtitles
+
+
Local Subtitle Generation
+
Generate Japanese subtitles from local audio in a standalone modal (Ctrl+Shift+G), the sidebar button, or launcher, with progress and optional managed model downloads. Requires whisper.cpp and FFmpeg. Optional Silero speech detection prioritizes dialogue in separately timed passages. Setup guide
+
TsukiHime
Search and download subtitles extracted from anime releases, with Japanese and secondary-language tabs (Ctrl+Shift+T) — no API key, requires xz on your PATH
@@ -197,7 +201,9 @@ wget https://github.com/ksyasuda/SubMiner/releases/latest/download/SubMiner.AppI
&& chmod +x ~/.local/bin/SubMiner.AppImage
```
-The AppImage is all you need. The optional `subminer` command-line launcher runs on [Bun](https://bun.sh), and first-run setup can install both for you. To grab it manually instead, install Bun first, then:
+The AppImage is all you need. First-run setup can install the optional `subminer` command-line launcher. Every current launcher uses Bun included with the app, so you do not need Bun installed or on `PATH`.
+
+You can also download the launcher wrapper directly:
```bash
wget https://github.com/ksyasuda/SubMiner/releases/latest/download/subminer -O ~/.local/bin/subminer \
@@ -218,6 +224,8 @@ Download the latest DMG from [GitHub Releases](https://github.com/ksyasuda/SubMi
Download and run the latest installer (`.exe`) from [GitHub Releases](https://github.com/ksyasuda/SubMiner/releases/latest).
+For terminal use, download `subminer.cmd`. It locates the installed app and uses its private Bun runtime.
+
@@ -229,14 +237,14 @@ See the [build-from-source guide](https://docs.subminer.moe/installation#from-so
### 2. Launch & Set Up
-Run SubMiner and the first-run setup wizard will guide you through importing Yomitan dictionaries and optionally installing the `subminer` command-line launcher.
+Run the installed app and the first-run setup wizard will guide you through importing Yomitan dictionaries and optionally installing the `subminer` command-line launcher. Setup records a custom app location when needed, and the wrapper runs with the app's private Bun runtime.
```bash
# Linux
-subminer app --setup
+~/.local/bin/SubMiner.AppImage --setup
-# macOS — open SubMiner.app, or:
-subminer app --setup
+# macOS
+open -a SubMiner --args --setup
```
On **Windows**, just run `SubMiner.exe` and the setup will open automatically on first launch.
@@ -269,6 +277,7 @@ SubMiner builds on the work of these open-source projects:
| [Aniyomi](https://github.com/aniyomiorg/aniyomi) | Anime extension API and data model the anime browser targets |
| [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 |
+| [Bun](https://github.com/oven-sh/bun) | Bundled runtime for the `subminer` command-line launcher |
| [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 |
@@ -287,3 +296,5 @@ downloaded from its upstream releases at runtime rather than
bundled or redistributed here; its bundles carry their own dependencies, including a JRE and
GPL-3.0 NewPipe Extractor. SubMiner includes none of them and talks to the bridge
over its own HTTP protocol. It ships no extensions or repositories by default.
+
+Release packages also bundle an unmodified copy of [Bun](https://github.com/oven-sh/bun), which is MIT licensed and statically links JavaScriptCore (LGPL 2.0) and TinyCC (LGPL 2.1). Its license texts and third-party notices ship inside the app under `resources/bun/licenses`, and each release publishes `bun-v1.3.5-source.tar.gz` with the corresponding source. See [Bundled Bun runtime](https://docs.subminer.moe/installation#bundled-bun-runtime).
diff --git a/build/bun-runtime-manifest.json b/build/bun-runtime-manifest.json
new file mode 100644
index 00000000..e0dcd726
--- /dev/null
+++ b/build/bun-runtime-manifest.json
@@ -0,0 +1,31 @@
+{
+ "schemaVersion": 1,
+ "version": "1.3.5",
+ "bunRevision": "1e86cebd74a5723e818b5c0555276b646bcf0e4c",
+ "releaseTagCommit": "fa5a5bbe556a4bda5bde77b4013aa6c3bb4ec9ab",
+ "artifacts": {
+ "darwin-arm64": {
+ "file": "bun-darwin-aarch64.zip",
+ "sha256": "db17588a4aea8804856825d4bead3f05e1f37276ca606f37e369b4f72f35d3fb"
+ },
+ "darwin-x64": {
+ "file": "bun-darwin-x64-baseline.zip",
+ "sha256": "34b9a56b851058dafa1bc9d61233f2c383aa996889bba30b3180f5ccc2cff1b2"
+ },
+ "linux-arm64": {
+ "file": "bun-linux-aarch64.zip",
+ "sha256": "ed01000f85bd97785228ad2845dc92a1860b8054856826d7317690ac8f8ee74b"
+ },
+ "linux-x64": {
+ "file": "bun-linux-x64-baseline.zip",
+ "sha256": "6bddacd6a65855698b9816f2d74871eda4dd0b7fa921140c6445248f94a742fd"
+ },
+ "win32-x64": {
+ "file": "bun-windows-x64-baseline.zip",
+ "sha256": "bf447dcc3b06aba9b9706a9db46fcd65e06a4d47d31439922313825d06eb47ca"
+ }
+ },
+ "licenseInventoryStatus": "source-and-notices-pinned-to-binary-revision",
+ "sourceManifest": "build/bun-source-manifest.json",
+ "correspondingSourceAsset": "bun-v1.3.5-source.tar.gz"
+}
diff --git a/build/bun-source-manifest.json b/build/bun-source-manifest.json
new file mode 100644
index 00000000..23b4864b
--- /dev/null
+++ b/build/bun-source-manifest.json
@@ -0,0 +1,148 @@
+{
+ "schemaVersion": 1,
+ "version": "1.3.5",
+ "releaseTag": "bun-v1.3.5",
+ "releaseTagCommit": "fa5a5bbe556a4bda5bde77b4013aa6c3bb4ec9ab",
+ "bunRevision": "1e86cebd74a5723e818b5c0555276b646bcf0e4c",
+ "archiveName": "bun-v1.3.5-source.tar.gz",
+ "sources": [
+ {
+ "name": "bun",
+ "repository": "oven-sh/bun",
+ "revision": "1e86cebd74a5723e818b5c0555276b646bcf0e4c",
+ "destination": "bun",
+ "sha256": "3a766087902a62a4920e5ac5452dbc7143ff97ea19721f945146629fc9f2d82c",
+ "licensePaths": ["LICENSE.md"]
+ },
+ {
+ "name": "WebKit",
+ "repository": "oven-sh/WebKit",
+ "revision": "6d0f3aac0b817cc01a846b3754b21271adedac12",
+ "destination": "bun/vendor/WebKit",
+ "transport": "git-sparse",
+ "exclude": ["JSTests", "LayoutTests", "ManualTests", "PerformanceTests", "WebDriverTests"],
+ "licensePaths": ["Source/JavaScriptCore/COPYING.LIB"]
+ },
+ {
+ "name": "boringssl",
+ "repository": "oven-sh/boringssl",
+ "revision": "f1ffd9e83d4f5c28a9c70d73f9a4e6fcf310062f",
+ "destination": "bun/vendor/boringssl",
+ "sha256": "af8fd325793bb261c70114d09a24f36092fbe252be8ec040f0054ec9455f0ea3",
+ "licensePaths": ["LICENSE"]
+ },
+ {
+ "name": "brotli",
+ "repository": "google/brotli",
+ "revision": "ed738e842d2fbdf2d6459e39267a633c4a9b2f5d",
+ "upstreamReference": "v1.1.0",
+ "destination": "bun/vendor/brotli",
+ "sha256": "aaa739962a45b508b2e783b915e6b2b57ed3b12bd4b0feac73acfb144dffa54f",
+ "licensePaths": ["LICENSE"]
+ },
+ {
+ "name": "cares",
+ "repository": "c-ares/c-ares",
+ "revision": "3ac47ee46edd8ea40370222f91613fc16c434853",
+ "destination": "bun/vendor/cares",
+ "sha256": "8c94116cb366ae4a44e487da4d9f7e736287d329efa6f88fdf077cd2d0a2e4b8",
+ "licensePaths": ["LICENSE.md"]
+ },
+ {
+ "name": "hdrhistogram",
+ "repository": "HdrHistogram/HdrHistogram_c",
+ "revision": "be60a9987ee48d0abf0d7b6a175bad8d6c1585d1",
+ "destination": "bun/vendor/hdrhistogram",
+ "sha256": "811c5e5ae5303a75ade50688880af6aad5d2f951ec5785f68186bd18635cdfc9",
+ "licensePaths": ["COPYING.txt", "LICENSE.txt"]
+ },
+ {
+ "name": "highway",
+ "repository": "google/highway",
+ "revision": "ac0d5d297b13ab1b89f48484fc7911082d76a93f",
+ "destination": "bun/vendor/highway",
+ "sha256": "a7a816f4b62a0414ff0d39c0a8875847468dd6f7c9ad71781a24469a756cdea7",
+ "licensePaths": ["LICENSE"]
+ },
+ {
+ "name": "libarchive",
+ "repository": "libarchive/libarchive",
+ "revision": "9525f90ca4bd14c7b335e2f8c84a4607b0af6bdf",
+ "destination": "bun/vendor/libarchive",
+ "sha256": "944db9ab58a3cbdb5d947db4f04a3cc15f83b3147fcf7830ada592ba8d4a102c",
+ "licensePaths": ["COPYING"]
+ },
+ {
+ "name": "libdeflate",
+ "repository": "ebiggers/libdeflate",
+ "revision": "c8c56a20f8f621e6a966b716b31f1dedab6a41e3",
+ "destination": "bun/vendor/libdeflate",
+ "sha256": "1e5cc06bdbf3e1245d8b89c9e3588f507e3c8bc53fe8b8229770a9e8661dea81",
+ "licensePaths": ["COPYING"]
+ },
+ {
+ "name": "libuv",
+ "repository": "libuv/libuv",
+ "revision": "f3ce527ea940d926c40878ba5de219640c362811",
+ "destination": "bun/vendor/libuv",
+ "sha256": "46040d51e8aa86a7c84e377e224d427c35022ec6e3ed8ed399493b0d8574d0cf",
+ "licensePaths": ["LICENSE"]
+ },
+ {
+ "name": "lolhtml",
+ "repository": "cloudflare/lol-html",
+ "revision": "d64457d9ff0143deef025d5df7e8586092b9afb7",
+ "destination": "bun/vendor/lolhtml",
+ "sha256": "893b77b460f4c4f4634c973f72cf35e38ebe30646d14a92db3f50ee7e586c0ad",
+ "licensePaths": ["LICENSE"]
+ },
+ {
+ "name": "lshpack",
+ "repository": "litespeedtech/ls-hpack",
+ "revision": "8905c024b6d052f083a3d11d0a169b3c2735c8a1",
+ "destination": "bun/vendor/lshpack",
+ "sha256": "07d8bf901bb1b15543f38eabd23938519e1210eebadb52f3d651d6ef130ef973",
+ "licensePaths": ["LICENSE"]
+ },
+ {
+ "name": "mimalloc",
+ "repository": "oven-sh/mimalloc",
+ "revision": "1beadf9651a7bfdec6b5367c380ecc3fe1c40d1a",
+ "destination": "bun/vendor/mimalloc",
+ "sha256": "317ec2a83462ece78c344c4955c6fee103b412a8e6a0d6ddf9ec8963ed9c0881",
+ "licensePaths": ["LICENSE"]
+ },
+ {
+ "name": "picohttpparser",
+ "repository": "h2o/picohttpparser",
+ "revision": "066d2b1e9ab820703db0837a7255d92d30f0c9f5",
+ "destination": "bun/vendor/picohttpparser",
+ "sha256": "637ff2ab6f5c7f7e05a5b5dc393d5cf2fea8d4754fcaceaaf935ffff5c1323ee",
+ "licensePaths": ["picohttpparser.c", "picohttpparser.h"]
+ },
+ {
+ "name": "tinycc",
+ "repository": "oven-sh/tinycc",
+ "revision": "29985a3b59898861442fa3b43f663fc1af2591d7",
+ "destination": "bun/vendor/tinycc",
+ "sha256": "813cc09aafd6cea9c1ae6b745781e6b27576a0c103f49b63b5c8a732bbe3d290",
+ "licensePaths": ["COPYING"]
+ },
+ {
+ "name": "zlib",
+ "repository": "cloudflare/zlib",
+ "revision": "886098f3f339617b4243b286f5ed364b9989e245",
+ "destination": "bun/vendor/zlib",
+ "sha256": "14bf449df8308696af52f87de88f54c9eb9c91ec5e280587f9d37f7a3f6ed9bb",
+ "licensePaths": ["LICENSE"]
+ },
+ {
+ "name": "zstd",
+ "repository": "facebook/zstd",
+ "revision": "f8745da6ff1ad1e7bab384bd1f9d742439278e99",
+ "destination": "bun/vendor/zstd",
+ "sha256": "4b0bd1f0cfb25e61b9103c35f27395530ff5b4c0d2513a00fd745849e85ea52c",
+ "licensePaths": ["COPYING", "LICENSE"]
+ }
+ ]
+}
diff --git a/bun.lock b/bun.lock
index fffea52b..d93cfcba 100644
--- a/bun.lock
+++ b/bun.lock
@@ -18,6 +18,7 @@
"ws": "^8.21.0",
},
"devDependencies": {
+ "@electron/asar": "3.4.1",
"@types/node": "^24.10.0",
"@types/ws": "^8.18.1",
"electron": "42.6.0",
@@ -34,14 +35,14 @@
"@discordjs/rest@2.6.1": "patches/@discordjs%2Frest@2.6.1.patch",
},
"overrides": {
- "@xmldom/xmldom": "0.8.13",
+ "@xmldom/xmldom": "0.8.15",
"app-builder-lib": "26.15.3",
"brace-expansion": "5.0.9",
"electron-builder-squirrel-windows": "26.15.3",
"fast-uri": "3.1.6",
"form-data": "4.0.6",
"ip-address": "10.2.0",
- "js-yaml": "4.3.1",
+ "js-yaml": "4.3.2",
"lodash": "4.18.0",
"minimatch": "10.2.5",
"picomatch": "4.0.4",
@@ -226,7 +227,7 @@
"@xhayper/discord-rpc": ["@xhayper/discord-rpc@1.3.4", "", { "dependencies": { "@discordjs/rest": "^2.6.1", "@vladfrangu/async_event_emitter": "^2.4.7", "discord-api-types": "^0.38.47", "ws": "^8.20.0" } }, "sha512-ff0uEXuibh9wi+l4vOj7xInLUjtlTaQBje/SCyQkeXZ0j2V0y+Zge5PQIQFRHH9TjjGaYJkTofEcQhncM2q7/w=="],
- "@xmldom/xmldom": ["@xmldom/xmldom@0.8.13", "", {}, "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw=="],
+ "@xmldom/xmldom": ["@xmldom/xmldom@0.8.15", "", {}, "sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA=="],
"abbrev": ["abbrev@4.0.0", "", {}, "sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA=="],
@@ -498,7 +499,7 @@
"jiti": ["jiti@2.6.1", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ=="],
- "js-yaml": ["js-yaml@4.3.1", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ=="],
+ "js-yaml": ["js-yaml@4.3.2", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA=="],
"json-buffer": ["json-buffer@3.0.1", "", {}, "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ=="],
diff --git a/changes/bundled-bun-runtime-docs.md b/changes/bundled-bun-runtime-docs.md
new file mode 100644
index 00000000..5ac31726
--- /dev/null
+++ b/changes/bundled-bun-runtime-docs.md
@@ -0,0 +1,5 @@
+type: docs
+area: launcher
+
+- Documented private-runtime launcher installation, simplified first-run setup, custom app locations, legacy launcher migration, and package-managed updates. Updated release-note download guidance for the bundled runtime and Windows launcher.
+- Documented the bundled Bun runtime's MIT and LGPL licensing, where the notices live in the app, and the corresponding-source release asset. The AUR package now lists the bundled runtime licenses and installs their notices under `/usr/share/licenses/subminer-bin`, and `subminer-assets.tar.gz` includes the same notices.
diff --git a/changes/bundled-bun-runtime.md b/changes/bundled-bun-runtime.md
new file mode 100644
index 00000000..b0cfc2d9
--- /dev/null
+++ b/changes/bundled-bun-runtime.md
@@ -0,0 +1,5 @@
+type: changed
+area: launcher
+
+- Made every installed and downloadable launcher use the Bun runtime included with SubMiner. Added a Windows `subminer.cmd` download, persistent private runtime caches for Linux and Windows, and migration for recognized legacy launchers. Deferred migrations survive overlapping update checks and remain pending when startup cannot safely refresh the launcher.
+- Simplified first-run setup to a single optional launcher control, with runtime repair guidance shown only when needed.
diff --git a/changes/caption-row-sentence-join.md b/changes/caption-row-sentence-join.md
deleted file mode 100644
index 354a605c..00000000
--- a/changes/caption-row-sentence-join.md
+++ /dev/null
@@ -1,4 +0,0 @@
-type: fixed
-area: overlay
-
-- Broadcast-style Japanese caption tracks (Crunchyroll JA subs) that split one sentence across two positioned events now publish it as a single line, so `preserveLineBreaks: false` flattens it, the sidebar lists it once, and mined sentences are whole. Rows from two different speakers, sound effects, and labeled turns still stay on separate lines.
diff --git a/changes/compressed-incremental-sync.md b/changes/compressed-incremental-sync.md
new file mode 100644
index 00000000..6cbf6352
--- /dev/null
+++ b/changes/compressed-incremental-sync.md
@@ -0,0 +1,6 @@
+type: changed
+area: sync
+
+- Sync uses compressed, incremental rsync transfers on compatible macOS and Linux machines, caching the last received snapshot per peer to reduce traffic on subsequent syncs. Cache helpers work through the launcher; older apps and launchers fall back to compressed transfers without an upload cache.
+- Machines without compatible rsync, including Windows endpoints, automatically use compressed scp transfers.
+- Rsync explicitly uses SSH and aborts transfers that exceed 30 minutes before merging.
diff --git a/changes/fix-first-launch-config-directory.md b/changes/fix-first-launch-config-directory.md
new file mode 100644
index 00000000..b50c9ef0
--- /dev/null
+++ b/changes/fix-first-launch-config-directory.md
@@ -0,0 +1,4 @@
+type: fixed
+area: startup
+
+- Fixed first launch exiting on macOS when the SubMiner config directory did not yet exist by creating it before acquiring the startup lock.
diff --git a/changes/fix-sidebar-space-seek.md b/changes/fix-sidebar-space-seek.md
new file mode 100644
index 00000000..4d677d8b
--- /dev/null
+++ b/changes/fix-sidebar-space-seek.md
@@ -0,0 +1,4 @@
+type: fixed
+area: overlay
+
+- Clicking a subtitle sidebar cue releases row focus, and Space no longer seeks back to a focused cue. Enter still seeks the focused cue, and Space keeps its configured playback action.
diff --git a/changes/hyprland-recovery-dialog.md b/changes/hyprland-recovery-dialog.md
new file mode 100644
index 00000000..7cd63c11
--- /dev/null
+++ b/changes/hyprland-recovery-dialog.md
@@ -0,0 +1,4 @@
+type: fixed
+area: overlay
+
+- Keep Hyprland recovery dialogs above SubMiner windows so overlay placement updates do not cover their Wait and Close buttons.
diff --git a/changes/japanese-subtitle-generation-docs.md b/changes/japanese-subtitle-generation-docs.md
new file mode 100644
index 00000000..798592e3
--- /dev/null
+++ b/changes/japanese-subtitle-generation-docs.md
@@ -0,0 +1,4 @@
+type: docs
+area: subtitles
+
+- Explain how dialogue generation retains uncertain audible sections, why songs may also be transcribed, how detected speech starts guide long-passage cuts to reduce early subtitles, and why each passage uses a fresh Whisper process.
diff --git a/changes/japanese-subtitle-generation.md b/changes/japanese-subtitle-generation.md
new file mode 100644
index 00000000..d3ee83bb
--- /dev/null
+++ b/changes/japanese-subtitle-generation.md
@@ -0,0 +1,6 @@
+type: added
+area: subtitles
+
+- Generate local Japanese SRT subtitles with whisper.cpp from a standalone modal opened with Ctrl+Shift+G, the empty subtitle sidebar's generation button, or `subminer generate-subs`, with shared progress reporting, cancellation, safe output files, and automatic loading into the matching mpv video. The sidebar button hides while subtitle lines are loaded.
+- Configure an existing multilingual model in Settings or choose an official multilingual model, including quantized variants, in the modal or launcher. The modal shows download sizes, speed and accuracy guidance, and a recommended starting model before explicitly downloading a verified SubMiner-managed model. Executable paths are optional overrides; empty fields find whisper-cli, ffmpeg, and ffprobe on PATH. The modal's Local tools check and the launcher name any missing executable and its setting before downloading a model or extracting audio, and generation confirms the destination directory grants write and search permissions up front.
+- Optionally select Focus on spoken dialogue in the modal and use Download speech detection model to install the separate Silero model with progress and cancellation. The choice lasts for the session; a configured VAD model path sets the default. Retain uncertain audible sections so VAD rejection does not discard dialogue under music, accepting that songs may also be transcribed. Keep passages intact within Whisper's audio window, split longer passages near detected speech starts or quiet pauses with overlapping context to reduce early subtitle timing, and combine overlapping duplicate cues even when punctuation differs. Run each passage in a fresh Whisper process to prevent repeated-character output caused by state carried between files, at the cost of reloading the model per passage. Preserve original media timing and separate repeated dialogue.
diff --git a/changes/jellyfin-zero-subtitle-delay.md b/changes/jellyfin-zero-subtitle-delay.md
deleted file mode 100644
index 92ae32ff..00000000
--- a/changes/jellyfin-zero-subtitle-delay.md
+++ /dev/null
@@ -1,4 +0,0 @@
-type: fixed
-area: jellyfin
-
-- Jellyfin subtitle files now load with zero mpv delay instead of inferring and saving an offset from Japanese and English cue timelines.
diff --git a/changes/mpv-overlay-bindings.md b/changes/mpv-overlay-bindings.md
new file mode 100644
index 00000000..f22597b5
--- /dev/null
+++ b/changes/mpv-overlay-bindings.md
@@ -0,0 +1,4 @@
+type: added
+area: overlay
+
+- The overlay discovers non-conflicting keyboard bindings from mpv defaults, input.conf, and loaded scripts in the background. SubMiner controls and explicitly disabled bindings take precedence. Discovered bindings stay session-only and do not appear in SubMiner's help menu.
diff --git a/changes/multiline-copy-timeline.md b/changes/multiline-copy-timeline.md
deleted file mode 100644
index 91b85be1..00000000
--- a/changes/multiline-copy-timeline.md
+++ /dev/null
@@ -1,4 +0,0 @@
-type: fixed
-area: mining
-
-- Multi-line copy and mining now select backward from the current subtitle in timeline order after seeking, instead of copying lines in playback encounter order. Jumping back to a short previous line also counts as a seek with external subtitle files, so that line becomes the current one.
diff --git a/changes/package-size-cleanup.md b/changes/package-size-cleanup.md
new file mode 100644
index 00000000..f1e225eb
--- /dev/null
+++ b/changes/package-size-cleanup.md
@@ -0,0 +1,5 @@
+type: changed
+area: release
+
+- Reduced installer and unpacked app size by excluding documentation demo media, dependency source maps, TypeScript files, test and fixture directories, other development files, and unused Koffi platform binaries, and sharing the existing Japanese UI font across windows.
+- Added package content checks, published size reports with release comparisons, and packaged asset/native-module smoke checks to the shared stable and prerelease build workflow. Size growth is reported without blocking releases.
diff --git a/changes/secondary-subtitle-track-visibility.md b/changes/secondary-subtitle-track-visibility.md
deleted file mode 100644
index 10ffaffd..00000000
--- a/changes/secondary-subtitle-track-visibility.md
+++ /dev/null
@@ -1,4 +0,0 @@
-type: fixed
-area: overlay
-
-- Native mpv secondary subtitles stay hidden when switching secondary subtitle tracks during playback.
diff --git a/changes/senren-field-grouping.md b/changes/senren-field-grouping.md
deleted file mode 100644
index 6c9646aa..00000000
--- a/changes/senren-field-grouping.md
+++ /dev/null
@@ -1,5 +0,0 @@
-type: added
-area: anki
-
-- Senren note type support for duplicate-card field grouping: enable `ankiConnect.isSenren` to merge duplicate mined cards using Senren's scene-switching markup, with grouped sentence, furigana, audio, picture, and miscInfo entries.
-- Senren field grouping supports the same auto/manual/disabled modes as Kiku, including the manual merge modal, and is mutually exclusive with Kiku (only one can be enabled at a time).
diff --git a/changes/sidebar-selection-copy.md b/changes/sidebar-selection-copy.md
new file mode 100644
index 00000000..b7ee4410
--- /dev/null
+++ b/changes/sidebar-selection-copy.md
@@ -0,0 +1,4 @@
+type: added
+area: overlay
+
+- Select dialogue across subtitle sidebar rows and copy it without timestamps using Ctrl/Cmd+C or the Copy button. Selection keeps the excerpt in view during playback and does not seek or require mining a card.
diff --git a/changes/subtitle-recorders-drop-ass-furigana.md b/changes/subtitle-recorders-drop-ass-furigana.md
deleted file mode 100644
index 0518aa58..00000000
--- a/changes/subtitle-recorders-drop-ass-furigana.md
+++ /dev/null
@@ -1,4 +0,0 @@
-type: fixed
-area: subtitles
-
-- Copying the current subtitle, Anki sentence mining from recent lines, and immersion stats no longer include the separate furigana lines that broadcast-caption ASS files place above a word; recorders now use the same furigana-free text the overlay displays.
diff --git a/changes/subtitle-sidebar-gap-follow.md b/changes/subtitle-sidebar-gap-follow.md
new file mode 100644
index 00000000..03d18f75
--- /dev/null
+++ b/changes/subtitle-sidebar-gap-follow.md
@@ -0,0 +1,4 @@
+type: fixed
+area: subtitles
+
+- Keep the subtitle sidebar near playback during gaps when the subtitle file has a cue starting at zero.
diff --git a/changes/sync-transfer-docs.md b/changes/sync-transfer-docs.md
new file mode 100644
index 00000000..74f6ec49
--- /dev/null
+++ b/changes/sync-transfer-docs.md
@@ -0,0 +1,4 @@
+type: docs
+area: sync
+
+- Documented compressed transfers, incremental sync cache storage, and compatibility with older peers.
diff --git a/config.example.jsonc b/config.example.jsonc
index 0daf73b0..64ccacf5 100644
--- a/config.example.jsonc
+++ b/config.example.jsonc
@@ -6,6 +6,23 @@
*/
{
+ // ==========================================
+ // Japanese Subtitle Generation
+ // Generate timed Japanese subtitles from local audio using whisper.cpp.
+ // Configure an existing GGML model path or explicitly download a SubMiner-managed model.
+ // Hot-reload: settings apply to the next generation or model download.
+ // ==========================================
+ "subtitleGeneration": {
+ "whisperPath": "", // Optional path override for whisper.cpp. Leave empty to find whisper-cli on PATH.
+ "modelPath": "", // Path to an existing multilingual whisper.cpp GGML model. Leave empty to use a SubMiner-managed model. A configured path always takes precedence.
+ "managedModel": "small", // Multilingual whisper.cpp model to use when modelPath is empty. Download it explicitly from the generation modal or launcher. Values: tiny | tiny-q5_1 | tiny-q8_0 | base | base-q5_1 | base-q8_0 | small | small-q5_1 | small-q8_0 | medium | medium-q5_0 | medium-q8_0 | large-v1 | large-v2 | large-v2-q5_0 | large-v2-q8_0 | large-v3 | large-v3-q5_0 | large-v3-turbo | large-v3-turbo-q5_0 | large-v3-turbo-q8_0
+ "threads": 4, // Positive integer CPU thread count for whisper.cpp Japanese transcription.
+ "ffmpegPath": "", // Optional FFmpeg path override for audio extraction. Leave empty to find ffmpeg on PATH.
+ "ffprobePath": "", // Optional FFprobe path override for audio tracks and timing. Leave empty to find ffprobe on PATH.
+ "vadModelPath": "", // Path to a whisper.cpp Silero VAD model. Enables dialogue-focused generation while retaining uncertain audible sections, which may include songs. Leave empty to transcribe the full audio.
+ "vadPath": "" // Optional speech detector executable override. With vadModelPath configured, leave empty to find whisper-vad-speech-segments or vad-speech-segments on PATH.
+ }, // Generate timed Japanese subtitles from local audio using whisper.cpp.
+
// ==========================================
// Visible Overlay Auto-Start
// Show the visible subtitle overlay automatically after managed mpv playback starts SubMiner.
@@ -206,6 +223,7 @@
"openRuntimeOptions": "CommandOrControl+Shift+O", // Accelerator that opens the runtime options modal.
"openJimaku": "Ctrl+Shift+J", // Accelerator that opens the Jimaku subtitle search modal.
"openTsukihime": "Ctrl+Shift+T", // Accelerator that opens the TsukiHime subtitle search modal (configured secondary/Japanese primary tabs).
+ "openSubtitleGeneration": "Ctrl+Shift+G", // Accelerator that opens the standalone Japanese subtitle generation modal.
"openSessionHelp": "CommandOrControl+Slash", // Accelerator that opens the session help / keybinding cheatsheet.
"openControllerSelect": "Alt+C", // Accelerator that opens the controller selection and learn-mode modal.
"openControllerDebug": "Alt+Shift+C", // Accelerator that opens the controller debug modal with live axis/button readouts.
@@ -529,7 +547,7 @@
// ==========================================
// AnkiConnect Integration
// Automatic Anki updates and media generation options.
- // Hot-reload: ankiConnect.ai.enabled, media.normalizeAudio/mirrorMpvVolume, knownWords, nPlusOne, fields.word/audio/image/sentence/miscInfo, behavior.autoUpdateNewCards, isLapis.sentenceCardModel, isKiku.fieldGrouping, isSenren.fieldGrouping, and lapisKiku.wordCardKind update live while SubMiner is running.
+ // Hot-reload: ankiConnect.ai.enabled, media.normalizeAudio/mirrorMpvVolume/reviewTiming, knownWords, nPlusOne, fields.word/audio/image/sentence/miscInfo, behavior.autoUpdateNewCards, isLapis.sentenceCardModel, isKiku.fieldGrouping, isSenren.fieldGrouping, and lapisKiku.wordCardKind update live while SubMiner is running.
// Shared AI provider transport settings are read from top-level ai and typically require restart.
// Most other AnkiConnect settings still require restart.
// ==========================================
@@ -575,6 +593,7 @@
"syncAnimatedImageToWordAudio": true, // For animated AVIF images, prepend a frozen first frame matching the existing word-audio duration so motion starts with sentence audio. Values: true | false
"normalizeAudio": true, // Normalize generated sentence audio loudness during media extraction. Changes apply live. Values: true | false
"mirrorMpvVolume": true, // Apply mpv's current software volume curve to generated sentence audio. Changes apply live. Values: true | false
+ "reviewTiming": false, // Review and preview subtitle media timing before SubMiner creates or enriches a mined card. Values: true | false
"audioPadding": 0, // Seconds of padding appended to both ends of generated sentence audio and animated AVIF clips.
"fallbackDuration": 3, // Fallback clip duration in seconds when subtitle timing data is unavailable.
"maxMediaDuration": 30 // Maximum allowed media clip duration in seconds.
diff --git a/docs-site/.vitepress/config.ts b/docs-site/.vitepress/config.ts
index c4f56ff0..8a4dcad1 100644
--- a/docs-site/.vitepress/config.ts
+++ b/docs-site/.vitepress/config.ts
@@ -370,6 +370,7 @@ const sidebar: DefaultTheme.SidebarItem[] = [
{ text: 'YouTube', link: '/youtube-integration' },
{ text: 'Anime Browser', link: '/anime-browser' },
{ text: 'Jimaku', link: '/jimaku-integration' },
+ { text: 'Subtitle Generation', link: '/subtitle-generation' },
{ text: 'TsukiHime', link: '/tsukihime-integration' },
{ text: 'AniList', link: '/anilist-integration' },
{ text: 'AniSkip', link: '/aniskip-integration' },
diff --git a/docs-site/README.md b/docs-site/README.md
index 16d10ef4..687452cb 100644
--- a/docs-site/README.md
+++ b/docs-site/README.md
@@ -1,4 +1,4 @@
-# SubMiner Docs
+# SubMiner docs
In-repo VitePress documentation source for SubMiner.
diff --git a/docs-site/anilist-integration.md b/docs-site/anilist-integration.md
index 4852f46c..a5a490b2 100644
--- a/docs-site/anilist-integration.md
+++ b/docs-site/anilist-integration.md
@@ -1,10 +1,10 @@
-# AniList Integration
+# AniList integration
-SubMiner can sync your watch progress to [AniList](https://anilist.co) automatically. When you finish an episode, SubMiner detects the title and episode number from the filename, finds the matching AniList entry, and updates your progress via the GraphQL API. Failed updates are retried with exponential backoff in the background.
+SubMiner syncs your watch progress to [AniList](https://anilist.co). Finish an episode and it reads the title and episode number off the filename, finds the matching AniList entry, and updates your progress through the GraphQL API. A failed update retries in the background with exponential backoff.
-AniList data also powers two additional features: [cover art](#cover-art) for the stats dashboard and the [Character Dictionary](/character-dictionary) for in-overlay name lookup.
+The same AniList data feeds [cover art](#cover-art) in the stats dashboard and the [Character Dictionary](/character-dictionary) for in-overlay name lookup.
-[AniList](https://anilist.co) is a free website for tracking which anime you have watched. An **access token** is a private key SubMiner stores so it can update your list on your behalf - you approve it once during setup, and you never paste a password into SubMiner.
+[AniList](https://anilist.co) is a free anime tracking site. The **access token** is a private key SubMiner keeps so it can update your list for you. You approve it once during setup, and your AniList password never touches SubMiner.
## Setup
@@ -32,18 +32,18 @@ If the embedded auth UI fails to render, SubMiner opens the authorize URL in you
You can also set `anilist.accessToken` directly in config to skip the setup flow entirely. When blank, SubMiner uses the locally stored encrypted token.
:::
-## How Tracking Works
+## How tracking works
-SubMiner monitors playback and triggers an AniList progress update when an episode is considered "watched" -- at least 85% of the episode duration viewed and a minimum of 10 minutes watched.
+SubMiner watches playback and pushes an AniList progress update once an episode counts as watched. That means at least 85% of its duration, and at least 10 minutes either way.
The update flow:
-1. **Title detection** -- SubMiner extracts the anime title, season, and episode number from the media filename and path. Season folders such as `Season 2` are treated as a strong season signal. SubMiner tries [`guessit`](https://github.com/guessit-io/guessit) first for accurate parsing, then falls back to an internal filename parser if guessit is unavailable.
-2. **AniList search** -- The base title (with any `Season N` / `SN` marker stripped) is searched against the AniList GraphQL API, and SubMiner picks the best match by comparing titles (romaji, English, native, synonyms) and filtering by episode count. AniList has no notion of numbered seasons -- sequels are separate entries with their own titles (`Zoku`, `Kan`, `2nd Season`), so searching ` Season 3` finds nothing. For season 2 and later, SubMiner instead walks `SEQUEL` relations from the season 1 entry, preferring the TV line, and falls back to ordering the franchise's TV entries by air date when the relation chain is incomplete. If neither locates the season, SubMiner **skips the update** rather than writing progress to the season 1 entry, and tells you to pin the right entry with a [character dictionary override](/character-dictionary#correcting-anilist-matches).
-3. **Progress check** -- SubMiner fetches your current list entry for the matched media. The media must already be in Planning or Watching; otherwise SubMiner shows an MPV message explaining that the update is not possible. If your recorded progress already meets or exceeds the detected episode, the update is skipped.
-4. **Mutation** -- A `SaveMediaListEntry` mutation sets the new progress and marks the entry as `CURRENT`, or `COMPLETED` when the watched episode is the final episode of the season (the "already at this progress" skip is bypassed for the final episode so completion still lands).
+1. **Title detection** - SubMiner extracts the anime title, season, and episode number from the media filename and path. Season folders such as `Season 2` are treated as a strong season signal. SubMiner tries [`guessit`](https://github.com/guessit-io/guessit) first for accurate parsing, then falls back to an internal filename parser if guessit is unavailable.
+2. **AniList search** - The base title (with any `Season N` / `SN` marker stripped) is searched against the AniList GraphQL API, and SubMiner picks the best match by comparing titles (romaji, English, native, synonyms) and filtering by episode count. AniList has no notion of numbered seasons - sequels are separate entries with their own titles (`Zoku`, `Kan`, `2nd Season`), so searching ` Season 3` finds nothing. For season 2 and later, SubMiner instead walks `SEQUEL` relations from the season 1 entry, preferring the TV line, and falls back to ordering the franchise's TV entries by air date when the relation chain is incomplete. If neither locates the season, SubMiner **skips the update** rather than writing progress to the season 1 entry, and tells you to pin the right entry with a [character dictionary override](/character-dictionary#correcting-anilist-matches).
+3. **Progress check** - SubMiner fetches your current list entry for the matched media. The media must already be in Planning or Watching; otherwise SubMiner shows an MPV message explaining that the update is not possible. If your recorded progress already meets or exceeds the detected episode, the update is skipped.
+4. **Mutation** - A `SaveMediaListEntry` mutation sets the new progress and marks the entry as `CURRENT`, or `COMPLETED` when the watched episode is the final episode of the season (the "already at this progress" skip is bypassed for the final episode so completion still lands).
-## Update Queue and Retry
+## Update queue and retry
Failed AniList updates are persisted to a retry queue on disk and retried with exponential backoff.
@@ -58,7 +58,7 @@ After 8 failed attempts, the update is moved to a dead-letter queue and no longe
Use `--anilist-retry-queue` to manually process one ready item from the queue.
-## Cover Art
+## Cover art
SubMiner fetches cover art from AniList for display in the stats dashboard. When a new video starts playing, the cover art fetcher:
@@ -71,11 +71,11 @@ A no-match result is cached for 5 minutes before SubMiner retries, preventing re
If the automatic match is wrong, use **Change AniList Entry** on a title in the stats Library. Relinking rewrites the cached art for every episode of that title, and both the detail view and the Library grid pick up the new cover right away: the grid refetches after a relink, and cover responses carry an ETag and are revalidated on each request instead of being cached for a day.
-## Rate Limiting
+## Rate limiting
All AniList API calls go through a shared rate limiter that enforces a sliding window of 20 requests per minute. The limiter also reads AniList's `X-RateLimit-Remaining` and `Retry-After` response headers and pauses requests when the server signals throttling. This applies to both episode tracking and cover art fetching.
-## Configuration Reference
+## Configuration reference
```jsonc
{
@@ -107,7 +107,7 @@ All AniList API calls go through a shared rate limiter that enforces a sliding w
There is no `characterDictionary.enabled` key: character dictionary sync is enabled by `subtitleStyle.nameMatchEnabled`. See the [Character Dictionary](/character-dictionary) page for full details on the character dictionary feature, including name generation, matching, auto-sync lifecycle, and dictionary entry format.
-## CLI Commands
+## CLI commands
| Command | Description |
| ----------------------- | ------------------------------------------------------------- |
@@ -124,10 +124,10 @@ There is no `characterDictionary.enabled` key: character dictionary sync is enab
- **Token issues:** Run `--anilist-status` to check token state. If the token is invalid or expired, run `--anilist-setup` or `--anilist-logout` and re-authenticate.
- **Updates failing repeatedly:** Run `--anilist-status` to see retry queue counters. Items that fail 8 times are moved to the dead-letter queue. Check network connectivity and AniList API status.
- **Cover art missing:** Cover art is fetched on a best-effort basis using title matching. If the filename is hard to parse, the search may return no results. The fetcher retries after 5 minutes.
-- **Encryption unavailable on Linux:** If you see warnings about safeStorage, try `--password-store=basic_text` as a workaround, or ensure your desktop keyring (gnome-keyring, KWallet) is running.
+- **Encryption unavailable on Linux:** If you see warnings about safeStorage, try `--password-store=basic_text` as a workaround, or start your desktop keyring (gnome-keyring, KWallet).
## Related
-- [Character Dictionary](/character-dictionary) -- AniList-powered character name dictionary for Yomitan
-- [Configuration Reference](/configuration) -- full config options
-- [Jellyfin Integration](/jellyfin-integration) -- media server integration
+- [Character Dictionary](/character-dictionary) - AniList-powered character name dictionary for Yomitan
+- [Configuration Reference](/configuration) - full config options
+- [Jellyfin Integration](/jellyfin-integration) - media server integration
diff --git a/docs-site/aniskip-integration.md b/docs-site/aniskip-integration.md
index fc9bc230..ee5ff5dd 100644
--- a/docs-site/aniskip-integration.md
+++ b/docs-site/aniskip-integration.md
@@ -1,8 +1,8 @@
-# AniSkip Integration
+# AniSkip integration
-SubMiner integrates with [AniSkip](https://aniskip.com) to automatically detect anime intro intervals and let you skip them with a single key press.
+SubMiner looks up anime intro timings from [AniSkip](https://aniskip.com) so you can jump past the OP with one key.
-Intro detection runs in the SubMiner app over the mpv IPC socket. It is available whenever the overlay is connected to mpv - not just at launch - and covers every local file loaded during an mpv session, including playlist advances.
+Intro detection runs in the SubMiner app over the mpv IPC socket. It works whenever the overlay is connected to mpv, not only at launch, and covers every local file loaded during the session including playlist advances.
## Setup
@@ -25,9 +25,9 @@ For best title and episode detection, install [`guessit`](https://github.com/gue
python3 -m pip install --user guessit
```
-Without `guessit`, SubMiner falls back to an internal filename parser which handles most common naming conventions but may miss unusual formats.
+Without `guessit`, SubMiner falls back to its own filename parser. That handles the usual release naming, but unusual formats slip past it.
-## How It Works
+## How it works
On each local file load:
@@ -39,15 +39,15 @@ On each local file load:
When a custom key (other than `TAB` or `y-k`) is configured, the legacy `y-k` chord is also bound as a fallback skip trigger.
-Results are cached per file for the app session; only definitive "no intro found" results are cached, so transient lookup failures are retried on the next file load. Reload detection is also handled: if mpv reloads the same file, SubMiner re-applies the chapter markers without a new API lookup.
+Results are cached per file for the app session. Only a definitive "no intro found" is cached, so a failed lookup gets retried on the next load rather than sticking. If mpv reloads the same file, SubMiner re-applies the chapter markers without hitting the API again.
## Triggering from mpv
-You can trigger AniSkip actions from mpv script-messages:
+AniSkip actions are also reachable from mpv script-messages:
| Command | Effect |
| ------- | ------ |
| `script-message subminer-skip-intro` | Skip to the intro end immediately (same as pressing the key) |
| `script-message subminer-aniskip-refresh` | Force a fresh lookup for the current file, discarding any cached result |
-These are handled by the SubMiner app over the IPC socket.
+The SubMiner app handles both over the IPC socket.
diff --git a/docs-site/anki-integration.md b/docs-site/anki-integration.md
index 5375691f..3a0814c3 100644
--- a/docs-site/anki-integration.md
+++ b/docs-site/anki-integration.md
@@ -1,4 +1,4 @@
-# Anki Integration
+# Anki integration
SubMiner uses the [AnkiConnect](https://ankiweb.net/shared/info/2055492159) add-on to create and update Anki cards with sentence context, audio, and screenshots.
This project is built primarily for [Kiku](https://kiku.youyoumu.my.id/) and [Lapis](https://github.com/donkuri/lapis) note types, including sentence-card and field-grouping behavior.
@@ -19,28 +19,27 @@ This project is built primarily for [Kiku](https://kiku.youyoumu.my.id/) and [La
AnkiConnect listens on `http://127.0.0.1:8765` by default. If you changed the port in AnkiConnect's settings, update `ankiConnect.url` in your SubMiner config.
-## Auto-Enrichment Transport
+## Auto-enrichment transport
-When you add a word via Yomitan, SubMiner detects the new card and fills in the sentence, audio, image, and translation fields automatically. Two detection methods are available:
+When you add a word via Yomitan, SubMiner detects the new card and fills in the sentence, audio, and image fields automatically. Two detection methods are available:
-**Proxy mode** (default) - SubMiner runs a local _proxy_: a small middleman server that sits between Yomitan and Anki. Yomitan sends new cards to SubMiner, SubMiner enriches them, then passes them along to Anki. This makes enrichment instant.
+**Proxy mode** (default) - SubMiner runs a small local server between Yomitan and Anki. Yomitan sends the new card to SubMiner, SubMiner fills in the media fields, and the finished card goes on to Anki. There is no polling delay.
-**Polling mode** (fallback, when the proxy is disabled) - SubMiner asks AnkiConnect every few seconds whether any new cards were added, then enriches them. Simpler setup, but with a short delay (~3 seconds).
+**Polling mode** (fallback, when the proxy is disabled) - SubMiner asks AnkiConnect every few seconds whether new cards showed up, then fills them in. Less to configure, at the cost of roughly a 3 second delay.
-Use proxy mode if you want immediate enrichment. Use polling mode if your Yomitan instance is external (browser-based) or you prefer minimal configuration.
+Use proxy mode unless your Yomitan runs in a browser rather than the bundled instance, in which case polling is the simpler path.
In both modes, the enrichment workflow is the same:
1. Checks if a duplicate expression already exists (for field grouping).
2. Updates the sentence field with the current subtitle.
3. Generates and uploads audio and image media.
-4. Fills the translation field from the secondary subtitle or AI.
-5. Writes metadata to the miscInfo field.
+4. Writes metadata to the miscInfo field.
Polling mode uses the query `"deck:" added:1` to find recently added cards. If no deck is configured, it searches all decks (`added:1`). In Settings, the AnkiConnect deck dropdown auto-fills and persists Yomitan's current mining deck when available, then falls back to the decks reported by AnkiConnect; stats-dashboard mining also falls back to Yomitan's mining deck when `ankiConnect.deck` is empty.
Known-word sync scope is controlled by `ankiConnect.knownWords.decks`.
-### Proxy Mode Setup (Yomitan / Texthooker)
+### Proxy mode setup (Yomitan / texthooker)
```jsonc
"ankiConnect": {
@@ -83,7 +82,7 @@ In Yomitan, go to Settings → Profile and:
This is only for non-bundled, external/browser Yomitan or other clients. The bundled profile auto-update logic only targets the active profile when its server is blank or still default.
-### Proxy Troubleshooting (quick checks)
+### Proxy troubleshooting (quick checks)
If auto-enrichment appears to do nothing:
@@ -107,7 +106,7 @@ curl -sS http://127.0.0.1:8766 \
- Launcher log: `launcher-YYYY-MM-DD.log`
- mpv log: `mpv-YYYY-MM-DD.log`
-4. Ensure config JSONC is valid and logging shape is correct:
+4. Check that the config JSONC parses and the logging shape is right:
```jsonc
"logging": {
@@ -117,30 +116,31 @@ curl -sS http://127.0.0.1:8766 \
`"logging": "debug"` is invalid for current schema and can break reload/start behavior.
-## Field Mapping
+## Field mapping
SubMiner maps its data to your Anki note fields. Configure these under `ankiConnect.fields`:
```jsonc
"ankiConnect": {
"fields": {
- "word": "Expression", // mined word / expression text
- "audio": "ExpressionAudio", // audio clip from the video
- "image": "Picture", // screenshot or animated clip
- "sentence": "Sentence", // subtitle text
- "miscInfo": "MiscInfo", // metadata (filename, timestamp)
- "translation": "SelectionText" // secondary sub or AI translation
+ "word": "Expression", // mined word / expression text
+ "audio": "SentenceAudio", // sentence audio clip cut from the video
+ "image": "Picture", // screenshot or animated clip
+ "sentence": "Sentence", // subtitle text
+ "miscInfo": "MiscInfo" // metadata (filename, timestamp)
}
}
```
+`fields.audio` receives the **sentence** audio SubMiner cuts from the video, not word audio. Yomitan writes its own dictionary audio when you mine, so point this at a separate field such as `SentenceAudio` to keep the two apart. The built-in default is still `ExpressionAudio`, which collides with Yomitan on note types that use that field for word audio.
+
Field names are matched against your Anki note type case-insensitively (an exact match wins, then a lowercase comparison). If a configured field does not exist on the note type, SubMiner skips it without error.
These mappings always control normal word-card enrichment, including Yomitan proxy/polling updates and manual clipboard updates. Enabling Lapis or Kiku does not replace the configured word-card sentence and audio fields with `Sentence` and `SentenceAudio`. The dedicated sentence-card and audio-card shortcuts still use those Lapis/Kiku field names.
Two related options live alongside `fields`: `ankiConnect.deck` (target deck; empty falls back as described above) and `ankiConnect.tags` (tags added to mined cards, default `["SubMiner"]`; set `[]` to disable tagging). The `miscInfo` content is controlled by `ankiConnect.metadata.pattern` (default `[SubMiner] %f (%t)`; tokens: `%f` filename, `%F` filename with extension, `%t` timestamp, `%T` timestamp with milliseconds, ` ` newline).
-### Minimal Config
+### Minimal config
If you only want sentence and audio on your cards:
@@ -149,14 +149,16 @@ If you only want sentence and audio on your cards:
"enabled": true,
"fields": {
"sentence": "Sentence",
- "audio": "ExpressionAudio"
+ "audio": "SentenceAudio"
}
}
```
-## Media Generation
+## Media generation
-SubMiner uses FFmpeg to generate audio and image media from the video. FFmpeg must be installed and on `PATH`.
+SubMiner shells out to FFmpeg for audio clips and screenshots, so FFmpeg has to be installed and on `PATH`.
+
+For remote streams such as Jellyfin playback, SubMiner downloads the clip's time window once into a temporary Matroska file (a stream copy, no re-encoding) and reads the timing review waveform, audio preview, audio, and image from that file instead of fetching the stream again for each step. The window covers the clip plus padding, plus the visible timeline in timing review, and grows when you reveal more of the timeline. It is deleted when a different window replaces it, after ten minutes without use, or when SubMiner exits. If the download fails, media generation reads the remote stream directly as before.
### Audio
@@ -168,6 +170,7 @@ Audio is extracted from the video file using the subtitle's start and end timest
"generateAudio": true,
"normalizeAudio": true, // normalize generated clip loudness
"mirrorMpvVolume": true, // apply the current mpv volume level
+ "reviewTiming": false, // review and adjust timing before media generation
"audioPadding": 0, // optional seconds before and after subtitle timing
"maxMediaDuration": 30 // cap total duration in seconds
}
@@ -180,7 +183,27 @@ Output format: MP3 at 44100 Hz. If the video has multiple audio streams, SubMine
The audio is uploaded to Anki's media folder and inserted as `[sound:audio_.mp3]`.
-### Screenshots (Static)
+Set `media.reviewTiming` to `true` to pause playback and check the clip before its media is generated. It applies to word, sentence, and audio cards.
+
+The review opens on the subtitle range plus your configured audio padding. Subtitles usually hang around after the dialogue has stopped, so once the waveform loads, an untouched clip end pulls back to just after the last speech in the line. The Line end rail still marks the original subtitle timing, Reset puts it back, and a line whose speech runs right through its end is left alone.
+
+**Adjusting the clip.** Drag either edge to trim, drag the middle to slide the whole clip without changing its length, or click anywhere on the waveform to snap the nearer edge there. A focused edge also moves with the arrow keys: 100 ms per press, or 500 ms with Shift. The 100 ms buttons do the same thing. Earlier and Later each reveal two more seconds of timeline without moving the selection.
+
+**Keys.** Space previews the selection with a playhead sweeping the clip. The preview ends when the hidden player has actually played the last sample, so Bluetooth output latency does not clip the tail. Enter confirms and Escape cancels.
+
+**The waveform.** SubMiner reads a center channel when one carries dialogue and falls back to a mono mix otherwise, keeps only the 250 to 3500 Hz speech band, and draws each slice's loudness against the clip's own noise floor. Steady background music flattens out and dialogue stands up, which makes it much easier to tell adjacent lines apart. The mined subtitle appears as a tinted band with labeled line-start and line-end rails. If waveform analysis fails, the timing controls still work.
+
+The range you confirm is used exactly as-is; SubMiner does not add audio padding a second time. Static screenshots take its midpoint, and animated AVIF clips cover the whole range.
+
+**Pulling in adjacent lines.** Press `P` or `N`, or use the Prev and Next steppers above the sentence preview, to add the previous or next subtitle line. Repeat for as many lines as exist. Shift+`P` and Shift+`N` remove them again. The sentence preview lists every included line with the mined one highlighted, so you always see the sentence field before confirming. The clip bounds and the waveform rails follow the outermost added line, keeping the review's audio padding.
+
+Confirming writes the combined lines to the sentence field. Reset drops the added lines along with any timing changes. Adjacent lines come from the parsed subtitle track when one is loaded; otherwise you only get lines that already played. A clip capped by `media.maxMediaDuration` still keeps the full combined sentence even when the audio cannot stretch to cover every added line.
+
+**Canceling.** You can go back to editing, finish with the original timing, create the card without audio or an image, or discard it. Discard deletes an existing Yomitan or audio card, and skips creation entirely for a direct sentence card. A failed audio preview does not block confirmation or card creation.
+
+Clipboard updates and stats-dashboard mining never open timing review. The option is off by default and hot-reloads. **Review Media Timing** in the runtime options palette (`Ctrl/Cmd+Shift+O`) toggles it for the current session.
+
+### Screenshots (static)
A single frame is captured at the current playback position.
@@ -197,9 +220,9 @@ A single frame is captured at the current playback position.
}
```
-### Animated Clips (AVIF)
+### Animated clips (AVIF)
-Instead of a static screenshot, SubMiner can generate an animated AVIF covering the subtitle duration.
+SubMiner can produce an animated AVIF spanning the subtitle duration instead of a still frame.
```jsonc
"ankiConnect": {
@@ -216,7 +239,7 @@ Instead of a static screenshot, SubMiner can generate an animated AVIF covering
Animated AVIF requires an AV1 encoder (`libaom-av1`, `libsvtav1`, or `librav1e`) in your FFmpeg build. Generation timeout is 60 seconds. `media.syncAnimatedImageToWordAudio` (default `true`) prepends a frozen first frame matching the existing word-audio duration, so the motion starts together with the sentence audio.
-### Behavior Options
+### Behavior options
```jsonc
"ankiConnect": {
@@ -237,40 +260,7 @@ When media is available, mined-card overlay and system notifications include the
`overwriteAudio` applies to automatic card updates and duplicate-card enrichment. Manual clipboard subtitle updates (`Ctrl/Cmd+C`, then `Ctrl/Cmd+V`) always replace generated sentence audio in `ankiConnect.fields.audio`, even when `overwriteAudio` is disabled.
-## AI Translation
-
-SubMiner can auto-translate the mined sentence and fill the translation field.
-Secondary subtitle text still wins when present. AI translation is only attempted when `ankiConnect.ai.enabled` is `true` and no secondary subtitle exists.
-
-```jsonc
-"ai": {
- "enabled": true,
- "apiKey": "sk-...",
- "apiKeyCommand": "",
- "baseUrl": "https://openrouter.ai/api",
- "requestTimeoutMs": 15000
-},
-"ankiConnect": {
- "ai": {
- "enabled": true,
- "model": "openai/gpt-4o-mini",
- "systemPrompt": "Translate mined sentence text only."
- }
-}
-```
-
-`ankiConnect.ai` controls feature-local enablement plus optional `model` / `systemPrompt` overrides.
-Provider credentials and request transport settings live in top-level `ai`.
-
-Translation priority:
-
-1. If a secondary subtitle is available, use it as the translation.
-2. If `ankiConnect.ai.enabled` is `true` and top-level `ai.enabled` is `true`, call the shared AI provider.
-3. If AI translation fails and no secondary subtitle exists, fall back to the original sentence text.
-
-The built-in translation request asks for English output by default. Customize that behavior through `ankiConnect.ai.systemPrompt`.
-
-## Sentence Cards (Lapis)
+## Sentence cards (Lapis)
SubMiner can create standalone sentence cards (without a word/expression) using a separate note type. This is designed for use with [Lapis](https://github.com/donkuri/Lapis) and similar sentence-focused note types.
@@ -293,7 +283,7 @@ The dedicated sentence-card and audio-card shortcuts use the Lapis/Kiku-compatib
To mine multiple subtitle lines as one sentence card, use `Ctrl/Cmd+Shift+S` followed by a digit (1–9) to select how many recent lines to combine.
-## Word Card Type (Kiku/Lapis)
+## Word card type (Kiku/Lapis)
Word cards get a card-type flag when SubMiner fills their sentence, whether that comes from Yomitan auto-enrichment, a manual clipboard update, or stats-dashboard word mining. By default the flag is `IsWordAndSentenceCard`; pick a different one with `ankiConnect.lapisKiku.wordCardKind`.
@@ -308,7 +298,7 @@ Word cards get a card-type flag when SubMiner fills their sentence, whether that
`click` marks `IsClickCard`, `sentence` marks `IsSentenceCard`, `audio` marks `IsAudioCard`, and `none` leaves the flags untouched for templates that manage them elsewhere. Whichever flag is chosen, the other card-type flags are cleared so the note never claims two card types. The setting is only read when `isKiku` or `isLapis` is enabled, and cards mined with Mine Sentence or Mine Audio keep their own flag.
-## Field Grouping (Kiku/Senren)
+## Field grouping (Kiku/Senren)
When you mine the same word multiple times, SubMiner can merge the cards instead of creating duplicates. This is designed for note types that support grouped fields: [Kiku](https://github.com/youyoumu/kiku) and [Senren](https://github.com/BrenoAqua/Senren) (which calls the feature scene switching).
@@ -342,20 +332,20 @@ For Senren note types, enable `isSenren` instead. Kiku and Senren write incompat
**Manual** (`"manual"`): A modal appears in the overlay showing both cards. You choose which card to keep, preview the merge result, then confirm. The modal has a 90-second timeout, after which it cancels automatically.
-### What Gets Merged
+### What gets merged
-| Field | Merge behavior |
-| -------- | --------------------------------------------- |
-| Sentence | Both cards' sentences kept as grouped entries |
-| Audio | Both cards' `[sound:...]` entries kept |
-| Image | Both cards' images kept |
+| Field | Merge behavior |
+| -------- | ----------------------------------------------- |
+| Sentence | Both cards' sentences kept as grouped entries |
+| Audio | Both cards' `[sound:...]` entries kept |
+| Image | Both cards' images kept |
| MiscInfo | Both cards' source info kept as grouped entries |
Identical values from both cards are kept as separate grouped entries; the merge does not deduplicate.
The merge markup depends on the note type. Kiku entries are wrapped in `` spans ordered newest first. Senren entries follow the [scene switching](https://github.com/BrenoAqua/Senren/blob/main/docs/scene_switching.md) format: sentence, sentenceFurigana, and miscInfo entries use `group` spans when ordinal order is sufficient and numbered `groupN` spans when they need an absolute scene target. Audio and pictures are appended positionally, and the number of sentenceAudio entries drives Senren's scene count. Ungrouped legacy content is wrapped into a group span on first merge, and source `groupN` spans are rebased after the kept note's existing audio scenes.
-### Keyboard Shortcuts in the Modal
+### Keyboard shortcuts in the modal
| Key | Action |
| ----------- | ---------------------------------- |
@@ -364,7 +354,7 @@ The merge markup depends on the note type. Kiku entries are wrapped in `
-SubMiner is configured through a single file (`config.jsonc`). Most settings are also editable from the in-app **Settings** window - you rarely need to edit the file by hand. This page is the full reference: it explains the Settings window, where the config file lives, and documents every option grouped by topic. New to SubMiner? The Quick Start below plus the [Settings window](#settings) cover everything most users need.
+One file, `config.jsonc`, holds everything. Most of it is also editable from the in-app **Settings** window, so hand-editing is rarely necessary.
-## Quick Start
+This page is the full reference. It covers the Settings window, where the config file lives, and every option grouped by topic. If you are just starting out, the Quick Start below and the [Settings window](#settings) are enough.
-For most users, start with this minimal configuration:
+## Quick start
+
+Start here:
```json
{
@@ -35,11 +37,11 @@ For most users, start with this minimal configuration:
Use the known-word deck map to choose which Anki decks and note fields feed the known-word cache.
-Then customize as needed using the sections below.
+Everything else is optional; the sections below cover it.
## Settings
-SubMiner includes a dedicated **Settings** window accessible from the tray menu, the app `--settings` flag, or launcher commands such as `subminer --settings` and `subminer settings`. It is the primary way to configure SubMiner - all changes are written directly to `config.jsonc`, so manual file editing is not required for most users.
+Open the **Settings** window from the tray menu, the app's `--settings` flag, or `subminer settings`. It writes straight to `config.jsonc`, so anything you change there is a normal config edit you can inspect afterward.
The Settings window groups options by workflow instead of mirroring the raw config-file shape:
@@ -57,11 +59,11 @@ Each field still writes to its current `config.jsonc` path. For example, subtitl
The Settings window preserves existing JSONC comments, trailing commas, and unrelated keys. Resetting a field removes the explicit config path so the built-in default applies.
-Secret fields do not display stored values. They show whether a value is configured; entering a new value writes it, and reset clears the explicit path. Prefer command-based secret options such as `ai.apiKeyCommand` when available.
+Secret fields do not display stored values. They show whether a value is configured; entering a new value writes it, and reset clears the explicit path. Prefer command-based secret options such as `jimaku.apiKeyCommand` when available.
Saving validates the candidate config before writing. Live-reloadable changes are applied immediately; other changes return a restart-required banner in the window.
-## Configuration File
+## Configuration file
The Settings window writes to `config.jsonc` directly, so most users do not need to edit the file by hand. The config file and the option reference below are provided for advanced use, scripting, or cases where you prefer editing config directly.
@@ -95,7 +97,7 @@ For valid JSON/JSONC with invalid option values, SubMiner uses warn-and-fallback
On macOS, these validation warnings also open a native dialog with full details (desktop notification banners can truncate long messages).
-### Hot-Reload Behavior
+### Hot-reload behavior
SubMiner watches the active config file (`config.jsonc` or `config.json`) while running and applies supported updates automatically.
@@ -103,7 +105,7 @@ Hot-reloadable settings include subtitle appearance, sidebar controls, keybindin
shortcuts, notifications, logging level, selected source-language preferences,
Jimaku/Subsync settings, AniSkip settings (`mpv.aniskipEnabled`, `mpv.aniskipButtonKey`),
stats keys (`stats.toggleKey`, `stats.markWatchedKey`), the secondary-subtitle default
-mode, and the Anki deck, known-word, N+1, field, sentence-card, AI, and Kiku options
+mode, and the Anki deck, known-word, N+1, field, sentence-card, and Kiku options
listed in the reference tables below.
When these values change, SubMiner applies them live. Invalid config edits are rejected and the previous valid runtime config remains active.
@@ -111,11 +113,10 @@ When these values change, SubMiner applies them live. Invalid config edits are r
Restart-required changes:
- Any other config sections still require restart.
-- Shared top-level `ai` provider settings still require restart.
- AnkiConnect transport/proxy/media/tag fields still require restart unless listed above.
- SubMiner shows an on-screen/system notification listing restart-required sections when they change.
-### Configuration Options Overview
+### Configuration options Overview
The configuration file includes several main sections:
@@ -146,7 +147,6 @@ The configuration file includes several main sections:
**Anki Integration**
-- [**Shared AI Provider**](#shared-ai-provider) - Canonical OpenAI-compatible provider config shared by Anki and YouTube subtitle fixing
- [**AnkiConnect**](#ankiconnect) - Automatic Anki card creation with media
- [**Kiku/Lapis Integration**](#kiku-lapis-integration) - Sentence cards and duplicate handling for Kiku/Lapis/Senren note types
- [**N+1 Word Highlighting**](#n-1-word-highlighting) - Known-word cache and single-target highlighting
@@ -169,7 +169,7 @@ The configuration file includes several main sections:
- [**Updates**](#updates) - Automatic update checks, notifications, and prerelease testing
- [**Notifications**](#notifications) - Overlay notification placement
-## Core Settings
+## Core settings
### Logging
@@ -244,13 +244,13 @@ Configure where overlay notification cards appear:
#### Notification history panel
-Every overlay notification shown during a session is also recorded in a notification history panel. Press `Ctrl/Cmd+N` (configurable via [`shortcuts.toggleNotificationHistory`](#shortcuts-configuration)) to toggle the panel; the binding works whether the overlay or mpv has focus. The panel slides in from the same edge the notifications use — left when `overlayPosition` is `"top-left"`, and right for `"top-right"` or `"top"` (centered). Character dictionary sync uses one live card but records each distinct phase in history. Each entry can be removed individually, or use **Clear** to empty the history. History is session-only and is not persisted across restarts.
+Every overlay notification shown during a session is also recorded in a notification history panel. Press `Ctrl/Cmd+N` (configurable via [`shortcuts.toggleNotificationHistory`](#shortcuts-configuration)) to toggle the panel; the binding works whether the overlay or mpv has focus. The panel slides in from the same edge the notifications use, so left when `overlayPosition` is `"top-left"` and right for `"top-right"` or `"top"` (centered). Character dictionary sync uses one live card but records each distinct phase in history. Each entry can be removed individually, or use **Clear** to empty the history. History is session-only and is not persisted across restarts.
Startup tokenization, subtitle annotation, and character dictionary status follow the configured notification surface. When the surface is `"overlay"` or `"both"`, SubMiner queues those startup notifications until the overlay renderer is ready instead of falling back to mpv OSD. If loading and ready states both finish before the overlay can paint, the loading card is delivered first and then updates to ready shortly after. With `"both"`, character dictionary checking/building/importing/ready status also goes to system notifications; building and importing are only emitted when that work is actually needed. The bundled mpv plugin only shows its startup OSD messages when `ankiConnect.behavior.notificationType` is set to `"osd"` or `"osd-system"` in `config.jsonc`; AniSkip prompts and skip result messages are playback feedback and still route to overlay notifications when configured.
The equivalent direct CLI command is `--playback-feedback ` (`playbackFeedback` internally). It sends that one non-empty feedback string through the same route controlled by `ankiConnect.behavior.notificationType`; it does not change the saved config.
-### Auto-Start Overlay
+### Auto-start overlay
Control whether the overlay automatically becomes visible when it connects to mpv:
@@ -268,7 +268,7 @@ When you launch through the SubMiner app or the `subminer` wrapper, the launcher
On Windows, packaged plugin installs also rewrite the plugin socket path to `\\.\pipe\subminer-socket`.
-### Startup Warmups
+### Startup warmups
Control which startup warmups run in the background versus deferring to first real usage:
@@ -294,7 +294,7 @@ Control which startup warmups run in the background versus deferring to first re
Defaults warm local tokenizer/dictionary work (`true` for `mecab`, `yomitanExtension`, and `subtitleDictionaries`) with `lowPowerMode: false`; Jellyfin remote session warmup is opt-in (`false` by default). Setting a warmup toggle to `false` defers that work until first usage.
-### WebSocket Server
+### WebSocket server
The overlay includes a built-in WebSocket server that broadcasts plain subtitle text to connected clients for external processing.
@@ -358,9 +358,9 @@ See `config.example.jsonc` for detailed configuration options.
| `launchAtStartup` | `true`, `false` | Start texthooker automatically with SubMiner startup (default: `false`) |
| `openBrowser` | `true`, `false` | Open browser tab when texthooker starts (default: `false`) |
-## Subtitle Display
+## Subtitle display
-### Subtitle Style
+### Subtitle style
Customize the appearance of primary and secondary subtitles:
@@ -458,7 +458,7 @@ Secondary subtitle styling lives in the secondary subtitle CSS object. Any CSS p
**See `config.example.jsonc`** for the complete list of subtitle style configuration options.
-### Subtitle Sidebar
+### Subtitle sidebar
Configure the parsed-subtitle sidebar modal.
@@ -520,7 +520,7 @@ For full details on layout modes, behavior, and the keyboard shortcut, see the [
| `N4` | `#8bd5ca` | JLPT N4 underline color |
| `N5` | `#8aadf4` | JLPT N5 underline color |
-### Subtitle Position
+### Subtitle position
Set the initial vertical subtitle position (measured from the bottom of the screen):
@@ -538,7 +538,7 @@ Set the initial vertical subtitle position (measured from the bottom of the scre
In the overlay, you can fine-tune subtitle position at runtime with `Right-click + drag` on subtitle text.
-### Secondary Subtitles
+### Secondary subtitles
Display a second subtitle track (e.g., English alongside Japanese) in the overlay:
@@ -564,8 +564,6 @@ Secondary subtitles do **not** auto-load by default. To turn them on for local a
These two settings apply to local and Jellyfin playback only. YouTube secondary selection is fixed to English and ignores them; see [YouTube Integration](/youtube-integration#secondary-subtitle-languages). `defaultMode` still controls how the loaded secondary bar is displayed in every case.
-Because the mined-card translation field is filled from the secondary subtitle when one is present, leaving `autoLoadSecondarySub` off means local-file cards fall back to AI translation (when configured) or the original sentence text.
-
The secondary-subtitle language list also acts as the fallback secondary-language priority for managed startup subtitle selection on local playback and YouTube playback.
**Display modes:**
@@ -576,7 +574,7 @@ The secondary-subtitle language list also acts as the fallback secondary-languag
**See `config.example.jsonc`** for additional secondary subtitle configuration options.
-## Keyboard & Controls
+## Keyboard and controls
### Keybindings
@@ -639,11 +637,16 @@ See `config.example.jsonc` for detailed configuration options and more examples.
**Supported commands:** Any valid mpv JSON IPC command array (`["cycle", "pause"]`, `["seek", 5]`, `["script-binding", "..."]`, etc.)
+Supported, unclaimed single-key keyboard bindings from the connected mpv session are also available
+in the overlay automatically. Configured SubMiner bindings, including `null` entries,
+take precedence. See [mpv binding discovery](/shortcuts#automatic-mpv-bindings) for session refresh
+behavior and limitations.
+
Subtitle delay commands (`sub-delay`, `sub-step`) show a native mpv OSD notification after the command runs. Subtitle-position and subtitle-track proxy commands (`sub-pos`, `sid`, `secondary-sid`) show playback feedback through the configured notification surface.
**See `config.example.jsonc`** for more keybinding examples and configuration options.
-### Shortcuts Configuration
+### Shortcuts configuration
Customize or disable the overlay keyboard shortcuts:
@@ -704,7 +707,7 @@ Set any shortcut to `null` to disable it.
Feature-dependent shortcuts/keybindings only run when their related integration is enabled. For example, Anki/Kiku shortcuts require `ankiConnect.enabled` (and Kiku-specific behavior where applicable), and Jellyfin remote startup behavior requires Jellyfin to be enabled.
-### Controller Support
+### Controller support
SubMiner can read controllers through the Chrome Gamepad API and map them onto the existing keyboard-only overlay workflow.
@@ -820,7 +823,7 @@ If you update this controller documentation or the generated controller examples
Tune `scrollPixelsPerSecond`, `horizontalJumpPixels`, deadzones, repeat timing, and profile `buttonIndices` to match your controller. See [config.example.jsonc](/config.example.jsonc) for the full generated comments for every controller field.
-### Manual Card Update Shortcuts
+### Manual card update shortcuts
When automatic card updates are disabled, new cards are detected but not automatically updated. Use these keyboard shortcuts for manual control:
@@ -847,7 +850,7 @@ When automatic card updates are disabled, new cards are detected but not automat
These shortcuts are only active when the overlay window is visible and automatically disabled when hidden.
-### Session Help Modal
+### Session help modal
The session help modal opens from the overlay with `Ctrl/Cmd+/` by default. The mpv plugin also exposes it through the `y-h` chord. It shows the current session keybindings and color legend.
@@ -871,13 +874,14 @@ The list is generated at runtime from:
When config hot-reload updates shortcut/keybinding/style values, close and reopen the help modal to refresh the displayed entries.
-### Runtime Option Palette
+### Runtime option palette
Use the runtime options palette to toggle settings live while SubMiner is running. These changes are session-only and reset on restart.
-Current runtime options cover automatic card updates, known-word highlighting,
-known-word maturity coloring, N+1 annotation, JLPT underlines, frequency
-highlighting, known-word match mode, and Kiku field grouping mode.
+Current runtime options cover automatic card updates, media timing review,
+known-word highlighting, known-word maturity coloring, N+1 annotation, JLPT
+underlines, frequency highlighting, known-word match mode, and Kiku field
+grouping mode.
Annotation toggles only apply to new subtitle lines after the toggle. The currently displayed line is not re-tokenized in place.
@@ -890,39 +894,7 @@ Palette controls:
- `Enter`: apply selected value
- `Esc`: close
-## Anki Integration
-
-### Shared AI Provider
-
-This is the single, shared connection to an OpenAI-compatible LLM endpoint. Configure it **once** here at the top level, and SubMiner reuses it wherever AI is needed (Anki translation/enrichment and YouTube subtitle fixing). Per-feature toggles and prompt/model tweaks live in their own sections (for example `ankiConnect.ai` and `youtubeSubgen.ai`) and inherit this transport.
-
-```json
-{
- "ai": {
- "enabled": false,
- "apiKey": "",
- "apiKeyCommand": "",
- "model": "openai/gpt-4o-mini",
- "baseUrl": "https://openrouter.ai/api",
- "requestTimeoutMs": 15000
- }
-}
-```
-
-| Option | Values | Description |
-| ------------------ | -------------------- | ------------------------------------------------------------------------------------ |
-| `ai.enabled` | `true`, `false` | Enable shared AI provider features (default: `false`) |
-| `apiKey` | string | Static API key for the shared provider |
-| `apiKeyCommand` | string | Shell command used to resolve the API key (preferred over a plaintext `apiKey`) |
-| `model` | string | Default model identifier requested from the provider (default: `openai/gpt-4o-mini`) |
-| `baseUrl` | string (URL) | OpenAI-compatible base URL (default: `https://openrouter.ai/api`) |
-| `systemPrompt` | string | Default system prompt sent with requests (default: a translation-engine prompt) |
-| `requestTimeoutMs` | integer milliseconds | Shared request timeout (default: `15000`) |
-
-SubMiner uses the shared provider for:
-
-- Anki translation/enrichment when Anki AI is enabled
-- YouTube generated-subtitle fixing when `youtubeSubgen.fixWithAi` is enabled (with optional `youtubeSubgen.ai.model` / `systemPrompt` overrides)
+## Anki integration
### AnkiConnect
@@ -944,16 +916,10 @@ Enable automatic Anki card creation and updates with media generation:
"deck": "Learning::Japanese",
"fields": {
"word": "Expression",
- "audio": "ExpressionAudio",
+ "audio": "SentenceAudio",
"image": "Picture",
"sentence": "Sentence",
- "miscInfo": "MiscInfo",
- "translation": "SelectionText"
- },
- "ai": {
- "enabled": false,
- "model": "",
- "systemPrompt": ""
+ "miscInfo": "MiscInfo"
},
"media": {
"generateAudio": true,
@@ -969,6 +935,7 @@ Enable automatic Anki card creation and updates with media generation:
"animatedCrf": 35,
"normalizeAudio": true,
"mirrorMpvVolume": true,
+ "reviewTiming": false,
"audioPadding": 0,
"fallbackDuration": 3,
"maxMediaDuration": 30
@@ -1010,17 +977,14 @@ This example is intentionally compact. The option table below documents availabl
| `tags` | array of strings | Tags automatically added to cards mined/updated by SubMiner (default: `['SubMiner']`; set `[]` to disable automatic tagging). |
| `ankiConnect.deck` | string | Restrict duplicate detection and card enrichment to this Anki deck. Leave empty to use the Yomitan mining deck when available. In Settings, this dropdown auto-fills and persists Yomitan's current mining deck when available. |
| `fields.word` | string | Card field for mined word / expression text (default: `Expression`) |
-| `fields.audio` | string | Card field for audio files (default: `ExpressionAudio`) |
+| `fields.audio` | string | Card field for the generated sentence audio clip (default: `ExpressionAudio`). Set this to a dedicated field such as `SentenceAudio` so it does not collide with the word audio Yomitan writes. |
| `fields.image` | string | Card field for images (default: `Picture`) |
| `fields.sentence` | string | Card field for sentences (default: `Sentence`) |
| `fields.miscInfo` | string | Card field for metadata (default: `"MiscInfo"`, set to `null` to disable) |
-| `fields.translation` | string | Card field for sentence-card translation/back text (default: `SelectionText`) |
-| `ankiConnect.ai.enabled` | `true`, `false` | Use AI translation for sentence cards. Also auto-attempted when secondary subtitle is missing. |
-| `ankiConnect.ai.model` | string | Optional model override for Anki AI translation/enrichment flows. |
-| `ankiConnect.ai.systemPrompt` | string | Optional system prompt override for Anki AI translation/enrichment flows. |
| `media.generateAudio` | `true`, `false` | Generate audio clips from video (default: `true`) |
| `media.normalizeAudio` | `true`, `false` | Normalize generated sentence-audio loudness during media extraction (default: `true`). Set to `false` to keep raw source loudness. Changes apply live. |
| `media.mirrorMpvVolume` | `true`, `false` | Apply mpv's cubic software-volume curve to each generated sentence-audio clip (default: `true`). This ignores mpv's separate mute state, falls back to unity scaling if volume cannot be read, and applies changes live. |
+| `media.reviewTiming` | `true`, `false` | Pause playback and review word, sentence, and audio card timing before media generation (default: `false`). Clipboard updates and stats-dashboard mining do not open the review. |
| `media.generateImage` | `true`, `false` | Generate image/animation screenshots (default: `true`) |
| `media.imageType` | `"static"`, `"avif"` | Image type: static screenshot or animated AVIF (default: `"static"`) |
| `media.imageFormat` | `"jpg"`, `"png"`, `"webp"` | Image format (default: `"jpg"`) |
@@ -1055,10 +1019,7 @@ This example is intentionally compact. The option table below documents availabl
| `isKiku` | object | Kiku-only config: `{ enabled, fieldGrouping, deleteDuplicateInAuto }` (shared sentence/audio/model settings are inherited from `isLapis`) |
| `isSenren` | object | Senren-only config: `{ enabled, fieldGrouping, deleteDuplicateInAuto }`. Merges duplicates using Senren's scene-switching markup. Mutually exclusive with `isKiku.enabled`. |
-`ankiConnect.ai` only controls feature-local enablement plus optional `model` / `systemPrompt` overrides.
-API key resolution, base URL, and timeout live under the shared top-level [`ai`](#shared-ai-provider) config.
-
-### Kiku/Lapis Integration
+### Kiku/Lapis integration
SubMiner is intentionally built for [Kiku](https://kiku.youyoumu.my.id/) and [Lapis](https://github.com/donkuri/lapis) workflows, with note-type-specific behavior built into Anki settings.
@@ -1086,7 +1047,7 @@ SubMiner is intentionally built for [Kiku](https://kiku.youyoumu.my.id/) and [La
- For [Senren](https://github.com/BrenoAqua/Senren) note types, enable `isSenren` instead of `isKiku`. Duplicate merges then use Senren's scene-switching markup (including grouped `miscInfo` entries), and `isSenren.fieldGrouping` supports the same three modes (default: `auto`). Kiku and Senren are mutually exclusive; if both are enabled, Kiku wins and Senren is turned off with a config warning.
- `lapisKiku.wordCardKind` picks the card-type flag set on word cards; see [Word Card Type](#word-card-type). It is read only while `isLapis` or `isKiku` is enabled.
-### Word Card Type
+### Word card type
When SubMiner fills the sentence on a mined word card - from Yomitan auto-enrichment, a manual clipboard update, or stats-dashboard word mining - it marks which card that note should generate. `ankiConnect.lapisKiku.wordCardKind` chooses the flag:
@@ -1100,7 +1061,7 @@ When SubMiner fills the sentence on a mined word card - from Yomitan auto-enrich
The other card-type flags are cleared so a note never claims two card types at once. Notes are skipped when the note type has no field for the chosen flag, and when the note was already mined as a sentence or audio card. Cards created by Mine Sentence and Mine Audio keep their own flag regardless of this setting.
-### N+1 Word Highlighting
+### N+1 word highlighting
When known-word highlighting is enabled, SubMiner builds a local cache of known words from Anki to highlight already learned tokens in subtitle rendering.
@@ -1137,7 +1098,7 @@ To refresh roughly once per day, set:
}
```
-### Field Grouping Modes
+### Field grouping modes
| Mode | Behavior |
| ---------- | -------------------------------------------------------------------------------------------------------------------------- |
@@ -1156,7 +1117,7 @@ When the manual merge popup opens, SubMiner pauses playback and closes any open
Open demo in a new tab
-## External Integrations
+## External integrations
### Anime Browser
@@ -1227,7 +1188,15 @@ The keyboard shortcut lives under `shortcuts.openTsukihime` (default `Ctrl+Shift
See [TsukiHime Integration](/tsukihime-integration) for the modal workflow, language tabs, and troubleshooting.
-### Subtitle Sync
+### Japanese subtitle generation
+
+Open the standalone modal with `Ctrl+Shift+G`, configurable through `shortcuts.openSubtitleGeneration`, or use the subtitle sidebar button. See [shortcuts](/shortcuts) for the shared mpv and overlay keybindings.
+
+`subtitleGeneration` configures local Japanese transcription for both the launcher and overlay. In **Settings → Integrations → Japanese Subtitle Generation**, set `modelPath` to an existing multilingual whisper.cpp GGML model, or leave it empty and choose a `managedModel` as the default. The generation modal lets you select another model for the current session, with download sizes and accuracy versus speed guidance. Downloads are explicit. Leave `whisperPath`, `ffmpegPath`, and `ffprobePath` empty to find the executables on `PATH`, or set them to override the executable paths. `threads` controls the CPU thread count. Settings apply to the next operation. See [subtitle generation](/subtitle-generation) for setup and behavior, and the [generated configuration example](/config.example.jsonc) for defaults.
+
+The generation modal offers an optional **Focus on spoken dialogue** checkbox and a separate Silero model download. Set `subtitleGeneration.vadModelPath` to a Silero GGML VAD model to make dialogue mode the default. `vadPath` overrides the speech detector executable. See [dialogue generation setup](/subtitle-generation#prioritizing-spoken-dialogue) for session behavior, the additional tool, and limitations.
+
+### Subtitle sync
Sync a subtitle track from the overlay picker using `alass` or `ffsubsync`. The picker lets you choose which track gets retimed (the active primary track by default) and, for alass, which reference it is aligned against (the secondary subtitle track by default). Both are **optional external tools** that must be installed separately and available on your `PATH` (or configured via the path options below).
@@ -1421,7 +1390,7 @@ Jellyfin playback auto-launched through SubMiner loads the mpv plugin the same w
When Jellyfin is enabled with a server URL and SubMiner is running, the tray menu also shows a `Jellyfin Discovery` checkbox. It starts or stops discovery for the current runtime session only and does not write config. Starting discovery still requires a valid stored or environment-provided Jellyfin auth session.
-### Discord Rich Presence
+### Discord rich presence
Discord Rich Presence is enabled by default. SubMiner publishes a polished activity card that reflects current media title, playback state, and session timer unless you turn it off.
@@ -1468,7 +1437,7 @@ Troubleshooting:
- If images do not render, confirm asset keys exactly match uploaded Discord asset names.
- If Discord is closed/not installed/disconnects, SubMiner continues running and quietly skips presence updates.
-### Immersion Tracking
+### Immersion tracking
Enable or disable local immersion analytics stored in SQLite for mined subtitles and media sessions. This data also powers the stats dashboard:
@@ -1542,7 +1511,7 @@ Set `dbPath` only if you want to relocate the database (for backup, syncing, or
See [Immersion Tracking Storage](/immersion-tracking) for schema details, query templates, dashboard access, retention/rollup behavior, backend portability notes, and the dedicated SQLite verification command.
-### Stats Dashboard
+### Stats dashboard
Configure the local stats UI served from SubMiner and the in-app stats overlay toggle:
@@ -1573,7 +1542,7 @@ Usage notes:
- The dashboard reads from the same immersion-tracking database, so keep `immersionTracking.enabled` on if you want data to appear.
- The UI includes Overview, Library, Trends, Vocabulary, Search, and Sessions tabs.
-### MPV Launcher
+### MPV launcher
Configure the mpv executable, profile, and window state for SubMiner-managed mpv launches (launcher playback, Windows `--launch-mpv`, and Jellyfin idle mpv startup):
@@ -1615,7 +1584,7 @@ Launch mode behavior:
- **`maximized`** - mpv starts maximized via `--window-maximized=yes`, keeping taskbar access.
- **`fullscreen`** - mpv starts in true fullscreen via `--fullscreen`.
-### YouTube Playback Settings
+### YouTube playback settings
Set defaults used by managed subtitle auto-selection and the `subminer` launcher YouTube flow:
@@ -1659,6 +1628,6 @@ Track selection:
These settings come from `config.jsonc` (or built-in defaults); there are no CLI flags or environment variables for subtitle language selection.
-#### YouTube Subtitle Generation (`youtubeSubgen`)
+#### YouTube subtitle generation (`youtubeSubgen`)
-An advanced, template-hidden section for Whisper-based YouTube subtitle generation: `whisperBin`, `whisperModel`, `whisperVadModel`, `whisperThreads` (default `4`), and `fixWithAi` (default `false`), which post-processes generated subtitles through the [Shared AI Provider](#shared-ai-provider) with optional `youtubeSubgen.ai.model` / `systemPrompt` overrides. These keys are accepted in `config.jsonc` but intentionally omitted from the generated template.
+An advanced, template-hidden section for Whisper-based YouTube subtitle generation: `whisperBin`, `whisperModel`, `whisperVadModel`, and `whisperThreads` (default `4`). These keys are accepted in `config.jsonc` but the generated template omits them.
diff --git a/docs-site/demos.md b/docs-site/demos.md
index e0097d4e..c947fb40 100644
--- a/docs-site/demos.md
+++ b/docs-site/demos.md
@@ -1,6 +1,8 @@
-# Feature Demos
+# Feature demos
-Short recordings of SubMiner's key features and integrations from real playback sessions. A few terms you'll see below: _Yomitan_ is the pop-up dictionary used for word lookups, _Jimaku_ is a community subtitle database, _alass_ and _ffsubsync_ are tools that retime subtitles to match the audio, _Jellyfin_ is a self-hosted media server, and a _texthooker_ is a web page that mirrors the current subtitle as selectable text for browser-based tools.
+Short recordings from real playback sessions.
+
+Some vocabulary for what follows. _Yomitan_ is the pop-up dictionary. _Jimaku_ is a community subtitle database. _alass_ and _ffsubsync_ retime subtitles against the audio. _Jellyfin_ is a self-hosted media server. A _texthooker_ is a web page that mirrors the current subtitle as selectable text so browser tools can read it.
-## Anki Card Mining & Enrichment
+## Anki card mining and enrichment
-Mine vocabulary cards from Yomitan or directly from subtitle lines. SubMiner automatically attaches the sentence, a timing-accurate audio clip, a screenshot, and a translation.
+Mine a card from Yomitan or straight from a subtitle line. SubMiner attaches the sentence, an audio clip cut to the line timing, and a screenshot.
-## Subtitle Download & Sync
+## Subtitle download and sync
-Search and download subtitles from Jimaku, then retime them with alass or ffsubsync - all from within SubMiner.
+Search Jimaku, download a track, then retime it with alass or ffsubsync without leaving SubMiner.
B
B --> C
C --> D
- D -- startup --> E
- D -- user request --> F
+ D - startup --> E
+ D - user request --> F
E --> G
F --> G
G --> H
@@ -52,7 +52,7 @@ flowchart TD
K --> L
```
-## Auto-Load Flow
+## Auto-load flow
On startup with a YouTube URL:
@@ -66,7 +66,7 @@ On startup with a YouTube URL:
6. Missing tracks are downloaded to a temp directory and loaded via `sub-add`.
7. Playback unpauses once the primary subtitle is ready.
-## Manual Subtitle Picker
+## Manual subtitle picker
Press **Ctrl+Alt+C** during YouTube playback to open the subtitle picker overlay. This lets you:
@@ -80,27 +80,27 @@ card to a success notification after the selected tracks load.
The picker displays each track with its language, kind (manual/auto), and title when available.
-## Subtitle Format Handling
+## Subtitle format handling
SubMiner handles several YouTube subtitle formats transparently:
| Format | Handling |
| ---------------------- | -------------------------------------------------------- |
| `srt`, `vtt` | Used directly (preferred for manual tracks) |
-| `srv1`, `srv2`, `srv3` | YouTube TimedText XML --- converted to VTT automatically |
+| `srv1`, `srv2`, `srv3` | YouTube TimedText XML - converted to VTT automatically |
| Auto-generated VTT | Normalized to remove rolling-caption text duplication |
For auto-generated tracks, SubMiner prefers `srv3` > `srv2` > `srv1` > `vtt` (TimedText XML produces cleaner output). For manual tracks, `srt` > `vtt` is preferred.
-## Card Media Cache
+## Card media cache
By default, YouTube card audio and screenshots are extracted directly from mpv's active stream URLs. If generated card media fails with YouTube `403` errors, set `youtube.mediaCache.mode` to `"background"`. Background mode starts a separate `yt-dlp` media download after playback loads, including YouTube URLs opened directly in mpv and resolved stream URLs when mpv still exposes the original YouTube playlist entry. It creates text fields immediately, queues audio/image work for mined notes, and fills those fields once the local cache file is ready.
Background cache downloads are capped at 720p by default (`youtube.mediaCache.maxHeight`; set `0` for unlimited) and use IPv4 and retry flags to reduce YouTube throttling failures. If the background download still fails, SubMiner shows a cache failure notification, shows queued-card failure notifications, and clears those pending updates so cards are not left waiting silently.
-## Configuration Reference
+## Configuration reference
-### Primary Subtitle Languages
+### Primary subtitle languages
```jsonc
{
@@ -114,11 +114,11 @@ Background cache downloads are capped at 720p by default (`youtube.mediaCache.ma
| --------------------- | ---------- | ------------------------------------------------------------------------------------- |
| `primarySubLanguages` | `string[]` | Languages that count as a satisfactory primary subtitle (default `["ja", "jpn"]`). Used by the "primary subtitle missing" notification and by managed local/playlist subtitle selection. |
-YouTube auto-selection itself always picks a Japanese track first (manual over auto), then falls back to any manual track — `primarySubLanguages` does not change which YouTube track is auto-picked.
+YouTube auto-selection itself always picks a Japanese track first (manual over auto), then falls back to any manual track. `primarySubLanguages` does not change which YouTube track is auto-picked.
-### Secondary Subtitle Languages
+### Secondary subtitle languages
-YouTube secondary selection is fixed: SubMiner always tries an English track (manual over auto) and loads it when found. The shared `secondarySub` config does not change YouTube track selection — `secondarySubLanguages` and `autoLoadSecondarySub` apply only to local/Jellyfin sidecar selection — but `defaultMode` still controls how the loaded secondary bar is displayed:
+YouTube secondary selection is fixed: SubMiner always tries an English track (manual over auto) and loads it when found. The shared `secondarySub` config does not change YouTube track selection. `secondarySubLanguages` and `autoLoadSecondarySub` apply only to local and Jellyfin sidecar selection. `defaultMode` still controls how the loaded secondary bar is displayed:
```jsonc
{
@@ -138,10 +138,10 @@ YouTube secondary selection is fixed: SubMiner always tries an English track (ma
These settings come from `config.jsonc` (or built-in defaults); there are no CLI flags or environment variables for subtitle language selection.
-## Limitations and Troubleshooting
+## Limitations and troubleshooting
- **No subtitles found**: The video may not have Japanese subtitles. Open the picker with `Ctrl+Alt+C` to see all available tracks.
-- **yt-dlp not found**: Install `yt-dlp` and ensure it is on `PATH`, or set `SUBMINER_YTDLP_BIN` to the binary path.
+- **yt-dlp not found**: Install `yt-dlp` and put it on `PATH`, or set `SUBMINER_YTDLP_BIN` to the binary path.
- **Probe timeout**: `yt-dlp` has a 15-second timeout per operation. Slow connections or rate-limited IPs may hit this. Retry or update `yt-dlp`.
- **Card media `403` errors**: Switch `youtube.mediaCache.mode` from `"direct"` to `"background"` so card media is generated from a local `yt-dlp` cache instead of ffmpeg reading an expiring YouTube stream URL.
- **Auto-caption quality**: YouTube auto-generated captions vary in quality. Manual subtitles (when available) are always preferred.
@@ -149,10 +149,10 @@ These settings come from `config.jsonc` (or built-in defaults); there are no CLI
- **Secondary subtitle fails**: Secondary track failures never block playback. The primary subtitle loads independently.
- **Native mpv secondary rendering**: Stays hidden during YouTube flows so the SubMiner overlay remains the visible secondary subtitle surface.
-## Related Pages
+## Related pages
-- [Usage --- YouTube Playback](/usage#youtube-playback)
-- [Configuration --- YouTube Playback Settings](/configuration#youtube-playback-settings)
-- [Configuration --- Secondary Subtitles](/configuration#secondary-subtitles)
+- [Usage - YouTube Playback](/usage#youtube-playback)
+- [Configuration - YouTube Playback Settings](/configuration#youtube-playback-settings)
+- [Configuration - Secondary Subtitles](/configuration#secondary-subtitles)
- [Keyboard Shortcuts](/shortcuts)
- [Jellyfin Integration](/jellyfin-integration)
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index cdc4e8e6..8438610c 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -11,6 +11,48 @@
`ANTHROPIC_API_KEY` works. Install from if
you don't already have it.
+## Package contents and size checks
+
+Stable and prerelease workflows share `.github/workflows/package-release.yml`.
+Both callers explicitly pass the five required macOS signing/notarization
+secrets; `GITHUB_TOKEN` remains automatically available to the reusable workflow.
+Each platform verifies its ASAR and external resources before signing, then
+measures the signed app and installers before upload. Missing runtime assets,
+foreign SQLite/Koffi binaries, duplicate UI fonts, demo media, source maps,
+TypeScript files, and nested test or fixture directories
+fail the build. Size measurements are informational and do not block releases.
+Current targets are Linux x64, macOS arm64, and Windows x64.
+
+The runtime allowlist includes `dist/`, `stats/dist/`, and
+`vendor/texthooker-ui/docs/` plus metadata, config example, and license. The
+texthooker `docs/` directory is its built UI. Keep the positive `package.json`
+pattern in platform `files` lists: electron-builder otherwise treats an
+exclusion-only platform list as a separate include-all matcher. Windows keeps
+only its target Koffi binary; other platforms omit Koffi. Desktop UIs share the
+original M PLUS 1 TTF in `dist/fonts/`.
+
+`release/package-size--.json` reports unpacked bytes, largest
+files inside and outside ASAR, native binaries, and compressed artifact sizes.
+Framework symlinks are not counted twice. Reports are checksummed and published.
+CI downloads the preceding release's reports for comparison; older releases
+without reports skip comparison. Review the inventory and reason for growth
+when comparing releases. An AppImage normally
+runs compressed; its extracted size is a separate measurement.
+
+The shared workflow runs `bun run test:package ` with the
+pinned Electron runtime and temporary user data. On headless Linux, prefix it
+with `xvfb-run -a`. This checks packaged SQLite, Windows FFI loading/polling,
+texthooker serving, Yomitan loading, UI assets, and Japanese font loading.
+Standalone pages lack app IPC handlers and can log related errors; this check
+does not replace an installed app session.
+
+Before shipping packaging changes, check each platform's installed app:
+startup and mpv tracking, dictionary lookup and stroke orders, settings/sync UI,
+stats persistence, sentence mining with AnkiConnect, and updating from the prior
+release. Preserve Electron locales, graphics fallbacks, codecs, dictionaries,
+license notices, updater metadata, blockmaps, and the macOS updater ZIP. Trim
+files before signing and generating updater hashes, never from a signed app.
+
## Stable Release
1. Confirm `main` is green: `gh run list --workflow CI --limit 5`.
@@ -31,6 +73,14 @@
`bun run test:fast`
`bun run test:env`
`bun run build`
+ Confirm `dist/launcher` contains only `subminer`, `subminer.cmd`,
+ `subminer.js`, `prepare.cjs`, and `version`. Release CI smoke-tests
+ `subminer.js` with Bun, then publishes both wrapper files and their checksums.
+ Tagged CI runs `bun scripts/package-bun-source.mjs` and must publish
+ `bun-v-source.tar.gz` plus its `.sha256` file. The script
+ fails if Bun's CMake dependency pins, WebKit pin, source checksums, patch
+ inputs, or collected license files differ from
+ `build/bun-source-manifest.json`.
When validating auto-update metadata, also run the relevant platform package
build and confirm `release/` contains the generated updater metadata
(`latest*.yml`) and blockmaps (`*.blockmap`).
@@ -54,6 +104,11 @@
`bun run test:fast`
`bun run test:env`
`bun run build`
+ Confirm both launcher wrappers and their checksums are included in the
+ prerelease assets.
+ Prerelease CI also assembles and publishes the pinned Bun corresponding
+ source archive. A missing source repository or license file fails the
+ release instead of publishing only the executable.
When validating packaged updater output, confirm the platform build writes
`latest*.yml` and `*.blockmap` files under `release/`.
5. Commit the prerelease prep (package.json version bump + the generated
@@ -97,6 +152,7 @@ Notes:
- AUR publish is best-effort: the workflow retries transient SSH clone/push failures, then warns and leaves the GitHub Release green if AUR still fails. Follow up with a manual `git push aur master` from the AUR checkout when needed.
- Required GitHub Actions secret: `AUR_SSH_PRIVATE_KEY`. Add the matching public key to your AUR account before relying on the automation.
- Release and prerelease workflows upload updater metadata (`latest*.yml`) and blockmaps (`*.blockmap`) alongside platform artifacts. Do not remove those files while `electron-updater` is enabled.
+- Release and prerelease workflows publish `subminer` for POSIX systems and `subminer.cmd` for Windows. Both locate a packaged app and use its private Bun runtime. Keep the corresponding-source archive named `bun-v1.3.5-source.tar.gz`.
- macOS tray app updates use the standard `electron-updater`/Squirrel path. Keep `latest-mac.yml`, the macOS `SubMiner--mac.zip`, and ZIP blockmap published; Squirrel uses the ZIP payload even when the DMG remains the user-facing installer.
- macOS update metadata and full ZIP downloads are routed through `/usr/bin/curl` before Squirrel installation to avoid Electron main-process network crashes on update checks.
- Windows tray app updates use the standard `electron-updater`/NSIS path. Keep `latest.yml`, the Windows NSIS installer, and installer blockmap published; updater HTTP is routed through main-process fetch to avoid Electron main-process network crashes during update checks.
diff --git a/docs/architecture/README.md b/docs/architecture/README.md
index a0c4858a..e62e26df 100644
--- a/docs/architecture/README.md
+++ b/docs/architecture/README.md
@@ -10,11 +10,15 @@ Read when: runtime ownership, composition boundaries, or layering questions
SubMiner runs as three cooperating runtimes:
- Electron desktop app in `src/`
-- Launcher CLI in `launcher/`
+- Launcher CLI in `launcher/`, with managed app-installed wrappers in `src/main/runtime/managed-launcher.ts`
- mpv Lua plugin in `plugin/subminer/`
The desktop app keeps `src/main.ts` as composition root and pushes behavior into small runtime/domain modules.
+Packaged apps include a private Bun runtime. Setup and release assets provide bootstrap wrappers generated from `src/main/runtime/*-launcher-bootstrap.ts`. macOS runs Bun and the CLI from app resources. Windows stages a versioned private Bun copy under `%LOCALAPPDATA%\SubMiner\launcher-runtime/` so a running launcher does not lock the updater-owned app executable. Linux stages Bun, the matching CLI, and licenses under `${XDG_DATA_HOME:-~/.local/share}/SubMiner/launcher`. Its steady-state path performs one app `stat` and starts the cache without Electron. A missing cache or changed app fingerprint runs `launcher/prepare.cjs` through Electron's Node mode to refresh it. Desktop startup migrates recognized writable legacy JavaScript launchers and refreshes managed payloads after app changes. Development commands still use system Bun.
+
+Update checks and startup launcher migration share a serialized update-state store. Deferred launcher paths are acknowledged only after migration succeeds or the candidate is no longer eligible. Running Windows launchers and unreadable or unwritable candidates remain pending for a later startup.
+
## Read Next
- [Domains](./domains.md) - who owns what
@@ -27,6 +31,7 @@ The desktop app keeps `src/main.ts` as composition root and pushes behavior into
- `src/main/` owns composition, runtime setup, IPC wiring, and app lifecycle adapters.
- `src/main/boot/` owns boot-phase assembly seams so `src/main.ts` can stay focused on lifecycle coordination and startup-path selection.
- `src/core/services/` owns focused runtime services plus pure or side-effect-bounded logic.
+- `src/core/services/subtitle-generation*.ts` shares local whisper.cpp transcription, safe model downloads, and progress between the launcher and Electron. Optional dialogue mode retains both Silero-detected speech and other audible sections, omits confidently silent gaps, decodes passages independently, and restores original media timing. `src/main/runtime/subtitle-generation-runtime.ts` owns the overlay job lifecycle and only loads completed subtitles into the same local media; `src/shared/subtitle-generation*.ts` owns configuration, the multilingual model catalog, and IPC contracts. The overlay runtime retains a session model selection, validates picker requests through IPC, and keeps external model paths authoritative.
- `src/renderer/` owns overlay rendering and input behavior.
- `src/config/` owns config definitions, defaults, loading, and resolution.
- `src/types/` owns shared cross-runtime contracts via domain entrypoints; `src/types.ts` stays a compatibility barrel.
@@ -40,3 +45,7 @@ The desktop app keeps `src/main.ts` as composition root and pushes behavior into
- Composition over monoliths
- Pure helpers where possible
- Stable user behavior while internals evolve
+
+Startup resolves and creates the user-data directory in `src/main-entry-runtime.ts`
+before the entry process requests Electron's single-instance lock. Main-process
+config bootstrap then writes the default config only when no config file exists.
diff --git a/docs/architecture/domains.md b/docs/architecture/domains.md
index b4ef5d9a..fd8c6557 100644
--- a/docs/architecture/domains.md
+++ b/docs/architecture/domains.md
@@ -27,6 +27,8 @@ Read when: you need to find the owner module for a behavior or test surface
Includes stats storage/query schema such as `imm_videos`, `imm_media_art`, and `imm_youtube_videos` for per-video and YouTube-specific library metadata.
Library-entry identity aliases and merge recommendations are persisted alongside this schema; the stats HTTP and SPA layers only expose and present those domain decisions.
`delete-maintenance-scheduler.ts` coalesces and serializes stats deletes; the expensive work runs in `delete-maintenance-worker-thread.ts` while the tracker queues playback writes. Each batch uses one transaction, lexical update, rollup refresh, and incremental lifetime subtraction (`planLifetimeRemovals`/`applyLifetimeRemovals` in `lifetime.ts`). Merges, moves, AniList reassignments, and `stats cleanup -l` use `repairLifetimeSummariesFromMedia` (recompute from the per-video media ledger). The full lifetime rebuild survives only as the empty-table bootstrap; anywhere else it would collapse lifetime totals to the session retention window.
+- Immersion sync: `src/core/services/stats-sync/`, bound by `src/main/sync-cli.ts`.
+ `snapshot-transfer.ts` selects compressed rsync or scp. `transfer-cache.ts` atomically retains the last successfully received snapshot per hashed peer/database identity under the config directory's `sync-transfer-cache/`. Cache copies seed isolated transfer directories; rsync verifies reconstructed files before the existing merge engine runs. The `--make-temp` / `--remove-temp` helpers accept an internal `--transfer-cache` key, with a fallback for older peers that do not recognize it.
- AniList tracking + character dictionary: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*`, `src/main/character-dictionary-runtime.ts`, `src/main/character-dictionary-runtime/`
- Jellyfin integration: `src/core/services/jellyfin*.ts`, `src/main/runtime/composers/jellyfin-*`
- Anime browser: extension bridge client, sidecar, and stream handling in `src/anime-bridge/`;
@@ -47,6 +49,25 @@ Read when: you need to find the owner module for a behavior or test surface
## Shared Contract Entry Points
+Automatic mpv keyboard discovery uses the `get-mpv-input-bindings` IPC request and
+`MpvInputBindingsSnapshot` in `src/types/session-bindings.ts`.
+`src/main/runtime/mpv-input-bindings.ts` queries the connected player and preserves
+configured keys, including disabled entries. `src/shared/mpv-input-bindings.ts`
+validates discovered keys and translates browser input. The renderer's
+`handlers/mpv-input-forwarding.ts` keeps the session lookup, coalesces asynchronous
+refreshes, and releases held keys on blur or disposal. `handlers/keyboard.ts` runs
+this fallback after SubMiner controls and refreshes on startup, a delayed startup
+pass, focus, and binding reload. Discovery does not enter compiled session bindings,
+the plugin artifact, persistent config, or session help.
+
+The subtitle sidebar consumes parsed cues through `SubtitleSidebarSnapshot`. Its `sourceKey`
+identifies the media and subtitle source so renderer selections are invalidated on source changes,
+including changes whose cue text and timings are identical. Native selection and clean clipboard
+serialization live in `src/renderer/modals/subtitle-sidebar-selection.ts`. Electron lets standard
+Copy input reach the renderer, where sidebar selection takes priority over the live-subtitle binding.
+The preload bridge writes selections through Electron's clipboard API so copying does not depend
+on Chromium document focus or require activating the overlay window.
+
- Config + app-state contracts: `src/types/config.ts`
- Subtitle/token/media annotation contracts: `src/types/subtitle.ts`
- Runtime/window/controller/Electron bridge contracts: `src/types/runtime.ts`
diff --git a/docs/architecture/layering.md b/docs/architecture/layering.md
index ef7e1440..794f3c3e 100644
--- a/docs/architecture/layering.md
+++ b/docs/architecture/layering.md
@@ -23,7 +23,7 @@ Renderer, launcher, plugin, and stats each keep their own local layering and sho
- Keep side effects explicit and close to composition boundaries.
- Put reusable business logic in focused services, not in top-level lifecycle files.
- Keep renderer concerns in `src/renderer/`; avoid leaking DOM behavior into main-process code.
-- Treat `launcher/*.ts` as source of truth for the launcher. Never hand-edit `dist/launcher/subminer`.
+- Treat `launcher/*.ts` and the runtime bootstrap generators as source of truth for launcher behavior. `scripts/build-launcher.ts` creates `dist/launcher`; never hand-edit those artifacts.
## Smells
diff --git a/docs/workflow/verification.md b/docs/workflow/verification.md
index 51d1b212..7f9c41c3 100644
--- a/docs/workflow/verification.md
+++ b/docs/workflow/verification.md
@@ -23,6 +23,8 @@ Read when: selecting the right verification lane for a change
there instead of copying them into caller workflows.
- The reusable gate installs Lua and runs `bun run test:env`, so the shipped mpv
plugin tests run for every pull request and tagged release.
+ Lua installation uses only the runner's Ubuntu package sources so unrelated
+ third-party repository failures do not block the gate.
## Default Handoff Gate
@@ -50,6 +52,11 @@ bun run docs:build
- Runtime-compat / compiled behavior: `bun run test:runtime:compat`
- Stats dashboard UI: `bun run test:stats`
- Build/release scripts (`scripts/**`): `bun run test:scripts`
+- Packaging: build the platform package, then run `bun run test:package `.
+ On headless Linux: `xvfb-run -a bun run test:package release/linux-unpacked/resources`.
+ Content checks and informational size reporting run inside electron-builder hooks. See the
+ [release guide](../RELEASING.md#package-contents-and-size-checks) for size reports
+ and the installed-app verification checklist.
- Coverage for the maintained source lane: `bun run test:coverage:src`
- Deep/local full gate: default handoff gate above
diff --git a/launcher/commands/generate-subtitles-command.test.ts b/launcher/commands/generate-subtitles-command.test.ts
new file mode 100644
index 00000000..9f47632d
--- /dev/null
+++ b/launcher/commands/generate-subtitles-command.test.ts
@@ -0,0 +1,267 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import path from 'node:path';
+import { parseArgs } from '../config.js';
+import {
+ createGenerationProgressReporter,
+ runGenerateSubtitlesCommand,
+} from './generate-subtitles-command.js';
+
+type Deps = NonNullable[1]>;
+
+function fixture(argv: string[] = ['generate-subs', '/media/episode.mkv']) {
+ const output: string[] = [];
+ const commands: unknown[][] = [];
+ const generations: Parameters>[0][] = [];
+ let exitCode: number | undefined;
+ let interrupted: (() => void) | undefined;
+ let detached = false;
+ const context = {
+ args: parseArgs(argv, 'subminer', {}),
+ mpvSocketPath: '/tmp/test-subminer-socket',
+ processAdapter: {
+ writeStdout: (text: string) => {
+ output.push(text);
+ },
+ setExitCode: (code: number) => {
+ exitCode = code;
+ },
+ },
+ };
+ const deps: Deps = {
+ readConfig: () => ({ subtitleGeneration: { modelPath: '/models/external.bin' } }),
+ configPath: () => '/settings/SubMiner/config.jsonc',
+ resolveModel: async () => ({ kind: 'external', path: '/models/external.bin' }),
+ resolveTools: async () => ({
+ ffmpeg: { kind: 'found', path: '/usr/bin/ffmpeg' },
+ ffprobe: { kind: 'found', path: '/usr/bin/ffprobe' },
+ whisper: { kind: 'found', path: '/usr/bin/whisper-cli' },
+ vad: null,
+ }),
+ downloadModel: async () => {
+ throw new Error('Unexpected model download');
+ },
+ generate: async (input) => {
+ generations.push(input);
+ input.onProgress?.({
+ stage: 'transcribe',
+ percent: 50,
+ message: 'Transcribing Japanese audio',
+ });
+ return '/media/episode.ja.srt';
+ },
+ mpvCommand: async (_socket, command) => {
+ commands.push(command);
+ if (command[1] === 'path') return '/media/episode.mkv';
+ if (command[1] === 'track-list') return [{ type: 'audio', selected: true, 'ff-index': 2 }];
+ return undefined;
+ },
+ onInterrupt: (handler) => {
+ interrupted = handler;
+ return () => {
+ detached = true;
+ };
+ },
+ };
+ return {
+ context,
+ deps,
+ output,
+ commands,
+ generations,
+ exitCode: () => exitCode,
+ interrupt: () => interrupted?.(),
+ detached: () => detached,
+ };
+}
+
+test('launcher uses the shared core and selected mpv audio then loads the generated file', async () => {
+ const f = fixture(['generate-subs']);
+ assert.equal(await runGenerateSubtitlesCommand(f.context, f.deps), true);
+ assert.equal(f.generations[0]?.mediaPath, '/media/episode.mkv');
+ assert.equal(f.generations[0]?.audioStreamIndex, 2);
+ assert.equal(
+ f.generations[0]?.modelDirectory,
+ path.join('/settings/SubMiner', 'models', 'whisper'),
+ );
+ assert.equal(f.generations[0]?.config.modelPath, '/models/external.bin');
+ assert.deepEqual(f.commands.at(-2), [
+ 'sub-add',
+ '/media/episode.ja.srt',
+ 'select',
+ 'Japanese (generated)',
+ 'ja',
+ ]);
+ assert.deepEqual(f.commands.at(-1), ['set_property', 'sub-delay', 0]);
+ assert.match(f.output.join(''), /50%/);
+ assert.match(f.output.join(''), /Saved Japanese subtitles/);
+ assert.equal(f.detached(), true);
+});
+
+test('launcher reports a missing executable before downloading a model', async () => {
+ const f = fixture(['generate-subs', '/media/episode.mkv', '--download-model']);
+ f.deps.resolveModel = async () => ({ kind: 'missing', path: '/models/missing.bin' });
+ f.deps.resolveTools = async () => ({
+ ffmpeg: { kind: 'found', path: '/usr/bin/ffmpeg' },
+ ffprobe: { kind: 'found', path: '/usr/bin/ffprobe' },
+ whisper: { kind: 'missing', message: 'whisper-cli was not found on PATH.' },
+ vad: null,
+ });
+ await assert.rejects(
+ runGenerateSubtitlesCommand(f.context, f.deps),
+ /whisper-cli was not found on PATH/,
+ );
+ assert.equal(f.generations.length, 0);
+});
+
+test('launcher never downloads a model without the explicit option', async () => {
+ const f = fixture();
+ f.deps.resolveModel = async () => ({ kind: 'missing', path: '/models/missing.bin' });
+ await assert.rejects(runGenerateSubtitlesCommand(f.context, f.deps), /--download-model/);
+ assert.equal(f.generations.length, 0);
+ assert.equal(f.detached(), true);
+});
+
+test('current mpv generation requires an identifiable selected audio track', async () => {
+ for (const tracks of [
+ [],
+ [{ type: 'audio', selected: true }],
+ [{ type: 'audio', selected: true, external: true, 'ff-index': 0 }],
+ ]) {
+ const f = fixture(['generate-subs']);
+ f.deps.mpvCommand = async (_socket, command) =>
+ command[1] === 'path' ? '/media/episode.mkv' : tracks;
+ await assert.rejects(runGenerateSubtitlesCommand(f.context, f.deps), /audio track/);
+ assert.equal(f.generations.length, 0);
+ }
+});
+
+test('explicit local file leaves Japanese track selection to the shared generator', async () => {
+ const f = fixture();
+ await runGenerateSubtitlesCommand(f.context, f.deps);
+ assert.equal(f.generations[0]?.audioStreamIndex, undefined);
+ assert.equal(
+ f.commands.some((command) => command[1] === 'track-list'),
+ false,
+ );
+});
+
+test('launcher does not load generated subtitles after mpv switches files', async () => {
+ const f = fixture(['generate-subs']);
+ let pathRequests = 0;
+ f.deps.mpvCommand = async (_socket, command) => {
+ f.commands.push(command);
+ if (command[1] === 'path')
+ return ++pathRequests === 1 ? '/media/episode.mkv' : '/media/next.mkv';
+ return [{ type: 'audio', selected: true, 'ff-index': 2 }];
+ };
+ await runGenerateSubtitlesCommand(f.context, f.deps);
+ assert.equal(
+ f.commands.some((command) => command[0] === 'sub-add'),
+ false,
+ );
+ assert.match(f.output.join(''), /Saved Japanese subtitles/);
+});
+
+test('explicit managed model overrides external config and downloads before generation', async () => {
+ const f = fixture([
+ 'generate-subs',
+ '/media/episode.mkv',
+ '--model',
+ 'medium',
+ '--download-model',
+ ]);
+ f.deps.resolveModel = async (config) => {
+ assert.equal(config.modelPath, '');
+ assert.equal(config.managedModel, 'medium');
+ return { kind: 'missing', path: '/models/medium.bin' };
+ };
+ let downloaded = false;
+ f.deps.downloadModel = async () => {
+ downloaded = true;
+ return '/models/medium.bin';
+ };
+ const generate = f.deps.generate;
+ f.deps.generate = async (input) => {
+ assert.equal(downloaded, true);
+ if (!generate) throw new Error('Missing fixture generator');
+ return generate(input);
+ };
+ await runGenerateSubtitlesCommand(f.context, f.deps);
+ assert.equal(f.generations.length, 1);
+});
+
+test('generation can run standalone and never loads subtitles into another video', async () => {
+ for (const playing of [null, '/media/different.mkv']) {
+ const f = fixture();
+ f.deps.mpvCommand = async (_socket, command) => {
+ f.commands.push(command);
+ if (playing === null) throw new Error('mpv is not running');
+ return playing;
+ };
+ await runGenerateSubtitlesCommand(f.context, f.deps);
+ assert.equal(f.generations.length, 1);
+ assert.equal(
+ f.commands.some((command) => command[0] === 'sub-add'),
+ false,
+ );
+ }
+});
+
+test('launcher preserves the saved path when loading into mpv fails', async () => {
+ const f = fixture();
+ const mpv = f.deps.mpvCommand;
+ f.deps.mpvCommand = async (socket, command, timeout) => {
+ if (command[0] === 'sub-add') throw new Error('load failed');
+ return mpv?.(socket, command, timeout);
+ };
+ await runGenerateSubtitlesCommand(f.context, f.deps);
+ assert.match(f.output.join(''), /Saved Japanese subtitles: \/media\/episode.ja.srt/);
+ assert.match(f.output.join(''), /mpv could not load them: load failed/);
+ assert.equal(f.exitCode(), 1);
+});
+
+test('SIGINT cancels shared generation and unregisters its handler', async () => {
+ const f = fixture();
+ f.deps.generate = async (input) => {
+ f.interrupt();
+ assert.equal(input.signal?.aborted, true);
+ throw new Error('Aborted');
+ };
+ await runGenerateSubtitlesCommand(f.context, f.deps);
+ assert.equal(f.exitCode(), 130);
+ assert.equal(f.detached(), true);
+ assert.match(f.output.join(''), /cancelled/);
+});
+
+test('cancellation after generation preserves the saved path and skips mpv loading', async () => {
+ const f = fixture();
+ f.deps.generate = async () => {
+ f.interrupt();
+ return '/media/episode.ja.srt';
+ };
+ await runGenerateSubtitlesCommand(f.context, f.deps);
+ assert.equal(
+ f.commands.some((command) => command[0] === 'sub-add'),
+ false,
+ );
+ assert.match(f.output.join(''), /Saved Japanese subtitles: \/media\/episode.ja.srt/);
+ assert.equal(f.exitCode(), 130);
+ assert.equal(f.detached(), true);
+});
+
+test('progress throttles repeated updates but always reports stage changes and completion', () => {
+ const output: string[] = [];
+ let time = 0;
+ const progress = createGenerationProgressReporter(
+ (text) => output.push(text),
+ () => time,
+ );
+ progress({ stage: 'download', percent: 0, message: 'Downloading' });
+ progress({ stage: 'download', percent: 1, message: 'Downloading' });
+ time = 1000;
+ progress({ stage: 'download', percent: 50, message: 'Downloading' });
+ progress({ stage: 'download', percent: 100, message: 'Downloading' });
+ progress({ stage: 'extract', message: 'Extracting audio' });
+ assert.equal(output.length, 4);
+});
diff --git a/launcher/commands/generate-subtitles-command.ts b/launcher/commands/generate-subtitles-command.ts
new file mode 100644
index 00000000..a98d9bff
--- /dev/null
+++ b/launcher/commands/generate-subtitles-command.ts
@@ -0,0 +1,225 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import {
+ downloadSubtitleGenerationModel,
+ generateJapaneseSubtitles,
+ resolveSubtitleGenerationModel,
+ resolveSubtitleGenerationTools,
+} from '../../src/core/services/subtitle-generation.js';
+import { requireSubtitleGenerationTools } from '../../src/core/services/subtitle-generation-tools.js';
+import {
+ resolveSubtitleGenerationConfig,
+ type SubtitleGenerationProgress,
+} from '../../src/shared/subtitle-generation.js';
+import {
+ readLauncherMainConfigObject,
+ resolveLauncherMainConfigPath,
+} from '../config/shared-config-reader.js';
+import { sendMpvCommandWithResponse } from '../mpv.js';
+import { resolvePathMaybe } from '../util.js';
+import type { LauncherCommandContext } from './context.js';
+
+type GenerationCommandContext = Pick & {
+ processAdapter: Pick;
+};
+
+interface GenerationCommandDeps {
+ readConfig: typeof readLauncherMainConfigObject;
+ configPath: typeof resolveLauncherMainConfigPath;
+ resolveModel: typeof resolveSubtitleGenerationModel;
+ resolveTools: typeof resolveSubtitleGenerationTools;
+ downloadModel: typeof downloadSubtitleGenerationModel;
+ generate: typeof generateJapaneseSubtitles;
+ mpvCommand: typeof sendMpvCommandWithResponse;
+ onInterrupt: (handler: () => void) => () => void;
+}
+
+const defaultDeps: GenerationCommandDeps = {
+ readConfig: readLauncherMainConfigObject,
+ configPath: resolveLauncherMainConfigPath,
+ resolveModel: resolveSubtitleGenerationModel,
+ resolveTools: resolveSubtitleGenerationTools,
+ downloadModel: downloadSubtitleGenerationModel,
+ generate: generateJapaneseSubtitles,
+ mpvCommand: sendMpvCommandWithResponse,
+ onInterrupt: (handler) => {
+ process.on('SIGINT', handler);
+ return () => process.off('SIGINT', handler);
+ },
+};
+
+function localMediaPath(value: string, workingDirectory = process.cwd()): string {
+ if (value.startsWith('file://')) return fileURLToPath(value);
+ if (/^[a-z][a-z\d+.-]*:\/\//i.test(value)) {
+ throw new Error('Japanese subtitle generation requires a local media file.');
+ }
+ return path.resolve(workingDirectory, resolvePathMaybe(value));
+}
+
+async function readMpvMedia(socketPath: string, command: GenerationCommandDeps['mpvCommand']) {
+ const media = await command(socketPath, ['get_property', 'path'], 1000);
+ if (typeof media !== 'string' || !media.trim()) return null;
+ let workingDirectory: string | undefined;
+ if (!path.isAbsolute(media) && !media.startsWith('file://')) {
+ const directory = await command(socketPath, ['get_property', 'working-directory'], 1000);
+ if (typeof directory !== 'string') return null;
+ workingDirectory = directory;
+ }
+ return localMediaPath(media, workingDirectory);
+}
+
+async function readMpvAudioStream(
+ socketPath: string,
+ command: GenerationCommandDeps['mpvCommand'],
+) {
+ const tracks = await command(socketPath, ['get_property', 'track-list'], 1000);
+ for (const track of Array.isArray(tracks) ? tracks : []) {
+ if (
+ typeof track === 'object' &&
+ track !== null &&
+ 'type' in track &&
+ track.type === 'audio' &&
+ 'selected' in track &&
+ track.selected === true
+ ) {
+ if ('external' in track && track.external === true) {
+ throw new Error(
+ 'The selected mpv audio track is external. Pass its local file to generate-subs.',
+ );
+ }
+ if (
+ 'ff-index' in track &&
+ typeof track['ff-index'] === 'number' &&
+ Number.isSafeInteger(track['ff-index']) &&
+ track['ff-index'] >= 0
+ ) {
+ return track['ff-index'];
+ }
+ }
+ }
+ throw new Error(
+ 'Select an audio track in mpv, or pass --audio-stream with its absolute stream index.',
+ );
+}
+
+function sameFile(left: string, right: string): boolean {
+ try {
+ return fs.realpathSync(left) === fs.realpathSync(right);
+ } catch {
+ return path.resolve(left) === path.resolve(right);
+ }
+}
+
+/** Keep progress readable in terminals and redirected logs, even for large model downloads. */
+export function createGenerationProgressReporter(write: (text: string) => void, now = Date.now) {
+ let previousStage: SubtitleGenerationProgress['stage'] | undefined;
+ let previousTime = -Infinity;
+ let previousLine = '';
+ return (progress: SubtitleGenerationProgress): void => {
+ const percent =
+ typeof progress.percent === 'number' && Number.isFinite(progress.percent)
+ ? Math.floor(Math.max(0, Math.min(100, progress.percent)))
+ : undefined;
+ const line = `[${progress.stage}] ${percent === undefined ? '' : `${percent}% `}${progress.message}\n`;
+ const timestamp = now();
+ if (
+ line === previousLine ||
+ (progress.stage === previousStage && timestamp - previousTime < 1000 && percent !== 100)
+ )
+ return;
+ write(line);
+ previousStage = progress.stage;
+ previousTime = timestamp;
+ previousLine = line;
+ };
+}
+
+export async function runGenerateSubtitlesCommand(
+ context: GenerationCommandContext,
+ overrides: Partial = {},
+): Promise {
+ const options = context.args.generateSubtitles;
+ if (!options) return false;
+ const deps = { ...defaultDeps, ...overrides };
+ const write = (text: string) => context.processAdapter.writeStdout(text);
+ const controller = new AbortController();
+ const removeInterrupt = deps.onInterrupt(() => controller.abort());
+ try {
+ const config = resolveSubtitleGenerationConfig(deps.readConfig()?.subtitleGeneration);
+ if (options.managedModel) {
+ config.managedModel = options.managedModel;
+ config.modelPath = '';
+ }
+ if (options.modelPath !== undefined)
+ config.modelPath = path.resolve(resolvePathMaybe(options.modelPath));
+ const modelDirectory = path.join(path.dirname(deps.configPath()), 'models', 'whisper');
+ const currentMedia = await readMpvMedia(context.mpvSocketPath, deps.mpvCommand).catch(
+ () => null,
+ );
+ const mediaPath = options.mediaPath ? localMediaPath(options.mediaPath) : currentMedia;
+ if (!mediaPath)
+ throw new Error('Pass a local video file or open one in mpv before running generate-subs.');
+ const audioStreamIndex =
+ options.audioStreamIndex ??
+ (!options.mediaPath
+ ? await readMpvAudioStream(context.mpvSocketPath, deps.mpvCommand)
+ : undefined);
+ const onProgress = createGenerationProgressReporter(write);
+ // Missing executables fail here, before any model download starts.
+ requireSubtitleGenerationTools(await deps.resolveTools(config));
+ const model = await deps.resolveModel(config, modelDirectory);
+ if (model.kind === 'invalid') throw new Error(model.message);
+ if (model.kind === 'missing') {
+ if (!options.downloadModel) {
+ throw new Error(
+ 'No Whisper model found. Run again with --download-model, or set subtitleGeneration.modelPath / --model-path.',
+ );
+ }
+ await deps.downloadModel({ config, modelDirectory, onProgress, signal: controller.signal });
+ }
+ const outputPath = await deps.generate({
+ config,
+ modelDirectory,
+ mediaPath,
+ audioStreamIndex,
+ outputPath: options.outputPath
+ ? path.resolve(resolvePathMaybe(options.outputPath))
+ : undefined,
+ onProgress,
+ signal: controller.signal,
+ });
+ write(`Saved Japanese subtitles: ${outputPath}\n`);
+ controller.signal.throwIfAborted();
+ const playingMedia = await readMpvMedia(context.mpvSocketPath, deps.mpvCommand).catch(
+ () => null,
+ );
+ controller.signal.throwIfAborted();
+ if (playingMedia && sameFile(playingMedia, mediaPath)) {
+ try {
+ await deps.mpvCommand(context.mpvSocketPath, [
+ 'sub-add',
+ outputPath,
+ 'select',
+ 'Japanese (generated)',
+ 'ja',
+ ]);
+ await deps.mpvCommand(context.mpvSocketPath, ['set_property', 'sub-delay', 0]);
+ write('Loaded Japanese subtitles into mpv.\n');
+ } catch (error) {
+ write(
+ `Subtitles are saved, but mpv could not load them: ${error instanceof Error ? error.message : String(error)}\n`,
+ );
+ context.processAdapter.setExitCode(1);
+ }
+ }
+ return true;
+ } catch (error) {
+ if (!controller.signal.aborted) throw error;
+ write('Subtitle generation cancelled.\n');
+ context.processAdapter.setExitCode(130);
+ return true;
+ } finally {
+ removeInterrupt();
+ }
+}
diff --git a/launcher/commands/update-command.test.ts b/launcher/commands/update-command.test.ts
index da7ce1d6..8f358e69 100644
--- a/launcher/commands/update-command.test.ts
+++ b/launcher/commands/update-command.test.ts
@@ -1,5 +1,9 @@
import test from 'node:test';
import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
import { runUpdateCommand } from './update-command';
import type { LauncherCommandContext } from './context';
@@ -62,6 +66,24 @@ test('runUpdateCommand updates directly on Linux without launching Electron', as
]);
});
+test('runUpdateCommand sends symlinked AUR installs to the package helper without network access', async () => {
+ const calls: string[] = [];
+ const handled = await runUpdateCommand(makeContext({ appPath: '/usr/bin/SubMiner.AppImage' }), {
+ resolveRealPath: () => '/opt/SubMiner/SubMiner.AppImage',
+ runDirectReleaseUpdate: async () => {
+ throw new Error('must not check GitHub releases for an AUR install');
+ },
+ log: (level, _configured, message) => {
+ calls.push(`${level}:${message}`);
+ },
+ });
+
+ assert.equal(handled, true);
+ assert.deepEqual(calls, [
+ 'warn:SubMiner is installed through subminer-bin. Update it with your AUR helper, for example: yay -S subminer-bin.',
+ ]);
+});
+
test('runUpdateCommand skips Linux asset replacement when release is not newer', async () => {
const calls: string[] = [];
const originalFetch = globalThis.fetch;
@@ -118,6 +140,65 @@ test('runUpdateCommand skips Linux asset replacement when release is not newer',
}
});
+test('Linux update does not replace the launcher after an AppImage hash failure', async () => {
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-update-order-'));
+ const appImagePath = path.join(workspace, 'SubMiner.AppImage');
+ const launcherPath = path.join(workspace, 'subminer');
+ fs.writeFileSync(appImagePath, 'old app');
+ fs.writeFileSync(launcherPath, '#!/bin/sh\n# SubMiner launcher\n');
+
+ const fetched: string[] = [];
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = (async (input: string | URL | Request) => {
+ const url = input instanceof Request ? input.url : String(input);
+ fetched.push(url);
+ if (url.endsWith('/releases')) {
+ return Response.json([
+ {
+ tag_name: 'v999.0.0',
+ prerelease: false,
+ draft: false,
+ assets: [
+ {
+ name: 'SHA256SUMS.txt',
+ browser_download_url: 'https://example.test/SHA256SUMS.txt',
+ },
+ {
+ name: 'SubMiner.AppImage',
+ browser_download_url: 'https://example.test/SubMiner.AppImage',
+ },
+ { name: 'subminer', browser_download_url: 'https://example.test/subminer' },
+ ],
+ },
+ ]);
+ }
+ if (url.endsWith('/SHA256SUMS.txt')) {
+ return new Response(
+ `${createHash('sha256').update('expected app').digest('hex')} SubMiner.AppImage\n${createHash('sha256').update('new launcher').digest('hex')} subminer\n`,
+ );
+ }
+ if (url.endsWith('/SubMiner.AppImage')) {
+ return new Response('corrupt app');
+ }
+ throw new Error(`launcher asset should not be fetched: ${url}`);
+ }) as typeof globalThis.fetch;
+
+ try {
+ const handled = await runUpdateCommand(
+ makeContext({ appPath: appImagePath, scriptPath: launcherPath }),
+ { readMainConfig: () => null, log: () => {} },
+ );
+
+ assert.equal(handled, true);
+ assert.equal(fs.readFileSync(appImagePath, 'utf8'), 'old app');
+ assert.equal(fs.readFileSync(launcherPath, 'utf8'), '#!/bin/sh\n# SubMiner launcher\n');
+ assert.equal(fetched.includes('https://example.test/subminer'), false);
+ } finally {
+ globalThis.fetch = originalFetch;
+ fs.rmSync(workspace, { recursive: true, force: true });
+ }
+});
+
test('runUpdateCommand keeps app-mediated update path on non-Linux', async () => {
const calls: string[] = [];
@@ -148,3 +229,32 @@ test('runUpdateCommand keeps app-mediated update path on non-Linux', async () =>
'remove:/tmp/subminer-update-test',
]);
});
+
+test('managed launcher passes its wrapper to app updates, protecting signed resources', async () => {
+ const previous = process.env.SUBMINER_LAUNCHER_PATH;
+ process.env.SUBMINER_LAUNCHER_PATH = '/Users/tester/.local/bin/subminer';
+ try {
+ let forwarded: string[] = [];
+ await runUpdateCommand(
+ makeContext({
+ processAdapter: { ...makeContext().processAdapter, platform: () => 'darwin' },
+ scriptPath: '/Applications/SubMiner.app/Contents/Resources/launcher/subminer',
+ appPath: '/Applications/SubMiner.app/Contents/MacOS/SubMiner',
+ }),
+ {
+ createTempDir: () => '/tmp/subminer-update-test',
+ joinPath: (...parts) => parts.join('/'),
+ runAppCommandCaptureOutput: (_app, args) => {
+ forwarded = args;
+ return { status: 0, stdout: '', stderr: '' };
+ },
+ waitForUpdateResponse: async () => ({ ok: true }),
+ removeDir: () => {},
+ },
+ );
+ assert.equal(forwarded[2], '/Users/tester/.local/bin/subminer');
+ } finally {
+ if (previous === undefined) delete process.env.SUBMINER_LAUNCHER_PATH;
+ else process.env.SUBMINER_LAUNCHER_PATH = previous;
+ }
+});
diff --git a/launcher/commands/update-command.ts b/launcher/commands/update-command.ts
index 0b0a88be..5fbf6c46 100644
--- a/launcher/commands/update-command.ts
+++ b/launcher/commands/update-command.ts
@@ -58,6 +58,7 @@ type UpdateCommandDeps = {
) => { status: number; stdout: string; stderr: string; error?: Error };
waitForUpdateResponse: (responsePath: string) => Promise;
removeDir: (targetPath: string) => void;
+ resolveRealPath: (targetPath: string) => string;
runDirectReleaseUpdate: (
request: DirectReleaseUpdateRequest,
) => Promise;
@@ -98,25 +99,36 @@ async function runDirectReleaseUpdate(
: new Map();
const downloadAsset = (url: string) => fetchReleaseAssetBuffer(fetchForUpdater, url);
- const [appImage, launcher, supportAssets] = await Promise.all([
- updateAppImageFromRelease({
- release,
- sha256Sums,
- appImagePath: request.appPath,
- downloadAsset,
- }),
- updateLauncherFromRelease({
+ const appImage = await updateAppImageFromRelease({
+ release,
+ sha256Sums,
+ appImagePath: request.appPath,
+ downloadAsset,
+ });
+ let launcher: DirectReleaseUpdateResult['launcher'];
+ if (appImage.status !== 'updated') {
+ launcher = {
+ status: 'skipped',
+ message: 'Launcher update requires a successful AppImage update first.',
+ };
+ } else if (process.env.SUBMINER_MANAGED_LAUNCHER === '1') {
+ launcher = {
+ status: 'skipped',
+ message: 'This launcher is updated with the SubMiner app.',
+ };
+ } else {
+ launcher = await updateLauncherFromRelease({
release,
sha256Sums,
launcherPath: request.launcherPath,
downloadAsset,
- }),
- updateSupportAssetsFromRelease({
- release,
- sha256Sums,
- downloadAsset,
- }),
- ]);
+ });
+ }
+ const supportAssets = await updateSupportAssetsFromRelease({
+ release,
+ sha256Sums,
+ downloadAsset,
+ });
return { appImage, launcher, supportAssets };
}
@@ -173,6 +185,13 @@ const defaultDeps: UpdateCommandDeps = {
removeDir: (targetPath) => {
fs.rmSync(targetPath, { recursive: true, force: true });
},
+ resolveRealPath: (targetPath) => {
+ try {
+ return fs.realpathSync(targetPath);
+ } catch {
+ return targetPath;
+ }
+ },
runDirectReleaseUpdate,
readMainConfig: readLauncherMainConfigObject,
log: launcherLog,
@@ -189,12 +208,20 @@ export async function runUpdateCommand(
}
if (context.processAdapter.platform() === 'linux') {
+ const logLevel = args.logLevel ?? 'warn';
+ if (resolvedDeps.resolveRealPath(appPath) === '/opt/SubMiner/SubMiner.AppImage') {
+ resolvedDeps.log(
+ 'warn',
+ logLevel,
+ 'SubMiner is installed through subminer-bin. Update it with your AUR helper, for example: yay -S subminer-bin.',
+ );
+ return true;
+ }
const result = await resolvedDeps.runDirectReleaseUpdate({
appPath,
launcherPath: scriptPath,
channel: readUpdateChannel(resolvedDeps.readMainConfig()),
});
- const logLevel = args.logLevel ?? 'warn';
logUpdateResult('AppImage', result.appImage, logLevel, resolvedDeps);
logUpdateResult('Launcher', result.launcher, logLevel, resolvedDeps);
for (const supportResult of result.supportAssets) {
@@ -203,6 +230,7 @@ export async function runUpdateCommand(
return true;
}
+ const launcherPath = path.resolve(process.env.SUBMINER_LAUNCHER_PATH ?? scriptPath);
const tempDir = resolvedDeps.createTempDir('subminer-update-');
const responsePath = resolvedDeps.joinPath(tempDir, 'response.json');
@@ -210,7 +238,7 @@ export async function runUpdateCommand(
const result = resolvedDeps.runAppCommandCaptureOutput(appPath, [
'--update',
'--update-launcher-path',
- scriptPath,
+ launcherPath,
'--update-response-path',
responsePath,
]);
diff --git a/launcher/config/args-normalizer.ts b/launcher/config/args-normalizer.ts
index 2afad051..47e95c47 100644
--- a/launcher/config/args-normalizer.ts
+++ b/launcher/config/args-normalizer.ts
@@ -249,6 +249,7 @@ export function applyRootOptionsToArgs(
}
export function applyInvocationsToArgs(parsed: Args, invocations: CliInvocations): void {
+ if (invocations.generateSubtitles) parsed.generateSubtitles = invocations.generateSubtitles;
if (invocations.dictionaryTriggered) parsed.dictionary = true;
if (invocations.dictionaryCandidates) parsed.dictionaryCandidates = true;
if (invocations.dictionarySelect) parsed.dictionarySelect = true;
diff --git a/launcher/config/cli-parser-builder.test.ts b/launcher/config/cli-parser-builder.test.ts
index 70ff8592..0360211e 100644
--- a/launcher/config/cli-parser-builder.test.ts
+++ b/launcher/config/cli-parser-builder.test.ts
@@ -1,6 +1,61 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { parseCliPrograms, resolveTopLevelCommand } from './cli-parser-builder.js';
+import { SUBTITLE_GENERATION_MODELS } from '../../src/shared/subtitle-generation-model-catalog.js';
+
+test('generate-subs accepts all downloadable multilingual model variants', () => {
+ for (const { id } of SUBTITLE_GENERATION_MODELS) {
+ const { invocations } = parseCliPrograms(['generate-subs', '--model', id], 'subminer');
+ assert.equal(invocations.generateSubtitles?.managedModel, id);
+ }
+});
+
+test('generate-subs parses local generation options separately from YouTube options', () => {
+ const result = parseCliPrograms(
+ [
+ 'generate-subs',
+ 'episode.mkv',
+ '--download-model',
+ '--model',
+ 'medium',
+ '--output',
+ 'episode.ja.srt',
+ '--audio-stream',
+ '2',
+ ],
+ 'subminer',
+ );
+ assert.deepEqual(result.invocations.generateSubtitles, {
+ mediaPath: 'episode.mkv',
+ downloadModel: true,
+ managedModel: 'medium',
+ modelPath: undefined,
+ outputPath: 'episode.ja.srt',
+ audioStreamIndex: 2,
+ });
+ assert.equal(
+ parseCliPrograms(['generate-subs'], 'subminer').invocations.generateSubtitles?.mediaPath,
+ undefined,
+ );
+ assert.equal(
+ parseCliPrograms(['generate-subs', '--model-path', '/models/ggml.bin'], 'subminer').invocations
+ .generateSubtitles?.modelPath,
+ '/models/ggml.bin',
+ );
+});
+
+test('generate-subs rejects conflicting models and malformed audio stream indices', () => {
+ for (const flags of [
+ ['--model', 'tiny.en'],
+ ['--model', 'small.en-q5_1'],
+ ['--model', 'toString'],
+ ['--audio-stream', '-1'],
+ ['--audio-stream', '1.5'],
+ ['--model-path', '/model.bin', '--download-model'],
+ ['--model-path', '/model.bin', '--model', 'small'],
+ ])
+ assert.throws(() => parseCliPrograms(['generate-subs', ...flags], 'subminer'), /Generation/);
+});
test('resolveTopLevelCommand skips root options and finds the first command', () => {
assert.deepEqual(resolveTopLevelCommand(['--backend', 'macos', 'config', 'show']), {
@@ -94,6 +149,23 @@ test('parseCliPrograms lowers sync options into app-owned CLI tokens', () => {
assert.deepEqual(removeTemp.invocations.syncCliTokens, ['--remove-temp', '/tmp/subminer-sync-x']);
});
+test('parseCliPrograms forwards transfer cache keys with both sync temp helpers', () => {
+ const key = 'a'.repeat(64);
+ for (const helper of [['--make-temp'], ['--remove-temp', '/tmp/subminer-sync-x']]) {
+ const tokens = [...helper, '--transfer-cache', key];
+ const result = parseCliPrograms(['sync', ...tokens], 'subminer');
+ assert.equal(result.invocations.syncTriggered, true);
+ assert.deepEqual(result.invocations.syncCliTokens, tokens);
+ }
+});
+
+test('parseCliPrograms rejects sync --ui with --transfer-cache', () => {
+ assert.throws(
+ () => parseCliPrograms(['sync', '--ui', '--transfer-cache', 'a'.repeat(64)], 'subminer'),
+ { message: 'Sync --ui cannot be combined with other sync options.' },
+ );
+});
+
test('parseCliPrograms leaves sync validation to the app parser', () => {
// Invalid combinations are forwarded; the app's parseSyncCliTokens rejects them.
const invalid = parseCliPrograms(['sync', 'media-box', '--push', '--pull'], 'subminer');
diff --git a/launcher/config/cli-parser-builder.ts b/launcher/config/cli-parser-builder.ts
index 4b19a9da..459a33e0 100644
--- a/launcher/config/cli-parser-builder.ts
+++ b/launcher/config/cli-parser-builder.ts
@@ -1,4 +1,9 @@
import { Command } from 'commander';
+import type { Args } from '../types.js';
+import {
+ isSubtitleGenerationModelId,
+ SUBTITLE_GENERATION_MODELS,
+} from '../../src/shared/subtitle-generation-model-catalog.js';
export interface JellyfinInvocation {
action?: string;
@@ -20,6 +25,7 @@ export interface CommandActionInvocation {
}
export interface CliInvocations {
+ generateSubtitles?: Args['generateSubtitles'];
jellyfinInvocation: JellyfinInvocation | null;
configInvocation: CommandActionInvocation | null;
settingsInvocation: CommandActionInvocation | null;
@@ -120,6 +126,7 @@ function getTopLevelCommand(argv: string[]): { name: string; index: number } | n
'mpv',
'logs',
'dictionary',
+ 'generate-subs',
'dict',
'stats',
'sync',
@@ -202,6 +209,7 @@ export function parseCliPrograms(
let texthookerOpenBrowser = false;
let doctorTriggered = false;
let texthookerTriggered = false;
+ let generateSubtitles: Args['generateSubtitles'];
const commandProgram = new Command();
commandProgram
@@ -226,6 +234,50 @@ export function parseCliPrograms(
.argument('[target]', 'file, directory, or URL');
applyRootOptions(rootProgram);
+ commandProgram
+ .command('generate-subs')
+ .description('Generate Japanese subtitles locally with whisper.cpp')
+ .argument('[video]', 'Local media file, or the current mpv file if omitted')
+ .option('--download-model', 'Download the selected managed model if missing')
+ .option('--model-path ', 'Use an existing whisper.cpp model file')
+ .option(
+ '--model ',
+ `Managed model: ${SUBTITLE_GENERATION_MODELS.map((model) => model.id).join(', ')}`,
+ )
+ .option('--output ', 'Save subtitles to this SRT path')
+ .option('--audio-stream ', 'Absolute audio stream index from ffprobe')
+ .action((mediaPath: string | undefined, options: Record) => {
+ const model = options.model;
+ if (model !== undefined && !isSubtitleGenerationModelId(model)) {
+ throw new Error(
+ `Generation --model must be one of: ${SUBTITLE_GENERATION_MODELS.map((entry) => entry.id).join(', ')}.`,
+ );
+ }
+ if (
+ options.modelPath !== undefined &&
+ (model !== undefined || options.downloadModel === true)
+ ) {
+ throw new Error(
+ 'Generation --model-path cannot be combined with --model or --download-model.',
+ );
+ }
+ let audioStreamIndex: number | undefined;
+ if (typeof options.audioStream === 'string') {
+ audioStreamIndex = Number(options.audioStream);
+ if (!/^\d+$/.test(options.audioStream) || !Number.isSafeInteger(audioStreamIndex)) {
+ throw new Error('Generation --audio-stream must be a non-negative integer stream index.');
+ }
+ }
+ generateSubtitles = {
+ mediaPath,
+ downloadModel: options.downloadModel === true,
+ modelPath: typeof options.modelPath === 'string' ? options.modelPath : undefined,
+ managedModel: model,
+ outputPath: typeof options.output === 'string' ? options.output : undefined,
+ audioStreamIndex,
+ };
+ });
+
commandProgram
.command('jellyfin')
.alias('jf')
@@ -363,6 +415,7 @@ export function parseCliPrograms(
.option('--json', 'Emit machine-readable NDJSON progress output')
.option('--make-temp', 'Create a sync temp directory and print its path (used over SSH)')
.option('--remove-temp ', 'Remove a sync temp directory created by --make-temp')
+ .option('--transfer-cache ', 'Reuse/save a received snapshot with temp helpers (internal)')
.option('--ui', 'Open the SubMiner sync window')
.option('--log-level ', 'Log level')
.action((rawHost: string | undefined, options: Record) => {
@@ -384,6 +437,7 @@ export function parseCliPrograms(
check ||
makeTemp ||
removeTemp ||
+ options.transferCache !== undefined ||
options.remoteCmd !== undefined ||
options.db !== undefined ||
options.json === true ||
@@ -405,6 +459,8 @@ export function parseCliPrograms(
if (merge) tokens.push('--merge', merge);
if (makeTemp) tokens.push('--make-temp');
if (removeTemp) tokens.push('--remove-temp', removeTemp);
+ if (typeof options.transferCache === 'string')
+ tokens.push('--transfer-cache', options.transferCache);
if (push) tokens.push('--push');
if (pull) tokens.push('--pull');
if (check) tokens.push('--check');
@@ -520,6 +576,7 @@ export function parseCliPrograms(
options: selectedProgram.opts>(),
rootTarget: rootProgram.processedArgs[0],
invocations: {
+ generateSubtitles,
jellyfinInvocation,
configInvocation,
settingsInvocation,
diff --git a/launcher/main.ts b/launcher/main.ts
index 884f5528..c68106b2 100644
--- a/launcher/main.ts
+++ b/launcher/main.ts
@@ -25,6 +25,7 @@ import { runHistorySession } from './commands/history-command.js';
import { runSyncCommand } from './commands/sync-command.js';
import { runPlaybackCommand } from './commands/playback-command.js';
import { runUpdateCommand } from './commands/update-command.js';
+import { runGenerateSubtitlesCommand } from './commands/generate-subtitles-command.js';
const APP_VERSION =
typeof packageJson.version === 'string' && packageJson.version.trim()
@@ -112,6 +113,10 @@ async function main(): Promise {
return;
}
+ if (await runGenerateSubtitlesCommand(context)) {
+ return;
+ }
+
const resolvedAppPath = ensureAppPath(context);
state.appPath = resolvedAppPath;
log('debug', args.logLevel, `Using SubMiner app binary: ${resolvedAppPath}`);
diff --git a/launcher/types.ts b/launcher/types.ts
index 8507d2d4..08c42497 100644
--- a/launcher/types.ts
+++ b/launcher/types.ts
@@ -1,6 +1,7 @@
import path from 'node:path';
import os from 'node:os';
import type { MpvBackend, MpvLaunchMode } from '../src/types/config.js';
+import type { SubtitleGenerationConfig } from '../src/shared/subtitle-generation.js';
import {
resolveDefaultLogFilePath,
type LogFileToggles,
@@ -88,6 +89,14 @@ export interface LauncherAiConfig {
}
export interface Args {
+ generateSubtitles?: {
+ mediaPath?: string;
+ downloadModel: boolean;
+ modelPath?: string;
+ managedModel?: SubtitleGenerationConfig['managedModel'];
+ outputPath?: string;
+ audioStreamIndex?: number;
+ };
backend: Backend;
directory: string;
recursive: boolean;
diff --git a/package.json b/package.json
index acd788eb..4e96b211 100644
--- a/package.json
+++ b/package.json
@@ -2,7 +2,7 @@
"name": "subminer",
"productName": "SubMiner",
"desktopName": "SubMiner.desktop",
- "version": "0.19.5",
+ "version": "0.19.6",
"description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration",
"packageManager": "bun@1.3.5",
"main": "dist/main-entry.js",
@@ -18,7 +18,7 @@
"compare-yomitan-api:electron": "bun run build:yomitan && bun build scripts/compare-yomitan-api.ts --format=cjs --target=node --outfile dist/scripts/compare-yomitan-api.js --external electron && env -u ELECTRON_RUN_AS_NODE electron dist/scripts/compare-yomitan-api.js",
"build:yomitan": "bun scripts/build-yomitan.mjs",
"build:assets": "bun scripts/prepare-build-assets.mjs",
- "build:launcher": "bun build ./launcher/main.ts --target=bun --packages=bundle --banner='#!/usr/bin/env bun' --outfile=dist/launcher/subminer",
+ "build:launcher": "bun run scripts/build-launcher.ts",
"build:stats": "cd stats && bun run build",
"dev:stats": "cd stats && bun run dev",
"build": "bun run build:yomitan && bun run build:stats && tsc -p tsconfig.json && bun run build:renderer && bun run build:settings && bun run build:syncui && bun run build:animeui && bun run build:launcher && bun run build:assets",
@@ -81,17 +81,18 @@
"build:mac:unsigned": "bun run build && env -u APPLE_ID -u APPLE_APP_SPECIFIC_PASSWORD -u APPLE_TEAM_ID -u CSC_LINK -u CSC_KEY_PASSWORD CSC_IDENTITY_AUTO_DISCOVERY=false electron-builder --mac dmg zip --publish never",
"build:mac:zip": "bun run build && electron-builder --mac zip --publish never",
"build:win": "bun run build && electron-builder --win nsis zip --publish never",
- "build:win:unsigned": "bun run build && node scripts/build-win-unsigned.mjs"
+ "build:win:unsigned": "bun run build && node scripts/build-win-unsigned.mjs",
+ "test:package": "bun scripts/run-package-smoke.mjs"
},
"overrides": {
- "@xmldom/xmldom": "0.8.13",
+ "@xmldom/xmldom": "0.8.15",
"app-builder-lib": "26.15.3",
"brace-expansion": "5.0.9",
"electron-builder-squirrel-windows": "26.15.3",
"fast-uri": "3.1.6",
"form-data": "4.0.6",
"ip-address": "10.2.0",
- "js-yaml": "4.3.1",
+ "js-yaml": "4.3.2",
"lodash": "4.18.0",
"minimatch": "10.2.5",
"picomatch": "4.0.4",
@@ -125,15 +126,16 @@
"ws": "^8.21.0"
},
"devDependencies": {
+ "@electron/asar": "3.4.1",
"@types/node": "^24.10.0",
"@types/ws": "^8.18.1",
"electron": "42.6.0",
"electron-builder": "26.15.3",
- "undici": "7.29.0",
"esbuild": "^0.25.12",
"eslint": "^10.8.0",
"prettier": "^3.8.1",
- "typescript": "^5.9.3"
+ "typescript": "^5.9.3",
+ "undici": "7.29.0"
},
"build": {
"appId": "com.sudacode.SubMiner",
@@ -160,6 +162,10 @@
"category": "AudioVideo",
"executableArgs": [
"--background"
+ ],
+ "files": [
+ "package.json",
+ "!node_modules/koffi{,/**/*}"
]
},
"mac": {
@@ -178,6 +184,10 @@
"from": "dist/scripts/get-mpv-window-macos",
"to": "scripts/get-mpv-window-macos"
}
+ ],
+ "files": [
+ "package.json",
+ "!node_modules/koffi{,/**/*}"
]
},
"dmg": {
@@ -189,7 +199,11 @@
"nsis",
"zip"
],
- "icon": "assets/SubMiner.ico"
+ "icon": "assets/SubMiner.ico",
+ "files": [
+ "package.json",
+ "!node_modules/koffi/build/koffi/!(win32_${arch}){,/**/*}"
+ ]
},
"nsis": {
"artifactName": "SubMiner-${version}.${ext}",
@@ -199,43 +213,19 @@
"include": "build/installer.nsh"
},
"files": [
- "**/*",
- "!assets{,/**/*}",
- "!src{,/**/*}",
- "!launcher{,/**/*}",
- "!docs{,/**/*}",
- "!tests{,/**/*}",
- "!packaging{,/**/*}",
- "!README.md",
- "!CHANGELOG.md",
- "!AGENTS.md",
- "!CLAUDE.md",
- "!stats/src{,/**/*}",
- "!stats/index.html",
- "!stats/public{,/**/*}",
- "!stats/package.json",
- "!stats/tsconfig.json",
- "!stats/vite.config.ts",
- "!docs-site{,/**/*}",
- "!changes{,/**/*}",
- "!.tmp{,/**/*}",
- "!release-*{,/**/*}",
- "!dist/**/*.map",
- "!dist/**/*.test.*",
- "!dist/**/__tests__{,/**/*}",
- "!scripts/**/*.test.*",
- "!plugin{,/**/*}",
- "!vendor/subminer-yomitan{,/**/*}",
- "!vendor/yomitan-jlpt-vocab{,/**/*}",
- "!vendor/texthooker-ui/src{,/**/*}",
- "!vendor/texthooker-ui/node_modules{,/**/*}",
- "!vendor/texthooker-ui/.svelte-kit{,/**/*}",
- "!vendor/texthooker-ui/.vscode{,/**/*}",
- "!vendor/texthooker-ui/public{,/**/*}",
- "!vendor/texthooker-ui/README.md",
- "!vendor/texthooker-ui/package.json",
- "!vendor/texthooker-ui/package-lock.json",
- "!vendor/texthooker-ui/tsconfig*.json",
+ "dist/**/*",
+ "stats/dist/**/*",
+ "vendor/texthooker-ui/docs/**/*",
+ "config.example.jsonc",
+ "LICENSE",
+ "!**/*.map",
+ "!**/*.{ts,tsx,mts,cts}",
+ "!**/*.{test,spec}.*",
+ "!**/{test,tests,__tests__,fixture,fixtures,__fixtures__}{,/**/*}",
+ "!dist/launcher{,/**/*}",
+ "!dist/scripts{,/**/*}",
+ "!dist/{renderer,settings,syncui}/fonts{,/**/*}",
+ "!node_modules/koffi/{src,vendor,doc}{,/**/*}",
"!node_modules/@libsql/linux-x64-musl{,/**/*}"
],
"extraResources": [
@@ -249,7 +239,13 @@
},
{
"from": "assets",
- "to": "assets"
+ "to": "assets",
+ "filter": [
+ "SubMiner*.png",
+ "SubMiner.ico",
+ "themes/**/*",
+ "thumbnailers/**/*"
+ ]
},
{
"from": "plugin/subminer",
@@ -260,14 +256,22 @@
"to": "plugin/subminer.conf"
},
{
- "from": "dist/launcher/subminer",
- "to": "launcher/subminer"
+ "from": "dist/launcher",
+ "to": "launcher",
+ "filter": [
+ "subminer",
+ "subminer.cmd",
+ "subminer.js",
+ "prepare.cjs",
+ "version"
+ ]
},
{
"from": "CHANGELOG.md",
"to": "CHANGELOG.md"
}
- ]
+ ],
+ "afterAllArtifactBuild": "scripts/package-audit.cjs"
},
"patchedDependencies": {
"@discordjs/rest@2.6.1": "patches/@discordjs%2Frest@2.6.1.patch"
diff --git a/packaging/aur/subminer-bin/.SRCINFO b/packaging/aur/subminer-bin/.SRCINFO
index 298afa3d..a74187f7 100644
--- a/packaging/aur/subminer-bin/.SRCINFO
+++ b/packaging/aur/subminer-bin/.SRCINFO
@@ -5,7 +5,11 @@ pkgbase = subminer-bin
url = https://github.com/ksyasuda/SubMiner
arch = x86_64
license = GPL-3.0-or-later
- depends = bun
+ license = MIT
+ license = LGPL-2.0-only
+ license = LGPL-2.1-only
+ license = Apache-2.0
+ license = BSD-3-Clause
depends = fuse2
depends = glibc
depends = mpv
diff --git a/packaging/aur/subminer-bin/PKGBUILD b/packaging/aur/subminer-bin/PKGBUILD
index bdbf4df4..0fca1913 100644
--- a/packaging/aur/subminer-bin/PKGBUILD
+++ b/packaging/aur/subminer-bin/PKGBUILD
@@ -6,10 +6,9 @@ pkgrel=2
pkgdesc='All-in-one sentence mining overlay with AnkiConnect and dictionary integration'
arch=('x86_64')
url='https://github.com/ksyasuda/SubMiner'
-license=('GPL-3.0-or-later')
+license=('GPL-3.0-or-later' 'MIT' 'LGPL-2.0-only' 'LGPL-2.1-only' 'Apache-2.0' 'BSD-3-Clause')
options=('!strip' '!debug')
depends=(
- 'bun'
'fuse2'
'glibc'
'mpv'
@@ -64,4 +63,9 @@ package() {
install -dm755 "${pkgdir}/usr/share/SubMiner/plugin/subminer"
cp -a "${srcdir}/plugin/subminer/." "${pkgdir}/usr/share/SubMiner/plugin/subminer/"
+
+ # Bundled Bun runtime notices: MIT and BSD texts are not in the licenses package.
+ install -dm755 "${pkgdir}/usr/share/licenses/${pkgname}"
+ install -m644 "${srcdir}"/resources/bun/licenses/* \
+ "${pkgdir}/usr/share/licenses/${pkgname}/"
}
diff --git a/release/prerelease-notes.md b/release/prerelease-notes.md
index ae7c87f0..6549b5cc 100644
--- a/release/prerelease-notes.md
+++ b/release/prerelease-notes.md
@@ -73,6 +73,9 @@ See the README and docs/installation guide for full setup steps.
- Linux: `SubMiner.AppImage`
- macOS: `SubMiner-*.dmg` and `SubMiner-*.zip`
- Windows: `SubMiner-*.exe` and `SubMiner-*-win.zip`
-- Optional extras: `subminer-assets.tar.gz` and the `subminer` launcher
+- Optional extras: `subminer-assets.tar.gz`, the `subminer` launcher, and the Windows `subminer.cmd` launcher
+- Bun corresponding source: `bun-v1.3.5-source.tar.gz` and its `.sha256` file
-Note: the `subminer` wrapper script uses Bun (`#!/usr/bin/env bun`), so `bun` must be installed and on `PATH`.
+Both launcher downloads use Bun included with the SubMiner app. Download `subminer` on Linux or macOS and `subminer.cmd` on Windows.
+
+The app bundles an unmodified Bun 1.3.5 runtime. Bun is MIT licensed and statically links JavaScriptCore (LGPL 2.0) and TinyCC (LGPL 2.1). License texts and third-party notices ship inside the app under `resources/bun/licenses`, and the source archive above contains the matching Bun, WebKit, and dependency sources for relinking.
diff --git a/resources/bun/licenses/Bun-LICENSE.md b/resources/bun/licenses/Bun-LICENSE.md
new file mode 100644
index 00000000..df8d965c
--- /dev/null
+++ b/resources/bun/licenses/Bun-LICENSE.md
@@ -0,0 +1,73 @@
+Bun itself is MIT-licensed.
+
+## JavaScriptCore
+
+Bun statically links JavaScriptCore (and WebKit) which is LGPL-2 licensed. WebCore files from WebKit are also licensed under LGPL2. Per LGPL2:
+
+> (1) If you statically link against an LGPL’d library, you must also provide your application in an object (not necessarily source) format, so that a user has the opportunity to modify the library and relink the application.
+
+You can find the patched version of WebKit used by Bun here: . If you would like to relink Bun with changes:
+
+- `git submodule update --init --recursive`
+- `make jsc`
+- `zig build`
+
+This compiles JavaScriptCore, compiles Bun’s `.cpp` bindings for JavaScriptCore (which are the object files using JavaScriptCore) and outputs a new `bun` binary with your changes.
+
+## Linked libraries
+
+Bun statically links these libraries:
+
+| Library | License |
+|---------|---------|
+| [`boringssl`](https://boringssl.googlesource.com/boringssl/) | [several licenses](https://boringssl.googlesource.com/boringssl/+/refs/heads/master/LICENSE) |
+| [`brotli`](https://github.com/google/brotli) | MIT |
+| [`libarchive`](https://github.com/libarchive/libarchive) | [several licenses](https://github.com/libarchive/libarchive/blob/master/COPYING) |
+| [`lol-html`](https://github.com/cloudflare/lol-html/tree/master/c-api) | BSD 3-Clause |
+| [`mimalloc`](https://github.com/microsoft/mimalloc) | MIT |
+| [`picohttp`](https://github.com/h2o/picohttpparser) | dual-licensed under the Perl License or the MIT License |
+| [`zstd`](https://github.com/facebook/zstd) | dual-licensed under the BSD License or GPLv2 license |
+| [`simdutf`](https://github.com/simdutf/simdutf) | Apache 2.0 |
+| [`tinycc`](https://github.com/tinycc/tinycc) | LGPL v2.1 |
+| [`uSockets`](https://github.com/uNetworking/uSockets) | Apache 2.0 |
+| [`zlib-cloudflare`](https://github.com/cloudflare/zlib) | zlib |
+| [`c-ares`](https://github.com/c-ares/c-ares) | MIT licensed |
+| [`libicu`](https://github.com/unicode-org/icu) 72 | [license here](https://github.com/unicode-org/icu/blob/main/icu4c/LICENSE) |
+| [`libbase64`](https://github.com/aklomp/base64/blob/master/LICENSE) | BSD 2-Clause |
+| [`libuv`](https://github.com/libuv/libuv) (on Windows) | MIT |
+| [`libdeflate`](https://github.com/ebiggers/libdeflate) | MIT |
+| A fork of [`uWebsockets`](https://github.com/jarred-sumner/uwebsockets) | Apache 2.0 licensed |
+| Parts of [Tigerbeetle's IO code](https://github.com/tigerbeetle/tigerbeetle/blob/532c8b70b9142c17e07737ab6d3da68d7500cbca/src/io/windows.zig#L1) | Apache 2.0 licensed |
+
+## Polyfills
+
+For compatibility reasons, the following packages are embedded into Bun's binary and injected if imported.
+
+| Package | License |
+|---------|---------|
+| [`assert`](https://npmjs.com/package/assert) | MIT |
+| [`browserify-zlib`](https://npmjs.com/package/browserify-zlib) | MIT |
+| [`buffer`](https://npmjs.com/package/buffer) | MIT |
+| [`constants-browserify`](https://npmjs.com/package/constants-browserify) | MIT |
+| [`crypto-browserify`](https://npmjs.com/package/crypto-browserify) | MIT |
+| [`domain-browser`](https://npmjs.com/package/domain-browser) | MIT |
+| [`events`](https://npmjs.com/package/events) | MIT |
+| [`https-browserify`](https://npmjs.com/package/https-browserify) | MIT |
+| [`os-browserify`](https://npmjs.com/package/os-browserify) | MIT |
+| [`path-browserify`](https://npmjs.com/package/path-browserify) | MIT |
+| [`process`](https://npmjs.com/package/process) | MIT |
+| [`punycode`](https://npmjs.com/package/punycode) | MIT |
+| [`querystring-es3`](https://npmjs.com/package/querystring-es3) | MIT |
+| [`stream-browserify`](https://npmjs.com/package/stream-browserify) | MIT |
+| [`stream-http`](https://npmjs.com/package/stream-http) | MIT |
+| [`string_decoder`](https://npmjs.com/package/string_decoder) | MIT |
+| [`timers-browserify`](https://npmjs.com/package/timers-browserify) | MIT |
+| [`tty-browserify`](https://npmjs.com/package/tty-browserify) | MIT |
+| [`url`](https://npmjs.com/package/url) | MIT |
+| [`util`](https://npmjs.com/package/util) | MIT |
+| [`vm-browserify`](https://npmjs.com/package/vm-browserify) | MIT |
+
+## Additional credits
+
+- Bun's JS transpiler, CSS lexer, and Node.js module resolver source code is a Zig port of [@evanw](https://github.com/evanw)’s [esbuild](https://github.com/evanw/esbuild) project.
+- Credit to [@kipply](https://github.com/kipply) for the name "Bun"!
diff --git a/resources/bun/licenses/LGPL-2.0.txt b/resources/bun/licenses/LGPL-2.0.txt
new file mode 100644
index 00000000..87c4a33d
--- /dev/null
+++ b/resources/bun/licenses/LGPL-2.0.txt
@@ -0,0 +1,488 @@
+
+
+NOTE! The LGPL below is copyrighted by the Free Software Foundation, but
+the instance of code that it refers to (the kde libraries) are copyrighted
+by the authors who actually wrote it.
+
+---------------------------------------------------------------------------
+ GNU LIBRARY GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1991 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor
+ Boston, MA 02110-1301, USA.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the library GPL. It is
+ numbered 2 because it goes with version 2 of the ordinary GPL.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Library General Public License, applies to some
+specially designated Free Software Foundation software, and to any
+other libraries whose authors decide to use it. You can use it for
+your libraries, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if
+you distribute copies of the library, or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link a program with the library, you must provide
+complete object files to the recipients so that they can relink them
+with the library, after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ Our method of protecting your rights has two steps: (1) copyright
+the library, and (2) offer you this license which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ Also, for each distributor's protection, we want to make certain
+that everyone understands that there is no warranty for this free
+library. If the library is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original
+version, so that any problems introduced by others will not reflect on
+the original authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that companies distributing free
+software will individually obtain patent licenses, thus in effect
+transforming the program into proprietary software. To prevent this,
+we have made it clear that any patent must be licensed for everyone's
+free use or not licensed at all.
+
+ Most GNU software, including some libraries, is covered by the ordinary
+GNU General Public License, which was designed for utility programs. This
+license, the GNU Library General Public License, applies to certain
+designated libraries. This license is quite different from the ordinary
+one; be sure to read it in full, and don't assume that anything in it is
+the same as in the ordinary license.
+
+ The reason we have a separate public license for some libraries is that
+they blur the distinction we usually make between modifying or adding to a
+program and simply using it. Linking a program with a library, without
+changing the library, is in some sense simply using the library, and is
+analogous to running a utility program or application program. However, in
+a textual and legal sense, the linked executable is a combined work, a
+derivative of the original library, and the ordinary General Public License
+treats it as such.
+
+ Because of this blurred distinction, using the ordinary General
+Public License for libraries did not effectively promote software
+sharing, because most developers did not use the libraries. We
+concluded that weaker conditions might promote sharing better.
+
+ However, unrestricted linking of non-free programs would deprive the
+users of those programs of all benefit from the free status of the
+libraries themselves. This Library General Public License is intended to
+permit developers of non-free programs to use free libraries, while
+preserving your freedom as a user of such programs to change the free
+libraries that are incorporated in them. (We have not seen how to achieve
+this as regards changes in header files, but we have achieved it as regards
+changes in the actual functions of the Library.) The hope is that this
+will lead to faster development of free libraries.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, while the latter only
+works together with the library.
+
+ Note that it is possible for a library to be covered by the ordinary
+General Public License rather than by this special one.
+
+ GNU LIBRARY GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library which
+contains a notice placed by the copyright holder or other authorized
+party saying it may be distributed under the terms of this Library
+General Public License (also called "this License"). Each licensee is
+addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also compile or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ c) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ d) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the source code distributed need not include anything that is normally
+distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Library General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ , 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
diff --git a/resources/bun/licenses/LGPL-2.1.txt b/resources/bun/licenses/LGPL-2.1.txt
new file mode 100644
index 00000000..223ede7d
--- /dev/null
+++ b/resources/bun/licenses/LGPL-2.1.txt
@@ -0,0 +1,504 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ , 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
+
+
diff --git a/resources/bun/licenses/SOURCE.md b/resources/bun/licenses/SOURCE.md
new file mode 100644
index 00000000..8fa0a336
--- /dev/null
+++ b/resources/bun/licenses/SOURCE.md
@@ -0,0 +1,19 @@
+# Bun 1.3.5 source and relinking materials
+
+SubMiner redistributes unmodified Bun 1.3.5 executables from the official Bun release. The executables report revision `1e86cebd74a5723e818b5c0555276b646bcf0e4c` through `bun --revision`. Bun's `bun-v1.3.5` Git tag points to the next commit, `fa5a5bbe556a4bda5bde77b4013aa6c3bb4ec9ab`, so the tag archive does not exactly match the distributed executables.
+
+The SubMiner GitHub release containing this application also contains `bun-v1.3.5-source.tar.gz` and its `.sha256` file. The archive contains:
+
+- Bun source at the binary's reported revision
+- WebKit and JavaScriptCore source at `6d0f3aac0b817cc01a846b3754b21271adedac12`
+- TinyCC source at `29985a3b59898861442fa3b43f663fc1af2591d7`
+- every external source repository registered by that Bun revision's CMake build, at its exact commit
+- Bun's dependency patches, build scripts, lockfiles, collected third-party license files, and instructions for rebuilding Bun against a modified JavaScriptCore
+
+The machine-readable inventory lives at `SOURCE-INVENTORY.json` inside the source archive and at `build/bun-source-manifest.json` in SubMiner's source repository.
+
+The archive vendors the source repositories linked through Bun's CMake build. It preserves Bun's package-manager lockfiles and lol-html's `Cargo.lock`, but it does not vendor npm packages, crates.io packages, compilers, SDKs, or other build tools. Rebuilding needs network access for those package-manager and toolchain inputs. The archive's rebuild README records the known tool versions and the remaining unpinned Rust nightly input.
+
+Bun's own license overview is included as `Bun-LICENSE.md`. WebKit's JavaScriptCore copy of GNU Library General Public License version 2 is included as `LGPL-2.0.txt`. TinyCC's GNU Lesser General Public License version 2.1 is included as `LGPL-2.1.txt`. `THIRD-PARTY-NOTICES.md` collects license texts from Bun's other externally fetched linked dependencies and identifies the scope of the remaining per-file notices in the source archive.
+
+This notice describes the materials supplied with the release. It is not a legal-compliance or reproducible-build claim.
diff --git a/resources/bun/licenses/THIRD-PARTY-NOTICES.md b/resources/bun/licenses/THIRD-PARTY-NOTICES.md
new file mode 100644
index 00000000..d4a64575
--- /dev/null
+++ b/resources/bun/licenses/THIRD-PARTY-NOTICES.md
@@ -0,0 +1,2011 @@
+# Bun 1.3.5 third-party notices
+
+This file collects the license texts shipped by the external source repositories used by Bun 1.3.5 at the revisions in build/bun-source-manifest.json. The corresponding-source release asset also preserves license notices embedded in individual Bun and WebKit source files. Bun’s own LICENSE.md lists additional embedded libraries and JavaScript polyfills whose source and per-file notices are included in that asset.
+
+## BoringSSL
+
+Source revision: f1ffd9e83d4f5c28a9c70d73f9a4e6fcf310062f
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+
+Licenses for support code
+-------------------------
+
+Parts of the TLS test suite are under the Go license. This code is not included
+in BoringSSL (i.e. libcrypto and libssl) when compiled, however, so
+distributing code linked against BoringSSL does not trigger this license:
+
+Copyright (c) 2009 The Go Authors. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+The Apache License, Version 2.0 (Apache-2.0)
+
+Copyright 2015-2020 the fiat-crypto authors (see the AUTHORS file)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+Copyright 2008, Google Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+## Brotli
+
+Source revision: ed738e842d2fbdf2d6459e39267a633c4a9b2f5d
+
+Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+## c-ares
+
+Source revision: 3ac47ee46edd8ea40370222f91613fc16c434853
+
+MIT License
+
+Copyright (c) 1998 Massachusetts Institute of Technology
+Copyright (c) 2007 - 2023 Daniel Stenberg with many contributors, see AUTHORS
+file.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice (including the next
+paragraph) shall be included in all copies or substantial portions of the
+Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+## HdrHistogram-CC0
+
+Source revision: be60a9987ee48d0abf0d7b6a175bad8d6c1585d1
+
+Creative Commons Legal Code
+
+CC0 1.0 Universal
+
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
+ HEREUNDER.
+
+Statement of Purpose
+
+The laws of most jurisdictions throughout the world automatically confer
+exclusive Copyright and Related Rights (defined below) upon the creator
+and subsequent owner(s) (each and all, an "owner") of an original work of
+authorship and/or a database (each, a "Work").
+
+Certain owners wish to permanently relinquish those rights to a Work for
+the purpose of contributing to a commons of creative, cultural and
+scientific works ("Commons") that the public can reliably and without fear
+of later claims of infringement build upon, modify, incorporate in other
+works, reuse and redistribute as freely as possible in any form whatsoever
+and for any purposes, including without limitation commercial purposes.
+These owners may contribute to the Commons to promote the ideal of a free
+culture and the further production of creative, cultural and scientific
+works, or to gain reputation or greater distribution for their Work in
+part through the use and efforts of others.
+
+For these and/or other purposes and motivations, and without any
+expectation of additional consideration or compensation, the person
+associating CC0 with a Work (the "Affirmer"), to the extent that he or she
+is an owner of Copyright and Related Rights in the Work, voluntarily
+elects to apply CC0 to the Work and publicly distribute the Work under its
+terms, with knowledge of his or her Copyright and Related Rights in the
+Work and the meaning and intended legal effect of CC0 on those rights.
+
+1. Copyright and Related Rights. A Work made available under CC0 may be
+protected by copyright and related or neighboring rights ("Copyright and
+Related Rights"). Copyright and Related Rights include, but are not
+limited to, the following:
+
+ i. the right to reproduce, adapt, distribute, perform, display,
+ communicate, and translate a Work;
+ ii. moral rights retained by the original author(s) and/or performer(s);
+iii. publicity and privacy rights pertaining to a person's image or
+ likeness depicted in a Work;
+ iv. rights protecting against unfair competition in regards to a Work,
+ subject to the limitations in paragraph 4(a), below;
+ v. rights protecting the extraction, dissemination, use and reuse of data
+ in a Work;
+ vi. database rights (such as those arising under Directive 96/9/EC of the
+ European Parliament and of the Council of 11 March 1996 on the legal
+ protection of databases, and under any national implementation
+ thereof, including any amended or successor version of such
+ directive); and
+vii. other similar, equivalent or corresponding rights throughout the
+ world based on applicable law or treaty, and any national
+ implementations thereof.
+
+2. Waiver. To the greatest extent permitted by, but not in contravention
+of, applicable law, Affirmer hereby overtly, fully, permanently,
+irrevocably and unconditionally waives, abandons, and surrenders all of
+Affirmer's Copyright and Related Rights and associated claims and causes
+of action, whether now known or unknown (including existing as well as
+future claims and causes of action), in the Work (i) in all territories
+worldwide, (ii) for the maximum duration provided by applicable law or
+treaty (including future time extensions), (iii) in any current or future
+medium and for any number of copies, and (iv) for any purpose whatsoever,
+including without limitation commercial, advertising or promotional
+purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
+member of the public at large and to the detriment of Affirmer's heirs and
+successors, fully intending that such Waiver shall not be subject to
+revocation, rescission, cancellation, termination, or any other legal or
+equitable action to disrupt the quiet enjoyment of the Work by the public
+as contemplated by Affirmer's express Statement of Purpose.
+
+3. Public License Fallback. Should any part of the Waiver for any reason
+be judged legally invalid or ineffective under applicable law, then the
+Waiver shall be preserved to the maximum extent permitted taking into
+account Affirmer's express Statement of Purpose. In addition, to the
+extent the Waiver is so judged Affirmer hereby grants to each affected
+person a royalty-free, non transferable, non sublicensable, non exclusive,
+irrevocable and unconditional license to exercise Affirmer's Copyright and
+Related Rights in the Work (i) in all territories worldwide, (ii) for the
+maximum duration provided by applicable law or treaty (including future
+time extensions), (iii) in any current or future medium and for any number
+of copies, and (iv) for any purpose whatsoever, including without
+limitation commercial, advertising or promotional purposes (the
+"License"). The License shall be deemed effective as of the date CC0 was
+applied by Affirmer to the Work. Should any part of the License for any
+reason be judged legally invalid or ineffective under applicable law, such
+partial invalidity or ineffectiveness shall not invalidate the remainder
+of the License, and in such case Affirmer hereby affirms that he or she
+will not (i) exercise any of his or her remaining Copyright and Related
+Rights in the Work or (ii) assert any associated claims and causes of
+action with respect to the Work, in either case contrary to Affirmer's
+express Statement of Purpose.
+
+4. Limitations and Disclaimers.
+
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
+ surrendered, licensed or otherwise affected by this document.
+ b. Affirmer offers the Work as-is and makes no representations or
+ warranties of any kind concerning the Work, express, implied,
+ statutory or otherwise, including without limitation warranties of
+ title, merchantability, fitness for a particular purpose, non
+ infringement, or the absence of latent or other defects, accuracy, or
+ the present or absence of errors, whether or not discoverable, all to
+ the greatest extent permissible under applicable law.
+ c. Affirmer disclaims responsibility for clearing rights of other persons
+ that may apply to the Work or any use thereof, including without
+ limitation any person's Copyright and Related Rights in the Work.
+ Further, Affirmer disclaims responsibility for obtaining any necessary
+ consents, permissions or other rights required for any use of the
+ Work.
+ d. Affirmer understands and acknowledges that Creative Commons is not a
+ party to this document and has no duty or obligation with respect to
+ this CC0 or use of the Work.
+
+## HdrHistogram-BSD-2-Clause
+
+Source revision: be60a9987ee48d0abf0d7b6a175bad8d6c1585d1
+
+The code in this repository code was Written by Gil Tene, Michael Barker,
+Matt Warren, and Philip Orwig, and released to the public domain, as explained at
+http://creativecommons.org/publicdomain/zero/1.0/
+
+For users of this code who wish to consume it under the "BSD" license
+rather than under the public domain or CC0 contribution text mentioned
+above, the code found under this directory is *also* provided under the
+following license (commonly referred to as the BSD 2-Clause License). This
+license does not detract from the above stated release of the code into
+the public domain, and simply represents an additional license granted by
+the Author.
+
+-----------------------------------------------------------------------------
+** Beginning of "BSD 2-Clause License" text. **
+
+ Copyright (c) 2012, 2013, 2014 Gil Tene
+ Copyright (c) 2014 Michael Barker
+ Copyright (c) 2014 Matt Warren
+ Copyright (c) 2015 Philip Orwig
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ THE POSSIBILITY OF SUCH DAMAGE.
+
+## Highway
+
+Source revision: ac0d5d297b13ab1b89f48484fc7911082d76a93f
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+## libarchive
+
+Source revision: 9525f90ca4bd14c7b335e2f8c84a4607b0af6bdf
+
+The libarchive distribution as a whole is Copyright by Tim Kientzle
+and is subject to the copyright notice reproduced at the bottom of
+this file.
+
+Each individual file in this distribution should have a clear
+copyright/licensing statement at the beginning of the file. If any do
+not, please let me know and I will rectify it. The following is
+intended to summarize the copyright status of the individual files;
+the actual statements in the files are controlling.
+
+* Except as listed below, all C sources (including .c and .h files)
+ and documentation files are subject to the copyright notice reproduced
+ at the bottom of this file.
+
+* The following source files are also subject in whole or in part to
+ a 3-clause UC Regents copyright; please read the individual source
+ files for details:
+ libarchive/archive_read_support_filter_compress.c
+ libarchive/archive_write_add_filter_compress.c
+ libarchive/mtree.5
+
+* The following source files are in the public domain:
+ libarchive/archive_parse_date.c
+
+* The following source files are triple-licensed with the ability to choose
+ from CC0 1.0 Universal, OpenSSL or Apache 2.0 licenses:
+ libarchive/archive_blake2.h
+ libarchive/archive_blake2_impl.h
+ libarchive/archive_blake2s_ref.c
+ libarchive/archive_blake2sp_ref.c
+
+* The build files---including Makefiles, configure scripts,
+ and auxiliary scripts used as part of the compile process---have
+ widely varying licensing terms. Please check individual files before
+ distributing them to see if those restrictions apply to you.
+
+I intend for all new source code to use the license below and hope over
+time to replace code with other licenses with new implementations that
+do use the license below. The varying licensing of the build scripts
+seems to be an unavoidable mess.
+
+
+Copyright (c) 2003-2018
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer
+ in this position and unchanged.
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+## libdeflate
+
+Source revision: c8c56a20f8f621e6a966b716b31f1dedab6a41e3
+
+Copyright 2016 Eric Biggers
+Copyright 2024 Google LLC
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation files
+(the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of the Software,
+and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+## libuv
+
+Source revision: f3ce527ea940d926c40878ba5de219640c362811
+
+Copyright (c) 2015-present libuv project contributors.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to
+deal in the Software without restriction, including without limitation the
+rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+IN THE SOFTWARE.
+
+## lol-html
+
+Source revision: d64457d9ff0143deef025d5df7e8586092b9afb7
+
+Copyright (C) 2019, Cloudflare, Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice,
+this list of conditions and the following disclaimer in the documentation and/or
+other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its contributors
+may be used to endorse or promote products derived from this software without
+specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+## ls-hpack
+
+Source revision: 8905c024b6d052f083a3d11d0a169b3c2735c8a1
+
+MIT License
+
+Copyright (c) 2018 - 2023 LiteSpeed Technologies Inc
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+## mimalloc
+
+Source revision: 1beadf9651a7bfdec6b5367c380ecc3fe1c40d1a
+
+MIT License
+
+Copyright (c) 2018-2021 Microsoft Corporation, Daan Leijen
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+## zlib
+
+Source revision: 886098f3f339617b4243b286f5ed364b9989e245
+
+Copyright notice:
+
+ (C) 1995-2022 Jean-loup Gailly and Mark Adler
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+ Jean-loup Gailly Mark Adler
+ jloup@gzip.org madler@alumni.caltech.edu
+
+## zstd-BSD
+
+Source revision: f8745da6ff1ad1e7bab384bd1f9d742439278e99
+
+BSD License
+
+For Zstandard software
+
+Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * Neither the name Facebook, nor Meta, nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+## zstd-GPLv2
+
+Source revision: f8745da6ff1ad1e7bab384bd1f9d742439278e99
+
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, write to the Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ , 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
+## picohttpparser
+
+Source revision: 066d2b1e9ab820703db0837a7255d92d30f0c9f5
+
+/*
+ * Copyright (c) 2009-2014 Kazuho Oku, Tokuhiro Matsuno, Daisuke Murase,
+ * Shigeo Mitsunari
+ *
+ * The software is licensed under either the MIT License (below) or the Perl
+ * license.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+## Bun uSockets fork
+
+
+
+Source: Bun source tree at packages/bun-usockets
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+## Bun uWebSockets fork
+
+
+
+Source: Bun source tree at packages/bun-uws
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+## zig-clap
+
+
+
+Source: Bun source tree at src/deps/zig-clap
+
+
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a compiled
+binary, for any purpose, commercial or non-commercial, and by any
+means.
+
+In jurisdictions that recognize copyright laws, the author or authors
+of this software dedicate any and all copyright interest in the
+software to the public domain. We make this dedication for the benefit
+of the public at large and to the detriment of our heirs and
+successors. We intend this dedication to be an overt act of
+relinquishment in perpetuity of all present and future rights to this
+software under copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+For more information, please refer to
diff --git a/scripts/build-changelog.test.ts b/scripts/build-changelog.test.ts
index 764bbffd..cfb2ef06 100644
--- a/scripts/build-changelog.test.ts
+++ b/scripts/build-changelog.test.ts
@@ -620,6 +620,10 @@ test('writePrereleaseNotesForVersion writes cumulative beta notes without mutati
assert.match(prereleaseNotes, /## Highlights\n### Added\n- Polished: added entry\./);
assert.match(prereleaseNotes, /### Fixed\n- Polished: fixed entry\./);
assert.match(prereleaseNotes, /## Installation\n\nSee the README and docs\/installation guide/);
+ assert.match(prereleaseNotes, /Windows `subminer\.cmd` launcher/);
+ assert.match(prereleaseNotes, /Both launcher downloads use Bun included with the SubMiner app/);
+ assert.match(prereleaseNotes, /Bun corresponding source: `bun-v1\.3\.5-source\.tar\.gz`/);
+ assert.match(prereleaseNotes, /statically links JavaScriptCore \(LGPL 2\.0\)/);
} finally {
fs.rmSync(workspace, { recursive: true, force: true });
}
diff --git a/scripts/build-changelog.ts b/scripts/build-changelog.ts
index 2330e26d..01cf7227 100644
--- a/scripts/build-changelog.ts
+++ b/scripts/build-changelog.ts
@@ -977,9 +977,12 @@ function renderReleaseNotes(
'- Linux: `SubMiner.AppImage`',
'- macOS: `SubMiner-*.dmg` and `SubMiner-*.zip`',
'- Windows: `SubMiner-*.exe` and `SubMiner-*-win.zip`',
- '- Optional extras: `subminer-assets.tar.gz` and the `subminer` launcher',
+ '- Optional extras: `subminer-assets.tar.gz`, the `subminer` launcher, and the Windows `subminer.cmd` launcher',
+ '- Bun corresponding source: `bun-v1.3.5-source.tar.gz` and its `.sha256` file',
'',
- 'Note: the `subminer` wrapper script uses Bun (`#!/usr/bin/env bun`), so `bun` must be installed and on `PATH`.',
+ 'Both launcher downloads use Bun included with the SubMiner app. Download `subminer` on Linux or macOS and `subminer.cmd` on Windows.',
+ '',
+ 'The app bundles an unmodified Bun 1.3.5 runtime. Bun is MIT licensed and statically links JavaScriptCore (LGPL 2.0) and TinyCC (LGPL 2.1). License texts and third-party notices ship inside the app under `resources/bun/licenses`, and the source archive above contains the matching Bun, WebKit, and dependency sources for relinking.',
'',
].join('\n');
}
diff --git a/scripts/build-launcher.ts b/scripts/build-launcher.ts
new file mode 100644
index 00000000..ff868a85
--- /dev/null
+++ b/scripts/build-launcher.ts
@@ -0,0 +1,54 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { execFileSync } from 'node:child_process';
+import packageJson from '../package.json';
+import { posixLauncherBootstrapContent } from '../src/main/runtime/posix-launcher-bootstrap';
+import { windowsLauncherBootstrapContent } from '../src/main/runtime/windows-launcher-bootstrap';
+
+const outputDirectory = path.join(process.cwd(), 'dist', 'launcher');
+
+function bundle(options: {
+ entrypoint: string;
+ outfile: string;
+ target: 'bun' | 'node';
+ format?: 'cjs';
+ banner?: string;
+}): void {
+ const args = [
+ 'build',
+ options.entrypoint,
+ `--outfile=${options.outfile}`,
+ `--target=${options.target}`,
+ '--packages=bundle',
+ ];
+ if (options.format) args.push(`--format=${options.format}`);
+ if (options.banner) args.push(`--banner=${options.banner}`);
+ execFileSync(process.execPath, args, { stdio: 'inherit' });
+}
+
+fs.mkdirSync(outputDirectory, { recursive: true });
+
+bundle({
+ entrypoint: path.join(process.cwd(), 'launcher', 'main.ts'),
+ outfile: path.join(outputDirectory, 'subminer.js'),
+ target: 'bun',
+ banner: '#!/usr/bin/env bun',
+});
+bundle({
+ entrypoint: path.join(process.cwd(), 'src', 'main', 'runtime', 'prepare-launcher-runtime.ts'),
+ outfile: path.join(outputDirectory, 'prepare.cjs'),
+ target: 'node',
+ format: 'cjs',
+});
+
+const posixLauncherPath = path.join(outputDirectory, 'subminer');
+fs.writeFileSync(posixLauncherPath, posixLauncherBootstrapContent(), { mode: 0o755 });
+fs.chmodSync(posixLauncherPath, 0o755);
+fs.writeFileSync(
+ path.join(outputDirectory, 'subminer.cmd'),
+ windowsLauncherBootstrapContent(),
+ 'utf8',
+);
+fs.writeFileSync(path.join(outputDirectory, 'version'), `${packageJson.version}\n`, 'utf8');
+
+console.log(`Built launcher runtime artifacts in ${outputDirectory}`);
diff --git a/scripts/electron-builder-after-pack.cjs b/scripts/electron-builder-after-pack.cjs
index 4153f760..52310ab2 100644
--- a/scripts/electron-builder-after-pack.cjs
+++ b/scripts/electron-builder-after-pack.cjs
@@ -86,15 +86,33 @@ async function verifyMacOSWindowHelper(
return true;
}
-async function afterPack(context) {
+async function stageBundledBunRuntime(context, deps = {}) {
+ const stageBunRuntime =
+ deps.stageBunRuntime ?? (await import('./stage-bun-runtime.mjs')).stageBunRuntime;
+ const productFilename = context.packager?.appInfo?.productFilename;
+ await stageBunRuntime({
+ appOutDir: context.appOutDir,
+ platform: context.electronPlatformName,
+ arch: context.arch,
+ productFilename:
+ typeof productFilename === 'string' && productFilename.trim()
+ ? productFilename.trim()
+ : 'SubMiner',
+ });
+}
+
+async function afterPack(context, deps = {}) {
await stageLinuxAppImageSharedLibrary(context);
await verifyMacOSWindowHelper(context);
+ await stageBundledBunRuntime(context, deps);
+ await (deps.auditPackage ?? require('./package-audit.cjs').auditPackage)(context);
}
module.exports = {
LINUX_FFMPEG_LIBRARY,
MACOS_WINDOW_HELPER,
resolveMacOSAppBundlePath,
+ stageBundledBunRuntime,
stageLinuxAppImageSharedLibrary,
verifyMacOSWindowHelper,
default: afterPack,
diff --git a/scripts/electron-builder-after-pack.test.ts b/scripts/electron-builder-after-pack.test.ts
index 5470b62c..d8cb3a36 100644
--- a/scripts/electron-builder-after-pack.test.ts
+++ b/scripts/electron-builder-after-pack.test.ts
@@ -13,7 +13,23 @@ const {
} = require('./electron-builder-after-pack.cjs') as {
LINUX_FFMPEG_LIBRARY: string;
MACOS_WINDOW_HELPER: string;
- default: (context: { appOutDir: string; electronPlatformName: string }) => Promise;
+ default: (
+ context: {
+ appOutDir: string;
+ arch?: number;
+ electronPlatformName: string;
+ packager?: { appInfo?: { productFilename?: string } };
+ },
+ deps?: {
+ auditPackage?: (context: { appOutDir: string }) => Promise;
+ stageBunRuntime?: (options: {
+ appOutDir: string;
+ platform: string;
+ arch: number | undefined;
+ productFilename: string;
+ }) => Promise;
+ },
+ ) => Promise;
stageLinuxAppImageSharedLibrary: (context: {
appOutDir: string;
electronPlatformName: string;
@@ -156,3 +172,55 @@ test('afterPack propagates Linux staging failures', async () => {
fs.rmSync(workspace, { recursive: true, force: true });
}
});
+
+test('afterPack stages Linux and Bun runtime assets before auditing the package', async () => {
+ const workspace = createWorkspace('subminer-after-pack-target');
+ const appOutDir = path.join(workspace, 'SubMiner-linux-arm64');
+ const sourceLibraryPath = path.join(appOutDir, LINUX_FFMPEG_LIBRARY);
+ const targetLibraryPath = path.join(appOutDir, 'usr', 'lib', LINUX_FFMPEG_LIBRARY);
+ const operations: string[] = [];
+ let stagedOptions:
+ | {
+ appOutDir: string;
+ platform: string;
+ arch: number | undefined;
+ productFilename: string;
+ }
+ | undefined;
+
+ fs.mkdirSync(appOutDir, { recursive: true });
+ fs.writeFileSync(sourceLibraryPath, 'bundled ffmpeg', 'utf8');
+
+ try {
+ await afterPack(
+ {
+ appOutDir,
+ arch: 3,
+ electronPlatformName: 'linux',
+ packager: { appInfo: { productFilename: 'SubMiner Preview' } },
+ },
+ {
+ stageBunRuntime: async (options) => {
+ stagedOptions = options;
+ operations.push('stage-bun');
+ },
+ auditPackage: async (context) => {
+ assert.equal(context.appOutDir, appOutDir);
+ assert.equal(fs.readFileSync(targetLibraryPath, 'utf8'), 'bundled ffmpeg');
+ operations.push('audit');
+ },
+ },
+ );
+
+ assert.deepEqual(operations, ['stage-bun', 'audit']);
+ assert.deepEqual(stagedOptions, {
+ appOutDir,
+ platform: 'linux',
+ arch: 3,
+ productFilename: 'SubMiner Preview',
+ });
+ assert.equal(fs.readFileSync(targetLibraryPath, 'utf8'), 'bundled ffmpeg');
+ } finally {
+ fs.rmSync(workspace, { recursive: true, force: true });
+ }
+});
diff --git a/scripts/package-audit.cjs b/scripts/package-audit.cjs
new file mode 100644
index 00000000..9dc15757
--- /dev/null
+++ b/scripts/package-audit.cjs
@@ -0,0 +1,243 @@
+const fs = require('node:fs');
+const path = require('node:path');
+const assert = require('node:assert/strict');
+const asar = require('@electron/asar');
+const { Arch } = require('builder-util');
+
+const MIB = 1024 * 1024;
+const currentReports = new Set();
+const REQUIRED_APP_FILES = [
+ 'package.json',
+ 'LICENSE',
+ 'config.example.jsonc',
+ 'dist/main-entry.js',
+ 'dist/main.js',
+ 'dist/preload.js',
+ 'dist/preload-settings.js',
+ 'dist/preload-syncui.js',
+ 'dist/preload-stats.js',
+ 'dist/preload-jellyfin-setup.js',
+ 'dist/fonts/MPLUS1[wght].ttf',
+ 'stats/dist/index.html',
+ 'vendor/texthooker-ui/docs/index.html',
+ ...['renderer', 'settings', 'syncui'].flatMap((ui) => [
+ `dist/${ui}/index.html`,
+ `dist/${ui}/style.css`,
+ `dist/${ui}/${ui}.js`,
+ ]),
+];
+const REQUIRED_RESOURCES = [
+ 'yomitan/manifest.json',
+ 'yomitan/data/fonts/kanji-stroke-orders.ttf',
+ 'yomitan/fonts/NotoSansJP-Regular.ttf',
+ 'yomitan/lib/resvg.wasm',
+ 'launcher/subminer',
+ 'plugin/subminer/main.lua',
+ 'plugin/subminer.conf',
+ 'assets/SubMiner.png',
+ 'assets/SubMiner-square.png',
+ 'assets/themes/subminer.rasi',
+ 'assets/thumbnailers/subminer-ffmpegthumbnailer.thumbnailer',
+ 'CHANGELOG.md',
+];
+
+// Do not follow framework symlinks or count ASAR unpacked entries twice.
+function listFiles(root, prefix = '') {
+ return fs.readdirSync(path.join(root, prefix), { withFileTypes: true }).flatMap((entry) => {
+ const name = prefix ? `${prefix}/${entry.name}` : entry.name;
+ if (entry.isSymbolicLink()) return [];
+ if (entry.isDirectory()) return listFiles(root, name);
+ return [{ path: name, bytes: fs.statSync(path.join(root, name)).size }];
+ });
+}
+
+function listAppFiles(archive) {
+ return asar.listPackage(archive).flatMap((entry) => {
+ const name = entry.replaceAll('\\', '/').replace(/^\//, '');
+ const stat = asar.statFile(archive, name);
+ return 'size' in stat ? [{ path: name, bytes: stat.size }] : [];
+ });
+}
+
+function verifyAppPath(name, platform, arch) {
+ const allowedRoots = new Set([
+ 'dist',
+ 'node_modules',
+ 'stats',
+ 'vendor',
+ 'package.json',
+ 'LICENSE',
+ 'config.example.jsonc',
+ ]);
+ assert(allowedRoots.has(name.split('/')[0]), `Unexpected app file: ${name}`);
+ assert(!name.endsWith('.map'), `Packaged source map: ${name}`);
+ assert(!/\.(?:[cm]?ts|tsx)$/.test(name), `Packaged TypeScript: ${name}`);
+ assert(!/\.(?:test|spec)\./.test(name), `Packaged test: ${name}`);
+ assert(
+ !/(?:^|\/)(?:tests?|__tests__|fixtures?|__fixtures__)\//.test(name),
+ `Packaged test or fixture directory: ${name}`,
+ );
+ assert(!/^dist\/.*\.test\./.test(name), `Packaged test: ${name}`);
+ assert(!/^dist\/(launcher|scripts)\//.test(name), `Duplicate helper: ${name}`);
+ assert(!/^dist\/(renderer|settings|syncui)\/fonts\//.test(name), `Duplicate font: ${name}`);
+ assert(!name.startsWith('stats/') || name.startsWith('stats/dist/'), `Stats source: ${name}`);
+ assert(
+ !name.startsWith('vendor/') || name.startsWith('vendor/texthooker-ui/docs/'),
+ `Vendor source: ${name}`,
+ );
+ if (name.startsWith('node_modules/koffi/')) {
+ assert.equal(platform, 'win32', `Koffi shipped on ${platform}`);
+ assert(!/^node_modules\/koffi\/(src|vendor|doc)\//.test(name), `Koffi build files: ${name}`);
+ if (name.endsWith('.node')) {
+ assert.equal(name, `node_modules/koffi/build/koffi/win32_${arch}/koffi.node`);
+ }
+ }
+}
+
+function verifyContents(archive, resources, platform, arch) {
+ const entries = listAppFiles(archive);
+ const names = new Set(entries.map((entry) => entry.path));
+ for (const name of REQUIRED_APP_FILES) assert(names.has(name), `Missing app file: ${name}`);
+ for (const name of REQUIRED_RESOURCES) {
+ assert(fs.statSync(path.join(resources, name)).size > 0, `Empty resource: ${name}`);
+ }
+ assert(listFiles(path.join(resources, 'yomitan-jlpt-vocab')).length > 0, 'Missing JLPT data');
+ for (const { path: name } of entries) verifyAppPath(name, platform, arch);
+ const libsqlPlatform = {
+ linux: `linux-${arch}-gnu`,
+ darwin: `darwin-${arch}`,
+ win32: `win32-${arch}-msvc`,
+ }[platform];
+ const libsqlBinary = `node_modules/@libsql/${libsqlPlatform}/index.node`;
+ assert(names.has(libsqlBinary), `Missing SQLite native binary: ${libsqlBinary}`);
+ for (const name of names) {
+ if (name.startsWith('node_modules/@libsql/') && name.endsWith('.node')) {
+ assert.equal(name, libsqlBinary, `Foreign SQLite binary: ${name}`);
+ }
+ }
+ if (platform === 'win32') {
+ for (const name of [
+ 'index.js',
+ 'package.json',
+ 'LICENSE.txt',
+ `build/koffi/win32_${arch}/koffi.node`,
+ ]) {
+ assert(names.has(`node_modules/koffi/${name}`), `Missing Windows FFI file: ${name}`);
+ }
+ }
+ for (const name of listFiles(path.join(resources, 'assets'))) {
+ assert(!name.path.startsWith('minecard'), `Demo media shipped: ${name.path}`);
+ }
+ for (const ui of ['renderer', 'settings', 'syncui']) {
+ const css = asar.extractFile(archive, `dist/${ui}/style.css`).toString();
+ assert(css.includes('../fonts/MPLUS1[wght].ttf'), `Shared font missing from ${ui} CSS`);
+ }
+ return entries;
+}
+
+async function auditPackage(context) {
+ const platform = context.electronPlatformName;
+ const arch = Arch[context.arch];
+ const key = `${platform}-${arch}`;
+ const appRoot =
+ platform === 'darwin'
+ ? path.join(context.appOutDir, `${context.packager.appInfo.productFilename}.app`)
+ : context.appOutDir;
+ const resources = path.join(appRoot, platform === 'darwin' ? 'Contents/Resources' : 'resources');
+ const appFiles = verifyContents(path.join(resources, 'app.asar'), resources, platform, arch);
+ const files = listFiles(appRoot);
+ const unpackedBytes = files.reduce((sum, entry) => sum + entry.bytes, 0);
+ const report = {
+ version: context.packager.appInfo.version,
+ platform,
+ arch,
+ unpackedBytes,
+ appDirectory: path.relative(context.outDir, appRoot),
+ largestFiles: [...files].sort((a, b) => b.bytes - a.bytes).slice(0, 25),
+ largestAppFiles: [...appFiles].sort((a, b) => b.bytes - a.bytes).slice(0, 25),
+ nativeBinaries: files.filter((entry) => /\.(node|dll|dylib)$|\.so(?:\.|$)/.test(entry.path)),
+ artifacts: [],
+ };
+ const output = path.join(context.outDir, `package-size-${key}.json`);
+ fs.mkdirSync(path.dirname(output), { recursive: true });
+ fs.writeFileSync(output, `${JSON.stringify(report, null, 2)}\n`);
+ currentReports.add(output);
+ console.log(
+ `Package contents verified: ${key}, ${(unpackedBytes / MIB).toFixed(2)} MiB unpacked`,
+ );
+}
+
+function artifactKind(name) {
+ if (name.endsWith('-mac.zip')) return 'mac.zip';
+ if (name.endsWith('-win.zip')) return 'win.zip';
+ const extension = path.extname(name).slice(1);
+ return ['AppImage', 'dmg', 'exe'].includes(extension) ? extension : undefined;
+}
+
+function compareSizes(report, previous) {
+ assert.equal(previous.platform, report.platform);
+ assert.equal(previous.arch, report.arch);
+ assert(Number.isFinite(previous.unpackedBytes), 'Invalid previous size report');
+ const previousArtifacts = Array.isArray(previous.artifacts) ? previous.artifacts : [];
+ return {
+ version: previous.version,
+ unpackedDeltaBytes: report.unpackedBytes - previous.unpackedBytes,
+ artifacts: report.artifacts.flatMap((artifact) => {
+ const old = previousArtifacts.find(
+ (entry) => entry && entry.kind === artifact.kind && Number.isFinite(entry.bytes),
+ );
+ return old ? [{ kind: artifact.kind, deltaBytes: artifact.bytes - old.bytes }] : [];
+ }),
+ };
+}
+
+// Runs after signing and installer creation, before release upload.
+async function afterAllArtifactBuild(result) {
+ const reports = [];
+ for (const reportPath of currentReports) {
+ const filename = path.basename(reportPath);
+ const report = JSON.parse(fs.readFileSync(reportPath, 'utf8'));
+ const key = `${report.platform}-${report.arch}`;
+ const files = listFiles(path.join(result.outDir, report.appDirectory));
+ report.unpackedBytes = files.reduce((sum, entry) => sum + entry.bytes, 0);
+ report.largestFiles = [...files].sort((a, b) => b.bytes - a.bytes).slice(0, 25);
+ report.artifacts = result.artifactPaths.flatMap((file) => {
+ const kind = artifactKind(file);
+ if (!kind) return [];
+ const bytes = fs.statSync(file).size;
+ return [{ name: path.basename(file), kind, bytes }];
+ });
+ const previousPath = path.join(result.outDir, '..', '.tmp', 'package-baseline', filename);
+ if (fs.existsSync(previousPath)) {
+ const previous = JSON.parse(fs.readFileSync(previousPath, 'utf8'));
+ report.comparison = compareSizes(report, previous);
+ }
+ fs.writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`);
+ const summary = [
+ `### Package size: ${key}`,
+ '',
+ `Unpacked: ${(report.unpackedBytes / MIB).toFixed(2)} MiB`,
+ ...report.artifacts.map((entry) => `${entry.name}: ${(entry.bytes / MIB).toFixed(2)} MiB`),
+ report.comparison
+ ? `Change from ${report.comparison.version}: ${(report.comparison.unpackedDeltaBytes / MIB).toFixed(2)} MiB unpacked`
+ : 'No previous size report available.',
+ '',
+ ].join('\n');
+ console.log(summary);
+ if (process.env.GITHUB_STEP_SUMMARY)
+ fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, summary);
+ reports.push(reportPath);
+ }
+ assert(reports.length > 0, 'No package size reports generated by afterPack');
+ return reports;
+}
+
+module.exports = {
+ auditPackage,
+ verifyContents,
+ verifyAppPath,
+ listFiles,
+ listAppFiles,
+ compareSizes,
+ default: afterAllArtifactBuild,
+};
diff --git a/scripts/package-audit.test.ts b/scripts/package-audit.test.ts
new file mode 100644
index 00000000..0232b580
--- /dev/null
+++ b/scripts/package-audit.test.ts
@@ -0,0 +1,178 @@
+import assert from 'node:assert/strict';
+import { mkdtempSync, mkdirSync, writeFileSync, statSync, rmSync, createReadStream } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+import { createPackageFromStreams } from '@electron/asar';
+import { FileMatcher, getFileMatchers } from 'app-builder-lib/out/fileMatcher';
+import config from '../package.json';
+import { listAppFiles, listFiles, compareSizes, verifyAppPath } from './package-audit.cjs';
+
+test('platform packaging preserves the runtime allowlist after builder normalizes global filters', () => {
+ const root = process.cwd();
+ const fileStat = statSync('package.json');
+ for (const platform of ['linux', 'mac', 'win'] as const) {
+ const matchers = getFileMatchers(
+ { files: [{ filter: config.build.files }] },
+ 'files',
+ '/tmp/subminer-filter-output',
+ {
+ defaultSrc: root,
+ globalOutDir: path.join(root, 'release'),
+ customBuildOptions: { files: config.build[platform].files },
+ macroExpander: (value) => value.replaceAll('${arch}', 'x64'),
+ },
+ );
+ assert(matchers);
+ // This is builder's default for an exclusion-only platform matcher.
+ for (const matcher of matchers) {
+ if (matcher.containsOnlyIgnore()) matcher.prependPattern('**/*');
+ }
+ const included = (name: string) =>
+ matchers.some((matcher) => matcher.createFilter()(path.join(root, name), fileStat));
+ for (const name of [
+ 'dist/main-entry.js',
+ 'dist/fonts/MPLUS1[wght].ttf',
+ 'stats/dist/index.html',
+ 'vendor/texthooker-ui/docs/index.html',
+ 'package.json',
+ ]) {
+ assert(included(name), `${platform} must ship ${name}`);
+ }
+ for (const name of [
+ '.agents/skills/test.md',
+ 'src/main.ts',
+ 'scripts/build-yomitan.mjs',
+ 'docs-site/index.md',
+ 'dist/main.js.map',
+ 'dist/main.test.js',
+ 'dist/nested/source.ts',
+ 'dist/nested/__tests__/helper.js',
+ 'stats/dist/nested/fixtures/data.json',
+ 'vendor/texthooker-ui/docs/nested/component.tsx',
+ 'dist/launcher/subminer',
+ 'dist/settings/fonts/MPLUS1[wght].ttf',
+ 'vendor/subminer-yomitan/ext/manifest.json',
+ ]) {
+ assert(!included(name), `${platform} must exclude ${name}`);
+ }
+ }
+});
+
+test('dependency filters keep only the target Windows Koffi binary', () => {
+ const root = process.cwd();
+ for (const arch of ['x64', 'arm64']) {
+ for (const platform of ['linux', 'mac', 'win'] as const) {
+ const patterns = [
+ '**/*',
+ ...config.build.files.filter((name) => name.startsWith('!')),
+ ...config.build[platform].files.filter((name) => name.startsWith('!')),
+ ];
+ const filter = new FileMatcher(
+ root,
+ '/tmp/subminer-filter-output',
+ (value) => value.replaceAll('${arch}', arch),
+ patterns,
+ ).createFilter();
+ const included = (name: string) =>
+ filter(path.join(root, 'node_modules', name), statSync('package.json'));
+ assert(included('@libsql/win32-x64-msvc/index.node'));
+ assert(!included('axios/dist/axios.js.map'));
+ assert(!included('koffi/src/koffi/src/ffi.c'));
+ assert(!included('agent-base/src/index.ts'));
+ assert(!included('@discordjs/rest/dist/index.d.mts'));
+ assert(!included('example/lib/tests/helper.js'));
+ for (const target of [
+ 'win32_x64',
+ 'win32_arm64',
+ 'linux_x64',
+ 'darwin_arm64',
+ 'openbsd_x64',
+ ]) {
+ assert.equal(
+ included(`koffi/build/koffi/${target}/koffi.node`),
+ platform === 'win' && target === `win32_${arch}`,
+ `${platform}/${arch}: ${target}`,
+ );
+ }
+ assert.equal(included('koffi/index.js'), platform === 'win');
+ assert.equal(included('koffi/LICENSE.txt'), platform === 'win');
+ }
+ }
+});
+
+test('content audit rejects development files beneath approved roots', () => {
+ for (const root of ['dist', 'stats/dist', 'vendor/texthooker-ui/docs', 'node_modules/example']) {
+ for (const suffix of [
+ 'nested/source.ts',
+ 'nested/component.tsx',
+ 'nested/types.d.mts',
+ 'nested/source.cts',
+ 'nested/__tests__/helper.js',
+ 'nested/tests/helper.js',
+ 'nested/test/helper.js',
+ 'nested/__fixtures__/data.json',
+ 'nested/fixtures/data.json',
+ 'nested/fixture/data.json',
+ 'nested/component.spec.js',
+ 'nested/component.test.cjs',
+ ]) {
+ assert.throws(() => verifyAppPath(`${root}/${suffix}`, 'linux', 'x64'), /Packaged/);
+ }
+ for (const suffix of ['nested/runtime.js', 'nested/style.css', 'nested/data.json']) {
+ assert.doesNotThrow(() => verifyAppPath(`${root}/${suffix}`, 'linux', 'x64'));
+ }
+ }
+});
+
+test('archive inventory handles native files without counting them twice on disk', async () => {
+ const root = mkdtempSync(path.join(tmpdir(), 'subminer-audit-'));
+ try {
+ const input = path.join(root, 'input');
+ const output = path.join(root, 'output');
+ mkdirSync(input);
+ mkdirSync(output);
+ writeFileSync(path.join(input, 'main.js'), 'hello');
+ writeFileSync(path.join(input, 'native.node'), 'native');
+ const archive = path.join(output, 'app.asar');
+ await createPackageFromStreams(
+ archive,
+ ['main.js', 'native.node'].map((name) => ({
+ path: name,
+ type: 'file',
+ unpacked: name.endsWith('.node'),
+ stat: statSync(path.join(input, name)),
+ streamGenerator: () => createReadStream(path.join(input, name)),
+ })),
+ );
+ assert.deepEqual(listAppFiles(archive), [
+ { path: 'main.js', bytes: 5 },
+ { path: 'native.node', bytes: 6 },
+ ]);
+ assert.equal(
+ listFiles(output).reduce((sum: number, entry: { bytes: number }) => sum + entry.bytes, 0),
+ statSync(archive).size + 6,
+ );
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('size comparison tolerates older reports without artifact measurements', () => {
+ const previous = { version: '0.19.6', platform: 'linux', arch: 'x64', unpackedBytes: 100 };
+ const current = { ...previous, unpackedBytes: 80, artifacts: [{ kind: 'AppImage', bytes: 40 }] };
+ assert.deepEqual(compareSizes(current, previous), {
+ version: '0.19.6',
+ unpackedDeltaBytes: -20,
+ artifacts: [],
+ });
+ assert.deepEqual(
+ compareSizes(current, { ...previous, artifacts: [null, { kind: 'AppImage', bytes: 50 }] })
+ .artifacts,
+ [{ kind: 'AppImage', deltaBytes: -10 }],
+ );
+ assert.throws(
+ () => compareSizes(current, { ...previous, unpackedBytes: 'unknown' }),
+ /Invalid previous size report/,
+ );
+});
diff --git a/scripts/package-bun-source.mjs b/scripts/package-bun-source.mjs
new file mode 100644
index 00000000..1d88d3c6
--- /dev/null
+++ b/scripts/package-bun-source.mjs
@@ -0,0 +1,456 @@
+import { createHash, randomUUID } from 'node:crypto';
+import { createReadStream, createWriteStream } from 'node:fs';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { pipeline } from 'node:stream/promises';
+import { Readable } from 'node:stream';
+
+const scriptDir = path.dirname(fileURLToPath(import.meta.url));
+const repoRoot = path.resolve(scriptDir, '..');
+
+export const DEFAULT_MANIFEST_PATH = path.join(repoRoot, 'build', 'bun-source-manifest.json');
+export const DEFAULT_RUNTIME_MANIFEST_PATH = path.join(
+ repoRoot,
+ 'build',
+ 'bun-runtime-manifest.json',
+);
+export const DEFAULT_PACKAGE_JSON_PATH = path.join(repoRoot, 'package.json');
+export const DEFAULT_OUTPUT_DIR = path.join(repoRoot, 'release');
+export const DEFAULT_CACHE_DIR = path.join(repoRoot, '.tmp', 'bun-corresponding-source');
+
+function isRecord(value) {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function requiredString(record, key, source) {
+ const value = record[key];
+ if (typeof value !== 'string' || value.length === 0) {
+ throw new Error(`${source} must contain a non-empty ${key} string.`);
+ }
+ return value;
+}
+
+function assertSafeRelativePath(value, source) {
+ if (path.isAbsolute(value) || value.split(/[\\/]/).includes('..')) {
+ throw new Error(`${source} contains an unsafe path: ${value}`);
+ }
+}
+
+export function parseSourceManifest(value) {
+ if (!isRecord(value) || value.schemaVersion !== 1) {
+ throw new Error('Bun source manifest must use schemaVersion 1.');
+ }
+ const version = requiredString(value, 'version', 'Bun source manifest');
+ const bunRevision = requiredString(value, 'bunRevision', 'Bun source manifest');
+ const archiveName = requiredString(value, 'archiveName', 'Bun source manifest');
+ if (!/^\d+\.\d+\.\d+$/.test(version) || !/^[a-f0-9]{40}$/.test(bunRevision)) {
+ throw new Error('Bun source manifest has an invalid version or bunRevision.');
+ }
+ if (path.basename(archiveName) !== archiveName || !archiveName.endsWith('.tar.gz')) {
+ throw new Error('Bun source manifest archiveName must be a safe .tar.gz filename.');
+ }
+ if (!Array.isArray(value.sources) || value.sources.length === 0) {
+ throw new Error('Bun source manifest must contain sources.');
+ }
+
+ const names = new Set();
+ const destinations = new Set();
+ const sources = value.sources.map((entry, index) => {
+ if (!isRecord(entry)) throw new Error(`Bun source ${index} must be an object.`);
+ const name = requiredString(entry, 'name', `Bun source ${index}`);
+ const repository = requiredString(entry, 'repository', `Bun source ${name}`);
+ const revision = requiredString(entry, 'revision', `Bun source ${name}`);
+ const destination = requiredString(entry, 'destination', `Bun source ${name}`);
+ if (!/^[\w.-]+\/[\w.-]+$/.test(repository) || !/^[a-f0-9]{40}$/.test(revision)) {
+ throw new Error(`Bun source ${name} has an invalid repository or revision.`);
+ }
+ assertSafeRelativePath(destination, `Bun source ${name}`);
+ if (names.has(name) || destinations.has(destination)) {
+ throw new Error(`Bun source manifest repeats ${name} or ${destination}.`);
+ }
+ names.add(name);
+ destinations.add(destination);
+
+ const transport = entry.transport ?? 'archive';
+ if (transport !== 'archive' && transport !== 'git-sparse') {
+ throw new Error(`Bun source ${name} has unsupported transport ${transport}.`);
+ }
+ const sha256 =
+ transport === 'archive' ? requiredString(entry, 'sha256', `Bun source ${name}`) : null;
+ if (sha256 !== null && !/^[a-f0-9]{64}$/.test(sha256)) {
+ throw new Error(`Bun source ${name} has an invalid SHA-256 digest.`);
+ }
+ if (!Array.isArray(entry.licensePaths) || entry.licensePaths.length === 0) {
+ throw new Error(`Bun source ${name} must declare licensePaths.`);
+ }
+ const licensePaths = entry.licensePaths.map((licensePath) => {
+ if (typeof licensePath !== 'string' || licensePath.length === 0) {
+ throw new Error(`Bun source ${name} has an invalid license path.`);
+ }
+ assertSafeRelativePath(licensePath, `Bun source ${name}`);
+ return licensePath;
+ });
+ const exclude = Array.isArray(entry.exclude) ? entry.exclude : [];
+ for (const excludedPath of exclude) assertSafeRelativePath(excludedPath, `Bun source ${name}`);
+ return {
+ ...entry,
+ name,
+ repository,
+ revision,
+ destination,
+ transport,
+ sha256,
+ licensePaths,
+ exclude,
+ };
+ });
+
+ const bun = sources.find((source) => source.name === 'bun');
+ if (!bun || bun.revision !== bunRevision || bun.destination !== 'bun') {
+ throw new Error('Bun source manifest must map bunRevision to the bun source at bun/.');
+ }
+ return { ...value, version, bunRevision, archiveName, sources };
+}
+
+export function parseRegisteredRepositories(cmakeText) {
+ const registrations = new Map();
+ const uncommented = cmakeText.replace(/#[^\n]*/g, '');
+ for (const match of uncommented.matchAll(/register_repository\(([\s\S]*?)\)/g)) {
+ const body = match[1];
+ const name = /\bNAME\s+([^\s#)]+)/.exec(body)?.[1];
+ const repository = /\bREPOSITORY\s+([^\s#)]+)/.exec(body)?.[1];
+ const reference = /\b(COMMIT|TAG)\s+(?:#[^\n]*\n\s*)?([^\s#)]+)/.exec(body);
+ if (name && repository && reference) {
+ registrations.set(name, {
+ repository,
+ kind: reference[1].toLowerCase(),
+ reference: reference[2],
+ });
+ }
+ }
+ return registrations;
+}
+
+export function validateRuntimeAlignment(manifest, packageJson, runtimeManifest) {
+ if (!isRecord(packageJson) || packageJson.packageManager !== `bun@${manifest.version}`) {
+ throw new Error(
+ `package.json must pin bun@${manifest.version} to match the Bun source manifest.`,
+ );
+ }
+ if (!isRecord(runtimeManifest)) throw new Error('Bun runtime manifest must be an object.');
+ for (const key of ['version', 'bunRevision']) {
+ if (runtimeManifest[key] !== manifest[key]) {
+ throw new Error(`Bun runtime manifest ${key} does not match the Bun source manifest.`);
+ }
+ }
+ if (runtimeManifest.correspondingSourceAsset !== manifest.archiveName) {
+ throw new Error(
+ 'Bun runtime manifest correspondingSourceAsset does not match the Bun source manifest.',
+ );
+ }
+}
+
+export function validateBunPins(manifest, cmakeTexts, setupWebKitText) {
+ const actual = new Map();
+ for (const cmakeText of cmakeTexts) {
+ for (const [name, registration] of parseRegisteredRepositories(cmakeText)) {
+ if (actual.has(name)) throw new Error(`Bun registers ${name} more than once.`);
+ actual.set(name, registration);
+ }
+ }
+ const expected = new Map(
+ manifest.sources
+ .filter((source) => source.destination.startsWith('bun/vendor/') && source.name !== 'WebKit')
+ .map((source) => [source.name, source]),
+ );
+ for (const [name, registration] of actual) {
+ const source = expected.get(name);
+ if (!source) throw new Error(`Source manifest omits Bun dependency ${name}.`);
+ if (source.repository !== registration.repository) {
+ throw new Error(`Source manifest repository mismatch for ${name}.`);
+ }
+ const expectedReference = source.upstreamReference ?? source.revision;
+ if (expectedReference !== registration.reference) {
+ throw new Error(`Source manifest revision mismatch for ${name}.`);
+ }
+ expected.delete(name);
+ }
+ if (expected.size > 0) {
+ throw new Error(
+ `Source manifest has unregistered Bun dependencies: ${[...expected.keys()].join(', ')}.`,
+ );
+ }
+
+ const webKitPin = /set\(WEBKIT_VERSION\s+([a-f0-9]{40})\)/.exec(setupWebKitText)?.[1];
+ const webKit = manifest.sources.find((source) => source.name === 'WebKit');
+ if (!webKitPin || !webKit || webKit.revision !== webKitPin) {
+ throw new Error('Source manifest WebKit revision does not match SetupWebKit.cmake.');
+ }
+}
+
+async function sha256File(filePath) {
+ const hash = createHash('sha256');
+ for await (const chunk of createReadStream(filePath)) hash.update(chunk);
+ return hash.digest('hex');
+}
+
+async function run(command, args, options = {}) {
+ await new Promise((resolve, reject) => {
+ const child = spawn(command, args, { stdio: 'inherit', ...options });
+ child.once('error', reject);
+ child.once('close', (code) => {
+ if (code === 0) resolve();
+ else reject(new Error(`${command} exited with status ${code}.`));
+ });
+ });
+}
+
+export async function downloadArchive(source, cacheDir, fetchImpl) {
+ const archivePath = path.join(cacheDir, `${source.name}-${source.revision}.tar.gz`);
+ try {
+ if ((await sha256File(archivePath)) === source.sha256) return archivePath;
+ await fs.rm(archivePath, { force: true });
+ } catch (error) {
+ if (!isRecord(error) || error.code !== 'ENOENT') throw error;
+ }
+
+ const url = `https://codeload.github.com/${source.repository}/tar.gz/${source.revision}`;
+ const temporaryPath = `${archivePath}.download-${randomUUID()}`;
+ try {
+ const response = await fetchImpl(url);
+ if (!response.ok || !response.body)
+ throw new Error(`Unable to download ${url}: HTTP ${response.status}`);
+ await pipeline(
+ Readable.fromWeb(response.body),
+ createWriteStream(temporaryPath, { flags: 'wx' }),
+ );
+ const actualSha256 = await sha256File(temporaryPath);
+ if (actualSha256 !== source.sha256) {
+ throw new Error(
+ `Source checksum mismatch for ${source.name}: expected ${source.sha256}, received ${actualSha256}.`,
+ );
+ }
+ await fs.rename(temporaryPath, archivePath);
+ return archivePath;
+ } finally {
+ // Cleanup must not replace the original download, validation, or rename error.
+ await fs.rm(temporaryPath, { force: true }).catch(() => {});
+ }
+}
+
+async function materializeArchive(source, root, cacheDir, fetchImpl) {
+ const archivePath = await downloadArchive(source, cacheDir, fetchImpl);
+ const destination = path.join(root, source.destination);
+ await fs.mkdir(destination, { recursive: true });
+ await run('tar', ['-xzf', archivePath, '-C', destination, '--strip-components=1']);
+}
+
+async function materializeGitSparse(source, root, cacheDir) {
+ const checkout = path.join(cacheDir, `${source.name}-${source.revision}-git`);
+ await fs.rm(checkout, { recursive: true, force: true });
+ await run('git', [
+ 'clone',
+ '--filter=blob:none',
+ '--no-checkout',
+ '--depth=1',
+ `https://github.com/${source.repository}.git`,
+ checkout,
+ ]);
+ await run('git', ['-C', checkout, 'fetch', '--depth=1', 'origin', source.revision]);
+ await run('git', ['-C', checkout, 'sparse-checkout', 'init', '--no-cone']);
+ const sparseRules = ['/*', ...source.exclude.map((entry) => `!/${entry}/`), ''];
+ await fs.writeFile(
+ path.join(checkout, '.git', 'info', 'sparse-checkout'),
+ sparseRules.join('\n'),
+ );
+ await run('git', ['-C', checkout, 'checkout', '--detach', source.revision]);
+ const actualRevision = (await fs.readFile(path.join(checkout, '.git', 'HEAD'), 'utf8')).trim();
+ if (actualRevision !== source.revision)
+ throw new Error(`Git checkout mismatch for ${source.name}.`);
+ await fs.rm(path.join(checkout, '.git'), { recursive: true, force: true });
+ await fs.mkdir(path.dirname(path.join(root, source.destination)), { recursive: true });
+ await fs.rename(checkout, path.join(root, source.destination));
+}
+
+async function applyBunDependencyPatches(root, manifest) {
+ const bunRoot = path.join(root, 'bun');
+ for (const source of manifest.sources) {
+ if (!source.destination.startsWith('bun/vendor/') || source.name === 'WebKit') continue;
+ const destination = path.join(root, source.destination);
+ const patchDirectory = path.join(bunRoot, 'patches', source.name);
+ let entries = [];
+ try {
+ entries = await fs.readdir(patchDirectory, { withFileTypes: true });
+ } catch (error) {
+ if (!isRecord(error) || error.code !== 'ENOENT') throw error;
+ }
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
+ const patchPath = path.join(patchDirectory, entry.name);
+ if (entry.isFile() && entry.name.endsWith('.patch')) {
+ await run(
+ 'git',
+ ['apply', '--ignore-whitespace', '--ignore-space-change', '--no-index', patchPath],
+ { cwd: destination },
+ );
+ } else if (entry.isFile()) {
+ await fs.copyFile(patchPath, path.join(destination, entry.name));
+ }
+ }
+ const cmakeReference = source.upstreamReference
+ ? `refs/tags/${source.upstreamReference}`
+ : source.revision;
+ await fs.writeFile(path.join(destination, '.ref'), `${cmakeReference}\n`);
+ }
+}
+
+async function validateAndCollectLicenses(root, manifest) {
+ const licensesRoot = path.join(root, 'THIRD-PARTY-LICENSES');
+ await fs.mkdir(licensesRoot, { recursive: true });
+ for (const source of manifest.sources) {
+ const target = path.join(licensesRoot, source.name);
+ await fs.mkdir(target, { recursive: true });
+ for (const licensePath of source.licensePaths) {
+ const sourcePath = path.join(root, source.destination, licensePath);
+ const stat = await fs.stat(sourcePath).catch(() => null);
+ if (!stat?.isFile() || stat.size === 0) {
+ throw new Error(`Missing required license material for ${source.name}: ${licensePath}`);
+ }
+ const safeName = licensePath.replaceAll('/', '__');
+ await fs.copyFile(sourcePath, path.join(target, safeName));
+ }
+ }
+}
+
+function rebuildReadme(manifest) {
+ const webKit = manifest.sources.find((source) => source.name === 'WebKit');
+ const tinycc = manifest.sources.find((source) => source.name === 'tinycc');
+ return `# Bun ${manifest.version} corresponding source and rebuild materials
+
+This archive matches the official Bun ${manifest.version} binaries whose \`bun --revision\` output names commit \`${manifest.bunRevision}\`. The GitHub release tag points to \`${manifest.releaseTagCommit}\`, one later commit, so this package intentionally uses the binary revision.
+
+The archive includes Bun's complete source tree, Bun's build scripts and dependency patches, every external repository registered by Bun's CMake build at its exact pin, and Oven's WebKit fork at \`${webKit.revision}\`. Large WebKit test-only trees are excluded. The JavaScriptCore, WTF, WebCore, build-tool, configuration, and resource trees used to build the library are included. TinyCC is \`${tinycc.revision}\`.
+
+## Rebuild with modified JavaScriptCore
+
+Install the prerequisites recorded in \`bun/.buildkite/Dockerfile\`, \`bun/scripts/bootstrap.sh\`, and the WebKit platform build scripts. Bun ${manifest.version} used LLVM 19.1.7, CMake 3.30.5 in its Linux build image, and Bun 1.1.38 as the bootstrap runtime. Its Rust input was nightly and was not pinned to a dated toolchain in the release source.
+
+From this archive root on Linux or macOS:
+
+\`\`\`sh
+cd bun
+bun install --frozen-lockfile
+bun run jsc:build
+bun run build:release:local -- -DVERSION=${manifest.version} -DREVISION=${manifest.bunRevision}
+\`\`\`
+
+The first command uses the bootstrap Bun. \`jsc:build\` builds the included \`vendor/WebKit\` checkout into \`vendor/WebKit/WebKitBuild/Release\`. \`build:release:local\` links Bun against that local JavaScriptCore build. The explicit version and revision replace metadata that Bun normally reads from its Git checkout. The included \`vendor/*/.ref\` files prevent Bun's CMake rules from replacing the packaged dependency sources, and this package has already applied the files under \`bun/patches//\` in the same order as \`bun/cmake/scripts/GitClone.cmake\`.
+
+The archive vendors the source repositories that Bun's CMake build links into the executable. It preserves Bun's \`bun.lock\` files and lol-html's \`Cargo.lock\`, but it does not vendor npm packages, crates.io packages used to build lol-html, compilers, SDKs, or other build tools. The rebuild therefore needs network access for those pinned package-manager inputs. License notices embedded in those downloaded packages are outside the collected \`THIRD-PARTY-LICENSES\` directory's scope.
+
+Windows uses the prerequisites in \`bun/docs/project/building-windows.mdx\` and WebKit's \`windows-release.ps1\`. The local-JavaScriptCore path above has not been verified on Windows.
+
+These instructions describe the source and build entry points. Toolchain and generated-output differences mean a rebuild is not expected to be byte-for-byte identical to Oven's release binary. No claim about legal compliance or reproducible builds is made here.
+`;
+}
+
+async function createDeterministicArchive(stagingParent, rootName, outputPath) {
+ const temporaryTar = `${outputPath}.tar-${randomUUID()}`;
+ const temporaryGzip = `${outputPath}.gzip-${randomUUID()}`;
+ try {
+ await run('tar', [
+ '--sort=name',
+ '--mtime=@0',
+ '--owner=0',
+ '--group=0',
+ '--numeric-owner',
+ '-cf',
+ temporaryTar,
+ '-C',
+ stagingParent,
+ rootName,
+ ]);
+ const gzip = spawn('gzip', ['-n', '-9', '-c', temporaryTar], {
+ stdio: ['ignore', 'pipe', 'inherit'],
+ });
+ const completion = new Promise((resolve, reject) => {
+ gzip.once('error', reject);
+ gzip.once('close', resolve);
+ });
+ const [, code] = await Promise.all([
+ pipeline(gzip.stdout, createWriteStream(temporaryGzip, { flags: 'wx' })),
+ completion,
+ ]);
+ if (code !== 0) throw new Error(`gzip exited with status ${code}.`);
+ await fs.rm(outputPath, { force: true });
+ await fs.rename(temporaryGzip, outputPath);
+ } finally {
+ await Promise.all([
+ fs.rm(temporaryTar, { force: true }),
+ fs.rm(temporaryGzip, { force: true }),
+ ]);
+ }
+}
+
+export async function packageBunSource({
+ manifestPath = DEFAULT_MANIFEST_PATH,
+ runtimeManifestPath = DEFAULT_RUNTIME_MANIFEST_PATH,
+ packageJsonPath = DEFAULT_PACKAGE_JSON_PATH,
+ outputDir = DEFAULT_OUTPUT_DIR,
+ cacheDir = DEFAULT_CACHE_DIR,
+ fetchImpl = globalThis.fetch,
+} = {}) {
+ const [manifestText, runtimeManifestText, packageJsonText] = await Promise.all([
+ fs.readFile(manifestPath, 'utf8'),
+ fs.readFile(runtimeManifestPath, 'utf8'),
+ fs.readFile(packageJsonPath, 'utf8'),
+ ]);
+ const manifest = parseSourceManifest(JSON.parse(manifestText));
+ validateRuntimeAlignment(manifest, JSON.parse(packageJsonText), JSON.parse(runtimeManifestText));
+ if (typeof fetchImpl !== 'function') throw new Error('No fetch implementation is available.');
+ await fs.mkdir(cacheDir, { recursive: true });
+ const stagingParent = await fs.mkdtemp(path.join(cacheDir, 'assemble-'));
+ const rootName = path.basename(manifest.archiveName, '.tar.gz');
+ const root = path.join(stagingParent, rootName);
+ await fs.mkdir(root);
+
+ try {
+ const bun = manifest.sources.find((source) => source.name === 'bun');
+ await materializeArchive(bun, root, cacheDir, fetchImpl);
+ const cmakeFiles = (await fs.readdir(path.join(root, 'bun', 'cmake', 'targets')))
+ .filter((name) => name.endsWith('.cmake'))
+ .map((name) => fs.readFile(path.join(root, 'bun', 'cmake', 'targets', name), 'utf8'));
+ validateBunPins(
+ manifest,
+ await Promise.all(cmakeFiles),
+ await fs.readFile(path.join(root, 'bun', 'cmake', 'tools', 'SetupWebKit.cmake'), 'utf8'),
+ );
+
+ for (const source of manifest.sources.filter((entry) => entry.name !== 'bun')) {
+ if (source.transport === 'git-sparse') await materializeGitSparse(source, root, cacheDir);
+ else await materializeArchive(source, root, cacheDir, fetchImpl);
+ }
+ await applyBunDependencyPatches(root, manifest);
+ await validateAndCollectLicenses(root, manifest);
+ await fs.writeFile(
+ path.join(root, 'SOURCE-INVENTORY.json'),
+ `${JSON.stringify(manifest, null, 2)}\n`,
+ );
+ await fs.writeFile(path.join(root, 'README-REBUILD.md'), rebuildReadme(manifest));
+
+ await fs.mkdir(outputDir, { recursive: true });
+ const outputPath = path.join(outputDir, manifest.archiveName);
+ await createDeterministicArchive(stagingParent, rootName, outputPath);
+ const digest = await sha256File(outputPath);
+ await fs.writeFile(`${outputPath}.sha256`, `${digest} ${manifest.archiveName}\n`);
+ return { outputPath, sha256: digest };
+ } finally {
+ await fs.rm(stagingParent, { recursive: true, force: true });
+ }
+}
+
+if (import.meta.main) {
+ const result = await packageBunSource();
+ console.log(`${result.sha256} ${path.basename(result.outputPath)}`);
+}
diff --git a/scripts/package-bun-source.test.ts b/scripts/package-bun-source.test.ts
new file mode 100644
index 00000000..d361523a
--- /dev/null
+++ b/scripts/package-bun-source.test.ts
@@ -0,0 +1,153 @@
+import { describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import {
+ downloadArchive,
+ parseRegisteredRepositories,
+ parseSourceManifest,
+ validateBunPins,
+ validateRuntimeAlignment,
+} from './package-bun-source.mjs';
+
+const projectRoot = path.resolve(import.meta.dir, '..');
+
+describe('Bun corresponding-source manifest', () => {
+ test('removes partial downloads when placing a valid archive fails', async () => {
+ const cacheDir = await fs.mkdtemp(path.join(os.tmpdir(), 'subminer-bun-source-test-'));
+ try {
+ const payload = new Uint8Array([1, 2, 3]);
+ const source = {
+ name: 'fixture',
+ repository: 'example/fixture',
+ revision: 'a'.repeat(40),
+ sha256: createHash('sha256').update(payload).digest('hex'),
+ };
+ const archivePath = path.join(cacheDir, `${source.name}-${source.revision}.tar.gz`);
+ await expect(
+ downloadArchive(source, cacheDir, async () => {
+ await fs.mkdir(archivePath);
+ return { ok: true, status: 200, body: new Response(payload).body };
+ }),
+ ).rejects.toMatchObject({ syscall: 'rename' });
+
+ const entries = await fs.readdir(cacheDir);
+ expect(entries.filter((entry) => entry.includes('.download-'))).toEqual([]);
+ } finally {
+ await fs.rm(cacheDir, { recursive: true, force: true });
+ }
+ });
+
+ test('pins the source to the revision reported by the distributed binary', async () => {
+ const manifest = parseSourceManifest(
+ JSON.parse(
+ await fs.readFile(path.join(projectRoot, 'build/bun-source-manifest.json'), 'utf8'),
+ ),
+ );
+
+ expect(manifest.version).toBe('1.3.5');
+ expect(manifest.bunRevision).toBe('1e86cebd74a5723e818b5c0555276b646bcf0e4c');
+ expect(manifest.releaseTagCommit).toBe('fa5a5bbe556a4bda5bde77b4013aa6c3bb4ec9ab');
+ expect(manifest.sources.find((source) => source.name === 'WebKit')?.revision).toBe(
+ '6d0f3aac0b817cc01a846b3754b21271adedac12',
+ );
+ expect(manifest.sources.find((source) => source.name === 'tinycc')?.revision).toBe(
+ '29985a3b59898861442fa3b43f663fc1af2591d7',
+ );
+ });
+
+ test('parses commit and tag registrations from Bun CMake', () => {
+ const registrations = parseRegisteredRepositories(`
+ register_repository(
+ NAME tinycc
+ REPOSITORY oven-sh/tinycc
+ COMMIT
+ # A comment between the field and its value is valid CMake.
+ 29985a3b59898861442fa3b43f663fc1af2591d7
+ )
+ register_repository(
+ NAME brotli
+ REPOSITORY google/brotli
+ TAG v1.1.0
+ )
+ `);
+
+ expect(registrations.get('tinycc')).toEqual({
+ repository: 'oven-sh/tinycc',
+ kind: 'commit',
+ reference: '29985a3b59898861442fa3b43f663fc1af2591d7',
+ });
+ expect(registrations.get('brotli')).toEqual({
+ repository: 'google/brotli',
+ kind: 'tag',
+ reference: 'v1.1.0',
+ });
+ });
+
+ test('rejects stale runtime or package-manager pins', async () => {
+ const manifest = parseSourceManifest(
+ JSON.parse(
+ await fs.readFile(path.join(projectRoot, 'build/bun-source-manifest.json'), 'utf8'),
+ ),
+ );
+ const runtimeManifest = {
+ version: manifest.version,
+ bunRevision: manifest.bunRevision,
+ correspondingSourceAsset: manifest.archiveName,
+ };
+
+ expect(() =>
+ validateRuntimeAlignment(manifest, { packageManager: 'bun@1.3.5' }, runtimeManifest),
+ ).not.toThrow();
+ expect(() =>
+ validateRuntimeAlignment(manifest, { packageManager: 'bun@1.3.6' }, runtimeManifest),
+ ).toThrow('package.json must pin bun@1.3.5');
+ expect(() =>
+ validateRuntimeAlignment(
+ manifest,
+ { packageManager: 'bun@1.3.5' },
+ {
+ ...runtimeManifest,
+ correspondingSourceAsset: 'stale.tar.gz',
+ },
+ ),
+ ).toThrow('correspondingSourceAsset does not match');
+ });
+
+ test('rejects drift in CMake dependency and WebKit pins', async () => {
+ const manifest = parseSourceManifest(
+ JSON.parse(
+ await fs.readFile(path.join(projectRoot, 'build/bun-source-manifest.json'), 'utf8'),
+ ),
+ );
+ const registrations = manifest.sources
+ .filter((source) => source.destination.startsWith('bun/vendor/') && source.name !== 'WebKit')
+ .map(
+ (source) => `register_repository(
+ NAME ${source.name}
+ REPOSITORY ${source.repository}
+ ${source.upstreamReference ? 'TAG' : 'COMMIT'} ${source.upstreamReference ?? source.revision}
+ )`,
+ )
+ .join('\n');
+
+ expect(() =>
+ validateBunPins(
+ manifest,
+ [registrations],
+ 'set(WEBKIT_VERSION 6d0f3aac0b817cc01a846b3754b21271adedac12)',
+ ),
+ ).not.toThrow();
+ expect(() =>
+ validateBunPins(
+ manifest,
+ [registrations.replace('29985a3b59898861442fa3b43f663fc1af2591d7', '0'.repeat(40))],
+ 'set(WEBKIT_VERSION 6d0f3aac0b817cc01a846b3754b21271adedac12)',
+ ),
+ ).toThrow('revision mismatch for tinycc');
+ expect(() =>
+ validateBunPins(manifest, [registrations], `set(WEBKIT_VERSION ${'0'.repeat(40)})`),
+ ).toThrow('WebKit revision does not match');
+ });
+});
diff --git a/scripts/prepare-build-assets.mjs b/scripts/prepare-build-assets.mjs
index 721808e5..8e225c7e 100644
--- a/scripts/prepare-build-assets.mjs
+++ b/scripts/prepare-build-assets.mjs
@@ -34,10 +34,6 @@ function copyAssets(sourceDir, outputDir, label, stylesheets = ['style.css']) {
for (const stylesheet of stylesheets) {
copyFile(path.join(sourceDir, stylesheet), path.join(outputDir, stylesheet));
}
- fs.cpSync(path.join(rendererSourceDir, 'fonts'), path.join(outputDir, 'fonts'), {
- recursive: true,
- force: true,
- });
process.stdout.write(`Staged ${label} assets in ${outputDir}\n`);
}
@@ -116,6 +112,10 @@ function buildMacosHelper() {
}
function main() {
+ fs.cpSync(path.join(rendererSourceDir, 'fonts'), path.join(repoRoot, 'dist', 'fonts'), {
+ recursive: true,
+ force: true,
+ });
copyRendererAssets();
copySettingsAssets();
copySyncUiAssets();
diff --git a/scripts/run-package-smoke.mjs b/scripts/run-package-smoke.mjs
new file mode 100644
index 00000000..4ef4d7b2
--- /dev/null
+++ b/scripts/run-package-smoke.mjs
@@ -0,0 +1,24 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { spawnSync } from 'node:child_process';
+import { createRequire } from 'node:module';
+import { fileURLToPath } from 'node:url';
+
+const resources = process.argv[2];
+if (!resources) throw new Error('Usage: bun run test:package ');
+const require = createRequire(import.meta.url);
+const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-package-smoke-'));
+const env = { ...process.env, SUBMINER_PACKAGE_SMOKE_DATA: profile };
+delete env.ELECTRON_RUN_AS_NODE;
+try {
+ const result = spawnSync(
+ require('electron'),
+ [fileURLToPath(new URL('./smoke-package.cjs', import.meta.url)), path.resolve(resources)],
+ { env, stdio: 'inherit', timeout: 75_000 },
+ );
+ if (result.error) throw result.error;
+ process.exitCode = result.status ?? 1;
+} finally {
+ fs.rmSync(profile, { recursive: true, force: true, maxRetries: 3 });
+}
diff --git a/scripts/smoke-package.cjs b/scripts/smoke-package.cjs
new file mode 100644
index 00000000..e0d39a67
--- /dev/null
+++ b/scripts/smoke-package.cjs
@@ -0,0 +1,94 @@
+// Run with the pinned Electron runtime against a finished app's resources folder.
+const { app, BrowserWindow, session } = require('electron');
+const fs = require('node:fs');
+const path = require('node:path');
+const { createRequire } = require('node:module');
+const assert = require('node:assert/strict');
+const { once } = require('node:events');
+
+const resources = path.resolve(process.argv[2]);
+const archive = path.join(resources, 'app.asar');
+const isolatedData = process.env.SUBMINER_PACKAGE_SMOKE_DATA;
+assert(
+ isolatedData && fs.existsSync(isolatedData),
+ 'Use bun run test:package to create an isolated profile',
+);
+app.setPath('userData', isolatedData);
+app.disableHardwareAcceleration();
+app.on('window-all-closed', () => {});
+const timeout = setTimeout(() => {
+ console.error('Package smoke timed out');
+ app.exit(1);
+}, 60_000);
+
+async function smoke() {
+ await app.whenReady();
+ const packagedRequire = createRequire(path.join(archive, 'package.json'));
+ const Database = packagedRequire('libsql');
+ const database = new Database(':memory:');
+ assert.equal(database.prepare('select 42 as answer').get().answer, 42);
+ database.close();
+ if (process.platform === 'win32') {
+ const win32 = packagedRequire('./dist/window-trackers/win32.js');
+ assert(Array.isArray(win32.findMpvWindows().matches));
+ }
+ const { Texthooker } = packagedRequire('./dist/core/services/texthooker.js');
+ const texthooker = new Texthooker();
+ const server = texthooker.start(0);
+ assert(server, 'Packaged texthooker assets could not be found');
+ try {
+ await once(server, 'listening');
+ const response = await fetch(`http://127.0.0.1:${server.address().port}/`);
+ assert.equal(response.status, 200);
+ assert((await response.text()).includes(' {
+ if (details.error !== 'net::ERR_ABORTED')
+ failedRequests.push(`${details.url}: ${details.error}`);
+ });
+ for (const ui of ['renderer', 'settings', 'syncui', 'stats']) {
+ const win = new BrowserWindow({
+ show: false,
+ webPreferences: {
+ sandbox: false,
+ preload: path.join(archive, 'dist', ui === 'renderer' ? 'preload.js' : `preload-${ui}.js`),
+ },
+ });
+ try {
+ await win.loadFile(
+ path.join(archive, ui === 'stats' ? 'stats/dist/index.html' : `dist/${ui}/index.html`),
+ );
+ if (ui !== 'stats') {
+ const loaded = await win.webContents.executeJavaScript(
+ `document.fonts.load('400 16px "M PLUS 1"', '日本語').then(fonts => fonts.length > 0 && fonts.every(font => font.status === 'loaded'))`,
+ );
+ assert(loaded, `${ui}: shared Japanese font failed to load`);
+ }
+ } finally {
+ win.destroy();
+ }
+ }
+ assert.deepEqual(failedRequests, [], 'Packaged UI resources failed to load');
+ console.log(
+ 'Package smoke passed: SQLite, platform FFI, texthooker, Yomitan loading, UI pages, shared Japanese font.',
+ );
+}
+
+smoke()
+ .then(() => {
+ clearTimeout(timeout);
+ app.exit(0);
+ })
+ .catch((error) => {
+ console.error(error);
+ clearTimeout(timeout);
+ app.exit(1);
+ });
diff --git a/scripts/stage-bun-runtime.mjs b/scripts/stage-bun-runtime.mjs
new file mode 100644
index 00000000..e18ce7ec
--- /dev/null
+++ b/scripts/stage-bun-runtime.mjs
@@ -0,0 +1,389 @@
+import { createHash, randomUUID } from 'node:crypto';
+import { createReadStream, createWriteStream } from 'node:fs';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { pipeline } from 'node:stream/promises';
+import { Readable } from 'node:stream';
+import { promisify } from 'node:util';
+import { execFile } from 'node:child_process';
+
+const execFileAsync = promisify(execFile);
+const scriptDir = path.dirname(fileURLToPath(import.meta.url));
+const repoRoot = path.resolve(scriptDir, '..');
+
+export const DEFAULT_PACKAGE_JSON_PATH = path.join(repoRoot, 'package.json');
+export const DEFAULT_MANIFEST_PATH = path.join(repoRoot, 'build', 'bun-runtime-manifest.json');
+export const DEFAULT_CACHE_DIR = path.join(repoRoot, '.tmp', 'bun-runtime');
+export const DEFAULT_LICENSES_SOURCE_DIR = path.join(repoRoot, 'resources', 'bun', 'licenses');
+export const STAGED_METADATA_FILE = 'metadata.json';
+export const REQUIRED_LICENSE_FILES = [
+ 'Bun-LICENSE.md',
+ 'LGPL-2.0.txt',
+ 'LGPL-2.1.txt',
+ 'SOURCE.md',
+ 'THIRD-PARTY-NOTICES.md',
+];
+
+const RELEASE_BASE_URL = 'https://github.com/oven-sh/bun/releases/download';
+const SUPPORTED_PLATFORMS = new Set(['darwin', 'linux', 'win32']);
+const ARCH_BY_BUILDER_VALUE = new Map([
+ [1, 'x64'],
+ [3, 'arm64'],
+ ['x64', 'x64'],
+ ['arm64', 'arm64'],
+]);
+
+function isRecord(value) {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function readRequiredString(record, key, source) {
+ const value = record[key];
+ if (typeof value !== 'string' || value.length === 0) {
+ throw new Error(`${source} must contain a non-empty ${key} string.`);
+ }
+ return value;
+}
+
+function readCommit(record, key, source) {
+ const value = readRequiredString(record, key, source);
+ if (!/^[a-f0-9]{40}$/.test(value)) {
+ throw new Error(`${source} must contain a 40-character ${key} commit.`);
+ }
+ return value;
+}
+
+export function normalizeTarget(platform, arch) {
+ if (!SUPPORTED_PLATFORMS.has(platform)) {
+ throw new Error(`Unsupported Bun runtime target platform: ${platform}`);
+ }
+
+ const normalizedArch = ARCH_BY_BUILDER_VALUE.get(arch);
+ if (!normalizedArch) {
+ throw new Error(`Unsupported Bun runtime target architecture for ${platform}: ${String(arch)}`);
+ }
+ if (platform === 'win32' && normalizedArch !== 'x64') {
+ throw new Error(`Unsupported Bun runtime target: ${platform}-${normalizedArch}`);
+ }
+
+ return {
+ platform,
+ arch: normalizedArch,
+ key: `${platform}-${normalizedArch}`,
+ executableName: platform === 'win32' ? 'bun.exe' : 'bun',
+ };
+}
+
+export function parsePackageManagerVersion(packageJson) {
+ if (!isRecord(packageJson)) {
+ throw new Error('package.json must contain a JSON object.');
+ }
+ const packageManager = readRequiredString(packageJson, 'packageManager', 'package.json');
+ const match = /^bun@(\d+\.\d+\.\d+)$/.exec(packageManager);
+ if (!match) {
+ throw new Error(
+ `package.json packageManager must pin Bun exactly, received ${packageManager}.`,
+ );
+ }
+ return match[1];
+}
+
+function parseArtifact(value, key) {
+ if (!isRecord(value)) {
+ throw new Error(`Bun runtime manifest artifact ${key} must be an object.`);
+ }
+ const file = readRequiredString(value, 'file', `Bun runtime manifest artifact ${key}`);
+ const sha256 = readRequiredString(value, 'sha256', `Bun runtime manifest artifact ${key}`);
+ if (!/^[a-f0-9]{64}$/.test(sha256)) {
+ throw new Error(`Bun runtime manifest artifact ${key} has an invalid SHA-256 digest.`);
+ }
+ if (path.basename(file) !== file || !file.endsWith('.zip')) {
+ throw new Error(`Bun runtime manifest artifact ${key} has an unsafe file name.`);
+ }
+ return { file, sha256 };
+}
+
+export function parseRuntimeManifest(manifest, version) {
+ if (!isRecord(manifest) || manifest.schemaVersion !== 1) {
+ throw new Error('Bun runtime manifest must use schemaVersion 1.');
+ }
+ const manifestVersion = readRequiredString(manifest, 'version', 'Bun runtime manifest');
+ if (manifestVersion !== version) {
+ throw new Error(
+ `Bun runtime manifest version ${manifestVersion} does not match packageManager bun@${version}.`,
+ );
+ }
+ if (!isRecord(manifest.artifacts)) {
+ throw new Error('Bun runtime manifest must contain an artifacts object.');
+ }
+ return {
+ version,
+ bunRevision: readCommit(manifest, 'bunRevision', 'Bun runtime manifest'),
+ releaseTagCommit: readCommit(manifest, 'releaseTagCommit', 'Bun runtime manifest'),
+ artifacts: manifest.artifacts,
+ licenseInventoryStatus: readRequiredString(
+ manifest,
+ 'licenseInventoryStatus',
+ 'Bun runtime manifest',
+ ),
+ sourceManifest: readRequiredString(manifest, 'sourceManifest', 'Bun runtime manifest'),
+ correspondingSourceAsset: readRequiredString(
+ manifest,
+ 'correspondingSourceAsset',
+ 'Bun runtime manifest',
+ ),
+ };
+}
+
+export async function loadRuntimeConfig({
+ packageJsonPath = DEFAULT_PACKAGE_JSON_PATH,
+ manifestPath = DEFAULT_MANIFEST_PATH,
+} = {}) {
+ const [packageJsonText, manifestText] = await Promise.all([
+ fs.readFile(packageJsonPath, 'utf8'),
+ fs.readFile(manifestPath, 'utf8'),
+ ]);
+ const version = parsePackageManagerVersion(JSON.parse(packageJsonText));
+ return parseRuntimeManifest(JSON.parse(manifestText), version);
+}
+
+export function resolveArtifact(config, platform, arch) {
+ const target = normalizeTarget(platform, arch);
+ const artifactValue = config.artifacts[target.key];
+ if (artifactValue === undefined) {
+ throw new Error(`Bun runtime manifest has no artifact for ${target.key}.`);
+ }
+ const artifact = parseArtifact(artifactValue, target.key);
+ return {
+ ...target,
+ ...artifact,
+ version: config.version,
+ url: `${RELEASE_BASE_URL}/bun-v${config.version}/${artifact.file}`,
+ };
+}
+
+export async function sha256File(filePath) {
+ const hash = createHash('sha256');
+ for await (const chunk of createReadStream(filePath)) {
+ hash.update(chunk);
+ }
+ return hash.digest('hex');
+}
+
+export async function ensureCachedArchive(
+ artifact,
+ { cacheDir = DEFAULT_CACHE_DIR, fetchImpl = globalThis.fetch } = {},
+) {
+ if (typeof fetchImpl !== 'function') {
+ throw new Error('No fetch implementation is available to download Bun.');
+ }
+ const versionCacheDir = path.join(cacheDir, artifact.version);
+ const archivePath = path.join(versionCacheDir, artifact.file);
+ await fs.mkdir(versionCacheDir, { recursive: true });
+
+ try {
+ if ((await sha256File(archivePath)) === artifact.sha256) return archivePath;
+ await fs.unlink(archivePath);
+ } catch (error) {
+ if (!isRecord(error) || error.code !== 'ENOENT') throw error;
+ }
+
+ const temporaryPath = `${archivePath}.download-${randomUUID()}`;
+ try {
+ const response = await fetchImpl(artifact.url);
+ if (!response.ok || !response.body) {
+ throw new Error(`Unable to download ${artifact.url}: HTTP ${response.status}`);
+ }
+ await pipeline(
+ Readable.fromWeb(response.body),
+ createWriteStream(temporaryPath, { flags: 'wx' }),
+ );
+ const actualSha256 = await sha256File(temporaryPath);
+ if (actualSha256 !== artifact.sha256) {
+ throw new Error(
+ `Bun archive checksum mismatch for ${artifact.file}: expected ${artifact.sha256}, received ${actualSha256}.`,
+ );
+ }
+ await fs.rename(temporaryPath, archivePath);
+ return archivePath;
+ } catch (error) {
+ await fs.rm(temporaryPath, { force: true });
+ throw error;
+ }
+}
+
+function isSafeZipEntry(entry) {
+ if (entry.startsWith('/') || /^[A-Za-z]:/.test(entry)) return false;
+ return !entry.replaceAll('\\', '/').split('/').includes('..');
+}
+
+function waitForProcess(child, description) {
+ let stderr = '';
+ child.stderr.setEncoding('utf8');
+ child.stderr.on('data', (chunk) => {
+ stderr += chunk;
+ });
+ return new Promise((resolve, reject) => {
+ child.once('error', reject);
+ child.once('close', (code) => {
+ if (code === 0) resolve();
+ else reject(new Error(`${description}: ${stderr.trim() || `process exited ${code}`}`));
+ });
+ });
+}
+
+export function buildWindowsExtractionCommand(archivePath, member, outputPath) {
+ const script = [
+ 'Add-Type -AssemblyName System.IO.Compression.FileSystem',
+ '$archive = [IO.Compression.ZipFile]::OpenRead($env:SUBMINER_BUN_ARCHIVE_PATH)',
+ 'try {',
+ ' $entry = $archive.Entries | Where-Object { $_.FullName -ceq $env:SUBMINER_BUN_ARCHIVE_MEMBER }',
+ ' if ($null -eq $entry) { throw "Archive member not found: $env:SUBMINER_BUN_ARCHIVE_MEMBER" }',
+ ' $inputStream = $entry.Open()',
+ ' $outputStream = [IO.File]::Create($env:SUBMINER_BUN_OUTPUT_PATH)',
+ ' try { $inputStream.CopyTo($outputStream) } finally { $outputStream.Dispose(); $inputStream.Dispose() }',
+ '} finally { $archive.Dispose() }',
+ ].join('; ');
+ return {
+ command: 'powershell.exe',
+ args: [
+ '-NoLogo',
+ '-NoProfile',
+ '-NonInteractive',
+ '-EncodedCommand',
+ Buffer.from(script, 'utf16le').toString('base64'),
+ ],
+ environment: {
+ SUBMINER_BUN_ARCHIVE_PATH: archivePath,
+ SUBMINER_BUN_ARCHIVE_MEMBER: member,
+ SUBMINER_BUN_OUTPUT_PATH: outputPath,
+ },
+ };
+}
+
+async function extractZipMemberOnWindows(archivePath, member, outputPath) {
+ const command = buildWindowsExtractionCommand(archivePath, member, outputPath);
+ const powershell = spawn(command.command, command.args, {
+ env: { ...process.env, ...command.environment },
+ stdio: ['ignore', 'ignore', 'pipe'],
+ });
+ await waitForProcess(powershell, `Unable to extract ${member}`);
+}
+
+export async function extractZipMember(archivePath, member, outputPath) {
+ if (!isSafeZipEntry(member)) {
+ throw new Error(`Refusing to extract unsafe Bun archive member ${member}.`);
+ }
+ await fs.mkdir(path.dirname(outputPath), { recursive: true });
+ const temporaryPath = `${outputPath}.extract-${randomUUID()}`;
+
+ if (process.platform === 'win32') {
+ try {
+ await extractZipMemberOnWindows(archivePath, member, temporaryPath);
+ await fs.chmod(temporaryPath, 0o755);
+ await fs.rename(temporaryPath, outputPath);
+ } catch (error) {
+ await fs.rm(temporaryPath, { force: true });
+ throw error;
+ }
+ return;
+ }
+
+ const { stdout } = await execFileAsync('unzip', ['-Z1', archivePath], {
+ encoding: 'utf8',
+ maxBuffer: 1024 * 1024,
+ });
+ const entries = stdout.split(/\r?\n/).filter(Boolean);
+ if (entries.some((entry) => !isSafeZipEntry(entry))) {
+ throw new Error(`Bun archive ${archivePath} contains an unsafe path.`);
+ }
+ if (!entries.includes(member)) {
+ throw new Error(`Bun archive ${archivePath} does not contain ${member}.`);
+ }
+
+ const output = createWriteStream(temporaryPath, { flags: 'wx', mode: 0o755 });
+ const unzip = spawn('unzip', ['-p', archivePath, member], { stdio: ['ignore', 'pipe', 'pipe'] });
+
+ try {
+ await Promise.all([
+ pipeline(unzip.stdout, output),
+ waitForProcess(unzip, `Unable to extract ${member}`),
+ ]);
+ await fs.chmod(temporaryPath, 0o755);
+ await fs.rename(temporaryPath, outputPath);
+ } catch (error) {
+ await fs.rm(temporaryPath, { force: true });
+ throw error;
+ }
+}
+
+export function resolveResourcesDirectory(appOutDir, platform, productFilename = 'SubMiner') {
+ if (platform !== 'darwin') return path.join(appOutDir, 'resources');
+ const appBundlePath = appOutDir.endsWith('.app')
+ ? appOutDir
+ : path.join(appOutDir, `${productFilename}.app`);
+ return path.join(appBundlePath, 'Contents', 'Resources');
+}
+
+export async function stageBunLicenses(
+ runtimeDirectory,
+ licensesSourceDir = DEFAULT_LICENSES_SOURCE_DIR,
+) {
+ const licensesDirectory = path.join(runtimeDirectory, 'licenses');
+ await Promise.all(
+ REQUIRED_LICENSE_FILES.map((fileName) => fs.access(path.join(licensesSourceDir, fileName))),
+ );
+ await fs.cp(licensesSourceDir, licensesDirectory, { recursive: true, force: true });
+ return licensesDirectory;
+}
+
+export async function stageBunRuntime(
+ { appOutDir, platform, arch, productFilename = 'SubMiner' },
+ {
+ configLoader = loadRuntimeConfig,
+ archiveLoader = ensureCachedArchive,
+ extractor = extractZipMember,
+ licenseStager = stageBunLicenses,
+ } = {},
+) {
+ const config = await configLoader();
+ const artifact = resolveArtifact(config, platform, arch);
+ const archivePath = await archiveLoader(artifact);
+ const archiveDirectory = path.basename(artifact.file, '.zip');
+ const archiveExecutableName = platform === 'win32' ? 'bun.exe' : 'bun';
+ const member = `${archiveDirectory}/${archiveExecutableName}`;
+ const runtimeDirectory = path.join(
+ resolveResourcesDirectory(appOutDir, platform, productFilename),
+ 'bun',
+ );
+ const executablePath = path.join(runtimeDirectory, artifact.executableName);
+ await extractor(archivePath, member, executablePath);
+ await licenseStager(runtimeDirectory);
+
+ const metadata = {
+ name: 'Bun',
+ version: config.version,
+ bunRevision: config.bunRevision,
+ releaseTagCommit: config.releaseTagCommit,
+ target: artifact.key,
+ artifact: artifact.file,
+ artifactSha256: artifact.sha256,
+ sourceUrl: artifact.url,
+ licenseInventoryStatus: config.licenseInventoryStatus,
+ correspondingSourceAsset: config.correspondingSourceAsset,
+ sourceInstructions: 'licenses/SOURCE.md',
+ thirdPartyNotices: 'licenses/THIRD-PARTY-NOTICES.md',
+ };
+ await fs.writeFile(
+ path.join(runtimeDirectory, STAGED_METADATA_FILE),
+ `${JSON.stringify(metadata, null, 2)}\n`,
+ { mode: 0o644 },
+ );
+ return {
+ executablePath,
+ metadataPath: path.join(runtimeDirectory, STAGED_METADATA_FILE),
+ artifact,
+ };
+}
diff --git a/scripts/stage-bun-runtime.test.ts b/scripts/stage-bun-runtime.test.ts
new file mode 100644
index 00000000..56f1c255
--- /dev/null
+++ b/scripts/stage-bun-runtime.test.ts
@@ -0,0 +1,307 @@
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+
+import {
+ buildWindowsExtractionCommand,
+ ensureCachedArchive,
+ extractZipMember,
+ loadRuntimeConfig,
+ normalizeTarget,
+ parsePackageManagerVersion,
+ parseRuntimeManifest,
+ resolveArtifact,
+ stageBunLicenses,
+ stageBunRuntime,
+} from './stage-bun-runtime.mjs';
+
+function sha256(content: Uint8Array): string {
+ return createHash('sha256').update(content).digest('hex');
+}
+
+function runtimeConfig() {
+ return {
+ version: '1.3.5',
+ bunRevision: '1e86cebd74a5723e818b5c0555276b646bcf0e4c',
+ releaseTagCommit: 'fa5a5bbe556a4bda5bde77b4013aa6c3bb4ec9ab',
+ artifacts: {
+ 'darwin-arm64': { file: 'bun-darwin-aarch64.zip', sha256: '1'.repeat(64) },
+ 'darwin-x64': { file: 'bun-darwin-x64-baseline.zip', sha256: '2'.repeat(64) },
+ 'linux-arm64': { file: 'bun-linux-aarch64.zip', sha256: '3'.repeat(64) },
+ 'linux-x64': { file: 'bun-linux-x64-baseline.zip', sha256: '4'.repeat(64) },
+ 'win32-x64': { file: 'bun-windows-x64-baseline.zip', sha256: '5'.repeat(64) },
+ },
+ licenseInventoryStatus: 'complete-for-bun-1.3.5-declared-linked-libraries',
+ sourceManifest: 'build/bun-source-manifest.json',
+ correspondingSourceAsset: 'bun-v1.3.5-source.tar.gz',
+ };
+}
+
+test('normalizeTarget maps each supported electron-builder target without using the host', () => {
+ assert.deepEqual(normalizeTarget('linux', 1), {
+ platform: 'linux',
+ arch: 'x64',
+ key: 'linux-x64',
+ executableName: 'bun',
+ });
+ assert.equal(normalizeTarget('linux', 3).key, 'linux-arm64');
+ assert.equal(normalizeTarget('darwin', 'x64').key, 'darwin-x64');
+ assert.equal(normalizeTarget('darwin', 'arm64').key, 'darwin-arm64');
+ assert.deepEqual(normalizeTarget('win32', 1), {
+ platform: 'win32',
+ arch: 'x64',
+ key: 'win32-x64',
+ executableName: 'bun.exe',
+ });
+ assert.throws(() => normalizeTarget('freebsd', 'x64'), /Unsupported Bun runtime target platform/);
+ assert.throws(() => normalizeTarget('win32', 'arm64'), /Unsupported Bun runtime target/);
+ assert.throws(() => normalizeTarget('linux', 0), /Unsupported Bun runtime target architecture/);
+});
+
+test('resolveArtifact chooses baseline x64 builds and standard arm64 builds', () => {
+ const config = runtimeConfig();
+ assert.equal(resolveArtifact(config, 'linux', 'x64').file, 'bun-linux-x64-baseline.zip');
+ assert.equal(resolveArtifact(config, 'darwin', 'x64').file, 'bun-darwin-x64-baseline.zip');
+ assert.equal(resolveArtifact(config, 'win32', 'x64').file, 'bun-windows-x64-baseline.zip');
+ assert.equal(resolveArtifact(config, 'linux', 'arm64').file, 'bun-linux-aarch64.zip');
+ assert.equal(resolveArtifact(config, 'darwin', 'arm64').file, 'bun-darwin-aarch64.zip');
+});
+
+test('tracked runtime manifest covers every supported target at the packageManager version', async () => {
+ const config = await loadRuntimeConfig();
+ assert.equal(config.version, '1.3.5');
+ for (const [platform, arch] of [
+ ['linux', 'x64'],
+ ['linux', 'arm64'],
+ ['darwin', 'x64'],
+ ['darwin', 'arm64'],
+ ['win32', 'x64'],
+ ]) {
+ const artifact = resolveArtifact(config, platform, arch);
+ assert.match(artifact.sha256, /^[a-f0-9]{64}$/);
+ assert.equal(
+ artifact.url,
+ `https://github.com/oven-sh/bun/releases/download/bun-v1.3.5/${artifact.file}`,
+ );
+ }
+});
+
+test('manifest version must match the exact packageManager Bun pin', () => {
+ assert.equal(parsePackageManagerVersion({ packageManager: 'bun@1.3.5' }), '1.3.5');
+ assert.throws(
+ () => parsePackageManagerVersion({ packageManager: 'bun@^1.3.5' }),
+ /must pin Bun exactly/,
+ );
+ assert.throws(
+ () =>
+ parseRuntimeManifest(
+ {
+ schemaVersion: 1,
+ version: '1.3.6',
+ bunRevision: '1e86cebd74a5723e818b5c0555276b646bcf0e4c',
+ releaseTagCommit: 'fa5a5bbe556a4bda5bde77b4013aa6c3bb4ec9ab',
+ artifacts: {},
+ licenseInventoryStatus: 'partial',
+ sourceManifest: 'build/bun-source-manifest.json',
+ correspondingSourceAsset: 'bun-v1.3.5-source.tar.gz',
+ },
+ '1.3.5',
+ ),
+ /does not match packageManager bun@1\.3\.5/,
+ );
+});
+
+test('ensureCachedArchive verifies downloads and reuses a verified cache entry offline', async () => {
+ const workspace = await fs.mkdtemp(path.join(os.tmpdir(), 'subminer-bun-cache-'));
+ const bytes = new TextEncoder().encode('verified Bun archive fixture');
+ const artifact = {
+ version: '1.3.5',
+ file: 'bun-linux-x64-baseline.zip',
+ sha256: sha256(bytes),
+ url: 'https://example.invalid/bun.zip',
+ };
+ let downloads = 0;
+ const fetchImpl = async () => {
+ downloads += 1;
+ return new Response(bytes);
+ };
+
+ try {
+ const firstPath = await ensureCachedArchive(artifact, { cacheDir: workspace, fetchImpl });
+ const secondPath = await ensureCachedArchive(artifact, {
+ cacheDir: workspace,
+ fetchImpl: async () => {
+ throw new Error('verified cache should not fetch');
+ },
+ });
+ assert.equal(firstPath, secondPath);
+ assert.equal(downloads, 1);
+ assert.deepEqual(await fs.readFile(firstPath), Buffer.from(bytes));
+ } finally {
+ await fs.rm(workspace, { recursive: true, force: true });
+ }
+});
+
+test('ensureCachedArchive rejects a checksum mismatch without caching the download', async () => {
+ const workspace = await fs.mkdtemp(path.join(os.tmpdir(), 'subminer-bun-cache-mismatch-'));
+ const artifact = {
+ version: '1.3.5',
+ file: 'bun-linux-x64-baseline.zip',
+ sha256: '0'.repeat(64),
+ url: 'https://example.invalid/bun.zip',
+ };
+
+ try {
+ await assert.rejects(
+ ensureCachedArchive(artifact, {
+ cacheDir: workspace,
+ fetchImpl: async () => new Response('tampered'),
+ }),
+ /checksum mismatch/,
+ );
+ const cacheEntries = await fs.readdir(path.join(workspace, '1.3.5'));
+ assert.deepEqual(cacheEntries, []);
+ } finally {
+ await fs.rm(workspace, { recursive: true, force: true });
+ }
+});
+
+test('extractZipMember extracts only the requested path and makes the runtime executable', async () => {
+ const workspace = await fs.mkdtemp(path.join(os.tmpdir(), 'subminer-bun-extract-'));
+ const archivePath = path.join(workspace, 'fixture.zip');
+ const outputPath = path.join(workspace, 'output', 'bun');
+ const archiveBase64 =
+ 'UEsDBAoAAAAAAMxcKl3rs337EgAAABIAAAAaABwAYnVuLWxpbnV4LXg2NC1iYXNlbGluZS9idW5VVAkAAyD5omog+aJqdXgLAAEE6AMAAAToAwAAYnVuIGZpeHR1cmUgYmluYXJ5UEsBAh4DCgAAAAAAzFwqXeuzffsSAAAAEgAAABoAGAAAAAAAAQAAAKSBAAAAAGJ1bi1saW51eC14NjQtYmFzZWxpbmUvYnVuVVQFAAMg+aJqdXgLAAEE6AMAAAToAwAAUEsFBgAAAAABAAEAYAAAAGYAAAAAAA==';
+
+ try {
+ await fs.writeFile(archivePath, Buffer.from(archiveBase64, 'base64'));
+ await extractZipMember(archivePath, 'bun-linux-x64-baseline/bun', outputPath);
+ assert.equal(await fs.readFile(outputPath, 'utf8'), 'bun fixture binary');
+ assert.equal((await fs.stat(outputPath)).mode & 0o777, 0o755);
+ await assert.rejects(
+ extractZipMember(archivePath, '../bun', path.join(workspace, 'unsafe')),
+ /unsafe Bun archive member/,
+ );
+ } finally {
+ await fs.rm(workspace, { recursive: true, force: true });
+ }
+});
+
+test('Windows extraction keeps paths and archive members out of PowerShell command text', () => {
+ const archivePath = String.raw`C:\Release Builds\bun $(archive) '1.3.5'.zip`;
+ const member = 'bun-windows-x64-baseline/bun.exe';
+ const outputPath = String.raw`C:\Staged App & Tools\resources\bun\bun.exe`;
+ const command = buildWindowsExtractionCommand(archivePath, member, outputPath);
+ const encodedCommand = command.args.at(-1);
+
+ assert.equal(command.command, 'powershell.exe');
+ assert.equal(command.args.at(-2), '-EncodedCommand');
+ assert.ok(encodedCommand);
+ const script = Buffer.from(encodedCommand, 'base64').toString('utf16le');
+ assert.match(script, /\$env:SUBMINER_BUN_ARCHIVE_PATH/);
+ assert.match(script, /\$env:SUBMINER_BUN_ARCHIVE_MEMBER/);
+ assert.match(script, /\$env:SUBMINER_BUN_OUTPUT_PATH/);
+ assert.doesNotMatch(script, /Release Builds|Staged App|bun-windows-x64-baseline/);
+ assert.deepEqual(command.environment, {
+ SUBMINER_BUN_ARCHIVE_PATH: archivePath,
+ SUBMINER_BUN_ARCHIVE_MEMBER: member,
+ SUBMINER_BUN_OUTPUT_PATH: outputPath,
+ });
+});
+
+test('stageBunLicenses copies the tracked inventory into resources/bun/licenses', async () => {
+ const workspace = await fs.mkdtemp(path.join(os.tmpdir(), 'subminer-bun-licenses-'));
+ const sourceDirectory = path.join(workspace, 'tracked-licenses');
+ const runtimeDirectory = path.join(workspace, 'resources', 'bun');
+
+ try {
+ await fs.mkdir(sourceDirectory, { recursive: true });
+ for (const fileName of [
+ 'Bun-LICENSE.md',
+ 'LGPL-2.0.txt',
+ 'LGPL-2.1.txt',
+ 'SOURCE.md',
+ 'THIRD-PARTY-NOTICES.md',
+ ]) {
+ await fs.writeFile(path.join(sourceDirectory, fileName), `${fileName}\n`);
+ }
+ const licensesDirectory = await stageBunLicenses(runtimeDirectory, sourceDirectory);
+ assert.equal(licensesDirectory, path.join(runtimeDirectory, 'licenses'));
+ assert.equal(
+ await fs.readFile(path.join(licensesDirectory, 'THIRD-PARTY-NOTICES.md'), 'utf8'),
+ 'THIRD-PARTY-NOTICES.md\n',
+ );
+ } finally {
+ await fs.rm(workspace, { recursive: true, force: true });
+ }
+});
+
+test('stageBunRuntime places target executables and metadata in app resources with safe modes', async () => {
+ const workspace = await fs.mkdtemp(path.join(os.tmpdir(), 'subminer-bun-stage-'));
+ const cases = [
+ {
+ platform: 'linux',
+ arch: 'x64',
+ appOutDir: path.join(workspace, 'linux'),
+ relativeExecutable: path.join('resources', 'bun', 'bun'),
+ member: 'bun-linux-x64-baseline/bun',
+ },
+ {
+ platform: 'darwin',
+ arch: 'arm64',
+ appOutDir: path.join(workspace, 'darwin'),
+ relativeExecutable: path.join('SubMiner.app', 'Contents', 'Resources', 'bun', 'bun'),
+ member: 'bun-darwin-aarch64/bun',
+ },
+ {
+ platform: 'win32',
+ arch: 'x64',
+ appOutDir: path.join(workspace, 'windows'),
+ relativeExecutable: path.join('resources', 'bun', 'bun.exe'),
+ member: 'bun-windows-x64-baseline/bun.exe',
+ },
+ ] as const;
+
+ try {
+ for (const targetCase of cases) {
+ let extractedMember = '';
+ const result = await stageBunRuntime(targetCase, {
+ configLoader: async () => runtimeConfig(),
+ archiveLoader: async () => path.join(workspace, 'fixture.zip'),
+ extractor: async (_archivePath: string, member: string, outputPath: string) => {
+ extractedMember = member;
+ await fs.mkdir(path.dirname(outputPath), { recursive: true });
+ await fs.writeFile(outputPath, 'bun fixture', { mode: 0o755 });
+ },
+ licenseStager: async (runtimeDirectory: string) => {
+ const licensesDirectory = path.join(runtimeDirectory, 'licenses');
+ await fs.mkdir(licensesDirectory, { recursive: true });
+ await fs.writeFile(path.join(licensesDirectory, 'Bun-LICENSE.md'), 'MIT fixture');
+ return licensesDirectory;
+ },
+ });
+ const expectedExecutable = path.join(targetCase.appOutDir, targetCase.relativeExecutable);
+ assert.equal(result.executablePath, expectedExecutable);
+ assert.equal(extractedMember, targetCase.member);
+ assert.equal((await fs.stat(expectedExecutable)).mode & 0o777, 0o755);
+ assert.equal((await fs.stat(result.metadataPath)).mode & 0o777, 0o644);
+ const metadata = JSON.parse(await fs.readFile(result.metadataPath, 'utf8'));
+ assert.equal(metadata.version, '1.3.5');
+ assert.equal(metadata.bunRevision, '1e86cebd74a5723e818b5c0555276b646bcf0e4c');
+ assert.equal(metadata.artifactSha256, result.artifact.sha256);
+ assert.equal(metadata.target, result.artifact.key);
+ assert.equal(
+ await fs.readFile(
+ path.join(path.dirname(expectedExecutable), 'licenses', 'Bun-LICENSE.md'),
+ 'utf8',
+ ),
+ 'MIT fixture',
+ );
+ }
+ } finally {
+ await fs.rm(workspace, { recursive: true, force: true });
+ }
+});
diff --git a/scripts/update-aur-package.test.ts b/scripts/update-aur-package.test.ts
index 70a46799..c1b8187a 100644
--- a/scripts/update-aur-package.test.ts
+++ b/scripts/update-aur-package.test.ts
@@ -70,6 +70,7 @@ test('update-aur-package updates PKGBUILD and .SRCINFO without makepkg', () => {
);
assert.match(pkgbuild, /^pkgver=0\.6\.3$/m);
+ assert.doesNotMatch(pkgbuild, /^\s*'bun'$/m);
assert.match(
pkgbuild,
/^\s*"subminer-\$\{pkgver\}::https:\/\/github\.com\/ksyasuda\/SubMiner\/releases\/download\/v\$\{pkgver\}\/subminer"$/m,
@@ -84,6 +85,7 @@ test('update-aur-package updates PKGBUILD and .SRCINFO without makepkg', () => {
);
assert.match(pkgbuild, /assets\/thumbnailers\/subminer-ffmpegthumbnailer\.thumbnailer/);
assert.match(srcinfo, /^\tpkgver = 0\.6\.3$/m);
+ assert.doesNotMatch(srcinfo, /^\tdepends = bun$/m);
assert.match(srcinfo, /^\tprovides = subminer=0\.6\.3$/m);
assert.match(
srcinfo,
diff --git a/scripts/verify-generated-launcher.sh b/scripts/verify-generated-launcher.sh
index aab1494d..4ce7c1be 100755
--- a/scripts/verify-generated-launcher.sh
+++ b/scripts/verify-generated-launcher.sh
@@ -2,23 +2,38 @@
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
-LAUNCHER_OUT="$REPO_ROOT/dist/launcher/subminer"
+LAUNCHER_DIR="$REPO_ROOT/dist/launcher"
+LAUNCHER_OUT="$LAUNCHER_DIR/subminer"
+EXPECTED_ARTIFACTS=(prepare.cjs subminer subminer.cmd subminer.js version)
if [[ ! -f "$REPO_ROOT/launcher/main.ts" ]]; then
echo "[FAIL] launcher source missing: launcher/main.ts"
exit 1
fi
-if ! grep -Fn -- "--outfile=\"\$(LAUNCHER_OUT)\"" "$REPO_ROOT/Makefile" >/dev/null; then
- echo "[FAIL] Makefile build-launcher target is not writing to dist/launcher/subminer"
+if ! grep -F -- "bun run build:launcher" "$REPO_ROOT/Makefile" >/dev/null; then
+ echo "[FAIL] Makefile build-launcher target does not call the canonical package script"
exit 1
fi
-if [[ ! -f "$LAUNCHER_OUT" ]]; then
- echo "[FAIL] generated launcher not found at dist/launcher/subminer"
- echo " run: make build-launcher"
- exit 1
-fi
+for artifact in "${EXPECTED_ARTIFACTS[@]}"; do
+ if [[ ! -f "$LAUNCHER_DIR/$artifact" ]]; then
+ echo "[FAIL] generated launcher artifact missing: dist/launcher/$artifact"
+ echo " run: make build-launcher"
+ exit 1
+ fi
+done
+
+for artifact_path in "$LAUNCHER_DIR"/*; do
+ artifact="${artifact_path##*/}"
+ case "$artifact" in
+ prepare.cjs | subminer | subminer.cmd | subminer.js | version) ;;
+ *)
+ echo "[FAIL] dist/launcher contains an unexpected runtime artifact: $artifact"
+ exit 1
+ ;;
+ esac
+done
if [[ ! -x "$LAUNCHER_OUT" ]]; then
echo "[FAIL] generated launcher is not executable: dist/launcher/subminer"
@@ -32,11 +47,11 @@ if [[ -f "$REPO_ROOT/subminer" ]]; then
exit 1
fi
-if git -C "$REPO_ROOT" ls-files --error-unmatch dist/launcher/subminer >/dev/null 2>&1; then
- echo "[FAIL] dist/launcher/subminer is tracked by git; generated artifacts must remain untracked"
+if git -C "$REPO_ROOT" ls-files --error-unmatch dist/launcher >/dev/null 2>&1; then
+ echo "[FAIL] dist/launcher contains tracked files; generated artifacts must remain untracked"
exit 1
fi
echo "[OK] launcher workflow verified"
echo " source: launcher/*.ts"
-echo " generated artifact: dist/launcher/subminer"
+echo " generated artifacts: ${EXPECTED_ARTIFACTS[*]}"
diff --git a/src/animeui/style.css b/src/animeui/style.css
index d0917a42..16bf6ceb 100644
--- a/src/animeui/style.css
+++ b/src/animeui/style.css
@@ -1,6 +1,6 @@
@font-face {
font-family: 'M PLUS 1';
- src: url('./fonts/MPLUS1[wght].ttf') format('truetype');
+ src: url('../fonts/MPLUS1[wght].ttf') format('truetype');
font-weight: 100 900;
font-display: swap;
}
diff --git a/src/anki-integration.test.ts b/src/anki-integration.test.ts
index 1be74119..ed63f04a 100644
--- a/src/anki-integration.test.ts
+++ b/src/anki-integration.test.ts
@@ -1263,6 +1263,41 @@ test('AnkiIntegration dismisses persistent overlay update progress when no termi
assert.deepEqual(dismissedIds, ['anki-update-progress']);
});
+test('AnkiIntegration dismisses overlay update progress after notifications switch to OSD', () => {
+ const behavior: NonNullable = {
+ notificationType: 'overlay',
+ };
+ const dismissedIds: string[] = [];
+ const integration = new AnkiIntegration(
+ { behavior },
+ {} as never,
+ {} as never,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ {},
+ undefined,
+ () => {},
+ undefined,
+ undefined,
+ undefined,
+ (id) => {
+ dismissedIds.push(id);
+ },
+ );
+ const updateNotifications = integration as unknown as {
+ beginUpdateProgress: (message: string) => void;
+ endUpdateProgress: () => void;
+ };
+
+ updateNotifications.beginUpdateProgress('Updating card');
+ behavior.notificationType = 'osd';
+ updateNotifications.endUpdateProgress();
+
+ assert.deepEqual(dismissedIds, ['anki-update-progress']);
+});
+
test('AnkiIntegration keeps overlay notification image when temp icon write fails', async () => {
const desktopNotifications: Array<{ title: string; body?: string; icon?: string }> = [];
const overlayNotifications: TestOverlayNotificationPayload[] = [];
diff --git a/src/anki-integration.ts b/src/anki-integration.ts
index c8db8773..059fcded 100644
--- a/src/anki-integration.ts
+++ b/src/anki-integration.ts
@@ -28,6 +28,8 @@ import {
KikuMergePreviewResponse,
NotificationOptions,
type WordCardKind,
+ type MediaTimingReviewDecision,
+ type MediaTimingReviewRequest,
} from './types/anki';
import { AiConfig } from './types/integrations';
import type { KnownWordMaturityTier } from './types/subtitle';
@@ -240,6 +242,9 @@ export class AnkiIntegration {
private recordCardsMinedCallback: ((count: number, noteIds?: number[]) => void) | null = null;
private knownWordCacheUpdatedCallback: (() => void) | null = null;
private consumeSubtitleMiningContextCallback: (() => SubtitleMiningContext | null) | null = null;
+ private mediaTimingReviewCallback:
+ | ((request: MediaTimingReviewRequest) => Promise)
+ | null = null;
private noteIdRedirects = new Map();
private trackedDuplicateNoteIds = new Map();
private getCachedMediaPath: MediaGenerationInputResolverOptions['getCachedMediaPath'] | null =
@@ -511,6 +516,7 @@ export class AnkiIntegration {
findNotes: async (query, options) =>
(await this.client.findNotes(query, options)) as number[],
retrieveMediaFile: (filename) => this.client.retrieveMediaFile(filename),
+ deleteNotes: (noteIds) => this.client.deleteNotes(noteIds),
},
mediaGenerator: {
generateAudio: (
@@ -568,6 +574,7 @@ export class AnkiIntegration {
getEffectiveSentenceCardConfig: () => this.getEffectiveSentenceCardConfig(),
getFallbackDurationSeconds: () => this.getFallbackDurationSeconds(),
appendKnownWordsFromNoteInfo: (noteInfo) => this.appendKnownWordsFromNoteInfo(noteInfo),
+ removeKnownWordNote: (noteId) => this.removeKnownWordNote(noteId),
isUpdateInProgress: () => this.updateInProgress,
setUpdateInProgress: (value) => {
this.updateInProgress = value;
@@ -583,6 +590,7 @@ export class AnkiIntegration {
recordCardsMinedCallback: (count, noteIds) => {
this.recordCardsMinedSafely(count, noteIds, 'card creation');
},
+ reviewMediaTiming: (request) => this.reviewMediaTiming(request),
});
}
@@ -639,12 +647,14 @@ export class AnkiIntegration {
notesInfo: async (noteIds) => (await this.client.notesInfo(noteIds)) as unknown,
updateNoteFields: (noteId, fields) => this.client.updateNoteFields(noteId, fields),
storeMediaFile: (filename, data) => this.client.storeMediaFile(filename, data),
+ deleteNotes: (noteIds) => this.client.deleteNotes(noteIds),
},
getConfig: () => this.config,
getCurrentSubtitleText: () => this.mpvClient.currentSubText,
getCurrentSubtitleStart: () => this.mpvClient.currentSubStart,
getEffectiveSentenceCardConfig: () => this.getEffectiveSentenceCardConfig(),
appendKnownWordsFromNoteInfo: (noteInfo) => this.appendKnownWordsFromNoteInfo(noteInfo),
+ removeKnownWordNote: (noteId) => this.removeKnownWordNote(noteId),
extractFields: (fields) => this.extractFields(fields),
findDuplicateNote: (expression, excludeNoteId, noteInfo) =>
this.findDuplicateNote(expression, excludeNoteId, noteInfo),
@@ -680,6 +690,7 @@ export class AnkiIntegration {
logWarn: (...args) => log.warn(args[0] as string, ...args.slice(1)),
logInfo: (...args) => log.info(args[0] as string, ...args.slice(1)),
logError: (...args) => log.error(args[0] as string, ...args.slice(1)),
+ reviewMediaTiming: (request) => this.reviewMediaTiming(request),
});
}
@@ -799,6 +810,12 @@ export class AnkiIntegration {
}
}
+ private removeKnownWordNote(noteId: number): void {
+ if (this.knownWordCache.removeNote(noteId)) {
+ this.notifyKnownWordCacheUpdated();
+ }
+ }
+
private notifyKnownWordCacheUpdated(): void {
if (!this.knownWordCacheUpdatedCallback) {
return;
@@ -1076,7 +1093,7 @@ export class AnkiIntegration {
videoPath,
startTime,
endTime,
- this.config.media?.audioPadding,
+ context?.mediaPaddingSeconds ?? this.config.media?.audioPadding,
resolveAudioStreamIndexForMediaGeneration(videoPath, this.mpvClient.currentAudioStreamIndex),
this.config.media?.normalizeAudio !== false,
await this.getMpvVolumeScale(),
@@ -1109,7 +1126,7 @@ export class AnkiIntegration {
videoPath,
mediaRange.startTime,
mediaRange.endTime,
- this.config.media?.audioPadding,
+ context?.mediaPaddingSeconds ?? this.config.media?.audioPadding,
{
fps: this.config.media?.animatedFps,
maxWidth: this.config.media?.animatedMaxWidth,
@@ -1257,11 +1274,11 @@ export class AnkiIntegration {
}
private endUpdateProgress(): void {
+ if (this.overlayUpdateProgressActive) {
+ this.overlayUpdateProgressActive = false;
+ this.overlayNotificationDismissCallback?.('anki-update-progress');
+ }
if (!this.shouldUseOsdNotifications()) {
- if (this.overlayUpdateProgressActive) {
- this.overlayUpdateProgressActive = false;
- this.overlayNotificationDismissCallback?.('anki-update-progress');
- }
return;
}
endUpdateProgress(this.uiFeedbackState, (timer) => {
@@ -1761,6 +1778,25 @@ export class AnkiIntegration {
this.consumeSubtitleMiningContextCallback = callback;
}
+ setMediaTimingReviewCallback(
+ callback: ((request: MediaTimingReviewRequest) => Promise) | null,
+ ): void {
+ this.mediaTimingReviewCallback = callback;
+ }
+
+ private async reviewMediaTiming(
+ request: Omit,
+ ): Promise {
+ if (this.config.media?.reviewTiming !== true || !this.mediaTimingReviewCallback) {
+ return { action: 'use-original' };
+ }
+ return await this.mediaTimingReviewCallback({
+ ...request,
+ audioPadding: Math.max(0, this.config.media.audioPadding ?? 0),
+ maxMediaDuration: Math.max(0, this.config.media.maxMediaDuration ?? 30),
+ });
+ }
+
resolveCurrentNoteId(noteId: number): number {
let resolved = noteId;
const seen = new Set();
diff --git a/src/anki-integration/card-creation-manual-update.test.ts b/src/anki-integration/card-creation-manual-update.test.ts
index 0c1c5fd4..2a8dcb2e 100644
--- a/src/anki-integration/card-creation-manual-update.test.ts
+++ b/src/anki-integration/card-creation-manual-update.test.ts
@@ -85,6 +85,7 @@ function createManualUpdateService(overrides: Partial = {}): {
},
findNotes: async () => [42],
retrieveMediaFile: async () => '',
+ deleteNotes: async () => undefined,
},
mediaGenerator: {
generateAudio: async () => Buffer.from('audio'),
@@ -128,6 +129,7 @@ function createManualUpdateService(overrides: Partial = {}): {
}),
getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined,
+ removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined,
@@ -200,6 +202,7 @@ test('manual clipboard word-card update uses configured fields with Lapis and Ki
storeMediaFile: async () => undefined,
findNotes: async () => [42],
retrieveMediaFile: async () => '',
+ deleteNotes: async () => undefined,
},
getEffectiveSentenceCardConfig: () => ({
model: 'Sentence',
@@ -266,6 +269,7 @@ test('audio-card action keeps Lapis and Kiku sentence fields', async () => {
storeMediaFile: async () => undefined,
findNotes: async () => [42],
retrieveMediaFile: async () => '',
+ deleteNotes: async () => undefined,
},
getEffectiveSentenceCardConfig: () => ({
model: 'Sentence',
@@ -328,6 +332,7 @@ test('manual clipboard subtitle update marks Kiku word cards as word-and-sentenc
storeMediaFile: async () => undefined,
findNotes: async () => [42],
retrieveMediaFile: async () => '',
+ deleteNotes: async () => undefined,
},
getEffectiveSentenceCardConfig: () => ({
model: 'Sentence',
@@ -374,6 +379,7 @@ test('manual clipboard subtitle update uses configured audio when SentenceAudio
},
findNotes: async () => [42],
retrieveMediaFile: async () => '',
+ deleteNotes: async () => undefined,
},
});
@@ -462,6 +468,7 @@ test('manual clipboard subtitle update uses resolved mpv stream URLs for remote
},
findNotes: async () => [42],
retrieveMediaFile: async () => '',
+ deleteNotes: async () => undefined,
},
mediaGenerator: {
generateAudio: async (path) => {
@@ -510,3 +517,98 @@ test('createSentenceCard relies on Anki progress notification without standalone
assert.deepEqual(progressMessages, ['Creating sentence card']);
assert.deepEqual(statusMessages, []);
});
+
+test('discarding an audio-card timing review deletes the note before evicting its cache entry', async () => {
+ const events: string[] = [];
+ const statusMessages: string[] = [];
+ const { service } = createManualUpdateService({
+ getMpvClient: () =>
+ ({
+ currentVideoPath: '/video.mp4',
+ currentSubText: '字幕',
+ currentSubStart: 4,
+ currentSubEnd: 6,
+ currentTimePos: 5,
+ }) as never,
+ client: {
+ addNote: async () => 0,
+ addTags: async () => undefined,
+ notesInfo: async () => [
+ {
+ noteId: 42,
+ fields: { Expression: { value: '単語' } },
+ },
+ ],
+ updateNoteFields: async () => undefined,
+ storeMediaFile: async () => undefined,
+ findNotes: async () => [42],
+ retrieveMediaFile: async () => '',
+ deleteNotes: async (noteIds) => {
+ events.push(`delete:${noteIds.join(',')}`);
+ },
+ },
+ reviewMediaTiming: async () => ({ action: 'discard' }),
+ removeKnownWordNote: (noteId) => {
+ events.push(`cache:${noteId}`);
+ },
+ showStatusNotification: (message) => {
+ statusMessages.push(message);
+ },
+ });
+
+ await service.markLastCardAsAudioCard();
+
+ assert.deepEqual(events, ['delete:42', 'cache:42']);
+ assert.deepEqual(statusMessages, ['Card deleted.']);
+});
+
+test('keeping an audio card without media skips generation and preserves the note', async () => {
+ let generatedAudio = false;
+ let deleted = false;
+ const updates: Array<{ noteId: number; fields: Record }> = [];
+ const { service, storedMedia } = createManualUpdateService({
+ getMpvClient: () =>
+ ({
+ currentVideoPath: '/video.mp4',
+ currentSubText: '字幕',
+ currentSubStart: 4,
+ currentSubEnd: 6,
+ currentTimePos: 5,
+ }) as never,
+ client: {
+ addNote: async () => 0,
+ addTags: async () => undefined,
+ notesInfo: async () => [
+ {
+ noteId: 42,
+ fields: { Expression: { value: '単語' }, Sentence: { value: '' } },
+ },
+ ],
+ updateNoteFields: async (noteId, fields) => {
+ updates.push({ noteId, fields });
+ },
+ storeMediaFile: async () => undefined,
+ findNotes: async () => [42],
+ retrieveMediaFile: async () => '',
+ deleteNotes: async () => {
+ deleted = true;
+ },
+ },
+ mediaGenerator: {
+ generateAudio: async () => {
+ generatedAudio = true;
+ return Buffer.from('audio');
+ },
+ generateScreenshot: async () => null,
+ generateAnimatedImage: async () => null,
+ },
+ reviewMediaTiming: async () => ({ action: 'skip-media' }),
+ });
+
+ await service.markLastCardAsAudioCard();
+
+ assert.equal(generatedAudio, false);
+ assert.equal(deleted, false);
+ assert.deepEqual(storedMedia, []);
+ assert.deepEqual(updates, [{ noteId: 42, fields: { Sentence: '字幕' } }]);
+});
diff --git a/src/anki-integration/card-creation-sentence-media.test.ts b/src/anki-integration/card-creation-sentence-media.test.ts
index b8c4604c..baadfd92 100644
--- a/src/anki-integration/card-creation-sentence-media.test.ts
+++ b/src/anki-integration/card-creation-sentence-media.test.ts
@@ -12,6 +12,7 @@ test('sentence card writes generated audio only to sentence audio field', async
const storedMedia: string[] = [];
const requestedProperties: string[] = [];
const audioVolumeScales: Array = [];
+ const audioRanges: Array<{ start: number; end: number; padding: number | undefined }> = [];
const deps: CardCreationDeps = {
getConfig: () =>
@@ -73,17 +74,19 @@ test('sentence card writes generated audio only to sentence audio field', async
},
findNotes: async () => [],
retrieveMediaFile: async () => '',
+ deleteNotes: async () => undefined,
},
mediaGenerator: {
generateAudio: async (
_path,
- _startTime,
- _endTime,
- _audioPadding,
+ startTime,
+ endTime,
+ audioPadding,
_audioStreamIndex,
_normalizeAudio,
volumeScale,
) => {
+ audioRanges.push({ start: startTime, end: endTime, padding: audioPadding });
audioVolumeScales.push(volumeScale);
return Buffer.from('audio');
},
@@ -121,17 +124,15 @@ test('sentence card writes generated audio only to sentence audio field', async
}),
getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined,
+ removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined,
+ reviewMediaTiming: async () => ({ action: 'confirm', startTime: 11.4, endTime: 14.2 }),
};
- const created = await new CardCreationService(deps).createSentenceCard(
- '字幕',
- 12,
- 14,
- 'Subtitle',
- );
+ const service = new CardCreationService(deps);
+ const created = await service.createSentenceCard('字幕', 12, 14, 'Subtitle');
assert.equal(created, true);
assert.deepEqual(addedFields[0], {
@@ -143,7 +144,19 @@ test('sentence card writes generated audio only to sentence audio field', async
assert.equal(storedMedia.length, 1);
assert.deepEqual(requestedProperties, ['volume']);
assert.deepEqual(audioVolumeScales, [0.4 ** 3]);
+ assert.deepEqual(audioRanges, [{ start: 11.4, end: 14.2, padding: 0 }]);
const mediaUpdate = updatedFields.find((fields) => 'SentenceAudio' in fields);
assert.equal(mediaUpdate?.SentenceAudio, `[sound:${storedMedia[0]}]`);
assert.equal('ExpressionAudio' in mediaUpdate!, false);
+
+ deps.reviewMediaTiming = async () => ({ action: 'discard' });
+ assert.equal(await service.createSentenceCard('作らない', 20, 22), false);
+ assert.equal(addedFields.length, 1);
+
+ deps.reviewMediaTiming = async () => ({ action: 'skip-media' });
+ assert.equal(await service.createSentenceCard('メディアなし', 30, 32), true);
+ assert.equal(addedFields.length, 2);
+ assert.equal(storedMedia.length, 1);
+ assert.deepEqual(audioRanges, [{ start: 11.4, end: 14.2, padding: 0 }]);
+ assert.deepEqual(requestedProperties, ['volume']);
});
diff --git a/src/anki-integration/card-creation.test.ts b/src/anki-integration/card-creation.test.ts
index 67857d03..b1a93438 100644
--- a/src/anki-integration/card-creation.test.ts
+++ b/src/anki-integration/card-creation.test.ts
@@ -42,6 +42,7 @@ test('CardCreationService counts locally created sentence cards', async () => {
storeMediaFile: async () => undefined,
findNotes: async () => [],
retrieveMediaFile: async () => '',
+ deleteNotes: async () => undefined,
},
mediaGenerator: {
generateAudio: async () => null,
@@ -73,6 +74,7 @@ test('CardCreationService counts locally created sentence cards', async () => {
}),
getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined,
+ removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined,
@@ -138,6 +140,7 @@ test('CardCreationService keeps updating after trackLastAddedNoteId throws', asy
storeMediaFile: async () => undefined,
findNotes: async () => [],
retrieveMediaFile: async () => '',
+ deleteNotes: async () => undefined,
},
mediaGenerator: {
generateAudio: async () => null,
@@ -171,6 +174,7 @@ test('CardCreationService keeps updating after trackLastAddedNoteId throws', asy
}),
getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined,
+ removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => {
@@ -236,6 +240,7 @@ test('CardCreationService keeps updating after recordCardsMinedCallback throws',
storeMediaFile: async () => undefined,
findNotes: async () => [],
retrieveMediaFile: async () => '',
+ deleteNotes: async () => undefined,
},
mediaGenerator: {
generateAudio: async () => null,
@@ -269,6 +274,7 @@ test('CardCreationService keeps updating after recordCardsMinedCallback throws',
}),
getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined,
+ removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined,
recordCardsMinedCallback: () => {
@@ -345,6 +351,7 @@ test('CardCreationService uses stream-open-filename for remote media generation'
storeMediaFile: async () => undefined,
findNotes: async () => [],
retrieveMediaFile: async () => '',
+ deleteNotes: async () => undefined,
},
mediaGenerator: {
generateAudio: async (path) => {
@@ -388,6 +395,7 @@ test('CardCreationService uses stream-open-filename for remote media generation'
}),
getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined,
+ removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined,
@@ -450,6 +458,7 @@ test('CardCreationService does not use mpv stream indexes for ready cached YouTu
storeMediaFile: async () => undefined,
findNotes: async () => [],
retrieveMediaFile: async () => '',
+ deleteNotes: async () => undefined,
},
mediaGenerator: {
generateAudio: async (path, _startTime, _endTime, _padding, audioStreamIndex) => {
@@ -490,6 +499,7 @@ test('CardCreationService does not use mpv stream indexes for ready cached YouTu
}),
getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined,
+ removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined,
@@ -585,6 +595,7 @@ test('CardCreationService queues YouTube media when required cache is not ready'
storeMediaFile: async () => undefined,
findNotes: async () => [],
retrieveMediaFile: async () => '',
+ deleteNotes: async () => undefined,
},
mediaGenerator: {
generateAudio: async () => {
@@ -628,6 +639,7 @@ test('CardCreationService queues YouTube media when required cache is not ready'
}),
getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined,
+ removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined,
@@ -695,6 +707,7 @@ test('CardCreationService tracks pre-add duplicate note ids for kiku sentence ca
storeMediaFile: async () => undefined,
findNotes: async () => [],
retrieveMediaFile: async () => '',
+ deleteNotes: async () => undefined,
},
mediaGenerator: {
generateAudio: async () => null,
@@ -726,6 +739,7 @@ test('CardCreationService tracks pre-add duplicate note ids for kiku sentence ca
}),
getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined,
+ removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined,
@@ -783,6 +797,7 @@ test('CardCreationService does not track duplicate ids when pre-add lookup retur
storeMediaFile: async () => undefined,
findNotes: async () => [],
retrieveMediaFile: async () => '',
+ deleteNotes: async () => undefined,
},
mediaGenerator: {
generateAudio: async () => null,
@@ -814,6 +829,7 @@ test('CardCreationService does not track duplicate ids when pre-add lookup retur
}),
getFallbackDurationSeconds: () => 10,
appendKnownWordsFromNoteInfo: () => undefined,
+ removeKnownWordNote: () => undefined,
isUpdateInProgress: () => false,
setUpdateInProgress: () => undefined,
trackLastAddedNoteId: () => undefined,
diff --git a/src/anki-integration/card-creation.ts b/src/anki-integration/card-creation.ts
index 50eb8e58..e15d1fcc 100644
--- a/src/anki-integration/card-creation.ts
+++ b/src/anki-integration/card-creation.ts
@@ -3,7 +3,13 @@ import {
getConfiguredWordFieldName,
getPreferredWordValueFromExtractedFields,
} from '../anki-field-config';
-import { AnkiConnectConfig, type CardKind, type WordCardKind } from '../types/anki';
+import {
+ AnkiConnectConfig,
+ type CardKind,
+ type MediaTimingReviewDecision,
+ type MediaTimingReviewRequest,
+ type WordCardKind,
+} from '../types/anki';
import { createLogger } from '../logger';
import type { MediaInput } from '../media-input';
import { SubtitleTimingTracker } from '../subtitle-timing-tracker';
@@ -55,6 +61,7 @@ interface CardCreationClient {
storeMediaFile(filename: string, data: Buffer): Promise;
findNotes(query: string, options?: { maxRetries?: number }): Promise;
retrieveMediaFile(filename: string): Promise;
+ deleteNotes(noteIds: number[]): Promise;
}
interface CardCreationMediaGenerator {
@@ -137,12 +144,16 @@ interface CardCreationDeps {
};
getFallbackDurationSeconds: () => number;
appendKnownWordsFromNoteInfo: (noteInfo: CardCreationNoteInfo) => void;
+ removeKnownWordNote: (noteId: number) => void;
isUpdateInProgress: () => boolean;
setUpdateInProgress: (value: boolean) => void;
trackLastAddedNoteId?: (noteId: number) => void;
trackLastAddedDuplicateNoteIds?: (noteId: number, duplicateNoteIds: number[]) => void;
findDuplicateNoteIds?: (expression: string, noteInfo: CardCreationNoteInfo) => Promise;
recordCardsMinedCallback?: (count: number, noteIds?: number[]) => void;
+ reviewMediaTiming?: (
+ request: Omit,
+ ) => Promise;
}
export class CardCreationService {
@@ -456,6 +467,30 @@ export class CardCreationService {
this.deps.getConfig(),
);
+ const timingDecision = this.deps.reviewMediaTiming
+ ? await this.deps.reviewMediaTiming({
+ kind: 'audio',
+ text: mpvClient.currentSubText,
+ startTime,
+ endTime,
+ noteId,
+ })
+ : ({ action: 'use-original' } as const);
+ if (timingDecision.action === 'discard') {
+ await this.deps.client.deleteNotes([noteId]);
+ this.deps.removeKnownWordNote(noteId);
+ this.deps.showStatusNotification('Card deleted.');
+ return;
+ }
+ const skipMedia = timingDecision.action === 'skip-media';
+ const exactReviewedRange = timingDecision.action === 'confirm';
+ let sentenceText = mpvClient.currentSubText;
+ if (timingDecision.action === 'confirm') {
+ startTime = timingDecision.startTime;
+ endTime = timingDecision.endTime;
+ sentenceText = timingDecision.text?.trim() || sentenceText;
+ }
+
const updatedFields: Record = {};
const errors: string[] = [];
let miscInfoFilename: string | null = null;
@@ -465,30 +500,33 @@ export class CardCreationService {
const sentenceCardConfig = this.deps.getEffectiveSentenceCardConfig();
const sentenceField = sentenceCardConfig.sentenceField;
if (sentenceField) {
- const processedSentence = this.deps.processSentence(mpvClient.currentSubText, fields);
+ const processedSentence = this.deps.processSentence(sentenceText, fields);
updatedFields[sentenceField] = processedSentence;
}
const audioFieldName = sentenceCardConfig.audioField;
- try {
- const audioFilename = this.generateAudioFilename();
- const audioBuffer = await this.mediaGenerateAudio(
- mpvClient.currentVideoPath,
- startTime,
- endTime,
- );
+ if (!skipMedia) {
+ try {
+ const audioFilename = this.generateAudioFilename();
+ const audioBuffer = await this.mediaGenerateAudio(
+ mpvClient.currentVideoPath,
+ startTime,
+ endTime,
+ exactReviewedRange ? 0 : undefined,
+ );
- if (audioBuffer) {
- await this.deps.client.storeMediaFile(audioFilename, audioBuffer);
- updatedFields[audioFieldName] = `[sound:${audioFilename}]`;
- miscInfoFilename = audioFilename;
+ if (audioBuffer) {
+ await this.deps.client.storeMediaFile(audioFilename, audioBuffer);
+ updatedFields[audioFieldName] = `[sound:${audioFilename}]`;
+ miscInfoFilename = audioFilename;
+ }
+ } catch (error) {
+ log.error('Failed to generate audio for audio card:', (error as Error).message);
+ errors.push('audio');
}
- } catch (error) {
- log.error('Failed to generate audio for audio card:', (error as Error).message);
- errors.push('audio');
}
- if (shouldGenerateImage(this.deps.getConfig())) {
+ if (!skipMedia && shouldGenerateImage(this.deps.getConfig())) {
try {
const animatedLeadInSeconds = await this.deps.getAnimatedImageLeadInSeconds(noteInfo);
const imageFilename = this.generateImageFilename();
@@ -497,6 +535,7 @@ export class CardCreationService {
startTime,
endTime,
animatedLeadInSeconds,
+ exactReviewedRange,
);
const imageField = this.deps.getConfig().fields?.image;
@@ -569,9 +608,29 @@ export class CardCreationService {
try {
return await this.deps.withUpdateProgress('Creating sentence card', async () => {
+ const timingDecision = this.deps.reviewMediaTiming
+ ? await this.deps.reviewMediaTiming({
+ kind: 'sentence',
+ text: sentence,
+ startTime,
+ endTime,
+ })
+ : ({ action: 'use-original' } as const);
+ if (timingDecision.action === 'discard') {
+ this.deps.showStatusNotification('Card creation cancelled.');
+ return false;
+ }
+ const skipMedia = timingDecision.action === 'skip-media';
+ const exactReviewedRange = timingDecision.action === 'confirm';
+ if (timingDecision.action === 'confirm') {
+ startTime = timingDecision.startTime;
+ endTime = timingDecision.endTime;
+ sentence = timingDecision.text?.trim() || sentence;
+ }
+
const config = this.deps.getConfig();
- const generateAudio = shouldGenerateAudio(config);
- const generateImage = shouldGenerateImage(config);
+ const generateAudio = !skipMedia && shouldGenerateAudio(config);
+ const generateImage = !skipMedia && shouldGenerateImage(config);
const mediaResolverOptions = this.getMediaResolverOptions();
const videoPath = generateImage
? await resolveMediaGenerationInput(mpvClient, 'video', mediaResolverOptions)
@@ -736,6 +795,7 @@ export class CardCreationService {
generateAudio,
generateImage,
volumeScale,
+ ...(exactReviewedRange ? { mediaPaddingSeconds: 0 } : {}),
});
await this.deps.showNotification(noteId, label, 'media queued');
return true;
@@ -751,7 +811,12 @@ export class CardCreationService {
try {
const audioFilename = this.generateAudioFilename();
const audioBuffer = audioSourcePath
- ? await this.mediaGenerateAudio(audioSourcePath, startTime, endTime)
+ ? await this.mediaGenerateAudio(
+ audioSourcePath,
+ startTime,
+ endTime,
+ exactReviewedRange ? 0 : undefined,
+ )
: null;
if (audioBuffer) {
@@ -769,7 +834,13 @@ export class CardCreationService {
if (generateImage) {
try {
const imageFilename = this.generateImageFilename();
- const imageBuffer = await this.generateImageBuffer(videoPath!, startTime, endTime);
+ const imageBuffer = await this.generateImageBuffer(
+ videoPath!,
+ startTime,
+ endTime,
+ 0,
+ exactReviewedRange,
+ );
const imageField = config.fields?.image;
if (imageBuffer && imageField) {
@@ -821,6 +892,7 @@ export class CardCreationService {
videoPath: MediaInput,
startTime: number,
endTime: number,
+ audioPaddingOverride?: number,
): Promise {
const mpvClient = this.deps.getMpvClient();
if (!mpvClient) {
@@ -831,7 +903,7 @@ export class CardCreationService {
videoPath,
startTime,
endTime,
- this.deps.getConfig().media?.audioPadding,
+ audioPaddingOverride ?? this.deps.getConfig().media?.audioPadding,
resolveAudioStreamIndexForMediaGeneration(
videoPath,
mpvClient.currentAudioStreamIndex ?? undefined,
@@ -849,13 +921,16 @@ export class CardCreationService {
startTime: number,
endTime: number,
animatedLeadInSeconds = 0,
+ exactReviewedRange = false,
): Promise {
const mpvClient = this.deps.getMpvClient();
if (!mpvClient) {
return null;
}
- const timestamp = mpvClient.currentTimePos || 0;
+ const timestamp = exactReviewedRange
+ ? startTime + (endTime - startTime) / 2
+ : mpvClient.currentTimePos || 0;
if (this.deps.getConfig().media?.imageType === 'avif') {
let imageStart = startTime;
@@ -871,7 +946,7 @@ export class CardCreationService {
videoPath,
imageStart,
imageEnd,
- this.deps.getConfig().media?.audioPadding,
+ exactReviewedRange ? 0 : this.deps.getConfig().media?.audioPadding,
{
fps: this.deps.getConfig().media?.animatedFps,
maxWidth: this.deps.getConfig().media?.animatedMaxWidth,
diff --git a/src/anki-integration/known-word-cache.test.ts b/src/anki-integration/known-word-cache.test.ts
index 3d54036b..306fdba8 100644
--- a/src/anki-integration/known-word-cache.test.ts
+++ b/src/anki-integration/known-word-cache.test.ts
@@ -261,6 +261,32 @@ test('KnownWordCacheManager invalidates persisted cache when fields.word changes
}
});
+test('KnownWordCacheManager removes a deleted note from memory and persisted state', () => {
+ const config: AnkiConnectConfig = {
+ fields: { word: 'Word' },
+ knownWords: { highlightEnabled: true },
+ };
+ const { manager, statePath, cleanup } = createKnownWordCacheHarness(config);
+
+ try {
+ manager.appendFromNoteInfo({
+ noteId: 42,
+ fields: { Word: { value: '猫' } },
+ });
+
+ assert.equal(manager.removeNote(42), true);
+ assert.equal(manager.removeNote(42), false);
+ assert.equal(manager.isKnownWord('猫'), false);
+
+ const persisted = JSON.parse(fs.readFileSync(statePath, 'utf-8')) as {
+ notes?: Record;
+ };
+ assert.deepEqual(persisted.notes, {});
+ } finally {
+ cleanup();
+ }
+});
+
test('KnownWordCacheManager refresh incrementally reconciles deleted and edited note words', async () => {
const config: AnkiConnectConfig = {
fields: {
diff --git a/src/anki-integration/known-word-cache.ts b/src/anki-integration/known-word-cache.ts
index f1fc16b7..436d3d71 100644
--- a/src/anki-integration/known-word-cache.ts
+++ b/src/anki-integration/known-word-cache.ts
@@ -350,6 +350,17 @@ export class KnownWordCacheManager {
return true;
}
+ removeNote(noteId: number): boolean {
+ if (!this.noteEntriesById.has(noteId)) {
+ return false;
+ }
+
+ this.removeNoteSnapshot(noteId);
+ this.persistKnownWordCacheState();
+ log.info('Known-word cache removed deleted note', `noteId=${noteId}`);
+ return true;
+ }
+
clearKnownWordCacheState(): void {
this.clearInMemoryState();
this.knownWordsStateKey = this.getKnownWordCacheStateKey();
diff --git a/src/anki-integration/note-update-workflow.test.ts b/src/anki-integration/note-update-workflow.test.ts
index be772765..06694d2c 100644
--- a/src/anki-integration/note-update-workflow.test.ts
+++ b/src/anki-integration/note-update-workflow.test.ts
@@ -44,6 +44,7 @@ function createWorkflowHarness() {
updates.push({ noteId, fields });
},
storeMediaFile: async () => undefined,
+ deleteNotes: async () => undefined,
},
getConfig: () => ({
fields: {
@@ -61,6 +62,7 @@ function createWorkflowHarness() {
fieldGroupingMode: 'disabled' as const,
}),
appendKnownWordsFromNoteInfo: (_noteInfo: NoteUpdateWorkflowNoteInfo) => undefined,
+ removeKnownWordNote: (_noteId: number) => undefined,
extractFields: (fields: Record) => {
const out: Record = {};
for (const [key, value] of Object.entries(fields)) {
@@ -634,3 +636,141 @@ test('NoteUpdateWorkflow queues media updates when YouTube cache is pending', as
assert.equal(queuedUpdates[0]?.context, undefined);
assert.deepEqual(harness.updates, [{ noteId: 42, fields: { Sentence: 'subtitle-text' } }]);
});
+
+test('NoteUpdateWorkflow deletes an existing word card when timing review discards it', async () => {
+ const harness = createWorkflowHarness();
+ const deletedNoteIds: number[][] = [];
+ const removedKnownWordNoteIds: number[] = [];
+ let appendedKnownWords = false;
+ harness.deps.captureSubtitleMediaContext = () => ({
+ source: 'overlay',
+ text: 'subtitle-text',
+ startTime: 4,
+ endTime: 6,
+ });
+ harness.deps.client.deleteNotes = async (noteIds) => {
+ deletedNoteIds.push(noteIds);
+ };
+ harness.deps.appendKnownWordsFromNoteInfo = () => {
+ appendedKnownWords = true;
+ };
+ harness.deps.removeKnownWordNote = (noteId) => {
+ removedKnownWordNoteIds.push(noteId);
+ };
+ harness.deps.reviewMediaTiming = async () => ({ action: 'discard' });
+
+ await harness.workflow.execute(42);
+
+ assert.deepEqual(deletedNoteIds, [[42]]);
+ assert.deepEqual(removedKnownWordNoteIds, [42]);
+ assert.equal(appendedKnownWords, false);
+ assert.deepEqual(harness.updates, []);
+ assert.deepEqual(harness.notifications, []);
+});
+
+test('NoteUpdateWorkflow keeps the word card but skips media after timing review', async () => {
+ const harness = createWorkflowHarness();
+ const mediaCalls: string[] = [];
+ const deletedNoteIds: number[][] = [];
+ const queuedUpdates: unknown[] = [];
+ harness.deps.captureSubtitleMediaContext = () => ({
+ source: 'overlay',
+ text: 'subtitle-text',
+ startTime: 4,
+ endTime: 6,
+ });
+ harness.deps.getConfig = () => ({
+ fields: { sentence: 'Sentence', image: 'Picture' },
+ media: { generateAudio: true, generateImage: true },
+ behavior: {},
+ });
+ harness.deps.reviewMediaTiming = async () => ({ action: 'skip-media' });
+ harness.deps.generateAudio = async () => {
+ mediaCalls.push('audio');
+ return Buffer.from('audio');
+ };
+ harness.deps.generateImage = async () => {
+ mediaCalls.push('image');
+ return Buffer.from('image');
+ };
+ harness.deps.queuePendingYoutubeMediaUpdate = async (update) => {
+ queuedUpdates.push(update);
+ return true;
+ };
+ harness.deps.client.deleteNotes = async (noteIds) => {
+ deletedNoteIds.push(noteIds);
+ };
+
+ await harness.workflow.execute(42);
+
+ assert.deepEqual(mediaCalls, []);
+ assert.deepEqual(queuedUpdates, []);
+ assert.deepEqual(deletedNoteIds, []);
+ assert.deepEqual(harness.updates, [{ noteId: 42, fields: { Sentence: 'subtitle-text' } }]);
+ assert.deepEqual(harness.notifications, [{ noteId: 42, label: 'taberu' }]);
+});
+
+test('NoteUpdateWorkflow uses the combined review sentence for the card and media range', async () => {
+ const harness = createWorkflowHarness();
+ const audioContexts: Array = [];
+ harness.deps.captureSubtitleMediaContext = () => ({
+ source: 'overlay',
+ text: 'current-line',
+ startTime: 4,
+ endTime: 6,
+ });
+ harness.deps.getConfig = () => ({
+ fields: { sentence: 'Sentence' },
+ media: { generateAudio: true, generateImage: false },
+ behavior: {},
+ });
+ harness.deps.reviewMediaTiming = async () => ({
+ action: 'confirm',
+ startTime: 2,
+ endTime: 7,
+ text: 'previous-line current-line next-line',
+ });
+ harness.deps.generateAudio = async (context) => {
+ audioContexts.push(context);
+ return null;
+ };
+
+ await harness.workflow.execute(42);
+
+ assert.deepEqual(harness.updates, [
+ { noteId: 42, fields: { Sentence: 'previous-line current-line next-line' } },
+ ]);
+ assert.equal(audioContexts.length, 1);
+ assert.equal(audioContexts[0]?.text, 'previous-line current-line next-line');
+ assert.equal(audioContexts[0]?.startTime, 2);
+ assert.equal(audioContexts[0]?.endTime, 7);
+ assert.equal(audioContexts[0]?.mediaPaddingSeconds, 0);
+});
+
+test('NoteUpdateWorkflow keeps cache unchanged and reports when deletion fails', async () => {
+ const harness = createWorkflowHarness();
+ const statusMessages: string[] = [];
+ let removedKnownWord = false;
+ harness.deps.captureSubtitleMediaContext = () => ({
+ source: 'overlay',
+ text: 'subtitle-text',
+ startTime: 4,
+ endTime: 6,
+ });
+ harness.deps.client.deleteNotes = async () => {
+ throw new Error('delete failed');
+ };
+ harness.deps.removeKnownWordNote = () => {
+ removedKnownWord = true;
+ };
+ harness.deps.showOsdNotification = (message) => {
+ statusMessages.push(message);
+ };
+ harness.deps.reviewMediaTiming = async () => ({ action: 'discard' });
+
+ await harness.workflow.execute(42);
+
+ assert.equal(removedKnownWord, false);
+ assert.deepEqual(statusMessages, ['Card deletion failed: delete failed']);
+ assert.ok(harness.warnings.length === 0);
+});
diff --git a/src/anki-integration/note-update-workflow.ts b/src/anki-integration/note-update-workflow.ts
index 27f07c16..4cc5e7ee 100644
--- a/src/anki-integration/note-update-workflow.ts
+++ b/src/anki-integration/note-update-workflow.ts
@@ -1,7 +1,12 @@
import { DEFAULT_ANKI_CONNECT_CONFIG } from '../config';
import { getPreferredWordValueFromExtractedFields } from '../anki-field-config';
import type { SubtitleMiningContext } from '../types/subtitle';
-import type { CardKind, WordCardKind } from '../types/anki';
+import type {
+ CardKind,
+ MediaTimingReviewDecision,
+ MediaTimingReviewRequest,
+ WordCardKind,
+} from '../types/anki';
import { resolveWordCardKind } from './note-field-utils';
export interface NoteUpdateWorkflowNoteInfo {
@@ -14,6 +19,7 @@ export interface NoteUpdateWorkflowDeps {
notesInfo(noteIds: number[]): Promise;
updateNoteFields(noteId: number, fields: Record): Promise;
storeMediaFile(filename: string, data: Buffer): Promise;
+ deleteNotes(noteIds: number[]): Promise;
};
getConfig: () => {
fields?: {
@@ -44,6 +50,7 @@ export interface NoteUpdateWorkflowDeps {
wordCardKind?: WordCardKind;
};
appendKnownWordsFromNoteInfo: (noteInfo: NoteUpdateWorkflowNoteInfo) => void;
+ removeKnownWordNote: (noteId: number) => void;
extractFields: (fields: Record) => Record;
findDuplicateNote: (
expression: string,
@@ -102,6 +109,9 @@ export interface NoteUpdateWorkflowDeps {
logWarn: (message: string, ...args: unknown[]) => void;
logInfo: (message: string, ...args: unknown[]) => void;
logError: (message: string, ...args: unknown[]) => void;
+ reviewMediaTiming?: (
+ request: Omit,
+ ) => Promise;
}
function normalizeSubtitleContextText(text: string): string {
@@ -171,7 +181,6 @@ export class NoteUpdateWorkflow {
}
const noteInfo = notesInfo[0]!;
- this.deps.appendKnownWordsFromNoteInfo(noteInfo);
const fields = this.deps.extractFields(noteInfo.fields);
const config = this.deps.getConfig();
@@ -207,11 +216,53 @@ export class NoteUpdateWorkflow {
// Audio and image generation run sequentially and audio extraction can take tens of
// seconds, so resolve the clip range exactly once up front; reading live mpv sub
// timings per generator clips whichever line is on screen when each one starts.
- const mediaTimingContext =
+ let mediaTimingContext =
subtitleMiningContext ?? this.deps.captureSubtitleMediaContext?.() ?? null;
+ let skipMedia = false;
+ let reviewedSentenceText: string | undefined;
const noteLabel = hasExpressionText ? expressionText : noteId;
- const currentSubtitleText = subtitleMiningContext?.text ?? this.deps.getCurrentSubtitleText();
+ if (mediaTimingContext) {
+ const timingDecision = this.deps.reviewMediaTiming
+ ? await this.deps.reviewMediaTiming({
+ kind: 'word',
+ text: mediaTimingContext.text,
+ startTime: mediaTimingContext.startTime,
+ endTime: mediaTimingContext.endTime,
+ noteId,
+ })
+ : ({ action: 'use-original' } as const);
+ if (timingDecision.action === 'discard') {
+ try {
+ await this.deps.client.deleteNotes([noteId]);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ this.deps.logError('Failed to delete discarded card:', message);
+ this.deps.showOsdNotification(`Card deletion failed: ${message}`);
+ return;
+ }
+ this.deps.removeKnownWordNote(noteId);
+ this.deps.showOsdNotification('Card deleted.');
+ return;
+ }
+ if (timingDecision.action === 'confirm') {
+ reviewedSentenceText = timingDecision.text?.trim() || undefined;
+ mediaTimingContext = {
+ ...mediaTimingContext,
+ ...(reviewedSentenceText !== undefined ? { text: reviewedSentenceText } : {}),
+ startTime: timingDecision.startTime,
+ endTime: timingDecision.endTime,
+ mediaPaddingSeconds: 0,
+ };
+ } else if (timingDecision.action === 'skip-media') {
+ skipMedia = true;
+ }
+ }
+
+ this.deps.appendKnownWordsFromNoteInfo(noteInfo);
+
+ const currentSubtitleText =
+ reviewedSentenceText ?? subtitleMiningContext?.text ?? this.deps.getCurrentSubtitleText();
if (sentenceField && currentSubtitleText) {
const processedSentence = this.deps.processSentence(currentSubtitleText, fields);
updatedFields[sentenceField] = processedSentence;
@@ -239,8 +290,8 @@ export class NoteUpdateWorkflow {
}
}
- const generateAudio = config.media?.generateAudio !== false;
- const generateImage = config.media?.generateImage !== false;
+ const generateAudio = !skipMedia && config.media?.generateAudio !== false;
+ const generateImage = !skipMedia && config.media?.generateImage !== false;
const mediaCacheQueued =
(generateAudio || generateImage) && this.deps.queuePendingYoutubeMediaUpdate
? await this.deps.queuePendingYoutubeMediaUpdate({
diff --git a/src/anki-integration/pending-youtube-media-queue.ts b/src/anki-integration/pending-youtube-media-queue.ts
index 0cd09195..1a3e659f 100644
--- a/src/anki-integration/pending-youtube-media-queue.ts
+++ b/src/anki-integration/pending-youtube-media-queue.ts
@@ -147,6 +147,9 @@ export class PendingYoutubeMediaQueue {
generateAudio: shouldGenerateAudio(config),
generateImage: shouldGenerateImage(config),
volumeScale,
+ ...(job.context?.mediaPaddingSeconds !== undefined
+ ? { mediaPaddingSeconds: job.context.mediaPaddingSeconds }
+ : {}),
});
return true;
}
@@ -282,7 +285,7 @@ export class PendingYoutubeMediaQueue {
cachedMediaInput,
job.startTime,
job.endTime,
- config.media?.audioPadding,
+ job.mediaPaddingSeconds ?? config.media?.audioPadding,
undefined,
config.media?.normalizeAudio !== false,
job.volumeScale,
@@ -316,6 +319,7 @@ export class PendingYoutubeMediaQueue {
job.startTime,
job.endTime,
animatedLeadInSeconds,
+ job.mediaPaddingSeconds,
);
if (imageBuffer) {
await this.deps.client.storeMediaFile(imageFilename, imageBuffer);
@@ -376,6 +380,7 @@ export class PendingYoutubeMediaQueue {
startTime: number,
endTime: number,
animatedLeadInSeconds = 0,
+ mediaPaddingSeconds?: number,
): Promise {
const config = this.deps.getConfig();
if (config.media?.imageType === 'avif') {
@@ -383,7 +388,7 @@ export class PendingYoutubeMediaQueue {
videoPath,
startTime,
endTime,
- config.media?.audioPadding,
+ mediaPaddingSeconds ?? config.media?.audioPadding,
{
fps: config.media?.animatedFps,
maxWidth: config.media?.animatedMaxWidth,
diff --git a/src/anki-integration/pending-youtube-media.ts b/src/anki-integration/pending-youtube-media.ts
index 52d65af8..4e0abfb0 100644
--- a/src/anki-integration/pending-youtube-media.ts
+++ b/src/anki-integration/pending-youtube-media.ts
@@ -10,6 +10,7 @@ export interface PendingYoutubeMediaUpdate {
generateAudio: boolean;
generateImage: boolean;
volumeScale?: number;
+ mediaPaddingSeconds?: number;
}
function trimToNonEmptyString(value: unknown): string | null {
diff --git a/src/config/config.test.ts b/src/config/config.test.ts
index c0973d8e..ad1723b0 100644
--- a/src/config/config.test.ts
+++ b/src/config/config.test.ts
@@ -2182,6 +2182,7 @@ test('runtime options registry is centralized', () => {
const ids = RUNTIME_OPTION_REGISTRY.map((entry) => entry.id);
assert.deepEqual(ids, [
'anki.autoUpdateNewCards',
+ 'anki.mediaReviewTiming',
'subtitle.annotation.knownWords.highlightEnabled',
'subtitle.annotation.knownWords.maturityEnabled',
'subtitle.annotation.nPlusOne',
diff --git a/src/config/definitions.ts b/src/config/definitions.ts
index 4aa85b7f..ab3d46e3 100644
--- a/src/config/definitions.ts
+++ b/src/config/definitions.ts
@@ -1,4 +1,5 @@
import { RawConfig, ResolvedConfig } from '../types/config';
+import { DEFAULT_SUBTITLE_GENERATION_CONFIG } from '../shared/subtitle-generation';
import { CORE_DEFAULT_CONFIG } from './definitions/defaults-core';
import { IMMERSION_DEFAULT_CONFIG } from './definitions/defaults-immersion';
import { INTEGRATIONS_DEFAULT_CONFIG } from './definitions/defaults-integrations';
@@ -55,6 +56,7 @@ const { immersionTracking } = IMMERSION_DEFAULT_CONFIG;
const { stats } = STATS_DEFAULT_CONFIG;
export const DEFAULT_CONFIG: ResolvedConfig = {
+ subtitleGeneration: { ...DEFAULT_SUBTITLE_GENERATION_CONFIG },
subtitlePosition,
keybindings,
websocket,
diff --git a/src/config/definitions/defaults-core.ts b/src/config/definitions/defaults-core.ts
index 7d61e884..2c2d8c2b 100644
--- a/src/config/definitions/defaults-core.ts
+++ b/src/config/definitions/defaults-core.ts
@@ -99,6 +99,7 @@ export const CORE_DEFAULT_CONFIG: Pick<
openRuntimeOptions: 'CommandOrControl+Shift+O',
openJimaku: 'Ctrl+Shift+J',
openTsukihime: 'Ctrl+Shift+T',
+ openSubtitleGeneration: 'Ctrl+Shift+G',
openSessionHelp: 'CommandOrControl+Slash',
openControllerSelect: 'Alt+C',
openControllerDebug: 'Alt+Shift+C',
diff --git a/src/config/definitions/defaults-integrations.ts b/src/config/definitions/defaults-integrations.ts
index 23cf6d33..8d75b8b2 100644
--- a/src/config/definitions/defaults-integrations.ts
+++ b/src/config/definitions/defaults-integrations.ts
@@ -55,6 +55,7 @@ export const INTEGRATIONS_DEFAULT_CONFIG: Pick<
syncAnimatedImageToWordAudio: true,
normalizeAudio: true,
mirrorMpvVolume: true,
+ reviewTiming: false,
audioPadding: 0,
fallbackDuration: 3.0,
maxMediaDuration: 30,
diff --git a/src/config/definitions/options-core.ts b/src/config/definitions/options-core.ts
index 46cd7399..8803b386 100644
--- a/src/config/definitions/options-core.ts
+++ b/src/config/definitions/options-core.ts
@@ -628,6 +628,12 @@ export function buildCoreConfigOptionRegistry(
defaultValue: defaultConfig.shortcuts.openSessionHelp,
description: 'Accelerator that opens the session help / keybinding cheatsheet.',
},
+ {
+ path: 'shortcuts.openSubtitleGeneration',
+ kind: 'string',
+ defaultValue: defaultConfig.shortcuts.openSubtitleGeneration,
+ description: 'Accelerator that opens the standalone Japanese subtitle generation modal.',
+ },
{
path: 'shortcuts.openControllerSelect',
kind: 'string',
diff --git a/src/config/definitions/options-integrations.ts b/src/config/definitions/options-integrations.ts
index bba4c58b..8fbc8dcf 100644
--- a/src/config/definitions/options-integrations.ts
+++ b/src/config/definitions/options-integrations.ts
@@ -196,6 +196,14 @@ export function buildIntegrationConfigOptionRegistry(
description:
"Apply mpv's current software volume curve to generated sentence audio. Changes apply live.",
},
+ {
+ path: 'ankiConnect.media.reviewTiming',
+ kind: 'boolean',
+ defaultValue: defaultConfig.ankiConnect.media.reviewTiming,
+ description:
+ 'Review and preview subtitle media timing before SubMiner creates or enriches a mined card.',
+ runtime: runtimeOptionById.get('anki.mediaReviewTiming'),
+ },
{
path: 'ankiConnect.media.generateImage',
kind: 'boolean',
diff --git a/src/config/definitions/options-subtitle.ts b/src/config/definitions/options-subtitle.ts
index b7ab187e..e96baf66 100644
--- a/src/config/definitions/options-subtitle.ts
+++ b/src/config/definitions/options-subtitle.ts
@@ -1,10 +1,46 @@
import { ResolvedConfig } from '../../types/config';
import { ConfigOptionRegistryEntry } from './shared';
+import { SUBTITLE_GENERATION_MODELS } from '../../shared/subtitle-generation-model-catalog';
export function buildSubtitleConfigOptionRegistry(
defaultConfig: ResolvedConfig,
): ConfigOptionRegistryEntry[] {
return [
+ ...(
+ ['whisperPath', 'modelPath', 'ffmpegPath', 'ffprobePath', 'vadModelPath', 'vadPath'] as const
+ ).map((key) => ({
+ path: `subtitleGeneration.${key}`,
+ kind: 'string' as const,
+ defaultValue: defaultConfig.subtitleGeneration[key],
+ description: {
+ whisperPath:
+ 'Optional path override for whisper.cpp. Leave empty to find whisper-cli on PATH.',
+ modelPath:
+ 'Path to an existing multilingual whisper.cpp GGML model. Leave empty to use a SubMiner-managed model. A configured path always takes precedence.',
+ ffmpegPath:
+ 'Optional FFmpeg path override for audio extraction. Leave empty to find ffmpeg on PATH.',
+ ffprobePath:
+ 'Optional FFprobe path override for audio tracks and timing. Leave empty to find ffprobe on PATH.',
+ vadModelPath:
+ 'Path to a whisper.cpp Silero VAD model. Enables dialogue-focused generation while retaining uncertain audible sections, which may include songs. Leave empty to transcribe the full audio.',
+ vadPath:
+ 'Optional speech detector executable override. With vadModelPath configured, leave empty to find whisper-vad-speech-segments or vad-speech-segments on PATH.',
+ }[key],
+ })),
+ {
+ path: 'subtitleGeneration.managedModel',
+ kind: 'enum',
+ enumValues: SUBTITLE_GENERATION_MODELS.map((model) => model.id),
+ defaultValue: defaultConfig.subtitleGeneration.managedModel,
+ description:
+ 'Multilingual whisper.cpp model to use when modelPath is empty. Download it explicitly from the generation modal or launcher.',
+ },
+ {
+ path: 'subtitleGeneration.threads',
+ kind: 'number',
+ defaultValue: defaultConfig.subtitleGeneration.threads,
+ description: 'Positive integer CPU thread count for whisper.cpp Japanese transcription.',
+ },
{
path: 'subtitleStyle.primaryDefaultMode',
kind: 'enum',
diff --git a/src/config/definitions/runtime-options.ts b/src/config/definitions/runtime-options.ts
index 06335930..7d9f5080 100644
--- a/src/config/definitions/runtime-options.ts
+++ b/src/config/definitions/runtime-options.ts
@@ -19,6 +19,20 @@ export function buildRuntimeOptionRegistry(
behavior: { autoUpdateNewCards: value === true },
}),
},
+ {
+ id: 'anki.mediaReviewTiming',
+ path: 'ankiConnect.media.reviewTiming',
+ label: 'Review Media Timing',
+ scope: 'ankiConnect',
+ valueType: 'boolean',
+ allowedValues: [true, false],
+ defaultValue: defaultConfig.ankiConnect.media.reviewTiming,
+ requiresRestart: false,
+ formatValueForOsd: (value) => (value === true ? 'On' : 'Off'),
+ toAnkiPatch: (value) => ({
+ media: { reviewTiming: value === true },
+ }),
+ },
{
id: 'subtitle.annotation.knownWords.highlightEnabled',
path: 'ankiConnect.knownWords.highlightEnabled',
diff --git a/src/config/definitions/template-sections.ts b/src/config/definitions/template-sections.ts
index 95f68c0f..7ec5bb44 100644
--- a/src/config/definitions/template-sections.ts
+++ b/src/config/definitions/template-sections.ts
@@ -1,6 +1,15 @@
import { ConfigTemplateSection } from './shared';
const CORE_TEMPLATE_SECTIONS: ConfigTemplateSection[] = [
+ {
+ title: 'Japanese Subtitle Generation',
+ description: [
+ 'Generate timed Japanese subtitles from local audio using whisper.cpp.',
+ 'Configure an existing GGML model path or explicitly download a SubMiner-managed model.',
+ ],
+ notes: ['Hot-reload: settings apply to the next generation or model download.'],
+ key: 'subtitleGeneration',
+ },
{
title: 'Visible Overlay Auto-Start',
description: [
@@ -135,7 +144,7 @@ const INTEGRATION_TEMPLATE_SECTIONS: ConfigTemplateSection[] = [
title: 'AnkiConnect Integration',
description: ['Automatic Anki updates and media generation options.'],
notes: [
- 'Hot-reload: ankiConnect.ai.enabled, media.normalizeAudio/mirrorMpvVolume, knownWords, nPlusOne, fields.word/audio/image/sentence/miscInfo, behavior.autoUpdateNewCards, isLapis.sentenceCardModel, isKiku.fieldGrouping, isSenren.fieldGrouping, and lapisKiku.wordCardKind update live while SubMiner is running.',
+ 'Hot-reload: ankiConnect.ai.enabled, media.normalizeAudio/mirrorMpvVolume/reviewTiming, knownWords, nPlusOne, fields.word/audio/image/sentence/miscInfo, behavior.autoUpdateNewCards, isLapis.sentenceCardModel, isKiku.fieldGrouping, isSenren.fieldGrouping, and lapisKiku.wordCardKind update live while SubMiner is running.',
'Shared AI provider transport settings are read from top-level ai and typically require restart.',
'Most other AnkiConnect settings still require restart.',
],
diff --git a/src/config/resolve/anki-connect.test.ts b/src/config/resolve/anki-connect.test.ts
index 6b469208..5246adf3 100644
--- a/src/config/resolve/anki-connect.test.ts
+++ b/src/config/resolve/anki-connect.test.ts
@@ -21,6 +21,34 @@ function makeContext(ankiConnect: unknown): {
return { context, warnings };
}
+test('media timing review is disabled by default and accepts a boolean override', () => {
+ const defaultContext = makeContext({});
+ applyAnkiConnectResolution(defaultContext.context);
+ assert.equal(defaultContext.context.resolved.ankiConnect.media.reviewTiming, false);
+
+ const enabledContext = makeContext({ media: { reviewTiming: true } });
+ applyAnkiConnectResolution(enabledContext.context);
+ assert.equal(enabledContext.context.resolved.ankiConnect.media.reviewTiming, true);
+ assert.deepEqual(enabledContext.warnings, []);
+});
+
+test('modern media duration accepts zero as the disabled cap sentinel', () => {
+ const disabledCap = makeContext({ media: { maxMediaDuration: 0 } });
+ applyAnkiConnectResolution(disabledCap.context);
+ assert.equal(disabledCap.context.resolved.ankiConnect.media.maxMediaDuration, 0);
+ assert.deepEqual(disabledCap.warnings, []);
+
+ const invalidCap = makeContext({ media: { maxMediaDuration: -1 } });
+ applyAnkiConnectResolution(invalidCap.context);
+ assert.equal(
+ invalidCap.context.resolved.ankiConnect.media.maxMediaDuration,
+ DEFAULT_CONFIG.ankiConnect.media.maxMediaDuration,
+ );
+ assert.ok(
+ invalidCap.warnings.some((warning) => warning.path === 'ankiConnect.media.maxMediaDuration'),
+ );
+});
+
test('modern invalid knownWords.highlightEnabled warns modern key and does not fallback to legacy', () => {
const { context, warnings } = makeContext({
nPlusOne: { highlightEnabled: true },
diff --git a/src/config/resolve/anki-connect/modern-media.ts b/src/config/resolve/anki-connect/modern-media.ts
index d391f1c0..0babef6f 100644
--- a/src/config/resolve/anki-connect/modern-media.ts
+++ b/src/config/resolve/anki-connect/modern-media.ts
@@ -19,6 +19,7 @@ export function applyModernMediaResolution(
'syncAnimatedImageToWordAudio',
'normalizeAudio',
'mirrorMpvVolume',
+ 'reviewTiming',
] as const) {
applyModernValue(
context,
@@ -128,18 +129,28 @@ export function applyModernMediaResolution(
'Expected non-negative number.',
);
- for (const key of ['fallbackDuration', 'maxMediaDuration'] as const) {
- applyModernValue(
- context,
- media,
- key,
- `ankiConnect.media.${key}`,
- asPositiveNumber,
- DEFAULT_CONFIG.ankiConnect.media[key],
- (value) => {
- context.resolved.ankiConnect.media[key] = value;
- },
- 'Expected positive number.',
- );
- }
+ applyModernValue(
+ context,
+ media,
+ 'fallbackDuration',
+ 'ankiConnect.media.fallbackDuration',
+ asPositiveNumber,
+ DEFAULT_CONFIG.ankiConnect.media.fallbackDuration,
+ (value) => {
+ context.resolved.ankiConnect.media.fallbackDuration = value;
+ },
+ 'Expected positive number.',
+ );
+ applyModernValue(
+ context,
+ media,
+ 'maxMediaDuration',
+ 'ankiConnect.media.maxMediaDuration',
+ asNonNegativeNumber,
+ DEFAULT_CONFIG.ankiConnect.media.maxMediaDuration,
+ (value) => {
+ context.resolved.ankiConnect.media.maxMediaDuration = value;
+ },
+ 'Expected non-negative number.',
+ );
}
diff --git a/src/config/resolve/core-domains.ts b/src/config/resolve/core-domains.ts
index c531fc52..4218f668 100644
--- a/src/config/resolve/core-domains.ts
+++ b/src/config/resolve/core-domains.ts
@@ -237,6 +237,7 @@ export function applyCoreDomainConfig(context: ResolveContext): void {
'openRuntimeOptions',
'openJimaku',
'openTsukihime',
+ 'openSubtitleGeneration',
'openSessionHelp',
'openControllerSelect',
'openControllerDebug',
diff --git a/src/config/resolve/subtitle-domains.ts b/src/config/resolve/subtitle-domains.ts
index 8d07e410..f9aead68 100644
--- a/src/config/resolve/subtitle-domains.ts
+++ b/src/config/resolve/subtitle-domains.ts
@@ -1,5 +1,6 @@
import { ResolvedConfig } from '../../types/config';
import { ResolveContext } from './context';
+import { resolveSubtitleGenerationConfig } from '../../shared/subtitle-generation';
import {
asBoolean,
asColor,
@@ -46,6 +47,17 @@ function applySubtitleHoverTokenCssCompatibility(
export function applySubtitleDomainConfig(context: ResolveContext): void {
const { src, resolved, warn } = context;
+ resolved.subtitleGeneration = resolveSubtitleGenerationConfig(
+ src.subtitleGeneration,
+ (key, value, message) => {
+ const configPath = key === 'subtitleGeneration' ? key : `subtitleGeneration.${key}`;
+ const fallback =
+ key === 'subtitleGeneration'
+ ? resolved.subtitleGeneration
+ : Object.entries(resolved.subtitleGeneration).find(([name]) => name === key)?.[1];
+ warn(configPath, value, fallback, message);
+ },
+ );
if (isObject(src.jimaku)) {
const apiKey = asString(src.jimaku.apiKey);
diff --git a/src/config/resolve/subtitle-generation.test.ts b/src/config/resolve/subtitle-generation.test.ts
new file mode 100644
index 00000000..10500cef
--- /dev/null
+++ b/src/config/resolve/subtitle-generation.test.ts
@@ -0,0 +1,90 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { resolveConfig } from '../resolve';
+import { buildConfigSettingsRegistry } from '../settings/registry';
+import { SUBTITLE_GENERATION_MODELS } from '../../shared/subtitle-generation-model-catalog';
+import { resolveSubtitleGenerationConfig } from '../../shared/subtitle-generation';
+
+test('every downloadable multilingual model is accepted by config and offered in settings', () => {
+ const settings = buildConfigSettingsRegistry(resolveConfig({}).resolved).find(
+ (entry) => entry.configPath === 'subtitleGeneration.managedModel',
+ );
+ assert.deepEqual(
+ settings?.enumValues,
+ SUBTITLE_GENERATION_MODELS.map((model) => model.id),
+ );
+ for (const { id } of SUBTITLE_GENERATION_MODELS) {
+ const { resolved, warnings } = resolveConfig({ subtitleGeneration: { managedModel: id } });
+ assert.equal(resolved.subtitleGeneration.managedModel, id);
+ assert.equal(warnings.length, 0);
+ }
+});
+
+test('generation config rejects English-only, unknown, and prototype model names', () => {
+ for (const managedModel of ['tiny.en', 'small.en-q5_1', 'unknown', 'toString', '__proto__']) {
+ const warnings: string[] = [];
+ const resolved = resolveSubtitleGenerationConfig({ managedModel }, (key) => warnings.push(key));
+ assert.equal(resolved.managedModel, 'small');
+ assert.equal(warnings.length, 1);
+ }
+});
+
+test('generation config is resolved and its external model path is editable without restart', () => {
+ const { resolved, warnings } = resolveConfig({
+ subtitleGeneration: { modelPath: '/models/japanese.bin', managedModel: 'medium', threads: 8 },
+ });
+ assert.equal(resolved.subtitleGeneration.modelPath, '/models/japanese.bin');
+ assert.equal(resolved.subtitleGeneration.managedModel, 'medium');
+ assert.equal(warnings.length, 0);
+ const field = buildConfigSettingsRegistry(resolved).find(
+ (entry) => entry.configPath === 'subtitleGeneration.modelPath',
+ );
+ assert.equal(field?.category, 'integrations');
+ assert.equal(field?.restartBehavior, 'hot-reload');
+});
+
+test('generation executable overrides default to empty and accept blank values without warnings', () => {
+ for (const subtitleGeneration of [
+ {},
+ { whisperPath: '', ffmpegPath: '', ffprobePath: '' },
+ { whisperPath: ' ', ffmpegPath: ' ', ffprobePath: ' ' },
+ ]) {
+ const { resolved, warnings } = resolveConfig({ subtitleGeneration });
+ assert.equal(resolved.subtitleGeneration.whisperPath, '');
+ assert.equal(resolved.subtitleGeneration.ffmpegPath, '');
+ assert.equal(resolved.subtitleGeneration.ffprobePath, '');
+ assert.equal(warnings.length, 0);
+ }
+});
+
+test('subtitle generation shortcut can be customized or disabled', () => {
+ assert.equal(resolveConfig({}).resolved.shortcuts.openSubtitleGeneration, 'Ctrl+Shift+G');
+ assert.equal(
+ resolveConfig({ shortcuts: { openSubtitleGeneration: 'Ctrl+Alt+G' } }).resolved.shortcuts
+ .openSubtitleGeneration,
+ 'Ctrl+Alt+G',
+ );
+ assert.equal(
+ resolveConfig({ shortcuts: { openSubtitleGeneration: null } }).resolved.shortcuts
+ .openSubtitleGeneration,
+ null,
+ );
+});
+
+test('dialogue detection paths are optional, validated, and editable in Settings', () => {
+ const { resolved, warnings } = resolveConfig({
+ subtitleGeneration: { vadModelPath: ' /models/silero.bin ', vadPath: ' /bin/vad ' },
+ });
+ assert.equal(resolved.subtitleGeneration.vadModelPath, '/models/silero.bin');
+ assert.equal(resolved.subtitleGeneration.vadPath, '/bin/vad');
+ assert.equal(warnings.length, 0);
+ for (const key of ['vadModelPath', 'vadPath'] as const) {
+ const field = buildConfigSettingsRegistry(resolved).find(
+ (entry) => entry.configPath === `subtitleGeneration.${key}`,
+ );
+ assert.equal(field?.category, 'integrations');
+ assert.equal(field?.restartBehavior, 'hot-reload');
+ assert.equal(resolveConfig({}).resolved.subtitleGeneration[key], '');
+ assert.equal(resolveConfig({ subtitleGeneration: { [key]: false } }).warnings.length, 1);
+ }
+});
diff --git a/src/config/settings/registry.test.ts b/src/config/settings/registry.test.ts
index ed1e3b0d..9068460a 100644
--- a/src/config/settings/registry.test.ts
+++ b/src/config/settings/registry.test.ts
@@ -369,6 +369,7 @@ test('settings registry marks safe live config paths as hot-reloadable', () => {
'ankiConnect.deck',
'ankiConnect.media.normalizeAudio',
'ankiConnect.media.mirrorMpvVolume',
+ 'ankiConnect.media.reviewTiming',
'ankiConnect.knownWords.highlightEnabled',
'ankiConnect.knownWords.refreshMinutes',
'ankiConnect.knownWords.addMinedWordsImmediately',
diff --git a/src/config/settings/registry.ts b/src/config/settings/registry.ts
index 7a13312e..fe308d65 100644
--- a/src/config/settings/registry.ts
+++ b/src/config/settings/registry.ts
@@ -248,6 +248,7 @@ const LABEL_OVERRIDES: Record = {
'mpv.aniskipButtonKey': 'AniSkip Button Key',
'anime.autoOpenJimaku': 'Auto-open Jimaku',
'ankiConnect.media.mirrorMpvVolume': 'Mirror mpv Volume',
+ 'ankiConnect.media.reviewTiming': 'Review Media Timing',
'discordPresence.updateIntervalMs': 'Update Interval (ms)',
};
@@ -452,6 +453,9 @@ function categoryAndSection(path: string): { category: ConfigSettingsCategory; s
if (path.startsWith('subsync.')) {
return { category: 'integrations', section: topSection(path) };
}
+ if (path.startsWith('subtitleGeneration.')) {
+ return { category: 'integrations', section: 'Japanese Subtitle Generation' };
+ }
if (path === 'stats.toggleKey' || path === 'stats.markWatchedKey') {
return { category: 'input', section: 'Overlay Shortcuts' };
}
@@ -624,6 +628,7 @@ function subsectionForPath(path: string): string | undefined {
leaf === 'openRuntimeOptions' ||
leaf === 'openJimaku' ||
leaf === 'openTsukihime' ||
+ leaf === 'openSubtitleGeneration' ||
leaf === 'openSessionHelp' ||
leaf === 'openControllerSelect' ||
leaf === 'openControllerDebug'
@@ -704,6 +709,7 @@ function restartBehaviorForPath(path: string): ConfigSettingsRestartBehavior {
path === 'ankiConnect.ai.enabled' ||
path === 'ankiConnect.media.normalizeAudio' ||
path === 'ankiConnect.media.mirrorMpvVolume' ||
+ path === 'ankiConnect.media.reviewTiming' ||
path === 'ankiConnect.behavior.autoUpdateNewCards' ||
path === 'ankiConnect.knownWords.highlightEnabled' ||
path === 'ankiConnect.knownWords.refreshMinutes' ||
@@ -732,7 +738,8 @@ function restartBehaviorForPath(path: string): ConfigSettingsRestartBehavior {
path === 'anime.autoOpenJimaku' ||
path === 'youtube.primarySubLanguages' ||
pathStartsWith(path, 'jimaku') ||
- pathStartsWith(path, 'subsync')
+ pathStartsWith(path, 'subsync') ||
+ pathStartsWith(path, 'subtitleGeneration')
) {
return 'hot-reload';
}
diff --git a/src/core/services/config-hot-reload.test.ts b/src/core/services/config-hot-reload.test.ts
index f316cc12..2628e103 100644
--- a/src/core/services/config-hot-reload.test.ts
+++ b/src/core/services/config-hot-reload.test.ts
@@ -33,6 +33,7 @@ test('classifyConfigHotReloadDiff treats safe nested config paths as hot-reloada
next.ankiConnect.deck = 'Mining';
next.ankiConnect.media.normalizeAudio = !prev.ankiConnect.media.normalizeAudio;
next.ankiConnect.media.mirrorMpvVolume = !prev.ankiConnect.media.mirrorMpvVolume;
+ next.ankiConnect.media.reviewTiming = !prev.ankiConnect.media.reviewTiming;
next.ankiConnect.behavior.autoUpdateNewCards = !prev.ankiConnect.behavior.autoUpdateNewCards;
next.ankiConnect.knownWords.highlightEnabled = !prev.ankiConnect.knownWords.highlightEnabled;
next.ankiConnect.knownWords.refreshMinutes = prev.ankiConnect.knownWords.refreshMinutes + 5;
@@ -69,6 +70,7 @@ test('classifyConfigHotReloadDiff treats safe nested config paths as hot-reloada
'ankiConnect.deck',
'ankiConnect.media.normalizeAudio',
'ankiConnect.media.mirrorMpvVolume',
+ 'ankiConnect.media.reviewTiming',
'ankiConnect.behavior.autoUpdateNewCards',
'ankiConnect.knownWords.highlightEnabled',
'ankiConnect.knownWords.refreshMinutes',
diff --git a/src/core/services/config-hot-reload.ts b/src/core/services/config-hot-reload.ts
index 6f3611d9..39cef3bc 100644
--- a/src/core/services/config-hot-reload.ts
+++ b/src/core/services/config-hot-reload.ts
@@ -71,6 +71,7 @@ const HOT_RELOAD_EXACT_OR_PREFIX_PATHS = [
'ankiConnect.deck',
'ankiConnect.media.normalizeAudio',
'ankiConnect.media.mirrorMpvVolume',
+ 'ankiConnect.media.reviewTiming',
'ankiConnect.behavior.autoUpdateNewCards',
'ankiConnect.knownWords.highlightEnabled',
'ankiConnect.knownWords.refreshMinutes',
diff --git a/src/core/services/hyprland-window-placement.test.ts b/src/core/services/hyprland-window-placement.test.ts
index 79e194ac..ea6fc36e 100644
--- a/src/core/services/hyprland-window-placement.test.ts
+++ b/src/core/services/hyprland-window-placement.test.ts
@@ -156,6 +156,107 @@ test('buildHyprlandPlacementDispatches does not pin already floating overlay win
);
});
+test('Hyprland placement keeps a recovery dialog above the input-catching overlay', () => {
+ for (const configProvider of ['hyprlang', 'lua']) {
+ for (const retryBounds of [false, true]) {
+ // Bottom to top, as when Hyprland opens its recovery dialog over playback.
+ const stack = ['0xmpv', '0xoverlay', '0xdialog'];
+ const clients = [
+ {
+ address: '0xoverlay',
+ pid: 456,
+ title: 'SubMiner Overlay',
+ floating: true,
+ workspace: { id: 1 },
+ at: [10, 20],
+ size: [100, 100],
+ },
+ {
+ address: '0xdialog',
+ class: 'hyprland-dialog',
+ mapped: true,
+ hidden: false,
+ workspace: { id: 1 },
+ },
+ ];
+ let clientReads = 0;
+ const status = ensureHyprlandWindowFloatingByTitleWithStatus({
+ title: 'SubMiner Overlay',
+ platform: 'linux',
+ env: { HYPRLAND_INSTANCE_SIGNATURE: 'abc' },
+ pid: 456,
+ bounds: retryBounds ? { x: 0, y: 0, width: 1280, height: 720 } : undefined,
+ execFileSync: (_command, args) => {
+ if (args.join(' ') === '-j clients') {
+ clientReads += 1;
+ return JSON.stringify(clients);
+ }
+ if (args.join(' ') === '-j status') return JSON.stringify({ configProvider });
+ if (args.join(' ').match(/alterzorder|alter_zorder/)) {
+ const address = args.join(' ').match(/address:(0x\w+)/)?.[1];
+ assert.ok(address);
+ stack.splice(stack.indexOf(address), 1);
+ stack.push(address);
+ }
+ return '';
+ },
+ });
+ assert.equal(status.dispatched, true);
+ assert.equal(clientReads, retryBounds ? 2 : 1);
+ assert.deepEqual(stack, ['0xmpv', '0xoverlay', '0xdialog'], configProvider);
+ }
+ }
+});
+
+test('Hyprland placement only promotes mapped dialogs on the placed window workspace', () => {
+ const calls: string[] = [];
+ const dialog = {
+ class: 'hyprland-dialog',
+ mapped: true,
+ hidden: false,
+ workspace: { id: 1 },
+ };
+ const clients = [
+ {
+ address: '0xoverlay',
+ pid: 456,
+ title: 'SubMiner Overlay',
+ floating: true,
+ workspace: { id: 1 },
+ },
+ { ...dialog, address: '0xhidden', hidden: true },
+ { ...dialog, address: '0xunmapped', mapped: false },
+ { ...dialog, address: '0xother', workspace: { id: 2 } },
+ { ...dialog, address: '0xordinary', class: 'terminal' },
+ { ...dialog, address: '0xinitial', class: '', initialClass: 'hyprland-dialog' },
+ ];
+ for (const promote of [true, false]) {
+ calls.length = 0;
+ ensureHyprlandWindowFloatingByTitleWithStatus({
+ title: 'SubMiner Overlay',
+ platform: 'linux',
+ env: { HYPRLAND_INSTANCE_SIGNATURE: 'abc' },
+ pid: 456,
+ promote,
+ execFileSync: (_command, args) => {
+ if (args.join(' ') === '-j clients') return JSON.stringify(clients);
+ if (args.join(' ') === '-j status') return JSON.stringify({ configProvider: 'hyprlang' });
+ calls.push(args.join(' '));
+ return '';
+ },
+ });
+ assert.deepEqual(
+ calls,
+ promote
+ ? [
+ 'dispatch alterzorder top,address:0xoverlay',
+ 'dispatch alterzorder top,address:0xinitial',
+ ]
+ : [],
+ );
+ }
+});
+
test('buildHyprlandPlacementDispatches can update placement without raising z-order', () => {
const buildDispatches = buildHyprlandPlacementDispatches as (
client: Parameters[0],
diff --git a/src/core/services/hyprland-window-placement.ts b/src/core/services/hyprland-window-placement.ts
index 16fd217a..6a4bf0a5 100644
--- a/src/core/services/hyprland-window-placement.ts
+++ b/src/core/services/hyprland-window-placement.ts
@@ -3,14 +3,17 @@ import { execFileSync } from 'node:child_process';
export interface HyprlandPlacementClient {
address?: string;
at?: [number, number];
+ class?: string;
floating?: boolean;
hidden?: boolean;
+ initialClass?: string;
initialTitle?: string;
mapped?: boolean;
pid?: number;
pinned?: boolean;
size?: [number, number];
title?: string;
+ workspace?: { id: number };
}
export interface HyprlandPlacementBounds {
@@ -25,7 +28,11 @@ export interface HyprlandPlacementDispatchOptions {
promote?: boolean;
}
-type ExecFileSync = typeof execFileSync;
+type ExecFileSync = (
+ file: string,
+ args: string[],
+ options: NonNullable[2]>,
+) => ReturnType;
export type HyprlandConfigProvider = 'hyprlang' | 'lua';
export function shouldAttemptHyprlandWindowPlacement(
@@ -154,6 +161,33 @@ function luaWindowDispatch(name: string, windowAddress: string, fields: string[]
];
}
+// Compositor recovery dialogs must remain clickable even when an overlay still owns input.
+function buildHyprlandDialogPromotionDispatches(
+ clients: HyprlandPlacementClient[],
+ placedClient: HyprlandPlacementClient,
+ configProvider: HyprlandConfigProvider,
+): string[][] {
+ if (typeof placedClient.workspace?.id !== 'number') return [];
+ return clients.flatMap((client) => {
+ if (
+ !client.address ||
+ client.address === placedClient.address ||
+ client.mapped === false ||
+ client.hidden === true ||
+ client.workspace?.id !== placedClient.workspace?.id ||
+ (client.class !== 'hyprland-dialog' && client.initialClass !== 'hyprland-dialog')
+ ) {
+ return [];
+ }
+ const windowAddress = `address:${client.address}`;
+ return [
+ configProvider === 'lua'
+ ? luaWindowDispatch('alter_zorder', windowAddress, ['mode = "top"'])
+ : ['dispatch', 'alterzorder', `top,${windowAddress}`],
+ ];
+ });
+}
+
function luaWindowSetProp(windowAddress: string, prop: string, value: string): string[] {
return luaWindowDispatch('set_prop', windowAddress, [
`prop = ${luaString(prop)}`,
@@ -331,12 +365,16 @@ export function ensureHyprlandWindowFloatingByTitleWithStatus(options: {
configProvider,
promote: options.promote,
});
+ if (options.promote !== false) {
+ dispatches.push(...buildHyprlandDialogPromotionDispatches(clients, client, configProvider));
+ }
for (const args of dispatches) {
run('hyprctl', args, { stdio: 'ignore' });
}
if (shouldVerifyBounds) {
try {
- const refreshedClient = findHyprlandWindowForPlacement(readHyprlandPlacementClients(run), {
+ const refreshedClients = readHyprlandPlacementClients(run);
+ const refreshedClient = findHyprlandWindowForPlacement(refreshedClients, {
pid: options.pid ?? process.pid,
title: options.title,
});
@@ -345,10 +383,20 @@ export function ensureHyprlandWindowFloatingByTitleWithStatus(options: {
targetBounds &&
clientMatchesPlacementBounds(refreshedClient, targetBounds) === false
) {
- for (const args of buildHyprlandPlacementDispatches(refreshedClient, targetBounds, {
+ const retryDispatches = buildHyprlandPlacementDispatches(refreshedClient, targetBounds, {
configProvider,
promote: options.promote,
- })) {
+ });
+ if (options.promote !== false) {
+ retryDispatches.push(
+ ...buildHyprlandDialogPromotionDispatches(
+ refreshedClients,
+ refreshedClient,
+ configProvider,
+ ),
+ );
+ }
+ for (const args of retryDispatches) {
run('hyprctl', args, { stdio: 'ignore' });
}
}
diff --git a/src/core/services/immersion-tracker/lexical-rollups.test.ts b/src/core/services/immersion-tracker/lexical-rollups.test.ts
index 8fae14c8..60ce4daf 100644
--- a/src/core/services/immersion-tracker/lexical-rollups.test.ts
+++ b/src/core/services/immersion-tracker/lexical-rollups.test.ts
@@ -306,9 +306,11 @@ test('vocabulary charts use complete top-word and lexical rollup data', () => {
`INSERT INTO imm_words(headword, word, reading, first_seen, last_seen, frequency)
VALUES (?, ?, '', 1700000000, 1700000000, ?)`,
);
+ db.exec('BEGIN');
for (let index = 0; index < 501; index += 1) {
insertWord.run(`語${index}`, `語${index}`, index === 500 ? 10_000 : 1);
}
+ db.exec('COMMIT');
const charts = getVocabularyChartData(db);
diff --git a/src/core/services/ipc.test.ts b/src/core/services/ipc.test.ts
index 21cb0d8d..8c2ddeeb 100644
--- a/src/core/services/ipc.test.ts
+++ b/src/core/services/ipc.test.ts
@@ -89,6 +89,7 @@ function createControllerConfigFixture() {
function createSubtitleSidebarSnapshotFixture(): SubtitleSidebarSnapshot {
return {
+ sourceKey: 'test-subtitles',
cues: [],
currentSubtitle: { text: '', startTime: null, endTime: null },
config: {
@@ -648,6 +649,83 @@ test('registerIpcHandlers exposes playback window activation request', async ()
assert.deepEqual(calls, ['activate']);
});
+test('registerIpcHandlers accepts the keep-without-media timing decision', async () => {
+ const { registrar, handlers } = createFakeIpcRegistrar();
+ const requests: unknown[] = [];
+ registerIpcHandlers(
+ createRegisterIpcDeps({
+ resolveMediaTimingReview: async (request) => {
+ requests.push(request);
+ return { ok: true };
+ },
+ }),
+ registrar,
+ );
+
+ const handler = handlers.handle.get(IPC_CHANNELS.request.mediaTimingReviewResolve);
+ assert.ok(handler);
+ assert.deepEqual(
+ await handler!({}, { reviewId: 'review-1', decision: { action: 'skip-media' } }),
+ { ok: true },
+ );
+ assert.deepEqual(requests, [{ reviewId: 'review-1', decision: { action: 'skip-media' } }]);
+});
+
+test('registerIpcHandlers validates and forwards combined timing review text', async () => {
+ const { registrar, handlers } = createFakeIpcRegistrar();
+ const requests: unknown[] = [];
+ registerIpcHandlers(
+ createRegisterIpcDeps({
+ resolveMediaTimingReview: async (request) => {
+ requests.push(request);
+ return { ok: true };
+ },
+ }),
+ registrar,
+ );
+
+ const handler = handlers.handle.get(IPC_CHANNELS.request.mediaTimingReviewResolve);
+ assert.ok(handler);
+ assert.deepEqual(
+ await handler!(
+ {},
+ {
+ reviewId: 'review-1',
+ decision: {
+ action: 'confirm',
+ startTime: 10,
+ endTime: 12,
+ text: '前の行 対象の行',
+ },
+ },
+ ),
+ { ok: true },
+ );
+ assert.deepEqual(requests, [
+ {
+ reviewId: 'review-1',
+ decision: {
+ action: 'confirm',
+ startTime: 10,
+ endTime: 12,
+ text: '前の行 対象の行',
+ },
+ },
+ ]);
+
+ assert.deepEqual(
+ await handler!(
+ {},
+ {
+ reviewId: 'review-1',
+ decision: { action: 'confirm', startTime: 10, endTime: 12, text: ' ' },
+ },
+ ),
+ { ok: false, message: 'Timing review is unavailable.' },
+ );
+ assert.equal(requests.length, 1);
+});
+
test('registerIpcHandlers forwards yomitan lookup tracking commands to immersion tracker', () => {
const { registrar, handlers } = createFakeIpcRegistrar();
const calls: string[] = [];
@@ -959,7 +1037,13 @@ test('registerIpcHandlers accepts per-controller profile config updates', async
},
};
await saveHandler({}, update);
- assert.deepEqual(controllerSaves, [update]);
+ assert.deepEqual(controllerSaves, [
+ {
+ ...update,
+ // Validation uses a null prototype to safely store arbitrary profile IDs.
+ profiles: { __proto__: null, ...update.profiles },
+ },
+ ]);
await assert.rejects(async () => {
await saveHandler(
@@ -1239,3 +1323,18 @@ test('registerIpcHandlers exposes character dictionary selection handlers', asyn
assert.deepEqual(calls, [21355]);
assert.deepEqual(searches, ['Re:ZERO']);
});
+
+test('mpv discovery has its own request and does not change session bindings', async () => {
+ const { registrar, handlers } = createFakeIpcRegistrar();
+ const snapshot = { keys: ['r'], blockedKeys: [] };
+ registerIpcHandlers(
+ createRegisterIpcDeps({ getMpvInputBindings: async () => snapshot }),
+ registrar,
+ );
+ const discovery = handlers.handle.get(IPC_CHANNELS.request.getMpvInputBindings);
+ const session = handlers.handle.get(IPC_CHANNELS.request.getSessionBindings);
+ assert.ok(discovery);
+ assert.ok(session);
+ assert.deepEqual(await discovery({}), snapshot);
+ assert.deepEqual(await session({}), []);
+});
diff --git a/src/core/services/ipc.ts b/src/core/services/ipc.ts
index 2475d215..2a26dac1 100644
--- a/src/core/services/ipc.ts
+++ b/src/core/services/ipc.ts
@@ -1,4 +1,5 @@
import electron from 'electron';
+import type { MpvInputBindingsSnapshot } from '../../types/session-bindings';
import type { BrowserWindow as ElectronBrowserWindow, IpcMainEvent } from 'electron';
import type {
ChangelogSnapshot,
@@ -19,6 +20,13 @@ import type {
YoutubePickerResolveRequest,
YoutubePickerResolveResult,
} from '../../types';
+import type {
+ MediaTimingReviewActionResult,
+ MediaTimingReviewPreviewRequest,
+ MediaTimingReviewResolveRequest,
+ MediaTimingReviewWaveformRequest,
+ MediaTimingReviewWaveformResult,
+} from '../../types/anki';
import { IPC_CHANNELS, type OverlayHostedModal } from '../../shared/ipc/contracts';
import {
parseMpvCommand,
@@ -82,6 +90,7 @@ export interface IpcServiceDeps {
setMecabEnabled: (enabled: boolean) => void;
handleMpvCommand: (command: Array) => void;
getKeybindings: () => unknown;
+ getMpvInputBindings?: () => Promise;
getSessionBindings?: () => CompiledSessionBinding[];
getConfiguredShortcuts: () => unknown;
dispatchSessionAction?: (request: SessionActionDispatchRequest) => void | Promise;
@@ -99,6 +108,16 @@ export interface IpcServiceDeps {
onYoutubePickerResolve: (
request: YoutubePickerResolveRequest,
) => Promise;
+ previewMediaTimingReview?: (
+ request: MediaTimingReviewPreviewRequest,
+ ) => Promise;
+ getMediaTimingReviewWaveform?: (
+ request: MediaTimingReviewWaveformRequest,
+ ) => Promise;
+ stopMediaTimingReviewPreview?: (reviewId: string) => Promise;
+ resolveMediaTimingReview?: (
+ request: MediaTimingReviewResolveRequest,
+ ) => MediaTimingReviewActionResult | Promise;
getAnkiConnectStatus: () => boolean;
getRuntimeOptions: () => unknown;
setRuntimeOption: (id: RuntimeOptionId, value: RuntimeOptionValue) => unknown;
@@ -222,6 +241,72 @@ function parseOverlayNotificationActionPayload(
return { notificationId, actionId, ...(typeof noteId === 'number' ? { noteId } : {}) };
}
+function parseMediaTimingReviewPreviewRequest(
+ payload: unknown,
+): MediaTimingReviewPreviewRequest | null {
+ if (!payload || typeof payload !== 'object') return null;
+ const record = payload as Record;
+ if (
+ typeof record.reviewId !== 'string' ||
+ !record.reviewId ||
+ typeof record.startTime !== 'number' ||
+ !Number.isFinite(record.startTime) ||
+ typeof record.endTime !== 'number' ||
+ !Number.isFinite(record.endTime)
+ ) {
+ return null;
+ }
+ return {
+ reviewId: record.reviewId,
+ startTime: record.startTime,
+ endTime: record.endTime,
+ };
+}
+
+function parseMediaTimingReviewWaveformRequest(
+ payload: unknown,
+): MediaTimingReviewWaveformRequest | null {
+ return parseMediaTimingReviewPreviewRequest(payload);
+}
+
+function parseMediaTimingReviewResolveRequest(
+ payload: unknown,
+): MediaTimingReviewResolveRequest | null {
+ if (!payload || typeof payload !== 'object') return null;
+ const record = payload as Record;
+ if (typeof record.reviewId !== 'string' || !record.reviewId) return null;
+ const decision = record.decision;
+ if (!decision || typeof decision !== 'object') return null;
+ const decisionRecord = decision as Record;
+ if (
+ decisionRecord.action === 'use-original' ||
+ decisionRecord.action === 'skip-media' ||
+ decisionRecord.action === 'discard'
+ ) {
+ return { reviewId: record.reviewId, decision: { action: decisionRecord.action } };
+ }
+ if (
+ decisionRecord.action === 'confirm' &&
+ typeof decisionRecord.startTime === 'number' &&
+ Number.isFinite(decisionRecord.startTime) &&
+ typeof decisionRecord.endTime === 'number' &&
+ Number.isFinite(decisionRecord.endTime) &&
+ (decisionRecord.text === undefined ||
+ (typeof decisionRecord.text === 'string' && decisionRecord.text.trim().length > 0))
+ ) {
+ return {
+ reviewId: record.reviewId,
+ decision: {
+ action: 'confirm',
+ startTime: decisionRecord.startTime,
+ endTime: decisionRecord.endTime,
+ ...(decisionRecord.text === undefined ? {} : { text: decisionRecord.text }),
+ },
+ };
+ }
+ return null;
+}
+
export interface IpcDepsRuntimeOptions {
getMainWindow: () => WindowLike | null;
getVisibleOverlayVisibility: () => boolean;
@@ -261,6 +346,7 @@ export interface IpcDepsRuntimeOptions {
getMecabTokenizer: () => MecabTokenizerLike | null;
handleMpvCommand: (command: Array) => void;
getKeybindings: () => unknown;
+ getMpvInputBindings?: () => Promise;
getSessionBindings?: () => CompiledSessionBinding[];
getConfiguredShortcuts: () => unknown;
dispatchSessionAction?: (request: SessionActionDispatchRequest) => void | Promise;
@@ -278,6 +364,10 @@ export interface IpcDepsRuntimeOptions {
onYoutubePickerResolve: (
request: YoutubePickerResolveRequest,
) => Promise;
+ previewMediaTimingReview?: IpcServiceDeps['previewMediaTimingReview'];
+ getMediaTimingReviewWaveform?: IpcServiceDeps['getMediaTimingReviewWaveform'];
+ stopMediaTimingReviewPreview?: IpcServiceDeps['stopMediaTimingReviewPreview'];
+ resolveMediaTimingReview?: IpcServiceDeps['resolveMediaTimingReview'];
getAnkiConnectStatus: () => boolean;
getRuntimeOptions: () => unknown;
setRuntimeOption: (id: RuntimeOptionId, value: RuntimeOptionValue) => unknown;
@@ -351,6 +441,7 @@ export function createIpcDepsRuntime(options: IpcDepsRuntimeOptions): IpcService
},
handleMpvCommand: options.handleMpvCommand,
getKeybindings: options.getKeybindings,
+ getMpvInputBindings: options.getMpvInputBindings,
getSessionBindings: options.getSessionBindings ?? (() => []),
getConfiguredShortcuts: options.getConfiguredShortcuts,
dispatchSessionAction: options.dispatchSessionAction ?? (async () => {}),
@@ -371,6 +462,10 @@ export function createIpcDepsRuntime(options: IpcDepsRuntimeOptions): IpcService
options.activatePlaybackWindowForOverlayInteraction ?? (() => false),
runSubsyncManual: options.runSubsyncManual,
onYoutubePickerResolve: options.onYoutubePickerResolve,
+ previewMediaTimingReview: options.previewMediaTimingReview,
+ getMediaTimingReviewWaveform: options.getMediaTimingReviewWaveform,
+ stopMediaTimingReviewPreview: options.stopMediaTimingReviewPreview,
+ resolveMediaTimingReview: options.resolveMediaTimingReview,
getAnkiConnectStatus: options.getAnkiConnectStatus,
getRuntimeOptions: options.getRuntimeOptions,
setRuntimeOption: options.setRuntimeOption,
@@ -498,6 +593,46 @@ export function registerIpcHandlers(deps: IpcServiceDeps, ipc: IpcMainRegistrar
},
);
+ ipc.handle(
+ IPC_CHANNELS.request.mediaTimingReviewPreview,
+ async (_event: unknown, payload: unknown) => {
+ const request = parseMediaTimingReviewPreviewRequest(payload);
+ if (!request || !deps.previewMediaTimingReview) {
+ return { ok: false, message: 'Timing preview is unavailable.' };
+ }
+ return await deps.previewMediaTimingReview(request);
+ },
+ );
+ ipc.handle(
+ IPC_CHANNELS.request.mediaTimingReviewWaveform,
+ async (_event: unknown, payload: unknown) => {
+ const request = parseMediaTimingReviewWaveformRequest(payload);
+ if (!request || !deps.getMediaTimingReviewWaveform) {
+ return { ok: false, message: 'Timing waveform is unavailable.' };
+ }
+ return await deps.getMediaTimingReviewWaveform(request);
+ },
+ );
+ ipc.handle(
+ IPC_CHANNELS.request.mediaTimingReviewStopPreview,
+ async (_event: unknown, reviewId: unknown) => {
+ if (typeof reviewId !== 'string' || !reviewId || !deps.stopMediaTimingReviewPreview) {
+ return { ok: false, message: 'Timing preview is unavailable.' };
+ }
+ return await deps.stopMediaTimingReviewPreview(reviewId);
+ },
+ );
+ ipc.handle(
+ IPC_CHANNELS.request.mediaTimingReviewResolve,
+ async (_event: unknown, payload: unknown) => {
+ const request = parseMediaTimingReviewResolveRequest(payload);
+ if (!request || !deps.resolveMediaTimingReview) {
+ return { ok: false, message: 'Timing review is unavailable.' };
+ }
+ return await deps.resolveMediaTimingReview(request);
+ },
+ );
+
ipc.on(IPC_CHANNELS.command.openYomitanSettings, () => {
deps.openYomitanSettings();
});
@@ -638,6 +773,10 @@ export function registerIpcHandlers(deps: IpcServiceDeps, ipc: IpcMainRegistrar
return deps.getKeybindings();
});
+ ipc.handle(IPC_CHANNELS.request.getMpvInputBindings, () => {
+ return deps.getMpvInputBindings?.() ?? { keys: [], blockedKeys: [] };
+ });
+
ipc.handle(IPC_CHANNELS.request.getSessionBindings, () => {
return deps.getSessionBindings?.() ?? [];
});
diff --git a/src/core/services/media-timing-preview.test.ts b/src/core/services/media-timing-preview.test.ts
new file mode 100644
index 00000000..c13cb61d
--- /dev/null
+++ b/src/core/services/media-timing-preview.test.ts
@@ -0,0 +1,291 @@
+import assert from 'node:assert/strict';
+import { EventEmitter } from 'node:events';
+import net from 'node:net';
+import { describe, test } from 'node:test';
+import { buildMediaTimingPreviewArgs, MediaTimingPreviewSession } from './media-timing-preview';
+
+describe('buildMediaTimingPreviewArgs', () => {
+ test('creates a hidden audio-only reusable mpv session', () => {
+ const args = buildMediaTimingPreviewArgs('/tmp/review.sock', {
+ mediaPath: '/video/show.mkv',
+ audioTrackId: 3,
+ volume: 55,
+ });
+
+ assert.ok(args.includes('--no-video'));
+ assert.ok(args.includes('--force-window=no'));
+ assert.ok(args.includes('--idle=yes'));
+ assert.ok(args.includes('--pause=yes'));
+ assert.ok(args.includes('--input-ipc-server=/tmp/review.sock'));
+ assert.ok(args.includes('--aid=3'));
+ assert.ok(args.includes('--volume=55'));
+ assert.equal(args.at(-2), '--');
+ assert.equal(args.at(-1), '/video/show.mkv');
+ });
+
+ test('keeps source timestamps for cached remote windows', () => {
+ const args = buildMediaTimingPreviewArgs('/tmp/review.sock', {
+ mediaPath: '/tmp/window.mkv',
+ absoluteTimestamps: true,
+ });
+
+ assert.ok(args.includes('--rebase-start-time=no'));
+ assert.equal(
+ buildMediaTimingPreviewArgs('/tmp/review.sock', { mediaPath: '/video/show.mkv' }).includes(
+ '--rebase-start-time=no',
+ ),
+ false,
+ );
+ });
+
+ test('separates an option-like media path without adding optional audio arguments', () => {
+ const args = buildMediaTimingPreviewArgs('/tmp/review.sock', {
+ mediaPath: '--fullscreen',
+ });
+
+ assert.equal(args.at(-2), '--');
+ assert.equal(args.at(-1), '--fullscreen');
+ assert.equal(
+ args.some((arg) => arg.startsWith('--aid=')),
+ false,
+ );
+ assert.equal(
+ args.some((arg) => arg.startsWith('--volume=')),
+ false,
+ );
+ });
+});
+
+test('preview session handles socket errors after connecting', async () => {
+ const socket = new net.Socket();
+ const child = new EventEmitter() as EventEmitter & { kill: () => boolean };
+ child.kill = () => true;
+ const session = new MediaTimingPreviewSession({
+ platform: 'linux',
+ spawnProcess: () => child as never,
+ connectSocket: () => {
+ queueMicrotask(() => socket.emit('connect'));
+ return socket;
+ },
+ removeSocketFile: () => undefined,
+ createSocketPath: () => '/tmp/review.sock',
+ });
+
+ await session.start({ mediaPath: '/video/show.mkv' });
+ assert.doesNotThrow(() => socket.emit('error', new Error('pipe closed')));
+ await assert.rejects(session.play(1, 2), /not ready/);
+ session.dispose();
+});
+
+test('preview session keeps failed connection errors handled through destruction', async () => {
+ const socket = new EventEmitter() as EventEmitter & {
+ destroy: () => void;
+ };
+ socket.destroy = () => {
+ socket.emit('error', new Error('socket failed again while closing'));
+ };
+ const child = new EventEmitter() as EventEmitter & { kill: () => boolean };
+ child.kill = () => true;
+ const times = [0, 0, 0, 6_000];
+ const session = new MediaTimingPreviewSession({
+ platform: 'linux',
+ spawnProcess: () => child as never,
+ connectSocket: () => {
+ queueMicrotask(() => socket.emit('error', new Error('connection failed')));
+ return socket as never;
+ },
+ now: () => times.shift() ?? 6_000,
+ removeSocketFile: () => undefined,
+ createSocketPath: () => '/tmp/review.sock',
+ });
+
+ await assert.rejects(session.start({ mediaPath: '/video/show.mkv' }), /Timed out starting/);
+});
+
+test('preview session rejects a connection that finishes after disposal', async () => {
+ const socket = new net.Socket();
+ const child = new EventEmitter() as EventEmitter & { kill: () => boolean };
+ child.kill = () => true;
+ const session = new MediaTimingPreviewSession({
+ platform: 'linux',
+ spawnProcess: () => child as never,
+ connectSocket: () => socket,
+ removeSocketFile: () => undefined,
+ createSocketPath: () => '/tmp/review.sock',
+ });
+
+ const pendingStart = session.start({ mediaPath: '-playlist' });
+ session.dispose();
+ socket.emit('connect');
+
+ await assert.rejects(pendingStart, /closed/);
+ assert.equal(socket.destroyed, true);
+});
+
+test('preview session shares one startup across concurrent start calls', async () => {
+ const socket = new net.Socket();
+ const child = new EventEmitter() as EventEmitter & { kill: () => boolean };
+ child.kill = () => true;
+ let spawnCount = 0;
+ const session = new MediaTimingPreviewSession({
+ platform: 'linux',
+ spawnProcess: () => {
+ spawnCount += 1;
+ return child as never;
+ },
+ connectSocket: () => socket,
+ removeSocketFile: () => undefined,
+ createSocketPath: () => '/tmp/review.sock',
+ });
+
+ const firstStart = session.start({ mediaPath: '/video/show.mkv' });
+ const secondStart = session.start({ mediaPath: '/video/show.mkv' });
+ socket.emit('connect');
+
+ await Promise.all([firstStart, secondStart]);
+ assert.equal(spawnCount, 1);
+ session.dispose();
+});
+
+test('preview session can start again after a startup failure', async () => {
+ const socket = new net.Socket();
+ const child = new EventEmitter() as EventEmitter & { kill: () => boolean };
+ child.kill = () => true;
+ let spawnCount = 0;
+ const session = new MediaTimingPreviewSession({
+ platform: 'linux',
+ spawnProcess: () => {
+ spawnCount += 1;
+ if (spawnCount === 1) throw new Error('spawn failed');
+ return child as never;
+ },
+ connectSocket: () => {
+ queueMicrotask(() => socket.emit('connect'));
+ return socket;
+ },
+ removeSocketFile: () => undefined,
+ createSocketPath: () => '/tmp/review.sock',
+ });
+
+ await assert.rejects(session.start({ mediaPath: '/video/show.mkv' }), /spawn failed/);
+ await session.start({ mediaPath: '/video/show.mkv' });
+ assert.equal(spawnCount, 2);
+ session.dispose();
+});
+
+test('preview session bounds a connection attempt that never settles', async () => {
+ const child = new EventEmitter() as EventEmitter & { kill: () => boolean };
+ child.kill = () => true;
+ let nowMs = 0;
+ let connectAttempts = 0;
+ const session = new MediaTimingPreviewSession({
+ platform: 'linux',
+ spawnProcess: () => child as never,
+ connectSocket: () => {
+ connectAttempts += 1;
+ const socket = new net.Socket();
+ socket.destroy = (() => {
+ socket.emit('error', new Error('socket failed while timing out'));
+ return socket;
+ }) as typeof socket.destroy;
+ return socket;
+ },
+ now: () => {
+ const current = nowMs;
+ nowMs += 1_000;
+ return current;
+ },
+ schedule: (callback) => setTimeout(callback, 0),
+ cancelSchedule: (timeout) => clearTimeout(timeout),
+ removeSocketFile: () => undefined,
+ createSocketPath: () => '/tmp/review.sock',
+ });
+
+ await assert.rejects(session.start({ mediaPath: '/video/show.mkv' }), /Timed out starting/);
+ assert.equal(connectAttempts, 1);
+});
+
+function createFakeSocket() {
+ const socket = new EventEmitter() as EventEmitter & {
+ destroyed: boolean;
+ write: (data: string) => boolean;
+ end: () => void;
+ destroy: () => void;
+ off: EventEmitter['off'];
+ };
+ const writes: string[] = [];
+ socket.destroyed = false;
+ socket.write = (data) => {
+ writes.push(data);
+ return true;
+ };
+ socket.end = () => undefined;
+ socket.destroy = () => {
+ socket.destroyed = true;
+ };
+ return { socket, writes };
+}
+
+test('preview session plays once to the clip end and reports when mpv has drained it', async () => {
+ const { socket, writes } = createFakeSocket();
+ const child = new EventEmitter() as EventEmitter & { kill: () => boolean };
+ child.kill = () => true;
+ const session = new MediaTimingPreviewSession({
+ platform: 'linux',
+ spawnProcess: () => child as never,
+ connectSocket: () => {
+ queueMicrotask(() => socket.emit('connect'));
+ return socket as never;
+ },
+ removeSocketFile: () => undefined,
+ createSocketPath: () => '/tmp/review.sock',
+ });
+ let endedCount = 0;
+ session.onPlaybackEnded(() => {
+ endedCount += 1;
+ });
+ const property = (name: string, data: boolean): string =>
+ `${JSON.stringify({ event: 'property-change', name, data })}\n`;
+
+ await session.start({ mediaPath: '/video/show.mkv' });
+ assert.deepEqual(
+ writes.map((line) => JSON.parse(line).command),
+ [
+ ['observe_property', 1, 'eof-reached'],
+ ['observe_property', 2, 'pause'],
+ ],
+ );
+ // The observers' initial replies describe the idle paused player, not a finished preview.
+ socket.emit('data', property('eof-reached', false) + property('pause', true));
+ assert.equal(endedCount, 0);
+
+ writes.length = 0;
+ await session.play(12.25, 14.5);
+ assert.deepEqual(
+ writes.map((line) => JSON.parse(line).command),
+ [
+ ['set_property', 'pause', true],
+ ['seek', 12.25, 'absolute+exact'],
+ ['set_property', 'end', '14.500'],
+ ['set_property', 'pause', false],
+ ],
+ );
+
+ // Events may arrive split across chunks. The decoder passing `end` flips eof-reached while
+ // audio still drains; only the keep-open pause that follows marks the preview as finished.
+ socket.emit('data', property('eof-reached', false) + property('pause', false).slice(0, 20));
+ socket.emit('data', property('pause', false).slice(20) + property('eof-reached', true));
+ assert.equal(endedCount, 0);
+ socket.emit('data', property('pause', true));
+ assert.equal(endedCount, 1);
+ socket.emit('data', property('pause', true));
+ assert.equal(endedCount, 1);
+
+ // Stopping early pauses without an end signal, and a later real EOF is not a preview end.
+ await session.play(1, 2);
+ socket.emit('data', property('eof-reached', false) + property('pause', false));
+ await session.stop();
+ socket.emit('data', property('pause', true) + property('eof-reached', true));
+ assert.equal(endedCount, 1);
+ session.dispose();
+});
diff --git a/src/core/services/media-timing-preview.ts b/src/core/services/media-timing-preview.ts
new file mode 100644
index 00000000..60f60863
--- /dev/null
+++ b/src/core/services/media-timing-preview.ts
@@ -0,0 +1,394 @@
+import { spawn, type ChildProcess } from 'child_process';
+import fs from 'fs';
+import net, { type Socket } from 'net';
+import os from 'os';
+import path from 'path';
+import { randomUUID } from 'crypto';
+
+const CONNECT_TIMEOUT_MS = 5_000;
+const CONNECT_ATTEMPT_TIMEOUT_MS = 500;
+const CONNECT_RETRY_MS = 40;
+/**
+ * mpv flips eof-reached as soon as the decoder passes `end`, while its audio buffer is still
+ * draining; keep-open then pauses once the buffer has played out. A preview has ended when
+ * both have happened.
+ */
+const EOF_OBSERVER_ID = 1;
+const PAUSE_OBSERVER_ID = 2;
+
+export interface MediaTimingPreviewStartOptions {
+ mediaPath: string;
+ executablePath?: string;
+ audioTrackId?: number;
+ volume?: number;
+ /** The file keeps source timestamps (a cached remote window); seek with the original times. */
+ absoluteTimestamps?: boolean;
+}
+
+type PreviewProcess = Pick;
+
+interface MediaTimingPreviewDeps {
+ platform: NodeJS.Platform;
+ spawnProcess: (command: string, args: string[]) => PreviewProcess;
+ connectSocket: (socketPath: string) => Socket;
+ now: () => number;
+ schedule: (callback: () => void, delayMs: number) => ReturnType;
+ cancelSchedule: (timeout: ReturnType) => void;
+ removeSocketFile: (socketPath: string) => void;
+ createSocketPath: () => string;
+}
+
+export function buildMediaTimingPreviewArgs(
+ socketPath: string,
+ options: MediaTimingPreviewStartOptions,
+): string[] {
+ const args = [
+ '--no-config',
+ '--no-video',
+ '--audio-display=no',
+ '--force-window=no',
+ '--idle=yes',
+ '--keep-open=yes',
+ '--pause=yes',
+ '--terminal=no',
+ '--msg-level=all=warn',
+ `--input-ipc-server=${socketPath}`,
+ ];
+ if (typeof options.audioTrackId === 'number' && Number.isInteger(options.audioTrackId)) {
+ args.push(`--aid=${options.audioTrackId}`);
+ }
+ if (typeof options.volume === 'number' && Number.isFinite(options.volume)) {
+ args.push(`--volume=${Math.max(0, options.volume)}`);
+ }
+ if (options.absoluteTimestamps) {
+ args.push('--rebase-start-time=no');
+ }
+ args.push('--', options.mediaPath);
+ return args;
+}
+
+function createDefaultSocketPath(): string {
+ const suffix = `${process.pid}-${randomUUID()}`;
+ return process.platform === 'win32'
+ ? `\\\\.\\pipe\\subminer-timing-preview-${suffix}`
+ : path.join(
+ // macOS limits Unix socket paths to 104 bytes, while its temp directory can be long.
+ process.platform === 'darwin' ? '/tmp' : os.tmpdir(),
+ `subminer-timing-preview-${suffix}.sock`,
+ );
+}
+
+function removePosixSocketFile(socketPath: string): void {
+ if (process.platform === 'win32') return;
+ try {
+ fs.unlinkSync(socketPath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ throw error;
+ }
+ }
+}
+
+export class MediaTimingPreviewSession {
+ private readonly deps: MediaTimingPreviewDeps;
+ private socketPath: string | null = null;
+ private socket: Socket | null = null;
+ private process: PreviewProcess | null = null;
+ private startupError: Error | null = null;
+ private startPromise: Promise | null = null;
+ private retryWait: {
+ timeout: ReturnType;
+ resolve: () => void;
+ } | null = null;
+ private disposed = false;
+ private readBuffer = '';
+ private playing = false;
+ private eofReached = false;
+ private paused = true;
+ private readonly endedListeners = new Set<() => void>();
+
+ constructor(deps: Partial = {}) {
+ this.deps = {
+ platform: process.platform,
+ spawnProcess: (command, args) => spawn(command, args, { stdio: 'ignore' }),
+ connectSocket: (socketPath) => net.createConnection(socketPath),
+ now: Date.now,
+ schedule: (callback, delayMs) => setTimeout(callback, delayMs),
+ cancelSchedule: (timeout) => clearTimeout(timeout),
+ removeSocketFile: removePosixSocketFile,
+ createSocketPath: createDefaultSocketPath,
+ ...deps,
+ };
+ }
+
+ async start(options: MediaTimingPreviewStartOptions): Promise {
+ if (this.disposed) throw new Error('Preview session is closed');
+ if (this.socket) return;
+ if (this.startPromise) return await this.startPromise;
+
+ const startPromise = this.startOnce(options);
+ this.startPromise = startPromise;
+ try {
+ await startPromise;
+ } catch (error) {
+ this.releaseResources();
+ throw error;
+ } finally {
+ if (this.startPromise === startPromise) this.startPromise = null;
+ }
+ }
+
+ private async startOnce(options: MediaTimingPreviewStartOptions): Promise {
+ const mediaPath = options.mediaPath.trim();
+ if (!mediaPath) throw new Error('No media source is available for preview');
+
+ const socketPath = this.deps.createSocketPath();
+ this.socketPath = socketPath;
+ if (this.deps.platform !== 'win32') {
+ this.deps.removeSocketFile(socketPath);
+ }
+
+ const command = options.executablePath?.trim() || 'mpv';
+ this.startupError = null;
+ const child = this.deps.spawnProcess(
+ command,
+ buildMediaTimingPreviewArgs(socketPath, { ...options, mediaPath }),
+ );
+ this.process = child;
+ child.once('error', (error) => {
+ if (this.process !== child) return;
+ this.startupError = error;
+ });
+ child.once('exit', () => {
+ if (this.process !== child) return;
+ if (!this.socket && !this.disposed && !this.startupError) {
+ this.startupError = new Error('The hidden mpv preview player exited during startup');
+ }
+ this.socket?.destroy();
+ this.socket = null;
+ this.process = null;
+ });
+
+ await this.connectWithRetry(socketPath);
+ }
+
+ /**
+ * Plays [startTime, endTime) once. mpv stops itself at `end` and, thanks to keep-open,
+ * pauses after draining the audio device, so the listener hears the whole clip even on
+ * high-latency outputs. onPlaybackEnded fires when mpv reports the end was reached.
+ */
+ async play(startTime: number, endTime: number): Promise {
+ if (!this.socket || this.socket.destroyed) {
+ throw new Error('Preview player is not ready');
+ }
+ if (!Number.isFinite(startTime) || !Number.isFinite(endTime) || endTime <= startTime) {
+ throw new Error('Preview timing is invalid');
+ }
+
+ this.playing = false;
+ this.send(['set_property', 'pause', true]);
+ this.send(['seek', startTime, 'absolute+exact']);
+ // The option parser wants a time string; a raw JSON number is not accepted for `end`.
+ this.send(['set_property', 'end', endTime.toFixed(3)]);
+ this.send(['set_property', 'pause', false]);
+ // Only the seek's eof-reached=false and the later keep-open pause count for this play.
+ this.eofReached = false;
+ this.paused = false;
+ this.playing = true;
+ }
+
+ async stop(): Promise {
+ this.playing = false;
+ if (!this.socket || this.socket.destroyed) return;
+ this.send(['set_property', 'pause', true]);
+ }
+
+ onPlaybackEnded(listener: () => void): void {
+ this.endedListeners.add(listener);
+ }
+
+ private finishPlayback(): void {
+ if (!this.playing) return;
+ this.playing = false;
+ for (const listener of this.endedListeners) listener();
+ }
+
+ private handleSocketData(chunk: Buffer | string): void {
+ this.readBuffer += chunk.toString();
+ let newline = this.readBuffer.indexOf('\n');
+ while (newline !== -1) {
+ const line = this.readBuffer.slice(0, newline).trim();
+ this.readBuffer = this.readBuffer.slice(newline + 1);
+ newline = this.readBuffer.indexOf('\n');
+ if (!line) continue;
+ let message: unknown;
+ try {
+ message = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ if (
+ typeof message === 'object' &&
+ message !== null &&
+ 'event' in message &&
+ message.event === 'property-change' &&
+ 'name' in message &&
+ 'data' in message
+ ) {
+ this.handlePropertyChange(message.name, message.data);
+ }
+ }
+ }
+
+ private handlePropertyChange(name: unknown, data: unknown): void {
+ if (name === 'eof-reached') this.eofReached = data === true;
+ else if (name === 'pause') this.paused = data === true;
+ else return;
+ if (this.playing && this.eofReached && this.paused) this.finishPlayback();
+ }
+
+ dispose(): void {
+ if (this.disposed) return;
+ this.disposed = true;
+ this.releaseResources();
+ }
+
+ private releaseResources(): void {
+ this.cancelRetryWait();
+ try {
+ this.send(['quit']);
+ } catch {
+ // The process may already have exited.
+ }
+ this.socket?.end();
+ this.socket?.destroy();
+ this.socket = null;
+ const child = this.process;
+ this.process = null;
+ child?.kill();
+ if (this.socketPath && this.deps.platform !== 'win32') {
+ try {
+ this.deps.removeSocketFile(this.socketPath);
+ } catch {
+ // mpv may still be releasing the socket. The OS temp directory owns cleanup.
+ }
+ }
+ this.socketPath = null;
+ }
+
+ private send(command: Array): void {
+ if (!this.socket || this.socket.destroyed) {
+ throw new Error('Preview player is not connected');
+ }
+ this.socket.write(`${JSON.stringify({ command })}\n`);
+ }
+
+ private async connectWithRetry(socketPath: string): Promise {
+ const deadline = this.deps.now() + CONNECT_TIMEOUT_MS;
+ while (!this.disposed && this.deps.now() < deadline) {
+ if (this.startupError) {
+ throw this.startupError;
+ }
+ try {
+ const remainingMs = deadline - this.deps.now();
+ if (remainingMs <= 0) break;
+ const socket = await this.connectOnce(
+ socketPath,
+ Math.min(CONNECT_ATTEMPT_TIMEOUT_MS, remainingMs),
+ );
+ if (this.disposed) {
+ socket.destroy();
+ throw new Error('Preview session is closed');
+ }
+ this.socket = socket;
+ this.readBuffer = '';
+ socket.on('data', (chunk: Buffer | string) => {
+ if (this.socket === socket) this.handleSocketData(chunk);
+ });
+ socket.once('close', () => this.finishPlayback());
+ this.send(['observe_property', EOF_OBSERVER_ID, 'eof-reached']);
+ this.send(['observe_property', PAUSE_OBSERVER_ID, 'pause']);
+ return;
+ } catch {
+ if (this.disposed) {
+ throw new Error('Preview session is closed');
+ }
+ const remainingMs = deadline - this.deps.now();
+ if (remainingMs <= 0) break;
+ await this.waitForRetry(Math.min(CONNECT_RETRY_MS, remainingMs));
+ }
+ }
+ if (this.startupError) {
+ throw this.startupError;
+ }
+ if (this.disposed) {
+ throw new Error('Preview session is closed');
+ }
+ throw new Error('Timed out starting the hidden mpv preview player');
+ }
+
+ private waitForRetry(delayMs: number): Promise {
+ return new Promise((resolve) => {
+ const timeout = this.deps.schedule(() => {
+ if (this.retryWait?.timeout === timeout) this.retryWait = null;
+ resolve();
+ }, delayMs);
+ this.retryWait = { timeout, resolve };
+ });
+ }
+
+ private cancelRetryWait(): void {
+ const pending = this.retryWait;
+ this.retryWait = null;
+ if (!pending) return;
+ this.deps.cancelSchedule(pending.timeout);
+ pending.resolve();
+ }
+
+ private connectOnce(socketPath: string, timeoutMs: number): Promise {
+ return new Promise((resolve, reject) => {
+ let timeout: ReturnType | null = null;
+ let settled = false;
+ const clearAttemptTimeout = (): void => {
+ if (timeout !== null) this.deps.cancelSchedule(timeout);
+ timeout = null;
+ };
+ const socket = this.deps.connectSocket(socketPath);
+ const onConnect = (): void => {
+ if (settled) return;
+ settled = true;
+ clearAttemptTimeout();
+ socket.off('error', onError);
+ socket.on('error', () => {
+ socket.destroy();
+ if (this.socket === socket) this.socket = null;
+ });
+ socket.once('close', () => {
+ if (this.socket === socket) this.socket = null;
+ });
+ resolve(socket);
+ };
+ const onError = (error: Error): void => {
+ if (settled) return;
+ settled = true;
+ clearAttemptTimeout();
+ socket.off('connect', onConnect);
+ socket.on('error', () => {});
+ socket.destroy();
+ reject(error);
+ };
+ socket.once('connect', onConnect);
+ socket.once('error', onError);
+ timeout = this.deps.schedule(() => {
+ if (settled) return;
+ settled = true;
+ timeout = null;
+ socket.off('connect', onConnect);
+ socket.off('error', onError);
+ socket.on('error', () => {});
+ socket.destroy();
+ reject(new Error('Timed out connecting to the hidden mpv preview player'));
+ }, timeoutMs);
+ });
+ }
+}
diff --git a/src/core/services/media-timing-waveform.test.ts b/src/core/services/media-timing-waveform.test.ts
new file mode 100644
index 00000000..3b555eb9
--- /dev/null
+++ b/src/core/services/media-timing-waveform.test.ts
@@ -0,0 +1,125 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import {
+ buildSpeechWaveformArgs,
+ computeWaveformPeaks,
+ generateSpeechWaveform,
+} from './media-timing-waveform';
+
+function pcm(samples: number[]): Buffer {
+ const result = Buffer.alloc(samples.length * 2);
+ samples.forEach((sample, index) => result.writeInt16LE(sample, index * 2));
+ return result;
+}
+
+test('speech waveform maps the selected FFmpeg stream and visible range', () => {
+ const args = buildSpeechWaveformArgs(
+ {
+ mediaPath: '/video/show.mkv',
+ startTime: 8,
+ endTime: 15,
+ audioStreamIndex: 3,
+ },
+ 'center',
+ );
+
+ assert.deepEqual(args.slice(args.indexOf('-ss'), args.indexOf('-t') + 2), [
+ '-ss',
+ '8',
+ '-i',
+ '/video/show.mkv',
+ '-t',
+ '7',
+ ]);
+ assert.deepEqual(args.slice(args.indexOf('-map'), args.indexOf('-map') + 2), ['-map', '0:3']);
+ assert.match(args[args.indexOf('-af') + 1] ?? '', /c0=FC/);
+});
+
+test('speech waveform seeks cached windows by source timestamps', () => {
+ const args = buildSpeechWaveformArgs(
+ {
+ mediaPath: { path: '/tmp/window.mkv', absoluteTimestamps: true, singleResolvedStream: true },
+ startTime: 8,
+ endTime: 15,
+ },
+ 'downmix',
+ );
+
+ assert.deepEqual(args.slice(args.indexOf('-ss'), args.indexOf('-t') + 2), [
+ '-ss',
+ '8',
+ '-seek_timestamp',
+ '1',
+ '-i',
+ '/tmp/window.mkv',
+ '-t',
+ '7',
+ ]);
+ assert.equal(args.includes('-map'), false);
+});
+
+test('waveform levels rise with loudness and top out at the reference level', () => {
+ const peaks = computeWaveformPeaks(pcm([0, 1_000, -2_000, 4_000, -8_000, 16_000]), 3);
+
+ assert.equal(peaks.length, 3);
+ assert.equal(peaks[0], 0);
+ assert.ok((peaks[1] ?? 0) > 0);
+ assert.ok((peaks[1] ?? 0) < (peaks[2] ?? 0));
+ assert.equal(peaks[2], 1);
+});
+
+test('waveform flattens steady background noise and keeps speech bursts tall', () => {
+ // 20 slices of steady noise at a fixed level with an 18 dB louder "speech" burst in the middle.
+ const noise = 1_000;
+ const samples: number[] = [];
+ for (let slice = 0; slice < 20; slice += 1) {
+ const level = slice >= 8 && slice < 12 ? noise * 8 : noise;
+ for (let sample = 0; sample < 50; sample += 1) {
+ samples.push(sample % 2 === 0 ? level : -level);
+ }
+ }
+
+ const peaks = computeWaveformPeaks(pcm(samples), 20);
+
+ for (const [index, peak] of peaks.entries()) {
+ if (index >= 8 && index < 12) assert.equal(peak, 1);
+ else assert.equal(peak, 0);
+ }
+});
+
+test('waveform stays flat when the whole range is a single steady level', () => {
+ const peaks = computeWaveformPeaks(
+ pcm(Array.from({ length: 400 }, (_, i) => (i % 2 ? 900 : -900))),
+ 40,
+ );
+
+ assert.ok(peaks.every((peak) => peak === 0));
+});
+
+test('speech waveform uses a mono downmix when the source has no center activity', async () => {
+ const calls: string[][] = [];
+ const peaks = await generateSpeechWaveform(
+ { mediaPath: '/video/show.mkv', startTime: 0, endTime: 2 },
+ async (args) => {
+ calls.push(args);
+ return calls.length === 1 ? pcm([0, 0, 0, 0]) : pcm([0, 4_000, -8_000, 16_000]);
+ },
+ );
+
+ assert.equal(calls.length, 2);
+ assert.match(calls[1]?.[calls[1].indexOf('-af') + 1] ?? '', /channel_layouts=mono/);
+ assert.equal(Math.max(...peaks), 1);
+});
+
+test('speech waveform keeps an active center channel without doing a second decode', async () => {
+ let calls = 0;
+ await generateSpeechWaveform(
+ { mediaPath: '/video/show.mkv', startTime: 0, endTime: 2 },
+ async () => {
+ calls += 1;
+ return pcm([0, 4_000, -8_000, 16_000]);
+ },
+ );
+
+ assert.equal(calls, 1);
+});
diff --git a/src/core/services/media-timing-waveform.ts b/src/core/services/media-timing-waveform.ts
new file mode 100644
index 00000000..59aa30ad
--- /dev/null
+++ b/src/core/services/media-timing-waveform.ts
@@ -0,0 +1,185 @@
+import { spawn } from 'node:child_process';
+import { normalizeMediaInput, type MediaInput } from '../../media-input';
+
+const WAVEFORM_SAMPLE_RATE = 8_000;
+const WAVEFORM_POINT_COUNT = 480;
+const WAVEFORM_TIMEOUT_MS = 15_000;
+const MAX_WAVEFORM_BYTES = 16 * 1024 * 1024;
+// Keep the band where speech intelligibility lives; bass, drums, and hum sit below it.
+const SPEECH_FILTER = 'highpass=f=250,lowpass=f=3500';
+const NOISE_FLOOR_PERCENTILE = 0.2;
+const REFERENCE_PERCENTILE = 0.95;
+const NOISE_GATE_DB = 3;
+const MIN_DISPLAY_RANGE_DB = 12;
+const SILENCE_DB = -100;
+const CENTER_CHANNEL_FILTER = `pan=mono|c0=FC,${SPEECH_FILTER}`;
+const DOWNMIX_FILTER = `aformat=channel_layouts=mono,${SPEECH_FILTER}`;
+
+export interface SpeechWaveformOptions {
+ mediaPath: MediaInput;
+ startTime: number;
+ endTime: number;
+ audioStreamIndex?: number;
+}
+
+type RunFfmpeg = (args: string[]) => Promise;
+
+export function buildSpeechWaveformArgs(
+ options: SpeechWaveformOptions,
+ mode: 'center' | 'downmix',
+): string[] {
+ const duration = options.endTime - options.startTime;
+ const input = normalizeMediaInput(options.mediaPath);
+ const args = [
+ '-hide_banner',
+ '-nostdin',
+ '-loglevel',
+ 'error',
+ '-ss',
+ String(options.startTime),
+ ...input.inputArgs,
+ '-i',
+ input.path,
+ '-t',
+ String(duration),
+ ];
+ if (
+ options.audioStreamIndex !== undefined &&
+ Number.isInteger(options.audioStreamIndex) &&
+ options.audioStreamIndex >= 0
+ ) {
+ args.push('-map', `0:${options.audioStreamIndex}`);
+ }
+ args.push(
+ '-vn',
+ '-sn',
+ '-dn',
+ '-af',
+ mode === 'center' ? CENTER_CHANNEL_FILTER : DOWNMIX_FILTER,
+ '-ac',
+ '1',
+ '-ar',
+ String(WAVEFORM_SAMPLE_RATE),
+ '-f',
+ 's16le',
+ 'pipe:1',
+ );
+ return args;
+}
+
+function runFfmpeg(args: string[]): Promise {
+ return new Promise((resolve, reject) => {
+ const child = spawn('ffmpeg', args, { stdio: ['ignore', 'pipe', 'pipe'] });
+ const chunks: Buffer[] = [];
+ let byteLength = 0;
+ let stderr = '';
+ let settled = false;
+ const timeout = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ child.kill('SIGKILL');
+ reject(new Error(`FFmpeg waveform analysis timed out after ${WAVEFORM_TIMEOUT_MS}ms`));
+ }, WAVEFORM_TIMEOUT_MS);
+
+ const settle = (callback: () => void): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeout);
+ callback();
+ };
+
+ child.stdout.on('data', (chunk: Buffer) => {
+ if (settled) return;
+ byteLength += chunk.byteLength;
+ if (byteLength > MAX_WAVEFORM_BYTES) {
+ settle(() => {
+ child.kill('SIGKILL');
+ reject(new Error('The visible waveform range is too large to analyze.'));
+ });
+ return;
+ }
+ chunks.push(chunk);
+ });
+ child.stderr.setEncoding('utf8');
+ child.stderr.on('data', (chunk) => {
+ if (stderr.length < 4_000) stderr += String(chunk);
+ });
+ child.once('error', (error) => settle(() => reject(error)));
+ child.once('close', (code) => {
+ settle(() => {
+ if (code === 0) {
+ resolve(Buffer.concat(chunks, byteLength));
+ return;
+ }
+ reject(new Error(stderr.trim() || `FFmpeg exited with status ${code ?? 'unknown'}`));
+ });
+ });
+ });
+}
+
+function percentile(sortedValues: number[], fraction: number): number {
+ const index = Math.min(sortedValues.length - 1, Math.floor(sortedValues.length * fraction));
+ return sortedValues[index] ?? SILENCE_DB;
+}
+
+/**
+ * Turns mono PCM into 0..1 display heights. Each point is the RMS level of its slice in
+ * dB, measured against the clip's own noise floor (a low percentile of the slices), so
+ * constant background noise draws flat and sustained speech stands out. Peak sampling
+ * would instead follow music transients and lift the floor to nearly speech height.
+ */
+export function computeWaveformPeaks(pcm: Buffer, pointCount = WAVEFORM_POINT_COUNT): number[] {
+ const sampleCount = Math.floor(pcm.byteLength / 2);
+ if (sampleCount === 0 || pointCount <= 0) return [];
+ const resolvedPointCount = Math.min(pointCount, sampleCount);
+ const levelsDb = Array.from({ length: resolvedPointCount }, () => SILENCE_DB);
+
+ for (let point = 0; point < resolvedPointCount; point += 1) {
+ const sampleStart = Math.floor((point * sampleCount) / resolvedPointCount);
+ const sampleEnd = Math.max(
+ sampleStart + 1,
+ Math.floor(((point + 1) * sampleCount) / resolvedPointCount),
+ );
+ let energy = 0;
+ for (let sample = sampleStart; sample < sampleEnd; sample += 1) {
+ const value = pcm.readInt16LE(sample * 2) / 32_768;
+ energy += value * value;
+ }
+ const rms = Math.sqrt(energy / (sampleEnd - sampleStart));
+ levelsDb[point] = rms > 0 ? Math.max(SILENCE_DB, 20 * Math.log10(rms)) : SILENCE_DB;
+ }
+
+ const sortedLevels = [...levelsDb].sort((left, right) => left - right);
+ const floorDb = percentile(sortedLevels, NOISE_FLOOR_PERCENTILE) + NOISE_GATE_DB;
+ const referenceDb = Math.max(
+ percentile(sortedLevels, REFERENCE_PERCENTILE),
+ floorDb + MIN_DISPLAY_RANGE_DB,
+ );
+ return levelsDb.map(
+ (levelDb) =>
+ Math.round(Math.min(1, Math.max(0, (levelDb - floorDb) / (referenceDb - floorDb))) * 1_000) /
+ 1_000,
+ );
+}
+
+function hasAudibleSamples(pcm: Buffer): boolean {
+ for (let offset = 0; offset + 1 < pcm.byteLength; offset += 2) {
+ if (Math.abs(pcm.readInt16LE(offset)) >= 164) return true;
+ }
+ return false;
+}
+
+export async function generateSpeechWaveform(
+ options: SpeechWaveformOptions,
+ execute: RunFfmpeg = runFfmpeg,
+): Promise {
+ try {
+ const centerPcm = await execute(buildSpeechWaveformArgs(options, 'center'));
+ if (hasAudibleSamples(centerPcm)) return computeWaveformPeaks(centerPcm);
+ } catch {
+ // Sources without a named center channel can reject the center-only filter.
+ }
+
+ const downmixPcm = await execute(buildSpeechWaveformArgs(options, 'downmix'));
+ return computeWaveformPeaks(downmixPcm);
+}
diff --git a/src/core/services/overlay-shortcut-handler.test.ts b/src/core/services/overlay-shortcut-handler.test.ts
index f6fff56e..2c4dc06e 100644
--- a/src/core/services/overlay-shortcut-handler.test.ts
+++ b/src/core/services/overlay-shortcut-handler.test.ts
@@ -29,6 +29,7 @@ function makeShortcuts(overrides: Partial = {}): Configured
openRuntimeOptions: null,
openJimaku: null,
openTsukihime: null,
+ openSubtitleGeneration: null,
openSessionHelp: null,
openControllerSelect: null,
openControllerDebug: null,
diff --git a/src/core/services/overlay-shortcut.test.ts b/src/core/services/overlay-shortcut.test.ts
index 8daa1867..7f3d6299 100644
--- a/src/core/services/overlay-shortcut.test.ts
+++ b/src/core/services/overlay-shortcut.test.ts
@@ -24,6 +24,7 @@ function createShortcuts(overrides: Partial = {}): Configur
openRuntimeOptions: null,
openJimaku: null,
openTsukihime: null,
+ openSubtitleGeneration: null,
openSessionHelp: null,
openControllerSelect: null,
openControllerDebug: null,
diff --git a/src/core/services/overlay-window-input.ts b/src/core/services/overlay-window-input.ts
index e39ecee4..5f783701 100644
--- a/src/core/services/overlay-window-input.ts
+++ b/src/core/services/overlay-window-input.ts
@@ -37,6 +37,15 @@ export function handleOverlayWindowBeforeInputEvent(options: {
if (options.kind === 'modal') return false;
if (!options.windowVisible) return false;
+ // The renderer decides whether Copy targets selected sidebar text or the live cue.
+ if (
+ (options.input.control || options.input.meta) &&
+ !options.input.alt &&
+ !options.input.shift &&
+ (options.input.code === 'KeyC' || options.input.key.toLowerCase() === 'c')
+ )
+ return false;
+
if (isKeyboardModeToggleInput(options.input)) {
options.preventDefault();
options.sendKeyboardModeToggleRequested();
diff --git a/src/core/services/overlay-window.test.ts b/src/core/services/overlay-window.test.ts
index 04650cec..b633439f 100644
--- a/src/core/services/overlay-window.test.ts
+++ b/src/core/services/overlay-window.test.ts
@@ -90,6 +90,35 @@ test('handleOverlayWindowBeforeInputEvent leaves modal Tab handling alone', () =
assert.deepEqual(calls, []);
});
+test('native Copy reaches the renderer before the current-subtitle fallback', () => {
+ for (const modifier of [{ control: true }, { meta: true }]) {
+ const handled = handleOverlayWindowBeforeInputEvent({
+ kind: 'visible',
+ windowVisible: true,
+ input: {
+ type: 'keyDown',
+ key: 'c',
+ code: 'KeyC',
+ isAutoRepeat: false,
+ isComposing: false,
+ shift: false,
+ control: false,
+ alt: false,
+ meta: false,
+ location: 0,
+ modifiers: [],
+ ...modifier,
+ },
+ preventDefault: () => assert.fail('Copy must reach Chromium'),
+ sendKeyboardModeToggleRequested: () => assert.fail('Unexpected mode toggle'),
+ sendLookupWindowToggleRequested: () => assert.fail('Unexpected lookup toggle'),
+ tryHandleOverlayShortcutLocalFallback: () => assert.fail('Renderer owns Copy'),
+ forwardTabToMpv: () => assert.fail('Unexpected mpv input'),
+ });
+ assert.equal(handled, false);
+ }
+});
+
test('handleOverlayWindowBlurred skips visible overlay restacking after manual hide', () => {
const calls: string[] = [];
diff --git a/src/core/services/remote-media-window-cache.test.ts b/src/core/services/remote-media-window-cache.test.ts
new file mode 100644
index 00000000..836ca149
--- /dev/null
+++ b/src/core/services/remote-media-window-cache.test.ts
@@ -0,0 +1,253 @@
+import assert from 'node:assert/strict';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import test from 'node:test';
+import {
+ buildRemoteMediaWindowArgs,
+ RemoteMediaWindowCache,
+ REMOTE_MEDIA_WINDOW_MAX_SECONDS,
+ type RemoteMediaWindowCacheOptions,
+} from './remote-media-window-cache';
+
+const SOURCE = {
+ path: 'https://jellyfin.example/Videos/abc/stream?static=true',
+ audioStreamIndex: 2,
+};
+
+type ExecFileStub = NonNullable;
+
+function createStub(options: { fail?: boolean; empty?: boolean; defer?: boolean } = {}) {
+ const calls: string[][] = [];
+ const pendingCallbacks: Array<() => void> = [];
+ const execFile: ExecFileStub = (_file, args, _options, callback) => {
+ calls.push([...args]);
+ const finish = (): void => {
+ const outputPath = args.at(-1);
+ assert.ok(outputPath);
+ if (options.fail) {
+ callback(Object.assign(new Error('boom'), { code: 1 }));
+ return;
+ }
+ if (!options.empty) {
+ fs.writeFileSync(outputPath, 'mkv', 'utf8');
+ }
+ callback(null);
+ };
+ if (options.defer) {
+ pendingCallbacks.push(finish);
+ } else {
+ queueMicrotask(finish);
+ }
+ };
+ return {
+ calls,
+ execFile,
+ flush: () => {
+ for (const finish of pendingCallbacks.splice(0)) finish();
+ },
+ };
+}
+
+async function withCache(
+ stubOptions: Parameters[0],
+ cacheOptions: Omit,
+ run: (cache: RemoteMediaWindowCache, stub: ReturnType) => Promise,
+): Promise {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-media-window-test-'));
+ const stub = createStub(stubOptions);
+ const cache = new RemoteMediaWindowCache({
+ tempDir,
+ execFile: stub.execFile,
+ idleTtlMs: 0,
+ logDebug: () => undefined,
+ ...cacheOptions,
+ });
+ try {
+ await run(cache, stub);
+ } finally {
+ cache.cleanup();
+ fs.rmSync(tempDir, { recursive: true, force: true });
+ }
+}
+
+function argValue(args: string[], flag: string): string | undefined {
+ const index = args.indexOf(flag);
+ return index === -1 ? undefined : args[index + 1];
+}
+
+test('buildRemoteMediaWindowArgs stream-copies the window with source timestamps intact', () => {
+ const args = buildRemoteMediaWindowArgs(
+ { ...SOURCE, inputOptions: { reconnect: true, headers: { Referer: 'https://a.example/' } } },
+ { startTime: 22.75, endTime: 33 },
+ '/tmp/window.mkv',
+ );
+
+ const inputIndex = args.indexOf('-i');
+ assert.equal(args[inputIndex + 1], SOURCE.path);
+ assert.ok(args.indexOf('-reconnect') < inputIndex);
+ assert.ok(args.indexOf('-headers') < inputIndex);
+ assert.equal(argValue(args, '-ss'), '22.75');
+ assert.equal(argValue(args, '-t'), '10.25');
+ assert.ok(args.indexOf('-t') < inputIndex);
+ assert.deepEqual(args.slice(args.indexOf('-map'), args.indexOf('-map') + 4), [
+ '-map',
+ '0:v:0?',
+ '-map',
+ '0:2',
+ ]);
+ assert.equal(argValue(args, '-c'), 'copy');
+ assert.ok(args.includes('-copyts'));
+ assert.ok(args.includes('-start_at_zero'));
+ assert.equal(argValue(args, '-f'), 'matroska');
+ assert.equal(args.at(-1), '/tmp/window.mkv');
+});
+
+test('buildRemoteMediaWindowArgs keeps every audio stream when none is selected', () => {
+ const args = buildRemoteMediaWindowArgs(
+ { path: SOURCE.path, audioStreamIndex: null },
+ { startTime: 0, endTime: 5 },
+ '/tmp/window.mkv',
+ );
+
+ assert.equal(args[args.lastIndexOf('-map') + 1], '0:a');
+});
+
+test('acquire downloads once and reuses the window for covered ranges', async () => {
+ await withCache({}, {}, async (cache, stub) => {
+ const window = await cache.acquire(SOURCE, { startTime: 10, endTime: 14 });
+
+ assert.equal(stub.calls.length, 1);
+ assert.equal(argValue(stub.calls[0]!, '-ss'), '9.75');
+ assert.equal(argValue(stub.calls[0]!, '-t'), '5.25');
+ assert.equal(window.startTime, 9.75);
+ assert.equal(window.endTime, 15);
+ assert.equal(window.audioStreamIndex, 2);
+ assert.ok(fs.existsSync(window.path));
+ assert.deepEqual(window.media, {
+ path: window.path,
+ source: 'remote-window',
+ singleResolvedStream: true,
+ absoluteTimestamps: true,
+ });
+
+ assert.equal(await cache.acquire(SOURCE, { startTime: 11, endTime: 15 }), window);
+ assert.equal(await cache.lookup(SOURCE, { startTime: 12, endTime: 12 }), window);
+ assert.equal(
+ await cache.lookup(
+ { path: SOURCE.path, audioStreamIndex: null },
+ { startTime: 12, endTime: 13 },
+ ),
+ window,
+ );
+ assert.equal(stub.calls.length, 1);
+ });
+});
+
+test('lookup never downloads and misses on other ranges, sources, or audio streams', async () => {
+ await withCache({}, {}, async (cache, stub) => {
+ assert.equal(await cache.lookup(SOURCE, { startTime: 10, endTime: 14 }), null);
+ assert.equal(stub.calls.length, 0);
+
+ await cache.acquire(SOURCE, { startTime: 10, endTime: 14 });
+ assert.equal(await cache.lookup(SOURCE, { startTime: 14, endTime: 16 }), null);
+ assert.equal(
+ await cache.lookup(
+ { path: 'https://other.example/stream', audioStreamIndex: 2 },
+ {
+ startTime: 11,
+ endTime: 12,
+ },
+ ),
+ null,
+ );
+ assert.equal(
+ await cache.lookup(
+ { path: SOURCE.path, audioStreamIndex: 3 },
+ { startTime: 11, endTime: 12 },
+ ),
+ null,
+ );
+ assert.equal(stub.calls.length, 1);
+ });
+});
+
+test('acquire widens to the union of the old window and replaces the old file', async () => {
+ await withCache({}, {}, async (cache, stub) => {
+ const first = await cache.acquire(SOURCE, { startTime: 10, endTime: 14 });
+ const second = await cache.acquire(SOURCE, { startTime: 8, endTime: 12 });
+
+ assert.equal(stub.calls.length, 2);
+ assert.equal(argValue(stub.calls[1]!, '-ss'), '7.75');
+ assert.equal(second.startTime, 7.75);
+ assert.equal(second.endTime, 15);
+ assert.notEqual(second.path, first.path);
+ assert.equal(fs.existsSync(first.path), false);
+ assert.ok(fs.existsSync(second.path));
+ assert.equal(cache.currentWindow, second);
+ });
+});
+
+test('acquire shares an in-flight download between concurrent callers', async () => {
+ await withCache({ defer: true }, {}, async (cache, stub) => {
+ const first = cache.acquire(SOURCE, { startTime: 10, endTime: 14 });
+ await Promise.resolve();
+ const second = cache.acquire(SOURCE, { startTime: 11, endTime: 13 });
+ const lookup = cache.lookup(SOURCE, { startTime: 12, endTime: 12 });
+ await Promise.resolve();
+ assert.equal(stub.calls.length, 1);
+
+ stub.flush();
+ const [a, b, c] = await Promise.all([first, second, lookup]);
+ assert.equal(a, b);
+ assert.equal(a, c);
+ assert.equal(stub.calls.length, 1);
+ });
+});
+
+test('acquire rejects on ffmpeg failure, leaves no file, and can retry', async () => {
+ await withCache({ fail: true }, {}, async (cache, stub) => {
+ await assert.rejects(
+ cache.acquire(SOURCE, { startTime: 10, endTime: 14 }),
+ /FFmpeg media window failed: boom/,
+ );
+ assert.equal(cache.currentWindow, null);
+ assert.equal(await cache.lookup(SOURCE, { startTime: 10, endTime: 14 }), null);
+
+ await assert.rejects(cache.acquire(SOURCE, { startTime: 10, endTime: 14 }));
+ assert.equal(stub.calls.length, 2);
+ });
+ await withCache({ empty: true }, {}, async (cache) => {
+ await assert.rejects(
+ cache.acquire(SOURCE, { startTime: 10, endTime: 14 }),
+ /exited without creating a media window/,
+ );
+ });
+});
+
+test('acquire refuses invalid and oversized ranges without spawning ffmpeg', async () => {
+ await withCache({}, {}, async (cache, stub) => {
+ await assert.rejects(cache.acquire(SOURCE, { startTime: 10, endTime: 10 }), /invalid/);
+ await assert.rejects(cache.acquire(SOURCE, { startTime: -1, endTime: 10 }), /invalid/);
+ await assert.rejects(
+ cache.acquire(SOURCE, { startTime: 0, endTime: REMOTE_MEDIA_WINDOW_MAX_SECONDS + 1 }),
+ /too long/,
+ );
+ assert.equal(stub.calls.length, 0);
+ });
+});
+
+test('the window is deleted after the idle timeout and on cleanup', async () => {
+ await withCache({}, { idleTtlMs: 20 }, async (cache) => {
+ const window = await cache.acquire(SOURCE, { startTime: 10, endTime: 14 });
+ await new Promise((resolve) => setTimeout(resolve, 60));
+
+ assert.equal(cache.currentWindow, null);
+ assert.equal(fs.existsSync(window.path), false);
+
+ const again = await cache.acquire(SOURCE, { startTime: 10, endTime: 14 });
+ cache.cleanup();
+ assert.equal(fs.existsSync(again.path), false);
+ assert.equal(fs.existsSync(path.dirname(again.path)), false);
+ });
+});
diff --git a/src/core/services/remote-media-window-cache.ts b/src/core/services/remote-media-window-cache.ts
new file mode 100644
index 00000000..ca486a66
--- /dev/null
+++ b/src/core/services/remote-media-window-cache.ts
@@ -0,0 +1,377 @@
+import { execFile as nodeExecFile, type ExecFileException } from 'child_process';
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { createLogger } from '../../logger';
+import { normalizeMediaInput, type MediaInput, type MediaInputOptions } from '../../media-input';
+
+const log = createLogger('media-window');
+
+export const REMOTE_MEDIA_WINDOW_TIMEOUT_MS = 120_000;
+export const REMOTE_MEDIA_WINDOW_MAX_SECONDS = 180;
+const HEAD_SLACK_SECONDS = 0.25;
+const TAIL_SLACK_SECONDS = 1;
+const DEFAULT_IDLE_TTL_MS = 10 * 60_000;
+const COVERAGE_EPSILON_SECONDS = 0.01;
+
+export interface RemoteMediaWindowSource {
+ path: string;
+ inputOptions?: MediaInputOptions;
+ /** FFmpeg stream index to keep; `null`/undefined keeps every audio stream. */
+ audioStreamIndex?: number | null;
+}
+
+export interface RemoteMediaWindowRange {
+ startTime: number;
+ endTime: number;
+}
+
+export interface RemoteMediaWindow {
+ path: string;
+ startTime: number;
+ endTime: number;
+ sourcePath: string;
+ audioStreamIndex: number | null;
+ /** Input descriptor for FFmpeg reads; timestamps stay absolute so callers keep source times. */
+ media: MediaInput;
+}
+
+type WindowExecFile = (
+ file: string,
+ args: readonly string[],
+ options: { timeout: number },
+ callback: (error: ExecFileException | null) => void,
+) => void;
+
+export interface RemoteMediaWindowCacheOptions {
+ tempDir?: string;
+ execFile?: WindowExecFile;
+ idleTtlMs?: number;
+ logDebug?: (message: string) => void;
+}
+
+interface PendingFetch extends RemoteMediaWindowRange {
+ sourcePath: string;
+ audioStreamIndex: number | null;
+ promise: Promise;
+}
+
+export function isRemoteMediaWindowSourcePath(value: string): boolean {
+ return /^https?:\/\//i.test(value.trim());
+}
+
+function describeSourceForDebugLog(sourcePath: string): string {
+ try {
+ return `remote:${new URL(sourcePath).hostname.toLowerCase() || 'unknown'}`;
+ } catch {
+ return 'remote:unknown';
+ }
+}
+
+function isUsableRange(range: RemoteMediaWindowRange, allowEmpty: boolean): boolean {
+ return (
+ Number.isFinite(range.startTime) &&
+ Number.isFinite(range.endTime) &&
+ range.startTime >= 0 &&
+ (allowEmpty ? range.endTime >= range.startTime : range.endTime > range.startTime)
+ );
+}
+
+function audioStreamMatches(
+ windowIndex: number | null,
+ requested: number | null | undefined,
+): boolean {
+ return requested == null || windowIndex === requested;
+}
+
+function covers(
+ candidate: RemoteMediaWindowRange & { sourcePath: string; audioStreamIndex: number | null },
+ source: RemoteMediaWindowSource,
+ range: RemoteMediaWindowRange,
+): boolean {
+ return (
+ candidate.sourcePath === source.path &&
+ audioStreamMatches(candidate.audioStreamIndex, source.audioStreamIndex) &&
+ candidate.startTime <= range.startTime + COVERAGE_EPSILON_SECONDS &&
+ candidate.endTime >= range.endTime - COVERAGE_EPSILON_SECONDS
+ );
+}
+
+/**
+ * Stream-copies `[startTime, endTime]` of a remote source into a local Matroska file.
+ * `-copyts -start_at_zero` keeps the source timestamps, so later reads seek with the
+ * original times via `-seek_timestamp 1` (see `MediaInput.absoluteTimestamps`).
+ */
+export function buildRemoteMediaWindowArgs(
+ source: RemoteMediaWindowSource,
+ range: RemoteMediaWindowRange,
+ outputPath: string,
+): string[] {
+ const input = normalizeMediaInput({ path: source.path, inputOptions: source.inputOptions });
+ const audioMap =
+ typeof source.audioStreamIndex === 'number' && Number.isInteger(source.audioStreamIndex)
+ ? `0:${source.audioStreamIndex}`
+ : '0:a';
+ return [
+ '-hide_banner',
+ '-nostdin',
+ '-loglevel',
+ 'error',
+ '-ss',
+ String(range.startTime),
+ '-t',
+ String(range.endTime - range.startTime),
+ ...input.inputArgs,
+ '-i',
+ input.path,
+ '-map',
+ '0:v:0?',
+ '-map',
+ audioMap,
+ '-c',
+ 'copy',
+ '-sn',
+ '-dn',
+ '-copyts',
+ '-start_at_zero',
+ '-f',
+ 'matroska',
+ '-y',
+ outputPath,
+ ];
+}
+
+/**
+ * Holds one downloaded window of the current remote stream so the timing review,
+ * audio extraction, and screenshot all read the same local bytes instead of each
+ * re-fetching the clip over HTTP. A new window replaces the old one; the file is
+ * deleted after `idleTtlMs` without use, on `clear()`, or on `cleanup()`.
+ */
+export class RemoteMediaWindowCache {
+ private readonly tempDir: string;
+ private readonly execFile: WindowExecFile;
+ private readonly idleTtlMs: number;
+ private readonly logDebug: (message: string) => void;
+ private current: RemoteMediaWindow | null = null;
+ private pending: PendingFetch | null = null;
+ private idleTimer: ReturnType | null = null;
+ private sequence = 0;
+
+ constructor(options: RemoteMediaWindowCacheOptions = {}) {
+ this.tempDir = options.tempDir ?? path.join(os.tmpdir(), 'subminer-media-windows');
+ this.execFile = options.execFile ?? nodeExecFile;
+ this.idleTtlMs = options.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
+ this.logDebug = options.logDebug ?? ((message) => log.debug(message));
+ }
+
+ get currentWindow(): RemoteMediaWindow | null {
+ return this.current;
+ }
+
+ /** Returns a ready or in-flight window covering the range; never starts a download. */
+ async lookup(
+ source: RemoteMediaWindowSource,
+ range: RemoteMediaWindowRange,
+ ): Promise {
+ if (!isUsableRange(range, true)) return null;
+ if (this.current && covers(this.current, source, range)) {
+ this.touch();
+ return this.current;
+ }
+ const pending = this.pending;
+ if (pending && covers(pending, source, range)) {
+ try {
+ const window = await pending.promise;
+ this.touch();
+ return window;
+ } catch {
+ return null;
+ }
+ }
+ return null;
+ }
+
+ /** Returns a window covering the range, downloading (and widening) one when needed. */
+ async acquire(
+ source: RemoteMediaWindowSource,
+ range: RemoteMediaWindowRange,
+ ): Promise {
+ if (!isUsableRange(range, false)) {
+ throw new Error('Media window range is invalid.');
+ }
+ if (range.endTime - range.startTime > REMOTE_MEDIA_WINDOW_MAX_SECONDS) {
+ throw new Error('Media window range is too long to download.');
+ }
+
+ for (;;) {
+ const hit = await this.lookup(source, range);
+ if (hit) return hit;
+ const pending = this.pending;
+ if (!pending) break;
+ // Another caller is already downloading; wait for it, then re-check coverage.
+ await pending.promise.catch(() => null);
+ }
+
+ return this.fetch(source, this.planFetchRange(source, range));
+ }
+
+ clear(): void {
+ this.cancelIdleTimer();
+ const current = this.current;
+ this.current = null;
+ if (current) this.removeFile(current.path);
+ }
+
+ cleanup(): void {
+ this.clear();
+ try {
+ fs.rmSync(this.tempDir, { recursive: true, force: true });
+ } catch (error) {
+ log.error('Failed to cleanup media window directory:', error);
+ }
+ }
+
+ private planFetchRange(
+ source: RemoteMediaWindowSource,
+ range: RemoteMediaWindowRange,
+ ): RemoteMediaWindowRange {
+ let startTime = Math.max(0, range.startTime - HEAD_SLACK_SECONDS);
+ let endTime = range.endTime + TAIL_SLACK_SECONDS;
+ const current = this.current;
+ if (
+ current &&
+ current.sourcePath === source.path &&
+ audioStreamMatches(current.audioStreamIndex, source.audioStreamIndex)
+ ) {
+ // Keep what was already downloaded when the review timeline grows in one direction.
+ const unionStart = Math.min(startTime, current.startTime);
+ const unionEnd = Math.max(endTime, current.endTime);
+ if (unionEnd - unionStart <= REMOTE_MEDIA_WINDOW_MAX_SECONDS) {
+ startTime = unionStart;
+ endTime = unionEnd;
+ }
+ }
+ return { startTime, endTime };
+ }
+
+ private fetch(
+ source: RemoteMediaWindowSource,
+ range: RemoteMediaWindowRange,
+ ): Promise {
+ fs.mkdirSync(this.tempDir, { recursive: true });
+ this.sequence += 1;
+ const outputPath = path.join(this.tempDir, `window_${Date.now()}_${this.sequence}.mkv`);
+ const audioStreamIndex =
+ typeof source.audioStreamIndex === 'number' ? source.audioStreamIndex : null;
+ const description = describeSourceForDebugLog(source.path);
+ const startedAt = Date.now();
+ this.logDebug(
+ `[media-window] fetch start ${description} start=${range.startTime} end=${range.endTime} audioStream=${audioStreamIndex ?? 'all'}`,
+ );
+
+ const promise = new Promise((resolve, reject) => {
+ this.execFile(
+ 'ffmpeg',
+ buildRemoteMediaWindowArgs(source, range, outputPath),
+ { timeout: REMOTE_MEDIA_WINDOW_TIMEOUT_MS },
+ (error) => {
+ const elapsedMs = Math.max(0, Date.now() - startedAt);
+ const size = error ? 0 : this.fileSize(outputPath);
+ if (error || size === 0) {
+ this.removeFile(outputPath);
+ const reason = error
+ ? error.code === 'ENOENT'
+ ? 'FFmpeg not found. Install FFmpeg to enable media generation.'
+ : `FFmpeg media window failed: ${error.message}`
+ : 'FFmpeg exited without creating a media window.';
+ this.logDebug(`[media-window] fetch failed ${description} elapsedMs=${elapsedMs}`);
+ reject(new Error(reason));
+ return;
+ }
+ const window: RemoteMediaWindow = {
+ path: outputPath,
+ startTime: range.startTime,
+ endTime: range.endTime,
+ sourcePath: source.path,
+ audioStreamIndex,
+ media: {
+ path: outputPath,
+ source: 'remote-window',
+ singleResolvedStream: true,
+ absoluteTimestamps: true,
+ },
+ };
+ this.logDebug(
+ `[media-window] fetch complete ${description} elapsedMs=${elapsedMs} bytes=${size}`,
+ );
+ this.replaceCurrent(window);
+ resolve(window);
+ },
+ );
+ });
+
+ const pending: PendingFetch = {
+ sourcePath: source.path,
+ audioStreamIndex,
+ startTime: range.startTime,
+ endTime: range.endTime,
+ promise,
+ };
+ this.pending = pending;
+ promise
+ .catch(() => undefined)
+ .then(() => {
+ if (this.pending === pending) this.pending = null;
+ });
+ return promise;
+ }
+
+ private replaceCurrent(window: RemoteMediaWindow): void {
+ const previous = this.current;
+ this.current = window;
+ if (previous && previous.path !== window.path) this.removeFile(previous.path);
+ this.touch();
+ }
+
+ private touch(): void {
+ this.cancelIdleTimer();
+ if (this.idleTtlMs <= 0 || !this.current) return;
+ const timer = setTimeout(() => {
+ if (this.idleTimer === timer) this.idleTimer = null;
+ this.clear();
+ }, this.idleTtlMs);
+ timer.unref?.();
+ this.idleTimer = timer;
+ }
+
+ private cancelIdleTimer(): void {
+ if (this.idleTimer) clearTimeout(this.idleTimer);
+ this.idleTimer = null;
+ }
+
+ private fileSize(filePath: string): number {
+ try {
+ return fs.statSync(filePath).size;
+ } catch {
+ return 0;
+ }
+ }
+
+ private removeFile(filePath: string): void {
+ try {
+ fs.unlinkSync(filePath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ log.debug(`Failed to remove media window ${filePath}:`, (error as Error).message);
+ }
+ }
+ }
+}
+
+let sharedCache: RemoteMediaWindowCache | null = null;
+
+/** Process-wide cache so the review modal and card media generation share one download. */
+export function getSharedRemoteMediaWindowCache(): RemoteMediaWindowCache {
+ sharedCache ??= new RemoteMediaWindowCache();
+ return sharedCache;
+}
diff --git a/src/core/services/session-actions.test.ts b/src/core/services/session-actions.test.ts
index 31386449..c260accf 100644
--- a/src/core/services/session-actions.test.ts
+++ b/src/core/services/session-actions.test.ts
@@ -41,6 +41,7 @@ function createDeps(overrides: Partial = {}) {
openControllerDebug: () => calls.push('controller-debug'),
openJimaku: () => calls.push('jimaku'),
openTsukihime: () => calls.push('tsukihime'),
+ openSubtitleGeneration: () => calls.push('subtitle-generation'),
openYoutubeTrackPicker: () => {
calls.push('youtube');
},
@@ -88,3 +89,9 @@ test('dispatchSessionAction opens the character dictionary manager', async () =>
assert.deepEqual(calls, ['character-dictionary-manager']);
});
+
+test('dispatchSessionAction opens subtitle generation without opening the sidebar', async () => {
+ const { calls, deps } = createDeps();
+ await dispatchSessionAction({ actionId: 'openSubtitleGeneration' }, deps);
+ assert.deepEqual(calls, ['subtitle-generation']);
+});
diff --git a/src/core/services/session-actions.ts b/src/core/services/session-actions.ts
index ed61e068..58574766 100644
--- a/src/core/services/session-actions.ts
+++ b/src/core/services/session-actions.ts
@@ -25,6 +25,7 @@ export interface SessionActionExecutorDeps {
openControllerDebug: () => void;
openJimaku: () => void;
openTsukihime: () => void;
+ openSubtitleGeneration: () => void;
openYoutubeTrackPicker: () => void | Promise;
openPlaylistBrowser: () => boolean | void | Promise;
openAnimeBrowser: () => boolean | void | Promise;
@@ -120,6 +121,9 @@ export async function dispatchSessionAction(
case 'openTsukihime':
deps.openTsukihime();
return;
+ case 'openSubtitleGeneration':
+ deps.openSubtitleGeneration();
+ return;
case 'openYoutubePicker':
await deps.openYoutubeTrackPicker();
return;
diff --git a/src/core/services/session-bindings.test.ts b/src/core/services/session-bindings.test.ts
index ece03ec7..1452b2bb 100644
--- a/src/core/services/session-bindings.test.ts
+++ b/src/core/services/session-bindings.test.ts
@@ -5,6 +5,7 @@ import type { ConfiguredShortcuts } from '../utils/shortcut-config';
import { DEFAULT_CONFIG, DEFAULT_KEYBINDINGS, SPECIAL_COMMANDS } from '../../config/definitions';
import { resolveConfiguredShortcuts } from '../utils/shortcut-config';
import { buildPluginSessionBindingsArtifact, compileSessionBindings } from './session-bindings';
+import { parseSessionActionDispatchRequest } from '../../shared/ipc/validators';
function createShortcuts(overrides: Partial = {}): ConfiguredShortcuts {
return {
@@ -23,6 +24,7 @@ function createShortcuts(overrides: Partial = {}): Configur
openRuntimeOptions: null,
openJimaku: null,
openTsukihime: null,
+ openSubtitleGeneration: null,
openSessionHelp: null,
openControllerSelect: null,
openControllerDebug: null,
@@ -37,6 +39,50 @@ function createKeybinding(key: string, command: Keybinding['command']): Keybindi
return { key, command };
}
+test('subtitle generation shortcut compiles for overlay and mpv without conflicting with field grouping', () => {
+ for (const platform of ['linux', 'darwin', 'win32'] as const) {
+ const result = compileSessionBindings({
+ shortcuts: resolveConfiguredShortcuts(DEFAULT_CONFIG, DEFAULT_CONFIG),
+ keybindings: DEFAULT_KEYBINDINGS,
+ platform,
+ });
+ const binding = result.bindings.find(
+ (entry) =>
+ entry.actionType === 'session-action' && entry.actionId === 'openSubtitleGeneration',
+ );
+ assert.ok(binding);
+ assert.deepEqual(binding.key, { code: 'KeyG', modifiers: ['ctrl', 'shift'] });
+ assert.equal(
+ result.warnings.some(
+ (warning) =>
+ warning.path === 'shortcuts.openSubtitleGeneration' ||
+ warning.conflictingPaths?.includes('shortcuts.openSubtitleGeneration'),
+ ),
+ false,
+ );
+ assert.ok(
+ result.bindings.some(
+ (entry) =>
+ entry.actionType === 'session-action' && entry.actionId === 'triggerFieldGrouping',
+ ),
+ );
+ const artifact = buildPluginSessionBindingsArtifact({
+ bindings: [binding],
+ warnings: [],
+ numericSelectionTimeoutMs: 3000,
+ });
+ const pluginBinding = artifact.bindings[0];
+ assert.ok(pluginBinding?.actionType === 'session-action');
+ assert.deepEqual(pluginBinding.cliArgs, [
+ '--session-action',
+ '{"actionId":"openSubtitleGeneration"}',
+ ]);
+ assert.deepEqual(parseSessionActionDispatchRequest({ actionId: 'openSubtitleGeneration' }), {
+ actionId: 'openSubtitleGeneration',
+ });
+ }
+});
+
test('compileSessionBindings merges shortcuts and keybindings into one canonical list', () => {
const result = compileSessionBindings({
shortcuts: createShortcuts({
diff --git a/src/core/services/session-bindings.ts b/src/core/services/session-bindings.ts
index 8ec08a81..eb90d01e 100644
--- a/src/core/services/session-bindings.ts
+++ b/src/core/services/session-bindings.ts
@@ -56,6 +56,7 @@ const SESSION_SHORTCUT_ACTIONS: Array<{
{ key: 'openRuntimeOptions', actionId: 'openRuntimeOptions' },
{ key: 'openJimaku', actionId: 'openJimaku' },
{ key: 'openTsukihime', actionId: 'openTsukihime' },
+ { key: 'openSubtitleGeneration', actionId: 'openSubtitleGeneration' },
{ key: 'openSessionHelp', actionId: 'openSessionHelp' },
{ key: 'openControllerSelect', actionId: 'openControllerSelect' },
{ key: 'openControllerDebug', actionId: 'openControllerDebug' },
@@ -211,7 +212,7 @@ function parseAccelerator(
};
}
-function parseDomKeyString(
+export function parseSessionBindingKey(
key: string,
platform: PlatformKeyModel,
): { key: SessionKeySpec | null; message?: string } {
@@ -439,7 +440,7 @@ export function compileSessionBindings(input: CompileSessionBindingsInput): {
}
if (statsToggleKey) {
- const parsed = parseDomKeyString(statsToggleKey, input.platform);
+ const parsed = parseSessionBindingKey(statsToggleKey, input.platform);
if (!parsed.key) {
warnings.push({
kind: 'unsupported',
@@ -466,7 +467,7 @@ export function compileSessionBindings(input: CompileSessionBindingsInput): {
}
if (statsMarkWatchedKey) {
- const parsed = parseDomKeyString(statsMarkWatchedKey, input.platform);
+ const parsed = parseSessionBindingKey(statsMarkWatchedKey, input.platform);
if (!parsed.key) {
warnings.push({
kind: 'unsupported',
@@ -494,7 +495,7 @@ export function compileSessionBindings(input: CompileSessionBindingsInput): {
input.keybindings.forEach((binding, index) => {
if (!binding.command) return;
- const parsed = parseDomKeyString(binding.key, input.platform);
+ const parsed = parseSessionBindingKey(binding.key, input.platform);
if (!parsed.key) {
warnings.push({
kind: 'unsupported',
diff --git a/src/core/services/stats-sync/cli-args.test.ts b/src/core/services/stats-sync/cli-args.test.ts
index aa5c8cc1..9a9d83b0 100644
--- a/src/core/services/stats-sync/cli-args.test.ts
+++ b/src/core/services/stats-sync/cli-args.test.ts
@@ -54,6 +54,20 @@ test('parseSyncCliTokens handles the temp-dir protocol modes', () => {
);
});
+test('transfer cache keys are restricted to temp helpers and cannot contain paths', () => {
+ const key = 'a'.repeat(64);
+ for (const mode of [['--make-temp'], ['--remove-temp', '/tmp/subminer-sync-x']]) {
+ const parsed = parseSyncCliTokens(['sync', ...mode, '--transfer-cache', key]);
+ assert.equal(parsed.kind, 'run');
+ if (parsed.kind === 'run') assert.equal(parsed.args.syncTransferCacheKey, key);
+ assert.equal(
+ parseSyncCliTokens(['sync', ...mode, '--transfer-cache', '../../bad']).kind,
+ 'error',
+ );
+ }
+ assert.equal(parseSyncCliTokens(['sync', 'host', '--transfer-cache', key]).kind, 'error');
+});
+
test('parseSyncCliTokens owns the sync CLI validation rules', () => {
assert.equal(parseSyncCliTokens([]).kind, 'error');
assert.equal(parseSyncCliTokens(['sync']).kind, 'error');
diff --git a/src/core/services/stats-sync/cli-args.ts b/src/core/services/stats-sync/cli-args.ts
index 2f865025..050c8b54 100644
--- a/src/core/services/stats-sync/cli-args.ts
+++ b/src/core/services/stats-sync/cli-args.ts
@@ -1,4 +1,5 @@
import type { SyncFlowArgs } from './sync-flow';
+import { isTransferCacheKey } from './transfer-cache';
export const SYNC_CLI_FLAG = '--sync-cli';
@@ -43,6 +44,7 @@ export function parseSyncCliTokens(tokens: readonly string[]): ParsedSyncCli {
let json = false;
let makeTemp = false;
let removeTemp = '';
+ let transferCacheKey = '';
let remoteCmd = '';
let dbPath = '';
let logLevel = 'warn';
@@ -51,6 +53,7 @@ export function parseSyncCliTokens(tokens: readonly string[]): ParsedSyncCli {
['--snapshot', (value) => (snapshot = value.trim())],
['--merge', (value) => (merge = value.trim())],
['--remove-temp', (value) => (removeTemp = value.trim())],
+ ['--transfer-cache', (value) => (transferCacheKey = value.trim())],
['--remote-cmd', (value) => (remoteCmd = value.trim())],
['--db', (value) => (dbPath = value.trim())],
['--log-level', (value) => (logLevel = value.trim() || 'warn')],
@@ -93,6 +96,13 @@ export function parseSyncCliTokens(tokens: readonly string[]): ParsedSyncCli {
}
if (push && pull) return { kind: 'error', message: 'Sync --push and --pull cannot be combined.' };
+ if (transferCacheKey && (!isTransferCacheKey(transferCacheKey) || (!makeTemp && !removeTemp))) {
+ return {
+ kind: 'error',
+ message:
+ '--transfer-cache requires a 64-character lowercase hex key and --make-temp or --remove-temp.',
+ };
+ }
if ((push || pull) && !host) {
return { kind: 'error', message: 'Sync --push and --pull require a host.' };
}
@@ -137,6 +147,7 @@ export function parseSyncCliTokens(tokens: readonly string[]): ParsedSyncCli {
syncCheck: check,
syncMakeTemp: makeTemp,
syncRemoveTempPath: removeTemp,
+ syncTransferCacheKey: transferCacheKey,
logLevel,
},
};
@@ -161,6 +172,7 @@ export function syncCliUsage(): string {
' --check Test the SSH connection and remote SubMiner availability',
' --db Override the local stats database path',
' --remote-cmd SubMiner app or launcher command to run on the remote host',
+ ' --transfer-cache Reuse/save a received snapshot with temp helpers (internal)',
' -f, --force Skip the running-app safety check',
' --json Emit machine-readable NDJSON progress output',
' --log-level Log level',
diff --git a/src/core/services/stats-sync/merge-occurrences.test.ts b/src/core/services/stats-sync/merge-occurrences.test.ts
index 1e0298aa..a8dbaffe 100644
--- a/src/core/services/stats-sync/merge-occurrences.test.ts
+++ b/src/core/services/stats-sync/merge-occurrences.test.ts
@@ -66,7 +66,7 @@ function mergedOccurrences(dbPath: string): Array<{ word: string; seenMs: number
for (const legacyOccurrences of [false, true]) {
const label = legacyOccurrences ? 'a peer predating the seen_ms column' : 'a current peer';
- test(`sync merge carries occurrence timestamps in from ${label}`, () => {
+ test(`sync merge carries occurrence timestamps in from ${label}`, { timeout: 15_000 }, () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-merge-occurrences-test-'));
try {
const local = buildDb(dir, 'local.sqlite', {
diff --git a/src/core/services/stats-sync/snapshot-transfer.test.ts b/src/core/services/stats-sync/snapshot-transfer.test.ts
new file mode 100644
index 00000000..e1d2d889
--- /dev/null
+++ b/src/core/services/stats-sync/snapshot-transfer.test.ts
@@ -0,0 +1,238 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { randomBytes } from 'node:crypto';
+import { spawnSync } from 'node:child_process';
+import { createSnapshotTransfer, runRsync } from './snapshot-transfer';
+import { createTransferCache, transferCacheKey } from './transfer-cache';
+
+type TransferDeps = NonNullable[2]>;
+
+function commandResult(status = 0, stderr = ''): ReturnType {
+ return { status, stderr, stdout: '', pid: 0, output: [null, '', stderr], signal: null };
+}
+
+function makeDeps(overrides: Partial = {}): TransferDeps {
+ return {
+ platform: 'linux',
+ runRsync: () => commandResult(),
+ runSsh: () => ({ status: 0, stdout: '', stderr: '' }),
+ runScp: () => assert.fail('Unexpected scp fallback'),
+ ...overrides,
+ };
+}
+
+test('snapshot transfer falls back when rsync is unavailable or an endpoint is Windows', () => {
+ for (const scenario of ['local-missing', 'remote-missing', 'local-windows', 'remote-windows']) {
+ const copies: string[][] = [];
+ const transfer = createSnapshotTransfer(
+ 'macbook',
+ scenario === 'remote-windows' ? 'windows-cmd' : 'posix',
+ makeDeps({
+ platform: scenario === 'local-windows' ? 'win32' : 'linux',
+ runRsync: () => commandResult(scenario === 'local-missing' ? 1 : 0),
+ runSsh: () => ({ status: scenario === 'remote-missing' ? 127 : 0, stdout: '', stderr: '' }),
+ runScp: (from, to) => copies.push([from, to]),
+ }),
+ );
+ assert.equal(transfer.kind, 'scp', scenario);
+ transfer.copy({
+ direction: 'download',
+ localPath: '/local.sqlite',
+ remotePath: '/remote.sqlite',
+ });
+ transfer.copy({
+ direction: 'upload',
+ localPath: '/local.sqlite',
+ remotePath: '/remote.sqlite',
+ });
+ assert.deepEqual(copies, [
+ ['macbook:/remote.sqlite', '/local.sqlite'],
+ ['/local.sqlite', 'macbook:/remote.sqlite'],
+ ]);
+ }
+});
+
+test('failed rsync transfers report errors without silently retrying through scp', () => {
+ const transfer = createSnapshotTransfer(
+ 'macbook',
+ 'posix',
+ makeDeps({
+ runRsync: (args) => commandResult(args.includes('--version') ? 0 : 23, 'Permission denied'),
+ }),
+ );
+ assert.throws(
+ () =>
+ transfer.copy({
+ direction: 'upload',
+ localPath: '/local.sqlite',
+ remotePath: '/remote.sqlite',
+ }),
+ /rsync upload failed for macbook: Permission denied/,
+ );
+ assert.throws(() => createSnapshotTransfer('-oProxyCommand=bad', 'posix', makeDeps()), /option/);
+});
+
+const hasRsync = process.platform !== 'win32' && spawnSync('rsync', ['--version']).status === 0;
+
+test(
+ 'rsync forces SSH, preserves its environment, and fails on a process timeout',
+ { skip: process.platform === 'win32' },
+ () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-rsync-process-test-'));
+ const previousPath = process.env.PATH;
+ const previousRsh = process.env.RSYNC_RSH;
+ try {
+ process.env.PATH = `${dir}${path.delimiter}${previousPath ?? ''}`;
+ process.env.RSYNC_RSH = 'unexpected-transport';
+ const executable = path.join(dir, 'rsync');
+ fs.writeFileSync(
+ executable,
+ '#!/bin/sh\nprintf "%s\\n" "$@" "$RSYNC_RSH" "$RSYNC_OLD_ARGS"\n',
+ { mode: 0o700 },
+ );
+ const result = runRsync(['--version']);
+ assert.equal(result.status, 0);
+ assert.deepEqual(result.stdout.trim().split('\n'), [
+ '--rsh=ssh',
+ '--version',
+ 'unexpected-transport',
+ '1',
+ ]);
+
+ fs.writeFileSync(executable, '#!/bin/sh\nexec /bin/sleep 5\n');
+ const transfer = createSnapshotTransfer(
+ 'macbook',
+ 'posix',
+ makeDeps({
+ runRsync: (args) => (args.includes('--version') ? commandResult() : runRsync(args, 50)),
+ }),
+ );
+ assert.throws(
+ () =>
+ transfer.copy({
+ direction: 'download',
+ localPath: '/local.sqlite',
+ remotePath: '/remote.sqlite',
+ }),
+ /rsync download timed out for macbook/,
+ );
+ } finally {
+ if (previousPath === undefined) delete process.env.PATH;
+ else process.env.PATH = previousPath;
+ if (previousRsh === undefined) delete process.env.RSYNC_RSH;
+ else process.env.RSYNC_RSH = previousRsh;
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ },
+);
+
+for (const direction of ['download', 'upload'] as const) {
+ test(
+ `rsync ${direction} reuses snapshot blocks and preserves the basis`,
+ { skip: !hasRsync },
+ () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-transfer-test-'));
+ try {
+ const localDir = path.join(dir, 'local');
+ const remoteDir = path.join(dir, "remote space ' $(false)");
+ fs.mkdirSync(localDir);
+ fs.mkdirSync(remoteDir);
+ // Emulate SSH's remote shell with real rsync processes, without sshd.
+ const remoteShell = path.join(dir, 'remote-shell');
+ fs.writeFileSync(remoteShell, '#!/bin/sh\nshift\nexec /bin/sh -c "$*"\n', { mode: 0o700 });
+ const localPath = path.join(
+ localDir,
+ direction === 'download' ? 'incoming' : '',
+ 'snapshot.sqlite',
+ );
+ const remotePath = path.join(
+ remoteDir,
+ direction === 'upload' ? 'incoming' : '',
+ 'snapshot.sqlite',
+ );
+ const source = direction === 'download' ? remotePath : localPath;
+ const destination = direction === 'download' ? localPath : remotePath;
+ const basis = path.join(path.dirname(destination), '..', 'snapshot.sqlite');
+ // Incompressible data ensures savings come from matching blocks.
+ const original = randomBytes(4 * 1024 * 1024);
+ fs.writeFileSync(basis, original);
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
+ fs.writeFileSync(destination, original);
+ const updated = Buffer.from(original);
+ updated.fill(42, 65536, 69632);
+ fs.writeFileSync(source, updated);
+ let stats = '';
+ const transfer = createSnapshotTransfer(
+ 'test-peer',
+ 'posix',
+ makeDeps({
+ runRsync: (args) => {
+ const result = spawnSync(
+ 'rsync',
+ [
+ `--rsh=${remoteShell}`,
+ ...args.map((arg) => (arg === '--quiet' ? '--stats' : arg)),
+ ],
+ { encoding: 'utf8', env: { ...process.env, RSYNC_OLD_ARGS: '1', LC_ALL: 'C' } },
+ );
+ stats = result.stdout;
+ return result;
+ },
+ }),
+ );
+ assert.equal(transfer.kind, 'rsync');
+ transfer.copy({ direction, localPath, remotePath });
+ assert.deepEqual(fs.readFileSync(destination), updated);
+ assert.deepEqual(fs.readFileSync(basis), original);
+ const matched = /Matched data: ([\d,]+) (?:bytes|B)/.exec(stats)?.[1];
+ assert.ok(matched, stats);
+ assert.ok(Number(matched.replaceAll(',', '')) > original.length * 0.95, stats);
+
+ const coldDir = path.join(dir, 'cold');
+ fs.mkdirSync(coldDir);
+ const coldDestination = path.join(coldDir, 'incoming', 'snapshot.sqlite');
+ transfer.copy({
+ direction,
+ localPath: direction === 'download' ? coldDestination : localPath,
+ remotePath: direction === 'upload' ? coldDestination : remotePath,
+ });
+ assert.deepEqual(fs.readFileSync(coldDestination), updated);
+
+ // A later sync starts in a new directory and reuses the prior peer's
+ // received file even when the source has grown since that transfer.
+ const cache = createTransferCache(path.join(dir, 'cache'));
+ const key = transferCacheKey('peer');
+ cache.remember(key, direction === 'download' ? localDir : remoteDir);
+ const nextDir = path.join(dir, 'next');
+ cache.seed(key, nextDir);
+ const grown = Buffer.concat([updated, randomBytes(4096)]);
+ fs.writeFileSync(source, grown);
+ const nextDestination = path.join(nextDir, 'incoming', 'snapshot.sqlite');
+ transfer.copy({
+ direction,
+ localPath: direction === 'download' ? nextDestination : localPath,
+ remotePath: direction === 'upload' ? nextDestination : remotePath,
+ });
+ assert.deepEqual(fs.readFileSync(nextDestination), grown);
+ const cachedMatches = /Matched data: ([\d,]+) (?:bytes|B)/.exec(stats)?.[1];
+ assert.ok(cachedMatches, stats);
+ assert.ok(Number(cachedMatches.replaceAll(',', '')) > updated.length * 0.95, stats);
+
+ // A retry must replace stale content even if size and mtime agree.
+ updated.fill(43, 131072, 135168);
+ fs.writeFileSync(source, updated);
+ const timestamp = new Date(1_700_000_000_000);
+ fs.utimesSync(source, timestamp, timestamp);
+ fs.utimesSync(destination, timestamp, timestamp);
+ transfer.copy({ direction, localPath, remotePath });
+ assert.deepEqual(fs.readFileSync(destination), updated);
+ assert.deepEqual(fs.readFileSync(basis), original);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ },
+ );
+}
diff --git a/src/core/services/stats-sync/snapshot-transfer.ts b/src/core/services/stats-sync/snapshot-transfer.ts
new file mode 100644
index 00000000..d58085fc
--- /dev/null
+++ b/src/core/services/stats-sync/snapshot-transfer.ts
@@ -0,0 +1,85 @@
+import { spawnSync } from 'node:child_process';
+import path from 'node:path';
+import { assertSafeSshHost, runScp, runSsh, shellQuote, type RemoteShellFlavor } from './ssh';
+
+const RSYNC_OPTIONS = ['--compress', '--checksum'];
+
+export function runRsync(args: string[], timeoutMs = 30 * 60_000) {
+ return spawnSync('rsync', ['--rsh=ssh', ...args], {
+ encoding: 'utf8',
+ stdio: ['inherit', 'pipe', 'pipe'],
+ timeout: timeoutMs,
+ killSignal: 'SIGKILL',
+ // Quote remote paths ourselves for both modern rsync and macOS openrsync.
+ env: { ...process.env, RSYNC_OLD_ARGS: '1' },
+ });
+}
+
+interface TransferDeps {
+ platform: NodeJS.Platform;
+ runRsync: typeof runRsync;
+ runSsh: typeof runSsh;
+ runScp: typeof runScp;
+}
+
+export interface SnapshotTransfer {
+ kind: 'rsync' | 'scp';
+ copy: (request: {
+ direction: 'download' | 'upload';
+ localPath: string;
+ remotePath: string;
+ }) => void;
+}
+
+/**
+ * For rsync, both paths name snapshot.sqlite, with the destination inside an
+ * incoming/ directory seeded from the transfer cache. rsync creates incoming/
+ * when there is no cached basis and verifies the reconstructed file.
+ * Missing rsync and Windows endpoints use compressed scp with ordinary paths.
+ */
+export function createSnapshotTransfer(
+ host: string,
+ flavor: RemoteShellFlavor,
+ deps: TransferDeps = { platform: process.platform, runRsync, runSsh, runScp },
+): SnapshotTransfer {
+ assertSafeSshHost(host);
+ const canUseRsync =
+ deps.platform !== 'win32' &&
+ flavor === 'posix' &&
+ deps.runRsync([...RSYNC_OPTIONS, '--version']).status === 0 &&
+ deps.runSsh(host, `rsync ${RSYNC_OPTIONS.join(' ')} --version`, {
+ batchMode: true,
+ connectTimeoutSeconds: 10,
+ timeoutMs: 15_000,
+ }).status === 0;
+
+ return {
+ kind: canUseRsync ? 'rsync' : 'scp',
+ copy: ({ direction, localPath, remotePath }) => {
+ // A directory destination lets rsync create incoming/ on either end,
+ // including peers running older SubMiner versions.
+ const local =
+ canUseRsync && direction === 'download' ? `${path.dirname(localPath)}/` : localPath;
+ const remoteTarget =
+ canUseRsync && direction === 'upload' ? `${path.posix.dirname(remotePath)}/` : remotePath;
+ const remote = `${host}:${canUseRsync ? shellQuote(remoteTarget) : remoteTarget}`;
+ const [from, to] =
+ direction === 'download' ? ([remote, local] as const) : ([local, remote] as const);
+ if (!canUseRsync) {
+ deps.runScp(from, to);
+ return;
+ }
+ // --checksum prevents a same-size, same-mtime snapshot being skipped.
+ // Without --inplace, rsync replaces the staged basis only after the
+ // reconstructed file passes its transfer checksum.
+ const result = deps.runRsync([...RSYNC_OPTIONS, '--quiet', '--', from, to]);
+ if (result.error && 'code' in result.error && result.error.code === 'ETIMEDOUT') {
+ throw new Error(`rsync ${direction} timed out for ${host}`);
+ }
+ if (result.error) throw new Error(`Failed to run rsync: ${result.error.message}`);
+ if (result.status !== 0) {
+ throw new Error(`rsync ${direction} failed for ${host}: ${result.stderr.trim()}`);
+ }
+ },
+ };
+}
diff --git a/src/core/services/stats-sync/ssh.ts b/src/core/services/stats-sync/ssh.ts
index 99deb1dd..37778d7b 100644
--- a/src/core/services/stats-sync/ssh.ts
+++ b/src/core/services/stats-sync/ssh.ts
@@ -74,7 +74,7 @@ function assertSafeScpEndpoint(endpoint: string): void {
export function runScp(from: string, to: string): void {
assertSafeScpEndpoint(from);
assertSafeScpEndpoint(to);
- const result = spawnSync('scp', ['-q', from, to], {
+ const result = spawnSync('scp', ['-C', '-q', from, to], {
encoding: 'utf8',
stdio: ['inherit', 'inherit', 'inherit'],
});
diff --git a/src/core/services/stats-sync/sync-flow.test.ts b/src/core/services/stats-sync/sync-flow.test.ts
index 94dc714a..e934457b 100644
--- a/src/core/services/stats-sync/sync-flow.test.ts
+++ b/src/core/services/stats-sync/sync-flow.test.ts
@@ -25,6 +25,7 @@ function makeContext(overrides: Partial = {}): SyncFlow
syncCheck: false,
syncMakeTemp: false,
syncRemoveTempPath: '',
+ syncTransferCacheKey: '',
logLevel: 'warn',
...overrides,
},
@@ -46,7 +47,8 @@ function makeDeps(overrides: Partial = {}): SyncFlowDeps {
assertSafeSshHost: () => {},
detectRemoteShellFlavor: () => 'posix',
resolveRemoteSubminerCommand: () => 'subminer',
- runScp: () => {},
+ createSnapshotTransfer: () => ({ kind: 'scp', copy: () => {} }),
+ transferCache: { seed: () => {}, remember: () => {} },
runSsh: () => ok(),
canConnectUnixSocket: async () => false,
realpathSync: (candidate) => candidate,
@@ -116,9 +118,9 @@ test('runSyncFlow dispatches snapshot, merge, host, and missing-target modes', a
calls.push(`ssh:${command}`);
return command.includes(' sync --make-temp') ? ok('/tmp/subminer-sync-remote\n') : ok();
},
- runScp: (from, to) => {
+ createSnapshotTransfer: scpTransfer((from, to) => {
calls.push(`scp:${from}->${to}`);
- },
+ }),
});
await runSyncFlow(
@@ -146,6 +148,19 @@ test('runSyncFlow dispatches snapshot, merge, host, and missing-target modes', a
);
});
+function scpTransfer(
+ copy: (from: string, to: string) => void,
+): SyncFlowDeps['createSnapshotTransfer'] {
+ return (host) => ({
+ kind: 'scp',
+ copy: ({ direction, localPath, remotePath }) => {
+ const remote = `${host}:${remotePath}`;
+ if (direction === 'download') copy(remote, localPath);
+ else copy(localPath, remote);
+ },
+ });
+}
+
function makeHostDeps(calls: string[], overrides: Partial = {}): SyncFlowDeps {
return makeDeps({
createDbSnapshot: (_dbPath, outPath) => {
@@ -164,10 +179,10 @@ function makeHostDeps(calls: string[], overrides: Partial = {}): S
if (command.includes(' sync --make-temp')) return ok('/tmp/subminer-sync-remote\n');
return ok();
},
- runScp: (from, to) => {
+ createSnapshotTransfer: scpTransfer((from, to) => {
calls.push(`scp:${from}->${to}`);
if (!to.includes(':')) fs.writeFileSync(to, 'pulled');
- },
+ }),
...overrides,
});
}
@@ -248,6 +263,153 @@ test('runHostSync pull only snapshots remotely and merges locally', async () =>
assert.ok(!calls.some((call) => call.includes(' sync --merge ')));
});
+for (const direction of ['push', 'pull', 'both'] as const) {
+ test(`runHostSync ${direction} snapshots sources and maintains receiver caches`, async () => {
+ const calls: string[] = [];
+ const copies: string[] = [];
+ const cacheCalls: string[] = [];
+ await runSyncFlow(
+ makeContext({
+ syncDbPath: '/tmp/local.sqlite',
+ syncHost: 'media-box',
+ syncDirection: direction,
+ }),
+ makeHostDeps(calls, {
+ transferCache: {
+ seed: (key) => cacheCalls.push(`seed:${key}`),
+ remember: (key) => cacheCalls.push(`remember:${key}`),
+ },
+ createSnapshotTransfer: () => ({
+ kind: 'rsync',
+ copy: ({ direction: copyDirection, localPath, remotePath }) => {
+ assert.equal(
+ calls.some((call) => call.startsWith('snapshot:')),
+ direction !== 'pull',
+ );
+ assert.equal(
+ calls.some((call) => call.includes(' sync --snapshot ')),
+ direction !== 'push',
+ );
+ if (copyDirection === 'upload')
+ assert.equal(fs.readFileSync(localPath, 'utf8'), 'snapshot');
+ assert.equal(path.posix.basename(remotePath), 'snapshot.sqlite');
+ assert.equal(
+ path.posix.basename(path.posix.dirname(remotePath)),
+ copyDirection === 'upload' ? 'incoming' : 'subminer-sync-remote',
+ );
+ copies.push(copyDirection);
+ },
+ }),
+ }),
+ );
+ assert.deepEqual(
+ copies,
+ direction === 'both'
+ ? ['download', 'upload']
+ : direction === 'pull'
+ ? ['download']
+ : ['upload'],
+ );
+ assert.equal(calls.includes('local-merge'), direction !== 'push');
+ assert.equal(cacheCalls.length, direction === 'push' ? 0 : 2);
+ if (cacheCalls.length) assert.equal(cacheCalls[0]?.slice(5), cacheCalls[1]?.slice(9));
+ const remoteCacheCalls = calls.filter((call) => call.includes('--transfer-cache'));
+ assert.equal(remoteCacheCalls.length, direction === 'pull' ? 0 : 2);
+ if (remoteCacheCalls.length) {
+ assert.ok(remoteCacheCalls[0]?.includes('--make-temp'));
+ assert.ok(remoteCacheCalls[1]?.includes('--remove-temp'));
+ assert.equal(
+ remoteCacheCalls[0]?.split('--transfer-cache ')[1],
+ remoteCacheCalls[1]?.split('--transfer-cache ')[1],
+ );
+ }
+ assert.equal(
+ calls.some((call) => call.includes(' sync --merge ')),
+ direction !== 'pull',
+ );
+ });
+}
+
+test('runHostSync does not merge an incomplete transfer and removes its temp files', async () => {
+ const calls: string[] = [];
+ let localTmpDir = '';
+ await assert.rejects(
+ () =>
+ runSyncFlow(
+ makeContext({ syncDbPath: '/tmp/local.sqlite', syncHost: 'media-box' }),
+ makeHostDeps(calls, {
+ transferCache: {
+ seed: () => {},
+ remember: () => assert.fail('Failed sync must not update cache'),
+ },
+ mkdtempSync: (prefix) => {
+ localTmpDir = fs.mkdtempSync(prefix);
+ return localTmpDir;
+ },
+ createSnapshotTransfer: () => ({
+ kind: 'rsync',
+ copy: () => {
+ throw new Error('connection lost');
+ },
+ }),
+ }),
+ ),
+ /connection lost/,
+ );
+ assert.ok(!calls.includes('local-merge'));
+ assert.ok(!calls.some((call) => call.includes(' sync --merge ')));
+ assert.ok(calls.some((call) => call.includes(' sync --remove-temp ')));
+ assert.equal(fs.existsSync(localTmpDir), false);
+ assert.ok(
+ !calls.some((call) => call.includes('--remove-temp') && call.includes('--transfer-cache')),
+ );
+});
+
+for (const stderr of [
+ 'Unknown sync option: --transfer-cache',
+ "error: unknown option '--transfer-cache'\n\nUsage: subminer sync [options] [host]",
+]) {
+ test(`runHostSync falls back when the peer reports ${stderr.split('\n')[0]}`, async () => {
+ const calls: string[] = [];
+ await runSyncFlow(
+ makeContext({ syncDbPath: '/tmp/local.sqlite', syncHost: 'media-box' }),
+ makeHostDeps(calls, {
+ createSnapshotTransfer: () => ({ kind: 'rsync', copy: () => {} }),
+ runSsh: (_host, command) => {
+ calls.push(command);
+ if (command.includes('--transfer-cache')) return { status: 2, stdout: '', stderr };
+ return command.includes('--make-temp') ? ok('/tmp/subminer-sync-remote') : ok();
+ },
+ }),
+ );
+ assert.equal(calls.filter((call) => call.includes('--make-temp')).length, 2);
+ assert.ok(
+ calls.some((call) => call.includes('--remove-temp') && !call.includes('--transfer-cache')),
+ );
+ });
+}
+
+test('runHostSync does not retry unrelated remote temp failures', async () => {
+ const calls: string[] = [];
+ await assert.rejects(
+ runSyncFlow(
+ makeContext({ syncDbPath: '/tmp/local.sqlite', syncHost: 'media-box' }),
+ makeHostDeps(calls, {
+ createSnapshotTransfer: () => ({
+ kind: 'rsync',
+ copy: () => assert.fail('Must not transfer'),
+ }),
+ runSsh: (_host, command) => {
+ calls.push(command);
+ return { status: 1, stdout: '', stderr: 'Permission denied' };
+ },
+ }),
+ ),
+ /Could not create a temporary directory on media-box.*\nPermission denied/,
+ );
+ assert.equal(calls.filter((call) => call.includes('--make-temp')).length, 1);
+});
+
test('runSyncFlow --json emits NDJSON progress events and a final result', async () => {
const lines: string[] = [];
const remoteSummary = {
@@ -436,10 +598,10 @@ test('runHostSync speaks Windows shells: app command, double quotes, temp protoc
if (command.includes(' sync --make-temp')) return ok(`${winTemp}\r\n`);
return ok();
},
- runScp: (from, to) => {
+ createSnapshotTransfer: scpTransfer((from, to) => {
scpCalls.push(`${from}->${to}`);
if (!to.includes(':')) fs.writeFileSync(to, 'pulled');
- },
+ }),
});
await runSyncFlow(makeContext({ syncDbPath: '/tmp/local.sqlite', syncHost: 'win-box' }), deps);
diff --git a/src/core/services/stats-sync/sync-flow.ts b/src/core/services/stats-sync/sync-flow.ts
index 415a0cc8..e0fed8ed 100644
--- a/src/core/services/stats-sync/sync-flow.ts
+++ b/src/core/services/stats-sync/sync-flow.ts
@@ -3,6 +3,8 @@ import path from 'node:path';
import { formatMergeSummary } from './merge';
import { quoteForRemoteShell } from './ssh';
import type { RemoteRunResult, RemoteShellFlavor, RunSshOptions } from './ssh';
+import type { createSnapshotTransfer } from './snapshot-transfer';
+import { transferCacheKey, type createTransferCache } from './transfer-cache';
import {
parseSyncProgressLine,
type SyncMergeSummary,
@@ -22,6 +24,7 @@ export interface SyncFlowArgs {
syncCheck: boolean;
syncMakeTemp: boolean;
syncRemoveTempPath: string;
+ syncTransferCacheKey: string;
logLevel: string;
}
@@ -31,7 +34,7 @@ export interface SyncFlowContext {
}
/**
- * Process/IO seams the sync flow needs stubbed in tests: SSH/scp, the DB
+ * Process/IO seams the sync flow needs stubbed in tests: SSH/transfers, the DB
* snapshot/merge engine, filesystem, and progress/bookkeeping output. The
* app's --sync-cli mode (src/main/sync-cli.ts) provides the only production
* binding; pure helpers are imported directly.
@@ -51,7 +54,8 @@ export interface SyncFlowDeps {
flavor: RemoteShellFlavor,
runRemote?: (host: string, remoteCommand: string) => RemoteRunResult,
) => string;
- runScp: (from: string, to: string) => void;
+ createSnapshotTransfer: typeof createSnapshotTransfer;
+ transferCache: ReturnType;
runSsh: (host: string, remoteCommand: string, options?: RunSshOptions) => RemoteRunResult;
canConnectUnixSocket: (socketPath: string) => Promise;
realpathSync: (candidate: string) => string;
@@ -95,12 +99,17 @@ function assertRemovableSyncTempDir(target: string): string {
return resolved;
}
-function runMakeTempMode(deps: SyncFlowDeps): void {
- deps.consoleLog(makeSyncTempDir(deps.mkdtempSync));
+function runMakeTempMode(context: SyncFlowContext, deps: SyncFlowDeps): void {
+ const dir = makeSyncTempDir(deps.mkdtempSync);
+ if (context.args.syncTransferCacheKey)
+ deps.transferCache.seed(context.args.syncTransferCacheKey, dir);
+ deps.consoleLog(dir);
}
function runRemoveTempMode(context: SyncFlowContext, deps: SyncFlowDeps): void {
const target = assertRemovableSyncTempDir(context.args.syncRemoveTempPath);
+ if (context.args.syncTransferCacheKey)
+ deps.transferCache.remember(context.args.syncTransferCacheKey, target);
deps.rmSync(target, { recursive: true, force: true });
}
@@ -260,9 +269,10 @@ function cleanupRemote(
remoteTmpDir: string,
quote: (value: string) => string,
deps: SyncFlowDeps,
+ cacheFlag = '',
): void {
if (!path.posix.basename(remoteTmpDir).startsWith(SYNC_TEMP_PREFIX)) return;
- deps.runSsh(host, `${remoteCmd} sync --remove-temp ${quote(remoteTmpDir)}`);
+ deps.runSsh(host, `${remoteCmd} sync --remove-temp ${quote(remoteTmpDir)}${cacheFlag}`);
}
/**
@@ -309,19 +319,37 @@ export async function runHostSync(
const flavor = deps.detectRemoteShellFlavor(host, deps.runSsh);
const remoteCmd = deps.resolveRemoteSubminerCommand(host, args.syncRemoteCmd || null, flavor);
+ const transfer = deps.createSnapshotTransfer(host, flavor);
const quote = (value: string) => quoteForRemoteShell(flavor, value);
if (args.logLevel === 'debug') {
console.error(`Remote subminer command (${flavor}): ${remoteCmd}`);
}
const localTmpDir = makeSyncTempDir(deps.mkdtempSync);
+ const localCacheKey = transferCacheKey(`download\0${dbPath}\0${host}`);
+ const remoteCacheKey = transferCacheKey(`upload\0${os.hostname()}\0${dbPath}`);
+ let remoteCacheFlag = transfer.kind === 'rsync' ? ` --transfer-cache ${remoteCacheKey}` : '';
+ let syncSucceeded = false;
let remoteTmpDir = '';
let pulledSummary: SyncMergeSummary | null = null;
try {
// Signal failures by throwing (not fail(), which exits synchronously and
// would skip the finally cleanup, leaking temp dirs holding snapshot data).
// main().catch() reports the message the same way fail() would.
- const mktemp = deps.runSsh(host, `${remoteCmd} sync --make-temp`);
+ if (transfer.kind === 'rsync' && shouldPull)
+ deps.transferCache.seed(localCacheKey, localTmpDir);
+ let mktemp = deps.runSsh(
+ host,
+ `${remoteCmd} sync --make-temp${shouldPush ? remoteCacheFlag : ''}`,
+ );
+ if (
+ mktemp.status !== 0 &&
+ (mktemp.stderr.includes('Unknown sync option: --transfer-cache') ||
+ mktemp.stderr.includes("error: unknown option '--transfer-cache'"))
+ ) {
+ remoteCacheFlag = '';
+ mktemp = deps.runSsh(host, `${remoteCmd} sync --make-temp`);
+ }
remoteTmpDir = mktemp.status === 0 ? parseRemoteTempDir(mktemp.stdout) : '';
if (!remoteTmpDir) {
throw new Error(
@@ -331,7 +359,7 @@ export async function runHostSync(
const forceFlag = args.syncForce ? ' --force' : '';
- const localSnapshot = path.join(localTmpDir, 'local.sqlite');
+ const localSnapshot = path.join(localTmpDir, 'snapshot.sqlite');
if (shouldPush) {
deps.consoleLog(`Snapshotting local database (${dbPath})...`);
deps.emitEvent({
@@ -355,19 +383,30 @@ export async function runHostSync(
}
}
- const pulledSnapshot = path.join(localTmpDir, 'remote.sqlite');
+ const pulledSnapshot = path.join(
+ localTmpDir,
+ transfer.kind === 'rsync' ? 'incoming/snapshot.sqlite' : 'remote.sqlite',
+ );
if (shouldPull) {
deps.emitEvent({
type: 'stage',
stage: 'download',
message: `Copying snapshot from ${host}`,
});
- deps.runScp(`${host}:${remoteSnapshot}`, pulledSnapshot);
+ transfer.copy({
+ direction: 'download',
+ remotePath: remoteSnapshot,
+ localPath: pulledSnapshot,
+ });
}
- const incomingSnapshot = `${remoteTmpDir}/incoming.sqlite`;
+ const incomingSnapshot = `${remoteTmpDir}/${transfer.kind === 'rsync' ? 'incoming/snapshot.sqlite' : 'incoming.sqlite'}`;
if (shouldPush) {
deps.emitEvent({ type: 'stage', stage: 'upload', message: `Copying snapshot to ${host}` });
- deps.runScp(localSnapshot, `${host}:${incomingSnapshot}`);
+ transfer.copy({
+ direction: 'upload',
+ localPath: localSnapshot,
+ remotePath: incomingSnapshot,
+ });
}
if (shouldPull) {
@@ -416,6 +455,7 @@ export async function runHostSync(
}
}
+ syncSucceeded = true;
deps.consoleLog('\nSync complete.');
deps.recordHostSyncResult(host, 'success', formatHostSyncDetail(direction, pulledSummary));
} catch (error) {
@@ -430,10 +470,19 @@ export async function runHostSync(
}
throw error;
} finally {
+ if (syncSucceeded && transfer.kind === 'rsync' && shouldPull)
+ deps.transferCache.remember(localCacheKey, localTmpDir);
deps.rmSync(localTmpDir, { recursive: true, force: true });
if (remoteTmpDir) {
try {
- cleanupRemote(host, remoteCmd, remoteTmpDir, quote, deps);
+ cleanupRemote(
+ host,
+ remoteCmd,
+ remoteTmpDir,
+ quote,
+ deps,
+ syncSucceeded && shouldPush ? remoteCacheFlag : '',
+ );
} catch {
// best effort
}
@@ -451,7 +500,7 @@ export async function runSyncFlow(
try {
if (args.syncMakeTemp) {
- runMakeTempMode(deps);
+ runMakeTempMode(context, deps);
} else if (args.syncRemoveTempPath) {
runRemoveTempMode(context, deps);
} else {
diff --git a/src/core/services/stats-sync/transfer-cache.test.ts b/src/core/services/stats-sync/transfer-cache.test.ts
new file mode 100644
index 00000000..041a6521
--- /dev/null
+++ b/src/core/services/stats-sync/transfer-cache.test.ts
@@ -0,0 +1,59 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { createTransferCache, transferCacheKey } from './transfer-cache';
+
+test('transfer cache isolates peers and active transfers while replacing previous snapshots', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-cache-test-'));
+ try {
+ const cacheDir = path.join(root, 'cache');
+ const cache = createTransferCache(cacheDir);
+ const key = transferCacheKey('peer');
+ const first = path.join(root, 'first');
+ fs.mkdirSync(path.join(first, 'incoming'), { recursive: true });
+ const incoming = path.join(first, 'incoming', 'snapshot.sqlite');
+ fs.writeFileSync(incoming, 'first received snapshot');
+ cache.remember(key, first);
+ const second = path.join(root, 'second');
+ cache.seed(key, second);
+ fs.writeFileSync(incoming, 'next received snapshot');
+ cache.remember(key, first);
+ assert.equal(
+ fs.readFileSync(path.join(second, 'incoming', 'snapshot.sqlite'), 'utf8'),
+ 'first received snapshot',
+ );
+ const third = path.join(root, 'third');
+ cache.seed(key, third);
+ assert.equal(
+ fs.readFileSync(path.join(third, 'incoming', 'snapshot.sqlite'), 'utf8'),
+ 'next received snapshot',
+ );
+ assert.deepEqual(fs.readdirSync(cacheDir), [`${key}.sqlite`]);
+ const other = path.join(root, 'other');
+ cache.seed(transferCacheKey('other peer'), other);
+ assert.equal(fs.existsSync(path.join(other, 'incoming', 'snapshot.sqlite')), false);
+ assert.throws(() => cache.seed('../outside', other), /Invalid/);
+ assert.throws(() => cache.remember('../outside', first), /Invalid/);
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('unavailable cache storage and missing incoming snapshots do not prevent sync', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-cache-test-'));
+ try {
+ const unavailable = path.join(root, 'file');
+ fs.writeFileSync(unavailable, 'not a directory');
+ const cache = createTransferCache(unavailable);
+ const key = transferCacheKey('peer');
+ const temp = path.join(root, 'transfer');
+ assert.doesNotThrow(() => cache.seed(key, temp));
+ assert.doesNotThrow(() => cache.remember(key, temp));
+ fs.writeFileSync(path.join(temp, 'incoming', 'snapshot.sqlite'), 'received');
+ assert.doesNotThrow(() => cache.remember(key, temp));
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
diff --git a/src/core/services/stats-sync/transfer-cache.ts b/src/core/services/stats-sync/transfer-cache.ts
new file mode 100644
index 00000000..91c344b4
--- /dev/null
+++ b/src/core/services/stats-sync/transfer-cache.ts
@@ -0,0 +1,61 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { createHash } from 'node:crypto';
+import { getDefaultConfigDir } from '../../../shared/setup-state';
+
+export function transferCacheKey(peer: string): string {
+ return createHash('sha256').update(peer).digest('hex');
+}
+
+export function isTransferCacheKey(value: string): boolean {
+ return /^[a-f0-9]{64}$/.test(value);
+}
+
+/**
+ * Keep one previously received snapshot per peer as an rsync basis. Copies
+ * isolate active transfers from concurrent cache replacements. A missing or
+ * unusable cache only costs bandwidth; it must never prevent a sync.
+ */
+export function createTransferCache(
+ directory = path.join(getDefaultConfigDir(), 'sync-transfer-cache'),
+) {
+ function cachePath(key: string): string {
+ if (!isTransferCacheKey(key)) throw new Error('Invalid sync transfer cache key');
+ return path.join(directory, `${key}.sqlite`);
+ }
+
+ return {
+ seed(key: string, tempDir: string): void {
+ const source = cachePath(key);
+ const incoming = path.join(tempDir, 'incoming', 'snapshot.sqlite');
+ try {
+ fs.mkdirSync(path.dirname(incoming), { recursive: true, mode: 0o700 });
+ fs.copyFileSync(source, incoming, fs.constants.COPYFILE_FICLONE);
+ } catch {
+ // A cold transfer sends a complete compressed snapshot.
+ }
+ },
+
+ remember(key: string, tempDir: string): void {
+ const target = cachePath(key);
+ const incoming = path.join(tempDir, 'incoming', 'snapshot.sqlite');
+ let staging = '';
+ try {
+ if (!fs.existsSync(incoming)) return;
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
+ staging = fs.mkdtempSync(path.join(directory, '.write-'));
+ const snapshot = path.join(staging, 'snapshot.sqlite');
+ fs.copyFileSync(incoming, snapshot, fs.constants.COPYFILE_FICLONE);
+ fs.renameSync(snapshot, target);
+ } catch {
+ // An older basis is still valid. Never publish a partially copied file.
+ } finally {
+ try {
+ if (staging) fs.rmSync(staging, { recursive: true, force: true });
+ } catch {
+ // Cache cleanup is optional too.
+ }
+ }
+ },
+ };
+}
diff --git a/src/core/services/subtitle-generation-chunks.test.ts b/src/core/services/subtitle-generation-chunks.test.ts
new file mode 100644
index 00000000..71398610
--- /dev/null
+++ b/src/core/services/subtitle-generation-chunks.test.ts
@@ -0,0 +1,107 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { appendSpeechChunkCues, splitSpeechPassages } from './subtitle-generation-chunks';
+
+test('long coverage cuts at nearby speech starts instead of leaving a quiet lead-in', () => {
+ const chunks = splitSpeechPassages(
+ [{ startSeconds: 544.418, endSeconds: 581.581 }],
+ [563.928],
+ [555.07, 567.23, 579.91],
+ );
+ assert.deepEqual(chunks, [
+ { startSeconds: 544.418, endSeconds: 567.48 },
+ { startSeconds: 566.98, endSeconds: 581.581 },
+ ]);
+});
+
+test('short audible passages stay intact even with several detected speech starts', () => {
+ assert.deepEqual(
+ splitSpeechPassages(
+ [{ startSeconds: 876.897, endSeconds: 897.812 }],
+ [],
+ [876.9, 881.15, 893.95, 897.99],
+ ),
+ [{ startSeconds: 876.897, endSeconds: 897.812 }],
+ );
+});
+
+test('speech anchors outside retained coverage cannot extend a chunk across a silent gap', () => {
+ const chunks = splitSpeechPassages(
+ [{ startSeconds: 100, endSeconds: 142 }],
+ [118],
+ [90, 142, 144],
+ );
+ assert.deepEqual(chunks, [
+ { startSeconds: 100, endSeconds: 118.25 },
+ { startSeconds: 117.75, endSeconds: 138.25 },
+ { startSeconds: 137.75, endSeconds: 142 },
+ ]);
+});
+
+test('long speech splits near a pause with context on both sides and no lost audio', () => {
+ assert.deepEqual(splitSpeechPassages([{ startSeconds: 100, endSeconds: 145 }], [105, 118, 137]), [
+ { startSeconds: 100, endSeconds: 118.25 },
+ { startSeconds: 117.75, endSeconds: 137.25 },
+ { startSeconds: 136.75, endSeconds: 145 },
+ ]);
+});
+
+test('uninterrupted speech retains overlapping context without crossing omitted gaps', () => {
+ const chunks = splitSpeechPassages([
+ { startSeconds: 0, endSeconds: 60 },
+ { startSeconds: 100, endSeconds: 100.15 },
+ ]);
+ assert.deepEqual(chunks, [
+ { startSeconds: 0, endSeconds: 20.25 },
+ { startSeconds: 19.75, endSeconds: 40.25 },
+ { startSeconds: 39.75, endSeconds: 60 },
+ { startSeconds: 100, endSeconds: 100.15 },
+ ]);
+});
+
+test('speech fitting one Whisper window stays intact instead of cutting a sentence at 20 seconds', () => {
+ const passage = { startSeconds: 251.71, endSeconds: 275.01 };
+ assert.deepEqual(splitSpeechPassages([passage], [271.327]), [passage]);
+});
+
+test('chunk stitching ignores punctuation differences without merging separate repetitions', () => {
+ const cues = [{ startTime: 19.7, endTime: 21.2, text: 'ありがとう' }];
+ appendSpeechChunkCues(cues, [
+ { startTime: 19.8, endTime: 21.3, text: 'ありがとう。' },
+ { startTime: 22, endTime: 23, text: 'ありがとう!' },
+ ]);
+ assert.deepEqual(cues, [
+ { startTime: 19.7, endTime: 21.3, text: 'ありがとう' },
+ { startTime: 22, endTime: 23, text: 'ありがとう!' },
+ ]);
+});
+
+test('chunk stitching removes matching overlap cues but retains repeated dialogue', () => {
+ const cues = [{ startTime: 19.7, endTime: 20.2, text: 'はい' }];
+ appendSpeechChunkCues(cues, [
+ { startTime: 19.8, endTime: 20.3, text: 'はい' },
+ { startTime: 21, endTime: 21.5, text: 'はい' },
+ { startTime: 21.4, endTime: 22, text: 'はい' },
+ ]);
+ assert.deepEqual(cues, [
+ { startTime: 19.7, endTime: 20.3, text: 'はい' },
+ { startTime: 21, endTime: 21.5, text: 'はい' },
+ { startTime: 21.4, endTime: 22, text: 'はい' },
+ ]);
+});
+
+test('chunk stitching matches repeated text to the greatest overlap without leaving a duplicate', () => {
+ const cues = [
+ { startTime: 10, endTime: 14, text: 'はい' },
+ { startTime: 13, endTime: 20, text: 'はい' },
+ ];
+ appendSpeechChunkCues(cues, [
+ { startTime: 12, endTime: 21, text: 'はい' },
+ { startTime: 22, endTime: 23, text: 'はい' },
+ ]);
+ assert.deepEqual(cues, [
+ { startTime: 10, endTime: 14, text: 'はい' },
+ { startTime: 12, endTime: 21, text: 'はい' },
+ { startTime: 22, endTime: 23, text: 'はい' },
+ ]);
+});
diff --git a/src/core/services/subtitle-generation-chunks.ts b/src/core/services/subtitle-generation-chunks.ts
new file mode 100644
index 00000000..95c9ed72
--- /dev/null
+++ b/src/core/services/subtitle-generation-chunks.ts
@@ -0,0 +1,87 @@
+import type { SubtitleCue } from './subtitle-cue-parser';
+import { SPEECH_PASSAGE_SECONDS, type SpeechPassage } from './subtitle-generation-speech';
+
+const CHUNK_CONTEXT_SECONDS = 0.25;
+const WHISPER_WINDOW_SECONDS = 30;
+const PAUSE_SEARCH_SECONDS = 5;
+
+// Prefer detected speech starts, then quiet pauses. Context stays inside retained audio.
+export function splitSpeechPassages(
+ passages: readonly SpeechPassage[],
+ pauses: readonly number[] = [],
+ speechStarts: readonly number[] = [],
+): SpeechPassage[] {
+ return passages.flatMap((passage) => {
+ if (passage.endSeconds - passage.startSeconds <= WHISPER_WINDOW_SECONDS)
+ return [{ ...passage }];
+ const chunks: SpeechPassage[] = [];
+ let boundary = passage.startSeconds;
+ while (boundary < passage.endSeconds) {
+ const target = boundary + SPEECH_PASSAGE_SECONDS;
+ let end = Math.min(target, passage.endSeconds);
+ if (target < passage.endSeconds) {
+ // Starting in a long quiet lead-in can make Whisper place the next line
+ // several seconds early. A nearby VAD start gives the next chunk an anchor.
+ let nearestSpeechStart: number | undefined;
+ for (const time of speechStarts) {
+ if (
+ time >= target - PAUSE_SEARCH_SECONDS &&
+ time <= target + PAUSE_SEARCH_SECONDS &&
+ time < passage.endSeconds &&
+ (nearestSpeechStart === undefined ||
+ Math.abs(time - target) < Math.abs(nearestSpeechStart - target))
+ )
+ nearestSpeechStart = time;
+ }
+ let latestPause: number | undefined;
+ for (const time of pauses) {
+ if (
+ time >= target - PAUSE_SEARCH_SECONDS &&
+ time <= target &&
+ (latestPause === undefined || time > latestPause)
+ )
+ latestPause = time;
+ }
+ end = nearestSpeechStart ?? latestPause ?? end;
+ }
+ chunks.push({
+ startSeconds: Math.max(passage.startSeconds, boundary - CHUNK_CONTEXT_SECONDS),
+ endSeconds: Math.min(passage.endSeconds, end + CHUNK_CONTEXT_SECONDS),
+ });
+ boundary = end;
+ }
+ return chunks;
+ });
+}
+
+// Deduplicate only matching text substantially overlapping cues from earlier chunks.
+// Repeated words within the current chunk or at separate times remain separate.
+export function appendSpeechChunkCues(cues: SubtitleCue[], incoming: readonly SubtitleCue[]): void {
+ const previousCount = cues.length;
+ const matched = new Set();
+ for (const cue of incoming) {
+ const text = cue.text.replace(/[\s\p{P}]+/gu, '');
+ let duplicate: SubtitleCue | undefined;
+ let greatestOverlap = 0;
+ for (const [index, previous] of cues.entries()) {
+ if (index >= previousCount) break;
+ if (!text || matched.has(previous) || previous.text.replace(/[\s\p{P}]+/gu, '') !== text)
+ continue;
+ const overlap =
+ Math.min(previous.endTime, cue.endTime) - Math.max(previous.startTime, cue.startTime);
+ const shorterDuration = Math.min(
+ previous.endTime - previous.startTime,
+ cue.endTime - cue.startTime,
+ );
+ if (overlap > greatestOverlap && overlap >= shorterDuration / 2) {
+ duplicate = previous;
+ greatestOverlap = overlap;
+ }
+ }
+ if (duplicate) {
+ duplicate.startTime = Math.min(duplicate.startTime, cue.startTime);
+ duplicate.endTime = Math.max(duplicate.endTime, cue.endTime);
+ matched.add(duplicate);
+ } else cues.push({ ...cue });
+ }
+}
diff --git a/src/core/services/subtitle-generation-coverage.test.ts b/src/core/services/subtitle-generation-coverage.test.ts
new file mode 100644
index 00000000..db95f265
--- /dev/null
+++ b/src/core/services/subtitle-generation-coverage.test.ts
@@ -0,0 +1,73 @@
+import assert from 'node:assert/strict';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+import { findAudiblePassages, mergeSpeechPassages } from './subtitle-generation-coverage';
+
+async function analyze(lines: string[], progress = 'out_time_us=20000000\n') {
+ const directory = await mkdtemp(path.join(tmpdir(), 'subtitle-coverage-test-'));
+ try {
+ const ffmpegPath = path.join(directory, 'ffmpeg');
+ await writeFile(
+ ffmpegPath,
+ `#!${process.execPath}
+process.stderr.write(${JSON.stringify(lines.join('\n') + '\n')});
+process.stdout.write(${JSON.stringify(progress)});
+`,
+ { mode: 0o755 },
+ );
+ return await findAudiblePassages({ ffmpegPath, wavPath: 'audio.wav' });
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+}
+
+test('audible coverage retains the full timeline when there is no confident silence', async () => {
+ assert.deepEqual(await analyze([]), [{ startSeconds: 0, endSeconds: 20 }]);
+});
+
+test('audible coverage omits silence while padding nearby audio without exceeding the timeline', async () => {
+ assert.deepEqual(
+ await analyze([
+ '[silencedetect] silence_start: 0',
+ '[silencedetect] silence_end: 2 | silence_duration: 2',
+ '[silencedetect] silence_start: 8',
+ '[silencedetect] silence_end: 12 | silence_duration: 4',
+ '[silencedetect] silence_start: 18',
+ ]),
+ [
+ { startSeconds: 1.65, endSeconds: 8.35 },
+ { startSeconds: 11.65, endSeconds: 18.35 },
+ ],
+ );
+ assert.deepEqual(await analyze(['[silencedetect] silence_end: 10.5 | silence_duration: 0.5']), [
+ { startSeconds: 0, endSeconds: 20 },
+ ]);
+});
+
+test('entirely silent audio has no audible passages', async () => {
+ assert.deepEqual(await analyze(['[silencedetect] silence_start: 0']), []);
+ assert.deepEqual(await analyze(['[silencedetect] silence_end: 20 | silence_duration: 20']), []);
+});
+
+test('missing analysis duration fails instead of silently dropping audio', async () => {
+ await assert.rejects(analyze([], ''), /valid duration/);
+});
+
+test('merging coverage preserves quiet VAD speech and does not mutate detector results', () => {
+ const speech = [{ startSeconds: 10, endSeconds: 11 }];
+ assert.deepEqual(
+ mergeSpeechPassages([
+ ...speech,
+ { startSeconds: 0, endSeconds: 5 },
+ { startSeconds: 4, endSeconds: 8 },
+ { startSeconds: 11, endSeconds: 12 },
+ ]),
+ [
+ { startSeconds: 0, endSeconds: 8 },
+ { startSeconds: 10, endSeconds: 12 },
+ ],
+ );
+ assert.deepEqual(speech, [{ startSeconds: 10, endSeconds: 11 }]);
+});
diff --git a/src/core/services/subtitle-generation-coverage.ts b/src/core/services/subtitle-generation-coverage.ts
new file mode 100644
index 00000000..92e2cf26
--- /dev/null
+++ b/src/core/services/subtitle-generation-coverage.ts
@@ -0,0 +1,78 @@
+import { runSubtitleGenerationProcess } from './subtitle-generation-process';
+import type { SpeechPassage } from './subtitle-generation-speech';
+
+const AUDIO_PADDING_SECONDS = 0.35;
+
+export function mergeSpeechPassages(passages: readonly SpeechPassage[]): SpeechPassage[] {
+ const merged: SpeechPassage[] = [];
+ for (const passage of [...passages].sort((a, b) => a.startSeconds - b.startSeconds)) {
+ const previous = merged.at(-1);
+ if (previous && passage.startSeconds <= previous.endSeconds)
+ previous.endSeconds = Math.max(previous.endSeconds, passage.endSeconds);
+ else merged.push({ ...passage });
+ }
+ return merged;
+}
+
+// VAD rejection is not proof of silence. Preserve audible gaps for Whisper to evaluate.
+export async function findAudiblePassages(input: {
+ ffmpegPath: string;
+ wavPath: string;
+ signal?: AbortSignal;
+}): Promise {
+ const silences: SpeechPassage[] = [];
+ let duration = 0;
+ let trailingSilence: number | undefined;
+ await runSubtitleGenerationProcess({
+ command: input.ffmpegPath,
+ args: [
+ '-nostdin',
+ '-hide_banner',
+ '-nostats',
+ '-i',
+ input.wavPath,
+ '-af',
+ 'silencedetect=noise=-50dB:d=0.5',
+ '-progress',
+ 'pipe:1',
+ '-f',
+ 'null',
+ '-',
+ ],
+ signal: input.signal,
+ onLine: (line) => {
+ const progress = /^out_time_us=(\d+)$/.exec(line);
+ if (progress) duration = Math.max(duration, Number(progress[1]) / 1_000_000);
+ const start = /silence_start: (\S+)/.exec(line);
+ if (start && Number.isFinite(Number(start[1]))) trailingSilence = Number(start[1]);
+ const end = /silence_end: (\S+) \| silence_duration: (\S+)/.exec(line);
+ if (!end) return;
+ const endSeconds = Number(end[1]);
+ const length = Number(end[2]);
+ if (Number.isFinite(endSeconds) && Number.isFinite(length) && length > 0) {
+ silences.push({ startSeconds: Math.max(0, endSeconds - length), endSeconds });
+ trailingSilence = undefined;
+ }
+ },
+ });
+ if (!Number.isFinite(duration) || duration <= 0)
+ throw new Error('Audio analysis did not report a valid duration.');
+ if (trailingSilence !== undefined)
+ silences.push({ startSeconds: trailingSilence, endSeconds: duration });
+
+ const audible: SpeechPassage[] = [];
+ let cursor = 0;
+ for (const silence of mergeSpeechPassages(silences)) {
+ if (cursor >= duration) break;
+ if (silence.startSeconds > cursor)
+ audible.push({ startSeconds: cursor, endSeconds: Math.min(duration, silence.startSeconds) });
+ cursor = Math.max(cursor, silence.endSeconds);
+ }
+ if (cursor < duration) audible.push({ startSeconds: cursor, endSeconds: duration });
+ return mergeSpeechPassages(
+ audible.map((passage) => ({
+ startSeconds: Math.max(0, passage.startSeconds - AUDIO_PADDING_SECONDS),
+ endSeconds: Math.min(duration, passage.endSeconds + AUDIO_PADDING_SECONDS),
+ })),
+ );
+}
diff --git a/src/core/services/subtitle-generation-dialogue.ts b/src/core/services/subtitle-generation-dialogue.ts
new file mode 100644
index 00000000..744d6a9f
--- /dev/null
+++ b/src/core/services/subtitle-generation-dialogue.ts
@@ -0,0 +1,151 @@
+import { access, readFile, rm } from 'node:fs/promises';
+import { constants } from 'node:fs';
+import path from 'node:path';
+import type {
+ SubtitleGenerationConfig,
+ SubtitleGenerationProgress,
+} from '../../shared/subtitle-generation';
+import { expandSubtitleGenerationPath } from './subtitle-generation-files';
+import { runSubtitleGenerationProcess } from './subtitle-generation-process';
+import type { SubtitleGenerationToolPaths } from './subtitle-generation-tools';
+import { formatTimestamp } from './subtitle-generation-srt';
+import {
+ parseSpeechPassages,
+ speechPassageCues,
+ SPEECH_PASSAGE_SECONDS,
+} from './subtitle-generation-speech';
+import type { SubtitleCue } from './subtitle-cue-parser';
+import { appendSpeechChunkCues, splitSpeechPassages } from './subtitle-generation-chunks';
+import { findSpeechPauses } from './subtitle-generation-pauses';
+import { findAudiblePassages, mergeSpeechPassages } from './subtitle-generation-coverage';
+
+export async function transcribeSubtitleDialogue(input: {
+ config: SubtitleGenerationConfig;
+ tools: SubtitleGenerationToolPaths & { vad: string };
+ modelPath: string;
+ wavPath: string;
+ directory: string;
+ onProgress?: (progress: SubtitleGenerationProgress) => void;
+ signal?: AbortSignal;
+}): Promise {
+ const vadModelPath = expandSubtitleGenerationPath(input.config.vadModelPath);
+ await access(vadModelPath, constants.R_OK);
+ input.onProgress?.({ stage: 'transcribe', percent: 0, message: 'Finding spoken dialogue...' });
+ const segmentLines: string[] = [];
+ await runSubtitleGenerationProcess({
+ command: input.tools.vad,
+ args: [
+ '-f',
+ input.wavPath,
+ '-vm',
+ vadModelPath,
+ '-t',
+ String(input.config.threads),
+ '-vt',
+ '0.3',
+ '--vad-min-speech-duration-ms',
+ '100',
+ '--vad-min-silence-duration-ms',
+ '500',
+ '-vp',
+ '350',
+ '-vmsd',
+ String(SPEECH_PASSAGE_SECONDS),
+ '-np',
+ ],
+ signal: input.signal,
+ // Capture structured result lines separately from the bounded process log.
+ onLine: (line) => {
+ if (line.startsWith('Detected ') || line.startsWith('Speech segment '))
+ segmentLines.push(line);
+ },
+ });
+ const speech = parseSpeechPassages(segmentLines.join('\n'));
+ input.onProgress?.({ stage: 'transcribe', percent: 0, message: 'Checking audio coverage...' });
+ const audible = await findAudiblePassages({
+ ffmpegPath: input.tools.ffmpeg,
+ wavPath: input.wavPath,
+ signal: input.signal,
+ });
+ const detected = mergeSpeechPassages([...speech, ...audible]);
+ if (detected.length === 0) throw new Error('No spoken dialogue detected.');
+ const pauses = detected.some(
+ (passage) => passage.endSeconds - passage.startSeconds > SPEECH_PASSAGE_SECONDS,
+ )
+ ? await findSpeechPauses({
+ ffmpegPath: input.tools.ffmpeg,
+ wavPath: input.wavPath,
+ signal: input.signal,
+ })
+ : [];
+ const passages = splitSpeechPassages(
+ detected,
+ pauses,
+ speech.map((passage) => passage.startSeconds),
+ );
+ const cues: SubtitleCue[] = [];
+ for (const [index, passage] of passages.entries()) {
+ const base = path.join(input.directory, `speech-${index}`);
+ input.onProgress?.({
+ stage: 'transcribe',
+ percent: Math.floor((index / passages.length) * 100),
+ message: `Transcribing dialogue passage ${index + 1} of ${passages.length}...`,
+ });
+ await runSubtitleGenerationProcess({
+ command: input.tools.ffmpeg,
+ args: [
+ '-nostdin',
+ '-hide_banner',
+ '-loglevel',
+ 'error',
+ '-ss',
+ String(passage.startSeconds),
+ '-i',
+ input.wavPath,
+ '-t',
+ String(passage.endSeconds - passage.startSeconds),
+ '-ac',
+ '1',
+ '-ar',
+ '16000',
+ '-c:a',
+ 'pcm_s16le',
+ `${base}.wav`,
+ ],
+ signal: input.signal,
+ });
+ // -mc 0 limits text context, but does not isolate decoder state across input files.
+ // A fresh process prevents earlier passages from corrupting later transcriptions.
+ await runSubtitleGenerationProcess({
+ command: input.tools.whisper,
+ args: [
+ '-m',
+ input.modelPath,
+ '-l',
+ 'ja',
+ '-t',
+ String(input.config.threads),
+ '-mc',
+ '0',
+ '-sns',
+ '-osrt',
+ '-f',
+ `${base}.wav`,
+ '-of',
+ base,
+ ],
+ signal: input.signal,
+ });
+ input.signal?.throwIfAborted();
+ appendSpeechChunkCues(cues, speechPassageCues(await readFile(`${base}.srt`, 'utf8'), passage));
+ await rm(`${base}.wav`);
+ }
+ if (cues.length === 0) throw new Error('Whisper recognized no dialogue in the detected speech.');
+ return cues
+ .sort((a, b) => a.startTime - b.startTime || a.endTime - b.endTime)
+ .map(
+ (cue, index) =>
+ `${index + 1}\n${formatTimestamp(cue.startTime * 1000)} --> ${formatTimestamp(cue.endTime * 1000)}\n${cue.text}\n`,
+ )
+ .join('\n');
+}
diff --git a/src/core/services/subtitle-generation-download.test.ts b/src/core/services/subtitle-generation-download.test.ts
new file mode 100644
index 00000000..f8c9498b
--- /dev/null
+++ b/src/core/services/subtitle-generation-download.test.ts
@@ -0,0 +1,75 @@
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+import { downloadSubtitleGenerationArtifact } from './subtitle-generation-download';
+import {
+ downloadSubtitleGenerationVadModel,
+ resolveSubtitleGenerationVadModel,
+} from './subtitle-generation-vad-model';
+import { DEFAULT_SUBTITLE_GENERATION_CONFIG } from '../../shared/subtitle-generation';
+
+test('verified model publication preserves existing files and cleans up failed or cancelled downloads', async () => {
+ const directory = await mkdtemp(path.join(tmpdir(), 'subtitle-model-download-'));
+ const originalFetch = globalThis.fetch;
+ const bytes = new TextEncoder().encode('fixture model');
+ const input = {
+ url: 'https://example.test/model',
+ size: bytes.length,
+ sha256: createHash('sha256').update(bytes).digest('hex'),
+ destination: path.join(directory, 'model.bin'),
+ label: 'test model',
+ };
+ try {
+ globalThis.fetch = Object.assign(async () => new Response(bytes), originalFetch);
+ await downloadSubtitleGenerationArtifact(input);
+ assert.equal(await readFile(input.destination, 'utf8'), 'fixture model');
+ await assert.rejects(downloadSubtitleGenerationArtifact(input), /EEXIST/);
+ await assert.rejects(
+ downloadSubtitleGenerationArtifact({
+ ...input,
+ destination: path.join(directory, 'bad.bin'),
+ sha256: 'wrong',
+ }),
+ /integrity/,
+ );
+ const controller = new AbortController();
+ await assert.rejects(
+ downloadSubtitleGenerationArtifact({
+ ...input,
+ destination: path.join(directory, 'cancelled.bin'),
+ signal: controller.signal,
+ onProgress: ({ percent }) => {
+ if (percent === 99) controller.abort();
+ },
+ }),
+ );
+ assert.deepEqual(await readdir(directory), ['model.bin']);
+ } finally {
+ globalThis.fetch = originalFetch;
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
+test('VAD setup recognizes existing paths and never replaces an invalid external model', async () => {
+ const directory = await mkdtemp(path.join(tmpdir(), 'subtitle-vad-model-'));
+ try {
+ const config = { ...DEFAULT_SUBTITLE_GENERATION_CONFIG };
+ assert.equal((await resolveSubtitleGenerationVadModel(config, directory)).kind, 'missing');
+ config.vadModelPath = path.join(directory, 'external.bin');
+ await assert.rejects(
+ downloadSubtitleGenerationVadModel({ config, modelDirectory: directory }),
+ /Cannot read/,
+ );
+ await writeFile(config.vadModelPath, 'external model');
+ assert.equal((await resolveSubtitleGenerationVadModel(config, directory)).kind, 'external');
+ assert.equal(
+ await downloadSubtitleGenerationVadModel({ config, modelDirectory: directory }),
+ config.vadModelPath,
+ );
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
diff --git a/src/core/services/subtitle-generation-download.ts b/src/core/services/subtitle-generation-download.ts
new file mode 100644
index 00000000..a3e041fa
--- /dev/null
+++ b/src/core/services/subtitle-generation-download.ts
@@ -0,0 +1,67 @@
+import { createHash } from 'node:crypto';
+import { mkdir, mkdtemp, open, rm } from 'node:fs/promises';
+import path from 'node:path';
+import { publishSubtitleGenerationFile } from './subtitle-generation-files';
+import type { SubtitleGenerationProgress } from '../../shared/subtitle-generation';
+
+export async function downloadSubtitleGenerationArtifact(input: {
+ url: string;
+ size: number;
+ sha256: string;
+ destination: string;
+ label: string;
+ onProgress?: (progress: SubtitleGenerationProgress) => void;
+ signal?: AbortSignal;
+}): Promise {
+ input.signal?.throwIfAborted();
+ await mkdir(path.dirname(input.destination), { recursive: true });
+ const temporaryDirectory = await mkdtemp(
+ path.join(path.dirname(input.destination), '.download-'),
+ );
+ const temporaryPath = path.join(temporaryDirectory, 'model.bin');
+ input.onProgress?.({ stage: 'download', percent: 0, message: `Downloading ${input.label}...` });
+ try {
+ const response = await fetch(input.url, { signal: input.signal });
+ if (!response.ok || !response.body) {
+ throw new Error(`Model download failed: HTTP ${response.status}`);
+ }
+ const file = await open(temporaryPath, 'wx');
+ const reader = response.body.getReader();
+ const digest = createHash('sha256');
+ let received = 0;
+ let previousPercent = -1;
+ try {
+ while (true) {
+ input.signal?.throwIfAborted();
+ const { done, value } = await reader.read();
+ if (done) break;
+ received += value.byteLength;
+ if (received > input.size) throw new Error('Downloaded model exceeds expected size.');
+ digest.update(value);
+ await file.writeFile(value);
+ const percent = Math.min(99, Math.floor((received / input.size) * 100));
+ if (percent !== previousPercent) {
+ previousPercent = percent;
+ input.onProgress?.({
+ stage: 'download',
+ percent,
+ message: `Downloading ${input.label}...`,
+ });
+ }
+ }
+ if (received !== input.size || digest.digest('hex') !== input.sha256) {
+ throw new Error('Downloaded model failed integrity verification. Try downloading again.');
+ }
+ await file.sync();
+ } finally {
+ await reader.cancel().catch(() => undefined);
+ await file.close();
+ }
+ input.signal?.throwIfAborted();
+ await publishSubtitleGenerationFile(temporaryPath, input.destination);
+ input.onProgress?.({ stage: 'download', percent: 100, message: `${input.label} is ready.` });
+ return input.destination;
+ } finally {
+ await rm(temporaryDirectory, { recursive: true, force: true });
+ }
+}
diff --git a/src/core/services/subtitle-generation-files.ts b/src/core/services/subtitle-generation-files.ts
new file mode 100644
index 00000000..0073742c
--- /dev/null
+++ b/src/core/services/subtitle-generation-files.ts
@@ -0,0 +1,32 @@
+import { constants } from 'node:fs';
+import { copyFile, link } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import path from 'node:path';
+
+export function expandSubtitleGenerationPath(value: string): string {
+ if (value === '~') return homedir();
+ if (value.startsWith('~/') || value.startsWith('~\\'))
+ return path.join(homedir(), value.slice(2));
+ return value;
+}
+
+// Prefer atomic publication. Filesystems without hard links still get exclusive creation.
+export async function publishSubtitleGenerationFile(
+ source: string,
+ destination: string,
+): Promise {
+ try {
+ await link(source, destination);
+ } catch (error) {
+ if (
+ !(error instanceof Error) ||
+ !('code' in error) ||
+ (error.code !== 'ENOTSUP' &&
+ error.code !== 'EOPNOTSUPP' &&
+ error.code !== 'EPERM' &&
+ error.code !== 'EXDEV')
+ )
+ throw error;
+ await copyFile(source, destination, constants.COPYFILE_EXCL);
+ }
+}
diff --git a/src/core/services/subtitle-generation-models.ts b/src/core/services/subtitle-generation-models.ts
new file mode 100644
index 00000000..9cc10b5e
--- /dev/null
+++ b/src/core/services/subtitle-generation-models.ts
@@ -0,0 +1,90 @@
+import { access, open, stat } from 'node:fs/promises';
+import { constants } from 'node:fs';
+import path from 'node:path';
+import { getSubtitleGenerationModel } from '../../shared/subtitle-generation-model-catalog';
+import { expandSubtitleGenerationPath } from './subtitle-generation-files';
+import { downloadSubtitleGenerationArtifact } from './subtitle-generation-download';
+import type {
+ SubtitleGenerationConfig,
+ SubtitleGenerationModelStatus,
+ SubtitleGenerationProgress,
+} from '../../shared/subtitle-generation';
+
+export function isMissingFile(error: unknown): boolean {
+ return error instanceof Error && 'code' in error && error.code === 'ENOENT';
+}
+
+async function modelCompatibilityError(modelPath: string): Promise {
+ const file = await open(modelPath, 'r');
+ try {
+ // whisper_model_load reads GGML magic, then n_vocab. is_multilingual uses n_vocab >= 51865.
+ const header = Buffer.alloc(8);
+ const { bytesRead } = await file.read(header, 0, header.length, 0);
+ if (
+ bytesRead !== header.length ||
+ header.readUInt32LE(0) !== 0x67676d6c ||
+ header.readInt32LE(4) <= 0
+ ) {
+ return 'Unsupported model format. Choose a whisper.cpp GGML .bin model.';
+ }
+ if (header.readInt32LE(4) < 51865) {
+ return 'This Whisper model is English-only. Japanese subtitle generation requires a multilingual model.';
+ }
+ return undefined;
+ } finally {
+ await file.close();
+ }
+}
+
+export async function resolveSubtitleGenerationModel(
+ config: SubtitleGenerationConfig,
+ modelDirectory: string,
+): Promise {
+ const external = config.modelPath.trim();
+ const modelPath = external
+ ? path.resolve(expandSubtitleGenerationPath(external))
+ : path.resolve(modelDirectory, `ggml-${config.managedModel}.bin`);
+ try {
+ const info = await stat(modelPath);
+ if (!info.isFile() || info.size === 0) {
+ return { kind: 'invalid', path: modelPath, message: 'Model must be a nonempty file.' };
+ }
+ await access(modelPath, constants.R_OK);
+ if (!external && info.size !== getSubtitleGenerationModel(config.managedModel).size) {
+ return { kind: 'invalid', path: modelPath, message: 'Managed model has an unexpected size.' };
+ }
+ const compatibilityError = await modelCompatibilityError(modelPath);
+ if (compatibilityError)
+ return { kind: 'invalid', path: modelPath, message: compatibilityError };
+ return { kind: external ? 'external' : 'managed', path: modelPath };
+ } catch (error) {
+ if (!external && isMissingFile(error)) return { kind: 'missing', path: modelPath };
+ return {
+ kind: 'invalid',
+ path: modelPath,
+ message: `Cannot read model: ${error instanceof Error ? error.message : String(error)}`,
+ };
+ }
+}
+
+export async function downloadSubtitleGenerationModel(input: {
+ config: SubtitleGenerationConfig;
+ modelDirectory: string;
+ onProgress?: (progress: SubtitleGenerationProgress) => void;
+ signal?: AbortSignal;
+}): Promise {
+ input.signal?.throwIfAborted();
+ const current = await resolveSubtitleGenerationModel(input.config, input.modelDirectory);
+ if (current.kind === 'external' || current.kind === 'managed') return current.path;
+ if (current.kind === 'invalid') throw new Error(current.message);
+ const model = getSubtitleGenerationModel(input.config.managedModel);
+ return downloadSubtitleGenerationArtifact({
+ url: `https://huggingface.co/ggerganov/whisper.cpp/resolve/5359861c739e955e79d9a303bcbc70fb988958b1/ggml-${input.config.managedModel}.bin`,
+ size: model.size,
+ sha256: model.sha256,
+ destination: current.path,
+ label: 'Whisper model',
+ onProgress: input.onProgress,
+ signal: input.signal,
+ });
+}
diff --git a/src/core/services/subtitle-generation-pauses.ts b/src/core/services/subtitle-generation-pauses.ts
new file mode 100644
index 00000000..f0fdbda1
--- /dev/null
+++ b/src/core/services/subtitle-generation-pauses.ts
@@ -0,0 +1,35 @@
+import { runSubtitleGenerationProcess } from './subtitle-generation-process';
+
+// Each completed silencedetect line contains both the end and duration of a quiet interval.
+export async function findSpeechPauses(input: {
+ ffmpegPath: string;
+ wavPath: string;
+ signal?: AbortSignal;
+}): Promise {
+ const pauses: number[] = [];
+ await runSubtitleGenerationProcess({
+ command: input.ffmpegPath,
+ args: [
+ '-nostdin',
+ '-hide_banner',
+ '-nostats',
+ '-i',
+ input.wavPath,
+ '-af',
+ 'silencedetect=noise=-35dB:d=0.12',
+ '-f',
+ 'null',
+ '-',
+ ],
+ signal: input.signal,
+ onLine: (line) => {
+ const match = /silence_end: (\S+) \| silence_duration: (\S+)/.exec(line);
+ if (!match) return;
+ const end = Number(match[1]);
+ const duration = Number(match[2]);
+ if (Number.isFinite(end) && Number.isFinite(duration) && duration > 0 && end >= duration)
+ pauses.push(end - duration / 2);
+ },
+ });
+ return pauses.sort((a, b) => a - b);
+}
diff --git a/src/core/services/subtitle-generation-process.ts b/src/core/services/subtitle-generation-process.ts
new file mode 100644
index 00000000..3905f7c7
--- /dev/null
+++ b/src/core/services/subtitle-generation-process.ts
@@ -0,0 +1,67 @@
+import { spawn } from 'node:child_process';
+import { expandSubtitleGenerationPath } from './subtitle-generation-files';
+
+const OUTPUT_LIMIT = 64 * 1024;
+
+// Keep partial lines between chunks: ffmpeg and whisper both report progress on stderr.
+export function runSubtitleGenerationProcess(input: {
+ command: string;
+ args: string[];
+ signal?: AbortSignal;
+ onLine?: (line: string) => void;
+}): Promise {
+ input.signal?.throwIfAborted();
+ return new Promise((resolve, reject) => {
+ const child = spawn(expandSubtitleGenerationPath(input.command), input.args, {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let stdout = '';
+ let stderr = '';
+ let killTimer: ReturnType | undefined;
+ const abort = () => {
+ child.kill('SIGTERM');
+ killTimer = setTimeout(() => child.kill('SIGKILL'), 2000);
+ killTimer.unref();
+ };
+ input.signal?.addEventListener('abort', abort, { once: true });
+ if (input.signal?.aborted) abort();
+ const cleanup = () => {
+ input.signal?.removeEventListener('abort', abort);
+ clearTimeout(killTimer);
+ };
+ for (const [stream, isStdout] of [
+ [child.stdout, true],
+ [child.stderr, false],
+ ] as const) {
+ let pending = '';
+ stream.setEncoding('utf8');
+ stream.on('data', (chunk: string) => {
+ if (isStdout) stdout = (stdout + chunk).slice(-OUTPUT_LIMIT);
+ else stderr = (stderr + chunk).slice(-OUTPUT_LIMIT);
+ const lines = (pending + chunk).split(/[\r\n]/);
+ pending = (lines.pop() ?? '').slice(-OUTPUT_LIMIT);
+ for (const line of lines) input.onLine?.(line);
+ });
+ stream.on('end', () => {
+ if (pending) input.onLine?.(pending);
+ });
+ }
+ child.once('error', (error) => {
+ cleanup();
+ reject(
+ new Error(
+ 'code' in error && error.code === 'ENOENT'
+ ? `${input.command} was not found. Install it or set its path under subtitleGeneration in Settings.`
+ : `Could not run ${input.command}: ${error.message}`,
+ ),
+ );
+ });
+ child.once('close', (code) => {
+ cleanup();
+ if (input.signal?.aborted) reject(new Error('Subtitle generation cancelled.'));
+ else if (code !== 0) {
+ reject(new Error(`${input.command} exited with status ${code}: ${stderr.trim()}`));
+ } else resolve(stdout);
+ });
+ });
+}
diff --git a/src/core/services/subtitle-generation-speech.test.ts b/src/core/services/subtitle-generation-speech.test.ts
new file mode 100644
index 00000000..c1f3c351
--- /dev/null
+++ b/src/core/services/subtitle-generation-speech.test.ts
@@ -0,0 +1,78 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { parseSpeechPassages, speechPassageCues } from './subtitle-generation-speech';
+
+test('speech passages convert centiseconds, group nearby speech, and retain long gaps', () => {
+ assert.deepEqual(
+ parseSpeechPassages(
+ [
+ 'Detected 4 speech segments:',
+ 'Speech segment 0: start = 0.00, end = 300.00',
+ 'Speech segment 1: start = 350.00, end = 900.00',
+ 'Speech segment 2: start = 10000.00, end = 11900.00',
+ 'Speech segment 3: start = 11950.00, end = 12500.00',
+ ].join('\n'),
+ ),
+ [
+ { startSeconds: 0, endSeconds: 9 },
+ { startSeconds: 100, endSeconds: 119 },
+ { startSeconds: 119.5, endSeconds: 125 },
+ ],
+ );
+});
+
+test('speech passages retain long merged detector segments for pause-aware splitting', () => {
+ assert.deepEqual(
+ parseSpeechPassages(
+ [
+ 'Detected 3 speech segments:',
+ 'Speech segment 0: start = 33714.00, end = 36756.00',
+ 'Speech segment 1: start = 40000.00, end = 46000.00',
+ 'Speech segment 2: start = 50000.00, end = 50100.00',
+ ].join('\n'),
+ ),
+ [
+ { startSeconds: 337.14, endSeconds: 367.56 },
+ { startSeconds: 400, endSeconds: 460 },
+ { startSeconds: 500, endSeconds: 501 },
+ ],
+ );
+});
+
+test('speech detector distinguishes no speech from missing, malformed, or truncated output', () => {
+ assert.deepEqual(parseSpeechPassages('Detected 0 speech segments:'), []);
+ assert.deepEqual(
+ parseSpeechPassages(
+ 'Detected 1 speech segments:\nSpeech segment 0: start = 79896.00, end = 82218.00',
+ ),
+ [{ startSeconds: 798.96, endSeconds: 822.18 }],
+ );
+ for (const output of [
+ '',
+ 'Detected 1 speech segments:',
+ 'Detected 1 speech segments:\nSpeech segment 1: start = 100.00, end = 200.00',
+ 'Detected 1 speech segments:\nSpeech segment 0: start = 200.00, end = 100.00',
+ 'Detected 1 speech segments:\nSpeech segment 0: start = NaN, end = 100.00',
+ 'Detected 2 speech segments:\nSpeech segment 0: start = 0.00, end = 200.00\nSpeech segment 1: start = 100.00, end = 300.00',
+ ])
+ assert.throws(() => parseSpeechPassages(output), /Speech detector/);
+});
+
+test('passage cue times cannot extend into omitted audio or accumulate offsets', () => {
+ const srt =
+ '1\n00:00:00,000 --> 00:00:01,000\nはい\n\n2\n00:00:01,000 --> 00:01:40,000\nはい\n\n3\n00:01:41,000 --> 00:01:42,000\n幻覚\n';
+ assert.deepEqual(
+ speechPassageCues(srt, { startSeconds: 1200.25, endSeconds: 1203.75 }).map(
+ ({ startTime, endTime, text }) => ({ startTime, endTime, text }),
+ ),
+ [
+ { startTime: 1200.25, endTime: 1201.25, text: 'はい' },
+ { startTime: 1201.25, endTime: 1203.75, text: 'はい' },
+ ],
+ );
+ assert.deepEqual(speechPassageCues('', { startSeconds: 0, endSeconds: 1 }), []);
+ assert.throws(
+ () => speechPassageCues('broken SRT', { startSeconds: 0, endSeconds: 1 }),
+ /malformed/,
+ );
+});
diff --git a/src/core/services/subtitle-generation-speech.ts b/src/core/services/subtitle-generation-speech.ts
new file mode 100644
index 00000000..5e4a65c1
--- /dev/null
+++ b/src/core/services/subtitle-generation-speech.ts
@@ -0,0 +1,66 @@
+import { parseSrtCues, type SubtitleCue } from './subtitle-cue-parser';
+
+export interface SpeechPassage {
+ startSeconds: number;
+ endSeconds: number;
+}
+
+export const SPEECH_PASSAGE_SECONDS = 20;
+
+// The standalone whisper.cpp detector reports centiseconds, unlike its diagnostic logs.
+export function parseSpeechPassages(output: string): SpeechPassage[] {
+ const count = /^Detected (\d+) speech segments:$/m.exec(output);
+ if (!count) throw new Error('Speech detector did not report its segment count.');
+ const passages: SpeechPassage[] = [];
+ for (const line of output.split(/\r?\n/)) {
+ if (!line.startsWith('Speech segment ')) continue;
+ const match = /^Speech segment (\d+): start = (\d+(?:\.\d+)?), end = (\d+(?:\.\d+)?)$/.exec(
+ line,
+ );
+ if (!match) throw new Error('Speech detector returned a malformed segment.');
+ const index = Number(match[1]);
+ const startSeconds = Number(match[2]) / 100;
+ const endSeconds = Number(match[3]) / 100;
+ if (
+ index !== passages.length ||
+ !Number.isFinite(startSeconds) ||
+ !Number.isFinite(endSeconds) ||
+ endSeconds <= startSeconds ||
+ startSeconds < (passages.at(-1)?.endSeconds ?? 0)
+ ) {
+ throw new Error('Speech detector returned unordered or invalid segment timing.');
+ }
+ passages.push({ startSeconds, endSeconds });
+ }
+ if (passages.length !== Number(count[1]))
+ throw new Error('Speech detector output is incomplete.');
+
+ const grouped: SpeechPassage[] = [];
+ for (const passage of passages) {
+ const previous = grouped.at(-1);
+ if (
+ previous &&
+ passage.startSeconds - previous.endSeconds <= 1 &&
+ passage.endSeconds - previous.startSeconds <= SPEECH_PASSAGE_SECONDS
+ ) {
+ previous.endSeconds = passage.endSeconds;
+ } else grouped.push({ ...passage });
+ }
+ return grouped;
+}
+
+// Clamp to the audio actually supplied to Whisper. A cue cannot cross an omitted gap.
+export function speechPassageCues(srt: string, passage: SpeechPassage): SubtitleCue[] {
+ const duration = passage.endSeconds - passage.startSeconds;
+ const cues = parseSrtCues(srt);
+ if (srt.trim() && cues.length === 0)
+ throw new Error('Whisper returned malformed subtitles for a speech passage.');
+ return cues.flatMap((cue) => {
+ const start = Math.max(0, cue.startTime);
+ const end = Math.min(duration, cue.endTime);
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start) return [];
+ return [
+ { ...cue, startTime: passage.startSeconds + start, endTime: passage.startSeconds + end },
+ ];
+ });
+}
diff --git a/src/core/services/subtitle-generation-srt.ts b/src/core/services/subtitle-generation-srt.ts
new file mode 100644
index 00000000..fec683a5
--- /dev/null
+++ b/src/core/services/subtitle-generation-srt.ts
@@ -0,0 +1,7 @@
+export function formatTimestamp(milliseconds: number): string {
+ const rounded = Math.max(0, Math.round(milliseconds));
+ const hours = Math.floor(rounded / 3600000);
+ const minutes = Math.floor((rounded % 3600000) / 60000);
+ const seconds = Math.floor((rounded % 60000) / 1000);
+ return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')},${String(rounded % 1000).padStart(3, '0')}`;
+}
diff --git a/src/core/services/subtitle-generation-tools.test.ts b/src/core/services/subtitle-generation-tools.test.ts
new file mode 100644
index 00000000..7b057735
--- /dev/null
+++ b/src/core/services/subtitle-generation-tools.test.ts
@@ -0,0 +1,85 @@
+import assert from 'node:assert/strict';
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+import { DEFAULT_SUBTITLE_GENERATION_CONFIG } from '../../shared/subtitle-generation';
+import {
+ requireSubtitleGenerationTools,
+ resolveSubtitleGenerationTools,
+} from './subtitle-generation-tools';
+
+async function fixture(run: (directory: string) => Promise) {
+ const directory = await mkdtemp(path.join(tmpdir(), 'subtitle-generation-tools-'));
+ try {
+ await run(directory);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+}
+
+async function executable(directory: string, name: string): Promise {
+ const file = path.join(directory, name);
+ await writeFile(file, '#!/bin/sh\n', { mode: 0o755 });
+ return file;
+}
+
+test('tools resolve from PATH, honor overrides, and only require the detector in dialogue mode', () =>
+ fixture(async (directory) => {
+ const bin = path.join(directory, 'bin');
+ await mkdir(bin);
+ for (const name of ['ffmpeg', 'ffprobe', 'whisper-cli']) await executable(bin, name);
+ const detector = await executable(bin, 'vad-speech-segments');
+ const customWhisper = await executable(directory, 'my-whisper');
+ await writeFile(path.join(directory, 'not-executable'), '', { mode: 0o644 });
+ const env = { PATH: bin };
+
+ const found = await resolveSubtitleGenerationTools(DEFAULT_SUBTITLE_GENERATION_CONFIG, env);
+ assert.deepEqual(found, {
+ ffmpeg: { kind: 'found', path: path.join(bin, 'ffmpeg') },
+ ffprobe: { kind: 'found', path: path.join(bin, 'ffprobe') },
+ whisper: { kind: 'found', path: path.join(bin, 'whisper-cli') },
+ vad: null,
+ });
+ assert.equal(requireSubtitleGenerationTools(found).vad, null);
+
+ const dialogue = await resolveSubtitleGenerationTools(
+ { ...DEFAULT_SUBTITLE_GENERATION_CONFIG, vadModelPath: '/models/vad.bin' },
+ env,
+ );
+ assert.deepEqual(dialogue.vad, { kind: 'found', path: detector });
+
+ const overridden = await resolveSubtitleGenerationTools(
+ {
+ ...DEFAULT_SUBTITLE_GENERATION_CONFIG,
+ whisperPath: customWhisper,
+ ffmpegPath: path.join(directory, 'not-executable'),
+ },
+ env,
+ );
+ assert.deepEqual(overridden.whisper, { kind: 'found', path: customWhisper });
+ assert.equal(overridden.ffmpeg.kind, 'missing');
+ assert.throws(
+ () => requireSubtitleGenerationTools(overridden),
+ /not-executable \(subtitleGeneration\.ffmpegPath\) is not an executable file/,
+ );
+ }));
+
+test('missing tools name the executable, the installer, and the setting', () =>
+ fixture(async (directory) => {
+ const tools = await resolveSubtitleGenerationTools(
+ { ...DEFAULT_SUBTITLE_GENERATION_CONFIG, vadModelPath: '/models/vad.bin' },
+ { PATH: directory },
+ );
+ assert.deepEqual(tools.whisper, {
+ kind: 'missing',
+ message:
+ 'whisper-cli was not found on PATH. Install whisper.cpp or set subtitleGeneration.whisperPath in Settings.',
+ });
+ assert.deepEqual(tools.vad, {
+ kind: 'missing',
+ message:
+ "whisper-vad-speech-segments was not found on PATH. Install whisper.cpp's speech segment detector or set subtitleGeneration.vadPath in Settings.",
+ });
+ assert.throws(() => requireSubtitleGenerationTools(tools), /ffmpeg was not found on PATH/);
+ }));
diff --git a/src/core/services/subtitle-generation-tools.ts b/src/core/services/subtitle-generation-tools.ts
new file mode 100644
index 00000000..0477bb1b
--- /dev/null
+++ b/src/core/services/subtitle-generation-tools.ts
@@ -0,0 +1,125 @@
+import { access, stat } from 'node:fs/promises';
+import { constants } from 'node:fs';
+import path from 'node:path';
+import type {
+ SubtitleGenerationConfig,
+ SubtitleGenerationToolStatus,
+ SubtitleGenerationTools,
+} from '../../shared/subtitle-generation';
+import { expandSubtitleGenerationPath } from './subtitle-generation-files';
+
+/** Executable paths ready to spawn. `vad` is null when dialogue mode is off. */
+export interface SubtitleGenerationToolPaths {
+ ffmpeg: string;
+ ffprobe: string;
+ whisper: string;
+ vad: string | null;
+}
+
+const TOOL_LOOKUPS = {
+ ffmpeg: { setting: 'ffmpegPath', names: ['ffmpeg'], install: 'Install FFmpeg' },
+ ffprobe: { setting: 'ffprobePath', names: ['ffprobe'], install: 'Install FFmpeg' },
+ whisper: { setting: 'whisperPath', names: ['whisper-cli'], install: 'Install whisper.cpp' },
+ vad: {
+ setting: 'vadPath',
+ names: ['whisper-vad-speech-segments', 'vad-speech-segments'],
+ install: "Install whisper.cpp's speech segment detector",
+ },
+} as const;
+
+async function isExecutableFile(filePath: string): Promise {
+ try {
+ if (!(await stat(filePath)).isFile()) return false;
+ await access(filePath, constants.X_OK);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function executableNames(name: string, env: NodeJS.ProcessEnv): string[] {
+ if (process.platform !== 'win32' || path.extname(name)) return [name];
+ const extensions = (env.PATHEXT ?? '.EXE;.CMD;.BAT')
+ .split(';')
+ .map((entry) => entry.trim())
+ .filter(Boolean);
+ return [name, ...extensions.map((extension) => `${name}${extension}`)];
+}
+
+async function findOnPath(names: readonly string[], env: NodeJS.ProcessEnv): Promise {
+ const directories = (env.PATH ?? '')
+ .split(path.delimiter)
+ .map((entry) => entry.trim())
+ .filter(Boolean);
+ for (const directory of directories) {
+ for (const name of names) {
+ for (const candidate of executableNames(name, env)) {
+ const filePath = path.join(directory, candidate);
+ if (await isExecutableFile(filePath)) return filePath;
+ }
+ }
+ }
+ return '';
+}
+
+async function resolveTool(
+ tool: keyof typeof TOOL_LOOKUPS,
+ config: SubtitleGenerationConfig,
+ env: NodeJS.ProcessEnv,
+): Promise {
+ const lookup = TOOL_LOOKUPS[tool];
+ const override = config[lookup.setting].trim();
+ if (override) {
+ const expanded = expandSubtitleGenerationPath(override);
+ const found =
+ path.dirname(expanded) === '.'
+ ? await findOnPath([expanded], env)
+ : (await isExecutableFile(expanded))
+ ? path.resolve(expanded)
+ : '';
+ return found
+ ? { kind: 'found', path: found }
+ : {
+ kind: 'missing',
+ message: `${override} (subtitleGeneration.${lookup.setting}) is not an executable file.`,
+ };
+ }
+ const found = await findOnPath(lookup.names, env);
+ return found
+ ? { kind: 'found', path: found }
+ : {
+ kind: 'missing',
+ message: `${lookup.names[0]} was not found on PATH. ${lookup.install} or set subtitleGeneration.${lookup.setting} in Settings.`,
+ };
+}
+
+/** Locate every executable a generation run needs, before any model download or audio work. */
+export async function resolveSubtitleGenerationTools(
+ config: SubtitleGenerationConfig,
+ env: NodeJS.ProcessEnv = process.env,
+): Promise {
+ const [ffmpeg, ffprobe, whisper, vad] = await Promise.all([
+ resolveTool('ffmpeg', config, env),
+ resolveTool('ffprobe', config, env),
+ resolveTool('whisper', config, env),
+ config.vadModelPath.trim() ? resolveTool('vad', config, env) : null,
+ ]);
+ return { ffmpeg, ffprobe, whisper, vad };
+}
+
+function foundPath(tool: SubtitleGenerationToolStatus): string {
+ if (tool.kind === 'missing') throw new Error(tool.message);
+ return tool.path;
+}
+
+/** Throw the first missing tool's message, otherwise narrow to spawnable paths. */
+export function requireSubtitleGenerationTools(
+ tools: SubtitleGenerationTools,
+): SubtitleGenerationToolPaths {
+ return {
+ ffmpeg: foundPath(tools.ffmpeg),
+ ffprobe: foundPath(tools.ffprobe),
+ whisper: foundPath(tools.whisper),
+ vad: tools.vad ? foundPath(tools.vad) : null,
+ };
+}
diff --git a/src/core/services/subtitle-generation-vad-model.ts b/src/core/services/subtitle-generation-vad-model.ts
new file mode 100644
index 00000000..7a17d9ec
--- /dev/null
+++ b/src/core/services/subtitle-generation-vad-model.ts
@@ -0,0 +1,63 @@
+import { access, stat } from 'node:fs/promises';
+import { constants } from 'node:fs';
+import path from 'node:path';
+import type {
+ SubtitleGenerationConfig,
+ SubtitleGenerationModelStatus,
+ SubtitleGenerationProgress,
+} from '../../shared/subtitle-generation';
+import { SUBTITLE_GENERATION_VAD_MODEL } from '../../shared/subtitle-generation-vad-model';
+import { expandSubtitleGenerationPath } from './subtitle-generation-files';
+import { isMissingFile } from './subtitle-generation-models';
+import { downloadSubtitleGenerationArtifact } from './subtitle-generation-download';
+
+export async function resolveSubtitleGenerationVadModel(
+ config: SubtitleGenerationConfig,
+ modelDirectory: string,
+): Promise {
+ const external = config.vadModelPath.trim();
+ const modelPath = external
+ ? path.resolve(expandSubtitleGenerationPath(external))
+ : path.resolve(modelDirectory, SUBTITLE_GENERATION_VAD_MODEL.filename);
+ try {
+ const info = await stat(modelPath);
+ if (
+ !info.isFile() ||
+ info.size === 0 ||
+ (!external && info.size !== SUBTITLE_GENERATION_VAD_MODEL.size)
+ )
+ return {
+ kind: 'invalid',
+ path: modelPath,
+ message: 'Speech detection model has an invalid size.',
+ };
+ await access(modelPath, constants.R_OK);
+ return { kind: external ? 'external' : 'managed', path: modelPath };
+ } catch (error) {
+ if (!external && isMissingFile(error)) return { kind: 'missing', path: modelPath };
+ return {
+ kind: 'invalid',
+ path: modelPath,
+ message: `Cannot read speech detection model: ${error instanceof Error ? error.message : String(error)}`,
+ };
+ }
+}
+
+export async function downloadSubtitleGenerationVadModel(input: {
+ config: SubtitleGenerationConfig;
+ modelDirectory: string;
+ onProgress?: (progress: SubtitleGenerationProgress) => void;
+ signal?: AbortSignal;
+}): Promise {
+ input.signal?.throwIfAborted();
+ const current = await resolveSubtitleGenerationVadModel(input.config, input.modelDirectory);
+ if (current.kind === 'invalid') throw new Error(current.message);
+ if (current.kind !== 'missing') return current.path;
+ return downloadSubtitleGenerationArtifact({
+ ...SUBTITLE_GENERATION_VAD_MODEL,
+ destination: current.path,
+ label: 'Silero speech detection model',
+ onProgress: input.onProgress,
+ signal: input.signal,
+ });
+}
diff --git a/src/core/services/subtitle-generation.test.ts b/src/core/services/subtitle-generation.test.ts
new file mode 100644
index 00000000..4637c7ca
--- /dev/null
+++ b/src/core/services/subtitle-generation.test.ts
@@ -0,0 +1,454 @@
+import assert from 'node:assert/strict';
+import { constants } from 'node:fs';
+import { access, chmod, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+import {
+ DEFAULT_SUBTITLE_GENERATION_CONFIG,
+ resolveSubtitleGenerationConfig,
+ type SubtitleGenerationProgress,
+} from '../../shared/subtitle-generation';
+import {
+ downloadSubtitleGenerationModel,
+ ensureWritableDirectory,
+ generateJapaneseSubtitles,
+ resolveSubtitleGenerationModel,
+} from './subtitle-generation';
+import { runSubtitleGenerationProcess } from './subtitle-generation-process';
+
+async function fixture(run: (directory: string) => Promise) {
+ const directory = await mkdtemp(path.join(tmpdir(), 'subtitle-generation-test-'));
+ try {
+ await run(directory);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+}
+
+async function executable(directory: string, name: string, body: string) {
+ const file = path.join(directory, name);
+ await writeFile(file, `#!${process.execPath}\n${body}`, { mode: 0o755 });
+ return file;
+}
+
+function modelHeader(vocabularySize = 51865): Buffer {
+ const header = Buffer.alloc(8);
+ header.writeUInt32LE(0x67676d6c, 0);
+ header.writeInt32LE(vocabularySize, 4);
+ return header;
+}
+
+async function generationFixture(directory: string) {
+ const modelPath = path.join(directory, 'external.bin');
+ const mediaPath = path.join(directory, 'episode.mkv');
+ const callsPath = path.join(directory, 'calls.jsonl');
+ await writeFile(modelPath, modelHeader());
+ await writeFile(mediaPath, 'local media');
+ const record = `require('node:fs').appendFileSync(${JSON.stringify(callsPath)}, JSON.stringify(process.argv.slice(2)) + '\\n');`;
+ const ffprobePath = await executable(
+ directory,
+ 'ffprobe',
+ `${record}\nprocess.stdout.write(JSON.stringify({streams: [{index:1,codec_type:'audio',start_time:'10',tags:{language:'eng'}},{index:3,codec_type:'audio',start_time:'12.5',duration:'20',tags:{language:'jpn'}}],format:{start_time:'10',duration:'25'}}));`,
+ );
+ const ffmpegPath = await executable(
+ directory,
+ 'ffmpeg',
+ `${record}
+if (process.argv.at(-1) === '-') {
+ process.stderr.write('[silencedetect] silence_end: 25 | silence_duration: 25\\n');
+ process.stdout.write('out_time_us=25000000\\nprogress=end\\n');
+} else {
+ require('node:fs').writeFileSync(process.argv.at(-1), 'wav');
+ process.stdout.write('out_time_');
+ setTimeout(() => process.stdout.write('us=10000000\\nprogress=end\\n'), 10);
+}`,
+ );
+ const whisperPath = await executable(
+ directory,
+ 'whisper-cli',
+ `${record}\nconst args=process.argv.slice(2); require('node:fs').writeFileSync(args[args.indexOf('-of')+1]+'.srt', '1\\n00:00:01,000 --> 00:00:02,000\\nこんにちは\\n'); process.stderr.write('whisper_print_progress_callback: progress = '); setTimeout(() => process.stderr.write('55%\\n'), 10);`,
+ );
+ return {
+ config: {
+ ...DEFAULT_SUBTITLE_GENERATION_CONFIG,
+ modelPath,
+ ffprobePath,
+ ffmpegPath,
+ whisperPath,
+ },
+ mediaPath,
+ modelDirectory: path.join(directory, 'models'),
+ callsPath,
+ };
+}
+
+test('config parser accepts supported models and rejects unsafe threads and wrong field types', () => {
+ const warnings: string[] = [];
+ const result = resolveSubtitleGenerationConfig(
+ { modelPath: '/tmp/whisper.bin', threads: 0, whisperPath: 42, managedModel: 'large-v3-turbo' },
+ (key) => warnings.push(key),
+ );
+ assert.equal(result.modelPath, '/tmp/whisper.bin');
+ assert.equal(result.managedModel, 'large-v3-turbo');
+ assert.equal(result.threads, DEFAULT_SUBTITLE_GENERATION_CONFIG.threads);
+ assert.deepEqual(warnings, ['whisperPath', 'threads']);
+});
+
+test('external model path wins and invalid external models never fall back to download', () =>
+ fixture(async (directory) => {
+ const input = await generationFixture(directory);
+ assert.deepEqual(await resolveSubtitleGenerationModel(input.config, input.modelDirectory), {
+ kind: 'external',
+ path: input.config.modelPath,
+ });
+ const invalid = { ...input.config, modelPath: path.join(directory, 'missing.bin') };
+ assert.equal(
+ (await resolveSubtitleGenerationModel(invalid, input.modelDirectory)).kind,
+ 'invalid',
+ );
+ await assert.rejects(
+ downloadSubtitleGenerationModel({ ...input, config: invalid }),
+ /Cannot read model/,
+ );
+ assert.equal(
+ (
+ await resolveSubtitleGenerationModel(
+ { ...input.config, modelPath: '' },
+ input.modelDirectory,
+ )
+ ).kind,
+ 'missing',
+ );
+ }));
+
+test('English-only and incompatible external models are rejected before transcription', () =>
+ fixture(async (directory) => {
+ const input = await generationFixture(directory);
+ await writeFile(input.config.modelPath, modelHeader(51864));
+ const englishOnly = await resolveSubtitleGenerationModel(input.config, input.modelDirectory);
+ assert.equal(englishOnly.kind, 'invalid');
+ assert.ok('message' in englishOnly);
+ assert.match(englishOnly.message, /English-only/);
+ await assert.rejects(generateJapaneseSubtitles(input), /requires a multilingual model/);
+ await writeFile(input.config.modelPath, 'not a GGML model');
+ await assert.rejects(generateJapaneseSubtitles(input), /Unsupported model format/);
+ await writeFile(input.config.modelPath, modelHeader().subarray(0, 4));
+ await assert.rejects(generateJapaneseSubtitles(input), /Unsupported model format/);
+ await assert.rejects(readFile(input.callsPath), /ENOENT/);
+ }));
+
+test('generation picks Japanese audio, restores timeline offsets, reports split progress, and preserves existing output', () =>
+ fixture(async (directory) => {
+ const input = await generationFixture(directory);
+ const existing = path.join(directory, 'episode.ja.generated.srt');
+ await writeFile(existing, 'user subtitles');
+ const progress: SubtitleGenerationProgress[] = [];
+ const result = await generateJapaneseSubtitles({
+ ...input,
+ onProgress: (event) => progress.push(event),
+ });
+ assert.equal(result, path.join(directory, 'episode.ja.generated.1.srt'));
+ assert.equal(await readFile(existing, 'utf8'), 'user subtitles');
+ assert.match(await readFile(result, 'utf8'), /00:00:03,500 --> 00:00:04,500\nこんにちは/);
+ const calls = (await readFile(input.callsPath, 'utf8'))
+ .trim()
+ .split('\n')
+ .map((line): unknown => JSON.parse(line));
+ assert.ok(Array.isArray(calls[1]));
+ assert.ok(calls[1].includes('0:3'));
+ assert.ok(Array.isArray(calls[2]));
+ assert.ok(calls[2].includes('ja'));
+ assert.ok(calls[2].includes('-osrt'));
+ assert.ok(progress.some((event) => event.stage === 'extract' && event.percent === 50));
+ assert.ok(progress.some((event) => event.stage === 'transcribe' && event.percent === 55));
+ assert.deepEqual(
+ (await readdir(directory)).filter((file) => file.startsWith('.subminer-')),
+ [],
+ );
+ }));
+
+test('explicit audio stream and output path are respected without overwriting existing files', () =>
+ fixture(async (directory) => {
+ const input = await generationFixture(directory);
+ const outputPath = path.join(directory, 'chosen.srt');
+ const result = await generateJapaneseSubtitles({ ...input, audioStreamIndex: 1, outputPath });
+ assert.equal(result, outputPath);
+ assert.match(await readFile(result, 'utf8'), /00:00:01,000 --> 00:00:02,000/);
+ await assert.rejects(generateJapaneseSubtitles({ ...input, outputPath }), /already exists/);
+ await assert.rejects(
+ generateJapaneseSubtitles({ ...input, audioStreamIndex: 99 }),
+ /stream 99 was not found/,
+ );
+ }));
+
+test('dialogue generation isolates Whisper state between passages and preserves media timing', () =>
+ fixture(async (directory) => {
+ const input = await generationFixture(directory);
+ const vadModelPath = path.join(directory, 'vad.bin');
+ await writeFile(vadModelPath, 'speech detector model');
+ const vadPath = await executable(
+ directory,
+ 'vad',
+ "process.stdout.write('Detected 2 speech segments:\\nSpeech segment 0: start = 1000.00, end = 1100.00\\nSpeech segment 1: start = 10000.00, end = 10100.00\\n');",
+ );
+ const whisperPath = await executable(
+ directory,
+ 'dialogue-whisper',
+ `const args = process.argv.slice(2);
+let files = 0;
+for (let i = 0; i < args.length; i++) if (args[i] === '-of') {
+ // Reproduce a decoder that degenerates when reused for another audio file.
+ const text = files++ === 0 ? 'はい' : 'お' + 'ぉ'.repeat(40) + 'ぇ'.repeat(178);
+ require('node:fs').writeFileSync(args[i + 1] + '.srt', '1\\n00:00:00,000 --> 00:01:39,000\\n' + text + '\\n');
+}`,
+ );
+ const output = await generateJapaneseSubtitles({
+ ...input,
+ config: { ...input.config, vadModelPath, vadPath, whisperPath },
+ });
+ assert.equal(
+ await readFile(output, 'utf8'),
+ '1\n00:00:12,500 --> 00:00:13,500\nはい\n\n2\n00:01:42,500 --> 00:01:43,500\nはい\n',
+ );
+ }));
+
+test('dialogue generation uses quiet pauses and stitches overlapping chunks on the media timeline', () =>
+ fixture(async (directory) => {
+ const input = await generationFixture(directory);
+ const vadModelPath = path.join(directory, 'vad.bin');
+ await writeFile(vadModelPath, 'speech detector model');
+ const vadPath = await executable(
+ directory,
+ 'vad',
+ `const assert = require('node:assert/strict');
+const args = process.argv.slice(2);
+assert.equal(args[args.indexOf('--vad-min-speech-duration-ms') + 1], '100');
+assert.equal(args[args.indexOf('-vp') + 1], '350');
+process.stdout.write('Detected 1 speech segments:\\nSpeech segment 0: start = 1000.00, end = 4500.00\\n');`,
+ );
+ const ffmpegPath = await executable(
+ directory,
+ 'pause-ffmpeg',
+ `const args = process.argv.slice(2);
+if (args.includes('silencedetect=noise=-50dB:d=0.5')) {
+ process.stderr.write('[silencedetect] silence_end: 45 | silence_duration: 45\\n');
+ process.stdout.write('out_time_us=45000000\\n');
+} else if (args.includes('-af')) {
+ process.stderr.write('[silencedetect] silence_end: 28.1 | silence_duration: 0.2\\n');
+} else {
+ require('node:fs').writeFileSync(args.at(-1), 'wav');
+}`,
+ );
+ const whisperPath = await executable(
+ directory,
+ 'overlap-whisper',
+ `const args = process.argv.slice(2);
+for (let i = 0; i < args.length; i++) if (args[i] === '-of') {
+ const time = args[i + 1].endsWith('speech-0')
+ ? '00:00:17,800 --> 00:00:18,250'
+ : '00:00:00,100 --> 00:00:00,650';
+ require('node:fs').writeFileSync(args[i + 1] + '.srt', '1\\n' + time + '\\nはい\\n');
+}`,
+ );
+ const output = await generateJapaneseSubtitles({
+ ...input,
+ config: { ...input.config, vadModelPath, vadPath, ffmpegPath, whisperPath },
+ });
+ assert.equal(await readFile(output, 'utf8'), '1\n00:00:30,300 --> 00:00:30,900\nはい\n');
+ }));
+
+test('silent audio with no detected speech stops generation without transcription', () =>
+ fixture(async (directory) => {
+ const input = await generationFixture(directory);
+ const vadModelPath = path.join(directory, 'vad.bin');
+ await writeFile(vadModelPath, 'speech detector model');
+ const vadPath = await executable(
+ directory,
+ 'vad',
+ "process.stdout.write('Detected 0 speech segments:\\n');",
+ );
+ await assert.rejects(
+ generateJapaneseSubtitles({ ...input, config: { ...input.config, vadModelPath, vadPath } }),
+ /No spoken dialogue detected/,
+ );
+ assert.equal((await readFile(input.callsPath, 'utf8')).trim().split('\n').length, 3);
+ assert.deepEqual(
+ (await readdir(directory)).filter((file) => file.endsWith('.srt')),
+ [],
+ );
+ }));
+
+test('dialogue generation retains audible audio rejected by VAD', () =>
+ fixture(async (directory) => {
+ const input = await generationFixture(directory);
+ const vadModelPath = path.join(directory, 'vad.bin');
+ await writeFile(vadModelPath, 'speech detector model');
+ const vadPath = await executable(
+ directory,
+ 'vad',
+ "process.stdout.write('Detected 0 speech segments:\\n');",
+ );
+ const ffmpegPath = await executable(
+ directory,
+ 'audible-ffmpeg',
+ `
+const args = process.argv.slice(2);
+if (args.at(-1) === '-') {
+ process.stdout.write('out_time_us=19000000\\nprogress=end\\n');
+} else {
+ require('node:fs').writeFileSync(args.at(-1), 'wav');
+}`,
+ );
+ const output = await generateJapaneseSubtitles({
+ ...input,
+ config: { ...input.config, vadModelPath, vadPath, ffmpegPath },
+ });
+ assert.match(await readFile(output, 'utf8'), /00:00:03,500 --> 00:00:04,500\nこんにちは/);
+ }));
+
+test('empty executable paths find tools on PATH and explicit overrides take precedence', () =>
+ fixture(async (directory) => {
+ const input = await generationFixture(directory);
+ const previousPath = process.env.PATH;
+ process.env.PATH = directory;
+ try {
+ const config = {
+ ...DEFAULT_SUBTITLE_GENERATION_CONFIG,
+ modelPath: input.config.modelPath,
+ };
+ const result = await generateJapaneseSubtitles({ ...input, config });
+ assert.match(await readFile(result, 'utf8'), /こんにちは/);
+ await assert.rejects(
+ generateJapaneseSubtitles({
+ ...input,
+ config: { ...config, ffprobePath: path.join(directory, 'missing-override') },
+ }),
+ /missing-override \(subtitleGeneration\.ffprobePath\) is not an executable file/,
+ );
+ } finally {
+ if (previousPath === undefined) delete process.env.PATH;
+ else process.env.PATH = previousPath;
+ }
+ }));
+
+test('generation rejects remote media, missing models, and missing tools before starting a subprocess', () =>
+ fixture(async (directory) => {
+ const input = await generationFixture(directory);
+ await assert.rejects(
+ generateJapaneseSubtitles({ ...input, mediaPath: 'https://example.com/movie.mkv' }),
+ /local media file/,
+ );
+ await assert.rejects(
+ generateJapaneseSubtitles({ ...input, config: { ...input.config, modelPath: '' } }),
+ /No Whisper model found/,
+ );
+ await assert.rejects(
+ generateJapaneseSubtitles({
+ ...input,
+ config: {
+ ...input.config,
+ vadModelPath: path.join(directory, 'vad.bin'),
+ vadPath: path.join(directory, 'missing-detector'),
+ },
+ }),
+ /missing-detector \(subtitleGeneration\.vadPath\) is not an executable file/,
+ );
+ await assert.rejects(readFile(input.callsPath), /ENOENT/);
+ }));
+
+test(
+ 'directory permission preflight rejects a write-only destination',
+ {
+ skip: process.platform === 'win32' || process.getuid?.() === 0,
+ },
+ () =>
+ fixture(async (directory) => {
+ const writeOnly = path.join(directory, 'write-only');
+ await mkdir(writeOnly);
+ try {
+ await chmod(writeOnly, 0o200);
+ await access(writeOnly, constants.W_OK);
+ await assert.rejects(ensureWritableDirectory(writeOnly), /write-only is not writable/);
+ } finally {
+ await chmod(writeOnly, 0o755);
+ }
+ }),
+);
+
+test(
+ 'generation rejects an unwritable destination before extracting audio',
+ {
+ skip: process.platform === 'win32' || process.getuid?.() === 0,
+ },
+ () =>
+ fixture(async (directory) => {
+ const input = await generationFixture(directory);
+ const readOnly = path.join(directory, 'read-only');
+ await mkdir(readOnly, { mode: 0o555 });
+ try {
+ await assert.rejects(
+ generateJapaneseSubtitles({ ...input, outputPath: path.join(readOnly, 'out.srt') }),
+ /read-only is not writable/,
+ );
+ await assert.rejects(readFile(input.callsPath), /ENOENT/);
+ } finally {
+ await chmod(readOnly, 0o755);
+ }
+ }),
+);
+
+test('process cancellation terminates work and bounds diagnostic output', () =>
+ fixture(async (directory) => {
+ const slow = await executable(
+ directory,
+ 'slow',
+ "process.stdout.write('ready\\n');setInterval(()=>{},1000);",
+ );
+ const controller = new AbortController();
+ await assert.rejects(
+ runSubtitleGenerationProcess({
+ command: slow,
+ args: [],
+ signal: controller.signal,
+ onLine: () => controller.abort(),
+ }),
+ /cancelled/,
+ );
+ const failed = await executable(
+ directory,
+ 'failed',
+ "process.stderr.write('x'.repeat(100000));process.exitCode=7;",
+ );
+ await assert.rejects(
+ runSubtitleGenerationProcess({ command: failed, args: [] }),
+ (error: unknown) =>
+ error instanceof Error &&
+ error.message.length < 66000 &&
+ error.message.includes('status 7'),
+ );
+ }));
+
+test('download uses the pinned model revision and removes files that fail integrity', () =>
+ fixture(async (directory) => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = Object.assign(async (request: string | URL | Request) => {
+ assert.equal(
+ request,
+ 'https://huggingface.co/ggerganov/whisper.cpp/resolve/5359861c739e955e79d9a303bcbc70fb988958b1/ggml-small.bin',
+ );
+ return new Response('not a model');
+ }, originalFetch);
+ try {
+ await assert.rejects(
+ downloadSubtitleGenerationModel({
+ config: DEFAULT_SUBTITLE_GENERATION_CONFIG,
+ modelDirectory: directory,
+ }),
+ /integrity verification/,
+ );
+ assert.deepEqual(await readdir(directory), []);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ }));
diff --git a/src/core/services/subtitle-generation.ts b/src/core/services/subtitle-generation.ts
new file mode 100644
index 00000000..0932ac96
--- /dev/null
+++ b/src/core/services/subtitle-generation.ts
@@ -0,0 +1,315 @@
+import { access, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
+import { constants } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import type {
+ SubtitleGenerationConfig,
+ SubtitleGenerationProgress,
+} from '../../shared/subtitle-generation';
+import { isMissingFile, resolveSubtitleGenerationModel } from './subtitle-generation-models';
+import { runSubtitleGenerationProcess } from './subtitle-generation-process';
+import { publishSubtitleGenerationFile } from './subtitle-generation-files';
+import { formatTimestamp } from './subtitle-generation-srt';
+import { transcribeSubtitleDialogue } from './subtitle-generation-dialogue';
+import {
+ requireSubtitleGenerationTools,
+ resolveSubtitleGenerationTools,
+} from './subtitle-generation-tools';
+
+export {
+ downloadSubtitleGenerationModel,
+ resolveSubtitleGenerationModel,
+} from './subtitle-generation-models';
+export { resolveSubtitleGenerationTools } from './subtitle-generation-tools';
+
+function numericTime(value: unknown): number | undefined {
+ if (typeof value !== 'number' && typeof value !== 'string') return undefined;
+ const number = Number(value);
+ return Number.isFinite(number) ? number : undefined;
+}
+
+function parseAudioProbe(raw: string, selectedIndex: number | undefined) {
+ const value: unknown = JSON.parse(raw);
+ if (
+ typeof value !== 'object' ||
+ value === null ||
+ !('streams' in value) ||
+ !Array.isArray(value.streams)
+ ) {
+ throw new Error('ffprobe did not return media streams.');
+ }
+ const streams = value.streams.flatMap((stream: unknown) => {
+ if (
+ typeof stream !== 'object' ||
+ stream === null ||
+ !('codec_type' in stream) ||
+ stream.codec_type !== 'audio' ||
+ !('index' in stream) ||
+ typeof stream.index !== 'number' ||
+ !Number.isInteger(stream.index) ||
+ stream.index < 0
+ )
+ return [];
+ const tags = 'tags' in stream ? stream.tags : undefined;
+ const language =
+ typeof tags === 'object' && tags !== null && 'language' in tags ? tags.language : undefined;
+ return [
+ {
+ index: stream.index,
+ start: 'start_time' in stream ? numericTime(stream.start_time) : undefined,
+ duration: 'duration' in stream ? numericTime(stream.duration) : undefined,
+ japanese: language === 'ja' || language === 'jpn',
+ },
+ ];
+ });
+ const selected =
+ selectedIndex === undefined
+ ? (streams.find((stream) => stream.japanese) ?? streams[0])
+ : streams.find((stream) => stream.index === selectedIndex);
+ if (!selected)
+ throw new Error(
+ selectedIndex === undefined
+ ? 'No audio track found.'
+ : `Audio stream ${selectedIndex} was not found.`,
+ );
+ const format = 'format' in value ? value.format : undefined;
+ const formatStart =
+ typeof format === 'object' && format !== null && 'start_time' in format
+ ? (numericTime(format.start_time) ?? 0)
+ : 0;
+ const duration =
+ selected.duration ??
+ (typeof format === 'object' && format !== null && 'duration' in format
+ ? numericTime(format.duration)
+ : undefined);
+ // mpv rebases media timestamps to the container start. Extraction rebases the selected audio.
+ return { index: selected.index, offset: (selected.start ?? formatStart) - formatStart, duration };
+}
+
+function shiftSubtitleTimestamps(srt: string, offsetSeconds: number): string {
+ let cueCount = 0;
+ const result = srt.replace(
+ /(\d{2,}):(\d{2}):(\d{2}),(\d{3}) --> (\d{2,}):(\d{2}):(\d{2}),(\d{3})/g,
+ (
+ _match,
+ sh: string,
+ sm: string,
+ ss: string,
+ sms: string,
+ eh: string,
+ em: string,
+ es: string,
+ ems: string,
+ ) => {
+ cueCount += 1;
+ const start = Number(sh) * 3600000 + Number(sm) * 60000 + Number(ss) * 1000 + Number(sms);
+ const end = Number(eh) * 3600000 + Number(em) * 60000 + Number(es) * 1000 + Number(ems);
+ return `${formatTimestamp(start + offsetSeconds * 1000)} --> ${formatTimestamp(end + offsetSeconds * 1000)}`;
+ },
+ );
+ if (cueCount === 0)
+ throw new Error(
+ 'Whisper produced no subtitle cues. The audio may contain no recognized speech.',
+ );
+ return result;
+}
+
+async function ensureAvailableOutput(outputPath: string): Promise {
+ try {
+ await stat(outputPath);
+ } catch (error) {
+ if (isMissingFile(error)) return;
+ throw error;
+ }
+ throw new Error(`Subtitle output already exists: ${outputPath}`);
+}
+
+// Fail before extraction and transcription when the destination cannot take the file.
+export async function ensureWritableDirectory(directory: string): Promise {
+ try {
+ await access(directory, constants.W_OK | constants.X_OK);
+ } catch {
+ throw new Error(`Cannot save subtitles: ${directory} is not writable.`);
+ }
+}
+
+async function writeSubtitles(input: {
+ mediaPath: string;
+ outputPath?: string;
+ contents: string;
+ signal?: AbortSignal;
+}): Promise {
+ const parsed = path.parse(input.mediaPath);
+ const directory = input.outputPath ? path.dirname(path.resolve(input.outputPath)) : parsed.dir;
+ const temporaryDirectory = await mkdtemp(path.join(directory, '.subminer-subtitles-'));
+ try {
+ const staged = path.join(temporaryDirectory, 'subtitles.srt');
+ await writeFile(staged, input.contents, { flag: 'wx' });
+ for (let suffix = 0; ; suffix += 1) {
+ input.signal?.throwIfAborted();
+ const destination = input.outputPath
+ ? path.resolve(input.outputPath)
+ : path.join(directory, `${parsed.name}.ja.generated${suffix ? `.${suffix}` : ''}.srt`);
+ try {
+ await publishSubtitleGenerationFile(staged, destination);
+ return destination;
+ } catch (error) {
+ if (
+ !input.outputPath &&
+ error instanceof Error &&
+ 'code' in error &&
+ error.code === 'EEXIST'
+ )
+ continue;
+ throw error;
+ }
+ }
+ } finally {
+ await rm(temporaryDirectory, { recursive: true, force: true });
+ }
+}
+
+export async function generateJapaneseSubtitles(input: {
+ config: SubtitleGenerationConfig;
+ modelDirectory: string;
+ mediaPath: string;
+ audioStreamIndex?: number;
+ outputPath?: string;
+ onProgress?: (progress: SubtitleGenerationProgress) => void;
+ signal?: AbortSignal;
+}): Promise {
+ input.signal?.throwIfAborted();
+ if (/^[a-z][a-z\d+.-]*:\/\//i.test(input.mediaPath))
+ throw new Error('Subtitle generation requires a local media file.');
+ const mediaPath = path.resolve(input.mediaPath);
+ if (!(await stat(mediaPath)).isFile())
+ throw new Error('Subtitle generation requires a local media file.');
+ if (input.outputPath) await ensureAvailableOutput(path.resolve(input.outputPath));
+ await ensureWritableDirectory(
+ input.outputPath ? path.dirname(path.resolve(input.outputPath)) : path.dirname(mediaPath),
+ );
+ const model = await resolveSubtitleGenerationModel(input.config, input.modelDirectory);
+ if (model.kind === 'missing')
+ throw new Error(
+ 'No Whisper model found. Download a model or configure an existing model path.',
+ );
+ if (model.kind === 'invalid') throw new Error(model.message);
+ const tools = requireSubtitleGenerationTools(await resolveSubtitleGenerationTools(input.config));
+ input.onProgress?.({ stage: 'extract', message: 'Inspecting audio tracks...' });
+ const probe = await runSubtitleGenerationProcess({
+ command: tools.ffprobe,
+ args: [
+ '-v',
+ 'error',
+ '-show_entries',
+ 'stream=index,codec_type,start_time,duration:stream_tags=language:format=start_time,duration',
+ '-of',
+ 'json',
+ mediaPath,
+ ],
+ signal: input.signal,
+ });
+ const audio = parseAudioProbe(probe, input.audioStreamIndex);
+ const temporaryDirectory = await mkdtemp(path.join(tmpdir(), 'subminer-whisper-'));
+ try {
+ const wavPath = path.join(temporaryDirectory, 'audio.wav');
+ const subtitleBase = path.join(temporaryDirectory, 'subtitles');
+ input.onProgress?.({ stage: 'extract', percent: 0, message: 'Extracting audio...' });
+ await runSubtitleGenerationProcess({
+ command: tools.ffmpeg,
+ args: [
+ '-nostdin',
+ '-hide_banner',
+ '-loglevel',
+ 'error',
+ '-i',
+ mediaPath,
+ '-map',
+ `0:${audio.index}`,
+ '-vn',
+ '-af',
+ 'asetpts=PTS-STARTPTS',
+ '-ac',
+ '1',
+ '-ar',
+ '16000',
+ '-c:a',
+ 'pcm_s16le',
+ '-progress',
+ 'pipe:1',
+ '-nostats',
+ wavPath,
+ ],
+ signal: input.signal,
+ onLine: (line) => {
+ const match = /^out_time_us=(\d+)$/.exec(line);
+ if (match && audio.duration && audio.duration > 0) {
+ input.onProgress?.({
+ stage: 'extract',
+ percent: Math.min(100, Math.floor(Number(match[1]) / 10000 / audio.duration)),
+ message: 'Extracting audio...',
+ });
+ }
+ },
+ });
+ input.onProgress?.({
+ stage: 'transcribe',
+ percent: 0,
+ message: 'Generating Japanese subtitles...',
+ });
+ let srt: string;
+ if (tools.vad !== null) {
+ srt = await transcribeSubtitleDialogue({
+ config: input.config,
+ tools: { ...tools, vad: tools.vad },
+ modelPath: model.path,
+ wavPath,
+ directory: temporaryDirectory,
+ signal: input.signal,
+ onProgress: input.onProgress,
+ });
+ } else {
+ await runSubtitleGenerationProcess({
+ command: tools.whisper,
+ args: [
+ '-m',
+ model.path,
+ '-f',
+ wavPath,
+ '-l',
+ 'ja',
+ '-t',
+ String(input.config.threads),
+ '-osrt',
+ '-of',
+ subtitleBase,
+ '-pp',
+ ],
+ signal: input.signal,
+ onLine: (line) => {
+ const match = /progress\s*=\s*(\d+(?:\.\d+)?)%/.exec(line);
+ if (match)
+ input.onProgress?.({
+ stage: 'transcribe',
+ percent: Math.min(100, Number(match[1])),
+ message: 'Generating Japanese subtitles...',
+ });
+ },
+ });
+ srt = await readFile(`${subtitleBase}.srt`, 'utf8');
+ }
+ input.signal?.throwIfAborted();
+ input.onProgress?.({ stage: 'write', message: 'Saving Japanese subtitles...' });
+ const contents = shiftSubtitleTimestamps(srt, audio.offset);
+ const outputPath = await writeSubtitles({
+ mediaPath,
+ outputPath: input.outputPath,
+ contents,
+ signal: input.signal,
+ });
+ input.onProgress?.({ stage: 'write', percent: 100, message: 'Japanese subtitles are ready.' });
+ return outputPath;
+ } finally {
+ await rm(temporaryDirectory, { recursive: true, force: true });
+ }
+}
diff --git a/src/core/services/tokenizer/golden-corpus-harness.ts b/src/core/services/tokenizer/golden-corpus-harness.ts
index ce17fa35..4a9b7d9e 100644
--- a/src/core/services/tokenizer/golden-corpus-harness.ts
+++ b/src/core/services/tokenizer/golden-corpus-harness.ts
@@ -396,7 +396,8 @@ function createInjectedScriptVm(store: ReplayMessageStore): (script: string) =>
Set,
String,
});
- return async (script: string) => await vm.runInContext(script, context);
+ // Clone results into the host realm, matching Electron's process boundary.
+ return async (script: string) => structuredClone(await vm.runInContext(script, context));
}
export function createReplayTokenizerDeps(fixture: GoldenFixture): TokenizerServiceDeps {
diff --git a/src/core/services/tokenizer/yomitan-scan-test-harness.ts b/src/core/services/tokenizer/yomitan-scan-test-harness.ts
index 01745a96..8c9efeaa 100644
--- a/src/core/services/tokenizer/yomitan-scan-test-harness.ts
+++ b/src/core/services/tokenizer/yomitan-scan-test-harness.ts
@@ -64,7 +64,8 @@ export async function runInjectedYomitanScript(
script: string,
handler: (action: string, params: unknown) => unknown,
): Promise {
- return await vm.runInNewContext(script, createYomitanScriptSandbox(handler));
+ // Clone results into the host realm, matching Electron's process boundary.
+ return structuredClone(await vm.runInNewContext(script, createYomitanScriptSandbox(handler)));
}
// Persistent page context shared across executeJavaScript calls, matching the
@@ -75,7 +76,8 @@ function createPersistentYomitanScriptRunner(
handler: (action: string, params: unknown) => unknown,
): (script: string) => Promise {
const context = vm.createContext(createYomitanScriptSandbox(handler));
- return async (script: string) => await vm.runInContext(script, context);
+ // Clone results into the host realm, matching Electron's process boundary.
+ return async (script: string) => structuredClone(await vm.runInContext(script, context));
}
// Deps whose parser window executes every injected script (profile metadata,
diff --git a/src/core/utils/shortcut-config.ts b/src/core/utils/shortcut-config.ts
index b45deeb3..b889031f 100644
--- a/src/core/utils/shortcut-config.ts
+++ b/src/core/utils/shortcut-config.ts
@@ -16,6 +16,7 @@ export interface ConfiguredShortcuts {
openRuntimeOptions: string | null | undefined;
openJimaku: string | null | undefined;
openTsukihime: string | null | undefined;
+ openSubtitleGeneration: string | null | undefined;
openSessionHelp: string | null | undefined;
openControllerSelect: string | null | undefined;
openControllerDebug: string | null | undefined;
@@ -67,6 +68,7 @@ export function resolveConfiguredShortcuts(
openRuntimeOptions: normalizeShortcut(shortcutValue('openRuntimeOptions')),
openJimaku: normalizeShortcut(shortcutValue('openJimaku')),
openTsukihime: normalizeShortcut(shortcutValue('openTsukihime')),
+ openSubtitleGeneration: normalizeShortcut(shortcutValue('openSubtitleGeneration')),
openSessionHelp: normalizeShortcut(shortcutValue('openSessionHelp')),
openControllerSelect: normalizeShortcut(shortcutValue('openControllerSelect')),
openControllerDebug: normalizeShortcut(shortcutValue('openControllerDebug')),
diff --git a/src/main-entry-runtime.test.ts b/src/main-entry-runtime.test.ts
index 7465c372..a6dcff24 100644
--- a/src/main-entry-runtime.test.ts
+++ b/src/main-entry-runtime.test.ts
@@ -585,24 +585,58 @@ test('shouldDetachBackgroundLaunch only for first background invocation', () =>
test('configureEarlyAppPaths pins userData to canonical SubMiner config dir', () => {
const calls: string[] = [];
-
- const userDataPath = configureEarlyAppPaths(
- {
- setName: (name) => {
- calls.push(`name:${name}`);
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-entry-paths-'));
+ const configDir = path.posix.join(tempDir, 'SubMiner');
+ try {
+ const userDataPath = configureEarlyAppPaths(
+ {
+ setName: (name) => {
+ calls.push(`name:${name}`);
+ },
+ setPath: (key, value) => {
+ calls.push(`path:${key}:${value}`);
+ },
},
- setPath: (key, value) => {
- calls.push(`path:${key}:${value}`);
+ {
+ platform: 'linux',
+ homeDir: tempDir,
+ xdgConfigHome: tempDir,
+ existsSync: (candidate) =>
+ candidate === path.posix.join(tempDir, 'subminer', 'config.jsonc'),
},
- },
- {
- platform: 'linux',
- homeDir: '/home/tester',
- xdgConfigHome: '/tmp/xdg',
- existsSync: (candidate) => candidate === '/tmp/xdg/subminer/config.jsonc',
- },
- );
+ );
- assert.equal(userDataPath, '/tmp/xdg/SubMiner');
- assert.deepEqual(calls, ['name:SubMiner', 'path:userData:/tmp/xdg/SubMiner']);
+ assert.equal(userDataPath, configDir);
+ assert.deepEqual(calls, ['name:SubMiner', `path:userData:${configDir}`]);
+ } finally {
+ fs.rmSync(tempDir, { recursive: true, force: true });
+ }
+});
+
+test('configureEarlyAppPaths creates a fresh macOS config directory before Electron uses it', () => {
+ const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-entry-first-launch-'));
+ const configDir = path.posix.join(homeDir, '.config', 'SubMiner');
+ try {
+ const app = {
+ setName: () => {},
+ setPath: (_key: 'userData', value: string) => {
+ assert.equal(value, configDir);
+ assert.equal(fs.statSync(value).isDirectory(), true);
+ },
+ };
+ const options = { platform: 'darwin', homeDir, xdgConfigHome: '' } satisfies Parameters<
+ typeof configureEarlyAppPaths
+ >[1];
+
+ assert.equal(fs.existsSync(path.join(homeDir, '.config')), false);
+ configureEarlyAppPaths(app, options);
+
+ const configPath = path.join(configDir, 'config.jsonc');
+ const existingConfig = '{"logging":{"level":"debug"}}\n';
+ fs.writeFileSync(configPath, existingConfig);
+ configureEarlyAppPaths(app, options);
+ assert.equal(fs.readFileSync(configPath, 'utf8'), existingConfig);
+ } finally {
+ fs.rmSync(homeDir, { recursive: true, force: true });
+ }
});
diff --git a/src/main-entry-runtime.ts b/src/main-entry-runtime.ts
index a344d6b8..f86e5016 100644
--- a/src/main-entry-runtime.ts
+++ b/src/main-entry-runtime.ts
@@ -260,6 +260,8 @@ export function configureEarlyAppPaths(app: EarlyAppLike, options?: EarlyAppPath
existsSync: options?.existsSync ?? fs.existsSync,
});
+ // The entry process requests its singleton lock before main-process config bootstrap.
+ fs.mkdirSync(userDataPath, { recursive: true });
app.setName(APP_NAME);
app.setPath('userData', userDataPath);
diff --git a/src/main.ts b/src/main.ts
index 8ff9ec43..5f7ab4fa 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -33,6 +33,7 @@ import {
} from 'electron';
import { applyControllerConfigUpdate } from './main/controller-config-update.js';
import { openPlaylistBrowser as openPlaylistBrowserRuntime } from './main/runtime/playlist-browser-open';
+import { readMpvInputBindings } from './main/runtime/mpv-input-bindings';
import { createAniSkipRuntime } from './main/runtime/aniskip-runtime';
import { resolveAniSkipMetadataForFile } from './main/runtime/aniskip-metadata';
import { createDiscordRpcClient } from './main/runtime/discord-rpc-client.js';
@@ -236,7 +237,10 @@ import {
createCycleSecondarySubModeRuntimeHandler,
} from './main/runtime/domains/mpv';
import { buildSubtitleTrackDiagnostics } from './main/runtime/mpv-track-diagnostics';
-import { resolveCanonicalPrimarySubtitle } from './main/runtime/primary-subtitle-text';
+import {
+ resolveCanonicalPrimarySubtitle,
+ resolvePrimarySubtitle,
+} from './main/runtime/primary-subtitle-text';
import {
createBuildCopyCurrentSubtitleMainDepsHandler,
createBuildHandleMineSentenceDigitMainDepsHandler,
@@ -386,6 +390,7 @@ import {
detectCommandLineLauncher,
installBun as installCommandLineBun,
installLauncher as installCommandLineLauncher,
+ refreshManagedCommandLineLauncher,
} from './main/runtime/command-line-launcher';
import {
createWindowsMpvLaunchDeps,
@@ -460,11 +465,23 @@ import {
} from './main/early-single-instance';
import { handleMpvCommandFromIpcRuntime } from './main/ipc-mpv-command';
import { registerIpcRuntimeServices } from './main/ipc-runtime';
+import { createSubtitleGenerationRuntime } from './main/runtime/subtitle-generation-runtime';
+import { registerSubtitleGenerationIpc } from './main/runtime/subtitle-generation-ipc';
+import { openSubtitleGenerationModal } from './main/runtime/subtitle-generation-open';
import { createAnkiJimakuIpcRuntimeServiceDeps } from './main/dependencies';
import { createMainBootServices, type MainBootServicesResult } from './main/boot/services';
import { handleCliCommandRuntimeServiceWithContext } from './main/cli-runtime';
import { createOverlayModalRuntimeService } from './main/overlay-runtime';
import { createOverlayModalInputState } from './main/runtime/overlay-modal-input-state';
+import { MediaTimingPreviewSession } from './core/services/media-timing-preview';
+import { getSharedRemoteMediaWindowCache } from './core/services/remote-media-window-cache';
+import { resolveMediaGenerationInput } from './anki-integration/media-source';
+import { generateSpeechWaveform } from './core/services/media-timing-waveform';
+import {
+ collectMediaTimingContextLines,
+ createMediaTimingReviewRuntime,
+} from './main/runtime/media-timing-review';
+import { openMediaTimingReviewModal } from './main/runtime/media-timing-review-open';
import { openYoutubeTrackPicker } from './main/runtime/youtube-picker-open';
import { openRuntimeOptionsModal as openRuntimeOptionsModalRuntime } from './main/runtime/runtime-options-open';
import { openJimakuModal as openJimakuModalRuntime } from './main/runtime/jimaku-open';
@@ -1438,6 +1455,10 @@ const createCommandLineLauncherRuntimeOptions = () => ({
cwd: process.cwd(),
resourcesPath: process.resourcesPath,
appExePath: process.execPath,
+ appVersion: app.getVersion(),
+ bundledBunPath: app.isPackaged
+ ? path.join(process.resourcesPath, 'bun', process.platform === 'win32' ? 'bun.exe' : 'bun')
+ : undefined,
});
const firstRunSetupService = createFirstRunSetupService({
platform: process.platform,
@@ -1523,7 +1544,7 @@ const firstRunSetupService = createFirstRunSetupService({
},
installCommandLineLauncher: async () => {
const snapshot = await installCommandLineLauncher(createCommandLineLauncherRuntimeOptions());
- const ok = snapshot.status === 'ready' || snapshot.status === 'installed_bun_missing';
+ const ok = snapshot.status === 'ready' || snapshot.status === 'not_on_path';
return {
ok,
installPath: snapshot.installPath,
@@ -1837,28 +1858,31 @@ function withCurrentSubtitleTiming(payload: SubtitleData): SubtitleData {
}
function captureCurrentPrimarySubtitleMiningContext(): SubtitleMiningContext | null {
- const canonical = resolveCanonicalPrimarySubtitle({
+ // Mine what the overlay shows, not raw mpv `sub-text`: the raw text lists every active
+ // event, so a finished caption row lingering beside a fresh line would end up on the
+ // card. The parsed view also carries the cue's own timings for the clip range.
+ const resolved = resolvePrimarySubtitle({
liveText: appState.mpvClient?.currentSubText ?? '',
currentTimeSec: Number(appState.mpvClient?.currentTimePos),
cues: appState.activeParsedSubtitleCues,
});
- // Same validity bar as the live capture path: an unusable canonical span must fall
+ // Same validity bar as the live capture path: an unusable resolved span must fall
// back rather than hand mining an empty line or an inverted range.
- const canonicalText = canonical?.text.trim();
+ const resolvedText = resolved?.text.replace(/\n{2,}/g, '\n').trim();
if (
- !canonical ||
- !canonicalText ||
- !Number.isFinite(canonical.startTime) ||
- !Number.isFinite(canonical.endTime) ||
- canonical.endTime <= canonical.startTime
+ !resolved ||
+ !resolvedText ||
+ !Number.isFinite(resolved.startTime) ||
+ !Number.isFinite(resolved.endTime) ||
+ resolved.endTime <= resolved.startTime
) {
return captureLiveSubtitleMiningContext(appState.mpvClient);
}
return {
source: 'overlay',
- text: canonicalText,
- startTime: canonical.startTime,
- endTime: canonical.endTime,
+ text: resolvedText,
+ startTime: resolved.startTime,
+ endTime: resolved.endTime,
capturedAtMs: Date.now(),
};
}
@@ -2982,6 +3006,49 @@ function createOverlayHostedModalOpenDeps(): {
};
}
+const mediaTimingReviewRuntime = createMediaTimingReviewRuntime({
+ getMpvClient: () => appState.mpvClient,
+ getCurrentMediaPath: () =>
+ appState.currentMediaPath?.trim() || appState.mpvClient?.currentVideoPath?.trim() || null,
+ getMpvExecutablePath: () =>
+ configService.getConfig().mpv.executablePath || process.env.SUBMINER_MPV_PATH?.trim() || '',
+ createPreviewSession: () => new MediaTimingPreviewSession(),
+ generateWaveform: (options) => generateSpeechWaveform(options),
+ resolveMediaSource: async () => {
+ const resolved = await resolveMediaGenerationInput(appState.mpvClient, 'audio', {
+ getCachedMediaPath: (currentVideoPath, kind) =>
+ getCachedYoutubeMediaPathForCurrentPlayback(currentVideoPath, kind),
+ remoteCacheMode: shouldRequireYoutubeMediaCacheForCurrentPlayback() ? 'required' : 'optional',
+ });
+ return resolved
+ ? {
+ path: resolved.path,
+ ...(resolved.inputOptions ? { inputOptions: resolved.inputOptions } : {}),
+ singleResolvedStream: resolved.singleResolvedStream,
+ }
+ : null;
+ },
+ acquireMediaWindow: (source, range) => getSharedRemoteMediaWindowCache().acquire(source, range),
+ getSubtitleContextLines: (range) =>
+ collectMediaTimingContextLines({
+ cues: appState.activeParsedSubtitleCues,
+ fallbackPrevious: appState.subtitleTimingTracker?.getRecentEntries(40) ?? [],
+ startTime: range.startTime,
+ endTime: range.endTime,
+ }),
+ openModal: (payload) => openMediaTimingReviewModal(createOverlayHostedModalOpenDeps(), payload),
+ onPreviewEnded: (reviewId) => {
+ // The review may live in either overlay window; the renderer ignores foreign review ids.
+ for (const window of [overlayManager.getMainWindow(), overlayManager.getModalWindow()]) {
+ if (window && !window.isDestroyed()) {
+ window.webContents.send(IPC_CHANNELS.event.mediaTimingReviewPreviewEnded, reviewId);
+ }
+ }
+ },
+ showStatus: (message) =>
+ overlayNotificationsRuntime.showConfiguredStatusNotification(message, { variant: 'warning' }),
+});
+
function openOverlayHostedModalWithOsd(
openModal: (deps: ReturnType) => Promise,
unavailableMessage: string,
@@ -3029,6 +3096,14 @@ function openTsukihimeOverlay(): void {
);
}
+function openSubtitleGenerationOverlay(): void {
+ openOverlayHostedModalWithOsd(
+ openSubtitleGenerationModal,
+ 'Subtitle generation overlay unavailable.',
+ 'Failed to open subtitle generation overlay.',
+ );
+}
+
function openSessionHelpOverlay(): void {
openOverlayHostedModalWithOsd(
openSessionHelpModalRuntime,
@@ -4167,6 +4242,7 @@ const {
cleanupInternalSubtitleTrackCache: () => cachedInternalSubtitleTrackExtractor.clear(),
cleanupYoutubeSubtitleTempDirs: () => youtubeFlowRuntime.cleanupSubtitleTempDirs(),
cleanupYoutubeMediaCache: () => youtubeMediaCache.cleanup(),
+ cleanupRemoteMediaWindows: () => getSharedRemoteMediaWindowCache().cleanup(),
cleanupJellyfinSubtitleCache: () => cleanupJellyfinSubtitleCache(),
stopDiscordPresenceService: () => {
void appState.discordPresenceService?.stop();
@@ -5319,6 +5395,7 @@ function initializeOverlayRuntime(): void {
appState.ankiIntegration?.setRecordCardsMinedCallback(recordTrackedCardsMined);
appState.ankiIntegration?.setKnownWordCacheUpdatedCallback(refreshCurrentSubtitleAnnotations);
appState.ankiIntegration?.setSubtitleMiningContextConsumer(consumePendingSubtitleMiningContext);
+ appState.ankiIntegration?.setMediaTimingReviewCallback(mediaTimingReviewRuntime.requestReview);
syncOverlayMpvSubtitleSuppression();
}
@@ -5452,7 +5529,7 @@ const { getChangelogSnapshot } = createChangelogRuntime({
logWarn: (message) => logger.warn(message),
});
-const { getUpdateService } = createUpdateServiceRuntime({
+const { getUpdateService, takePendingLauncherMigrationPath } = createUpdateServiceRuntime({
userDataPath: USER_DATA_PATH,
getUpdatesConfig: () => configService.getConfig().updates,
logInfo: (message) => logger.info(message),
@@ -5665,6 +5742,7 @@ async function dispatchSessionAction(request: SessionActionDispatchRequest): Pro
openJimaku: () => openJimakuOverlay(),
openTsukihime: () => openTsukihimeOverlay(),
openSessionHelp: () => openSessionHelpOverlay(),
+ openSubtitleGeneration: () => openSubtitleGenerationOverlay(),
openCharacterDictionaryManager: () => openCharacterDictionaryManagerOverlay(),
openControllerSelect: () => openControllerSelectOverlay(),
openControllerDebug: () => openControllerDebugOverlay(),
@@ -5730,6 +5808,10 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
showMpvOsd: (text: string) => showConfiguredPlaybackFeedback(text),
},
mainDeps: {
+ previewMediaTimingReview: (request) => mediaTimingReviewRuntime.previewRange(request),
+ getMediaTimingReviewWaveform: (request) => mediaTimingReviewRuntime.getWaveform(request),
+ stopMediaTimingReviewPreview: (reviewId) => mediaTimingReviewRuntime.stopPreview(reviewId),
+ resolveMediaTimingReview: (request) => mediaTimingReviewRuntime.resolveReview(request),
getMainWindow: () => overlayManager.getMainWindow(),
getVisibleOverlayVisibility: () => overlayManager.getVisibleOverlayVisible(),
focusMainWindow: () => {
@@ -5763,6 +5845,9 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
}
},
onOverlayModalClosed: (modal, senderWindow) => {
+ if (modal === 'media-timing-review') {
+ void mediaTimingReviewRuntime.dispose();
+ }
if (modal === 'subtitle-sidebar' && senderWindow === overlayManager.getMainWindow()) {
subtitleSidebarRequestedOpen = false;
}
@@ -5883,6 +5968,10 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
const client = appState.mpvClient;
if (!client?.connected) {
return {
+ sourceKey: JSON.stringify([
+ appState.activeParsedSubtitleMediaPath,
+ appState.activeParsedSubtitleSource,
+ ]),
cues: appState.activeParsedSubtitleCues,
currentTimeSec,
currentSubtitle,
@@ -5902,6 +5991,10 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
const videoPath = typeof videoPathRaw === 'string' ? videoPathRaw : '';
if (!videoPath) {
return {
+ sourceKey: JSON.stringify([
+ appState.activeParsedSubtitleMediaPath,
+ appState.activeParsedSubtitleSource,
+ ]),
cues: appState.activeParsedSubtitleCues,
currentTimeSec,
currentSubtitle,
@@ -5916,6 +6009,10 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
})
) {
return {
+ sourceKey: JSON.stringify([
+ appState.activeParsedSubtitleMediaPath,
+ appState.activeParsedSubtitleSource,
+ ]),
cues: appState.activeParsedSubtitleCues,
currentTimeSec,
currentSubtitle,
@@ -5932,6 +6029,10 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
});
if (!resolvedSource) {
return {
+ sourceKey: JSON.stringify([
+ appState.activeParsedSubtitleMediaPath,
+ appState.activeParsedSubtitleSource,
+ ]),
cues: appState.activeParsedSubtitleCues,
currentTimeSec,
currentSubtitle,
@@ -5942,6 +6043,10 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
try {
if (appState.activeParsedSubtitleSource === resolvedSource.sourceKey) {
return {
+ sourceKey: JSON.stringify([
+ appState.activeParsedSubtitleMediaPath,
+ appState.activeParsedSubtitleSource,
+ ]),
cues: appState.activeParsedSubtitleCues,
currentTimeSec,
currentSubtitle,
@@ -5955,6 +6060,10 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
appState.activeParsedSubtitleSource = resolvedSource.sourceKey;
appState.activeParsedSubtitleMediaPath = videoPath || null;
return {
+ sourceKey: JSON.stringify([
+ appState.activeParsedSubtitleMediaPath,
+ appState.activeParsedSubtitleSource,
+ ]),
cues,
currentTimeSec,
currentSubtitle,
@@ -5965,6 +6074,10 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
}
} catch {
return {
+ sourceKey: JSON.stringify([
+ appState.activeParsedSubtitleMediaPath,
+ appState.activeParsedSubtitleSource,
+ ]),
cues: appState.activeParsedSubtitleCues,
currentTimeSec,
currentSubtitle,
@@ -5985,6 +6098,17 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
saveSubtitlePosition: (position) => saveSubtitlePosition(position),
getMecabTokenizer: () => appState.mecabTokenizer,
getKeybindings: () => appState.keybindings,
+ getMpvInputBindings: () =>
+ readMpvInputBindings({
+ getMpvClient: () => appState.mpvClient,
+ getConfiguredKeybindings: () => configService.getConfig().keybindings ?? [],
+ platform:
+ process.platform === 'darwin'
+ ? 'darwin'
+ : process.platform === 'win32'
+ ? 'win32'
+ : 'linux',
+ }),
getSessionBindings: () => appState.sessionBindings,
getConfiguredShortcuts: () => getConfiguredShortcuts(),
dispatchSessionAction: (request) => dispatchSessionAction(request),
@@ -6119,6 +6243,9 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
appState.ankiIntegration?.setSubtitleMiningContextConsumer(
consumePendingSubtitleMiningContext,
);
+ appState.ankiIntegration?.setMediaTimingReviewCallback(
+ mediaTimingReviewRuntime.requestReview,
+ );
},
getKnownWordCacheStatePath: () => path.join(USER_DATA_PATH, 'known-words-cache.json'),
getCachedMediaPath: (currentVideoPath, kind) =>
@@ -6386,6 +6513,15 @@ const { runAndApplyStartupState } = composeHeadlessStartupHandlers<
runAndApplyStartupState();
void app.whenReady().then(() => {
+ void takePendingLauncherMigrationPath(async (pendingLauncherPath) => {
+ const acknowledgedPaths = await refreshManagedCommandLineLauncher({
+ ...createCommandLineLauncherRuntimeOptions(),
+ additionalLauncherPaths: pendingLauncherPath ? [pendingLauncherPath] : [],
+ });
+ return pendingLauncherPath !== undefined && acknowledgedPaths.includes(pendingLauncherPath);
+ }).catch((error) => {
+ logger.warn('Failed to refresh the installed command-line launcher', error);
+ });
if (!shouldStartAutomaticUpdateChecks(appState.initialArgs)) {
return;
}
@@ -6452,6 +6588,7 @@ const { createMainWindow: createMainWindowHandler, createModalWindow: createModa
if (overlayManager.getModalWindow() !== window) {
return;
}
+ void mediaTimingReviewRuntime.dispose();
overlayManager.setModalWindow(null);
}
},
@@ -6765,3 +6902,25 @@ function setOverlayVisible(visible: boolean): void {
}
registerIpcRuntimeHandlers();
+const subtitleGenerationRuntime = createSubtitleGenerationRuntime({
+ getConfig: () => configService.getConfig().subtitleGeneration,
+ getModelDirectory: () =>
+ path.join(path.dirname(configService.getConfigPath()), 'models', 'whisper'),
+ getMpvClient: () => appState.mpvClient,
+ onProgress: (progress) => {
+ for (const window of [overlayManager.getMainWindow(), overlayManager.getModalWindow()]) {
+ if (window && !window.isDestroyed())
+ window.webContents.send(IPC_CHANNELS.event.subtitleGenerationProgress, progress);
+ }
+ },
+});
+registerSubtitleGenerationIpc({
+ ipc: ipcMain,
+ isAllowedSender: (sender) =>
+ [overlayManager.getMainWindow(), overlayManager.getModalWindow()].some(
+ (window) => window && !window.isDestroyed() && window.webContents === sender,
+ ),
+ runtime: subtitleGenerationRuntime,
+ openModal: () => openSubtitleGenerationModal(createOverlayHostedModalOpenDeps()),
+});
+app.on('before-quit', () => subtitleGenerationRuntime.cancel());
diff --git a/src/main/dependencies.ts b/src/main/dependencies.ts
index d2e1f6b7..49e0c58b 100644
--- a/src/main/dependencies.ts
+++ b/src/main/dependencies.ts
@@ -62,6 +62,10 @@ export interface MainIpcRuntimeServiceDepsParams {
onOverlayInteractiveHint?: IpcDepsRuntimeOptions['onOverlayInteractiveHint'];
handleOverlayNotificationAction?: IpcDepsRuntimeOptions['handleOverlayNotificationAction'];
onYoutubePickerResolve: IpcDepsRuntimeOptions['onYoutubePickerResolve'];
+ previewMediaTimingReview?: IpcDepsRuntimeOptions['previewMediaTimingReview'];
+ getMediaTimingReviewWaveform?: IpcDepsRuntimeOptions['getMediaTimingReviewWaveform'];
+ stopMediaTimingReviewPreview?: IpcDepsRuntimeOptions['stopMediaTimingReviewPreview'];
+ resolveMediaTimingReview?: IpcDepsRuntimeOptions['resolveMediaTimingReview'];
openYomitanSettings: IpcDepsRuntimeOptions['openYomitanSettings'];
quitApp: IpcDepsRuntimeOptions['quitApp'];
toggleVisibleOverlay: IpcDepsRuntimeOptions['toggleVisibleOverlay'];
@@ -79,6 +83,7 @@ export interface MainIpcRuntimeServiceDepsParams {
getMecabTokenizer: IpcDepsRuntimeOptions['getMecabTokenizer'];
handleMpvCommand: IpcDepsRuntimeOptions['handleMpvCommand'];
getKeybindings: IpcDepsRuntimeOptions['getKeybindings'];
+ getMpvInputBindings?: IpcDepsRuntimeOptions['getMpvInputBindings'];
getSessionBindings: IpcDepsRuntimeOptions['getSessionBindings'];
getConfiguredShortcuts: IpcDepsRuntimeOptions['getConfiguredShortcuts'];
dispatchSessionAction: IpcDepsRuntimeOptions['dispatchSessionAction'];
@@ -260,6 +265,10 @@ export function createMainIpcRuntimeServiceDeps(
onOverlayInteractiveHint: params.onOverlayInteractiveHint,
handleOverlayNotificationAction: params.handleOverlayNotificationAction,
onYoutubePickerResolve: params.onYoutubePickerResolve,
+ previewMediaTimingReview: params.previewMediaTimingReview,
+ getMediaTimingReviewWaveform: params.getMediaTimingReviewWaveform,
+ stopMediaTimingReviewPreview: params.stopMediaTimingReviewPreview,
+ resolveMediaTimingReview: params.resolveMediaTimingReview,
openYomitanSettings: params.openYomitanSettings,
quitApp: params.quitApp,
toggleVisibleOverlay: params.toggleVisibleOverlay,
@@ -275,6 +284,7 @@ export function createMainIpcRuntimeServiceDeps(
getMecabTokenizer: params.getMecabTokenizer,
handleMpvCommand: params.handleMpvCommand,
getKeybindings: params.getKeybindings,
+ getMpvInputBindings: params.getMpvInputBindings,
getSessionBindings: params.getSessionBindings,
getConfiguredShortcuts: params.getConfiguredShortcuts,
dispatchSessionAction: params.dispatchSessionAction,
diff --git a/src/main/overlay-runtime.test.ts b/src/main/overlay-runtime.test.ts
index 47094d60..65a33ad4 100644
--- a/src/main/overlay-runtime.test.ts
+++ b/src/main/overlay-runtime.test.ts
@@ -382,6 +382,8 @@ test('anime browser modal keeps its document warm across close on Linux', () =>
restoreOnModalClose: 'anime-browser',
preferModalWindow: true,
});
+ assert.equal(modalWindow.isVisible(), false);
+ runtime.notifyOverlayModalOpened('anime-browser');
assert.equal(modalWindow.isVisible(), true);
});
@@ -883,6 +885,7 @@ test('modal fallback reveal skips showing window when content is not ready', asy
setModalWindowBounds: () => {},
},
{
+ platform: 'darwin',
scheduleRevealFallback: (callback) => {
scheduledReveal = callback;
return { scheduled: true } as never;
@@ -1418,3 +1421,62 @@ test('modal placement reconcile cancels stale retry ladder after a newer visible
globalThis.clearTimeout = originalClearTimeout;
}
});
+
+test('Linux keeps the dedicated modal window unmapped until the renderer opens the modal, then hides the overlay before revealing it', () => {
+ const mainWindow = createMockWindow();
+ mainWindow.visible = true;
+ const modalWindow = createMockWindow();
+ const order: string[] = [];
+ const hideMain = mainWindow.hide;
+ mainWindow.hide = () => {
+ order.push('main:hide');
+ hideMain();
+ };
+ const showModal = modalWindow.show;
+ modalWindow.show = () => {
+ order.push('modal:show');
+ showModal();
+ };
+ let revealScheduled = false;
+ const runtime = createOverlayModalRuntimeService(
+ {
+ getMainWindow: () => mainWindow as never,
+ getModalWindow: () => modalWindow as never,
+ createModalWindow: () => modalWindow as never,
+ getModalGeometry: () => ({ x: 0, y: 0, width: 400, height: 300 }),
+ setModalWindowBounds: () => {},
+ },
+ {
+ platform: 'linux',
+ scheduleRevealFallback: () => {
+ revealScheduled = true;
+ return { scheduled: true } as never;
+ },
+ clearRevealFallback: () => {},
+ },
+ );
+
+ const open = () =>
+ runtime.sendToActiveOverlayWindow(
+ 'media-timing-review:open',
+ { reviewId: 'review' },
+ { restoreOnModalClose: 'media-timing-review', preferModalWindow: true },
+ );
+
+ assert.equal(open(), true);
+ assert.deepEqual(modalWindow.sent, [['media-timing-review:open', { reviewId: 'review' }]]);
+ assert.equal(revealScheduled, false);
+ assert.equal(modalWindow.getShowCount(), 0);
+ assert.equal(mainWindow.getHideCount(), 0);
+
+ // The open retry must not map the window before the renderer answers either.
+ assert.equal(open(), true);
+ assert.equal(modalWindow.getShowCount(), 0);
+
+ runtime.notifyOverlayModalOpened('media-timing-review');
+
+ assert.deepEqual(order, ['main:hide', 'modal:show']);
+ assert.equal(mainWindow.isVisible(), false);
+ assert.equal(modalWindow.isVisible(), true);
+ assert.equal(modalWindow.ignoreMouseEvents, false);
+});
diff --git a/src/main/overlay-runtime.ts b/src/main/overlay-runtime.ts
index a25cf61d..f59908d0 100644
--- a/src/main/overlay-runtime.ts
+++ b/src/main/overlay-runtime.ts
@@ -93,6 +93,12 @@ export function createOverlayModalRuntimeService(
const shouldPrimeModalWindow = platform === 'darwin' || platform === 'win32';
const shouldReuseModalWindowAfterClose = (): boolean =>
platform === 'darwin' || (platform !== 'win32' && retainModalWindowState);
+ // On Linux (Hyprland) every placement dispatch on a mapped window (resize, move, set_prop)
+ // blanks the still-visible overlay for a few frames while mpv is fullscreen. Revealing the
+ // dedicated modal window before its renderer has the modal open runs the placement ladder,
+ // and the open retry, against a visible overlay, which the user sees as flicker. Keep the
+ // window unmapped until the renderer acknowledges the open, then hide the overlay first.
+ const deferModalRevealUntilOpened = platform === 'linux';
const focusApplication = options.focusApplication ?? requestOverlayApplicationFocus;
const scheduleRevealFallback = (callback: () => void, delayMs: number): RevealFallbackHandle =>
(options.scheduleRevealFallback ?? globalThis.setTimeout)(callback, delayMs);
@@ -463,7 +469,9 @@ export function createOverlayModalRuntimeService(
deps.setModalWindowBounds(deps.getModalGeometry());
const wasVisible = modalWindow.isVisible();
if (!wasVisible) {
- if (modalWindowPrimedForImmediateShow && isWindowReadyForIpc(modalWindow)) {
+ if (deferModalRevealUntilOpened) {
+ // notifyOverlayModalOpened reveals the window once the renderer has the modal open.
+ } else if (modalWindowPrimedForImmediateShow && isWindowReadyForIpc(modalWindow)) {
showModalWindow(modalWindow);
} else {
scheduleModalWindowReveal(modalWindow);
@@ -567,15 +575,23 @@ export function createOverlayModalRuntimeService(
}
const modalWindow = deps.getModalWindow();
+ const targetIsModalWindow =
+ modalWindow !== null && !modalWindow.isDestroyed() && targetWindow === modalWindow;
+ const handOffMainWindowToModal = (): void => {
+ setMainWindowMousePassthroughForModal(true);
+ setMainWindowVisibilityForModal(true);
+ };
+
+ if (targetIsModalWindow && deferModalRevealUntilOpened) {
+ handOffMainWindowToModal();
+ }
if (targetWindow.isVisible()) {
ensureModalWindowInteractive(targetWindow);
} else {
showModalWindow(targetWindow);
}
-
- if (modalWindow && !modalWindow.isDestroyed() && targetWindow === modalWindow) {
- setMainWindowMousePassthroughForModal(true);
- setMainWindowVisibilityForModal(true);
+ if (targetIsModalWindow && !deferModalRevealUntilOpened) {
+ handOffMainWindowToModal();
}
};
diff --git a/src/main/runtime/app-lifecycle-actions.test.ts b/src/main/runtime/app-lifecycle-actions.test.ts
index 39acb3ac..cc391bad 100644
--- a/src/main/runtime/app-lifecycle-actions.test.ts
+++ b/src/main/runtime/app-lifecycle-actions.test.ts
@@ -48,12 +48,13 @@ test('on will quit cleanup handler runs all cleanup steps', async () => {
cleanupInternalSubtitleTrackCache: () => calls.push('cleanup-internal-subtitles'),
cleanupYoutubeSubtitleTempDirs: () => calls.push('cleanup-youtube-subtitles'),
cleanupYoutubeMediaCache: () => calls.push('cleanup-youtube-media'),
+ cleanupRemoteMediaWindows: () => calls.push('cleanup-remote-media-windows'),
cleanupJellyfinSubtitleCache: () => calls.push('cleanup-jellyfin-subtitles'),
stopDiscordPresenceService: () => calls.push('stop-discord-presence'),
});
await cleanup();
- assert.equal(calls.length, 35);
+ assert.equal(calls.length, 36);
assert.equal(calls[0], 'destroy-tray');
assert.equal(calls[calls.length - 1], 'stop-discord-presence');
assert.ok(calls.includes('cleanup-jellyfin-subtitles'));
@@ -62,6 +63,7 @@ test('on will quit cleanup handler runs all cleanup steps', async () => {
assert.ok(calls.includes('clear-linux-mpv-fullscreen-overlay-refresh-timeouts'));
assert.ok(calls.includes('cleanup-youtube-subtitles'));
assert.ok(calls.includes('cleanup-youtube-media'));
+ assert.ok(calls.includes('cleanup-remote-media-windows'));
assert.ok(calls.indexOf('flush-mpv-log') < calls.indexOf('destroy-socket'));
});
@@ -104,6 +106,7 @@ test('on will quit cleanup handler cleans jellyfin subtitle cache when stopping
cleanupInternalSubtitleTrackCache: () => calls.push('cleanup-internal-subtitles'),
cleanupYoutubeSubtitleTempDirs: () => calls.push('cleanup-youtube-subtitles'),
cleanupYoutubeMediaCache: () => calls.push('cleanup-youtube-media'),
+ cleanupRemoteMediaWindows: () => calls.push('cleanup-remote-media-windows'),
cleanupJellyfinSubtitleCache: () => calls.push('cleanup-jellyfin-subtitles'),
stopDiscordPresenceService: () => calls.push('stop-discord-presence'),
});
diff --git a/src/main/runtime/app-lifecycle-actions.ts b/src/main/runtime/app-lifecycle-actions.ts
index a8080ad6..e436483c 100644
--- a/src/main/runtime/app-lifecycle-actions.ts
+++ b/src/main/runtime/app-lifecycle-actions.ts
@@ -32,6 +32,7 @@ export function createOnWillQuitCleanupHandler(deps: {
cleanupInternalSubtitleTrackCache: () => void;
cleanupYoutubeSubtitleTempDirs: () => void;
cleanupYoutubeMediaCache: () => void;
+ cleanupRemoteMediaWindows: () => void;
cleanupJellyfinSubtitleCache: () => void;
stopDiscordPresenceService: () => void;
}) {
@@ -76,6 +77,7 @@ export function createOnWillQuitCleanupHandler(deps: {
}
deps.cleanupYoutubeSubtitleTempDirs();
deps.cleanupYoutubeMediaCache();
+ deps.cleanupRemoteMediaWindows();
deps.stopDiscordPresenceService();
await stopSyncAutoScheduler;
};
diff --git a/src/main/runtime/app-lifecycle-main-cleanup.test.ts b/src/main/runtime/app-lifecycle-main-cleanup.test.ts
index d926248d..2fc77ac9 100644
--- a/src/main/runtime/app-lifecycle-main-cleanup.test.ts
+++ b/src/main/runtime/app-lifecycle-main-cleanup.test.ts
@@ -75,6 +75,7 @@ test('cleanup deps builder returns handlers that guard optional runtime objects'
cleanupInternalSubtitleTrackCache: () => calls.push('cleanup-internal-subtitles'),
cleanupYoutubeSubtitleTempDirs: () => calls.push('cleanup-youtube-subtitles'),
cleanupYoutubeMediaCache: () => calls.push('cleanup-youtube-media'),
+ cleanupRemoteMediaWindows: () => calls.push('cleanup-remote-media-windows'),
cleanupJellyfinSubtitleCache: () => calls.push('cleanup-jellyfin-subtitles'),
stopDiscordPresenceService: () => calls.push('stop-discord-presence'),
});
@@ -157,6 +158,7 @@ test('cleanup deps builder skips destroyed yomitan window', () => {
cleanupInternalSubtitleTrackCache: () => {},
cleanupYoutubeSubtitleTempDirs: () => {},
cleanupYoutubeMediaCache: () => {},
+ cleanupRemoteMediaWindows: () => {},
cleanupJellyfinSubtitleCache: () => {},
stopDiscordPresenceService: () => {},
});
@@ -210,6 +212,7 @@ test('cleanup deps builder skips global shortcut cleanup before app ready', () =
cleanupInternalSubtitleTrackCache: () => {},
cleanupYoutubeSubtitleTempDirs: () => {},
cleanupYoutubeMediaCache: () => {},
+ cleanupRemoteMediaWindows: () => {},
cleanupJellyfinSubtitleCache: () => {},
stopDiscordPresenceService: () => {},
});
diff --git a/src/main/runtime/app-lifecycle-main-cleanup.ts b/src/main/runtime/app-lifecycle-main-cleanup.ts
index b539c6f2..d8c182df 100644
--- a/src/main/runtime/app-lifecycle-main-cleanup.ts
+++ b/src/main/runtime/app-lifecycle-main-cleanup.ts
@@ -61,6 +61,7 @@ export function createBuildOnWillQuitCleanupDepsHandler(deps: {
cleanupInternalSubtitleTrackCache: () => void;
cleanupYoutubeSubtitleTempDirs: () => void;
cleanupYoutubeMediaCache: () => void;
+ cleanupRemoteMediaWindows: () => void;
cleanupJellyfinSubtitleCache: () => void;
stopDiscordPresenceService: () => void;
}) {
@@ -148,6 +149,7 @@ export function createBuildOnWillQuitCleanupDepsHandler(deps: {
cleanupInternalSubtitleTrackCache: () => deps.cleanupInternalSubtitleTrackCache(),
cleanupYoutubeSubtitleTempDirs: () => deps.cleanupYoutubeSubtitleTempDirs(),
cleanupYoutubeMediaCache: () => deps.cleanupYoutubeMediaCache(),
+ cleanupRemoteMediaWindows: () => deps.cleanupRemoteMediaWindows(),
cleanupJellyfinSubtitleCache: () => deps.cleanupJellyfinSubtitleCache(),
stopDiscordPresenceService: () => deps.stopDiscordPresenceService(),
});
diff --git a/src/main/runtime/command-line-launcher-deps.ts b/src/main/runtime/command-line-launcher-deps.ts
index 69b654af..58f01693 100644
--- a/src/main/runtime/command-line-launcher-deps.ts
+++ b/src/main/runtime/command-line-launcher-deps.ts
@@ -32,6 +32,8 @@ export type CommonOptions = FsDeps & {
resourcesPath?: string;
appExePath?: string;
launcherResourcePath?: string;
+ bundledBunPath?: string;
+ appVersion?: string;
runCommand?: RunCommand;
};
@@ -143,8 +145,40 @@ function needsWindowsShell(command: string): boolean {
return process.platform === 'win32' && /\.(cmd|bat)$/i.test(command);
}
-function quoteForWindowsShell(value: string): string {
- return `"${value.replace(/([&|<>^%!])/g, '^$1').replace(/"/g, '""')}"`;
+/*!
+ * Windows command escaping adapted from cross-spawn 7.0.6.
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Made With MOXY Lda
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+const WINDOWS_SHELL_META_CHARACTERS = /([()\][%!^"`<>&|;, *?])/g;
+
+// Quote for both cmd.exe and the Windows argv parser. The outer caret escapes
+// are consumed by cmd, leaving the quoted argument unchanged for the command.
+function escapeWindowsShellArgument(value: string): string {
+ const quotesEscaped = value
+ .replace(/(?=(\\+?)?)\1"/g, '$1$1\\"')
+ .replace(/(?=(\\+?)?)\1$/, '$1$1');
+ return `"${quotesEscaped}"`.replace(WINDOWS_SHELL_META_CHARACTERS, '^$1');
}
function createDefaultRunCommand(): RunCommand {
@@ -153,16 +187,24 @@ function createDefaultRunCommand(): RunCommand {
const useShell = needsWindowsShell(command);
let child: ReturnType;
try {
- child = useShell
- ? spawn(quoteForWindowsShell(command), args.map(quoteForWindowsShell), {
- env: options.env ?? process.env,
- windowsHide: false,
- shell: true,
- })
- : spawn(command, args, {
- env: options.env ?? process.env,
- windowsHide: false,
- });
+ const env = options.env ?? process.env;
+ if (useShell) {
+ const shellCommand = [
+ escapeWindowsShellArgument(command),
+ ...args.map(escapeWindowsShellArgument),
+ ].join(' ');
+ const commandProcessor = env.ComSpec ?? env.COMSPEC ?? process.env.ComSpec ?? 'cmd.exe';
+ child = spawn(commandProcessor, ['/d', '/s', '/v:off', '/c', `"${shellCommand}"`], {
+ env,
+ windowsHide: false,
+ windowsVerbatimArguments: true,
+ });
+ } else {
+ child = spawn(command, args, {
+ env,
+ windowsHide: false,
+ });
+ }
} catch (error) {
resolve({
exitCode: 1,
diff --git a/src/main/runtime/command-line-launcher.test.ts b/src/main/runtime/command-line-launcher.test.ts
index 68e516b4..97e29600 100644
--- a/src/main/runtime/command-line-launcher.test.ts
+++ b/src/main/runtime/command-line-launcher.test.ts
@@ -91,43 +91,54 @@ test('resolveBunInstallCommand prefers winget on Windows', () => {
test('default runCommand preserves Windows cmd metacharacter args', async (t) => {
if (process.platform !== 'win32') return;
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-cmd-args-'));
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer cmd & 100% ! '));
const scriptPath = path.join(tempDir, 'argv.cmd');
- const outputPath = path.join(tempDir, 'argv.txt');
+ const argvScriptPath = path.join(tempDir, 'argv.js');
t.after(() => {
fs.rmSync(tempDir, { recursive: true, force: true });
});
+ fs.writeFileSync(
+ argvScriptPath,
+ 'process.stdout.write(JSON.stringify(process.argv.slice(2)));',
+ 'utf8',
+ );
fs.writeFileSync(
scriptPath,
[
'@echo off',
'setlocal DisableDelayedExpansion',
- '> "%SUBMINER_ARGV_OUT%" (',
- ' echo 1=%~1',
- ' echo 2=%~2',
- ' echo 3=%~3',
- ' echo 4=%~4',
- ' echo 5=%~5',
- ' echo 6=%~6',
- ')',
+ '"%SUBMINER_TEST_RUNTIME%" "%SUBMINER_ARGV_SCRIPT%" %*',
+ 'exit /b %errorlevel%',
'',
].join('\r\n'),
'utf8',
);
- const result = await getRunCommand({})(
- scriptPath,
- ['plain', 'has space', 'a&b', 'x|y', 'p%PATH%q', 'bang!z'],
- {
- env: { ...process.env, SUBMINER_ARGV_OUT: outputPath },
+ const args = [
+ 'plain',
+ 'has space',
+ 'a&b',
+ 'x|y',
+ 'p%TEMP%q',
+ 'bang!z',
+ 'caret^z',
+ '',
+ 'say "hi"',
+ 'slash\\"quote',
+ 'trailing\\',
+ '',
+ '日本語',
+ ];
+ const result = await getRunCommand({})(scriptPath, args, {
+ env: {
+ ...process.env,
+ SUBMINER_ARGV_SCRIPT: argvScriptPath,
+ SUBMINER_TEST_RUNTIME: process.execPath,
},
- );
+ });
assert.equal(result.exitCode, 0, result.stderr);
- assert.equal(
- fs.readFileSync(outputPath, 'utf8'),
- ['1=plain', '2=has space', '3=a&b', '4=x|y', '5=p%PATH%q', '6=bang!z', ''].join('\r\n'),
- );
+ assert.deepEqual(JSON.parse(result.stdout), args);
});
test('resolveBunInstallCommand falls back to scoop on Windows before official installer', () => {
@@ -189,7 +200,7 @@ test('resolveLauncherInstallTarget prefers writable user bin on Linux', async ()
assert.equal(target.installPath, '/home/tester/.local/bin/subminer');
});
-test('resolveLauncherInstallTarget returns not_installable without writable PATH dirs', async () => {
+test('resolveLauncherInstallTarget offers a user bin without writable PATH dirs', async () => {
const target = await resolveLauncherInstallTarget({
platform: 'linux',
homeDir: '/home/tester',
@@ -200,8 +211,9 @@ test('resolveLauncherInstallTarget returns not_installable without writable PATH
},
});
- assert.equal(target.status, 'not_installable');
- assert.equal(target.installPath, null);
+ assert.equal(target.status, 'not_installed');
+ assert.equal(target.installPath, '/home/tester/.local/bin/subminer');
+ assert.match(target.message ?? '', /export PATH=/);
});
test('resolveLauncherInstallTarget skips Homebrew bin for empty macOS manual installs', async () => {
diff --git a/src/main/runtime/command-line-launcher.ts b/src/main/runtime/command-line-launcher.ts
index 0194b4b5..eab7c053 100644
--- a/src/main/runtime/command-line-launcher.ts
+++ b/src/main/runtime/command-line-launcher.ts
@@ -1,6 +1,13 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
+import {
+ cleanupOldWindowsManagedRuntimes,
+ isManagedLauncher,
+ managedLauncherContent,
+ shellQuote,
+ stageManagedLauncher,
+} from './managed-launcher';
import {
accessSyncOf,
envOf,
@@ -115,8 +122,13 @@ export function resolveBunInstallCommand(
}
export async function detectBun(options: CommonOptions = {}): Promise {
- const bunPath = findCommand('bun', options);
- const installCommand = resolveBunInstallCommand(options);
+ const bundled = options.bundledBunPath;
+ const bunPath = bundled
+ ? existsSyncOf(options)(bundled)
+ ? bundled
+ : null
+ : findCommand('bun', options);
+ const installCommand = bundled ? null : resolveBunInstallCommand(options);
if (!bunPath) {
return {
status: 'missing',
@@ -124,7 +136,9 @@ export async function detectBun(options: CommonOptions = {}): Promise {
@@ -201,19 +232,7 @@ export async function resolveLauncherInstallTarget(
const homeDir = options.homeDir ?? os.homedir();
const pathDirs = collectPathDirs(options);
- const preferred =
- platform === 'darwin'
- ? [
- '/opt/homebrew/bin',
- '/usr/local/bin',
- path.posix.join(homeDir, '.local', 'bin'),
- path.posix.join(homeDir, 'bin'),
- ]
- : [
- path.posix.join(homeDir, '.local', 'bin'),
- path.posix.join(homeDir, 'bin'),
- '/usr/local/bin',
- ];
+ const preferred = preferredLauncherDirs(platform, homeDir);
const manualPreferred =
platform === 'darwin'
? [
@@ -251,13 +270,15 @@ export async function resolveLauncherInstallTarget(
isWritableDir(dir, options),
);
if (!selected) {
+ const pathDir = path.posix.join(homeDir, '.local', 'bin');
+ const installPath = path.posix.join(pathDir, 'subminer');
return {
- status: 'not_installable',
- commandPath: null,
- installPath: null,
- pathDir: null,
+ status: existsSyncOf(options)(installPath) ? 'not_on_path' : 'not_installed',
+ commandPath: existsSyncOf(options)(installPath) ? installPath : null,
+ installPath,
+ pathDir,
shadowedBy: null,
- message: 'No writable directory was found on your command-line PATH.',
+ message: `Add ${pathDir} to your terminal PATH: export PATH=${shellQuote(pathDir)}:"$PATH". Save this in your shell configuration for future terminals.`,
};
}
const installPath = path.posix.join(selected, 'subminer');
@@ -283,7 +304,29 @@ export async function detectLauncher(
const launcherResourcePath = resolveLauncherResourcePath(options);
const appExePath = options.appExePath ?? process.execPath;
- if (platform === 'win32' && existsSyncOf(options)(expectedPath)) {
+ if (options.bundledBunPath && existsSyncOf(options)(expectedPath)) {
+ const content = String((options.readFileSync ?? fs.readFileSync)(expectedPath, 'utf8'));
+ if (!isManagedLauncher(content)) {
+ return {
+ ...target,
+ status: 'not_installed',
+ message: 'Reinstall the launcher to use the runtime included with SubMiner.',
+ };
+ }
+ if (
+ content !==
+ managedLauncherContent({
+ platform,
+ appPath: envOf(options).APPIMAGE ?? appExePath,
+ })
+ ) {
+ return {
+ ...target,
+ status: 'not_installed',
+ message: 'Reinstall the launcher to refresh its SubMiner location.',
+ };
+ }
+ } else if (platform === 'win32' && existsSyncOf(options)(expectedPath)) {
const content = String((options.readFileSync ?? fs.readFileSync)(expectedPath, 'utf8'));
if (!shimMatchesCurrentInstall(content, appExePath, launcherResourcePath)) {
return {
@@ -305,26 +348,19 @@ export async function detectLauncher(
}
if (!existsSyncOf(options)(expectedPath))
return { ...target, status: 'not_installed', commandPath: null };
- if (!commandPath) {
- return {
- ...target,
- status: 'not_on_path',
- commandPath: expectedPath,
- message: 'Launcher exists but its directory is not on PATH.',
- };
- }
-
const bunSnapshot = options.bunSnapshot ?? (await detectBun(options));
if (bunSnapshot.status !== 'ready') {
return {
...target,
status: 'installed_bun_missing',
commandPath,
- message: 'Launcher is installed, but Bun is missing. Install Bun, then open a new terminal.',
+ message: options.bundledBunPath
+ ? bunSnapshot.message
+ : 'Launcher is installed, but Bun is missing. Install Bun, then open a new terminal.',
};
}
- const result = await getRunCommand(options)(commandPath, ['--help'], {
+ const result = await getRunCommand(options)(expectedPath, ['--help'], {
timeoutMs: COMMAND_TIMEOUT_MS,
env: envOf(options) as NodeJS.ProcessEnv,
});
@@ -336,6 +372,16 @@ export async function detectLauncher(
message: failureMessage(result, 'subminer --help failed'),
};
}
+ if (!commandPath) {
+ return {
+ ...target,
+ status: 'not_on_path',
+ commandPath: expectedPath,
+ message:
+ target.message ??
+ `Launcher installed. Add ${target.pathDir} to your terminal PATH: export PATH=${shellQuote(target.pathDir ?? '')}:"$PATH". Save this in your shell configuration for future terminals.`,
+ };
+ }
return { ...target, status: 'ready', commandPath, message: null };
}
@@ -354,6 +400,48 @@ export async function installLauncher(
};
}
+ if (options.bundledBunPath) {
+ const bun = await detectBun(options);
+ if (bun.status !== 'ready')
+ return {
+ ...target,
+ status: 'failed',
+ message: bun.message ?? 'The included launcher runtime failed to start.',
+ };
+ try {
+ stageManagedLauncher({
+ ...options,
+ bundledBunPath: options.bundledBunPath,
+ launcherResourcePath,
+ force: true,
+ });
+ (options.mkdirSync ?? fs.mkdirSync)(target.pathDir, { recursive: true });
+ (options.writeFileSync ?? fs.writeFileSync)(
+ target.installPath,
+ managedLauncherContent({
+ platform,
+ appPath: envOf(options).APPIMAGE ?? options.appExePath ?? process.execPath,
+ }),
+ );
+ (options.chmodSync ?? fs.chmodSync)(target.installPath, 0o755);
+ if (platform === 'win32') {
+ cleanupOldWindowsManagedRuntimes(options);
+ const nextPath = await appendWindowsUserPathDir(target.pathDir, options);
+ if (nextPath && options.env) {
+ options.env.PATH = nextPath;
+ options.env.Path = nextPath;
+ }
+ }
+ return await detectLauncher({ ...options, bunSnapshot: bun });
+ } catch (error) {
+ return {
+ ...target,
+ status: 'failed',
+ message: error instanceof Error ? error.message : String(error),
+ };
+ }
+ }
+
if (platform === 'win32') {
(options.mkdirSync ?? fs.mkdirSync)(target.pathDir, { recursive: true });
(options.writeFileSync ?? fs.writeFileSync)(
@@ -375,6 +463,8 @@ export async function installLauncher(
};
}
} else {
+ if (!existsSyncOf(options)(target.pathDir))
+ (options.mkdirSync ?? fs.mkdirSync)(target.pathDir, { recursive: true });
(options.copyFileSync ?? fs.copyFileSync)(launcherResourcePath, target.installPath);
(options.chmodSync ?? fs.chmodSync)(target.installPath, 0o755);
}
@@ -384,6 +474,7 @@ export async function installLauncher(
export async function installBun(
options: CommonOptions & WindowsPathOptions = {},
): Promise {
+ if (options.bundledBunPath) return detectBun(options);
const platform = platformOf(options);
if (platform === 'win32') {
const bunDir = defaultBunRepairPath(options);
@@ -455,6 +546,84 @@ export async function installBun(
};
}
+// Runs at app startup. Migrates recognized launchers in the standard bin dirs,
+// the setup install target, and any paths a deferred update handed over.
+// Returns paths that were refreshed or are no longer eligible for migration.
+export async function refreshManagedCommandLineLauncher(
+ options: CommonOptions & WindowsPathOptions & { additionalLauncherPaths?: string[] },
+): Promise {
+ if (!options.bundledBunPath) return [];
+ const target = await resolveLauncherInstallTarget(options);
+ const platform = platformOf(options);
+ const platformPath = pathModuleFor(platform);
+ // cmd.exe reads a batch file incrementally while it runs, so the launcher that
+ // started this app is left alone until a later app start rewrites it.
+ const runningLauncherPath =
+ platform === 'win32' ? envOf(options).SUBMINER_LAUNCHER_PATH : undefined;
+ const isRunningLauncher = (candidate: string) =>
+ runningLauncherPath !== undefined &&
+ platformPath.normalize(candidate).toLowerCase() ===
+ platformPath.normalize(runningLauncherPath).toLowerCase();
+ const candidates = new Set([
+ ...(target.installPath ? [target.installPath] : []),
+ ...(options.additionalLauncherPaths ?? []),
+ ...(platform === 'win32'
+ ? []
+ : preferredLauncherDirs(platform, options.homeDir ?? os.homedir()).map((directory) =>
+ path.posix.join(directory, 'subminer'),
+ )),
+ ]);
+ const readFile = options.readFileSync ?? fs.readFileSync;
+ const acknowledgedPaths: string[] = [];
+ let payload: ReturnType | undefined;
+ for (const candidate of candidates) {
+ if (isRunningLauncher(candidate)) continue;
+ if (!existsSyncOf(options)(candidate)) {
+ acknowledgedPaths.push(candidate);
+ continue;
+ }
+ let existing: string;
+ try {
+ existing = String(readFile(candidate, 'utf8'));
+ } catch {
+ continue;
+ }
+ const legacy =
+ (existing.startsWith('#!/usr/bin/env bun\n') &&
+ (existing.includes('SubMiner launcher') ||
+ existing.includes('Launch MPV with SubMiner'))) ||
+ (platform === 'win32' &&
+ existing ===
+ windowsShimContent(
+ options.appExePath ?? process.execPath,
+ resolveLauncherResourcePath(options).replace(/subminer\.js$/, 'subminer'),
+ ));
+ if (!isManagedLauncher(existing) && !legacy) {
+ acknowledgedPaths.push(candidate);
+ continue;
+ }
+ if (!isWritableDir(pathModuleFor(platform).dirname(candidate), options)) continue;
+ try {
+ accessSyncOf(options)(candidate, fs.constants.W_OK);
+ } catch {
+ continue;
+ }
+ payload ??= stageManagedLauncher({
+ ...options,
+ bundledBunPath: options.bundledBunPath,
+ launcherResourcePath: resolveLauncherResourcePath(options),
+ });
+ const content = managedLauncherContent({
+ platform,
+ appPath: envOf(options).APPIMAGE ?? options.appExePath ?? process.execPath,
+ });
+ if (existing !== content) (options.writeFileSync ?? fs.writeFileSync)(candidate, content);
+ acknowledgedPaths.push(candidate);
+ }
+ if (platform === 'win32' && payload) cleanupOldWindowsManagedRuntimes(options);
+ return acknowledgedPaths;
+}
+
export async function detectCommandLineLauncher(
options: CommonOptions & WindowsPathOptions = {},
): Promise {
diff --git a/src/main/runtime/composers/startup-lifecycle-composer.test.ts b/src/main/runtime/composers/startup-lifecycle-composer.test.ts
index fbe18443..6c31e386 100644
--- a/src/main/runtime/composers/startup-lifecycle-composer.test.ts
+++ b/src/main/runtime/composers/startup-lifecycle-composer.test.ts
@@ -52,6 +52,7 @@ test('composeStartupLifecycleHandlers returns callable startup lifecycle handler
cleanupInternalSubtitleTrackCache: () => {},
cleanupYoutubeSubtitleTempDirs: () => {},
cleanupYoutubeMediaCache: () => {},
+ cleanupRemoteMediaWindows: () => {},
cleanupJellyfinSubtitleCache: () => {},
stopDiscordPresenceService: () => {},
},
diff --git a/src/main/runtime/config-hot-reload-handlers.test.ts b/src/main/runtime/config-hot-reload-handlers.test.ts
index d8b2b761..d7d49f7a 100644
--- a/src/main/runtime/config-hot-reload-handlers.test.ts
+++ b/src/main/runtime/config-hot-reload-handlers.test.ts
@@ -156,6 +156,7 @@ test('createConfigHotReloadAppliedHandler applies only changed Anki media option
const config = deepCloneConfig(DEFAULT_CONFIG);
config.ankiConnect.media.normalizeAudio = false;
config.ankiConnect.media.mirrorMpvVolume = false;
+ config.ankiConnect.media.reviewTiming = true;
const ankiPatches: unknown[] = [];
const applyHotReload = createConfigHotReloadAppliedHandler({
@@ -181,10 +182,18 @@ test('createConfigHotReloadAppliedHandler applies only changed Anki media option
},
config,
);
+ applyHotReload(
+ {
+ hotReloadFields: ['ankiConnect.media.reviewTiming'],
+ restartRequiredFields: [],
+ },
+ config,
+ );
assert.deepEqual(ankiPatches, [
{ media: { normalizeAudio: false } },
{ media: { mirrorMpvVolume: false } },
+ { media: { reviewTiming: true } },
]);
});
diff --git a/src/main/runtime/config-hot-reload-handlers.ts b/src/main/runtime/config-hot-reload-handlers.ts
index c07e7dca..bd99a209 100644
--- a/src/main/runtime/config-hot-reload-handlers.ts
+++ b/src/main/runtime/config-hot-reload-handlers.ts
@@ -100,6 +100,9 @@ function buildAnkiRuntimeConfigPatch(
if (diff.hotReloadFields.includes('ankiConnect.media.mirrorMpvVolume')) {
mediaPatch.mirrorMpvVolume = config.ankiConnect.media.mirrorMpvVolume;
}
+ if (diff.hotReloadFields.includes('ankiConnect.media.reviewTiming')) {
+ mediaPatch.reviewTiming = config.ankiConnect.media.reviewTiming;
+ }
if (Object.keys(mediaPatch).length > 0) {
patch.media = mediaPatch;
}
diff --git a/src/main/runtime/first-run-setup-window.test.ts b/src/main/runtime/first-run-setup-window.test.ts
index e62dc335..024ff27e 100644
--- a/src/main/runtime/first-run-setup-window.test.ts
+++ b/src/main/runtime/first-run-setup-window.test.ts
@@ -271,7 +271,7 @@ test('parseFirstRunSetupSubmissionUrl parses supported custom actions', () => {
assert.equal(parseFirstRunSetupSubmissionUrl('https://example.com'), null);
});
-test('buildFirstRunSetupHtml renders command-line launcher section and actions', () => {
+test('buildFirstRunSetupHtml reports a broken included runtime in the optional launcher controls', () => {
const html = buildFirstRunSetupHtml({
configReady: true,
dictionaryCount: 1,
@@ -294,9 +294,9 @@ test('buildFirstRunSetupHtml renders command-line launcher section and actions',
status: 'failed',
commandPath: null,
version: null,
- installMethod: 'official-script',
- installCommand: ['bash', '-lc', 'curl -fsSL https://bun.com/install | bash'],
- message: 'network failed',
+ installMethod: null,
+ installCommand: null,
+ message: 'Included Bun runtime is missing.',
},
launcher: {
status: 'installed_bun_missing',
@@ -311,14 +311,11 @@ test('buildFirstRunSetupHtml renders command-line launcher section and actions',
});
assert.match(html, /Command line launcher/);
- assert.match(html, /Optional\. Setup can finish without Bun or the launcher\./);
- assert.match(html, /Bun runtime/);
+ assert.match(html, /Optional\. Install the launcher to use SubMiner from your terminal\./);
assert.match(html, /Failed/);
- assert.match(html, /bash -lc curl -fsSL https:\/\/bun\.com\/install \| bash/);
- assert.match(html, /Install Bun/);
- assert.match(html, /action=install-bun/);
assert.match(html, /SubMiner launcher/);
- assert.match(html, /Installed, Bun missing/);
+ assert.match(html, /Reinstall SubMiner to repair it/);
+ assert.match(html, /