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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: download and verify real Qwen voice model snapshots (#8857)
[._.]/ Adam Eivy2d67cb38f054
diff --git a/docs/features/voice.md b/docs/features/voice.mdindex a2868dd775..26634059e4 100644--- a/docs/features/voice.md+++ b/docs/features/voice.md@@ -16,11 +16,17 @@ PortOS includes an optional voice assistant with support for fully local operatiThe TTS engine is selectable in **Settings → Voice → TTS engine**.**Qwen3-TTS status:** the bundled adapter currently refuses synthesis, design,-cloning, training, and model acquisition with an explicit unavailable error.+cloning, and training with an explicit unavailable error. Explicit model+downloads in Settings fetch the official Qwen snapshot at an immutable Hub+revision and verify the size and digest of every required file, including the+speech tokenizer weights, before publishing readiness. Downloads require+`huggingface_hub` in the isolated Qwen Python environment. A missing dependency+or failed verification returns an error; it never marks the model downloaded.Earlier versions produced test tones, placeholder checkpoints and downloadmetadata; those artifacts are not evidence of model readiness. Runtime probes-therefore report unavailable and do not treat existing model folders as verified-installations. Use Piper for working local speech until #8857 delivers a real+still report inference unavailable. Model download readiness is separate: it+requires a verified snapshot marker and all required files at their verified+sizes; old metadata-only model folders remain unavailable. Use Piper for working local speech until #8857 delivers a realadapter and an intelligibility smoke run. No model download runs automatically.Interactive profile benchmarks measure elapsed time until the buffered WAV isdiff --git a/scripts/qwen3_tts_runner.py b/scripts/qwen3_tts_runner.pyindex 092eda82ea..43bd30b906 100755--- a/scripts/qwen3_tts_runner.py+++ b/scripts/qwen3_tts_runner.py@@ -12,11 +12,109 @@ Provides CLI entry points for:from __future__ import annotationsimport argparse+import hashlib+import os+import reimport jsonimport sysfrom pathlib import Path+SUPPORTED_MODELS = (+ "Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign",+ "Qwen/Qwen3-TTS-12Hz-1.7B-Base",+ "Qwen/Qwen3-TTS-12Hz-0.6B-Base",+)+# Both the language model and speech codec are required. A directory, old+# metadata.json, or a lone language-model weight is not an installed snapshot.+REQUIRED_FILES = (+ "config.json", "generation_config.json", "merges.txt", "model.safetensors",+ "preprocessor_config.json", "tokenizer_config.json", "vocab.json",+ "speech_tokenizer/config.json", "speech_tokenizer/configuration.json",+ "speech_tokenizer/model.safetensors", "speech_tokenizer/preprocessor_config.json",+)+++def installed_snapshot(model_dir: Path, model_id: str) -> Path | None:+ """Read only a completely verified revision; never perform network access."""+ try:+ manifest = json.loads((model_dir / "verified.json").read_text())+ revision = manifest["revision"]+ if manifest["model_id"] != model_id or not re.fullmatch(r"[0-9a-f]{40}", revision):+ return None+ snapshot = model_dir / revision+ sizes = manifest["files"]+ for filename in REQUIRED_FILES:+ expected = sizes[filename]+ if not isinstance(expected, int) or expected <= 0:+ return None+ if (snapshot / filename).stat().st_size != expected:+ return None+ return snapshot+ except (OSError, ValueError, KeyError, TypeError):+ return None+++def download_model(model_id: str, models_dir: Path) -> dict:+ """Fetch an immutable Hub revision and verify every required file's digest.++ Hub blob IDs are Git SHA-1 for ordinary files and SHA-256 for LFS weights.+ Only publish the readiness marker after verification, leaving a prior+ installed revision usable if an update fails or the process is interrupted.+ """+ if model_id not in SUPPORTED_MODELS:+ raise ValueError("Unsupported Qwen3-TTS model")+ from huggingface_hub import HfApi, hf_hub_download++ info = HfApi().model_info(model_id, files_metadata=True)+ revision = info.sha+ if not isinstance(revision, str) or not re.fullmatch(r"[0-9a-f]{40}", revision):+ raise ValueError("Model repository did not return an immutable revision")+ files = {entry.rfilename: entry for entry in info.siblings}+ if not all(filename in files for filename in REQUIRED_FILES):+ raise ValueError("Model repository is missing required Qwen3-TTS files")+ model_dir = models_dir / model_id.replace("/", "--")+ snapshot = model_dir / revision+ sizes = {}+ for filename in REQUIRED_FILES:+ entry = files[filename]+ if not isinstance(entry.size, int) or entry.size <= 0:+ raise ValueError(f"Missing file size: {filename}")+ lfs = entry.lfs+ digest = lfs.sha256 if lfs else entry.blob_id+ algorithm = "sha256" if lfs else "sha1"+ if not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}" if lfs else r"[0-9a-f]{40}", digest):+ raise ValueError(f"Missing file digest: {filename}")+ # The explicit download operation is the only path allowed to fetch.+ hf_hub_download(repo_id=model_id, filename=filename, revision=revision, local_dir=snapshot)+ target = snapshot / filename+ if target.stat().st_size != entry.size:+ raise ValueError(f"Incomplete model file: {filename}")+ checksum = hashlib.new(algorithm)+ if not lfs:+ checksum.update(f"blob {entry.size}\0".encode())+ with target.open("rb") as source:+ for chunk in iter(lambda: source.read(1024 * 1024), b""):+ checksum.update(chunk)+ if checksum.hexdigest() != digest:+ raise ValueError(f"Model file checksum mismatch: {filename}")+ sizes[filename] = entry.size++ marker = model_dir / "verified.json"+ # Unique temporary markers also make separate explicit CLI downloads safe.+ import tempfile+ descriptor, temporary = tempfile.mkstemp(prefix=".verified-", dir=model_dir)+ try:+ with os.fdopen(descriptor, "w") as output:+ json.dump({"model_id": model_id, "revision": revision, "files": sizes}, output)+ output.flush()+ os.fsync(output.fileno())+ os.replace(temporary, marker)+ finally:+ Path(temporary).unlink(missing_ok=True)+ return {"ok": True, "modelId": model_id, "revision": revision, "path": str(snapshot)}++def probe_runtime(models_dir: Path | None = None) -> dict:"""Probe hardware, PyTorch, Transformers, and cached model weights."""result = {@@ -55,26 +153,13 @@ def probe_runtime(models_dir: Path | None = None) -> dict:except ImportError:pass- supported_models = [- "Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign",- "Qwen/Qwen3-TTS-12Hz-1.7B-Base",- "Qwen/Qwen3-TTS-12Hz-0.6B-Base",- ]-- if models_dir and models_dir.exists():- for model_id in supported_models:- safe_name = model_id.replace("/", "--")- model_path = models_dir / safe_name- result["models"][model_id] = {- "downloaded": False,- "path": str(model_path) if model_path.exists() else None,- }- else:- for model_id in supported_models:- result["models"][model_id] = {- "downloaded": False,- "path": None,- }+ for model_id in SUPPORTED_MODELS:+ model_path = models_dir / model_id.replace("/", "--") if models_dir else None+ snapshot = installed_snapshot(model_path, model_id) if model_path else None+ result["models"][model_id] = {+ "downloaded": snapshot is not None,+ "path": str(snapshot) if snapshot else None,+ }return result@@ -99,6 +184,7 @@ def run_fine_tuning(args: argparse.Namespace) -> int:def main() -> int:parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--download", action="store_true", help="Explicitly download and verify a model snapshot")parser.add_argument("--probe", action="store_true", help="Probe runtime and available models")parser.add_argument("--models-dir", type=str, help="Directory containing downloaded model weights")parser.add_argument("--mode", choices=["design", "clone", "synthesize", "fine-tune"], default="synthesize")@@ -119,6 +205,16 @@ def main() -> int:args = parser.parse_args()+ if args.download:+ if not args.model_id or not args.models_dir:+ parser.error("--download requires --model-id and --models-dir")+ try:+ print(json.dumps(download_model(args.model_id, Path(args.models_dir))))+ return 0+ except Exception as error:+ print(json.dumps({"ok": False, "code": "QWEN3_DOWNLOAD_FAILED", "error": str(error)}), file=sys.stderr)+ return 1+if args.probe:models_dir = Path(args.models_dir) if args.models_dir else Noneprint(json.dumps(probe_runtime(models_dir)))diff --git a/scripts/qwen3_tts_runner.test.js b/scripts/qwen3_tts_runner.test.jsnew file mode 100644index 0000000000..687237ccad--- /dev/null+++ b/scripts/qwen3_tts_runner.test.js@@ -0,0 +1,100 @@+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { describe, expect, it } from 'vitest';+import { resolveTestPython } from '../server/lib/testHelper.js';++const python = resolveTestPython();+const script = fileURLToPath(new URL('./qwen3_tts_runner.py', import.meta.url));++// Exercise the production download/probe boundary with a tool-free fake Hub;+// no model, provider, hardware, credentials, or real user directories are used.+const fixture = String.raw`+import hashlib, importlib.util, json, sys, tempfile, types+from pathlib import Path+spec = importlib.util.spec_from_file_location("qwen_runner", sys.argv[1])+runner = importlib.util.module_from_spec(spec)+spec.loader.exec_module(runner)+model_id = runner.SUPPORTED_MODELS[0]+revision = "a" * 40+payloads = {name: ("fixture:" + name).encode() for name in runner.REQUIRED_FILES}+entries = []+for name, data in payloads.items():+ is_weight = name.endswith(".safetensors")+ entries.append(types.SimpleNamespace(+ rfilename=name, size=len(data),+ lfs=types.SimpleNamespace(sha256=hashlib.sha256(data).hexdigest()) if is_weight else None,+ blob_id=hashlib.sha1(f"blob {len(data)}\0".encode() + data).hexdigest(),+ ))+info = types.SimpleNamespace(sha=revision, siblings=entries)+calls = []+corrupt = None+hub = types.ModuleType("huggingface_hub")+hub.HfApi = lambda: types.SimpleNamespace(model_info=lambda *args, **kwargs: info)+def download(**kwargs):+ calls.append(kwargs)+ assert kwargs["revision"] == revision+ path = kwargs["local_dir"] / kwargs["filename"]+ path.parent.mkdir(parents=True, exist_ok=True)+ data = payloads[kwargs["filename"]]+ path.write_bytes(b"x" * len(data) if kwargs["filename"] == corrupt else data)+ return str(path)+hub.hf_hub_download = download+sys.modules["huggingface_hub"] = hub+`;+const run = (source) => JSON.parse(execFileSync(python, ['-c', fixture + source, script], { encoding: 'utf8' }));++describe.skipIf(!python)('Qwen3 explicit model acquisition', () => {+ it('publishes only complete immutable snapshots and detects missing/truncated required weights', () => {+ const result = run(String.raw`+with tempfile.TemporaryDirectory() as temp:+ root = Path(temp)+ model_dir = root / model_id.replace("/", "--")+ model_dir.mkdir()+ (model_dir / "metadata.json").write_text("{}")+ assert runner.installed_snapshot(model_dir, model_id) is None+ result = runner.download_model(model_id, root)+ snapshot = runner.installed_snapshot(model_dir, model_id)+ assert snapshot == Path(result["path"])+ assert len(calls) == len(runner.REQUIRED_FILES)+ # A metadata-only directory or incomplete codec must never report installed.+ codec = snapshot / "speech_tokenizer/model.safetensors"+ codec.write_bytes(b"truncated")+ assert runner.installed_snapshot(model_dir, model_id) is None+ codec.unlink()+ assert runner.installed_snapshot(model_dir, model_id) is None+ print(json.dumps({"ok": result["ok"], "revision": result["revision"]}))+`);+ expect(result).toEqual({ ok: true, revision: 'a'.repeat(40) });+ });++ it('rejects corrupt content and incomplete upstream repositories without publishing readiness', () => {+ const result = run(String.raw`+with tempfile.TemporaryDirectory() as temp:+ root = Path(temp)+ model_dir = root / model_id.replace("/", "--")+ failures = []+ for name in ("config.json", "model.safetensors"):+ corrupt = name+ try:+ runner.download_model(model_id, root)+ raise AssertionError("accepted corrupt file")+ except ValueError as error:+ failures.append(str(error))+ assert not (model_dir / "verified.json").exists()+ corrupt = None+ info.siblings = entries[:-1]+ try:+ runner.download_model(model_id, root)+ raise AssertionError("accepted missing codec configuration")+ except ValueError as error:+ failures.append(str(error))+ assert runner.installed_snapshot(model_dir, model_id) is None+ print(json.dumps(failures))+`);+ expect(result).toEqual([+ 'Model file checksum mismatch: config.json',+ 'Model file checksum mismatch: model.safetensors',+ 'Model repository is missing required Qwen3-TTS files',+ ]);+ });+});diff --git a/server/services/voice/qwen3TtsRuntime.js b/server/services/voice/qwen3TtsRuntime.jsindex 04db2466d7..7e397ad1b1 100644--- a/server/services/voice/qwen3TtsRuntime.js+++ b/server/services/voice/qwen3TtsRuntime.js@@ -92,7 +92,7 @@ export async function getQwen3RuntimeStatus() {try {const probeArgs = [QWEN3_TTS_RUNNER_SCRIPT, '--probe', '--models-dir', QWEN3_TTS_MODELS_DIR];- const { stdout } = await spawnProbe(python, probeArgs);+ const { stdout } = await runRuntime(python, probeArgs);const data = JSON.parse(stdout.trim());const modelsState = {};@@ -135,23 +135,26 @@ export async function getQwen3RuntimeStatus() {}}-function spawnProbe(pythonPath, args) {+function runRuntime(pythonPath, args, timeout = 10000) {return new Promise((resolve, reject) => {- const child = spawn(pythonPath, args, safeChildProcessOptions({ timeout: 10000 }));+ const child = spawn(pythonPath, args, safeChildProcessOptions({ timeout }));let stdout = '';let stderr = '';- child.stdout.on('data', (d) => { stdout += d.toString(); });- child.stderr.on('data', (d) => { stderr += d.toString(); });+ child.stdout.on('data', (d) => { stdout = (stdout + d.toString()).slice(-65536); });+ child.stderr.on('data', (d) => { stderr = (stderr + d.toString()).slice(-8192); });child.on('close', (code) => {if (code === 0) resolve({ stdout, stderr });- else reject(new Error(`Probe failed (code ${code}): ${stderr || stdout}`));+ else reject(new Error(`Qwen3 runtime failed (code ${code}): ${stderr || stdout}`));});child.on('error', reject);});}+const downloads = new Map();+/**- * Explicit user-triggered model download.+ * Explicit user-triggered model download. Coalesce overlapping requests for one+ * model; readiness is published by the runner only after checksum verification.*/export async function downloadQwen3Model(modelId) {const modelSpec = SUPPORTED_QWEN3_MODELS.find((m) => m.id === modelId);@@ -162,8 +165,30 @@ export async function downloadQwen3Model(modelId) {});}- throw new ServerError('Qwen3-TTS model acquisition is unavailable: no verified download adapter is implemented', {- status: 503,- code: 'QWEN3_DOWNLOAD_UNAVAILABLE',- });+ if (downloads.has(modelId)) return downloads.get(modelId);+ const download = (async () => {+ const python = await resolveQwen3Python();+ if (!python) {+ throw new ServerError('Python with huggingface_hub is required to download Qwen3-TTS models', {+ status: 503, code: 'QWEN3_DOWNLOAD_UNAVAILABLE',+ });+ }+ const { stdout } = await runRuntime(python, [+ QWEN3_TTS_RUNNER_SCRIPT, '--download', '--model-id', modelId,+ '--models-dir', QWEN3_TTS_MODELS_DIR,+ ], 30 * 60 * 1000);+ const result = JSON.parse(stdout.trim());+ if (result.ok !== true || result.modelId !== modelId || !/^[a-f0-9]{40}$/.test(result.revision)) {+ throw new ServerError('Qwen3-TTS download did not return a verified snapshot', {+ status: 502, code: 'QWEN3_DOWNLOAD_INVALID_RESULT',+ });+ }+ return result;+ })();+ downloads.set(modelId, download);+ try {+ return await download;+ } finally {+ downloads.delete(modelId);+ }}diff --git a/server/services/voice/qwen3TtsRuntime.test.js b/server/services/voice/qwen3TtsRuntime.test.jsindex 6836bed5fa..dc12817321 100644--- a/server/services/voice/qwen3TtsRuntime.test.js+++ b/server/services/voice/qwen3TtsRuntime.test.js@@ -1,4 +1,10 @@-import { describe, it, expect } from 'vitest';+import { EventEmitter } from 'node:events';+import { describe, it, expect, vi, beforeEach } from 'vitest';+vi.mock('../../lib/childProcess.js', () => ({ spawn: vi.fn() }));+vi.mock('../../lib/processEnv.js', () => ({+ whichFirst: vi.fn().mockResolvedValue('python3'), safeChildProcessOptions: (options) => options,+}));+import { spawn } from '../../lib/childProcess.js';import {SUPPORTED_QWEN3_MODELS,downloadQwen3Model,@@ -17,20 +23,44 @@ describe('qwen3TtsRuntime', () => {expect(interactiveModel).toBeDefined();});- it('probes runtime health without throwing when python is available', async () => {+ beforeEach(() => vi.clearAllMocks());++ function runnerResponse(data, code = 0) {+ spawn.mockImplementation(() => {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ queueMicrotask(() => {+ child.stdout.emit('data', JSON.stringify(data));+ child.emit('close', code);+ });+ return child;+ });+ }++ it('keeps inference unavailable even when a real snapshot is downloaded', async () => {+ const modelId = SUPPORTED_QWEN3_MODELS[0].id;+ runnerResponse({ ok: false, error: 'No inference adapter', models: { [modelId]: { downloaded: true } } });const status = await getQwen3RuntimeStatus();- expect(status.ok).toBe(false);- expect(status.installed).toBe(false);- expect(status).toHaveProperty('installed');- expect(status).toHaveProperty('supportedModels');+ expect(status).toMatchObject({ ok: false, installed: false });+ expect(status.models[modelId].downloaded).toBe(true);+ expect(spawn.mock.calls[0][1]).toContain('--probe');+ expect(spawn.mock.calls[0][1]).not.toContain('--download');});- it('downloads model explicitly on user request and rejects unknown models', async () => {- await expect(downloadQwen3Model('unknown/invalid-model')).rejects.toThrow(/unsupported qwen3/i);+ it('downloads explicitly, coalesces duplicate requests, and requires verified results', async () => {+ const modelId = SUPPORTED_QWEN3_MODELS[0].id;+ const result = { ok: true, modelId, revision: 'a'.repeat(40) };+ runnerResponse(result);+ expect(await Promise.all([downloadQwen3Model(modelId), downloadQwen3Model(modelId)])).toEqual([result, result]);+ expect(spawn).toHaveBeenCalledTimes(1);+ expect(spawn.mock.calls[0][1]).toContain('--download');+ expect(spawn.mock.calls[0][2].timeout).toBe(30 * 60 * 1000);- await expect(downloadQwen3Model('Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign')).rejects.toMatchObject({- status: 503,- code: 'QWEN3_DOWNLOAD_UNAVAILABLE',- });+ runnerResponse({ ok: true, modelId });+ await expect(downloadQwen3Model(modelId)).rejects.toMatchObject({ code: 'QWEN3_DOWNLOAD_INVALID_RESULT' });+ runnerResponse({ error: 'checksum mismatch' }, 1);+ await expect(downloadQwen3Model(modelId)).rejects.toThrow(/checksum mismatch/);+ await expect(downloadQwen3Model('unknown/invalid-model')).rejects.toMatchObject({ code: 'UNKNOWN_QWEN3_MODEL' });});});