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
pin a queued job's conditioning against the inbox sweep, and ask before re-sending (#4348)
[._.]/ Adam Eivyd94041c4412a
diff --git a/server/lib/federatedMediaWire.js b/server/lib/federatedMediaWire.jsindex 05491292a8..17798bd24c 100644--- a/server/lib/federatedMediaWire.js+++ b/server/lib/federatedMediaWire.js@@ -1,3 +1,4 @@+import { createHash } from 'node:crypto';import { z } from 'zod';export const FEDERATED_MEDIA_WIRE_VERSION = 1;@@ -177,14 +178,47 @@ 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.+// Which of those roles hold a LIST rather than a single slot. One home, because+// both sides read it for opposite halves of the same fact: the consumer decides+// whether to append or assign when building the body, the provider decides+// whether to hand the runner an array or a scalar path. Disagreeing produces a+// shape mismatch that surfaces only as a wrong render.+export const FEDERATED_MEDIA_MULTI_INPUT_ROLES = Object.freeze(['referenceImages']);+export const isMultiInputRole = (role) => FEDERATED_MEDIA_MULTI_INPUT_ROLES.includes(role);++// `<callerHash>-<sha256>`. The caller half is derived from the AUTHENTICATED+// caller id and re-checked provider-side on every reference, so an asset id is+// unusable across callers even if it leaks.export const federatedMediaAssetIdSchema = z.string().trim().regex(/^[a-f0-9]{16}-[a-f0-9]{64}$/,- 'assetId must be a provider-issued <callerHash>-<sha256> pair',+ 'assetId must be a <callerHash>-<sha256> pair',);+/**+ * The caller half of an asset id.+ *+ * Lives in the WIRE module, not in the provider's store, because both sides need+ * it and they must agree exactly: the provider derives it from the authenticated+ * caller to scope what a peer may reference, and the consumer derives it from+ * its own instance id so it can name an asset it already uploaded — which is+ * what lets it check-then-skip instead of re-sending megabytes on every replay.+ *+ * @param {string} instanceId - the consumer's PortOS instance id+ */+export const federatedMediaAssetOwner = (instanceId) =>+ createHash('sha256').update(String(instanceId)).digest('hex').slice(0, 16);++/**+ * The full, fully-derivable asset id for a caller's copy of some bytes. Content+ * addressing is only useful if BOTH sides can compute the address; otherwise the+ * consumer has to upload just to learn the name of what it uploaded.+ *+ * @param {string} instanceId+ * @param {string} sha256 - hex digest of the asset bytes+ */+export const federatedMediaAssetId = (instanceId, sha256) =>+ `${federatedMediaAssetOwner(instanceId)}-${sha256}`;+// 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.diff --git a/server/routes/federatedMedia.js b/server/routes/federatedMedia.jsindex c92bacebb1..4f33a2e4fb 100644--- a/server/routes/federatedMedia.js+++ b/server/routes/federatedMedia.js@@ -34,6 +34,15 @@ import {const router = Router();+// Authorize BEFORE the body parser below, not inside the handler after it.+// Mounted the other way round, an unregistered caller's 32 MiB would be+// transferred and buffered in full before anything checked whether it was+// allowed to send it — work that was always going to end in a 403.+const assetAuth = asyncHandler(async (req, _res, next) => {+ req.federatedMediaCaller = (await authorizeFederatedMediaPeer(req)).callerId;+ next();+});+// 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@@ -54,10 +63,9 @@ router.get('/status', asyncHandler(async (req, res) => {// 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);+router.post('/assets', assetAuth, assetBody, asyncHandler(async (req, res) => {const stored = await storeFederatedMediaAsset({- callerId,+ callerId: req.federatedMediaCaller,mimeType: (req.get('Content-Type') || '').split(';')[0].trim().toLowerCase(),declaredSha256: req.get('X-Content-SHA256'),body: req.body,diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 3f2a12a0cf..4b49020df6 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -456,10 +456,7 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {// 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,- });+ const inputAssets = collectRemoteInputAssets('image', params);// 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.diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 28f93a53be..e13c3cafcc 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -1048,27 +1048,18 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {{ 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,- });+ // An end frame with no start frame is refused — but by the shared+ // `inputAssetRejection` inside prepareRemoteMediaJob, not here. Every lane+ // funnels through it, so the rule lives once instead of being written per+ // route and forgotten on the unattended one. (The wire schema refuses the+ // same shape but never sees it: a conditioning image reaches the request as+ // an asset id resolved at submit time.)+ const inputAssets = collectRemoteInputAssets('video', body);// `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') {+ if (body.mode !== undefined && body.mode !== impliedMode) {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.`,diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex be888da54c..500d6f9179 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -2364,20 +2364,27 @@ describe('videoGen routes', () => {}));});- // 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 () => {+ // Both frames reach the submitter as LOCAL paths for it to stage. The+ // "an end frame needs a start frame" rule is NOT asserted here: it moved+ // into the shared inputAssetRejection, which every lane funnels through and+ // which this suite mocks out — see remoteSubmission.test.js for its guard.+ it('hands a first-last-frame pair to the submitter as local paths', async () => {const r = await request(app).post('/api/video-gen/').send({prompt: 'a slow pan across a harbour',modelId: 'ltx2',+ mode: 'fflf',+ sourceImageFile: 'start.png',lastImageFile: 'end.png',mediaProviderPeerId: federatedPeerId,});- expect(r.status).toBe(400);- expect(r.body.code).toBe('MEDIA_PROVIDER_INPUT_UNSUPPORTED');- expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();+ expect(r.status).toBe(200);+ expect(prepareRemoteMediaJob).toHaveBeenCalledWith(expect.objectContaining({+ inputAssets: [+ { role: 'sourceImage', path: 'start.png' },+ { role: 'lastImage', path: 'end.png' },+ ],+ }));});// A LoRA is a MODEL, not conditioning, and remote model installation is outdiff --git a/server/services/audioGen/remote.test.js b/server/services/audioGen/remote.test.jsindex dee472d2cd..e711679caf 100644--- a/server/services/audioGen/remote.test.js+++ b/server/services/audioGen/remote.test.js@@ -31,6 +31,9 @@ vi.mock('../federatedMediaConsumer.js', () => ({vi.mock('../instances.js', () => ({getPeers: vi.fn(async () => federation.peers),+ // Used to derive the consumer's own half of a content-addressed asset id, so it+ // can ask the peer whether bytes are already staged before re-sending them.+ getInstanceId: vi.fn(async () => 'consumer-instance'),}));import { audioGenEvents } from './events.js';diff --git a/server/services/dataManager.busy.test.js b/server/services/dataManager.busy.test.jsindex dcaedad8e9..b222ac8ad3 100644--- a/server/services/dataManager.busy.test.js+++ b/server/services/dataManager.busy.test.js@@ -23,6 +23,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {const idle = () => Promise.resolve({ busy: false, reason: null });vi.mock('./dataManagerBusy.js', () => ({+ federatedMediaInboxBusy: vi.fn(idle),imageCleanTmpBusy: vi.fn(idle),trainingRunsBusy: vi.fn(idle),updateDetachedBusy: vi.fn(idle),diff --git a/server/services/dataManager.js b/server/services/dataManager.jsindex bdadd1e29e..8ef6dd1dce 100644--- a/server/services/dataManager.js+++ b/server/services/dataManager.js@@ -5,7 +5,9 @@ import { execFile } from '../lib/childProcess.js';import { promisify } from 'util';import { PATHS, ensureDir, isTopLevelEntryName } from '../lib/fileUtils.js';import { ServerError } from '../lib/errorHandler.js';-import { imageCleanTmpBusy, trainingRunsBusy, updateDetachedBusy } from './dataManagerBusy.js';+import {+ federatedMediaInboxBusy, imageCleanTmpBusy, trainingRunsBusy, updateDetachedBusy,+} from './dataManagerBusy.js';const execFileAsync = promisify(execFile);const DATA_DIR = PATHS.data;@@ -71,7 +73,7 @@ export const CATEGORIES = {// 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' },+ 'federated-media-inbox': { label: 'Federated Media Inbox', description: 'Source images peers uploaded for federated renders — expire automatically, safe to purge when no federated render is in flight', archivable: false, deletable: true, purgeScope: 'category', busyCheck: federatedMediaInboxBusy },'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/dataManager.strict.test.js b/server/services/dataManager.strict.test.jsindex c172dc1f80..4e470f4cd3 100644--- a/server/services/dataManager.strict.test.js+++ b/server/services/dataManager.strict.test.js@@ -25,6 +25,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {return makePathsProxy(actual, { dataRoot: testDataRoot });});vi.mock('./dataManagerBusy.js', () => ({+ federatedMediaInboxBusy: vi.fn(async () => ({ busy: false })),imageCleanTmpBusy: vi.fn(async () => ({ busy: false })),trainingRunsBusy: vi.fn(async () => ({ busy: false })),updateDetachedBusy: vi.fn(async () => ({ busy: false })),diff --git a/server/services/dataManagerBusy.js b/server/services/dataManagerBusy.jsindex c56f53bc3a..4217ff6fa5 100644--- a/server/services/dataManagerBusy.js+++ b/server/services/dataManagerBusy.js@@ -31,6 +31,7 @@ import { PATHS } from '../lib/fileUtils.js';import { isDetachedRunning } from '../lib/detachedSpawn.js';import { listJobs } from './mediaJobQueue/index.js';import { collectActiveCleanBasenames } from './imageCleanTmpGc.js';+import { collectActiveFederatedAssetBasenames } from './federatedMedia/assetStore.js';const IDLE = { busy: false, reason: null };@@ -76,6 +77,37 @@ export async function imageCleanTmpBusy({ jobs = null, entries = null } = {}) {};}+/**+ * `data/federated-media-inbox` — conditioning images an allowlisted peer+ * uploaded for a federated render (#4348). Structurally the same case as+ * `image-clean-tmp`: ephemeral image inputs a queued or running media job is+ * about to read, reached through the same `initImagePath`-style params.+ *+ * The pinned set comes from the SAME predicate the TTL sweep uses+ * (`collectActiveFederatedAssetBasenames`), so a one-click purge can never be+ * more permissive than the automatic sweep that deliberately leaves them alone.+ * Destroying one of these is worse than the local case: the consumer already+ * committed and is waiting, and nothing re-uploads — the asset ids were resolved+ * at admission, and this side never tells the peer the bytes went away.+ *+ * Not scoped to one kind: image and video jobs both stage conditioning here.+ *+ * @param {{ jobs?: Array, entries?: string[] }} [state] - injected job list / directory listing+ * @returns {Promise<{ busy: boolean, reason: string|null }>}+ */+export async function federatedMediaInboxBusy({ jobs = null, entries = null } = {}) {+ const pinned = collectActiveFederatedAssetBasenames(jobs || listJobs());+ if (pinned.size === 0) return IDLE;+ const present = entries+ || (await listDirEntries(join(PATHS.data, 'federated-media-inbox'))).filter(e => e.isFile()).map(e => e.name);+ const atRisk = present.filter(name => pinned.has(name));+ if (atRisk.length === 0) return IDLE;+ return {+ busy: true,+ reason: `A federated render is queued or running and ${atRisk.length} source image(s) here belong to it — purge once it finishes.`+ };+}+/*** `data/training-runs`. Two sources, because neither alone covers a restart:*diff --git a/server/services/federatedMedia/assetStore.js b/server/services/federatedMedia/assetStore.jsindex c352cea3c8..8ccedaab2c 100644--- a/server/services/federatedMedia/assetStore.js+++ b/server/services/federatedMedia/assetStore.js@@ -20,12 +20,12 @@* state (rule 4). Neither is conditioning, and neither has a field on the wire.*/-import { readdir, rm, stat, writeFile } from 'node:fs/promises';+import { readdir, rm, stat, utimes } from 'node:fs/promises';import { join } from 'node:path';import { ServerError } from '../../lib/errorHandler.js';import {+ atomicWrite,detectImageFormat,- ensureDir,PATHS,resolveFederatedMediaAsset,sha256Text,@@ -36,29 +36,23 @@ import {FEDERATED_MEDIA_ASSET_MIME_TYPES,FEDERATED_MEDIA_ASSET_TTL_MS,FEDERATED_MEDIA_WIRE_VERSION,+ federatedMediaAssetId,federatedMediaAssetIdSchema,+ federatedMediaAssetOwner,} 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))];+// 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.const MIME_BY_EXTENSION = Object.fromEntries(FEDERATED_MEDIA_ASSET_MIME_TYPES.map((mime) => [FEDERATED_MEDIA_ASSET_EXTENSION[mime], mime]),);+const ASSET_EXTENSIONS = Object.keys(MIME_BY_EXTENSION);const expiresAtFor = (mtimeMs) => new Date(mtimeMs + FEDERATED_MEDIA_ASSET_TTL_MS).toISOString();@@ -73,25 +67,28 @@ const expiresAtFor = (mtimeMs) => new Date(mtimeMs + FEDERATED_MEDIA_ASSET_TTL_Mexport 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;+ if (!parsed.data.startsWith(`${federatedMediaAssetOwner(callerId)}-`)) return null;- for (const extension of ASSET_EXTENSIONS) {+ // The mime type is not encoded in the id, so the extension has to be probed.+ // Concurrently: a webp asset would otherwise always pay for two misses first,+ // and the not-found path (the 410 a consumer acts on) always pays for all of+ // them.+ const found = await Promise.all(ASSET_EXTENSIONS.map(async (extension) => {// 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;+ if (!path) return null;const info = await stat(path).catch(() => null);- if (!info?.isFile()) continue;- if (now - info.mtimeMs > FEDERATED_MEDIA_ASSET_TTL_MS) continue;+ if (!info?.isFile() || now - info.mtimeMs > FEDERATED_MEDIA_ASSET_TTL_MS) return null;return {path,mimeType: MIME_BY_EXTENSION[extension],sizeBytes: info.size,expiresAt: expiresAtFor(info.mtimeMs),};- }- return null;+ }));+ return found.find(Boolean) || null;}/**@@ -141,13 +138,23 @@ export async function storeFederatedMediaAsset({ callerId, mimeType, declaredShareject('Conditioning image digest does not match its bytes', 'MEDIA_PROVIDER_ASSET_INTEGRITY');}- const assetId = `${callerAssetPrefix(callerId)}-${sha256}`;- await ensureDir(PATHS.federatedMediaInbox);+ const assetId = federatedMediaAssetId(callerId, sha256);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);+ // Already staged? The bytes are identical by construction (the name IS the+ // digest), so a replay only needs its TTL refreshed — one utimes rather than+ // rewriting up to 32 MiB to change a timestamp.+ //+ // atomicWrite (temp + rename) on the miss, not a plain writeFile: this file's+ // NAME asserts a digest that findFederatedMediaAsset trusts without re-hashing,+ // so a torn write would leave a file claiming a hash its bytes do not have —+ // and the runner would render from a truncated image. It ensures the directory+ // itself, so no separate ensureDir.+ const existing = await stat(path).catch(() => null);+ if (existing?.isFile() && existing.size === body.length) {+ await utimes(path, new Date(), new Date());+ } else {+ await atomicWrite(path, body);+ }return {wireVersion: FEDERATED_MEDIA_WIRE_VERSION,assetId,@@ -180,25 +187,84 @@ export async function describeFederatedMediaAsset(callerId, assetId) {};}+// The queue params a federated job reaches its conditioning through — the same+// four the provider writes in `buildQueueParams`. Listed here because this is+// where they have to be READ back to keep them alive.+const CONDITIONING_PARAMS = ['initImagePath', 'referenceImagePaths', 'sourceImagePath', 'lastImagePath'];+/**- * 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.+ * Basenames any queued or running job still depends on.+ *+ * The age gate alone is a BACKSTOP, not the safety property — the same lesson+ * `imageCleanTmpGc.js` records for the structurally identical `image-clean-tmp`+ * dir. A federated job queued behind a long render or a first-run model+ * download can easily sit past the TTL, and deleting its staged init image+ * leaves the runner unable to open a file the consumer already committed to and+ * is waiting on. Nothing re-uploads it: the ids were resolved at admission, and+ * the provider never tells the consumer the bytes went away.*- * Never throws: a sweep failure must not fail the job that triggered it.+ * Pure over its argument so it is testable without the real queue, and shared+ * with the Data Manager purge probe so a one-click purge can never be more+ * permissive than the automatic sweep.*+ * @param {object[]} jobs+ * @returns {Set<string>}+ */+export function collectActiveFederatedAssetBasenames(jobs = []) {+ const keep = new Set();+ for (const job of Array.isArray(jobs) ? jobs : []) {+ // Only in-flight work pins bytes; a terminal job has already rendered.+ if (job?.status !== 'queued' && job?.status !== 'running') continue;+ for (const key of CONDITIONING_PARAMS) {+ const value = job.params?.[key];+ for (const path of Array.isArray(value) ? value : [value]) {+ if (typeof path !== 'string' || !path) continue;+ const base = path.split(/[/\\]/).pop();+ if (base) keep.add(base);+ }+ }+ }+ return keep;+}++// A sweep only ever finds different files across a TTL boundary, so running one+// per submission is pure duplicate work when several jobs arrive together.+// Throttling is a redundancy guard here, not a concurrency control.+const SWEEP_MIN_INTERVAL_MS = 5 * 60 * 1000;+let lastSweptAt = 0;++/** @internal — lets a test drive consecutive sweeps without waiting out the throttle. */+export const __resetFederatedAssetSweepForTests = () => { lastSweptAt = 0; };++/**+ * Drop expired staged assets that no in-flight job still needs.+ *+ * 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 as work arrives.+ *+ * Never throws — a sweep failure must not fail the job that triggered it.+ *+ * @param {object} [options]+ * @param {object[]} [options.jobs] - live queue jobs, for the active-job pin* @returns {Promise<number>} files removed*/-export async function sweepFederatedMediaAssets({ now = Date.now() } = {}) {+export async function sweepFederatedMediaAssets({ jobs = [], now = Date.now(), force = false } = {}) {+ if (!force && now - lastSweptAt < SWEEP_MIN_INTERVAL_MS) return 0;+ lastSweptAt = now;const entries = await readdir(PATHS.federatedMediaInbox).catch(() => null);if (!entries) return 0;- let removed = 0;- for (const name of entries) {+ const pinned = collectActiveFederatedAssetBasenames(jobs);+ const candidates = entries.filter((name) => !pinned.has(name));+ const stats = await Promise.all(candidates.map(async (name) => {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;- }+ return { path, info: await stat(path).catch(() => null) };+ }));+ const expired = stats.filter(({ info }) =>+ info?.isFile() && now - info.mtimeMs > FEDERATED_MEDIA_ASSET_TTL_MS);+ const results = await Promise.all(expired.map(({ path }) =>+ rm(path, { force: true }).then(() => true, () => false)));+ const removed = results.filter(Boolean).length;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.jsindex f99243a468..163e2b8b1d 100644--- a/server/services/federatedMedia/assetStore.test.js+++ b/server/services/federatedMedia/assetStore.test.js@@ -3,9 +3,13 @@ import { mkdtempSync, rmSync, writeFileSync, existsSync, utimesSync } from 'nodeimport { 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,+ FEDERATED_MEDIA_ASSET_TTL_MS,+ federatedMediaAssetId,+} from '../../lib/federatedMediaWire.js';+import {+ __resetFederatedAssetSweepForTests,+ collectActiveFederatedAssetBasenames,describeFederatedMediaAsset,findFederatedMediaAsset,storeFederatedMediaAsset,@@ -27,6 +31,9 @@ beforeEach(() => {tempRoot = mkdtempSync(join(tmpdir(), 'portos-federated-inbox-'));originalInbox = PATHS.federatedMediaInbox;PATHS.federatedMediaInbox = tempRoot;+ // The sweep throttles itself to one run per few minutes, which is a+ // duplicate-work guard rather than a behavior these cases are asserting.+ __resetFederatedAssetSweepForTests();});afterEach(() => {@@ -54,7 +61,7 @@ describe('federated media asset store', () => {sizeBytes: PNG.length,mimeType: 'image/png',});- expect(stored.assetId).toBe(`${callerAssetPrefix('peer-a')}-${await sha256(PNG)}`);+ expect(stored.assetId).toBe(federatedMediaAssetId('peer-a', await sha256(PNG)));await expect(findFederatedMediaAsset('peer-a', stored.assetId)).resolves.toMatchObject({mimeType: 'image/png',sizeBytes: PNG.length,@@ -87,7 +94,7 @@ describe('federated media asset store', () => {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);+ await expect(sweepFederatedMediaAssets({ force: true })).resolves.toBe(0);});// The declared Content-Type is the caller's word for what this is; the magic@@ -118,13 +125,13 @@ describe('federated media asset store', () => {utimesSync(staged, stale, stale);await expect(findFederatedMediaAsset('peer-a', stored.assetId)).resolves.toBeNull();- await expect(sweepFederatedMediaAssets()).resolves.toBe(1);+ await expect(sweepFederatedMediaAssets({ force: true })).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(sweepFederatedMediaAssets({ force: true })).resolves.toBe(0);await expect(findFederatedMediaAsset('peer-a', stored.assetId)).resolves.not.toBeNull();});@@ -150,6 +157,60 @@ describe('federated media asset store', () => {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);+ await expect(sweepFederatedMediaAssets({ force: true })).resolves.toBe(0);+ });++ // The age gate is a BACKSTOP, not the safety property — the lesson+ // imageCleanTmpGc.js records for the structurally identical image-clean-tmp+ // dir. A federated job queued behind a long render or a first-run model+ // download can easily sit past the TTL, and deleting its staged init image+ // leaves the runner unable to open a file the consumer already committed to+ // and is waiting on. Nothing re-uploads it: the ids were resolved at+ // admission, and the provider never tells the consumer the bytes went away.+ describe('active-job pinning', () => {+ const expire = (path) => {+ const stale = (Date.now() - FEDERATED_MEDIA_ASSET_TTL_MS - 60_000) / 1000;+ utimesSync(path, stale, stale);+ };++ it('spares an expired asset a queued job still depends on', async () => {+ const stored = await upload('peer-a');+ const staged = (await findFederatedMediaAsset('peer-a', stored.assetId)).path;+ expire(staged);++ const jobs = [{ status: 'queued', params: { initImagePath: staged } }];+ await expect(sweepFederatedMediaAssets({ jobs, force: true })).resolves.toBe(0);+ expect(existsSync(staged)).toBe(true);+ });++ it('collects every conditioning slot, from paths and from arrays alike', () => {+ const keep = collectActiveFederatedAssetBasenames([+ { status: 'running', params: { initImagePath: '/inbox/a.png' } },+ { status: 'queued', params: { referenceImagePaths: ['/inbox/b.png', '/inbox/c.png'] } },+ { status: 'queued', params: { sourceImagePath: '/inbox/d.png', lastImagePath: '/inbox/e.png' } },+ ]);+ expect([...keep].sort()).toEqual(['a.png', 'b.png', 'c.png', 'd.png', 'e.png']);+ });++ // A terminal job has already rendered, so its conditioning is free to go —+ // otherwise the inbox would only ever grow.+ it.each([['completed'], ['failed'], ['canceled']])('does not pin a %s job', async (status) => {+ const stored = await upload('peer-a');+ const staged = (await findFederatedMediaAsset('peer-a', stored.assetId)).path;+ expire(staged);++ const jobs = [{ status, params: { initImagePath: staged } }];+ await expect(sweepFederatedMediaAssets({ jobs, force: true })).resolves.toBe(1);+ expect(existsSync(staged)).toBe(false);+ });++ it('tolerates jobs with no conditioning params at all', () => {+ expect(collectActiveFederatedAssetBasenames([+ { status: 'queued', params: { prompt: 'a lighthouse' } },+ { status: 'running' },+ null,+ ]).size).toBe(0);+ expect(collectActiveFederatedAssetBasenames().size).toBe(0);+ });});});diff --git a/server/services/federatedMedia/defaultRouting.js b/server/services/federatedMedia/defaultRouting.jsindex db219001bb..387d86d73b 100644--- a/server/services/federatedMedia/defaultRouting.js+++ b/server/services/federatedMedia/defaultRouting.js@@ -185,15 +185,11 @@ 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 });+ // Single-render conditioning DOES cross (rule 1). Collected through the same+ // shared reader the interactive routes use, so the unattended lane sends+ // exactly what they send — same param aliases, same asset upload, same+ // capability gate in prepareRemoteMediaJob, same marker shape.+ const inputAssets = collectRemoteInputAssets(kind, params);const request = buildFederatedMediaRequest({kind,engine: route.engine,diff --git a/server/services/federatedMedia/inputAssets.js b/server/services/federatedMedia/inputAssets.jsindex 7cb8042591..4b72dd91f5 100644--- a/server/services/federatedMedia/inputAssets.js+++ b/server/services/federatedMedia/inputAssets.js@@ -22,6 +22,7 @@ import { z } from 'zod';import {FEDERATED_MEDIA_ASSET_MAX_COUNT,FEDERATED_MEDIA_INPUT_ROLES,+ isMultiInputRole,} from '../../lib/federatedMediaWire.js';// Deliberately NOT imported from remoteExecutor.js. That module statically@@ -31,8 +32,30 @@ import {// 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']);+// Which local param each role reads, per kind. One table, because three call+// sites were hand-writing this map and two of them had already drifted: the+// unattended router accepted `sourceImagePath` OR `sourceImageFile` (a planner+// writes either) while the interactive video route read only `sourceImageFile`.+// A divergence like that is invisible from either file.+const ROLE_PARAMS = Object.freeze({+ image: Object.freeze({+ initImage: ['initImagePath'],+ referenceImages: ['referenceImagePaths'],+ }),+ video: Object.freeze({+ sourceImage: ['sourceImagePath', 'sourceImageFile'],+ lastImage: ['lastImagePath', 'lastImageFile'],+ }),+});++// Pairings a single render cannot be missing half of. Enforced HERE rather than+// per-lane because all four lanes (Image Gen, Video Gen, the unattended router,+// and any future one) funnel through `inputAssetRejection` — the video route had+// its own copy and the unattended router had none, which is exactly the+// nobody-is-watching case where a silently-wrong render costs most.+const REQUIRED_PAIRS = Object.freeze([+ { role: 'lastImage', needs: 'sourceImage', why: 'a first-last-frame render needs both ends' },+]);export const remoteInputAssetSchema = z.object({role: z.enum(FEDERATED_MEDIA_INPUT_ROLES),@@ -54,15 +77,25 @@ export const remoteInputAssetsSchema = z.array(remoteInputAssetSchema)*/export function inputAssetRejection(capability, assets = []) {const limits = capability?.inputAssets;+ const model = capability?.modelName || 'The selected model';+ // The remedy names the kind the caller is actually rendering. Saying+ // "pick a text-to-image model" to someone blocked on a VIDEO render is worse+ // than saying nothing — it points at a control that is not on their screen.+ const textToKind = `text-to-${capability?.kind === 'video' ? 'video' : 'image'}`;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.`+ ? `${model} renders only from a source image — add one, or pick a ${textToKind} 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.`;+ return `${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))];+ for (const pair of REQUIRED_PAIRS) {+ if (roles.includes(pair.role) && !roles.includes(pair.needs)) {+ return `This render supplies a ${pair.role} with no ${pair.needs} — ${pair.why}. Add one, or render on this instance.`;+ }+ }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.`;@@ -77,17 +110,31 @@ export function inputAssetRejection(capability, assets = []) {* Stage each local asset on the provider and fold the returned ids into the* wire request.*+ * The assembled body is re-validated against the kind's REFINED schema before it+ * is returned. The marker stores the base (un-refined) shape because at rest the+ * asset refs are legitimately absent — but the body that leaves this machine is+ * complete, so its cross-field rules ("a strength needs an image", "an end frame+ * needs a start frame") have something to check and must run here. Skipping that+ * left them enforced only on the provider, which cannot tell the user which+ * local input to clear.+ ** @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+ * @param {import('zod').ZodTypeAny} [schema] - refined schema for the finished body* @returns {Promise<object>} the request with `{ assetId }` refs filled in*/-export async function applyRemoteInputAssets(request, assets, stageAsset) {+export async function applyRemoteInputAssets(request, assets, stageAsset, schema) {if (!Array.isArray(assets) || assets.length === 0) return request;+ // Staged CONCURRENTLY: up to 8 independent multi-megabyte uploads, each one+ // otherwise waiting out the last inside the run's timeout envelope. The+ // results are folded in afterwards, in the original order, because reference+ // order is conditioning order.+ const assetIds = await Promise.all(assets.map(({ path }) => stageAsset(path)));const next = { ...request };- for (const { role, path } of assets) {- const assetId = await stageAsset(path);- if (MULTI_ROLES.has(role)) {+ for (const [index, { role }] of assets.entries()) {+ const assetId = assetIds[index];+ if (isMultiInputRole(role)) {next[role] = [...(next[role] || []), { assetId }];} else if (next[role]) {// Two assets claiming one slot means the caller built the list wrong.@@ -97,21 +144,37 @@ export async function applyRemoteInputAssets(request, assets, stageAsset) {next[role] = { assetId };}}- return next;+ const parsed = schema?.safeParse(next);+ if (parsed && !parsed.success) {+ throw inputAssetError(+ `Assembled federated request is invalid: ${parsed.error.issues.map((i) => i.message).join(', ')}`,+ 'MEDIA_PROVIDER_INPUT_UNSUPPORTED',+ );+ }+ return parsed ? parsed.data : 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.+ * shape, reading each role off the LOCAL params by the one shared table above.+ * Returns `[]` when there is none, so a caller can treat "no conditioning" and+ * "conditioning this build does not know about" identically.+ *+ * Takes the raw params rather than a hand-built `{ role: path }` object on+ * purpose: three call sites used to build that object themselves and two of them+ * disagreed about which param a video start frame lives in.*- * @param {object} slots - `{ [role]: string | string[] | null | undefined }`+ * @param {'image'|'video'} kind+ * @param {object} params - local job params*/-export function collectRemoteInputAssets(slots) {+export function collectRemoteInputAssets(kind, params) {+ const roleParams = ROLE_PARAMS[kind];+ if (!roleParams) return [];const assets = [];for (const role of FEDERATED_MEDIA_INPUT_ROLES) {- const value = slots?.[role];+ // First param that carries a value wins; the aliases are spellings of one+ // slot, never two separate inputs.+ const value = roleParams[role]?.map((key) => params?.[key]).find(Boolean);if (!value) continue;for (const path of Array.isArray(value) ? value : [value]) {if (typeof path === 'string' && path.trim()) assets.push({ role, path: path.trim() });diff --git a/server/services/federatedMedia/remoteExecutor.js b/server/services/federatedMedia/remoteExecutor.jsindex 777ebfc5cb..9b937b6788 100644--- a/server/services/federatedMedia/remoteExecutor.js+++ b/server/services/federatedMedia/remoteExecutor.js@@ -29,6 +29,7 @@ import {FEDERATED_MEDIA_ASSET_MAX_BYTES,FEDERATED_MEDIA_ASSET_MIME_TYPES,FEDERATED_MEDIA_WIRE_VERSION,+ federatedMediaAssetId,federatedMediaAssetSchema,federatedMediaProviderJobSchema,} from '../../lib/federatedMediaWire.js';@@ -36,7 +37,7 @@ import { peerFetch } from '../../lib/peerHttpClient.js';import { peerBaseUrl } from '../../lib/peerUrl.js';import { readResponseJson } from '../../lib/readResponseJson.js';import { resolveFederatedMediaProvider } from '../federatedMediaConsumer.js';-import { getPeers } from '../instances.js';+import { getInstanceId, getPeers } from '../instances.js';import { isTailnetPeer } from '../../lib/tailnetPeer.js';const RETRYABLE_HTTP_STATUSES = new Set([408, 425, 429]);@@ -210,24 +211,46 @@ export function createRemoteMediaExecutor({// 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) {+ const info = resolved ? await stat(resolved).catch(() => null) : null;+ if (!info?.isFile()) {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) {+ if (info.size > 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',});}+ // Streamed above 512 KB, so the ASK-FIRST path below never buffers a+ // multi-megabyte image just to learn it is already staged.+ const digest = await sha256File(resolved);+ const assetId = federatedMediaAssetId(await getInstanceId(), digest);++ // Ask before sending. The id is fully derivable from our own instance id and+ // the content digest — that is what content addressing buys — so a job+ // replayed after a restart, or a second render from the same init image,+ // costs one small GET instead of re-sending up to 32 MiB. A 404 is the+ // normal miss (never uploaded, or swept), not an error.+ const staged = await requestJson(state, `/api/federation/media/v1/assets/${assetId}`)+ .then((body) => federatedMediaAssetSchema.safeParse(body), () => null);+ if (staged?.success && staged.data.sha256 === digest) {+ state.assetIds.set(localPath, staged.data.assetId);+ return staged.data.assetId;+ }++ const body = await readFile(resolved).catch(() => null);+ if (!body) {+ throw remoteMediaError('A conditioning image for this render is missing or unreadable', {+ code: 'MEDIA_PROVIDER_INPUT_UNREADABLE',+ });+ }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',@@ -238,6 +261,9 @@ export function createRemoteMediaExecutor({timeoutMs: requestTimeoutMs * 10,});const parsed = federatedMediaAssetSchema.safeParse(response);+ // The provider echoes back the digest it computed. 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.if (!parsed.success || parsed.data.sha256 !== digest) {throw remoteMediaError('Remote media provider returned an invalid asset receipt', {code: 'MEDIA_PROVIDER_ASSET_INTEGRITY',diff --git a/server/services/federatedMedia/remoteSubmission.test.js b/server/services/federatedMedia/remoteSubmission.test.jsindex a8fa57b34f..56eebeebf2 100644--- a/server/services/federatedMedia/remoteSubmission.test.js+++ b/server/services/federatedMedia/remoteSubmission.test.js@@ -208,3 +208,77 @@ describe('prepareRemoteMediaJob', () => {expect(result.remoteMedia.request.numFrames).toBe(33);});});++// Every lane — Image Gen, Video Gen, and the unattended router — funnels through+// prepareRemoteMediaJob, so the conditioning gate lives HERE rather than being+// written per route. It previously was written per route, and the unattended+// lane (the one with nobody watching) had no copy at all.+describe('prepareRemoteMediaJob — conditioning gate', () => {+ const PEER_ID = '00000000-0000-4000-8000-000000000001';+ const peer = { id: PEER_ID, enabled: true };+ const capability = (inputAssets, kind = 'video') => ({+ kind, engine: 'local', modelId: 'ltx2', modelName: 'LTX-2', inputAssets,+ });+ const roles = (...names) => ({+ roles: names, required: false, maxCount: 8, maxBytes: 1, mimeTypes: ['image/png'],+ });++ const prepare = (kind, request, inputAssets, cap) => {+ mockGetPeers.mockResolvedValue([peer]);+ mockResolveFederatedMediaProvider.mockResolvedValue({ peer, capability: cap });+ return prepareRemoteMediaJob({ peerId: PEER_ID, kind, request, inputAssets });+ };++ it('refuses an end frame with no start frame, on every lane at once', async () => {+ await expect(prepare(+ 'video',+ { kind: 'video', engine: 'local', modelId: 'ltx2', prompt: 'a harbour' },+ [{ role: 'lastImage', path: 'end.png' }],+ capability(roles('sourceImage', 'lastImage')),+ )).rejects.toMatchObject({ status: 400, code: 'MEDIA_PROVIDER_INPUT_UNSUPPORTED' });+ });++ it('accepts the pair, and persists the local paths on the marker', async () => {+ const assets = [+ { role: 'sourceImage', path: 'start.png' },+ { role: 'lastImage', path: 'end.png' },+ ];+ const result = await prepare(+ 'video',+ { kind: 'video', engine: 'local', modelId: 'ltx2', prompt: 'a harbour' },+ assets,+ capability(roles('sourceImage', 'lastImage')),+ );+ // Local paths, never provider asset ids — those name slots in a TTL-swept+ // area and would reconcile into a reference to bytes that are gone.+ expect(result.remoteMedia.inputAssets).toEqual(assets);+ });++ // The remedy has to name the kind the caller is actually rendering; pointing a+ // blocked VIDEO render at "a text-to-image model" names a control that is not+ // on their screen.+ it('names the caller’s own kind when a model needs conditioning it did not get', async () => {+ await expect(prepare(+ 'video',+ { kind: 'video', engine: 'local', modelId: 'ltx2', prompt: 'a harbour' },+ [],+ capability({ ...roles('sourceImage'), required: true }),+ )).rejects.toThrow(/text-to-video/);++ await expect(prepare(+ 'image',+ { kind: 'image', engine: 'local', modelId: 'flux', prompt: 'a lighthouse', width: 512, height: 512 },+ [],+ capability({ ...roles('initImage'), required: true }, 'image'),+ )).rejects.toThrow(/text-to-image/);+ });++ it('refuses a role the peer model never advertised', async () => {+ await expect(prepare(+ 'image',+ { kind: 'image', engine: 'local', modelId: 'flux', prompt: 'a lighthouse', width: 512, height: 512 },+ [{ role: 'referenceImages', path: 'ref.png' }],+ capability(roles('initImage'), 'image'),+ )).rejects.toMatchObject({ status: 400, code: 'MEDIA_PROVIDER_INPUT_UNSUPPORTED' });+ });+});diff --git a/server/services/federatedMediaProvider.js b/server/services/federatedMediaProvider.jsindex 8cdd126215..fc341d9f12 100644--- a/server/services/federatedMediaProvider.js+++ b/server/services/federatedMediaProvider.js@@ -24,8 +24,10 @@ import {FEDERATED_MEDIA_RESULT_EXTENSION,FEDERATED_MEDIA_STALE_AFTER_MS,FEDERATED_MEDIA_WIRE_VERSION,+ isMultiInputRole,KNOWN_MEDIA_KINDS,} from '../lib/federatedMediaWire.js';+import { resolveVideoSupportedModes } from '../lib/videoModeProfiles.js';import { findFederatedMediaAsset, sweepFederatedMediaAssets } from './federatedMedia/assetStore.js';import { getSettings } from './settings.js';import {@@ -100,9 +102,13 @@ function federatedInputProfile(kind, 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;+ // Through the registry resolver, not a local Array.isArray fallback: it is+ // the single documented answer to "which modes does this model support?",+ // and its undeclared-model fallback is the OPPOSITE of a naive null (see+ // server/services/videoGen/modeContract.js, which rules against restating+ // this).+ const modes = resolveVideoSupportedModes(model);+ if (!Array.isArray(modes) || modes.length === 0) return null;const roles = [];if (modes.includes('image') || modes.includes('fflf')) roles.push('sourceImage');if (modes.includes('fflf')) roles.push('lastImage');@@ -119,14 +125,15 @@ function federatedInputProfile(kind, model) {// `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.+//+// That leaves only VIDEO with anything to reject here: every image model is now+// drivable (an edit-only one via its init image), so the old `isEditOnly` filter+// is gone rather than kept as a condition that can no longer be false. A video+// model with declared modes but neither `text` nor a frame slot has no way in.const supportsFederatedInput = (kind, model) => {- if (kind === 'image') return !isEditOnly(model) || !!federatedInputProfile(kind, model);- if (kind === 'video') {- const modes = model?.supportedModes;- if (!Array.isArray(modes) || modes.includes('text')) return true;- return !!federatedInputProfile(kind, model);- }- return true;+ if (kind !== 'video') return true;+ if (resolveVideoSupportedModes(model).includes('text')) return true;+ return !!federatedInputProfile(kind, model);};// The capability's input-asset block. Limits only — never a filename, digest, or@@ -148,12 +155,12 @@ const federatedInputAssetsBlock = (kind, model) => {// 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 },+ { role: 'initImage', param: 'initImagePath' },+ { role: 'referenceImages', param: 'referenceImagePaths' },],video: [- { role: 'sourceImage', field: 'sourceImage', param: 'sourceImagePath', many: false },- { role: 'lastImage', field: 'lastImage', param: 'lastImagePath', many: false },+ { role: 'sourceImage', param: 'sourceImagePath' },+ { role: 'lastImage', param: 'lastImagePath' },],});@@ -172,12 +179,11 @@ const INPUT_ASSET_FIELDS = Object.freeze({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]] : []),- }))+ // A role is named for the submission field it lands in, so there is no+ // second mapping to consult. `.flat()` handles the scalar, array, and+ // absent shapes without restating which roles are lists — that fact lives+ // once, in the wire module.+ .map((entry) => ({ ...entry, refs: [input[entry.role]].flat().filter(Boolean) })).filter((entry) => entry.refs.length > 0);const limits = capability.inputAssets;@@ -217,23 +223,24 @@ async function resolveSubmissionInputAssets({ callerId, input, capability }) {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);+ // Independent lookups; `Promise.all` preserves order, which matters because+ // reference-image order is conditioning order.+ const found = await Promise.all(entry.refs.map((ref) =>+ findFederatedMediaAsset(callerId, ref.assetId)));+ const missing = entry.refs[found.findIndex((hit) => !hit)];+ if (missing) {+ // 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: missing.assetId },+ );}- params[entry.param] = entry.many ? paths : paths[0];+ const paths = found.map((hit) => hit.path);+ params[entry.param] = isMultiInputRole(entry.role) ? paths : paths[0];}return params;}@@ -806,7 +813,10 @@ export async function submitFederatedMediaJob({ callerId, config, input, idempot// 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) => {+ // Jobs are passed in so the sweep can PIN an in-flight job's conditioning:+ // the TTL alone is a backstop, and a job queued behind a long render can+ // outlive it (imageCleanTmpGc.js records the same lesson for its dir).+ sweepFederatedMediaAssets({ jobs: listJobs() }).catch((error) => {console.error(`❌ Federated media inbox sweep failed: ${error.message}`);});diff --git a/server/services/imageGen/remote.js b/server/services/imageGen/remote.jsindex 42ca59a68b..86ff42e9c1 100644--- a/server/services/imageGen/remote.js+++ b/server/services/imageGen/remote.js@@ -16,7 +16,10 @@ import { join } from 'node:path';import { z } from 'zod';import { PATHS, atomicWrite } from '../../lib/fileUtils.js';import { FEDERATED_MEDIA_WIRE_VERSION } from '../../lib/federatedMediaWire.js';-import { federatedMediaImageJobSubmissionBaseSchema } from '../../lib/validation.js';+import {+ federatedMediaImageJobSubmissionBaseSchema,+ federatedMediaImageJobSubmissionSchema,+} from '../../lib/validation.js';import { createRemoteMediaExecutor } from '../federatedMedia/remoteExecutor.js';import { applyRemoteInputAssets, remoteInputAssetsSchema } from '../federatedMedia/inputAssets.js';import { imageGenEvents } from '../imageGenEvents.js';@@ -51,8 +54,9 @@ const executor = createRemoteMediaExecutor({label: 'image',events: imageGenEvents,markerSchema: remoteImageMarkerSchema,- buildRequest: (marker, { stageAsset }) =>- applyRemoteInputAssets(marker.request, marker.inputAssets, stageAsset),+ buildRequest: (marker, { stageAsset }) => applyRemoteInputAssets(+ marker.request, marker.inputAssets, stageAsset, federatedMediaImageJobSubmissionSchema,+ ),// 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 0f970c4efc..9bbdd0d371 100644--- a/server/services/imageGen/remote.test.js+++ b/server/services/imageGen/remote.test.js@@ -3,6 +3,7 @@ import { createHash } from 'node:crypto';import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';+import { federatedMediaAssetId } from '../../lib/federatedMediaWire.js';let tempImageDir;const transport = vi.hoisted(() => ({ fetch: vi.fn() }));@@ -40,6 +41,9 @@ vi.mock('../federatedMediaConsumer.js', () => ({vi.mock('../instances.js', () => ({getPeers: vi.fn(async () => federation.peers),+ // Used to derive the consumer's own half of a content-addressed asset id, so it+ // can ask the peer whether bytes are already staged before re-sending them.+ getInstanceId: vi.fn(async () => 'consumer-instance'),}));import { imageGenEvents } from '../imageGenEvents.js';@@ -221,7 +225,7 @@ describe('federated image consumer adapter', () => {Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),Buffer.from('init-image-bytes'),]);- const ASSET_ID = `${'0'.repeat(16)}-${sha256(png)}`;+ const ASSET_ID = federatedMediaAssetId('consumer-instance', sha256(png));const conditionedParams = () => {writeFileSync(join(tempImageDir, 'init.png'), png);@@ -272,6 +276,38 @@ describe('federated image consumer adapter', () => {expect(submission[1].body).not.toContain('init.png');});+ // Content addressing only pays off if BOTH sides can compute the address.+ // The consumer derives the id from its own instance id and the file digest,+ // asks, and sends nothing when the peer already has it — which is what makes+ // a reconcile after a restart, or a second render from the same init image,+ // cost one small GET instead of up to 32 MiB.+ it('asks before sending, and skips the upload when the peer already has the bytes', async () => {+ transport.fetch.mockImplementation(async (url, options) => {+ if (url.includes('/assets/')) {+ return jsonResponse({+ wireVersion: 1,+ assetId: ASSET_ID,+ sha256: sha256(png),+ sizeBytes: png.length,+ mimeType: 'image/png',+ expiresAt: '2026-08-22T18:00:00.000Z',+ });+ }+ if (url.endsWith('/jobs') && options.method === 'POST') return jsonResponse(providerJob('canceled'), 202);+ throw new Error(`Unexpected test URL: ${url}`);+ });++ const terminal = captureTerminal(LOCAL_JOB_ID);+ await generateImage(conditionedParams()).catch(() => {});+ await terminal;++ expect(transport.fetch.mock.calls.some(([url, options]) =>+ url.endsWith('/assets') && options?.method === 'POST')).toBe(false);+ 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 });+ });+// 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.diff --git a/server/services/videoGen/remote.js b/server/services/videoGen/remote.jsindex e7e0e28259..ea4685d32a 100644--- a/server/services/videoGen/remote.js+++ b/server/services/videoGen/remote.js@@ -17,7 +17,10 @@ import { z } from 'zod';import { PATHS } from '../../lib/fileUtils.js';import { generateThumbnail, optimizeForStreaming } from '../../lib/ffmpeg.js';import { FEDERATED_MEDIA_WIRE_VERSION } from '../../lib/federatedMediaWire.js';-import { federatedMediaVideoJobSubmissionBaseSchema } from '../../lib/validation.js';+import {+ federatedMediaVideoJobSubmissionBaseSchema,+ federatedMediaVideoJobSubmissionSchema,+} from '../../lib/validation.js';import { createRemoteMediaExecutor } from '../federatedMedia/remoteExecutor.js';import { applyRemoteInputAssets, remoteInputAssetsSchema } from '../federatedMedia/inputAssets.js';import { videoGenEvents } from './events.js';@@ -53,8 +56,9 @@ const executor = createRemoteMediaExecutor({label: 'video',events: videoGenEvents,markerSchema: remoteVideoMarkerSchema,- buildRequest: (marker, { stageAsset }) =>- applyRemoteInputAssets(marker.request, marker.inputAssets, stageAsset),+ buildRequest: (marker, { stageAsset }) => applyRemoteInputAssets(+ marker.request, marker.inputAssets, stageAsset, federatedMediaVideoJobSubmissionSchema,+ ),// `<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` }),diff --git a/server/services/videoGen/remote.test.js b/server/services/videoGen/remote.test.jsindex a705b8e58e..7a7f0b6853 100644--- a/server/services/videoGen/remote.test.js+++ b/server/services/videoGen/remote.test.js@@ -42,6 +42,9 @@ vi.mock('../federatedMediaConsumer.js', () => ({vi.mock('../instances.js', () => ({getPeers: vi.fn(async () => federation.peers),+ // Used to derive the consumer's own half of a content-addressed asset id, so it+ // can ask the peer whether bytes are already staged before re-sending them.+ getInstanceId: vi.fn(async () => 'consumer-instance'),}));import { videoGenEvents } from './events.js';