Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: repair incomplete voice model downloads before reporting readiness (#9808)

[._.]/ Adam Eivy1a6a690122d6
diff --git a/docs/features/voice.md b/docs/features/voice.md
index cc687664da..21071f1fb2 100644
--- a/docs/features/voice.md
+++ b/docs/features/voice.md
@@ -263,6 +263,40 @@ PortOS will:
Piper voice models live under `~/.portos/voice/voices/`.
+### Model download completion and repair
+
+A model file that merely exists is not proof its download finished — a dropped
+connection leaves a truncated file at the final path. Both setup scripts
+(`scripts/setup-voice.sh`, `scripts/setup-voice.ps1`) therefore:
+
+- download each managed asset (Whisper `.bin`, Piper `.onnx` and `.onnx.json`) to a unique
+ temp sibling, check that the transfer completed with a non-empty payload, and parse the Piper
+ config (`audio.sample_rate`) **before** promoting anything — a failed replacement leaves the
+ previous files in place, and temp files are removed on failure;
+- write a `<asset>.portos-complete.json` receipt (size + sha256 per file) only after the whole
+ asset is promoted — for Piper, only once the `.onnx` **and** its `.onnx.json` are both in place;
+- on every run, re-verify the receipt (including sha256) and repair anything that no longer
+ matches.
+
+The server applies the same contract through `server/lib/voiceModelAssets.js`. A model is **ready**
+when its receipt matches the file sizes on disk, or — for installs that predate receipts and for
+files at a path you chose yourself — when it is non-empty and, for Piper, the `.onnx.json` next to
+it parses. A Piper `.onnx` without a valid `.onnx.json`, an empty file, or a file that disagrees
+with its receipt is **incomplete**: `/api/voice/status` and the Piper health badge stop reporting it
+ready (`models.ttsVoiceState` / `sttModelState` carry `verified`, `unverified`, `incomplete` or
+`missing`).
+
+Repair is always user-authorized. **Save & Reconcile** and the Settings voice-picker download re-run
+the setup script for an incomplete model instead of skipping it. Server boot only reads state: an
+incomplete model is logged and left for the next Save & Reconcile, and boot starts no model download.
+
+Models that predate receipts keep working. The next Save & Reconcile has the script adopt them: a
+Piper pair with a parseable config is recorded as complete with no network access; a Whisper file is
+compared with the remote size (adopted on a match, re-downloaded on a mismatch, left untouched when
+the remote size cannot be read). Only files directly in `~/.portos/voice/models/` and
+`~/.portos/voice/voices/` are managed this way — a model at any other path is validated but never
+replaced, so give a hand-installed model its own filename or directory.
+
You can also run the bootstrap script directly:
```bash
diff --git a/scripts/setup-voice.ps1 b/scripts/setup-voice.ps1
index b691e224b8..f6a4234f66 100644
--- a/scripts/setup-voice.ps1
+++ b/scripts/setup-voice.ps1
@@ -7,6 +7,12 @@
# VOICE_NAME Piper voice name (default: en_GB-jenny_dioco-medium)
# TTS_ENGINE 'piper' (default) | 'qwen3-tts'
# INSTALL_COREML '1' — ignored on Windows (CoreML is Apple Silicon only)
+#
+# Model downloads are staged to a unique temp sibling, validated, then promoted;
+# a `<asset>.portos-complete.json` receipt (sizes + sha256, see
+# server/lib/voiceModelAssets.js) is written only after the whole asset (for
+# Piper: BOTH the .onnx and its .json) is in place. A file without a valid
+# receipt is repaired on the next run — existence alone never counts.
$ErrorActionPreference = 'Stop'
@@ -32,6 +38,110 @@ function Download-File($url, $dest) {
Invoke-WebRequest -Uri $url -OutFile $dest -UseBasicParsing
}
+# ── Completion contract (shared with setup-voice.sh via scripts/voice-asset.js) ─
+# Staged files are unique temp siblings of the final path; the finally block at
+# the model sections removes whatever a failed transfer left behind.
+$script:StagedFiles = @()
+
+function Invoke-VoiceAsset {
+ $out = & node (Join-Path $PSScriptRoot 'voice-asset.js') @args
+ if ($LASTEXITCODE -ne 0) { throw "voice-asset $($args -join ' ') failed (exit $LASTEXITCODE)" }
+ return $out
+}
+
+function Get-AssetState($kind, $path) {
+ [string](Invoke-VoiceAsset state $kind $path | Select-Object -Last 1).Trim()
+}
+
+function Test-PiperConfig($path) {
+ & node (Join-Path $PSScriptRoot 'voice-asset.js') check-config $path
+ return ($LASTEXITCODE -eq 0)
+}
+
+# Content-Length of a remote file, or $null when it cannot be determined.
+function Get-RemoteSize($url) {
+ try {
+ $resp = Invoke-WebRequest -Uri $url -Method Head -UseBasicParsing
+ $len = $resp.Headers['Content-Length']
+ if ($len -is [array]) { $len = $len[0] }
+ if ($len) { return [int64]$len }
+ } catch { }
+ return $null
+}
+
+# Download into a fresh temp sibling of $final and return its path.
+function Download-Staged($url, $final) {
+ $tmp = "$final.part.$([guid]::NewGuid().ToString('N').Substring(0, 8))"
+ $script:StagedFiles += $tmp
+ Write-Host "⬇️ $(Split-Path $final -Leaf)"
+ Invoke-WebRequest -Uri $url -OutFile $tmp -UseBasicParsing
+ if (-not (Test-Path -LiteralPath $tmp) -or (Get-Item -LiteralPath $tmp).Length -eq 0) {
+ throw "Empty download from $url"
+ }
+ return $tmp
+}
+
+function Ensure-WhisperModel {
+ $path = Join-Path $MODELS_DIR $MODEL_NAME
+ $url = "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/$MODEL_NAME"
+ $state = Get-AssetState 'whisper' $path
+ if ($state -eq 'verified') { return }
+ if ($state -eq 'unverified') {
+ # Installed before completion receipts (or user-supplied). A partial
+ # transfer looks identical to a complete file, so compare against the
+ # remote size: adopt a match, replace a mismatch, and leave the file
+ # alone when the remote size cannot be read.
+ $want = Get-RemoteSize $url
+ $have = (Get-Item -LiteralPath $path).Length
+ if ($null -eq $want) {
+ Write-Host "⚠️ Cannot verify existing Whisper model (remote size unavailable) — leaving $path as is" -ForegroundColor Yellow
+ return
+ }
+ if ($want -eq $have) {
+ Invoke-VoiceAsset receipt whisper $path | Out-Null
+ return
+ }
+ Write-Host "⚠️ Existing Whisper model is $have bytes, expected $want — re-downloading" -ForegroundColor Yellow
+ }
+ Write-Host "⬇️ Whisper model → $path"
+ $tmp = Download-Staged $url $path
+ Move-Item -LiteralPath $tmp -Destination $path -Force
+ Invoke-VoiceAsset receipt whisper $path | Out-Null
+}
+
+# Both halves are staged and validated before either is promoted, so a failed
+# replacement leaves the previous (complete) pair untouched.
+function Ensure-PiperVoice {
+ $onnxPath = Join-Path $VOICES_DIR "$VOICE_NAME.onnx"
+ $jsonPath = Join-Path $VOICES_DIR "$VOICE_NAME.onnx.json"
+ $state = Get-AssetState 'piper' $onnxPath
+ if ($state -eq 'verified') { return }
+ if ($state -eq 'unverified') {
+ # Pair predates receipts. The old script fetched the sidecar only after
+ # the ONNX finished, so a parseable sidecar next to a non-empty ONNX is a
+ # complete pair — adopt it without touching the network.
+ Invoke-VoiceAsset receipt piper $onnxPath | Out-Null
+ return
+ }
+ # en_US-ryan-high → en / en_US / ryan / high
+ $locale = ($VOICE_NAME -split '-')[0] # en_US
+ $lang = ($locale -split '_')[0] # en
+ $rest = $VOICE_NAME.Substring($locale.Length + 1) # ryan-high
+ $parts = $rest -split '-'
+ $speaker = $parts[0] # ryan
+ $quality = $parts[1] # high
+ $base = "https://huggingface.co/rhasspy/piper-voices/resolve/main/$lang/$locale/$speaker/$quality"
+ Write-Host "⬇️ Piper voice → $onnxPath"
+ $onnxTmp = Download-Staged "$base/$VOICE_NAME.onnx" $onnxPath
+ $jsonTmp = Download-Staged "$base/$VOICE_NAME.onnx.json" $jsonPath
+ if (-not (Test-PiperConfig $jsonTmp)) {
+ throw "Downloaded Piper config for $VOICE_NAME is not a valid voice config"
+ }
+ Move-Item -LiteralPath $onnxTmp -Destination $onnxPath -Force
+ Move-Item -LiteralPath $jsonTmp -Destination $jsonPath -Force
+ Invoke-VoiceAsset receipt piper $onnxPath | Out-Null
+}
+
# ── whisper-server ────────────────────────────────────────────────────────────
if ($STT_ENGINE -eq 'whisper') {
$whisperExe = Join-Path $PIPER_DIR '..\whisper\whisper-server.exe'
@@ -72,32 +182,13 @@ if ($TTS_ENGINE -eq 'piper') {
}
}
-# ── Whisper GGUF model ────────────────────────────────────────────────────────
-if ($STT_ENGINE -eq 'whisper') {
- $modelPath = Join-Path $MODELS_DIR $MODEL_NAME
- if (-not (Test-Path $modelPath)) {
- $url = "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/$MODEL_NAME"
- Write-Host "⬇️ Whisper model → $modelPath"
- Invoke-WebRequest -Uri $url -OutFile $modelPath -UseBasicParsing
- }
-}
-
-# ── Piper voice (ONNX + JSON sidecar) ────────────────────────────────────────
-if ($TTS_ENGINE -eq 'piper') {
- $onnxPath = Join-Path $VOICES_DIR "$VOICE_NAME.onnx"
- $jsonPath = Join-Path $VOICES_DIR "$VOICE_NAME.onnx.json"
- if (-not (Test-Path $onnxPath)) {
- # en_US-ryan-high → en / en_US / ryan / high
- $locale = ($VOICE_NAME -split '-')[0] # en_US
- $lang = ($locale -split '_')[0] # en
- $rest = $VOICE_NAME.Substring($locale.Length + 1) # ryan-high
- $parts = $rest -split '-'
- $speaker = $parts[0] # ryan
- $quality = $parts[1] # high
- $base = "https://huggingface.co/rhasspy/piper-voices/resolve/main/$lang/$locale/$speaker/$quality"
- Write-Host "⬇️ Piper voice → $onnxPath"
- Invoke-WebRequest -Uri "$base/$VOICE_NAME.onnx" -OutFile $onnxPath -UseBasicParsing
- Invoke-WebRequest -Uri "$base/$VOICE_NAME.onnx.json" -OutFile $jsonPath -UseBasicParsing
+# ── Whisper GGUF model + Piper voice (ONNX + JSON sidecar) ────────────────────
+try {
+ if ($STT_ENGINE -eq 'whisper') { Ensure-WhisperModel }
+ if ($TTS_ENGINE -eq 'piper') { Ensure-PiperVoice }
+} finally {
+ foreach ($staged in $script:StagedFiles) {
+ Remove-Item -LiteralPath $staged -Force -ErrorAction SilentlyContinue
}
}
diff --git a/scripts/setup-voice.ps1.test.js b/scripts/setup-voice.ps1.test.js
new file mode 100644
index 0000000000..d922d8c775
--- /dev/null
+++ b/scripts/setup-voice.ps1.test.js
@@ -0,0 +1,99 @@
+// Windows-installer counterpart of setup-voice.test.js. Runs the real
+// setup-voice.ps1 under PowerShell with Invoke-WebRequest replaced by a function
+// stub (functions outrank cmdlets), in a disposable USERPROFILE — no network.
+// Skipped where no PowerShell is installed; Windows and ubuntu CI runners ship one.
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { spawnSync } from 'child_process';
+import { tmpdir } from 'os';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+import { inspectVoiceAsset } from '../server/lib/voiceModelAssets.js';
+
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+const VOICE = 'en_US-test-low';
+const PS = ['pwsh', 'powershell'].find((bin) => spawnSync(bin, ['-NoProfile', '-Command', 'exit 0']).status === 0);
+
+const WRAPPER = `
+$ErrorActionPreference = 'Stop'
+function Invoke-WebRequest {
+ param($Uri, $OutFile, $Method, [switch]$UseBasicParsing)
+ Add-Content -Path $env:CURL_LOG -Value "$Method $Uri"
+ if ($env:CURL_FAIL_MATCH -and $Uri -like "*$($env:CURL_FAIL_MATCH)*") {
+ Set-Content -Path $OutFile -Value 'partial' -NoNewline
+ throw 'transfer dropped'
+ }
+ if ($Uri -like '*.onnx.json') { Set-Content -Path $OutFile -Value '{"audio":{"sample_rate":22050}}' -NoNewline }
+ elseif ($Uri -like '*.onnx') { Set-Content -Path $OutFile -Value 'onnx-v1' -NoNewline }
+ else { Set-Content -Path $OutFile -Value 'whisper-v1' -NoNewline }
+}
+. (Join-Path $env:REPO_ROOT 'scripts/setup-voice.ps1')
+`;
+
+describe.skipIf(!PS)('setup-voice.ps1 model provisioning', () => {
+ let home;
+ let voices;
+ let log;
+ let wrapper;
+
+ const run = (env = {}) => spawnSync(PS, ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', wrapper], {
+ cwd: ROOT,
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ USERPROFILE: home,
+ REPO_ROOT: ROOT,
+ STT_ENGINE: 'web-speech',
+ TTS_ENGINE: 'piper',
+ VOICE_NAME: VOICE,
+ CURL_LOG: log,
+ ...env,
+ },
+ });
+ const onnx = () => join(voices, `${VOICE}.onnx`);
+ const leftovers = () => readdirSync(voices).filter((f) => f.includes('.part.'));
+
+ beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), 'setup-voice-ps-'));
+ wrapper = join(home, 'wrapper.ps1');
+ writeFileSync(wrapper, WRAPPER);
+ log = join(home, 'web.log');
+ // Piper binary already installed, so only the voice is provisioned.
+ const piper = join(home, '.portos/voice/piper');
+ mkdirSync(piper, { recursive: true });
+ writeFileSync(join(piper, 'piper.exe'), 'x');
+ chmodSync(join(piper, 'piper.exe'), 0o755);
+ voices = join(home, '.portos/voice/voices');
+ });
+ afterEach(() => rmSync(home, { recursive: true, force: true }));
+
+ it('leaves no partial pair when the sidecar transfer drops, then recovers on retry', () => {
+ const failed = run({ CURL_FAIL_MATCH: '.onnx.json' });
+ expect(failed.status).not.toBe(0);
+ expect(existsSync(onnx())).toBe(false);
+ expect(leftovers()).toEqual([]);
+
+ const retry = run();
+ expect(retry.status, `${retry.stdout}\n${retry.stderr}`).toBe(0);
+ expect(inspectVoiceAsset('piper', onnx()).state).toBe('verified');
+ });
+
+ it('repairs a poisoned ONNX that has no sidecar', () => {
+ mkdirSync(voices, { recursive: true });
+ writeFileSync(onnx(), 'partial');
+ const result = run();
+ expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
+ expect(readFileSync(onnx(), 'utf8')).toBe('onnx-v1');
+ expect(inspectVoiceAsset('piper', onnx()).state).toBe('verified');
+ });
+
+ it('adopts a complete pre-receipt pair without downloading', () => {
+ mkdirSync(voices, { recursive: true });
+ writeFileSync(onnx(), 'legacy-onnx');
+ writeFileSync(`${onnx()}.json`, '{"audio":{"sample_rate":22050}}');
+ expect(run().status).toBe(0);
+ expect(existsSync(log)).toBe(false);
+ expect(inspectVoiceAsset('piper', onnx()).state).toBe('verified');
+ });
+});
diff --git a/scripts/setup-voice.sh b/scripts/setup-voice.sh
index d754d096d5..aff382b5ec 100755
--- a/scripts/setup-voice.sh
+++ b/scripts/setup-voice.sh
@@ -11,7 +11,12 @@
# INSTALL_COREML '1' to download CoreML encoder for Whisper on macOS (default: 0)
#
# Models live under ~/.portos/voice/{models,voices}/.
-
+#
+# Model downloads are staged to a unique temp sibling, validated, then promoted
+# with an atomic rename; a `<asset>.portos-complete.json` receipt (sizes +
+# sha256, see server/lib/voiceModelAssets.js) is written only after the whole
+# asset (for Piper: BOTH the .onnx and its .json) is in place. A file without a
+# valid receipt is repaired on the next run — existence alone never counts.
set -euo pipefail
VOICE_HOME="${HOME}/.portos/voice"
@@ -25,6 +30,37 @@ INSTALL_COREML="${INSTALL_COREML:-0}"
mkdir -p "$MODELS_DIR" "$VOICES_DIR"
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+
+# Unique temp siblings of the final path, removed on any exit so a failed or
+# interrupted transfer never leaves a partial file behind.
+STAGED_FILES=()
+cleanup_staged() { if ((${#STAGED_FILES[@]})); then rm -f "${STAGED_FILES[@]}"; fi; }
+trap cleanup_staged EXIT
+
+# Completion contract shared with the server and setup-voice.ps1.
+asset() { node "${SCRIPT_DIR}/voice-asset.js" "$@"; }
+
+# Download $1 into a fresh temp sibling of $2; the path is left in STAGED_TMP.
+# Global rather than echoed: command substitution would run in a subshell and
+# lose the STAGED_FILES registration the EXIT cleanup depends on.
+download_staged() {
+ local url="$1" final="$2"
+ STAGED_TMP="$(mktemp "${final}.part.XXXXXX")"
+ STAGED_FILES+=("$STAGED_TMP")
+ curl --fail --location --progress-bar "$url" -o "$STAGED_TMP"
+ if [[ ! -s "$STAGED_TMP" ]]; then
+ echo "❌ Empty download from $url" >&2
+ exit 1
+ fi
+}
+
+# Content-Length of a remote file, or empty when it cannot be determined (offline,
+# unknown name). The last header wins so a redirect hop's own length is ignored.
+remote_size() {
+ { curl --fail --location --silent --head "$1" 2>/dev/null || true; } \
+ | tr -d '\r' | awk 'tolower($1) == "content-length:" { n = $2 } END { print n }'
+}
have() { command -v "$1" >/dev/null 2>&1; }
is_macos() { [[ "$(uname -s)" == "Darwin" ]]; }
@@ -88,11 +124,38 @@ if [[ "$TTS_ENGINE" == "piper" ]]; then
fi
# Whisper model (GGUF) — only when whisper engine is active.
-if [[ "$STT_ENGINE" == "whisper" && ! -f "${MODELS_DIR}/${MODEL_NAME}" ]]; then
- echo "⬇️ Whisper model → ${MODELS_DIR}/${MODEL_NAME}"
- curl --fail --location --progress-bar \
- "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/${MODEL_NAME}" \
- -o "${MODELS_DIR}/${MODEL_NAME}"
+ensure_whisper_model() {
+ local path="${MODELS_DIR}/${MODEL_NAME}"
+ local url="https://huggingface.co/ggerganov/whisper.cpp/resolve/main/${MODEL_NAME}"
+ local state want have
+ state="$(asset state whisper "$path")"
+ if [[ "$state" == "verified" ]]; then
+ return 0
+ fi
+ if [[ "$state" == "unverified" ]]; then
+ # Installed before completion receipts (or user-supplied). A partial transfer
+ # looks identical to a complete file here, so compare against the remote
+ # size: adopt a match, replace a mismatch, and leave the file alone when the
+ # remote size cannot be read — never discard a model on a guess.
+ want="$(remote_size "$url")"
+ have="$(wc -c < "$path" | tr -d ' ')"
+ if [[ -z "$want" ]]; then
+ echo "⚠️ Cannot verify existing Whisper model (remote size unavailable) — leaving ${path} as is" >&2
+ return 0
+ fi
+ if [[ "$want" == "$have" ]]; then
+ asset receipt whisper "$path"
+ return 0
+ fi
+ echo "⚠️ Existing Whisper model is ${have} bytes, expected ${want} — re-downloading" >&2
+ fi
+ echo "⬇️ Whisper model → ${path}"
+ download_staged "$url" "$path"
+ mv -f "$STAGED_TMP" "$path"
+ asset receipt whisper "$path"
+}
+if [[ "$STT_ENGINE" == "whisper" ]]; then
+ ensure_whisper_model
fi
# CoreML encoder companion (macOS only) — 2–3× faster STT on Apple Silicon.
@@ -113,20 +176,44 @@ fi
# Piper voice (ONNX + JSON sidecar). Only when active engine uses it.
# Voice names encode path: en_US-ryan-high → en/en_US/ryan/high/
-if [[ "$TTS_ENGINE" == "piper" ]]; then
- ONNX_PATH="${VOICES_DIR}/${VOICE_NAME}.onnx"
- JSON_PATH="${VOICES_DIR}/${VOICE_NAME}.onnx.json"
- if [[ ! -f "${ONNX_PATH}" ]]; then
- LOCALE="${VOICE_NAME%%-*}" # en_US
- LANG_="${LOCALE%%_*}" # en
- REST="${VOICE_NAME#*-}" # ryan-high
- SPEAKER="${REST%-*}" # ryan
- QUALITY="${REST##*-}" # high
- BASE="https://huggingface.co/rhasspy/piper-voices/resolve/main/${LANG_}/${LOCALE}/${SPEAKER}/${QUALITY}"
- echo "⬇️ Piper voice → ${ONNX_PATH}"
- curl --fail --location --progress-bar "${BASE}/${VOICE_NAME}.onnx" -o "${ONNX_PATH}"
- curl --fail --location --progress-bar "${BASE}/${VOICE_NAME}.onnx.json" -o "${JSON_PATH}"
+# Both halves are staged and validated before either is promoted, so a failed
+# replacement leaves the previous (complete) pair untouched.
+ONNX_PATH="${VOICES_DIR}/${VOICE_NAME}.onnx"
+JSON_PATH="${VOICES_DIR}/${VOICE_NAME}.onnx.json"
+ensure_piper_voice() {
+ local state locale lang_ rest speaker quality base onnx_tmp json_tmp
+ state="$(asset state piper "$ONNX_PATH")"
+ if [[ "$state" == "verified" ]]; then
+ return 0
fi
+ if [[ "$state" == "unverified" ]]; then
+ # Pair predates receipts. The old script fetched the sidecar only after the
+ # ONNX finished, so a parseable sidecar next to a non-empty ONNX is a
+ # complete pair — adopt it without touching the network.
+ asset receipt piper "$ONNX_PATH"
+ return 0
+ fi
+ locale="${VOICE_NAME%%-*}" # en_US
+ lang_="${locale%%_*}" # en
+ rest="${VOICE_NAME#*-}" # ryan-high
+ speaker="${rest%-*}" # ryan
+ quality="${rest##*-}" # high
+ base="https://huggingface.co/rhasspy/piper-voices/resolve/main/${lang_}/${locale}/${speaker}/${quality}"
+ echo "⬇️ Piper voice → ${ONNX_PATH}"
+ download_staged "${base}/${VOICE_NAME}.onnx" "$ONNX_PATH"
+ onnx_tmp="$STAGED_TMP"
+ download_staged "${base}/${VOICE_NAME}.onnx.json" "$JSON_PATH"
+ json_tmp="$STAGED_TMP"
+ if ! asset check-config "$json_tmp"; then
+ echo "❌ Downloaded Piper config for ${VOICE_NAME} is not a valid voice config" >&2
+ exit 1
+ fi
+ mv -f "$onnx_tmp" "$ONNX_PATH"
+ mv -f "$json_tmp" "$JSON_PATH"
+ asset receipt piper "$ONNX_PATH"
+}
+if [[ "$TTS_ENGINE" == "piper" ]]; then
+ ensure_piper_voice
fi
echo "✅ Voice stack ready"
diff --git a/scripts/setup-voice.test.js b/scripts/setup-voice.test.js
new file mode 100644
index 0000000000..6a2fa1ffd2
--- /dev/null
+++ b/scripts/setup-voice.test.js
@@ -0,0 +1,172 @@
+// Script-boundary coverage for scripts/setup-voice.sh: runs the real script in a
+// disposable HOME with a `curl` stub on PATH, so no network, model or host state
+// is touched. The stub can fail a chosen transfer after writing a partial file
+// to the requested destination — what a dropped connection leaves behind.
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { spawnSync } from 'child_process';
+import { tmpdir } from 'os';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+import { inspectVoiceAsset } from '../server/lib/voiceModelAssets.js';
+
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+const VOICE = 'en_US-test-low';
+const CURL_STUB = `#!/usr/bin/env bash
+dest=""; head=0; url=""
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ -o) dest="$2"; shift 2 ;;
+ --head) head=1; shift ;;
+ --fail|--location|--silent|--progress-bar) shift ;;
+ *) url="$1"; shift ;;
+ esac
+done
+echo "$head $url" >> "$CURL_LOG"
+if [[ $head == 1 ]]; then
+ [[ -n "\${CURL_REMOTE_SIZE:-}" ]] || exit 22
+ printf 'HTTP/2 200\\r\\ncontent-length: %s\\r\\n\\r\\n' "$CURL_REMOTE_SIZE"
+ exit 0
+fi
+if [[ -n "\${CURL_FAIL_MATCH:-}" && "$url" == *"\${CURL_FAIL_MATCH}"* ]]; then
+ printf 'partial' > "$dest"
+ exit 18
+fi
+case "$url" in
+ *.onnx.json) printf '{"audio":{"sample_rate":22050}}' > "$dest" ;;
+ *.onnx) printf 'onnx-%s' "\${CURL_TAG:-v1}" > "$dest" ;;
+ *) printf 'whisper-%s' "\${CURL_TAG:-v1}" > "$dest" ;;
+esac
+`;
+
+describe.skipIf(process.platform === 'win32')('setup-voice.sh model provisioning', () => {
+ let home;
+ let stubDir;
+ let voices;
+ let models;
+ let log;
+
+ const run = (env = {}) => spawnSync('bash', [join(ROOT, 'scripts/setup-voice.sh')], {
+ cwd: ROOT,
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ HOME: home,
+ PATH: `${stubDir}:${process.env.PATH}`,
+ STT_ENGINE: 'web-speech',
+ TTS_ENGINE: 'piper',
+ VOICE_NAME: VOICE,
+ MODEL_NAME: 'ggml-test.bin',
+ CURL_LOG: log,
+ ...env,
+ },
+ });
+ const downloads = () => (existsSync(log) ? readFileSync(log, 'utf8').split('\n').filter((l) => l.startsWith('0 ')) : []);
+ const onnx = () => join(voices, `${VOICE}.onnx`);
+ const leftovers = (dir) => readdirSync(dir).filter((f) => f.includes('.part.'));
+
+ beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), 'setup-voice-'));
+ stubDir = join(home, 'stub');
+ mkdirSync(stubDir);
+ writeFileSync(join(stubDir, 'curl'), CURL_STUB);
+ chmodSync(join(stubDir, 'curl'), 0o755);
+ log = join(home, 'curl.log');
+ // Pretend the Piper binary and its libs are already installed.
+ const piper = join(home, '.portos/voice/piper');
+ mkdirSync(join(piper, 'lib'), { recursive: true });
+ writeFileSync(join(piper, 'piper'), '#!/bin/sh\n');
+ chmodSync(join(piper, 'piper'), 0o755);
+ writeFileSync(join(piper, 'lib/libpiper_phonemize.1.dylib'), 'x');
+ voices = join(home, '.portos/voice/voices');
+ models = join(home, '.portos/voice/models');
+ });
+ afterEach(() => rmSync(home, { recursive: true, force: true }));
+
+ it.each([
+ ['ONNX', `${VOICE}.onnx`],
+ ['sidecar', '.onnx.json'],
+ ])('leaves no partial Piper asset when the %s transfer drops, then recovers on retry', (_label, failMatch) => {
+ const failed = run({ CURL_FAIL_MATCH: failMatch });
+ expect(failed.status).toBe(18);
+ expect(existsSync(onnx())).toBe(false);
+ expect(leftovers(voices)).toEqual([]);
+
+ const retry = run();
+ expect(retry.status).toBe(0);
+ expect(inspectVoiceAsset('piper', onnx()).state).toBe('verified');
+ });
+
+ it('repairs a poisoned ONNX with no sidecar instead of reporting ready', () => {
+ mkdirSync(voices, { recursive: true });
+ writeFileSync(onnx(), 'partial');
+ const result = run();
+ expect(result.status).toBe(0);
+ expect(downloads()).toHaveLength(2);
+ expect(readFileSync(onnx(), 'utf8')).toBe('onnx-v1');
+ expect(inspectVoiceAsset('piper', onnx()).state).toBe('verified');
+ });
+
+ it('keeps the existing pair when its replacement fails partway, and writes no new receipt', () => {
+ expect(run().status).toBe(0);
+ const receipt = readFileSync(`${onnx()}.portos-complete.json`, 'utf8');
+ // Same-size tamper: only the hash pass can tell, and it forces a re-download.
+ writeFileSync(onnx(), 'onnx-vX');
+ const failed = run({ CURL_FAIL_MATCH: '.onnx.json', CURL_TAG: 'v2' });
+ expect(failed.status).toBe(18);
+ expect(readFileSync(onnx(), 'utf8')).toBe('onnx-vX');
+ expect(readFileSync(`${onnx()}.portos-complete.json`, 'utf8')).toBe(receipt);
+ expect(leftovers(voices)).toEqual([]);
+ });
+
+ it('adopts a complete pre-receipt pair without any download', () => {
+ mkdirSync(voices, { recursive: true });
+ writeFileSync(onnx(), 'legacy-onnx');
+ writeFileSync(`${onnx()}.json`, '{"audio":{"sample_rate":22050}}');
+ expect(run().status).toBe(0);
+ expect(downloads()).toEqual([]);
+ expect(readFileSync(onnx(), 'utf8')).toBe('legacy-onnx');
+ expect(inspectVoiceAsset('piper', onnx()).state).toBe('verified');
+ });
+
+ describe('Whisper model', () => {
+ const model = () => join(models, 'ggml-test.bin');
+ const whisperEnv = () => {
+ writeFileSync(join(stubDir, 'whisper-server'), '#!/bin/sh\n');
+ chmodSync(join(stubDir, 'whisper-server'), 0o755);
+ return { STT_ENGINE: 'whisper', TTS_ENGINE: 'qwen3-tts' };
+ };
+
+ it('drops a partial download instead of leaving a model at the final path', () => {
+ const env = whisperEnv();
+ const failed = run({ ...env, CURL_FAIL_MATCH: 'ggml-test.bin' });
+ expect(failed.status).toBe(18);
+ expect(existsSync(model())).toBe(false);
+ expect(leftovers(models)).toEqual([]);
+ expect(run(env).status).toBe(0);
+ expect(inspectVoiceAsset('whisper', model()).state).toBe('verified');
+ });
+
+ it('re-downloads a pre-receipt file whose size differs from the remote one', () => {
+ const env = whisperEnv();
+ mkdirSync(models, { recursive: true });
+ writeFileSync(model(), 'trunc');
+ expect(run({ ...env, CURL_REMOTE_SIZE: '9' }).status).toBe(0);
+ expect(readFileSync(model(), 'utf8')).toBe('whisper-v1');
+ });
+
+ it('adopts a pre-receipt file whose size matches, and leaves it alone when the remote size is unknown', () => {
+ const env = whisperEnv();
+ mkdirSync(models, { recursive: true });
+ writeFileSync(model(), 'custom-model');
+ expect(run(env).status).toBe(0);
+ expect(downloads()).toEqual([]);
+ expect(inspectVoiceAsset('whisper', model()).state).toBe('unverified');
+ expect(run({ ...env, CURL_REMOTE_SIZE: String('custom-model'.length) }).status).toBe(0);
+ expect(downloads()).toEqual([]);
+ expect(readFileSync(model(), 'utf8')).toBe('custom-model');
+ expect(inspectVoiceAsset('whisper', model()).state).toBe('verified');
+ });
+ });
+});
diff --git a/scripts/voice-asset.js b/scripts/voice-asset.js
new file mode 100644
index 0000000000..c979feec93
--- /dev/null
+++ b/scripts/voice-asset.js
@@ -0,0 +1,39 @@
+#!/usr/bin/env node
+// CLI face of server/lib/voiceModelAssets.js for scripts/setup-voice.sh and
+// setup-voice.ps1, so the shell and PowerShell installers share one completion
+// contract (receipt format, sidecar validation, hash check) instead of each
+// re-implementing it.
+//
+// voice-asset.js state <whisper|piper> <primary-path> print verified|unverified|incomplete|missing
+// (re-hashes a receipted asset)
+// voice-asset.js receipt <whisper|piper> <primary-path> record completion after promotion
+// voice-asset.js check-config <piper-config.json> exit 0 when a usable Piper config
+
+import { readFileSync } from 'fs';
+import {
+ isValidPiperConfig, verifyVoiceAssetHashes, writeVoiceAssetReceipt,
+} from '../server/lib/voiceModelAssets.js';
+
+const [command, ...args] = process.argv.slice(2);
+
+const main = async () => {
+ if (command === 'state') {
+ const { state, reason } = await verifyVoiceAssetHashes(args[0], args[1]);
+ console.log(state);
+ if (reason) console.error(`ℹ️ ${args[1]}: ${reason}`);
+ return 0;
+ }
+ if (command === 'receipt') {
+ await writeVoiceAssetReceipt(args[0], args[1]);
+ return 0;
+ }
+ if (command === 'check-config') {
+ return isValidPiperConfig(readFileSync(args[0], 'utf8')) ? 0 : 1;
+ }
+ console.error('usage: voice-asset.js state|receipt <whisper|piper> <path> | check-config <file>');
+ return 2;
+};
+
+main()
+ .then((code) => { process.exitCode = code; })
+ .catch((err) => { console.error(`❌ voice-asset ${command}: ${err.message}`); process.exitCode = 1; });
diff --git a/server/lib/README.md b/server/lib/README.md
index 8138e86fe4..21859f4e2a 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -764,6 +764,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `videoTimelineFades.js` | Browser-safe `fitFades()` proportionally fits a fade pair to its visible duration. Shared by timeline normalization/export and the editor preview/trim controls; legacy import paths re-export it. |
| `voiceEcho.js` | Pure voice-echo detection helpers — tokenization, trigram building, thresholds shared by server and client echo gates. |
| `voiceEngines.js` | Shared TTS engine IDs, display metadata, supported-engine set, persisted configuration keys, and retired TTS config migration. |
+| `voiceModelAssets.js` | Completion contract for downloaded voice model assets (Whisper `.bin`, Piper `.onnx` + `.onnx.json`). `inspectVoiceAsset(kind, path)` is the read-only readiness check (`verified` / `unverified` / `incomplete` / `missing` — stat plus one small JSON read, no hashing or network); `verifyVoiceAssetHashes` and `writeVoiceAssetReceipt` are the script-side halves that re-hash and record the `.portos-complete.json` receipt after promotion. `isManagedVoiceAsset` separates setup-script-owned files from user-supplied ones. Shared by `voice/bootstrap.js`, `voice/health.js` and `scripts/voice-asset.js`. |
| `auditQuality.js` | Category discovery strategies, assessment prompt and strict schema, sentinel parsing, and freshness-aware app quality aggregation with deterministic latest-per-category selection across peers. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 5cf967297b..fa2a0d6f3b 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -739,6 +739,7 @@ export * from './videoTimelineFades.js';
// `tokenize` collides with `bm25.js`'s own tokenizer — namespaced like `runners`.
export * as voiceEcho from './voiceEcho.js';
export * from './voiceEngines.js';
+export * from './voiceModelAssets.js';
export * from './httpCompression.js';
export * from './auditQuality.js';
diff --git a/server/lib/voiceModelAssets.js b/server/lib/voiceModelAssets.js
new file mode 100644
index 0000000000..228bc9edcd
--- /dev/null
+++ b/server/lib/voiceModelAssets.js
@@ -0,0 +1,164 @@
+// Completion contract for downloaded voice model assets (Whisper .bin, Piper
+// .onnx + .onnx.json pair). The setup scripts download into temp siblings,
+// promote the verified files, and only then write a receipt next to the primary
+// asset. A bare file's existence is NOT evidence the download finished — a
+// dropped transfer leaves a partial file at the final path.
+//
+// Readiness states (the server reads these without any network or hashing):
+// verified receipt present and every listed file still has its recorded size
+// unverified no receipt (installed before receipts, or a user-supplied file)
+// but structurally usable: non-empty, and a Piper pair has a
+// parseable sidecar. Stays usable; the next user-authorized setup
+// run adopts it by writing a receipt
+// incomplete present but not usable: empty, sidecar missing/invalid, or a
+// receipt that no longer matches the files on disk
+// missing the primary file is absent
+//
+// The scripts (setup-voice.sh / .ps1, via scripts/voice-asset.js) additionally
+// re-verify sha256 so a same-size replacement cannot keep a valid receipt.
+
+import { createHash } from 'crypto';
+import { createReadStream, existsSync, readFileSync, renameSync, statSync, writeFileSync, unlinkSync } from 'fs';
+import { basename, dirname, join, resolve } from 'path';
+
+export const VOICE_ASSET_RECEIPT_VERSION = 1;
+export const VOICE_ASSET_KINDS = Object.freeze(['whisper', 'piper']);
+export const VOICE_ASSET_STATES = Object.freeze(['verified', 'unverified', 'incomplete', 'missing']);
+
+export const voiceAssetReceiptPath = (primaryPath) => `${primaryPath}.portos-complete.json`;
+const piperSidecarPath = (onnxPath) => `${onnxPath}.json`;
+
+// Piper refuses a config without audio.sample_rate, so that is the minimum
+// evidence the sidecar is a real config rather than an error page or a stub.
+export const isValidPiperConfig = (text) => {
+ let parsed;
+ try { parsed = JSON.parse(text); } catch { return false; }
+ return Number.isFinite(parsed?.audio?.sample_rate);
+};
+
+const fileSize = (path) => {
+ try {
+ const st = statSync(path);
+ return st.isFile() ? st.size : null;
+ } catch {
+ return null;
+ }
+};
+
+const readText = (path) => {
+ try { return readFileSync(path, 'utf8'); } catch { return null; }
+};
+
+const expectedFiles = (kind, primaryPath) => (kind === 'piper'
+ ? [primaryPath, piperSidecarPath(primaryPath)]
+ : [primaryPath]);
+
+const readReceipt = (primaryPath) => {
+ const text = readText(voiceAssetReceiptPath(primaryPath));
+ if (text === null) return { present: false };
+ try {
+ const parsed = JSON.parse(text);
+ const valid = parsed?.version === VOICE_ASSET_RECEIPT_VERSION && Array.isArray(parsed.files);
+ return { present: true, receipt: valid ? parsed : null };
+ } catch {
+ return { present: true, receipt: null };
+ }
+};
+
+/**
+ * Cheap, read-only readiness check — stat + one small JSON read, no hashing, no
+ * network. Safe to call from boot and from every status poll.
+ */
+// Receipt-independent half: are the files themselves usable? Returns null when
+// they are, else the missing/incomplete verdict.
+const structuralProblem = (kind, primaryPath) => {
+ if (!VOICE_ASSET_KINDS.includes(kind)) throw new Error(`unknown voice asset kind: ${kind}`);
+ if (!primaryPath || !existsSync(primaryPath)) return { state: 'missing', reason: 'primary file absent' };
+ const files = expectedFiles(kind, primaryPath);
+ const sizes = files.map(fileSize);
+ if (!(sizes[0] > 0)) return { state: 'incomplete', reason: 'primary file empty' };
+ if (kind === 'piper') {
+ if (sizes[1] === null) return { state: 'incomplete', reason: 'sidecar config missing' };
+ if (!isValidPiperConfig(readText(files[1]) ?? '')) return { state: 'incomplete', reason: 'sidecar config invalid' };
+ }
+ return null;
+};
+
+export const inspectVoiceAsset = (kind, primaryPath) => {
+ const problem = structuralProblem(kind, primaryPath);
+ if (problem) return problem;
+ const files = expectedFiles(kind, primaryPath);
+ const sizes = files.map(fileSize);
+
+ const { present, receipt } = readReceipt(primaryPath);
+ if (!present) return { state: 'unverified', reason: 'no completion receipt' };
+ if (!receipt) return { state: 'incomplete', reason: 'completion receipt unreadable' };
+ for (let i = 0; i < files.length; i += 1) {
+ const entry = receipt.files.find((f) => f?.name === basename(files[i]));
+ if (!entry || entry.size !== sizes[i]) return { state: 'incomplete', reason: `${basename(files[i])} does not match its receipt` };
+ }
+ return { state: 'verified', reason: '' };
+};
+
+/** True when the state is usable for synthesis / transcription. */
+export const isVoiceAssetUsable = (state) => state === 'verified' || state === 'unverified';
+
+/**
+ * Whether `path` sits directly in the setup script's managed directory. Only
+ * those files carry receipts or get replaced; a model at any other path is the
+ * user's and is validated but never touched.
+ */
+export const isManagedVoiceAsset = (path, managedDir) => !!path && !!managedDir
+ && resolve(dirname(path)) === resolve(managedDir);
+
+const sha256File = (path) => new Promise((resolveHash, reject) => {
+ const hash = createHash('sha256');
+ createReadStream(path)
+ .on('error', reject)
+ .on('data', (chunk) => hash.update(chunk))
+ .on('end', () => resolveHash(hash.digest('hex')));
+});
+
+/**
+ * Full verification used by the setup scripts: everything inspectVoiceAsset
+ * checks plus the recorded sha256 of every file. Streams, so a multi-GB Whisper
+ * model never has to fit in memory.
+ */
+export const verifyVoiceAssetHashes = async (kind, primaryPath) => {
+ const base = inspectVoiceAsset(kind, primaryPath);
+ if (base.state !== 'verified') return base;
+ const { receipt } = readReceipt(primaryPath);
+ for (const file of expectedFiles(kind, primaryPath)) {
+ const entry = receipt.files.find((f) => f?.name === basename(file));
+ if (!entry || (await sha256File(file)) !== entry.sha256) {
+ return { state: 'incomplete', reason: `${basename(file)} content hash differs from its receipt` };
+ }
+ }
+ return base;
+};
+
+/**
+ * Record completion for an already-promoted asset. Refuses to write a receipt
+ * for an unusable asset, and writes through a temp file so a crash cannot leave
+ * a truncated receipt that reads as "corrupt" forever.
+ */
+export const writeVoiceAssetReceipt = async (kind, primaryPath) => {
+ // Structure only: a stale receipt from the previous install must not block
+ // recording the replacement that was just promoted over it.
+ const problem = structuralProblem(kind, primaryPath);
+ if (problem) throw new Error(`cannot record completion for ${basename(primaryPath || '')}: ${problem.reason}`);
+ const files = [];
+ for (const file of expectedFiles(kind, primaryPath)) {
+ files.push({ name: basename(file), size: fileSize(file), sha256: await sha256File(file) });
+ }
+ const receiptPath = voiceAssetReceiptPath(primaryPath);
+ const tmpPath = join(dirname(receiptPath), `.${basename(receiptPath)}.${process.pid}.tmp`);
+ try {
+ writeFileSync(tmpPath, JSON.stringify({ version: VOICE_ASSET_RECEIPT_VERSION, kind, files }, null, 2));
+ renameSync(tmpPath, receiptPath);
+ } catch (err) {
+ try { unlinkSync(tmpPath); } catch { /* temp already gone */ }
+ throw err;
+ }
+ return receiptPath;
+};
diff --git a/server/lib/voiceModelAssets.test.js b/server/lib/voiceModelAssets.test.js
new file mode 100644
index 0000000000..d48282303f
--- /dev/null
+++ b/server/lib/voiceModelAssets.test.js
@@ -0,0 +1,73 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import {
+ inspectVoiceAsset, isManagedVoiceAsset, isVoiceAssetUsable, verifyVoiceAssetHashes,
+ voiceAssetReceiptPath, writeVoiceAssetReceipt,
+} from './voiceModelAssets.js';
+
+const CONFIG = JSON.stringify({ audio: { sample_rate: 22050 } });
+
+describe('voice model asset completion contract', () => {
+ let dir;
+ let onnx;
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'voice-assets-'));
+ onnx = join(dir, 'voice.onnx');
+ });
+ afterEach(() => rmSync(dir, { recursive: true, force: true }));
+
+ it('refuses a Piper model whose sidecar is missing or not a real config', () => {
+ expect(inspectVoiceAsset('piper', onnx).state).toBe('missing');
+ writeFileSync(onnx, 'onnx-bytes');
+ expect(inspectVoiceAsset('piper', onnx)).toMatchObject({ state: 'incomplete', reason: 'sidecar config missing' });
+ writeFileSync(`${onnx}.json`, '{"audio":');
+ expect(inspectVoiceAsset('piper', onnx).state).toBe('incomplete');
+ writeFileSync(`${onnx}.json`, CONFIG);
+ expect(inspectVoiceAsset('piper', onnx).state).toBe('unverified');
+ });
+
+ it('treats an empty primary file as incomplete, never usable', () => {
+ writeFileSync(join(dir, 'ggml.bin'), '');
+ const { state } = inspectVoiceAsset('whisper', join(dir, 'ggml.bin'));
+ expect(state).toBe('incomplete');
+ expect(isVoiceAssetUsable(state)).toBe(false);
+ });
+
+ it('keeps a receipted pair verified, then rejects it once a file is truncated', async () => {
+ writeFileSync(onnx, 'onnx-bytes');
+ writeFileSync(`${onnx}.json`, CONFIG);
+ await writeVoiceAssetReceipt('piper', onnx);
+ expect(inspectVoiceAsset('piper', onnx).state).toBe('verified');
+ writeFileSync(onnx, 'onnx');
+ expect(inspectVoiceAsset('piper', onnx)).toMatchObject({ state: 'incomplete', reason: 'voice.onnx does not match its receipt' });
+ });
+
+ it('catches a same-size replacement only on the hash pass the scripts run', async () => {
+ writeFileSync(onnx, 'AAAAAAAAAA');
+ writeFileSync(`${onnx}.json`, CONFIG);
+ await writeVoiceAssetReceipt('piper', onnx);
+ writeFileSync(onnx, 'BBBBBBBBBB');
+ expect(inspectVoiceAsset('piper', onnx).state).toBe('verified');
+ expect((await verifyVoiceAssetHashes('piper', onnx)).state).toBe('incomplete');
+ });
+
+ it('re-records a receipt over a stale one left by the previous install', async () => {
+ writeFileSync(onnx, 'AAAA');
+ writeFileSync(`${onnx}.json`, CONFIG);
+ await writeVoiceAssetReceipt('piper', onnx);
+ writeFileSync(onnx, 'a longer replacement');
+ expect(inspectVoiceAsset('piper', onnx).state).toBe('incomplete');
+ await writeVoiceAssetReceipt('piper', onnx);
+ expect(inspectVoiceAsset('piper', onnx).state).toBe('verified');
+ expect(JSON.parse(readFileSync(voiceAssetReceiptPath(onnx), 'utf8')).files).toHaveLength(2);
+ });
+
+ it('only treats files directly in the managed directory as the script\'s to replace', () => {
+ mkdirSync(join(dir, 'voices'));
+ expect(isManagedVoiceAsset(join(dir, 'voices', 'a.onnx'), join(dir, 'voices'))).toBe(true);
+ expect(isManagedVoiceAsset(join(dir, 'mine', 'a.onnx'), join(dir, 'voices'))).toBe(false);
+ expect(isManagedVoiceAsset(join(dir, 'voices', 'nested', 'a.onnx'), join(dir, 'voices'))).toBe(false);
+ });
+});
diff --git a/server/services/voice/bootstrap.js b/server/services/voice/bootstrap.js
index 0741213255..fbe9055ef4 100644
--- a/server/services/voice/bootstrap.js
+++ b/server/services/voice/bootstrap.js
@@ -17,6 +17,7 @@ import { getProviderById } from '../providers.js';
import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';
import { whichFirst } from '../../lib/processEnv.js';
import { PORTS } from '../../lib/ports.js';
+import { inspectVoiceAsset, isManagedVoiceAsset, isVoiceAssetUsable } from '../../lib/voiceModelAssets.js';
export const pexec = promisify(execFile);
@@ -37,13 +38,23 @@ export const verifyBinaries = async (cfg) => {
return { whisper, piper: piperResolved ?? piperOnPath, piperRequired };
};
+// A model is ready only when it passes the completion contract
+// (lib/voiceModelAssets.js) — a file that merely exists may be a truncated
+// download. `*State` carries the verdict ('verified' | 'unverified' |
+// 'incomplete' | 'missing') so callers can tell "repair me" from "install me".
export const verifyModels = (cfg) => {
const modelPath = expandPath(cfg.stt.modelPath);
- const out = { sttModel: existsSync(modelPath) ? modelPath : null };
+ const sttAsset = inspectVoiceAsset('whisper', modelPath);
+ const out = {
+ sttModel: isVoiceAssetUsable(sttAsset.state) ? modelPath : null,
+ sttModelState: sttAsset.state,
+ };
if (cfg.tts.engine === 'piper') {
const voicePath = expandPath(cfg.tts.piper.voicePath);
- out.ttsVoice = existsSync(voicePath) ? voicePath : null;
+ const voiceAsset = inspectVoiceAsset('piper', voicePath);
+ out.ttsVoice = isVoiceAssetUsable(voiceAsset.state) ? voicePath : null;
+ out.ttsVoiceState = voiceAsset.state;
} else {
// Qwen3 runtime owns its model readiness.
out.ttsVoice = null;
@@ -102,7 +113,11 @@ export const runSetupScript = async (cfg) => {
export const downloadPiperVoice = async (voiceId, currentCfg) => {
if (!voiceId || typeof voiceId !== 'string') throw new Error('voiceId required');
const voicePath = piperVoiceTildePath(voiceId);
- if (existsSync(expandPath(voicePath))) return { skipped: true, voicePath };
+ const absVoicePath = expandPath(voicePath);
+ // Only a receipted pair is done. A bare .onnx may be a truncated download
+ // (or lack its .onnx.json), and an unreceipted pair gets its receipt from the
+ // script — so both go through setup instead of being skipped.
+ if (inspectVoiceAsset('piper', absVoicePath).state === 'verified') return { skipped: true, voicePath };
// Re-use the existing setup script but force it into Piper-only mode. The
// script already short-circuits whisper steps when the model/binary are
// present, so this is cheap on repeat invocations.
@@ -110,6 +125,10 @@ export const downloadPiperVoice = async (voiceId, currentCfg) => {
...currentCfg,
tts: { engine: 'piper', piper: { voicePath } },
});
+ const after = inspectVoiceAsset('piper', absVoicePath);
+ if (after.state !== 'verified') {
+ throw new Error(`Piper voice ${voiceId} is still not usable after setup (${after.reason || after.state})`);
+ }
return { downloaded: true, voicePath };
};
@@ -163,7 +182,11 @@ export const startWhisper = async (cfg) => {
const whisperBin = await which('whisper-server');
if (!whisperBin) throw new Error('whisper-server not on PATH — run scripts/setup-voice.sh');
const modelPath = expandPath(cfg.stt.modelPath);
- if (!existsSync(modelPath)) throw new Error(`whisper model missing: ${modelPath}`);
+ const modelAsset = inspectVoiceAsset('whisper', modelPath);
+ if (modelAsset.state === 'missing') throw new Error(`whisper model missing: ${modelPath}`);
+ if (!isVoiceAssetUsable(modelAsset.state)) {
+ throw new Error(`whisper model incomplete: ${modelPath} (${modelAsset.reason}) — run Save & Reconcile in Settings → Voice to repair it`);
+ }
const url = new URL(cfg.stt.endpoint);
const host = url.hostname;
@@ -408,18 +431,55 @@ export const reconcile = async (cfg, { allowSetup = true } = {}) => {
const models = verifyModels(cfg);
const piperMissing = bins.piperRequired && (!bins.piper || !models.ttsVoice);
const webSpeech = cfg.stt?.engine === 'web-speech';
+ const coremlMissing = cfg.stt.coreml && !models.coreml;
+
+ // Boot is read-only: an asset that is present but incomplete is repaired by
+ // the user's next Save & Reconcile / voice download, never by a restart
+ // kicking off a surprise multi-hundred-MB transfer. Missing assets keep their
+ // existing first-install behavior.
+ if (!allowSetup) {
+ const repair = [];
+ if (bins.piperRequired && models.ttsVoiceState === 'incomplete') repair.push('piper');
+ if (!webSpeech && models.sttModelState === 'incomplete') repair.push('whisper');
+ if (repair.length) {
+ console.warn(`🎙️ voice: incomplete model download (${repair.join(', ')}) — run Save & Reconcile in Settings → Voice to repair`);
+ const setupRequired = repair.join(',');
+ if (webSpeech) {
+ await stopWhisper().catch(() => null);
+ } else if (!repair.includes('whisper') && bins.whisper && models.sttModel && !coremlMissing) {
+ return { ...await startWhisper(cfg), setupRequired };
+ }
+ return { setupRequired };
+ }
+ }
+
+ // Models that predate completion receipts are usable as-is, but only the
+ // setup script can establish their receipt (it may need a remote size check).
+ // Do that on a user-authorized pass, for files the script manages — a model
+ // at a user-chosen path is validated, never touched.
+ const sttNeedsReceipt = !webSpeech && models.sttModelState === 'unverified'
+ && isManagedVoiceAsset(expandPath(cfg.stt.modelPath), join(voiceHome(), 'models'));
+ const ttsNeedsReceipt = bins.piperRequired && models.ttsVoiceState === 'unverified'
+ && isManagedVoiceAsset(expandPath(cfg.tts.piper.voicePath), join(voiceHome(), 'voices'));
+ const adoptReceipts = async () => {
+ if (!allowSetup || !(sttNeedsReceipt || ttsNeedsReceipt)) return;
+ await runSetupScript(cfg).catch((err) => {
+ console.warn(`🎙️ voice: could not record model completion receipts: ${err.message}`);
+ });
+ };
// Web Speech STT runs entirely in the browser — stop any leftover whisper
// instance and skip STT provisioning. Piper voice provisioning still runs.
if (webSpeech) {
if (piperMissing) await runSetupScript(cfg);
+ else await adoptReceipts();
await stopWhisper().catch(() => null);
return { skipped: 'web-speech', piperProvisioned: piperMissing };
}
- const coremlMissing = cfg.stt.coreml && !models.coreml;
const sttMissing = !bins.whisper || !models.sttModel || coremlMissing;
if (piperMissing || sttMissing) await runSetupScript(cfg);
+ else await adoptReceipts();
return startWhisper(cfg);
};
diff --git a/server/services/voice/bootstrap.modelAssets.test.js b/server/services/voice/bootstrap.modelAssets.test.js
new file mode 100644
index 0000000000..007f707ecf
--- /dev/null
+++ b/server/services/voice/bootstrap.modelAssets.test.js
@@ -0,0 +1,88 @@
+// Regression for #9808: a Piper voice that merely EXISTS must not short-circuit
+// repair. Runs against a real temp HOME (no fs mock) so the completion contract
+// in lib/voiceModelAssets.js is exercised end to end through bootstrap.js.
+
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const home = vi.hoisted(() => ({ dir: '' }));
+vi.mock('os', async (importOriginal) => {
+ const actual = await importOriginal();
+ const fs = await import('fs');
+ home.dir = fs.mkdtempSync(actual.tmpdir() + '/voice-bootstrap-');
+ return { ...actual, default: { ...actual, homedir: () => home.dir }, homedir: () => home.dir };
+});
+vi.mock('../pm2.js', () => ({ execPm2: vi.fn(async () => ({})), getAppStatus: vi.fn(async () => null) }));
+vi.mock('../../lib/processEnv.js', () => ({ whichFirst: vi.fn(async () => null) }));
+vi.mock('../../lib/childProcess.js', () => ({ execFile: vi.fn() }));
+vi.mock('../providers.js', () => ({ getProviderById: vi.fn() }));
+vi.mock('../settings.js', () => ({ getSettings: vi.fn(), updateSettings: vi.fn() }));
+vi.mock('./llm.js', () => ({ isToolCapable: vi.fn(), isReasoningModel: vi.fn() }));
+
+const { execFile } = await import('../../lib/childProcess.js');
+const { VOICE_DEFAULTS, expandPath, piperVoiceTildePath } = await import('./config.js');
+const { writeVoiceAssetReceipt, inspectVoiceAsset } = await import('../../lib/voiceModelAssets.js');
+const { verifyModels, downloadPiperVoice, reconcile } = await import('./bootstrap.js');
+
+const VOICE_ID = 'en_US-test-low';
+const CONFIG = JSON.stringify({ audio: { sample_rate: 22050 } });
+const onnxPath = () => expandPath(piperVoiceTildePath(VOICE_ID));
+const cfg = (overrides = {}) => ({
+ ...VOICE_DEFAULTS, enabled: true,
+ stt: { ...VOICE_DEFAULTS.stt, engine: 'web-speech' },
+ tts: { engine: 'piper', piper: { voicePath: piperVoiceTildePath(VOICE_ID) } },
+ ...overrides,
+});
+
+// A setup script double that completes the pair the way the real one does.
+const setupScriptCompletes = () => execFile.mockImplementation((_cmd, _args, _opts, done) => {
+ writeFileSync(onnxPath(), 'onnx-bytes');
+ writeFileSync(`${onnxPath()}.json`, CONFIG);
+ writeVoiceAssetReceipt('piper', onnxPath()).then(() => done(null, { stdout: '', stderr: '' }), done);
+});
+
+describe('Piper voice with an ONNX but no sidecar (#9808)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ rmSync(join(home.dir, '.portos'), { recursive: true, force: true });
+ mkdirSync(join(home.dir, '.portos/voice/voices'), { recursive: true });
+ writeFileSync(onnxPath(), 'partial');
+ });
+ afterAll(() => rmSync(home.dir, { recursive: true, force: true }));
+
+ it('is not reported as a ready voice', () => {
+ const models = verifyModels(cfg());
+ expect(models.ttsVoice).toBeNull();
+ expect(models.ttsVoiceState).toBe('incomplete');
+ });
+
+ it('is repaired by the voice download action instead of being skipped', async () => {
+ setupScriptCompletes();
+ await expect(downloadPiperVoice(VOICE_ID, cfg())).resolves.toMatchObject({ downloaded: true });
+ expect(execFile).toHaveBeenCalledTimes(1);
+ expect(inspectVoiceAsset('piper', onnxPath()).state).toBe('verified');
+ // …and once verified, the next request really is a no-op.
+ await expect(downloadPiperVoice(VOICE_ID, cfg())).resolves.toMatchObject({ skipped: true });
+ expect(execFile).toHaveBeenCalledTimes(1);
+ });
+
+ it('never reports a download that left the voice unusable', async () => {
+ execFile.mockImplementation((_cmd, _args, _opts, done) => done(null, { stdout: '', stderr: '' }));
+ await expect(downloadPiperVoice(VOICE_ID, cfg())).rejects.toThrow(/still not usable/);
+ });
+
+ it('is repaired by Save & Reconcile (default allowSetup) via the setup script', async () => {
+ setupScriptCompletes();
+ await reconcile(cfg());
+ expect(execFile).toHaveBeenCalledTimes(1);
+ expect(inspectVoiceAsset('piper', onnxPath()).state).toBe('verified');
+ });
+
+ it('is left alone at boot: readiness is read-only and starts no download', async () => {
+ mkdirSync(join(home.dir, '.portos/voice/piper'), { recursive: true });
+ await expect(reconcile(cfg(), { allowSetup: false })).resolves.toMatchObject({ setupRequired: 'piper' });
+ expect(execFile).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/voice/bootstrap.retirement.test.js b/server/services/voice/bootstrap.retirement.test.js
index 0ee32d0008..c2858f5635 100644
--- a/server/services/voice/bootstrap.retirement.test.js
+++ b/server/services/voice/bootstrap.retirement.test.js
@@ -1,6 +1,15 @@
import { expect, it, vi } from 'vitest';
vi.mock('fs', () => ({ existsSync: vi.fn(() => false) }));
+// These boot-flow tests model "the file is there" through the fs mock; asset
+// completion has its own coverage in voiceModelAssets.test.js.
+vi.mock('../../lib/voiceModelAssets.js', async (importOriginal) => {
+ const { existsSync: exists } = await import('fs');
+ return {
+ ...(await importOriginal()),
+ inspectVoiceAsset: (_kind, path) => (exists(path) ? { state: 'verified', reason: '' } : { state: 'missing', reason: '' }),
+ };
+});
vi.mock('../../lib/processEnv.js', () => ({ whichFirst: vi.fn(async () => null) }));
vi.mock('../pm2.js', () => ({ execPm2: vi.fn(async () => ({})), getAppStatus: vi.fn(async () => null) }));
vi.mock('../../lib/fetchWithTimeout.js', () => ({ fetchWithTimeout: vi.fn(async () => ({})) }));
diff --git a/server/services/voice/health.js b/server/services/voice/health.js
index de79170d4d..65505909d8 100644
--- a/server/services/voice/health.js
+++ b/server/services/voice/health.js
@@ -8,6 +8,7 @@ import { which } from './bootstrap.js';
import { resolveLlmEndpoint, authHeaders } from './llm.js';
import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';
import { checkSetup as checkFaceTimeSetup } from './facetimeBridge.js';
+import { inspectVoiceAsset, isVoiceAssetUsable } from '../../lib/voiceModelAssets.js';
const PROBE_TIMEOUT_MS = 1500;
const CACHE_TTL_MS = 3000;
@@ -58,10 +59,12 @@ export const checkAll = async (cfg) => {
// CLI-mode piper has no server to probe — check binary + selected voice.
const localPiper = join(voiceHome(), 'piper', PIPER_BIN_NAME);
const [hasBin, voicePath] = [existsSync(localPiper) || !!(await which('piper')), expandPath(voice.tts.piper?.voicePath || '')];
- const hasVoice = voicePath && existsSync(voicePath);
- out.piper = hasBin && hasVoice
+ // A voice file that exists may still be a truncated download or lack its
+ // .onnx.json sidecar — both fail at synthesis time, so neither is "ready".
+ const voiceAsset = voicePath ? inspectVoiceAsset('piper', voicePath) : { state: 'missing' };
+ out.piper = hasBin && isVoiceAssetUsable(voiceAsset.state)
? { ok: true, state: 'ready' }
- : { ok: false, state: !hasBin ? 'no binary' : 'voice missing' };
+ : { ok: false, state: !hasBin ? 'no binary' : (voiceAsset.state === 'incomplete' ? 'voice incomplete' : 'voice missing') };
}
if (sttEngine === 'web-speech') {
diff --git a/server/services/voice/health.test.js b/server/services/voice/health.test.js
index efbc536603..b7f6e42022 100644
--- a/server/services/voice/health.test.js
+++ b/server/services/voice/health.test.js
@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({
authHeaders: vi.fn(() => ({})),
fetchWithTimeout: vi.fn(async () => ({ ok: true, status: 200 })),
checkSetup: vi.fn(async () => ({})),
+ inspectVoiceAsset: vi.fn(() => ({ state: 'verified', reason: '' })),
}));
vi.mock('fs', () => ({ existsSync: mocks.existsSync }));
@@ -25,6 +26,10 @@ vi.mock('./bootstrap.js', () => ({ which: mocks.which }));
vi.mock('./llm.js', () => ({ resolveLlmEndpoint: mocks.resolveLlmEndpoint, authHeaders: mocks.authHeaders }));
vi.mock('../../lib/fetchWithTimeout.js', () => ({ fetchWithTimeout: mocks.fetchWithTimeout }));
vi.mock('./facetimeBridge.js', () => ({ checkSetup: mocks.checkSetup }));
+vi.mock('../../lib/voiceModelAssets.js', () => ({
+ inspectVoiceAsset: mocks.inspectVoiceAsset,
+ isVoiceAssetUsable: (state) => state === 'verified' || state === 'unverified',
+}));
const { checkAll, invalidateHealthCache } = await import('./health.js');
@@ -33,6 +38,20 @@ describe('voice health Piper probe', () => {
invalidateHealthCache();
vi.clearAllMocks();
mocks.existsSync.mockReturnValue(true);
+ mocks.inspectVoiceAsset.mockReturnValue({ state: 'verified', reason: '' });
+ });
+
+ const piperCfg = () => ({
+ stt: { engine: 'web-speech', endpoint: '' },
+ llm: { provider: 'lmstudio' },
+ tts: { engine: 'piper', piper: { voicePath: '/voice/en.onnx' } },
+ });
+
+ it('does not report Piper ready for a voice whose download is incomplete', async () => {
+ mocks.inspectVoiceAsset.mockReturnValue({ state: 'incomplete', reason: 'sidecar config missing' });
+ const result = await checkAll(piperCfg());
+ expect(mocks.inspectVoiceAsset).toHaveBeenCalledWith('piper', '/voice/en.onnx');
+ expect(result.piper).toEqual({ ok: false, state: 'voice incomplete' });
});
it('uses the platform-specific Piper binary name for local detection', async () => {