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: let Image Gen and Video Gen render on a federated peer (#4348)

[._.]/ Adam Eivy7d549882f73d
diff --git a/client/src/components/federatedMedia/RemoteMediaTargetPicker.jsx b/client/src/components/federatedMedia/RemoteMediaTargetPicker.jsx
new file mode 100644
index 0000000000..4167379d9a
--- /dev/null
+++ b/client/src/components/federatedMedia/RemoteMediaTargetPicker.jsx
@@ -0,0 +1,100 @@
+/**
+ * "Generation target" selector for any render form that can run a job on a
+ * federated peer instead of on this machine (#4348).
+ *
+ * The peer list, the per-kind model allowlist intersection, and the readiness
+ * verdict all come from `useFederatedMediaTarget` — this component only renders
+ * them, so Music Studio, Image Gen and Video Gen cannot drift into three
+ * different readings of the same peer.
+ *
+ * `localBlockedReason` is the HOST form's own veto (conditioning the federated
+ * wire cannot carry, a mode that isn't text-to-media). It renders alongside the
+ * target's readiness rather than replacing it: the two answer different
+ * questions, and a form can be blocked by both at once.
+ */
+
+import { Server } from 'lucide-react';
+import { federatedMediaModelKey, resolvePeerMediaReadiness } from '../../lib/federatedMediaReadiness.js';
+
+const peerLabel = (peer) => peer.name || peer.address || 'Federated peer';
+
+export default function RemoteMediaTargetPicker({
+ target,
+ kind,
+ disabled = false,
+ localBlockedReason = null,
+ children = null,
+}) {
+ const {
+ peers, peer, peerId, setPeerId, models, modelKey, setModelKey,
+ isRemote, readiness, queueSegments, blockedReason,
+ } = target;
+ // Nothing is opted in as a provider — an empty "This instance" dropdown is a
+ // control with one option and no way for the user to grow another.
+ if (peers.length === 0) return null;
+
+ return (
+ <div className="space-y-2">
+ <label className="block">
+ <span className="block text-[11px] uppercase tracking-wider text-gray-500 mb-1">Generation target</span>
+ <select
+ aria-label="Generation target"
+ value={peerId}
+ onChange={(e) => setPeerId(e.target.value)}
+ disabled={disabled}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm disabled:opacity-50"
+ >
+ <option value="">This instance</option>
+ {peers.map((candidate) => {
+ // Same reading as the caption and the submit button. Without the
+ // suffix a switched-off or lapsed peer sits in the list looking
+ // exactly like a ready one.
+ const candidateReadiness = resolvePeerMediaReadiness(candidate);
+ const suffix = candidateReadiness.usable ? '' : ` (${candidateReadiness.label})`;
+ return (
+ <option key={candidate.id} value={candidate.id}>
+ {peerLabel(candidate)}{suffix}
+ </option>
+ );
+ })}
+ </select>
+ </label>
+
+ {isRemote && (
+ <div className="space-y-2 rounded-lg border border-port-accent/30 bg-port-accent/5 p-2">
+ <div className="flex items-center gap-1.5 text-[11px] text-gray-400">
+ <Server size={12} className="text-port-accent" />
+ Rendered on {peerLabel(peer)} — {readiness?.label || 'checking'}
+ </div>
+ <label className="block">
+ <span className="block text-[11px] uppercase tracking-wider text-gray-500 mb-1">Remote {kind} model</span>
+ <select
+ aria-label={`Remote ${kind} model`}
+ value={modelKey}
+ onChange={(e) => setModelKey(e.target.value)}
+ disabled={disabled || models.length === 0}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm disabled:opacity-50"
+ >
+ {models.length === 0 ? (
+ <option value="">No allowlisted models discovered</option>
+ ) : models.map((entry) => (
+ <option key={federatedMediaModelKey(entry)} value={federatedMediaModelKey(entry)}>
+ {entry.modelName} — {entry.ready ? 'ready' : entry.unavailableReason || 'unavailable'}
+ </option>
+ ))}
+ </select>
+ </label>
+ {/* A usable target carries no remedy text, so falling through to the
+ generic sentence would print "not ready" beside a live button. */}
+ <p className="text-[11px] text-gray-400" role="status">
+ {blockedReason || queueSegments.join(' · ') || 'Peer is ready.'}
+ </p>
+ {localBlockedReason && (
+ <p className="text-[11px] text-port-warning" role="status">{localBlockedReason}</p>
+ )}
+ {children}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/federatedMedia/RemoteMediaTargetPicker.test.jsx b/client/src/components/federatedMedia/RemoteMediaTargetPicker.test.jsx
new file mode 100644
index 0000000000..6df7de338d
--- /dev/null
+++ b/client/src/components/federatedMedia/RemoteMediaTargetPicker.test.jsx
@@ -0,0 +1,188 @@
+/**
+ * The picker and `useFederatedMediaTarget` are tested together: the component is
+ * deliberately stateless, so testing it against a hand-built `target` object
+ * would only assert that the fixture renders — the interesting behaviour is the
+ * hook's verdict reaching the caption, the dropdown suffix, and the submission
+ * fields at the same time.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+
+const getInstances = vi.fn();
+vi.mock('../../services/api', () => ({ getInstances: (...args) => getInstances(...args) }));
+
+const { useFederatedMediaTarget } = await import('../../hooks/useFederatedMediaTarget.js');
+const { default: RemoteMediaTargetPicker } = await import('./RemoteMediaTargetPicker.jsx');
+
+const CAPABILITY = {
+ kind: 'image',
+ engine: 'local',
+ engineName: 'Local diffusers',
+ modelId: 'flux2-klein',
+ modelName: 'FLUX.2 Klein',
+ ready: true,
+ unavailableReason: null,
+ runtimeReady: true,
+ platformSupported: true,
+ cudaRequired: false,
+ cudaState: 'available',
+};
+
+const peer = ({
+ allowlist = [{ engine: 'local', modelId: 'flux2-klein' }],
+ capabilities = [CAPABILITY],
+ freshForMs = 60_000,
+ state = 'ready',
+ queue = { accepting: true, running: 0, queued: 0, totalActive: 1, maxQueuedJobs: 4 },
+ ...overrides
+} = {}) => ({
+ id: 'peer-example',
+ name: 'Example GPU',
+ status: 'online',
+ enabled: true,
+ mediaProvider: { enabled: true, imageModels: allowlist },
+ mediaProviderStatus: {
+ state,
+ checkedAt: new Date().toISOString(),
+ freshUntil: new Date(Date.now() + freshForMs).toISOString(),
+ snapshot: { queue, capabilities },
+ },
+ ...overrides,
+});
+
+// A host that surfaces what the hook resolved, so a test can assert the exact
+// body a generate route would receive without driving a whole page.
+function Harness({ localBlockedReason = null, onTarget }) {
+ const target = useFederatedMediaTarget('image');
+ onTarget?.(target);
+ return (
+ <div>
+ <RemoteMediaTargetPicker target={target} kind="image" localBlockedReason={localBlockedReason} />
+ <span data-testid="submission">{JSON.stringify(target.submissionFields)}</span>
+ <span data-testid="can-submit">{String(target.canSubmit)}</span>
+ </div>
+ );
+}
+
+const selectPeer = async (id = 'peer-example') => {
+ fireEvent.change(await screen.findByRole('combobox', { name: /generation target/i }), { target: { value: id } });
+};
+
+describe('RemoteMediaTargetPicker', () => {
+ beforeEach(() => {
+ getInstances.mockReset();
+ vi.restoreAllMocks();
+ });
+
+ it('renders nothing until a peer is opted in as a media provider', async () => {
+ getInstances.mockResolvedValue({
+ peers: [{ id: 'peer-example', name: 'Example GPU', status: 'online', mediaProvider: { enabled: false } }],
+ });
+ render(<Harness />);
+ await waitFor(() => expect(getInstances).toHaveBeenCalled());
+ expect(screen.queryByRole('combobox', { name: /generation target/i })).not.toBeInTheDocument();
+ });
+
+ // The allowlist and the advertised capabilities are two independent lists and
+ // the server admits only their intersection. Offering the union here would
+ // list a model `assertFederatedMediaProviderSelection` refuses.
+ it('offers only models present in BOTH the local allowlist and the peer’s capabilities', async () => {
+ getInstances.mockResolvedValue({
+ peers: [peer({
+ allowlist: [{ engine: 'local', modelId: 'flux2-klein' }],
+ capabilities: [
+ CAPABILITY,
+ { ...CAPABILITY, modelId: 'not-allowlisted', modelName: 'Some Other Model' },
+ ],
+ })],
+ });
+ render(<Harness />);
+ await selectPeer();
+
+ expect(screen.getByRole('option', { name: /FLUX\.2 Klein/ })).toBeInTheDocument();
+ expect(screen.queryByRole('option', { name: /Some Other Model/ })).not.toBeInTheDocument();
+ });
+
+ // Two empty-list causes with two different fixes: nothing allowlisted locally
+ // is a config gap on this machine, while an allowlist the peer answers with
+ // nothing means the model went away on its side.
+ it('separates “nothing allowlisted here” from “the peer is not advertising it”', async () => {
+ getInstances.mockResolvedValue({ peers: [peer({ allowlist: [] })] });
+ const { unmount } = render(<Harness />);
+ await selectPeer();
+ expect(screen.getByText(/no allowlisted image model/i)).toBeInTheDocument();
+ unmount();
+
+ getInstances.mockResolvedValue({ peers: [peer({ capabilities: [] })] });
+ render(<Harness />);
+ await selectPeer();
+ expect(screen.getByText(/not advertising any allowlisted image model/i)).toBeInTheDocument();
+ });
+
+ // A snapshot probed as `ready` keeps saying `ready` after its window closes.
+ // Trusting the stored state would leave Generate live against a peer the
+ // server is about to refuse.
+ it('blocks a peer whose capacity window has expired, in the caption and the dropdown', async () => {
+ getInstances.mockResolvedValue({ peers: [peer({ freshForMs: -60_000 })] });
+ render(<Harness />);
+ await selectPeer();
+
+ expect(screen.getByText(/capacity snapshot expired/i)).toBeInTheDocument();
+ expect(screen.getByRole('option', { name: /Example GPU \(stale\)/ })).toBeInTheDocument();
+ expect(screen.getByTestId('can-submit')).toHaveTextContent('false');
+ });
+
+ // The provider allowlist is keyed on the (engine, modelId) PAIR — a payload
+ // carrying the model id alone is refused, so the engine has to travel with it.
+ it('reports the peer, its engine and its model id as one submission unit', async () => {
+ getInstances.mockResolvedValue({ peers: [peer()] });
+ render(<Harness />);
+ await selectPeer();
+
+ expect(screen.getByTestId('can-submit')).toHaveTextContent('true');
+ expect(JSON.parse(screen.getByTestId('submission').textContent)).toEqual({
+ mediaProviderPeerId: 'peer-example',
+ mediaProviderEngine: 'local',
+ modelId: 'flux2-klein',
+ });
+ expect(screen.getByText(/1\/4 shared slots active/)).toBeInTheDocument();
+ });
+
+ // The host's veto and the peer's readiness answer different questions, and a
+ // form can be blocked by both — showing only one hides half the remedy.
+ it('shows the host’s own veto alongside the peer readiness line', async () => {
+ getInstances.mockResolvedValue({ peers: [peer()] });
+ render(<Harness localBlockedReason="clear the init image to render on this peer" />);
+ await selectPeer();
+
+ expect(screen.getByText(/1\/4 shared slots active/)).toBeInTheDocument();
+ expect(screen.getByText(/clear the init image/i)).toBeInTheDocument();
+ });
+
+ // A capacity window expires on the clock, not on a re-render, so the reading
+ // behind an enabled button can already be wrong by the time it is clicked.
+ it('re-derives at verify() time rather than trusting the last render', async () => {
+ getInstances.mockResolvedValue({ peers: [peer()] });
+ let target = null;
+ render(<Harness onTarget={(value) => { target = value; }} />);
+ await selectPeer();
+ expect(target.verify()).toEqual({ ok: true });
+
+ const realNow = Date.now();
+ vi.spyOn(Date, 'now').mockReturnValue(realNow + 120_000);
+ expect(target.verify()).toEqual({ ok: false, message: expect.stringMatching(/capacity snapshot expired/i) });
+ });
+
+ // A peer switched off inside its freshness window still carries `state:
+ // 'ready'`. The server rejects it with MEDIA_PROVIDER_PEER_DISABLED, so the
+ // form must not advertise it as available.
+ it('refuses a switched-off peer holding a fresh snapshot', async () => {
+ getInstances.mockResolvedValue({ peers: [peer({ enabled: false })] });
+ render(<Harness />);
+ await selectPeer();
+
+ expect(screen.getByTestId('can-submit')).toHaveTextContent('false');
+ expect(screen.getByText(/peer connection is switched off/i)).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/music/MusicGenPanel.jsx b/client/src/components/music/MusicGenPanel.jsx
index 739ec816b4..db8a3e7682 100644
--- a/client/src/components/music/MusicGenPanel.jsx
+++ b/client/src/components/music/MusicGenPanel.jsx
@@ -30,13 +30,11 @@ import toast from '../ui/Toast';
import { analyzeMusicLyrics } from '../../lib/musicDuration.js';
import { formatDurationSec } from '../../utils/formatters.js';
import {
- listMusicEngines, getInstances, generateMusic, installAudioModel, removeAudioModel, getActiveProcessing, getMediaJob, getTrack, cancelMediaJob,
+ listMusicEngines, generateMusic, installAudioModel, removeAudioModel, getActiveProcessing, getMediaJob, getTrack, cancelMediaJob,
} from '../../services/api';
import { formatDownloadGb } from '../../utils/formatters';
-import {
- resolvePeerMediaReadiness,
- summarizePeerMediaQueue,
-} from '../../lib/federatedMediaReadiness.js';
+import { useFederatedMediaTarget } from '../../hooks/useFederatedMediaTarget.js';
+import RemoteMediaTargetPicker from '../federatedMedia/RemoteMediaTargetPicker';
import RuntimeInstallModal from '../install/RuntimeInstallModal';
/**
@@ -114,22 +112,15 @@ const DEFAULT_REMOTE_PROFILE = Object.freeze({
const formatRemoteOption = (value) => value.replaceAll('-', ' ');
-function remoteModelsForPeer(peer) {
- const allowed = new Set((peer?.mediaProvider?.audioModels || [])
- .filter((model) => model?.engine && model?.modelId)
- .map((model) => `${model.engine}\u0000${model.modelId}`));
- return (peer?.mediaProviderStatus?.snapshot?.capabilities || [])
- .filter((model) => model?.kind === 'audio' && allowed.has(`${model.engine}\u0000${model.modelId}`));
-}
-
export default function MusicGenPanel({ track, title = '', artistId = '', artist = '', albumId = '', prompt, lyrics, onGenerated, remix }) {
const [engines, setEngines] = useState([]);
- const [peers, setPeers] = useState([]);
const [loading, setLoading] = useState(true);
const [engineId, setEngineId] = useState('');
const [modelId, setModelId] = useState('');
- const [mediaProviderPeerId, setMediaProviderPeerId] = useState('');
- const [remoteModelKey, setRemoteModelKey] = useState('');
+ // Peer list, per-kind allowlist intersection, readiness verdict and the
+ // submit-time re-check all live in the shared hook (#4348), so this panel,
+ // Image Gen and Video Gen cannot read the same peer three different ways.
+ const remoteTarget = useFederatedMediaTarget('audio');
const [remoteProfile, setRemoteProfile] = useState(() => ({ ...DEFAULT_REMOTE_PROFILE }));
const [durationSec, setDurationSec] = useState(null);
const [durationMode, setDurationMode] = useState('auto');
@@ -220,14 +211,6 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
useEffect(() => { loadEngines(); }, []);
- useEffect(() => {
- let canceled = false;
- getInstances({ silent: true }).then((data) => {
- if (!canceled && Array.isArray(data?.peers)) setPeers(data.peers);
- }).catch(() => {});
- return () => { canceled = true; };
- }, []);
-
useEffect(() => {
if (!isGenerating) return undefined;
const startedAt = activeJob?.startedAt ? Date.parse(activeJob.startedAt) : Date.now();
@@ -247,13 +230,9 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
// engine's default id. Use that effective option for readiness and generation
// too, so the first paint cannot briefly disable an otherwise ready engine.
const selectedModelId = selectedModel?.id || modelId;
- const selectedRemotePeer = useMemo(
- () => peers.find((peer) => peer.id === mediaProviderPeerId) || null,
- [mediaProviderPeerId, peers],
- );
- const remoteModels = useMemo(() => remoteModelsForPeer(selectedRemotePeer), [selectedRemotePeer]);
- const selectedRemoteModel = remoteModels.find((model) => `${model.engine}\u0000${model.modelId}` === remoteModelKey) || remoteModels[0] || null;
- const isRemote = Boolean(selectedRemotePeer);
+ const selectedRemotePeer = remoteTarget.peer;
+ const selectedRemoteModel = remoteTarget.model;
+ const isRemote = remoteTarget.isRemote;
const generationEngine = isRemote ? selectedRemoteModel : engine;
const selectedModelReady = !engine?.fixedModelInstall
? true
@@ -269,11 +248,6 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
}), [conditioningLyrics, generationEngine?.defaultDurationSec, generationEngine?.maxDurationSec]);
const usingAutoDuration = autoDurationAvailable && durationMode === 'auto';
- useEffect(() => {
- const next = remoteModels[0];
- setRemoteModelKey(next ? `${next.engine}\u0000${next.modelId}` : '');
- }, [selectedRemotePeer?.id, remoteModels]);
-
useEffect(() => {
if (!selectedRemoteModel) return;
setDurationSec((current) => current == null
@@ -322,19 +296,7 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
setDurationSec((d) => (d == null ? engine.defaultDurationSec : d));
}, [engine?.id, engine?.models]);
- // The same resolver the Instances card and System Health use, rather than the
- // `state` recorded on the stored probe: a snapshot written as `ready` keeps
- // saying so after its freshness window closes, and this is the surface where
- // the user actually commits a render to that peer. It gates the button as
- // well as the caption — a caption reading "stale" beside an enabled Generate
- // just moves the rejection to the server.
- const remoteReadiness = selectedRemotePeer ? resolvePeerMediaReadiness(selectedRemotePeer) : null;
- const remoteQueueSegments = remoteReadiness ? summarizePeerMediaQueue(remoteReadiness.queue) : [];
- const remoteReady = isRemote
- && remoteReadiness?.usable === true
- && remoteReadiness.queue?.accepting === true
- && selectedRemoteModel?.ready === true;
- const canGenerate = (isRemote ? remoteReady : !!engine?.ready && selectedModelReady)
+ const canGenerate = (isRemote ? remoteTarget.canSubmit : !!engine?.ready && selectedModelReady)
&& !!prompt?.trim() && !isGenerating;
const selectedModelSizeGb = engine?.modelSizeGbById?.[selectedModelId] ?? null;
const setup = isRemote ? null : engineSetupState(engine, selectedModelReady, selectedModelSizeGb);
@@ -403,11 +365,8 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
// now, and say so here instead of letting the server reject a submission the
// user just committed to.
if (isRemote) {
- const fresh = resolvePeerMediaReadiness(selectedRemotePeer);
- if (!fresh.usable) {
- toast.error(fresh.help || 'The selected peer is no longer reporting available capacity');
- return;
- }
+ const fresh = remoteTarget.verify();
+ if (!fresh.ok) { toast.error(fresh.message); return; }
}
setGenerating(true);
const body = {
@@ -509,70 +468,31 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
<Wand2 size={14} className="text-port-accent" /> Generate audio on-device
</div>
- <label className="block">
- <span className="block text-[11px] uppercase tracking-wider text-gray-500 mb-1">Generation target</span>
- <select
- aria-label="Generation target"
- value={mediaProviderPeerId}
- onChange={(e) => setMediaProviderPeerId(e.target.value)}
- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
- >
- <option value="">This instance</option>
- {peers.filter((peer) => peer.mediaProvider?.enabled === true).map((peer) => {
- // Same reading as the caption and the button below. The stored
- // `state` alone would leave a switched-off or lapsed peer listed
- // with no suffix — reading as ready — beside a caption explaining
- // why it is not.
- const readiness = resolvePeerMediaReadiness(peer);
- const suffix = readiness.usable ? '' : ` (${readiness.label})`;
- return <option key={peer.id} value={peer.id}>{peer.name || peer.address || 'Federated peer'}{suffix}</option>;
- })}
- </select>
- </label>
-
- {isRemote ? (
- <div className="space-y-2 rounded-lg border border-port-accent/30 bg-port-accent/5 p-2">
- <label className="block">
- <span className="block text-[11px] uppercase tracking-wider text-gray-500 mb-1">Remote audio model</span>
- <select
- aria-label="Remote audio model"
- value={selectedRemoteModel ? `${selectedRemoteModel.engine}\u0000${selectedRemoteModel.modelId}` : ''}
- onChange={(e) => setRemoteModelKey(e.target.value)}
- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
- >
- {remoteModels.length === 0 ? <option value="">No allowlisted models discovered</option> : remoteModels.map((model) => (
- <option key={`${model.engine}\u0000${model.modelId}`} value={`${model.engine}\u0000${model.modelId}`}>
- {model.modelName} — {model.ready ? 'ready' : model.unavailableReason || 'unavailable'}
- </option>
- ))}
- </select>
- </label>
- <p className="text-[11px] text-gray-400">
- {remoteReadiness?.usable
- // A usable peer carries no remedy text, so falling through would
- // print the not-ready sentence beside an enabled button.
- ? (remoteQueueSegments.join(' · ') || 'Peer is ready.')
- : remoteReadiness?.help
- || 'Remote generation requires a ready, authenticated peer with fresh capacity.'}
- </p>
- <div className="grid grid-cols-2 gap-2">
- {(['style', 'mood', 'tempo', 'energy']).map((field) => (
- <label key={field} className="block">
- <span className="block text-[11px] uppercase tracking-wider text-gray-500 mb-1">{field}</span>
- <select
- aria-label={`Remote ${field}`}
- value={remoteProfile[field]}
- onChange={(e) => setRemoteProfile((current) => ({ ...current, [field]: e.target.value }))}
- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
- >
- {REMOTE_AUDIO_OPTIONS[field].map((option) => <option key={option} value={option}>{formatRemoteOption(option)}</option>)}
- </select>
- </label>
- ))}
- </div>
- <p className="text-[10px] text-gray-500">Only this fixed musical profile crosses the peer boundary; your prompt and lyrics remain on this instance.</p>
+ <RemoteMediaTargetPicker target={remoteTarget} kind="audio">
+ {/* Audio's fixed-vocabulary conditioning profile — the only musical
+ direction allowed across the peer boundary (ADR
+ docs/decisions/2026-08-20-federated-visual-prompts.md). Rendered as
+ the picker's children so it sits inside the remote block without
+ the shared component knowing anything about audio. */}
+ <div className="grid grid-cols-2 gap-2">
+ {(['style', 'mood', 'tempo', 'energy']).map((field) => (
+ <label key={field} className="block">
+ <span className="block text-[11px] uppercase tracking-wider text-gray-500 mb-1">{field}</span>
+ <select
+ aria-label={`Remote ${field}`}
+ value={remoteProfile[field]}
+ onChange={(e) => setRemoteProfile((current) => ({ ...current, [field]: e.target.value }))}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
+ >
+ {REMOTE_AUDIO_OPTIONS[field].map((option) => <option key={option} value={option}>{formatRemoteOption(option)}</option>)}
+ </select>
+ </label>
+ ))}
</div>
- ) : (
+ <p className="text-[10px] text-gray-500">Only this fixed musical profile crosses the peer boundary; your prompt and lyrics remain on this instance.</p>
+ </RemoteMediaTargetPicker>
+
+ {!isRemote && (
<div className="grid grid-cols-2 gap-2">
<label className="block">
<span className="block text-[11px] uppercase tracking-wider text-gray-500 mb-1">Engine</span>
@@ -728,7 +648,7 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
type="button"
onClick={handleGenerate}
disabled={!canGenerate}
- title={!prompt?.trim() ? 'Add a generation prompt' : isRemote && !remoteReady ? 'Wait for the remote peer to report ready capacity' : !isRemote && !engine?.ready ? 'Complete engine setup first' : !isRemote && !selectedModelReady ? 'Install the selected model first' : track?.id ? 'Generate audio' : 'Generate and create a standalone track'}
+ title={!prompt?.trim() ? 'Add a generation prompt' : isRemote && !remoteTarget.canSubmit ? (remoteTarget.blockedReason || 'Wait for the remote peer to report ready capacity') : !isRemote && !engine?.ready ? 'Complete engine setup first' : !isRemote && !selectedModelReady ? 'Install the selected model first' : track?.id ? 'Generate audio' : 'Generate and create a standalone track'}
className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
>
{isGenerating ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}
diff --git a/client/src/components/music/MusicGenPanel.test.jsx b/client/src/components/music/MusicGenPanel.test.jsx
index e61d04c917..cdeb046fdc 100644
--- a/client/src/components/music/MusicGenPanel.test.jsx
+++ b/client/src/components/music/MusicGenPanel.test.jsx
@@ -327,7 +327,18 @@ describe('MusicGenPanel', () => {
state: 'ready',
checkedAt: new Date().toISOString(),
freshUntil: new Date(Date.now() + 60_000).toISOString(),
- snapshot: { queue, capabilities: [] },
+ // The peer has to be advertising the allowlisted model for this to be
+ // the USABLE branch at all: an allowlist the peer answers with nothing
+ // is its own blocked state, and it now says so here instead of printing
+ // a queue reading beside a disabled button.
+ snapshot: {
+ queue,
+ capabilities: [{
+ kind: 'audio', engine: 'minimax-music3', engineName: 'MiniMax Music 3', modelId: 'minimax-music3',
+ modelName: 'MiniMax Music 3', ready: true, autoDuration: false, lyrics: true,
+ minDurationSec: 10, maxDurationSec: 300, defaultDurationSec: 60,
+ }],
+ },
},
});
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 7d2452a3a7..5df4354a26 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -165,6 +165,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useCodeReviewDefaults` | Global Code Review Defaults (Review Loop reviewer chain + every per-reviewer `<reviewer>Model` / `<reviewer>Effort` pin scalar) via a small Provider/hook pair. | TaskAddForm, ScheduleTab, anywhere a default reviewer picker is shown. |
| `useCatalogTypes` | Catalog ingredient type registry (system + user-defined) merged with the static fallback via a Provider/hook pair; synchronous fallback to the built-in six so first render never blanks. | Catalog list/picker/editor; anywhere the catalog type list/lookup is needed. |
| `useDeathClock` | 1-second countdown for death-clock display. | Mortality / death-clock surfaces. |
+| `useFederatedMediaTarget` | 'Render here, or on a peer?' for one media kind (#4348): loads the opted-in provider peers, intersects the local per-kind allowlist with the peer’s advertised capabilities, and resolves one readiness verdict via `resolvePeerMediaReadiness`. Returns the selection state plus `submissionFields` (`mediaProviderPeerId`/`mediaProviderEngine`/`modelId`), a `blockedReason` carrying the remedy, and `verify()` which re-runs the same gates against the clock at submit time. Never polls — a capacity window expires on the clock, so only the submit-time check is trustworthy. | Any render form offering a federated target: `RemoteMediaTargetPicker` in Image Gen, Video Gen, Music Studio. |
| `useGoalDetail` | All state + handlers backing the GoalDetailPanel (edit form, todos, milestones, plan/phases, check-ins, progress log, activity/calendar links). Loads activities + subcalendars on mount. | GoalDetailPanel composition shell; not intended for reuse outside the goals panel. |
| `usePostSession` | MeatSpace POST drill-run state, refresh snapshots, scoring, and idempotent test/training saves. | POST launcher and drill runners. |
| `useRecordMerge` | Duplicate Universe/Series merge flow: open → dry-run preview → resolve field conflicts → execute, with an `onMerged` refresh callback. Drives `<MergeModal>`. | Surfacing the merge-duplicates UI anywhere (Sharing → Duplicates, Universes page). Don't re-implement the preview/execute dance. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index d456fb6086..618734d74b 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -191,6 +191,7 @@ export * from './useOpenWorldPlayback.js';
export { default as useOpenWorldViewport } from './useOpenWorldViewport.js';
export * from './useOpenWorldViewport.js';
export * from './useDeathClock.js';
+export * from './useFederatedMediaTarget.js';
export * from './useGoalDetail.js';
export * from './usePostSession.js';
export * from './useRecordMerge.js';
diff --git a/client/src/hooks/useFederatedMediaTarget.js b/client/src/hooks/useFederatedMediaTarget.js
new file mode 100644
index 0000000000..1df8acc0e8
--- /dev/null
+++ b/client/src/hooks/useFederatedMediaTarget.js
@@ -0,0 +1,149 @@
+/**
+ * "Render here, or on a peer?" — one hook behind every interactive render form
+ * that can route a job to a federated media provider (#4348).
+ *
+ * Three surfaces now ask this question (Music Studio, Image Gen, Video Gen).
+ * Each one would otherwise have to fetch the peer list, intersect the local
+ * allowlist with the peer's advertised capabilities, and decide for itself what
+ * "ready" means — three chances to disagree with the server's own admission
+ * check. `resolvePeerMediaReadiness` already collapsed the readiness verdict;
+ * this collapses the selection state that feeds it.
+ *
+ * Deliberately does not poll. A capacity window expires on the clock, not on a
+ * state change, so no poll interval makes the button's reading trustworthy at
+ * the instant of a click — `verify()` re-derives against the clock at submit
+ * time instead, which is the only moment that matters. The server re-probes and
+ * fail-closes after that regardless.
+ */
+
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { getInstances } from '../services/api';
+import {
+ federatedMediaModelKey,
+ federatedMediaModelsForPeer,
+ peerMediaProviderConfig,
+ resolvePeerMediaReadiness,
+ summarizePeerMediaQueue,
+} from '../lib/federatedMediaReadiness.js';
+
+// Stable identities so a form that memoizes on these doesn't re-run on every
+// render while nothing is selected (the common case).
+const NO_PEERS = Object.freeze([]);
+const NO_SEGMENTS = Object.freeze([]);
+
+const QUEUE_CLOSED = 'The peer’s shared media queue is not accepting new work right now.';
+
+/**
+ * Why this target cannot take the job, or `null` when it can.
+ *
+ * Mirrors the order `assertFederatedMediaProviderSelection` rejects in, so a
+ * form never advertises a target the server is about to refuse. Every branch
+ * returns the remedy rather than a bare "not ready".
+ *
+ * Takes `now` so the submit-time check and the rendered caption run the same
+ * gates: the only difference between them is which clock reading they use.
+ */
+function blockingReason({ peer, models, model, kind, now }) {
+ if (!peer) return null;
+ const readiness = resolvePeerMediaReadiness(peer, { now });
+ if (!readiness.usable) {
+ return readiness.help || 'The selected peer is no longer reporting available capacity.';
+ }
+ if (models.length === 0) {
+ // Two different failures, two different remedies: nothing allowlisted here
+ // is a local config gap, while an allowlist the peer answers none of means
+ // the model was removed or renamed on its side.
+ return (peerMediaProviderConfig(peer).models[kind]?.length ?? 0) === 0
+ ? `This peer has no allowlisted ${kind} model. Add one on its card under Instances.`
+ : `The peer is not advertising any allowlisted ${kind} model right now.`;
+ }
+ if (readiness.queue?.accepting !== true) return QUEUE_CLOSED;
+ if (model?.ready !== true) {
+ return model?.unavailableReason || `The selected ${kind} model is not ready on that peer.`;
+ }
+ return null;
+}
+
+/**
+ * @param {'audio'|'image'|'video'} kind
+ * @returns {{
+ * peers: object[], peer: object|null, peerId: string, setPeerId: (id: string) => void,
+ * models: object[], model: object|null, modelKey: string, setModelKey: (key: string) => void,
+ * isRemote: boolean, readiness: object|null, queueSegments: string[],
+ * canSubmit: boolean, blockedReason: string|null,
+ * submissionFields: object|null, verify: () => {ok: boolean, message?: string},
+ * }}
+ */
+export function useFederatedMediaTarget(kind) {
+ const [allPeers, setAllPeers] = useState(NO_PEERS);
+ const [peerId, setPeerId] = useState('');
+ const [modelKey, setModelKey] = useState('');
+
+ useEffect(() => {
+ getInstances({ silent: true })
+ .then((data) => { if (Array.isArray(data?.peers)) setAllPeers(data.peers); })
+ .catch(() => {});
+ }, []);
+
+ // Opting a peer in is a local config fact that survives a failed probe, so
+ // the list is filtered on that alone. A peer whose capacity has gone stale
+ // stays listed (carrying its own suffix) rather than vanishing from the
+ // dropdown with no explanation of where it went.
+ const peers = useMemo(
+ () => allPeers.filter((candidate) => candidate?.mediaProvider?.enabled === true),
+ [allPeers],
+ );
+ const peer = useMemo(() => peers.find((candidate) => candidate.id === peerId) || null, [peers, peerId]);
+ const models = useMemo(() => federatedMediaModelsForPeer(peer, kind), [peer, kind]);
+ // Fall back to the first option for the same reason a native <select> does:
+ // that is what the closed dropdown is displaying while `modelKey` is empty or
+ // still points at the previous peer's list.
+ const model = models.find((entry) => federatedMediaModelKey(entry) === modelKey) || models[0] || null;
+
+ useEffect(() => {
+ const next = models[0];
+ setModelKey(next ? federatedMediaModelKey(next) : '');
+ }, [peer?.id, models]);
+
+ const readiness = useMemo(() => (peer ? resolvePeerMediaReadiness(peer) : null), [peer]);
+ const queueSegments = useMemo(
+ () => (readiness ? summarizePeerMediaQueue(readiness.queue) : NO_SEGMENTS),
+ [readiness],
+ );
+ const blockedReason = useMemo(
+ () => blockingReason({ peer, models, model, kind, now: Date.now() }),
+ [peer, models, model, kind],
+ );
+
+ // The three fields the generate routes read. Built here so a page cannot ship
+ // a peer id without the engine that pairs with it — the provider allowlist is
+ // keyed on the (engine, modelId) pair, not on the model id alone.
+ const submissionFields = useMemo(() => (peer && model ? {
+ mediaProviderPeerId: peer.id,
+ mediaProviderEngine: model.engine,
+ modelId: model.modelId,
+ } : null), [peer, model]);
+
+ const verify = useCallback(() => {
+ const reason = blockingReason({ peer, models, model, kind, now: Date.now() });
+ return reason ? { ok: false, message: reason } : { ok: true };
+ }, [peer, models, model, kind]);
+
+ return {
+ peers,
+ peer,
+ peerId,
+ setPeerId,
+ models,
+ model,
+ modelKey,
+ setModelKey,
+ isRemote: Boolean(peer),
+ readiness,
+ queueSegments,
+ canSubmit: Boolean(peer) && blockedReason === null,
+ blockedReason,
+ submissionFields,
+ verify,
+ };
+}
diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.js
index dc50f0dfb7..130d865a77 100644
--- a/client/src/hooks/useVideoGenForm.js
+++ b/client/src/hooks/useVideoGenForm.js
@@ -56,8 +56,14 @@ const editableRemixModel = (models, defaultModelId) => {
* - `availableLoras` — the installed LoRA library, for name resolution.
* - `grokEnabled` — the Settings → Image Gen toggle that reveals the
* Local/Grok backend switch.
+ * - `remoteSubmissionFields` — `{ mediaProviderPeerId, mediaProviderEngine,
+ * modelId }` from `useFederatedMediaTarget` when the user picked a peer as
+ * the render target (#4348), else null. Present, it makes
+ * `buildGeneratePayload()` emit the text-to-video-only shape the federated
+ * wire accepts — kept here rather than in the page so there stays exactly
+ * one builder for what `server/routes/videoGen.js` validates.
*/
-export function useVideoGenForm({ models, status, availableLoras, grokEnabled }) {
+export function useVideoGenForm({ models, status, availableLoras, grokEnabled, remoteSubmissionFields = null }) {
const [searchParams, setSearchParams] = useSearchParams();
const incomingSourceImage = searchParams.get('sourceImageFile');
const incomingAudioFilename = searchParams.get('audioFilename');
@@ -1268,6 +1274,30 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })
sourceImage: mode === 'image' ? (sourceImageUpload || '') : '',
};
}
+ if (remoteSubmissionFields) {
+ // Text-to-video only: the wire carries no source/end frame, keyframes,
+ // source clip, audio track, IC references or LoRA weights, and the page
+ // blocks submission while any of those are set rather than dropping them
+ // here. `mode` and `backend` are pinned to the only combination the
+ // provider route accepts, so a stale mode cannot ride along and 400.
+ // The peer negotiates frames/fps/canvas against its own capability
+ // (negotiateVideoConstraints), so these go as requested, not pre-snapped
+ // to a LOCAL model this render never touches.
+ return {
+ backend: 'local',
+ mode: 'text',
+ prompt: composed.prompt,
+ negativePrompt: composed.negativePrompt,
+ width: clampImageEdge(width, VIDEO_EDGE_BOUNDS),
+ height: clampImageEdge(height, VIDEO_EDGE_BOUNDS),
+ numFrames,
+ fps,
+ steps: steps || '',
+ guidanceScale: guidanceScale || '',
+ seed: seed || '',
+ ...remoteSubmissionFields,
+ };
+ }
// Append "no music, no soundtrack" only when the toggle is on AND audio
// generation is itself active — there's no point steering audio output
// when audio is disabled outright. Idempotent: if the user already
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 8072469578..1e3d3c6d3f 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -44,7 +44,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `creativeDirectorPlan.js` | Pure presentation helpers for the CD studio Plan board (CDO Phase 4) — annotate `plan.steps[]` with tool cost-class/timing/approval flags, cost/status summaries, owning-surface deep links, status/cost badge tone maps. |
| `creativeDirectorPreview.js` | `selectProjectPreview(project)` → `{ kind: 'video'\|'image'\|'audio'\|'none', jobId?, src?, poster?, label, durationSec? }` — picks a CD project's representative produced asset (finalVideoId → last rendered scene → last done plan video/image step → `musicBed` audio → startingImageFile) for the list cards + Overview tab (#2702, audio #2772). Pure, computed off the already-returned project payload (no fetch). Plus `previewAspectClass(aspectRatio)` (literal Tailwind classes — a computed `aspect-[w/h]` never lands in the build), `startingImageSrc()` (client mirror of `localImageFilename`), and the `videoSrcForJob`/`videoPosterForJob`/`imageSrcForJob`/`musicBedSrc` path builders — the one client-side definition of the `<jobId>`-named asset convention, shared with `ScenePreview.jsx`. |
| `editorialRoadmap.js` | `projectAnalyzedPoints` (aggregate roadmap → analyzed chart points with arc-position `frac`) + `dominant` (most-frequent string). Shared by EditorialRoadmapPanel and the Reader Map page. |
-| `federatedMediaReadiness.js` | One reading of a peer’s federated media-provider readiness (#4348), shared by the Instances peer card and the System Health capacity panel so the two cannot disagree. `resolvePeerMediaReadiness(peer, { now })` maps the stored probe onto a display state/label/tone plus its remedy text, queue snapshot, capabilities, and per-kind allowlists; it re-derives `stale` when the snapshot’s `freshUntil` has passed, so a snapshot probed as `ready` cannot keep reading `ready` after the server would refuse to submit against it. Also exports `FEDERATED_MEDIA_KINDS` (audio/image/video + their config fields and icons), the state/help tables, and `peerMediaProviderConfig`. `summarizePeerMediaQueue(queue)` renders the peer’s queue block into finished display segments — slot occupancy, how many jobs drain in parallel, and which kinds are busy — so every surface shows the same words, dropping any segment an older provider did not send rather than showing it as a zero. Display only — the server re-probes and fail-closes before any job leaves. |
+| `federatedMediaReadiness.js` | One reading of a peer’s federated media-provider readiness (#4348), shared by the Instances peer card and the System Health capacity panel so the two cannot disagree. `resolvePeerMediaReadiness(peer, { now })` maps the stored probe onto a display state/label/tone plus its remedy text, queue snapshot, capabilities, and per-kind allowlists; it re-derives `stale` when the snapshot’s `freshUntil` has passed, so a snapshot probed as `ready` cannot keep reading `ready` after the server would refuse to submit against it. Also exports `FEDERATED_MEDIA_KINDS` (audio/image/video + their config fields and icons), the state/help tables, and `peerMediaProviderConfig`. `summarizePeerMediaQueue(queue)` renders the peer’s queue block into finished display segments — slot occupancy, how many jobs drain in parallel, and which kinds are busy — so every surface shows the same words, dropping any segment an older provider did not send rather than showing it as a zero. `federatedMediaModelsForPeer(peer, kind)` intersects the local per-kind allowlist with the peer’s advertised capabilities and returns the capability entries (with their `ready` / `unavailableReason`), so no surface can offer a model the server would refuse or hide why a listed one cannot run. Display only — the server re-probes and fail-closes before any job leaves. |
| `glbFailure.js` | Turns a 3D asset failure into an actionable sentence. `glbFailureHint(error)` matches the message against a shared table (an HTML body reaching the glTF parser, a WebGL context failure, a 404) and returns `null` when nothing recognizes it — so a caller can tell "we know the cause" from "we don't" and fall back to the raw text. `glbErrorText(error)` reads a message off whatever shape was thrown. Shared because the CoS avatars load remote GLBs too: every caught error there used to be reported as "this display has no WebGL", sending the user to change an unrelated setting (#4688). Consumed by `media/GlbViewer.jsx` and `cos/CoSCanvasGuard.jsx`. |
| `grokVideoClip.js` | Mirror of `server/lib/grokVideoClip.js` — `GROK_VIDEO_DURATIONS` (`[6, 10]`) + `GROK_VIDEO_DEFAULT_DURATION`, the clip lengths grok's `image_to_video` actually delivers. |
| `imageCleaners.js` | Mirror of `resolveCleanersFromConfig` from `server/lib/imageClean.js`. Reads `{cleanC2PA, denoise}` off a per-mode settings record. `cleanC2PA` defaults are mode-aware (on for `codex` + `external` — the backends that emit C2PA chunks today — off otherwise, as an allow-list rather than a deny-list); `denoise` defaults off everywhere (lossy, opt-in only). |
diff --git a/client/src/lib/federatedMediaReadiness.js b/client/src/lib/federatedMediaReadiness.js
index fd976ee5a9..c1e87ab677 100644
--- a/client/src/lib/federatedMediaReadiness.js
+++ b/client/src/lib/federatedMediaReadiness.js
@@ -236,3 +236,37 @@ export function resolvePeerMediaReadiness(peer, { now = Date.now() } = {}) {
kinds: FEDERATED_MEDIA_KINDS.filter(({ kind }) => config.models[kind].length > 0).map(({ kind }) => kind),
};
}
+
+/**
+ * The models of one kind a peer will actually accept work for right now.
+ *
+ * Two independent lists have to agree before a model is offerable, and each one
+ * alone is misleading: the LOCAL allowlist (`mediaProvider.<kind>Models`) is
+ * what this instance opted into and is exactly what
+ * `assertFederatedMediaProviderSelection` checks on submit, while the peer's
+ * advertised `capabilities` is the only thing carrying live readiness. Offering
+ * the union would list a model the server refuses; offering the allowlist alone
+ * would hide why a listed model can't run.
+ *
+ * Returns the advertised capability objects (not the config rows) so callers get
+ * `ready` / `unavailableReason` with each option, and the shared empty array
+ * when nothing qualifies — callers memoize on this result, and a fresh `[]` per
+ * render would defeat that memo for every peer with nothing to offer.
+ *
+ * @param {object} peer - a sanitized peer record from `GET /api/instances`
+ * @param {'audio'|'image'|'video'} kind
+ * @returns {object[]} capability entries, possibly empty
+ */
+export function federatedMediaModelsForPeer(peer, kind) {
+ if (!FEDERATED_MEDIA_KINDS.some((entry) => entry.kind === kind)) return NO_CAPABILITIES;
+ const { models } = peerMediaProviderConfig(peer);
+ const allowed = new Set(models[kind]
+ .filter((model) => model?.engine && model?.modelId)
+ .map(federatedMediaModelKey));
+ if (allowed.size === 0) return NO_CAPABILITIES;
+ const advertised = peer?.mediaProviderStatus?.snapshot?.capabilities;
+ if (!Array.isArray(advertised)) return NO_CAPABILITIES;
+ const matched = advertised.filter((capability) => capability?.kind === kind
+ && allowed.has(federatedMediaModelKey(capability)));
+ return matched.length > 0 ? matched : NO_CAPABILITIES;
+}
diff --git a/client/src/lib/federatedMediaReadiness.test.js b/client/src/lib/federatedMediaReadiness.test.js
index 3faebde456..81f347941a 100644
--- a/client/src/lib/federatedMediaReadiness.test.js
+++ b/client/src/lib/federatedMediaReadiness.test.js
@@ -3,6 +3,7 @@ import {
FEDERATED_MEDIA_KINDS,
FEDERATED_MEDIA_STATE_HELP,
federatedMediaModelKey,
+ federatedMediaModelsForPeer,
peerMediaProviderConfig,
resolvePeerMediaReadiness,
summarizePeerMediaQueue,
@@ -290,3 +291,50 @@ describe('summarizePeerMediaQueue', () => {
for (const bad of [null, undefined, 'busy']) expect(summarizePeerMediaQueue(bad)).toEqual([]);
});
});
+
+describe('federatedMediaModelsForPeer', () => {
+ const withCapabilities = (capabilities, allowlist) => peer({
+ mediaProvider: { enabled: true, audioModels: allowlist },
+ mediaProviderStatus: { checkedAt: iso(-1000), freshUntil: iso(60_000), state: 'ready', snapshot: { capabilities } },
+ });
+ const capability = (overrides) => ({
+ kind: 'audio', engine: 'minimax', engineName: 'MiniMax', modelId: 'music-3',
+ modelName: 'MiniMax Music 3', ready: true, unavailableReason: null, ...overrides,
+ });
+
+ // The allowlist is what the SERVER checks on submit; the capabilities are the
+ // only thing carrying readiness. Either list alone would offer a model that
+ // gets refused, or hide why a listed one cannot run.
+ it('returns only the models present in both the allowlist and the capabilities', () => {
+ const result = federatedMediaModelsForPeer(withCapabilities(
+ [capability(), capability({ modelId: 'other', modelName: 'Other' })],
+ [{ engine: 'minimax', modelId: 'music-3' }],
+ ), 'audio');
+ expect(result.map((entry) => entry.modelId)).toEqual(['music-3']);
+ });
+
+ // Same model id under a different engine is a different entry on the server's
+ // allowlist, so matching on the id alone would offer work the peer refuses.
+ it('keys the match on the engine/model PAIR, not the model id', () => {
+ const result = federatedMediaModelsForPeer(withCapabilities(
+ [capability({ engine: 'other-engine' })],
+ [{ engine: 'minimax', modelId: 'music-3' }],
+ ), 'audio');
+ expect(result).toEqual([]);
+ });
+
+ it('keeps an unadvertised kind, an unknown kind and a missing snapshot all empty', () => {
+ const allowed = [{ engine: 'minimax', modelId: 'music-3' }];
+ expect(federatedMediaModelsForPeer(withCapabilities([capability()], allowed), 'image')).toEqual([]);
+ expect(federatedMediaModelsForPeer(withCapabilities([capability()], allowed), 'hologram')).toEqual([]);
+ expect(federatedMediaModelsForPeer(withCapabilities(undefined, allowed), 'audio')).toEqual([]);
+ expect(federatedMediaModelsForPeer(null, 'audio')).toEqual([]);
+ });
+
+ // Callers memoize on this result; a fresh [] per call would defeat that memo
+ // for exactly the peers with nothing to recompute.
+ it('returns one shared array identity when there is nothing to offer', () => {
+ const empty = federatedMediaModelsForPeer(null, 'audio');
+ expect(federatedMediaModelsForPeer(withCapabilities([], []), 'audio')).toBe(empty);
+ });
+});
diff --git a/client/src/pages/ImageGen.federatedTarget.test.jsx b/client/src/pages/ImageGen.federatedTarget.test.jsx
new file mode 100644
index 0000000000..5ce526357a
--- /dev/null
+++ b/client/src/pages/ImageGen.federatedTarget.test.jsx
@@ -0,0 +1,150 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+
+const MODEL = { id: 'dev', name: 'FLUX.1 Dev', runner: 'mflux', steps: 20, guidance: 3.5 };
+
+// A peer opted in as an image provider, advertising one allowlisted model with a
+// verifiable freshness window — the shape `GET /api/instances` returns.
+const PEER = {
+ id: 'peer-example',
+ name: 'Example GPU',
+ status: 'online',
+ enabled: true,
+ mediaProvider: { enabled: true, imageModels: [{ engine: 'local', modelId: 'peer-flux' }] },
+ mediaProviderStatus: {
+ state: 'ready',
+ checkedAt: new Date().toISOString(),
+ freshUntil: new Date(Date.now() + 60_000).toISOString(),
+ snapshot: {
+ queue: { accepting: true, running: 0, queued: 0, totalActive: 0, maxQueuedJobs: 4 },
+ capabilities: [{
+ kind: 'image', engine: 'local', engineName: 'Local image', modelId: 'peer-flux',
+ modelName: 'FLUX.2 Klein', ready: true, unavailableReason: null,
+ runtimeReady: true, platformSupported: true, cudaRequired: false, cudaState: 'available',
+ }],
+ },
+ },
+};
+
+const state = vi.hoisted(() => ({ generateImage: vi.fn(), attachJobEvents: vi.fn() }));
+
+vi.mock('../services/api', () => ({
+ getInstances: vi.fn(async () => ({ peers: [PEER] })),
+ getImageGenStatus: vi.fn(async () => ({ connected: true, mode: 'local', model: 'FLUX.1 Dev' })),
+ generateImage: (...args) => state.generateImage(...args),
+ generateImageMultipart: vi.fn(async () => ({})),
+ listImageModels: vi.fn(async () => [MODEL]),
+ listLorasFull: vi.fn(async () => []),
+ listImageGallery: vi.fn(async () => []),
+ cancelImageGen: vi.fn(async () => ({})),
+ deleteImage: vi.fn(async () => ({})),
+ setImageHidden: vi.fn(async () => ({})),
+ cleanGalleryImage: vi.fn(async () => ({})),
+ getActiveImageJob: vi.fn(async () => ({ activeJob: null })),
+ getSettings: vi.fn(async () => ({ imageGen: { mode: 'local' } })),
+ buildFormData: vi.fn(() => new FormData()),
+ listMediaJobs: vi.fn(async () => ({ jobs: [] })),
+ regenerateGalleryImage: vi.fn(async () => ({})),
+ getRegenAvailability: vi.fn(async () => ({ available: false })),
+ removeImageWatermark: vi.fn(async () => ({})),
+ getFlux2Status: vi.fn(async () => ({ installed: true, ready: true })),
+}));
+
+vi.mock('../hooks/useImageGenProgress', () => ({
+ useImageGenProgress: () => ({ progress: null, begin: vi.fn(), end: vi.fn(), resume: vi.fn() }),
+}));
+vi.mock('../hooks/useMediaJobSse', () => ({
+ useMediaJobSse: () => ({ attach: (...a) => state.attachJobEvents(...a), eventSourceRef: { current: null } }),
+}));
+vi.mock('../hooks/useModelDownloadStatus', () => ({
+ useModelDownloadStatus: () => ({
+ getStatus: () => ({ cached: true }), start: vi.fn(), cancel: vi.fn(), repair: vi.fn(), refresh: vi.fn(),
+ downloading: false, repairing: false, progress: null, lastError: null, activeModelId: null, extra: {}, loading: false, statusError: null,
+ }),
+}));
+vi.mock('../hooks/useHfTokenStatus', () => ({ useHfTokenStatus: () => ({ present: true, refresh: vi.fn() }) }));
+vi.mock('../hooks/useAgyModels', () => ({ useAgyModels: () => ({ models: [], error: null }) }));
+vi.mock('../hooks/useMediaCompletionRefresh', () => ({ useMediaCompletionRefresh: vi.fn() }));
+vi.mock('../hooks/useMediaAnnotations', () => ({
+ useMediaAnnotations: () => ({ annotations: {}, updateAnnotation: vi.fn(), getCardProps: vi.fn(() => ({})) }),
+}));
+vi.mock('../hooks/useAutoRefetch', () => ({ useAutoRefetch: vi.fn() }));
+vi.mock('../hooks/usePreviewRoute', () => ({ default: () => [null, vi.fn()] }));
+vi.mock('../components/ui/Toast', () => ({
+ default: Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn(), loading: vi.fn() }),
+}));
+vi.mock('../components/media/PromptEnhancer', () => ({ default: () => null }));
+vi.mock('../components/media/PromptFromMedia', () => ({ default: () => null }));
+vi.mock('../components/media/StylePresetPicker', () => ({ default: () => null }));
+vi.mock('../components/media/MediaPreview', () => ({ default: () => null }));
+vi.mock('../components/media/MediaJobsQueue', () => ({ default: () => null }));
+vi.mock('../components/media/ResolutionField', () => ({ default: () => null }));
+vi.mock('../components/Drawer', () => ({ default: () => null }));
+vi.mock('../components/settings/ImageGenTab', () => ({ ImageGenTab: () => null }));
+vi.mock('../components/imageGen/Flux2InstallModal', () => ({ default: () => null }));
+vi.mock('../components/imageGen/GalleryImagePicker', () => ({ default: () => null }));
+vi.mock('../components/imageGen/InitImagePicker', () => ({ default: () => null }));
+vi.mock('../components/imageGen/ReferenceImagePicker', () => ({ default: () => null }));
+vi.mock('../components/imageGen/LoraPicker', () => ({ default: () => null }));
+
+const { default: ImageGen } = await import('./ImageGen.jsx');
+
+const mount = async (promptText = 'a lighthouse at dusk') => {
+ await act(async () => {
+ render(
+ <MemoryRouter initialEntries={['/media/image']}>
+ <ImageGen />
+ </MemoryRouter>,
+ );
+ });
+ fireEvent.change(await screen.findByLabelText('Prompt'), { target: { value: promptText } });
+};
+
+describe('ImageGen federated render target', () => {
+ beforeEach(() => {
+ state.generateImage.mockReset().mockResolvedValue({ jobId: 'job-1' });
+ state.attachJobEvents.mockReset().mockReturnValue(new Promise(() => {}));
+ });
+
+ // The whole point of the picker: a peer's model reaches the generate route as
+ // an explicit (peer, engine, model) selection, and nothing that only describes
+ // a LOCAL dispatch rides along with it.
+ it('submits the peer, its engine and its model — and no local-only fields', async () => {
+ await mount();
+ fireEvent.change(await screen.findByRole('combobox', { name: /generation target/i }), { target: { value: 'peer-example' } });
+
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /^Generate$/ })); });
+
+ await waitFor(() => expect(state.generateImage).toHaveBeenCalled());
+ expect(state.generateImage.mock.calls[0][0]).toMatchObject({
+ prompt: 'a lighthouse at dusk',
+ mediaProviderPeerId: 'peer-example',
+ mediaProviderEngine: 'local',
+ modelId: 'peer-flux',
+ });
+ // `mode` picks a local dispatcher lane, `quantize` and the cleaners describe
+ // work on this machine's bytes — none of them mean anything on a peer.
+ for (const field of ['mode', 'quantize', 'cleanC2PA', 'denoise', 'loraFilenames', 'cloudModel']) {
+ expect(state.generateImage.mock.calls[0][0]).not.toHaveProperty(field);
+ }
+ });
+
+ // A stale snapshot still records `state: 'ready'`; gating on it would leave
+ // Generate live against a peer the server is about to refuse.
+ it('disables Generate and explains why when the peer’s capacity window lapsed', async () => {
+ const { getInstances } = await import('../services/api');
+ getInstances.mockResolvedValueOnce({
+ peers: [{
+ ...PEER,
+ mediaProviderStatus: { ...PEER.mediaProviderStatus, freshUntil: new Date(Date.now() - 60_000).toISOString() },
+ }],
+ });
+ await mount();
+ fireEvent.change(await screen.findByRole('combobox', { name: /generation target/i }), { target: { value: 'peer-example' } });
+
+ expect(screen.getByText(/capacity snapshot expired/i)).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /^Generate$/ })).toBeDisabled();
+ expect(state.generateImage).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index cfe2460b3e..e9e37d7dd3 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -29,6 +29,7 @@ import InitImagePicker from '../components/imageGen/InitImagePicker';
import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';
import LoraPicker from '../components/imageGen/LoraPicker';
import ReferenceImagePicker from '../components/imageGen/ReferenceImagePicker';
+import RemoteMediaTargetPicker from '../components/federatedMedia/RemoteMediaTargetPicker';
import MediaJobsQueue from '../components/media/MediaJobsQueue';
import { FormField } from '../components/ui/FormField';
import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';
@@ -51,6 +52,7 @@ import { useMediaJobSse } from '../hooks/useMediaJobSse';
import { useModelDownloadStatus } from '../hooks/useModelDownloadStatus';
import { useHfTokenStatus } from '../hooks/useHfTokenStatus';
import { useAgyModels } from '../hooks/useAgyModels';
+import { useFederatedMediaTarget } from '../hooks/useFederatedMediaTarget';
import {
getImageGenStatus, generateImage, generateImageMultipart, listImageModels, listLorasFull, listImageGallery,
cancelImageGen, deleteImage, setImageHidden, cleanGalleryImage, getActiveImageJob, getSettings,
@@ -232,7 +234,12 @@ export default function ImageGen() {
const isCloudMode = isCloudCliMode(effectiveMode);
const cloudModeLabel = modeLabel(effectiveMode);
const isAgyMode = effectiveMode === IMAGE_GEN_MODE.AGY;
- const isAsyncMode = isLocalMode || isCloudMode;
+ // Federated render target (#4348). Selecting a peer supersedes the local
+ // backend entirely: the render never touches this machine’s mflux/cloud
+ // CLI, so every local readiness gate below is answered by the peer’s own
+ // capacity instead. Its job is queued locally as a proxy, hence the async lane.
+ const remoteTarget = useFederatedMediaTarget('image');
+ const isAsyncMode = isLocalMode || isCloudMode || remoteTarget.isRemote;
// Only probe `agy models` while Agy is the active backend — it spawns a
// child process server-side, so an unselected backend must not pay for it.
const agy = useAgyModels(isAgyMode);
@@ -670,6 +677,27 @@ export default function ImageGen() {
() => referenceImages.slice(referenceSlotCount).filter((s) => s.file != null).length,
[referenceImages, referenceSlotCount],
);
+ // What this form is holding that the federated wire cannot carry. The server
+ // refuses these outright (MEDIA_PROVIDER_INPUT_UNSUPPORTED) rather than
+ // dropping them, so the button says so up front instead of letting the user
+ // commit to a render that silently loses its source image. Nothing is cleared
+ // on selecting a peer — the pickers stay live so the user can empty them, and
+ // still has them intact after switching back to This instance.
+ const remoteUnsupportedInputs = useMemo(() => {
+ if (!remoteTarget.isRemote) return null;
+ const present = [
+ ['an init image', initImage.source != null],
+ ['reference images', populatedRefs.length > 0],
+ ['LoRA weights', selectedLoras.length > 0],
+ ].filter(([, set]) => set).map(([label]) => label);
+ return present.length
+ ? `A federated provider renders text-to-image only — clear ${present.join(' and ')} to render on this peer.`
+ : null;
+ }, [remoteTarget.isRemote, initImage.source, populatedRefs.length, selectedLoras.length]);
+ // One reading for the submit button and the picker caption alike.
+ const remoteBlocked = remoteTarget.isRemote
+ ? (remoteTarget.blockedReason || remoteUnsupportedInputs)
+ : null;
// Cloud text-to-image still needs a prompt — mirror the server rule
// (cloudPromptRequired: codex/grok can run image-only, agy always needs a
// Prompt) so the user sees a disabled button + hint instead of a failed job
@@ -782,7 +810,19 @@ export default function ImageGen() {
// payload hits imageEdgeSchema.
const w = clampImageEdge(width);
const h = clampImageEdge(height);
- const payload = isCloudMode ? {
+ // A federated render carries only what the wire schema accepts. Backend
+ // selectors (`mode`, `cloudModel`, `quantize`) and the cleaner toggles all
+ // describe work on THIS machine, so sending them would either be dropped
+ // server-side or, worse, read as a local dispatch.
+ const payload = remoteTarget.isRemote ? {
+ prompt: composed.prompt,
+ negativePrompt: composed.negativePrompt || undefined,
+ width: w, height: h,
+ steps: steps ? Number(steps) : undefined,
+ guidance: guidance ? Number(guidance) : undefined,
+ seed: seed && Number(seed) >= 0 ? Number(seed) : undefined,
+ ...remoteTarget.submissionFields,
+ } : isCloudMode ? {
prompt: composed.prompt,
negativePrompt: composed.negativePrompt || undefined,
width: w, height: h,
@@ -902,6 +942,15 @@ export default function ImageGen() {
// fires onSubmit — gate here too so an edit-only model without a source image
// (or codex text-to-image with no prompt) hits the inline hint, not a 400 toast.
if (editImageMissing || cloudNeedsPrompt) return;
+ // The button reading is as old as the last render and a capacity window
+ // expires on the clock, so an enabled button can already be pointing at a
+ // lapsed peer. Re-derive here and say so, rather than letting the server
+ // reject a render the user just committed to.
+ if (remoteTarget.isRemote) {
+ if (remoteUnsupportedInputs) { toast.error(remoteUnsupportedInputs); return; }
+ const fresh = remoteTarget.verify();
+ if (!fresh.ok) { toast.error(fresh.message); return; }
+ }
const batchN = isAsyncMode ? Math.max(1, batchCount) : 1;
if (generating) return queueAdditional(batchN);
// Snap the custom-dimension state to the server's per-edge bounds up front
@@ -1256,6 +1305,13 @@ export default function ImageGen() {
/>
)}
+ <RemoteMediaTargetPicker
+ target={remoteTarget}
+ kind="image"
+ disabled={statusLoading}
+ localBlockedReason={remoteUnsupportedInputs}
+ />
+
<ImageGenControls
mode={effectiveMode}
models={models}
@@ -1273,6 +1329,11 @@ export default function ImageGen() {
seed={seed} onSeedChange={setSeed}
showSeed
disabled={statusLoading}
+ // The peer advertises its own models and runs its own quantization;
+ // the local dropdowns would name neither. Resolution/steps/guidance/
+ // seed do cross the wire, so those stay.
+ showModel={!remoteTarget.isRemote}
+ showQuantize={!remoteTarget.isRemote}
modelStatus={isLocalMode ? modelDownload.getStatus(modelId) : null}
onModelDownload={isLocalMode ? modelDownload.start : undefined}
onModelDownloadCancel={modelDownload.cancel}
@@ -1347,8 +1408,10 @@ export default function ImageGen() {
<div className="flex items-center gap-2 pt-1 flex-wrap">
<button
type="submit"
- disabled={notConnected || editImageMissing || cloudNeedsPrompt}
- title={editImageMissing ? 'This image-edit model needs a source image — upload one below first' : cloudNeedsPrompt ? cloudPromptHint : undefined}
+ disabled={remoteTarget.isRemote
+ ? remoteBlocked !== null
+ : (notConnected || editImageMissing || cloudNeedsPrompt)}
+ title={remoteBlocked || (editImageMissing ? 'This image-edit model needs a source image — upload one below first' : cloudNeedsPrompt ? cloudPromptHint : undefined)}
className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg min-h-[40px]"
>
<Sparkles className="w-4 h-4" /> {generating ? 'Queue' : 'Generate'}
diff --git a/client/src/pages/VideoGen.composeWhileBusy.test.jsx b/client/src/pages/VideoGen.composeWhileBusy.test.jsx
index 9952f52792..cce9ff7334 100644
--- a/client/src/pages/VideoGen.composeWhileBusy.test.jsx
+++ b/client/src/pages/VideoGen.composeWhileBusy.test.jsx
@@ -41,6 +41,10 @@ vi.mock('../services/apiImageVideo.js', () => ({
}));
vi.mock('../services/api', () => ({
+ // The page offers a federated render target (#4348); with no peer opted in
+ // as a media provider the picker renders nothing and every local path below
+ // is unchanged.
+ getInstances: vi.fn(async () => ({ peers: [] })),
getVideoGenStatus: vi.fn(async () => ({
connected: true,
pythonPath: '/opt/example/python3',
diff --git a/client/src/pages/VideoGen.federatedTarget.test.jsx b/client/src/pages/VideoGen.federatedTarget.test.jsx
new file mode 100644
index 0000000000..1d75cc5193
--- /dev/null
+++ b/client/src/pages/VideoGen.federatedTarget.test.jsx
@@ -0,0 +1,237 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+
+const TERMS_ID = 'minimax-h3-license-v1';
+const MODEL = {
+ id: 'h3-one',
+ name: 'MiniMax h3-one',
+ repo: 'example-org/h3-one',
+ revision: '1111111111111111111111111111111111111111',
+ runtime: 'minimax_h3',
+ supportedModes: ['text'],
+ defaultFrames: 124,
+ frameOptions: [124, 141],
+ fpsOptions: [24],
+ steps: 8,
+ guidance: 0,
+ samplerLocked: true,
+ supportsNegativePrompt: false,
+ supportsTiling: false,
+ supportsDisableAudio: false,
+ termsGate: {
+ id: TERMS_ID,
+ title: 'Terms for h3-one',
+ summary: 'This model is available only in its applicable territory.',
+ acknowledgement: `I am eligible and accept ${TERMS_ID}.`,
+ licenseUrl: 'https://example.com/license',
+ },
+};
+
+// A peer opted in as a video provider, advertising one allowlisted model with a
+// verifiable freshness window — the shape `GET /api/instances` returns.
+const PEER = {
+ id: 'peer-example',
+ name: 'Example GPU',
+ status: 'online',
+ enabled: true,
+ mediaProvider: { enabled: true, videoModels: [{ engine: 'local', modelId: 'peer-wan' }] },
+ mediaProviderStatus: {
+ state: 'ready',
+ checkedAt: new Date().toISOString(),
+ freshUntil: new Date(Date.now() + 60_000).toISOString(),
+ snapshot: {
+ queue: { accepting: true, running: 0, queued: 0, totalActive: 0, maxQueuedJobs: 4 },
+ capabilities: [{
+ kind: 'video', engine: 'local', engineName: 'Local video', modelId: 'peer-wan',
+ modelName: 'Wan 2.2 T2V', ready: true, unavailableReason: null,
+ runtimeReady: true, platformSupported: true, cudaRequired: false, cudaState: 'available',
+ }],
+ },
+ },
+};
+
+const state = vi.hoisted(() => ({
+ generateVideo: vi.fn(),
+ attach: vi.fn(),
+ enqueue: vi.fn(),
+ eventSourceRef: { current: null },
+}));
+
+vi.mock('../services/apiImageVideo.js', () => ({
+ getVideoModelTerms: vi.fn(async () => ({ accepted: [TERMS_ID] })),
+ setVideoModelTerms: vi.fn(async () => ({ accepted: [TERMS_ID] })),
+}));
+
+vi.mock('../services/api', () => ({
+ getInstances: vi.fn(async () => ({ peers: [PEER] })),
+ getVideoGenStatus: vi.fn(async () => ({
+ connected: true,
+ pythonPath: '/opt/example/python3',
+ defaultModel: 'h3-one',
+ models: [MODEL],
+ byovRuntimes: [],
+ systemMemoryGb: 128,
+ backendDisclosures: [],
+ })),
+ generateVideo: (...args) => state.generateVideo(...args),
+ cancelVideoGen: vi.fn(async () => ({})),
+ listVideoHistory: vi.fn(async () => []),
+ deleteVideoHistoryItem: vi.fn(async () => ({})),
+ setVideoHidden: vi.fn(async () => ({})),
+ extractLastFrame: vi.fn(async () => ({})),
+ upscaleVideo: vi.fn(async () => ({})),
+ listImageGallery: vi.fn(async () => []),
+ patchSettingsSlice: vi.fn(async () => ({})),
+ getActiveVideoJob: vi.fn(async () => ({ activeJob: null })),
+ getSettings: vi.fn(async () => ({ imageGen: { grok: { enabled: false } } })),
+ getVideoGenRuntimeStatus: vi.fn(async () => ({ installed: true, ready: true, current: true })),
+ listLorasFull: vi.fn(async () => []),
+ getProviders: vi.fn(async () => ({ providers: [] })),
+ getVisionModels: vi.fn(async () => ({ models: [] })),
+}));
+
+vi.mock('../hooks/useModelDownloadStatus', () => ({
+ TEXT_ENCODER_DOWNLOAD_ID: '__text_encoder__',
+ useModelDownloadStatus: () => ({
+ extra: {},
+ loading: false,
+ statusError: null,
+ activeModelId: null,
+ progress: null,
+ lastError: null,
+ downloading: false,
+ repairing: false,
+ getStatus: () => ({ id: MODEL.id, repo: MODEL.repo, cached: true, sizeBytes: 100 }),
+ start: vi.fn(),
+ cancel: vi.fn(),
+ repair: vi.fn(),
+ refresh: vi.fn(),
+ }),
+}));
+
+vi.mock('../hooks/useMediaJobSse', () => ({
+ useMediaJobSse: () => ({ attach: state.attach, eventSourceRef: state.eventSourceRef }),
+}));
+vi.mock('../hooks/useMediaCompletionRefresh', () => ({ useMediaCompletionRefresh: vi.fn() }));
+vi.mock('../hooks/useMediaAnnotations', () => ({
+ useMediaAnnotations: () => ({ annotations: {}, updateAnnotation: vi.fn(), getCardProps: vi.fn(() => ({})) }),
+}));
+vi.mock('../hooks/usePreviewRoute', () => ({ default: () => [null, vi.fn()] }));
+vi.mock('../hooks/useVideoGenQueue.js', () => ({
+ useVideoGenQueue: () => ({
+ queue: [],
+ enqueue: state.enqueue,
+ removeFromQueue: vi.fn(),
+ clearFinishedQueue: vi.fn(),
+ cancelRunning: vi.fn(),
+ }),
+}));
+vi.mock('../components/ui/Toast', () => ({
+ default: Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn(), loading: vi.fn() }),
+}));
+
+vi.mock('../components/media/PromptEnhancer', () => ({
+ default: ({ disabled }) => (
+ <div data-testid="prompt-enhancer" data-disabled={disabled ? '1' : '0'}>Enhance with AI</div>
+ ),
+}));
+vi.mock('../components/media/PromptFromMedia', () => ({
+ default: ({ disabled }) => (
+ <div data-testid="prompt-from-media" data-disabled={disabled ? '1' : '0'}>Prompt from media</div>
+ ),
+}));
+
+vi.mock('../components/Drawer', () => ({ default: () => null }));
+vi.mock('../components/settings/ImageGenTab', () => ({ ImageGenTab: () => null }));
+vi.mock('../components/settings/LocalSetupPanel', () => ({ default: () => null }));
+vi.mock('../components/install/RuntimeInstallModal', () => ({ default: () => null }));
+vi.mock('../components/videoGen/FramePanel', () => ({ default: () => null }));
+vi.mock('../components/videoGen/KeyframePanel', () => ({ default: () => null }));
+vi.mock('../components/videoGen/AudioPanel', () => ({ default: () => null }));
+vi.mock('../components/videoGen/ExtendPanel', () => ({ default: () => null }));
+vi.mock('../components/videoGen/IcLoraPanel', () => ({ default: () => null }));
+vi.mock('../components/videoGen/AdvancedParamsPanel', () => ({ default: () => null }));
+vi.mock('../components/videoGen/RuntimeFingerprint', () => ({ default: () => null }));
+vi.mock('../components/videoGen/VideoGenGallery', () => ({ default: () => null }));
+vi.mock('../components/media/MediaPreview', () => ({ default: () => null }));
+vi.mock('../components/media/StylePresetPicker', () => ({ default: () => null }));
+vi.mock('../components/media/BatchQueuePanel', () => ({ default: () => null }));
+vi.mock('../components/media/MediaJobsQueue', () => ({ default: () => null }));
+vi.mock('../components/imageGen/LoraPicker', () => ({ default: () => null }));
+vi.mock('../components/media/ResolutionField', () => ({ default: () => null }));
+
+
+const { default: VideoGen } = await import('./VideoGen.jsx');
+
+const startRender = async (promptText = 'a fox watches the rain') => {
+ await act(async () => {
+ render(
+ <MemoryRouter initialEntries={['/media/video']}>
+ <VideoGen />
+ </MemoryRouter>,
+ );
+ });
+ fireEvent.change(await screen.findByLabelText('Prompt'), { target: { value: promptText } });
+};
+
+describe('VideoGen federated render target', () => {
+ beforeEach(() => {
+ state.generateVideo.mockReset().mockReturnValue(new Promise(() => {}));
+ state.attach.mockReset().mockReturnValue(new Promise(() => {}));
+ state.enqueue.mockReset();
+ state.eventSourceRef.current = null;
+ });
+
+ // The whole point of the picker: a peer's model reaches the generate route as
+ // an explicit (peer, engine, model) selection, and nothing that only describes
+ // a LOCAL dispatch rides along with it.
+ it('submits the peer, its engine and its model — and no local-only fields', async () => {
+ await startRender();
+ fireEvent.change(await screen.findByRole('combobox', { name: /generation target/i }), { target: { value: 'peer-example' } });
+ await waitFor(() => expect(screen.getByRole('button', { name: /^Generate$/ })).toBeEnabled());
+
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /^Generate$/ })); });
+
+ await waitFor(() => expect(state.generateVideo).toHaveBeenCalled());
+ const payload = state.generateVideo.mock.calls[0][0];
+ expect(payload).toMatchObject({
+ backend: 'local',
+ mode: 'text',
+ prompt: 'a fox watches the rain',
+ mediaProviderPeerId: 'peer-example',
+ mediaProviderEngine: 'local',
+ modelId: 'peer-wan',
+ });
+ // Every one of these means "run this on my hardware" and the provider route
+ // refuses a body carrying them.
+ for (const field of ['sourceImageFile', 'lastImageFile', 'keyframes', 'extendFromVideoId', 'audioFile', 'loraFilenames', 'textEncoderId', 'tiling', 'chunks']) {
+ expect(payload).not.toHaveProperty(field);
+ }
+ });
+
+ // The local model dropdown lists models the peer does not have. Leaving it
+ // visible would let a stale selection read as the model that rendered the clip.
+ it('replaces the local model dropdown with the peer’s advertised models', async () => {
+ await startRender();
+ expect(screen.getByRole('option', { name: /MiniMax h3-one/ })).toBeInTheDocument();
+
+ fireEvent.change(await screen.findByRole('combobox', { name: /generation target/i }), { target: { value: 'peer-example' } });
+
+ expect(screen.queryByRole('option', { name: /MiniMax h3-one/ })).not.toBeInTheDocument();
+ expect(screen.getByRole('option', { name: /Wan 2\.2 T2V/ })).toBeInTheDocument();
+ });
+ // The federated wire is text-to-video only, and the server refuses a body
+ // carrying conditioning rather than rendering something else — so the form
+ // has to say so before the user commits, not after.
+ it('blocks a non-text mode instead of dropping its conditioning', async () => {
+ await startRender();
+ fireEvent.change(await screen.findByRole('combobox', { name: /generation target/i }), { target: { value: 'peer-example' } });
+ await waitFor(() => expect(screen.getByRole('button', { name: /^Generate$/ })).toBeEnabled());
+
+ fireEvent.click(screen.getByRole('button', { name: /^Image$/ }));
+
+ expect(screen.getByText(/renders text-to-video only/i)).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /^Generate$/ })).toBeDisabled();
+ });
+});
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 4f3e1eb5b1..b000b0d698 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -80,6 +80,8 @@ import usePreviewRoute from '../hooks/usePreviewRoute';
import useMediaPreviewActions from '../hooks/useMediaPreviewActions';
import { useVideoGenQueue } from '../hooks/useVideoGenQueue.js';
import { useVideoGenForm } from '../hooks/useVideoGenForm.js';
+import { useFederatedMediaTarget } from '../hooks/useFederatedMediaTarget';
+import RemoteMediaTargetPicker from '../components/federatedMedia/RemoteMediaTargetPicker';
import {
getVideoGenStatus, generateVideo, cancelVideoGen,
listVideoHistory, deleteVideoHistoryItem, setVideoHidden,
@@ -140,6 +142,10 @@ export default function VideoGen() {
const [availableLoras, setAvailableLoras] = useState([]);
useEffect(() => { listLorasFull().then((l) => setAvailableLoras(Array.isArray(l) ? l : [])).catch(() => {}); }, []);
+ // Federated render target (#4348). Picking a peer replaces the local runtime
+ // outright — the clip is rendered there and imported back — so it feeds the
+ // payload builder rather than sitting beside it.
+ const remoteTarget = useFederatedMediaTarget('video');
// Every field the form submits, plus the payload builder both submit paths
// share. See client/src/hooks/useVideoGenForm.js.
const {
@@ -171,7 +177,39 @@ export default function VideoGen() {
addIcReferenceImage, updateIcReferenceImage, removeIcReferenceImage,
icStrength, setIcStrength, icSkipStage2, setIcSkipStage2,
applyRemix, applyFinish, applyResumedParams, buildGeneratePayload,
- } = useVideoGenForm({ models, status, availableLoras, grokEnabled });
+ } = useVideoGenForm({
+ models, status, availableLoras, grokEnabled,
+ remoteSubmissionFields: remoteTarget.isRemote ? remoteTarget.submissionFields : null,
+ });
+ // Conditioning the federated wire cannot carry. The server refuses a job
+ // holding any of it (MEDIA_PROVIDER_INPUT_UNSUPPORTED) rather than silently
+ // rendering something else, so the form says so before the user commits.
+ // Nothing is cleared on picking a peer: the inputs stay filled and intact
+ // for a switch back to This instance.
+ const remoteUnsupportedInputs = useMemo(() => {
+ if (!remoteTarget.isRemote) return null;
+ const present = [
+ ['the Grok backend', isGrok],
+ [`${mode} mode`, mode !== 'text'],
+ ['a source image', !!sourceImageFile || !!sourceImageUpload],
+ ['an end frame', !!lastImageFile || !!lastImageUpload],
+ ['keyframes', keyframesActive],
+ ['a source clip to extend', !!extendFromVideoId],
+ ['an audio track', !!audioFile],
+ ['IC-LoRA references', !!icReferenceFile || !!icReferenceVideoId || icReferenceImageFiles.length > 0],
+ ['LoRA weights', selectedLoras.length > 0],
+ ['chained chunks', chunks > 1],
+ ].filter(([, set]) => set).map(([label]) => label);
+ return present.length
+ ? `A federated provider renders text-to-video only — clear ${present.join(', ')} to render on this peer.`
+ : null;
+ }, [remoteTarget.isRemote, isGrok, mode, sourceImageFile, sourceImageUpload, lastImageFile,
+ lastImageUpload, keyframesActive, extendFromVideoId, audioFile, icReferenceFile,
+ icReferenceVideoId, icReferenceImageFiles, selectedLoras, chunks]);
+ // One reading for the Generate button, the enqueue guard and the caption.
+ const remoteBlocked = remoteTarget.isRemote
+ ? (remoteTarget.blockedReason || remoteUnsupportedInputs)
+ : null;
const localResolutionOptions = resolutionOptionsForModel(currentModel);
const localResolutionBounds = videoEdgeBoundsForModel(currentModel);
@@ -664,7 +702,14 @@ export default function VideoGen() {
if (canEnqueue) handleEnqueue();
return;
}
- if (!prompt.trim() || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || weightsGateBlocked || keyframesBlocked))) return;
+ if (!canEnqueue) return;
+ // A capacity window expires on the clock, so an enabled button can already
+ // be pointing at a lapsed peer — re-derive at the moment of commit and say
+ // so, rather than letting the peer reject a render already paid for.
+ if (remoteTarget.isRemote) {
+ const fresh = remoteTarget.verify();
+ if (!fresh.ok) { toast.error(fresh.message); return; }
+ }
await runGeneration(buildGeneratePayload()).catch(() => {});
};
@@ -673,7 +718,7 @@ export default function VideoGen() {
// would silently queue a doomed job that fails late in the worker with
// VENV_MISSING, hiding the installer banner from the user. Block at
// enqueue time so the only path forward is the install banner above.
- if (!prompt.trim() || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || weightsGateBlocked || keyframesBlocked))) return;
+ if (!canEnqueue) return;
// useVideoGenQueue strips the File blobs into `_blobs` and snapshots the
// rest as a stable summary for the queue UI.
enqueue(buildGeneratePayload());
@@ -716,9 +761,14 @@ export default function VideoGen() {
// configured" error from the unrelated legacy probe.
const notConnected = !!status && status.connected === false && !needsByovProbe;
- const canEnqueue = prompt.trim() && (isGrok || (!notConnected && !extendModeBlocked
- && !a2vModeBlocked && !icLoraModeBlocked && !byovGateBlocked
- && !weightsGateBlocked && !keyframesBlocked));
+ // A federated render answers to the PEER’s readiness, not to this machine’s
+ // runtime gates — none of the local probes below describe the hardware it
+ // will actually run on.
+ const canEnqueue = prompt.trim() && (remoteTarget.isRemote
+ ? remoteBlocked === null
+ : (isGrok || (!notConnected && !extendModeBlocked
+ && !a2vModeBlocked && !icLoraModeBlocked && !byovGateBlocked
+ && !weightsGateBlocked && !keyframesBlocked)));
return (
<div className="space-y-3">
@@ -1072,6 +1122,12 @@ export default function VideoGen() {
/>
)}
+ <RemoteMediaTargetPicker
+ target={remoteTarget}
+ kind="video"
+ localBlockedReason={remoteUnsupportedInputs}
+ />
+
{isGrok ? (
<div className="grid grid-cols-2 gap-3">
<FormField label="Clip length" labelClassName="block text-xs font-medium text-gray-400 mb-1">
@@ -1099,7 +1155,10 @@ export default function VideoGen() {
</div>
) : (
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
- {models.length > 0 && (
+ {/* The peer advertises its own models; the local list would name
+ none of them, and a stale selection here must not read as the
+ model that rendered the clip. */}
+ {models.length > 0 && !remoteTarget.isRemote && (
<FormField className="col-span-2 sm:col-span-3" label="Model" labelClassName="block text-xs font-medium text-gray-400 mb-1">
<ModelSelect
models={visibleModels}
@@ -1276,10 +1335,13 @@ export default function VideoGen() {
) : (
<button
type="submit"
- disabled={!prompt.trim() || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || weightsGateBlocked || keyframesBlocked))}
+ disabled={!canEnqueue}
className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg min-h-[40px]"
title={
- byovRuntimeMissing ? `${byovStatus?.label || byovRuntime} runtime is not installed — use the install banner above`
+ // A federated render is gated on the peer, so none of the
+ // local runtime remedies below apply to it.
+ remoteBlocked ? remoteBlocked
+ : byovRuntimeMissing ? `${byovStatus?.label || byovRuntime} runtime is not installed — use the install banner above`
: byovGateBlocked ? `Checking ${byovRuntime} runtime status…`
: modelWeightsBlocked ? 'Download the selected model weights before generating'
: textEncoderWeightsBlocked ? 'Download the shared text encoder before generating'
diff --git a/client/src/pages/VideoGen.terms.test.jsx b/client/src/pages/VideoGen.terms.test.jsx
index 93d793be69..4d276e10b6 100644
--- a/client/src/pages/VideoGen.terms.test.jsx
+++ b/client/src/pages/VideoGen.terms.test.jsx
@@ -54,6 +54,10 @@ vi.mock('../services/apiImageVideo.js', () => ({
}));
vi.mock('../services/api', () => ({
+ // The page offers a federated render target (#4348); with no peer opted in
+ // as a media provider the picker renders nothing and every local path below
+ // is unchanged.
+ getInstances: vi.fn(async () => ({ peers: [] })),
getVideoGenStatus: vi.fn(async () => ({
connected: true,
pythonPath: '/opt/example/python3',
diff --git a/client/src/pages/VideoGen.textEncoderAutoDownload.test.jsx b/client/src/pages/VideoGen.textEncoderAutoDownload.test.jsx
index f4dd6ae2f2..01215dfaa0 100644
--- a/client/src/pages/VideoGen.textEncoderAutoDownload.test.jsx
+++ b/client/src/pages/VideoGen.textEncoderAutoDownload.test.jsx
@@ -61,6 +61,10 @@ vi.mock('../services/apiImageVideo.js', () => ({
}));
vi.mock('../services/api', () => ({
+ // The page offers a federated render target (#4348); with no peer opted in
+ // as a media provider the picker renders nothing and every local path below
+ // is unchanged.
+ getInstances: vi.fn(async () => ({ peers: [] })),
getVideoGenStatus: vi.fn(async () => ({
connected: true,
pythonPath: '/opt/example/python3',
diff --git a/docs/FEDERATED_MEDIA_PROVIDERS.md b/docs/FEDERATED_MEDIA_PROVIDERS.md
index 2eee3392c2..83ba9522cd 100644
--- a/docs/FEDERATED_MEDIA_PROVIDERS.md
+++ b/docs/FEDERATED_MEDIA_PROVIDERS.md
@@ -127,6 +127,37 @@ federation" rule, what stays absolutely prompt-free, and what a future standing
(unattended) route may not do are all decided in ADR
[federated visual prompts](./decisions/2026-08-20-federated-visual-prompts.md).
+### Picking a target in the UI
+
+Image Gen, Video Gen and the Music Studio panel all carry the same
+**Generation target** dropdown — `This instance` plus every peer switched on
+as a media provider. Picking a peer swaps the local model dropdown for the
+peer's advertised models and replaces the local runtime gates with the peer's
+own readiness.
+
+One resolver answers "is this peer usable right now?" for all three surfaces
+(`client/src/hooks/useFederatedMediaTarget.js` over
+`client/src/lib/federatedMediaReadiness.js`), applying the same gates, in the
+same order, that `assertFederatedMediaProviderSelection` applies server-side.
+Two consequences worth knowing:
+
+- **Only the intersection is offered.** A model has to be on this machine’s
+ per-kind allowlist *and* advertised by the peer. An allowlisted model the
+ peer stops advertising, and a model the peer offers that was never
+ allowlisted here, are both un-pickable — with different remedies said out
+ loud, since the fixes are on different machines.
+- **The verdict is re-derived at submit time.** A capacity window expires on
+ the clock, not on a state change, so the reading behind an enabled Generate
+ can already be stale by the time it is clicked. The click re-runs the gates
+ and refuses locally rather than letting the peer reject work the user
+ already committed to.
+
+Because wire v1 is text-to-image / text-to-video only, a form holding an init
+image, reference images, keyframes, a clip to extend, IC-LoRA references, LoRA
+weights, chained chunks, or a non-`text` mode blocks Generate and names what
+has to be cleared. Nothing is cleared for you: the inputs stay filled, so
+switching the target back to `This instance` renders exactly what was set up.
+
### Video frame and canvas constraint negotiation
Providers advertise their model geometry and frame constraints in their capability status:
@@ -400,4 +431,4 @@ A remote job's conditioning prompt is persisted **only inside its versioned `rem
## Current boundary
-Wire v1 carries instrumental audio, text-to-image, and text-to-video. Interactive remote selection is exposed through the Music Studio panel and the generation APIs rather than a peer picker on the Image Gen / Video Gen pages; unattended work routes through **Instances → Unattended render routing**. Still remaining from #4348: those Image Gen / Video Gen pickers, a privacy-preserving design for remote lyrical conditioning (which is also what keeps unattended audio local), input-asset transfer (init/reference images, LoRAs, chained renders), and multi-provider fairness/failover.
+Wire v1 carries instrumental audio, text-to-image, and text-to-video. Interactive remote selection is exposed on the Image Gen, Video Gen and Music Studio surfaces; unattended work routes through **Instances → Unattended render routing**. Still remaining from #4348: a privacy-preserving design for remote lyrical conditioning (which is also what keeps unattended audio local), input-asset transfer (init/reference images, LoRAs, chained renders), and multi-provider fairness/failover.