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([voice-picker-on-character-cards-voiceid-binding]): bind TTS voice per character + per-line override in Audio stage

[._.]/ Adam Eivy7d1180c41fb1
diff --git a/DONE.md b/DONE.md
index 2a7f1e203d..9c4d960a5a 100644
--- a/DONE.md
+++ b/DONE.md
@@ -10,6 +10,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./
### 2026-05-19
+- **[voice-picker-on-character-cards-voiceid-binding] Voice picker on character cards + per-line override.** New reusable `client/src/components/voice/VoicePicker.jsx` — engine-grouped dropdown over the merged `/api/pipeline/tts/voices` flat namespaced list (Kokoro + Piper today; future engines slot in upstream) with an audition button that POSTs to `/api/pipeline/tts/preview` and pipes the resulting WAV through `voiceClient.playWav` so it composes with voice-mode echo gating. Module-local cache shared between mounts so the universe character editor opening N picker instances fires exactly one `listPipelineTtsVoices` request. Wired into two consumers: (1) `CharacterDetailEditor`'s Identity section binds `entry.voiceId` (canon-level default for every line spoken by that character — server-side `resolveVoiceForLine` already preferred `character.voiceId` after a per-line override); (2) `AudioStage`'s per-line row gets a `compact + hideWhenEmpty` picker driving `voiceIdOverride` through the existing per-line PATCH path (`saveLineText` generalized to `saveLinePatch` so both text edits and voice-override changes share the in-flight-promise gate that `handleRender` already awaits — preventing a synth fired before the override PATCH settles from rendering against the prior voice). New client API helpers `listPipelineTtsVoices` + `previewPipelineTtsVoice` in `apiPipeline.js` (preview uses raw fetch since the shared `request()` helper auto-parses JSON). Unavailable saved voiceIds (engine uninstalled, voice renamed) are preserved as an `(unavailable)` option so the user sees what was bound instead of silently dropping to the placeholder. Empty voices catalog hides the AudioStage row picker (`hideWhenEmpty`) so a broken TTS install doesn't print an empty picker on every line. Coverage: 9 new vitest cases in `VoicePicker.test.jsx` cover catalog fetch + engine-group rendering, namespaced onChange + null-on-clear, unavailable-voice retention, audition→preview→playWav pipe, audition disabled with no selection, load-error inline display, hideWhenEmpty no-op, and the module-cache single-fetch invariant across mounts. Server-side voiceId + voiceIdOverride support was already complete (storyBible.js sanitizer, audio.js#resolveVoiceForLine, lineEditSchema in routes/pipeline.js, audio.test.js for both resolution priorities). All 5755 server tests + 130 client tests pass.
- **[high-tests-create-test-files-for-server-services] Create test files for `server/services/clinvar.js` and `server/services/telegramBridge.js`.** Both services had no sibling test file — clinvar covers the genome-scan path PortOS uses to flag actionable variants from a 23andMe upload, and telegramBridge is the outbound HTTP bridge that mirrors notifications to a Telegram chat. New `clinvar.test.js` (12 cases) pins `getClinvarStatus`, `scanClinvar` (severity sort + star tiebreak + corrupt-JSON + unknown-severity fallback), `invalidateClinvarCache`, and `deleteClinvar` (success + ENOENT-swallowed). New `telegramBridge.test.js` (14 cases) pins `init` (4 branches: no token, no allowFrom, getMe rejection, happy path + multi-line .env), `sendMessage` (pre-init, success body shape, ok:false surfaced, rate-limit drain at 30), `reload` (no-op when inactive, chat-id swap when active), `cleanup` (state reset + listener unsubscribe), and notification forwarding through the real `notificationEvents` EventEmitter (HTML-escape + emoji formatting + cachedForwardTypes whitelist filter). Module-level token-bucket reset between tests uses `vi.useFakeTimers({ toFake: ['Date'] })` + `setSystemTime` advancing 5 minutes per test so `refillTokens()` fires on the next consumeToken call. All 5781 server tests pass.
- **[wardroberow-migrate-to-userowdraft] Migrate `WardrobeRow` to consume `useRowDraft`.** `client/src/components/pipeline/CanonCard.jsx` no longer runs two `useFieldDraft` calls per outfit row — a single `useRowDraft(wardrobe, onCommit)` call covers both columns, so wardrobe entries pick up the same sibling-draft ride-along race protection that landed for `ListRow` in `[characterdetaileditor-listrow-row-draft-hook]`. `WardrobeSection.commit` reshapes from `(idx, field, value)` to `(idx, nextRow)`; the pending-row promotion trigger moves from "per-field `name` commit with non-empty value" to "any commit where `nextRow.name.trim()` is non-empty" — same end state, and the rewrite fires earlier for the ride-along case (description blur with a pending name draft now promotes the row instead of stranding it in `pendingNew`). The deferred concern from PLAN ("promotion semantics need their own design pass") resolved by following the existing `CharacterDetailEditor.updateRow` pattern, which already runs the same required-column check against `nextRow`. Removed the now-unused `useFieldDraft` import from `CanonCard.jsx`. +1 ride-along regression test in `CanonCard.test.jsx` (description blurs first with a pending name draft → row promotes with both fields intact). All 121 client tests pass.
- **[code-quality-dedup-batch] Code quality / dedup batch — 8 items shipped together.** (1) `[extract-optionalbooleanmap-zod-helper]` — new `optionalBooleanMap(keys)` helper in `server/lib/validation.js` collapsing the `Object.fromEntries(KEYS.map((k) => [k, z.boolean().optional()]))` pattern at 3 sites (`server/routes/universeBuilder.js`, `server/routes/pipeline.js` ×2). (2) `[extract-a-tryreadfile-helper]` — new `tryReadFile(path, encoding='utf8')` in `server/lib/fileUtils.js` replacing the `readFile(...).catch(() => null)` pattern at ~60 sites across `server/`; `readFile` import removed from 22 files where all uses migrated. Auto-injected `tryReadFile` mock into ~80 test files' `vi.mock('../lib/fileUtils.js')` bodies to keep partial mocks working. (3) `[aitoolkit-loadproviders-corrupt-fallback]` — `loadProviders` in `server/lib/aiToolkit/providers.js` now wraps `JSON.parse` in a `parseOrRescue(content, source)` helper that renames the corrupt user file to `<path>.corrupt.<timestamp>` + logs + returns `{ activeProvider: null, providers: {} }` so a garbled providers.json can't crash server boot. The shipped-sample path parses BEFORE persisting so a malformed sample can't seed user-side providers.json with garbage (per codex review). (4) `[more-resolveproviderandmodel-migration-candidates]` — migrated 3 sites onto the existing `resolveProviderAndModel` helper (`server/services/agentContentGenerator.js#runAIGeneration`, `server/services/agentPersonalityGenerator.js`, `server/services/loops.js#runIteration`); loops.js wraps with `.catch(() => ({ provider: null }))` to preserve the original "swallow all" semantics across both `getProviderById` and `getActiveProvider` failures. (5) `[extract-assertprovider-helper]` — new `assertProvider(provider, { message, code, status = 503 })` helper in `server/lib/promptRunner.js`; throws `ServerError` with code+status when `code` is provided, plain `Error` otherwise (preserves each caller's original error shape). Migrated 7 `if (!provider) throw …` sites (`universeBuilderAutoSort.js`, `universeBuilderRefine.js`, `universeBuilderExpand.js` ×2, `universeBuilderPromote.js`, `agentContentGenerator.js`, `agentPersonalityGenerator.js`). Auto-injected `assertProvider` mock into 6 test files mocking `promptRunner.js`. (6) `[extract-uselocktoggle-hook]` — new `useLockToggle({ patchFn, onSuccess, lockedMessage, unlockedMessage, errorMessage })` returning `{ busy, toggle }` in `client/src/hooks/useLockToggle.js` collapsing the optimistic-PATCH lock toggle pattern at 4 sites: `toggleArcLock`/`FieldLockToggle#toggle`/`toggleSeasonLock` in `client/src/components/pipeline/ArcCanvas.jsx`, `handleStageLockToggle` in `client/src/pages/PipelineIssue.jsx` (removes the now-dead `stageLockSaving` useState). (7) `[skip-the-text-accumulator-in-promptrunner]` — `runPromptThroughProvider`'s `onData` now skips the `APPEND_CHUNK` text concat for TUI providers (which discard the accumulated `text` anyway in favor of `result.text` from `executeTuiRun`); TUI screen-redraw streams can hit hundreds of KB per run. (8) `[aitoolkit-createprovider-field-parity-test]` — new exhaustive test in `server/lib/aiToolkit/providers.test.js` that round-trips all 20 fields defined in `createProvider`'s explicit field list through `create → save → reload`, guarding against the regression where a Zod-schema field is added without being mirrored into the explicit `createProvider` field list. All 5690 server tests + 103 client tests pass; client build clean.
diff --git a/PLAN.md b/PLAN.md
index 5b5a063603..5f78c53dec 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -27,7 +27,6 @@ _Nothing currently parked — pick the next item from the Backlog._
- [ ] [render-slowness-on-long-sessions-per-scene-render] **Render slowness on long sessions.** Per-scene render time degraded from ~3.5 min to 10–30 min within one project. Profile after sustained use; verify round-22 dedup helped.
- [ ] [pipeline-audio-phase-4c-2-4c-3-4d-2-local-oss] **Pipeline Audio Phase 4c.2/4c.3/4d.2.** Local OSS music gen (MusicGen sidecar; pick generator first); 3rd-party engine stubs; VO line muxing into the CD stitch with per-line offsets + music-bed ducking.
-- [ ] [voice-picker-on-character-cards-voiceid-binding] **Voice picker on character cards.** `voiceId` binding via dropdown on `CanonCard` when `kind === 'character'`; audition button hitting `/api/pipeline/tts/preview`. Same picker re-usable as per-line override in `AudioStage.jsx`.
### Video Gen (LTX-2.3)
@@ -70,6 +69,7 @@ _Nothing currently parked — pick the next item from the Backlog._
- [ ] [useasyncaction-post-unmount-setstate-guard-add] **`useAsyncAction` post-unmount setState guard.** Add `mountedRef` to gate `setRunning(false)`. YAGNI today; do at 4th consumer.
- [ ] [scene-level-wardrobe-picking-per-scene] **Scene-level wardrobe picking.** Per-scene `characterAppearances: [{ characterId, wardrobeId? }]` on storyboard scenes with wardrobe-picker dropdown. Decide first: does the extractor guess or does the user pick? Append wardrobe after physicalDescription vs substitute body fields?
- [ ] [extract-usecanonpatch-universe-setuniverse] **Extract `useCanonPatch(universe, setUniverse, universeId, mountedRef)`.** `UniverseCanon.jsx` + `NounsStage.jsx` 95% identical optimistic-patch handlers. Extract when a 3rd caller appears.
+- [ ] [apicore-request-arraybuffer-response-type] **Add an `arraybuffer` responseType escape hatch to `apiCore.request()`.** Two TTS audition helpers (`client/src/services/apiVoice.js#testTts` and `client/src/services/apiPipeline.js#previewPipelineTtsVoice`) currently bypass `request()` and do raw `fetch` because the shared helper assumes JSON. Collapsing both onto `request(endpoint, { ..., responseType: 'arraybuffer' })` would drop ~25 LOC of duplicated error-shaping + dedupe the path. Surfaced by /simplify during `[voice-picker-on-character-cards-voiceid-binding]`; deferred to keep that PR scoped to the picker. Not blocked on anything.
- [ ] [extract-usependinglistrows-hook] **Extract `usePendingListRows({ persisted, requiredColumn, idPrefix, onChange }) → { merged, isPending, addRow, updateRow, removeRow }`.** Surfaced by /simplify during `[wardroberow-migrate-to-userowdraft]`. `WardrobeSection` in `client/src/components/pipeline/CanonCard.jsx:155-211` and `CharacterDetailEditor` list-section block in `client/src/components/universe/CharacterDetailEditor.jsx:202-278` now share substantial structure: pending rows held client-side until a required column fills, then promoted to `onChange`/`patchList`, with an index space that concatenates `[...persisted, ...pending]` and an `isPending(idx)` partition. Estimated ~70 LOC savings across both call sites. Two load-bearing details to preserve in the extraction: (1) `WardrobeSection` mints `wd-<uuid>` ids that round-trip verbatim; `CharacterDetailEditor` mints `pending-<key>-<uuid>` that get stripped at promotion — pass an `idPrefix` and a `stripIdOnPromote` flag (or unify both onto server-shaped ids and drop the strip); (2) hook is per-list (one instance per `LIST_SECTION` in `CharacterDetailEditor`, one in `WardrobeSection`), NOT per-component. Deferred to keep this PR focused on the `useRowDraft` migration; revisit when a third caller appears or the parallel divergence drifts.
- [ ] [client-tests-for-deep-routing-drag-smoke-tests-for] **Client tests for deep routing + drag.** Smoke tests for `goToWorld(id)` URL transitions and chip-reorder ordering (mock `useSortable`).
- [ ] [shallow-equal-guard-in-usemediaannotations-socket] **Shallow-equal guard in `useMediaAnnotations` socket handler.** Speculative micro-opt; theoretical until observed.
diff --git a/client/src/components/pipeline/stages/AudioStage.jsx b/client/src/components/pipeline/stages/AudioStage.jsx
index 6b56ca0c85..a72165d42d 100644
--- a/client/src/components/pipeline/stages/AudioStage.jsx
+++ b/client/src/components/pipeline/stages/AudioStage.jsx
@@ -14,6 +14,7 @@
import { useEffect, useRef, useState } from 'react';
import { Loader2, Sparkles, Wand2, Mic, Music, Upload, Trash2 } from 'lucide-react';
import toast from '../../ui/Toast';
+import VoicePicker from '../../voice/VoicePicker';
import {
extractPipelineAudioLines,
renderPipelineAudioLine,
@@ -169,10 +170,14 @@ export default function AudioStage({ issue, onStageUpdate }) {
}
};
- // Per-line text save. Returns the in-flight Promise so handleRender can
- // await it before firing the synth request.
- const saveLineText = (lineIdx, text) => {
- const promise = patchPipelineAudioLine(issue.id, lineIdx, { text })
+ // Per-line patch (text edit OR voice override). Returns the in-flight
+ // Promise so handleRender can await it before firing the synth request —
+ // the server resolves character.voiceId / line.voiceIdOverride at render
+ // time, so a render fired before the override PATCH settles would synth
+ // against the prior voice. Same pending-Promise map keyed by lineIdx is
+ // reused for either field.
+ const saveLinePatch = (lineIdx, patch) => {
+ const promise = patchPipelineAudioLine(issue.id, lineIdx, patch)
.then((updated) => {
if (updated) onStageUpdate?.('audio', updated.stage, updated.issue);
return updated;
@@ -195,10 +200,16 @@ export default function AudioStage({ issue, onStageUpdate }) {
setDrafts((prev) => { const next = { ...prev }; delete next[lineIdx]; return next; });
return;
}
- void saveLineText(lineIdx, draft);
+ void saveLinePatch(lineIdx, { text: draft });
setDrafts((prev) => { const next = { ...prev }; delete next[lineIdx]; return next; });
};
+ // Voice override change. `voiceId: null` clears the override so the line
+ // falls back to the canon character voice (or project default).
+ const handleVoiceOverride = (lineIdx, voiceId) => {
+ void saveLinePatch(lineIdx, { voiceIdOverride: voiceId });
+ };
+
const handleRender = async (lineIdx) => {
// If a blur-save is in flight for this line, wait for it so the synth
// reads the up-to-date persisted text instead of stale bytes.
@@ -208,7 +219,7 @@ export default function AudioStage({ issue, onStageUpdate }) {
// without losing focus), flush it now and await.
const draftBeforeRender = drafts[lineIdx];
if (draftBeforeRender !== undefined && draftBeforeRender !== (lines[lineIdx]?.text || '')) {
- await saveLineText(lineIdx, draftBeforeRender);
+ await saveLinePatch(lineIdx, { text: draftBeforeRender });
setDrafts((prev) => { const next = { ...prev }; delete next[lineIdx]; return next; });
}
@@ -304,6 +315,18 @@ export default function AudioStage({ issue, onStageUpdate }) {
className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
maxLength={4000}
/>
+ <div className="mt-2 max-w-md">
+ <VoicePicker
+ compact
+ hideWhenEmpty
+ value={line.voiceIdOverride || null}
+ onChange={(v) => handleVoiceOverride(i, v)}
+ placeholder={line.characterId
+ ? `Inherit (${line.characterName} default)`
+ : 'Inherit (project default)'}
+ previewText={textValue?.trim() ? textValue.slice(0, 200) : undefined}
+ />
+ </div>
{line.audioFilename ? (
<audio
controls
diff --git a/client/src/components/settings/VoiceTab.jsx b/client/src/components/settings/VoiceTab.jsx
index 2a2221f98c..864385eef2 100644
--- a/client/src/components/settings/VoiceTab.jsx
+++ b/client/src/components/settings/VoiceTab.jsx
@@ -7,6 +7,7 @@ import {
} from '../../services/apiVoice';
import { playWav, webSpeechSupported } from '../../services/voiceClient';
import { readVoiceHidden, writeVoiceHidden } from '../../services/voiceVisibility';
+import { formatVoiceLabel } from '../../lib/voiceLabel';
const SERVICE_LABELS = {
whisper: 'Whisper (STT)',
@@ -33,26 +34,6 @@ const KOKORO_DTYPES = [
{ value: 'fp32', label: 'fp32 (best quality, slowest)' },
];
-const ACCENT_LABELS = { 'en-US': 'American', 'en-GB': 'British' };
-
-const formatVoiceLabel = (v, engine) => {
- if (engine === 'piper') {
- // Always lead with the voice ID so entries are distinguishable even if the
- // catalog metadata (accent/gender/note) is stripped or missing.
- const meta = [v.accent, v.gender].filter(Boolean).join(' — ');
- const dl = v.downloaded ? '' : ' ⬇';
- const note = v.note ? ` · ${v.note}` : '';
- return meta ? `${v.name} — ${meta}${note}${dl}` : `${v.name}${note}${dl}`;
- }
- const accent = ACCENT_LABELS[v.language] || v.language || '';
- const [, ...rest] = v.name.split('_');
- const raw = rest.join(' ') || v.name;
- const display = raw.charAt(0).toUpperCase() + raw.slice(1);
- const who = [accent, v.gender].filter(Boolean).join(' ');
- const traits = v.traits ? `${v.traits} ` : '';
- const grade = v.grade ? ` (${v.grade})` : '';
- return `${traits}${who ? `${who} — ${display}` : display}${grade}`;
-};
const WHISPER_MODELS = [
{ value: 'tiny.en', file: 'ggml-tiny.en.bin', label: 'tiny.en — 75 MB, fastest' },
diff --git a/client/src/components/universe/CharacterDetailEditor.jsx b/client/src/components/universe/CharacterDetailEditor.jsx
index b1927131e8..4560bc67fb 100644
--- a/client/src/components/universe/CharacterDetailEditor.jsx
+++ b/client/src/components/universe/CharacterDetailEditor.jsx
@@ -18,6 +18,7 @@ import {
import { BIBLE_LIMITS as L } from '../../lib/bibleLimits';
import useFieldDraft from '../../hooks/useFieldDraft';
import useRowDraft from '../../hooks/useRowDraft';
+import VoicePicker from '../voice/VoicePicker';
const SECTIONS = Object.freeze([
{
@@ -309,6 +310,16 @@ export default function CharacterDetailEditor({ entry, onPatch, onExpand, expand
idPrefix={entry.id}
/>
))}
+ {section.key === 'identity' ? (
+ <VoicePicker
+ label="Voice (TTS)"
+ value={entry.voiceId || null}
+ onChange={(v) => patchField('voiceId', v)}
+ disabled={disabled}
+ placeholder="Project default voice"
+ previewText={entry.name ? `Hi, I'm ${entry.name}. This is how I sound.` : undefined}
+ />
+ ) : null}
</CollapsibleSection>
))}
diff --git a/client/src/components/voice/VoicePicker.jsx b/client/src/components/voice/VoicePicker.jsx
new file mode 100644
index 0000000000..2dcf8abba6
--- /dev/null
+++ b/client/src/components/voice/VoicePicker.jsx
@@ -0,0 +1,188 @@
+/**
+ * VoicePicker — reusable namespaced-voiceId dropdown + audition button.
+ *
+ * Pulls the flat voice list from `/api/pipeline/tts/voices` (Kokoro + Piper
+ * today; future engines slot in upstream) and renders an engine-grouped
+ * <optgroup> picker. The audition button POSTs to `/api/pipeline/tts/preview`
+ * and plays the returned WAV through the shared `playWav` queue so it
+ * composes with voice-mode echo gating.
+ *
+ * Used by:
+ * - Universe character editor (`CharacterDetailEditor`) — binds the picked
+ * voice to `character.voiceId` (canon-level default for every line spoken
+ * by that character).
+ * - Audio stage per-line row (`AudioStage`) — per-line override that wins
+ * over the canon character voice for one specific dialogue line.
+ *
+ * The list is fetched lazily on first mount of any VoicePicker and cached
+ * module-locally so opening N pickers across one page doesn't hammer the
+ * voices endpoint N times.
+ */
+
+import { useEffect, useId, useMemo, useRef, useState } from 'react';
+import { Loader2, Play } from 'lucide-react';
+import { listPipelineTtsVoices, previewPipelineTtsVoice } from '../../services/apiPipeline';
+import { playWav } from '../../services/voiceClient';
+import { formatVoiceLabel } from '../../lib/voiceLabel';
+import toast from '../ui/Toast';
+
+let voiceListCache = null;
+let voiceListPromise = null;
+
+const loadVoiceList = () => {
+ if (voiceListCache) return Promise.resolve(voiceListCache);
+ if (voiceListPromise) return voiceListPromise;
+ voiceListPromise = listPipelineTtsVoices()
+ .then((res) => {
+ voiceListCache = Array.isArray(res?.voices) ? res.voices : [];
+ return voiceListCache;
+ })
+ .catch((err) => {
+ voiceListPromise = null;
+ throw err;
+ });
+ return voiceListPromise;
+};
+
+// Exposed for tests so they can reset module-local state between cases.
+export const __resetVoicePickerCache = () => {
+ voiceListCache = null;
+ voiceListPromise = null;
+};
+
+export default function VoicePicker({
+ value,
+ onChange,
+ disabled = false,
+ label = 'Voice',
+ // Placeholder for the "inherit / no override" select option. Use this
+ // to make the empty state self-explanatory in different contexts —
+ // "Inherit (default)" on the canon character editor vs "Inherit from
+ // character" on the audio-stage per-line row.
+ placeholder = 'Default voice',
+ previewText,
+ // `compact` hides the inline label and squeezes vertical padding for
+ // dense rows (AudioStage per-line). When false the picker stacks
+ // label-above-control like the rest of CharacterDetailEditor.
+ compact = false,
+ // Hide the entire field rendering when no voices load. Used in the
+ // audio-stage per-line row so a broken TTS install doesn't print an
+ // empty picker on every line.
+ hideWhenEmpty = false,
+}) {
+ const id = useId();
+ const [voices, setVoices] = useState(voiceListCache || []);
+ const [loading, setLoading] = useState(!voiceListCache);
+ const [loadError, setLoadError] = useState(null);
+ const [previewing, setPreviewing] = useState(false);
+ // Synchronous guard against double-click during the async pre-disable
+ // window — `setPreviewing(true)` doesn't commit to the disabled attr
+ // until React renders, so two rapid-fire clicks can both pass the
+ // `previewing` check and fire two TTS requests.
+ const previewingRef = useRef(false);
+
+ useEffect(() => {
+ if (voiceListCache) return undefined;
+ let cancelled = false;
+ setLoading(true);
+ loadVoiceList()
+ .then((list) => {
+ if (cancelled) return;
+ setVoices(list);
+ setLoadError(null);
+ })
+ .catch((err) => {
+ if (cancelled) return;
+ setLoadError(err?.message || 'Failed to load voices');
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => { cancelled = true; };
+ }, []);
+
+ const byEngine = useMemo(() => voices.reduce((acc, v) => {
+ const e = v.engine || 'other';
+ if (!acc[e]) acc[e] = [];
+ acc[e].push(v);
+ return acc;
+ }, {}), [voices]);
+ const engineKeys = useMemo(() => Object.keys(byEngine).sort(), [byEngine]);
+
+ const handleAudition = async () => {
+ if (!value || previewingRef.current) return;
+ previewingRef.current = true;
+ setPreviewing(true);
+ const buf = await previewPipelineTtsVoice(value, previewText).catch((err) => {
+ toast.error(`Voice preview failed: ${err.message}`);
+ return null;
+ });
+ previewingRef.current = false;
+ setPreviewing(false);
+ if (buf) playWav(buf);
+ };
+
+ if (hideWhenEmpty && !loading && voices.length === 0 && !loadError) return null;
+
+ const select = (
+ <div className="flex items-center gap-1.5 min-w-0">
+ <select
+ id={id}
+ value={value || ''}
+ onChange={(e) => onChange?.(e.target.value || null)}
+ disabled={disabled || loading}
+ className="flex-1 min-w-0 px-1.5 py-0.5 text-xs bg-port-bg border border-port-border rounded text-white disabled:opacity-50"
+ >
+ <option value="">{loading ? 'Loading voices…' : placeholder}</option>
+ {/* Preserve a previously-saved voiceId that no longer appears in the
+ catalog (engine uninstalled, voice renamed) so the user can see
+ what they had bound before — losing it silently to a dropdown
+ reset would mask the underlying drift. */}
+ {value && !voices.some((v) => v.id === value) ? (
+ <option value={value}>{value} (unavailable)</option>
+ ) : null}
+ {engineKeys.map((engine) => (
+ <optgroup key={engine} label={engine.charAt(0).toUpperCase() + engine.slice(1)}>
+ {byEngine[engine].map((v) => (
+ <option key={v.id} value={v.id}>{formatVoiceLabel(v)}</option>
+ ))}
+ </optgroup>
+ ))}
+ </select>
+ <button
+ type="button"
+ onClick={handleAudition}
+ disabled={!value || previewing || disabled}
+ title={value ? `Audition ${value}` : 'Pick a voice to audition'}
+ aria-label={value ? `Audition ${value}` : 'Audition voice'}
+ className="shrink-0 p-1 rounded text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed"
+ >
+ {previewing ? <Loader2 size={12} className="animate-spin" /> : <Play size={12} />}
+ </button>
+ </div>
+ );
+
+ if (loadError) {
+ return (
+ <div className="space-y-0.5">
+ {!compact ? (
+ <label htmlFor={id} className="block text-[10px] uppercase tracking-wider text-gray-500">
+ {label}
+ </label>
+ ) : null}
+ <p className="text-[10px] text-port-error">{loadError}</p>
+ </div>
+ );
+ }
+
+ if (compact) return select;
+
+ return (
+ <div className="space-y-0.5">
+ <label htmlFor={id} className="block text-[10px] uppercase tracking-wider text-gray-500">
+ {label}
+ </label>
+ {select}
+ </div>
+ );
+}
diff --git a/client/src/components/voice/VoicePicker.test.jsx b/client/src/components/voice/VoicePicker.test.jsx
new file mode 100644
index 0000000000..9d3c30170a
--- /dev/null
+++ b/client/src/components/voice/VoicePicker.test.jsx
@@ -0,0 +1,125 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+vi.mock('../../services/apiPipeline', () => ({
+ listPipelineTtsVoices: vi.fn(),
+ previewPipelineTtsVoice: vi.fn(),
+}));
+vi.mock('../../services/voiceClient', () => ({
+ playWav: vi.fn(),
+}));
+vi.mock('../ui/Toast', () => ({
+ default: { error: vi.fn() },
+}));
+
+import VoicePicker, { __resetVoicePickerCache } from './VoicePicker';
+import { listPipelineTtsVoices, previewPipelineTtsVoice } from '../../services/apiPipeline';
+import { playWav } from '../../services/voiceClient';
+
+const SAMPLE_VOICES = [
+ { id: 'kokoro:af_bella', engine: 'kokoro', voice: 'af_bella', name: 'af_bella', gender: 'female', language: 'en-US', grade: 'A' },
+ { id: 'kokoro:am_michael', engine: 'kokoro', voice: 'am_michael', name: 'am_michael', gender: 'male', language: 'en-US', grade: 'B' },
+ { id: 'piper:lessac-medium', engine: 'piper', voice: 'lessac-medium', name: 'lessac-medium', gender: 'female', accent: 'American', downloaded: true },
+];
+
+beforeEach(() => {
+ __resetVoicePickerCache();
+ vi.clearAllMocks();
+});
+
+describe('VoicePicker', () => {
+ it('fetches voices on mount and groups them by engine', async () => {
+ listPipelineTtsVoices.mockResolvedValue({ voices: SAMPLE_VOICES });
+ render(<VoicePicker value={null} onChange={() => {}} />);
+ await waitFor(() => {
+ expect(document.querySelector('option[value="kokoro:af_bella"]')).toBeInTheDocument();
+ });
+ expect(document.querySelector('option[value="piper:lessac-medium"]')).toBeInTheDocument();
+ expect(document.querySelector('optgroup[label="Kokoro"]')).toBeInTheDocument();
+ expect(document.querySelector('optgroup[label="Piper"]')).toBeInTheDocument();
+ expect(listPipelineTtsVoices).toHaveBeenCalledTimes(1);
+ });
+
+ it('fires onChange with the selected namespaced voiceId', async () => {
+ listPipelineTtsVoices.mockResolvedValue({ voices: SAMPLE_VOICES });
+ const onChange = vi.fn();
+ const user = userEvent.setup();
+ render(<VoicePicker value={null} onChange={onChange} />);
+ await waitFor(() => document.querySelector('option[value="kokoro:af_bella"]'));
+ const select = screen.getByRole('combobox');
+ await user.selectOptions(select, 'kokoro:af_bella');
+ expect(onChange).toHaveBeenCalledWith('kokoro:af_bella');
+ });
+
+ it('fires onChange(null) when the placeholder is selected (clears binding)', async () => {
+ listPipelineTtsVoices.mockResolvedValue({ voices: SAMPLE_VOICES });
+ const onChange = vi.fn();
+ const user = userEvent.setup();
+ render(<VoicePicker value="kokoro:af_bella" onChange={onChange} placeholder="Project default voice" />);
+ await waitFor(() => document.querySelector('option[value="kokoro:af_bella"]'));
+ const select = screen.getByRole('combobox');
+ await user.selectOptions(select, '');
+ expect(onChange).toHaveBeenCalledWith(null);
+ });
+
+ it('preserves an unavailable saved voiceId so the user sees what was bound', async () => {
+ listPipelineTtsVoices.mockResolvedValue({ voices: SAMPLE_VOICES });
+ render(<VoicePicker value="kokoro:retired-voice" onChange={() => {}} />);
+ await waitFor(() => document.querySelector('option[value="kokoro:af_bella"]'));
+ expect(screen.getByRole('option', { name: /retired-voice \(unavailable\)/i })).toBeInTheDocument();
+ });
+
+ it('audition button posts to preview and pipes the wav through playWav', async () => {
+ listPipelineTtsVoices.mockResolvedValue({ voices: SAMPLE_VOICES });
+ const buf = new ArrayBuffer(8);
+ previewPipelineTtsVoice.mockResolvedValue(buf);
+ const user = userEvent.setup();
+ render(<VoicePicker value="kokoro:af_bella" onChange={() => {}} previewText="hello" />);
+ await waitFor(() => document.querySelector('option[value="kokoro:af_bella"]'));
+ const button = screen.getByRole('button', { name: /audition kokoro:af_bella/i });
+ await user.click(button);
+ await waitFor(() => {
+ expect(previewPipelineTtsVoice).toHaveBeenCalledWith('kokoro:af_bella', 'hello');
+ expect(playWav).toHaveBeenCalledWith(buf);
+ });
+ });
+
+ it('disables the audition button when no voice is selected', async () => {
+ listPipelineTtsVoices.mockResolvedValue({ voices: SAMPLE_VOICES });
+ render(<VoicePicker value={null} onChange={() => {}} />);
+ await waitFor(() => document.querySelector('option[value="kokoro:af_bella"]'));
+ const button = screen.getByRole('button', { name: /audition voice/i });
+ expect(button).toBeDisabled();
+ });
+
+ it('shows the load error inline when listPipelineTtsVoices rejects', async () => {
+ listPipelineTtsVoices.mockRejectedValue(new Error('Boom'));
+ render(<VoicePicker value={null} onChange={() => {}} />);
+ await waitFor(() => {
+ expect(screen.getByText('Boom')).toBeInTheDocument();
+ });
+ });
+
+ it('hideWhenEmpty + zero voices renders nothing', async () => {
+ listPipelineTtsVoices.mockResolvedValue({ voices: [] });
+ const { container } = render(<VoicePicker value={null} onChange={() => {}} hideWhenEmpty />);
+ await waitFor(() => {
+ expect(listPipelineTtsVoices).toHaveBeenCalled();
+ });
+ // After the resolve settles, the component returns null when the list is empty.
+ await waitFor(() => {
+ expect(container.firstChild).toBeNull();
+ });
+ });
+
+ it('shares the module-local cache between mounts (single fetch)', async () => {
+ listPipelineTtsVoices.mockResolvedValue({ voices: SAMPLE_VOICES });
+ const { unmount } = render(<VoicePicker value={null} onChange={() => {}} />);
+ await waitFor(() => document.querySelector('option[value="kokoro:af_bella"]'));
+ unmount();
+ render(<VoicePicker value={null} onChange={() => {}} />);
+ await waitFor(() => document.querySelector('option[value="kokoro:af_bella"]'));
+ expect(listPipelineTtsVoices).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 7f6eb7d9d8..dc7060eabb 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -58,3 +58,4 @@ grep -i "what you want to do" client/src/lib/README.md
| `mediaNavigation.js` | `getAdjacentMedia(items, item)` — prev/next computation for lightboxes. |
| `unsorted.js` | Synthetic "Unsorted" collection from media not filed in any real collection. |
| `upsertByIdPrepend.js` | Newest-first upsert into an id-keyed list. |
+| `voiceLabel.js` | `formatVoiceLabel(v, engine?)` — display label for a TTS voice record. Engine-specific formatters plug into a lookup table; new engines extend that map. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index f3181e983f..cd603165af 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -29,3 +29,4 @@ export * from './joinInfluenceList.js';
export * from './mediaNavigation.js';
export * from './unsorted.js';
export * from './upsertByIdPrepend.js';
+export * from './voiceLabel.js';
diff --git a/client/src/lib/voiceLabel.js b/client/src/lib/voiceLabel.js
new file mode 100644
index 0000000000..042c1d3e71
--- /dev/null
+++ b/client/src/lib/voiceLabel.js
@@ -0,0 +1,40 @@
+// Display-formatter for TTS voice entries. Engine-specific shapes plug in
+// via the ENGINE_FORMATTERS table — adding a new engine here is the single
+// surface every voice-picker UI (settings VoiceTab + character VoicePicker
+// + future per-line picker) reads through, so a new label format propagates
+// to every consumer without per-component edits.
+
+const LANGUAGE_LABELS = Object.freeze({
+ 'en-US': 'American',
+ 'en-GB': 'British',
+});
+
+const ENGINE_FORMATTERS = Object.freeze({
+ kokoro: (v) => {
+ const accent = LANGUAGE_LABELS[v.language] || v.language || '';
+ const display = (v.name || '').split('_').slice(1).join(' ') || v.name || v.voice || '';
+ const cleaned = display.charAt(0).toUpperCase() + display.slice(1);
+ const who = [accent, v.gender].filter(Boolean).join(' ');
+ const traits = v.traits ? `${v.traits} ` : '';
+ const grade = v.grade ? ` (${v.grade})` : '';
+ return `${traits}${who ? `${who} — ${cleaned}` : cleaned}${grade}`;
+ },
+ piper: (v) => {
+ const id = v.name || v.voice || '';
+ const meta = [v.accent, v.gender].filter(Boolean).join(' — ');
+ const note = v.note ? ` · ${v.note}` : '';
+ const dl = v.downloaded === false ? ' ⬇' : '';
+ return meta ? `${id} — ${meta}${note}${dl}` : `${id}${note}${dl}`;
+ },
+});
+
+const fallbackLabel = (v) => v.label || v.voice || v.name || v.id || '';
+
+// `engineOverride` lets callers that don't carry `engine` on the voice
+// record (the legacy `/voice/voices?engine=...` shape used by VoiceTab)
+// pass it positionally. New callers attach `engine` to each item (per the
+// `/pipeline/tts/voices` flat-list shape) and omit the override.
+export const formatVoiceLabel = (v, engineOverride) => {
+ const engine = engineOverride || v.engine;
+ return (ENGINE_FORMATTERS[engine] || fallbackLabel)(v);
+};
diff --git a/client/src/lib/voiceLabel.test.js b/client/src/lib/voiceLabel.test.js
new file mode 100644
index 0000000000..d416361fa6
--- /dev/null
+++ b/client/src/lib/voiceLabel.test.js
@@ -0,0 +1,53 @@
+import { describe, it, expect } from 'vitest';
+import { formatVoiceLabel } from './voiceLabel';
+
+describe('formatVoiceLabel', () => {
+ it('formats a Kokoro voice with language + gender + grade', () => {
+ expect(formatVoiceLabel({
+ engine: 'kokoro', name: 'af_bella', language: 'en-US', gender: 'female', grade: 'A',
+ })).toBe('American female — Bella (A)');
+ });
+
+ it('formats a Kokoro British voice', () => {
+ expect(formatVoiceLabel({
+ engine: 'kokoro', name: 'bm_smith', language: 'en-GB', gender: 'male', grade: 'B',
+ })).toBe('British male — Smith (B)');
+ });
+
+ it('prepends Kokoro traits when present', () => {
+ expect(formatVoiceLabel({
+ engine: 'kokoro', name: 'af_bella', language: 'en-US', gender: 'female', traits: '❤️',
+ })).toBe('❤️ American female — Bella');
+ });
+
+ it('falls back to the bare voice name when Kokoro metadata is missing', () => {
+ expect(formatVoiceLabel({ engine: 'kokoro', name: 'unprefixed' })).toBe('Unprefixed');
+ });
+
+ it('formats a Piper voice with accent + gender', () => {
+ expect(formatVoiceLabel({
+ engine: 'piper', name: 'lessac-medium', accent: 'American', gender: 'female', downloaded: true,
+ })).toBe('lessac-medium — American — female');
+ });
+
+ it('marks an undownloaded Piper voice with ⬇', () => {
+ expect(formatVoiceLabel({
+ engine: 'piper', name: 'glados', accent: 'Synthetic', downloaded: false,
+ })).toBe('glados — Synthetic ⬇');
+ });
+
+ it('omits ⬇ when downloaded is unspecified (avoid spurious download prompts)', () => {
+ expect(formatVoiceLabel({ engine: 'piper', name: 'glados', accent: 'Synthetic' })).toBe('glados — Synthetic');
+ });
+
+ it('uses engineOverride when the voice record carries no engine field', () => {
+ expect(formatVoiceLabel({ name: 'lessac-medium', accent: 'American' }, 'piper'))
+ .toBe('lessac-medium — American');
+ });
+
+ it('falls back to label / voice / id when engine is unrecognised', () => {
+ expect(formatVoiceLabel({ engine: 'elevenlabs', label: 'Rachel' })).toBe('Rachel');
+ expect(formatVoiceLabel({ engine: 'elevenlabs', voice: 'rachel' })).toBe('rachel');
+ expect(formatVoiceLabel({ engine: 'elevenlabs', id: 'elevenlabs:rachel' })).toBe('elevenlabs:rachel');
+ });
+});
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index b6bf00ec1c..1bce547d66 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -398,6 +398,33 @@ export const pipelineAutoRunSseUrl = (issueId) =>
`/api/pipeline/issues/${encodeURIComponent(issueId)}/auto-run-text/progress`;
// ---- Audio stage ----
+// Flat list of every voice the active engines expose, namespaced as
+// `engine:voiceName` (e.g. `kokoro:af_bella`, `piper:lessac-medium`). The
+// character voice picker + per-line override picker pull from this single
+// list so a new engine surfaces in every consumer with one server-side edit.
+// Silent — VoicePicker owns its own inline error UI.
+export const listPipelineTtsVoices = () => request('/pipeline/tts/voices', { silent: true });
+
+// Audition a voice — returns the rendered WAV as an ArrayBuffer so callers
+// can feed it to `playWav` from voiceClient. Uses raw fetch because the
+// shared `request()` helper auto-parses JSON. Optional `text` overrides the
+// server-side default preview line.
+export const previewPipelineTtsVoice = async (voiceId, text) => {
+ const res = await fetch('/api/pipeline/tts/preview', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(text ? { voiceId, text } : { voiceId }),
+ });
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
+ const e = new Error(err.error || 'Preview failed');
+ e.code = err.code;
+ e.status = res.status;
+ throw e;
+ }
+ return res.arrayBuffer();
+};
+
// Walks storyboards.scenes[].dialogue and populates stages.audio.lines[].
// Pass { force: true } to replace existing lines wholesale (server defaults
// to a 409 when lines[] is already populated so a stray click can't wipe