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: refuse fabricated Qwen voice operations and persist measured qualification (#8857)

[._.]/ Adam Eivycc1d241d1bfe
diff --git a/docs/features/voice.md b/docs/features/voice.md
index 471d10aafc..fea05d5dbf 100644
--- a/docs/features/voice.md
+++ b/docs/features/voice.md
@@ -10,11 +10,27 @@ 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 | ✅ |
+| Text-to-speech | [Piper](https://github.com/rhasspy/piper) (CLI) | Qwen3-TTS (currently unavailable) | ✅ |
| 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, training, and model acquisition with an explicit unavailable error.
+Earlier versions produced test tones, placeholder checkpoints and download
+metadata; 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
+adapter and an intelligibility smoke run. No model download runs automatically.
+
+Interactive profile benchmarks measure elapsed time until the buffered WAV is
+available at the synthesis service boundary. This includes model startup and
+rendering, but excludes browser/network playback latency. They record no
+similarity score without an actual similarity evaluator. Passing this latency
+gate does not establish intelligibility, speaker identity, or non-silent speech.
+Qualification and its
+route decision are saved together only for the profile revision rendered.
+
### FaceTime Audio control plane
FaceTime Audio controls are off by default and remain machine-local. On macOS, run `npm run setup:facetime`, grant the installed helper Accessibility permission in System Settings, choose the configured BlackHole devices in FaceTime, then enable **FaceTime Audio** in Settings → Features. Set a target name and E.164 phone number or email in Settings → Voice, save, and use **Probe**, **Test call**, or **Hang up**. The helper refuses ambiguous FaceTime surfaces and never uses coordinate clicks.
diff --git a/scripts/qwen3_tts_runner.py b/scripts/qwen3_tts_runner.py
index 8afd51027e..092eda82ea 100755
--- a/scripts/qwen3_tts_runner.py
+++ b/scripts/qwen3_tts_runner.py
@@ -13,18 +13,15 @@ from __future__ import annotations
import argparse
import json
-import math
-import os
import sys
-import time
-import wave
from pathlib import Path
def probe_runtime(models_dir: Path | None = None) -> dict:
"""Probe hardware, PyTorch, Transformers, and cached model weights."""
result = {
- "ok": True,
+ "ok": False,
+ "error": "Qwen3-TTS model operations are unavailable until a real adapter is implemented",
"torch_installed": False,
"transformers_installed": False,
"device": "cpu",
@@ -69,7 +66,7 @@ def probe_runtime(models_dir: Path | None = None) -> dict:
safe_name = model_id.replace("/", "--")
model_path = models_dir / safe_name
result["models"][model_id] = {
- "downloaded": model_path.exists() and any(model_path.iterdir()),
+ "downloaded": False,
"path": str(model_path) if model_path.exists() else None,
}
else:
@@ -82,108 +79,22 @@ def probe_runtime(models_dir: Path | None = None) -> dict:
return result
-def generate_mock_speech_wav(output_file: Path, text: str, sample_rate: int = 24000, rate: float = 1.0) -> float:
- """Generate a clean synthetic sine-modulated WAV for test/fallback/readiness execution."""
- words = max(1, len(text.split()))
- duration_s = max(0.5, (words * 0.25) / max(0.25, min(4.0, rate)))
- total_samples = int(sample_rate * duration_s)
-
- output_file.parent.mkdir(parents=True, exist_ok=True)
- with wave.open(str(output_file), "wb") as wav:
- wav.setnchannels(1)
- wav.setsampwidth(2)
- wav.setframerate(sample_rate)
-
- base_freq = 180.0
- frames = bytearray()
- for i in range(total_samples):
- t = float(i) / sample_rate
- env = min(1.0, t * 20.0) * min(1.0, (duration_s - t) * 20.0)
- if env < 0:
- env = 0.0
- sample_val = (
- 0.6 * math.sin(2.0 * math.pi * base_freq * t) +
- 0.3 * math.sin(2.0 * math.pi * (base_freq * 2) * t) +
- 0.1 * math.sin(2.0 * math.pi * (base_freq * 3) * t)
- )
- syllable_mod = 0.7 + 0.3 * math.sin(2.0 * math.pi * 4.0 * t)
- val = int(sample_val * env * syllable_mod * 16000.0)
- val = max(-32767, min(32767, val))
- frames.extend(val.to_bytes(2, byteorder="little", signed=True))
- wav.writeframes(frames)
- return duration_s
+def unavailable(operation: str) -> int:
+ """Refuse unsupported operations without producing audio or checkpoints."""
+ print(json.dumps({
+ "ok": False,
+ "code": "QWEN3_RUNTIME_UNAVAILABLE",
+ "error": f"Qwen3-TTS {operation} is unavailable: no real model adapter is implemented",
+ }), file=sys.stderr)
+ return 1
def run_synthesis(args: argparse.Namespace) -> int:
- t0 = time.time()
- out_path = Path(args.output_wav).resolve()
- text = args.text or "Qwen3-TTS test audio."
- rate = args.rate if args.rate is not None else 1.0
-
- first_audio_ms = 45.0
- duration_s = generate_mock_speech_wav(out_path, text, sample_rate=24000, rate=rate)
- total_latency_ms = round((time.time() - t0) * 1000, 2)
-
- meta = {
- "ok": True,
- "output_wav": str(out_path),
- "duration_s": duration_s,
- "latency_ms": total_latency_ms,
- "first_audio_ms": first_audio_ms,
- "rate": rate,
- "mode": args.mode,
- "seed": args.seed,
- "instructions": args.instructions,
- "model_id": args.model_id or "Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign",
- }
- print(json.dumps(meta))
- return 0
+ return unavailable(args.mode)
def run_fine_tuning(args: argparse.Namespace) -> int:
- """Execute fine-tuning loop, emitting checkpoints and progress logs."""
- dataset_dir = Path(args.dataset_dir).resolve()
- output_dir = Path(args.output_dir).resolve()
- output_dir.mkdir(parents=True, exist_ok=True)
- epochs = args.epochs or 5
- checkpoint_steps = args.checkpoint_interval or 50
- total_steps = epochs * 50
-
- print(json.dumps({"stage": "init", "total_steps": total_steps, "dataset": str(dataset_dir)}), flush=True)
-
- for step in range(1, total_steps + 1):
- time.sleep(0.001)
- loss = round(2.5 * math.exp(-step / 40.0) + 0.15 * math.sin(step), 4)
-
- if step % 10 == 0 or step == total_steps:
- print(json.dumps({
- "stage": "training",
- "step": step,
- "total_steps": total_steps,
- "loss": loss,
- "progress": round((step / total_steps) * 100, 1),
- }), flush=True)
-
- if step % checkpoint_steps == 0 or step == total_steps:
- ckpt_name = f"checkpoint-{step}.safetensors"
- ckpt_path = output_dir / ckpt_name
- ckpt_path.write_text(f"portos_voice_checkpoint_step_{step}\n")
-
- sample_name = f"sample-step-{step}.wav"
- sample_path = output_dir / sample_name
- generate_mock_speech_wav(sample_path, "This is an evaluation sample from checkpoint step.", rate=1.0)
-
- print(json.dumps({
- "stage": "checkpoint",
- "step": step,
- "checkpoint": ckpt_name,
- "checkpoint_path": str(ckpt_path),
- "sample_wav": str(sample_path),
- "loss": loss,
- }), flush=True)
-
- print(json.dumps({"stage": "completed", "total_steps": total_steps, "output_dir": str(output_dir)}), flush=True)
- return 0
+ return unavailable("fine-tuning")
def main() -> int:
diff --git a/server/services/voice/fineTuning.test.js b/server/services/voice/fineTuning.test.js
index a4c372bf31..5a6b0170f1 100644
--- a/server/services/voice/fineTuning.test.js
+++ b/server/services/voice/fineTuning.test.js
@@ -382,7 +382,7 @@ describe('fineTuning', () => {
// Python runner through the real spawn, so a rename in either the runner's
// stdout contract or the arguments it is handed fails here.
describe.skipIf(!resolveTestPython())('fineTuning runner boundary', () => {
- it('drives the real Qwen3 runner from spawn to a terminal sidecar', async () => {
+ it('records unsupported training as failed without fabricated checkpoints', async () => {
queryMock.mockResolvedValue({ rows: [{ data: PROFILE }] });
await seedSourceAudio();
// Windows ships a `python` Store-alias stub that resolves but cannot run, so
@@ -401,19 +401,10 @@ describe.skipIf(!resolveTestPython())('fineTuning runner boundary', () => {
// vitest budget so a genuinely stuck run reports the status it observed
// instead of producing a bare test timeout.
const record = await drainJobRecord(jobId, { timeout: Math.floor(PY_TEST_TIMEOUT_MS * 0.75) });
- expect(record.status).toBe('completed');
- expect(record.checkpoints.length).toBeGreaterThan(0);
- // Same projection the scripted frames assert, mapped off the runner's own
- // snake_case stdout keys.
- expect(record.checkpoints[0]).toMatchObject({
- id: expect.stringMatching(/^checkpoint-\d+\.safetensors$/),
- step: expect.any(Number),
- checkpointPath: expect.stringContaining('checkpoint-'),
- sampleWav: expect.stringContaining('sample-step-'),
- });
-
+ expect(record.status).toBe('failed');
+ expect(record.checkpoints).toEqual([]);
const status = await getFineTuningJobStatus(jobId, PROFILE.id);
- expect(status.status).toBe('completed');
- expect(status.progress).toBe(100);
+ expect(status.status).toBe('failed');
+ expect(status.progress).not.toBe(100);
}, PY_TEST_TIMEOUT_MS);
});
diff --git a/server/services/voice/profileBenchmarks.js b/server/services/voice/profileBenchmarks.js
index 2e3a6e6800..c7bf232a2e 100644
--- a/server/services/voice/profileBenchmarks.js
+++ b/server/services/voice/profileBenchmarks.js
@@ -3,6 +3,7 @@
import { mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { synthesize } from './tts.js';
+import { ServerError } from '../../lib/errorHandler.js';
import {
getProfileForSynthesis,
getVoiceProfileRequired,
@@ -65,7 +66,7 @@ export async function renderProfileBenchmark(profileId, { signal } = {}) {
}
/**
- * Run host-specific interactive latency and similarity qualification benchmark.
+ * Run host-specific interactive latency qualification (not speech/identity quality).
* Enables interactive route if latency satisfies the configured maxFirstAudioMs gate.
*/
export async function benchmarkProfileInteractive(profileId, { maxFirstAudioMs = 900, signal } = {}) {
@@ -77,28 +78,24 @@ export async function benchmarkProfileInteractive(profileId, { maxFirstAudioMs =
route: 'studio', // test against the artifact without failing on disabled route
signal,
});
- const latencyMs = Math.round(performance.now() - t0);
- const firstAudioMs = result.firstAudioMs || Math.min(latencyMs, 100);
- const passesLatency = firstAudioMs <= maxFirstAudioMs;
-
- const updatedProfile = {
- ...profile,
- routes: {
- ...profile.routes,
- interactive: {
- enabled: passesLatency,
- maxFirstAudioMs,
- },
- },
- };
-
+ // The public synthesis boundary returns buffered audio, so measure when it is
+ // actually available rather than trusting engine estimates of first audio.
+ const firstAudioMs = Math.ceil(performance.now() - t0);
+ const { wavDurationMs } = await import('../../lib/wavAudioFile.js');
+ if (wavDurationMs(result.wav) <= 0) {
+ throw new ServerError('Interactive benchmark returned no playable audio', {
+ status: 502, code: 'VOICE_BENCHMARK_NO_AUDIO',
+ });
+ }
const benchmarkData = {
...(profile.benchmark || {}),
profileRevision: profile.version,
renderedAt: new Date().toISOString(),
interactiveLatencyMs: firstAudioMs,
- similarityScore: 0.95,
+ similarityScore: null,
};
- return saveProfileBenchmark(updatedProfile, benchmarkData);
+ return saveProfileBenchmark(profile, benchmarkData, {
+ interactive: { enabled: firstAudioMs <= maxFirstAudioMs, maxFirstAudioMs },
+ });
}
diff --git a/server/services/voice/profileBenchmarks.test.js b/server/services/voice/profileBenchmarks.test.js
index 00eb1b315a..4a42cc11a7 100644
--- a/server/services/voice/profileBenchmarks.test.js
+++ b/server/services/voice/profileBenchmarks.test.js
@@ -1,9 +1,11 @@
import { join } from 'node:path';
+import { pcmToWavBuffer } from '../../lib/chiptuneRender.js';
import { describe, expect, it, vi } from 'vitest';
vi.mock('./tts.js', () => ({ synthesize: vi.fn() }));
vi.mock('./profiles.js', () => ({
getProfileForSynthesis: vi.fn(),
+ getVoiceProfileRequired: vi.fn(),
profileArtifactDirectory: vi.fn((id) => join('/tmp', id)),
saveProfileBenchmark: vi.fn(),
}));
@@ -13,10 +15,11 @@ import { mkdir, writeFile } from 'node:fs/promises';
import { synthesize } from './tts.js';
import {
getProfileForSynthesis,
+ getVoiceProfileRequired,
profileArtifactDirectory,
saveProfileBenchmark,
} from './profiles.js';
-import { VOICE_PROFILE_BENCHMARK_LINES, renderProfileBenchmark } from './profileBenchmarks.js';
+import { VOICE_PROFILE_BENCHMARK_LINES, renderProfileBenchmark, benchmarkProfileInteractive } from './profileBenchmarks.js';
const PROFILE = {
id: 'voice-profile-1', version: 2, label: 'Example Character',
@@ -51,3 +54,31 @@ describe('voice profile benchmarks', () => {
});
});
});
+
+describe('interactive qualification', () => {
+ it('measures buffered audio availability instead of trusting fabricated engine latency', async () => {
+ getVoiceProfileRequired.mockResolvedValue(PROFILE);
+ const clock = vi.spyOn(performance, 'now').mockReturnValueOnce(100).mockReturnValueOnce(1300);
+ synthesize.mockResolvedValue({ wav: pcmToWavBuffer(new Float32Array(240), { sampleRate: 24000 }), firstAudioMs: 45 });
+ await benchmarkProfileInteractive(PROFILE.id);
+ expect(saveProfileBenchmark).toHaveBeenLastCalledWith(PROFILE, expect.objectContaining({
+ interactiveLatencyMs: 1200, similarityScore: null, profileRevision: 2,
+ }), { interactive: { enabled: false, maxFirstAudioMs: 900 } });
+ clock.mockRestore();
+ });
+
+ it('qualifies timely audio and refuses empty output', async () => {
+ getVoiceProfileRequired.mockResolvedValue(PROFILE);
+ const clock = vi.spyOn(performance, 'now').mockReturnValueOnce(100).mockReturnValueOnce(150);
+ synthesize.mockResolvedValue({ wav: pcmToWavBuffer(new Float32Array(240), { sampleRate: 24000 }) });
+ await benchmarkProfileInteractive(PROFILE.id);
+ expect(saveProfileBenchmark).toHaveBeenLastCalledWith(PROFILE, expect.objectContaining({
+ interactiveLatencyMs: 50, similarityScore: null,
+ }), { interactive: { enabled: true, maxFirstAudioMs: 900 } });
+ clock.mockRestore();
+ saveProfileBenchmark.mockClear();
+ synthesize.mockResolvedValue({ wav: Buffer.alloc(0) });
+ await expect(benchmarkProfileInteractive(PROFILE.id)).rejects.toMatchObject({ code: 'VOICE_BENCHMARK_NO_AUDIO' });
+ expect(saveProfileBenchmark).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/voice/profiles.db.test.js b/server/services/voice/profiles.db.test.js
new file mode 100644
index 0000000000..37794c6340
--- /dev/null
+++ b/server/services/voice/profiles.db.test.js
@@ -0,0 +1,38 @@
+import { afterAll, describe, expect, it } from 'vitest';
+import { randomUUID } from 'node:crypto';
+import { checkHealth, close, ensureSchema, query } from '../../lib/db.js';
+import { requireDbOrSkip } from '../../lib/dbTestGate.js';
+import { getVoiceProfile, saveProfileBenchmark } from './profiles.js';
+
+const health = await checkHealth().catch(() => ({ connected: false }));
+const runDb = requireDbOrSkip('voice profile qualification', health.connected, 'Postgres unavailable');
+const id = `voice-test-${randomUUID()}`;
+
+describe.skipIf(!runDb)('voice profile qualification persistence', () => {
+ afterAll(async () => {
+ await query('DELETE FROM voice_profiles WHERE id = $1', [id]);
+ await close();
+ });
+
+ it('persists route evidence together and rejects stale revisions', async () => {
+ await ensureSchema();
+ const profile = {
+ id, version: 1, binding: { universeId: id, characterId: 'example-character' },
+ label: 'Example Voice', engine: 'piper', kind: 'preset', voiceId: 'piper:example',
+ routes: { studio: { enabled: true }, interactive: { enabled: false } },
+ approval: { status: 'draft' },
+ };
+ await query(`INSERT INTO voice_profiles (id, universe_id, character_id, approval_status, data)
+ VALUES ($1, $1, 'example-character', 'draft', $2::jsonb)`, [id, JSON.stringify(profile)]);
+ const benchmark = { renderedAt: new Date().toISOString(), profileRevision: 1, interactiveLatencyMs: 250, similarityScore: null };
+ await saveProfileBenchmark(profile, benchmark, { interactive: { enabled: true, maxFirstAudioMs: 900 } });
+ expect(await getVoiceProfile(id)).toMatchObject({
+ label: 'Example Voice', benchmark,
+ routes: { studio: { enabled: true }, interactive: { enabled: true, maxFirstAudioMs: 900 } },
+ });
+ await query(`UPDATE voice_profiles SET data = data || '{"version":2,"label":"Revised Voice"}'::jsonb WHERE id = $1`, [id]);
+ await expect(saveProfileBenchmark(profile, benchmark, { interactive: { enabled: false } }))
+ .rejects.toMatchObject({ code: 'VOICE_PROFILE_BENCHMARK_STALE' });
+ expect(await getVoiceProfile(id)).toMatchObject({ version: 2, label: 'Revised Voice', routes: { interactive: { enabled: true } } });
+ });
+});
diff --git a/server/services/voice/profiles.js b/server/services/voice/profiles.js
index 5567636c7c..e9706ac89d 100644
--- a/server/services/voice/profiles.js
+++ b/server/services/voice/profiles.js
@@ -94,7 +94,7 @@ const sanitizeBenchmark = (raw) => {
},
};
}).filter(Boolean).slice(0, MAX_BENCHMARK_LINES) : [];
- if (!renderedAt || lines.length === 0) return null;
+ if (!renderedAt || (lines.length === 0 && !Number.isFinite(raw.interactiveLatencyMs))) return null;
return {
profileRevision: positiveInteger(raw.profileRevision),
renderedAt,
@@ -529,14 +529,29 @@ export async function promotePresetProfile({
return persist(next);
}
-export async function saveProfileBenchmark(profile, benchmark) {
- const current = await getVoiceProfileRequired(profile?.id);
- const next = sanitizeVoiceProfile({
- ...current,
- benchmark,
- updatedAt: timestamp(),
- });
- return persist(next);
+export async function saveProfileBenchmark(profile, benchmark, { interactive } = {}) {
+ const cleanBenchmark = sanitizeBenchmark(benchmark);
+ // Patch only the measured fields in one DB statement. A concurrent profile
+ // revision change invalidates the evidence instead of qualifying new audio
+ // against an old render or overwriting another writer's profile changes.
+ const patch = { benchmark: cleanBenchmark, updatedAt: timestamp() };
+ const route = interactive ? sanitizeRoutes({ interactive }).interactive : null;
+ const { rows } = await query(
+ `UPDATE voice_profiles SET
+ data = CASE WHEN $4::jsonb IS NULL THEN data || $2::jsonb
+ ELSE jsonb_set(data || $2::jsonb, '{routes}',
+ COALESCE(data->'routes', '{}'::jsonb) || jsonb_build_object('interactive', $4::jsonb)) END,
+ updated_at = $5
+ WHERE id = $1 AND (data->>'version')::int = $3
+ RETURNING data`,
+ [profile.id, JSON.stringify(patch), profile.version, route ? JSON.stringify(route) : null, patch.updatedAt],
+ );
+ if (!rows.length) {
+ throw new ServerError('Voice profile changed during benchmarking; run the benchmark again', {
+ status: 409, code: 'VOICE_PROFILE_BENCHMARK_STALE',
+ });
+ }
+ return sanitizeVoiceProfile(rows[0].data);
}
/**
diff --git a/server/services/voice/qwen3TtsRuntime.js b/server/services/voice/qwen3TtsRuntime.js
index ef6ffe3eab..04db2466d7 100644
--- a/server/services/voice/qwen3TtsRuntime.js
+++ b/server/services/voice/qwen3TtsRuntime.js
@@ -8,7 +8,6 @@
*/
import { existsSync } from 'node:fs';
-import { mkdir, writeFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { spawn } from '../../lib/childProcess.js';
@@ -67,8 +66,8 @@ export async function resolveQwen3Python() {
* Check if the isolated runtime venv or compatible Python interpreter is installed.
*/
export async function isQwen3RuntimeInstalled() {
- const python = await resolveQwen3Python();
- return Boolean(python);
+ const status = await getQwen3RuntimeStatus();
+ return status.ok;
}
/**
@@ -107,8 +106,9 @@ export async function getQwen3RuntimeStatus() {
}
return {
- ok: true,
- installed: true,
+ ok: data.ok === true,
+ installed: data.ok === true,
+ message: data.error || null,
venvPresent,
pythonPath: python,
hardware: {
@@ -124,7 +124,7 @@ export async function getQwen3RuntimeStatus() {
} catch (err) {
return {
ok: false,
- installed: true,
+ installed: false,
venvPresent,
pythonPath: python,
hardware: { device: 'cpu', cuda: false, mps: false, vramGb: null },
@@ -153,7 +153,7 @@ function spawnProbe(pythonPath, args) {
/**
* Explicit user-triggered model download.
*/
-export async function downloadQwen3Model(modelId, { signal } = {}) {
+export async function downloadQwen3Model(modelId) {
const modelSpec = SUPPORTED_QWEN3_MODELS.find((m) => m.id === modelId);
if (!modelSpec) {
throw new ServerError(`Unsupported Qwen3-TTS model: ${modelId}`, {
@@ -162,25 +162,8 @@ export async function downloadQwen3Model(modelId, { signal } = {}) {
});
}
- await mkdir(QWEN3_TTS_MODELS_DIR, { recursive: true });
- const safeName = modelId.replace('/', '--');
- const targetDir = join(QWEN3_TTS_MODELS_DIR, safeName);
- await mkdir(targetDir, { recursive: true });
-
- // In test/mock or real runtime, mark directory with metadata snapshot
- await writeFile(
- join(targetDir, 'model_meta.json'),
- JSON.stringify({
- modelId,
- downloadedAt: new Date().toISOString(),
- sizeGb: modelSpec.sizeGb,
- }, null, 2),
- );
-
- return {
- ok: true,
- modelId,
- path: targetDir,
- label: modelSpec.label,
- };
+ throw new ServerError('Qwen3-TTS model acquisition is unavailable: no verified download adapter is implemented', {
+ status: 503,
+ code: 'QWEN3_DOWNLOAD_UNAVAILABLE',
+ });
}
diff --git a/server/services/voice/qwen3TtsRuntime.test.js b/server/services/voice/qwen3TtsRuntime.test.js
index b4d470a370..6836bed5fa 100644
--- a/server/services/voice/qwen3TtsRuntime.test.js
+++ b/server/services/voice/qwen3TtsRuntime.test.js
@@ -1,9 +1,8 @@
-import { describe, it, expect, vi } from 'vitest';
+import { describe, it, expect } from 'vitest';
import {
SUPPORTED_QWEN3_MODELS,
downloadQwen3Model,
getQwen3RuntimeStatus,
- resolveQwen3Python,
} from './qwen3TtsRuntime.js';
describe('qwen3TtsRuntime', () => {
@@ -20,7 +19,8 @@ describe('qwen3TtsRuntime', () => {
it('probes runtime health without throwing when python is available', async () => {
const status = await getQwen3RuntimeStatus();
- expect(status).toHaveProperty('ok');
+ expect(status.ok).toBe(false);
+ expect(status.installed).toBe(false);
expect(status).toHaveProperty('installed');
expect(status).toHaveProperty('supportedModels');
});
@@ -28,10 +28,9 @@ describe('qwen3TtsRuntime', () => {
it('downloads model explicitly on user request and rejects unknown models', async () => {
await expect(downloadQwen3Model('unknown/invalid-model')).rejects.toThrow(/unsupported qwen3/i);
- const result = await downloadQwen3Model('Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign');
- expect(result).toMatchObject({
- ok: true,
- modelId: 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign',
+ await expect(downloadQwen3Model('Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign')).rejects.toMatchObject({
+ status: 503,
+ code: 'QWEN3_DOWNLOAD_UNAVAILABLE',
});
});
});
diff --git a/server/services/voice/tts-qwen3.js b/server/services/voice/tts-qwen3.js
index 135594eeba..94c45dae50 100644
--- a/server/services/voice/tts-qwen3.js
+++ b/server/services/voice/tts-qwen3.js
@@ -85,7 +85,7 @@ export async function synthesizeQwen3(text, opts = {}, signal) {
const t0 = performance.now();
try {
- const { stdout, stderr } = await new Promise((resolve, reject) => {
+ await new Promise((resolve, reject) => {
const child = spawn(python, args, safeChildProcessOptions({ timeout: 60000, signal }));
let out = '';
let err = '';
@@ -100,16 +100,10 @@ export async function synthesizeQwen3(text, opts = {}, signal) {
child.on('error', reject);
});
- const elapsedMs = Math.round(performance.now() - t0);
- let parsedMeta = {};
- try {
- parsedMeta = JSON.parse(stdout.trim());
- } catch {
- // Ignored if output wasn't pure JSON
- }
-
const wavBuffer = await readFile(tempOut);
- const firstAudioMs = parsedMeta.first_audio_ms || Math.min(elapsedMs, 120);
+ // This adapter buffers the whole WAV; audio cannot be played before this read.
+ const elapsedMs = Math.round(performance.now() - t0);
+ const firstAudioMs = elapsedMs;
return {
wav: wavBuffer,
diff --git a/server/services/voice/tts-qwen3.test.js b/server/services/voice/tts-qwen3.test.js
index 3c09c8a852..d87f0c228b 100644
--- a/server/services/voice/tts-qwen3.test.js
+++ b/server/services/voice/tts-qwen3.test.js
@@ -20,26 +20,9 @@ describe('tts-qwen3', () => {
expect(voices.every((preset) => preset.id === `qwen3-tts:${preset.voice}`)).toBe(true);
});
- it.skipIf(!testPython)('synthesizes speech with voice design and rate controls', async () => {
- const result = await synthesizeQwen3('This is a test of voice design synthesis.', {
- mode: 'design',
- voice: 'warm-narrator',
- instructions: 'warm low alto',
- seed: 42,
- rate: 1.1,
- });
-
- expect(result).toMatchObject({
- engine: 'qwen3-tts',
- effectiveControls: {
- rate: 1.1,
- seed: 42,
- instructions: 'warm low alto',
- mode: 'design',
- },
- });
- expect(result.wav).toBeInstanceOf(Buffer);
- expect(result.wav.length).toBeGreaterThan(44); // standard WAV header + data
- expect(result.latencyMs).toBeGreaterThanOrEqual(0);
+ it.skipIf(!testPython)('refuses synthesis instead of returning a synthetic tone', async () => {
+ await expect(synthesizeQwen3('An invented example sentence.', {
+ mode: 'design', instructions: 'warm low alto',
+ })).rejects.toThrow(/unavailable/);
});
});
diff --git a/server/vitest.config.db.js b/server/vitest.config.db.js
index d9a13138f7..efd20b0a30 100644
--- a/server/vitest.config.db.js
+++ b/server/vitest.config.db.js
@@ -15,6 +15,7 @@ process.env.NODE_ENV = 'test';
* listed explicitly below (the drift guard fails the build if you forget).
*/
export const DB_TEST_INCLUDE = [
+ 'services/voice/profiles.db.test.js',
'../scripts/perf/collectionFixture.db.test.js',
'services/appQuality.db.test.js',
'**/db.test.js',