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
refactor: make a published feature list authoritative and bind the client gates (#4826)
[._.]/ Adam Eivy029dfa4fbc16
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 5df4354a26..b90a248580 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -165,7 +165,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useCodeReviewDefaults` | Global Code Review Defaults (Review Loop reviewer chain + every per-reviewer `<reviewer>Model` / `<reviewer>Effort` pin scalar) via a small Provider/hook pair. | TaskAddForm, ScheduleTab, anywhere a default reviewer picker is shown. || `useCatalogTypes` | Catalog ingredient type registry (system + user-defined) merged with the static fallback via a Provider/hook pair; synchronous fallback to the built-in six so first render never blanks. | Catalog list/picker/editor; anywhere the catalog type list/lookup is needed. || `useDeathClock` | 1-second countdown for death-clock display. | Mortality / death-clock surfaces. |-| `useFederatedMediaTarget` | 'Render here, or on a peer?' for one media kind (#4348): loads the opted-in provider peers, intersects the local per-kind allowlist with the peer’s advertised capabilities, and resolves one readiness verdict via `resolvePeerMediaReadiness`. Returns the selection state plus `submissionFields` (`mediaProviderPeerId`/`mediaProviderEngine`/`modelId`), a `blockedReason` carrying the remedy, and `verify()` which re-runs the same gates against the clock at submit time. Never polls — a capacity window expires on the clock, so only the submit-time check is trustworthy. | Any render form offering a federated target: `RemoteMediaTargetPicker` in Image Gen, Video Gen, Music Studio. |+| `useFederatedMediaTarget` | 'Render here, or on a peer?' for one media kind (#4348): loads the opted-in provider peers, intersects the local per-kind allowlist with the peer’s advertised capabilities, and resolves one readiness verdict via `resolvePeerMediaReadiness`. Returns the selection state plus `submissionFields` (`mediaProviderPeerId`/`mediaProviderEngine`/`modelId`), a `blockedReason` carrying the remedy, and `verify()` which re-runs the same gates against the clock at submit time. `supports(feature)` and `acceptsInput(role)` are bound over the selected peer’s status snapshot so no form holds it directly — the underlying helpers take that status optionally and fall back to the pre-#4826 per-capability reading when it is omitted, which would fail open. Never polls — a capacity window expires on the clock, so only the submit-time check is trustworthy. | Any render form offering a federated target: `RemoteMediaTargetPicker` in Image Gen, Video Gen, Music Studio. || `useGoalDetail` | All state + handlers backing the GoalDetailPanel (edit form, todos, milestones, plan/phases, check-ins, progress log, activity/calendar links). Loads activities + subcalendars on mount. | GoalDetailPanel composition shell; not intended for reuse outside the goals panel. || `usePostSession` | MeatSpace POST drill-run state, refresh snapshots, scoring, and idempotent test/training saves. | POST launcher and drill runners. || `useRecordMerge` | Duplicate Universe/Series merge flow: open → dry-run preview → resolve field conflicts → execute, with an `onMerged` refresh callback. Drives `<MergeModal>`. | Surfacing the merge-duplicates UI anywhere (Sharing → Duplicates, Universes page). Don't re-implement the preview/execute dance. |diff --git a/client/src/hooks/useFederatedMediaTarget.js b/client/src/hooks/useFederatedMediaTarget.jsindex 402beb60f0..d812103e42 100644--- a/client/src/hooks/useFederatedMediaTarget.js+++ b/client/src/hooks/useFederatedMediaTarget.js@@ -24,6 +24,7 @@ import {federatedMediaSupports,peerMediaProviderConfig,peerMediaProviderSnapshot,+ peerModelAcceptsInput,resolvePeerMediaReadiness,summarizePeerMediaQueue,} from '../lib/federatedMediaReadiness.js';@@ -72,7 +73,7 @@ function blockingReason({ peer, models, model, kind, now }) {* peers: object[], peer: object|null, peerId: string, setPeerId: (id: string) => void,* models: object[], model: object|null, modelKey: string, setModelKey: (key: string) => void,* isRemote: boolean, readiness: object|null, queueSegments: string[],- * snapshot: object|null, supports: (feature: string) => boolean,+ * supports: (feature: string) => boolean, acceptsInput: (role: string) => boolean,* canSubmit: boolean, blockedReason: string|null,* submissionFields: object|null, verify: () => {ok: boolean, message?: string},* }}@@ -117,7 +118,9 @@ export function useFederatedMediaTarget(kind) {const readiness = useMemo(() => (peer ? resolvePeerMediaReadiness(peer) : null), [peer]);// The peer's own status payload, exposed so a form can ask what the peer's// BUILD speaks rather than re-deriving it from a per-capability field (#4826).- const snapshot = useMemo(() => peerMediaProviderSnapshot(peer), [peer]);+ // Not memoized: the helper returns the stored reference (or null) rather than+ // building anything, so its identity already tracks `peer`.+ const snapshot = peerMediaProviderSnapshot(peer);// Bound to the selected model so callers ask one question instead of two: the// root feature list, with the overlap fallback against a peer still on the// previous build. Fails closed on an absent status, like every gate here.@@ -125,6 +128,14 @@ export function useFederatedMediaTarget(kind) {(feature) => federatedMediaSupports(snapshot, feature, model),[snapshot, model],);+ // Bound for the same reason: `peerModelAcceptsInput`'s status argument is+ // optional and omitting it falls silently back to the pre-#4826 reading, so a+ // page that forgot to thread the snapshot would fail OPEN with nothing to+ // catch it. Nothing outside this hook needs to hold the snapshot at all.+ const acceptsInput = useCallback(+ (role) => peerModelAcceptsInput(model, role, snapshot),+ [snapshot, model],+ );const queueSegments = useMemo(() => (readiness ? summarizePeerMediaQueue(readiness.queue) : NO_SEGMENTS),[readiness],@@ -160,8 +171,8 @@ export function useFederatedMediaTarget(kind) {isRemote: Boolean(peer),readiness,queueSegments,- snapshot,supports,+ acceptsInput,canSubmit: Boolean(peer) && blockedReason === null,blockedReason,submissionFields,diff --git a/client/src/hooks/useFederatedMediaTarget.test.js b/client/src/hooks/useFederatedMediaTarget.test.jsnew file mode 100644index 0000000000..4512ddde7b--- /dev/null+++ b/client/src/hooks/useFederatedMediaTarget.test.js@@ -0,0 +1,108 @@+/**+ * The two capability questions this hook answers on the caller's behalf (#4826).+ *+ * `supports` and `acceptsInput` are bound closures over the selected peer's+ * status snapshot precisely so no form has to hold that snapshot itself. The+ * underlying `peerModelAcceptsInput` takes its status as an OPTIONAL third+ * argument, and omitting it falls silently back to the pre-#4826 reading — so a+ * page that reached for the raw helper would fail OPEN with nothing to catch+ * it. These cases are what make that binding load-bearing rather than stylistic.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest';+import { act, renderHook, waitFor } from '@testing-library/react';++const state = vi.hoisted(() => ({ peers: [] }));++vi.mock('../services/api', () => ({+ getInstances: vi.fn(async () => ({ peers: state.peers })),+}));++const { useFederatedMediaTarget } = await import('./useFederatedMediaTarget');++const CAPABILITY = {+ kind: 'image',+ engine: 'local',+ engineName: 'Local image',+ modelId: 'peer-flux',+ modelName: 'Example Model',+ ready: true,+ unavailableReason: null,+ runtimeReady: true,+ platformSupported: true,+ cudaRequired: false,+ cudaState: 'available',+ inputAssets: { roles: ['initImage'], required: false, maxCount: 4 },+};++const peer = ({ features, capability = CAPABILITY } = {}) => ({+ id: 'peer-example',+ name: 'Example GPU',+ status: 'online',+ enabled: true,+ mediaProvider: { enabled: true, imageModels: [{ engine: 'local', modelId: 'peer-flux' }] },+ mediaProviderStatus: {+ state: 'ready',+ checkedAt: new Date().toISOString(),+ freshUntil: new Date(Date.now() + 60_000).toISOString(),+ snapshot: {+ ...(features ? { features } : {}),+ queue: { accepting: true, running: 0, queued: 0, totalActive: 0, maxQueuedJobs: 4 },+ capabilities: [capability],+ },+ },+});++// Select the only opted-in peer and wait for its model to resolve, so the bound+// closures have something to close over.+const selectPeer = async () => {+ const { result } = renderHook(() => useFederatedMediaTarget('image'));+ await waitFor(() => expect(result.current.peers).toHaveLength(1));+ await act(async () => { result.current.setPeerId('peer-example'); });+ await waitFor(() => expect(result.current.model?.modelId).toBe('peer-flux'));+ return result;+};++describe('useFederatedMediaTarget — bound capability questions', () => {+ beforeEach(() => {+ state.peers = [];+ });++ it('reads a published feature list as the answer for both questions', async () => {+ state.peers = [peer({ features: ['lyrics', 'inputAssets'] })];+ const result = await selectPeer();+ expect(result.current.supports('inputAssets')).toBe(true);+ expect(result.current.acceptsInput('initImage')).toBe(true);+ // Advertised roles still gate per model — the build speaking conditioning+ // does not mean this model takes every slot.+ expect(result.current.acceptsInput('referenceImages')).toBe(false);+ });++ // The case a page could not get wrong once the closure is bound, and would+ // have gotten wrong by simply omitting the optional status argument.+ it('refuses conditioning when the peer published a list that omits it', async () => {+ state.peers = [peer({ features: ['lyrics'] })];+ const result = await selectPeer();+ expect(result.current.supports('inputAssets')).toBe(false);+ // The capability still carries a roles array; the peer's own vocabulary+ // overrules it, so the form must not offer the render.+ expect(result.current.acceptsInput('initImage')).toBe(false);+ });++ // The overlap release: a peer on the previous build publishes no list at all+ // and is read through the block it does send.+ it('falls back to the advertised block when no list was published', async () => {+ state.peers = [peer()];+ const result = await selectPeer();+ expect(result.current.supports('inputAssets')).toBe(true);+ expect(result.current.acceptsInput('initImage')).toBe(true);+ });++ it('answers false with no peer selected rather than throwing', async () => {+ const { result } = renderHook(() => useFederatedMediaTarget('image'));+ await act(async () => {});+ expect(result.current.isRemote).toBe(false);+ expect(result.current.supports('lyrics')).toBe(false);+ expect(result.current.acceptsInput('initImage')).toBe(false);+ });+});diff --git a/client/src/lib/federatedMediaReadiness.js b/client/src/lib/federatedMediaReadiness.jsindex 5c39113748..29985f8094 100644--- a/client/src/lib/federatedMediaReadiness.js+++ b/client/src/lib/federatedMediaReadiness.js@@ -152,6 +152,11 @@ const LEGACY_FEATURE_TELL = Object.freeze({* would offer a render the peer answers with a 400. Display only — the route* re-checks and the provider re-checks again at admission.*+ * A published list WINS over the legacy per-capability field rather than being+ * OR'd with it: a peer that told us its whole vocabulary and left this feature+ * out has positively denied it, so the legacy tell is consulted only when there+ * is no list to read. Mirrors the server rule exactly.+ ** @param {object|null} status - a peer's `mediaProviderStatus.snapshot`* @param {string} feature - 'lyrics' | 'inputAssets'* @param {object|null} [capability] - for the overlap fallback against a peer@@ -159,7 +164,7 @@ const LEGACY_FEATURE_TELL = Object.freeze({* @returns {boolean} false whenever the answer cannot be established*/export function federatedMediaSupports(status, feature, capability = null) {- if (Array.isArray(status?.features) && status.features.includes(feature)) return true;+ if (Array.isArray(status?.features)) return status.features.includes(feature);return LEGACY_FEATURE_TELL[feature]?.(capability) === true;}@@ -239,7 +244,7 @@ export function summarizePeerMediaQueue(queue) {export function resolvePeerMediaReadiness(peer, { now = Date.now() } = {}) {const config = peerMediaProviderConfig(peer);const status = isRecord(peer?.mediaProviderStatus) ? peer.mediaProviderStatus : null;- const snapshot = isRecord(status?.snapshot) ? status.snapshot : null;+ const snapshot = peerMediaProviderSnapshot(peer);// An unverifiable status does not get to keep whatever the probe concluded —// including the `ready` it concluded at probe time.const state = status ? verifiedState(status, now) : null;@@ -304,7 +309,7 @@ export function federatedMediaModelsForPeer(peer, kind) {.filter((model) => model?.engine && model?.modelId).map(federatedMediaModelKey));if (allowed.size === 0) return NO_CAPABILITIES;- const advertised = peer?.mediaProviderStatus?.snapshot?.capabilities;+ const advertised = peerMediaProviderSnapshot(peer)?.capabilities;if (!Array.isArray(advertised)) return NO_CAPABILITIES;const matched = advertised.filter((capability) => capability?.kind === kind&& allowed.has(federatedMediaModelKey(capability)));diff --git a/client/src/lib/federatedMediaReadiness.test.js b/client/src/lib/federatedMediaReadiness.test.jsindex 20983ce025..17f87ec087 100644--- a/client/src/lib/federatedMediaReadiness.test.js+++ b/client/src/lib/federatedMediaReadiness.test.js@@ -364,6 +364,11 @@ describe('peerModelAcceptsInput / peerModelRequiresInput', () => {// treated as a denial.const model = withInput({ roles: ['initImage'], required: false, maxCount: 8 });expect(peerModelAcceptsInput(model, 'initImage', { features: ['inputAssets'] })).toBe(true);+ // A peer that published its vocabulary and left conditioning out has said+ // no, and its capability block does not get to overrule that.+ expect(peerModelAcceptsInput(model, 'initImage', { features: ['lyrics'] })).toBe(false);+ // A peer that published no list at all is read through the block it did+ // send, which is how the pre-migration build keeps working.expect(peerModelAcceptsInput(model, 'initImage', {})).toBe(true);// The build speaks it; this model simply takes nothing.expect(peerModelAcceptsInput(withInput(null), 'initImage', { features: ['inputAssets'] })).toBe(false);@@ -404,8 +409,14 @@ describe('federatedMediaSupports / peerMediaProviderSnapshot', () => {it('reads the status-root list, and falls back to the legacy per-capability field', () => {expect(federatedMediaSupports({ features: ['lyrics'] }, 'lyrics')).toBe(true);expect(federatedMediaSupports({}, 'lyrics', { ...capability, acceptsLyrics: true })).toBe(true);+ // List wins: a published vocabulary that omits the feature overrules the+ // legacy field rather than being OR'd with it.+ expect(federatedMediaSupports({ features: [] }, 'lyrics', { ...capability, acceptsLyrics: true })).toBe(false);expect(federatedMediaSupports({}, 'inputAssets', { inputAssets: { roles: [] } })).toBe(true);expect(federatedMediaSupports({}, 'inputAssets', { inputAssets: null })).toBe(false);+ // Pinned identically in server/lib/federatedMediaWire.test.js: an array is+ // not a block, and the two ends must not disagree on a malformed one.+ expect(federatedMediaSupports({}, 'inputAssets', { inputAssets: [] })).toBe(false);});it('returns the peer snapshot only when one is actually stored', () => {diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex 6adcf0991e..012c2b18a1 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -43,7 +43,7 @@ import {import { composeStyledPrompt } from '../lib/composeStyledPrompt';import { isCloudCliMode, deriveAvailableBackends, AGY_IMAGEGEN_DEFAULT_MODEL, IMAGE_GEN_MODE, cloudPromptRequired, isI2iCapableMode, pickI2iMode, modeLabel, referenceSlotsFor, supportsReferenceStrength } from '../lib/imageGenBackends';import { clampImageDimensions, clampImageEdge } from '../lib/imageGenResolutions';-import { peerModelAcceptsInput, peerModelRequiresInput } from '../lib/federatedMediaReadiness.js';+import { peerModelRequiresInput } from '../lib/federatedMediaReadiness.js';import { DEFAULT_NEGATIVE_PROMPT } from '../lib/imageGenDefaults';import { resolveCleanersFromConfig } from '../lib/imageCleaners';import toast from '../components/ui/Toast';@@ -694,8 +694,8 @@ export default function ImageGen() {if (!remoteTarget.isRemote) return null;const model = remoteTarget.model;const present = [- ['an init image', initImage.source != null && !peerModelAcceptsInput(model, 'initImage', remoteTarget.snapshot)],- ['reference images', populatedRefs.length > 0 && !peerModelAcceptsInput(model, 'referenceImages', remoteTarget.snapshot)],+ ['an init image', initImage.source != null && !remoteTarget.acceptsInput('initImage')],+ ['reference images', populatedRefs.length > 0 && !remoteTarget.acceptsInput('referenceImages')],['LoRA weights', selectedLoras.length > 0],].filter(([, set]) => set).map(([label]) => label);if (present.length) {@@ -708,7 +708,7 @@ export default function ImageGen() {return `${model?.modelName || 'The selected peer model'} renders only from a source image — add an init image, or pick a text-to-image model.`;}return null;- }, [remoteTarget.isRemote, remoteTarget.model, remoteTarget.snapshot, initImage.source, populatedRefs.length, selectedLoras.length]);+ }, [remoteTarget.isRemote, remoteTarget.model, remoteTarget.acceptsInput, initImage.source, populatedRefs.length, selectedLoras.length]);// One reading for the submit button and the picker caption alike.const remoteBlocked = remoteTarget.isRemote? (remoteTarget.blockedReason || remoteUnsupportedInputs)diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex c3ad22ea03..badca2179b 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -98,7 +98,7 @@ import { GROK_VIDEO_DURATIONS, GROK_VIDEO_DEFAULT_DURATION } from '../lib/grokViimport ResolutionField from '../components/media/ResolutionField';import { VIDEO_EDGE_BOUNDS, videoEdgeBoundsForModel, IC_LORA_MODES } from '../lib/videoGenParams.js';import { finishTargetForRecord } from '../lib/videoFinish.js';-import { peerModelAcceptsInput, peerModelRequiresInput } from '../lib/federatedMediaReadiness.js';+import { peerModelRequiresInput } from '../lib/federatedMediaReadiness.js';const MODES = [{ id: 'text', label: 'Text', icon: Type, desc: 'Text-to-video' },{ id: 'image', label: 'Image', icon: ImageIcon, desc: 'Image-to-video (start frame)' },@@ -206,8 +206,8 @@ export default function VideoGen() {// mode can be set before that input is filled — so gate the mode too// rather than letting an a2v render reach the peer as plain text-to-video.[`${mode} mode`, ![undefined, 'text', 'image', 'fflf'].includes(mode)],- ['a source image', !!sourceImageFile && !peerModelAcceptsInput(model, 'sourceImage', remoteTarget.snapshot)],- ['an end frame', !!lastImageFile && !peerModelAcceptsInput(model, 'lastImage', remoteTarget.snapshot)],+ ['a source image', !!sourceImageFile && !remoteTarget.acceptsInput('sourceImage')],+ ['an end frame', !!lastImageFile && !remoteTarget.acceptsInput('lastImage')],['an uploaded frame (save it to the gallery first)', !!sourceImageUpload || !!lastImageUpload],['keyframes', keyframesActive],['a source clip to extend', !!extendFromVideoId],@@ -228,7 +228,7 @@ export default function VideoGen() {return `${model?.modelName || 'The selected peer model'} renders only from a source image — add a start frame, or pick a text-to-video model.`;}return null;- }, [remoteTarget.isRemote, remoteTarget.model, remoteTarget.snapshot, isGrok, mode, sourceImageFile, sourceImageUpload,+ }, [remoteTarget.isRemote, remoteTarget.model, remoteTarget.acceptsInput, isGrok, mode, sourceImageFile, sourceImageUpload,lastImageFile, lastImageUpload, keyframesActive, extendFromVideoId, audioFile, icReferenceFile,icReferenceVideoId, icReferenceImageFiles, selectedLoras, chunks]);// One reading for the Generate button, the enqueue guard and the caption.diff --git a/server/lib/README.md b/server/lib/README.mdindex e4ae7e8010..fb65bf8a26 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -255,7 +255,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `fetchWithTimeout.js` | `fetch` wrapper with AbortController timeout. || `tailnetPeer.js` | `isTailnetPeer(peer)` — fail-closed security predicate for "is this peer reachable only over the tailnet". Deliberately separate from `instances.js`'s `peerRequiresTailscale()` probe-deferral heuristic so a polling-noise tweak can't widen a privacy boundary; required by the unattended-routing gate in ADR 2026-08-20-federated-visual-prompts. || `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). `FEDERATED_MEDIA_FEATURES` + `federatedMediaSupports(status, feature, capability)` answer "does the peer BUILD speak this wire feature" from the status-root `features` list — the one place the "absent reads as the wire-v1 baseline" rule lives, with an overlap fallback to the legacy per-capability field. |+| `federatedMediaWire.js` | Versioned federated-media status schema/constants plus fail-closed consumer freshness checks (stale and clock-skewed snapshots are never assignable). `FEDERATED_MEDIA_FEATURES` + `federatedMediaSupports(status, feature, capability)` answer "does the peer BUILD speak this wire feature" from the status-root `features` list — the one place the "absent reads as the wire-v1 baseline" rule lives; a published list wins outright, with the legacy per-capability field consulted only when a peer published none. `federatedMediaDeclaresFeatures(status)` and `federatedMediaDeniesFeature(status, feature, capability)` separate "positively denied" from "could not establish" for MESSAGE selection only — both gate identically, and which missing signal indicts the peer’s build is recorded per feature rather than at each call site. || `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. || `pinterestFeed.js` | Pure Pinterest board RSS helpers: `normalizePinterestFeedUrl(input)` (board URL or `.rss` → `{ feedUrl, boardUrl }`, host-gated) + `parsePinterestRss(xml)` (per-pin `pinUrl`/`imageUrl`/title/description, 736x size upgrade). Feeds the mood-board Pinterest importer. |diff --git a/server/lib/federatedMediaWire.js b/server/lib/federatedMediaWire.jsindex ce1f91c8d2..d59b63c897 100644--- a/server/lib/federatedMediaWire.js+++ b/server/lib/federatedMediaWire.js@@ -1,5 +1,6 @@import { createHash } from 'node:crypto';import { z } from 'zod';+import { isPlainObject } from './objects.js';export const FEDERATED_MEDIA_WIRE_VERSION = 1;export const FEDERATED_MEDIA_STALE_AFTER_MS = 60_000;@@ -373,13 +374,34 @@ const federatedMediaFeatureSchema = z.string().regex(/^[a-zA-Z][a-zA-Z0-9]{0,39}// consumer degrades to something it can explain instead.//// `capability` is the OVERLAP path only: for one release a provider on the-// previous build advertises the same build-level fact per-capability, so a-// consumer reads the root list first and falls back to the legacy field.+// previous build advertises the same build-level fact per-capability. A+// published list WINS over it outright rather than being OR'd with it — a peer+// that told us its whole vocabulary and left this feature out has positively+// denied it, and honoring a stale or contradictory per-capability field against+// that would resurrect the very ambiguity the list replaced. The legacy tell is+// consulted only when there is no list to read.+// `decisive` records whether a FAILING legacy tell proves the peer's build is+// old, and it differs per feature — which is why it belongs in the table rather+// than in a comment at each call site (whoever adds the third feature would+// otherwise inherit whichever policy they happened to read first):+//+// lyrics — the previous build stamped `acceptsLyrics` on EVERY audio+// capability, so its absence can only mean an older build.+// inputAssets — the block is genuinely per-model, so its absence is ambiguous:+// mid-overlap the peer may speak conditioning and simply have a+// text-only model configured.+//+// Both gate identically; only a message that blames the BUILD may distinguish+// them. See federatedMediaDeniesFeature.const FEDERATED_MEDIA_LEGACY_FEATURE_TELL = Object.freeze({- lyrics: (capability) => capability?.acceptsLyrics === true,+ lyrics: { tell: (capability) => capability?.acceptsLyrics === true, decisive: true },// A build that predates conditioning omits the block entirely; one that// speaks it advertises the block (possibly with no roles for this model).- inputAssets: (capability) => !!capability?.inputAssets && typeof capability.inputAssets === 'object',+ // `isPlainObject`, not a bare `typeof === 'object'`: the client mirror uses+ // its own array-excluding record guard, and a malformed `inputAssets: []`+ // reading true here and false there is exactly the provider/consumer+ // disagreement this helper exists to prevent.+ inputAssets: { tell: (capability) => isPlainObject(capability?.inputAssets), decisive: false },});/**@@ -392,8 +414,40 @@ const FEDERATED_MEDIA_LEGACY_FEATURE_TELL = Object.freeze({* @returns {boolean} false whenever the answer cannot be established*/export function federatedMediaSupports(status, feature, capability = null) {- if (Array.isArray(status?.features) && status.features.includes(feature)) return true;- return FEDERATED_MEDIA_LEGACY_FEATURE_TELL[feature]?.(capability) === true;+ if (federatedMediaDeclaresFeatures(status)) return status.features.includes(feature);+ return FEDERATED_MEDIA_LEGACY_FEATURE_TELL[feature]?.tell(capability) === true;+}++/**+ * Did this provider publish its feature vocabulary at all?+ *+ * @param {object|null} status - a validated provider status payload+ * @returns {boolean}+ */+export function federatedMediaDeclaresFeatures(status) {+ return Array.isArray(status?.features);+}++/**+ * Is this a denial we can attribute to the peer's BUILD, rather than merely an+ * answer we could not establish?+ *+ * `federatedMediaSupports` flattens two different "no"s, because both must gate+ * the same way: a peer that published a list and left the feature out has+ * POSITIVELY denied it, while a peer that published no list may simply predate+ * the list — or, for an ambiguous feature, speak it and have nothing configured+ * that uses it. Only a MESSAGE may distinguish them, and telling a healthy peer+ * to update itself is worse than giving the generic remedy.+ *+ * @param {object|null} status - a validated provider status payload+ * @param {string} feature - a FEDERATED_MEDIA_FEATURES member+ * @param {object|null} [capability] - the capability being acted on+ * @returns {boolean} true only when the peer's build is provably the reason+ */+export function federatedMediaDeniesFeature(status, feature, capability = null) {+ if (federatedMediaSupports(status, feature, capability)) return false;+ return federatedMediaDeclaresFeatures(status)+ || FEDERATED_MEDIA_LEGACY_FEATURE_TELL[feature]?.decisive === true;}// Strip unknown fields from peer responses before persisting or exposing themdiff --git a/server/lib/federatedMediaWire.test.js b/server/lib/federatedMediaWire.test.jsindex 38142cce6b..89a86c1d9a 100644--- a/server/lib/federatedMediaWire.test.js+++ b/server/lib/federatedMediaWire.test.js@@ -2,6 +2,8 @@ import { describe, expect, it } from 'vitest';import {FEDERATED_MEDIA_FEATURES,federatedMediaAudioProfileSchema,+ federatedMediaDeclaresFeatures,+ federatedMediaDeniesFeature,federatedMediaCapabilitySchema,federatedMediaProviderStatusSchema,federatedMediaProviderJobSchema,@@ -244,7 +246,7 @@ describe('federated media status kind projection', () => {expect(bad(['x'.repeat(41)])).toBe(false);});- it('rejects a concurrency that claims no capacity at all', () => {+ it('rejects a concurrency that claims no capacity at all', () => {expect(federatedMediaProviderStatusSchema.safeParse(status({queue: { ...status().queue, concurrency: 0 },})).success).toBe(false);@@ -345,11 +347,49 @@ describe('federatedMediaSupports', () => {// The overlap release: a peer on the previous build sends the per-capability// field and no root list, and must keep working unchanged.- it('falls back to the legacy per-capability field', () => {+ it('falls back to the legacy per-capability field only when no list was published', () => {expect(federatedMediaSupports({}, 'lyrics', capability({ acceptsLyrics: true }))).toBe(true);+ // A peer that published its vocabulary and left the feature out has+ // positively denied it; a stale or contradictory legacy field on the+ // capability does not get to overrule that.+ expect(federatedMediaSupports({ features: [] }, 'lyrics', capability({ acceptsLyrics: true }))).toBe(false);+ expect(federatedMediaSupports({ features: ['inputAssets'] }, 'lyrics', capability({ acceptsLyrics: true }))).toBe(false);expect(federatedMediaSupports({}, 'lyrics', capability({ acceptsLyrics: false }))).toBe(false);expect(federatedMediaSupports({}, 'inputAssets', capability({ inputAssets: { roles: ['initImage'] } }))).toBe(true);expect(federatedMediaSupports({}, 'inputAssets', capability({ inputAssets: null }))).toBe(false);+ // An array is not a block. The client mirror's record guard excludes+ // arrays, so a bare `typeof === 'object'` here would have the two ends+ // disagreeing on a malformed capability — pinned on both sides.+ expect(federatedMediaSupports({}, 'inputAssets', capability({ inputAssets: [] }))).toBe(false);+ });++ // The tri-state `federatedMediaSupports` flattens: "published a list without+ // this feature" is a positive denial, "published no list" is undecidable.+ // Only a message that blames the peer's build may distinguish them.+ it('separates a published vocabulary from silence', () => {+ expect(federatedMediaDeclaresFeatures({ features: [] })).toBe(true);+ expect(federatedMediaDeclaresFeatures({})).toBe(false);+ expect(federatedMediaDeclaresFeatures(null)).toBe(false);+ expect(federatedMediaDeclaresFeatures({ features: 'lyrics' })).toBe(false);+ });++ // Gating is identical for both "no"s; only a MESSAGE may distinguish them,+ // and which missing signal indicts the peer's build differs per feature.+ it('attributes a denial to the build only where the missing signal proves it', () => {+ const withBlock = capability({ inputAssets: { roles: ['initImage'] } });+ // A published list that omits the feature is a positive denial either way.+ expect(federatedMediaDeniesFeature({ features: [] }, 'lyrics', capability())).toBe(true);+ expect(federatedMediaDeniesFeature({ features: ['lyrics'] }, 'inputAssets', withBlock)).toBe(true);+ // No list: the previous build stamped acceptsLyrics on EVERY audio+ // capability, so its absence can only mean an older build...+ expect(federatedMediaDeniesFeature({}, 'lyrics', capability())).toBe(true);+ // ...while an absent inputAssets block is ambiguous — a healthy peer may+ // speak conditioning and simply have a text-only model configured, so it+ // must not be told to update itself.+ expect(federatedMediaDeniesFeature({}, 'inputAssets', capability({ inputAssets: null }))).toBe(false);+ // Never a denial when the feature is actually supported.+ expect(federatedMediaDeniesFeature({ features: ['lyrics'] }, 'lyrics', capability())).toBe(false);+ expect(federatedMediaDeniesFeature({}, 'inputAssets', withBlock)).toBe(false);});it('exposes every feature this build emits, and answers false for anything else', () => {diff --git a/server/routes/music.js b/server/routes/music.jsindex 21c44aa064..a14689f586 100644--- a/server/routes/music.js+++ b/server/routes/music.js@@ -43,6 +43,7 @@ import { getCudaCapability } from '../lib/cudaCapability.js';import {FEDERATED_MEDIA_WIRE_VERSION,federatedMediaAudioProfileSchema,+ federatedMediaDeniesFeature,federatedMediaSupports,} from '../lib/federatedMediaWire.js';import { enqueueJob, listJobs } from '../services/mediaJobQueue/index.js';@@ -468,8 +469,14 @@ router.post('/generate', asyncHandler(async (req, res) => {);}if (!federatedMediaSupports(resolved.status, 'lyrics', capability)) {+ // Blaming the peer's build is safe for THIS feature — the previous+ // build stamped the legacy tell on every audio capability, so its+ // absence can only mean an older one. `federatedMediaDeniesFeature`+ // is what records that, per feature, rather than this call site.throw new ServerError(- 'The selected peer runs a PortOS build that cannot carry lyrics to its provider. Update the peer, or render this track locally.',+ federatedMediaDeniesFeature(resolved.status, 'lyrics', capability)+ ? 'The selected peer runs a PortOS build that cannot carry lyrics to its provider. Update the peer, or render this track locally.'+ : 'The selected peer is not reporting that it can carry lyrics to its provider. Render this track locally, or pick a lyric-capable peer.',{ status: 400, code: 'MEDIA_PROVIDER_LYRICS_UNSUPPORTED' },);}diff --git a/server/services/federatedMedia/inputAssets.js b/server/services/federatedMedia/inputAssets.jsindex 4727d42acd..17ab90b2ed 100644--- a/server/services/federatedMedia/inputAssets.js+++ b/server/services/federatedMedia/inputAssets.js@@ -33,6 +33,7 @@ import {FEDERATED_MEDIA_INPUT_ROLES,federatedMediaAssetId,federatedMediaAssetSchema,+ federatedMediaDeniesFeature,federatedMediaSupports,isMultiInputRole,} from '../../lib/federatedMediaWire.js';@@ -111,13 +112,17 @@ export function inputAssetRejection(capability, assets = [], status = null) {? `${model} renders only from a source image — add one, or pick a ${textToKind} model.`: null;}- if (!limits) {- // The build-level remedy fires only when the peer POSITIVELY published its- // vocabulary and this feature is not in it. A peer that sent no list at all- // is undecidable — mid-overlap it may speak conditioning and simply have- // only text-only models allowlisted — so it keeps the merged message rather- // than being accused of running an old build on no evidence.- return Array.isArray(status?.features) && !federatedMediaSupports(status, 'inputAssets', capability)+ // Both halves, in the same order the client's `peerModelAcceptsInput` checks+ // them: the BUILD has to carry conditioning at all, and THIS MODEL has to+ // advertise a block. Gating on the block alone would admit a job a peer that+ // published a vocabulary without `inputAssets` then answers with a 400 —+ // and would leave this end more permissive than the UI that fronts it.+ if (!limits || !federatedMediaSupports(status, 'inputAssets', capability)) {+ // Which remedy is a MESSAGE decision, not a gating one, so it asks the+ // shared policy rather than restating when a missing signal indicts the+ // peer's build. For conditioning it does not: mid-overlap a healthy peer+ // may speak it and simply have only text-only models allowlisted.+ return federatedMediaDeniesFeature(status, 'inputAssets', capability)? 'The selected peer runs a PortOS build that cannot carry conditioning images. Update the peer, or render locally.': `${model} on this peer does not accept source or reference images. Render locally, or pick a peer model that does.`;}diff --git a/server/services/federatedMediaProvider.test.js b/server/services/federatedMediaProvider.test.jsindex 78d5bed7d3..3bd150e7cf 100644--- a/server/services/federatedMediaProvider.test.js+++ b/server/services/federatedMediaProvider.test.js@@ -306,13 +306,6 @@ describe('federated media provider capacity and idempotency', () => {expect(status.capabilities[0].lyrics).toBe(false);});- it('emits a features copy a consumer cannot mutate back into the module constant', async () => {- const status = await getFederatedMediaProviderStatus(config());- status.features.push('holoProjection');- expect((await getFederatedMediaProviderStatus(config())).features)- .toEqual(['lyrics', 'inputAssets']);- });-it('renders lyrics on a lyric-capable model and advertises that its wire accepts them', async () => {await submitFederatedMediaJob({callerId: 'peer-example', config: config(),