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
refuse an unattended render route that could never run, at the save instead of on every job (#4348)
[._.]/ Adam Eivyb4039d93657d
diff --git a/client/src/components/instances/UnattendedRenderRouting.jsx b/client/src/components/instances/UnattendedRenderRouting.jsxindex 9047de48c8..fb6bc79605 100644--- a/client/src/components/instances/UnattendedRenderRouting.jsx+++ b/client/src/components/instances/UnattendedRenderRouting.jsx@@ -2,6 +2,13 @@ import { useEffect, useMemo, useState } from 'react';import { Bot } from 'lucide-react';import toast from '../ui/Toast';import { getSettings, updateSettings } from '../../services/api';+import {+ federatedMediaModelsForPeer,+ peerMediaProviderConfig,+ resolvePeerMediaReadiness,+ summarizePeerMediaQueue,+} from '../../lib/federatedMediaReadiness.js';+import { isTailnetPeer } from '../../lib/tailnetPeer.js';// 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@@ -9,34 +16,33 @@ import { getSettings, updateSettings } from '../../services/api';// 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' },+ { kind: 'image', label: 'Image' },+ { kind: 'video', label: 'Video' },]);const isRecord = (value) => value && typeof value === 'object' && !Array.isArray(value);const optionValue = ({ peerId, engine, modelId }) => JSON.stringify([peerId, engine, modelId]);-const modelKey = ({ engine, modelId }) => `${engine}\u0000${modelId}`;-// Mirrors the server's fail-closed `isTailnetPeer` gate (server/lib/tailnetPeer.js).-// A standing route exports every future prompt of its kind unreviewed, so ADR-// 2026-08-20-federated-visual-prompts (rule 5) refuses a non-tailnet peer. The-// server is authoritative; this only keeps the UI from offering a choice it-// would reject on the first job.-const isTailnetPeer = (peer) => {- const host = typeof peer?.host === 'string' ? peer.host.trim() : '';- if (host) return /\.ts\.net$/i.test(host);- const address = (typeof peer?.address === 'string' ? peer.address : '').trim().replace(/^\[|\]$/g, '');- if (!address) return false;- if (/\.ts\.net$/i.test(address) || /^fd7a:115c:a1e0:/i.test(address)) return true;- const v4 = address.match(/^100\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/);- return !!v4 && Number(v4[1]) >= 64 && Number(v4[1]) <= 127;+const TONE_CLASS = {+ success: 'text-port-success',+ warning: 'text-port-warning',+ note: 'text-gray-400',+ muted: 'text-gray-500',};// 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) {+//+// The two hard filters below are DURABLE configuration, which is why they can+// gate the option list: a peer switched off or not enabled as a provider stays+// that way until someone changes it. Live capacity deliberately does NOT gate —+// a provider is routinely asleep when its route is configured, and hiding it+// then would make the card unusable at exactly the moment it is being set up.+// Current state is reported as a caption instead, and the server re-checks+// everything at enqueue.+function routeOptions(peers, kind) {const options = [];for (const peer of peers) {// Both switches matter. `peer.enabled === false` disables the peer wholesale@@ -44,16 +50,12 @@ function routeOptions(peers, kind, field) {// it here would save a route whose every job dies on// MEDIA_PROVIDER_PEER_DISABLED.if (peer?.enabled === false) continue;- if (peer?.mediaProvider?.enabled !== true) continue;- // Offering a non-tailnet peer here would save a route the server refuses on- // every job with MEDIA_ROUTING_PEER_NOT_TAILNET.+ if (!peerMediaProviderConfig(peer).enabled) continue;+ // Offering a non-tailnet peer here would save a route the server refuses,+ // now at save time and again on every job, with+ // MEDIA_ROUTING_PEER_NOT_TAILNET.if (!isTailnetPeer(peer)) continue;- const allowed = new Set((peer.mediaProvider[field] || [])- .filter((model) => model?.engine && model?.modelId)- .map(modelKey));- for (const capability of peer.mediaProviderStatus?.snapshot?.capabilities || []) {- if (capability?.kind !== kind) continue;- if (!allowed.has(modelKey(capability))) continue;+ for (const capability of federatedMediaModelsForPeer(peer, kind)) {options.push({peerId: peer.id,engine: capability.engine,@@ -66,6 +68,29 @@ function routeOptions(peers, kind, field) {return options;}+/**+ * What the peer behind a saved route is reporting right now.+ *+ * Read through the same `resolvePeerMediaReadiness` the Instances card, System+ * Health, and the interactive pickers use, so this card cannot become a fourth+ * surface with its own opinion — the reason it is advisory here and blocking+ * there is the standing-vs-interactive distinction, not a different verdict.+ */+function routeStatus(peers, route) {+ if (!route) return null;+ const peer = peers.find((candidate) => candidate.id === route.peerId);+ if (!peer) {+ return { tone: 'warning', label: 'peer not registered', help: null, segments: [] };+ }+ const readiness = resolvePeerMediaReadiness(peer);+ return {+ tone: readiness.tone,+ label: readiness.label,+ help: readiness.help,+ segments: summarizePeerMediaQueue(readiness.queue),+ };+}+/*** Chooses where UNATTENDED renders (Creative Director, Creative Commission) go.*@@ -93,7 +118,7 @@ export default function UnattendedRenderRouting({ peers }) {}, []);const optionsByKind = useMemo(- () => Object.fromEntries(KINDS.map(({ kind, field }) => [kind, routeOptions(peers, kind, field)])),+ () => Object.fromEntries(KINDS.map(({ kind }) => [kind, routeOptions(peers, kind)])),[peers],);@@ -122,18 +147,22 @@ export default function UnattendedRenderRouting({ peers }) {const base = isRecord(fresh.federation) ? fresh.federation : {};const baseRouting = isRecord(base.mediaRouting) ? base.mediaRouting : routing;const nextRouting = { ...baseRouting, [kind]: route };- const merged = await updateSettings(+ const outcome = await updateSettings({ federation: { mediaRouting: nextRouting } },{ silent: true },- ).catch(() => null);+ ).then((merged) => ({ merged }), (error) => ({ error }));setSaving(false);- if (!merged) {+ if (outcome.error) {// The select is controlled off `routing`, so a failed save silently snaps- // it back to the old value. Say why, or it reads as the click not landing.- toast.error('Failed to save unattended render routing');+ // it back to the old value. Say why, or it reads as the click not landing+ // — and the server's own reason is the useful half now that it refuses a+ // route that could never run (unknown/disabled/un-allowlisted/non-tailnet+ // peer) instead of storing it to fail on every future render.+ toast.error(outcome.error.message || 'Failed to save unattended render routing');return;}- setRouting(isRecord(merged.federation?.mediaRouting) ? merged.federation.mediaRouting : nextRouting);+ const { merged } = outcome;+ setRouting(isRecord(merged?.federation?.mediaRouting) ? merged.federation.mediaRouting : nextRouting);};const savedRoute = (kind) => (isRecord(routing?.[kind]) ? routing[kind] : null);@@ -173,35 +202,54 @@ export default function UnattendedRenderRouting({ peers }) {{KINDS.map(({ kind, label }) => {const options = optionsByKind[kind];const current = savedRoute(kind);+ const status = routeStatus(peers, current);const selectId = `unattended-routing-${kind}`;+ const statusId = `${selectId}-status`;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) : ''}- // Enabled whenever there is something to choose OR something to- // clear; only a kind with neither is inert.- disabled={saving || (options.length === 0 && !current)}- 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 key={kind}>+ <label className="block" htmlFor={selectId}>+ <span className="block text-[10px] uppercase tracking-wider text-gray-500 mb-1">{label}</span>+ <select+ id={selectId}+ // The caption below reports the routed peer's live state; tie+ // it to the control so it is announced with it rather than+ // read as unrelated text after it.+ aria-describedby={status ? statusId : undefined}+ value={current ? optionValue(current) : ''}+ // Enabled whenever there is something to choose OR something to+ // clear; only a kind with neither is inert.+ disabled={saving || (options.length === 0 && !current)}+ 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>+ {/* Capacity messaging for a routed kind. Advisory, not a gate:+ what it answers is "will the next unattended render actually+ run, or queue behind something?" — which the select alone+ cannot say, and which nobody is watching for at enqueue time. */}+ {status && (+ <p id={statusId} className={`mt-1 text-[10px] ${TONE_CLASS[status.tone] || TONE_CLASS.muted}`}>+ {status.label}+ {status.segments.length > 0 && ` · ${status.segments.join(' · ')}`}+ {status.help && <span className="block text-gray-500">{status.help}</span>}+ </p>+ )}+ </div>);})}</div>diff --git a/client/src/components/instances/UnattendedRenderRouting.test.jsx b/client/src/components/instances/UnattendedRenderRouting.test.jsxindex 8e571f29ac..13aee811fd 100644--- a/client/src/components/instances/UnattendedRenderRouting.test.jsx+++ b/client/src/components/instances/UnattendedRenderRouting.test.jsx@@ -150,16 +150,33 @@ describe('UnattendedRenderRouting — failure and staleness handling', () => {}, { silent: true }));});- it('tells the user when a route save fails instead of silently reverting', async () => {- updateSettings.mockRejectedValue(new Error('nope'));+ // The server refuses a route that could never run (#4348) with a named+ // reason. Reporting a generic failure instead would leave the user re-picking+ // the same unrunnable option, since the select just snaps back either way.+ it('surfaces the server\u2019s reason when a route save is refused', async () => {+ updateSettings.mockRejectedValue(Object.assign(+ new Error('Unattended image routing requires a Tailscale peer'),+ { code: 'MEDIA_ROUTING_PEER_NOT_TAILNET', status: 403 },+ ));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(toast.error).toHaveBeenCalledWith('Failed to save unattended render routing'));+ await waitFor(() => expect(toast.error)+ .toHaveBeenCalledWith('Unattended image routing requires a Tailscale peer'));expect(select.value).toBe('');});++ it('falls back to a generic message when the failure carries none', async () => {+ updateSettings.mockRejectedValue(new Error(''));+ 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(toast.error).toHaveBeenCalledWith('Failed to save unattended render routing'));+ });});describe('UnattendedRenderRouting — writes against the freshest settings', () => {@@ -210,6 +227,66 @@ describe('UnattendedRenderRouting — a failed read is not an empty configuratio});});+// #4348 — item 6 asks for provider/model selection AND capacity messaging on+// the Creative Commission flow, which this card is. It reads through the same+// shared readiness lib the Instances card, System Health, and the interactive+// pickers use, so this cannot become a fourth surface with its own verdict.+describe('UnattendedRenderRouting — capacity messaging', () => {+ const routed = { federation: { mediaRouting: { image: { peerId: 'peer-1', engine: 'comfy', modelId: 'sdxl-base' } } } };++ it('reports the routed peer\u2019s readiness and queue occupancy', async () => {+ getSettings.mockResolvedValue(routed);+ const peer = peerWith({+ status: 'online',+ mediaProviderStatus: {+ state: 'ready',+ freshUntil: new Date(Date.now() + 60_000).toISOString(),+ snapshot: {+ capabilities: [capability({+ kind: 'image', engine: 'comfy', engineName: 'ComfyUI',+ modelId: 'sdxl-base', modelName: 'SDXL Base',+ })],+ queue: { totalActive: 1, maxQueuedJobs: 4, concurrency: 2, running: 0, queued: 0 },+ },+ },+ });+ render(<UnattendedRenderRouting peers={[peer]} />);++ expect(await screen.findByText(/1\/4 shared slots active/)).toBeInTheDocument();+ expect(screen.getByText(/runs 2 at a time/)).toBeInTheDocument();+ });++ // A snapshot probed as `ready` keeps SAYING ready long after the server would+ // refuse to submit against it; the shared lib re-derives that at render time.+ it('reads an expired snapshot as stale rather than repeating its own ready', async () => {+ getSettings.mockResolvedValue(routed);+ const peer = peerWith({+ status: 'online',+ mediaProviderStatus: {+ state: 'ready',+ freshUntil: new Date(Date.now() - 60_000).toISOString(),+ snapshot: { capabilities: [] },+ },+ });+ render(<UnattendedRenderRouting peers={[peer]} />);++ expect(await screen.findByText('stale')).toBeInTheDocument();+ });++ it('says so when the routed peer is no longer registered here', async () => {+ getSettings.mockResolvedValue(routed);+ render(<UnattendedRenderRouting peers={[]} />);+ expect(await screen.findByText('peer not registered')).toBeInTheDocument();+ });++ it('reports nothing for a kind that renders locally', async () => {+ getSettings.mockResolvedValue({ federation: {} });+ render(<UnattendedRenderRouting peers={[peerWith()]} />);+ await screen.findByLabelText('Image');+ expect(screen.queryByText(/shared slots active/)).not.toBeInTheDocument();+ });+});+describe('UnattendedRenderRouting — tailnet gate', () => {it('does not offer a peer reachable outside the tailnet', async () => {// The server refuses such a route on every job; offering it here would onlydiff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 1e3d3c6d3f..8a8b2e3e6b 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -187,6 +187,7 @@ grep -i "what you want to do" client/src/lib/README.md| `streakGlyph.js` | `streakGlyph(streak)` — the single POST streak emoji (✨ / ⚡ / 🔥 by day count) shared by the POST launcher, Morse trainer, daily widget, and dashboard streak widget. || `syncCounts.js` | Directional pending-sync counts for the Instances federation cards. `directionalCounts({ localMax, peerMax, ourCursor, peerCursorForUs })` → `{ toPull, toPush }` (each a non-negative Number, or `null` when unknown) from monotonic change-log seqs; `diffSeq(ahead, behind)` is the BigInt-safe clamp-at-zero subtraction (handles numeric strings past `MAX_SAFE_INTEGER`); `describeDirectional({ toPull, toPush })` renders the plain-language `{ state, text }` ("in sync" / "N to pull · M to push" / "checking…"). No React — `SyncStatusBadge` drives it. || `tabNotation.js` | Guitar-tab / chord-sheet / ChordPro text parser for SongBook (`/songbook`). `parseTabSheet(text)` → `{ lines, meta, errors }` classifying each line (`section`/`chords`/`lyric`/`tabstaff`/`chordlyric`/`blank`/`text`) with chord names + column offsets, plus ChordPro meta (`{title:}`/`{artist:}`/`{key:}`/`{capo:}`); `detectFormat(text)` → `'chordpro' \| 'tab' \| 'plain'`; `normalizePastedTab(text)` cleans HTML remnants/entities, CRLF, tabs→spaces, blank-line runs; `transposeChordName(name, n)` / `transposeText(text, n)` transpose chord symbols (slash chords, sensible sharp/flat spelling, column-preserving on chord lines); `TAB_ARTICULATIONS` documents tab-staff technique characters for the viewer legend; `CHORD_TOKEN_RE` exported for reuse, plus `NOTE_TO_PC` / `spellPitchClass` exported minimally so `chordShapes.js` derives voicings from the same pitch-class tables. Forgiving — never throws, unknown lines classify as `text`. NOT the lead-sheet parser (`scoreNotation.js`). |+| `tailnetPeer.js` | `isTailnetPeer(peer)` — is this registered peer reachable ONLY over the tailnet? A faithful port of `server/lib/tailnetPeer.js` (MagicDNS `.ts.net`, the 100.64.0.0/10 CGNAT range with every octet range-checked, and the `fd7a:115c:a1e0::/48` ULA; an explicit non-tailnet `host` overrides a tailnet-looking `address`). FAIL-CLOSED — anything not positively recognized is not tailnet. Used to keep the unattended-render-routing picker from OFFERING a peer the server would refuse under ADR [federated visual prompts](../../../docs/decisions/2026-08-20-federated-visual-prompts.md) rule 5; the server stays authoritative and refuses such a route both on save and on every enqueue. Keep the table in `tailnetPeer.test.js` identical to the server suite’s. || `terminalDictation.js` | Voice-dictation/IME bridge for the Shell's xterm.js terminal. Apple dictation streams progressively refined guesses and *replaces* what it already typed; xterm forwards each insertion and drops the matching deletions, so the PTY accumulates a garble (`determin` + `determine` + `determines`…). `attachDictationBridge(terminal, sendData)` binds capture-phase listeners on `terminal.element` — ahead of xterm's own textarea listeners, which it stops — and forwards a diff instead: `TERMINAL_DEL` (`0x7f`) per dropped character, then the added text. `sendData` returns `false` to report a dropped send, which leaves the mirror where the PTY actually is. Paths that reach the PTY some other way (a keystroke xterm handles itself, paste, blur, composition end, screen-reader mode) resync the mirror without emitting. `planFieldEdit(mirror, next, floor)` → `{ data, committed }` is the pure core: `floor` is the prefix we did not write and must never rewind through, and `committed` (what the PTY holds afterward, which is *not* the field's value when the floor blocked a rewind) is what the caller must track. The prefix scan never splits a surrogate pair — cutting between the halves of an astral character would send a lone surrogate that serializes to `U+FFFD`. Wired in `useShellSession`; the test suite pins the seam against a real `Terminal`. || `terminalScroll.js` | Scrolling the Shell terminal by touch, and inside a full-screen TUI. Two gaps, one primitive: xterm 6 binds **no touch handlers at all** (its viewport is VS Code’s `SmoothScrollableElement`, whose scroll extent is virtual — there is no oversized spacer for the browser to scroll natively), and a TUI’s ALTERNATE screen buffer additionally has no scrollback, so `scrollLines()` clamps to a no-op there. `attachTerminalTouchScroll(terminal)` (→ detach fn) makes a one-finger drag scroll in either buffer; `scrollTerminalLines(terminal, lines, geometry?)` / `scrollTerminalPage(terminal, direction)` drive it — via `scrollLines()` in the normal buffer, and in the alternate buffer by synthesizing `DOM_DELTA_LINE` wheel events on `terminal.element`, xterm’s only injection point (`attachCustomWheelEventHandler` intercepts, it cannot inject), so xterm’s own table picks SGR mouse report vs cursor key from the DEC modes the TUI set. `measureTerminalGeometry(terminal)` takes the one layout-forcing read per gesture (row height + screen centre); `planTouchScrollSteps(accumPx, rowHeightPx)` is the pure sub-row-remainder core. Wired in `useShellSession` (`scrollPage`) + the `SCROLL_KEYS` buttons in `components/shell/TerminalHotKeys.jsx`. || `terminalTheme.js` | Pure xterm.js palette builder for the Shell terminal. `buildTerminalTheme({ bg, fg, accent, card, error, success, warning }, mode)` assembles the xterm `theme` object — base ANSI colors from the active theme's CSS vars, the rest from mode-tuned literals (`ANSI_NIGHT` bright/pastel for dark backgrounds, `ANSI_DAY` darkened/saturated so colored CLI output stays legible on daytime themes). `parseCssColorToHex(raw, fallback)` normalizes both the `15 15 15` triple form and the `rgb(7 7 7 / 0.86)` function form (used by `--port-terminal-*` tokens) to `#rrggbb`, dropping alpha. No DOM reads — `Shell.jsx` resolves CSS vars and re-applies on theme switch. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 20c957f2cf..d55a1036d9 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -152,6 +152,7 @@ export * from './spriteWalkUnlock.js';export * from './streakGlyph.js';export * from './syncCounts.js';export * from './tabNotation.js';+export * from './tailnetPeer.js';export * from './terminalDictation.js';export * from './terminalScroll.js';export * from './terminalTheme.js';diff --git a/client/src/lib/tailnetPeer.js b/client/src/lib/tailnetPeer.jsnew file mode 100644index 0000000000..db4a4b6f91--- /dev/null+++ b/client/src/lib/tailnetPeer.js@@ -0,0 +1,56 @@+/**+ * Is a peer reachable ONLY over the tailnet? — the browser's copy of the gate.+ *+ * A faithful port of `server/lib/tailnetPeer.js`, which stays authoritative:+ * the server refuses a standing route to a non-tailnet peer both when the route+ * is SAVED (`server/services/federatedMedia/routingPolicy.js`) and again on+ * every enqueue, per ADR `docs/decisions/2026-08-20-federated-visual-prompts.md`+ * rule 5. All this copy does is keep a picker from OFFERING a peer the server is+ * about to refuse, which is the difference between an explained absence and a+ * click that fails.+ *+ * It exists as its own module because it previously lived inline in one+ * component, where its CGNAT check quietly skipped the octet-range validation+ * the server does — so `100.64.999.1` read as tailnet in the browser and as+ * public space on the server. A port that diverges is worse than no port; this+ * module's test table is the server's, case for case, so a future edit to+ * either side fails loudly.+ *+ * FAIL-CLOSED: an address this cannot positively recognize as tailnet is+ * treated as NOT tailnet.+ */++// Tailscale's MagicDNS suffix.+const MAGIC_DNS = /\.ts\.net$/i;+// Tailscale's IPv6 ULA prefix, fd7a:115c:a1e0::/48.+const TAILSCALE_ULA = /^fd7a:115c:a1e0:/i;++const trimmed = (value) => (typeof value === 'string' ? value.trim() : '');++// 100.64.0.0/10 — the CGNAT range Tailscale assigns IPv4 addresses from. The+// second octet must be 64-127; 100.0.0.0/10 and 100.128.0.0/9 are ordinary+// public space and must NOT read as tailnet.+function isCgnatV4(address) {+ const match = address.match(/^100\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);+ if (!match) return false;+ const octets = match.slice(1).map(Number);+ if (octets.some((octet) => octet > 255)) return false;+ return octets[0] >= 64 && octets[0] <= 127;+}++/**+ * @param {object} peer - Registered peer record (`host` and/or `address`).+ * @returns {boolean} True only when the peer is positively recognized as a+ * tailnet host.+ */+export function isTailnetPeer(peer) {+ const host = trimmed(peer?.host);+ // An explicit host wins: it is what the server actually dials, so a+ // non-tailnet hostname is not rescued by a tailnet-looking `address`.+ if (host) return MAGIC_DNS.test(host);+ const address = trimmed(peer?.address);+ if (!address) return false;+ // Strip brackets from a literal IPv6 address (`[fd7a:…]`).+ const bare = address.replace(/^\[|\]$/g, '');+ return MAGIC_DNS.test(bare) || isCgnatV4(bare) || TAILSCALE_ULA.test(bare);+}diff --git a/client/src/lib/tailnetPeer.test.js b/client/src/lib/tailnetPeer.test.jsnew file mode 100644index 0000000000..f671d4e399--- /dev/null+++ b/client/src/lib/tailnetPeer.test.js@@ -0,0 +1,56 @@+import { describe, it, expect } from 'vitest';+import { isTailnetPeer } from './tailnetPeer.js';++// The table below is `server/lib/tailnetPeer.test.js`, case for case. Keeping+// them identical is the whole point of the port: the previous inline copy in+// UnattendedRenderRouting had no table of its own and had already drifted.+describe('isTailnetPeer (client port)', () => {+ it('accepts a MagicDNS host', () => {+ expect(isTailnetPeer({ host: 'example-host.tailnet-example.ts.net' })).toBe(true);+ expect(isTailnetPeer({ host: ' example-host.tailnet-example.ts.net ' })).toBe(true);+ });++ it('accepts a Tailscale CGNAT v4 address across the whole 100.64.0.0/10 range', () => {+ for (const address of ['100.64.0.1', '100.64.0.5', '100.127.255.254']) {+ expect(isTailnetPeer({ address })).toBe(true);+ }+ });++ it('rejects 100.x addresses OUTSIDE the CGNAT range, which are ordinary public space', () => {+ for (const address of ['100.63.0.1', '100.128.0.1', '100.255.255.1']) {+ expect(isTailnetPeer({ address })).toBe(false);+ }+ });++ it('accepts the Tailscale IPv6 ULA, bracketed or bare', () => {+ expect(isTailnetPeer({ address: 'fd7a:115c:a1e0::1' })).toBe(true);+ expect(isTailnetPeer({ address: '[fd7a:115c:a1e0::1]' })).toBe(true);+ });++ it('rejects a plain LAN address, a public host, and a lookalike suffix', () => {+ for (const address of ['192.0.2.10', '10.0.0.5', 'example.com', 'notreally-ts.net.example.com']) {+ expect(isTailnetPeer({ address })).toBe(false);+ }+ });++ // `host` is what the server actually dials, so a tailnet-looking address must+ // not rescue a peer configured to reach a non-tailnet hostname.+ it('lets an explicit non-tailnet host override a tailnet-looking address', () => {+ expect(isTailnetPeer({ host: 'render.example.com', address: '100.64.0.1' })).toBe(false);+ });++ it('fails closed on missing, empty, or malformed input', () => {+ for (const peer of [undefined, null, {}, { host: ' ' }, { address: '' }, { address: '100.64.0' }, { address: '100.999.0.1' }]) {+ expect(isTailnetPeer(peer)).toBe(false);+ }+ });++ // The exact divergence the inline copy shipped: it range-checked only the+ // SECOND octet, so a malformed address inside 100.64/10 read as tailnet in+ // the browser while the server called it public space.+ it('rejects a malformed address whose leading octets look like CGNAT', () => {+ for (const address of ['100.64.999.1', '100.127.0.999']) {+ expect(isTailnetPeer({ address })).toBe(false);+ }+ });+});diff --git a/docs/FEDERATED_MEDIA_PROVIDERS.md b/docs/FEDERATED_MEDIA_PROVIDERS.mdindex 83ba9522cd..4b20070bc8 100644--- a/docs/FEDERATED_MEDIA_PROVIDERS.md+++ b/docs/FEDERATED_MEDIA_PROVIDERS.md@@ -198,7 +198,31 @@ prevent. Their routing lives in this instance's own settings instead: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.+by that peer. A kind set to `null` (the default) renders locally. The card also+reports what the routed peer is saying right now — readiness plus the shared+queue occupancy — through the same `resolvePeerMediaReadiness` /+`summarizePeerMediaQueue` helpers the Instances peer card, System Health and the+interactive pickers read, so no surface can disagree with another.++**The route is validated where it is SAVED, not only where it is used.**+`PUT /api/settings` refuses a `federation.mediaRouting.<kind>` naming a peer that+is unknown (`404 MEDIA_PROVIDER_PEER_NOT_FOUND`), switched off+(`409 MEDIA_PROVIDER_PEER_DISABLED`), not enabled as a media provider+(`409 MEDIA_PROVIDER_NOT_CONFIGURED`), not allowlisted for that exact+engine/model pair (`403 MEDIA_PROVIDER_MODEL_NOT_ALLOWED`), or reachable outside+the tailnet (`403 MEDIA_ROUTING_PEER_NOT_TAILNET`). None of those is a transient+capacity problem — a route in any of those states can never run — and unattended+work has no human at the moment it fails, so the refusal belongs at the save,+where there is one (`server/services/federatedMedia/routingPolicy.js`).++Only *durable configuration* is checked at save time. Live capacity is not: a+provider is routinely asleep, busy, or mid-probe when its route is configured,+and gating the save on a fresh snapshot would make the card unusable at exactly+the moment someone sits down to set it up. Freshness, queue admission, and+per-model readiness stay on the enqueue path, which re-checks all of them — and+re-checks the tailnet gate per request, since a peer's host can be edited after+the route is saved. **Clearing a route is always allowed**, whatever became of+its peer, so a bad configuration can never become permanent.An unattended route inherits the same text-to-image/text-to-video boundary theinteractive routes enforce. A job carrying an init image, reference images,@@ -225,8 +249,9 @@ settles the scene through its normal failure path instead of leaving it stuck in`rendering`.**A standing route requires a Tailscale peer.** A non-tailnet peer is refused-with `403 MEDIA_ROUTING_PEER_NOT_TAILNET`, and the Instances picker does not-offer one. Interactive routing is unchanged — the difference is review cadence:+with `403 MEDIA_ROUTING_PEER_NOT_TAILNET` — on save and again on every enqueue —+and the Instances picker does not offer one. Interactive routing is unchanged+— the difference is review cadence:a standing route exports every future prompt of its kind with nobody looking, soa misconfigured counterparty is a permanent leak rather than a one-time mistake,and `peerFetch`'s `rejectUnauthorized: false` leaves a plain-LAN or non-`.ts.net`@@ -236,7 +261,8 @@ reads it before failing to answer. Required by ADR[federated visual prompts](./decisions/2026-08-20-federated-visual-prompts.md)(rule 5); the gate is its own fail-closed predicate (`server/lib/tailnetPeer.js`)rather than a re-export of the probe-deferral heuristic, so tuning that heuristic-can never widen this boundary.+can never widen this boundary. The browser ports it as `client/src/lib/tailnetPeer.js`+only so the picker can explain an absent option; the server never trusts that copy.Three properties are worth stating explicitly:diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 6f521db0db..b00094e6e4 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -9,6 +9,7 @@ import {CODEX_PARALLEL_MAX,CODEX_PARALLEL_DEFAULT,} from '../services/mediaJobQueue/index.js';+import { assertMediaRoutingConfig } from '../services/federatedMedia/routingPolicy.js';import { asyncHandler } from '../lib/errorHandler.js';import { isPlainObject } from '../lib/objects.js';import { agentContextSettingsSchema } from '../lib/agentContextValidation.js';@@ -196,6 +197,13 @@ router.put('/', asyncHandler(async (req, res) => {}if (req.body?.federation !== undefined) {validateRequest(federationSettingsSchema, req.body.federation);+ // The schema only proves a route is well-SHAPED. A route naming a peer that+ // is unknown, switched off, not a media provider, not allowlisted for that+ // model, or outside the tailnet is well-shaped and permanently unusable —+ // and unattended work has no human at the moment it fails, so it would just+ // break every future Creative Director / Commission render in silence.+ // Refuse it here, where there IS a human. See routingPolicy.js.+ await assertMediaRoutingConfig(req.body.federation.mediaRouting);}// Home location ({ lat, lon }) read by the weather_now voice tool. The schema// already makes both fields optional + nullable (clearing falls back to thediff --git a/server/routes/settings.test.js b/server/routes/settings.test.jsindex 2c09c8ffda..fa95e65470 100644--- a/server/routes/settings.test.js+++ b/server/routes/settings.test.js@@ -20,6 +20,13 @@ vi.mock('../services/settings.js', () => ({return { ...store };}),}));+// The settings route now refuses a standing render route naming a peer that+// could never run it (see services/federatedMedia/routingPolicy.js), so this+// suite owns a peer registry. Mocked rather than real: the routing policy loads+// the registry lazily, and letting it fall through would read this developer's+// own data/instances.json.+let peers = [];+vi.mock('../services/instances.js', () => ({ getPeers: vi.fn(async () => peers) }));vi.mock('../services/aiAssignments.js', () => ({getAiAssignments: vi.fn(async () => ({})),updateAiAssignment: vi.fn(async () => ({})),@@ -84,9 +91,21 @@ describe('Settings routes — apiAccess slice', () => {});});+// A peer that satisfies every durable gate the routing policy checks: enabled,+// enabled as a provider, allowlisted for the routed pair, and on the tailnet.+const routablePeer = (overrides = {}) => ({+ id: 'peer-1',+ name: 'Render Box',+ host: 'render-box.tailnet-example.ts.net',+ enabled: true,+ mediaProvider: { enabled: true, imageModels: [{ engine: 'ltx', modelId: 'ltx-1' }], videoModels: [] },+ ...overrides,+});+describe('Settings routes — agent context and federated media provider slices', () => {beforeEach(() => {store = {};+ peers = [];vi.clearAllMocks();});@@ -145,6 +164,7 @@ describe('Settings routes — agent context and federated media provider slices'const app = buildApp();store = { federation: { strictPullAuthorization: false } };const route = { peerId: 'peer-1', engine: 'ltx', modelId: 'ltx-1' };+ peers = [routablePeer()];const sharing = await request(app).put('/api/settings')@@ -187,6 +207,49 @@ describe('Settings routes — agent context and federated media provider slices'expect(res.body.federation).toEqual({ mediaRouting: {}, strictPullAuthorization: true });});+ // #4348 — a standing route is validated where it is SAVED, not only where it+ // is used. An unattended render has no human at the moment it fails, so a+ // route that can never run must not reach disk in the first place.+ it('saves a standing route to an allowlisted model on an enabled tailnet provider', async () => {+ peers = [routablePeer()];+ const res = await request(buildApp())+ .put('/api/settings')+ .send({ federation: { mediaRouting: { image: { peerId: 'peer-1', engine: 'ltx', modelId: 'ltx-1' } } } });+ expect(res.status).toBe(200);+ expect(res.body.federation.mediaRouting.image).toEqual({ peerId: 'peer-1', engine: 'ltx', modelId: 'ltx-1' });+ });++ it('refuses a standing route whose model was never allowlisted for that peer', async () => {+ peers = [routablePeer()];+ const res = await request(buildApp())+ .put('/api/settings')+ .send({ federation: { mediaRouting: { image: { peerId: 'peer-1', engine: 'ltx', modelId: 'not-allowlisted' } } } });+ expect(res.status).toBe(403);+ expect(res.body.code).toBe('MEDIA_PROVIDER_MODEL_NOT_ALLOWED');+ expect(store.federation).toBeUndefined();+ });++ it('refuses a standing route to a peer reachable outside the tailnet (ADR rule 5)', async () => {+ peers = [routablePeer({ host: undefined, address: '192.0.2.10' })];+ const res = await request(buildApp())+ .put('/api/settings')+ .send({ federation: { mediaRouting: { image: { peerId: 'peer-1', engine: 'ltx', modelId: 'ltx-1' } } } });+ expect(res.status).toBe(403);+ expect(res.body.code).toBe('MEDIA_ROUTING_PEER_NOT_TAILNET');+ });++ // Clearing must survive whatever happened to the peer, or a bad route becomes+ // permanent — the exact failure a save-time gate would otherwise create.+ it('still clears a route whose peer has since been unregistered', async () => {+ store = { federation: { mediaRouting: { image: { peerId: 'peer-1', engine: 'ltx', modelId: 'ltx-1' } } } };+ peers = [];+ const res = await request(buildApp())+ .put('/api/settings')+ .send({ federation: { mediaRouting: { image: null } } });+ expect(res.status).toBe(200);+ expect(res.body.federation.mediaRouting).toEqual({ image: null });+ });+it('rejects invalid limits and duplicate engine/model pairs', async () => {const invalidLimit = await request(buildApp()).put('/api/settings')diff --git a/server/services/federatedMedia/defaultRouting.js b/server/services/federatedMedia/defaultRouting.jsindex 0f6a73991b..228ffcf7d7 100644--- a/server/services/federatedMedia/defaultRouting.js+++ b/server/services/federatedMedia/defaultRouting.js@@ -30,43 +30,15 @@ import { buildFederatedMediaRequest } from '../../lib/federatedMediaRequest.js';import { getSettingsWithStatus } from '../settings.js';import { isTailnetPeer } from '../../lib/tailnetPeer.js';import { CLOUD_VIDEO_GEN_MODES, VIDEO_GEN_MODES } from '../videoGen/modes.js';+import { ROUTABLE_MEDIA_KINDS, normalizeMediaRoutingConfig } from './routingPolicy.js';-// Only the visual kinds. See the audio note in the module docblock.-export const ROUTABLE_MEDIA_KINDS = Object.freeze(['image', 'video']);+// The route's shape and its save-time policy live in routingPolicy.js; this+// module owns only what happens at ENQUEUE time. Re-exported so existing+// callers keep one import site.+export { ROUTABLE_MEDIA_KINDS, normalizeMediaRoutingConfig };-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;-}-// Params that ask for conditioning wire v1 cannot carry. The interactive routes// reject these outright rather than dropping them, because "silently dropping// the source image a user pinned returns a plausible render of the wrongdiff --git a/server/services/federatedMedia/routingPolicy.js b/server/services/federatedMedia/routingPolicy.jsnew file mode 100644index 0000000000..835ffef4f9--- /dev/null+++ b/server/services/federatedMedia/routingPolicy.js@@ -0,0 +1,165 @@+/**+ * What a standing unattended render route IS, and whether one may be SAVED.+ *+ * `defaultRouting.js` owns the other half — resolving a saved route at enqueue+ * time, where it re-runs the full capacity preflight and fails closed. This+ * module owns the route's shape and the durable configuration policy, so the+ * settings route can refuse a bad route where the user is standing rather than+ * only where the job is.+ *+ * The distinction matters because the two failures look nothing alike. A route+ * naming a peer that is unknown, switched off, not enabled as a media provider,+ * not allowlisted for that exact model, or reachable outside the tailnet cannot+ * EVER run — it is not a transient capacity problem, it is a configuration that+ * has no working state. Saved unchecked, it persisted silently and then failed+ * every future Creative Director / Creative Commission render, one job at a+ * time, with nobody watching, because unattended work has no human at the+ * moment of failure. That is the "fail closed, never fail quiet" rule of #4679+ * applied one step earlier: refuse it at the save, where there IS a human.+ *+ * Only DURABLE configuration is checked here — never live capacity. A provider+ * peer is routinely asleep, busy, or mid-probe when its route is configured, so+ * gating the save on a fresh snapshot would make the feature unusable at+ * exactly the moment a user sits down to set it up. Freshness, queue admission,+ * and per-model readiness stay on the enqueue path, which re-checks all of them+ * (`assertFederatedMediaProviderSelection`) and re-checks the tailnet gate again+ * per request, since a peer's host can be edited after the route is saved.+ *+ * Clearing a route is ALWAYS allowed. A route saved before its peer changed+ * must stay removable, or a bad configuration becomes permanent.+ */++import { ServerError } from '../../lib/errorHandler.js';+import { isTailnetPeer } from '../../lib/tailnetPeer.js';++// 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. See the module docblock in+// defaultRouting.js.+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() : '');++/**+ * Normalize one route entry, or `null` when it is not a usable route.+ *+ * A half-written route is not a route. Requiring all three fields 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.+ */+export function sanitizeRoute(raw) {+ if (!isRecord(raw)) return null;+ const peerId = trimmed(raw.peerId);+ const engine = trimmed(raw.engine);+ const modelId = trimmed(raw.modelId);+ 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;+}++const reject = (message, code, status) => {+ throw new ServerError(message, { status, code });+};++/**+ * Refuse a `federation.mediaRouting` patch that names a route no enqueue could+ * ever honour.+ *+ * The rejection order mirrors `assertFederatedMediaProviderSelection` so the+ * user sees the same reason at save time that the enqueue would have given+ * them later, rather than two different vocabularies for one misconfiguration.+ *+ * @param {any} routing - The incoming `federation.mediaRouting` value.+ * @returns {Promise<void>} Resolves when every named route is savable.+ */+export async function assertMediaRoutingConfig(routing) {+ if (routing === null || routing === undefined) return;+ if (!isRecord(routing)) {+ reject('Unattended render routing must be an object', 'MEDIA_ROUTING_INVALID', 400);+ }+ // A kind sent as `null` is the user clearing that route, and a kind this+ // build cannot execute is not ours to police — neither reaches a peer, so+ // neither is checked. Only a route actually being SET is.+ const requested = ROUTABLE_MEDIA_KINDS+ .map((kind) => [kind, routing[kind]])+ .filter(([, raw]) => raw !== null && raw !== undefined);+ if (requested.length === 0) return;++ // Imported lazily for the same reason prepareRemoteMediaJob does it: a static+ // edge from the settings route to the peer registry would drag the registry+ // (and its socket-relay / sharing dependencies) into every settings-route+ // suite's module graph. Nothing here loads until a route is actually saved.+ const [{ getPeers }, { modelKey, normalizePeerMediaProviderConfig }] = await Promise.all([+ import('../instances.js'),+ import('../federatedMediaConsumer.js'),+ ]);+ const peers = await getPeers();++ for (const [kind, raw] of requested) {+ const route = sanitizeRoute(raw);+ if (!route) {+ reject(+ `The ${kind} route needs a peer, an engine, and a model`,+ 'MEDIA_ROUTING_INVALID',+ 400,+ );+ }+ const peer = peers.find((candidate) => candidate.id === route.peerId);+ if (!peer) {+ reject(+ `The peer named by the ${kind} route is not registered on this instance`,+ 'MEDIA_PROVIDER_PEER_NOT_FOUND',+ 404,+ );+ }+ const name = peer.name || peer.id;+ if (peer.enabled === false) {+ reject(`"${name}" is switched off, so it cannot take unattended ${kind} renders`, 'MEDIA_PROVIDER_PEER_DISABLED', 409);+ }+ const config = normalizePeerMediaProviderConfig(peer);+ if (!config.enabled) {+ reject(`"${name}" is not enabled as a media provider`, 'MEDIA_PROVIDER_NOT_CONFIGURED', 409);+ }+ const allowlist = config[`${kind}Models`] || [];+ if (!allowlist.some((model) => modelKey(model) === modelKey(route))) {+ reject(+ `"${route.modelId}" is not allowlisted for ${kind} on "${name}". Add it on that peer's card under Instances.`,+ 'MEDIA_PROVIDER_MODEL_NOT_ALLOWED',+ 403,+ );+ }+ // ADR docs/decisions/2026-08-20-federated-visual-prompts.md, rule 5. The+ // enqueue path checks this too and stays authoritative — a host edited from+ // a .ts.net name to a LAN address after the save must not carry a queued+ // job — but a route that can never satisfy it should not be storable in the+ // first place.+ if (!isTailnetPeer(peer)) {+ reject(+ `Unattended ${kind} routing requires a Tailscale peer — "${name}" is reachable outside the tailnet, `+ + 'so a standing route would export every future prompt over an unauthenticated hop.',+ 'MEDIA_ROUTING_PEER_NOT_TAILNET',+ 403,+ );+ }+ }+}diff --git a/server/services/federatedMedia/routingPolicy.test.js b/server/services/federatedMedia/routingPolicy.test.jsnew file mode 100644index 0000000000..4aef71675e--- /dev/null+++ b/server/services/federatedMedia/routingPolicy.test.js@@ -0,0 +1,172 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const getPeers = vi.fn();+vi.mock('../instances.js', () => ({ getPeers: (...args) => getPeers(...args) }));++import {+ assertMediaRoutingConfig,+ normalizeMediaRoutingConfig,+ sanitizeRoute,+} from './routingPolicy.js';++const ROUTE = { peerId: 'peer-1', engine: 'comfy', modelId: 'sdxl-base' };++const peerWith = (overrides = {}) => ({+ id: 'peer-1',+ name: 'Render Box',+ host: 'render-box.tailnet-example.ts.net',+ enabled: true,+ mediaProvider: {+ enabled: true,+ imageModels: [{ engine: 'comfy', modelId: 'sdxl-base' }],+ videoModels: [],+ },+ ...overrides,+});++// The assertion throws a ServerError; return its shape so each case can pin the+// code a user would actually see rather than just "it rejected".+const failureOf = async (routing, peers = [peerWith()]) => {+ getPeers.mockResolvedValue(peers);+ return assertMediaRoutingConfig(routing).then(+ () => null,+ (error) => ({ code: error.code, status: error.status, message: error.message }),+ );+};++beforeEach(() => {+ vi.clearAllMocks();+});++describe('sanitizeRoute', () => {+ it('trims a complete route', () => {+ expect(sanitizeRoute({ peerId: ' p ', engine: ' e ', modelId: ' m ' }))+ .toEqual({ peerId: 'p', engine: 'e', modelId: 'm' });+ });++ it('rejects a half-written route rather than resolving it to "peer, whatever model"', () => {+ for (const partial of [{ peerId: 'p' }, { peerId: 'p', engine: 'e' }, { engine: 'e', modelId: 'm' }, null, 'x']) {+ expect(sanitizeRoute(partial)).toBeNull();+ }+ });+});++describe('normalizeMediaRoutingConfig', () => {+ it('reports no route for a settings object that has none', () => {+ expect(normalizeMediaRoutingConfig(undefined)).toEqual({ image: null, video: null });+ expect(normalizeMediaRoutingConfig({ federation: {} })).toEqual({ image: null, video: null });+ });++ it('drops a kind this build cannot route', () => {+ const config = normalizeMediaRoutingConfig({+ federation: { mediaRouting: { audio: ROUTE, image: ROUTE } },+ });+ expect(config.image).toEqual(ROUTE);+ expect(config.audio).toBeUndefined();+ });+});++describe('assertMediaRoutingConfig — nothing to check', () => {+ it('accepts an absent or empty routing map without reading the peer registry', async () => {+ for (const routing of [undefined, null, {}, { image: null, video: null }]) {+ await expect(assertMediaRoutingConfig(routing)).resolves.toBeUndefined();+ }+ expect(getPeers).not.toHaveBeenCalled();+ });++ // The whole point of a fail-closed save gate is that it must never make a bad+ // configuration permanent: clearing has to work even when the peer behind the+ // old route is long gone.+ it('always allows clearing a route, even with no peers registered at all', async () => {+ getPeers.mockResolvedValue([]);+ await expect(assertMediaRoutingConfig({ image: null })).resolves.toBeUndefined();+ });++ it('ignores a kind this build cannot route', async () => {+ getPeers.mockResolvedValue([]);+ await expect(assertMediaRoutingConfig({ audio: ROUTE })).resolves.toBeUndefined();+ });+});++describe('assertMediaRoutingConfig — refuses a route that could never run', () => {+ it('accepts a route to an allowlisted model on an enabled tailnet provider', async () => {+ expect(await failureOf({ image: ROUTE })).toBeNull();+ });++ it('rejects a half-written route', async () => {+ expect(await failureOf({ image: { peerId: 'peer-1' } }))+ .toMatchObject({ code: 'MEDIA_ROUTING_INVALID', status: 400 });+ });++ it('rejects a peer that is not registered here', async () => {+ expect(await failureOf({ image: { ...ROUTE, peerId: 'ghost' } }))+ .toMatchObject({ code: 'MEDIA_PROVIDER_PEER_NOT_FOUND', status: 404 });+ });++ it('rejects a peer whose connection is switched off', async () => {+ expect(await failureOf({ image: ROUTE }, [peerWith({ enabled: false })]))+ .toMatchObject({ code: 'MEDIA_PROVIDER_PEER_DISABLED', status: 409 });+ });++ it('rejects a peer that is not enabled as a media provider', async () => {+ const peer = peerWith({ mediaProvider: { enabled: false, imageModels: [{ engine: 'comfy', modelId: 'sdxl-base' }] } });+ expect(await failureOf({ image: ROUTE }, [peer]))+ .toMatchObject({ code: 'MEDIA_PROVIDER_NOT_CONFIGURED', status: 409 });+ });++ it('rejects a model that is not allowlisted for that kind on that peer', async () => {+ expect(await failureOf({ image: { ...ROUTE, modelId: 'never-allowlisted' } }))+ .toMatchObject({ code: 'MEDIA_PROVIDER_MODEL_NOT_ALLOWED', status: 403 });+ });++ // The allowlist is keyed on the (engine, modelId) PAIR, so a matching model+ // id under a different engine is a different capability.+ it('rejects a matching model id under an engine that was never allowlisted', async () => {+ expect(await failureOf({ image: { ...ROUTE, engine: 'other-engine' } }))+ .toMatchObject({ code: 'MEDIA_PROVIDER_MODEL_NOT_ALLOWED', status: 403 });+ });++ it('rejects a kind whose allowlist is empty even though another kind has one', async () => {+ expect(await failureOf({ video: ROUTE }))+ .toMatchObject({ code: 'MEDIA_PROVIDER_MODEL_NOT_ALLOWED', status: 403 });+ });++ // ADR 2026-08-20-federated-visual-prompts rule 5.+ it('rejects a peer reachable outside the tailnet', async () => {+ const lanPeer = peerWith({ host: undefined, address: '192.0.2.10' });+ expect(await failureOf({ image: ROUTE }, [lanPeer]))+ .toMatchObject({ code: 'MEDIA_ROUTING_PEER_NOT_TAILNET', status: 403 });+ });++ it('accepts a CGNAT-addressed peer', async () => {+ expect(await failureOf({ image: ROUTE }, [peerWith({ host: undefined, address: '100.64.0.5' })]))+ .toBeNull();+ });++ it('checks every kind in the patch, not just the first', async () => {+ const peer = peerWith({+ mediaProvider: {+ enabled: true,+ imageModels: [{ engine: 'comfy', modelId: 'sdxl-base' }],+ videoModels: [],+ },+ });+ expect(await failureOf({ image: ROUTE, video: ROUTE }, [peer]))+ .toMatchObject({ code: 'MEDIA_PROVIDER_MODEL_NOT_ALLOWED' });+ });++ // Live capacity is deliberately NOT a save-time gate: a provider is routinely+ // asleep when its route is configured. The enqueue path re-checks it.+ it('saves a route to a peer that is currently offline with no capacity snapshot', async () => {+ const sleeping = peerWith({ status: 'offline', mediaProviderStatus: undefined });+ expect(await failureOf({ image: ROUTE }, [sleeping])).toBeNull();+ });++ it('saves a route to a peer whose last capacity probe went stale', async () => {+ const stale = peerWith({+ status: 'online',+ mediaProviderStatus: { state: 'stale', freshUntil: new Date(Date.now() - 60_000).toISOString() },+ });+ expect(await failureOf({ image: ROUTE }, [stale])).toBeNull();+ });+});diff --git a/server/services/federatedMediaConsumer.js b/server/services/federatedMediaConsumer.jsindex dd6073a82e..8cf2114e84 100644--- a/server/services/federatedMediaConsumer.js+++ b/server/services/federatedMediaConsumer.js@@ -23,7 +23,10 @@ export const DEFAULT_FEDERATED_MEDIA_PEER_CONFIG = Object.freeze({});const isRecord = (value) => value && typeof value === 'object' && !Array.isArray(value);-const modelKey = ({ engine, modelId }) => `${engine}\u0000${modelId}`;+// Exported so the standing-route save gate (federatedMedia/routingPolicy.js)+// compares an allowlist entry to a requested pair the same way this module+// does — the two must never disagree about what "allowlisted" means.+export const modelKey = ({ engine, modelId }) => `${engine}\u0000${modelId}`;function sanitizeModels(models, { preserveUnknown = false } = {}) {if (!Array.isArray(models)) return [];