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: run verified local Qwen voice design and cloning (#8857)

[._.]/ Adam Eivy7459d9d474dc
diff --git a/docs/features/voice.md b/docs/features/voice.md
index 209205f25e..d03a565393 100644
--- a/docs/features/voice.md
+++ b/docs/features/voice.md
@@ -10,13 +10,18 @@ PortOS includes an optional voice assistant with support for fully local operati
|-------|----------------|--------------|--------|
| Speech-to-text | Browser [Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API) (default — **note**: Chromium browsers forward audio to a vendor cloud speech service) or [whisper.cpp](https://github.com/ggerganov/whisper.cpp) via `whisper-server` (HTTP :5562, fully local) | — | ✅ (whisper) / ⚠️ (web-speech) |
| LLM | LM Studio (`/v1/chat/completions`) | OpenAI-compatible local server | ✅ |
-| Text-to-speech | [Piper](https://github.com/rhasspy/piper) (CLI) | Qwen3-TTS (currently unavailable) | ✅ |
+| Text-to-speech | [Piper](https://github.com/rhasspy/piper) (CLI) | Qwen3-TTS (CPU/CUDA; MLX pending) | ✅ |
| Voice activity | AudioWorklet + RMS VAD (hands-free) or `MediaRecorder` (push-to-talk) — Web Speech mode bypasses server audio and posts final text via `voice:text` | — | ✅ |
The TTS engine is selectable in **Settings → Voice → TTS engine**.
-**Qwen3-TTS status:** the bundled adapter currently refuses synthesis, design,
-cloning, and training with an explicit unavailable error. Explicit model
+**Qwen3-TTS status:** the bundled runner calls the official
+[qwen-tts inference API](https://github.com/QwenLM/Qwen3-TTS#python-package-usage)
+for voice design and reference cloning on CPU/CUDA. Install `qwen-tts` in the
+isolated Qwen Python environment; the package supplies Torch, NumPy and
+SoundFile. Apple Silicon MLX, training and custom checkpoints are still
+unavailable. Speech-rate changes and instruction-controlled Base cloning are
+refused rather than reported as applied controls. 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
@@ -24,12 +29,37 @@ speech tokenizer weights, before publishing readiness. Downloads require
or failed verification returns an error; it never marks the model downloaded.
Earlier versions produced test tones, placeholder checkpoints and download
metadata; those artifacts are not evidence of model readiness. Runtime probes
-still report inference unavailable. Model download readiness is separate: it
+report dependency/hardware availability without loading weights. Model download readiness is separate: it
requires a verified snapshot marker and all required files. Unchanged verified
files use their size, change timestamps, and filesystem identity; changed files
are rehashed before they can report ready. Windows probes rehash all files because
-Python does not expose a reliable change timestamp there; old metadata-only model folders remain unavailable. Use Piper for working local speech until #8857 delivers a real
-adapter and an intelligibility smoke run. No model download runs automatically.
+Python does not expose a reliable change timestamp there; old metadata-only model folders remain unavailable.
+Inference loads only these verified snapshots with Hub/Transformers offline
+mode enabled, never a repository ID that might trigger an implicit download.
+The returned model revision includes the immutable commit hash. No model
+download runs automatically. Audio is buffered, not streamed.
+
+A real-model intelligibility smoke run is still pending in #8857; fixture tests
+prove the adapter contract, not speech quality. On a CPU/CUDA host with the
+isolated environment and verified weights, run the following manually from
+the repository root (substitute the isolated Python executable and model root):
+
+```sh
+python scripts/qwen3_tts_runner.py --models-dir <model-root> \
+ --mode design --model-id Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign \
+ --text 'The example garden gate is open.' --instructions 'A clear warm alto.' \
+ --output-wav <scratch-dir>/design.wav
+python scripts/qwen3_tts_runner.py --models-dir <model-root> \
+ --mode clone --model-id Qwen/Qwen3-TTS-12Hz-1.7B-Base \
+ --reference-audio <scratch-dir>/design.wav \
+ --reference-transcript 'The example garden gate is open.' \
+ --text 'Please close the gate after you enter.' --output-wav <scratch-dir>/clone.wav
+```
+
+Listen to both files and record intelligibility and voice continuity with the
+reported revisions before treating this as a validated speech runtime. The
+reference is generated, so no personal recording or consent is needed for this
+smoke. A successful command or non-silent WAV alone does not establish quality.
Interactive profile benchmarks measure elapsed time until the buffered WAV is
available at the synthesis service boundary. This includes model startup and
diff --git a/scripts/qwen3_tts_runner.py b/scripts/qwen3_tts_runner.py
index 340db3c867..fd9c4a5816 100755
--- a/scripts/qwen3_tts_runner.py
+++ b/scripts/qwen3_tts_runner.py
@@ -12,10 +12,12 @@ Provides CLI entry points for:
from __future__ import annotations
import argparse
+import contextlib
import hashlib
import os
import re
import json
+import platform
import sys
import tempfile
from pathlib import Path
@@ -164,7 +166,7 @@ def probe_runtime(models_dir: Path | None = None) -> dict:
"""Probe hardware, PyTorch, Transformers, and cached model weights."""
result = {
"ok": False,
- "error": "Qwen3-TTS model operations are unavailable until a real adapter is implemented",
+ "error": "Qwen3-TTS inference requires qwen-tts, torch and soundfile on CPU/CUDA",
"torch_installed": False,
"transformers_installed": False,
"device": "cpu",
@@ -198,6 +200,19 @@ def probe_runtime(models_dir: Path | None = None) -> dict:
except ImportError:
pass
+ # Apple Silicon is deliberately unavailable until the MLX adapter exists;
+ # the presence of a Torch MPS device must not advertise supported inference.
+ if platform.system() == "Darwin" and platform.machine() == "arm64":
+ result["error"] = "Qwen3-TTS MLX inference is unavailable on Apple Silicon"
+ elif result["torch_installed"] and result["transformers_installed"]:
+ try:
+ from qwen_tts import Qwen3TTSModel
+ import soundfile
+ result["ok"] = True
+ result["error"] = None
+ except ImportError:
+ pass
+
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
@@ -220,7 +235,84 @@ def unavailable(operation: str) -> int:
def run_synthesis(args: argparse.Namespace) -> int:
- return unavailable(args.mode)
+ # Resolve the verified immutable snapshot ourselves. Never let a model ID,
+ # arbitrary checkpoint, or missing local file trigger an implicit download.
+ if args.checkpoint_path or args.model_path:
+ return unavailable("custom checkpoints/model paths")
+ if args.rate != 1.0:
+ return unavailable("speech-rate control")
+ if platform.system() == "Darwin" and platform.machine() == "arm64":
+ return unavailable("MLX inference on Apple Silicon")
+ if args.model_id not in SUPPORTED_MODELS or not args.models_dir:
+ return unavailable("inference without a supported verified local model")
+ model_dir = Path(args.models_dir) / args.model_id.replace("/", "--")
+ snapshot = installed_snapshot(model_dir, args.model_id)
+ if snapshot is None:
+ return unavailable("inference without downloaded and verified weights")
+ if not args.text or not args.text.strip():
+ return unavailable("inference without text")
+ design = args.model_id.endswith("-VoiceDesign")
+ if (args.mode == "clone" and design) or (args.mode == "design" and not design):
+ return unavailable("the requested mode for this model variant")
+ if not design and (not args.reference_audio or not Path(args.reference_audio).is_file()):
+ return unavailable("cloning without a local reference recording")
+ if not design and args.instructions:
+ return unavailable("instruction-controlled reference cloning")
+
+ # qwen-tts loads its processor/codec independently. Offline flags cover those
+ # nested loads too; status and inference cannot acquire unrequested weights.
+ os.environ["HF_HUB_OFFLINE"] = "1"
+ os.environ["TRANSFORMERS_OFFLINE"] = "1"
+ try:
+ with contextlib.redirect_stdout(sys.stderr):
+ import numpy as np
+ import soundfile as sf
+ import torch
+ from qwen_tts import Qwen3TTSModel
+
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
+ dtype = (torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16) if device != "cpu" else torch.float32
+ torch.manual_seed(args.seed)
+ model = Qwen3TTSModel.from_pretrained(
+ str(snapshot), device_map=device, dtype=dtype,
+ attn_implementation="eager", local_files_only=True,
+ )
+ with torch.inference_mode():
+ if design:
+ wavs, sample_rate = model.generate_voice_design(
+ text=args.text, language="Auto",
+ instruct=args.instructions or "A clear natural speaking voice.",
+ )
+ else:
+ wavs, sample_rate = model.generate_voice_clone(
+ text=args.text, language="Auto",
+ ref_audio=str(Path(args.reference_audio).resolve()),
+ ref_text=args.reference_transcript or None,
+ x_vector_only_mode=not bool(args.reference_transcript),
+ )
+ if len(wavs) != 1 or not isinstance(sample_rate, int) or sample_rate <= 0:
+ raise ValueError("Invalid model audio result")
+ audio = np.asarray(wavs[0])
+ if audio.ndim != 1 or not audio.size or not np.isfinite(audio).all() or not np.any(audio):
+ raise ValueError("Model returned empty, silent or invalid audio")
+ # Publish only the completed PCM WAV; the JS transport buffers it.
+ sf.write(args.output_wav, audio, sample_rate, format="WAV", subtype="PCM_16")
+ print(json.dumps({
+ "ok": True, "modelRevision": f"{args.model_id}@{snapshot.name}",
+ "effectiveControls": {"rate": 1.0, "seed": args.seed,
+ "instructions": (args.instructions or "A clear natural speaking voice.") if design else None,
+ "mode": "design" if design else "clone"},
+ }))
+ return 0
+ except ImportError:
+ return unavailable("inference dependencies (install qwen-tts in the isolated environment)")
+ except Exception:
+ # Provider exceptions may contain private reference paths/transcripts.
+ # Return a bounded error instead of publishing their raw exception text.
+ Path(args.output_wav).unlink(missing_ok=True)
+ print(json.dumps({"ok": False, "code": "QWEN3_SYNTHESIS_FAILED",
+ "error": "Qwen3-TTS model inference failed; no audio was published"}), file=sys.stderr)
+ return 1
def run_fine_tuning(args: argparse.Namespace) -> int:
@@ -263,7 +355,9 @@ def main() -> int:
if args.probe:
models_dir = Path(args.models_dir) if args.models_dir else None
- print(json.dumps(probe_runtime(models_dir)))
+ with contextlib.redirect_stdout(sys.stderr):
+ status = probe_runtime(models_dir)
+ print(json.dumps(status))
return 0
if args.mode == "fine-tune":
diff --git a/scripts/qwen3_tts_runner.test.js b/scripts/qwen3_tts_runner.test.js
index 9433887345..e34ce0147c 100644
--- a/scripts/qwen3_tts_runner.test.js
+++ b/scripts/qwen3_tts_runner.test.js
@@ -44,6 +44,60 @@ sys.modules["huggingface_hub"] = hub
`;
const run = (source) => JSON.parse(execFileSync(python, ['-c', fixture + source, script], { encoding: 'utf8' }));
+// Test doubles exercise the verified snapshot -> official adapter -> PCM WAV
+// boundary. These fixture samples are deliberately not claimed to be speech.
+const inferenceFixture = String.raw`
+import contextlib, io, wave
+runner.platform.system = lambda: "Linux"
+runner.platform.machine = lambda: "x86_64"
+events = []
+class Array:
+ ndim, size = 1, 240
+numpy = types.ModuleType("numpy")
+numpy.asarray = lambda values: Array()
+numpy.isfinite = lambda values: types.SimpleNamespace(all=lambda: True)
+numpy.any = lambda values: True
+sys.modules["numpy"] = numpy
+torch = types.ModuleType("torch")
+torch.cuda = types.SimpleNamespace(is_available=lambda: False, is_bf16_supported=lambda: False)
+torch.float32, torch.float16, torch.bfloat16 = "float32", "float16", "bfloat16"
+torch.manual_seed = lambda seed: events.append({"seed": seed})
+torch.inference_mode = contextlib.nullcontext
+sys.modules["torch"] = torch
+def write_wav(path, audio, sample_rate, **kwargs):
+ assert kwargs == {"format": "WAV", "subtype": "PCM_16"}
+ with wave.open(str(path), "wb") as output:
+ output.setnchannels(1)
+ output.setsampwidth(2)
+ output.setframerate(sample_rate)
+ output.writeframes(b"\x01\x00" * 240)
+soundfile = types.ModuleType("soundfile")
+soundfile.write = write_wav
+sys.modules["soundfile"] = soundfile
+class Model:
+ @classmethod
+ def from_pretrained(cls, path, **kwargs):
+ assert os.environ["HF_HUB_OFFLINE"] == "1"
+ assert os.environ["TRANSFORMERS_OFFLINE"] == "1"
+ events.append({"path": path, **kwargs})
+ return cls()
+ def generate_voice_design(self, **kwargs):
+ events.append({"design": kwargs})
+ return [[1]], 24000
+ def generate_voice_clone(self, **kwargs):
+ events.append({"clone": kwargs})
+ return [[1]], 24000
+qwen = types.ModuleType("qwen_tts")
+qwen.Qwen3TTSModel = Model
+sys.modules["qwen_tts"] = qwen
+def args_for(root, **kwargs):
+ return types.SimpleNamespace(checkpoint_path=None, model_path=None, rate=1.0,
+ models_dir=str(root), model_id=model_id, text="An invented sentence.",
+ reference_audio=kwargs.get("reference"), reference_transcript=kwargs.get("transcript"),
+ mode=kwargs.get("mode", "design"), instructions=kwargs.get("instructions"),
+ seed=42, output_wav=str(root / "output.wav"))
+`;
+
describe.skipIf(!python)('Qwen3 explicit model acquisition', () => {
it('publishes only complete immutable snapshots and detects missing/truncated required weights', () => {
const result = run(String.raw`
@@ -117,3 +171,94 @@ with tempfile.TemporaryDirectory() as temp:
]);
});
});
+
+describe.skipIf(!python)('Qwen3 verified local inference', () => {
+ it('loads the immutable local snapshot and invokes design/clone with accurate revision evidence', () => {
+ const result = run(inferenceFixture + String.raw`
+with tempfile.TemporaryDirectory() as temp:
+ root = Path(temp)
+ runner.download_model(model_id, root)
+ output = io.StringIO()
+ with contextlib.redirect_stdout(output):
+ assert runner.run_synthesis(args_for(root, instructions="Warm natural alto")) == 0
+ design_result = json.loads(output.getvalue())
+ assert events[1]["local_files_only"] is True
+ assert events[1]["device_map"] == "cpu"
+ assert events[1]["dtype"] == "float32"
+ assert Path(events[1]["path"]).name == revision
+ assert events[2]["design"]["instruct"] == "Warm natural alto"
+ with wave.open(str(root / "output.wav")) as audio:
+ assert audio.getnframes() == 240 and audio.getframerate() == 24000
+ reference = root / "reference.wav"
+ reference.write_bytes(b"explicit test fixture")
+ model_id = runner.SUPPORTED_MODELS[1]
+ runner.download_model(model_id, root)
+ events.clear()
+ output = io.StringIO()
+ with contextlib.redirect_stdout(output):
+ assert runner.run_synthesis(args_for(root, mode="clone", reference=str(reference), transcript="Reference words.")) == 0
+ clone_result = json.loads(output.getvalue())
+ assert events[2]["clone"]["ref_audio"] == str(reference.resolve())
+ assert events[2]["clone"]["ref_text"] == "Reference words."
+ assert events[2]["clone"]["x_vector_only_mode"] is False
+ print(json.dumps({"design": design_result, "clone": clone_result}))
+`);
+ expect(result.design).toMatchObject({ ok: true, modelRevision: `Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign@${'a'.repeat(40)}`, effectiveControls: { mode: 'design', rate: 1 } });
+ expect(result.clone).toMatchObject({ ok: true, modelRevision: `Qwen/Qwen3-TTS-12Hz-1.7B-Base@${'a'.repeat(40)}`, effectiveControls: { mode: 'clone' } });
+ });
+
+ it('refuses missing weights, unsupported controls/variants and Apple Silicon without calling the model', () => {
+ const result = run(inferenceFixture + String.raw`
+with tempfile.TemporaryDirectory() as temp:
+ root = Path(temp)
+ args = args_for(root)
+ with contextlib.redirect_stderr(io.StringIO()):
+ assert runner.run_synthesis(args) == 1
+ runner.download_model(model_id, root)
+ args.rate = 1.2
+ assert runner.run_synthesis(args) == 1
+ args.rate = 1.0
+ args.mode = "clone"
+ assert runner.run_synthesis(args) == 1
+ args.mode = "design"
+ args.checkpoint_path = str(root / "bogus.safetensors")
+ assert runner.run_synthesis(args) == 1
+ args.checkpoint_path = None
+ runner.platform.system = lambda: "Darwin"
+ runner.platform.machine = lambda: "arm64"
+ assert runner.run_synthesis(args) == 1
+ assert runner.run_fine_tuning(args) == 1
+ assert events == []
+ assert not (root / "output.wav").exists()
+ print(json.dumps({"noModelCalls": True}))
+`);
+ expect(result).toEqual({ noModelCalls: true });
+ });
+
+ it('fails instead of publishing invalid model audio or exposing a private inference error', () => {
+ const result = run(inferenceFixture + String.raw`
+with tempfile.TemporaryDirectory() as temp:
+ root = Path(temp)
+ runner.download_model(model_id, root)
+ args = args_for(root)
+ failures = []
+ numpy.any = lambda values: False
+ error = io.StringIO()
+ with contextlib.redirect_stderr(error):
+ assert runner.run_synthesis(args) == 1
+ failures.append(json.loads(error.getvalue()))
+ numpy.any = lambda values: True
+ def private_failure(*args, **kwargs):
+ raise RuntimeError("private reference transcript")
+ Model.generate_voice_design = private_failure
+ error = io.StringIO()
+ with contextlib.redirect_stderr(error):
+ assert runner.run_synthesis(args) == 1
+ assert "private reference transcript" not in error.getvalue()
+ failures.append(json.loads(error.getvalue()))
+ assert not (root / "output.wav").exists()
+ print(json.dumps(failures))
+`);
+ expect(result.every((failure) => failure.code === 'QWEN3_SYNTHESIS_FAILED')).toBe(true);
+ });
+});
diff --git a/server/services/voice/tts-qwen3.js b/server/services/voice/tts-qwen3.js
index 94c45dae50..0e14dce4f7 100644
--- a/server/services/voice/tts-qwen3.js
+++ b/server/services/voice/tts-qwen3.js
@@ -16,6 +16,7 @@ import {
DEFAULT_CLONE_MODEL,
DEFAULT_DESIGN_MODEL,
QWEN3_TTS_RUNNER_SCRIPT,
+ QWEN3_TTS_MODELS_DIR,
resolveQwen3Python,
} from './qwen3TtsRuntime.js';
@@ -66,6 +67,7 @@ export async function synthesizeQwen3(text, opts = {}, signal) {
'--rate', String(rate),
'--seed', String(seed),
'--model-id', modelId,
+ '--models-dir', QWEN3_TTS_MODELS_DIR,
'--output-wav', tempOut,
];
@@ -85,22 +87,43 @@ export async function synthesizeQwen3(text, opts = {}, signal) {
const t0 = performance.now();
try {
- await new Promise((resolve, reject) => {
- const child = spawn(python, args, safeChildProcessOptions({ timeout: 60000, signal }));
+ const { stdout } = await new Promise((resolve, reject) => {
+ const child = spawn(python, args, safeChildProcessOptions({ timeout: 5 * 60 * 1000, signal }));
let out = '';
let err = '';
- child.stdout.on('data', (d) => { out += d.toString(); });
- child.stderr.on('data', (d) => { err += d.toString(); });
+ child.stdout.on('data', (d) => { out = (out + d.toString()).slice(-8192); });
+ child.stderr.on('data', (d) => { err = (err + d.toString()).slice(-8192); });
child.on('close', (code) => {
if (code === 0) resolve({ stdout: out, stderr: err });
- else reject(new ServerError(`Qwen3-TTS synthesis failed (code ${code}): ${err || out}`, { status: 500 }));
+ else {
+ let failure;
+ try { failure = JSON.parse(err.trim().split(/\r?\n/).at(-1)); } catch { /* Process failure without structured output. */ }
+ const unavailable = failure?.code === 'QWEN3_RUNTIME_UNAVAILABLE';
+ reject(new ServerError(unavailable ? 'Qwen3-TTS operation is unavailable for this runtime, model or control' : 'Qwen3-TTS model inference failed', {
+ status: unavailable ? 503 : 502,
+ code: unavailable ? 'QWEN3_RUNTIME_UNAVAILABLE' : 'QWEN3_SYNTHESIS_FAILED',
+ }));
+ }
});
child.on('error', reject);
});
+ let result;
+ try { result = JSON.parse(stdout.trim()); } catch { /* Invalid adapter output is never successful speech. */ }
+ if (result?.ok !== true || typeof result.modelRevision !== 'string' || !result.modelRevision.startsWith(`${modelId}@`)
+ || !/^[a-f0-9]{40}$/.test(result.modelRevision.slice(modelId.length + 1))
+ || !['design', 'clone'].includes(result.effectiveControls?.mode)
+ || result.effectiveControls?.rate !== rate || result.effectiveControls?.seed !== seed) {
+ throw new ServerError('Qwen3-TTS returned invalid inference evidence', { status: 502, code: 'QWEN3_SYNTHESIS_INVALID_RESULT' });
+ }
+
const wavBuffer = await readFile(tempOut);
+ const { wavDurationMs } = await import('../../lib/wavAudioFile.js');
+ if (wavDurationMs(wavBuffer) <= 0) {
+ throw new ServerError('Qwen3-TTS returned no playable WAV', { status: 502, code: 'QWEN3_SYNTHESIS_INVALID_RESULT' });
+ }
// This adapter buffers the whole WAV; audio cannot be played before this read.
const elapsedMs = Math.round(performance.now() - t0);
const firstAudioMs = elapsedMs;
@@ -110,13 +133,8 @@ export async function synthesizeQwen3(text, opts = {}, signal) {
latencyMs: elapsedMs,
firstAudioMs,
engine: 'qwen3-tts',
- modelRevision: modelId,
- effectiveControls: {
- rate,
- seed,
- instructions: opts.instructions || null,
- mode,
- },
+ modelRevision: result.modelRevision,
+ effectiveControls: result.effectiveControls,
};
} finally {
await unlink(tempOut).catch(() => {});
diff --git a/server/services/voice/tts-qwen3.test.js b/server/services/voice/tts-qwen3.test.js
index d87f0c228b..e0c81dd6e8 100644
--- a/server/services/voice/tts-qwen3.test.js
+++ b/server/services/voice/tts-qwen3.test.js
@@ -1,14 +1,43 @@
-import { describe, it, expect } from 'vitest';
-import { resolveTestPython } from '../../lib/testHelper.js';
+import { EventEmitter } from 'node:events';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+vi.mock('../../lib/childProcess.js', async (importOriginal) => ({ ...await importOriginal(), spawn: vi.fn() }));
+vi.mock('node:fs/promises', async (importOriginal) => ({
+ ...await importOriginal(), readFile: vi.fn(), unlink: vi.fn().mockResolvedValue(),
+}));
+vi.mock('./qwen3TtsRuntime.js', async (importOriginal) => ({
+ ...await importOriginal(), resolveQwen3Python: vi.fn().mockResolvedValue('python3'),
+}));
+import { spawn } from '../../lib/childProcess.js';
+import { readFile, unlink } from 'node:fs/promises';
import { synthesizeQwen3, listQwen3Voices } from './tts-qwen3.js';
-// The runner boundary is valuable when Python is installed, but Windows CI
-// does not guarantee a Python runtime. Keep the deterministic preset test
-// available everywhere and skip only the subprocess case when no runnable
-// interpreter exists.
-const testPython = resolveTestPython();
+const modelId = 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign';
+const evidence = { ok: true, modelRevision: `${modelId}@${'a'.repeat(40)}`, effectiveControls: { mode: 'design', seed: 42, rate: 1, instructions: 'warm low alto' } };
+// Explicit PCM fixture, never production/model-generated speech.
+const wav = Buffer.alloc(4844, 1);
+wav.write('RIFF', 0); wav.writeUInt32LE(wav.length - 8, 4); wav.write('WAVEfmt ', 8);
+wav.writeUInt32LE(16, 16); wav.writeUInt16LE(1, 20); wav.writeUInt16LE(1, 22);
+wav.writeUInt32LE(24000, 24); wav.writeUInt32LE(48000, 28); wav.writeUInt16LE(2, 32); wav.writeUInt16LE(16, 34);
+wav.write('data', 36); wav.writeUInt32LE(4800, 40);
+
+function runnerResponse(response, code = 0) {
+ spawn.mockImplementation(() => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter(); child.stderr = new EventEmitter();
+ queueMicrotask(() => {
+ (code === 0 ? child.stdout : child.stderr).emit('data', JSON.stringify(response));
+ child.emit('close', code);
+ });
+ return child;
+ });
+}
describe('tts-qwen3', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ readFile.mockResolvedValue(wav);
+ runnerResponse(evidence);
+ });
it('enumerates default Qwen3 voices', async () => {
const voices = await listQwen3Voices();
expect(voices).toContainEqual(expect.objectContaining({
@@ -20,9 +49,29 @@ describe('tts-qwen3', () => {
expect(voices.every((preset) => preset.id === `qwen3-tts:${preset.voice}`)).toBe(true);
});
- it.skipIf(!testPython)('refuses synthesis instead of returning a synthetic tone', async () => {
+ it('returns only playable audio with the actual immutable revision and buffered latency', async () => {
+ const result = await synthesizeQwen3('An invented example sentence.', { mode: 'design', instructions: 'warm low alto' });
+ expect(result).toMatchObject({ wav, modelRevision: evidence.modelRevision, effectiveControls: evidence.effectiveControls });
+ expect(result.firstAudioMs).toBe(result.latencyMs);
+ expect(spawn.mock.calls[0][1]).toContain('--models-dir');
+ expect(unlink).toHaveBeenCalledOnce();
+ });
+
+ it('refuses unsupported operations without exposing child logs', async () => {
+ runnerResponse({ code: 'QWEN3_RUNTIME_UNAVAILABLE', error: 'private reference detail' }, 1);
await expect(synthesizeQwen3('An invented example sentence.', {
mode: 'design', instructions: 'warm low alto',
- })).rejects.toThrow(/unavailable/);
+ })).rejects.toMatchObject({ status: 503, code: 'QWEN3_RUNTIME_UNAVAILABLE' });
+ expect(readFile).not.toHaveBeenCalled();
+ });
+
+ it('rejects missing or mismatched inference evidence and invalid WAV despite process success', async () => {
+ runnerResponse({ ok: true });
+ await expect(synthesizeQwen3('Example')).rejects.toMatchObject({ code: 'QWEN3_SYNTHESIS_INVALID_RESULT' });
+ runnerResponse({ ...evidence, modelRevision: `other/model@${'a'.repeat(40)}` });
+ await expect(synthesizeQwen3('Example')).rejects.toMatchObject({ code: 'QWEN3_SYNTHESIS_INVALID_RESULT' });
+ runnerResponse(evidence);
+ readFile.mockResolvedValue(Buffer.from('not a wav'));
+ await expect(synthesizeQwen3('Example')).rejects.toMatchObject({ code: 'QWEN3_SYNTHESIS_INVALID_RESULT' });
});
});