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
feat(voice): add Qwen3-TTS voice design, consented cloning, and fine-tuning (#5381)
[._.]/ Adam Eivydc638dddff85
diff --git a/client/src/components/universe/CharacterDetailEditor.jsx b/client/src/components/universe/CharacterDetailEditor.jsxindex ed37ac2998..d747ba1aec 100644--- a/client/src/components/universe/CharacterDetailEditor.jsx+++ b/client/src/components/universe/CharacterDetailEditor.jsx@@ -26,6 +26,14 @@ import {listVoiceProfiles,promoteVoicePreset,renderVoiceProfileBenchmark,+ createVoiceDesignCandidate,+ createClonedVoiceCandidate,+ promoteVoiceProfile,+ benchmarkProfileInteractive,+ startFineTuningJob,+ getFineTuningJobStatus,+ cancelFineTuningJob,+ promoteFineTunedCheckpoint,} from '../../services/apiVoice';import VoicePicker from '../voice/VoicePicker';import CollapsibleSection from '../ui/CollapsibleSection';@@ -757,15 +765,45 @@ function VoiceCanonSection({ entry, onPatch, disabled }) {function VoiceProfileSection({ universeId, entry, disabled }) {const [profile, setProfile] = useState(null);+ const [profiles, setProfiles] = useState([]);const [loading, setLoading] = useState(Boolean(universeId));const [loadError, setLoadError] = useState(null);const [engineCapability, setEngineCapability] = useState(null);+ const [activeTab, setActiveTab] = useState('overview');++ // Voice Design form state+ const [designInstructions, setDesignInstructions] = useState('');+ const [designSeed, setDesignSeed] = useState(42);+ const [designRate, setDesignRate] = useState(1.0);++ // Consented Cloning form state+ const [cloneFile, setCloneFile] = useState(null);+ const [cloneFileName, setCloneFileName] = useState('');+ const [cloneTranscript, setCloneTranscript] = useState('');+ const [cloneConsentConfirmed, setCloneConsentConfirmed] = useState(false);+ const [cloneLicensePosture, setCloneLicensePosture] = useState('consented-performance');++ // Fine-tuning state+ const [fineTuneEpochs, setFineTuneEpochs] = useState(5);+ const [fineTuneJob, setFineTuneJob] = useState(null);+const loadGeneration = useRef(0);++ const refreshProfiles = async () => {+ if (!universeId || !entry?.id) return;+ const result = await listVoiceProfiles({ universeId, characterId: entry.id }, { silent: true });+ const list = Array.isArray(result?.profiles) ? result.profiles : [];+ setProfiles(list);+ const active = list.find((p) => p.approval?.status === 'approved') || list[0] || null;+ if (active) setProfile(active);+ };+useEffect(() => {let cancelled = false;const generation = ++loadGeneration.current;if (!universeId || !entry?.id) {setProfile(null);+ setProfiles([]);setLoading(false);return () => { cancelled = true; };}@@ -773,12 +811,15 @@ function VoiceProfileSection({ universeId, entry, disabled }) {listVoiceProfiles({ universeId, characterId: entry.id }, { silent: true }).then((result) => {if (cancelled || generation !== loadGeneration.current) return;- setProfile(Array.isArray(result?.profiles) ? result.profiles[0] || null : null);+ const list = Array.isArray(result?.profiles) ? result.profiles : [];+ setProfiles(list);+ const active = list.find((p) => p.approval?.status === 'approved') || list[0] || null;+ setProfile(active);setLoadError(null);}).catch((err) => {if (!cancelled && generation === loadGeneration.current) {- setLoadError(err?.message || 'Failed to load the local voice profile');+ setLoadError(err?.message || 'Failed to load voice profiles');}}).finally(() => {@@ -793,7 +834,7 @@ function VoiceProfileSection({ universeId, entry, disabled }) {listVoiceEngines({ silent: true }).then((result) => {if (cancelled) return;- const engine = entry?.voiceId?.split(':')[0];+ const engine = entry?.voiceId?.split(':')[0] || 'qwen3-tts';setEngineCapability((result?.engines || []).find((item) => item.id === engine) || null);}).catch(() => {@@ -802,8 +843,7 @@ function VoiceProfileSection({ universeId, entry, disabled }) {return () => { cancelled = true; };}, [universeId, entry?.voiceId]);- const [promote, promoting] = useAsyncAction(async () => {- // A pending initial fetch must not erase the user action that just won.+ const [promotePreset, promotingPreset] = useAsyncAction(async () => {loadGeneration.current += 1;const result = await promoteVoicePreset({universeId,@@ -812,69 +852,320 @@ function VoiceProfileSection({ universeId, entry, disabled }) {voiceId: entry.voiceId,}, { silent: true });setProfile(result?.profile || null);+ await refreshProfiles();+ return result;+ }, { errorMessage: 'Could not promote preset' });++ const [designVoice, designingVoice] = useAsyncAction(async () => {+ const result = await createVoiceDesignCandidate({+ universeId,+ characterId: entry.id,+ characterName: entry.name || '',+ instructions: designInstructions,+ seed: designSeed,+ rate: designRate,+ }, { silent: true });+ await refreshProfiles();+ return result;+ }, { errorMessage: 'Voice design candidate generation failed' });++ const [cloneVoice, cloningVoice] = useAsyncAction(async () => {+ if (!cloneFile || !cloneConsentConfirmed) return null;+ const arrayBuffer = await cloneFile.arrayBuffer();+ const bytes = new Uint8Array(arrayBuffer);+ let binary = '';+ for (let i = 0; i < bytes.byteLength; i++) {+ binary += String.fromCharCode(bytes[i]);+ }+ const audioBase64 = btoa(binary);++ const result = await createClonedVoiceCandidate({+ universeId,+ characterId: entry.id,+ characterName: entry.name || '',+ filename: cloneFileName || cloneFile.name || 'reference.wav',+ audioBase64,+ transcript: cloneTranscript,+ performerConsentConfirmed: cloneConsentConfirmed,+ licensePosture: cloneLicensePosture,+ }, { silent: true });+ await refreshProfiles();return result;- }, { errorMessage: 'Could not promote the selected preset' });+ }, { errorMessage: 'Consented cloning candidate creation failed' });const [renderBenchmark, renderingBenchmark] = useAsyncAction(async () => {+ if (!profile?.id) return null;const result = await renderVoiceProfileBenchmark(profile.id, { silent: true });- setProfile(result?.profile || profile);+ await refreshProfiles();return result;- }, { errorMessage: 'Could not render the voice benchmark' });+ }, { errorMessage: 'Could not render voice benchmark' });++ const [qualifyInteractive, qualifyingInteractive] = useAsyncAction(async () => {+ if (!profile?.id) return null;+ const result = await benchmarkProfileInteractive(profile.id, { maxFirstAudioMs: 900 }, { silent: true });+ await refreshProfiles();+ return result;+ }, { errorMessage: 'Interactive benchmark qualification failed' });++ const [promoteSelected, promotingSelected] = useAsyncAction(async (targetProfileId) => {+ const result = await promoteVoiceProfile(targetProfileId, {}, { silent: true });+ await refreshProfiles();+ return result;+ }, { errorMessage: 'Could not promote candidate profile' });++ const [startFineTune, startingFineTune] = useAsyncAction(async () => {+ if (!profile?.id) return null;+ const result = await startFineTuningJob(profile.id, { epochs: fineTuneEpochs }, { silent: true });+ setFineTuneJob(result);+ return result;+ }, { errorMessage: 'Failed to start fine-tuning' });if (!universeId) return null;const approved = profile?.approval?.status === 'approved';const benchmarkCount = profile?.benchmark?.lines?.length || 0;- const profileState = approved ? `approved v${profile.version}` : profile?.approval?.status || 'not promoted';+ const profileState = approved ? `approved v${profile.version} (${profile.kind})` : profile?.approval?.status || 'not promoted';+return (- <BoxedSection icon={Mic} label="Local voice profile" summary={loading ? 'loading' : profileState}>+ <BoxedSection icon={Mic} label="Local voice profile & Voice Lab" summary={loading ? 'loading' : profileState}><p className="text-[10px] leading-snug text-gray-500">- This machine-local profile wins over the portable preset binding. It never writes a profile id into the synced Universe record.+ Machine-local voice design, consented cloning, and optional fine-tuning. Candidate profiles never mutate approved character voice until explicitly promoted.</p>{loadError ? <p className="text-[10px] text-port-error">{loadError}</p> : null}- {approved ? (- <p className="text-[10px] text-gray-400">- {profile.voiceId} · {profile.modelRevision} · rate {profile.delivery?.rate ?? 1} · benchmark {benchmarkCount ? `${benchmarkCount} lines rendered` : 'not rendered'}- </p>- ) : profile ? (- <p className="text-[10px] text-gray-500">This local profile is {profileState}; it is unavailable for synthesis until explicitly approved.</p>- ) : <p className="text-[10px] text-gray-500">Promote the selected Kokoro or Piper preset to give this character a stable local voice.</p>}- <div className="flex flex-wrap gap-1.5">- <button- type="button" onClick={promote} disabled={disabled || promoting || !entry.voiceId}- className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-400 hover:text-white hover:border-gray-500 disabled:opacity-40"- >- <BadgeCheck size={10} /> {approved ? 'Re-promote selected preset' : 'Promote selected preset'}- </button>- <button- type="button" onClick={renderBenchmark} disabled={disabled || renderingBenchmark || !approved}- className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-400 hover:text-white hover:border-gray-500 disabled:opacity-40"- >- {renderingBenchmark ? <Loader2 size={10} className="animate-spin" /> : <Play size={10} />} Render fixed benchmark- </button>++ {/* Sub-tab navigation */}+ <div className="flex gap-1 border-b border-port-border/40 pb-1 text-[11px]">+ {['overview', 'design', 'clone', 'finetune'].map((tab) => (+ <button+ key={tab}+ type="button"+ onClick={() => setActiveTab(tab)}+ className={`px-2 py-0.5 rounded capitalize ${activeTab === tab ? 'bg-port-accent text-white font-medium' : 'text-gray-400 hover:text-white'}`}+ >+ {tab === 'finetune' ? 'Fine-Tuning' : tab}+ </button>+ ))}</div>- <p className="text-[10px] leading-snug text-gray-500">- {engineCapability?.unavailableControls- || 'Kokoro and Piper support preset selection plus rate only. Pitch and formant controls are intentionally unavailable until a compatible local backend and formant-preserving transform are installed.'}- </p>- {profile?.benchmark?.lines?.length ? (- <div className="space-y-1.5">- <p className="text-[10px] text-gray-500">Fixed benchmark renders</p>- {profile.benchmark.lines.map((line, index) => (- <div key={line.filename} className="flex items-center gap-2">- <span className="w-4 shrink-0 text-[10px] text-gray-600">{index + 1}</span>- <audio- controls- preload="none"- src={`/data/${line.filename.split('/').map(encodeURIComponent).join('/')}`}- aria-label={`Voice benchmark ${line.key || index + 1}`}- className="h-7 min-w-0 flex-1"- >- <track kind="captions" />- </audio>++ {activeTab === 'overview' && (+ <div className="space-y-2">+ {approved ? (+ <div className="rounded border border-port-border/40 bg-port-bg/40 p-2 space-y-1">+ <p className="text-[11px] text-gray-300 font-medium">+ Active Approved Voice: <span className="text-port-accent">{profile.voiceId}</span> ({profile.kind})+ </p>+ <p className="text-[10px] text-gray-400">+ Model: {profile.modelRevision} · Rate: {profile.delivery?.rate ?? 1} · Studio: {profile.routes?.studio?.enabled ? 'Yes' : 'No'} · Interactive: {profile.routes?.interactive?.enabled ? 'Qualified' : 'Pending qualification'}+ </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)+ </p>+ ) : null}</div>- ))}+ ) : (+ <p className="text-[10px] text-gray-500">Promote the selected Kokoro or Piper preset to give this character a stable local voice.</p>+ )}++ <div className="flex flex-wrap gap-1.5">+ <button+ type="button" onClick={promotePreset} disabled={disabled || promotingPreset || !entry.voiceId}+ className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-400 hover:text-white hover:border-gray-500 disabled:opacity-40"+ >+ <BadgeCheck size={10} /> {approved ? 'Re-promote selected preset' : 'Promote selected preset'}+ </button>+ <button+ type="button" onClick={renderBenchmark} disabled={disabled || renderingBenchmark || !approved}+ className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-400 hover:text-white hover:border-gray-500 disabled:opacity-40"+ >+ {renderingBenchmark ? <Loader2 size={10} className="animate-spin" /> : <Play size={10} />} Render fixed benchmark+ </button>+ <button+ type="button" onClick={qualifyInteractive} disabled={disabled || qualifyingInteractive || !approved}+ className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-400 hover:text-white hover:border-gray-500 disabled:opacity-40"+ >+ {qualifyingInteractive ? <Loader2 size={10} className="animate-spin" /> : <Activity size={10} />} Qualify interactive route+ </button>+ </div>++ {profile?.benchmark?.lines?.length ? (+ <div className="space-y-1.5">+ <p className="text-[10px] text-gray-500">Fixed benchmark renders</p>+ {profile.benchmark.lines.map((line, index) => (+ <div key={line.filename} className="flex items-center gap-2">+ <span className="w-4 shrink-0 text-[10px] text-gray-600">{index + 1}</span>+ <span className="w-20 shrink-0 text-[10px] text-gray-400 truncate">{line.key}</span>+ <audio+ controls+ preload="none"+ src={`/data/${line.filename.split('/').map(encodeURIComponent).join('/')}`}+ aria-label={`Voice benchmark ${line.key || index + 1}`}+ className="h-7 min-w-0 flex-1"+ >+ <track kind="captions" />+ </audio>+ </div>+ ))}+ </div>+ ) : null}++ {/* Candidate & Historical Profiles */}+ {profiles.length > 1 && (+ <div className="space-y-1 pt-2 border-t border-port-border/40">+ <p className="text-[10px] text-gray-500 font-medium">Candidate & Previous Profiles</p>+ {profiles.map((p) => (+ <div key={p.id} className="flex items-center justify-between gap-2 p-1 text-[10px] border border-port-border/30 rounded">+ <div className="min-w-0 truncate">+ <span className="font-semibold text-gray-300">{p.voiceId}</span> ({p.kind}, v{p.version}, {p.approval?.status})+ </div>+ {p.approval?.status !== 'approved' ? (+ <button+ type="button"+ onClick={() => promoteSelected(p.id)}+ disabled={disabled || promotingSelected}+ className="px-1.5 py-0.5 rounded bg-port-accent/20 text-port-accent hover:bg-port-accent hover:text-white"+ >+ Promote+ </button>+ ) : (+ <span className="text-port-success font-medium">Active</span>+ )}+ </div>+ ))}+ </div>+ )}</div>- ) : null}+ )}++ {activeTab === 'design' && (+ <div className="space-y-2">+ <p className="text-[10px] text-gray-400">Design an original character voice via natural language instructions and seed controls (Qwen3-TTS 1.7B Voice Design).</p>+ <div className="space-y-1.5">+ <label className="block text-[10px] text-gray-400">+ Voice Description & Delivery Instructions+ <input+ type="text"+ value={designInstructions}+ onChange={(e) => setDesignInstructions(e.target.value)}+ placeholder="e.g. warm low alto; dry texture; controlled breath; intimate"+ className="w-full mt-0.5 px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-white"+ />+ </label>+ <div className="flex gap-2">+ <label className="block text-[10px] text-gray-400 flex-1">+ Seed+ <input+ type="number"+ value={designSeed}+ onChange={(e) => setDesignSeed(parseInt(e.target.value, 10) || 42)}+ className="w-full mt-0.5 px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-white"+ />+ </label>+ <label className="block text-[10px] text-gray-400 flex-1">+ Rate Multiplier ({designRate}x)+ <input+ type="range"+ min="0.5"+ max="2.0"+ step="0.05"+ value={designRate}+ onChange={(e) => setDesignRate(parseFloat(e.target.value))}+ className="w-full mt-0.5"+ />+ </label>+ </div>+ </div>+ <button+ type="button"+ onClick={designVoice}+ disabled={disabled || designingVoice}+ className="inline-flex items-center gap-1 px-2 py-1 text-xs rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-40"+ >+ {designingVoice ? <Loader2 size={12} className="animate-spin" /> : <WandSparkles size={12} />}+ Design Candidate Voice+ </button>+ </div>+ )}++ {activeTab === 'clone' && (+ <div className="space-y-2">+ <p className="text-[10px] text-gray-400">Rapid single-speaker cloning with documented consent. Audio remains strictly machine-local.</p>+ <div className="space-y-1.5">+ <label className="block text-[10px] text-gray-400">+ Reference Audio File (WAV/MP3)+ <input+ type="file"+ accept="audio/*"+ onChange={(e) => {+ const f = e.target.files?.[0];+ setCloneFile(f || null);+ setCloneFileName(f?.name || '');+ }}+ className="w-full mt-0.5 text-xs text-gray-300"+ />+ </label>+ <label className="block text-[10px] text-gray-400">+ Audio Transcription+ <textarea+ value={cloneTranscript}+ onChange={(e) => setCloneTranscript(e.target.value)}+ placeholder="Exact spoken words in the recording for conditioning alignment..."+ rows={2}+ className="w-full mt-0.5 px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-white"+ />+ </label>+ <label className="flex items-center gap-1.5 text-[10px] text-gray-300">+ <input+ type="checkbox"+ checked={cloneConsentConfirmed}+ onChange={(e) => setCloneConsentConfirmed(e.target.checked)}+ />+ <span>I confirm the performer consented to this voice clone and PortOS keeps this audio machine-local.</span>+ </label>+ </div>+ <button+ type="button"+ onClick={cloneVoice}+ disabled={disabled || cloningVoice || !cloneFile || !cloneConsentConfirmed}+ className="inline-flex items-center gap-1 px-2 py-1 text-xs rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-40"+ >+ {cloningVoice ? <Loader2 size={12} className="animate-spin" /> : <Mic size={12} />}+ Create Cloned Candidate+ </button>+ </div>+ )}++ {activeTab === 'finetune' && (+ <div className="space-y-2">+ <p className="text-[10px] text-gray-400">Optional character voice fine-tuning. Checkpointed and cancellable; never assumes the last checkpoint is best.</p>+ <div className="flex gap-2">+ <label className="block text-[10px] text-gray-400 flex-1">+ Epochs+ <input+ type="number"+ value={fineTuneEpochs}+ onChange={(e) => setFineTuneEpochs(parseInt(e.target.value, 10) || 5)}+ min="1"+ max="20"+ className="w-full mt-0.5 px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-white"+ />+ </label>+ </div>+ <button+ type="button"+ onClick={startFineTune}+ disabled={disabled || startingFineTune || !profile?.id}+ className="inline-flex items-center gap-1 px-2 py-1 text-xs rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-40"+ >+ {startingFineTune ? <Loader2 size={12} className="animate-spin" /> : <Activity size={12} />}+ Start Fine-Tuning Job+ </button>+ {fineTuneJob ? (+ <div className="p-2 border border-port-border/40 rounded bg-port-bg/40 text-[10px] space-y-1">+ <p>Job ID: {fineTuneJob.jobId} · Status: {fineTuneJob.status}</p>+ </div>+ ) : null}+ </div>+ )}</BoxedSection>);}diff --git a/client/src/components/universe/CharacterDetailEditor.test.jsx b/client/src/components/universe/CharacterDetailEditor.test.jsxindex bc66065cc4..591df80904 100644--- a/client/src/components/universe/CharacterDetailEditor.test.jsx+++ b/client/src/components/universe/CharacterDetailEditor.test.jsx@@ -8,14 +8,25 @@ vi.mock('../voice/VoicePicker', () => ({ default: () => null }));vi.mock('../../services/apiVoice', () => ({listVoiceEngines: vi.fn().mockResolvedValue({ engines: [] }),listVoiceProfiles: vi.fn(),+ promotePresetProfile: vi.fn(),promoteVoicePreset: vi.fn(),renderVoiceProfileBenchmark: vi.fn(),+ createVoiceDesignCandidate: vi.fn(),+ createClonedVoiceCandidate: vi.fn(),+ promoteVoiceProfile: vi.fn(),+ benchmarkProfileInteractive: vi.fn(),+ startFineTuningJob: vi.fn(),}));import {listVoiceEngines,listVoiceProfiles,+ promotePresetProfile,promoteVoicePreset,+ createVoiceDesignCandidate,+ createClonedVoiceCandidate,+ promoteVoiceProfile,+ benchmarkProfileInteractive,} from '../../services/apiVoice';const ARIA = { id: 'chr-aria', name: 'Aria' };@@ -216,6 +227,87 @@ describe('CharacterDetailEditor — production package (#5378)', () => {);});+ it('generates a voice design candidate via Voice Lab', async () => {+ listVoiceEngines.mockResolvedValue({ engines: [] });+ listVoiceProfiles.mockResolvedValue({ profiles: [] });+ createVoiceDesignCandidate.mockResolvedValueOnce({+ profile: {+ id: 'voice-profile-des-1', version: 1, kind: 'designed', engine: 'qwen3-tts',+ approval: { status: 'draft' },+ },+ });++ render(<CharacterDetailEditor+ entry={ARIA} universeId="uni-1" characters={[ARIA]} onPatch={() => {}}+ />);+ fireEvent.click(screen.getByRole('button', { name: /Local voice profile/i }));++ // Switch to Design tab+ fireEvent.click(screen.getByRole('button', { name: /Design/i }));+ fireEvent.change(screen.getByPlaceholderText(/warm low alto/i), {+ target: { value: 'calm, measured alto' },+ });+ fireEvent.click(screen.getByRole('button', { name: /Design Candidate Voice/i }));++ await waitFor(() => expect(createVoiceDesignCandidate).toHaveBeenCalledWith({+ universeId: 'uni-1',+ characterId: 'chr-aria',+ characterName: 'Aria',+ instructions: 'calm, measured alto',+ seed: 42,+ rate: 1,+ }, { silent: true }));+ });++ it('gates consented voice cloning on explicit performer consent confirmation', async () => {+ listVoiceEngines.mockResolvedValue({ engines: [] });+ listVoiceProfiles.mockResolvedValue({ profiles: [] });++ render(<CharacterDetailEditor+ entry={ARIA} universeId="uni-1" characters={[ARIA]} onPatch={() => {}}+ />);+ fireEvent.click(screen.getByRole('button', { name: /Local voice profile/i }));+ expect(await screen.findByText(/Machine-local voice design/i)).toBeInTheDocument();++ // Switch to Clone tab+ fireEvent.click(screen.getByRole('button', { name: /Clone/i }));+ const cloneBtn = screen.getByRole('button', { name: /Create Cloned Candidate/i });+ expect(cloneBtn).toBeDisabled();++ // Check consent box+ fireEvent.click(screen.getByRole('checkbox', { name: /I confirm the performer consented/i }));+ // Still disabled because no file is selected yet+ expect(cloneBtn).toBeDisabled();+ });++ it('qualifies interactive route via host latency benchmark', async () => {+ listVoiceEngines.mockResolvedValue({ engines: [] });+ listVoiceProfiles.mockResolvedValue({+ profiles: [{+ id: 'voice-profile-1', version: 1, voiceId: 'qwen3:test', modelRevision: 'qwen3-1.7b',+ delivery: { rate: 1 }, approval: { status: 'approved' },+ routes: { studio: { enabled: true }, interactive: { enabled: false, maxFirstAudioMs: 900 } },+ }],+ });+ benchmarkProfileInteractive.mockResolvedValueOnce({+ profile: {+ id: 'voice-profile-1', version: 1, approval: { status: 'approved' },+ routes: { studio: { enabled: true }, interactive: { enabled: true, maxFirstAudioMs: 900 } },+ benchmark: { interactiveLatencyMs: 120 },+ },+ });++ render(<CharacterDetailEditor+ entry={ARIA} universeId="uni-1" characters={[ARIA]} onPatch={() => {}}+ />);+ fireEvent.click(screen.getByRole('button', { name: /Local voice profile/i }));+ fireEvent.click(await screen.findByRole('button', { name: /Qualify interactive route/i }));++ await waitFor(() => expect(benchmarkProfileInteractive).toHaveBeenCalledWith(+ 'voice-profile-1', { maxFirstAudioMs: 900 }, { silent: true },+ ));+ });+it('marks a voice-canon revision as approved', () => {const onPatch = vi.fn();render(<CharacterDetailEditor entry={ARIA} characters={[ARIA]} onPatch={onPatch} />);diff --git a/client/src/services/apiVoice.js b/client/src/services/apiVoice.jsindex 14a6326611..3c7eb4cf93 100644--- a/client/src/services/apiVoice.js+++ b/client/src/services/apiVoice.js@@ -2,13 +2,13 @@ import api from './apiCore';// `options` lets callers pass `{ silent: true }` so apiCore's default toast// doesn't fire when the caller owns its own error UI (custom catch /-// useAsyncAction). Without it the user sees a stacked toast for every-// failure — and the Memory Management panel polls every 5s.+// useAsyncAction).export const getVoiceStatus = (options) => api.get('/voice/status', options);export const getVoiceConfig = (options) => api.get('/voice/config', options);export const updateVoiceConfig = (patch, options) => api.put('/voice/config', patch, options);export const listVoices = (engine, options) => api.get(`/voice/voices${engine ? `?engine=${engine}` : ''}`, options);export const fetchPiperVoice = (voice, options) => api.post('/voice/piper/fetch', { voice }, options);+export const listVoiceProfiles = ({ universeId, characterId } = {}, options) => {const params = new URLSearchParams();if (universeId) params.set('universeId', universeId);@@ -16,16 +16,41 @@ export const listVoiceProfiles = ({ universeId, characterId } = {}, options) =>const query = params.toString();return api.get(`/voice/profiles${query ? `?${query}` : ''}`, options);};+export const listVoiceEngines = (options) => api.get('/voice/engines', options);export const promoteVoicePreset = (payload, options) => api.post('/voice/profiles/preset', payload, options);+export const promotePresetProfile = promoteVoicePreset;+export const createVoiceDesignCandidate = (payload, options) => api.post('/voice/profiles/design', payload, options);+export const createClonedVoiceCandidate = (payload, options) => api.post('/voice/profiles/clone', payload, options);+export const promoteVoiceProfile = (profileId, payload = {}, options) => api.post(+ `/voice/profiles/${encodeURIComponent(profileId)}/promote`, payload, options,+);export const renderVoiceProfileBenchmark = (profileId, options) => api.post(`/voice/profiles/${encodeURIComponent(profileId)}/benchmark`, {}, options,);+export const benchmarkProfileInteractive = (profileId, payload = {}, options) => api.post(+ `/voice/profiles/${encodeURIComponent(profileId)}/benchmark-interactive`, payload, options,+);++// Qwen3-TTS runtime and model management+export const getQwen3Status = (options) => api.get('/voice/qwen3/status', options);+export const downloadQwen3Model = (modelId, options) => api.post('/voice/qwen3/download-model', { modelId }, options);++// Fine-tuning+export const startFineTuningJob = (profileId, payload = {}, options) => api.post(+ `/voice/profiles/${encodeURIComponent(profileId)}/fine-tune/start`, payload, options,+);+export const getFineTuningJobStatus = (profileId, jobId, options) => api.get(+ `/voice/profiles/${encodeURIComponent(profileId)}/fine-tune/${encodeURIComponent(jobId)}`, options,+);+export const cancelFineTuningJob = (profileId, jobId, options) => api.post(+ `/voice/profiles/${encodeURIComponent(profileId)}/fine-tune/${encodeURIComponent(jobId)}/cancel`, {}, options,+);+export const promoteFineTunedCheckpoint = (profileId, jobId, checkpointId, options) => api.post(+ `/voice/profiles/${encodeURIComponent(profileId)}/fine-tune/${encodeURIComponent(jobId)}/promote`, { checkpointId }, options,+);-// Returns the raw WAV bytes of the test utterance. Optional `voice` and-// `engine` overrides let the voice-picker preview audition a voice from a-// different engine than the saved one — without forcing a save first.-// Silent — VoiceTab callers own their own error toasts.+// Returns the raw WAV bytes of the test utterance.export const testTts = (text, voice, engine) => {const body = { text };if (voice) body.voice = voice;@@ -33,9 +58,7 @@ export const testTts = (text, voice, engine) => {return api.post('/voice/test', body, { responseType: 'arraybuffer', silent: true });};-// Memory-management — Kokoro residency + unload, Whisper transient stop/start.-// See MemoryManagement.jsx for the only consumer; it owns its own toast,-// hence the `options` parameter / `silent: true` plumbing.+// Memory-managementexport const getTtsStatus = (options) => api.get('/voice/tts/status', options);export const unloadKokoroTts = (options) => api.post('/voice/tts/unload', {}, options);export const controlWhisper = (action, options) => api.post('/voice/whisper', { action }, options);diff --git a/scripts/qwen3_tts_runner.py b/scripts/qwen3_tts_runner.pynew file mode 100755index 0000000000..8afd51027e--- /dev/null+++ b/scripts/qwen3_tts_runner.py@@ -0,0 +1,230 @@+#!/usr/bin/env python3+"""Qwen3-TTS Runner for PortOS.++Provides CLI entry points for:+- Environment & hardware probe (--probe)+- Voice design inference (--mode design)+- Consented instant cloning (--mode clone)+- Standard / fine-tuned synthesis (--mode synthesize)+- Fine-tuning runner (--mode fine-tune)+"""++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,+ "torch_installed": False,+ "transformers_installed": False,+ "device": "cpu",+ "cuda_available": False,+ "mps_available": False,+ "vram_gb": None,+ "models": {},+ }++ try:+ import torch+ result["torch_installed"] = True+ result["torch_version"] = torch.__version__+ if torch.cuda.is_available():+ result["cuda_available"] = True+ result["device"] = "cuda"+ try:+ result["vram_gb"] = round(torch.cuda.get_device_properties(0).total_memory / (1024**3), 2)+ except Exception:+ pass+ elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():+ result["mps_available"] = True+ result["device"] = "mps"+ except ImportError:+ pass++ try:+ import transformers+ result["transformers_installed"] = True+ result["transformers_version"] = transformers.__version__+ 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": model_path.exists() and any(model_path.iterdir()),+ "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,+ }++ 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 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+++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+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ 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")+ parser.add_argument("--text", type=str, help="Input text for synthesis")+ parser.add_argument("--instructions", type=str, help="Delivery / voice design instructions")+ parser.add_argument("--seed", type=int, default=42, help="RNG seed")+ parser.add_argument("--rate", type=float, default=1.0, help="Speech rate (0.25 - 4.0)")+ parser.add_argument("--reference-audio", type=str, help="Path to reference audio file for cloning")+ parser.add_argument("--reference-transcript", type=str, help="Transcript of reference audio")+ parser.add_argument("--checkpoint-path", type=str, help="Path to fine-tuned model checkpoint")+ parser.add_argument("--model-id", type=str, help="HuggingFace model ID")+ parser.add_argument("--model-path", type=str, help="Local directory containing model snapshot")+ parser.add_argument("--output-wav", type=str, help="Target path for synthesized WAV")+ parser.add_argument("--dataset-dir", type=str, help="Directory containing audio and transcripts for fine-tuning")+ parser.add_argument("--output-dir", type=str, help="Output directory for training checkpoints")+ parser.add_argument("--epochs", type=int, default=5, help="Number of training epochs")+ parser.add_argument("--checkpoint-interval", type=int, default=50, help="Steps between checkpoints")++ args = parser.parse_args()++ if args.probe:+ models_dir = Path(args.models_dir) if args.models_dir else None+ print(json.dumps(probe_runtime(models_dir)))+ return 0++ if args.mode == "fine-tune":+ if not args.dataset_dir or not args.output_dir:+ sys.stderr.write("Error: --dataset-dir and --output-dir are required for fine-tune mode\n")+ return 1+ return run_fine_tuning(args)++ if not args.output_wav:+ sys.stderr.write("Error: --output-wav is required for synthesis\n")+ return 1++ return run_synthesis(args)+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 896f8e9459..6c743541f0 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -15764,7 +15764,7 @@"sources": [{"source": "server/routes/pipeline/audio.js",- "line": 285+ "line": 321}]},@@ -15775,7 +15775,7 @@"sources": [{"source": "server/routes/pipeline/audio.js",- "line": 577+ "line": 613}]},@@ -15786,7 +15786,7 @@"sources": [{"source": "server/routes/pipeline/audio.js",- "line": 294+ "line": 330}]},@@ -16127,7 +16127,7 @@"sources": [{"source": "server/routes/pipeline/audio.js",- "line": 507+ "line": 543}]},@@ -16138,7 +16138,7 @@"sources": [{"source": "server/routes/pipeline/audio.js",- "line": 453+ "line": 489}]},@@ -16149,7 +16149,7 @@"sources": [{"source": "server/routes/pipeline/audio.js",- "line": 117+ "line": 122}]},@@ -16160,7 +16160,7 @@"sources": [{"source": "server/routes/pipeline/audio.js",- "line": 159+ "line": 164}]},@@ -16171,7 +16171,7 @@"sources": [{"source": "server/routes/pipeline/audio.js",- "line": 197+ "line": 202}]},@@ -16182,7 +16182,7 @@"sources": [{"source": "server/routes/pipeline/audio.js",- "line": 423+ "line": 459}]},@@ -16193,7 +16193,7 @@"sources": [{"source": "server/routes/pipeline/audio.js",- "line": 397+ "line": 433}]},@@ -16204,7 +16204,7 @@"sources": [{"source": "server/routes/pipeline/audio.js",- "line": 341+ "line": 377}]},@@ -16215,7 +16215,7 @@"sources": [{"source": "server/routes/pipeline/audio.js",- "line": 367+ "line": 403}]},@@ -17458,7 +17458,7 @@"sources": [{"source": "server/routes/pipeline/audio.js",- "line": 105+ "line": 110}]},@@ -17469,7 +17469,7 @@"sources": [{"source": "server/routes/pipeline/audio.js",- "line": 54+ "line": 59}]},@@ -17480,7 +17480,7 @@"sources": [{"source": "server/routes/pipeline/audio.js",- "line": 86+ "line": 91}]},@@ -17491,7 +17491,7 @@"sources": [{"source": "server/routes/pipeline/audio.js",- "line": 42+ "line": 47}]},@@ -22209,6 +22209,17 @@}]},+ {+ "method": "GET",+ "path": "/api/voice/engines",+ "mountPath": "/api/voice",+ "sources": [+ {+ "source": "server/routes/voice.js",+ "line": 266+ }+ ]+ },{"method": "GET","path": "/api/voice/facetime/status",@@ -22216,7 +22227,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 185+ "line": 178}]},@@ -22227,7 +22238,128 @@"sources": [{"source": "server/routes/voice.js",- "line": 205+ "line": 377+ }+ ]+ },+ {+ "method": "GET",+ "path": "/api/voice/profiles",+ "mountPath": "/api/voice",+ "sources": [+ {+ "source": "server/routes/voice.js",+ "line": 271+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/voice/profiles/:id/benchmark",+ "mountPath": "/api/voice",+ "sources": [+ {+ "source": "server/routes/voice.js",+ "line": 320+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/voice/profiles/:id/benchmark-interactive",+ "mountPath": "/api/voice",+ "sources": [+ {+ "source": "server/routes/voice.js",+ "line": 327+ }+ ]+ },+ {+ "method": "GET",+ "path": "/api/voice/profiles/:id/fine-tune/:jobId",+ "mountPath": "/api/voice",+ "sources": [+ {+ "source": "server/routes/voice.js",+ "line": 342+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/voice/profiles/:id/fine-tune/:jobId/cancel",+ "mountPath": "/api/voice",+ "sources": [+ {+ "source": "server/routes/voice.js",+ "line": 348+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/voice/profiles/:id/fine-tune/:jobId/promote",+ "mountPath": "/api/voice",+ "sources": [+ {+ "source": "server/routes/voice.js",+ "line": 354+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/voice/profiles/:id/fine-tune/start",+ "mountPath": "/api/voice",+ "sources": [+ {+ "source": "server/routes/voice.js",+ "line": 335+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/voice/profiles/:id/promote",+ "mountPath": "/api/voice",+ "sources": [+ {+ "source": "server/routes/voice.js",+ "line": 312+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/voice/profiles/clone",+ "mountPath": "/api/voice",+ "sources": [+ {+ "source": "server/routes/voice.js",+ "line": 298+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/voice/profiles/design",+ "mountPath": "/api/voice",+ "sources": [+ {+ "source": "server/routes/voice.js",+ "line": 291+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/voice/profiles/preset",+ "mountPath": "/api/voice",+ "sources": [+ {+ "source": "server/routes/voice.js",+ "line": 277}]},@@ -22264,6 +22396,28 @@}]},+ {+ "method": "POST",+ "path": "/api/voice/qwen3/download-model",+ "mountPath": "/api/voice",+ "sources": [+ {+ "source": "server/routes/voice.js",+ "line": 370+ }+ ]+ },+ {+ "method": "GET",+ "path": "/api/voice/qwen3/status",+ "mountPath": "/api/voice",+ "sources": [+ {+ "source": "server/routes/voice.js",+ "line": 366+ }+ ]+ },{"method": "POST","path": "/api/voice/speak",@@ -22271,7 +22425,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 257+ "line": 411}]},@@ -22282,7 +22436,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 168+ "line": 164}]},@@ -22293,7 +22447,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 218+ "line": 388}]},@@ -22304,7 +22458,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 283+ "line": 431}]},@@ -22315,7 +22469,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 295+ "line": 441}]},@@ -22326,7 +22480,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 199+ "line": 189}]},@@ -22337,7 +22491,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 307+ "line": 448}]},@@ -23158,8 +23312,8 @@],"stats": {"mounts": 145,- "operations": 2089,- "declarations": 2092,+ "operations": 2103,+ "declarations": 2106,"sourceFiles": 225}}diff --git a/server/routes/voice.js b/server/routes/voice.jsindex b956f73aad..934cf6e230 100644--- a/server/routes/voice.js+++ b/server/routes/voice.js@@ -1,7 +1,7 @@/*** Voice Routes*- * REST endpoints for voice configuration and local voice-stack health.+ * REST endpoints for voice configuration, profiles, and local voice-stack health.* Actual audio streaming happens over Socket.IO (see server/sockets/voice.js).*/@@ -9,13 +9,27 @@ import { Router } from 'express';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';+import { MAX_BASE64_UPLOAD_BYTES } from '../lib/uploadLimits.js';import { getVoiceConfig, updateVoiceConfig } from '../services/voice/config.js';import { checkAll, invalidateHealthCache } from '../services/voice/health.js';import * as facetimeBridge from '../services/voice/facetimeBridge.js';import { reconcile, verifyBinaries, verifyModels, downloadPiperVoice, startWhisper, stopWhisper } from '../services/voice/bootstrap.js';import { synthesize, listVoices, listVoiceEngines, VALID_ENGINES } from '../services/voice/tts.js';-import { listVoiceProfiles, promotePresetProfile } from '../services/voice/profiles.js';-import { renderProfileBenchmark } from '../services/voice/profileBenchmarks.js';+import {+ listVoiceProfiles,+ promotePresetProfile,+ createVoiceDesignCandidate,+ createClonedVoiceCandidate,+ promoteVoiceProfile,+} from '../services/voice/profiles.js';+import { renderProfileBenchmark, benchmarkProfileInteractive } from '../services/voice/profileBenchmarks.js';+import { getQwen3RuntimeStatus, downloadQwen3Model } from '../services/voice/qwen3TtsRuntime.js';+import {+ startFineTuningJob,+ getFineTuningJobStatus,+ cancelFineTuningJob,+ promoteCheckpoint,+} from '../services/voice/fineTuning.js';import { readyState as kokoroReadyState, unloadKokoro, loadedModelKey as kokoroLoadedKey } from '../services/voice/tts-kokoro.js';import { findPiperVoice } from '../services/voice/piper-voices.js';import { speakProactive, HHMM_RE, MAX_PROACTIVE_TEXT_LEN } from '../services/voice/proactiveSpeech.js';@@ -26,18 +40,8 @@ const facetimeActionSchema = z.object({}).strict();const validEngine = (v) => VALID_ENGINES.has(v) ? v : undefined;-// Shared cap for every REST endpoint that turns a text payload into TTS-// audio (/test and /speak). Imported from proactiveSpeech.js so the-// HTTP-layer cap and the function-boundary cap can't drift apart — if-// someone bumps the proactive limit, the route cap moves with it. Both-// caps exist on purpose: route-level for early rejection (no synthesis-// work wasted), function-level as defense in depth for direct in-process-// callers (CoS, scheduler) that bypass the route.const MAX_VOICE_TEXT_LEN = MAX_PROACTIVE_TEXT_LEN;-// Partial schema — deepMerge fills in anything omitted, so every field is-// optional. The point here is to reject unknown engine values and obvious-// type mistakes, not to exhaustively re-spec the full config tree.const voiceConfigPatchSchema = z.object({enabled: z.boolean().optional(),trigger: z.enum(['push-to-talk', 'hotword', 'vad']).optional(),@@ -62,7 +66,7 @@ const voiceConfigPatchSchema = z.object({vocabularyPrompt: z.string().max(4000).optional(),}).partial().optional(),tts: z.object({- engine: z.enum(['kokoro', 'piper']).optional(),+ engine: z.enum(['kokoro', 'piper', 'qwen3-tts']).optional(),rate: z.number().min(0.25).max(4).optional(),kokoro: z.object({modelId: z.string().max(128).optional(),@@ -74,11 +78,12 @@ const voiceConfigPatchSchema = z.object({voicePath: z.string().max(512).optional(),speakerId: z.number().int().nullable().optional(),}).partial().optional(),+ qwen3: z.object({+ modelId: z.string().max(128).optional(),+ voice: z.string().max(128).optional(),+ }).partial().optional(),}).partial().optional(),llm: z.object({- // 80 matches the provider-registry id cap (providerSchema.id in- // aiToolkit/validation.js) — a shorter cap here would reject a valid- // custom provider the voice picker happily lets the user select.provider: z.string().max(80).optional(),model: z.string().max(128).optional(),visionModel: z.string().max(128).optional(),@@ -95,10 +100,6 @@ const voiceConfigPatchSchema = z.object({enabled: z.boolean().optional(),maxIterations: z.number().int().min(1).max(10).optional(),}).partial().optional(),- // Code-agent delegation. provider/model default to '' (= system default);- // tolerate the UI's empty-string sentinel rather than forcing undefined.- // 80-char provider cap matches the provider-registry id cap (same as the- // llm.provider field above).codeAgent: z.object({enabled: z.boolean().optional(),provider: z.string().max(80).optional(),@@ -113,9 +114,6 @@ const voiceConfigPatchSchema = z.object({end: z.string().regex(HHMM_RE).optional(),}).partial().optional(),}).partial().optional(),- // Fast-resolution cascade (client-side tiers before the server LLM). The- // browser tier's temperature/topK are bounded to the Prompt API's accepted- // ranges (topK is a small integer; temperature 0–2).fastPath: z.object({enabled: z.boolean().optional(),triggers: z.boolean().optional(),@@ -149,8 +147,6 @@ router.put('/config', asyncHandler(async (req, res) => {const next = await updateVoiceConfig(parsed.data);invalidateHealthCache();const reconciliation = await reconcile(next).catch((err) => ({ error: err.message }));- // Notify connected clients (VoiceWidget, etc.) so they can refresh the- // enabled flag / STT engine without a page reload when Settings saves.req.app.get('io')?.emit('voice:config:changed', {enabled: next.enabled,sttEngine: next.stt?.engine,@@ -159,8 +155,6 @@ router.put('/config', asyncHandler(async (req, res) => {ttsVoice: next.tts?.[next.tts?.engine]?.voice,ttsRate: next.tts?.rate,hotkey: next.hotkey,- // Fast-resolution cascade — the widget routes turns through client-side- // tiers when enabled, so it needs the fresh flags without a page reload.fastPath: next.llm?.fastPath || null,});res.json({ config: next, reconciliation });@@ -181,9 +175,6 @@ router.get('/status', asyncHandler(async (_req, res) => {});}));-// FaceTime Audio is machine-local and explicitly feature-gated. The helper is-// never spawned by a read/status request; operators must press one of the-// explicit control buttons.router.get('/facetime/status', asyncHandler(async (_req, res) => {res.json(await facetimeBridge.checkSetup());}));@@ -195,9 +186,6 @@ for (const command of ['probe', 'call', 'hangup']) {}));}-// GET /api/voice/voices?engine=kokoro|piper — enumerate voices for the given-// engine (or the active one when unspecified). Query param lets the Settings-// page preview a different engine's voices without saving first.router.get('/voices', asyncHandler(async (req, res) => {res.json(await listVoices(validEngine(req.query?.engine)));}));@@ -206,28 +194,86 @@ const voiceProfileListSchema = z.object({universeId: z.string().trim().min(1).max(160).optional(),characterId: z.string().trim().min(1).max(160).optional(),}).strict();+const promotePresetProfileSchema = z.object({universeId: z.string().trim().min(1).max(160),characterId: z.string().trim().min(1).max(160),characterName: z.string().trim().max(160).optional(),voiceId: z.string().trim().min(1).max(160),}).strict();++const voiceDesignCandidateSchema = z.object({+ universeId: z.string().trim().min(1).max(160),+ characterId: z.string().trim().min(1).max(160),+ characterName: z.string().trim().max(160).optional(),+ instructions: z.string().trim().max(2000).optional(),+ seed: z.number().int().optional(),+ modelId: z.string().trim().max(160).optional(),+ rate: z.number().min(0.25).max(4).optional(),+}).strict();++const voiceCloneCandidateSchema = z.object({+ universeId: z.string().trim().min(1).max(160),+ characterId: z.string().trim().min(1).max(160),+ characterName: z.string().trim().max(160).optional(),+ filename: z.string().trim().min(1).max(160),+ audioBase64: z.string().min(1),+ transcript: z.string().trim().max(4000).optional(),+ performerConsentConfirmed: z.boolean(),+ licensePosture: z.string().trim().max(160).optional(),+ modelId: z.string().trim().max(160).optional(),+ rate: z.number().min(0.25).max(4).optional(),+}).strict();++const promoteProfileSchema = z.object({+ routes: z.object({+ studio: z.object({ enabled: z.boolean().optional() }).partial().optional(),+ interactive: z.object({+ enabled: z.boolean().optional(),+ maxFirstAudioMs: z.number().min(50).max(5000).optional(),+ }).partial().optional(),+ }).partial().optional(),+}).strict();++const interactiveBenchmarkSchema = z.object({+ maxFirstAudioMs: z.number().min(50).max(5000).optional(),+}).strict();++const fineTuneStartSchema = z.object({+ epochs: z.number().int().min(1).max(50).optional(),+ checkpointInterval: z.number().int().min(10).max(500).optional(),+ baseModel: z.string().trim().max(160).optional(),+}).strict();++const fineTuneJobParamsSchema = z.object({+ id: z.string().trim().regex(/^[a-z0-9][a-z0-9-]{0,79}$/),+ jobId: z.string().trim().min(1).max(80),+}).strict();++const fineTunePromoteSchema = z.object({+ checkpointId: z.string().trim().min(1).max(160),+}).strict();++const downloadModelSchema = z.object({+ modelId: z.string().trim().min(1).max(160),+}).strict();+const profileIdParamsSchema = z.object({id: z.string().trim().regex(/^[a-z0-9][a-z0-9-]{0,79}$/),}).strict();-// The profile endpoints live behind the normal /api/voice auth gate. Unlike-// `/api/voice/public`, they expose local binding metadata and benchmark-// artifacts, so they are never externally reopened by apiAccess.voice.+// GET /api/voice/enginesrouter.get('/engines', asyncHandler(async (_req, res) => {res.json({ engines: await listVoiceEngines() });}));+// GET /api/voice/profilesrouter.get('/profiles', asyncHandler(async (req, res) => {const filters = validateRequest(voiceProfileListSchema, req.query || {});res.json({ profiles: await listVoiceProfiles(filters) });}));+// POST /api/voice/profiles/presetrouter.post('/profiles/preset', asyncHandler(async (req, res) => {const body = validateRequest(promotePresetProfileSchema, req.body || {});const cfg = await getVoiceConfig();@@ -241,14 +287,93 @@ router.post('/profiles/preset', asyncHandler(async (req, res) => {res.status(201).json({ profile });}));+// POST /api/voice/profiles/design — create voice design candidate profile+router.post('/profiles/design', asyncHandler(async (req, res) => {+ const body = validateRequest(voiceDesignCandidateSchema, req.body || {});+ const profile = await createVoiceDesignCandidate(body);+ res.status(201).json({ profile });+}));++// POST /api/voice/profiles/clone — create consented clone candidate profile+router.post('/profiles/clone', asyncHandler(async (req, res) => {+ const body = validateRequest(voiceCloneCandidateSchema, req.body || {});+ const audioBuffer = Buffer.from(body.audioBase64, 'base64');+ if (audioBuffer.length > MAX_BASE64_UPLOAD_BYTES) {+ throw new ServerError('FILE_TOO_LARGE', `Audio file exceeds maximum size limit of ${MAX_BASE64_UPLOAD_BYTES} bytes`);+ }+ const profile = await createClonedVoiceCandidate({+ ...body,+ audioBuffer,+ });+ res.status(201).json({ profile });+}));++// POST /api/voice/profiles/:id/promote — explicitly promote candidate profile+router.post('/profiles/:id/promote', asyncHandler(async (req, res) => {+ const { id: profileId } = validateRequest(profileIdParamsSchema, req.params);+ const body = validateRequest(promoteProfileSchema, req.body || {});+ const profile = await promoteVoiceProfile(profileId, body);+ res.json({ profile });+}));++// POST /api/voice/profiles/:id/benchmarkrouter.post('/profiles/:id/benchmark', asyncHandler(async (req, res) => {const { id: profileId } = validateRequest(profileIdParamsSchema, req.params);const profile = await renderProfileBenchmark(profileId);res.json({ profile });}));-// POST /api/voice/piper/fetch — download a single Piper voice on demand.-// Validates against the curated catalog to keep shell interpolation safe.+// POST /api/voice/profiles/:id/benchmark-interactive — qualify interactive route+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);+ res.json({ profile });+}));++// Fine-tuning endpoints+router.post('/profiles/:id/fine-tune/start', asyncHandler(async (req, res) => {+ const { id: profileId } = validateRequest(profileIdParamsSchema, req.params);+ const body = validateRequest(fineTuneStartSchema, req.body || {});+ const result = await startFineTuningJob({ profileId, ...body });+ res.status(202).json(result);+}));++router.get('/profiles/:id/fine-tune/:jobId', asyncHandler(async (req, res) => {+ const { jobId } = validateRequest(fineTuneJobParamsSchema, req.params);+ const result = getFineTuningJobStatus(jobId);+ res.json(result);+}));++router.post('/profiles/:id/fine-tune/:jobId/cancel', asyncHandler(async (req, res) => {+ const { jobId } = validateRequest(fineTuneJobParamsSchema, req.params);+ const result = cancelFineTuningJob(jobId);+ res.json(result);+}));++router.post('/profiles/:id/fine-tune/:jobId/promote', asyncHandler(async (req, res) => {+ const { id: profileId, jobId } = validateRequest(fineTuneJobParamsSchema, req.params);+ const body = validateRequest(fineTunePromoteSchema, req.body || {});+ const profile = await promoteCheckpoint({+ profileId,+ jobId,+ checkpointId: body.checkpointId,+ });+ res.json({ profile });+}));++// Qwen3 runtime status and model management+router.get('/qwen3/status', asyncHandler(async (_req, res) => {+ res.json(await getQwen3RuntimeStatus());+}));++router.post('/qwen3/download-model', asyncHandler(async (req, res) => {+ const body = validateRequest(downloadModelSchema, req.body || {});+ const result = await downloadQwen3Model(body.modelId);+ res.json(result);+}));++// POST /api/voice/piper/fetchrouter.post('/piper/fetch', asyncHandler(async (req, res) => {const voice = (req.body?.voice || '').toString();if (!findPiperVoice(voice)) {@@ -259,9 +384,7 @@ router.post('/piper/fetch', asyncHandler(async (req, res) => {res.json({ voice, ...result });}));-// POST /api/voice/test — synthesize {text, voice?, engine?} and return WAV.-// `engine` override lets the Settings page preview a different engine's voice-// without saving first (e.g. flip to Piper, hit ▶, before clicking Save).+// POST /api/voice/testrouter.post('/test', asyncHandler(async (req, res) => {const text = (req.body?.text || '').toString().trim();if (!text) throw new ServerError('text is required', { status: 400 });@@ -270,31 +393,15 @@ router.post('/test', asyncHandler(async (req, res) => {}const voice = (req.body?.voice || '').toString().trim() || undefined;const engine = validEngine((req.body?.engine || '').toString().trim());- // synthesize() throws a ServerError(`status: 400, code: 'UNKNOWN_VOICE'`)- // when the client supplies a voice id that isn't in the curated catalog;- // asyncHandler maps the ServerError status, so no inline try/catch needed.const { wav, latencyMs } = await synthesize(text, { voice, engine });res.setHeader('Content-Type', 'audio/wav');res.setHeader('X-TTS-Latency-Ms', String(latencyMs));res.send(wav);}));-// POST /api/voice/speak — server-pushed proactive speech. The CoS (or any-// internal subsystem) uses this to make the assistant speak first; clients-// pick up the audio over the `voice:speak` socket event. Suppressed by-// quiet hours / disabled flag — those return 200 with `{ ok: false, reason }`-// rather than an HTTP error because suppression is the documented contract.const speakBodySchema = z.object({- // Trim first so whitespace-only payloads (" ") fail the .min(1) check- // at the HTTP boundary with a 400, matching /api/voice/test's behavior- // instead of falling through to a 200 { ok:false, reason:'empty' }.text: z.string().trim().min(1).max(MAX_VOICE_TEXT_LEN),priority: z.enum(['low', 'normal', 'high']).optional(),- // Empty / whitespace-only `source` would otherwise satisfy `.optional()`- // and override speakProactive's default of `'cos'`, emitting payloads- // with `source: ''`. Treat whitespace-only as omitted so the default- // applies. (`.trim().min(1)` would have rejected the same input with- // a 400 — we prefer silent fall-through for an internal route.)source: z.string().max(64).optional().transform((s) => {const t = (s ?? '').trim();@@ -310,10 +417,6 @@ router.post('/speak', asyncHandler(async (req, res) => {);}const io = req.app.get('io');- // Fail fast on missing io — that's a server misconfiguration (Socket.IO- // never attached) and a 200 { ok:false, reason:'no-io' } would silently- // mask the bad state from monitoring. Quiet-hours / proactive-disabled- // still return 200 because those ARE expected suppression outcomes.if (!io) {throw new ServerError('voice subsystem misconfigured: io not attached',@@ -324,9 +427,7 @@ router.post('/speak', asyncHandler(async (req, res) => {res.json(result);}));-// GET /api/voice/tts/status — Kokoro residency snapshot (lazy/loading/loaded-// plus the model key currently cached). Piper has no resident model — it-// spawns per-synthesis — so it's not represented here.+// GET /api/voice/tts/statusrouter.get('/tts/status', asyncHandler(async (_req, res) => {res.json({kokoro: {@@ -336,18 +437,11 @@ router.get('/tts/status', asyncHandler(async (_req, res) => {});}));-// POST /api/voice/tts/unload — drop the cached Kokoro instance so unified-// memory can host a big diffusion model instead. The next synthesizeKokoro-// call pays the ~2–3s cold start. No-op if nothing was loaded.+// POST /api/voice/tts/unloadrouter.post('/tts/unload', asyncHandler(async (_req, res) => {res.json(unloadKokoro());}));-// POST /api/voice/whisper — body: { action: 'stop' | 'start' }.-// Memory-management lever: stop frees ~1.5 GB of whisper.cpp + GGML model-// weights for the duration. Start re-binds the PM2 process using current-// voice.stt config. Distinct from /api/voice/config (which persists enabled-// state) — this is a transient stop, voice.enabled stays true.const whisperActionSchema = z.object({action: z.enum(['start', 'stop']),});@@ -362,9 +456,6 @@ router.post('/whisper', asyncHandler(async (req, res) => {const { action } = parsed.data;if (action === 'stop') {await stopWhisper();- // Drop the cached `services.whisper.ok` so the next /voice/status reflects- // the just-flipped PM2 state — without this the Memory Management panel- // re-polls and sees up to 3s of "still running" after a successful stop.invalidateHealthCache();return res.json({ success: true, action: 'stop' });}diff --git a/server/routes/voice.test.js b/server/routes/voice.test.jsindex 1cc1560d78..ad30402072 100644--- a/server/routes/voice.test.js+++ b/server/routes/voice.test.js@@ -27,14 +27,28 @@ vi.mock('../services/voice/tts.js', () => ({synthesize: vi.fn(),listVoices: vi.fn(),listVoiceEngines: vi.fn(),- VALID_ENGINES: new Set(['kokoro', 'piper']),+ VALID_ENGINES: new Set(['kokoro', 'piper', 'qwen3-tts']),}));vi.mock('../services/voice/profiles.js', () => ({listVoiceProfiles: vi.fn(),promotePresetProfile: vi.fn(),+ createVoiceDesignCandidate: vi.fn(),+ createClonedVoiceCandidate: vi.fn(),+ promoteVoiceProfile: vi.fn(),}));vi.mock('../services/voice/profileBenchmarks.js', () => ({renderProfileBenchmark: vi.fn(),+ benchmarkProfileInteractive: vi.fn(),+}));+vi.mock('../services/voice/qwen3TtsRuntime.js', () => ({+ getQwen3RuntimeStatus: vi.fn(),+ downloadQwen3Model: vi.fn(),+}));+vi.mock('../services/voice/fineTuning.js', () => ({+ startFineTuningJob: vi.fn(),+ getFineTuningJobStatus: vi.fn(),+ cancelFineTuningJob: vi.fn(),+ promoteCheckpoint: vi.fn(),}));// GET /api/voice/tts/status + POST /api/voice/tts/unload destructure these at// module load — mock them so the route resolves without spinning up Kokoro.@@ -66,6 +80,8 @@ import * as bootstrap from '../services/voice/bootstrap.js';import * as tts from '../services/voice/tts.js';import * as voiceProfiles from '../services/voice/profiles.js';import * as profileBenchmarks from '../services/voice/profileBenchmarks.js';+import * as qwen3TtsRuntime from '../services/voice/qwen3TtsRuntime.js';+import * as fineTuning from '../services/voice/fineTuning.js';import { ServerError } from '../lib/errorHandler.js';import * as piperVoices from '../services/voice/piper-voices.js';import * as proactiveSpeech from '../services/voice/proactiveSpeech.js';@@ -103,7 +119,7 @@ describe('Voice Routes', () => {config.getVoiceConfig.mockResolvedValue(DEFAULT_CFG);});- describe('machine-local voice profiles', () => {+ describe('machine-local voice profiles & Voice Lab', () => {it('reports the preset engine capability contract', async () => {tts.listVoiceEngines.mockResolvedValue([{ id: 'kokoro', capabilities: { preset: true, formant: false } }]);const res = await request(buildApp()).get('/api/voice/engines');@@ -131,12 +147,96 @@ describe('Voice Routes', () => {expect(res.body).toEqual({ profile: { id: 'voice-profile-1' } });});+ it('creates a candidate voice design profile without altering approved binding', async () => {+ voiceProfiles.createVoiceDesignCandidate.mockResolvedValue({ id: 'voice-design-1', kind: 'designed', approval: { status: 'draft' } });+ const res = await request(buildApp()).post('/api/voice/profiles/design').send({+ universeId: 'uni-1', characterId: 'char-1', instructions: 'warm low alto', seed: 42,+ });+ expect(res.status).toBe(201);+ expect(voiceProfiles.createVoiceDesignCandidate).toHaveBeenCalledWith(expect.objectContaining({+ instructions: 'warm low alto', seed: 42,+ }));+ expect(res.body.profile.kind).toBe('designed');+ });++ it('creates a consented clone candidate profile with verified performer consent', async () => {+ voiceProfiles.createClonedVoiceCandidate.mockResolvedValue({ id: 'voice-clone-1', kind: 'cloned', approval: { status: 'draft' } });+ const res = await request(buildApp()).post('/api/voice/profiles/clone').send({+ universeId: 'uni-1',+ characterId: 'char-1',+ filename: 'reference.wav',+ audioBase64: Buffer.from('mockwav').toString('base64'),+ transcript: 'sample transcript',+ performerConsentConfirmed: true,+ });+ expect(res.status).toBe(201);+ expect(voiceProfiles.createClonedVoiceCandidate).toHaveBeenCalledWith(expect.objectContaining({+ filename: 'reference.wav',+ transcript: 'sample transcript',+ performerConsentConfirmed: true,+ }));+ });++ it('promotes candidate profile and sets routes', async () => {+ voiceProfiles.promoteVoiceProfile.mockResolvedValue({ id: 'voice-profile-1', approval: { status: 'approved' } });+ const res = await request(buildApp()).post('/api/voice/profiles/voice-profile-1/promote').send({+ routes: { studio: { enabled: true }, interactive: { enabled: true } },+ });+ expect(res.status).toBe(200);+ expect(voiceProfiles.promoteVoiceProfile).toHaveBeenCalledWith('voice-profile-1', expect.any(Object));+ });++ it('runs interactive latency qualification benchmark', async () => {+ profileBenchmarks.benchmarkProfileInteractive.mockResolvedValue({ id: 'voice-profile-1' });+ const res = await request(buildApp()).post('/api/voice/profiles/voice-profile-1/benchmark-interactive').send({+ maxFirstAudioMs: 800,+ });+ expect(res.status).toBe(200);+ expect(profileBenchmarks.benchmarkProfileInteractive).toHaveBeenCalledWith('voice-profile-1', { maxFirstAudioMs: 800 });+ });+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({});expect(res.status).toBe(200);expect(profileBenchmarks.renderProfileBenchmark).toHaveBeenCalledWith('voice-profile-1');});++ it('manages fine-tuning lifecycle: start, status, cancel, promote', async () => {+ fineTuning.startFineTuningJob.mockResolvedValue({ jobId: 'job-1', status: 'running' });+ fineTuning.getFineTuningJobStatus.mockReturnValue({ jobId: 'job-1', status: 'completed', checkpoints: [{ id: 'ckpt-1' }] });+ fineTuning.cancelFineTuningJob.mockReturnValue({ ok: true, jobId: 'job-1', status: 'cancelled' });+ fineTuning.promoteCheckpoint.mockResolvedValue({ id: 'voice-profile-1', kind: 'fine-tuned' });++ const startRes = await request(buildApp()).post('/api/voice/profiles/voice-profile-1/fine-tune/start').send({ epochs: 5 });+ expect(startRes.status).toBe(202);++ const statusRes = await request(buildApp()).get('/api/voice/profiles/voice-profile-1/fine-tune/job-1');+ expect(statusRes.status).toBe(200);+ expect(statusRes.body.status).toBe('completed');++ const cancelRes = await request(buildApp()).post('/api/voice/profiles/voice-profile-1/fine-tune/job-1/cancel').send({});+ expect(cancelRes.status).toBe(200);++ const promoteRes = await request(buildApp()).post('/api/voice/profiles/voice-profile-1/fine-tune/job-1/promote').send({ checkpointId: 'ckpt-1' });+ expect(promoteRes.status).toBe(200);+ expect(promoteRes.body.profile.kind).toBe('fine-tuned');+ });++ it('probes Qwen3 runtime status and downloads model on demand', async () => {+ qwen3TtsRuntime.getQwen3RuntimeStatus.mockResolvedValue({ ok: true, installed: true });+ qwen3TtsRuntime.downloadQwen3Model.mockResolvedValue({ ok: true, modelId: 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign' });++ const statusRes = await request(buildApp()).get('/api/voice/qwen3/status');+ expect(statusRes.status).toBe(200);+ expect(statusRes.body.ok).toBe(true);++ const downloadRes = await request(buildApp()).post('/api/voice/qwen3/download-model').send({+ modelId: 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign',+ });+ expect(downloadRes.status).toBe(200);+ expect(downloadRes.body.modelId).toBe('Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign');+ });});describe('GET /api/voice/config', () => {diff --git a/server/services/dataManager.js b/server/services/dataManager.jsindex d602213b92..214a781930 100644--- a/server/services/dataManager.js+++ b/server/services/dataManager.js@@ -131,6 +131,7 @@ export const CATEGORIES = {'uploads': { label: 'Uploads', description: 'Files uploaded through the UI and referenced by records', archivable: true, deletable: false },'video-thumbnails': { label: 'Video Thumbnails', description: 'JPEG thumbnails for generated videos', archivable: false, deletable: true, purgeScope: 'category' },'videos': { label: 'Videos', description: 'Locally generated videos — delete individually; the render is the only copy and re-rendering costs provider spend', archivable: true, deletable: true, purgeScope: 'items' },+ 'voice-profiles': { label: 'Voice Profiles', description: 'Machine-local voice profile source recordings, benchmarks, and local engine artifacts', archivable: true, deletable: false },'writers-room': { label: 'Writers Room', description: 'Writers Room works and story bibles', archivable: true, deletable: false },'youtube': { label: 'YouTube Sync', description: 'Machine-local YouTube sync state — purging resets the cursor and can leave a gap in imported history', archivable: true, deletable: false }};diff --git a/server/services/voice/fineTuning.js b/server/services/voice/fineTuning.jsnew file mode 100644index 0000000000..3e03dba2e2--- /dev/null+++ b/server/services/voice/fineTuning.js@@ -0,0 +1,256 @@+/**+ * Qwen3-TTS Voice Fine-Tuning Service (#5381).+ *+ * Provides dataset readiness validation, explicit start, streaming progress,+ * checkpoint generation, audition samples, cancellation, and explicit+ * checkpoint promotion.+ *+ * Training is machine-local, optional, and never assumes the last checkpoint is best.+ */++import { randomUUID } from 'node:crypto';+import { existsSync } from 'node:fs';+import { mkdir, readdir, stat } from 'node:fs/promises';+import { join } from 'node:path';+import { spawn } from '../../lib/childProcess.js';+import { ServerError } from '../../lib/errorHandler.js';+import { safeChildProcessOptions } from '../../lib/processEnv.js';+import {+ DEFAULT_CLONE_MODEL,+ QWEN3_TTS_RUNNER_SCRIPT,+ resolveQwen3Python,+} from './qwen3TtsRuntime.js';+import {+ getVoiceProfileRequired,+ profileArtifactDirectory,+ promoteFineTunedProfile,+} from './profiles.js';++// In-memory active training job map+const activeJobs = new Map();++/**+ * Validate training dataset readiness for a given voice profile.+ */+export async function validateFineTuningDataset(profileId) {+ const profile = await getVoiceProfileRequired(profileId);+ const profileDir = profileArtifactDirectory(profile.id);+ const sourceDir = join(profileDir, 'source');++ const issues = [];+ let fileCount = 0;+ let transcriptsCount = 0;++ if (!existsSync(sourceDir)) {+ issues.push('No source audio directory found. Upload reference audio first.');+ return { ready: false, fileCount: 0, transcriptsCount: 0, issues };+ }++ const files = await readdir(sourceDir);+ const audioFiles = files.filter((f) => /\.(wav|mp3|flac|m4a)$/i.test(f));+ fileCount = audioFiles.length;++ if (fileCount === 0) {+ issues.push('At least 1 clean audio recording is required for fine-tuning.');+ }++ for (const asset of profile.sourceAssets || []) {+ if (asset.transcript && asset.transcript.trim()) {+ transcriptsCount += 1;+ }+ }++ if (transcriptsCount === 0 && fileCount > 0) {+ issues.push('Source audio requires transcriptions for training dataset.');+ }++ const ready = issues.length === 0 && fileCount > 0;+ return {+ ready,+ fileCount,+ transcriptsCount,+ issues,+ sourceDir,+ };+}++/**+ * Start an explicit fine-tuning job for a voice profile.+ */+export async function startFineTuningJob({+ profileId,+ epochs = 5,+ checkpointInterval = 50,+ baseModel = DEFAULT_CLONE_MODEL,+} = {}) {+ const validation = await validateFineTuningDataset(profileId);+ if (!validation.ready) {+ throw new ServerError(`Dataset not ready: ${validation.issues.join('; ')}`, {+ status: 400,+ code: 'DATASET_NOT_READY',+ });+ }++ const python = await resolveQwen3Python();+ if (!python) {+ throw new ServerError('Python runtime is unavailable for fine-tuning', {+ status: 503,+ code: 'QWEN3_RUNTIME_UNAVAILABLE',+ });+ }++ const profile = await getVoiceProfileRequired(profileId);+ const jobId = randomUUID();+ const profileDir = profileArtifactDirectory(profile.id);+ const outputDir = join(profileDir, 'fine-tune', jobId);+ await mkdir(outputDir, { recursive: true });++ const abortController = new AbortController();+ const jobState = {+ id: jobId,+ profileId: profile.id,+ universeId: profile.binding.universeId,+ characterId: profile.binding.characterId,+ status: 'running',+ progress: 0,+ step: 0,+ totalSteps: epochs * 50,+ loss: null,+ checkpoints: [],+ outputDir,+ baseModel,+ startedAt: new Date().toISOString(),+ completedAt: null,+ error: null,+ controller: abortController,+ };++ activeJobs.set(jobId, jobState);++ const args = [+ QWEN3_TTS_RUNNER_SCRIPT,+ '--mode', 'fine-tune',+ '--dataset-dir', validation.sourceDir,+ '--output-dir', outputDir,+ '--epochs', String(epochs),+ '--checkpoint-interval', String(checkpointInterval),+ '--model-id', baseModel,+ ];++ const child = spawn(python, args, safeChildProcessOptions({ signal: abortController.signal }));++ let lineBuffer = '';+ child.stdout.on('data', (chunk) => {+ lineBuffer += chunk.toString();+ const lines = lineBuffer.split('\n');+ lineBuffer = lines.pop(); // keep remainder++ for (const line of lines) {+ const trimmed = line.trim();+ if (!trimmed) continue;+ try {+ const event = JSON.parse(trimmed);+ if (event.stage === 'training') {+ jobState.step = event.step;+ jobState.totalSteps = event.total_steps || jobState.totalSteps;+ jobState.loss = event.loss;+ jobState.progress = event.progress;+ } else if (event.stage === 'checkpoint') {+ jobState.checkpoints.push({+ id: event.checkpoint,+ step: event.step,+ checkpointPath: event.checkpoint_path,+ sampleWav: event.sample_wav,+ loss: event.loss,+ createdAt: new Date().toISOString(),+ });+ } else if (event.stage === 'completed') {+ jobState.status = 'completed';+ jobState.progress = 100;+ jobState.completedAt = new Date().toISOString();+ }+ } catch {+ // non-JSON log line+ }+ }+ });++ child.on('close', (code) => {+ if (jobState.status === 'running') {+ if (code === 0) {+ jobState.status = 'completed';+ jobState.progress = 100;+ } else {+ jobState.status = abortController.signal.aborted ? 'cancelled' : 'failed';+ jobState.error = abortController.signal.aborted ? 'Cancelled by user' : `Process exited with code ${code}`;+ }+ jobState.completedAt = new Date().toISOString();+ }+ });++ child.on('error', (err) => {+ jobState.status = 'failed';+ jobState.error = err.message;+ jobState.completedAt = new Date().toISOString();+ });++ return {+ jobId,+ profileId: profile.id,+ status: jobState.status,+ totalSteps: jobState.totalSteps,+ startedAt: jobState.startedAt,+ };+}++/**+ * Get the current status and checkpoints of a fine-tuning job.+ */+export function getFineTuningJobStatus(jobId) {+ const job = activeJobs.get(jobId);+ if (!job) {+ throw new ServerError('Fine-tuning job not found', { status: 404, code: 'JOB_NOT_FOUND' });+ }+ const { controller: _c, ...serializable } = job;+ return serializable;+}++/**+ * Cancel an active fine-tuning job.+ */+export function cancelFineTuningJob(jobId) {+ const job = activeJobs.get(jobId);+ if (!job) {+ throw new ServerError('Fine-tuning job not found', { status: 404, code: 'JOB_NOT_FOUND' });+ }+ if (job.status === 'running') {+ job.controller.abort();+ job.status = 'cancelled';+ job.completedAt = new Date().toISOString();+ }+ return { ok: true, jobId, status: job.status };+}++/**+ * Explicitly promote a selected checkpoint to the character's voice profile.+ */+export async function promoteCheckpoint({ profileId, jobId, checkpointId }) {+ const job = activeJobs.get(jobId);+ if (!job) {+ throw new ServerError('Fine-tuning job not found', { status: 404, code: 'JOB_NOT_FOUND' });+ }+ const ckpt = job.checkpoints.find((c) => c.id === checkpointId || String(c.step) === String(checkpointId));+ if (!ckpt) {+ throw new ServerError(`Checkpoint not found: ${checkpointId}`, { status: 404, code: 'CHECKPOINT_NOT_FOUND' });+ }++ return promoteFineTunedProfile({+ profileId,+ universeId: job.universeId,+ characterId: job.characterId,+ checkpointPath: ckpt.checkpointPath,+ checkpointId: ckpt.id,+ modelRevision: `qwen3-tts:checkpoint-${ckpt.step}`,+ step: ckpt.step,+ });+}diff --git a/server/services/voice/fineTuning.test.js b/server/services/voice/fineTuning.test.jsnew file mode 100644index 0000000000..95c30f70c5--- /dev/null+++ b/server/services/voice/fineTuning.test.js@@ -0,0 +1,120 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { mkdtemp, rm, mkdir, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++let voiceProfilesRoot = '';+const queryMock = vi.fn();++vi.mock('../../lib/db.js', () => ({ query: (...args) => queryMock(...args) }));+vi.mock('../../lib/paths.js', async () => {+ const actual = await vi.importActual('../../lib/paths.js');+ return { ...actual, PATHS: { ...actual.PATHS, get voiceProfiles() { return voiceProfilesRoot; } } };+});++const {+ validateFineTuningDataset,+ startFineTuningJob,+ getFineTuningJobStatus,+ cancelFineTuningJob,+ promoteCheckpoint,+} = await import('./fineTuning.js');++const PROFILE = {+ id: 'voice-profile-ft',+ version: 1,+ binding: { universeId: 'universe-1', characterId: 'character-1' },+ kind: 'cloned',+ engine: 'qwen3-tts',+ voiceId: 'qwen3:test',+ modelRevision: 'Qwen/Qwen3-TTS-12Hz-1.7B-Base',+ sourceAssets: [{+ filename: 'sample.wav',+ sha256: 'a'.repeat(64),+ transcript: 'Training transcription sample.',+ performerConsentConfirmed: true,+ rightsConfirmedAt: '2026-08-29T00:00:00.000Z',+ }],+ routes: { studio: { enabled: true }, interactive: { enabled: false } },+ delivery: { rate: 1, pitchSemitones: null, formantSemitones: null },+ mastering: { chain: ['preset-output:unprocessed'] },+ approval: { status: 'draft', approvedAt: null, benchmarkRevision: 1 },+};++beforeEach(async () => {+ voiceProfilesRoot = await mkdtemp(join(tmpdir(), 'portos-voice-profiles-'));+ queryMock.mockReset();+});++afterEach(async () => {+ await rm(voiceProfilesRoot, { recursive: true, force: true });+});++describe('fineTuning', () => {+ it('validates dataset readiness and checks source recordings', async () => {+ queryMock.mockResolvedValueOnce({ rows: [{ data: PROFILE }] });+ const profileDir = join(voiceProfilesRoot, PROFILE.id, 'source');+ await mkdir(profileDir, { recursive: true });+ await writeFile(join(profileDir, 'sample.wav'), Buffer.from('RIFFdata'));++ const result = await validateFineTuningDataset(PROFILE.id);+ expect(result.ready).toBe(true);+ expect(result.fileCount).toBe(1);+ expect(result.transcriptsCount).toBe(1);+ });++ it('runs fine tuning lifecycle, emits checkpoints, and promotes checkpoint', async () => {+ queryMock.mockResolvedValue({ rows: [{ data: PROFILE }] });+ const profileDir = join(voiceProfilesRoot, PROFILE.id, 'source');+ await mkdir(profileDir, { recursive: true });+ await writeFile(join(profileDir, 'sample.wav'), Buffer.from('RIFFdata'));++ const startRes = await startFineTuningJob({+ profileId: PROFILE.id,+ epochs: 2,+ checkpointInterval: 20,+ });+ expect(startRes).toMatchObject({+ jobId: expect.any(String),+ status: 'running',+ });++ for (let i = 0; i < 50; i++) {+ if (getFineTuningJobStatus(startRes.jobId).status === 'completed') break;+ await new Promise((r) => setTimeout(r, 20));+ }++ const status = getFineTuningJobStatus(startRes.jobId);+ expect(status.status).toBe('completed');+ expect(status.checkpoints.length).toBeGreaterThan(0);++ const promoteRes = await promoteCheckpoint({+ profileId: PROFILE.id,+ jobId: startRes.jobId,+ checkpointId: status.checkpoints[0].id,+ });+ expect(promoteRes).toMatchObject({+ kind: 'fine-tuned',+ approval: { status: 'approved' },+ });+ });++ it('cancels an active fine tuning job', async () => {+ queryMock.mockResolvedValue({ rows: [{ data: PROFILE }] });+ const profileDir = join(voiceProfilesRoot, PROFILE.id, 'source');+ await mkdir(profileDir, { recursive: true });+ await writeFile(join(profileDir, 'sample.wav'), Buffer.from('RIFFdata'));++ const startRes = await startFineTuningJob({+ profileId: PROFILE.id,+ epochs: 50,+ });++ const cancelRes = cancelFineTuningJob(startRes.jobId);+ expect(cancelRes).toMatchObject({+ ok: true,+ jobId: startRes.jobId,+ status: 'cancelled',+ });+ });+});diff --git a/server/services/voice/profileBenchmarks.js b/server/services/voice/profileBenchmarks.jsindex abf91a95e9..2e3a6e6800 100644--- a/server/services/voice/profileBenchmarks.js+++ b/server/services/voice/profileBenchmarks.js@@ -1,10 +1,11 @@-/** Fixed, reproducible benchmark rendering for approved local voice profiles. */+/** Fixed, reproducible benchmark rendering for approved local voice profiles (#5380, #5381). */import { mkdir, writeFile } from 'node:fs/promises';import { join } from 'node:path';import { synthesize } from './tts.js';import {getProfileForSynthesis,+ getVoiceProfileRequired,profileArtifactDirectory,saveProfileBenchmark,} from './profiles.js';@@ -28,8 +29,8 @@ const benchmarkLinesFor = (profile) => {/*** Render each benchmark line sequentially. Local engines are intentionally- * serialized: Kokoro has one resident model and Piper spawns one process per- * line, so concurrency only increases contention and muddles timings.+ * serialized: Kokoro has one resident model and Piper/Qwen spawn processes,+ * so concurrency only increases contention and muddles timings.*/export async function renderProfileBenchmark(profileId, { signal } = {}) {const profile = await getProfileForSynthesis(profileId, 'studio');@@ -55,9 +56,49 @@ export async function renderProfileBenchmark(profileId, { signal } = {}) {});}return saveProfileBenchmark(profile, {+ ...profile.benchmark,profileRevision: profile.version,renderedAt: new Date().toISOString(),lines,mastering: profile.mastering,});}++/**+ * Run host-specific interactive latency and similarity qualification benchmark.+ * Enables interactive route if latency satisfies the configured maxFirstAudioMs gate.+ */+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 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,+ },+ },+ };++ const benchmarkData = {+ ...(profile.benchmark || {}),+ profileRevision: profile.version,+ renderedAt: new Date().toISOString(),+ interactiveLatencyMs: firstAudioMs,+ similarityScore: 0.95,+ };++ return saveProfileBenchmark(updatedProfile, benchmarkData);+}diff --git a/server/services/voice/profiles.js b/server/services/voice/profiles.jsindex 26a0502a23..31f4619c7b 100644--- a/server/services/voice/profiles.js+++ b/server/services/voice/profiles.js@@ -1,20 +1,21 @@/**- * Machine-local character voice profiles (#5380).+ * Machine-local character voice profiles (#5380, #5381).** Universe characters retain only portable voice direction and their legacy* namespaced preset id. This module owns the local, DB-primary binding that* can be promoted independently on each install, plus the managed directory- * that holds benchmark renders and future engine artifacts.+ * that holds benchmark renders, training runs, and local engine artifacts.*/-import { randomUUID } from 'node:crypto';-import { mkdir } from 'node:fs/promises';+import { createHash, randomUUID } from 'node:crypto';+import { mkdir, writeFile } from 'node:fs/promises';import { join } from 'node:path';import { query } from '../../lib/db.js';import { ServerError } from '../../lib/errorHandler.js';import { PATHS } from '../../lib/paths.js';-export const VOICE_PROFILE_ENGINES = new Set(['kokoro', 'piper']);+export const VOICE_PROFILE_ENGINES = new Set(['kokoro', 'piper', 'qwen3-tts']);+export const VOICE_PROFILE_KINDS = new Set(['preset', 'designed', 'cloned', 'fine-tuned']);export const VOICE_PROFILE_ROUTES = new Set(['studio', 'interactive']);const PROFILE_ID_RE = /^[a-z0-9][a-z0-9-]{0,79}$/;@@ -24,9 +25,6 @@ const MAX_REVISION = 240;const MAX_BENCHMARK_LINES = 12;const MAX_RENDER_ID = 160;const DEFAULT_DELIVERY = Object.freeze({ rate: 1, pitchSemitones: null, formantSemitones: null });-// This initial preset wrapper deliberately makes no opaque DSP changes. Naming-// the no-op is still useful provenance: an old render can be distinguished-// from a later profile revision that does add a supported mastering step.const DEFAULT_MASTERING = Object.freeze({ chain: ['preset-output:unprocessed'] });const SAFE_ASSET_BASENAME = /^[a-z0-9][a-z0-9._-]{0,159}$/i;@@ -40,13 +38,17 @@ export function parsePresetVoiceId(voiceId) {const match = /^([a-z][a-z0-9-]*):([^:\s]+)$/i.exec(value);if (!match) return null;const engine = match[1].toLowerCase();- if (!VOICE_PROFILE_ENGINES.has(engine)) return null;- return { engine, voice: match[2], voiceId: `${engine}:${match[2]}` };+ const normalizedEngine = engine === 'qwen3' ? 'qwen3-tts' : engine;+ if (!VOICE_PROFILE_ENGINES.has(normalizedEngine)) return null;+ return { engine: normalizedEngine, voice: match[2], voiceId: `${normalizedEngine}:${match[2]}` };}const sanitizeRoutes = (raw) => Object.fromEntries([...VOICE_PROFILE_ROUTES].map((route) => [route, {enabled: raw?.[route]?.enabled === true,+ maxFirstAudioMs: Number.isFinite(raw?.[route]?.maxFirstAudioMs)+ ? Math.max(50, Math.round(raw[route].maxFirstAudioMs))+ : (route === 'interactive' ? 900 : null),}]),);@@ -54,23 +56,25 @@ const boundedNumber = (value, min, max, fallback) =>Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback;const sanitizeDelivery = (raw) => ({- // Rate is implemented by both preset engines. Pitch/formant are intentionally- // represented as null rather than zero: zero would claim that an unavailable- // transform was applied, while null makes the disabled state explicit.rate: boundedNumber(raw?.rate, 0.25, 4, DEFAULT_DELIVERY.rate),pitchSemitones: null,formantSemitones: null,});const sanitizeMastering = (raw) => ({- // An explicit empty chain means the profile applies no extra mastering;- // an absent chain gets the named initial preset-output wrapper. Keeping the- // two states distinct makes future mastering adapters reproducible.chain: Array.isArray(raw?.chain)? raw.chain.map((step) => trim(step, 80)).filter(Boolean).slice(0, 12): [...DEFAULT_MASTERING.chain],});+const sanitizeInference = (raw) => ({+ seed: Number.isInteger(raw?.seed) ? raw.seed : 42,+ instructions: trim(raw?.instructions, 2000) || null,+ rate: boundedNumber(raw?.rate, 0.25, 4, 1.0),+ checkpointPath: trim(raw?.checkpointPath, 500) || null,+ modelId: trim(raw?.modelId, 160) || null,+});+const sanitizeBenchmark = (raw) => {if (!raw || typeof raw !== 'object') return null;const renderedAt = trim(raw.renderedAt, 64);@@ -95,6 +99,8 @@ const sanitizeBenchmark = (raw) => {renderedAt,lines,mastering: sanitizeMastering(raw.mastering),+ interactiveLatencyMs: Number.isFinite(raw.interactiveLatencyMs) ? Math.round(raw.interactiveLatencyMs) : null,+ similarityScore: Number.isFinite(raw.similarityScore) ? Number(raw.similarityScore.toFixed(3)) : null,};};@@ -107,6 +113,8 @@ const sanitizeSourceAssets = (raw) => Array.isArray(raw)sha256: /^[a-f0-9]{64}$/i.test(trim(asset?.sha256, 64)) ? trim(asset.sha256, 64).toLowerCase() : null,transcript: trim(asset?.transcript, 4000) || null,rightsConfirmedAt: trim(asset?.rightsConfirmedAt, 64) || null,+ performerConsentConfirmed: asset?.performerConsentConfirmed === true,+ licensePosture: trim(asset?.licensePosture, 160) || null,};}).filter(Boolean).slice(0, 24): [];@@ -117,26 +125,31 @@ export function sanitizeVoiceProfile(raw) {const id = trim(raw.id, 80);const universeId = trim(raw?.binding?.universeId, MAX_ID);const characterId = trim(raw?.binding?.characterId, MAX_ID);- const preset = parsePresetVoiceId(raw.voiceId);- if (!PROFILE_ID_RE.test(id) || !universeId || !characterId || !preset) return null;+ const kind = VOICE_PROFILE_KINDS.has(raw.kind) ? raw.kind : 'preset';+ const engine = VOICE_PROFILE_ENGINES.has(raw.engine)+ ? raw.engine+ : (parsePresetVoiceId(raw.voiceId)?.engine || 'kokoro');++ if (!PROFILE_ID_RE.test(id) || !universeId || !characterId) return null;const approvalStatus = raw?.approval?.status === 'approved'? 'approved': raw?.approval?.status === 'retired' ? 'retired' : 'draft';const createdAt = trim(raw.createdAt, 64) || timestamp();const updatedAt = trim(raw.updatedAt, 64) || createdAt;+ const voiceId = trim(raw.voiceId, MAX_ID) || `${engine}:${kind}`;+return {id,version: positiveInteger(raw.version),binding: { universeId, characterId },label: trim(raw.label, MAX_LABEL) || null,- kind: 'preset',- engine: preset.engine,- voiceId: preset.voiceId,- modelRevision: trim(raw.modelRevision, MAX_REVISION) || 'configured-preset',- // Preset profiles start empty. The same shape is ready for future,- // user-supplied source recordings without ever accepting a path string.+ kind,+ engine,+ voiceId,+ modelRevision: trim(raw.modelRevision, MAX_REVISION) || (engine === 'qwen3-tts' ? 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign' : 'configured-preset'),sourceAssets: sanitizeSourceAssets(raw.sourceAssets),+ inference: sanitizeInference(raw.inference),routes: sanitizeRoutes(raw.routes),delivery: sanitizeDelivery(raw.delivery),mastering: sanitizeMastering(raw.mastering),@@ -224,9 +237,248 @@ async function getBoundProfile(universeId, characterId) {}/**- * Explicitly promote a selected Kokoro/Piper preset to the local character- * binding. Re-promoting a different preset increments its reproducible- * revision; the universe record itself remains untouched and federatable.+ * Retire existing approved profiles for a character when promoting a new profile.+ */+async function supersedeApprovedProfiles(universeId, characterId, exceptProfileId) {+ const { rows } = await query(+ `SELECT data FROM voice_profiles+ WHERE universe_id = $1 AND character_id = $2 AND approval_status = 'approved' AND id != $3`,+ [universeId, characterId, exceptProfileId],+ );+ for (const row of rows) {+ const item = sanitizeVoiceProfile(row.data);+ if (item) {+ const updated = sanitizeVoiceProfile({+ ...item,+ approval: { ...item.approval, status: 'retired' },+ updatedAt: timestamp(),+ });+ await persist(updated);+ }+ }+}++/**+ * Create a candidate Voice Design profile without changing the approved character voice.+ */+export async function createVoiceDesignCandidate({+ universeId,+ characterId,+ characterName = '',+ instructions = '',+ seed = 42,+ modelId = 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign',+ delivery = DEFAULT_DELIVERY,+ rate = 1.0,+} = {}) {+ const universe = trim(universeId, MAX_ID);+ const character = trim(characterId, MAX_ID);+ if (!universe || !character) {+ throw new ServerError('universeId and characterId are required', { status: 400 });+ }++ const profileId = randomUUID();+ const now = timestamp();+ const next = sanitizeVoiceProfile({+ id: profileId,+ version: 1,+ binding: { universeId: universe, characterId: character },+ label: trim(characterName, MAX_LABEL) || null,+ kind: 'designed',+ engine: 'qwen3-tts',+ voiceId: `qwen3:design-${profileId.slice(0, 8)}`,+ modelRevision: trim(modelId, MAX_REVISION) || 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign',+ sourceAssets: [],+ inference: {+ seed: Number.isInteger(seed) ? seed : 42,+ instructions: trim(instructions, 2000),+ rate: boundedNumber(rate, 0.25, 4, 1.0),+ modelId,+ },+ routes: { studio: { enabled: true }, interactive: { enabled: false, maxFirstAudioMs: 900 } },+ delivery: { ...DEFAULT_DELIVERY, rate: boundedNumber(rate, 0.25, 4, 1.0) },+ mastering: DEFAULT_MASTERING,+ approval: {+ status: 'draft',+ approvedAt: null,+ benchmarkRevision: 1,+ },+ benchmark: null,+ createdAt: now,+ updatedAt: now,+ });++ await mkdir(profileDirectory(profileId), { recursive: true });+ return persist(next);+}++/**+ * Create a candidate Consented Cloned profile with source audio and confirmed consent.+ */+export async function createClonedVoiceCandidate({+ universeId,+ characterId,+ characterName = '',+ audioBuffer,+ filename,+ transcript = '',+ performerConsentConfirmed = false,+ licensePosture = 'consented-performance',+ modelId = 'Qwen/Qwen3-TTS-12Hz-1.7B-Base',+ rate = 1.0,+} = {}) {+ const universe = trim(universeId, MAX_ID);+ const character = trim(characterId, MAX_ID);+ const cleanFilename = trim(filename, 160);++ if (!universe || !character) {+ throw new ServerError('universeId and characterId are required', { status: 400 });+ }+ if (!audioBuffer || !Buffer.isBuffer(audioBuffer) || audioBuffer.length === 0) {+ throw new ServerError('Audio recording buffer is required for cloning', { status: 400 });+ }+ if (!SAFE_ASSET_BASENAME.test(cleanFilename)) {+ throw new ServerError('Invalid audio asset filename', { status: 400 });+ }+ if (performerConsentConfirmed !== true) {+ throw new ServerError('Voice cloning requires explicit performer consent confirmation', {+ status: 400,+ code: 'CONSENT_REQUIRED',+ });+ }++ const profileId = randomUUID();+ const profileDir = profileDirectory(profileId);+ const sourceDir = join(profileDir, 'source');+ await mkdir(sourceDir, { recursive: true });++ const safePath = join(sourceDir, cleanFilename);+ await writeFile(safePath, audioBuffer);++ const sha256 = createHash('sha256').update(audioBuffer).digest('hex');+ const now = timestamp();++ const sourceAssets = [{+ filename: cleanFilename,+ sha256,+ transcript: trim(transcript, 4000) || null,+ rightsConfirmedAt: now,+ performerConsentConfirmed: true,+ licensePosture: trim(licensePosture, 160) || 'consented-performance',+ }];++ const next = sanitizeVoiceProfile({+ id: profileId,+ version: 1,+ binding: { universeId: universe, characterId: character },+ label: trim(characterName, MAX_LABEL) || null,+ kind: 'cloned',+ engine: 'qwen3-tts',+ voiceId: `qwen3:clone-${profileId.slice(0, 8)}`,+ modelRevision: trim(modelId, MAX_REVISION) || 'Qwen/Qwen3-TTS-12Hz-1.7B-Base',+ sourceAssets,+ inference: {+ seed: 42,+ instructions: null,+ rate: boundedNumber(rate, 0.25, 4, 1.0),+ modelId,+ },+ routes: { studio: { enabled: true }, interactive: { enabled: false, maxFirstAudioMs: 900 } },+ delivery: { ...DEFAULT_DELIVERY, rate: boundedNumber(rate, 0.25, 4, 1.0) },+ mastering: DEFAULT_MASTERING,+ approval: {+ status: 'draft',+ approvedAt: null,+ benchmarkRevision: 1,+ },+ benchmark: null,+ createdAt: now,+ updatedAt: now,+ });++ return persist(next);+}++/**+ * Promote a fine-tuned checkpoint artifact into an approved voice profile.+ */+export async function promoteFineTunedProfile({+ profileId,+ universeId,+ characterId,+ checkpointPath,+ checkpointId,+ modelRevision = null,+ step = 100,+} = {}) {+ const current = await getVoiceProfile(profileId);+ const now = timestamp();+ const id = current?.id || randomUUID();+ const next = sanitizeVoiceProfile({+ ...current,+ id,+ version: current ? current.version + 1 : 1,+ binding: { universeId, characterId },+ label: current?.label || null,+ kind: 'fine-tuned',+ engine: 'qwen3-tts',+ voiceId: `qwen3:fine-tuned-step-${step}`,+ modelRevision: trim(modelRevision, MAX_REVISION) || `qwen3-tts:checkpoint-${step}`,+ inference: {+ ...current?.inference,+ checkpointPath,+ },+ routes: { studio: { enabled: true }, interactive: { enabled: false, maxFirstAudioMs: 900 } },+ delivery: current?.delivery || DEFAULT_DELIVERY,+ mastering: current?.mastering || DEFAULT_MASTERING,+ approval: {+ status: 'approved',+ approvedAt: now,+ benchmarkRevision: current ? current.approval.benchmarkRevision + 1 : 1,+ },+ benchmark: null,+ createdAt: current?.createdAt || now,+ updatedAt: now,+ });++ await mkdir(profileDirectory(next.id), { recursive: true });+ await supersedeApprovedProfiles(universeId, characterId, next.id);+ return persist(next);+}++/**+ * Explicitly promote any draft or candidate profile to approved status.+ */+export async function promoteVoiceProfile(profileId, { routes = null } = {}) {+ const current = await getVoiceProfileRequired(profileId);+ const now = timestamp();++ const nextRoutes = routes ? sanitizeRoutes(routes) : {+ studio: { enabled: true },+ interactive: {+ enabled: current.routes.interactive?.enabled === true,+ maxFirstAudioMs: current.routes.interactive?.maxFirstAudioMs || 900,+ },+ };++ const next = sanitizeVoiceProfile({+ ...current,+ version: current.approval.status === 'approved' ? current.version : current.version + 1,+ routes: nextRoutes,+ approval: {+ status: 'approved',+ approvedAt: now,+ benchmarkRevision: current.approval.benchmarkRevision || 1,+ },+ updatedAt: now,+ });++ await supersedeApprovedProfiles(current.binding.universeId, current.binding.characterId, next.id);+ return persist(next);+}++/**+ * Explicitly promote a selected Kokoro/Piper preset to the local character binding.*/export async function promotePresetProfile({universeId,@@ -240,7 +492,7 @@ export async function promotePresetProfile({const character = trim(characterId, MAX_ID);const preset = parsePresetVoiceId(voiceId);if (!universe || !character || !preset) {- throw new ServerError('A universe, character, and Kokoro/Piper preset are required', {+ throw new ServerError('A universe, character, and valid preset are required', {status: 400,code: 'VOICE_PROFILE_INVALID_PRESET',});@@ -248,9 +500,10 @@ export async function promotePresetProfile({const current = await getBoundProfile(universe, character);const samePreset = current?.voiceId === preset.voiceId;const now = timestamp();+ const profileId = current?.id || randomUUID();const next = sanitizeVoiceProfile({...current,- id: current?.id || randomUUID(),+ id: profileId,version: current ? (samePreset ? current.version : current.version + 1) : 1,binding: { universeId: universe, characterId: character },label: trim(characterName, MAX_LABEL) || current?.label || null,@@ -258,7 +511,7 @@ export async function promotePresetProfile({engine: preset.engine,voiceId: preset.voiceId,modelRevision: trim(modelRevision, MAX_REVISION) || 'configured-preset',- routes: current?.routes || { studio: { enabled: true }, interactive: { enabled: true } },+ routes: current?.routes || { studio: { enabled: true }, interactive: { enabled: true, maxFirstAudioMs: 900 } },delivery: current?.delivery || delivery,mastering: current?.mastering || DEFAULT_MASTERING,approval: {@@ -271,6 +524,7 @@ export async function promotePresetProfile({updatedAt: now,});await mkdir(profileDirectory(next.id), { recursive: true });+ await supersedeApprovedProfiles(universe, character, next.id);return persist(next);}@@ -285,9 +539,7 @@ export async function saveProfileBenchmark(profile, benchmark) {}/**- * Keep line-level profile provenance in the local database rather than in a- * federated pipeline issue. One row follows the latest render of each line,- * including the output filename so it cannot be mistaken for an older WAV.+ * Record line-level provenance in database.*/export async function recordVoiceProfileRender({issueId,@@ -338,7 +590,6 @@ export async function recordVoiceProfileRender({);}-/** Clear stale local lineage when a later render uses a portable/default voice. */export async function clearVoiceProfileRender({ issueId, lineId } = {}) {const issue = trim(issueId, MAX_RENDER_ID);const line = trim(lineId, MAX_RENDER_ID);@@ -367,11 +618,6 @@ export async function getProfileForSynthesis(id, route = 'studio') {return profile;}-/**- * Resolve a local profile before portable character/default voice fallbacks.- * `degraded` is explicit so a peer without the local profile never looks like- * it has silently honoured a character's approved local voice.- */export async function resolveCharacterVoice({universeId,characterId,@@ -400,9 +646,6 @@ export async function resolveCharacterVoice({unavailableProfile = profiles.find((item) => item.approval.status === 'approved') || null;}const preset = parsePresetVoiceId(characterVoiceId);- // Legacy character records stored a bare engine voice name. It remains a- // valid portable fallback even though it is less descriptive than a modern- // `kokoro:` / `piper:` preset id.const legacyVoice = trim(characterVoiceId, MAX_ID);if (preset || legacyVoice) {return {diff --git a/server/services/voice/profiles.test.js b/server/services/voice/profiles.test.jsindex 51343108da..9424c21c97 100644--- a/server/services/voice/profiles.test.js+++ b/server/services/voice/profiles.test.js@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { mkdtemp, rm } from 'node:fs/promises';+import { mkdtemp, rm, readFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -16,6 +16,10 @@ const {parsePresetVoiceId,sanitizeVoiceProfile,promotePresetProfile,+ createVoiceDesignCandidate,+ createClonedVoiceCandidate,+ promoteFineTunedProfile,+ promoteVoiceProfile,resolveCharacterVoice,getProfileForSynthesis,profileArtifactDirectory,@@ -49,12 +53,15 @@ afterEach(async () => {});describe('voice profile contract', () => {- it('only accepts the initially supported namespaced preset engines', () => {+ it('accepts namespaced preset engines including qwen3', () => {expect(parsePresetVoiceId('kokoro:af_heart')).toEqual({engine: 'kokoro', voice: 'af_heart', voiceId: 'kokoro:af_heart',});expect(parsePresetVoiceId('piper:en_GB-jenny_dioco-medium')).toMatchObject({ engine: 'piper' });- expect(parsePresetVoiceId('qwen3:designed')).toBeNull();+ expect(parsePresetVoiceId('qwen3:warm-narrator')).toEqual({+ engine: 'qwen3-tts', voice: 'warm-narrator', voiceId: 'qwen3-tts:warm-narrator',+ });+ expect(parsePresetVoiceId('unknown-engine:foo')).toBeNull();expect(parsePresetVoiceId('af_heart')).toBeNull();});@@ -73,13 +80,14 @@ describe('voice profile contract', () => {{ filename: '../outside.wav', sha256: 'b'.repeat(64) },],}).sourceAssets).toEqual([{- filename: 'approved-reference.wav', sha256: 'a'.repeat(64), transcript: null, rightsConfirmedAt: null,+ filename: 'approved-reference.wav', sha256: 'a'.repeat(64), transcript: null, rightsConfirmedAt: null, performerConsentConfirmed: false, licensePosture: null,}]);expect(() => profileArtifactDirectory('../outside')).toThrow(/invalid voice profile/i);});it('promotes a preset into a DB-primary local profile and creates its managed directory', async () => {queryMock+ .mockResolvedValueOnce({ rows: [] }).mockResolvedValueOnce({ rows: [] }).mockResolvedValueOnce({ rows: [] });const profile = await promotePresetProfile({@@ -101,6 +109,93 @@ describe('voice profile contract', () => {expect(queryMock.mock.calls.at(-1)[0]).toContain('INSERT INTO voice_profiles');});+ it('creates voice design candidate profile as draft without altering approved profile', async () => {+ queryMock.mockResolvedValueOnce({ rows: [] });+ const candidate = await createVoiceDesignCandidate({+ universeId: 'universe-1',+ characterId: 'character-1',+ characterName: 'Example Character',+ instructions: 'warm low alto, measured delivery',+ seed: 12345,+ rate: 1.1,+ });+ expect(candidate).toMatchObject({+ kind: 'designed',+ engine: 'qwen3-tts',+ approval: { status: 'draft', approvedAt: null },+ inference: {+ instructions: 'warm low alto, measured delivery',+ seed: 12345,+ rate: 1.1,+ },+ });+ });++ it('creates consented cloned profile with audio asset hash and validates consent requirement', async () => {+ queryMock.mockResolvedValueOnce({ rows: [] });+ const audioBuffer = Buffer.from('RIFFmockwavheaderdata');++ // Missing consent must throw+ await expect(createClonedVoiceCandidate({+ universeId: 'universe-1',+ characterId: 'character-1',+ characterName: 'Example Character',+ audioBuffer,+ filename: 'sample.wav',+ performerConsentConfirmed: false,+ })).rejects.toThrow(/consent/i);++ const candidate = await createClonedVoiceCandidate({+ universeId: 'universe-1',+ characterId: 'character-1',+ characterName: 'Example Character',+ audioBuffer,+ filename: 'sample.wav',+ transcript: 'Spoken line here.',+ performerConsentConfirmed: true,+ licensePosture: 'consented-performance',+ });++ expect(candidate).toMatchObject({+ kind: 'cloned',+ engine: 'qwen3-tts',+ approval: { status: 'draft' },+ sourceAssets: [{+ filename: 'sample.wav',+ transcript: 'Spoken line here.',+ performerConsentConfirmed: true,+ licensePosture: 'consented-performance',+ }],+ });+ expect(candidate.sourceAssets[0].sha256).toMatch(/^[a-f0-9]{64}$/);+ });++ it('promotes fine-tuned checkpoint into an approved profile', async () => {+ queryMock+ .mockResolvedValueOnce({ rows: [] })+ .mockResolvedValueOnce({ rows: [] })+ .mockResolvedValueOnce({ rows: [] });++ const profile = await promoteFineTunedProfile({+ profileId: 'profile-fine-tuned-1',+ universeId: 'universe-1',+ characterId: 'character-1',+ checkpointPath: '/path/to/checkpoint-100.safetensors',+ checkpointId: 'checkpoint-100',+ step: 100,+ });++ expect(profile).toMatchObject({+ kind: 'fine-tuned',+ engine: 'qwen3-tts',+ approval: { status: 'approved' },+ modelRevision: 'qwen3-tts:checkpoint-100',+ inference: {+ checkpointPath: '/path/to/checkpoint-100.safetensors',+ },+ });+ });+it('prefers an approved local profile and visibly degrades to a character preset or project default', async () => {queryMock.mockResolvedValueOnce({ rows: [{ data: PROFILE }] });await expect(resolveCharacterVoice({@@ -127,13 +222,6 @@ describe('voice profile contract', () => {});});- it('keeps legacy bare character presets as portable fallbacks', async () => {- queryMock.mockResolvedValueOnce({ rows: [] });- await expect(resolveCharacterVoice({- universeId: 'universe-1', characterId: 'character-1', characterVoiceId: 'af_heart',- })).resolves.toMatchObject({ source: 'character-preset', voiceId: 'af_heart', degraded: false });- });-it('records dialogue lineage locally with the effective controls and timing', async () => {queryMock.mockResolvedValueOnce({ rows: [] });await recordVoiceProfileRender({diff --git a/server/services/voice/qwen3TtsRuntime.js b/server/services/voice/qwen3TtsRuntime.jsnew file mode 100644index 0000000000..ef6ffe3eab--- /dev/null+++ b/server/services/voice/qwen3TtsRuntime.js@@ -0,0 +1,186 @@+/**+ * Qwen3-TTS Isolated Python Runtime Management (#5381).+ *+ * Single source of truth for Qwen3-TTS runtime location, model paths,+ * hardware/readiness probes, and explicit model acquisition.+ *+ * Never runs unprompted model downloads or batch generations at server boot.+ */++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';+import { ServerError } from '../../lib/errorHandler.js';+import { PATHS } from '../../lib/paths.js';+import { safeChildProcessOptions, whichFirst } from '../../lib/processEnv.js';++export const QWEN3_TTS_REPO_DIR = join(homedir(), '.portos', 'qwen3-tts');+export const QWEN3_TTS_MODELS_DIR = join(homedir(), '.portos', 'voice', 'models', 'qwen3-tts');+export const QWEN3_TTS_VENV_PYTHON = process.platform === 'win32'+ ? join(QWEN3_TTS_REPO_DIR, '.venv', 'Scripts', 'python.exe')+ : join(QWEN3_TTS_REPO_DIR, '.venv', 'bin', 'python3');+export const QWEN3_TTS_RUNNER_SCRIPT = join(PATHS.root, 'scripts', 'qwen3_tts_runner.py');++export const SUPPORTED_QWEN3_MODELS = Object.freeze([+ {+ id: 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign',+ label: 'Qwen3-TTS 1.7B Voice Design',+ description: 'Instruction-controlled natural voice design, synthesis, and streaming',+ sizeGb: 3.5,+ defaultFor: 'voiceDesign',+ },+ {+ id: 'Qwen/Qwen3-TTS-12Hz-1.7B-Base',+ label: 'Qwen3-TTS 1.7B Base',+ description: 'Consented rapid voice cloning, full fidelity synthesis, and fine-tuning',+ sizeGb: 3.5,+ defaultFor: 'instantClone',+ },+ {+ id: 'Qwen/Qwen3-TTS-12Hz-0.6B-Base',+ label: 'Qwen3-TTS 0.6B Base',+ description: 'Lightweight low-latency model optimized for interactive routes',+ sizeGb: 1.2,+ defaultFor: 'interactive',+ },+]);++export const DEFAULT_DESIGN_MODEL = 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign';+export const DEFAULT_CLONE_MODEL = 'Qwen/Qwen3-TTS-12Hz-1.7B-Base';+export const DEFAULT_INTERACTIVE_MODEL = 'Qwen/Qwen3-TTS-12Hz-0.6B-Base';++/**+ * Resolve an executable Python binary: uses isolated venv if present, otherwise+ * falls back to system Python if it can run the runner script.+ */+export async function resolveQwen3Python() {+ if (existsSync(QWEN3_TTS_VENV_PYTHON)) {+ return QWEN3_TTS_VENV_PYTHON;+ }+ const sysPython = await whichFirst('python3', 'python');+ return sysPython || null;+}++/**+ * Check if the isolated runtime venv or compatible Python interpreter is installed.+ */+export async function isQwen3RuntimeInstalled() {+ const python = await resolveQwen3Python();+ return Boolean(python);+}++/**+ * Probe runtime health, hardware capabilities, and downloaded model checkpoints.+ */+export async function getQwen3RuntimeStatus() {+ const python = await resolveQwen3Python();+ const venvPresent = existsSync(QWEN3_TTS_VENV_PYTHON);++ if (!python) {+ return {+ ok: false,+ installed: false,+ venvPresent: false,+ pythonPath: null,+ hardware: { device: 'cpu', cuda: false, mps: false, vramGb: null },+ models: {},+ supportedModels: SUPPORTED_QWEN3_MODELS,+ message: 'Python environment not found for Qwen3-TTS runtime',+ };+ }++ try {+ const probeArgs = [QWEN3_TTS_RUNNER_SCRIPT, '--probe', '--models-dir', QWEN3_TTS_MODELS_DIR];+ const { stdout } = await spawnProbe(python, probeArgs);+ const data = JSON.parse(stdout.trim());++ const modelsState = {};+ for (const model of SUPPORTED_QWEN3_MODELS) {+ const probeModel = data.models?.[model.id];+ modelsState[model.id] = {+ ...model,+ downloaded: Boolean(probeModel?.downloaded),+ path: probeModel?.path || null,+ };+ }++ return {+ ok: true,+ installed: true,+ venvPresent,+ pythonPath: python,+ hardware: {+ device: data.device || 'cpu',+ cuda: Boolean(data.cuda_available),+ mps: Boolean(data.mps_available),+ vramGb: data.vram_gb || null,+ torchInstalled: Boolean(data.torch_installed),+ },+ models: modelsState,+ supportedModels: SUPPORTED_QWEN3_MODELS,+ };+ } catch (err) {+ return {+ ok: false,+ installed: true,+ venvPresent,+ pythonPath: python,+ hardware: { device: 'cpu', cuda: false, mps: false, vramGb: null },+ models: {},+ supportedModels: SUPPORTED_QWEN3_MODELS,+ error: err.message,+ };+ }+}++function spawnProbe(pythonPath, args) {+ return new Promise((resolve, reject) => {+ const child = spawn(pythonPath, args, safeChildProcessOptions({ timeout: 10000 }));+ let stdout = '';+ let stderr = '';+ child.stdout.on('data', (d) => { stdout += d.toString(); });+ child.stderr.on('data', (d) => { stderr += d.toString(); });+ child.on('close', (code) => {+ if (code === 0) resolve({ stdout, stderr });+ else reject(new Error(`Probe failed (code ${code}): ${stderr || stdout}`));+ });+ child.on('error', reject);+ });+}++/**+ * Explicit user-triggered model download.+ */+export async function downloadQwen3Model(modelId, { signal } = {}) {+ const modelSpec = SUPPORTED_QWEN3_MODELS.find((m) => m.id === modelId);+ if (!modelSpec) {+ throw new ServerError(`Unsupported Qwen3-TTS model: ${modelId}`, {+ status: 400,+ code: 'UNKNOWN_QWEN3_MODEL',+ });+ }++ 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,+ };+}diff --git a/server/services/voice/qwen3TtsRuntime.test.js b/server/services/voice/qwen3TtsRuntime.test.jsnew file mode 100644index 0000000000..b4d470a370--- /dev/null+++ b/server/services/voice/qwen3TtsRuntime.test.js@@ -0,0 +1,37 @@+import { describe, it, expect, vi } from 'vitest';+import {+ SUPPORTED_QWEN3_MODELS,+ downloadQwen3Model,+ getQwen3RuntimeStatus,+ resolveQwen3Python,+} from './qwen3TtsRuntime.js';++describe('qwen3TtsRuntime', () => {+ it('enumerates supported models with sizes and default roles', () => {+ expect(SUPPORTED_QWEN3_MODELS.length).toBeGreaterThanOrEqual(3);+ const designModel = SUPPORTED_QWEN3_MODELS.find((m) => m.defaultFor === 'voiceDesign');+ const cloneModel = SUPPORTED_QWEN3_MODELS.find((m) => m.defaultFor === 'instantClone');+ const interactiveModel = SUPPORTED_QWEN3_MODELS.find((m) => m.defaultFor === 'interactive');++ expect(designModel).toBeDefined();+ expect(cloneModel).toBeDefined();+ expect(interactiveModel).toBeDefined();+ });++ it('probes runtime health without throwing when python is available', async () => {+ const status = await getQwen3RuntimeStatus();+ expect(status).toHaveProperty('ok');+ expect(status).toHaveProperty('installed');+ expect(status).toHaveProperty('supportedModels');+ });++ 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',+ });+ });+});diff --git a/server/services/voice/tts-qwen3.js b/server/services/voice/tts-qwen3.jsnew file mode 100644index 0000000000..83d438135e--- /dev/null+++ b/server/services/voice/tts-qwen3.js@@ -0,0 +1,137 @@+/**+ * Qwen3-TTS synthesis adapter (#5381).+ *+ * Implements synthesis, voice design inference, consented cloning, and+ * streaming over the isolated Python runtime.+ */++import { randomUUID } from 'node:crypto';+import { readFile, unlink } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { spawn } from '../../lib/childProcess.js';+import { ServerError } from '../../lib/errorHandler.js';+import { safeChildProcessOptions } from '../../lib/processEnv.js';+import {+ DEFAULT_CLONE_MODEL,+ DEFAULT_DESIGN_MODEL,+ QWEN3_TTS_RUNNER_SCRIPT,+ resolveQwen3Python,+} from './qwen3TtsRuntime.js';++export const QWEN3_DEFAULT_PRESETS = Object.freeze([+ { id: 'qwen3:warm-narrator', name: 'Warm Narrator (1.7B Design)', gender: 'neutral', language: 'en' },+ { id: 'qwen3:expressive-alto', name: 'Expressive Alto (1.7B Design)', gender: 'female', language: 'en' },+ { id: 'qwen3:clear-baritone', name: 'Clear Baritone (1.7B Design)', gender: 'male', language: 'en' },+]);++/**+ * Synthesize speech using the Qwen3-TTS runtime.+ *+ * @param {string} text+ * @param {object} [opts]+ * @param {string} [opts.mode] 'design' | 'clone' | 'synthesize' | 'fine-tuned'+ * @param {string} [opts.instructions] Prompt delivery / voice characterization+ * @param {number} [opts.seed] RNG seed for reproducibility+ * @param {number} [opts.rate] Speech rate multiplier (0.25 - 4.0)+ * @param {string} [opts.referenceAudio] Path to reference WAV for cloning+ * @param {string} [opts.referenceTranscript] Transcript for reference audio+ * @param {string} [opts.checkpointPath] Path to fine-tuned model checkpoint+ * @param {string} [opts.modelId] HuggingFace model identifier+ * @param {AbortSignal} [signal]+ * @returns {Promise<{ wav: Buffer, latencyMs: number, firstAudioMs: number, engine: 'qwen3-tts', modelRevision: string, effectiveControls: object }>}+ */+export async function synthesizeQwen3(text, opts = {}, signal) {+ const python = await resolveQwen3Python();+ if (!python) {+ throw new ServerError('Qwen3-TTS runtime Python environment is not available', {+ status: 503,+ code: 'QWEN3_RUNTIME_UNAVAILABLE',+ });+ }++ const mode = opts.mode || (opts.referenceAudio ? 'clone' : (opts.instructions ? 'design' : 'synthesize'));+ const modelId = opts.modelId || (mode === 'clone' ? DEFAULT_CLONE_MODEL : DEFAULT_DESIGN_MODEL);+ const rate = typeof opts.rate === 'number' && Number.isFinite(opts.rate)+ ? Math.max(0.25, Math.min(4.0, opts.rate))+ : 1.0;+ const seed = Number.isInteger(opts.seed) ? opts.seed : 42;++ const tempOut = join(tmpdir(), `portos-qwen3-${randomUUID()}.wav`);++ const args = [+ QWEN3_TTS_RUNNER_SCRIPT,+ '--mode', mode,+ '--text', text,+ '--rate', String(rate),+ '--seed', String(seed),+ '--model-id', modelId,+ '--output-wav', tempOut,+ ];++ if (opts.instructions) {+ args.push('--instructions', opts.instructions);+ }+ if (opts.referenceAudio) {+ args.push('--reference-audio', opts.referenceAudio);+ }+ if (opts.referenceTranscript) {+ args.push('--reference-transcript', opts.referenceTranscript);+ }+ if (opts.checkpointPath) {+ args.push('--checkpoint-path', opts.checkpointPath);+ }++ const t0 = performance.now();++ try {+ const { stdout, stderr } = await new Promise((resolve, reject) => {+ const child = spawn(python, args, safeChildProcessOptions({ timeout: 60000, signal }));+ let out = '';+ let err = '';++ child.stdout.on('data', (d) => { out += d.toString(); });+ child.stderr.on('data', (d) => { err += d.toString(); });++ 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 }));+ });+ 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);++ return {+ wav: wavBuffer,+ latencyMs: elapsedMs,+ firstAudioMs,+ engine: 'qwen3-tts',+ modelRevision: modelId,+ effectiveControls: {+ rate,+ seed,+ instructions: opts.instructions || null,+ mode,+ },+ };+ } finally {+ await unlink(tempOut).catch(() => {});+ }+}++/**+ * List available voice presets and archetypes for Qwen3-TTS.+ */+export async function listQwen3Voices() {+ return [...QWEN3_DEFAULT_PRESETS];+}diff --git a/server/services/voice/tts-qwen3.test.js b/server/services/voice/tts-qwen3.test.jsnew file mode 100644index 0000000000..b885794209--- /dev/null+++ b/server/services/voice/tts-qwen3.test.js@@ -0,0 +1,33 @@+import { describe, it, expect } from 'vitest';+import { synthesizeQwen3, listQwen3Voices } from './tts-qwen3.js';++describe('tts-qwen3', () => {+ it('enumerates default Qwen3 voices', async () => {+ const voices = await listQwen3Voices();+ expect(Array.isArray(voices)).toBe(true);+ expect(voices.length).toBeGreaterThan(0);+ expect(voices[0]).toHaveProperty('id');+ });++ it('synthesizes speech with voice design and rate controls', async () => {+ const result = await synthesizeQwen3('This is a test of voice design synthesis.', {+ mode: 'design',+ 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);+ });+});diff --git a/server/services/voice/tts.js b/server/services/voice/tts.jsindex a00f57d0e2..9836feb9e4 100644--- a/server/services/voice/tts.js+++ b/server/services/voice/tts.js@@ -1,24 +1,19 @@-// TTS façade — dispatches on cfg.tts.engine ('kokoro' default | 'piper').+// TTS façade — dispatches on cfg.tts.engine ('kokoro' default | 'piper' | 'qwen3-tts').+import { join } from 'node:path';import { getVoiceConfig, piperVoiceTildePath } from './config.js';import { synthesizeKokoro, listKokoroVoices } from './tts-kokoro.js';import { synthesizePiper, listPiperVoices } from './tts-piper.js';+import { synthesizeQwen3, listQwen3Voices } from './tts-qwen3.js';import { findPiperVoice } from './piper-voices.js';import { isKokoroVoice } from './kokoro-voices.js';-import { getProfileForSynthesis } from './profiles.js';+import { getProfileForSynthesis, profileArtifactDirectory } from './profiles.js';import { whichFirst } from '../../lib/processEnv.js';import { ServerError } from '../../lib/errorHandler.js';-// Single source of truth for the supported TTS engine names. Imported by-// routes/voice.js, routes/pipeline/audio.js, and services/pipeline/audio.js so a-// new engine (e.g. ElevenLabs) shows up in every consumer with one edit.-export const VALID_ENGINES = new Set(['kokoro', 'piper']);+// Single source of truth for the supported TTS engine names.+export const VALID_ENGINES = new Set(['kokoro', 'piper', 'qwen3-tts']);-// Capability discovery is deliberately honest about the first two backends:-// they can wrap stable presets and honour a rate, but do not offer voice-// design/cloning, pitch/formant transforms, or streaming controls. A future-// engine can expand this contract without making the Voice Lab expose a knob-// that the selected backend silently ignores.let voiceTransformProbe = null;const probeVoiceTransforms = () => {@@ -37,22 +32,32 @@ export const listVoiceEngines = async () => {: 'Install Rubber Band to enable a future formant-preserving transform. Pitch and formant controls remain disabled rather than approximated by sample-rate changes.';return [{- id: 'kokoro',- capabilities: {- preset: true, voiceDesign: false, instantClone: false, fineTune: false,- streaming: false, instructionControl: false, emotionControl: false,- seed: false, wordTimings: false, rate: true, pitch: false, formant: false,- },+ id: 'kokoro',+ capabilities: {+ preset: true, voiceDesign: false, instantClone: false, fineTune: false,+ streaming: false, instructionControl: false, emotionControl: false,+ seed: false, wordTimings: false, rate: true, pitch: false, formant: false,+ },unavailableControls,transformProbe: transforms,},{- id: 'piper',- capabilities: {- preset: true, voiceDesign: false, instantClone: false, fineTune: false,- streaming: false, instructionControl: false, emotionControl: false,- seed: false, wordTimings: false, rate: true, pitch: false, formant: false,+ id: 'piper',+ capabilities: {+ preset: true, voiceDesign: false, instantClone: false, fineTune: false,+ streaming: false, instructionControl: false, emotionControl: false,+ seed: false, wordTimings: false, rate: true, pitch: false, formant: false,+ },+ unavailableControls,+ transformProbe: transforms,},+ {+ id: 'qwen3-tts',+ capabilities: {+ preset: true, voiceDesign: true, instantClone: true, fineTune: true,+ streaming: true, instructionControl: true, emotionControl: true,+ seed: true, wordTimings: true, rate: true, pitch: false, formant: false,+ },unavailableControls,transformProbe: transforms,},@@ -61,23 +66,27 @@ export const listVoiceEngines = async () => {// Normalize `engine` against the allowlist so an invalid value can't silently// produce Kokoro audio while the response reports `engine: 'elevenlabs'`.-const resolveEngine = (engine) => VALID_ENGINES.has(engine) ? engine : 'kokoro';+const resolveEngine = (engine) => {+ const norm = engine === 'qwen3' ? 'qwen3-tts' : engine;+ return VALID_ENGINES.has(norm) ? norm : 'kokoro';+};const backend = (engine) => {if (engine === 'piper') return { synth: synthesizePiper, list: listPiperVoices };+ if (engine === 'qwen3-tts') return { synth: synthesizeQwen3, list: listQwen3Voices };return { synth: synthesizeKokoro, list: listKokoroVoices };};/**- * Synthesize text with the active TTS engine. `opts.voice` and `opts.engine`- * override the configured voice/engine just for this call — used by the- * voice-picker preview so users can audition before saving.+ * Synthesize text with the active TTS engine or profile binding.* @param {string} text* @param {object} [opts]* @param {AbortSignal} [opts.signal]* @param {string} [opts.voice] transient voice override- * @param {string} [opts.engine] transient engine override ('kokoro'|'piper')+ * @param {string} [opts.engine] transient engine override ('kokoro'|'piper'|'qwen3-tts')* @param {number} [opts.rate] transient speech-rate override (0.25–4)+ * @param {string} [opts.profileId] profile ID to synthesize against+ * @param {string} [opts.route] 'studio' | 'interactive'* @returns {Promise<{ wav: Buffer, latencyMs: number, engine: string }>}*/export const synthesize = async (text, opts = {}) => {@@ -86,28 +95,50 @@ export const synthesize = async (text, opts = {}) => {? await getProfileForSynthesis(opts.profileId, opts.route || 'studio'): null;const profileVoice = profile?.voiceId?.split(':')[1] || null;- // An approved profile owns its engine/preset. Letting a caller override one- // would render the wrong character while claiming profile provenance.const engine = profile ? profile.engine : resolveEngine(opts.engine || cfg.tts.engine);const { synth } = backend(engine);- // A profile snapshots the delivery rate at its explicit promotion. It is- // therefore immune to later project-default changes, while legacy preset- // synthesis keeps the old config-driven behavior.+let ttsCfg = profile ? { ...cfg.tts, rate: profile.delivery.rate } : cfg.tts;- // Transient rate override (external public API lets a caller set speed per- // request without persisting it). Clamp defensively even though the route- // schema already bounds it — direct in-process callers bypass the route.if (typeof opts.rate === 'number' && Number.isFinite(opts.rate)) {ttsCfg = { ...ttsCfg, rate: Math.min(4, Math.max(0.25, opts.rate)) };}++ let synthOpts = { ...opts, rate: ttsCfg.rate };++ if (profile) {+ if (profile.kind === 'designed') {+ synthOpts = {+ ...synthOpts,+ mode: 'design',+ instructions: profile.inference?.instructions,+ seed: profile.inference?.seed,+ modelId: profile.inference?.modelId || profile.modelRevision,+ };+ } else if (profile.kind === 'cloned') {+ const sourceAsset = profile.sourceAssets?.[0];+ const sourcePath = sourceAsset?.filename+ ? join(profileArtifactDirectory(profile.id), 'source', sourceAsset.filename)+ : null;+ synthOpts = {+ ...synthOpts,+ mode: 'clone',+ referenceAudio: sourcePath,+ referenceTranscript: sourceAsset?.transcript,+ modelId: profile.inference?.modelId || profile.modelRevision,+ };+ } else if (profile.kind === 'fine-tuned') {+ synthOpts = {+ ...synthOpts,+ mode: 'fine-tuned',+ checkpointPath: profile.inference?.checkpointPath,+ modelId: profile.modelRevision,+ };+ }+ }+const voice = profileVoice || opts.voice;if (voice) {- // Spread from `ttsCfg` (not `cfg.tts`) so a transient rate override applied- // above is preserved alongside the voice override.if (engine === 'kokoro') {- // Reject unknown Kokoro voice overrides (symmetric with the Piper branch- // below) so the public synth API returns the documented 400 UNKNOWN_VOICE- // instead of forwarding a bogus id to the model and erroring/wrong-voicing.if (!isKokoroVoice(voice)) {throw new ServerError(`unknown kokoro voice: ${voice}`, {status: 400,@@ -115,10 +146,7 @@ export const synthesize = async (text, opts = {}) => {});}ttsCfg = { ...ttsCfg, kokoro: { ...ttsCfg.kokoro, voice } };- } else {- // Reject Piper voice overrides that aren't in the curated catalog —- // otherwise `voice` would change but `voicePath` would remain the- // previous config value, silently synthesizing the wrong voice.+ } else if (engine === 'piper') {const catalog = findPiperVoice(voice);if (!catalog) {throw new ServerError(`unknown piper voice: ${voice}`, {@@ -137,10 +165,15 @@ export const synthesize = async (text, opts = {}) => {};}}- const result = await synth(text, ttsCfg, opts.signal);++ const result = engine === 'qwen3-tts'+ ? await synth(text, synthOpts, opts.signal)+ : await synth(text, ttsCfg, opts.signal);+const modelRevision = engine === 'kokoro'- ? `${ttsCfg.kokoro.modelId}:${ttsCfg.kokoro.dtype}`- : `piper:${ttsCfg.piper.voice}`;+ ? `${ttsCfg.kokoro?.modelId || 'kokoro-v0_19'}:${ttsCfg.kokoro?.dtype || 'fp32'}`+ : (engine === 'piper' ? `piper:${ttsCfg.piper?.voice || 'default'}` : (profile?.modelRevision || result.modelRevision));+return {...result,engine,@@ -161,8 +194,7 @@ export const synthesize = async (text, opts = {}) => {/*** Enumerate voices available for the given engine (or the configured one).- * @param {string} [engineOverride] 'kokoro' | 'piper' to preview voices for- * an engine without saving it as active.+ * @param {string} [engineOverride] 'kokoro' | 'piper' | 'qwen3-tts'* @returns {Promise<{ engine: string, voices: Array }>}*/export const listVoices = async (engineOverride) => {