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
send an init image, reference images, or a video start/end frame to a peer (#4348)
[._.]/ Adam Eivy88608cda29b1
diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 8a8b2e3e6b..f3756ddcf4 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -44,7 +44,7 @@ grep -i "what you want to do" client/src/lib/README.md| `creativeDirectorPlan.js` | Pure presentation helpers for the CD studio Plan board (CDO Phase 4) — annotate `plan.steps[]` with tool cost-class/timing/approval flags, cost/status summaries, owning-surface deep links, status/cost badge tone maps. || `creativeDirectorPreview.js` | `selectProjectPreview(project)` → `{ kind: 'video'\|'image'\|'audio'\|'none', jobId?, src?, poster?, label, durationSec? }` — picks a CD project's representative produced asset (finalVideoId → last rendered scene → last done plan video/image step → `musicBed` audio → startingImageFile) for the list cards + Overview tab (#2702, audio #2772). Pure, computed off the already-returned project payload (no fetch). Plus `previewAspectClass(aspectRatio)` (literal Tailwind classes — a computed `aspect-[w/h]` never lands in the build), `startingImageSrc()` (client mirror of `localImageFilename`), and the `videoSrcForJob`/`videoPosterForJob`/`imageSrcForJob`/`musicBedSrc` path builders — the one client-side definition of the `<jobId>`-named asset convention, shared with `ScenePreview.jsx`. || `editorialRoadmap.js` | `projectAnalyzedPoints` (aggregate roadmap → analyzed chart points with arc-position `frac`) + `dominant` (most-frequent string). Shared by EditorialRoadmapPanel and the Reader Map page. |-| `federatedMediaReadiness.js` | One reading of a peer’s federated media-provider readiness (#4348), shared by the Instances peer card and the System Health capacity panel so the two cannot disagree. `resolvePeerMediaReadiness(peer, { now })` maps the stored probe onto a display state/label/tone plus its remedy text, queue snapshot, capabilities, and per-kind allowlists; it re-derives `stale` when the snapshot’s `freshUntil` has passed, so a snapshot probed as `ready` cannot keep reading `ready` after the server would refuse to submit against it. Also exports `FEDERATED_MEDIA_KINDS` (audio/image/video + their config fields and icons), the state/help tables, and `peerMediaProviderConfig`. `summarizePeerMediaQueue(queue)` renders the peer’s queue block into finished display segments — slot occupancy, how many jobs drain in parallel, and which kinds are busy — so every surface shows the same words, dropping any segment an older provider did not send rather than showing it as a zero. `federatedMediaModelsForPeer(peer, kind)` intersects the local per-kind allowlist with the peer’s advertised capabilities and returns the capability entries (with their `ready` / `unavailableReason`), so no surface can offer a model the server would refuse or hide why a listed one cannot run. Display only — the server re-probes and fail-closes before any job leaves. |+| `federatedMediaReadiness.js` | One reading of a peer’s federated media-provider readiness (#4348), shared by the Instances peer card and the System Health capacity panel so the two cannot disagree. `resolvePeerMediaReadiness(peer, { now })` maps the stored probe onto a display state/label/tone plus its remedy text, queue snapshot, capabilities, and per-kind allowlists; it re-derives `stale` when the snapshot’s `freshUntil` has passed, so a snapshot probed as `ready` cannot keep reading `ready` after the server would refuse to submit against it. Also exports `FEDERATED_MEDIA_KINDS` (audio/image/video + their config fields and icons), the state/help tables, and `peerMediaProviderConfig`. `summarizePeerMediaQueue(queue)` renders the peer’s queue block into finished display segments — slot occupancy, how many jobs drain in parallel, and which kinds are busy — so every surface shows the same words, dropping any segment an older provider did not send rather than showing it as a zero. `federatedMediaModelsForPeer(peer, kind)` intersects the local per-kind allowlist with the peer’s advertised capabilities and returns the capability entries (with their `ready` / `unavailableReason`), so no surface can offer a model the server would refuse or hide why a listed one cannot run. `peerModelAcceptsInput(capability, role)` / `peerModelRequiresInput(capability)` read the capability’s `inputAssets` block — which conditioning slots (`initImage` / `referenceImages` / `sourceImage` / `lastImage`) a peer model takes, and whether it can render without one — with **absent reading as NO**, so a provider predating that field is never offered a render it would reject. Display only — the server re-probes and fail-closes before any job leaves. || `glbFailure.js` | Turns a 3D asset failure into an actionable sentence. `glbFailureHint(error)` matches the message against a shared table (an HTML body reaching the glTF parser, a WebGL context failure, a 404) and returns `null` when nothing recognizes it — so a caller can tell "we know the cause" from "we don't" and fall back to the raw text. `glbErrorText(error)` reads a message off whatever shape was thrown. Shared because the CoS avatars load remote GLBs too: every caught error there used to be reported as "this display has no WebGL", sending the user to change an unrelated setting (#4688). Consumed by `media/GlbViewer.jsx` and `cos/CoSCanvasGuard.jsx`. || `grokVideoClip.js` | Mirror of `server/lib/grokVideoClip.js` — `GROK_VIDEO_DURATIONS` (`[6, 10]`) + `GROK_VIDEO_DEFAULT_DURATION`, the clip lengths grok's `image_to_video` actually delivers. || `imageCleaners.js` | Mirror of `resolveCleanersFromConfig` from `server/lib/imageClean.js`. Reads `{cleanC2PA, denoise}` off a per-mode settings record. `cleanC2PA` defaults are mode-aware (on for `codex` + `external` — the backends that emit C2PA chunks today — off otherwise, as an allow-list rather than a deny-list); `denoise` defaults off everywhere (lossy, opt-in only). |diff --git a/client/src/lib/federatedMediaReadiness.js b/client/src/lib/federatedMediaReadiness.jsindex c1e87ab677..d895eee0f8 100644--- a/client/src/lib/federatedMediaReadiness.js+++ b/client/src/lib/federatedMediaReadiness.js@@ -270,3 +270,37 @@ export function federatedMediaModelsForPeer(peer, kind) {&& allowed.has(federatedMediaModelKey(capability)));return matched.length > 0 ? matched : NO_CAPABILITIES;}++/**+ * Does this advertised capability accept a conditioning image in `role`+ * (`initImage` / `referenceImages` / `sourceImage` / `lastImage`)?+ *+ * **Absent reads as NO.** A provider built before ADR+ * `docs/decisions/2026-08-22-federated-media-input-assets.md` omits the+ * `inputAssets` block entirely and rejects the fields, so treating a missing+ * block as unrestricted would offer a render the peer answers with a 400. Same+ * fail-closed rule the queue-capacity fields follow.+ *+ * Mirrors the server's `inputAssetRejection`+ * (`server/services/federatedMedia/inputAssets.js`) — display only; the route+ * re-checks and the provider re-checks again at admission.+ *+ * @param {object|null} capability - an entry from `federatedMediaModelsForPeer`+ * @param {string} role+ * @returns {boolean}+ */+export function peerModelAcceptsInput(capability, role) {+ const roles = capability?.inputAssets?.roles;+ return Array.isArray(roles) && roles.includes(role);+}++/**+ * Can this model render nothing at all without a conditioning image? True for+ * an edit-only image model or a video model with no text-to-video mode — both+ * are advertisable only because conditioning now crosses, so a text-only+ * submission to one is refused rather than queued.+ *+ * @param {object|null} capability+ * @returns {boolean}+ */+export const peerModelRequiresInput = (capability) => capability?.inputAssets?.required === true;diff --git a/client/src/lib/federatedMediaReadiness.test.js b/client/src/lib/federatedMediaReadiness.test.jsindex 81f347941a..0f8e61612b 100644--- a/client/src/lib/federatedMediaReadiness.test.js+++ b/client/src/lib/federatedMediaReadiness.test.js@@ -5,6 +5,8 @@ import {federatedMediaModelKey,federatedMediaModelsForPeer,peerMediaProviderConfig,+ peerModelAcceptsInput,+ peerModelRequiresInput,resolvePeerMediaReadiness,summarizePeerMediaQueue,} from './federatedMediaReadiness.js';@@ -338,3 +340,37 @@ describe('federatedMediaModelsForPeer', () => {expect(federatedMediaModelsForPeer(withCapabilities([], []), 'audio')).toBe(empty);});});++// ADR docs/decisions/2026-08-22-federated-media-input-assets.md rule 1. The+// fail-closed reading is the whole point: a provider built before that ADR+// advertises no `inputAssets` block AND rejects the fields, so an absent block+// read as "unrestricted" would offer a render the peer answers with a 400.+describe('peerModelAcceptsInput / peerModelRequiresInput', () => {+ const withInput = (inputAssets) => ({ modelName: 'Example', inputAssets });++ it('accepts only the roles the capability actually advertises', () => {+ const model = withInput({ roles: ['initImage'], required: false, maxCount: 8 });+ expect(peerModelAcceptsInput(model, 'initImage')).toBe(true);+ expect(peerModelAcceptsInput(model, 'referenceImages')).toBe(false);+ });++ it.each([+ ['an absent block (a provider predating the ADR)', undefined],+ ['an explicit null', null],+ ['a block with no roles array', { required: false }],+ ['a malformed roles value', { roles: 'initImage' }],+ ])('reads %s as accepting nothing', (_name, inputAssets) => {+ expect(peerModelAcceptsInput(withInput(inputAssets), 'initImage')).toBe(false);+ expect(peerModelRequiresInput(withInput(inputAssets))).toBe(false);+ });++ it('reports a model that cannot render without conditioning', () => {+ expect(peerModelRequiresInput(withInput({ roles: ['initImage'], required: true }))).toBe(true);+ expect(peerModelRequiresInput(withInput({ roles: ['initImage'], required: false }))).toBe(false);+ });++ it('tolerates a null capability rather than throwing on an unpicked model', () => {+ expect(peerModelAcceptsInput(null, 'initImage')).toBe(false);+ expect(peerModelRequiresInput(null)).toBe(false);+ });+});diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex e9e37d7dd3..4e476956e7 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -43,6 +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 { DEFAULT_NEGATIVE_PROMPT } from '../lib/imageGenDefaults';import { resolveCleanersFromConfig } from '../lib/imageCleaners';import toast from '../components/ui/Toast';@@ -677,23 +678,37 @@ export default function ImageGen() {() => referenceImages.slice(referenceSlotCount).filter((s) => s.file != null).length,[referenceImages, referenceSlotCount],);- // What this form is holding that the federated wire cannot carry. The server- // refuses these outright (MEDIA_PROVIDER_INPUT_UNSUPPORTED) rather than+ // What this form is holding that the SELECTED PEER MODEL cannot take. The+ // server refuses these outright (MEDIA_PROVIDER_INPUT_UNSUPPORTED) rather than// dropping them, so the button says so up front instead of letting the user// commit to a render that silently loses its source image. Nothing is cleared// on selecting a peer — the pickers stay live so the user can empty them, and// still has them intact after switching back to This instance.+ //+ // Conditioning images are no longer blanket-refused (ADR+ // docs/decisions/2026-08-22-federated-media-input-assets.md rule 1): they+ // cross when the model advertises the role, so the check is per-role and+ // fails closed on a provider too old to advertise anything. LoRA weights stay+ // refused on every peer — a LoRA is a MODEL, not conditioning (rule 3).const remoteUnsupportedInputs = useMemo(() => {if (!remoteTarget.isRemote) return null;+ const model = remoteTarget.model;const present = [- ['an init image', initImage.source != null],- ['reference images', populatedRefs.length > 0],+ ['an init image', initImage.source != null && !peerModelAcceptsInput(model, 'initImage')],+ ['reference images', populatedRefs.length > 0 && !peerModelAcceptsInput(model, 'referenceImages')],['LoRA weights', selectedLoras.length > 0],].filter(([, set]) => set).map(([label]) => label);- return present.length- ? `A federated provider renders text-to-image only — clear ${present.join(' and ')} to render on this peer.`- : null;- }, [remoteTarget.isRemote, initImage.source, populatedRefs.length, selectedLoras.length]);+ if (present.length) {+ return `The selected peer model cannot take ${present.join(' and ')} — clear it to render on this peer.`;+ }+ // The mirror case: a model that renders ONLY from a source image. Advertised+ // at all only because conditioning crosses now, and a text-only submission+ // to one is refused rather than queued.+ if (peerModelRequiresInput(model) && initImage.source == null) {+ 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, 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.federatedTarget.test.jsx b/client/src/pages/VideoGen.federatedTarget.test.jsxindex 1d75cc5193..f14cf5fb8b 100644--- a/client/src/pages/VideoGen.federatedTarget.test.jsx+++ b/client/src/pages/VideoGen.federatedTarget.test.jsx@@ -221,17 +221,36 @@ describe('VideoGen federated render target', () => {expect(screen.queryByRole('option', { name: /MiniMax h3-one/ })).not.toBeInTheDocument();expect(screen.getByRole('option', { name: /Wan 2\.2 T2V/ })).toBeInTheDocument();});- // The federated wire is text-to-video only, and the server refuses a body- // carrying conditioning rather than rendering something else — so the form- // has to say so before the user commits, not after.- it('blocks a non-text mode instead of dropping its conditioning', async () => {+ // Image-to-video is no longer refused outright (ADR+ // docs/decisions/2026-08-22-federated-media-input-assets.md rule 1): the+ // FRAME is what has to cross, and whether it can is a per-model question+ // answered at the moment one is picked. Selecting the mode with no frame yet+ // conditions nothing, so blocking there would refuse a render that is still+ // a plain text-to-video job.+ it('lets image mode be selected on a peer, since a mode alone conditions nothing', async () => {await startRender();fireEvent.change(await screen.findByRole('combobox', { name: /generation target/i }), { target: { value: 'peer-example' } });await waitFor(() => expect(screen.getByRole('button', { name: /^Generate$/ })).toBeEnabled());fireEvent.click(screen.getByRole('button', { name: /^Image$/ }));- expect(screen.getByText(/renders text-to-video only/i)).toBeInTheDocument();+ expect(screen.queryByText(/cannot take/i)).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: /^Generate$/ })).toBeEnabled();+ });++ // Extend and audio-to-video are multi-step CHAIN STATE and an input the wire+ // has no field for (rule 4) — still refused, and refused at the MODE rather+ // than only at the input, since the mode can be set before its input is+ // filled. Blocking must beat dropping: an a2v render that reached the peer as+ // plain text-to-video is a valid-looking clip of a different thing.+ it.each([['Extend'], ['Audio']])('blocks %s mode, which cannot cross at all', async (label) => {+ await startRender();+ fireEvent.change(await screen.findByRole('combobox', { name: /generation target/i }), { target: { value: 'peer-example' } });+ await waitFor(() => expect(screen.getByRole('button', { name: /^Generate$/ })).toBeEnabled());++ fireEvent.click(screen.getByRole('button', { name: new RegExp(`^${label}$`) }));++ expect(screen.getByText(/cannot take/i)).toBeInTheDocument();expect(screen.getByRole('button', { name: /^Generate$/ })).toBeDisabled();});});diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex b000b0d698..cea933663f 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -98,6 +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';const MODES = [{ id: 'text', label: 'Text', icon: Type, desc: 'Text-to-video' },{ id: 'image', label: 'Image', icon: ImageIcon, desc: 'Image-to-video (start frame)' },@@ -181,18 +182,33 @@ export default function VideoGen() {models, status, availableLoras, grokEnabled,remoteSubmissionFields: remoteTarget.isRemote ? remoteTarget.submissionFields : null,});- // Conditioning the federated wire cannot carry. The server refuses a job+ // Conditioning the selected peer model cannot take. The server refuses a job// holding any of it (MEDIA_PROVIDER_INPUT_UNSUPPORTED) rather than silently// rendering something else, so the form says so before the user commits.// Nothing is cleared on picking a peer: the inputs stay filled and intact// for a switch back to This instance.+ //+ // Start and end FRAMES now cross when the model advertises the role (ADR+ // docs/decisions/2026-08-22-federated-media-input-assets.md rule 1) — but only+ // as a GALLERY pick. An UPLOAD is still staged in the multipart temp dir when+ // the federated branch runs, so it is not a path the uploader can read; the+ // remedy is to save it to the gallery first, which is what the message says.+ //+ // The rest stay refused, each for a recorded reason: LoRA weights are a MODEL+ // (rule 3), and keyframes / a clip to extend / IC-LoRA references / chained+ // chunks are multi-step CHAIN STATE this machine sequences (rule 4).const remoteUnsupportedInputs = useMemo(() => {if (!remoteTarget.isRemote) return null;+ const model = remoteTarget.model;const present = [['the Grok backend', isGrok],- [`${mode} mode`, mode !== 'text'],- ['a source image', !!sourceImageFile || !!sourceImageUpload],- ['an end frame', !!lastImageFile || !!lastImageUpload],+ // Each remaining pipeline semantic has its own input listed below, but the+ // 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')],+ ['an end frame', !!lastImageFile && !peerModelAcceptsInput(model, 'lastImage')],+ ['an uploaded frame (save it to the gallery first)', !!sourceImageUpload || !!lastImageUpload],['keyframes', keyframesActive],['a source clip to extend', !!extendFromVideoId],['an audio track', !!audioFile],@@ -200,11 +216,20 @@ export default function VideoGen() {['LoRA weights', selectedLoras.length > 0],['chained chunks', chunks > 1],].filter(([, set]) => set).map(([label]) => label);- return present.length- ? `A federated provider renders text-to-video only — clear ${present.join(', ')} to render on this peer.`- : null;- }, [remoteTarget.isRemote, isGrok, mode, sourceImageFile, sourceImageUpload, lastImageFile,- lastImageUpload, keyframesActive, extendFromVideoId, audioFile, icReferenceFile,+ if (present.length) {+ return `The selected peer model cannot take ${present.join(', ')} — clear it to render on this peer.`;+ }+ // An end frame alone would render a plain text-to-video clip with the frame+ // silently discarded — a valid-looking render of a different thing.+ if (lastImageFile && !sourceImageFile) {+ return 'A federated first-last-frame render needs both ends — add a start frame, or render on this instance.';+ }+ if (peerModelRequiresInput(model) && !sourceImageFile) {+ 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, isGrok, mode, sourceImageFile, sourceImageUpload,+ lastImageFile, lastImageUpload, keyframesActive, extendFromVideoId, audioFile, icReferenceFile,icReferenceVideoId, icReferenceImageFiles, selectedLoras, chunks]);// One reading for the Generate button, the enqueue guard and the caption.const remoteBlocked = remoteTarget.isRemotediff --git a/docs/FEDERATED_MEDIA_PROVIDERS.md b/docs/FEDERATED_MEDIA_PROVIDERS.mdindex 809ddb8d0f..6a60df012e 100644--- a/docs/FEDERATED_MEDIA_PROVIDERS.md+++ b/docs/FEDERATED_MEDIA_PROVIDERS.md@@ -124,17 +124,28 @@ queued media-job response, with `mode: null` (no local backend is renderingit) and the peer id echoed back as `mediaProviderPeerId`. Omitting`mediaProviderPeerId` keeps the existing local/cloud behavior byte for byte.-Wire v1 is **text-to-image and text-to-video only**. A federated request that-carries an init image, reference images, keyframes, a clip to extend, IC-LoRA-references, LoRA weights, a chained (multi-chunk) render, or a non-`text` render-mode is rejected with `400 MEDIA_PROVIDER_INPUT_UNSUPPORTED` naming what has to-go. That is deliberate: silently dropping the source image a user pinned would-return a plausible render of the wrong thing. Input-asset transfer is a later-slice.+**Conditioning images cross; models and chain state do not.** An init image,+reference images, and a video start/end frame are what the render is *of*, so+they travel with it (ADR [conditioning crosses to an allowlisted+peer](./decisions/2026-08-22-federated-media-input-assets.md) rule 1) — see+[Upload a conditioning image](#upload-a-conditioning-image) for the mechanism.+Everything else is still rejected with `400 MEDIA_PROVIDER_INPUT_UNSUPPORTED`+naming what has to go, and each refusal is a recorded decision rather than a+missing feature:++| Input | Crosses? | Why |+|---|---|---|+| init image, reference images, start/end frame | **yes**, when the model advertises the role | conditioning — the render is defined by it |+| LoRA weights | no | a LoRA is a **model**; remote model installation is out of scope (rule 3) |+| keyframes, clip to extend, IC-LoRA refs, chained chunks | no | multi-step **chain state** this machine sequences (rule 4) |+| an uploaded (not gallery-saved) video frame | no | still in the multipart temp dir when the federated branch runs — save it to the gallery first |++Refusing beats dropping throughout: silently discarding the source image a user+pinned returns a plausible render of the wrong thing.Unlike audio, image and video prompts cross as submitted rather than beingre-rendered from a fixed vocabulary. Why that is not a hole in the "no PII on-federation" rule, what stays absolutely prompt-free, and what a future standing+federation" rule, what stays absolutely prompt-free, and what a standing(unattended) route may not do are all decided in ADR[federated visual prompts](./decisions/2026-08-20-federated-visual-prompts.md).@@ -163,11 +174,14 @@ Two consequences worth knowing:and refuses locally rather than letting the peer reject work the useralready committed to.-Because wire v1 is text-to-image / text-to-video only, a form holding an init-image, reference images, keyframes, a clip to extend, IC-LoRA references, LoRA-weights, chained chunks, or a non-`text` mode blocks Generate and names what-has to be cleared. Nothing is cleared for you: the inputs stay filled, so-switching the target back to `This instance` renders exactly what was set up.+A form holding an input the **selected peer model** cannot take blocks Generate+and names what has to be cleared — per role, against that model's advertised+`inputAssets`, with an absent block reading as "accepts nothing" so a peer on an+older build is never offered a render it would reject. The mirror case is+handled too: a model that can only render FROM an image (an edit-only image+model, a video model with no text mode) blocks until one is supplied. Nothing is+cleared for you: the inputs stay filled, so switching the target back to+`This instance` renders exactly what was set up.### Video frame and canvas constraint negotiation@@ -420,6 +434,67 @@ lane as idle that the peer never reported on.Status never includes prompts, lyrics, credentials, local paths, commission records, or private creative metadata.+### Upload a conditioning image++Conditioning bytes go up **before** the job that references them, through their+own endpoint — never inline in a job body, and never as a filesystem path (ADR+[conditioning crosses to an allowlisted peer](./decisions/2026-08-22-federated-media-input-assets.md)+rule 1):++```+POST /api/federation/media/v1/assets+Content-Type: image/png # png | jpeg | webp+X-Content-SHA256: <hex digest of the body>+<raw bytes>+```++The provider hashes the body itself and refuses a mismatch+(`MEDIA_PROVIDER_ASSET_INTEGRITY`) — a truncated transfer must fail rather than+render something subtly different. It also sniffs the magic bytes and refuses a+body that contradicts its declared type, because the header is the caller's word+for what this is while the bytes are what the generator will open. The reply is+a receipt:++```json+{+ "wireVersion": 1,+ "assetId": "1f0c8a3b9d2e4a67-<sha256>",+ "sha256": "<sha256>",+ "sizeBytes": 284119,+ "mimeType": "image/png",+ "expiresAt": "2026-08-22T18:00:00.000Z"+}+```++A job body then names `{ "assetId": "…" }` in `initImage`, `referenceImages`,+`sourceImage`, or `lastImage` — only roles the capability's `inputAssets.roles`+advertises, and at most `inputAssets.maxCount` of them. An id that is not staged+(expired, swept, or never uploaded) fails the submission with+`410 MEDIA_PROVIDER_ASSET_NOT_FOUND` **before** the job is queued, so the+consumer can re-upload and retry rather than watching a job die minutes later.++Four properties are worth knowing:++- **Content-addressed.** The id embeds the digest, so re-sending identical bytes+ returns the same id and refreshes the expiry. That is what makes a reconcile+ after a restart one transfer rather than a duplicated render.+- **Caller-scoped.** The id's first half is derived from the *authenticated*+ caller — re-derived on every reference, never parsed from the request — so one+ peer cannot reach another's staged asset even given its exact id. Absent,+ expired, and someone else's all answer the same 404.+- **TTL-bounded.** Staged bytes live 6 hours under `data/federated-media-inbox/`,+ swept opportunistically on each admission. That directory sits outside every+ media root the gallery and the sync layer read, and is excluded from backups —+ it holds another machine's data, not this install's.+- **Consumers persist paths, not ids.** A queued job's marker records the LOCAL+ source paths; ids are obtained immediately before each submission. An id names+ a slot in a TTL-swept area, so a marker holding one would reconcile into a+ confident reference to bytes that are gone.++A provider that predates this ADR omits `inputAssets` from its capabilities+entirely, and **absence reads as unsupported** — a consumer refuses to send+conditioning rather than discovering at submit time that the peer rejects it.+### Submit a jobSend a unique, stable `Idempotency-Key` header with the canonical instrumental request rendered by the consumer:@@ -468,7 +543,7 @@ A remote job's conditioning — the prompt, and an audio job's lyrics — is per## Current boundary-Wire v1 carries lyrical and instrumental audio, text-to-image, and text-to-video. Interactive remote selection is exposed on the Image Gen, Video Gen and Music Studio surfaces; unattended work routes through **Instances → Unattended render routing**.+Wire v1 carries lyrical and instrumental audio, and image/video renders both text-only and conditioned on an init, reference, or start/end frame. Interactive remote selection is exposed on the Image Gen, Video Gen and Music Studio surfaces; unattended work routes through **Instances → Unattended render routing**.The boundary's remaining edges are **decisions, not gaps** — see ADR [conditioning crosses to an allowlisted peer](decisions/2026-08-22-federated-media-input-assets.md):@@ -476,4 +551,6 @@ The boundary's remaining edges are **decisions, not gaps** — see ADR [conditio- **Multi-step chain state never crosses** (rule 4) — a source video to extend, chained chunks, IC-LoRA references. The consumer sequences the chain; a provider holding one step of it cannot see the rest.- **No automatic fairness or failover** (rule 5). A job that silently re-targets another peer has changed both where the data went and which model produced the result.-Each is refused with `400 MEDIA_PROVIDER_INPUT_UNSUPPORTED` naming what has to go.+- **No fixed-vocabulary "visual profile"** (rule 6). Any enum small enough to be privacy-safe cannot express what the user asked for; it would not protect the prompt so much as discard it.++The first two are refused with `400 MEDIA_PROVIDER_INPUT_UNSUPPORTED` naming what has to go. Changing any of them needs a new ADR saying what changed about the reason — not a reading of the existing one.diff --git a/server/lib/federatedMediaWire.js b/server/lib/federatedMediaWire.jsindex 10465961e2..05491292a8 100644--- a/server/lib/federatedMediaWire.js+++ b/server/lib/federatedMediaWire.js@@ -136,6 +136,89 @@ export function normalizeRequestedMediaKinds(raw) {return kinds.length ? kinds : ['audio'];}+// ---------------------------------------------------------------------------+// Input conditioning assets (ADR+// docs/decisions/2026-08-22-federated-media-input-assets.md rule 1)+//+// A conditioning image is what the render is OF, so it crosses under the same+// gate as the prompt — but as bytes rather than JSON, through a dedicated+// authenticated endpoint that verifies the declared digest before storing.+// Model weights (rule 3) and multi-step chain state (rule 4) are NOT+// conditioning and never appear here.+// ---------------------------------------------------------------------------++// { mimeType -> extension }. One source, so the upload endpoint, the on-disk+// staging name, and the provider's path resolver cannot drift on what an+// acceptable conditioning image is.+export const FEDERATED_MEDIA_ASSET_EXTENSION = Object.freeze({+ 'image/png': 'png',+ 'image/jpeg': 'jpg',+ 'image/webp': 'webp',+});+export const FEDERATED_MEDIA_ASSET_MIME_TYPES = Object.freeze(Object.keys(FEDERATED_MEDIA_ASSET_EXTENSION));++// 32 MiB is generous for a conditioning image (a 4096² PNG lands well under it)+// and small enough that an accidental video upload is refused by size before+// it is refused by MIME.+export const FEDERATED_MEDIA_ASSET_MAX_BYTES = 32 * 1024 * 1024;+// How many assets one submission may reference. Bounded so a reference-image+// array cannot become a bulk upload channel.+export const FEDERATED_MEDIA_ASSET_MAX_COUNT = 8;+// Staged bytes live long enough to survive a provider restart and a queue+// backlog, and no longer. A reconcile past this simply re-uploads — the upload+// is content-addressed and idempotent, so that costs one transfer, not a+// duplicated render.+export const FEDERATED_MEDIA_ASSET_TTL_MS = 6 * 60 * 60 * 1000;++// Which conditioning slot an asset fills. Named for the submission field it+// lands in so a capability's `roles` list reads as the set of fields a consumer+// may send, with no second mapping to keep in sync.+export const FEDERATED_MEDIA_INPUT_ROLES = Object.freeze([+ 'initImage', 'referenceImages', 'sourceImage', 'lastImage',+]);++// `<callerHash>-<sha256>`. The caller half is derived provider-side from the+// AUTHENTICATED caller id and re-checked on every reference, so an asset id is+// unguessable-by-construction AND unusable across callers even if guessed.+export const federatedMediaAssetIdSchema = z.string().trim().regex(+ /^[a-f0-9]{16}-[a-f0-9]{64}$/,+ 'assetId must be a provider-issued <callerHash>-<sha256> pair',+);++// What a submission carries in place of the bytes. Deliberately just the id:+// the id embeds the digest the provider verified at upload, so a second copy on+// the wire would be a second source of truth for the same fact.+export const federatedMediaInputAssetRefSchema = z.object({+ assetId: federatedMediaAssetIdSchema,+}).strict();++// The provider's answer to "may I send conditioning, and of what shape?".+// Optional and nullable, and **absent must read as unsupported** — a provider+// predating this ADR omits the block entirely, and treating that as permission+// would submit assets it refuses. Limits only: no filename, no digest, no+// prompt (ADR 2026-08-20 rule 3 still governs the status payload).+export const federatedMediaInputAssetsSchema = z.object({+ maxBytes: z.number().int().positive().max(1_073_741_824),+ maxCount: z.number().int().positive().max(64),+ mimeTypes: z.array(z.enum(FEDERATED_MEDIA_ASSET_MIME_TYPES)).min(1).max(10),+ roles: z.array(z.enum(FEDERATED_MEDIA_INPUT_ROLES)).min(1).max(FEDERATED_MEDIA_INPUT_ROLES.length),+ // True for a model that cannot render text-only at all (an edit-only image+ // model, a video model with no `text` mode). Such a model is federatable ONLY+ // with conditioning, which is why it was unadvertised before this ADR.+ required: z.boolean(),+}).nullable().optional();++// What the upload endpoint answers with, validated by the consumer before it+// records the id on a job marker.+export const federatedMediaAssetSchema = z.object({+ wireVersion: z.literal(FEDERATED_MEDIA_WIRE_VERSION),+ assetId: federatedMediaAssetIdSchema,+ sha256: z.string().regex(/^[a-f0-9]{64}$/),+ sizeBytes: z.number().int().positive().max(FEDERATED_MEDIA_ASSET_MAX_BYTES),+ mimeType: z.enum(FEDERATED_MEDIA_ASSET_MIME_TYPES),+ expiresAt: z.string().datetime(),+});+// { mimeType -> file extension } for the result Content-Disposition header// and any provider-side filename validation. One source so a new result kind// can't drift the two.@@ -190,6 +273,7 @@ export const federatedMediaCapabilitySchema = z.object({h: z.number().int().min(64).max(2048),label: z.string().trim().max(120).optional(),})).max(100).nullable().optional(),+ inputAssets: federatedMediaInputAssetsSchema,});// Per-kind occupancy of the provider's own generation lanes. Counts only —diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex d69b780fd7..3212bed101 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -168,6 +168,18 @@ export const PATHS = {// A sibling of `images/` — never surfaced by the gallery's flat `.png`// enumeration; swept by imageCleanTmpGc.js on an age gate. Not federated.imageCleanTmp: join(INSTALL_ROOT, 'data/image-clean-tmp'),+ // PROVIDER-side staging for conditioning images an allowlisted peer uploaded+ // ahead of a federated render (ADR+ // docs/decisions/2026-08-22-federated-media-input-assets.md rule 1). Files are+ // named `<callerHash>-<sha256>.<ext>` and swept on a TTL.+ //+ // Deliberately its own root rather than a corner of `images/` or `uploads/`:+ // these are ANOTHER machine's bytes, held briefly to run one job. Under+ // `images/` the gallery would enumerate them and the sync layer would federate+ // them onward (the failure this repo already hit once with temp files in+ // data/images). Excluded from backups for the same reason — restoring a peer's+ // half-hour-old init image is worth nothing.+ federatedMediaInbox: join(INSTALL_ROOT, 'data/federated-media-inbox'),loras: join(INSTALL_ROOT, 'data/loras'),// Per-character LoRA training datasets (collectionStore layout:// lora-datasets/<id>/index.json + lora-datasets/<id>/images/*.png).@@ -1717,6 +1729,22 @@ export const resolveImageRef = makePathResolver(() => PATHS.imageRefs);*/export const resolveImageCleanTmp = makePathResolver(() => PATHS.imageCleanTmp);+/**+ * Resolve a peer-uploaded conditioning image staged under+ * `PATHS.federatedMediaInbox` to an absolute path. The provider maps an+ * accepted asset id onto one of these before handing the job to the local+ * generator, so the runner must accept this root as a valid `initImagePath` /+ * reference / keyframe source.+ *+ * Extension-restricted at the resolver rather than only at upload: the upload+ * endpoint already MIME-allowlists, but this is the boundary the *runner*+ * crosses, and a second check here means a hand-written file in the inbox still+ * cannot become an arbitrary path argument to the generator.+ */+export const resolveFederatedMediaAsset = makePathResolver(() => PATHS.federatedMediaInbox, {+ extensions: ['png', 'jpg', 'jpeg', 'webp'],+});+/*** Resolve a sprite reference asset used as an image-gen init image (issue* #2896 — anchors i2i from the locked main reference; uploaded design@@ -1784,6 +1812,10 @@ const IMAGE_INPUT_RESOLVERS = [// Image Cleaner temp init images (issue #2264) — the GPU FLUX round-trip// stages sync-cleaned bytes here as the img2img init.['imageCleanTmp', resolveImageCleanTmp],+ // Peer-uploaded conditioning images (#4348) — an allowlisted peer's init /+ // reference / keyframe bytes, staged for the one federated render they were+ // uploaded for.+ ['federatedMediaInbox', resolveFederatedMediaAsset],// Sprite reference assets (issue #2896) — the locked main reference /// uploaded design reference as the anchors' i2i init. Absolute-only// (returns null on basename input, so the fall-through loop skips it).diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 1016d70bba..7afe040a4b 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -13,7 +13,11 @@ import {import { PR_COMPLETION_VALUES } from './prDisposition.js';import { EFFORT_LEVELS } from './providerModels.js';import { MAX_TIMEOUT as AI_RUN_TIMEOUT_MAX_MS, MIN_TIMEOUT as AI_RUN_TIMEOUT_MIN_MS } from './aiToolkit/constants.js';-import { isFederatedMediaAudioPrompt } from './federatedMediaWire.js';+import {+ FEDERATED_MEDIA_ASSET_MAX_COUNT,+ federatedMediaInputAssetRefSchema,+ isFederatedMediaAudioPrompt,+} from './federatedMediaWire.js';import { isPlainObject } from './objects.js';// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total@@ -809,8 +813,15 @@ const federatedMediaAudioJobSubmissionSchema = federatedMediaJobRoutingSchema.ex// the way audio has a finite style/mood/instrument alphabet. Why that does not// breach the "no PII on federation" rule — a submitted job body is not a status// payload, and status/capability payloads stay absolutely prompt-free — is-// ADR docs/decisions/2026-08-20-federated-visual-prompts.md. Local input assets-// (init/reference images, LoRAs) are refused by the routes, not here.+// ADR docs/decisions/2026-08-20-federated-visual-prompts.md.+//+// Conditioning IMAGES ride the same rule (ADR+// docs/decisions/2026-08-22-federated-media-input-assets.md rule 1), by id+// rather than by value: the bytes went up through the authenticated,+// digest-verified asset endpoint first. What is still refused here — and refused+// by the routes, since neither has a field to name it — is a MODEL (LoRA+// weights, rule 3) and multi-step CHAIN STATE (a video to extend, chained+// chunks, IC-LoRA references, rule 4).export const federatedMediaImageJobSubmissionSchema = federatedMediaJobRoutingSchema.omit({durationSec: true, durationMode: true,}).extend({@@ -822,10 +833,28 @@ export const federatedMediaImageJobSubmissionSchema = federatedMediaJobRoutingScsteps: z.number().int().min(1).max(150).optional(),guidance: z.number().finite().min(0).max(30).optional(),seed: z.number().int().min(0).optional(),-}).strict().refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });+ initImage: federatedMediaInputAssetRefSchema.optional(),+ initImageStrength: z.number().finite().min(0).max(1).optional(),+ referenceImages: z.array(federatedMediaInputAssetRefSchema)+ .max(FEDERATED_MEDIA_ASSET_MAX_COUNT).optional(),+}).strict()+ .refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] })+ // A strength with nothing to apply it to is a caller bug, not a default to+ // guess at: silently ignoring it renders at full denoise, which is the+ // opposite of what a low strength asked for.+ .refine((value) => value.initImageStrength === undefined || value.initImage !== undefined, {+ message: 'initImageStrength requires an initImage',+ path: ['initImageStrength'],+ });-// Same boundary as the image schema above — see the ADR named there.-export const federatedMediaVideoJobSubmissionSchema = federatedMediaJobRoutingSchema.omit({+// Same boundary as the image schema above — see the ADRs named there.+//+// Exported UN-REFINED as well: `negotiateVideoConstraints` re-validates a+// partially-negotiated body against `.partial()`, and Zod refuses `.partial()`+// on a schema carrying refinements. Splitting the object from its cross-field+// rule keeps both callers honest instead of dropping the rule to keep the+// partial working.+export const federatedMediaVideoJobSubmissionBaseSchema = federatedMediaJobRoutingSchema.omit({durationSec: true, durationMode: true,}).extend({kind: z.literal('video'),@@ -838,8 +867,18 @@ export const federatedMediaVideoJobSubmissionSchema = federatedMediaJobRoutingScsteps: z.number().int().min(1).max(150).optional(),guidance: z.number().finite().min(0).max(30).optional(),seed: z.number().int().min(0).optional(),+ sourceImage: federatedMediaInputAssetRefSchema.optional(),+ lastImage: federatedMediaInputAssetRefSchema.optional(),}).strict();+export const federatedMediaVideoJobSubmissionSchema = federatedMediaVideoJobSubmissionBaseSchema+ // First-last-frame needs both ends. A lone end frame would render a plain+ // text-to-video clip and quietly discard the frame the caller supplied.+ .refine((value) => value.lastImage === undefined || value.sourceImage !== undefined, {+ message: 'lastImage requires a sourceImage (first-last-frame needs both ends)',+ path: ['lastImage'],+ });+// An already-shipped consumer's request body never carries `kind` — it only// knows the pre-existing audio-only shape. Defaulting the missing field to// 'audio' before the discriminated union runs keeps that body validatingdiff --git a/server/routes/federatedMedia.js b/server/routes/federatedMedia.jsindex 22f104285b..c92bacebb1 100644--- a/server/routes/federatedMedia.js+++ b/server/routes/federatedMedia.js@@ -3,7 +3,7 @@* additionally require its verified-Basic marker plus a registered peer id.*/-import { Router } from 'express';+import { Router, raw } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import {federatedMediaIdempotencyKeySchema,@@ -12,7 +12,13 @@ import {federatedMediaStatusQuerySchema,validateRequest,} from '../lib/validation.js';-import { FEDERATED_MEDIA_RESULT_EXTENSION, normalizeRequestedMediaKinds } from '../lib/federatedMediaWire.js';+import {+ FEDERATED_MEDIA_ASSET_MAX_BYTES,+ FEDERATED_MEDIA_ASSET_MIME_TYPES,+ FEDERATED_MEDIA_RESULT_EXTENSION,+ federatedMediaAssetIdSchema,+ normalizeRequestedMediaKinds,+} from '../lib/federatedMediaWire.js';import {authorizeFederatedMediaPeer,cancelFederatedMediaJob,@@ -21,9 +27,20 @@ import {getFederatedMediaResult,submitFederatedMediaJob,} from '../services/federatedMediaProvider.js';+import {+ describeFederatedMediaAsset,+ storeFederatedMediaAsset,+} from '../services/federatedMedia/assetStore.js';const router = Router();+// Raw bytes, scoped to this one route and to the image types the store accepts.+// The app-wide express.json() only parses JSON content-types, so an upload+// passes through it untouched and arrives here as a Buffer. The limit is the+// same constant the store enforces, so an oversized body is refused before it+// is buffered rather than after.+const assetBody = raw({ type: FEDERATED_MEDIA_ASSET_MIME_TYPES, limit: FEDERATED_MEDIA_ASSET_MAX_BYTES });+router.get('/status', asyncHandler(async (req, res) => {const { config } = await authorizeFederatedMediaPeer(req);const { kinds: kindsParam } = validateRequest(federatedMediaStatusQuerySchema, req.query);@@ -31,6 +48,32 @@ router.get('/status', asyncHandler(async (req, res) => {res.json(await getFederatedMediaProviderStatus(config, { kinds }));}));+// Conditioning-image upload (ADR+// docs/decisions/2026-08-22-federated-media-input-assets.md rule 1). Bytes go up+// here first and a job body then references the returned id — never a+// filesystem path, and never the bytes inline. Content-addressed, so re-sending+// identical bytes returns the same id and just refreshes the expiry, which is+// what makes a reconcile after a restart cheap.+router.post('/assets', assetBody, asyncHandler(async (req, res) => {+ const { callerId } = await authorizeFederatedMediaPeer(req);+ const stored = await storeFederatedMediaAsset({+ callerId,+ mimeType: (req.get('Content-Type') || '').split(';')[0].trim().toLowerCase(),+ declaredSha256: req.get('X-Content-SHA256'),+ body: req.body,+ });+ res.status(201).json(stored);+}));++// Lets a consumer skip a re-upload after a restart. Absent, expired, and+// another caller's asset all answer 404 — distinguishing them would confirm the+// existence of a peer's asset to someone who is not that peer.+router.get('/assets/:id', asyncHandler(async (req, res) => {+ const { callerId } = await authorizeFederatedMediaPeer(req);+ const assetId = validateRequest(federatedMediaAssetIdSchema, req.params.id);+ res.json(await describeFederatedMediaAsset(callerId, assetId));+}));+router.post('/jobs', asyncHandler(async (req, res) => {const { callerId, config } = await authorizeFederatedMediaPeer(req);const input = validateRequest(federatedMediaJobSubmissionSchema, req.body);diff --git a/server/routes/federatedMedia.test.js b/server/routes/federatedMedia.test.jsindex 5cc404ed37..3fb833adc4 100644--- a/server/routes/federatedMedia.test.js+++ b/server/routes/federatedMedia.test.js@@ -1,10 +1,12 @@import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import express from 'express';import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { createHash } from 'node:crypto';import { join } from 'node:path';import { tmpdir } from 'node:os';import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';+import { PATHS } from '../lib/fileUtils.js';const provider = vi.hoisted(() => ({replayed: false,@@ -38,14 +40,22 @@ vi.mock('../services/federatedMediaProvider.js', () => ({import federatedMediaRoutes from './federatedMedia.js';let tempRoot;+let originalInbox;beforeAll(() => {tempRoot = mkdtempSync(join(tmpdir(), 'portos-federated-media-route-'));provider.resultPath = join(tempRoot, 'result.wav');writeFileSync(provider.resultPath, 'RIFF');+ // The asset routes use the REAL store (only the provider service is mocked),+ // so give it a temp inbox rather than the install's data dir.+ originalInbox = PATHS.federatedMediaInbox;+ PATHS.federatedMediaInbox = join(tempRoot, 'inbox');});-afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));+afterAll(() => {+ PATHS.federatedMediaInbox = originalInbox;+ rmSync(tempRoot, { recursive: true, force: true });+});beforeEach(() => {vi.clearAllMocks();@@ -126,6 +136,58 @@ describe('federated media routes', () => {}));});+ // Conditioning-image upload (ADR+ // docs/decisions/2026-08-22-federated-media-input-assets.md rule 1). The store+ // itself is covered by services/federatedMedia/assetStore.test.js; what these+ // guard is the ROUTE's own contract — that raw bytes reach the store at all+ // (the app-wide express.json() must not swallow them), and that the peer+ // authorization gate fires before any byte is written.+ describe('conditioning-image upload', () => {+ const png = Buffer.concat([+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ Buffer.from('portos-test-conditioning-image'),+ ]);+ const digest = createHash('sha256').update(png).digest('hex');++ it('stages verified bytes and returns a content-addressed receipt', async () => {+ const response = await request(buildApp()).post('/api/federation/media/v1/assets')+ .set('Content-Type', 'image/png')+ .set('X-Content-SHA256', digest)+ .send(png);++ expect(response.status).toBe(201);+ expect(response.body).toMatchObject({+ wireVersion: 1, sha256: digest, sizeBytes: png.length, mimeType: 'image/png',+ });+ expect(response.body.assetId.endsWith(`-${digest}`)).toBe(true);++ // The same peer can then read it back and skip a re-upload after a restart.+ const described = await request(buildApp())+ .get(`/api/federation/media/v1/assets/${response.body.assetId}`);+ expect(described.status).toBe(200);+ expect(described.body.sha256).toBe(digest);+ });++ it('refuses an unauthorized peer before writing anything', async () => {+ provider.authorize.mockRejectedValueOnce(Object.assign(+ new Error('Verified peer Basic authentication is required'),+ { status: 403, code: 'MEDIA_PROVIDER_PEER_AUTH_REQUIRED' },+ ));+ const response = await request(buildApp()).post('/api/federation/media/v1/assets')+ .set('Content-Type', 'image/png')+ .set('X-Content-SHA256', digest)+ .send(png);+ expect(response.status).toBe(403);+ });++ it('refuses a malformed asset id rather than letting it reach the filesystem', async () => {+ const response = await request(buildApp())+ .get('/api/federation/media/v1/assets/..%2F..%2Fetc%2Fpasswd');+ expect(response.status).toBe(400);+ expect(response.body.code).toBe('VALIDATION_ERROR');+ });+ });+it('serves completed bytes with an integrity header and no source path', async () => {const response = await request(buildApp()).get(`/api/federation/media/v1/jobs/${jobId}/result`);expect(response.status).toBe(200);diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 0e823693f0..3f2a12a0cf 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -43,6 +43,7 @@ import { randomUUID } from 'crypto';import { buildUniverseRunTag } from '../services/universeRunTag.js';import { getSettings } from '../services/settings.js';import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';+import { collectRemoteInputAssets } from '../services/federatedMedia/inputAssets.js';import { buildFederatedMediaRequest } from '../lib/federatedMediaRequest.js';const router = Router();@@ -437,22 +438,28 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {// locally. Checked BEFORE the cloud/local dispatch below — those branches// resolve this machine's backends, which a remote render never uses.if (params.mediaProviderPeerId) {- // The federated wire is text-to-image only: it carries no init image,- // reference images, or LoRA weights, and cleaners run on the bytes this- // machine renders. Reject rather than silently dropping conditioning the- // user asked for — a render that quietly ignores its source image is worse- // than one that refuses.- const unsupported = [- ['an init image', params.initImagePath],- ['reference images', params.referenceImagePaths?.length],- ['LoRA weights', params.loraFilenames?.length || params.loraPaths?.length],- ].filter(([, present]) => present).map(([label]) => label);- if (unsupported.length) {+ // LoRA weights are the one input that still cannot cross, and it is a+ // decision rather than a gap: a LoRA is a MODEL, not conditioning, and+ // remote model installation is out of scope for federation (ADR+ // docs/decisions/2026-08-22-federated-media-input-assets.md rule 3). Refuse+ // rather than silently dropping it — a render that quietly ignores its LoRA+ // is worse than one that says why.+ if (params.loraFilenames?.length || params.loraPaths?.length) {throw new ServerError(- `A federated media provider renders text-to-image only — this request uses ${unsupported.join(' and ')}. Render locally instead.`,+ 'A federated media provider renders with the models its own operator installed — LoRA weights do not cross. '+ + 'Render locally, or install the LoRA on the peer and allowlist a model that uses it.',{ status: 400, code: 'MEDIA_PROVIDER_INPUT_UNSUPPORTED' },);}+ // Conditioning images DO cross (rule 1), by id: the bytes go up through the+ // provider's authenticated, digest-verified asset endpoint immediately+ // before submission. The marker keeps these LOCAL paths, never the+ // provider-issued ids, so a reconcile after a restart re-stages the same+ // bytes instead of naming staging slots that have since expired.+ const inputAssets = collectRemoteInputAssets({+ initImage: params.initImagePath,+ referenceImages: params.referenceImagePaths,+ });// A peer advertises specific models; it has no notion of 'this caller's// default'. Say so rather than letting the wire schema report a bare// 'expected string, received undefined' for a field the local path defaults.@@ -470,6 +477,7 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {peerId: params.mediaProviderPeerId,kind: 'image',request,+ inputAssets,});// Drop every field that only means something to a LOCAL dispatch: the// routing inputs consumed above, plus the backend selectors this renderdiff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex 62f90c5daa..2c06f7927b 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -1462,6 +1462,9 @@ describe('Image Gen Routes', () => {height: 512,seed: 42,},+ // A text-to-image render carries none, but the field is always passed —+ // an empty list and an absent one must read the same to the submitter.+ inputAssets: [],});const [{ params }] = mediaJobQueue.enqueueJob.mock.calls[0];diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 87688650b3..28f93a53be 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -69,6 +69,7 @@ import { saveUploadedGalleryVideo } from '../services/videoUpload.js';import { JSON_BODY_LIMIT_BYTES } from '../lib/uploadLimits.js';import { createInstallLogger } from '../lib/installLogger.js';import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';+import { collectRemoteInputAssets } from '../services/federatedMedia/inputAssets.js';import { effectiveJobPrompt } from '../lib/federatedMediaWire.js';import { isRemoteMediaJob } from '../services/mediaJobQueue/remoteMediaJob.js';import { buildFederatedMediaRequest } from '../lib/federatedMediaRequest.js';@@ -1016,20 +1017,25 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {// locally. Handled BEFORE prepareVideoGenParams, which resolves this// machine's backend and stages uploads a remote render can never use.if (body.mediaProviderPeerId) {- // The federated wire is text-to-video only. Every input below changes what- // the clip actually is, and none of it can cross — refuse rather than- // render something the user didn't ask for.+ // Start and end FRAMES cross as conditioning (ADR+ // docs/decisions/2026-08-22-federated-media-input-assets.md rule 1) — but+ // only when they name an existing gallery image. A multipart upload has been+ // staged to the OS temp dir by the parser and is not resolvable through the+ // shared image roots the asset stager reads, so it stays refused here rather+ // than being silently dropped.+ //+ // Everything else below is a decision, not a gap. Model weights are a MODEL+ // (rule 3), and a video to extend / chained chunks / IC-LoRA references are+ // multi-step CHAIN STATE whose sequence lives on this machine (rule 4) — a+ // provider holding one step of a chain cannot see the rest of it.const unsupported = [['uploaded files', Object.keys(uploads).length],- ['a source image', body.sourceImageFile],- ['an end frame', body.lastImageFile],['keyframes', body.keyframes?.length],['a source video to extend', body.extendFromVideoId],['IC-LoRA references', body.icReferenceVideoIds?.length || body.icReferenceImageFiles?.length],['LoRA weights', body.loraFilenames?.length],['chained chunks', body.chunks > 1],['the Grok backend', body.backend === 'grok'],- ['a non-text render mode', body.mode !== undefined && body.mode !== 'text'],// A director-board render is image-to-video by construction (its scene// reference frame conditions the shot), and its project/scene ids are// validated inside prepareVideoGenParams, which this branch bypasses.@@ -1038,7 +1044,34 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {if (unsupported.length) {await cleanupMultipartTemp(uploads);throw new ServerError(- `A federated media provider renders text-to-video only — this request uses ${unsupported.join(' and ')}. Render locally instead.`,+ `A federated media provider cannot render this clip — it uses ${unsupported.join(' and ')}. Render locally instead.`,+ { status: 400, code: 'MEDIA_PROVIDER_INPUT_UNSUPPORTED' },+ );+ }+ // An end frame with no start frame would render a plain text-to-video clip+ // and silently discard the frame the caller supplied. The wire schema+ // refuses the same shape, but it never sees this one: a conditioning image+ // reaches the request as an asset id resolved at submit time, so by the time+ // the schema runs the field is simply absent. Refuse here.+ if (body.lastImageFile && !body.sourceImageFile) {+ await cleanupMultipartTemp(uploads);+ throw new ServerError(+ 'A federated first-last-frame render needs both ends — this request supplies only an end frame. Add a start frame, or render locally.',+ { status: 400, code: 'MEDIA_PROVIDER_INPUT_UNSUPPORTED' },+ );+ }+ const inputAssets = collectRemoteInputAssets({+ sourceImage: body.sourceImageFile,+ lastImage: body.lastImageFile,+ });+ // `mode` is resolved by the peer from the conditioning it receives, so a+ // caller-supplied pipeline semantic is redundant at best. Refuse a mode that+ // contradicts what was actually sent instead of rendering the other one.+ const impliedMode = body.lastImageFile ? 'fflf' : body.sourceImageFile ? 'image' : 'text';+ if (body.mode !== undefined && body.mode !== impliedMode && body.mode !== 'local') {+ await cleanupMultipartTemp(uploads);+ throw new ServerError(+ `A federated render mode must match its conditioning — this request asks for '${body.mode}' but supplies ${impliedMode === 'text' ? 'no frames' : `a ${impliedMode} frame set`}. Render locally instead.`,{ status: 400, code: 'MEDIA_PROVIDER_INPUT_UNSUPPORTED' },);}@@ -1059,6 +1092,7 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {peerId: body.mediaProviderPeerId,kind: 'video',request,+ inputAssets,});// Prompt and dials ride only inside the versioned marker: enqueueJob// normalizes any job carrying one into the downgrade-safe shape, so a builddiff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 7f085d8a11..be888da54c 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -2321,6 +2321,9 @@ describe('videoGen routes', () => {numFrames: 121,fps: 24,},+ // A text-to-video render carries none, but the field is always passed —+ // an empty list and an absent one must read the same to the submitter.+ inputAssets: [],});const [{ params }] = mediaJobQueue.enqueueJob.mock.calls[0];@@ -2343,7 +2346,11 @@ describe('videoGen routes', () => {expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();});- it('refuses a federated render that carries conditioning the wire cannot take', async () => {+ // A start frame is single-render conditioning and now crosses (ADR+ // docs/decisions/2026-08-22-federated-media-input-assets.md rule 1) — as a+ // LOCAL path handed to the submitter, which uploads it through the+ // provider's digest-verified asset endpoint immediately before submitting.+ it('routes a start frame to the peer as conditioning rather than refusing it', async () => {const r = await request(app).post('/api/video-gen/').send({prompt: 'a slow pan across a harbour',modelId: 'ltx2',@@ -2351,9 +2358,40 @@ describe('videoGen routes', () => {mediaProviderPeerId: federatedPeerId,});+ expect(r.status).toBe(200);+ expect(prepareRemoteMediaJob).toHaveBeenCalledWith(expect.objectContaining({+ inputAssets: [{ role: 'sourceImage', path: 'frame.png' }],+ }));+ });++ // The end frame alone would render a plain text-to-video clip with the+ // supplied frame silently discarded — a valid-looking render of a different+ // thing, which is the failure the whole guard exists to prevent.+ it('refuses an end frame with no start frame', async () => {+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'a slow pan across a harbour',+ modelId: 'ltx2',+ lastImageFile: 'end.png',+ mediaProviderPeerId: federatedPeerId,+ });+expect(r.status).toBe(400);expect(r.body.code).toBe('MEDIA_PROVIDER_INPUT_UNSUPPORTED');- expect(r.body.error).toMatch(/source image/);+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();+ });++ // A LoRA is a MODEL, not conditioning, and remote model installation is out+ // of scope for federation (rule 3). This one stays a refusal on purpose.+ it('refuses a federated render that carries LoRA weights', async () => {+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'a slow pan across a harbour',+ modelId: 'ltx2',+ loraFilenames: ['style.safetensors'],+ mediaProviderPeerId: federatedPeerId,+ });++ expect(r.status).toBe(400);+ expect(r.body.error).toMatch(/LoRA weights/);expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();expect(prepareRemoteMediaJob).not.toHaveBeenCalled();});diff --git a/server/services/backup.js b/server/services/backup.jsindex 4a2f16cfb5..5e0112c7d9 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -80,7 +80,12 @@ export const DEFAULT_EXCLUDES = [// model.glb, which IS backed up), and at ~1 GB per render it would otherwise// dominate every snapshot. Overridable, because it is the only copy of the// discarded detail and someone archiving finished work may want it.- { path: '/image-to-3d/*/model.obj', reason: 'TRELLIS.2 full-resolution mesh sidecar — ~1 GB per render, regenerable by re-rendering at the same seed. The exported model.glb and keyed source ARE backed up.', overridable: true }+ { path: '/image-to-3d/*/model.obj', reason: 'TRELLIS.2 full-resolution mesh sidecar — ~1 GB per render, regenerable by re-rendering at the same seed. The exported model.glb and keyed source ARE backed up.', overridable: true },+ // Anchored, like every entry here. Not overridable: these are another+ // machine's conditioning bytes, staged for one federated render and swept on+ // a TTL measured in hours. Nothing here is this install's data to keep, and a+ // restored inbox entry is either already expired or already rendered.+ { path: '/federated-media-inbox/', reason: 'Conditioning images an allowlisted peer uploaded for one federated render — TTL-swept, and another machine\'s data rather than this install\'s', overridable: false }// NOTE: legacy file→Postgres migration artifacts (`.imported` / `.bak-NNN`)// are intentionally NOT excluded here. They are deleted on disk by the// boot-time prune (pruneImportedLegacyFiles.js) the same boot the migrationdiff --git a/server/services/dataManager.js b/server/services/dataManager.jsindex 3fc01149bf..bdadd1e29e 100644--- a/server/services/dataManager.js+++ b/server/services/dataManager.js@@ -65,6 +65,13 @@ export const CATEGORIES = {'db-dumps': { label: 'DB Dumps', description: 'PostgreSQL database backups', archivable: true, deletable: true, purgeScope: 'category' },'digital-twin': { label: 'Digital Twin', description: 'Identity, goals, character data', archivable: true, deletable: false },'fableloom': { label: 'FableLoom', description: 'Branching-narrative records (file mirror of the Postgres store)', archivable: true, deletable: false },+ // Another machine's conditioning images, staged for one federated render and+ // swept on a TTL (#4348). Not archivable for the same reason it is excluded+ // from backups: none of it is this install's data, and a restored entry is+ // either already expired or already rendered. Purgeable as a category —+ // deleting a staged asset only forces the peer that owns it to re-upload,+ // which is one transfer, not lost work.+ 'federated-media-inbox': { label: 'Federated Media Inbox', description: 'Source images peers uploaded for federated renders — expire automatically, safe to purge', archivable: false, deletable: true, purgeScope: 'category' },'games': { label: 'Games', description: 'Game project records and assets', archivable: true, deletable: false },'health': { label: 'Apple Health', description: 'Daily health JSON snapshots', archivable: true, deletable: false },'image-clean-tmp': { label: 'Image Cleaner Scratch', description: 'Ephemeral working files for Image Cleaner renders — swept automatically, safe to purge when no render is in flight', archivable: false, deletable: true, purgeScope: 'category', busyCheck: imageCleanTmpBusy },diff --git a/server/services/federatedMedia/assetStore.js b/server/services/federatedMedia/assetStore.jsnew file mode 100644index 0000000000..c352cea3c8--- /dev/null+++ b/server/services/federatedMedia/assetStore.js@@ -0,0 +1,204 @@+/**+ * Provider-side staging for conditioning images an allowlisted peer uploads+ * ahead of a federated render (ADR+ * docs/decisions/2026-08-22-federated-media-input-assets.md rule 1).+ *+ * Three properties do the work here, and each one is load-bearing:+ *+ * - **Content-addressed.** The stored name embeds the SHA-256 the provider+ * computed itself, so re-uploading identical bytes is a no-op that refreshes+ * the expiry. That is what makes a reconcile after a restart cost one HEAD-ish+ * round trip instead of a second multi-megabyte transfer.+ * - **Caller-scoped.** The name is prefixed with a digest of the AUTHENTICATED+ * caller id, re-derived (never parsed from the request) on every reference. An+ * asset id from one peer is unusable by another even if it leaks.+ * - **TTL-bounded.** These are another machine's bytes held to run one job.+ * Nothing here is this install's data, so it expires rather than accumulating,+ * and it is excluded from backups.+ *+ * What is NOT here, deliberately: model weights (rule 3) and multi-step chain+ * state (rule 4). Neither is conditioning, and neither has a field on the wire.+ */++import { readdir, rm, stat, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { ServerError } from '../../lib/errorHandler.js';+import {+ detectImageFormat,+ ensureDir,+ PATHS,+ resolveFederatedMediaAsset,+ sha256Text,+} from '../../lib/fileUtils.js';+import {+ FEDERATED_MEDIA_ASSET_EXTENSION,+ FEDERATED_MEDIA_ASSET_MAX_BYTES,+ FEDERATED_MEDIA_ASSET_MIME_TYPES,+ FEDERATED_MEDIA_ASSET_TTL_MS,+ FEDERATED_MEDIA_WIRE_VERSION,+ federatedMediaAssetIdSchema,+} from '../../lib/federatedMediaWire.js';++const reject = (message, code, status = 400, context) => {+ throw new ServerError(message, { status, code, ...(context ? { context } : {}) });+};++/**+ * The caller half of an asset id. Derived from the authenticated caller id+ * rather than accepted from the request, so it is an authorization check and+ * not merely a namespace.+ */+export const callerAssetPrefix = (callerId) => sha256Text(String(callerId)).slice(0, 16);++const assetFilename = (assetId, mimeType) => `${assetId}.${FEDERATED_MEDIA_ASSET_EXTENSION[mimeType]}`;++// Every extension this store can produce, for the id -> file lookup. The stored+// mime type is not part of the id (the id is caller + digest), so finding an+// asset means trying the extensions rather than being told which one it is.+const ASSET_EXTENSIONS = [...new Set(Object.values(FEDERATED_MEDIA_ASSET_EXTENSION))];+const MIME_BY_EXTENSION = Object.fromEntries(+ FEDERATED_MEDIA_ASSET_MIME_TYPES.map((mime) => [FEDERATED_MEDIA_ASSET_EXTENSION[mime], mime]),+);++const expiresAtFor = (mtimeMs) => new Date(mtimeMs + FEDERATED_MEDIA_ASSET_TTL_MS).toISOString();++/**+ * Locate one staged asset for a caller.+ *+ * @returns {Promise<{path: string, mimeType: string, sizeBytes: number, expiresAt: string}|null>}+ * `null` for absent, unreadable, expired, or belonging to another caller —+ * all four are "you cannot use this", and distinguishing them to the caller+ * would confirm the existence of another peer's asset.+ */+export async function findFederatedMediaAsset(callerId, assetId, { now = Date.now() } = {}) {+ const parsed = federatedMediaAssetIdSchema.safeParse(assetId);+ if (!parsed.success) return null;+ if (!parsed.data.startsWith(`${callerAssetPrefix(callerId)}-`)) return null;++ for (const extension of ASSET_EXTENSIONS) {+ // Through the shared resolver, not join(): it basenames and re-anchors at+ // the inbox root, so this stays a single containment check shared with the+ // image runner's own re-validation of the same path.+ const path = resolveFederatedMediaAsset(`${parsed.data}.${extension}`);+ if (!path) continue;+ const info = await stat(path).catch(() => null);+ if (!info?.isFile()) continue;+ if (now - info.mtimeMs > FEDERATED_MEDIA_ASSET_TTL_MS) continue;+ return {+ path,+ mimeType: MIME_BY_EXTENSION[extension],+ sizeBytes: info.size,+ expiresAt: expiresAtFor(info.mtimeMs),+ };+ }+ return null;+}++/**+ * Accept one uploaded conditioning image.+ *+ * `declaredSha256` is the caller's claim and is checked against a digest this+ * side computes — a mismatch is a truncated or altered transfer, and rendering+ * from it would produce a plausible image of the wrong thing.+ *+ * @param {object} args+ * @param {string} args.callerId - Authenticated peer instance id.+ * @param {string} args.mimeType - Declared Content-Type.+ * @param {string} args.declaredSha256 - Caller's X-Content-SHA256 header.+ * @param {Buffer} args.body+ */+export async function storeFederatedMediaAsset({ callerId, mimeType, declaredSha256, body }) {+ if (!FEDERATED_MEDIA_ASSET_MIME_TYPES.includes(mimeType)) {+ reject(+ `Unsupported conditioning image type: ${mimeType || 'none'}`,+ 'MEDIA_PROVIDER_ASSET_TYPE_UNSUPPORTED',+ 415,+ { supported: FEDERATED_MEDIA_ASSET_MIME_TYPES },+ );+ }+ if (!Buffer.isBuffer(body) || body.length === 0) {+ reject('Conditioning image upload was empty', 'MEDIA_PROVIDER_ASSET_EMPTY');+ }+ if (body.length > FEDERATED_MEDIA_ASSET_MAX_BYTES) {+ reject('Conditioning image exceeds the provider limit', 'MEDIA_PROVIDER_ASSET_TOO_LARGE', 413, {+ maxBytes: FEDERATED_MEDIA_ASSET_MAX_BYTES,+ });+ }+ // Magic bytes, not just the declared header. The header is the caller's word+ // for what this is; the bytes are what the generator will actually open.+ const detected = detectImageFormat(body);+ if (!detected || detected.mime !== mimeType) {+ reject(+ `Conditioning image bytes are not ${mimeType}`,+ 'MEDIA_PROVIDER_ASSET_TYPE_MISMATCH',+ 415,+ { declared: mimeType, detected: detected?.mime || null },+ );+ }+ // sha256Text takes a Buffer as well as a string — see its doc comment.+ const sha256 = sha256Text(body);+ if (typeof declaredSha256 !== 'string' || declaredSha256.toLowerCase() !== sha256) {+ reject('Conditioning image digest does not match its bytes', 'MEDIA_PROVIDER_ASSET_INTEGRITY');+ }++ const assetId = `${callerAssetPrefix(callerId)}-${sha256}`;+ await ensureDir(PATHS.federatedMediaInbox);+ const path = join(PATHS.federatedMediaInbox, assetFilename(assetId, mimeType));+ // Unconditional write, even when the same bytes are already staged: the+ // content is identical by construction (the name IS the digest), and+ // rewriting is what refreshes the TTL for a replayed submission.+ await writeFile(path, body);+ return {+ wireVersion: FEDERATED_MEDIA_WIRE_VERSION,+ assetId,+ sha256,+ sizeBytes: body.length,+ mimeType,+ expiresAt: expiresAtFor(Date.now()),+ };+}++/**+ * Metadata for one staged asset, so a consumer can skip a re-upload after a+ * restart. 404 covers absent, expired, and another caller's — see+ * findFederatedMediaAsset.+ */+export async function describeFederatedMediaAsset(callerId, assetId) {+ const found = await findFederatedMediaAsset(callerId, assetId);+ if (!found) {+ reject('Conditioning image is not staged for this peer', 'MEDIA_PROVIDER_ASSET_NOT_FOUND', 404);+ }+ return {+ wireVersion: FEDERATED_MEDIA_WIRE_VERSION,+ assetId,+ // Re-read off the id rather than re-hashing the file: the id half IS the+ // digest this provider computed when it accepted the bytes.+ sha256: assetId.slice(-64),+ sizeBytes: found.sizeBytes,+ mimeType: found.mimeType,+ expiresAt: found.expiresAt,+ };+}++/**+ * Drop expired staged assets. Called opportunistically from the provider's+ * admission path rather than on a timer — a provider that receives no federated+ * work has nothing to sweep, and one that does gets swept on every submission.+ *+ * Never throws: a sweep failure must not fail the job that triggered it.+ *+ * @returns {Promise<number>} files removed+ */+export async function sweepFederatedMediaAssets({ now = Date.now() } = {}) {+ const entries = await readdir(PATHS.federatedMediaInbox).catch(() => null);+ if (!entries) return 0;+ let removed = 0;+ for (const name of entries) {+ const path = join(PATHS.federatedMediaInbox, name);+ const info = await stat(path).catch(() => null);+ if (!info?.isFile() || now - info.mtimeMs <= FEDERATED_MEDIA_ASSET_TTL_MS) continue;+ if (await rm(path, { force: true }).then(() => true, () => false)) removed += 1;+ }+ if (removed) console.log(`🧹 Federated media inbox: swept ${removed} expired conditioning image(s)`);+ return removed;+}diff --git a/server/services/federatedMedia/assetStore.test.js b/server/services/federatedMedia/assetStore.test.jsnew file mode 100644index 0000000000..f99243a468--- /dev/null+++ b/server/services/federatedMedia/assetStore.test.js@@ -0,0 +1,155 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, existsSync, utimesSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { PATHS } from '../../lib/fileUtils.js';+import { FEDERATED_MEDIA_ASSET_TTL_MS } from '../../lib/federatedMediaWire.js';+import {+ callerAssetPrefix,+ describeFederatedMediaAsset,+ findFederatedMediaAsset,+ storeFederatedMediaAsset,+ sweepFederatedMediaAssets,+} from './assetStore.js';++// Minimal real PNG: the store sniffs magic bytes rather than trusting the+// declared Content-Type, so a placeholder buffer would be refused.+const PNG = Buffer.concat([+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ Buffer.from('portos-test-conditioning-image'),+]);+const JPEG = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff]), Buffer.from('jpeg-body')]);++let tempRoot;+let originalInbox;++beforeEach(() => {+ tempRoot = mkdtempSync(join(tmpdir(), 'portos-federated-inbox-'));+ originalInbox = PATHS.federatedMediaInbox;+ PATHS.federatedMediaInbox = tempRoot;+});++afterEach(() => {+ PATHS.federatedMediaInbox = originalInbox;+ rmSync(tempRoot, { recursive: true, force: true });+ vi.restoreAllMocks();+});++const sha256 = async (buf) => (await import('node:crypto'))+ .createHash('sha256').update(buf).digest('hex');++const upload = async (callerId, body = PNG, mimeType = 'image/png', digest) => storeFederatedMediaAsset({+ callerId,+ mimeType,+ declaredSha256: digest ?? await sha256(body),+ body,+});++describe('federated media asset store', () => {+ it('accepts a verified image and answers with a content-addressed, caller-scoped id', async () => {+ const stored = await upload('peer-a');+ expect(stored).toMatchObject({+ wireVersion: 1,+ sha256: await sha256(PNG),+ sizeBytes: PNG.length,+ mimeType: 'image/png',+ });+ expect(stored.assetId).toBe(`${callerAssetPrefix('peer-a')}-${await sha256(PNG)}`);+ await expect(findFederatedMediaAsset('peer-a', stored.assetId)).resolves.toMatchObject({+ mimeType: 'image/png',+ sizeBytes: PNG.length,+ });+ });++ // Content-addressing is what makes a reconcile after a restart cheap: the+ // consumer re-sends the same bytes and gets the same slot back rather than a+ // second staged copy.+ it('is idempotent for identical bytes from the same caller', async () => {+ const first = await upload('peer-a');+ const second = await upload('peer-a');+ expect(second.assetId).toBe(first.assetId);+ });++ // The caller half of the id is derived from the AUTHENTICATED caller, not+ // parsed from the request — so it is an authorization check, not a namespace.+ it('refuses to resolve another caller’s asset even given its exact id', async () => {+ const stored = await upload('peer-a');+ await expect(findFederatedMediaAsset('peer-b', stored.assetId)).resolves.toBeNull();+ await expect(describeFederatedMediaAsset('peer-b', stored.assetId))+ .rejects.toMatchObject({ status: 404, code: 'MEDIA_PROVIDER_ASSET_NOT_FOUND' });+ // Identical bytes from a different caller are a different asset, not a+ // shared one — otherwise one peer could observe another peer's uploads by+ // guessing content.+ const other = await upload('peer-b');+ expect(other.assetId).not.toBe(stored.assetId);+ });++ it('rejects a digest that does not match the bytes rather than staging them', async () => {+ await expect(upload('peer-a', PNG, 'image/png', 'f'.repeat(64)))+ .rejects.toMatchObject({ code: 'MEDIA_PROVIDER_ASSET_INTEGRITY' });+ await expect(sweepFederatedMediaAssets()).resolves.toBe(0);+ });++ // The declared Content-Type is the caller's word for what this is; the magic+ // bytes are what the generator will actually open.+ it('rejects bytes whose magic number contradicts the declared type', async () => {+ await expect(upload('peer-a', JPEG, 'image/png'))+ .rejects.toMatchObject({ code: 'MEDIA_PROVIDER_ASSET_TYPE_MISMATCH' });+ });++ it('rejects a media type outside the conditioning allowlist', async () => {+ await expect(upload('peer-a', PNG, 'image/gif'))+ .rejects.toMatchObject({ status: 415, code: 'MEDIA_PROVIDER_ASSET_TYPE_UNSUPPORTED' });+ });++ it('rejects an empty body instead of staging a zero-byte conditioning image', async () => {+ await expect(upload('peer-a', Buffer.alloc(0)))+ .rejects.toMatchObject({ code: 'MEDIA_PROVIDER_ASSET_EMPTY' });+ });++ // Staged bytes are another machine's, held to run one job. They expire rather+ // than accumulating — and an expired asset must read as absent BEFORE the+ // sweep runs, or a job admitted between sweeps would render from bytes the+ // TTL had already disowned.+ it('treats an expired asset as absent and sweeps it', async () => {+ const stored = await upload('peer-a');+ const staged = (await findFederatedMediaAsset('peer-a', stored.assetId)).path;+ const stale = (Date.now() - FEDERATED_MEDIA_ASSET_TTL_MS - 60_000) / 1000;+ utimesSync(staged, stale, stale);++ await expect(findFederatedMediaAsset('peer-a', stored.assetId)).resolves.toBeNull();+ await expect(sweepFederatedMediaAssets()).resolves.toBe(1);+ expect(existsSync(staged)).toBe(false);+ });++ it('leaves a live asset alone when sweeping', async () => {+ const stored = await upload('peer-a');+ await expect(sweepFederatedMediaAssets()).resolves.toBe(0);+ await expect(findFederatedMediaAsset('peer-a', stored.assetId)).resolves.not.toBeNull();+ });++ // The id shape is the containment check: anything that is not+ // <16-hex>-<64-hex> cannot address a file, so a traversal attempt never+ // reaches the resolver.+ it.each([+ ['a traversal attempt', '../../../etc/passwd'],+ ['an absolute path', '/etc/passwd'],+ ['a bare filename', 'photo.png'],+ ['a malformed pair', `${'0'.repeat(15)}-${'a'.repeat(64)}`],+ ])('refuses %s as an asset id', async (_name, assetId) => {+ await expect(findFederatedMediaAsset('peer-a', assetId)).resolves.toBeNull();+ });++ // A file dropped into the inbox by hand — the sweep and the resolver both key+ // on the id shape, so an unparseable name is unreachable rather than a path+ // the generator could be pointed at.+ it('ignores a hand-written file whose name is not a valid asset id', async () => {+ writeFileSync(join(tempRoot, 'not-an-asset.png'), PNG);+ await expect(findFederatedMediaAsset('peer-a', 'not-an-asset')).resolves.toBeNull();+ });++ it('answers a missing inbox directory with zero swept rather than throwing', async () => {+ rmSync(tempRoot, { recursive: true, force: true });+ await expect(sweepFederatedMediaAssets()).resolves.toBe(0);+ });+});diff --git a/server/services/federatedMedia/defaultRouting.js b/server/services/federatedMedia/defaultRouting.jsindex 228ffcf7d7..db219001bb 100644--- a/server/services/federatedMedia/defaultRouting.js+++ b/server/services/federatedMedia/defaultRouting.js@@ -31,6 +31,7 @@ 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';+import { collectRemoteInputAssets } from './inputAssets.js';// 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@@ -39,18 +40,20 @@ export { ROUTABLE_MEDIA_KINDS, normalizeMediaRoutingConfig };const trimmed = (value) => (typeof value === 'string' ? value.trim() : '');-// 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 wrong-// thing" — and that reasoning is STRONGER here, not weaker: an unattended run-// has nobody watching to notice the shot came back unconditioned. Keyed by the-// param a planner actually writes, valued by the noun the error names.+// Params the wire still cannot carry, each for a recorded reason rather than a+// missing feature: LoRA weights are a MODEL (ADR+// docs/decisions/2026-08-22-federated-media-input-assets.md rule 3), and+// IC-LoRA references / keyframes / a video to extend are multi-step CHAIN STATE+// this machine sequences (rule 4).+//+// Refusing beats dropping, because "silently dropping the source image a user+// pinned returns a plausible render of the wrong thing" — and that reasoning is+// STRONGER here, not weaker: an unattended run has nobody watching to notice the+// shot came back unconditioned. Init/reference/start/end frames are absent from+// this map on purpose: they are single-render conditioning and now cross under+// rule 1. Keyed by the param a planner actually writes, valued by the noun the+// error names.const UNSUPPORTED_CONDITIONING = Object.freeze({- initImagePath: 'an init image',- sourceImagePath: 'a source image',- sourceImageFile: 'a source image',- lastImageFile: 'an end frame',- referenceImagePaths: 'reference images',icReferenceVideoIds: 'IC-LoRA references',icReferenceImageFiles: 'IC-LoRA references',keyframes: 'keyframes',@@ -182,6 +185,15 @@ export async function resolveDefaultMediaRoute({ kind, params }) {);}assertRoutableConditioning(kind, params);+ // Single-render conditioning DOES cross (rule 1). Collected here so the+ // unattended lane sends exactly what the interactive routes send — same asset+ // upload, same capability gate in prepareRemoteMediaJob, same marker shape.+ // A planner writes image conditioning as `initImagePath`/`referenceImagePaths`+ // and video conditioning as `sourceImagePath`/`sourceImageFile`, so both+ // spellings feed the one role.+ const inputAssets = collectRemoteInputAssets(kind === 'image'+ ? { initImage: params?.initImagePath, referenceImages: params?.referenceImagePaths }+ : { sourceImage: params?.sourceImagePath || params?.sourceImageFile, lastImage: params?.lastImageFile });const request = buildFederatedMediaRequest({kind,engine: route.engine,@@ -198,6 +210,7 @@ export async function resolveDefaultMediaRoute({ kind, params }) {peerId: route.peerId,kind,request,+ inputAssets,});// ADR docs/decisions/2026-08-20-federated-visual-prompts.md, rule 5: a// STANDING route must refuse a non-tailnet peer. It exports every futurediff --git a/server/services/federatedMedia/defaultRouting.test.js b/server/services/federatedMedia/defaultRouting.test.jsindex 447bb85e0a..2803a91b5b 100644--- a/server/services/federatedMedia/defaultRouting.test.js+++ b/server/services/federatedMedia/defaultRouting.test.js@@ -169,15 +169,18 @@ describe('routed conditioning guard', () => {getSettings.mockResolvedValue({ federation: { mediaRouting: { image: route, video: route } } });});- // The interactive routes reject these rather than dropping them, because a- // render that silently ignores its source image comes back plausible and- // wrong. Unattended work has nobody watching, so the guard matters more here.+ // What still cannot cross, and why each one is a DECISION rather than a gap+ // (ADR docs/decisions/2026-08-22-federated-media-input-assets.md): a LoRA is+ // a model, not conditioning (rule 3); keyframes, a video to extend, and+ // IC-LoRA references are multi-step chain state this machine sequences+ // (rule 4). Refusing beats dropping — a render that silently ignores its+ // conditioning comes back plausible and wrong, and unattended work has nobody+ // watching to notice.it.each([- ['initImagePath', { initImagePath: '/x/a.png' }, 'an init image'],- ['sourceImagePath', { sourceImagePath: '/x/a.png' }, 'a source image'],- ['referenceImagePaths', { referenceImagePaths: ['/x/a.png'] }, 'reference images'],['loraFilenames', { loraFilenames: ['style.safetensors'] }, 'LoRA weights'],['keyframes', { keyframes: [{ at: 0 }] }, 'keyframes'],+ ['extendFromVideoId', { extendFromVideoId: 'clip-1' }, 'a source video to extend'],+ ['icReferenceVideoIds', { icReferenceVideoIds: ['clip-1'] }, 'IC-LoRA references'],])('refuses a routed image job carrying %s', async (_name, extra, label) => {await expect(resolveDefaultMediaRoute({ kind: 'image', params: { prompt: 'p', ...extra } })).rejects.toMatchObject({ code: 'MEDIA_PROVIDER_INPUT_UNSUPPORTED' });@@ -186,6 +189,29 @@ describe('routed conditioning guard', () => {expect(prepareRemoteMediaJob).not.toHaveBeenCalled();});+ // Single-render conditioning DOES cross now (rule 1), and the unattended lane+ // must send it the same way the interactive routes do — same marker shape,+ // same capability gate inside prepareRemoteMediaJob. A route that kept+ // refusing these would leave every conditioned Creative Director shot local.+ it.each([+ ['image', { initImagePath: 'a.png' }, [{ role: 'initImage', path: 'a.png' }]],+ ['image', { referenceImagePaths: ['a.png', 'b.png'] }, [+ { role: 'referenceImages', path: 'a.png' },+ { role: 'referenceImages', path: 'b.png' },+ ]],+ ['video', { sourceImagePath: 'a.png' }, [{ role: 'sourceImage', path: 'a.png' }]],+ ['video', { sourceImageFile: 'a.png', lastImageFile: 'b.png' }, [+ { role: 'sourceImage', path: 'a.png' },+ { role: 'lastImage', path: 'b.png' },+ ]],+ ])('routes a %s job carrying conditioning, handing its local paths to the submitter', async (kind, extra, expected) => {+ await expect(resolveDefaultMediaRoute({ kind, params: { prompt: 'p', ...extra } }))+ .resolves.toMatchObject({ peer: { id: 'peer-1' } });+ expect(prepareRemoteMediaJob).toHaveBeenCalledWith(+ expect.objectContaining({ inputAssets: expected }),+ );+ });+it('refuses a chained multi-chunk video, which the provider cannot continue', async () => {await expect(resolveDefaultMediaRoute({ kind: 'video', params: { prompt: 'p', chunks: 3 } })).rejects.toThrow(/chained chunks/);diff --git a/server/services/federatedMedia/inputAssets.js b/server/services/federatedMedia/inputAssets.jsnew file mode 100644index 0000000000..7cb8042591--- /dev/null+++ b/server/services/federatedMedia/inputAssets.js@@ -0,0 +1,121 @@+/**+ * Consumer-side conditioning-asset plumbing shared by the image and video+ * remote adapters (ADR+ * docs/decisions/2026-08-22-federated-media-input-assets.md rule 1).+ *+ * The central decision here is **what the queue marker persists**: LOCAL file+ * paths, not the provider-issued asset ids.+ *+ * An asset id is the provider's, and it expires — the staging area is TTL-swept+ * because it holds another machine's bytes. A marker that stored ids would+ * therefore reconcile after a restart into a `410 MEDIA_PROVIDER_ASSET_NOT_FOUND`+ * with nothing left on this side to recover from. Storing the source paths means+ * a replay re-stages the same bytes; the upload is content-addressed, so that+ * costs one transfer and yields the same id, never a duplicate render.+ *+ * The paths themselves never cross the wire — they are resolved to ids+ * immediately before submission and are meaningless to the peer, which is the+ * same reason the audio marker keeps its profile rather than a rendered prompt.+ */++import { z } from 'zod';+import {+ FEDERATED_MEDIA_ASSET_MAX_COUNT,+ FEDERATED_MEDIA_INPUT_ROLES,+} from '../../lib/federatedMediaWire.js';++// Deliberately NOT imported from remoteExecutor.js. That module statically+// pulls the peer registry and consumer, and this one is reached from the image+// and video generate routes — the same edge remoteSubmission.js lazily imports+// around so a partially-mocked route suite can still load. One three-line+// helper is cheaper than re-introducing that graph.+const inputAssetError = (message, code) => Object.assign(new Error(message), { code });++// Only `referenceImages` is a list on the wire; every other role is one slot.+const MULTI_ROLES = new Set(['referenceImages']);++export const remoteInputAssetSchema = z.object({+ role: z.enum(FEDERATED_MEDIA_INPUT_ROLES),+ path: z.string().trim().min(1).max(4096),+}).strict();++export const remoteInputAssetsSchema = z.array(remoteInputAssetSchema)+ .max(FEDERATED_MEDIA_ASSET_MAX_COUNT);++/**+ * Would this capability accept these conditioning assets? Consumer-side+ * preflight only — the provider re-checks everything at admission — but it+ * turns "the peer 400s after you commit" into "Generate tells you why".+ *+ * Absent `inputAssets` reads as UNSUPPORTED, never as unrestricted: a provider+ * predating this ADR omits the block and rejects the fields.+ *+ * @returns {string|null} a human-facing reason, or null when acceptable+ */+export function inputAssetRejection(capability, assets = []) {+ const limits = capability?.inputAssets;+ if (!assets.length) {+ return limits?.required+ ? `${capability?.modelName || 'The selected model'} renders only from a source image — add one, or pick a text-to-image model.`+ : null;+ }+ if (!limits) {+ return `${capability?.modelName || 'The selected model'} on this peer does not accept source or reference images. Render locally, or pick a peer model that does.`;+ }+ const roles = [...new Set(assets.map((asset) => asset.role))];+ const unsupported = roles.filter((role) => !limits.roles.includes(role));+ if (unsupported.length) {+ return `The selected peer model does not accept ${unsupported.join(' or ')}. Render locally, or clear that input.`;+ }+ if (assets.length > limits.maxCount) {+ return `The selected peer model accepts at most ${limits.maxCount} conditioning image(s); this render has ${assets.length}.`;+ }+ return null;+}++/**+ * Stage each local asset on the provider and fold the returned ids into the+ * wire request.+ *+ * @param {object} request - validated wire submission, without asset refs+ * @param {Array<{role: string, path: string}>} assets+ * @param {(path: string) => Promise<string>} stageAsset - uploads and returns an assetId+ * @returns {Promise<object>} the request with `{ assetId }` refs filled in+ */+export async function applyRemoteInputAssets(request, assets, stageAsset) {+ if (!Array.isArray(assets) || assets.length === 0) return request;+ const next = { ...request };+ for (const { role, path } of assets) {+ const assetId = await stageAsset(path);+ if (MULTI_ROLES.has(role)) {+ next[role] = [...(next[role] || []), { assetId }];+ } else if (next[role]) {+ // Two assets claiming one slot means the caller built the list wrong.+ // Overwriting would render from whichever happened to be last, so refuse.+ throw inputAssetError(`Remote render supplied more than one ${role}`, 'MEDIA_PROVIDER_INPUT_UNSUPPORTED');+ } else {+ next[role] = { assetId };+ }+ }+ return next;+}++/**+ * Collect the conditioning a local render would have used into the marker+ * shape, dropping empty slots. Returns `[]` when there is none, so a caller can+ * treat "no conditioning" and "conditioning this build does not know about"+ * identically.+ *+ * @param {object} slots - `{ [role]: string | string[] | null | undefined }`+ */+export function collectRemoteInputAssets(slots) {+ const assets = [];+ for (const role of FEDERATED_MEDIA_INPUT_ROLES) {+ const value = slots?.[role];+ if (!value) continue;+ for (const path of Array.isArray(value) ? value : [value]) {+ if (typeof path === 'string' && path.trim()) assets.push({ role, path: path.trim() });+ }+ }+ return assets;+}diff --git a/server/services/federatedMedia/remoteExecutor.js b/server/services/federatedMedia/remoteExecutor.jsindex 2c3ed8359e..777ebfc5cb 100644--- a/server/services/federatedMedia/remoteExecutor.js+++ b/server/services/federatedMedia/remoteExecutor.js@@ -17,14 +17,19 @@*/import { createWriteStream } from 'node:fs';-import { mkdir, rename, stat, unlink } from 'node:fs/promises';+import { mkdir, readFile, rename, stat, unlink } from 'node:fs/promises';import { createHash } from 'node:crypto';import { join } from 'node:path';import { Readable, Transform } from 'node:stream';import { pipeline } from 'node:stream/promises';-import { sha256File } from '../../lib/fileUtils.js';import {+ detectImageFormat, resolveImageInputPath, sha256File, sha256Text,+} from '../../lib/fileUtils.js';+import {+ FEDERATED_MEDIA_ASSET_MAX_BYTES,+ FEDERATED_MEDIA_ASSET_MIME_TYPES,FEDERATED_MEDIA_WIRE_VERSION,+ federatedMediaAssetSchema,federatedMediaProviderJobSchema,} from '../../lib/federatedMediaWire.js';import { peerFetch } from '../../lib/peerHttpClient.js';@@ -182,6 +187,66 @@ export function createRemoteMediaExecutor({return body;}+ /**+ * Upload one local conditioning image and return the provider's asset id+ * (ADR docs/decisions/2026-08-22-federated-media-input-assets.md rule 1).+ *+ * Memoized per run rather than persisted: an id belongs to the provider's+ * TTL-swept staging area, so caching it across a restart would produce a+ * confident reference to bytes that are gone. Within one run the cache means+ * a retried submission re-sends the body once, not once per attempt.+ *+ * The digest is computed here and echoed back by the provider; a mismatch+ * means the bytes it stored are not the bytes we sent, and rendering from+ * them would produce a plausible image of the wrong thing.+ */+ async function stageInputAsset(state, localPath) {+ const cached = state.assetIds.get(localPath);+ if (cached) return cached;++ // Re-anchored against the approved image roots on every attempt, exactly as+ // the LOCAL runner re-validates the same input. The marker is persisted,+ // user-editable queue state, so the path that becomes an outbound upload has+ // to be one this machine would have rendered from — a bare basename resolves,+ // and anything outside those roots resolves to null and is refused.+ const resolved = resolveImageInputPath(localPath);+ const body = resolved ? await readFile(resolved).catch(() => null) : null;+ if (!body) {+ throw remoteMediaError('A conditioning image for this render is missing or unreadable', {+ code: 'MEDIA_PROVIDER_INPUT_UNREADABLE',+ });+ }+ if (body.length > FEDERATED_MEDIA_ASSET_MAX_BYTES) {+ throw remoteMediaError('A conditioning image for this render is too large to send to a peer', {+ code: 'MEDIA_PROVIDER_ASSET_TOO_LARGE',+ });+ }+ const detected = detectImageFormat(body);+ if (!detected || !FEDERATED_MEDIA_ASSET_MIME_TYPES.includes(detected.mime)) {+ throw remoteMediaError('A conditioning image for this render is not a format peers accept', {+ code: 'MEDIA_PROVIDER_ASSET_TYPE_UNSUPPORTED',+ });+ }+ const digest = sha256Text(body);+ emitStatus(state.jobId, 'Sending source image to the remote provider');+ const response = await requestJson(state, '/api/federation/media/v1/assets', {+ method: 'POST',+ headers: { 'Content-Type': detected.mime, 'X-Content-SHA256': digest },+ body,+ }, {+ // A multi-megabyte upload legitimately outruns the JSON request timeout.+ timeoutMs: requestTimeoutMs * 10,+ });+ const parsed = federatedMediaAssetSchema.safeParse(response);+ if (!parsed.success || parsed.data.sha256 !== digest) {+ throw remoteMediaError('Remote media provider returned an invalid asset receipt', {+ code: 'MEDIA_PROVIDER_ASSET_INTEGRITY',+ });+ }+ state.assetIds.set(localPath, parsed.data.assetId);+ return parsed.data.assetId;+ }+function parseProviderJob(body, expectedId) {const parsed = federatedMediaProviderJobSchema.safeParse(body);if (!parsed.success || parsed.data.kind !== kind || (expectedId && parsed.data.id !== expectedId)) {@@ -431,7 +496,10 @@ export function createRemoteMediaExecutor({}async function runRemote(state, marker) {- const request = buildRequest(marker);+ // Awaited: an image/video marker resolves its persisted LOCAL conditioning+ // paths into provider asset ids here, inside this run's retry, cancel and+ // timeout envelope rather than before it.+ const request = await buildRequest(marker, { stageAsset: (path) => stageInputAsset(state, path) });const selection = { kind, engine: request.engine, modelId: request.modelId };if (!marker.reconcile) await preflight(state, selection);if (state.cancelRequested && !marker.reconcile && !state.submissionMayExist) throw canceledError();@@ -476,6 +544,11 @@ export function createRemoteMediaExecutor({// Absent on an interactive marker (and on any marker queued before this// shipped), which reads correctly as "not a standing route".standingRoute: marker.data.standingRoute === true,+ // localPath -> provider assetId, for this run only. Deliberately not+ // persisted: the id names a slot in the peer's TTL-swept staging area, so+ // a cached id that outlived the run would be a confident reference to+ // bytes that are gone. See federatedMedia/inputAssets.js.+ assetIds: new Map(),requestController: null,wake: null,};diff --git a/server/services/federatedMedia/remoteSubmission.js b/server/services/federatedMedia/remoteSubmission.jsindex f38f7de297..47a7357deb 100644--- a/server/services/federatedMedia/remoteSubmission.js+++ b/server/services/federatedMedia/remoteSubmission.js@@ -14,9 +14,13 @@import { ServerError } from '../../lib/errorHandler.js';import { FEDERATED_MEDIA_WIRE_VERSION } from '../../lib/federatedMediaWire.js';-import { federatedMediaVideoJobSubmissionSchema } from '../../lib/validation.js';+import { federatedMediaVideoJobSubmissionBaseSchema } from '../../lib/validation.js';+import { inputAssetRejection } from './inputAssets.js';-const partialVideoJobSubmissionSchema = federatedMediaVideoJobSubmissionSchema.partial();+// The BASE (un-refined) schema: this validates a partially-negotiated body,+// and Zod refuses `.partial()` on a schema carrying cross-field refinements.+// The full schema still guards the submitted body — see remote.js.+const partialVideoJobSubmissionSchema = federatedMediaVideoJobSubmissionBaseSchema.partial();/*** Negotiate frame and canvas constraints against the provider capability.@@ -174,9 +178,12 @@ export function negotiateVideoConstraints(request, capability) {* @param {string} args.peerId - Registered peer the user selected.* @param {'audio'|'image'|'video'} args.kind* @param {object} args.request - Validated wire submission (carries engine/modelId).+ * @param {Array<{role: string, path: string}>} [args.inputAssets] - Local+ * conditioning images for this render, checked against the peer's advertised+ * `inputAssets` block here and uploaded by the executor at submit time.* @returns {Promise<{peer: object, capability: object, request: object, remoteMedia: object}>}*/-export async function prepareRemoteMediaJob({ peerId, kind, request }) {+export async function prepareRemoteMediaJob({ peerId, kind, request, inputAssets = [] }) {// Imported lazily, not statically: the image/video generate routes reach this// module, and a static edge to the peer registry would drag it (and its// settings/DB dependencies) into every route suite's module graph — where a@@ -199,6 +206,13 @@ export async function prepareRemoteMediaJob({ peerId, kind, request }) {engine: request.engine,modelId: request.modelId,});+ // Advisory, like every other check here — the provider re-validates at+ // admission. Doing it now turns "the peer 400s after the user committed" into+ // a message on the Generate button naming the input to clear.+ const rejection = inputAssetRejection(capability, inputAssets);+ if (rejection) {+ throw new ServerError(rejection, { status: 400, code: 'MEDIA_PROVIDER_INPUT_UNSUPPORTED' });+ }const effectiveRequest = kind === 'video'? negotiateVideoConstraints(request, capability): request;@@ -212,6 +226,7 @@ export async function prepareRemoteMediaJob({ peerId, kind, request }) {reconcile: false,cancelRequested: false,request: effectiveRequest,+ ...(inputAssets.length ? { inputAssets } : {}),},};}diff --git a/server/services/federatedMediaProvider.js b/server/services/federatedMediaProvider.jsindex 5e1b3d45e3..8cdd126215 100644--- a/server/services/federatedMediaProvider.js+++ b/server/services/federatedMediaProvider.js@@ -18,11 +18,15 @@ import { findCachedRepoFiles, inspectModelCache } from '../lib/hfCache.js';import { getImageModels, getVideoModels, isEditOnly, isFlux2, repoForModel } from '../lib/mediaModels.js';import { isMiniMaxH3Runtime, usesDiffusersRunner } from '../lib/runners.js';import {+ FEDERATED_MEDIA_ASSET_MAX_BYTES,+ FEDERATED_MEDIA_ASSET_MAX_COUNT,+ FEDERATED_MEDIA_ASSET_MIME_TYPES,FEDERATED_MEDIA_RESULT_EXTENSION,FEDERATED_MEDIA_STALE_AFTER_MS,FEDERATED_MEDIA_WIRE_VERSION,KNOWN_MEDIA_KINDS,} from '../lib/federatedMediaWire.js';+import { findFederatedMediaAsset, sweepFederatedMediaAssets } from './federatedMedia/assetStore.js';import { getSettings } from './settings.js';import {cancelJob,@@ -72,18 +76,168 @@ const requiresConfiguredPython = (kind, model) => {return false;};-// The federated wire intentionally carries no source image, keyframes, or-// semantic video mode. Do not advertise a catalog model that cannot render a-// text-only request through this contract; otherwise the provider accepts the-// job, persists it, and only rejects it after a worker starts.+/**+ * Which conditioning slots this model can actually fill, and whether it can+ * render at all without one (ADR+ * docs/decisions/2026-08-22-federated-media-input-assets.md rule 1).+ *+ * Derived from what the LOCAL RUNNER accepts, not from a wish list: only the+ * FLUX.2 branch of imageGen/local.js passes `--reference-image`, and a video+ * model's start/end frame slots follow its declared `supportedModes`. Offering+ * a role the runner would drop is how a render silently comes back+ * unconditioned.+ *+ * @returns {{roles: string[], required: boolean}|null} `null` when this model+ * takes no conditioning at all.+ */+function federatedInputProfile(kind, model) {+ if (!model) return null;+ if (kind === 'image') {+ return {+ roles: isFlux2(model) ? ['initImage', 'referenceImages'] : ['initImage'],+ // An edit-only model has nothing to edit without one.+ required: isEditOnly(model),+ };+ }+ if (kind === 'video') {+ // No declared modes is the historical text-only assumption, not "all modes".+ const modes = Array.isArray(model.supportedModes) ? model.supportedModes : null;+ if (!modes) return null;+ const roles = [];+ if (modes.includes('image') || modes.includes('fflf')) roles.push('sourceImage');+ if (modes.includes('fflf')) roles.push('lastImage');+ if (!roles.length) return null;+ return { roles, required: !modes.includes('text') };+ }+ return null;+}++// Do not advertise a catalog model this contract cannot drive; otherwise the+// provider accepts the job, persists it, and only rejects it after a worker+// starts. Since conditioning images cross, "can render text-only" is no longer+// the bar — a model that needs an init image is advertisable, carrying+// `inputAssets.required` so a consumer knows to send one. An older consumer+// blind to that field submits text-only and gets a typed+// MEDIA_PROVIDER_INPUT_REQUIRED at admission rather than a stalled job.const supportsFederatedInput = (kind, model) => {- if (kind === 'image') return !isEditOnly(model);+ if (kind === 'image') return !isEditOnly(model) || !!federatedInputProfile(kind, model);if (kind === 'video') {- return !Array.isArray(model?.supportedModes) || model.supportedModes.includes('text');+ const modes = model?.supportedModes;+ if (!Array.isArray(modes) || modes.includes('text')) return true;+ return !!federatedInputProfile(kind, model);}return true;};+// The capability's input-asset block. Limits only — never a filename, digest, or+// anything derived from a prompt (ADR 2026-08-20 rule 3 still governs status).+const federatedInputAssetsBlock = (kind, model) => {+ const profile = federatedInputProfile(kind, model);+ if (!profile) return null;+ return {+ maxBytes: FEDERATED_MEDIA_ASSET_MAX_BYTES,+ maxCount: FEDERATED_MEDIA_ASSET_MAX_COUNT,+ mimeTypes: [...FEDERATED_MEDIA_ASSET_MIME_TYPES],+ roles: profile.roles,+ required: profile.required,+ };+};++// Which submission field feeds which slot, per kind. One table so the+// capability's advertised `roles`, this admission check, and the local-runner+// param names cannot drift into disagreeing about what a role means.+const INPUT_ASSET_FIELDS = Object.freeze({+ image: [+ { role: 'initImage', field: 'initImage', param: 'initImagePath', many: false },+ { role: 'referenceImages', field: 'referenceImages', param: 'referenceImagePaths', many: true },+ ],+ video: [+ { role: 'sourceImage', field: 'sourceImage', param: 'sourceImagePath', many: false },+ { role: 'lastImage', field: 'lastImage', param: 'lastImagePath', many: false },+ ],+});++/**+ * Turn a submission's asset REFERENCES into local paths, refusing anything this+ * capability did not advertise (ADR+ * docs/decisions/2026-08-22-federated-media-input-assets.md rule 1).+ *+ * Resolution happens at admission rather than at render time on purpose: an+ * expired or never-uploaded asset is a re-upload the consumer can act on right+ * now, whereas discovering it when a worker starts leaves a queued job that+ * fails minutes later with the consumer no longer watching.+ *+ * @returns {Promise<object>} local generator params for the resolved assets+ */+async function resolveSubmissionInputAssets({ callerId, input, capability }) {+ const fields = INPUT_ASSET_FIELDS[input.kind] || [];+ const requested = fields+ .map((entry) => ({+ ...entry,+ refs: entry.many+ ? (Array.isArray(input[entry.field]) ? input[entry.field] : [])+ : (input[entry.field] ? [input[entry.field]] : []),+ }))+ .filter((entry) => entry.refs.length > 0);+ const limits = capability.inputAssets;++ if (requested.length === 0) {+ if (limits?.required) {+ unavailable(+ 'Requested model renders only from a conditioning image; none was supplied',+ 'MEDIA_PROVIDER_INPUT_REQUIRED',+ 400,+ { roles: limits.roles },+ );+ }+ return {};+ }+ if (!limits) {+ unavailable(+ 'Requested model does not accept conditioning images',+ 'MEDIA_PROVIDER_INPUT_UNSUPPORTED',+ 400,+ );+ }+ const unsupportedRoles = requested.filter((entry) => !limits.roles.includes(entry.role));+ if (unsupportedRoles.length) {+ unavailable(+ `Requested model does not accept ${unsupportedRoles.map((entry) => entry.role).join(' or ')}`,+ 'MEDIA_PROVIDER_INPUT_UNSUPPORTED',+ 400,+ { roles: limits.roles },+ );+ }+ const total = requested.reduce((sum, entry) => sum + entry.refs.length, 0);+ if (total > limits.maxCount) {+ unavailable('Too many conditioning images for one job', 'MEDIA_PROVIDER_INPUT_UNSUPPORTED', 400, {+ maxCount: limits.maxCount,+ });+ }++ const params = {};+ for (const entry of requested) {+ const paths = [];+ for (const ref of entry.refs) {+ const found = await findFederatedMediaAsset(callerId, ref.assetId);+ if (!found) {+ // 410, not 404: the id was well-formed and caller-scoped, so "gone"+ // (expired, or swept) is the actionable reading — re-upload and retry.+ // The upload is content-addressed, so the retry keeps the same id.+ unavailable(+ 'A referenced conditioning image is no longer staged on the provider',+ 'MEDIA_PROVIDER_ASSET_NOT_FOUND',+ 410,+ { assetId: ref.assetId },+ );+ }+ paths.push(found.path);+ }+ params[entry.param] = entry.many ? paths : paths[0];+ }+ return params;+}+const requiredModelCacheGroups = (model) => {const groups = [];if (Array.isArray(model?.repoFiles)) {@@ -222,6 +376,7 @@ async function configuredAudioCapabilities(config) {defaultDurationSec: engine?.defaultDurationSec ?? null,lyrics: engine?.lyrics === true,acceptsLyrics: engine?.lyrics === true,+ inputAssets: null,autoDuration: engine?.autoDuration === true,frameStride: null,maxNumFrames: null,@@ -312,6 +467,7 @@ async function localGeneratorCapabilities(kind, pythonPath, { models, configureddefaultDurationSec: null,lyrics: false,acceptsLyrics: false,+ inputAssets: federatedInputAssetsBlock(kind, model),autoDuration: false,frameStride,maxNumFrames: Number.isFinite(maxNumFrames) && maxNumFrames > 0 ? maxNumFrames : null,@@ -646,6 +802,14 @@ export async function submitFederatedMediaJob({ callerId, config, input, idempot});}+ const inputAssetParams = await resolveSubmissionInputAssets({ callerId, input, capability });+ // Opportunistic, and only once a submission has actually arrived: a provider+ // nobody sends work to has nothing to sweep, and one that does gets swept on+ // every admission. Never allowed to fail the job it rode in on.+ sweepFederatedMediaAssets().catch((error) => {+ console.error(`❌ Federated media inbox sweep failed: ${error.message}`);+ });+const federatedMedia = {wireVersion: FEDERATED_MEDIA_WIRE_VERSION,callerInstanceId: callerId,@@ -655,7 +819,7 @@ export async function submitFederatedMediaJob({ callerId, config, input, idempotconst queued = enqueueJob({kind: input.kind,owner: jobOwner(callerId),- params: buildQueueParams(input, capability, federatedMedia),+ params: buildQueueParams(input, capability, federatedMedia, inputAssetParams),});return {replayed: false,@@ -672,7 +836,7 @@ export async function submitFederatedMediaJob({ callerId, config, input, idempot// image/video params keeps the queue's dispatcher on the local runner (see// getGenModuleForJob in mediaJobQueue/index.js): only the cloud-CLI modes// (codex/grok/agy) need an explicit mode, and those aren't federatable here.-function buildQueueParams(input, capability, federatedMedia) {+function buildQueueParams(input, capability, federatedMedia, inputAssetParams = {}) {if (input.kind === 'audio') {return {prompt: input.prompt,@@ -697,7 +861,14 @@ function buildQueueParams(input, capability, federatedMedia) {federatedMedia,};if (input.kind === 'image') {- return { ...shared, ...(input.guidance !== undefined ? { guidance: input.guidance } : {}) };+ return {+ ...shared,+ ...(input.guidance !== undefined ? { guidance: input.guidance } : {}),+ ...inputAssetParams,+ ...(input.initImageStrength !== undefined && inputAssetParams.initImagePath+ ? { initImageStrength: input.initImageStrength }+ : {}),+ };}// video — videoGen/local.js's generateVideo takes `guidanceScale`, not// `guidance` (image's field name).@@ -706,6 +877,17 @@ function buildQueueParams(input, capability, federatedMedia) {...(input.numFrames !== undefined ? { numFrames: input.numFrames } : {}),...(input.fps !== undefined ? { fps: input.fps } : {}),...(input.guidance !== undefined ? { guidanceScale: input.guidance } : {}),+ ...inputAssetParams,+ // `mode` is normally omitted so the queue's dispatcher keeps this on the+ // LOCAL runner (only the cloud-CLI modes need an explicit one). A+ // conditioned render must name its pipeline anyway: generateVideo infers+ // `image` from a bare sourceImagePath, but first-last-frame has to be+ // explicit or the end frame is silently dropped and the clip comes back as+ // a plain image-to-video. 'image'/'fflf' are pipeline semantics, not+ // backend tokens, so neither diverts the dispatcher off the local runner.+ ...(inputAssetParams.lastImagePath+ ? { mode: 'fflf' }+ : inputAssetParams.sourceImagePath ? { mode: 'image' } : {}),};}diff --git a/server/services/federatedMediaProvider.test.js b/server/services/federatedMediaProvider.test.jsindex 9326af224d..f79f1f3041 100644--- a/server/services/federatedMediaProvider.test.js+++ b/server/services/federatedMediaProvider.test.js@@ -522,7 +522,13 @@ describe('federated media provider — image/video kinds', () => {});});- it('does not advertise image-edit or image-only video models for this text-only wire', async () => {+ // These two models used to be hidden entirely: neither can render text-only,+ // and the wire carried no conditioning for them to render FROM. Now that+ // conditioning images cross (ADR+ // docs/decisions/2026-08-22-federated-media-input-assets.md rule 1) they are+ // advertisable — but only with `inputAssets.required`, which is what tells a+ // consumer the model is unusable without an init/source image.+ it('advertises input-only image and video models as requiring conditioning', async () => {const incompatibleImageConfig = () => ({enabled: true, maxQueuedJobs: 2, audioModels: [], videoModels: [],imageModels: [{ engine: 'local', modelId: 'edit-only' }],@@ -533,7 +539,11 @@ describe('federated media provider — image/video kinds', () => {}];state.cachedRepos = new Set(['example/edit']);const imageStatus = await getFederatedMediaProviderStatus(incompatibleImageConfig(), { kinds: ['image'] });- expect(imageStatus.capabilities[0]).toMatchObject({ ready: false, unavailableReason: 'unsupported-input' });+ expect(imageStatus.capabilities[0]).toMatchObject({+ ready: true,+ unavailableReason: null,+ inputAssets: expect.objectContaining({ required: true, roles: ['initImage'] }),+ });const incompatibleVideoConfig = () => ({enabled: true, maxQueuedJobs: 2, audioModels: [], imageModels: [],@@ -544,7 +554,70 @@ describe('federated media provider — image/video kinds', () => {}];state.cachedRepos = new Set(['example/image-only']);const videoStatus = await getFederatedMediaProviderStatus(incompatibleVideoConfig(), { kinds: ['video'] });- expect(videoStatus.capabilities[0]).toMatchObject({ ready: false, unavailableReason: 'unsupported-input' });+ expect(videoStatus.capabilities[0]).toMatchObject({+ ready: true,+ unavailableReason: null,+ inputAssets: expect.objectContaining({ required: true, roles: ['sourceImage'] }),+ });+ });++ // The other half of that trade: an older consumer cannot read `inputAssets`,+ // so it will submit text-only against a required-input model. It must get a+ // typed refusal it can surface, not a queued job that dies when a worker+ // picks it up minutes later.+ it('refuses a text-only submission to a model that requires conditioning', async () => {+ const editOnlyConfig = () => ({+ enabled: true, maxQueuedJobs: 2, audioModels: [], videoModels: [],+ imageModels: [{ engine: 'local', modelId: 'edit-only' }],+ });+ state.settings = { federation: { mediaProvider: editOnlyConfig() }, imageGen: { local: { pythonPath: '/usr/bin/python3' } } };+ state.imageModels = [{ id: 'edit-only', name: 'Edit only', repo: 'example/edit', editOnly: true }];+ state.cachedRepos = new Set(['example/edit']);++ await expect(submitFederatedMediaJob({+ callerId: 'peer-example',+ config: editOnlyConfig(),+ input: { kind: 'image', engine: 'local', modelId: 'edit-only', prompt: 'a lighthouse at dawn' },+ idempotencyKey: 'commission-edit-1',+ })).rejects.toMatchObject({ status: 400, code: 'MEDIA_PROVIDER_INPUT_REQUIRED' });+ expect(enqueueJob).not.toHaveBeenCalled();+ });++ it('refuses a conditioning role the selected model does not advertise', async () => {+ state.settings = {+ federation: { mediaProvider: imageConfig() },+ imageGen: { local: { pythonPath: '/usr/bin/python3' } },+ };+ state.cachedRepos = new Set(['black-forest-labs/FLUX.1-dev']);+ // FLUX.1-dev is not a FLUX.2 model, so only `initImage` is advertised —+ // its runner branch never passes reference images through.+ await expect(submitFederatedMediaJob({+ callerId: 'peer-example',+ config: imageConfig(),+ input: {+ ...imageInput(),+ referenceImages: [{ assetId: `${'0'.repeat(16)}-${'a'.repeat(64)}` }],+ },+ idempotencyKey: 'commission-refs-1',+ })).rejects.toMatchObject({ status: 400, code: 'MEDIA_PROVIDER_INPUT_UNSUPPORTED' });+ expect(enqueueJob).not.toHaveBeenCalled();+ });++ // 410 rather than 404: the id was well-formed and caller-scoped, so "gone"+ // is the actionable reading — re-upload (same content, same id) and retry.+ it('refuses a submission naming an asset that is not staged, without queueing it', async () => {+ state.settings = {+ federation: { mediaProvider: imageConfig() },+ imageGen: { local: { pythonPath: '/usr/bin/python3' } },+ };+ state.cachedRepos = new Set(['black-forest-labs/FLUX.1-dev']);+ await expect(submitFederatedMediaJob({+ callerId: 'peer-example',+ config: imageConfig(),+ input: { ...imageInput(), initImage: { assetId: `${'0'.repeat(16)}-${'a'.repeat(64)}` } },+ idempotencyKey: 'commission-missing-asset',+ })).rejects.toMatchObject({ status: 410, code: 'MEDIA_PROVIDER_ASSET_NOT_FOUND' });+ expect(enqueueJob).not.toHaveBeenCalled();});it('does not report image/video capabilities unless the caller opts into that kind', async () => {diff --git a/server/services/imageGen/remote.js b/server/services/imageGen/remote.jsindex ef29a00604..d8f7f483f2 100644--- a/server/services/imageGen/remote.js+++ b/server/services/imageGen/remote.js@@ -18,6 +18,7 @@ import { PATHS, atomicWrite } from '../../lib/fileUtils.js';import { FEDERATED_MEDIA_WIRE_VERSION } from '../../lib/federatedMediaWire.js';import { federatedMediaImageJobSubmissionSchema } from '../../lib/validation.js';import { createRemoteMediaExecutor } from '../federatedMedia/remoteExecutor.js';+import { applyRemoteInputAssets, remoteInputAssetsSchema } from '../federatedMedia/inputAssets.js';import { imageGenEvents } from '../imageGenEvents.js';const remoteImageMarkerSchema = z.object({@@ -29,10 +30,20 @@ const remoteImageMarkerSchema = z.object({// Optional so a marker already queued by an older build still validates; its// absence means "interactive", which is the correct reading of history.standingRoute: z.boolean().optional(),- // The full wire submission, re-validated on every replay. Persisted queue- // state is user-editable, so the body that actually leaves this machine is- // the one this schema accepted — not whatever the file happens to contain.+ // The full wire submission MINUS its conditioning refs, re-validated on every+ // replay. Persisted queue state is user-editable, so the body that actually+ // leaves this machine is the one this schema accepted — not whatever the file+ // happens to contain.request: federatedMediaImageJobSubmissionSchema,+ // LOCAL paths for this render's conditioning images, resolved to provider+ // asset ids immediately before each submission. Ids are NOT persisted here:+ // they name slots in the peer's TTL-swept staging area, so a reconcile after a+ // restart re-stages the same bytes instead of referencing bytes that are gone.+ // The paths themselves never cross the wire. See federatedMedia/inputAssets.js.+ //+ // Optional so a marker queued before this shipped still validates; absent+ // means the text-only render that build was the only one able to route.+ inputAssets: remoteInputAssetsSchema.optional(),}).passthrough();const executor = createRemoteMediaExecutor({@@ -40,7 +51,8 @@ const executor = createRemoteMediaExecutor({label: 'image',events: imageGenEvents,markerSchema: remoteImageMarkerSchema,- buildRequest: (marker) => marker.request,+ buildRequest: (marker, { stageAsset }) =>+ applyRemoteInputAssets(marker.request, marker.inputAssets, stageAsset),// PATHS is read per job (not captured at module load) so a test that swaps// the gallery directory still sees its own temp root. The `<jobId>.png`// filename is the same shape imageGen/local.js uses, which is what lets thediff --git a/server/services/imageGen/remote.test.js b/server/services/imageGen/remote.test.jsindex 217f939f11..0f970c4efc 100644--- a/server/services/imageGen/remote.test.js+++ b/server/services/imageGen/remote.test.js@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { createHash } from 'node:crypto';-import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -18,6 +18,15 @@ vi.mock('../../lib/fileUtils.js', async () => {return target[key];},}),+ // The real resolver closes over fileUtils' OWN `PATHS` binding, not the+ // proxy above, so it would validate a conditioning path against this+ // machine's actual gallery. Anchor it at the temp gallery instead — its+ // containment behavior is fileUtils' own suite's job; what matters here is+ // that the executor resolves before uploading, and refuses when it cannot.+ resolveImageInputPath: (raw) => {+ const candidate = join(tempImageDir, raw.split('/').pop());+ return existsSync(candidate) ? candidate : null;+ },};});@@ -202,6 +211,110 @@ describe('federated image consumer adapter', () => {expect(submission[1].headers['Idempotency-Key']).toBe(LOCAL_JOB_ID);});+ // ADR docs/decisions/2026-08-22-federated-media-input-assets.md rule 1. The+ // marker persists LOCAL paths; the ids are obtained immediately before+ // submission. That ordering is the whole point — an id names a slot in the+ // peer's TTL-swept staging area, so a marker holding one would reconcile after+ // a restart into a confident reference to bytes that are gone.+ describe('conditioning images', () => {+ const png = Buffer.concat([+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ Buffer.from('init-image-bytes'),+ ]);+ const ASSET_ID = `${'0'.repeat(16)}-${sha256(png)}`;++ const conditionedParams = () => {+ writeFileSync(join(tempImageDir, 'init.png'), png);+ const base = params();+ return {+ ...base,+ remoteMedia: {+ ...base.remoteMedia,+ inputAssets: [{ role: 'initImage', path: 'init.png' }],+ },+ };+ };++ const respondWith = (onSubmit) => {+ transport.fetch.mockImplementation(async (url, options) => {+ if (url.endsWith('/assets') && options.method === 'POST') {+ return jsonResponse({+ wireVersion: 1,+ assetId: ASSET_ID,+ sha256: sha256(png),+ sizeBytes: png.length,+ mimeType: 'image/png',+ expiresAt: '2026-08-22T18:00:00.000Z',+ }, 201);+ }+ if (url.endsWith('/jobs') && options.method === 'POST') return onSubmit(options);+ throw new Error(`Unexpected test URL: ${url}`);+ });+ };++ it('uploads the bytes with their digest, then submits the id in their place', async () => {+ respondWith(() => jsonResponse(providerJob('canceled'), 202));+ const terminal = captureTerminal(LOCAL_JOB_ID);+ await generateImage(conditionedParams()).catch(() => {});+ await terminal;++ const upload = transport.fetch.mock.calls.find(([url]) => url.endsWith('/assets'));+ expect(upload[1].headers).toMatchObject({+ 'Content-Type': 'image/png',+ 'X-Content-SHA256': sha256(png),+ });+ expect(Buffer.from(upload[1].body)).toEqual(png);++ const submission = transport.fetch.mock.calls+ .find(([url, options]) => url.endsWith('/jobs') && options.method === 'POST');+ expect(JSON.parse(submission[1].body).initImage).toEqual({ assetId: ASSET_ID });+ // The local path is machine-local routing state and never crosses.+ expect(submission[1].body).not.toContain('init.png');+ });++ // A provider echoing back a digest that is not ours means the bytes it+ // stored are not the bytes we sent; rendering from them would produce a+ // plausible image of the wrong thing.+ it('fails closed when the provider’s asset receipt does not match the sent bytes', async () => {+ transport.fetch.mockImplementation(async (url) => {+ if (!url.endsWith('/assets')) throw new Error(`Unexpected test URL: ${url}`);+ return jsonResponse({+ wireVersion: 1,+ assetId: `${'0'.repeat(16)}-${'b'.repeat(64)}`,+ sha256: 'b'.repeat(64),+ sizeBytes: png.length,+ mimeType: 'image/png',+ expiresAt: '2026-08-22T18:00:00.000Z',+ }, 201);+ });++ const terminal = captureTerminal(LOCAL_JOB_ID);+ await generateImage(conditionedParams()).catch(() => {});+ const outcome = await terminal;+ expect(outcome.type).toBe('failed');+ expect(transport.fetch.mock.calls.some(([url, options]) =>+ url.endsWith('/jobs') && options?.method === 'POST')).toBe(false);+ });++ // The marker is persisted, user-editable queue state, so a path it names+ // must still resolve inside the approved image roots at submit time.+ it('refuses to submit when the conditioning image no longer resolves', async () => {+ respondWith(() => jsonResponse(providerJob('queued'), 202));+ const base = params();+ const terminal = captureTerminal(LOCAL_JOB_ID);+ await generateImage({+ ...base,+ remoteMedia: {+ ...base.remoteMedia,+ inputAssets: [{ role: 'initImage', path: 'vanished.png' }],+ },+ }).catch(() => {});+ const outcome = await terminal;+ expect(outcome.type).toBe('failed');+ expect(transport.fetch).not.toHaveBeenCalled();+ });+ });+it('rejects a provider response whose kind is not image', async () => {transport.fetch.mockImplementation(async (url, options) => {if (url.endsWith('/jobs') && options.method === 'POST') {diff --git a/server/services/videoGen/remote.js b/server/services/videoGen/remote.jsindex 4044db64c2..c3911a3a2b 100644--- a/server/services/videoGen/remote.js+++ b/server/services/videoGen/remote.js@@ -19,6 +19,7 @@ import { generateThumbnail, optimizeForStreaming } from '../../lib/ffmpeg.js';import { FEDERATED_MEDIA_WIRE_VERSION } from '../../lib/federatedMediaWire.js';import { federatedMediaVideoJobSubmissionSchema } from '../../lib/validation.js';import { createRemoteMediaExecutor } from '../federatedMedia/remoteExecutor.js';+import { applyRemoteInputAssets, remoteInputAssetsSchema } from '../federatedMedia/inputAssets.js';import { videoGenEvents } from './events.js';import { mutateVideoHistory } from './history.js';@@ -31,9 +32,20 @@ const remoteVideoMarkerSchema = z.object({// Optional so a marker already queued by an older build still validates; its// absence means "interactive", which is the correct reading of history.standingRoute: z.boolean().optional(),- // Re-validated on every replay — persisted queue state is user-editable, so- // the body that leaves this machine is the one this schema accepted.+ // The full wire submission MINUS its conditioning refs, re-validated on every+ // replay. Persisted queue state is user-editable, so the body that actually+ // leaves this machine is the one this schema accepted — not whatever the file+ // happens to contain.request: federatedMediaVideoJobSubmissionSchema,+ // LOCAL paths for this render's conditioning images, resolved to provider+ // asset ids immediately before each submission. Ids are NOT persisted here:+ // they name slots in the peer's TTL-swept staging area, so a reconcile after a+ // restart re-stages the same bytes instead of referencing bytes that are gone.+ // The paths themselves never cross the wire. See federatedMedia/inputAssets.js.+ //+ // Optional so a marker queued before this shipped still validates; absent+ // means the text-only render that build was the only one able to route.+ inputAssets: remoteInputAssetsSchema.optional(),}).passthrough();const executor = createRemoteMediaExecutor({@@ -41,7 +53,8 @@ const executor = createRemoteMediaExecutor({label: 'video',events: videoGenEvents,markerSchema: remoteVideoMarkerSchema,- buildRequest: (marker) => marker.request,+ buildRequest: (marker, { stageAsset }) =>+ applyRemoteInputAssets(marker.request, marker.inputAssets, stageAsset),// `<jobId>.mp4` is videoGen/local.js's own filename shape, which is what the// provider-side result guard and the local history row both key on.resolveDestination: ({ jobId }) => ({ dir: PATHS.videos, filename: `${jobId}.mp4` }),