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

Finish Voice Lab fine-tuning: live runs, cancel and checkpoint promotion

Claudee81425b95945
diff --git a/client/src/components/universe/CharacterDetailEditor.jsx b/client/src/components/universe/CharacterDetailEditor.jsx
index 63f603a87a..f644859f15 100644
--- a/client/src/components/universe/CharacterDetailEditor.jsx
+++ b/client/src/components/universe/CharacterDetailEditor.jsx
@@ -47,10 +47,10 @@ import {
createVoiceDesignCandidate,
createClonedVoiceCandidate,
promoteVoiceProfile,
- startFineTuningJob,
} from '../../services/apiVoice';
import { prepareProfilePlayback } from '../../services/voiceProfileBenchmark';
import VoicePicker from '../voice/VoicePicker';
+import VoiceFineTuningPanel from '../voice/VoiceFineTuningPanel';
import TabPills from '../ui/TabPills';
import useDrawerTab from '../../hooks/useDrawerTab';
@@ -783,10 +783,6 @@ function VoiceProfileSection({ universeId, entry, disabled }) {
const [cloneConsentConfirmed, setCloneConsentConfirmed] = useState(false);
const [cloneLicensePosture, _setCloneLicensePosture] = useState('consented-performance');
- // Fine-tuning state
- const [fineTuneEpochs, setFineTuneEpochs] = useState(5);
- const [fineTuneJob, setFineTuneJob] = useState(null);
-
const loadGeneration = useRef(0);
const refreshProfiles = async () => {
@@ -922,13 +918,6 @@ function VoiceProfileSection({ universeId, entry, disabled }) {
return result;
}, { errorMessage: 'Could not promote candidate profile' });
- const [startFineTune, startingFineTune] = useAsyncAction(async () => {
- if (!profile?.id) return null;
- const result = await startFineTuningJob(profile.id, { epochs: fineTuneEpochs }, { silent: true });
- setFineTuneJob(result);
- return result;
- }, { errorMessage: 'Failed to start fine-tuning' });
-
if (!universeId) return null;
const approved = profile?.approval?.status === 'approved';
const _benchmarkCount = profile?.benchmark?.lines?.length || 0;
@@ -1145,36 +1134,12 @@ function VoiceProfileSection({ universeId, entry, disabled }) {
)}
{activeTab === 'finetune' && (
- <div className="space-y-2">
- <p className="text-[10px] text-gray-400">Optional character voice fine-tuning. Requires a supported Qwen training adapter; without one the request is refused and no checkpoint is created.</p>
- <div className="flex gap-2">
- <label className="block text-[10px] text-gray-400 flex-1">
- Epochs
- <input
- type="number"
- value={fineTuneEpochs}
- onChange={(e) => setFineTuneEpochs(parseInt(e.target.value, 10) || 5)}
- min="1"
- max="20"
- className="w-full mt-0.5 px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-white"
- />
- </label>
- </div>
- <button
- type="button"
- onClick={startFineTune}
- disabled={disabled || startingFineTune || !profile?.id}
- className="inline-flex items-center gap-1 px-2 py-1 text-xs rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-40"
- >
- {startingFineTune ? <Loader2 size={12} className="animate-spin" /> : <Activity size={12} />}
- Start Fine-Tuning Job
- </button>
- {fineTuneJob ? (
- <div className="p-2 border border-port-border/40 rounded bg-port-bg/40 text-[10px] space-y-1">
- <p>Job ID: {fineTuneJob.jobId} · Status: {fineTuneJob.status}</p>
- </div>
- ) : null}
- </div>
+ <VoiceFineTuningPanel
+ profileId={profile?.id || null}
+ disabled={disabled}
+ activeModelRevision={approved && profile.kind === 'fine-tuned' ? profile.modelRevision : null}
+ onPromoted={refreshProfiles}
+ />
)}
</BoxedSection>
);
diff --git a/client/src/components/voice/VoiceFineTuningPanel.jsx b/client/src/components/voice/VoiceFineTuningPanel.jsx
new file mode 100644
index 0000000000..b2fbdf8ab2
--- /dev/null
+++ b/client/src/components/voice/VoiceFineTuningPanel.jsx
@@ -0,0 +1,268 @@
+/**
+ * VoiceFineTuningPanel — the Voice Lab's Fine-Tuning tab (#10400).
+ *
+ * Starts a Qwen3-TTS fine-tune for one voice profile, then shows each run's
+ * live status and sealed checkpoints with their audition samples, cancels a
+ * running job, and promotes a verified checkpoint to the character's voice.
+ *
+ * Runs load once from the profile's job sidecars (so a reload recovers them)
+ * and then update from `voice:fine-tune:updated` frames, which carry the whole
+ * job — no timer, no refetch per frame. A reconnect or tab re-show reconciles
+ * against the list through `useSocketResource`.
+ */
+
+import { useRef, useState } from 'react';
+import { Activity, BadgeCheck, Loader2, Square } from 'lucide-react';
+import useAsyncAction from '../../hooks/useAsyncAction';
+import { useSocketResource } from '../../hooks/useSocketResource';
+import {
+ cancelFineTuningJob,
+ listFineTuningJobs,
+ promoteFineTunedCheckpoint,
+ startFineTuningJob,
+} from '../../services/apiVoice';
+import { formatCount, formatPercent, timeAgo } from '../../utils/formatters';
+
+const FINE_TUNE_EVENTS = ['voice:fine-tune:updated'];
+
+const STATUS_CLASS = {
+ running: 'text-port-accent',
+ completed: 'text-port-success',
+ failed: 'text-port-error',
+ interrupted: 'text-port-warning',
+ cancelled: 'text-gray-400',
+};
+
+const byNewest = (a, b) => String(b.startedAt || '').localeCompare(String(a.startedAt || ''));
+const upsertJob = (jobs, job) => [job, ...jobs.filter((existing) => existing.id !== job.id)].sort(byNewest);
+
+function CheckpointRow({ job, checkpoint, active, disabled, promoting, error, onPromote }) {
+ const label = `Step ${formatCount(checkpoint.step)}`;
+ const blocked = !checkpoint.promotable;
+ return (
+ <li className="flex flex-col gap-1 rounded border border-port-border/30 p-1.5 sm:flex-row sm:items-center sm:gap-2">
+ <div className="flex min-w-0 items-center gap-2 text-[10px] sm:w-32 sm:shrink-0">
+ <span className="font-medium text-gray-300">{label}</span>
+ {Number.isFinite(checkpoint.loss) ? <span className="text-gray-500">loss {checkpoint.loss.toFixed(3)}</span> : null}
+ </div>
+ {checkpoint.auditionUrl ? (
+ <audio
+ controls
+ preload="none"
+ src={checkpoint.auditionUrl}
+ aria-label={`Audition for ${label}`}
+ className="h-8 w-full min-w-0 sm:flex-1"
+ >
+ <track kind="captions" />
+ </audio>
+ ) : (
+ <span className="text-[10px] text-gray-500 sm:flex-1">No audition sample</span>
+ )}
+ <div className="flex min-w-0 flex-wrap items-center gap-1.5 sm:shrink-0 sm:justify-end">
+ {active ? (
+ <span className="inline-flex items-center gap-1 text-[10px] font-medium text-port-success">
+ <BadgeCheck size={10} /> Active voice
+ </span>
+ ) : (
+ <button
+ type="button"
+ onClick={() => onPromote(job, checkpoint)}
+ disabled={disabled || blocked || promoting}
+ aria-label={`Promote ${label}`}
+ className="inline-flex min-h-8 items-center gap-1 rounded bg-port-accent/20 px-2 py-0.5 text-[10px] text-port-accent hover:bg-port-accent hover:text-white disabled:opacity-40 disabled:hover:bg-port-accent/20 disabled:hover:text-port-accent"
+ >
+ {promoting ? <Loader2 size={10} className="animate-spin" /> : <BadgeCheck size={10} />} Promote
+ </button>
+ )}
+ {blocked || error ? (
+ <span role="note" className="min-w-0 break-words text-[10px] text-port-warning">
+ {error || checkpoint.promotionBlockedReason}
+ </span>
+ ) : null}
+ </div>
+ </li>
+ );
+}
+
+function JobCard({ job, activeModelRevision, disabled, cancelling, onCancel, promotingKey, promoteErrors, onPromote }) {
+ const running = job.status === 'running';
+ const progress = Number.isFinite(job.progress) ? Math.max(0, Math.min(100, job.progress)) : 0;
+ return (
+ <div className="space-y-1.5 rounded border border-port-border/40 bg-port-bg/40 p-2 text-[10px]">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <p className="min-w-0 text-gray-400">
+ <span className={`font-semibold capitalize ${STATUS_CLASS[job.status] || 'text-gray-300'}`}>{job.status}</span>
+ {' · '}started {timeAgo(job.startedAt, 'unknown')}
+ {job.step ? <> · step {formatCount(job.step)}{job.totalSteps ? ` / ${formatCount(job.totalSteps)}` : ''}</> : null}
+ {Number.isFinite(job.loss) ? <> · loss {job.loss.toFixed(3)}</> : null}
+ </p>
+ {running ? (
+ <button
+ type="button"
+ onClick={() => onCancel(job.id)}
+ disabled={disabled || cancelling}
+ className="inline-flex min-h-8 items-center gap-1 rounded border border-port-error/60 px-2 py-0.5 text-[10px] text-port-error hover:bg-port-error hover:text-white disabled:opacity-40"
+ >
+ {cancelling ? <Loader2 size={10} className="animate-spin" /> : <Square size={10} />} Cancel
+ </button>
+ ) : null}
+ </div>
+ {running ? (
+ <div
+ role="progressbar"
+ aria-label="Fine-tuning progress"
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={Math.round(progress)}
+ className="h-1.5 overflow-hidden rounded bg-port-border/40"
+ >
+ <div className="h-full bg-port-accent transition-all" style={{ width: `${progress}%` }} />
+ </div>
+ ) : null}
+ {running ? <p className="text-gray-500">{formatPercent(progress, { decimals: 0 })} · checkpoints appear here as they are sealed and auditioned.</p> : null}
+ {job.error && job.status !== 'running' ? <p className="break-words text-port-error">{job.error}</p> : null}
+ {job.checkpoints?.length ? (
+ <ul className="space-y-1" aria-label="Checkpoints">
+ {job.checkpoints.map((checkpoint) => {
+ const key = `${job.id}:${checkpoint.id}`;
+ return (
+ <CheckpointRow
+ key={key}
+ job={job}
+ checkpoint={checkpoint}
+ active={Boolean(activeModelRevision) && checkpoint.modelRevision === activeModelRevision}
+ disabled={disabled}
+ promoting={promotingKey === key}
+ error={promoteErrors[key]}
+ onPromote={onPromote}
+ />
+ );
+ })}
+ </ul>
+ ) : (
+ !running && <p className="text-gray-500">This run produced no checkpoints.</p>
+ )}
+ </div>
+ );
+}
+
+export default function VoiceFineTuningPanel({ profileId, disabled, activeModelRevision = null, onPromoted }) {
+ const [epochs, setEpochs] = useState(5);
+ const [promotingKey, setPromotingKey] = useState(null);
+ const [promoteErrors, setPromoteErrors] = useState({});
+ // The list the last read produced, keyed by profile, so event frames merge
+ // onto it without a network round-trip.
+ const jobsRef = useRef({ key: null, jobs: null });
+
+ const { data: jobs, loading, error, refetch, updateData } = useSocketResource(async ({ reconcile, events, signal }) => {
+ let list = jobsRef.current.key === profileId ? jobsRef.current.jobs : null;
+ if (reconcile || !list) list = (await listFineTuningJobs(profileId, { signal, silent: true }))?.jobs ?? [];
+ for (const { payload } of events) list = upsertJob(list, payload.job);
+ jobsRef.current = { key: profileId, jobs: list };
+ return list;
+ }, {
+ events: FINE_TUNE_EVENTS,
+ resourceKey: profileId || null,
+ enabled: Boolean(profileId),
+ matchesEvent: (payload) => payload?.profileId === profileId && Boolean(payload.job?.id),
+ });
+
+ // Apply a mutation's own response at once. Before the first list lands there
+ // is nothing to merge onto, so read instead of replacing it with one job.
+ const applyJob = (job) => {
+ const current = jobsRef.current.key === profileId ? jobsRef.current.jobs : null;
+ if (!job || !current) {
+ refetch();
+ return;
+ }
+ const next = upsertJob(current, job);
+ jobsRef.current = { key: profileId, jobs: next };
+ updateData(next);
+ };
+
+ const [start, starting] = useAsyncAction(async () => {
+ const result = await startFineTuningJob(profileId, { epochs }, { silent: true });
+ applyJob(result?.job);
+ return result;
+ }, { errorMessage: 'Failed to start fine-tuning' });
+
+ const [cancel, cancelling] = useAsyncAction(async (jobId) => {
+ const result = await cancelFineTuningJob(profileId, jobId, { silent: true });
+ applyJob(result?.job);
+ return result;
+ }, { errorMessage: 'Failed to cancel fine-tuning' });
+
+ // The refusal reason belongs beside the checkpoint it refused, so the error
+ // renders inline rather than as a toast.
+ const promote = async (job, checkpoint) => {
+ const key = `${job.id}:${checkpoint.id}`;
+ setPromotingKey(key);
+ const result = await promoteFineTunedCheckpoint(profileId, job.id, checkpoint.id, { silent: true })
+ .catch((err) => {
+ setPromoteErrors((prev) => ({ ...prev, [key]: err?.message || 'Could not promote checkpoint' }));
+ return null;
+ });
+ setPromotingKey(null);
+ if (!result) return;
+ setPromoteErrors(({ [key]: _cleared, ...rest }) => rest);
+ await onPromoted?.(result.profile);
+ };
+
+ const anyRunning = Boolean(jobs?.some((job) => job.status === 'running'));
+ const epochsId = `fine-tune-epochs-${profileId || 'none'}`;
+
+ return (
+ <div className="space-y-2">
+ <p className="text-[10px] text-gray-400">
+ Optional character voice fine-tuning. Requires a supported Qwen training adapter; without one the request is refused and no checkpoint is created.
+ </p>
+ <div className="flex flex-wrap items-end gap-2">
+ <div className="w-24">
+ <label htmlFor={epochsId} className="block text-[10px] text-gray-400">Epochs</label>
+ <input
+ id={epochsId}
+ type="number"
+ value={epochs}
+ onChange={(e) => setEpochs(parseInt(e.target.value, 10) || 5)}
+ min="1"
+ max="20"
+ className="mt-0.5 w-full rounded border border-port-border bg-port-bg px-2 py-1 text-xs text-white"
+ />
+ </div>
+ <button
+ type="button"
+ onClick={start}
+ disabled={disabled || starting || !profileId || anyRunning}
+ title={anyRunning ? 'A fine-tuning run is already in progress for this voice' : undefined}
+ className="inline-flex min-h-8 items-center gap-1 rounded bg-port-accent px-2 py-1 text-xs text-white hover:bg-port-accent/80 disabled:opacity-40"
+ >
+ {starting ? <Loader2 size={12} className="animate-spin" /> : <Activity size={12} />}
+ Start Fine-Tuning Job
+ </button>
+ </div>
+ {!profileId ? <p className="text-[10px] text-gray-500">Create or promote a voice profile before fine-tuning.</p> : null}
+ {profileId && loading && !jobs ? (
+ <p className="inline-flex items-center gap-1 text-[10px] text-gray-500"><Loader2 size={10} className="animate-spin" /> Loading runs…</p>
+ ) : null}
+ {error && !jobs ? <p className="text-[10px] text-port-error">Could not load fine-tuning runs: {error.message}</p> : null}
+ {jobs?.length ? (
+ <div className="space-y-1.5">
+ {jobs.map((job) => (
+ <JobCard
+ key={job.id}
+ job={job}
+ activeModelRevision={activeModelRevision}
+ disabled={disabled}
+ cancelling={cancelling}
+ onCancel={cancel}
+ promotingKey={promotingKey}
+ promoteErrors={promoteErrors}
+ onPromote={promote}
+ />
+ ))}
+ </div>
+ ) : null}
+ {jobs && !jobs.length ? <p className="text-[10px] text-gray-500">No fine-tuning runs for this voice yet.</p> : null}
+ </div>
+ );
+}
diff --git a/client/src/components/voice/VoiceFineTuningPanel.test.jsx b/client/src/components/voice/VoiceFineTuningPanel.test.jsx
new file mode 100644
index 0000000000..b3c33e6338
--- /dev/null
+++ b/client/src/components/voice/VoiceFineTuningPanel.test.jsx
@@ -0,0 +1,115 @@
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import VoiceFineTuningPanel from './VoiceFineTuningPanel';
+
+const mocks = vi.hoisted(() => ({
+ handlers: new Map(), list: vi.fn(), start: vi.fn(), cancel: vi.fn(), promote: vi.fn(),
+}));
+vi.mock('../../services/socket', () => ({ default: {
+ on: (event, callback) => { if (!mocks.handlers.has(event)) mocks.handlers.set(event, new Set()); mocks.handlers.get(event).add(callback); },
+ off: (event, callback) => mocks.handlers.get(event)?.delete(callback),
+} }));
+vi.mock('../../services/apiVoice', () => ({
+ listFineTuningJobs: (...args) => mocks.list(...args),
+ startFineTuningJob: (...args) => mocks.start(...args),
+ cancelFineTuningJob: (...args) => mocks.cancel(...args),
+ promoteFineTunedCheckpoint: (...args) => mocks.promote(...args),
+}));
+vi.mock('../ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));
+
+const emit = (event, data) => act(() => { mocks.handlers.get(event)?.forEach((callback) => callback(data)); });
+
+const PROFILE_ID = 'voice-profile-1';
+const JOB_ID = '11111111-2222-4333-8444-555555555555';
+const REVISION = `Qwen/Base@${'a'.repeat(40)}+sha256.${'b'.repeat(64)}`;
+const job = (overrides = {}) => ({
+ id: JOB_ID, profileId: PROFILE_ID, status: 'running', progress: 10, step: 10, totalSteps: 100,
+ startedAt: '2026-01-01T00:00:00.000Z', checkpoints: [], error: null, ...overrides,
+});
+const checkpoint = (step, overrides = {}) => ({
+ id: `checkpoint-step-${step}`, step, loss: 0.5, modelRevision: REVISION,
+ auditionUrl: `/data/voice-profiles/${PROFILE_ID}/fine-tune/${JOB_ID}/checkpoint-step-${step}/audition.wav`,
+ promotable: true, promotionBlockedReason: null, ...overrides,
+});
+const frame = (overrides) => ({ profileId: PROFILE_ID, job: job(overrides) });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.handlers.clear();
+ mocks.list.mockResolvedValue({ jobs: [] });
+});
+
+describe('VoiceFineTuningPanel', () => {
+ it('recovers the newest run on mount and applies pushed frames without refetching', async () => {
+ mocks.list.mockResolvedValue({ jobs: [job()] });
+ render(<VoiceFineTuningPanel profileId={PROFILE_ID} />);
+ expect(await screen.findByText('running')).toBeTruthy();
+ expect(mocks.list).toHaveBeenCalledTimes(1);
+ expect(mocks.list).toHaveBeenCalledWith(PROFILE_ID, expect.objectContaining({ silent: true }));
+ // A run in progress blocks a second one on the same voice.
+ expect(screen.getByRole('button', { name: /Start Fine-Tuning Job/ })).toBeDisabled();
+
+ emit('voice:fine-tune:updated', { profileId: 'other-profile', job: job({ id: 'x', checkpoints: [checkpoint(5)] }) });
+ emit('voice:fine-tune:updated', frame({ step: 20, progress: 20, checkpoints: [checkpoint(20)] }));
+ const audio = await screen.findByLabelText('Audition for Step 20');
+ expect(audio.getAttribute('src')).toBe(checkpoint(20).auditionUrl);
+ expect(screen.queryByLabelText('Audition for Step 5')).toBeNull();
+ expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).toBe('20');
+
+ emit('voice:fine-tune:updated', frame({ status: 'completed', progress: 100, checkpoints: [checkpoint(20)] }));
+ expect(await screen.findByText('completed')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /Cancel/ })).toBeNull();
+ expect(mocks.list).toHaveBeenCalledTimes(1);
+ });
+
+ it('starts a run, then cancels it and shows cancelled from the response', async () => {
+ render(<VoiceFineTuningPanel profileId={PROFILE_ID} />);
+ expect(await screen.findByText(/No fine-tuning runs/)).toBeTruthy();
+ mocks.start.mockResolvedValue({ jobId: JOB_ID, status: 'running', job: job({ step: 0, progress: 0 }) });
+ fireEvent.change(screen.getByLabelText('Epochs'), { target: { value: '8' } });
+ fireEvent.click(screen.getByRole('button', { name: /Start Fine-Tuning Job/ }));
+ await waitFor(() => expect(mocks.start).toHaveBeenCalledWith(PROFILE_ID, { epochs: 8 }, { silent: true }));
+ expect(await screen.findByText('running')).toBeTruthy();
+
+ mocks.cancel.mockResolvedValue({ ok: true, jobId: JOB_ID, status: 'cancelled', job: job({ status: 'cancelled', error: 'Cancelled by user' }) });
+ fireEvent.click(screen.getByRole('button', { name: /Cancel/ }));
+ expect(await screen.findByText('cancelled')).toBeTruthy();
+ expect(mocks.cancel).toHaveBeenCalledWith(PROFILE_ID, JOB_ID, { silent: true });
+ expect(screen.getByText('Cancelled by user')).toBeTruthy();
+ });
+
+ it('promotes a verified checkpoint, refreshes profiles, and keeps an unverified one blocked with its reason', async () => {
+ const unverified = checkpoint(10, {
+ id: 'checkpoint-10.safetensors', modelRevision: undefined, auditionUrl: null,
+ promotable: false, promotionBlockedReason: 'Checkpoint was not produced by a supported training adapter',
+ });
+ mocks.list.mockResolvedValue({ jobs: [job({ status: 'completed', checkpoints: [unverified, checkpoint(20)] })] });
+ const onPromoted = vi.fn();
+ const { rerender } = render(<VoiceFineTuningPanel profileId={PROFILE_ID} onPromoted={onPromoted} />);
+
+ const blocked = await screen.findByRole('button', { name: 'Promote Step 10' });
+ expect(blocked).toBeDisabled();
+ expect(within(blocked.closest('li')).getByRole('note').textContent).toMatch(/supported training adapter/);
+
+ const promotedProfile = { id: PROFILE_ID, kind: 'fine-tuned', modelRevision: REVISION, approval: { status: 'approved' } };
+ mocks.promote.mockResolvedValue({ profile: promotedProfile });
+ fireEvent.click(screen.getByRole('button', { name: 'Promote Step 20' }));
+ await waitFor(() => expect(onPromoted).toHaveBeenCalledWith(promotedProfile));
+ expect(mocks.promote).toHaveBeenCalledWith(PROFILE_ID, JOB_ID, 'checkpoint-step-20', { silent: true });
+
+ rerender(<VoiceFineTuningPanel profileId={PROFILE_ID} onPromoted={onPromoted} activeModelRevision={REVISION} />);
+ expect(screen.getByText('Active voice')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'Promote Step 20' })).toBeNull();
+ });
+
+ it('shows the server refusal beside the checkpoint it refused', async () => {
+ mocks.list.mockResolvedValue({ jobs: [job({ status: 'interrupted', error: 'Training stopped when the server restarted', checkpoints: [checkpoint(20)] })] });
+ render(<VoiceFineTuningPanel profileId={PROFILE_ID} />);
+ const button = await screen.findByRole('button', { name: 'Promote Step 20' });
+ expect(screen.getByText(/server restarted/)).toBeTruthy();
+ const refusal = Object.assign(new Error('Checkpoint was not produced by a supported training adapter'), { status: 409 });
+ mocks.promote.mockRejectedValue(refusal);
+ fireEvent.click(button);
+ await waitFor(() => expect(within(button.closest('li')).getByRole('note').textContent).toMatch(/supported training adapter/));
+ });
+});
diff --git a/client/src/services/apiVoice.js b/client/src/services/apiVoice.js
index 4fdcc6f173..66e2dd5d77 100644
--- a/client/src/services/apiVoice.js
+++ b/client/src/services/apiVoice.js
@@ -39,6 +39,15 @@ export const completeVoiceProfileInteractiveBenchmark = (profileId, payload, opt
export const startFineTuningJob = (profileId, payload = {}, options) => api.post(
`/voice/profiles/${encodeURIComponent(profileId)}/fine-tune/start`, payload, options,
);
+const fineTunePath = (profileId, jobId = '') => `/voice/profiles/${encodeURIComponent(profileId)}/fine-tune${
+ jobId ? `/${encodeURIComponent(jobId)}` : ''}`;
+export const listFineTuningJobs = (profileId, options) => api.get(fineTunePath(profileId), options);
+export const cancelFineTuningJob = (profileId, jobId, options) => api.post(
+ `${fineTunePath(profileId, jobId)}/cancel`, {}, options,
+);
+export const promoteFineTunedCheckpoint = (profileId, jobId, checkpointId, options) => api.post(
+ `${fineTunePath(profileId, jobId)}/promote`, { checkpointId }, options,
+);
// Returns the raw WAV bytes of the test utterance.
export const testTts = (text, voice, engine) => {
diff --git a/docs/features/voice.md b/docs/features/voice.md
index 21071f1fb2..b97dd787e9 100644
--- a/docs/features/voice.md
+++ b/docs/features/voice.md
@@ -472,3 +472,12 @@ Fixture tests prove this publication contract, not training quality. A real trai
hardware is still pending in #8857. Operators should listen to each audition before promoting. The runtime 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.
+
+The character Voice Lab's **Fine-Tuning** tab drives the whole run (#10400). On open it reads the profile's
+runs from their `job.json` sidecars (`GET /api/voice/profiles/:id/fine-tune`, newest first), so a reload
+recovers them. After that it applies `voice:fine-tune:updated` frames, which carry the whole job, on each
+status change, each sealed checkpoint, and at most once a second during training. It does not poll. Each
+checkpoint plays its audition from `/data/voice-profiles/…`. **Promote** is disabled, with the refusal
+reason beside it, on any checkpoint the server would refuse. **Cancel** appears while a run is live. A
+sidecar left `running` by a server restart is reported as `interrupted`, because its process is gone. Its
+sealed checkpoints remain promotable.
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index 242bc6d7ba..0dcf90c501 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -57,6 +57,31 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({
direction: 'server-to-client', summary: 'Voice library or runtime setup changed; refetch authenticated state.',
payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
},
+ 'voice:fine-tune:updated': {
+ direction: 'server-to-client',
+ summary: 'One voice fine-tuning job after a status change, a sealed checkpoint, or throttled training progress.',
+ payloadSchema: {
+ type: 'object',
+ required: ['profileId', 'job'],
+ properties: {
+ profileId: { type: 'string' },
+ job: {
+ type: 'object',
+ required: ['id', 'profileId', 'status', 'checkpoints'],
+ properties: {
+ id: { type: 'string', format: 'uuid' },
+ profileId: { type: 'string' },
+ status: { type: 'string', enum: ['running', 'completed', 'failed', 'cancelled', 'interrupted'] },
+ progress: { type: ['number', 'null'] },
+ step: { type: ['integer', 'null'] },
+ totalSteps: { type: ['integer', 'null'] },
+ error: { type: ['string', 'null'] },
+ checkpoints: { type: 'array', items: { type: 'object' } },
+ },
+ },
+ },
+ },
+ },
'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/routes/voice.js b/server/routes/voice.js
index ec154cc863..019cda2580 100644
--- a/server/routes/voice.js
+++ b/server/routes/voice.js
@@ -31,6 +31,7 @@ import { renderProfileBenchmark, benchmarkProfileInteractive, completeProfileInt
import { getQwen3RuntimeStatus, downloadQwen3Model, DEFAULT_DESIGN_MODEL } from '../services/voice/qwen3TtsRuntime.js';
import {
startFineTuningJob,
+ listFineTuningJobs,
getFineTuningJobStatus,
cancelFineTuningJob,
promoteCheckpoint,
@@ -438,6 +439,14 @@ router.post('/profiles/:id/fine-tune/start', asyncHandler(async (req, res) => {
res.status(202).json(result);
}));
+// Newest-first runs from their job.json sidecars, so the Voice Lab recovers a
+// run (and its checkpoints) after a reload; live changes arrive on
+// `voice:fine-tune:updated`.
+router.get('/profiles/:id/fine-tune', asyncHandler(async (req, res) => {
+ const { id: profileId } = validateRequest(profileIdParamsSchema, req.params);
+ res.json({ jobs: await listFineTuningJobs(profileId) });
+}));
+
router.get('/profiles/:id/fine-tune/:jobId', asyncHandler(async (req, res) => {
const { id: profileId, jobId } = validateRequest(fineTuneJobParamsSchema, req.params);
const result = await getFineTuningJobStatus(jobId, profileId);
@@ -445,8 +454,8 @@ router.get('/profiles/:id/fine-tune/:jobId', asyncHandler(async (req, res) => {
}));
router.post('/profiles/:id/fine-tune/:jobId/cancel', asyncHandler(async (req, res) => {
- const { jobId } = validateRequest(fineTuneJobParamsSchema, req.params);
- const result = cancelFineTuningJob(jobId);
+ const { id: profileId, jobId } = validateRequest(fineTuneJobParamsSchema, req.params);
+ const result = cancelFineTuningJob(jobId, profileId);
res.json(result);
}));
diff --git a/server/routes/voice.test.js b/server/routes/voice.test.js
index 1e6194a5f1..95f7dde217 100644
--- a/server/routes/voice.test.js
+++ b/server/routes/voice.test.js
@@ -51,6 +51,7 @@ vi.mock('../services/voice/qwen3TtsRuntime.js', () => ({
}));
vi.mock('../services/voice/fineTuning.js', () => ({
startFineTuningJob: vi.fn(),
+ listFineTuningJobs: vi.fn(),
getFineTuningJobStatus: vi.fn(),
cancelFineTuningJob: vi.fn(),
promoteCheckpoint: vi.fn(),
@@ -244,12 +245,29 @@ describe('Voice Routes', () => {
const cancelRes = await request(buildApp()).post(`/api/voice/profiles/voice-profile-1/fine-tune/${jobId}/cancel`).send({});
expect(cancelRes.status).toBe(200);
+ // Cancel is scoped to the profile in the URL, like status and promote.
+ expect(fineTuning.cancelFineTuningJob).toHaveBeenCalledWith(jobId, 'voice-profile-1');
const promoteRes = await request(buildApp()).post(`/api/voice/profiles/voice-profile-1/fine-tune/${jobId}/promote`).send({ checkpointId: 'ckpt-1' });
expect(promoteRes.status).toBe(200);
expect(promoteRes.body.profile.kind).toBe('fine-tuned');
});
+ it('lists a profile\'s fine-tuning jobs so the Voice Lab recovers them after a reload', async () => {
+ const jobs = [{ id: '11111111-2222-4333-8444-555555555555', status: 'interrupted', checkpoints: [] }];
+ fineTuning.listFineTuningJobs.mockResolvedValue(jobs);
+
+ const res = await request(buildApp()).get('/api/voice/profiles/voice-profile-1/fine-tune');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ jobs });
+ expect(fineTuning.listFineTuningJobs).toHaveBeenCalledWith('voice-profile-1');
+
+ fineTuning.listFineTuningJobs.mockClear();
+ const bad = await request(buildApp()).get('/api/voice/profiles/Not_A_Profile/fine-tune');
+ expect(bad.status).toBe(400);
+ expect(fineTuning.listFineTuningJobs).not.toHaveBeenCalled();
+ });
+
it('rejects a fine-tuning job id that could escape the profile directory', async () => {
const res = await request(buildApp())
.get('/api/voice/profiles/voice-profile-1/fine-tune/..%2F..%2Fother-profile');
diff --git a/server/services/socket.js b/server/services/socket.js
index 456c65beba..a96cc6222e 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -37,6 +37,7 @@ import { importerEvents, getImporterProgressFrames } from './importerEvents.js';
import { catalogEvents } from './catalogEvents.js';
import { writersRoomEvents } from './writersRoomEvents.js';
import { musicVideoEvents } from './musicVideo/events.js';
+import { fineTuningEvents } from './voice/fineTuningEvents.js';
import { videoGenEvents } from './videoGen/events.js';
import { audioGenEvents } from './audioGen/events.js';
import { aiStatusEvents } from './aiStatusEvents.js';
@@ -306,6 +307,9 @@ const SIMPLE_BRIDGES = [
// The call-host tab already gets `voice:call:state` from its own socket
// handler (server/sockets/voice.js); this fans it out to every OTHER tab.
{ emitter: callStateEvents, event: 'state', channel: 'voice:call:state' },
+ // A Voice Lab fine-tuning run changed status, sealed a checkpoint, or
+ // advanced (throttled) — the Fine-Tuning tab applies the job frame (#10400).
+ { emitter: fineTuningEvents, event: 'updated', channel: 'voice:fine-tune:updated' },
// A storyboard render filed durably by writersRoomSceneImageHook (#1363).
{ emitter: writersRoomEvents, event: 'scene-image', channel: 'writers-room:scene-image' },
// Scene reference frame / i2v clip filed durably by the music-video hooks
diff --git a/server/services/voice/fineTuning.js b/server/services/voice/fineTuning.js
index 0c903a6277..42c9565cb8 100644
--- a/server/services/voice/fineTuning.js
+++ b/server/services/voice/fineTuning.js
@@ -1,8 +1,9 @@
/**
* Qwen3-TTS Voice Fine-Tuning Service (#5381).
*
- * Provides dataset readiness validation, explicit start, streaming progress,
- * checkpoint generation, audition samples, cancellation, and explicit
+ * Provides dataset readiness validation, explicit start, pushed progress
+ * (`fineTuningEvents` → `voice:fine-tune:updated`), checkpoint generation,
+ * audition samples, per-profile job listing, cancellation, and explicit
* checkpoint promotion.
*
* Training is machine-local, optional, and never assumes the last checkpoint is best.
@@ -16,11 +17,12 @@
import { randomUUID } from 'node:crypto';
import { existsSync } from 'node:fs';
import { mkdir, readdir } from 'node:fs/promises';
-import { dirname, join } from 'node:path';
+import { dirname, isAbsolute, join, relative, sep } from 'node:path';
import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { spawn } from '../../lib/childProcess.js';
import { ServerError } from '../../lib/errorHandler.js';
import { atomicWrite, readJSONFileStrict } from '../../lib/fileUtils.js';
+import { PATHS } from '../../lib/paths.js';
import { safeChildProcessOptions } from '../../lib/processEnv.js';
import { closeJobAfterDelay } from '../../lib/sseUtils.js';
import {
@@ -35,6 +37,7 @@ import {
profileArtifactDirectory,
promoteFineTunedProfile,
} from './profiles.js';
+import { fineTuningEvents } from './fineTuningEvents.js';
// In-memory active training job map. Entries are evicted once terminal (see
// `finalizeJob`); the durable record is the `job.json` sidecar written beside
@@ -64,6 +67,18 @@ const TRAINING_SPEAKER = 'portos_voice';
const DATASET_MANIFEST_FILE = 'dataset.json';
const AUDIO_FILE_RE = /\.(wav|mp3|flac|m4a)$/i;
const STDERR_TAIL_BYTES = 8192;
+// Training frames arrive every optimizer step; the UI only needs a progress
+// tick, so step progress is pushed at most this often. Status changes and
+// sealed checkpoints are always pushed immediately.
+const PROGRESS_PUSH_INTERVAL_MS = 1000;
+// The Voice Lab shows the newest runs; older sidecars stay on disk untouched.
+const MAX_LISTED_JOBS = 20;
+// A `running` sidecar with no live process is a run the server lost on
+// restart: its child is gone, so it can neither progress nor be cancelled.
+const INTERRUPTED_ERROR = 'Training stopped when the server restarted';
+// The one reason a checkpoint is refused promotion; shown beside the disabled
+// Promote control and returned as the 409 message.
+const UNVERIFIED_CHECKPOINT_REASON = 'Checkpoint was not produced by a supported training adapter';
const jobRecordPath = (profileId, jobId) =>
join(profileArtifactDirectory(profileId), 'fine-tune', jobId, JOB_RECORD_FILE);
@@ -89,6 +104,48 @@ const serializableJob = ({
...record
}) => record;
+// Earlier runners wrote text placeholders named .safetensors. A checkpoint
+// without its producing adapter and sealed revision never becomes a voice.
+const promotionBlockedReason = (job, checkpoint) => (
+ !job.trainingAdapter || typeof checkpoint.modelRevision !== 'string' ? UNVERIFIED_CHECKPOINT_REASON : null
+);
+
+// The audition WAV is written beside its checkpoint under the voice-profiles
+// root, which is mounted at /data/voice-profiles.
+const auditionUrl = (sampleWav) => {
+ if (typeof sampleWav !== 'string') return null;
+ const rel = relative(PATHS.voiceProfiles, sampleWav);
+ if (!rel || rel.startsWith('..') || isAbsolute(rel)) return null;
+ return `/data/voice-profiles/${rel.split(sep).map(encodeURIComponent).join('/')}`;
+};
+
+/**
+ * The client view of a job: the durable record plus what the Voice Lab renders
+ * per checkpoint — a playable audition URL and whether (and why not) it can be
+ * promoted, decided by the same predicate `promoteCheckpoint` enforces.
+ */
+const publicJob = (job) => {
+ const record = serializableJob(job);
+ return {
+ ...record,
+ checkpoints: record.checkpoints.map((checkpoint) => {
+ const blockedReason = promotionBlockedReason(record, checkpoint);
+ return {
+ ...checkpoint,
+ auditionUrl: auditionUrl(checkpoint.sampleWav),
+ promotable: !blockedReason,
+ promotionBlockedReason: blockedReason,
+ };
+ }),
+ };
+};
+
+// Pushes the live state at the moment of the change, so frames arrive in the
+// order the state moved and the last one is always current.
+const publishJob = (jobState) => {
+ fineTuningEvents.emit('updated', { profileId: jobState.profileId, job: publicJob(jobState) });
+};
+
/**
* Write the job record to disk. Writes are chained per job because `close` and
* `error` can both fire for one child and each rewrites the same file.
@@ -104,6 +161,7 @@ const persistJob = (jobState) => {
// write that runs after a later terminal event serializes the mutable current
// object and can race the terminal write out of order.
const record = structuredClone(serializableJob(jobState));
+ publishJob(jobState);
jobState.persistChain = (jobState.persistChain || Promise.resolve())
.then(() => withBackupAssetPublication(() => atomicWrite(jobRecordPath(jobState.profileId, jobState.id), record)))
.catch((err) => console.error(`❌ Failed to persist fine-tune job ${jobState.id}: ${err.message}`));
@@ -127,6 +185,8 @@ async function loadJob(jobId, profileId) {
code: 'JOB_RECORD_UNREADABLE',
});
}
+ // Reported, not rewritten: the sidecar stays exactly as the run left it.
+ if (value?.status === 'running') return { ...value, status: 'interrupted', error: value.error || INTERRUPTED_ERROR };
return value;
}
@@ -320,6 +380,7 @@ export async function startFineTuningJob({
};
let lineBuffer = '';
+ let lastProgressPush = 0;
child.stdout.on('data', (chunk) => {
lineBuffer += chunk.toString();
const lines = lineBuffer.split('\n');
@@ -335,6 +396,10 @@ export async function startFineTuningJob({
jobState.totalSteps = event.total_steps || jobState.totalSteps;
jobState.loss = event.loss;
jobState.progress = event.progress;
+ if (Date.now() - lastProgressPush >= PROGRESS_PUSH_INTERVAL_MS) {
+ lastProgressPush = Date.now();
+ publishJob(jobState);
+ }
} else if (event.stage === 'checkpoint' && isPublishedCheckpoint(event, outputDir)) {
jobState.checkpoints.push({
id: event.checkpoint,
@@ -354,6 +419,7 @@ export async function startFineTuningJob({
jobState.status = 'completed';
jobState.progress = 100;
jobState.completedAt = new Date().toISOString();
+ publishJob(jobState);
}
} catch {
// non-JSON log line
@@ -397,9 +463,36 @@ export async function startFineTuningJob({
totalSteps: jobState.totalSteps,
trainingAdapter: jobState.trainingAdapter,
startedAt: jobState.startedAt,
+ job: publicJob(jobState),
};
}
+/**
+ * List a profile's fine-tuning runs, newest first, from their `job.json`
+ * sidecars (live state for a run still in memory). This is how the Voice Lab
+ * recovers a run after a reload or a restart.
+ */
+export async function listFineTuningJobs(profileId) {
+ const profile = await getVoiceProfileRequired(profileId);
+ const root = join(profileArtifactDirectory(profile.id), 'fine-tune');
+ const entries = await readdir(root, { withFileTypes: true }).catch((err) => {
+ if (err.code === 'ENOENT') return [];
+ throw err;
+ });
+ const jobs = await Promise.all(entries
+ .filter((entry) => entry.isDirectory() && JOB_ID_RE.test(entry.name))
+ .map((entry) => loadJob(entry.name, profile.id).catch((err) => {
+ // One corrupt sidecar must not hide every other run of this voice.
+ console.warn(`⚠️ Skipping unreadable fine-tune job ${entry.name}: ${err.message}`);
+ return null;
+ })));
+ return jobs
+ .filter(Boolean)
+ .map(publicJob)
+ .sort((a, b) => String(b.startedAt || '').localeCompare(String(a.startedAt || '')))
+ .slice(0, MAX_LISTED_JOBS);
+}
+
/**
* Get the current status and checkpoints of a fine-tuning job, from memory
* while it is live and from its `job.json` sidecar afterwards.
@@ -409,22 +502,24 @@ export async function getFineTuningJobStatus(jobId, profileId) {
if (!job) {
throw new ServerError('Fine-tuning job not found', { status: 404, code: 'JOB_NOT_FOUND' });
}
- return serializableJob(job);
+ return publicJob(job);
}
/**
- * Cancel an active fine-tuning job.
+ * Cancel an active fine-tuning job. With a `profileId`, a job belonging to a
+ * different profile is reported as not found.
*/
-export function cancelFineTuningJob(jobId) {
+export function cancelFineTuningJob(jobId, profileId) {
const job = activeJobs.get(jobId);
- if (!job) {
+ if (!job || (profileId && job.profileId !== profileId)) {
throw new ServerError('Fine-tuning job not found', { status: 404, code: 'JOB_NOT_FOUND' });
}
if (job.status === 'running') {
job.controller.abort();
Object.assign(job, CANCELLED_OUTCOME, { completedAt: new Date().toISOString() });
+ publishJob(job);
}
- return { ok: true, jobId, status: job.status };
+ return { ok: true, jobId, status: job.status, job: publicJob(job) };
}
/**
@@ -439,13 +534,9 @@ export async function promoteCheckpoint({ profileId, jobId, checkpointId }) {
if (!ckpt) {
throw new ServerError(`Checkpoint not found: ${checkpointId}`, { status: 404, code: 'CHECKPOINT_NOT_FOUND' });
}
- // Earlier runners wrote text placeholders named .safetensors. A checkpoint
- // without its producing adapter and sealed revision never becomes a voice.
- if (!job.trainingAdapter || typeof ckpt.modelRevision !== 'string') {
- throw new ServerError('Checkpoint was not produced by a supported training adapter', {
- status: 409,
- code: 'CHECKPOINT_UNVERIFIED',
- });
+ const blockedReason = promotionBlockedReason(job, ckpt);
+ if (blockedReason) {
+ throw new ServerError(blockedReason, { status: 409, code: 'CHECKPOINT_UNVERIFIED' });
}
return promoteFineTunedProfile({
diff --git a/server/services/voice/fineTuning.test.js b/server/services/voice/fineTuning.test.js
index 530a514c61..8ca5f72189 100644
--- a/server/services/voice/fineTuning.test.js
+++ b/server/services/voice/fineTuning.test.js
@@ -36,8 +36,10 @@ vi.mock('./qwen3TtsRuntime.js', async (importOriginal) => {
return { ...actual, getQwen3RuntimeStatus: async () => runtimeOverride ?? actual.getQwen3RuntimeStatus() };
});
+const { fineTuningEvents } = await import('./fineTuningEvents.js');
const {
validateFineTuningDataset,
+ listFineTuningJobs,
startFineTuningJob,
getFineTuningJobStatus,
cancelFineTuningJob,
@@ -339,6 +341,82 @@ describe('fineTuning', () => {
});
});
+ it('pushes status changes, sealed checkpoints and throttled progress for the Voice Lab (#10400)', async () => {
+ queryMock.mockResolvedValue({ rows: [{ data: PROFILE }] });
+ await seedSourceAudio();
+ const scripted = useScriptedRunner();
+ const frames = [];
+ const onUpdated = (frame) => frames.push(frame);
+ fineTuningEvents.on('updated', onUpdated);
+ try {
+ const { jobId, job } = await startFineTuningJob({ profileId: PROFILE.id, epochs: 2, checkpointInterval: 20 });
+ // The start response carries the same projection the event does.
+ expect(job).toMatchObject({ id: jobId, status: 'running', checkpoints: [] });
+ expect(frames.at(-1)).toMatchObject({ profileId: PROFILE.id, job: { id: jobId, status: 'running' } });
+
+ // Two steps in one burst: the first is pushed, the second is throttled.
+ const before = frames.length;
+ scripted().emitFrames(
+ { stage: 'training', step: 10, total_steps: 100, loss: 1.5, progress: 10 },
+ { stage: 'training', step: 11, total_steps: 100, loss: 1.4, progress: 11 },
+ );
+ expect(frames.slice(before).map((frame) => frame.job.step)).toEqual([10]);
+
+ scripted().emitFrames(checkpointFrame(jobId, 20));
+ expect(frames.at(-1).job.checkpoints).toEqual([expect.objectContaining({
+ id: 'checkpoint-step-20',
+ auditionUrl: `/data/voice-profiles/${PROFILE.id}/fine-tune/${jobId}/checkpoint-step-20/audition.wav`,
+ promotable: true,
+ promotionBlockedReason: null,
+ })]);
+
+ // Cancel is scoped to the profile that owns the run.
+ expect(() => cancelFineTuningJob(jobId, 'other-profile')).toThrow(/not found/i);
+ expect(cancelFineTuningJob(jobId, PROFILE.id).job.status).toBe('cancelled');
+ expect(frames.at(-1).job.status).toBe('cancelled');
+
+ await drainJobRecord(jobId);
+ expect(frames.at(-1).job).toMatchObject({ status: 'cancelled', checkpoints: [expect.any(Object)] });
+ } finally {
+ fineTuningEvents.off('updated', onUpdated);
+ }
+ });
+
+ it('lists a profile\'s runs newest first from their sidecars, flagging lost and unverified ones', async () => {
+ queryMock.mockResolvedValue({ rows: [{ data: PROFILE }] });
+ expect(await listFineTuningJobs(PROFILE.id)).toEqual([]);
+
+ const seedRecord = async (jobId, record) => {
+ await mkdir(jobDir(jobId), { recursive: true });
+ if (record !== undefined) await writeFile(jobRecordPath(jobId), typeof record === 'string' ? record : JSON.stringify(record));
+ };
+ const older = '11111111-2222-4333-8444-555555555555';
+ const newer = '22222222-2222-4333-8444-555555555555';
+ await seedRecord(older, {
+ id: older, profileId: PROFILE.id, status: 'completed', startedAt: '2026-01-01T00:00:00.000Z',
+ // A legacy placeholder: no producing adapter, no sealed revision.
+ checkpoints: [{ id: 'checkpoint-20.safetensors', step: 20, checkpointPath: '/legacy/checkpoint-20.safetensors' }],
+ });
+ // The server restarted mid-run: the sidecar still says running.
+ await seedRecord(newer, {
+ id: newer, profileId: PROFILE.id, status: 'running', startedAt: '2026-02-01T00:00:00.000Z',
+ trainingAdapter: 'qwen-tts-sft-12hz', checkpoints: [],
+ });
+ await seedRecord('33333333-2222-4333-8444-555555555555', '{ truncated');
+ await seedRecord('not-a-job');
+
+ const jobs = await listFineTuningJobs(PROFILE.id);
+ expect(jobs.map((job) => [job.id, job.status])).toEqual([[newer, 'interrupted'], [older, 'completed']]);
+ expect(jobs[0].error).toMatch(/server restarted/);
+ expect(jobs[1].checkpoints[0]).toMatchObject({
+ promotable: false,
+ promotionBlockedReason: 'Checkpoint was not produced by a supported training adapter',
+ auditionUrl: null,
+ });
+ // Reported, never rewritten.
+ expect(JSON.parse(await readFile(jobRecordPath(newer), 'utf8')).status).toBe('running');
+ });
+
it('persists a job.json sidecar beside the checkpoints when the run finishes', async () => {
queryMock.mockResolvedValue({ rows: [{ data: PROFILE }] });
await seedSourceAudio();
diff --git a/server/services/voice/fineTuningEvents.js b/server/services/voice/fineTuningEvents.js
new file mode 100644
index 0000000000..565cc1b7ab
--- /dev/null
+++ b/server/services/voice/fineTuningEvents.js
@@ -0,0 +1,11 @@
+import { EventEmitter } from 'node:events';
+
+// Voice fine-tuning job bus (#10400). Kept apart from `fineTuning.js` so the
+// Socket.IO bridge in services/socket.js does not pull the training service's
+// child-process and runtime imports into its closure.
+//
+// 'updated' → { profileId, job } — the client projection of one job after a
+// status change, a sealed checkpoint, or (throttled) training progress.
+//
+// socket.js bridges it to `voice:fine-tune:updated`.
+export const fineTuningEvents = new EventEmitter();