Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add local character Voice Studio with AuK (#8859)

[._.]/76ebec9e6421
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 29e8afdb66..edfc6cffd9 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -96,6 +96,7 @@ const Privacy = lazyWithReload(() => import('./pages/Privacy'));
const Agents = lazyWithReload(() => import('./pages/Agents'));
const Uploads = lazyWithReload(() => import('./pages/Uploads'));
const Settings = lazyWithReload(() => import('./pages/Settings'));
+const VoiceStudio = lazyWithReload(() => import('./pages/VoiceStudio'));
const VoiceCallHost = lazyWithReload(() => import('./pages/VoiceCallHost'));
const ApiExplorer = lazyWithReload(() => import('./pages/ApiExplorer'));
const LocalLlmPlayground = lazyWithReload(() => import('./pages/LocalLlmPlayground'));
@@ -388,6 +389,8 @@ export default function App() {
{/* The FaceTime call host runs in its own tab on the Mac — device
permissions and setSinkId need a real browser profile, and the
page holds a Web Lock so a second tab cannot double-answer. */}
+ <Route path="voices" element={<VoiceStudio />} />
+ <Route path="voices/:profileId" element={<VoiceStudio />} />
<Route path="voice/call-host" element={<VoiceCallHost />} />
<Route path="api-reference" element={<Navigate to="/api-reference/catalog" replace />} />
<Route path="api-reference/:tab" element={<ApiExplorer />} />
diff --git a/client/src/components/universe/CharacterDetailEditor.jsx b/client/src/components/universe/CharacterDetailEditor.jsx
index c9746ad67b..ea085ecf95 100644
--- a/client/src/components/universe/CharacterDetailEditor.jsx
+++ b/client/src/components/universe/CharacterDetailEditor.jsx
@@ -10,6 +10,7 @@
* only knows the field shape.
*/
+import { Link } from 'react-router';
import { useEffect, useId, useRef, useState } from 'react';
import {
Plus, Trash2, WandSparkles, Loader2,
@@ -926,6 +927,7 @@ function VoiceProfileSection({ universeId, entry, disabled }) {
return (
<BoxedSection icon={Mic} label="Local voice profile & Voice Lab" summary={loading ? 'loading' : profileState}>
+
<p className="text-[10px] leading-snug text-gray-500">
Machine-local voice design, consented cloning, and optional fine-tuning. Candidate profiles never mutate approved character voice until explicitly promoted.
</p>
@@ -953,7 +955,7 @@ function VoiceProfileSection({ universeId, entry, disabled }) {
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'}
+ Model: {profile.modelRevision} · Rate: {profile.delivery?.rate ?? 1} · Studio: {profile.routes?.studio?.enabled ? 'Yes' : 'No'} · Interactive: {profile.engine === 'auk' ? (profile.routes?.interactive?.enabled ? 'Buffered enabled' : 'Studio only') : (profile.routes?.interactive?.enabled ? 'Qualified' : 'Pending qualification')}
</p>
{profile.benchmark?.interactiveLatencyMs ? (
<p className="text-[10px] text-port-success">
@@ -1413,6 +1415,12 @@ export default function CharacterDetailEditor({ entry, universeId = null, onPatc
<div className="mt-3 space-y-3">
<div className="flex flex-wrap items-center justify-between gap-2 border-t border-port-border pt-3">
<h3 className="text-sm font-semibold text-port-accent">Character sheet</h3>
+ {universeId && (<Link
+ to={`/voices?${new URLSearchParams({ universeId, characterId: entry.id })}`}
+ className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline"
+ >
+ <Mic size={14} /> Create or assign a voice in Voice Studio
+ </Link>)}
{onExpand ? (
<button type="button" onClick={onExpand} disabled={expanding || disabled}
className="inline-flex min-h-[40px] items-center gap-1.5 px-3 py-2 text-xs rounded border border-port-accent/40 bg-port-accent/10 text-port-accent hover:bg-port-accent/20 disabled:opacity-40"
diff --git a/client/src/components/universe/CharacterDetailEditor.test.jsx b/client/src/components/universe/CharacterDetailEditor.test.jsx
index ebfcb1bb97..16feed91a6 100644
--- a/client/src/components/universe/CharacterDetailEditor.test.jsx
+++ b/client/src/components/universe/CharacterDetailEditor.test.jsx
@@ -507,3 +507,9 @@ describe('CharacterDetailEditor — sheet navigation', () => {
expect(screen.getByRole('button', { name: 'AI: expand character' })).toBeDisabled();
});
});
+
+it('links directly from character design to the shared voice studio with its casting target', () => {
+ render(<CharacterDetailEditor entry={ARIA} universeId="example-universe" onPatch={() => {}} />);
+ expect(screen.getByRole('link', { name: 'Create or assign a voice in Voice Studio' }))
+ .toHaveAttribute('href', '/voices?universeId=example-universe&characterId=chr-aria');
+});
diff --git a/client/src/lib/navPresentation.js b/client/src/lib/navPresentation.js
index eaea98a8be..59ebbce126 100644
--- a/client/src/lib/navPresentation.js
+++ b/client/src/lib/navPresentation.js
@@ -1,4 +1,4 @@
-import {
+import { AudioLines,
Wrench,
Home,
Package,
@@ -191,6 +191,7 @@ export const NAV_PRESENTATION = {
'/start-story': { icon: Rocket },
'/story-builder': { icon: Wand2 },
'/media/threejs': { icon: Box },
+ '/voices': { icon: AudioLines },
'/universes': { icon: Globe, dynamic: 'universes' },
'/writers-room': { icon: NotebookPen },
'/devtools/agents': { icon: Cpu },
diff --git a/client/src/pages/VoiceStudio.jsx b/client/src/pages/VoiceStudio.jsx
new file mode 100644
index 0000000000..cb0c877099
--- /dev/null
+++ b/client/src/pages/VoiceStudio.jsx
@@ -0,0 +1,194 @@
+import { useCallback, useState } from 'react';
+import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
+import { AudioLines, Plus, Loader2, ArrowLeft, Check } from 'lucide-react';
+import { usePagedCollection } from '../hooks/usePagedCollection';
+import InfiniteScrollFooter from '../components/ui/InfiniteScrollFooter';
+import { useSocketResource } from '../hooks/useSocketResource';
+import useAsyncAction from '../hooks/useAsyncAction';
+import useMounted from '../hooks/useMounted';
+import { listUniverseNames, getUniverse } from '../services/apiUniverseBuilder';
+import { listStudioVoices, getStudioVoice, getVoiceStudioStatus, setupVoiceStudio, unloadVoiceStudio,
+ designStudioVoice, assignStudioVoice } from '../services/apiVoice';
+import { formatCount } from '../utils/formatters';
+
+const EVENTS = ['voice-studio:changed'];
+const NO_EVENTS = [];
+const fieldClass = 'w-full min-w-0 rounded border border-port-border bg-port-bg p-2 text-sm';
+const buttonClass = 'inline-flex items-center justify-center gap-2 rounded bg-port-accent px-3 py-2 text-sm text-white disabled:opacity-40';
+const audioUrl = filename => `/data/${filename.split('/').map(encodeURIComponent).join('/')}`;
+
+function VoiceDesignForm({ character, source, ready, onCreated }) {
+ const mounted = useMounted();
+ const [label, setLabel] = useState(source?.label ? `${source.label} variation` : character?.name ? `${character.name} voice` : '');
+ const [instructions, setInstructions] = useState(source?.inference?.instructions || [character?.speechAccent, character?.speechPattern].filter(Boolean).join('. '));
+ const [text, setText] = useState(source?.sourceAssets?.[0]?.transcript || 'There is more to this story than we first imagined.');
+ const [seed, setSeed] = useState(source?.inference?.seed ?? 42);
+ const [rate, setRate] = useState(source?.inference?.rate || 1);
+ const [pitch, setPitch] = useState(source?.inference?.pitchSemitones || 0);
+ const [duration, setDuration] = useState(source?.inference?.genSeconds || 4);
+ const [generate, generating] = useAsyncAction(async () => {
+ const result = await designStudioVoice({ label, instructions, text, seed, rate,
+ pitchSemitones: pitch, genSeconds: duration }, { silent: true });
+ if (mounted.current) onCreated(result.profile);
+ });
+ return <form className="space-y-4" onSubmit={event => { event.preventDefault(); if (!generating) generate(); }}>
+ <h2 className="text-lg font-semibold">Design a character voice</h2>
+ <p className="text-sm text-gray-400">AuK-Flash · local Apple Silicon. Describe timbre, accent, age, and delivery, then audition a short line. Each generation saves a new candidate in your library.</p>
+ <fieldset disabled={generating} className="min-w-0 space-y-3">
+ <div><label htmlFor="voice-label" className="block text-sm mb-1">Voice name</label>
+ <input id="voice-label" required maxLength={160} value={label} onChange={event => setLabel(event.target.value)} className={fieldClass} /></div>
+ <div><label htmlFor="voice-description" className="block text-sm mb-1">Timbre & character direction</label>
+ <textarea id="voice-description" required maxLength={2000} rows={3} value={instructions} onChange={event => setInstructions(event.target.value)}
+ placeholder="Warm low alto, slightly raspy texture, rounded vowels, measured delivery…" className={fieldClass} /></div>
+ <div><label htmlFor="voice-preview-text" className="block text-sm mb-1">Preview dialogue</label>
+ <textarea id="voice-preview-text" required maxLength={400} rows={2} value={text} onChange={event => setText(event.target.value)} className={fieldClass} /></div>
+ <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,12rem),1fr))] gap-3">
+ <div><label htmlFor="voice-pitch" className="block text-sm">Pitch edit: {pitch} semitones</label>
+ <input id="voice-pitch" type="range" min={-12} max={12} step={1} value={pitch} onChange={event => setPitch(Number(event.target.value))} className="w-full" /></div>
+ <div><label htmlFor="voice-rate" className="block text-sm">Pace: {rate}×</label>
+ <input id="voice-rate" type="range" min={0.5} max={2} step={0.1} value={rate} onChange={event => setRate(Number(event.target.value))} className="w-full" /></div>
+ <div><label htmlFor="voice-seed" className="block text-sm mb-1">Variation seed</label>
+ <input id="voice-seed" type="number" required min={0} max={2147483647} value={seed} onChange={event => setSeed(Number(event.target.value))} className={fieldClass} /></div>
+ <div><label htmlFor="voice-duration" className="block text-sm mb-1">Base duration (seconds)</label>
+ <input id="voice-duration" type="number" required min={2} max={6} step={0.5} value={duration} onChange={event => setDuration(Number(event.target.value))} className={fieldClass} /></div>
+ </div>
+ <p className="text-xs text-gray-500">Controls apply when you generate. Pace adjusts the target duration; pitch uses a second model edit. Keep the line short enough to fit. First generation also loads the model.</p>
+ </fieldset>
+ <button type="submit" disabled={!ready || generating || !label.trim() || !instructions.trim() || !text.trim()} className={buttonClass}>
+ {generating ? <Loader2 size={16} className="animate-spin" /> : <AudioLines size={16} />}
+ {generating ? 'Generating voice preview…' : 'Generate & save preview'}
+ </button>
+ <p className="text-xs text-gray-500">Characters keep their current voice until you explicitly assign a candidate.</p>
+ </form>;
+}
+
+function VoiceAssignment({ profile, universeId, character, onAssigned }) {
+ const [assigned, setAssigned] = useState(false);
+ const [enableInteractive, setEnableInteractive] = useState(false);
+ const [assign, assigning] = useAsyncAction(async () => {
+ const result = await assignStudioVoice(profile.id, { universeId, characterId: character.id, enableInteractive }, { silent: true });
+ setAssigned(true);
+ onAssigned(result.profile);
+ });
+ const available = profile.approval.status === 'approved' && ['auk', 'piper'].includes(profile.engine);
+ return <div className="space-y-2 border-t border-port-border pt-4">
+ {profile.engine === 'auk' && <label className="flex items-start gap-2 text-sm">
+ <input type="checkbox" checked={enableInteractive} disabled={assigning || assigned} onChange={event => setEnableInteractive(event.target.checked)} />
+ <span>Use this voice in FableLoom live conversations too. Replies wait for the complete audio; a cold model can take about a minute. This is buffered playback, not streaming.</span>
+ </label>}
+ <button type="button" disabled={!character || !available || assigning || assigned} onClick={assign} className={buttonClass}>
+ {assigning ? <Loader2 size={16} className="animate-spin" /> : assigned ? <Check size={16} /> : null}
+ {assigned ? `Assigned to ${character.name}` : character ? `Use for ${character.name}` : 'Choose a character to assign'}
+ </button>
+ <p className="text-xs text-gray-400">Assignment saves a local snapshot for this universe character. Series dialogue uses this character’s approved studio voice. FableLoom live conversations use it when you enable buffered playback above; otherwise the existing live voice fallback remains.</p>
+ {!available && <p className="text-sm text-port-warning">This legacy voice is not available for assignment here. Create an AuK voice or use a Piper preset.</p>}
+ </div>;
+}
+
+export default function VoiceStudio() {
+ const { profileId } = useParams();
+ const navigate = useNavigate();
+ const [params, setParams] = useSearchParams();
+ const universeId = params.get('universeId') || '';
+ const characterId = params.get('characterId') || '';
+ const context = params.toString() ? `?${params}` : '';
+ const newVoiceParams = new URLSearchParams(params);
+ newVoiceParams.delete('from');
+ const fetchPage = useCallback(({ cursor, signal }) => listStudioVoices({ cursor, limit: 30 }, { signal, silent: true }), []);
+ const library = usePagedCollection(fetchPage);
+ const engine = useSocketResource(async ({ reconcile, events }) => {
+ if (events.length || (reconcile && library.loaded)) await library.reload();
+ return getVoiceStudioStatus({ silent: true });
+ }, { events: EVENTS });
+ const detailId = profileId === 'new' ? params.get('from') : profileId;
+ const detail = useSocketResource(async ({ signal }) => (await getStudioVoice(detailId, { signal, silent: true })).profile,
+ { events: EVENTS, resourceKey: detailId, enabled: Boolean(detailId) });
+ const universes = useSocketResource(() => listUniverseNames({ silent: true }), { events: NO_EVENTS });
+ const universe = useSocketResource(() => getUniverse(universeId, { silent: true }),
+ { events: NO_EVENTS, resourceKey: universeId, enabled: Boolean(universeId) });
+ const character = universe.data?.characters?.find(item => item.id === characterId);
+ const profiles = library.items;
+ const variation = profileId === 'new' ? detail.data : null;
+ const selected = profileId !== 'new' ? detail.data : null;
+ const status = engine.data;
+ const putProfile = () => library.reload();
+ const [setup, settingUp] = useAsyncAction(async () => {
+ const result = await setupVoiceStudio({ silent: true });
+ engine.updateData(current => ({ ...current, ...result }));
+ });
+ const [unload, unloading] = useAsyncAction(async () => {
+ await unloadVoiceStudio({ silent: true });
+ engine.updateData(current => ({ ...current, loaded: false }));
+ });
+ const changeTarget = (key, value) => {
+ const next = new URLSearchParams(params);
+ if (value) next.set(key, value); else next.delete(key);
+ if (key === 'universeId') next.delete('characterId');
+ setParams(next);
+ };
+ return <div className="@container space-y-4 min-w-0">
+ <header className="flex flex-wrap items-center justify-between gap-3">
+ <h1 className="flex items-center gap-2 text-2xl font-semibold"><AudioLines /> Voice Studio</h1>
+ <Link to={`/voices/new?${newVoiceParams}`} className={buttonClass}><Plus size={16} /> Create voice</Link>
+ </header>
+ <p className="text-sm text-gray-400">Create voices once, audition them, and cast characters across your universes and stories.</p>
+ {engine.error && <p role="alert" className="text-port-error">{engine.error.message} <button onClick={engine.refetch} className="underline">Retry</button></p>}
+ {library.loading && <p role="status">Loading voice library…</p>}
+ {status && <section aria-label="Voice engine" className="rounded border border-port-border p-3 flex flex-wrap items-center gap-3">
+ <div className="flex-1 min-w-0 text-sm">
+ <strong>AuK-Flash</strong> · {status.state === 'running' ? status.stage : status.busy ? 'Rendering voice…' : status.ready ? 'Ready on this Mac' : 'Setup required'}
+ {!status.supported && <p className="text-gray-400">Generation requires an Apple Silicon Mac. Saved voices remain browsable.</p>}
+ {status.error && <p role="alert" className="text-port-error">{status.error}</p>}
+ {!status.ready && status.supported && <p className="text-xs text-gray-400">Setup installs an isolated runtime and downloads/converts several GB of model weights. Allow at least 40 GB of free disk space. No speech is generated during setup.</p>}
+ </div>
+ {status.supported && <button className={buttonClass} onClick={setup} disabled={settingUp || status.busy || status.state === 'running'}>{status.ready ? 'Repair setup' : 'Set up AuK locally'}</button>}
+ {status.loaded && <button className="text-sm text-port-accent" onClick={unload} disabled={unloading || status.busy}>Unload model</button>}
+ </section>}
+ <section aria-label="Character assignment target" className="rounded border border-port-border p-3 space-y-2">
+ <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),24rem))] gap-3">
+ <div><label htmlFor="voice-universe" className="block text-sm mb-1">Universe</label>
+ <select id="voice-universe" value={universeId} onChange={event => changeTarget('universeId', event.target.value)} className={fieldClass}>
+ <option value="">Choose a universe</option>{(universes.data || []).map(item => <option key={item.id} value={item.id}>{item.name}</option>)}
+ </select></div>
+ <div><label htmlFor="voice-character" className="block text-sm mb-1">Character</label>
+ <select id="voice-character" value={characterId} disabled={!universe.data} onChange={event => changeTarget('characterId', event.target.value)} className={fieldClass}>
+ <option value="">Choose a character</option>{(universe.data?.characters || []).map(item => <option key={item.id} value={item.id}>{item.name}</option>)}
+ </select></div>
+ </div>
+ {(universes.error || universe.error) && <p role="alert" className="text-port-error">Unable to load character choices. Reload this page to retry.</p>}
+ {universeId && !universe.loading && characterId && !character && <p role="alert">This character is no longer available. Choose another character.</p>}
+ {universeId && <Link className="inline-flex items-center gap-1 text-sm text-port-accent" to={`/universes/${encodeURIComponent(universeId)}?tab=cast`}><ArrowLeft size={14} /> Back to universe cast</Link>}
+ </section>
+ <div className="grid grid-cols-1 @[760px]:grid-cols-[minmax(15rem,1fr)_minmax(0,2fr)] gap-4">
+ <section aria-label="Voice library" className="min-w-0 rounded border border-port-border p-3 space-y-2">
+ <h2 className="font-semibold">Library <span className="text-gray-500">({formatCount(library.total ?? profiles.length)})</span></h2>
+ {!library.loading && !library.error && !profiles.length && <p className="text-sm text-gray-400">No voices yet. Create a voice, listen to the preview, then assign it to a character.</p>}
+ {profiles.map(profile => <Link key={profile.id} to={`/voices/${encodeURIComponent(profile.id)}${context}`}
+ aria-current={profile.id === profileId ? 'page' : undefined}
+ className={`block rounded border p-3 break-words ${profile.id === profileId ? 'border-port-accent bg-port-accent/10' : 'border-port-border hover:border-port-accent/50'}`}>
+ <span className="block text-sm font-medium">{profile.label || profile.voiceId}</span>
+ <span className="text-xs text-gray-500">{profile.engine} · {profile.library ? 'Library voice' : 'Character snapshot'}</span>
+ </Link>)}
+ <InfiniteScrollFooter hasMore={library.hasMore} loading={library.loading} error={library.error} onLoadMore={library.loadMore} autoLoad={false} label="Load more voices" />
+ </section>
+ <section className="min-w-0 rounded border border-port-border p-4">
+ {detailId && detail.error ? <p role="alert">Voice not found or unavailable. Select another voice from the library.</p> : detailId && detail.loading ? <p>Loading voice…</p> : profileId === 'new' ? ((universeId && universe.loading) || (detailId && detail.loading) ? <p>Loading voice direction…</p> :
+ <VoiceDesignForm key={`${universeId}:${characterId}:${variation?.id || ""}`} character={character} source={variation} ready={status?.ready && !status.busy && status.state !== 'running'} onCreated={profile => {
+ putProfile(profile); navigate(`/voices/${profile.id}${context}`);
+ }} />) : selected ? <div className="space-y-4">
+ <h2 className="text-lg font-semibold break-words">{selected.label || selected.voiceId}</h2>
+ <p className="text-sm text-gray-400 whitespace-pre-wrap break-words">{selected.inference?.instructions || 'Preset voice'}</p>
+ {selected.sourceAssets?.[0] && <div className="space-y-2">
+ <p className="text-sm">{selected.sourceAssets[0].transcript}</p>
+ <audio controls preload="none" aria-label="Voice preview" className="w-full" src={audioUrl(`voice-profiles/${selected.id}/source/${selected.sourceAssets[0].filename}`)}><track kind="captions" /></audio>
+ </div>}
+ {!selected.sourceAssets?.length && <p className="text-sm text-gray-400">This legacy profile has no saved reference preview.</p>}
+ <p className="text-xs text-gray-500">Seed {selected.inference?.seed} · Pitch {selected.inference?.pitchSemitones || 0} semitones · Preview pace {selected.inference?.rate || 1}×</p>
+ <Link className="inline-flex text-sm text-port-accent" to={`/voices/new?${new URLSearchParams({ ...Object.fromEntries(params), from: selected.id })}`}>Adjust this voice as a new candidate</Link>
+ <VoiceAssignment key={`${selected.id}:${universeId}:${characterId}`} profile={selected} universeId={universeId} character={character} onAssigned={putProfile} />
+ </div> : profileId && !library.loading && !library.error ? <p role="alert">Voice not found. Select another voice from the library.</p> :
+ <p className="text-sm text-gray-400">Select a voice to listen and assign, or create a new character voice.</p>}
+ </section>
+ </div>
+ </div>;
+}
diff --git a/client/src/pages/VoiceStudio.test.jsx b/client/src/pages/VoiceStudio.test.jsx
new file mode 100644
index 0000000000..7d7d56ff87
--- /dev/null
+++ b/client/src/pages/VoiceStudio.test.jsx
@@ -0,0 +1,63 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { MemoryRouter, Routes, Route } from 'react-router';
+import VoiceStudio from './VoiceStudio';
+import * as api from '../services/apiVoice';
+import { getUniverse } from '../services/apiUniverseBuilder';
+vi.mock('../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));
+vi.mock('../services/apiVoice', () => ({
+ listStudioVoices: vi.fn(), getStudioVoice: vi.fn(), getVoiceStudioStatus: vi.fn(), setupVoiceStudio: vi.fn(), unloadVoiceStudio: vi.fn(),
+ designStudioVoice: vi.fn(), assignStudioVoice: vi.fn(),
+}));
+vi.mock('../services/apiUniverseBuilder', () => ({ listUniverseNames: vi.fn().mockResolvedValue([{ id: 'u1', name: 'Example Universe' }]), getUniverse: vi.fn() }));
+vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn() } }));
+const profile = { id: 'voice-1', label: 'Example voice', library: true, engine: 'auk', approval: { status: 'approved' },
+ sourceAssets: [{ filename: 'reference.wav', transcript: 'Hello there.' }], inference: { seed: 42, instructions: 'Warm alto' } };
+const open = path => render(<MemoryRouter initialEntries={[path]}><Routes>
+ <Route path="/voices" element={<VoiceStudio />} /><Route path="/voices/:profileId" element={<VoiceStudio />} />
+</Routes></MemoryRouter>);
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.listStudioVoices.mockResolvedValue({ items: [profile], total: 1, nextCursor: null });
+ api.getStudioVoice.mockResolvedValue({ profile });
+ api.getVoiceStudioStatus.mockResolvedValue({ supported: true, ready: true, state: 'idle' });
+ getUniverse.mockResolvedValue({ characters: [{ id: 'c1', name: 'Example Character', speechAccent: 'Warm alto' }] });
+});
+describe('Voice Studio', () => {
+ it('opens a bookmarked audition and assigns only after an explicit action to the linked character', async () => {
+ api.assignStudioVoice.mockResolvedValue({ profile: { ...profile, id: 'bound-1', library: false, binding: { universeId: 'u1', characterId: 'c1' } } });
+ api.listStudioVoices.mockResolvedValue({ items: [], total: 0, nextCursor: null });
+ open('/voices/voice-1?universeId=u1&characterId=c1');
+ expect(await screen.findByLabelText('Voice preview')).toHaveAttribute('src', '/data/voice-profiles/voice-1/source/reference.wav');
+ expect(api.assignStudioVoice).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('checkbox'));
+ fireEvent.click(await screen.findByRole('button', { name: 'Use for Example Character' }));
+ await waitFor(() => expect(api.assignStudioVoice).toHaveBeenCalledWith('voice-1', { universeId: 'u1', characterId: 'c1', enableInteractive: true }, { silent: true }));
+ expect(await screen.findByRole('button', { name: 'Assigned to Example Character' })).toBeDisabled();
+ });
+ it('generates with explicit controls, navigates to the saved preview, and keeps assignment separate', async () => {
+ api.designStudioVoice.mockResolvedValue({ profile });
+ open('/voices/new?universeId=u1&characterId=c1');
+ const label = await screen.findByLabelText('Voice name');
+ expect(label).toHaveValue('Example Character voice');
+ fireEvent.change(screen.getByLabelText('Pitch edit: 0 semitones'), { target: { value: '-3' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Generate & save preview' }));
+ expect(await screen.findByLabelText('Voice preview')).toBeInTheDocument();
+ expect(api.designStudioVoice).toHaveBeenCalledWith(expect.objectContaining({ pitchSemitones: -3, instructions: 'Warm alto' }), { silent: true });
+ expect(api.assignStudioVoice).not.toHaveBeenCalled();
+ });
+ it('never installs or generates on page load and disables generation until setup succeeds', async () => {
+ api.getVoiceStudioStatus.mockResolvedValue({ supported: true, ready: false, state: 'idle' });
+ open('/voices/new');
+ expect(await screen.findByRole('button', { name: 'Set up AuK locally' })).toBeEnabled();
+ expect(screen.getByRole('button', { name: 'Generate & save preview' })).toBeDisabled();
+ expect(api.setupVoiceStudio).not.toHaveBeenCalled();
+ expect(api.designStudioVoice).not.toHaveBeenCalled();
+ });
+ it('shows a stale voice URL as missing instead of silently selecting another voice', async () => {
+ api.getStudioVoice.mockRejectedValue(new Error('Not found'));
+ open('/voices/deleted');
+ expect(await screen.findByRole('alert')).toHaveTextContent('Voice not found');
+ expect(screen.queryByLabelText('Voice preview')).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/services/apiVoice.js b/client/src/services/apiVoice.js
index 3a2a286e48..f6cd53ed31 100644
--- a/client/src/services/apiVoice.js
+++ b/client/src/services/apiVoice.js
@@ -50,3 +50,19 @@ export const unloadKokoroTts = (options) => api.post('/voice/tts/unload', {}, op
export const controlWhisper = (action, options) => api.post('/voice/whisper', { action }, options);
export const getFaceTimeStatus = (options) => api.get('/voice/facetime/status', options);
export const controlFaceTime = (action, options) => api.post(`/voice/facetime/${action}`, {}, options);
+
+// Voice Studio: local reusable character voices and explicit runtime setup.
+export const getVoiceStudioStatus = options => api.get('/voice/studio/status', options);
+export const setupVoiceStudio = options => api.post('/voice/studio/setup', {}, options);
+export const unloadVoiceStudio = options => api.post('/voice/studio/unload', {}, options);
+export const designStudioVoice = (payload, options) => api.post('/voice/studio/design', payload, options);
+export const assignStudioVoice = (id, payload, options) => api.post(
+ `/voice/profiles/${encodeURIComponent(id)}/assign`, payload, options,
+);
+
+export const listStudioVoices = ({ cursor, limit = 30 } = {}, options) => {
+ const params = new URLSearchParams({ limit });
+ if (cursor) params.set('cursor', cursor);
+ return api.get(`/voice/studio/profiles?${params}`, options);
+};
+export const getStudioVoice = (id, options) => api.get(`/voice/profiles/${encodeURIComponent(id)}`, options);
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 9b90328492..a434c4205b 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -48,6 +48,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- `catalog_user_types` — user-defined ingredient types (the registry that defines catalog row semantics), one row per type (`id` PK, the definition in `data` JSONB, `updated_at`/`deleted_at` mirroring the federation LWW clock + tombstone). Migrated from the `data/settings.json` `catalogUserTypes` slice in Phase 4 lead-in (#1001) so type evolution versions/syncs alongside the catalog data it governs. Federates via the catalog sync `catalogTypes` envelope block (wire shape unchanged by the move). Adapter: `server/services/catalogUserTypes/db.js`, dispatched via `store.js`.
- `sync_feed` — the commit-ordered federation change feed (#8315) behind the `memories` and catalog-table peer pulls: one row per live row version, `(stream = table name, row_sequence = that row's sync_sequence) → position`. A position is drawn at COMMIT by deferred constraint triggers serialized on one transaction-scoped advisory lock, so a transaction that commits late can never land below a cursor a peer already advanced past (the write-time `sync_sequence` could). Peers page by position; positions start at 1e15, so a pre-feed cursor replays each stream once after an upgrade (apply is LWW / ON CONFLICT, so nothing is duplicated). Machine-local bookkeeping — only the rows it points at federate. DDL: `server/lib/db/schema/syncFeed.js` + `init-db.sql`; existing rows are backfilled by db-migration `009-commit-ordered-sync-feed.js`.
- `universes` / `universe_runs` — Universe Builder records (canon bibles, categories, composite sheets, locks, influences, and portable character production packages) one row per universe with the full sanitized record in `data` JSONB and `name`/`schema_version`/`ephemeral`/`updated_at`/`deleted`/`deleted_at` mirrored into columns; render-run history one row per run (local-only, capped 200, never federated). Character production packages carry only versioned voice direction and approved managed-image roles; local profiles, recordings, provider ids, and training artifacts are excluded from the federated wire. Migrated from `data/universes/{id}/index.json` (collectionStore) in Phase 3 Create slice 1 (#1014). **NO `sync_sequence`** — universes federate via the EXISTING `dataSync` snapshot/push model (LWW on the body's `updatedAt`), so the storage swap is invisible to peers (no schema-version bump). The store bumps an in-process mutation epoch on every write that `dataSync` folds into its checksum fingerprint, since a DB edit no longer changes the `data/universes/` directory the fingerprint used to watch. **`universe_runs` is intentionally never federated** — a regenerable render cache under a 200-row *global* cap that two producers would mutually evict, while the durable universe record already syncs (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724). Adapter: `server/services/universeBuilder/db.js`, dispatched via `store.js`. **One universe ships with the product:** `universe-reality` ("Reality"), seeded by `scripts/migrations/395-reality-universe-seed.js` — not by `data.reference/`, because universes are PG rows and `setup-data.js` only copies files. It carries the federated `factual: true` flag (#7616), which marks a world whose people and places are real so the catalog extractor reads captured text as lived record rather than invented story; `factual` is persisted ONLY when true, so every fiction universe keeps its exact on-disk shape and wire checksum, and `PORTOS_SCHEMA_VERSIONS.universes` is 12 so a `factual`-unaware peer cannot strip-then-LWW the flag away. The migration gates on the ABSENCE of any row with that id — tombstone included — so a Reality the user deleted is never resurrected by an upgrade.
+- Voice Studio extends `voice_profiles` with unbound library records (`library: true`, nullable universe/character columns). Assignment copies the approved reference and creates a bound snapshot with `originProfileId`; the existing unique approved-binding index remains in force. Metadata is `db-primary`, reference WAVs are managed assets under the existing backup path, and neither is federated. Migration 416 records the idempotent boot DDL; no seed is shipped.
- `voice_profiles` / `voice_profile_renders` — machine-local DB-primary records for approved `(universeId, characterId)` bindings and the latest rendered dialogue line per `(issueId, lineId)`. They store the promoted Kokoro/Piper preset, profile revision, route availability, benchmark provenance, and reproducible dialogue delivery details (engine/model revision, timing, controls, and mastering). The portable Universe character and federated pipeline issue keep only portable voice data and audio filenames; they never store a local profile id. Rendered benchmark WAVs, safe-basename source-asset metadata, and future local engine artifacts live under `data/voice-profiles/<profileId>/`. Both the PostgreSQL dump and that managed directory are included in normal backup, while peer sync intentionally carries neither. Adapter: `server/services/voice/profiles.js`.
- `tribe_people` / `tribe_touchpoints` / `tribe_memory_links` — the Tribe relationship/CRM graph (people + their care cadence, contact touchpoints, and cross-links into brain `memories`). **Intentionally machine-local — never federated** (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724): it is relationship-graph data, mirroring the deliberate "memory_links are instance-local" boundary in `memorySync.js` (memory *nodes* federate, the link graph does not), and is coupled to machine-local domains — `tribe_memory_links` extends the non-federated `memory_links` layer and `tribe_touchpoints` carry per-machine calendar-account refs. NO `sync_sequence`, no peer-sync record kind, no `dataSync` category. **Deletes are erased after 30 days** (#8459): deleting a person is a soft delete (a recovery window only — the tombstone is never needed for sync), and the daily `tribePurge` sweep (`server/services/tribePurge.js` → `tribe.purgeDeletedPeople`) hard-deletes people tombstoned more than `DELETED_PERSON_RETENTION_DAYS` ago — cascading to their touchpoints, identities and memory links — and removes every `record_audit` snapshot of them. The same sweep expires all `tribe_*` `record_audit` rows older than the window, since those snapshots copy a third party's contact details and notes; creative-table audit rows are never touched. Adapter: `server/services/tribe.js`.
- `creative_commissions` — Creative Commissions (Autonomous Creation Engine, #2657/#2686): standing recurring creative briefs that fire on a cron cadence and drive the Creative Director directive pipeline unattended. One row per commission, the full sanitized record in `data` JSONB with `name`/`enabled`/`created_at`/`updated_at` mirrored into columns for the scheduler's "arm every enabled commission" query. The brief/identity federates as `creativeCommission` so synced feedback can attach to the same commission; `schedule`, `runs`, `assignment`, `enabled`, and feedback view stay machine-local (the per-reaction `commissionFeedback` records federate separately). The opt-in Digital Twin music-taste configuration is bounded brief metadata; raw taste sources and per-run recipes never cross the wire. The file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only. Adapter: `server/services/creativeCommissions/db.js`, selected pg-vs-file by `server/services/creativeCommissions/store.js` (file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only).
diff --git a/docs/features/voice.md b/docs/features/voice.md
index fea05d5dbf..a2868dd775 100644
--- a/docs/features/voice.md
+++ b/docs/features/voice.md
@@ -277,3 +277,41 @@ reuses the same `voice:call:audio` PCM frames (`voice:capture:start` /
| Whisper base.en (no CoreML) | 0 (server resident) | 400–800 ms / 2 s of audio | Good |
| Whisper base.en + CoreML | 0 | 150–300 ms / 2 s of audio | Good |
| Whisper small.en + CoreML | 0 | 300–600 ms / 2 s of audio | Better |
+
+## Character Voice Studio
+
+**Create → Voice Studio** (`/voices`) is the reusable voice library. A character's
+sheet links here with its universe and character selected. `/voices/new`
+creates a voice; `/voices/:profileId` auditions and assigns it. Series dialogue
+and FableLoom live conversations reuse the universe-character voice resolver.
+Assigning copies an approved reference into a separate character profile, so
+experimentation in the library does not silently replace a cast voice. Profiles
+and reference audio remain machine-local, following the existing voice policy.
+
+AuK-Flash uses the official `feat/mlx-apple-silicon` backend with 8-bit inference.
+On Apple Silicon, **Set up AuK locally** provisions an isolated Python runtime
+under `~/.portos/auk`, downloads weights, and converts them to MLX. It requires
+`uv`, network access, and at least 40 GB free disk space. Setup is explicit;
+startup and page reads never download weights or generate speech. Other hosts
+can browse their stored library but cannot run this MLX engine.
+
+Timbre/accent/delivery use natural-language direction. Pitch is a separate AuK
+acoustic edit in semitones. Pace changes target duration; the operator must
+listen for intelligibility and clipping before assigning. Previews are 2–6
+base seconds, scaled by pace. Longer dialogue is split without dropping text
+into model segments of at most 12 seconds, all conditioned on the same voice
+reference, then joined into one WAV (up to 32 segments per request). Controls take
+effect on generation, not continuously during playback. Each generation creates
+a new candidate, with a preserved WAV reference, transcript, seed, and settings.
+The resident model is reused for previews and unloaded after ten idle minutes
+or through **Unload model**. Inference is serialized and times out after three
+minutes. Assignment offers an explicit **Use this voice in FableLoom live
+conversations too** option. It accepts buffered playback (the whole reply must
+finish before playback, up to the three-minute runtime timeout), not low-latency
+streaming qualification. Without that opt-in, AuK remains studio-only and the
+existing interactive fallback is retained. The production planner checks the
+interactive route rather than treating every approved studio voice as live-ready.
+
+The legacy Qwen runtime has placeholder inference/training and is excluded from
+Voice Studio assignment until repaired (issue #8857). Voice Studio does not
+claim a Qwen runtime is working merely because its metadata exists.
diff --git a/scripts/auk_voice_worker.py b/scripts/auk_voice_worker.py
new file mode 100644
index 0000000000..8f6a87d92b
--- /dev/null
+++ b/scripts/auk_voice_worker.py
@@ -0,0 +1,62 @@
+"""Resident AuK MLX worker. One JSON request/response per line; models load on demand."""
+import contextlib
+import json
+import os
+import sys
+import time
+from pathlib import Path
+
+
+def main():
+ # Never fetch models during synthesis; installation is an explicit UI action.
+ os.environ["HF_HUB_OFFLINE"] = "1"
+ os.environ["TRANSFORMERS_OFFLINE"] = "1"
+ root = Path(sys.argv[1])
+ engine = None
+ for line in sys.stdin:
+ request = json.loads(line)
+ started = time.monotonic()
+ try:
+ with contextlib.redirect_stdout(sys.stderr):
+ import soundfile as sf
+ from auk_mlx.infer import AukMLX, GenerateOptions
+ if engine is None:
+ engine = AukMLX(str(root / 'ckpts/mlx'),
+ str(root / 'ckpts/AuK-Flash/config.yaml'),
+ str(root / 'ckpts/Qwen2.5-Omni-3B'), bits=8)
+ import numpy as np
+ reference = request.get('referenceAudio')
+ chunks = []
+ intermediate = request['output'] + '.source.wav'
+ generated_reference = request['output'] + '.reference.wav'
+ try:
+ for segment in request['segments']:
+ text = json.dumps(segment['text'], ensure_ascii=False)
+ instruction = (f'Say the following with the same voice: {text}' if reference else
+ f'Generate speech based on the following description: {json.dumps(request["instructions"], ensure_ascii=False)}. The content to speak is: {text}.')
+ opts = GenerateOptions(gen_seconds=segment['seconds'], seed=request['seed'])
+ audio, sr = engine.generate(instruction, audio_path=reference, opts=opts)
+ pitch = request.get('pitchSemitones', 0)
+ if pitch:
+ sf.write(intermediate, audio, sr)
+ audio, sr = engine.generate(
+ f'{"Raise" if pitch > 0 else "Lower"} the pitch by {abs(pitch)} semitones.',
+ audio_path=intermediate, opts=opts)
+ chunks.append(audio)
+ # Longer narration keeps one identity even without a preexisting profile.
+ if not reference and len(request['segments']) > 1:
+ sf.write(generated_reference, audio, sr)
+ reference = generated_reference
+ sf.write(request['output'], np.concatenate(chunks, axis=0), sr)
+ finally:
+ Path(intermediate).unlink(missing_ok=True)
+ Path(generated_reference).unlink(missing_ok=True)
+ elapsed = round((time.monotonic() - started) * 1000)
+ print(json.dumps({'ok': True, 'latencyMs': elapsed, 'firstAudioMs': elapsed}), flush=True)
+ except Exception as exc:
+ # Keep prompts, local paths, and dependency diagnostics out of HTTP responses.
+ print(json.dumps({'ok': False, 'error': type(exc).__name__}), flush=True)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/migrations/416-voice-studio-library.js b/scripts/migrations/416-voice-studio-library.js
new file mode 100644
index 0000000000..7a9632fcef
--- /dev/null
+++ b/scripts/migrations/416-voice-studio-library.js
@@ -0,0 +1,9 @@
+/** Voice Studio library profiles have no character binding until assigned.
+ * ensureSchema applies the idempotent nullability change to existing installs.
+ * Existing bound records and their unique approved-binding index are preserved.
+ */
+export default {
+ async up() {
+ console.log('🎙️ Voice Studio library schema is applied by ensureSchema at boot');
+ },
+};
diff --git a/server/lib/apiToolResource.test.js b/server/lib/apiToolResource.test.js
index 78c2d8ad2d..b68ea545c8 100644
--- a/server/lib/apiToolResource.test.js
+++ b/server/lib/apiToolResource.test.js
@@ -52,7 +52,7 @@ describe('buildToolResource', () => {
it('flattens an object request body into the argument schema and keeps property descriptions', () => {
const input = byName('voice.synthesize').input_schema;
expect(input.required).toEqual(['text']);
- expect(input.properties.engine.enum).toEqual(['piper', 'qwen3-tts']);
+ expect(input.properties.engine.enum).toEqual(['auk', 'piper', 'qwen3-tts']);
// The description is what lets a model pick a valid rate — minimization must not strip it.
expect(input.properties.rate.description).toMatch(/Speech rate/);
expect(input.additionalProperties).toBe(false);
@@ -60,7 +60,7 @@ describe('buildToolResource', () => {
it('turns query parameters into input properties', () => {
const input = byName('voice.list-voices').input_schema;
- expect(input.properties.engine).toEqual({ type: 'string', enum: ['piper', 'qwen3-tts'] });
+ expect(input.properties.engine).toEqual({ type: 'string', enum: ['auk', 'piper', 'qwen3-tts'] });
expect(input.required).toBeUndefined(); // the engine param is optional
});
diff --git a/server/lib/db/schema/universes.js b/server/lib/db/schema/universes.js
index 0277e18667..2cc2bebfdd 100644
--- a/server/lib/db/schema/universes.js
+++ b/server/lib/db/schema/universes.js
@@ -46,6 +46,8 @@ export const universesDdl = [
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
)`,
+ `ALTER TABLE voice_profiles ALTER COLUMN universe_id DROP NOT NULL`,
+ `ALTER TABLE voice_profiles ALTER COLUMN character_id DROP NOT NULL`,
`CREATE INDEX IF NOT EXISTS idx_voice_profiles_binding ON voice_profiles (universe_id, character_id, updated_at DESC)`,
`CREATE UNIQUE INDEX IF NOT EXISTS idx_voice_profiles_approved_binding ON voice_profiles (universe_id, character_id) WHERE approval_status = 'approved'`,
diff --git a/server/lib/fableLoomProduction.js b/server/lib/fableLoomProduction.js
index 57eca66d41..1cf5a6410d 100644
--- a/server/lib/fableLoomProduction.js
+++ b/server/lib/fableLoomProduction.js
@@ -42,7 +42,7 @@ export const FABLELOOM_RENDER_PREFERENCE_KEYS = Object.freeze([
]);
const isRecord = (value) => value != null && typeof value === 'object' && !Array.isArray(value);
-const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
+const hasOwn = (value, key) => Object.hasOwn(value, key);
const trimModelId = (value) => (typeof value === 'string' && value.trim()
? value.trim().slice(0, 64)
: null);
@@ -715,6 +715,7 @@ export function buildEpisodeProductionPlan({
profile.binding?.characterId === interactionCharacterId
&& (!universe?.id || profile.binding?.universeId === universe.id)
&& profile.approval?.status === 'approved'
+ && profile.routes?.interactive?.enabled === true
));
if (!approvedProfile && !interactionCharacter?.voiceId && !loom?.defaultVoiceId) {
nodeBlockers.push(`Live interaction protagonist "${interactionCharacterId || 'unknown'}" has no approved voice binding.`);
@@ -878,6 +879,7 @@ export function buildEpisodeProductionPlan({
p.binding?.characterId === charId
&& (!universe?.id || p.binding?.universeId === universe.id)
&& p.approval?.status === 'approved'
+ && p.routes?.interactive?.enabled === true
));
const dialogueBlockers = [];
diff --git a/server/lib/fableLoomProduction.test.js b/server/lib/fableLoomProduction.test.js
index 7a8a11f1b0..0a602140f3 100644
--- a/server/lib/fableLoomProduction.test.js
+++ b/server/lib/fableLoomProduction.test.js
@@ -185,6 +185,19 @@ describe('fableLoomProduction', () => {
.toBe(true);
});
+ it('requires the interactive route before an approved studio voice satisfies live casting', () => {
+ const episode = { ...sampleEpisode, nodes: [{ ...sampleEpisode.nodes[0], transitions: [],
+ interactionWindow: { enabled: true, protagonistCharacterId: 'char-1' } }] };
+ const profile = { id: 'voice-1', binding: { universeId: 'u1', characterId: 'char-1' },
+ approval: { status: 'approved' }, routes: { studio: { enabled: true }, interactive: { enabled: false } } };
+ const options = { episode, universe: { id: 'u1', characters: [{ id: 'char-1', name: 'Example' }] },
+ loom: { id: 'loom-1', protagonistCharacterId: 'char-1' }, localVoiceProfiles: [profile] };
+ const reasons = () => buildEpisodeProductionPlan(options).plannedAssets.find(asset => asset.type === 'dialogue').readiness.reasons;
+ expect(reasons().some(reason => /no approved voice binding/i.test(reason))).toBe(true);
+ profile.routes.interactive.enabled = true;
+ expect(reasons().some(reason => /no approved voice binding/i.test(reason))).toBe(false);
+ });
+
it('refuses exact-input planning when a node has no recorded provenance', () => {
const plan = buildEpisodeProductionPlan({
episode: sampleEpisode,
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 3292fee284..47564bf58b 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -68,6 +68,7 @@ const RAW_NAV_COMMANDS = [
{ id: 'nav.media.sprites', path: '/sprites', label: 'Sprites', section: 'Create', previousPaths: ['/media/sprites', '/media/sprites/:id'], aliases: ['sprites', 'sprite', 'sprite-manager', 'sprite-sheets'], keywords: ['sprite sheet', 'atlas', 'game art', 'pixel art', 'character animation', 'walk cycle', 'anchors'] },
{ id: 'nav.create.3d', path: '/3d', label: '3D', section: 'Create', previousPaths: ['/media/3d', '/media/3d/:id'], aliases: ['3d', 'image-to-mesh', 'mesh', 'trellis', 'pixal3d', 'neural-3d'], keywords: ['trellis', 'pixal3d', 'pixal', 'glb', 'mesh', 'photogrammetry', 'neural', 'image to 3d', 'render', 'generate', 'pbr'] },
{ id: 'nav.create.authors', path: '/authors', label: 'Authors', section: 'Create', aliases: ['authors', 'author', 'byline', 'author-persona', 'writer-persona'], keywords: ['author', 'byline', 'pen name', 'persona', 'writing style', 'bio', 'headshot', 'cover', 'book author'] },
+ { id: 'nav.create.voice-studio', path: '/voices', label: 'Voice Studio', section: 'Create', aliases: ['voice-studio', 'character-voices', 'voice-lab'], keywords: ['auk', 'speech', 'timbre', 'pitch', 'design', 'characters', 'tts'] },
{ id: 'nav.create.universe-builder', path: '/universes', label: 'Universes', section: 'Create', previousPaths: ['/media/universe-builder', '/media/universe-builder/:universeId', '/universe-builder', '/universe-builder/:universeId'], aliases: ['universes', 'universe', 'universe-builder', 'worldbuilder', 'worldbuild', 'world', 'lore', 'universe-canon', 'canon'], keywords: ['style template', 'sci-fi', 'fantasy', 'concept art', 'batch render', 'variations', 'characters', 'settings', 'objects', 'canon entries', 'list', 'manage'] },
{ id: 'nav.create.importer', path: '/importer', label: 'Importer', section: 'Create', aliases: ['importer', 'import'], keywords: ['paste', 'screenplay', 'novel', 'short story', 'comic script', 'analyze', 'reverse-engineer', 'extract'] },
{ id: 'nav.create.pipeline', path: '/pipeline', label: 'Series Pipeline', section: 'Create', aliases: ['series', 'pipeline', 'production', 'series-pipeline', 'production-pipeline'], keywords: ['series', 'issue', 'episode', 'comic', 'script', 'prose', 'storyboard', 'narrative', 'workflow'] },
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index f2ea7aa38b..0c484be967 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -44,6 +44,10 @@ const loomRunSnapshot = (production) => Object.freeze({
});
export const SOCKET_EVENT_CONTRACTS = Object.freeze({
+ 'voice-studio:changed': {
+ direction: 'server-to-client', summary: 'Voice library or runtime setup changed; refetch authenticated state.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
'fleet-host:subscribe': {
direction: 'client-to-server', summary: 'Observe local fleet host readiness while this operator socket is subscribed.',
payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
diff --git a/server/lib/voiceEngines.js b/server/lib/voiceEngines.js
index bc4650e31c..8d7828d21d 100644
--- a/server/lib/voiceEngines.js
+++ b/server/lib/voiceEngines.js
@@ -1,6 +1,15 @@
// Shared TTS engine metadata. The registry is returned by /api/voice/engines so
// clients can render and update engines without copying IDs or config keys.
export const TTS_ENGINE_REGISTRY = Object.freeze({
+ auk: Object.freeze({
+ configKey: 'auk', label: 'AuK-Flash', description: 'Local character voice design on Apple Silicon',
+ voiceHint: 'Create and audition reusable character voices in Create → Voice Studio.',
+ capabilities: {
+ preset: false, voiceDesign: true, instantClone: false, fineTune: false,
+ streaming: false, instructionControl: true, emotionControl: true,
+ seed: true, wordTimings: false, rate: true, pitch: true, formant: false,
+ },
+ }),
piper: Object.freeze({
configKey: 'piper',
label: 'Piper',
diff --git a/server/routes/voice.js b/server/routes/voice.js
index e8b6f22e3f..bae54d46be 100644
--- a/server/routes/voice.js
+++ b/server/routes/voice.js
@@ -19,6 +19,8 @@ import { reconcile, verifyBinaries, verifyModels, downloadPiperVoice, startWhisp
import { synthesize, listVoices, listVoiceEngines, VALID_ENGINES } from '../services/voice/tts.js';
import {
listVoiceProfiles,
+ listStudioProfiles,
+ getVoiceProfileRequired,
parsePresetVoiceId,
promotePresetProfile,
createVoiceDesignCandidate,
@@ -189,10 +191,11 @@ router.get('/facetime/status', asyncHandler(async (_req, res) => {
res.json(await facetimeBridge.checkSetup());
}));
+const facetimeActions = { probe: facetimeBridge.probe, call: facetimeBridge.call, hangup: facetimeBridge.hangup };
for (const command of ['probe', 'call', 'hangup']) {
router.post(`/facetime/${command}`, asyncHandler(async (req, res) => {
validateRequest(facetimeActionSchema, req.body || {});
- res.json(await facetimeBridge[command]());
+ res.json(await facetimeActions[command]());
}));
}
@@ -275,6 +278,71 @@ const profileIdParamsSchema = z.object({
id: z.string().trim().regex(/^[a-z0-9][a-z0-9-]{0,79}$/),
}).strict();
+const studioDesignSchema = z.object({
+ label: z.string().trim().min(1).max(160),
+ instructions: z.string().trim().min(1).max(2000),
+ text: z.string().trim().min(1).max(400),
+ seed: z.number().int().min(0).max(2147483647).default(42),
+ rate: z.number().min(0.5).max(2).default(1),
+ pitchSemitones: z.number().int().min(-12).max(12).default(0),
+ genSeconds: z.number().min(2).max(6).default(4),
+}).strict();
+const studioAssignmentSchema = z.object({
+ enableInteractive: z.boolean().default(false),
+ universeId: z.string().trim().min(1).max(160),
+ characterId: z.string().trim().min(1).max(160),
+}).strict();
+const notifyStudio = req => req.app.get('io')?.emit('voice-studio:changed', {});
+// Include legacy character-editor mutations so an open library stays current.
+router.use('/profiles', (req, res, next) => {
+ if (req.method !== 'GET' && req.method !== 'HEAD') res.once('finish', () => {
+ if (res.statusCode < 400) notifyStudio(req);
+ });
+ next();
+});
+
+router.get('/studio/profiles', asyncHandler(async (req, res) => {
+ const filters = validateRequest(z.object({
+ limit: z.coerce.number().int().min(1).max(100).default(30),
+ cursor: z.string().max(512).optional(),
+ }).strict(), req.query);
+ res.json(await listStudioProfiles(filters));
+}));
+router.get('/profiles/:id', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(profileIdParamsSchema, req.params);
+ res.json({ profile: await getVoiceProfileRequired(id) });
+}));
+router.get('/studio/status', asyncHandler(async (_req, res) => {
+ const { getAukStatus } = await import('../services/voice/aukRuntime.js');
+ res.json(await getAukStatus());
+}));
+router.post('/studio/setup', asyncHandler(async (req, res) => {
+ validateRequest(facetimeActionSchema, req.body || {});
+ const { startAukSetup } = await import('../services/voice/aukRuntime.js');
+ res.status(202).json(startAukSetup(() => notifyStudio(req)));
+}));
+router.post('/studio/unload', asyncHandler(async (req, res) => {
+ validateRequest(facetimeActionSchema, req.body || {});
+ const { unloadAuk } = await import('../services/voice/aukRuntime.js');
+ unloadAuk();
+ notifyStudio(req);
+ res.json({ ok: true });
+}));
+router.post('/studio/design', asyncHandler(async (req, res) => {
+ const body = validateRequest(studioDesignSchema, req.body || {});
+ const { createStudioVoice } = await import('../services/voice/studio.js');
+ const profile = await createStudioVoice(body);
+ notifyStudio(req);
+ res.status(201).json({ profile });
+}));
+router.post('/profiles/:id/assign', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(profileIdParamsSchema, req.params);
+ const body = validateRequest(studioAssignmentSchema, req.body || {});
+ const { assignStudioVoice } = await import('../services/voice/studio.js');
+ const profile = await assignStudioVoice(id, body);
+ res.json({ profile });
+}));
+
// GET /api/voice/engines
router.get('/engines', asyncHandler(async (_req, res) => {
res.json({ engines: await listVoiceEngines() });
diff --git a/server/routes/voice.test.js b/server/routes/voice.test.js
index c0682d2350..dfdfc5bb83 100644
--- a/server/routes/voice.test.js
+++ b/server/routes/voice.test.js
@@ -2,6 +2,8 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import express from 'express';
const { request } = await import('../lib/testHelper.js');
+vi.mock('../services/voice/studio.js', () => ({ createStudioVoice: vi.fn(), assignStudioVoice: vi.fn() }));
+
// Mock all voice service modules before importing the router so the route
// file's top-level imports resolve to the mocks.
vi.mock('../services/voice/config.js', () => ({
@@ -637,3 +639,18 @@ describe('Voice Routes', () => {
});
});
});
+
+describe('Voice Studio HTTP contract', () => {
+ it('validates controls before generation and emits only a payload-free invalidation after success', async () => {
+ const { createStudioVoice } = await import('../services/voice/studio.js');
+ const emit = vi.fn();
+ const app = buildApp({ io: { emit } });
+ createStudioVoice.mockResolvedValue({ id: 'voice-example', label: 'Example voice' });
+ const invalid = await request(app).post('/api/voice/studio/design').send({ label: 'Example', instructions: 'Alto', text: 'Hello', pitchSemitones: 99 });
+ expect(invalid.status).toBe(400);
+ expect(createStudioVoice).not.toHaveBeenCalled();
+ const valid = await request(app).post('/api/voice/studio/design').send({ label: 'Example', instructions: 'Alto', text: 'Hello' });
+ expect(valid.status).toBe(201);
+ expect(emit).toHaveBeenCalledWith('voice-studio:changed', {});
+ });
+});
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index f9cd763a6d..0c6a9bf7c3 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -1050,6 +1050,8 @@ CREATE TABLE IF NOT EXISTS voice_profiles (
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
+ALTER TABLE voice_profiles ALTER COLUMN universe_id DROP NOT NULL;
+ALTER TABLE voice_profiles ALTER COLUMN character_id DROP NOT NULL;
CREATE INDEX IF NOT EXISTS idx_voice_profiles_binding ON voice_profiles (universe_id, character_id, updated_at DESC);
CREATE UNIQUE INDEX IF NOT EXISTS idx_voice_profiles_approved_binding ON voice_profiles (universe_id, character_id) WHERE approval_status = 'approved';
diff --git a/server/services/fableLoom/hostedSession.js b/server/services/fableLoom/hostedSession.js
index 0810fbbd90..ec4271254d 100644
--- a/server/services/fableLoom/hostedSession.js
+++ b/server/services/fableLoom/hostedSession.js
@@ -25,9 +25,6 @@ import { transcribe } from '../voice/stt.js';
import { isEchoOfRecentTts, rememberTtsSentence } from '../voice/echo.js';
import { pcmToWavBuffer } from '../../lib/chiptuneRender.js';
import { pcmToFloat } from '../voice/callEndpointing.js';
-import {
- audienceCanParticipate,
-} from '../../lib/fableLoomParticipation.js';
import {
FABLELOOM_AUDIO_TARGETS,
isAssetSafeForLiveVoice,
@@ -36,7 +33,6 @@ import {
import {
findEpisode,
getLoom,
- mutateLoom,
} from './records.js';
import {
publicNode,
@@ -45,6 +41,12 @@ import {
import { getUniverse } from '../universeBuilder.js';
import { parseVoiceId } from '../pipeline/audio.js';
+// Explicit casting wins over array order; legacy looms without a selection keep
+// their first-character fallback. A deleted selection never becomes another actor.
+const protagonistVoiceCharacter = (loom, universe) => loom.protagonistCharacterId
+ ? universe?.characters?.find(character => character.id === loom.protagonistCharacterId) || null
+ : universe?.characters?.[0] || null;
+
// Active hosted sessions in memory (ephemeral, machine-local)
const activeSessions = new Map();
@@ -152,7 +154,7 @@ export async function checkHostedSessionReadiness({ loomId, episodeId, loom: cus
if (loom.universeId) {
universe = await getUniverse(loom.universeId).catch(() => null);
}
- const protagonistChar = universe?.characters?.[0] || null;
+ const protagonistChar = protagonistVoiceCharacter(loom, universe);
if (protagonistChar) {
resolvedVoice = await resolveCharacterVoice({
universeId: loom.universeId,
@@ -170,7 +172,7 @@ export async function checkHostedSessionReadiness({ loomId, episodeId, loom: cus
}
// 5. Playback readiness check
- let playbackReady = true;
+ const playbackReady = true;
if (startNode) {
const asset = resolvePlaybackPhaseAsset({
node: startNode,
@@ -217,7 +219,7 @@ export async function checkHostedSessionReadiness({ loomId, episodeId, loom: cus
* 5. Active hold asset is safe for live voice (no character dialogue / blocking SFX)
*/
export function revalidateLiveConversationGate({ session, node, asset }) {
- if (!session || session.status !== 'active') {
+ if (session?.status !== 'active') {
return { allowed: false, reason: 'SESSION_INACTIVE' };
}
if (!node) {
@@ -341,7 +343,7 @@ export async function createHostedSession(loomId, episodeId, {
function verifyHostedTokenAgainst(sessionId, token, hashField) {
if (!sessionId || !token || typeof token !== 'string') return false;
const session = activeSessions.get(sessionId);
- if (!session || session.status !== 'active') return false;
+ if (session?.status !== 'active') return false;
if (isExpired(session)) {
session.status = 'ended';
return false;
@@ -417,7 +419,7 @@ export function _getInternalSession(sessionId) {
*/
export async function updateHostedSession(sessionId, patch = {}, { io } = {}) {
const session = activeSessions.get(sessionId);
- if (!session || session.status !== 'active') {
+ if (session?.status !== 'active') {
throw new ServerError('Hosted session not found or ended', { status: 404, code: 'SESSION_NOT_FOUND' });
}
@@ -476,7 +478,7 @@ export async function updateHostedSession(sessionId, patch = {}, { io } = {}) {
*/
export async function switchHostedEpisode(sessionId, episodeId, { io } = {}) {
const session = activeSessions.get(sessionId);
- if (!session || session.status !== 'active') {
+ if (session?.status !== 'active') {
throw new ServerError('Hosted session not found or ended', { status: 404, code: 'SESSION_NOT_FOUND' });
}
@@ -585,7 +587,7 @@ export function endHostedSession(sessionId, { reason = 'ended', io } = {}) {
*/
export async function startHostedListening(sessionId, { io } = {}) {
const session = activeSessions.get(sessionId);
- if (!session || session.status !== 'active') {
+ if (session?.status !== 'active') {
throw new ServerError('Session is not active', { status: 400, code: 'SESSION_INACTIVE' });
}
@@ -654,7 +656,7 @@ export async function processHostedUtterance(sessionId, {
io,
} = {}) {
const session = activeSessions.get(sessionId);
- if (!session || session.status !== 'active') {
+ if (session?.status !== 'active') {
throw new ServerError('Session is not active', { status: 400, code: 'SESSION_INACTIVE' });
}
@@ -791,7 +793,7 @@ export async function processHostedUtterance(sessionId, {
if (loom.universeId) {
universe = await getUniverse(loom.universeId).catch(() => null);
}
- const char = universe?.characters?.[0] || null;
+ const char = protagonistVoiceCharacter(loom, universe);
const resolved = await resolveCharacterVoice({
universeId: loom.universeId,
characterId: char?.id,
diff --git a/server/services/fableLoom/hostedSession.test.js b/server/services/fableLoom/hostedSession.test.js
index a39b14f1ed..9ff9ac37ee 100644
--- a/server/services/fableLoom/hostedSession.test.js
+++ b/server/services/fableLoom/hostedSession.test.js
@@ -10,7 +10,6 @@ import {
initialPhaseForNode,
processHostedUtterance,
revalidateLiveConversationGate,
- sanitizeHostedSession,
startHostedListening,
startHostedSessionSweep,
stopHostedSessionSweep,
@@ -288,7 +287,7 @@ describe('fableLoom hostedSession', () => {
describe('half-duplex turn execution', () => {
it('executes full speech-first turn and commits story transition', async () => {
- const { session, token } = await createHostedSession('loom-1', 'ep-1');
+ const { session } = await createHostedSession('loom-1', 'ep-1');
const mockIo = {
of: () => ({
to: () => ({
@@ -322,20 +321,22 @@ describe('fableLoom hostedSession', () => {
expect(afterSession.transcript.length).toBeGreaterThan(1);
});
- it('synthesizes live replies with the approved interactive voice profile', async () => {
- const { session } = await createHostedSession('loom-1', 'ep-1');
- await startHostedListening(session.id);
+ it('synthesizes the selected protagonist with its approved AuK profile regardless of character order', async () => {
+ vi.spyOn(records, 'getLoom').mockResolvedValue({ ...mockLoom, protagonistCharacterId: 'character-1' });
vi.spyOn(universeBuilder, 'getUniverse').mockResolvedValue({
- characters: [{ id: 'character-1', voiceId: 'kokoro:af_heart' }],
+ characters: [{ id: 'another-character' }, { id: 'character-1', voiceId: 'piper:example' }],
});
vi.spyOn(voiceProfiles, 'resolveCharacterVoice').mockResolvedValue({
source: 'profile',
profileId: 'voice-profile-1',
profileRevision: 3,
- voiceId: 'qwen3-tts:character-1',
+ voiceId: 'auk:character-1',
degraded: false,
warning: null,
});
+ const { session } = await createHostedSession('loom-1', 'ep-1');
+ expect(voiceProfiles.resolveCharacterVoice).toHaveBeenLastCalledWith(expect.objectContaining({ characterId: 'character-1', route: 'interactive' }));
+ await startHostedListening(session.id);
vi.spyOn(weave, 'playTurn').mockResolvedValue({
action: 'stay',
narration: 'The signal is clear.',
@@ -344,8 +345,9 @@ describe('fableLoom hostedSession', () => {
await processHostedUtterance(session.id, { textMessage: 'Can you hear me?' });
+ expect(voiceProfiles.resolveCharacterVoice).toHaveBeenLastCalledWith(expect.objectContaining({ characterId: 'character-1', route: 'interactive' }));
expect(tts.synthesize).toHaveBeenCalledWith('The signal is clear.', {
- engine: 'qwen3-tts',
+ engine: 'auk',
profileId: 'voice-profile-1',
route: 'interactive',
signal: expect.any(AbortSignal),
diff --git a/server/services/voice/aukRuntime.js b/server/services/voice/aukRuntime.js
new file mode 100644
index 0000000000..fb9407f531
--- /dev/null
+++ b/server/services/voice/aukRuntime.js
@@ -0,0 +1,157 @@
+/** AuK-Flash MLX: explicit installation, lazy resident inference, bounded lifetime. */
+import { access, mkdir, readFile, rm } from 'node:fs/promises';
+import { homedir, tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { promisify } from 'node:util';
+import { createInterface } from 'node:readline';
+import { execFile, spawn } from '../../lib/childProcess.js';
+import { safeChildProcessOptions, whichFirst } from '../../lib/processEnv.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { withSpawnCwdEnv } from '../../lib/spawnCwd.js';
+import { PATHS } from '../../lib/paths.js';
+import { chunkRawText } from '../../lib/catalogChunking.js';
+
+const run = promisify(execFile);
+const AUK_REVISION = '6943a1e967409e8c73139a7a345f2a611cfb3dd6';
+const root = join(homedir(), '.portos', 'auk');
+const python = join(root, '.venv', 'bin', 'python');
+const supported = () => process.platform === 'darwin' && process.arch === 'arm64';
+let setup = { state: 'idle', stage: null, error: null };
+let worker = null;
+let pending = null;
+let idleTimer = null;
+const present = path => access(path).then(() => true, () => false);
+const required = ['.venv/bin/python', 'ckpts/AuK-Flash/config.yaml', 'ckpts/mlx/vae.safetensors',
+ 'ckpts/mlx/dit_flash.safetensors', 'ckpts/mlx/fusion_flash.safetensors',
+ 'ckpts/mlx/thinker/thinker.safetensors', 'ckpts/mlx/thinker/thinker_config.json',
+ 'ckpts/Qwen2.5-Omni-3B/preprocessor_config.json'];
+
+export async function getAukStatus() {
+ const ready = supported() && (await Promise.all(required.map(file => present(join(root, file))))).every(Boolean);
+ return { supported: supported(), ready, loaded: Boolean(worker), busy: Boolean(pending), ...setup };
+}
+
+export function startAukSetup(notify = () => {}) {
+ if (!supported()) throw new ServerError('AuK local setup requires Apple Silicon macOS.', { status: 409 });
+ if (setup.state === 'running' || pending) throw new ServerError('AuK is busy.', { status: 409 });
+ if (worker) unloadAuk();
+ setup = { state: 'running', stage: 'Preparing isolated runtime', error: null };
+ notify();
+ const stage = async (label, command, args, cwd = root) => {
+ setup = { ...setup, stage: label };
+ notify();
+ await run(command, args, safeChildProcessOptions({ cwd, env: withSpawnCwdEnv(process.env, cwd), timeout: 30 * 60_000, killSignal: 'SIGKILL', maxBuffer: 2 * 1024 * 1024 }));
+ };
+ const install = async () => {
+ const uv = await whichFirst('uv');
+ if (!uv) throw new ServerError('Install uv, then retry AuK setup.', { status: 503 });
+ await mkdir(root, { recursive: true });
+ if (!(await present(join(root, '.git')))) {
+ await stage('Downloading AuK source', 'git', ['clone', '--depth', '1', '--branch', 'feat/mlx-apple-silicon',
+ 'https://github.com/Tencent-Hunyuan/AuK.git', root], homedir());
+ }
+ await stage('Pinning compatible AuK backend', 'git', ['fetch', '--depth', '1', 'origin', AUK_REVISION]);
+ await stage('Checking out compatible backend', 'git', ['checkout', '--detach', AUK_REVISION]);
+ if (!(await present(python))) await stage('Creating Python environment', uv, ['venv', '--python', '3.10', join(root, '.venv')]);
+ await stage('Installing MLX dependencies', uv, ['pip', 'install', '--python', python, '-e', `${root}[mlx]`, 'huggingface_hub']);
+ for (const [repo, directory] of [['tencent/AuK-Flash', 'AuK-Flash'], ['Qwen/Qwen2.5-Omni-3B', 'Qwen2.5-Omni-3B']]) {
+ await stage(`Downloading ${directory} weights`, python, ['-c',
+ 'from huggingface_hub import snapshot_download; import sys; snapshot_download(repo_id=sys.argv[1], local_dir=sys.argv[2])',
+ repo, join(root, 'ckpts', directory)]);
+ }
+ for (const args of [
+ ['vae', 'ckpts/AuK-Flash/vae.safetensors', 'ckpts/mlx/vae.safetensors'],
+ ['dit', 'ckpts/AuK-Flash/auk_flash.safetensors', 'ckpts/mlx/dit_flash.safetensors'],
+ ['thinker', 'ckpts/Qwen2.5-Omni-3B', 'ckpts/mlx/thinker'],
+ ]) await stage(`Converting ${args[0]} for Apple Silicon`, python, ['-m', 'auk_mlx.convert', ...args]);
+ if (!(await getAukStatus()).ready) throw new Error('Required model artifacts are missing');
+ };
+ install().then(() => {
+ setup = { state: 'complete', stage: 'Ready', error: null };
+ notify();
+ }, error => {
+ setup = { state: 'failed', stage: setup.stage, error: error instanceof ServerError
+ ? error.message : 'AuK setup failed. Check network access, free disk space, and retry.' };
+ notify();
+ });
+ return { ...setup };
+}
+
+export function unloadAuk() {
+ if (pending) throw new ServerError('Wait for the current voice render before unloading.', { status: 409 });
+ clearTimeout(idleTimer);
+ worker?.kill('SIGKILL');
+ worker = null;
+}
+
+function ensureWorker() {
+ if (worker) return worker;
+ const child = spawn(python, [join(PATHS.root, 'scripts', 'auk_voice_worker.py'), root],
+ safeChildProcessOptions({ cwd: root, env: withSpawnCwdEnv(process.env, root), stdio: ['pipe', 'pipe', 'pipe'] }));
+ worker = child;
+ // Drain diagnostics without copying prompts, paths, or model data into shared logs.
+ child.stderr.on('data', () => {});
+ child.stdin.on('error', () => { if (pending?.child === child) pending.reject(new ServerError('AuK input stream closed.', { status: 502 })); });
+ const lines = createInterface({ input: child.stdout });
+ lines.on('line', line => {
+ if (!pending || pending.child !== child) return;
+ let response;
+ try { response = JSON.parse(line); } catch { pending.reject(new Error('Invalid AuK worker response')); return; }
+ if (response.ok) pending.resolve(response);
+ else pending.reject(new ServerError(`AuK inference failed (${response.error || 'runtime error'}).`, { status: 502 }));
+ });
+ child.on('error', () => pending?.child === child && pending.reject(new ServerError('AuK could not start. Run setup again.', { status: 503 })));
+ child.on('close', () => {
+ lines.close();
+ if (worker === child) worker = null;
+ if (pending?.child === child) pending.reject(new ServerError('AuK worker stopped before producing audio.', { status: 502 }));
+ });
+ return child;
+}
+
+export async function synthesizeAuk(text, opts = {}, signal) {
+ if (pending || setup.state === 'running') throw new ServerError('AuK is busy. Wait for the current operation.', { status: 409 });
+ if (!(await getAukStatus()).ready) throw new ServerError('Set up AuK in Voice Studio before generating speech.', { status: 503 });
+ if (signal?.aborted) throw new ServerError('Voice render canceled.', { status: 409 });
+ // Reserve after the asynchronous readiness check as well.
+ if (pending || setup.state === 'running') throw new ServerError('AuK is busy.', { status: 409 });
+ const rate = opts.rate || 1;
+ const duration = value => Math.max(2, Math.max(value.trim().split(/\s+/).length,
+ (value.match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/gu) || []).length / 2) / (2.5 * rate));
+ const split = value => {
+ const seconds = duration(value);
+ if (seconds <= 12) return [{ text: value, seconds }];
+ return chunkRawText(value, { maxChars: Math.max(1, Math.floor(value.length * 10 / seconds)), maxChunks: 1000 }).flatMap(split);
+ };
+ const segments = opts.genSeconds ? [{ text, seconds: opts.genSeconds }] : split(text);
+ if (segments.length > 32 || segments.some(segment => segment.seconds > 12)) {
+ throw new ServerError('This voice render is too long. Split it into shorter dialogue turns.', { status: 400 });
+ }
+ const output = join(tmpdir(), `portos-auk-${randomUUID()}.wav`);
+ const child = ensureWorker();
+ clearTimeout(idleTimer);
+ let timer;
+ const abort = () => { child.kill('SIGKILL'); };
+ const result = new Promise((resolve, reject) => {
+ pending = { child, resolve, reject };
+ timer = setTimeout(abort, 180_000);
+ signal?.addEventListener('abort', abort, { once: true });
+ child.stdin.write(`${JSON.stringify({ segments, instructions: opts.instructions || 'Natural, clear speaking voice',
+ referenceAudio: opts.referenceAudio || null, seed: opts.seed ?? 42,
+ pitchSemitones: opts.pitchSemitones || 0, output })}\n`, error => {
+ if (error) reject(new ServerError('AuK request could not be sent.', { status: 502 }));
+ });
+ });
+ return result.then(async meta => ({ ...meta, wav: await readFile(output), engine: 'auk',
+ modelRevision: 'tencent/AuK-Flash:mlx-8bit',
+ effectiveControls: { rate: opts.rate || 1, pitchSemitones: opts.pitchSemitones || 0, seed: opts.seed ?? 42 },
+ })).finally(async () => {
+ clearTimeout(timer);
+ signal?.removeEventListener('abort', abort);
+ pending = null;
+ idleTimer = setTimeout(() => { if (!pending) unloadAuk(); }, 10 * 60_000);
+ idleTimer.unref?.();
+ await Promise.all([output, `${output}.source.wav`, `${output}.reference.wav`].map(file => rm(file, { force: true })));
+ });
+}
diff --git a/server/services/voice/aukRuntime.test.js b/server/services/voice/aukRuntime.test.js
new file mode 100644
index 0000000000..1ec4977d83
--- /dev/null
+++ b/server/services/voice/aukRuntime.test.js
@@ -0,0 +1,74 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { EventEmitter } from 'node:events';
+import { PassThrough } from 'node:stream';
+import { pinPlatform, pinArch } from '../../lib/testHelper.js';
+const children = [];
+const access = vi.fn();
+vi.mock('node:fs/promises', () => ({ access: (...args) => access(...args), mkdir: vi.fn(),
+ readFile: vi.fn().mockResolvedValue(Buffer.from('test wav')), rm: vi.fn().mockResolvedValue() }));
+vi.mock('../../lib/childProcess.js', () => ({ execFile: vi.fn(), spawn: vi.fn(() => {
+ const child = new EventEmitter();
+ child.stdin = new PassThrough(); child.stdout = new PassThrough(); child.stderr = new PassThrough();
+ child.kill = vi.fn(() => { child.emit('close', null); return true; });
+ children.push(child); return child;
+}) }));
+vi.mock('../../lib/processEnv.js', () => ({ safeChildProcessOptions: value => value, whichFirst: vi.fn() }));
+vi.mock('../../lib/spawnCwd.js', () => ({ withSpawnCwdEnv: (env, cwd) => ({ ...env, PWD: cwd }) }));
+vi.mock('../../lib/paths.js', () => ({ PATHS: { root: '/example' } }));
+const { synthesizeAuk, getAukStatus, unloadAuk } = await import('./aukRuntime.js');
+let restorePlatform;
+let restoreArch;
+beforeEach(() => {
+ restorePlatform = pinPlatform('darwin');
+ restoreArch = pinArch('arm64');
+ access.mockReset().mockResolvedValue(); children.length = 0;
+});
+afterEach(() => {
+ unloadAuk();
+ restorePlatform();
+ restoreArch();
+ vi.useRealTimers();
+});
+const response = child => child.stdout.write(`${JSON.stringify({ ok: true, latencyMs: 1500, firstAudioMs: 1500 })}\n`);
+describe('AuK resident inference lifecycle', () => {
+ it('reuses a warm worker, refuses overlapping inference, and keeps actual full-audio latency', async () => {
+ const first = synthesizeAuk('Hello.', { instructions: 'Warm alto', genSeconds: 4 });
+ await vi.waitFor(() => expect(children).toHaveLength(1));
+ await expect(synthesizeAuk('Overlap')).rejects.toMatchObject({ status: 409 });
+ response(children[0]);
+ expect(await first).toMatchObject({ firstAudioMs: 1500, engine: 'auk' });
+ const second = synthesizeAuk('Again.', {});
+ await vi.waitFor(async () => expect((await getAukStatus()).busy).toBe(true));
+ response(children[0]);
+ await second;
+ expect(children).toHaveLength(1);
+ });
+ it('preserves all narration text in bounded model segments within one worker request', async () => {
+ const text = 'A thoughtful character walks toward the old library. '.repeat(12);
+ const render = synthesizeAuk(text, { referenceAudio: '/example/reference.wav' });
+ await vi.waitFor(() => expect(children).toHaveLength(1));
+ const request = JSON.parse(children[0].stdin.read().toString());
+ expect(request.segments.length).toBeGreaterThan(1);
+ expect(request.segments.map(segment => segment.text).join('')).toBe(text);
+ expect(request.segments.every(segment => segment.seconds <= 12)).toBe(true);
+ expect(request.referenceAudio).toBe('/example/reference.wav');
+ response(children[0]);
+ await render;
+ });
+ it('kills a canceled worker and releases the busy state for a later request', async () => {
+ const controller = new AbortController();
+ const pending = synthesizeAuk('Hello.', {}, controller.signal);
+ const failure = expect(pending).rejects.toThrow('stopped');
+ await vi.waitFor(() => expect(children).toHaveLength(1));
+ controller.abort();
+ await failure;
+ expect(children[0].kill).toHaveBeenCalledWith('SIGKILL');
+ expect(await getAukStatus()).toMatchObject({ busy: false, loaded: false });
+ });
+ it('never starts a process or reports readiness for missing model artifacts', async () => {
+ access.mockRejectedValue(new Error('missing'));
+ expect(await getAukStatus()).toMatchObject({ ready: false, loaded: false });
+ await expect(synthesizeAuk('Hello.')).rejects.toMatchObject({ status: 503 });
+ expect(children).toHaveLength(0);
+ });
+});
diff --git a/server/services/voice/profiles.js b/server/services/voice/profiles.js
index e9706ac89d..496cff6330 100644
--- a/server/services/voice/profiles.js
+++ b/server/services/voice/profiles.js
@@ -16,7 +16,7 @@ import { PATHS } from '../../lib/paths.js';
import { writeFileGuarded } from '../../lib/fileUtils.js';
import { trimTo } from '../../lib/textUtils.js';
-export const VOICE_PROFILE_ENGINES = new Set(['kokoro', 'piper', 'qwen3-tts']);
+export const VOICE_PROFILE_ENGINES = new Set(['kokoro', 'piper', 'qwen3-tts', 'auk']);
export const VOICE_PROFILE_KINDS = new Set(['preset', 'designed', 'cloned', 'fine-tuned']);
export const VOICE_PROFILE_ROUTES = new Set(['studio', 'interactive']);
@@ -74,6 +74,8 @@ const sanitizeInference = (raw) => ({
rate: boundedNumber(raw?.rate, 0.25, 4, 1.0),
checkpointPath: trimTo(raw?.checkpointPath, 500) || null,
modelId: trimTo(raw?.modelId, 160) || null,
+ pitchSemitones: boundedNumber(raw?.pitchSemitones, -12, 12, 0),
+ genSeconds: boundedNumber(raw?.genSeconds, 2, 12, 4),
});
const sanitizeBenchmark = (raw) => {
@@ -131,7 +133,7 @@ export function sanitizeVoiceProfile(raw) {
? raw.engine
: (parsePresetVoiceId(raw.voiceId)?.engine || 'kokoro');
- if (!PROFILE_ID_RE.test(id) || !universeId || !characterId) return null;
+ if (!PROFILE_ID_RE.test(id) || (raw.library !== true && (!universeId || !characterId))) return null;
const approvalStatus = raw?.approval?.status === 'approved'
? 'approved'
@@ -143,7 +145,9 @@ export function sanitizeVoiceProfile(raw) {
return {
id,
version: positiveInteger(raw.version),
- binding: { universeId, characterId },
+ binding: raw.library === true ? { universeId: null, characterId: null } : { universeId, characterId },
+ library: raw.library === true,
+ originProfileId: PROFILE_ID_RE.test(raw.originProfileId || '') ? raw.originProfileId : null,
label: trimTo(raw.label, MAX_LABEL) || null,
kind,
engine,
@@ -174,8 +178,8 @@ export function profileArtifactDirectory(id) {
return profileDirectory(id);
}
-const persist = async (profile) => {
- await query(
+export const persistVoiceProfile = async (profile, execute = query) => {
+ await execute(
`INSERT INTO voice_profiles (id, universe_id, character_id, approval_status, data, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7)
ON CONFLICT (id) DO UPDATE SET
@@ -197,6 +201,8 @@ const persist = async (profile) => {
return profile;
};
+const persist = persistVoiceProfile;
+
export async function getVoiceProfile(id) {
const profileId = trimTo(id, 80);
if (!PROFILE_ID_RE.test(profileId)) return null;
@@ -227,6 +233,31 @@ export async function listVoiceProfiles({ universeId, characterId } = {}) {
return rows.map((row) => sanitizeVoiceProfile(row.data)).filter(Boolean);
}
+/** Bounded metadata only; transcripts and training assets load with one selected profile. */
+export async function listStudioProfiles({ limit = 30, cursor } = {}) {
+ let before = null;
+ if (cursor) {
+ try { before = JSON.parse(Buffer.from(cursor, 'base64url').toString()); } catch { /* validated below */ }
+ if (!before || !PROFILE_ID_RE.test(before.id || '') || typeof before.at !== 'string' || !Number.isFinite(Date.parse(before.at))) {
+ throw new ServerError('Invalid voice library cursor', { status: 400 });
+ }
+ }
+ const filter = "(data->>'library' = 'true' OR approval_status = 'approved')";
+ const [page, count] = await Promise.all([
+ query(`SELECT id, data->>'label' AS label, data->>'voiceId' AS "voiceId", data->>'engine' AS engine,
+ (data->>'library' = 'true') AS library,
+ to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS "updatedAt"
+ FROM voice_profiles WHERE ${filter}
+ ${before ? 'AND (updated_at, id) < ($2::timestamptz, $3)' : ''}
+ ORDER BY updated_at DESC, id DESC LIMIT $1`, before ? [limit + 1, before.at, before.id] : [limit + 1]),
+ query(`SELECT count(*)::int AS total FROM voice_profiles WHERE ${filter}`),
+ ]);
+ const items = page.rows.slice(0, limit);
+ const last = items.at(-1);
+ return { items, total: count.rows[0].total, nextCursor: page.rows.length > limit
+ ? Buffer.from(JSON.stringify({ at: last.updatedAt, id: last.id })).toString('base64url') : null };
+}
+
async function getBoundProfile(universeId, characterId) {
const { rows } = await query(
`SELECT data FROM voice_profiles
@@ -269,7 +300,7 @@ export async function createVoiceDesignCandidate({
instructions = '',
seed = 42,
modelId = 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign',
- delivery = DEFAULT_DELIVERY,
+ delivery: _delivery = DEFAULT_DELIVERY,
rate = 1.0,
} = {}) {
const universe = trimTo(universeId, MAX_ID);
@@ -408,7 +439,7 @@ export async function promoteFineTunedProfile({
universeId,
characterId,
checkpointPath,
- checkpointId,
+ checkpointId: _checkpointId,
modelRevision = null,
step = 100,
} = {}) {
@@ -492,7 +523,7 @@ export async function promotePresetProfile({
const universe = trimTo(universeId, MAX_ID);
const character = trimTo(characterId, MAX_ID);
const preset = parsePresetVoiceId(voiceId);
- if (!universe || !character || !preset) {
+ if (!universe || !character || !preset || preset.engine === 'auk') {
throw new ServerError('A universe, character, and valid preset are required', {
status: 400,
code: 'VOICE_PROFILE_INVALID_PRESET',
@@ -509,6 +540,9 @@ export async function promotePresetProfile({
binding: { universeId: universe, characterId: character },
label: trimTo(characterName, MAX_LABEL) || current?.label || null,
kind: 'preset',
+ sourceAssets: samePreset ? current?.sourceAssets : [],
+ inference: samePreset ? current?.inference : {},
+ originProfileId: samePreset ? current?.originProfileId : null,
engine: preset.engine,
voiceId: preset.voiceId,
modelRevision: trimTo(modelRevision, MAX_REVISION) || 'configured-preset',
diff --git a/server/services/voice/profiles.test.js b/server/services/voice/profiles.test.js
index 9424c21c97..25d6cc1e11 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, readFile } from 'node:fs/promises';
+import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -19,7 +19,6 @@ const {
createVoiceDesignCandidate,
createClonedVoiceCandidate,
promoteFineTunedProfile,
- promoteVoiceProfile,
resolveCharacterVoice,
getProfileForSynthesis,
profileArtifactDirectory,
@@ -109,6 +108,18 @@ describe('voice profile contract', () => {
expect(queryMock.mock.calls.at(-1)[0]).toContain('INSERT INTO voice_profiles');
});
+ it('requires an auditioned AuK profile and clears its reference when switching to a preset', async () => {
+ await expect(promotePresetProfile({ universeId: 'universe-1', characterId: 'character-1', voiceId: 'auk:invented' }))
+ .rejects.toMatchObject({ code: 'VOICE_PROFILE_INVALID_PRESET' });
+ expect(queryMock).not.toHaveBeenCalled();
+ queryMock.mockResolvedValue({ rows: [] }).mockResolvedValueOnce({ rows: [{ data: {
+ ...PROFILE, engine: 'auk', voiceId: 'auk:voice-profile-1', kind: 'designed', originProfileId: 'library-1',
+ sourceAssets: [{ filename: 'reference.wav', transcript: 'Hello.' }], inference: { instructions: 'Old voice' },
+ } }] });
+ const replacement = await promotePresetProfile({ universeId: 'universe-1', characterId: 'character-1', voiceId: 'piper:example' });
+ expect(replacement).toMatchObject({ engine: 'piper', sourceAssets: [], originProfileId: null, inference: { instructions: null } });
+ });
+
it('creates voice design candidate profile as draft without altering approved profile', async () => {
queryMock.mockResolvedValueOnce({ rows: [] });
const candidate = await createVoiceDesignCandidate({
diff --git a/server/services/voice/studio.db.test.js b/server/services/voice/studio.db.test.js
new file mode 100644
index 0000000000..ab8ea30cf2
--- /dev/null
+++ b/server/services/voice/studio.db.test.js
@@ -0,0 +1,62 @@
+/** Real PostgreSQL library/assignment round trip; run only via test:db. */
+import { beforeAll, afterAll, describe, it, expect, vi } from 'vitest';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';
+import { requireDbOrSkip } from '../../lib/dbTestGate.js';
+let root;
+vi.mock('../../lib/paths.js', async () => {
+ const actual = await vi.importActual('../../lib/paths.js');
+ return { ...actual, PATHS: { ...actual.PATHS, get voiceProfiles() { return root; } } };
+});
+// Exercise the real universe lookup against PG while avoiding the test-only file backend.
+vi.mock('../universeBuilder/storeFacade.js', async () => {
+ const { readRaw } = await import('../universeBuilder/db.js');
+ return { store: () => ({ loadOne: readRaw }) };
+});
+vi.mock('./aukRuntime.js', () => ({ synthesizeAuk: async () => {
+ const wav = Buffer.alloc(48); wav.write('RIFF', 0); wav.write('WAVE', 8);
+ return { wav, modelRevision: 'test-auk', latencyMs: 10 };
+} }));
+const health = await checkHealth().catch(error => ({ connected: false, error: error.message }));
+const runDb = requireDbOrSkip('voice/studio.db.test', health.connected, health.error || 'Test database unavailable');
+const { createStudioVoice, assignStudioVoice } = await import('./studio.js');
+const { listVoiceProfiles, listStudioProfiles, resolveCharacterVoice } = await import('./profiles.js');
+const ids = [];
+const { writeRaw } = await import('../universeBuilder/db.js');
+beforeAll(async () => {
+ if (!health.connected) return;
+ await ensureSchema();
+ root = await mkdtemp(join(tmpdir(), 'voice-studio-db-'));
+});
+afterAll(async () => {
+ if (health.connected && ids.length) await query("DELETE FROM voice_profiles WHERE id = ANY($1::text[]) OR data->>'originProfileId' = ANY($1::text[])", [ids]);
+ if (health.connected && ids.length) await query('DELETE FROM universes WHERE id = ANY($1::text[])', [ids]);
+ if (root) await rm(root, { recursive: true, force: true });
+ await close();
+});
+describe.runIf(runDb)('Voice Studio database contract', () => {
+ it('allows multiple unbound voices and atomically serializes competing assignments', async () => {
+ const first = await createStudioVoice({ label: 'Example first', instructions: 'Warm alto', text: 'Hello there.' }); ids.push(first.id);
+ const second = await createStudioVoice({ label: 'Example second', instructions: 'Low tenor', text: 'Hello there.' }); ids.push(second.id);
+ const page = await listStudioProfiles({ limit: 1 });
+ const next = await listStudioProfiles({ limit: 1, cursor: page.nextCursor });
+ expect(page.items).toHaveLength(1);
+ expect(next.items).toHaveLength(1);
+ expect(page.items[0].id).not.toBe(next.items[0].id);
+ expect(page.items[0]).not.toHaveProperty('sourceAssets');
+ expect(page.items[0]).not.toHaveProperty('inference');
+ expect(page.total).toBeGreaterThanOrEqual(2);
+ await expect(listStudioProfiles({ cursor: 'not-a-cursor' })).rejects.toMatchObject({ status: 400 });
+ await writeRaw(first.id, { id: first.id, name: 'Example universe', schemaVersion: 5, characters: [{ id: 'example-character', name: 'Example character' }], createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() });
+ const target = { universeId: first.id, characterId: 'example-character' };
+ const copies = await Promise.all([assignStudioVoice(first.id, target), assignStudioVoice(second.id, target)]);
+ const bound = await listVoiceProfiles(target);
+ expect(bound).toHaveLength(2);
+ expect(bound.filter(profile => profile.approval.status === 'approved')).toHaveLength(1);
+ expect(await resolveCharacterVoice(target)).toMatchObject({ source: 'profile', profileId: expect.any(String) });
+ expect(copies.map(profile => profile.originProfileId).sort()).toEqual([first.id, second.id].sort());
+ expect((await listVoiceProfiles()).filter(profile => ids.includes(profile.id)).every(profile => profile.library && profile.binding.universeId === null)).toBe(true);
+ });
+});
diff --git a/server/services/voice/studio.js b/server/services/voice/studio.js
new file mode 100644
index 0000000000..b10173d490
--- /dev/null
+++ b/server/services/voice/studio.js
@@ -0,0 +1,75 @@
+/** Auditioned library voices; assigning creates an immutable character snapshot. */
+import { randomUUID, createHash } from 'node:crypto';
+import { mkdir, writeFile, copyFile, rm } from 'node:fs/promises';
+import { join } from 'node:path';
+import { withTransaction } from '../../lib/db.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { synthesizeAuk } from './aukRuntime.js';
+import { getUniverse } from '../universeBuilder/crud.js';
+import { getVoiceProfileRequired, sanitizeVoiceProfile, persistVoiceProfile, profileArtifactDirectory } from './profiles.js';
+
+export async function createStudioVoice({ label, instructions, text, seed = 42, rate = 1, pitchSemitones = 0, genSeconds = 4 }) {
+ // No record is published unless the actual model has produced playable audio.
+ const result = await synthesizeAuk(text, { instructions, seed, rate, pitchSemitones, genSeconds: genSeconds / rate });
+ if (result.wav.length < 44 || result.wav.toString('ascii', 0, 4) !== 'RIFF' || result.wav.toString('ascii', 8, 12) !== 'WAVE') {
+ throw new ServerError('AuK did not produce valid WAV audio.', { status: 502 });
+ }
+ const id = randomUUID();
+ const directory = profileArtifactDirectory(id);
+ await mkdir(join(directory, 'source'), { recursive: true });
+ const filename = 'reference.wav';
+ const now = new Date().toISOString();
+ const profile = sanitizeVoiceProfile({
+ id, library: true, label, version: 1, kind: 'designed', engine: 'auk', voiceId: `auk:${id}`,
+ modelRevision: result.modelRevision, inference: { instructions, seed, rate, pitchSemitones, genSeconds },
+ delivery: { rate: 1 }, // reference already embodies the auditioned pacing
+ sourceAssets: [{ filename, transcript: text, sha256: createHash('sha256').update(result.wav).digest('hex'),
+ licensePosture: 'generated-original-voice' }],
+ routes: { studio: { enabled: true }, interactive: { enabled: false } },
+ approval: { status: 'approved', approvedAt: now, benchmarkRevision: 1 },
+ benchmark: { renderedAt: now, profileRevision: 1, lines: [{ key: 'preview', text,
+ filename: `voice-profiles/${id}/source/${filename}`, latencyMs: result.latencyMs,
+ engine: 'auk', modelRevision: result.modelRevision, effectiveControls: result.effectiveControls }] },
+ createdAt: now, updatedAt: now,
+ });
+ return writeFile(join(directory, 'source', filename), result.wav)
+ .then(() => persistVoiceProfile(profile))
+ .catch(async error => { await rm(directory, { recursive: true, force: true }); throw error; });
+}
+
+export async function assignStudioVoice(profileId, { universeId, characterId, enableInteractive = false }) {
+ const universe = await getUniverse(universeId);
+ if (!universe?.characters?.some(character => character.id === characterId)) {
+ throw new ServerError('Choose an existing character in this universe.', { status: 404 });
+ }
+ const source = await getVoiceProfileRequired(profileId);
+ if (source.approval.status !== 'approved' || !['auk', 'piper'].includes(source.engine)) {
+ throw new ServerError('Choose an approved, available voice.', { status: 409 });
+ }
+ const id = randomUUID();
+ const directory = profileArtifactDirectory(id);
+ await mkdir(join(directory, 'source'), { recursive: true });
+ const now = new Date().toISOString();
+ const assigned = sanitizeVoiceProfile({ ...source, id, library: false,
+ binding: { universeId, characterId }, originProfileId: source.originProfileId || source.id,
+ // AuK returns whole clips. Live use is an explicit acceptance of buffered
+ // playback, not a claim that it passed the low-latency streaming benchmark.
+ routes: { ...source.routes, interactive: source.engine === 'auk'
+ ? { enabled: enableInteractive, maxFirstAudioMs: enableInteractive ? 180_000 : 900 }
+ : source.routes.interactive },
+ benchmark: null, createdAt: now, updatedAt: now,
+ });
+ const save = async () => {
+ for (const asset of source.sourceAssets) await copyFile(
+ join(profileArtifactDirectory(source.id), 'source', asset.filename), join(directory, 'source', asset.filename));
+ return withTransaction(async client => {
+ // Serializes same-character assignments, including when no binding exists yet.
+ await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [JSON.stringify([universeId, characterId])]);
+ await client.query(`UPDATE voice_profiles SET approval_status = 'retired',
+ data = jsonb_set(data, '{approval,status}', '"retired"'::jsonb), updated_at = NOW()
+ WHERE universe_id = $1 AND character_id = $2 AND approval_status = 'approved'`, [universeId, characterId]);
+ return persistVoiceProfile(assigned, client.query.bind(client));
+ });
+ };
+ return save().catch(async error => { await rm(directory, { recursive: true, force: true }); throw error; });
+}
diff --git a/server/services/voice/studio.test.js b/server/services/voice/studio.test.js
new file mode 100644
index 0000000000..24a4ed3b46
--- /dev/null
+++ b/server/services/voice/studio.test.js
@@ -0,0 +1,87 @@
+import { beforeEach, afterEach, describe, it, expect, vi } from 'vitest';
+import { mkdtemp, rm, readFile, readdir } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+let root;
+let records;
+let statements;
+let rejectInsert;
+const synthesizeAuk = vi.fn();
+const getUniverse = vi.fn();
+vi.mock('./aukRuntime.js', () => ({ synthesizeAuk: (...args) => synthesizeAuk(...args) }));
+vi.mock('../universeBuilder/crud.js', () => ({ getUniverse: (...args) => getUniverse(...args) }));
+vi.mock('../../lib/paths.js', () => ({ PATHS: { get voiceProfiles() { return root; } } }));
+async function execute(sql, args = []) {
+ statements.push(sql);
+ if (sql.includes('INSERT INTO voice_profiles')) {
+ if (rejectInsert) throw new Error('database unavailable');
+ records.set(args[0], JSON.parse(args[4]));
+ }
+ if (sql.includes('SELECT data FROM voice_profiles WHERE id')) return { rows: records.has(args[0]) ? [{ data: records.get(args[0]) }] : [] };
+ if (sql.includes('UPDATE voice_profiles SET')) {
+ for (const [id, p] of records) if (p.binding.universeId === args[0] && p.binding.characterId === args[1] && p.approval.status === 'approved') {
+ records.set(id, { ...p, approval: { ...p.approval, status: 'retired' } });
+ }
+ }
+ if (sql.includes('SELECT data FROM voice_profiles')) return { rows: [...records.values()]
+ .filter(p => !args.length || (p.binding.universeId === args[0] && p.binding.characterId === args[1])).map(data => ({ data })) };
+ return { rows: [] };
+}
+vi.mock('../../lib/db.js', () => ({ query: (...args) => execute(...args), withTransaction: async fn => {
+ const snapshot = new Map(records);
+ return fn({ query: execute }).catch(error => { records = snapshot; throw error; });
+} }));
+const { createStudioVoice, assignStudioVoice } = await import('./studio.js');
+const { resolveCharacterVoice } = await import('./profiles.js');
+const input = { label: 'Example voice', instructions: 'Warm alto', text: 'Hello there.', seed: 42, genSeconds: 4, pitchSemitones: -2 };
+const wav = Buffer.alloc(48);
+wav.write('RIFF', 0); wav.write('WAVE', 8);
+
+beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), 'voice-studio-test-'));
+ records = new Map(); statements = []; rejectInsert = false;
+ synthesizeAuk.mockReset().mockResolvedValue({ wav, latencyMs: 3200, modelRevision: 'test-auK' });
+ getUniverse.mockReset().mockResolvedValue({ characters: [{ id: 'character-1' }, { id: 'character-2' }] });
+});
+afterEach(async () => { await rm(root, { recursive: true, force: true }); });
+
+describe('Voice Studio audition and casting workflow', () => {
+ it('keeps the auditioned reference reusable and assigns independent snapshots consumed by the character resolver', async () => {
+ const library = await createStudioVoice(input);
+ expect(library).toMatchObject({ library: true, binding: { universeId: null, characterId: null }, engine: 'auk' });
+ expect(await readFile(join(root, library.id, 'source/reference.wav'))).toEqual(wav);
+ const assigned = await assignStudioVoice(library.id, { universeId: 'universe-1', characterId: 'character-1' });
+ const second = await assignStudioVoice(library.id, { universeId: 'universe-1', characterId: 'character-2', enableInteractive: true });
+ expect(await resolveCharacterVoice({ universeId: 'universe-1', characterId: 'character-1', route: 'interactive' })).toMatchObject({ source: 'project-default' });
+ expect(await resolveCharacterVoice({ universeId: 'universe-1', characterId: 'character-2', route: 'interactive' })).toMatchObject({ profileId: second.id });
+ expect(assigned.id).not.toBe(second.id);
+ expect(assigned.originProfileId).toBe(library.id);
+ expect(await readFile(join(root, assigned.id, 'source/reference.wav'))).toEqual(wav);
+ expect(await resolveCharacterVoice({ universeId: 'universe-1', characterId: 'character-1' }))
+ .toMatchObject({ source: 'profile', profileId: assigned.id, voiceId: library.voiceId });
+ expect(records.get(library.id).binding).toEqual({ universeId: null, characterId: null });
+ expect(statements.some(sql => sql.includes('pg_advisory_xact_lock'))).toBe(true);
+ });
+ it('does not publish failed or invalid auditions', async () => {
+ synthesizeAuk.mockRejectedValueOnce(new Error('not installed'));
+ await expect(createStudioVoice(input)).rejects.toThrow('not installed');
+ synthesizeAuk.mockResolvedValueOnce({ wav: Buffer.from('not audio') });
+ await expect(createStudioVoice(input)).rejects.toThrow('valid WAV');
+ expect(records.size).toBe(0);
+ expect(await readdir(root)).toEqual([]);
+ });
+ it('preserves the prior approved assignment and removes staged files if replacing it fails', async () => {
+ const library = await createStudioVoice(input);
+ const assigned = await assignStudioVoice(library.id, { universeId: 'universe-1', characterId: 'character-1' });
+ rejectInsert = true;
+ await expect(assignStudioVoice(library.id, { universeId: 'universe-1', characterId: 'character-1' })).rejects.toThrow('database unavailable');
+ expect(records.get(assigned.id).approval.status).toBe('approved');
+ expect((await readdir(root)).sort()).toEqual([library.id, assigned.id].sort());
+ });
+ it('rejects a deleted character before creating any assignment', async () => {
+ const library = await createStudioVoice(input);
+ await expect(assignStudioVoice(library.id, { universeId: 'universe-1', characterId: 'missing' })).rejects.toThrow('existing character');
+ expect(records.size).toBe(1);
+ });
+});
diff --git a/server/services/voice/tts.js b/server/services/voice/tts.js
index 55af7ffa78..db5be0abe3 100644
--- a/server/services/voice/tts.js
+++ b/server/services/voice/tts.js
@@ -36,7 +36,7 @@ export const listVoiceEngines = async () => {
return TTS_ENGINE_IDS.map((id) => ({
id,
...TTS_ENGINE_REGISTRY[id],
- unavailableControls,
+ unavailableControls: id === 'auk' ? 'Pitch edits run in Voice Studio; formant controls are unavailable.' : unavailableControls,
transformProbe: transforms,
}));
};
@@ -49,6 +49,10 @@ const resolveEngine = (engine) => {
};
const backend = (engine) => {
+ if (engine === 'auk') return {
+ synth: async (...args) => (await import('./aukRuntime.js')).synthesizeAuk(...args),
+ list: async () => [],
+ };
if (engine === 'piper') return { synth: synthesizePiper, list: listPiperVoices };
if (engine === 'qwen3-tts') return { synth: synthesizeQwen3, list: listQwen3Voices };
return { synth: synthesizePiper, list: listPiperVoices };
@@ -118,6 +122,15 @@ export const synthesize = async (text, opts = {}) => {
}
}
+ if (profile?.engine === 'auk') {
+ const sample = profile.sourceAssets?.[0];
+ synthOpts = { ...synthOpts, instructions: profile.inference.instructions, seed: profile.inference.seed,
+ referenceAudio: sample ? join(profileArtifactDirectory(profile.id), 'source', sample.filename) : null,
+ // The approved reference already contains the pitch edit. Never apply it twice.
+ pitchSemitones: sample ? 0 : profile.inference.pitchSemitones,
+ };
+ }
+
const voice = profileVoice || opts.voice;
if (voice) {
if (engine === 'piper') {
@@ -140,7 +153,7 @@ export const synthesize = async (text, opts = {}) => {
}
}
- const result = engine === 'qwen3-tts'
+ const result = engine === 'qwen3-tts' || engine === 'auk'
? await synth(text, synthOpts, opts.signal)
: await synth(text, ttsCfg, opts.signal);
diff --git a/server/services/voice/tts.test.js b/server/services/voice/tts.test.js
index 8dd2194d4b..95afc51cd3 100644
--- a/server/services/voice/tts.test.js
+++ b/server/services/voice/tts.test.js
@@ -1,13 +1,15 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { join } from 'node:path';
vi.mock('./config.js', () => ({
getVoiceConfig: vi.fn(),
piperVoiceTildePath: vi.fn((voice) => `~/.portos/voice/voices/${voice}.onnx`),
}));
+vi.mock('./aukRuntime.js', () => ({ synthesizeAuk: vi.fn() }));
vi.mock('./tts-piper.js', () => ({ synthesizePiper: vi.fn(), listPiperVoices: vi.fn() }));
vi.mock('./tts-qwen3.js', () => ({ synthesizeQwen3: vi.fn(), listQwen3Voices: vi.fn() }));
vi.mock('./piper-voices.js', () => ({ findPiperVoice: vi.fn() }));
-vi.mock('./profiles.js', () => ({ getProfileForSynthesis: vi.fn() }));
+vi.mock('./profiles.js', () => ({ getProfileForSynthesis: vi.fn(), profileArtifactDirectory: id => `/voice-profiles/${id}` }));
vi.mock('./bootstrap.js', () => ({ which: vi.fn() }));
vi.mock('../../lib/processEnv.js', () => ({ whichFirst: vi.fn().mockResolvedValue(null) }));
@@ -109,3 +111,18 @@ describe('profile-aware TTS', () => {
});
});
});
+
+it('uses the approved AuK reference for dialogue without repeating its pitch edit', async () => {
+ const { synthesizeAuk } = await import('./aukRuntime.js');
+ getVoiceConfig.mockResolvedValue(CONFIG);
+ getProfileForSynthesis.mockResolvedValue({ id: 'voice-example', version: 1, engine: 'auk', kind: 'designed',
+ voiceId: 'auk:example', modelRevision: 'auk-flash', delivery: { rate: 1 },
+ inference: { instructions: 'Warm alto', seed: 7, pitchSemitones: -4 },
+ sourceAssets: [{ filename: 'reference.wav' }],
+ });
+ synthesizeAuk.mockResolvedValue({ wav: Buffer.from('audio'), latencyMs: 1000 });
+ await synthesize('Example dialogue.', { profileId: 'voice-example' });
+ expect(synthesizeAuk).toHaveBeenCalledWith('Example dialogue.', expect.objectContaining({
+ referenceAudio: join('/voice-profiles', 'voice-example', 'source', 'reference.wav'), pitchSemitones: 0, seed: 7,
+ }), undefined);
+});
diff --git a/server/vitest.config.db.js b/server/vitest.config.db.js
index efd20b0a30..960987bac6 100644
--- a/server/vitest.config.db.js
+++ b/server/vitest.config.db.js
@@ -16,6 +16,7 @@ process.env.NODE_ENV = 'test';
*/
export const DB_TEST_INCLUDE = [
'services/voice/profiles.db.test.js',
+ 'services/voice/studio.db.test.js',
'../scripts/perf/collectionFixture.db.test.js',
'services/appQuality.db.test.js',
'**/db.test.js',