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: qualify voice profiles at browser playback startup (#8857)

[._.]/ Adam Eivy1db7fe6bf53c
diff --git a/client/src/components/universe/CharacterDetailEditor.jsx b/client/src/components/universe/CharacterDetailEditor.jsx
index ea085ecf95..2039bbcbf8 100644
--- a/client/src/components/universe/CharacterDetailEditor.jsx
+++ b/client/src/components/universe/CharacterDetailEditor.jsx
@@ -47,9 +47,9 @@ import {
createVoiceDesignCandidate,
createClonedVoiceCandidate,
promoteVoiceProfile,
- benchmarkProfileInteractive,
startFineTuningJob,
} from '../../services/apiVoice';
+import { qualifyProfilePlayback } from '../../services/voiceProfileBenchmark';
import VoicePicker from '../voice/VoicePicker';
import TabPills from '../ui/TabPills';
import useDrawerTab from '../../hooks/useDrawerTab';
@@ -902,7 +902,7 @@ function VoiceProfileSection({ universeId, entry, disabled }) {
const [qualifyInteractive, qualifyingInteractive] = useAsyncAction(async () => {
if (!profile?.id) return null;
- const result = await benchmarkProfileInteractive(profile.id, { maxFirstAudioMs: 900 }, { silent: true });
+ const result = await qualifyProfilePlayback(profile.id, { maxFirstAudioMs: 900 }, { silent: true });
await refreshProfiles();
return result;
}, { errorMessage: 'Interactive benchmark qualification failed' });
@@ -959,7 +959,7 @@ function VoiceProfileSection({ universeId, entry, disabled }) {
</p>
{profile.benchmark?.interactiveLatencyMs ? (
<p className="text-[10px] text-port-success">
- Interactive Latency Benchmark: {profile.benchmark.interactiveLatencyMs}ms (threshold: {profile.routes?.interactive?.maxFirstAudioMs || 900}ms)
+ Request-to-playback benchmark: {profile.benchmark.interactiveLatencyMs}ms (threshold: {profile.routes?.interactive?.maxFirstAudioMs || 900}ms)
</p>
) : null}
</div>
diff --git a/client/src/components/universe/CharacterDetailEditor.test.jsx b/client/src/components/universe/CharacterDetailEditor.test.jsx
index 16feed91a6..a0d1d02fc2 100644
--- a/client/src/components/universe/CharacterDetailEditor.test.jsx
+++ b/client/src/components/universe/CharacterDetailEditor.test.jsx
@@ -16,7 +16,7 @@ vi.mock('../../services/apiVoice', () => ({
createVoiceDesignCandidate: vi.fn(),
createClonedVoiceCandidate: vi.fn(),
promoteVoiceProfile: vi.fn(),
- benchmarkProfileInteractive: vi.fn(),
+
startFineTuningJob: vi.fn(),
}));
@@ -25,9 +25,11 @@ import {
listVoiceProfiles,
promoteVoicePreset,
createVoiceDesignCandidate,
- benchmarkProfileInteractive,
} from '../../services/apiVoice';
+vi.mock('../../services/voiceProfileBenchmark', () => ({ qualifyProfilePlayback: vi.fn() }));
+import { qualifyProfilePlayback } from '../../services/voiceProfileBenchmark';
+
const ARIA = { id: 'chr-aria', name: 'Aria' };
const BRAM = { id: 'chr-bram', name: 'Bram' };
const CASS = { id: 'chr-cass', name: 'Cass' };
@@ -287,7 +289,7 @@ describe('CharacterDetailEditor — production package (#5378)', () => {
routes: { studio: { enabled: true }, interactive: { enabled: false, maxFirstAudioMs: 900 } },
}],
});
- benchmarkProfileInteractive.mockResolvedValueOnce({
+ qualifyProfilePlayback.mockResolvedValueOnce({
profile: {
id: 'voice-profile-1', version: 1, approval: { status: 'approved' },
routes: { studio: { enabled: true }, interactive: { enabled: true, maxFirstAudioMs: 900 } },
@@ -301,7 +303,7 @@ describe('CharacterDetailEditor — production package (#5378)', () => {
fireEvent.click(screen.getByRole('tab', { name: 'Voice' }));
fireEvent.click(await screen.findByRole('button', { name: /Qualify interactive route/i }));
- await waitFor(() => expect(benchmarkProfileInteractive).toHaveBeenCalledWith(
+ await waitFor(() => expect(qualifyProfilePlayback).toHaveBeenCalledWith(
'voice-profile-1', { maxFirstAudioMs: 900 }, { silent: true },
));
});
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 2b67320c4c..840703f78f 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -150,6 +150,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| File | Purpose |
|---|---|
+| `voiceProfileBenchmark.js` | Measures request-to-playing latency for fresh profile probes and submits a one-use playback receipt. |
| `voiceClient.js` | Browser-side voice capture + playback (two modes). |
| `browserLlm.js` | Client for Chrome's on-device "Gemini Nano" (Prompt API): dual-shape detection, availability enum, cached `promptNano()` with timeout. Tier 2 of the voice fast-resolution cascade. |
| `voiceFastPath.js` | Voice fast-resolution cascade: trigger nav → on-device Nano → server LLM. Decides how each spoken/typed turn is resolved. |
diff --git a/client/src/services/apiVoice.js b/client/src/services/apiVoice.js
index f6cd53ed31..4fdcc6f173 100644
--- a/client/src/services/apiVoice.js
+++ b/client/src/services/apiVoice.js
@@ -31,6 +31,10 @@ export const benchmarkProfileInteractive = (profileId, payload = {}, options) =>
`/voice/profiles/${encodeURIComponent(profileId)}/benchmark-interactive`, payload, options,
);
+export const completeVoiceProfileInteractiveBenchmark = (profileId, payload, options) => api.post(
+ `/voice/profiles/${encodeURIComponent(profileId)}/benchmark-interactive/complete`, payload, options,
+);
+
// Fine-tuning
export const startFineTuningJob = (profileId, payload = {}, options) => api.post(
`/voice/profiles/${encodeURIComponent(profileId)}/fine-tune/start`, payload, options,
diff --git a/client/src/services/voiceProfileBenchmark.js b/client/src/services/voiceProfileBenchmark.js
new file mode 100644
index 0000000000..1fd44ed1ff
--- /dev/null
+++ b/client/src/services/voiceProfileBenchmark.js
@@ -0,0 +1,33 @@
+import { benchmarkProfileInteractive, completeVoiceProfileInteractiveBenchmark } from './apiVoice';
+
+/** Measure a fresh render through the browser's actual playback-start event. */
+export async function qualifyProfilePlayback(profileId, payload = {}, options) {
+ const startedAt = performance.now();
+ const { benchmark } = await benchmarkProfileInteractive(profileId, payload, options);
+ if (!benchmark?.benchmarkId || !benchmark?.audioBase64) throw new Error('No playable benchmark was returned');
+ const audio = new Audio(`data:audio/wav;base64,${benchmark.audioBase64}`);
+ const playbackLatencyMs = await new Promise((resolve, reject) => {
+ let settled = false;
+ const finish = (error) => {
+ if (settled) return;
+ settled = true;
+ const elapsed = Math.ceil(performance.now() - startedAt);
+ clearTimeout(timeout);
+ audio.removeEventListener('playing', onPlaying);
+ audio.removeEventListener('error', onError);
+ audio.pause();
+ audio.removeAttribute('src');
+ if (error) reject(error);
+ else resolve(elapsed);
+ };
+ const onPlaying = () => finish();
+ const onError = () => finish(new Error('The benchmark audio could not play'));
+ const timeout = setTimeout(() => finish(new Error('Benchmark playback timed out')), 30000);
+ audio.addEventListener('playing', onPlaying);
+ audio.addEventListener('error', onError);
+ Promise.resolve().then(() => audio.play()).catch(finish);
+ });
+ return completeVoiceProfileInteractiveBenchmark(profileId, {
+ benchmarkId: benchmark.benchmarkId, playbackLatencyMs,
+ }, options);
+}
diff --git a/client/src/services/voiceProfileBenchmark.test.js b/client/src/services/voiceProfileBenchmark.test.js
new file mode 100644
index 0000000000..bf0825e223
--- /dev/null
+++ b/client/src/services/voiceProfileBenchmark.test.js
@@ -0,0 +1,46 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+vi.mock('./apiVoice', () => ({ benchmarkProfileInteractive: vi.fn(), completeVoiceProfileInteractiveBenchmark: vi.fn() }));
+import { benchmarkProfileInteractive, completeVoiceProfileInteractiveBenchmark } from './apiVoice';
+import { qualifyProfilePlayback } from './voiceProfileBenchmark';
+
+afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.useRealTimers(); vi.clearAllMocks(); });
+const prepare = (play = vi.fn().mockResolvedValue()) => {
+ const audio = new EventTarget();
+ Object.assign(audio, { play, pause: vi.fn(), removeAttribute: vi.fn() });
+ vi.stubGlobal('Audio', vi.fn(function () { return audio; }));
+ benchmarkProfileInteractive.mockResolvedValue({ benchmark: { benchmarkId: 'probe-1', audioBase64: 'fixture' } });
+ return audio;
+};
+
+describe('profile browser playback qualification', () => {
+ it('waits for playing, includes request time, and submits only actual playback evidence', async () => {
+ const audio = prepare();
+ const clock = vi.spyOn(performance, 'now').mockReturnValue(100);
+ completeVoiceProfileInteractiveBenchmark.mockResolvedValue({ profile: { id: 'profile-1' } });
+ const pending = qualifyProfilePlayback('profile-1');
+ await vi.waitFor(() => expect(audio.play).toHaveBeenCalled());
+ expect(completeVoiceProfileInteractiveBenchmark).not.toHaveBeenCalled();
+ clock.mockReturnValue(550);
+ audio.dispatchEvent(new Event('playing'));
+ await expect(pending).resolves.toEqual({ profile: { id: 'profile-1' } });
+ expect(completeVoiceProfileInteractiveBenchmark).toHaveBeenCalledWith('profile-1', {
+ benchmarkId: 'probe-1', playbackLatencyMs: 450,
+ }, undefined);
+ expect(audio.pause).toHaveBeenCalled();
+ expect(audio.removeAttribute).toHaveBeenCalledWith('src');
+ });
+
+ it('does not qualify rejected playback or a playback timeout', async () => {
+ prepare(vi.fn().mockRejectedValue(new Error('Playback denied')));
+ await expect(qualifyProfilePlayback('profile-1')).rejects.toThrow('Playback denied');
+ expect(completeVoiceProfileInteractiveBenchmark).not.toHaveBeenCalled();
+ vi.useFakeTimers();
+ const audio = prepare();
+ const pending = qualifyProfilePlayback('profile-1');
+ const rejection = expect(pending).rejects.toThrow('Benchmark playback timed out');
+ await vi.advanceTimersByTimeAsync(30000);
+ await rejection;
+ expect(audio.pause).toHaveBeenCalled();
+ expect(completeVoiceProfileInteractiveBenchmark).not.toHaveBeenCalled();
+ });
+});
diff --git a/docs/features/voice.md b/docs/features/voice.md
index d03a565393..555c611d39 100644
--- a/docs/features/voice.md
+++ b/docs/features/voice.md
@@ -61,13 +61,18 @@ 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
-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.
+Interactive profile qualification plays a fresh buffered WAV in the browser.
+Timing starts before the render request and stops at the browser's `playing`
+event, so it includes rendering, response transfer, decoding and playback startup.
+It is a request-to-playback benchmark, not first-chunk streaming latency. Rendering
+alone never enables the route. A one-use receipt expires after two minutes, binds
+the measurement to the rendered profile revision, and saves its boundary, model
+revision and route decision together. Restarting the server or changing the
+profile requires a fresh benchmark. Playback rejection or timeout cannot qualify.
+The browser reports its own playback event; this is an operator measurement,
+not an attestation of another machine's audio output. No similarity score is
+invented, and passing this latency gate does not establish intelligibility or
+speaker identity.
### FaceTime Audio control plane
diff --git a/server/routes/voice.js b/server/routes/voice.js
index bae54d46be..a807aa63f5 100644
--- a/server/routes/voice.js
+++ b/server/routes/voice.js
@@ -27,7 +27,7 @@ import {
createClonedVoiceCandidate,
promoteVoiceProfile,
} from '../services/voice/profiles.js';
-import { renderProfileBenchmark, benchmarkProfileInteractive } from '../services/voice/profileBenchmarks.js';
+import { renderProfileBenchmark, benchmarkProfileInteractive, completeProfileInteractiveBenchmark } from '../services/voice/profileBenchmarks.js';
import { getQwen3RuntimeStatus, downloadQwen3Model, DEFAULT_DESIGN_MODEL } from '../services/voice/qwen3TtsRuntime.js';
import {
startFineTuningJob,
@@ -252,6 +252,11 @@ const interactiveBenchmarkSchema = z.object({
maxFirstAudioMs: z.number().min(50).max(5000).optional(),
}).strict();
+const interactivePlaybackReceiptSchema = z.object({
+ benchmarkId: z.string().uuid(),
+ playbackLatencyMs: z.number().min(0).max(120000),
+}).strict();
+
const fineTuneStartSchema = z.object({
epochs: z.number().int().min(1).max(50).optional(),
checkpointInterval: z.number().int().min(10).max(500).optional(),
@@ -413,7 +418,14 @@ router.post('/profiles/:id/benchmark', asyncHandler(async (req, res) => {
router.post('/profiles/:id/benchmark-interactive', asyncHandler(async (req, res) => {
const { id: profileId } = validateRequest(profileIdParamsSchema, req.params);
const body = validateRequest(interactiveBenchmarkSchema, req.body || {});
- const profile = await benchmarkProfileInteractive(profileId, body);
+ const benchmark = await benchmarkProfileInteractive(profileId, body);
+ res.json({ benchmark });
+}));
+
+router.post('/profiles/:id/benchmark-interactive/complete', asyncHandler(async (req, res) => {
+ const { id: profileId } = validateRequest(profileIdParamsSchema, req.params);
+ const body = validateRequest(interactivePlaybackReceiptSchema, req.body || {});
+ const profile = await completeProfileInteractiveBenchmark(profileId, body);
res.json({ profile });
}));
diff --git a/server/routes/voice.test.js b/server/routes/voice.test.js
index dfdfc5bb83..35d985a7bf 100644
--- a/server/routes/voice.test.js
+++ b/server/routes/voice.test.js
@@ -42,6 +42,7 @@ vi.mock('../services/voice/profiles.js', async (importActual) => ({
vi.mock('../services/voice/profileBenchmarks.js', () => ({
renderProfileBenchmark: vi.fn(),
benchmarkProfileInteractive: vi.fn(),
+ completeProfileInteractiveBenchmark: vi.fn(),
}));
vi.mock('../services/voice/qwen3TtsRuntime.js', () => ({
getQwen3RuntimeStatus: vi.fn(),
@@ -198,14 +199,27 @@ describe('Voice Routes', () => {
});
it('runs interactive latency qualification benchmark', async () => {
- profileBenchmarks.benchmarkProfileInteractive.mockResolvedValue({ id: 'voice-profile-1' });
+ profileBenchmarks.benchmarkProfileInteractive.mockResolvedValue({ benchmarkId: 'example-probe', audioBase64: 'fixture' });
const res = await request(buildApp()).post('/api/voice/profiles/voice-profile-1/benchmark-interactive').send({
maxFirstAudioMs: 800,
});
expect(res.status).toBe(200);
+ expect(res.body).toEqual({ benchmark: { benchmarkId: 'example-probe', audioBase64: 'fixture' } });
expect(profileBenchmarks.benchmarkProfileInteractive).toHaveBeenCalledWith('voice-profile-1', { maxFirstAudioMs: 800 });
});
+ it('validates a playback receipt before completing interactive qualification', async () => {
+ profileBenchmarks.completeProfileInteractiveBenchmark.mockResolvedValue({ id: 'voice-profile-1' });
+ const receipt = { benchmarkId: '12345678-1234-4234-8234-123456789012', playbackLatencyMs: 200 };
+ const res = await request(buildApp()).post('/api/voice/profiles/voice-profile-1/benchmark-interactive/complete').send(receipt);
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ profile: { id: 'voice-profile-1' } });
+ expect(profileBenchmarks.completeProfileInteractiveBenchmark).toHaveBeenCalledWith('voice-profile-1', receipt);
+ const invalid = await request(buildApp()).post('/api/voice/profiles/voice-profile-1/benchmark-interactive/complete')
+ .send({ ...receipt, playbackLatencyMs: -1 });
+ expect(invalid.status).toBe(400);
+ });
+
it('runs fixed benchmarks only for a valid profile id', async () => {
profileBenchmarks.renderProfileBenchmark.mockResolvedValue({ id: 'voice-profile-1' });
const res = await request(buildApp()).post('/api/voice/profiles/voice-profile-1/benchmark').send({});
diff --git a/server/services/voice/profileBenchmarks.js b/server/services/voice/profileBenchmarks.js
index c7bf232a2e..3831556462 100644
--- a/server/services/voice/profileBenchmarks.js
+++ b/server/services/voice/profileBenchmarks.js
@@ -1,5 +1,6 @@
/** Fixed, reproducible benchmark rendering for approved local voice profiles (#5380, #5381). */
+import { randomUUID } from 'node:crypto';
import { mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { synthesize } from './tts.js';
@@ -57,7 +58,6 @@ export async function renderProfileBenchmark(profileId, { signal } = {}) {
});
}
return saveProfileBenchmark(profile, {
- ...profile.benchmark,
profileRevision: profile.version,
renderedAt: new Date().toISOString(),
lines,
@@ -65,37 +65,62 @@ export async function renderProfileBenchmark(profileId, { signal } = {}) {
});
}
-/**
- * Run host-specific interactive latency qualification (not speech/identity quality).
- * Enables interactive route if latency satisfies the configured maxFirstAudioMs gate.
- */
+// Evidence is one-use and process-local: restarting requires a fresh playback.
+// Lazy expiry keeps this user-triggered workflow free of recurring timers.
+const playbackBenchmarks = new Map();
+const PLAYBACK_TTL_MS = 120000;
+
+/** Render a playable probe; rendering alone never qualifies an interactive route. */
export async function benchmarkProfileInteractive(profileId, { maxFirstAudioMs = 900, signal } = {}) {
const profile = await getVoiceProfileRequired(profileId);
- const testText = 'Hello. I am ready to speak with you.';
- const t0 = performance.now();
- const result = await synthesize(testText, {
- profileId: profile.id,
- route: 'studio', // test against the artifact without failing on disabled route
- signal,
+ const startedAt = performance.now();
+ const result = await synthesize('Hello. I am ready to speak with you.', {
+ profileId: profile.id, route: 'studio', signal,
});
- // 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 synthesisLatencyMs = Math.ceil(performance.now() - startedAt);
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,
+ const now = performance.now();
+ for (const [id, pending] of playbackBenchmarks) {
+ if (pending.expiresAt <= now || pending.profile.id === profile.id) playbackBenchmarks.delete(id);
+ }
+ // A bounded set even when requests complete without a playback receipt.
+ if (playbackBenchmarks.size >= 100) playbackBenchmarks.delete(playbackBenchmarks.keys().next().value);
+ const benchmarkId = randomUUID();
+ playbackBenchmarks.set(benchmarkId, {
+ profile, maxFirstAudioMs, synthesisLatencyMs, expiresAt: now + PLAYBACK_TTL_MS,
+ modelRevision: result.provenance?.modelRevision || profile.modelRevision,
+ });
+ return { benchmarkId, profileRevision: profile.version, audioBase64: result.wav.toString('base64') };
+}
+
+/** Save only a receipt for the probe actually played by the browser. */
+export async function completeProfileInteractiveBenchmark(profileId, { benchmarkId, playbackLatencyMs }) {
+ const pending = playbackBenchmarks.get(benchmarkId);
+ if (!pending || pending.profile.id !== profileId || pending.expiresAt <= performance.now()) {
+ throw new ServerError('Playback benchmark expired or does not match this profile; run it again', {
+ status: 409, code: 'VOICE_BENCHMARK_RECEIPT_INVALID',
+ });
+ }
+ playbackBenchmarks.delete(benchmarkId);
+ if (!Number.isFinite(playbackLatencyMs) || playbackLatencyMs < pending.synthesisLatencyMs || playbackLatencyMs > PLAYBACK_TTL_MS) {
+ throw new ServerError('Playback timing does not include the rendered probe; run it again', {
+ status: 400, code: 'VOICE_BENCHMARK_TIMING_INVALID',
+ });
+ }
+ const latencyMs = Math.ceil(playbackLatencyMs);
+ return saveProfileBenchmark(pending.profile, {
+ profileRevision: pending.profile.version,
renderedAt: new Date().toISOString(),
- interactiveLatencyMs: firstAudioMs,
+ interactiveLatencyMs: latencyMs,
similarityScore: null,
- };
-
- return saveProfileBenchmark(profile, benchmarkData, {
- interactive: { enabled: firstAudioMs <= maxFirstAudioMs, maxFirstAudioMs },
- });
+ interactiveMeasurement: {
+ boundary: 'browser-playing', synthesisLatencyMs: pending.synthesisLatencyMs,
+ modelRevision: pending.modelRevision,
+ },
+ }, { interactive: { enabled: latencyMs <= pending.maxFirstAudioMs, maxFirstAudioMs: pending.maxFirstAudioMs } });
}
diff --git a/server/services/voice/profileBenchmarks.test.js b/server/services/voice/profileBenchmarks.test.js
index 4a42cc11a7..e839e71779 100644
--- a/server/services/voice/profileBenchmarks.test.js
+++ b/server/services/voice/profileBenchmarks.test.js
@@ -19,7 +19,7 @@ import {
profileArtifactDirectory,
saveProfileBenchmark,
} from './profiles.js';
-import { VOICE_PROFILE_BENCHMARK_LINES, renderProfileBenchmark, benchmarkProfileInteractive } from './profileBenchmarks.js';
+import { VOICE_PROFILE_BENCHMARK_LINES, renderProfileBenchmark, benchmarkProfileInteractive, completeProfileInteractiveBenchmark } from './profileBenchmarks.js';
const PROFILE = {
id: 'voice-profile-1', version: 2, label: 'Example Character',
@@ -56,29 +56,56 @@ describe('voice profile benchmarks', () => {
});
describe('interactive qualification', () => {
- it('measures buffered audio availability instead of trusting fabricated engine latency', async () => {
+ it('never qualifies rendering alone and persists actual browser playback evidence and route together', 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);
+ synthesize.mockResolvedValue({
+ wav: pcmToWavBuffer(new Float32Array(240), { sampleRate: 24000 }), firstAudioMs: 45,
+ provenance: { modelRevision: 'example-model@revision' },
+ });
+ saveProfileBenchmark.mockClear();
+ const clock = vi.spyOn(performance, 'now').mockReturnValue(100);
+ const probe = await benchmarkProfileInteractive(PROFILE.id);
+ expect(saveProfileBenchmark).not.toHaveBeenCalled();
+ expect(probe).toMatchObject({ profileRevision: 2, audioBase64: expect.any(String) });
+ await completeProfileInteractiveBenchmark(PROFILE.id, {
+ benchmarkId: probe.benchmarkId, playbackLatencyMs: 1200,
+ });
expect(saveProfileBenchmark).toHaveBeenLastCalledWith(PROFILE, expect.objectContaining({
interactiveLatencyMs: 1200, similarityScore: null, profileRevision: 2,
+ interactiveMeasurement: { boundary: 'browser-playing', synthesisLatencyMs: 0, modelRevision: 'example-model@revision' },
}), { interactive: { enabled: false, maxFirstAudioMs: 900 } });
+ await expect(completeProfileInteractiveBenchmark(PROFILE.id, {
+ benchmarkId: probe.benchmarkId, playbackLatencyMs: 10,
+ })).rejects.toMatchObject({ code: 'VOICE_BENCHMARK_RECEIPT_INVALID' });
+ const timely = await benchmarkProfileInteractive(PROFILE.id);
+ await completeProfileInteractiveBenchmark(PROFILE.id, { benchmarkId: timely.benchmarkId, playbackLatencyMs: 50 });
+ expect(saveProfileBenchmark).toHaveBeenLastCalledWith(PROFILE, expect.objectContaining({ interactiveLatencyMs: 50 }), {
+ interactive: { enabled: true, maxFirstAudioMs: 900 },
+ });
clock.mockRestore();
});
- it('qualifies timely audio and refuses empty output', async () => {
+ it('rejects missing audio, mismatched, replaced, expired and impossible playback receipts without qualifying', 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) });
+ saveProfileBenchmark.mockClear();
await expect(benchmarkProfileInteractive(PROFILE.id)).rejects.toMatchObject({ code: 'VOICE_BENCHMARK_NO_AUDIO' });
+ synthesize.mockResolvedValue({ wav: pcmToWavBuffer(new Float32Array(240), { sampleRate: 24000 }) });
+ const clock = vi.spyOn(performance, 'now').mockReturnValue(100);
+ const first = await benchmarkProfileInteractive(PROFILE.id);
+ await expect(completeProfileInteractiveBenchmark('another-profile', { benchmarkId: first.benchmarkId, playbackLatencyMs: 50 }))
+ .rejects.toMatchObject({ code: 'VOICE_BENCHMARK_RECEIPT_INVALID' });
+ const second = await benchmarkProfileInteractive(PROFILE.id);
+ await expect(completeProfileInteractiveBenchmark(PROFILE.id, { benchmarkId: first.benchmarkId, playbackLatencyMs: 50 }))
+ .rejects.toMatchObject({ code: 'VOICE_BENCHMARK_RECEIPT_INVALID' });
+ clock.mockReturnValue(120101);
+ await expect(completeProfileInteractiveBenchmark(PROFILE.id, { benchmarkId: second.benchmarkId, playbackLatencyMs: 50 }))
+ .rejects.toMatchObject({ code: 'VOICE_BENCHMARK_RECEIPT_INVALID' });
+ clock.mockReturnValueOnce(100).mockReturnValueOnce(200).mockReturnValue(200);
+ const third = await benchmarkProfileInteractive(PROFILE.id);
+ await expect(completeProfileInteractiveBenchmark(PROFILE.id, { benchmarkId: third.benchmarkId, playbackLatencyMs: 50 }))
+ .rejects.toMatchObject({ code: 'VOICE_BENCHMARK_TIMING_INVALID' });
expect(saveProfileBenchmark).not.toHaveBeenCalled();
+ clock.mockRestore();
});
});
diff --git a/server/services/voice/profiles.js b/server/services/voice/profiles.js
index 496cff6330..207096ee85 100644
--- a/server/services/voice/profiles.js
+++ b/server/services/voice/profiles.js
@@ -103,6 +103,12 @@ const sanitizeBenchmark = (raw) => {
lines,
mastering: sanitizeMastering(raw.mastering),
interactiveLatencyMs: Number.isFinite(raw.interactiveLatencyMs) ? Math.round(raw.interactiveLatencyMs) : null,
+ interactiveMeasurement: raw.interactiveMeasurement?.boundary === 'browser-playing' &&
+ Number.isFinite(raw.interactiveMeasurement.synthesisLatencyMs) ? {
+ boundary: 'browser-playing',
+ synthesisLatencyMs: Math.max(0, Math.round(raw.interactiveMeasurement.synthesisLatencyMs)),
+ modelRevision: trimTo(raw.interactiveMeasurement.modelRevision, MAX_REVISION) || null,
+ } : null,
similarityScore: Number.isFinite(raw.similarityScore) ? Number(raw.similarityScore.toFixed(3)) : null,
};
};
@@ -568,13 +574,19 @@ export async function saveProfileBenchmark(profile, benchmark, { interactive } =
// 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() };
+ // Each workflow supplies only its own fields: a playback receipt must not
+ // erase fixed-script renders produced while the operator was playing it.
+ const benchmarkPatch = Object.fromEntries(Object.entries(cleanBenchmark || {})
+ .filter(([key]) => Object.hasOwn(benchmark, key)));
+ const patch = { benchmark: benchmarkPatch, 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
+ data = jsonb_set(
+ 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,
+ '{benchmark}', COALESCE(data->'benchmark', '{}'::jsonb) || ($2::jsonb->'benchmark')),
updated_at = $5
WHERE id = $1 AND (data->>'version')::int = $3
RETURNING data`,
diff --git a/server/services/voice/profiles.test.js b/server/services/voice/profiles.test.js
index 25d6cc1e11..99b4cdcaee 100644
--- a/server/services/voice/profiles.test.js
+++ b/server/services/voice/profiles.test.js
@@ -23,6 +23,7 @@ const {
getProfileForSynthesis,
profileArtifactDirectory,
recordVoiceProfileRender,
+ saveProfileBenchmark,
} = await import('./profiles.js');
const PROFILE = {
@@ -256,6 +257,28 @@ describe('voice profile contract', () => {
});
});
+ it('saves playback evidence and route atomically for the rendered revision and rejects stale revisions', async () => {
+ const benchmark = {
+ renderedAt: '2026-09-01T00:00:00.000Z', profileRevision: PROFILE.version,
+ interactiveLatencyMs: 120, similarityScore: null,
+ interactiveMeasurement: { boundary: 'browser-playing', synthesisLatencyMs: 90, modelRevision: PROFILE.modelRevision },
+ };
+ const interactive = { enabled: true, maxFirstAudioMs: 900 };
+ queryMock.mockResolvedValueOnce({ rows: [{ data: { ...PROFILE, benchmark, routes: { ...PROFILE.routes, interactive } } }] });
+ const saved = await saveProfileBenchmark(PROFILE, benchmark, { interactive });
+ expect(saved.benchmark.interactiveMeasurement).toEqual(benchmark.interactiveMeasurement);
+ expect(saved.routes.interactive).toEqual(interactive);
+ const [sql, args] = queryMock.mock.calls[0];
+ expect(sql).toContain("(data->>'version')::int = $3");
+ expect(sql).toContain("COALESCE(data->'benchmark', '{}'::jsonb) || ($2::jsonb->'benchmark')");
+ expect(JSON.parse(args[1]).benchmark).not.toHaveProperty('lines');
+ expect(JSON.parse(args[1]).benchmark.interactiveMeasurement).toEqual(benchmark.interactiveMeasurement);
+ expect(args[2]).toBe(PROFILE.version);
+ expect(JSON.parse(args[3])).toEqual(interactive);
+ queryMock.mockResolvedValueOnce({ rows: [] });
+ await expect(saveProfileBenchmark(PROFILE, benchmark, { interactive })).rejects.toMatchObject({ code: 'VOICE_PROFILE_BENCHMARK_STALE' });
+ });
+
it('rejects a profile on a disabled route instead of silently synthesizing it', async () => {
queryMock.mockResolvedValueOnce({ rows: [{ data: PROFILE }] });
await expect(getProfileForSynthesis(PROFILE.id, 'interactive'))