Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-4348]): route unattended renders to a configured federated peer
[._.]/ Adam Eivy0227484fb01d
diff --git a/client/src/components/instances/PeerMediaProviderPanel.jsx b/client/src/components/instances/PeerMediaProviderPanel.jsxindex 624a21cc76..a38735fd9d 100644--- a/client/src/components/instances/PeerMediaProviderPanel.jsx+++ b/client/src/components/instances/PeerMediaProviderPanel.jsx@@ -1,8 +1,19 @@import { useMemo, useState } from 'react';-import { Check, ChevronDown, ChevronRight, Gauge, Music2 } from 'lucide-react';+import { Check, ChevronDown, ChevronRight, Film, Gauge, Image, Music2 } from 'lucide-react';import { probePeer, updatePeer } from '../../services/api';import Pill from '../ui/Pill';+// Wire v1 shipped audio-only, then grew image and video (#4348). The panel is+// driven off this table rather than one hardcoded lane so a peer that shares a+// GPU for renders is configurable at all — before this, image/video models were+// accepted by the server but had no surface to allowlist them from, which left+// federated renders unreachable from the UI.+const KINDS = Object.freeze([+ { kind: 'audio', label: 'audio', field: 'audioModels', Icon: Music2 },+ { kind: 'image', label: 'image', field: 'imageModels', Icon: Image },+ { kind: 'video', label: 'video', field: 'videoModels', Icon: Film },+]);+const STATE_META = {ready: { label: 'ready', tone: 'success' },busy: { label: 'busy', tone: 'warning' },@@ -27,37 +38,41 @@ const STATE_HELP = {};const isRecord = (value) => value && typeof value === 'object' && !Array.isArray(value);+// NUL separator, matching the server's own model key: a printable separator+// would let an engine name containing it collide with a different pair.const keyOf = ({ engine, modelId }) => `${engine}\u0000${modelId}`;+const listOf = (raw, field) => (Array.isArray(raw?.[field]) ? raw[field] : []);function configOf(peer) {const raw = isRecord(peer?.mediaProvider) ? peer.mediaProvider : {};- return {- raw,- enabled: raw.enabled === true,- audioModels: Array.isArray(raw.audioModels) ? raw.audioModels : [],- };+ const models = {};+ for (const { kind, field } of KINDS) models[kind] = listOf(raw, field);+ return { raw, enabled: raw.enabled === true, models };}-function modelRows(config, status) {+// A peer only advertises the kinds this instance asked for, and it only asks+// for kinds that already have an allowlisted model — so an already-selected+// model the peer has stopped advertising still has to appear, or the user could+// never uncheck it. Those rows render as `not-advertised`.+function modelRows(selected, status, kind) {const rows = new Map();for (const capability of status?.snapshot?.capabilities || []) {- if (capability?.kind !== 'audio' || !capability.engine || !capability.modelId) continue;+ if (capability?.kind !== kind || !capability.engine || !capability.modelId) continue;rows.set(keyOf(capability), capability);}- for (const selected of config.audioModels) {- if (!selected?.engine || !selected.modelId) continue;- const key = keyOf(selected);- if (!rows.has(key)) {- rows.set(key, {- kind: 'audio',- engine: selected.engine,- engineName: selected.engine,- modelId: selected.modelId,- modelName: selected.modelId,- ready: false,- unavailableReason: 'not-advertised',- });- }+ for (const model of selected) {+ if (!model?.engine || !model.modelId) continue;+ const key = keyOf(model);+ if (rows.has(key)) continue;+ rows.set(key, {+ kind,+ engine: model.engine,+ engineName: model.engine,+ modelId: model.modelId,+ modelName: model.modelId,+ ready: false,+ unavailableReason: 'not-advertised',+ });}return [...rows.values()];}@@ -67,10 +82,11 @@ export default function PeerMediaProviderPanel({ peer, onRefresh }) {const [saving, setSaving] = useState(false);const config = configOf(peer);const status = peer.mediaProviderStatus || null;- const rows = useMemo(() => modelRows(config, status), [config.raw, status]);- const selectedKeys = new Set(config.audioModels- .filter((model) => model?.engine && model.modelId)- .map(keyOf));+ const rowsByKind = useMemo(+ () => Object.fromEntries(KINDS.map(({ kind }) => [kind, modelRows(config.models[kind], status, kind)])),+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [config.raw, status],+ );const stateMeta = !config.enabled? { label: 'off', tone: 'note' }: peer.status !== 'online'@@ -78,26 +94,32 @@ export default function PeerMediaProviderPanel({ peer, onRefresh }) {: STATE_META[status?.state] || { label: 'checking', tone: 'muted' };const queue = status?.snapshot?.queue;- const saveConfig = async (next, { probe = false } = {}) => {+ // Carry every kind's list forward on each write. The server merges the+ // mediaProvider object, but a patch that omitted a list this panel never+ // rendered would only read as "unchanged" by luck — send the full shape.+ const saveConfig = async (patch, { probe = false } = {}) => {setSaving(true);+ const next = {+ ...config.raw,+ enabled: config.enabled,+ ...Object.fromEntries(KINDS.map(({ kind, field }) => [field, config.models[kind]])),+ ...patch,+ };const updated = await updatePeer(peer.id, { mediaProvider: next }).catch(() => null);if (updated && probe) await probePeer(peer.id).catch(() => null);if (updated) onRefresh();setSaving(false);};- const toggleEnabled = () => saveConfig(- { ...config.raw, enabled: !config.enabled, audioModels: config.audioModels },- { probe: !config.enabled },- );+ const toggleEnabled = () => saveConfig({ enabled: !config.enabled }, { probe: !config.enabled });- const toggleModel = (model) => {+ const toggleModel = (kind, field, model) => {const key = keyOf(model);- const selected = selectedKeys.has(key);- const audioModels = selected- ? config.audioModels.filter((candidate) => keyOf(candidate) !== key)- : [...config.audioModels, { engine: model.engine, modelId: model.modelId }];- return saveConfig({ ...config.raw, enabled: config.enabled, audioModels });+ const current = config.models[kind];+ const next = current.some((candidate) => keyOf(candidate) === key)+ ? current.filter((candidate) => keyOf(candidate) !== key)+ : [...current, { engine: model.engine, modelId: model.modelId }];+ return saveConfig({ [field]: next });};const safePeerId = String(peer.id || 'peer').replace(/[^A-Za-z0-9_-]/g, '-');@@ -133,7 +155,7 @@ export default function PeerMediaProviderPanel({ peer, onRefresh }) {className="mt-0.5 accent-port-accent"/><label htmlFor={enabledId} className="flex-1 text-gray-300 cursor-pointer">- Use this peer for remote audio+ Use this peer for remote media<span className="block text-[10px] text-gray-600 mt-0.5">Opt-in only. The server also requires an allowlisted model and fresh available capacity before routing.</span>@@ -155,47 +177,55 @@ export default function PeerMediaProviderPanel({ peer, onRefresh }) {<p className="text-[10px] text-port-warning leading-snug">{STATE_HELP[status.state]}</p>)}- <div className="space-y-1">- <div className="text-[10px] text-gray-500 uppercase tracking-wider">Allowed audio models</div>- {rows.length === 0 ? (- <p className="text-[10px] text-gray-600">- No capabilities discovered yet. Verify peer authentication and probe again.- </p>- ) : rows.map((model, index) => {- const key = keyOf(model);- const selected = selectedKeys.has(key);- const inputId = `${safePeerId}-remote-media-model-${index}`;- return (- <label- key={key}- htmlFor={inputId}- className="flex items-start gap-2 rounded border border-port-border/70 px-2 py-1.5 cursor-pointer"- >- <input- id={inputId}- type="checkbox"- checked={selected}- disabled={saving}- onChange={() => toggleModel(model)}- className="sr-only"- aria-label={`Allow ${model.modelName}`}- />- <span className={`w-3 h-3 mt-0.5 rounded-sm border flex items-center justify-center shrink-0 ${- selected ? 'bg-port-accent border-port-accent' : 'border-gray-600'- }`}>- {selected && <Check size={8} className="text-white" />}- </span>- <Music2 size={12} className={model.ready ? 'text-port-success mt-0.5' : 'text-gray-500 mt-0.5'} />- <span className="min-w-0 flex-1">- <span className="block text-gray-300 truncate">{model.modelName}</span>- <span className="block text-[10px] text-gray-600 truncate">- {model.engineName} · {model.ready ? 'ready' : model.unavailableReason || 'unavailable'}- </span>- </span>- </label>- );- })}- </div>+ {KINDS.map(({ kind, label, field, Icon }) => {+ const rows = rowsByKind[kind];+ const selectedKeys = new Set(config.models[kind]+ .filter((model) => model?.engine && model.modelId)+ .map(keyOf));+ return (+ <div key={kind} className="space-y-1">+ <div className="text-[10px] text-gray-500 uppercase tracking-wider">Allowed {label} models</div>+ {rows.length === 0 ? (+ <p className="text-[10px] text-gray-600">+ No {label} capabilities discovered yet. Verify peer authentication and probe again.+ </p>+ ) : rows.map((model, index) => {+ const key = keyOf(model);+ const selected = selectedKeys.has(key);+ const inputId = `${safePeerId}-remote-media-${kind}-model-${index}`;+ return (+ <label+ key={key}+ htmlFor={inputId}+ className="flex items-start gap-2 rounded border border-port-border/70 px-2 py-1.5 cursor-pointer"+ >+ <input+ id={inputId}+ type="checkbox"+ checked={selected}+ disabled={saving}+ onChange={() => toggleModel(kind, field, model)}+ className="sr-only"+ aria-label={`Allow ${label} model ${model.modelName}`}+ />+ <span className={`w-3 h-3 mt-0.5 rounded-sm border flex items-center justify-center shrink-0 ${+ selected ? 'bg-port-accent border-port-accent' : 'border-gray-600'+ }`}>+ {selected && <Check size={8} className="text-white" />}+ </span>+ <Icon size={12} className={model.ready ? 'text-port-success mt-0.5' : 'text-gray-500 mt-0.5'} />+ <span className="min-w-0 flex-1">+ <span className="block text-gray-300 truncate">{model.modelName}</span>+ <span className="block text-[10px] text-gray-600 truncate">+ {model.engineName} · {model.ready ? 'ready' : model.unavailableReason || 'unavailable'}+ </span>+ </span>+ </label>+ );+ })}+ </div>+ );+ })}</>)}</div>diff --git a/client/src/components/instances/PeerMediaProviderPanel.test.jsx b/client/src/components/instances/PeerMediaProviderPanel.test.jsxindex 16e1708b12..a10b35922f 100644--- a/client/src/components/instances/PeerMediaProviderPanel.test.jsx+++ b/client/src/components/instances/PeerMediaProviderPanel.test.jsx@@ -16,6 +16,12 @@ const basePeer = {status: 'online',};+const capability = (overrides) => ({+ ready: true,+ unavailableReason: null,+ ...overrides,+});+const readyStatus = {state: 'ready',reason: null,@@ -23,18 +29,20 @@ const readyStatus = {freshUntil: '2026-08-17T12:01:00.000Z',snapshot: {queue: { running: 1, queued: 2, totalActive: 3, maxQueuedJobs: 4, accepting: true },- capabilities: [{+ capabilities: [capability({kind: 'audio',engine: 'minimax-music3',engineName: 'MiniMax Music 3',modelId: 'minimax-music3',modelName: 'MiniMax Music 3',- ready: true,- unavailableReason: null,- }],+ })],},};+// Every write sends the full per-kind shape, so the expected payload is verbose+// by design — a patch that omitted a list would only read as "unchanged" by luck.+const emptyLists = { audioModels: [], imageModels: [], videoModels: [] };+beforeEach(() => {vi.clearAllMocks();updatePeer.mockResolvedValue({ id: basePeer.id });@@ -47,10 +55,10 @@ describe('PeerMediaProviderPanel', () => {render(<PeerMediaProviderPanel peer={basePeer} onRefresh={onRefresh} />);fireEvent.click(screen.getByRole('button', { name: /Remote media provider/i }));- fireEvent.click(screen.getByLabelText(/Use this peer for remote audio/i));+ fireEvent.click(screen.getByLabelText(/Use this peer for remote media/i));await waitFor(() => expect(updatePeer).toHaveBeenCalledWith('peer-example', {- mediaProvider: { enabled: true, audioModels: [] },+ mediaProvider: { enabled: true, ...emptyLists },}));await waitFor(() => expect(probePeer).toHaveBeenCalledWith('peer-example'));expect(onRefresh).toHaveBeenCalled();@@ -67,18 +75,69 @@ describe('PeerMediaProviderPanel', () => {fireEvent.click(screen.getByRole('button', { name: /Remote media provider/i }));expect(screen.getByText(/1 running · 2 queued · 3\/4 shared slots active/i)).toBeInTheDocument();- fireEvent.click(screen.getByLabelText('Allow MiniMax Music 3'));+ fireEvent.click(screen.getByLabelText('Allow audio model MiniMax Music 3'));await waitFor(() => expect(updatePeer).toHaveBeenCalledWith('peer-example', {mediaProvider: {enabled: true,futureField: 'keep',+ ...emptyLists,audioModels: [{ engine: 'minimax-music3', modelId: 'minimax-music3' }],},}));expect(probePeer).not.toHaveBeenCalled();});+ // #4348 — image and video landed on the wire before they had any surface to+ // be allowlisted from, which left federated renders unreachable from the UI.+ it('allowlists an image model into its own list, leaving the audio list alone', async () => {+ const peer = {+ ...basePeer,+ mediaProvider: {+ enabled: true,+ audioModels: [{ engine: 'minimax-music3', modelId: 'minimax-music3' }],+ },+ mediaProviderStatus: {+ ...readyStatus,+ snapshot: {+ ...readyStatus.snapshot,+ capabilities: [+ ...readyStatus.snapshot.capabilities,+ capability({+ kind: 'image', engine: 'comfy', engineName: 'ComfyUI',+ modelId: 'sdxl-base', modelName: 'SDXL Base',+ }),+ ],+ },+ },+ };+ render(<PeerMediaProviderPanel peer={peer} onRefresh={vi.fn()} />);++ fireEvent.click(screen.getByRole('button', { name: /Remote media provider/i }));+ fireEvent.click(screen.getByLabelText('Allow image model SDXL Base'));++ await waitFor(() => expect(updatePeer).toHaveBeenCalledWith('peer-example', {+ mediaProvider: {+ enabled: true,+ audioModels: [{ engine: 'minimax-music3', modelId: 'minimax-music3' }],+ imageModels: [{ engine: 'comfy', modelId: 'sdxl-base' }],+ videoModels: [],+ },+ }));+ });++ it('keeps a selected model visible after the peer stops advertising it, so it can be removed', () => {+ render(<PeerMediaProviderPanel peer={{+ ...basePeer,+ mediaProvider: { enabled: true, videoModels: [{ engine: 'wan', modelId: 'wan-2.2' }] },+ mediaProviderStatus: readyStatus,+ }} onRefresh={vi.fn()} />);++ fireEvent.click(screen.getByRole('button', { name: /Remote media provider/i }));+ expect(screen.getByLabelText('Allow video model wan-2.2')).toBeChecked();+ expect(screen.getByText(/not-advertised/)).toBeInTheDocument();+ });+it('explains that stale capacity blocks new work', () => {render(<PeerMediaProviderPanel peer={{...basePeer,diff --git a/client/src/components/instances/UnattendedRenderRouting.jsx b/client/src/components/instances/UnattendedRenderRouting.jsxnew file mode 100644index 0000000000..e3f1bd02e5--- /dev/null+++ b/client/src/components/instances/UnattendedRenderRouting.jsx@@ -0,0 +1,140 @@+import { useEffect, useMemo, useState } from 'react';+import { Bot } from 'lucide-react';+import { getSettings, updateSettings } from '../../services/api';++// Only the visual kinds route. A federated audio submission may carry nothing+// but a canonical prompt rendered from a fixed enum profile (free-form music+// prompts and lyrics can hold PII), and a Creative Director music bed is+// free-form by construction — so audio stays local rather than being silently+// rewritten into a profile the user never picked.+const KINDS = Object.freeze([+ { kind: 'image', label: 'Image', field: 'imageModels' },+ { kind: 'video', label: 'Video', field: 'videoModels' },+]);++const isRecord = (value) => value && typeof value === 'object' && !Array.isArray(value);+const optionValue = ({ peerId, engine, modelId }) => JSON.stringify([peerId, engine, modelId]);++// One option per (peer, allowlisted model) pair that the peer currently+// advertises as a capability. A model the user allowlisted but the peer no+// longer advertises is deliberately absent: routing unattended work at it would+// fail the server's capacity preflight on every single job.+function routeOptions(peers, kind, field) {+ const options = [];+ for (const peer of peers) {+ if (peer?.mediaProvider?.enabled !== true) continue;+ const allowed = new Set((peer.mediaProvider[field] || [])+ .filter((model) => model?.engine && model?.modelId)+ .map((model) => `${model.engine}\u0000${model.modelId}`));+ for (const capability of peer.mediaProviderStatus?.snapshot?.capabilities || []) {+ if (capability?.kind !== kind) continue;+ if (!allowed.has(`${capability.engine}\u0000${capability.modelId}`)) continue;+ options.push({+ peerId: peer.id,+ engine: capability.engine,+ modelId: capability.modelId,+ label: `${peer.name || peer.address || 'Peer'} — ${capability.modelName || capability.modelId}`,+ ready: capability.ready === true,+ });+ }+ }+ return options;+}++/**+ * Chooses where UNATTENDED renders (Creative Director, Creative Commission) go.+ *+ * The planner never names a peer — that would be exactly the arbitrary-peer+ * routing the provider contract forbids — so the choice lives in this+ * instance's own settings and the server reads it at enqueue time.+ */+export default function UnattendedRenderRouting({ peers }) {+ const [routing, setRouting] = useState(null);+ const [federation, setFederation] = useState({});+ const [saving, setSaving] = useState(false);++ useEffect(() => {+ getSettings({ silent: true })+ .then((settings) => {+ const slice = isRecord(settings?.federation) ? settings.federation : {};+ setFederation(slice);+ setRouting(isRecord(slice.mediaRouting) ? slice.mediaRouting : {});+ })+ .catch(() => setRouting({}));+ }, []);++ const optionsByKind = useMemo(+ () => Object.fromEntries(KINDS.map(({ kind, field }) => [kind, routeOptions(peers, kind, field)])),+ [peers],+ );++ const save = async (kind, route) => {+ setSaving(true);+ const nextRouting = { ...routing, [kind]: route };+ // The settings PATCH shallow-merges TOP-LEVEL keys, so `federation` is+ // replaced wholesale — carry the rest of the slice forward or a save here+ // would drop the provider config the Sharing tab owns.+ const merged = await updateSettings(+ { federation: { ...federation, mediaRouting: nextRouting } },+ { silent: true },+ ).catch(() => null);+ if (merged) {+ setRouting(nextRouting);+ setFederation(isRecord(merged.federation) ? merged.federation : { ...federation, mediaRouting: nextRouting });+ }+ setSaving(false);+ };++ // Nothing is routable until at least one peer advertises an allowlisted+ // visual model, and an empty control would read as a broken feature.+ const anyOptions = KINDS.some(({ kind }) => optionsByKind[kind].length > 0);+ if (routing === null || !anyOptions) return null;++ return (+ <div className="mb-3 rounded-lg border border-port-border bg-port-bg/40 p-3">+ <div className="flex items-center gap-2 mb-1">+ <Bot size={14} className="text-port-accent" />+ <h3 className="text-xs font-medium text-gray-300 uppercase tracking-wider">Unattended render routing</h3>+ </div>+ <p className="text-[11px] text-gray-500 mb-2">+ Where Creative Director and Creative Commission send their renders. Agents never choose a peer;+ this instance does. A routed kind fails with the peer’s reason rather than quietly rendering+ locally, so unavailable capacity is visible instead of silent.+ </p>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">+ {KINDS.map(({ kind, label }) => {+ const options = optionsByKind[kind];+ const current = isRecord(routing[kind]) ? routing[kind] : null;+ const selectId = `unattended-routing-${kind}`;+ return (+ <label key={kind} className="block" htmlFor={selectId}>+ <span className="block text-[10px] uppercase tracking-wider text-gray-500 mb-1">{label}</span>+ <select+ id={selectId}+ value={current ? optionValue(current) : ''}+ disabled={saving || options.length === 0}+ onChange={(event) => save(kind, event.target.value+ ? (([peerId, engine, modelId]) => ({ peerId, engine, modelId }))(JSON.parse(event.target.value))+ : null)}+ 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>+ {options.map((option) => (+ <option key={optionValue(option)} value={optionValue(option)}>+ {option.label}{option.ready ? '' : ' (not ready)'}+ </option>+ ))}+ {/* A route saved against a model no longer advertised must stay+ selectable, or the control would silently show "This+ instance" while the server still routes every job. */}+ {current && !options.some((option) => optionValue(option) === optionValue(current)) && (+ <option value={optionValue(current)}>{current.modelId} (unavailable)</option>+ )}+ </select>+ </label>+ );+ })}+ </div>+ </div>+ );+}diff --git a/client/src/components/instances/UnattendedRenderRouting.test.jsx b/client/src/components/instances/UnattendedRenderRouting.test.jsxnew file mode 100644index 0000000000..232a919453--- /dev/null+++ b/client/src/components/instances/UnattendedRenderRouting.test.jsx@@ -0,0 +1,105 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';++vi.mock('../../services/api', () => ({+ getSettings: vi.fn(),+ updateSettings: vi.fn(),+}));++import { getSettings, updateSettings } from '../../services/api';+import UnattendedRenderRouting from './UnattendedRenderRouting';++const capability = (overrides) => ({ ready: true, unavailableReason: null, ...overrides });++const peerWith = (overrides = {}) => ({+ id: 'peer-1',+ name: 'Render Box',+ mediaProvider: {+ enabled: true,+ imageModels: [{ engine: 'comfy', modelId: 'sdxl-base' }],+ videoModels: [],+ },+ mediaProviderStatus: {+ state: 'ready',+ snapshot: {+ capabilities: [capability({+ kind: 'image', engine: 'comfy', engineName: 'ComfyUI',+ modelId: 'sdxl-base', modelName: 'SDXL Base',+ })],+ },+ },+ ...overrides,+});++beforeEach(() => {+ vi.clearAllMocks();+ getSettings.mockResolvedValue({ federation: {} });+ updateSettings.mockImplementation(async (patch) => patch);+});++describe('UnattendedRenderRouting', () => {+ it('stays hidden until a peer advertises an allowlisted visual model', async () => {+ const { container } = render(<UnattendedRenderRouting peers={[]} />);+ await waitFor(() => expect(getSettings).toHaveBeenCalled());+ expect(container).toBeEmptyDOMElement();+ });++ it('offers no audio lane — free-form music prompts cannot cross the wire', async () => {+ render(<UnattendedRenderRouting peers={[peerWith()]} />);+ expect(await screen.findByLabelText('Image')).toBeInTheDocument();+ expect(screen.getByLabelText('Video')).toBeInTheDocument();+ expect(screen.queryByLabelText('Audio')).not.toBeInTheDocument();+ });++ it('saves a chosen route while carrying the rest of the federation slice forward', async () => {+ getSettings.mockResolvedValue({+ federation: { strictPullAuthorization: true, mediaProvider: { enabled: true } },+ });+ render(<UnattendedRenderRouting peers={[peerWith()]} />);++ const select = await screen.findByLabelText('Image');+ fireEvent.change(select, { target: { value: JSON.stringify(['peer-1', 'comfy', 'sdxl-base']) } });++ await waitFor(() => expect(updateSettings).toHaveBeenCalledWith({+ federation: {+ strictPullAuthorization: true,+ mediaProvider: { enabled: true },+ mediaRouting: { image: { peerId: 'peer-1', engine: 'comfy', modelId: 'sdxl-base' } },+ },+ }, { silent: true }));+ });++ it('clears a route back to local rendering', async () => {+ getSettings.mockResolvedValue({+ federation: { mediaRouting: { image: { peerId: 'peer-1', engine: 'comfy', modelId: 'sdxl-base' } } },+ });+ render(<UnattendedRenderRouting peers={[peerWith()]} />);++ const select = await screen.findByLabelText('Image');+ fireEvent.change(select, { target: { value: '' } });++ await waitFor(() => expect(updateSettings).toHaveBeenCalledWith({+ federation: { mediaRouting: { image: null } },+ }, { silent: true }));+ });++ it('keeps a saved route selectable after the peer stops advertising its model', async () => {+ getSettings.mockResolvedValue({+ federation: { mediaRouting: { image: { peerId: 'peer-1', engine: 'comfy', modelId: 'retired-model' } } },+ });+ render(<UnattendedRenderRouting peers={[peerWith()]} />);++ const select = await screen.findByLabelText('Image');+ expect(select.value).toBe(JSON.stringify(['peer-1', 'comfy', 'retired-model']));+ expect(screen.getByText('retired-model (unavailable)')).toBeInTheDocument();+ });++ it('does not offer a model the peer advertises but the user never allowlisted', async () => {+ const peer = peerWith({+ mediaProvider: { enabled: true, imageModels: [], videoModels: [] },+ });+ const { container } = render(<UnattendedRenderRouting peers={[peer]} />);+ await waitFor(() => expect(getSettings).toHaveBeenCalled());+ expect(container).toBeEmptyDOMElement();+ });+});diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex 6aadfb7bff..69f1a0d439 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -24,6 +24,7 @@ import PeerAppsList from '../components/instances/PeerAppsList';import PeerAgentsSection from '../components/instances/PeerAgentsSection';import { SchemaGapBadge } from '../components/instances/SchemaGapBadge';import PeerMediaProviderPanel from '../components/instances/PeerMediaProviderPanel';+import UnattendedRenderRouting from '../components/instances/UnattendedRenderRouting';import BrainParityPanel from '../components/instances/BrainParityPanel';import BrainParitySchedule from '../components/instances/BrainParitySchedule';import { timeAgo, timeUntil } from '../utils/formatters';@@ -1459,6 +1460,7 @@ export default function Instances() {<h2 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-3">Peers ({peers.length})</h2>+ <UnattendedRenderRouting peers={peers} /><BrainParitySchedule /><div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">{peers.map(peer => (diff --git a/docs/FEDERATED_MEDIA_PROVIDERS.md b/docs/FEDERATED_MEDIA_PROVIDERS.mdindex a99a229f17..187f60fef3 100644--- a/docs/FEDERATED_MEDIA_PROVIDERS.md+++ b/docs/FEDERATED_MEDIA_PROVIDERS.md@@ -35,8 +35,8 @@ An older install without this settings slice behaves exactly like the default ab1. Register the provider under **Instances** and make the relationship mutual so the provider recognizes this consumer's instance id.2. Store the provider's instance-password credential on its peer card. The normal peer health probe may work without it when provider auth is off, but the federated-media API intentionally does not.-3. Expand **Remote media provider** on the peer card and enable **Use this peer for remote audio**. PortOS immediately probes the versioned status endpoint through `peerFetch`.-4. Select the exact advertised engine/model pairs this instance may use. This local allowlist is independent from the provider's sharing allowlist; both sides must permit a model.+3. Expand **Remote media provider** on the peer card and enable **Use this peer for remote media**. PortOS immediately probes the versioned status endpoint through `peerFetch`.+4. Select the exact advertised engine/model pairs this instance may use, per kind — the panel lists an **Allowed audio / image / video models** group. This local allowlist is independent from the provider's sharing allowlist; both sides must permit a model.The consumer default is also disabled:@@ -111,6 +111,53 @@ 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).+### Unattended renders (Creative Director / Creative Commission)++Everything above is a *per-request* choice: a human picks a peer in the UI and+the server validates it. Creative Director and Creative Commission have no human+in the loop at enqueue time, and their planners are LLMs — so "let the caller+name a peer" would be exactly the arbitrary-peer routing this contract exists to+prevent. Their routing lives in this instance's own settings instead:++```json+{+ "federation": {+ "mediaRouting": {+ "image": {+ "peerId": "00000000-0000-4000-8000-000000000001",+ "engine": "comfy",+ "modelId": "sdxl-base"+ },+ "video": null+ }+ }+}+```++Set it under **Instances → Unattended render routing**, which offers only+(peer, model) pairs that are both locally allowlisted and currently advertised+by that peer. A kind set to `null` (the default) renders locally.++Three properties are worth stating explicitly:++- **The agent names nothing.** The planner's own `modelId` is discarded in favour+ of the route's — a peer advertises its own model ids, and a local model name+ would fail the peer's allowlist check with a confusing "not allowlisted".+- **A routed kind fails closed, it does not fall back.** When the provider is+ stale, busy, unauthorized, or unavailable, the enqueue fails with that typed+ reason. It does not quietly render locally: that would burn hours of local GPU+ on work deliberately routed to another machine, invisibly.+- **Audio is deliberately unroutable.** A federated audio submission may carry+ only a canonical prompt rendered from a fixed enum profile, and a Creative+ Director music bed is free-form by construction — so it stays local rather+ than being silently rewritten into a profile the user never chose.++Destination tags on the job (`creativeDirectorSceneImage`, `musicVideo`,+`catalogAttach`, …) survive routing untouched, so the same completion hooks file+a federated render exactly where a local one would land. An unreadable settings+file is treated as "no route configured" — logged, then rendered locally —+because a transient read error must not hard-fail every autonomous render.+## Authentication and identityEvery request requires both:@@ -194,4 +241,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. Remote selection is exposed through the generation APIs rather than a peer picker on the Image Gen / Video Gen pages. Still remaining from #4348: those pickers, a privacy-preserving design for remote lyrical conditioning, input-asset transfer (init/reference images, LoRAs, chained renders), multi-provider fairness/failover, Creative Commission routing/UX, and aggregate provider health on System Health.+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), multi-provider fairness/failover, and aggregate provider health on System Health.diff --git a/server/lib/README.md b/server/lib/README.mdindex 83662d8997..478cb0c8dc 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -239,6 +239,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `httpClient.js` | Fetch-based HTTP client factory (axios.create replacement). || `abortTimeout.js` | `withAbortTimeout(timeoutMs, fn)` — runs `fn(signal)` under an `AbortController` that aborts after `timeoutMs` and always clears the timer on settle. Generic lifecycle helper for callers that need the insecure-agent `peerFetch` (so can't use `fetchWithTimeout`) or one signal across parallel fetches. || `fetchWithTimeout.js` | `fetch` wrapper with AbortController timeout. |+| `federatedMediaRequest.js` | Builds and validates the versioned federated-media submission body for a visual kind, so every call site that persists a remote-job marker projects local params onto the wire identically. || `federatedMediaWire.js` | Versioned federated-media status schema/constants plus fail-closed consumer freshness checks (stale and clock-skewed snapshots are never assignable). || `connectivity.js` | `isMachineOnline({timeoutMs?, hosts?})` — internet-reachability probe: bare TCP `connect` to public anycast resolvers on :443 (no DNS, no HTTP), resolves `true` on the first connect and `false` only after all fail; never rejects. Reuse when a caller needs a best-effort local reachability signal. || `safeUrlFetch.js` | SSRF-guarded public-URL fetch: `isPublicHttpUrlSafe`/`assertPublicHttpUrl` (scheme + blocked-host-literal via `catalogValidation.isBlockedIngestHost` + DNS-resolve), exported strict `isPrivateAddress`, plus `fetchPublicText`/`fetchPublicBinary` (timeout, redirect revalidation, size cap) and `buildPinnedLookup`/`buildPinnedDispatcher` (the connect-time IP pin that closes the DNS-rebinding TOCTOU). Reuse instead of copying the SSRF guard for any "fetch this remote thing the user pointed us at" flow. |diff --git a/server/lib/federatedMediaRequest.js b/server/lib/federatedMediaRequest.jsnew file mode 100644index 0000000000..59dc1f86d1--- /dev/null+++ b/server/lib/federatedMediaRequest.js@@ -0,0 +1,88 @@+/**+ * One builder for the versioned federated-media submission body.+ *+ * Three call sites now produce this object — the image generate route, the+ * video generate route, and the unattended default-provider router used by+ * Creative Director / Creative Commission — and every one of them persists it+ * inside the job's `remoteMedia` marker, where it is replayed verbatim on each+ * reconcile. A field that one site spreads and another forgets is therefore not+ * a cosmetic drift: it is a render that silently loses its seed or its+ * resolution the first time a worker restart replays it.+ *+ * Optional fields are conditionally spread rather than passed as `undefined`+ * because the wire schemas are `.strict()` and the marker is compared by shape+ * on the provider side; an explicit `undefined` would serialize to a key that+ * was never requested.+ */++import {+ federatedMediaImageJobSubmissionSchema,+ federatedMediaVideoJobSubmissionSchema,+ validateRequest,+} from './validation.js';++// Local param name -> wire field name, per kind. The two generate routes speak+// slightly different local dialects (video's route carries `guidanceScale`+// while the wire says `guidance`), so the mapping lives here rather than in a+// spread at each call site.+const FIELD_MAPS = Object.freeze({+ image: Object.freeze({+ negativePrompt: 'negativePrompt',+ width: 'width',+ height: 'height',+ steps: 'steps',+ guidance: 'guidance',+ guidanceScale: 'guidance',+ seed: 'seed',+ }),+ video: Object.freeze({+ negativePrompt: 'negativePrompt',+ width: 'width',+ height: 'height',+ numFrames: 'numFrames',+ fps: 'fps',+ steps: 'steps',+ guidance: 'guidance',+ guidanceScale: 'guidance',+ seed: 'seed',+ }),+});++const SCHEMAS = Object.freeze({+ image: federatedMediaImageJobSubmissionSchema,+ video: federatedMediaVideoJobSubmissionSchema,+});++/**+ * Build and validate a wire submission for a visual media kind.+ *+ * Audio is deliberately absent: its wire body is not a projection of local+ * params at all but a canonical prompt rendered from a fixed enum profile+ * (`renderFederatedMediaAudioPrompt`), so it has no field mapping to share.+ *+ * @param {object} args+ * @param {'image'|'video'} args.kind+ * @param {object} args.params - Local job params to project onto the wire.+ * @param {string} [args.engine] - Provider engine; defaults to `'local'`.+ * @returns {object} Validated wire submission body.+ */+export function buildFederatedMediaRequest({ kind, params, engine }) {+ const schema = SCHEMAS[kind];+ if (!schema) throw new Error(`buildFederatedMediaRequest: unsupported kind ${kind}`);+ const body = {+ kind,+ engine: engine || params?.mediaProviderEngine || 'local',+ modelId: params?.modelId,+ prompt: params?.prompt,+ };+ for (const [local, wire] of Object.entries(FIELD_MAPS[kind])) {+ // `negativePrompt` is the one field where an empty string is meaningless+ // rather than meaningful — the wire schema trims it to '' and then rejects+ // the min(1)-free optional as noise, so treat blank as absent.+ const value = params?.[local];+ if (value === undefined || value === null) continue;+ if (wire === 'negativePrompt' && !String(value).trim()) continue;+ if (body[wire] === undefined) body[wire] = value;+ }+ return validateRequest(schema, body);+}diff --git a/server/lib/federatedMediaRequest.test.js b/server/lib/federatedMediaRequest.test.jsnew file mode 100644index 0000000000..99ea979d74--- /dev/null+++ b/server/lib/federatedMediaRequest.test.js@@ -0,0 +1,56 @@+import { describe, it, expect } from 'vitest';+import { buildFederatedMediaRequest } from './federatedMediaRequest.js';++describe('buildFederatedMediaRequest', () => {+ it('projects local image params onto the wire body', () => {+ expect(buildFederatedMediaRequest({+ kind: 'image',+ params: { modelId: 'sdxl-base', prompt: 'a lighthouse', width: 512, height: 768, steps: 20, guidance: 7, seed: 3 },+ })).toEqual({+ kind: 'image', engine: 'local', modelId: 'sdxl-base', prompt: 'a lighthouse',+ width: 512, height: 768, steps: 20, guidance: 7, seed: 3,+ });+ });++ it('maps the video route dialect guidanceScale onto the wire guidance field', () => {+ const request = buildFederatedMediaRequest({+ kind: 'video',+ params: { modelId: 'wan-2.2', prompt: 'a drifting balloon', guidanceScale: 5.5, numFrames: 33, fps: 16 },+ });+ expect(request.guidance).toBe(5.5);+ expect(request).not.toHaveProperty('guidanceScale');+ expect(request.numFrames).toBe(33);+ });++ it('omits absent optionals rather than sending explicit undefined into a strict schema', () => {+ const request = buildFederatedMediaRequest({ kind: 'image', params: { modelId: 'm', prompt: 'p' } });+ expect(Object.keys(request).sort()).toEqual(['engine', 'kind', 'modelId', 'prompt']);+ });++ it('treats a blank negative prompt as absent', () => {+ const request = buildFederatedMediaRequest({+ kind: 'image',+ params: { modelId: 'm', prompt: 'p', negativePrompt: ' ' },+ });+ expect(request).not.toHaveProperty('negativePrompt');+ });++ it('prefers an explicit engine over the local mediaProviderEngine param', () => {+ expect(buildFederatedMediaRequest({+ kind: 'image', engine: 'comfy', params: { mediaProviderEngine: 'local', modelId: 'm', prompt: 'p' },+ }).engine).toBe('comfy');+ expect(buildFederatedMediaRequest({+ kind: 'image', params: { mediaProviderEngine: 'comfy', modelId: 'm', prompt: 'p' },+ }).engine).toBe('comfy');+ });++ it('rejects a body the provider would refuse instead of persisting it into a marker', () => {+ expect(() => buildFederatedMediaRequest({ kind: 'image', params: { modelId: 'm' } })).toThrow();+ expect(() => buildFederatedMediaRequest({ kind: 'image', params: { prompt: 'p' } })).toThrow();+ });++ it('refuses a kind with no wire projection', () => {+ expect(() => buildFederatedMediaRequest({ kind: 'audio', params: { modelId: 'm', prompt: 'p' } }))+ .toThrow(/unsupported kind audio/);+ });+});diff --git a/server/lib/federationSettingsSchema.test.js b/server/lib/federationSettingsSchema.test.jsnew file mode 100644index 0000000000..7944a8e64c--- /dev/null+++ b/server/lib/federationSettingsSchema.test.js@@ -0,0 +1,55 @@+import { describe, it, expect } from 'vitest';+import { federationSettingsSchema } from './validation.js';++// #4348 — `federation.mediaRouting` decides where UNATTENDED renders go, so a+// shape that slips past validation becomes a job silently routed at the wrong+// peer (or a route the UI can never clear).+describe('federationSettingsSchema.mediaRouting', () => {+ const parse = (mediaRouting) => federationSettingsSchema.safeParse({ mediaRouting });++ it('accepts a fully specified route', () => {+ const result = parse({ image: { peerId: 'peer-1', engine: 'comfy', modelId: 'sdxl-base' } });+ expect(result.success).toBe(true);+ expect(result.data.mediaRouting.image.modelId).toBe('sdxl-base');+ });++ it('accepts null as the way to turn a kind back off', () => {+ expect(parse({ image: null, video: null }).success).toBe(true);+ });++ it('accepts an absent slice — routing is opt-in', () => {+ expect(federationSettingsSchema.safeParse({}).success).toBe(true);+ });++ it('rejects a partial route rather than storing a peer with no model', () => {+ expect(parse({ image: { peerId: 'peer-1' } }).success).toBe(false);+ expect(parse({ image: { peerId: 'peer-1', engine: 'comfy' } }).success).toBe(false);+ expect(parse({ image: { engine: 'comfy', modelId: 'm' } }).success).toBe(false);+ });++ it('rejects an empty identifier that would resolve to no peer at all', () => {+ expect(parse({ image: { peerId: ' ', engine: 'comfy', modelId: 'm' } }).success).toBe(false);+ });++ it('rejects unknown fields inside a route so a stray key cannot ride into the marker', () => {+ expect(parse({ image: { peerId: 'p', engine: 'e', modelId: 'm', url: 'http://example.com' } }).success)+ .toBe(false);+ });++ it('carries an unknown ROUTING kind through, so a downgrade round trip keeps a newer config', () => {+ const result = parse({ audio: { peerId: 'p', engine: 'e', modelId: 'm' } });+ expect(result.success).toBe(true);+ expect(result.data.mediaRouting.audio).toBeTruthy();+ });++ it('keeps validating the pre-existing federation keys alongside routing', () => {+ const result = federationSettingsSchema.safeParse({+ strictPullAuthorization: true,+ mediaProvider: { enabled: true, maxQueuedJobs: 2 },+ mediaRouting: { video: { peerId: 'p', engine: 'e', modelId: 'm' } },+ });+ expect(result.success).toBe(true);+ expect(result.data.strictPullAuthorization).toBe(true);+ expect(result.data.mediaProvider.maxQueuedJobs).toBe(2);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex f4ad88be43..dd1b1d8733 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -231,6 +231,7 @@ export * from './ytdlp.js';export * from './abortTimeout.js';export * from './connectivity.js';export * from './fetchWithTimeout.js';+export * from './federatedMediaRequest.js';export * from './federatedMediaWire.js';export * from './requestAbort.js';export * from './httpClient.js';diff --git a/server/lib/validation.js b/server/lib/validation.jsindex df8f3825d5..f1957d4e6a 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -744,9 +744,26 @@ export const federatedMediaPeerSettingsSchema = z.object({videoModels: federatedMediaModelListSchema.optional(),}).passthrough();+// Where UNATTENDED jobs (Creative Director / Creative Commission) of a given+// kind render. One peer + one model per kind, chosen by the local operator and+// stored server-side, so an LLM planner never names a peer. Nullable because+// clearing a kind is how routing is turned back off — an absent key means+// "unchanged", an explicit null means "render locally again".+export const federatedMediaRouteSchema = z.object({+ peerId: z.string().trim().min(1).max(200),+ engine: z.string().trim().min(1).max(80),+ modelId: z.string().trim().min(1).max(256),+}).strict();++export const federatedMediaRoutingSchema = z.object({+ image: federatedMediaRouteSchema.nullable().optional(),+ video: federatedMediaRouteSchema.nullable().optional(),+}).passthrough();+export const federationSettingsSchema = z.object({strictPullAuthorization: z.boolean().optional(),mediaProvider: federatedMediaProviderSettingsSchema.optional(),+ mediaRouting: federatedMediaRoutingSchema.optional(),}).passthrough();export const federatedMediaJobRoutingSchema = z.object({diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 77301879fe..598ecd7334 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -42,8 +42,8 @@ import * as characterService from '../services/character.js';import { randomUUID } from 'crypto';import { buildUniverseRunTag } from '../services/universeRunTag.js';import { getSettings } from '../services/settings.js';-import { federatedMediaImageJobSubmissionSchema } from '../lib/validation.js';import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';+import { buildFederatedMediaRequest } from '../lib/federatedMediaRequest.js';const router = Router();@@ -454,18 +454,7 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {// Re-validate against the wire schema here rather than trusting the route// schema's overlap with it: this object is what gets persisted and replayed// on every reconcile, so it must already be a body the provider accepts.- const request = validateRequest(federatedMediaImageJobSubmissionSchema, {- kind: 'image',- engine: params.mediaProviderEngine || 'local',- modelId: params.modelId,- prompt: params.prompt,- ...(params.negativePrompt ? { negativePrompt: params.negativePrompt } : {}),- ...(params.width !== undefined ? { width: params.width } : {}),- ...(params.height !== undefined ? { height: params.height } : {}),- ...(params.steps !== undefined ? { steps: params.steps } : {}),- ...(params.guidance !== undefined ? { guidance: params.guidance } : {}),- ...(params.seed !== undefined ? { seed: params.seed } : {}),- });+ const request = buildFederatedMediaRequest({ kind: 'image', params });const { peer, remoteMedia } = await prepareRemoteMediaJob({peerId: params.mediaProviderPeerId,kind: 'image',diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 1b3a313de5..8d5d54ba41 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -14,7 +14,7 @@ import { z } from 'zod';import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';import { uploadFields } from '../lib/multipart.js';import {- validateRequest, videoModelTermsSchema, federatedMediaVideoJobSubmissionSchema,+ validateRequest, videoModelTermsSchema,} from '../lib/validation.js';import { grokVideoDurationSchema } from '../lib/sharedSchemas.js';import { MIN_CONTEXT_FRAMES, MAX_CONTEXT_FRAMES } from '../lib/videoContinuity.js';@@ -71,6 +71,7 @@ import { createInstallLogger } from '../lib/installLogger.js';import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';import { effectiveJobPrompt } from '../lib/federatedMediaWire.js';import { isRemoteMediaJob } from '../services/mediaJobQueue/remoteMediaJob.js';+import { buildFederatedMediaRequest } from '../lib/federatedMediaRequest.js';const router = Router();@@ -1053,20 +1054,7 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {// Re-validate against the wire schema rather than trusting this route// schema's overlap with it: this object is persisted and replayed on every// reconcile, so it must already be a body the provider accepts.- const request = validateRequest(federatedMediaVideoJobSubmissionSchema, {- kind: 'video',- engine: body.mediaProviderEngine || 'local',- modelId: body.modelId,- prompt: body.prompt,- ...(body.negativePrompt ? { negativePrompt: body.negativePrompt } : {}),- ...(body.width !== undefined ? { width: body.width } : {}),- ...(body.height !== undefined ? { height: body.height } : {}),- ...(body.numFrames !== undefined ? { numFrames: body.numFrames } : {}),- ...(body.fps !== undefined ? { fps: body.fps } : {}),- ...(body.steps !== undefined ? { steps: body.steps } : {}),- ...(body.guidanceScale !== undefined ? { guidance: body.guidanceScale } : {}),- ...(body.seed !== undefined ? { seed: body.seed } : {}),- });+ const request = buildFederatedMediaRequest({ kind: 'video', params: body });const { peer, remoteMedia } = await prepareRemoteMediaJob({peerId: body.mediaProviderPeerId,kind: 'video',diff --git a/server/services/creative/tools/media.js b/server/services/creative/tools/media.jsindex 6d1a2e3b68..e2d17d045e 100644--- a/server/services/creative/tools/media.js+++ b/server/services/creative/tools/media.js@@ -6,6 +6,7 @@import { z } from 'zod';import { enqueueJob } from '../../mediaJobQueue/index.js';+import { resolveDefaultMediaRoute, routedJobParams } from '../../federatedMedia/defaultRouting.js';import { ASPECT_PRESETS, QUALITY_PRESETS, presetToRenderParams } from '../../../lib/creativeDirectorPresets.js';import { getSettings } from '../../settings.js';import { IMAGE_GEN_MODE, resolveQueueImageMode } from '../../imageGen/modes.js';@@ -360,6 +361,20 @@ const mediaTool = (kind, label) => ({params = reconcileVideoParamsWithModel(params, project);}}+ // Unattended jobs never name a peer — the planner is an LLM, and letting+ // it pick one is exactly the arbitrary-peer routing the provider contract+ // forbids. Routing comes from this instance's own settings instead, and is+ // resolved LAST so the project/install pin ladder above has already run:+ // a configured remote provider overrides those local backend choices, and+ // a job that would have rendered locally is unaffected.+ const routed = await resolveDefaultMediaRoute({ kind, params });+ if (routed) {+ return enqueueJob({+ kind,+ params: routedJobParams(params, routed),+ owner: resolveOwner(args, ctx),+ });+ }return enqueueJob({ kind, params, owner: resolveOwner(args, ctx) });},});diff --git a/server/services/creative/tools/media.test.js b/server/services/creative/tools/media.test.jsindex 6235ca6812..c08720ca60 100644--- a/server/services/creative/tools/media.test.js+++ b/server/services/creative/tools/media.test.js@@ -10,6 +10,10 @@ const getCommissionMusicContextForProject = vi.fn(async () => null);vi.mock('../../creativeCommissions/store.js', () => ({getCommissionMusicContextForProject: (...args) => getCommissionMusicContextForProject(...args),}));+const prepareRemoteMediaJob = vi.fn();+vi.mock('../../federatedMedia/remoteSubmission.js', () => ({+ prepareRemoteMediaJob: (...args) => prepareRemoteMediaJob(...args),+}));import { enqueueJob } from '../../mediaJobQueue/index.js';import { getSettings } from '../../settings.js';@@ -439,3 +443,70 @@ describe('audio enqueues', () => {expect(enqueueJob).not.toHaveBeenCalled();});});++// #4348 — unattended jobs route to a peer only because THIS instance's settings+// say so. The planner never names a peer, so these assertions are all about+// what reaches the queue when `federation.mediaRouting` is (and is not) set.+describe('federated default provider routing (#4348)', () => {+ const route = { peerId: 'peer-1', engine: 'comfy', modelId: 'sdxl-remote' };+ const routedSettings = (mediaRouting) => ({ federation: { mediaRouting } });++ beforeEach(() => {+ prepareRemoteMediaJob.mockReset();+ prepareRemoteMediaJob.mockImplementation(async ({ peerId, kind, request }) => ({+ peer: { id: peerId },+ remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request },+ }));+ });++ it('renders locally, with its prompt intact, when no route is configured', async () => {+ getSettings.mockResolvedValue({});+ await run('media_enqueueImageJob', { prompt: 'a lighthouse' }, { projectId: 'cd-1' });+ expect(prepareRemoteMediaJob).not.toHaveBeenCalled();+ expect(enqueued().params.prompt).toBe('a lighthouse');+ expect(enqueued().params).not.toHaveProperty('remoteMedia');+ });++ it('routes an image job to the configured peer without the planner naming one', async () => {+ getSettings.mockResolvedValue(routedSettings({ image: route }));+ await run('media_enqueueImageJob', { prompt: 'a lighthouse', modelId: 'local-sdxl' }, { projectId: 'cd-1' });+ expect(prepareRemoteMediaJob).toHaveBeenCalledWith(expect.objectContaining({ peerId: 'peer-1', kind: 'image' }));+ const { params } = enqueued();+ // The prompt rides ONLY inside the versioned marker, so a build that cannot+ // read `remoteMedia` fails closed instead of re-rendering on local hardware.+ expect(params.prompt).toBe('');+ expect(params.remoteMedia.request.prompt).toBe('a lighthouse');+ // The route's model wins: a peer advertises its own ids, not the planner's.+ expect(params.modelId).toBe('sdxl-remote');+ });++ it('keeps the owner tag so a routed render stays attributable to its project', async () => {+ getSettings.mockResolvedValue(routedSettings({ image: route }));+ await run('media_enqueueImageJob', { prompt: 'a lighthouse' }, { projectId: 'cd-1' });+ expect(enqueued().owner).toBe('creative-director:cd-1');+ });++ it('routes a video job independently of the image route', async () => {+ getSettings.mockResolvedValue(routedSettings({ video: { ...route, modelId: 'wan-remote' } }));+ await run('media_enqueueVideoJob', { prompt: 'a drifting balloon' }, { projectId: 'cd-1' });+ expect(prepareRemoteMediaJob).toHaveBeenCalledWith(expect.objectContaining({ kind: 'video' }));+ expect(enqueued().params.modelId).toBe('wan-remote');+ });++ it('leaves audio local — free-form music prompts cannot cross the wire', async () => {+ getSettings.mockResolvedValue(routedSettings({ audio: route, image: route }));+ await run('media_enqueueAudioJob', { prompt: 'a warm ambient bed' });+ expect(prepareRemoteMediaJob).not.toHaveBeenCalled();+ expect(enqueued().params.prompt).toBe('a warm ambient bed');+ });++ it('fails the enqueue rather than silently burning local GPU when the peer is busy', async () => {+ getSettings.mockResolvedValue(routedSettings({ image: route }));+ prepareRemoteMediaJob.mockRejectedValue(+ Object.assign(new Error('Media provider is at capacity'), { code: 'MEDIA_PROVIDER_BUSY' }),+ );+ await expect(run('media_enqueueImageJob', { prompt: 'a lighthouse' }, { projectId: 'cd-1' }))+ .rejects.toThrow('Media provider is at capacity');+ expect(enqueueJob).not.toHaveBeenCalled();+ });+});diff --git a/server/services/federatedMedia/defaultRouting.js b/server/services/federatedMedia/defaultRouting.jsnew file mode 100644index 0000000000..8678bb2bd9--- /dev/null+++ b/server/services/federatedMedia/defaultRouting.js@@ -0,0 +1,146 @@+/**+ * Server-owned default provider routing for UNATTENDED media jobs.+ *+ * The interactive generate routes route a job because a human picked a peer in+ * the UI and the server validated that choice. Creative Director and Creative+ * Commission have no human in the loop at enqueue time, and their planners are+ * LLMs — so "let the caller name a peer" is exactly the arbitrary-peer routing+ * the provider contract exists to prevent (#4348). Instead the routing policy+ * lives in this instance's own settings: `federation.mediaRouting.<kind>` names+ * one peer and one model, the agent names nothing, and the resolver still runs+ * the full allowlist + capacity preflight before a job leaves the node.+ *+ * Audio is intentionally unroutable here. Its wire body is not a projection of+ * the local job at all: only a canonical prompt rendered from a fixed enum+ * profile may cross the boundary, because free-form music prompts and lyrics+ * carry PII. A Creative Director music bed is free-form by construction, so it+ * stays local rather than being silently rewritten into a profile the user+ * never chose.+ *+ * FAIL-CLOSED, NEVER FAIL-QUIET: when a kind has a configured route and the+ * provider is stale, busy, unauthorized, or unavailable, the enqueue FAILS with+ * the typed reason instead of falling back to a local render. Falling back+ * would burn hours of local GPU on work the user deliberately routed to another+ * machine, and would do it invisibly — the opposite of the "show clear+ * blocked/busy/unavailable states and avoid silently falling back" requirement.+ */++import { ServerError } from '../../lib/errorHandler.js';+import { buildFederatedMediaRequest } from '../../lib/federatedMediaRequest.js';+import { getSettings } from '../settings.js';++// Only the visual kinds. See the audio note in the module docblock.+export const ROUTABLE_MEDIA_KINDS = Object.freeze(['image', 'video']);++const isRecord = (value) => value && typeof value === 'object' && !Array.isArray(value);+const trimmed = (value) => (typeof value === 'string' ? value.trim() : '');++function sanitizeRoute(raw) {+ if (!isRecord(raw)) return null;+ const peerId = trimmed(raw.peerId);+ const engine = trimmed(raw.engine);+ const modelId = trimmed(raw.modelId);+ // A half-written route is not a route. Requiring all three up front is what+ // keeps a partially-saved settings blob from resolving to "peer X, whatever+ // model" — the allowlist check downstream is keyed on the exact pair.+ if (!peerId || !engine || !modelId) return null;+ return { peerId, engine, modelId };+}++/**+ * Project `settings.federation.mediaRouting` down to the routes this build+ * understands. Unknown kinds are dropped rather than carried: a route is only+ * ever consumed by a matching enqueue path, so a kind this version cannot+ * execute must read as "no route" and stay local.+ *+ * @param {object} settings - Full settings record.+ * @returns {{image: object|null, video: object|null}}+ */+export function normalizeMediaRoutingConfig(settings) {+ const raw = settings?.federation?.mediaRouting;+ const config = {};+ for (const kind of ROUTABLE_MEDIA_KINDS) {+ config[kind] = isRecord(raw) ? sanitizeRoute(raw[kind]) : null;+ }+ return config;+}++/**+ * Resolve the configured default provider for one unattended job, if any.+ *+ * @param {object} args+ * @param {'image'|'video'} args.kind+ * @param {object} args.params - Local job params the planner produced.+ * @returns {Promise<{peer: object, request: object, remoteMedia: object}|null>}+ * `null` when this kind has no configured route (render locally). Throws a+ * typed ServerError when a route IS configured but cannot be honoured.+ */+export async function resolveDefaultMediaRoute({ kind, params }) {+ if (!ROUTABLE_MEDIA_KINDS.includes(kind)) return null;+ // An unreadable settings file is an install-level fault, not a provider+ // fault: no configuration is knowable at all, which is the same state as a+ // fresh install. Rendering locally matches what the rest of this enqueue+ // path already does with an unreadable settings read (the render-backend+ // pin ladder falls through untouched) — hard-failing every autonomous+ // render on a transient read error would be a far worse outcome than one+ // local render. It is logged rather than swallowed so it can never look+ // like "no route configured".+ const settings = await getSettings().catch((error) => {+ console.error(`❌ Federated media routing could not read settings: ${error.message}`);+ return null;+ });+ if (!settings) return null;+ const route = normalizeMediaRoutingConfig(settings)[kind];+ if (!route) return null;++ if (!trimmed(params?.prompt)) {+ throw new ServerError(+ `A federated ${kind} render needs a prompt`,+ { status: 400, code: 'MEDIA_PROVIDER_PROMPT_REQUIRED' },+ );+ }+ const request = buildFederatedMediaRequest({+ kind,+ engine: route.engine,+ // The route's model wins over whatever the planner wrote: a peer advertises+ // its own model ids, and a local model name would fail the peer's allowlist+ // check with a confusing "not allowlisted" rather than an honest mismatch.+ params: { ...params, modelId: route.modelId },+ });+ // Lazy, for the same reason remoteSubmission.js is lazy: the creative tool+ // module is imported by agent-tool suites that mock the settings/DB layer,+ // and a static edge to the peer registry would drag that graph into them.+ const { prepareRemoteMediaJob } = await import('./remoteSubmission.js');+ const { peer, remoteMedia } = await prepareRemoteMediaJob({+ peerId: route.peerId,+ kind,+ request,+ });+ return { peer, request, remoteMedia };+}++/**+ * Local params that only mean something to a LOCAL dispatch. Dropping them+ * mirrors the generate routes: the backend selectors would otherwise ride into+ * a job no local backend ever runs, and a rollback to a build that cannot read+ * `remoteMedia` must fail closed rather than re-render the job for real.+ *+ * Destination tags (`creativeDirectorSceneImage`, `musicVideo`, `catalogAttach`,+ * …) deliberately stay: their completion hooks fire off the finished filename+ * and work identically for a federated render.+ */+const LOCAL_ONLY_ROUTED_PARAMS = Object.freeze([+ 'mode', 'cloudModel', 'backend', 'pythonPath',+ 'mediaProviderPeerId', 'mediaProviderEngine',+]);++/**+ * Turn a resolved route plus the planner's params into the job params to+ * enqueue. The prompt is blanked because it rides ONLY inside the versioned+ * marker (see the generate routes for the same reasoning).+ */+export function routedJobParams(params, { request, remoteMedia }) {+ const jobParams = { ...(params || {}) };+ for (const key of LOCAL_ONLY_ROUTED_PARAMS) delete jobParams[key];+ return { ...jobParams, prompt: '', modelId: request.modelId, remoteMedia };+}diff --git a/server/services/federatedMedia/defaultRouting.test.js b/server/services/federatedMedia/defaultRouting.test.jsnew file mode 100644index 0000000000..29dc1efc6a--- /dev/null+++ b/server/services/federatedMedia/defaultRouting.test.js@@ -0,0 +1,120 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const getSettings = vi.fn();+const prepareRemoteMediaJob = vi.fn();++vi.mock('../settings.js', () => ({ getSettings: (...args) => getSettings(...args) }));+vi.mock('./remoteSubmission.js', () => ({+ prepareRemoteMediaJob: (...args) => prepareRemoteMediaJob(...args),+}));++const { normalizeMediaRoutingConfig, resolveDefaultMediaRoute, routedJobParams } =+ await import('./defaultRouting.js');++const route = { peerId: 'peer-1', engine: 'comfy', modelId: 'sdxl-remote' };+const withRoute = (mediaRouting) => ({ federation: { mediaRouting } });++beforeEach(() => {+ getSettings.mockReset();+ prepareRemoteMediaJob.mockReset();+ prepareRemoteMediaJob.mockImplementation(async ({ peerId, kind, request }) => ({+ peer: { id: peerId },+ remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request },+ }));+});++describe('normalizeMediaRoutingConfig', () => {+ it('reads nothing as no routes', () => {+ expect(normalizeMediaRoutingConfig(undefined)).toEqual({ image: null, video: null });+ expect(normalizeMediaRoutingConfig({ federation: {} })).toEqual({ image: null, video: null });+ });++ it('keeps a fully specified route and trims it', () => {+ expect(normalizeMediaRoutingConfig(withRoute({ image: { peerId: ' p ', engine: ' e ', modelId: ' m ' } })).image)+ .toEqual({ peerId: 'p', engine: 'e', modelId: 'm' });+ });++ it('treats a half-written route as no route rather than peer-plus-any-model', () => {+ for (const partial of [{ peerId: 'p' }, { peerId: 'p', engine: 'e' }, { engine: 'e', modelId: 'm' }, { peerId: 'p', engine: ' ', modelId: 'm' }]) {+ expect(normalizeMediaRoutingConfig(withRoute({ image: partial })).image).toBeNull();+ }+ });++ it('drops a kind this build cannot execute so it stays local', () => {+ const config = normalizeMediaRoutingConfig(withRoute({ audio: route, image: route }));+ expect(config).not.toHaveProperty('audio');+ expect(config.image).toEqual(route);+ });+});++describe('resolveDefaultMediaRoute', () => {+ it('returns null for an unroutable kind without reading settings', async () => {+ await expect(resolveDefaultMediaRoute({ kind: 'audio', params: { prompt: 'p' } })).resolves.toBeNull();+ expect(getSettings).not.toHaveBeenCalled();+ });++ it('returns null when the kind has no configured route', async () => {+ getSettings.mockResolvedValue(withRoute({ video: route }));+ await expect(resolveDefaultMediaRoute({ kind: 'image', params: { prompt: 'p', modelId: 'local-sdxl' } }))+ .resolves.toBeNull();+ expect(prepareRemoteMediaJob).not.toHaveBeenCalled();+ });++ it('routes to the configured peer and overrides the planner model with the route model', async () => {+ getSettings.mockResolvedValue(withRoute({ image: route }));+ const resolved = await resolveDefaultMediaRoute({+ kind: 'image',+ params: { prompt: 'a lighthouse', modelId: 'local-sdxl', width: 512, height: 512 },+ });+ expect(prepareRemoteMediaJob).toHaveBeenCalledWith(expect.objectContaining({ peerId: 'peer-1', kind: 'image' }));+ expect(resolved.request).toMatchObject({ engine: 'comfy', modelId: 'sdxl-remote', prompt: 'a lighthouse' });+ expect(resolved.peer.id).toBe('peer-1');+ });++ it('fails closed instead of rendering locally when the provider rejects the preflight', async () => {+ getSettings.mockResolvedValue(withRoute({ video: route }));+ prepareRemoteMediaJob.mockRejectedValue(Object.assign(new Error('Media provider is at capacity'), { code: 'MEDIA_PROVIDER_BUSY' }));+ await expect(resolveDefaultMediaRoute({ kind: 'video', params: { prompt: 'a balloon' } }))+ .rejects.toThrow('Media provider is at capacity');+ });++ it('rejects a promptless routed job with a typed error', async () => {+ getSettings.mockResolvedValue(withRoute({ image: route }));+ await expect(resolveDefaultMediaRoute({ kind: 'image', params: { prompt: ' ' } }))+ .rejects.toMatchObject({ code: 'MEDIA_PROVIDER_PROMPT_REQUIRED' });+ expect(prepareRemoteMediaJob).not.toHaveBeenCalled();+ });+});++describe('routedJobParams', () => {+ const resolved = {+ request: { modelId: 'sdxl-remote' },+ remoteMedia: { peerId: 'peer-1' },+ };++ it('blanks the prompt so a build that cannot read the marker fails closed', () => {+ expect(routedJobParams({ prompt: 'a lighthouse' }, resolved).prompt).toBe('');+ });++ it('drops local-only dispatch params that no local backend will run', () => {+ const params = routedJobParams({+ prompt: 'p', mode: 'local', backend: 'comfy', pythonPath: '/x/py',+ cloudModel: 'grok', mediaProviderPeerId: 'other', mediaProviderEngine: 'local',+ }, resolved);+ for (const key of ['mode', 'backend', 'pythonPath', 'cloudModel', 'mediaProviderPeerId', 'mediaProviderEngine']) {+ expect(params).not.toHaveProperty(key);+ }+ });++ it('preserves destination tags so completion hooks still fire', () => {+ const params = routedJobParams({+ prompt: 'p',+ creativeDirectorSceneImage: { projectId: 'proj-1', sceneId: 'scene-2' },+ catalogAttach: { id: 'ing-1' },+ }, resolved);+ expect(params.creativeDirectorSceneImage).toEqual({ projectId: 'proj-1', sceneId: 'scene-2' });+ expect(params.catalogAttach).toEqual({ id: 'ing-1' });+ expect(params.remoteMedia).toEqual({ peerId: 'peer-1' });+ expect(params.modelId).toBe('sdxl-remote');+ });+});