Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: centralize video constraint negotiation in remoteSubmission and bound resolutionOptions (#4681)
[._.]/ Adam Eivy108a280dd9af
diff --git a/server/lib/federatedMediaWire.js b/server/lib/federatedMediaWire.jsindex 713cf9b5a9..88cb0fc29d 100644--- a/server/lib/federatedMediaWire.js+++ b/server/lib/federatedMediaWire.js@@ -171,10 +171,10 @@ export const federatedMediaCapabilitySchema = z.object({frameStride: z.number().int().positive().nullable().optional(),maxNumFrames: z.number().int().positive().nullable().optional(),resolutionOptions: z.array(z.object({- w: z.number().int().positive(),- h: z.number().int().positive(),+ w: z.number().int().min(64).max(4096),+ h: z.number().int().min(64).max(4096),label: z.string().trim().max(120).optional(),- })).nullable().optional(),+ })).max(100).nullable().optional(),});const federatedMediaQueueStatusSchema = z.object({diff --git a/server/services/federatedMedia/defaultRouting.js b/server/services/federatedMedia/defaultRouting.jsindex 49da12793a..f37cd89645 100644--- a/server/services/federatedMedia/defaultRouting.js+++ b/server/services/federatedMedia/defaultRouting.js@@ -222,7 +222,7 @@ export async function resolveDefaultMediaRoute({ kind, params }) {// module is imported by agent-tool suites that mock the settings/DB layer,// and a static edge to the peer registry would drag that graph into them.const { prepareRemoteMediaJob } = await import('./remoteSubmission.js');- const { peer, capability, remoteMedia } = await prepareRemoteMediaJob({+ const { peer, capability, request: finalRequest, remoteMedia } = await prepareRemoteMediaJob({peerId: route.peerId,kind,request,@@ -244,52 +244,12 @@ export async function resolveDefaultMediaRoute({ kind, params }) {{ status: 403, code: 'MEDIA_ROUTING_PEER_NOT_TAILNET' },);}- // Frame constraint negotiation (issue #4681): re-snap numFrames against the- // remote provider capability's frameStride and maxNumFrames down to the- // nearest legal n*stride + 1 (never up — spending unbudgeted provider GPU- // time). Reject rather than snap when the request cannot be made legal at all.- let finalRequest = request;- if (kind === 'video' && finalRequest.numFrames !== undefined) {- const frameStride = Number(capability?.frameStride);- const maxNumFrames = Number(capability?.maxNumFrames);- const hasStride = Number.isFinite(frameStride) && frameStride > 0;- const hasMax = Number.isFinite(maxNumFrames);-- if (hasStride || hasMax) {- const requestedFrames = Number(finalRequest.numFrames);- if (requestedFrames < 1) {- throw new ServerError(- `Requested frame count (${requestedFrames}) is invalid for ${capability?.modelName || capability?.modelId || route.modelId}`,- { status: 400, code: 'MEDIA_PROVIDER_INPUT_UNSUPPORTED' },- );- }- let legalFrames = requestedFrames;- if (hasStride) {- legalFrames = Math.floor((legalFrames - 1) / frameStride) * frameStride + 1;- }- if (hasMax && legalFrames > maxNumFrames) {- legalFrames = hasStride- ? Math.floor((maxNumFrames - 1) / frameStride) * frameStride + 1- : maxNumFrames;- }- if (legalFrames < 1) {- throw new ServerError(- `Requested frame count (${requestedFrames}) cannot be satisfied by ${capability?.modelName || capability?.modelId || route.modelId}`,- { status: 400, code: 'MEDIA_PROVIDER_INPUT_UNSUPPORTED' },- );- }- if (legalFrames !== requestedFrames) {- console.log(`🌐 Federated render: adjusted numFrames from ${requestedFrames} to ${legalFrames} for ${capability?.modelName || capability?.modelId || route.modelId}`);- finalRequest = { ...finalRequest, numFrames: legalFrames };- }- }- }// Stamp the marker so the boundary survives the job, not just the enqueue.// The tailnet check above ran against the peer record as it looked NOW; a// queued or reconciling job re-resolves its peer from the registry on every// request, and that record can change (a host edited from a .ts.net name to a// LAN address) between enqueue and submit. The executor re-checks on this bit.- return { peer, request: finalRequest, remoteMedia: { ...remoteMedia, request: finalRequest, standingRoute: true } };+ return { peer, capability, request: finalRequest, remoteMedia: { ...remoteMedia, standingRoute: true } };}/**diff --git a/server/services/federatedMedia/defaultRouting.test.js b/server/services/federatedMedia/defaultRouting.test.jsindex a977268664..c772d9b3ec 100644--- a/server/services/federatedMedia/defaultRouting.test.js+++ b/server/services/federatedMedia/defaultRouting.test.js@@ -17,9 +17,15 @@ vi.mock('../settings.js', () => ({}},}));-vi.mock('./remoteSubmission.js', () => ({- prepareRemoteMediaJob: (...args) => prepareRemoteMediaJob(...args),-}));+vi.mock('./remoteSubmission.js', async () => {+ const actual = await vi.importActual('./remoteSubmission.js');+ return {+ ...actual,+ prepareRemoteMediaJob: (...args) => prepareRemoteMediaJob(...args),+ };+});++const { negotiateVideoConstraints } = await import('./remoteSubmission.js');const enqueueJob = vi.fn(() => ({ jobId: 'mj-test' }));vi.mock('../mediaJobQueue/index.js', () => ({ enqueueJob: (...args) => enqueueJob(...args) }));@@ -36,10 +42,26 @@ beforeEach(() => {getSettings.mockReset();enqueueJob.mockClear();prepareRemoteMediaJob.mockReset();- prepareRemoteMediaJob.mockImplementation(async ({ peerId, kind, request }) => ({- peer: { id: peerId, name: 'Render Box', host: 'render-box.tailnet-example.ts.net' },- remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request },- }));+ prepareRemoteMediaJob.mockImplementation(async ({ peerId, kind, request }) => {+ const capability = {+ kind,+ engine: request.engine,+ modelId: request.modelId,+ ready: true,+ frameStride: null,+ maxNumFrames: null,+ resolutionOptions: null,+ };+ const effectiveRequest = kind === 'video'+ ? negotiateVideoConstraints(request, capability)+ : request;+ return {+ peer: { id: peerId, name: 'Render Box', host: 'render-box.tailnet-example.ts.net' },+ capability,+ request: effectiveRequest,+ remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request: effectiveRequest },+ };+ });});describe('normalizeMediaRoutingConfig', () => {@@ -418,17 +440,22 @@ describe('frame constraint negotiation (issue #4681)', () => {});it('snaps a Wan-2.2-shaped capability frame count (33 -> 33 and 40 -> 33 with stride 8)', async () => {- prepareRemoteMediaJob.mockImplementation(async ({ peerId, kind, request }) => ({- peer: { id: peerId, name: 'Render Box', host: 'render-box.tailnet-example.ts.net' },- capability: {+ prepareRemoteMediaJob.mockImplementation(async ({ peerId, kind, request }) => {+ const capability = {kind,engine: request.engine,modelId: request.modelId,ready: true,frameStride: 8,- },- remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request },- }));+ };+ const effectiveRequest = negotiateVideoConstraints(request, capability);+ return {+ peer: { id: peerId, name: 'Render Box', host: 'render-box.tailnet-example.ts.net' },+ capability,+ request: effectiveRequest,+ remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request: effectiveRequest },+ };+ });const exact = await resolveDefaultMediaRoute({kind: 'video',@@ -446,18 +473,23 @@ describe('frame constraint negotiation (issue #4681)', () => {});it('snaps frame count down with stride 4 and maxNumFrames', async () => {- prepareRemoteMediaJob.mockImplementation(async ({ peerId, kind, request }) => ({- peer: { id: peerId, name: 'Render Box', host: 'render-box.tailnet-example.ts.net' },- capability: {+ prepareRemoteMediaJob.mockImplementation(async ({ peerId, kind, request }) => {+ const capability = {kind,engine: request.engine,modelId: request.modelId,ready: true,frameStride: 4,maxNumFrames: 33,- },- remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request },- }));+ };+ const effectiveRequest = negotiateVideoConstraints(request, capability);+ return {+ peer: { id: peerId, name: 'Render Box', host: 'render-box.tailnet-example.ts.net' },+ capability,+ request: effectiveRequest,+ remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request: effectiveRequest },+ };+ });const result = await resolveDefaultMediaRoute({kind: 'video',@@ -468,17 +500,22 @@ describe('frame constraint negotiation (issue #4681)', () => {});it('leaves frame count untouched when capability has no frameStride', async () => {- prepareRemoteMediaJob.mockImplementation(async ({ peerId, kind, request }) => ({- peer: { id: peerId, name: 'Render Box', host: 'render-box.tailnet-example.ts.net' },- capability: {+ prepareRemoteMediaJob.mockImplementation(async ({ peerId, kind, request }) => {+ const capability = {kind,engine: request.engine,modelId: request.modelId,ready: true,frameStride: null,- },- remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request },- }));+ };+ const effectiveRequest = negotiateVideoConstraints(request, capability);+ return {+ peer: { id: peerId, name: 'Render Box', host: 'render-box.tailnet-example.ts.net' },+ capability,+ request: effectiveRequest,+ remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request: effectiveRequest },+ };+ });const result = await resolveDefaultMediaRoute({kind: 'video',@@ -489,16 +526,21 @@ describe('frame constraint negotiation (issue #4681)', () => {});it('validates an older provider payload without the fields and leaves numFrames untouched', async () => {- prepareRemoteMediaJob.mockImplementation(async ({ peerId, kind, request }) => ({- peer: { id: peerId, name: 'Render Box', host: 'render-box.tailnet-example.ts.net' },- capability: {+ prepareRemoteMediaJob.mockImplementation(async ({ peerId, kind, request }) => {+ const capability = {kind,engine: request.engine,modelId: request.modelId,ready: true,- },- remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request },- }));+ };+ const effectiveRequest = negotiateVideoConstraints(request, capability);+ return {+ peer: { id: peerId, name: 'Render Box', host: 'render-box.tailnet-example.ts.net' },+ capability,+ request: effectiveRequest,+ remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request: effectiveRequest },+ };+ });const result = await resolveDefaultMediaRoute({kind: 'video',@@ -509,18 +551,23 @@ describe('frame constraint negotiation (issue #4681)', () => {});it('rejects when frame count cannot be made legal at all', async () => {- prepareRemoteMediaJob.mockImplementation(async ({ peerId, kind, request }) => ({- peer: { id: peerId, name: 'Render Box', host: 'render-box.tailnet-example.ts.net' },- capability: {+ prepareRemoteMediaJob.mockImplementation(async ({ peerId, kind, request }) => {+ const capability = {kind,engine: request.engine,modelId: request.modelId,ready: true,frameStride: 8,maxNumFrames: 0,- },- remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request },- }));+ };+ const effectiveRequest = negotiateVideoConstraints(request, capability);+ return {+ peer: { id: peerId, name: 'Render Box', host: 'render-box.tailnet-example.ts.net' },+ capability,+ request: effectiveRequest,+ remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request: effectiveRequest },+ };+ });await expect(resolveDefaultMediaRoute({kind: 'video',@@ -530,18 +577,23 @@ describe('frame constraint negotiation (issue #4681)', () => {it('logs the adjustment when numFrames is snapped', async () => {const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});- prepareRemoteMediaJob.mockImplementation(async ({ peerId, kind, request }) => ({- peer: { id: peerId, name: 'Render Box', host: 'render-box.tailnet-example.ts.net' },- capability: {+ prepareRemoteMediaJob.mockImplementation(async ({ peerId, kind, request }) => {+ const capability = {kind,engine: request.engine,modelId: 'wan22_t2v_a14b',modelName: 'Wan 2.2 T2V A14B',ready: true,frameStride: 8,- },- remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request },- }));+ };+ const effectiveRequest = negotiateVideoConstraints(request, capability);+ return {+ peer: { id: peerId, name: 'Render Box', host: 'render-box.tailnet-example.ts.net' },+ capability,+ request: effectiveRequest,+ remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request: effectiveRequest },+ };+ });await resolveDefaultMediaRoute({kind: 'video',diff --git a/server/services/federatedMedia/remoteSubmission.js b/server/services/federatedMedia/remoteSubmission.jsindex c82f4fcf97..358006c0ca 100644--- a/server/services/federatedMedia/remoteSubmission.js+++ b/server/services/federatedMedia/remoteSubmission.js@@ -15,12 +15,75 @@import { ServerError } from '../../lib/errorHandler.js';import { FEDERATED_MEDIA_WIRE_VERSION } from '../../lib/federatedMediaWire.js';+/**+ * Negotiate frame and canvas constraints against the provider capability.+ * Snaps numFrames down to the nearest legal n*stride + 1, bounds against maxNumFrames,+ * and matches resolution against the closest aspect ratio in resolutionOptions if advertised.+ */+export function negotiateVideoConstraints(request, capability) {+ if (!request || !capability) return request;+ let negotiated = request;++ // Frame constraint negotiation (issue #4681)+ if (negotiated.numFrames !== undefined) {+ const frameStride = Number(capability.frameStride);+ const maxNumFrames = Number(capability.maxNumFrames);+ const hasStride = Number.isFinite(frameStride) && frameStride > 0;+ const hasMax = Number.isFinite(maxNumFrames);++ if (hasStride || hasMax) {+ const requestedFrames = Number(negotiated.numFrames);+ if (requestedFrames < 1) {+ throw new ServerError(+ `Requested frame count (${requestedFrames}) is invalid for ${capability.modelName || capability.modelId}`,+ { status: 400, code: 'MEDIA_PROVIDER_INPUT_UNSUPPORTED' },+ );+ }+ let legalFrames = requestedFrames;+ if (hasStride) {+ legalFrames = Math.floor((legalFrames - 1) / frameStride) * frameStride + 1;+ }+ if (hasMax && legalFrames > maxNumFrames) {+ legalFrames = hasStride+ ? Math.floor((maxNumFrames - 1) / frameStride) * frameStride + 1+ : maxNumFrames;+ }+ if (legalFrames < 1) {+ throw new ServerError(+ `Requested frame count (${requestedFrames}) cannot be satisfied by ${capability.modelName || capability.modelId}`,+ { status: 400, code: 'MEDIA_PROVIDER_INPUT_UNSUPPORTED' },+ );+ }+ if (legalFrames !== requestedFrames) {+ console.log(`🌐 Federated render: adjusted numFrames from ${requestedFrames} to ${legalFrames} for ${capability.modelName || capability.modelId}`);+ negotiated = { ...negotiated, numFrames: legalFrames };+ }+ }+ }++ // Canvas constraint negotiation (issue #4681)+ if (Array.isArray(capability.resolutionOptions) && capability.resolutionOptions.length > 0+ && negotiated.width !== undefined && negotiated.height !== undefined) {+ const aspectValue = Number(negotiated.width) / Number(negotiated.height);+ const bestOption = capability.resolutionOptions.reduce((best, option) => {+ const distance = Math.abs((Number(option.w) / Number(option.h)) - aspectValue);+ return !best || distance < best.distance ? { option, distance } : best;+ }, null)?.option;+ if (bestOption && (negotiated.width !== bestOption.w || negotiated.height !== bestOption.h)) {+ console.log(`🌐 Federated render: adjusted resolution from ${negotiated.width}x${negotiated.height} to ${bestOption.w}x${bestOption.h} for ${capability.modelName || capability.modelId}`);+ negotiated = { ...negotiated, width: bestOption.w, height: bestOption.h };+ }+ }++ return negotiated;+}+/*** @param {object} args* @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).- * @returns {Promise<{peer: object, capability: object, remoteMedia: object}>}+ * @returns {Promise<{peer: object, capability: object, request: object, remoteMedia: object}>}*/export async function prepareRemoteMediaJob({ peerId, kind, request }) {// Imported lazily, not statically: the image/video generate routes reach this@@ -45,15 +108,19 @@ export async function prepareRemoteMediaJob({ peerId, kind, request }) {engine: request.engine,modelId: request.modelId,});+ const effectiveRequest = kind === 'video'+ ? negotiateVideoConstraints(request, capability)+ : request;return {peer,capability,+ request: effectiveRequest,remoteMedia: {wireVersion: FEDERATED_MEDIA_WIRE_VERSION,peerId: peer.id,reconcile: false,cancelRequested: false,- request,+ request: effectiveRequest,},};}diff --git a/server/services/federatedMedia/remoteSubmission.test.js b/server/services/federatedMedia/remoteSubmission.test.jsnew file mode 100644index 0000000000..3517a5a8a0--- /dev/null+++ b/server/services/federatedMedia/remoteSubmission.test.js@@ -0,0 +1,101 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { negotiateVideoConstraints, prepareRemoteMediaJob } from './remoteSubmission.js';++const mockGetPeers = vi.fn();+const mockResolveFederatedMediaProvider = vi.fn();++vi.mock('../instances.js', () => ({+ getPeers: (...args) => mockGetPeers(...args),+}));++vi.mock('../federatedMediaConsumer.js', () => ({+ resolveFederatedMediaProvider: (...args) => mockResolveFederatedMediaProvider(...args),+}));++beforeEach(() => {+ mockGetPeers.mockReset();+ mockResolveFederatedMediaProvider.mockReset();+});++describe('negotiateVideoConstraints', () => {+ it('snaps numFrames down to the nearest n*stride + 1', () => {+ const capability = {+ modelId: 'wan22_t2v_a14b',+ frameStride: 8,+ };++ expect(negotiateVideoConstraints({ numFrames: 33 }, capability).numFrames).toBe(33);+ expect(negotiateVideoConstraints({ numFrames: 40 }, capability).numFrames).toBe(33);+ expect(negotiateVideoConstraints({ numFrames: 41 }, capability).numFrames).toBe(41);+ });++ it('clamps numFrames to maxNumFrames respecting stride', () => {+ const capability = {+ modelId: 'wan22_t2v_a14b',+ frameStride: 4,+ maxNumFrames: 33,+ };++ expect(negotiateVideoConstraints({ numFrames: 40 }, capability).numFrames).toBe(33);+ });++ it('leaves numFrames untouched when capability has no frameStride or maxNumFrames', () => {+ const capability = { modelId: 'ltx2' };+ expect(negotiateVideoConstraints({ numFrames: 40 }, capability).numFrames).toBe(40);+ });++ it('snaps width and height to closest aspect ratio when resolutionOptions is present', () => {+ const capability = {+ modelId: 'minimax_h3',+ resolutionOptions: [+ { label: '16:9', w: 1344, h: 768 },+ { label: '9:16', w: 768, h: 1344 },+ ],+ };++ const snapped = negotiateVideoConstraints({ width: 1280, height: 720 }, capability);+ expect(snapped.width).toBe(1344);+ expect(snapped.height).toBe(768);+ });++ it('rejects when frame count cannot be made legal', () => {+ const capability = {+ modelId: 'wan22',+ frameStride: 8,+ maxNumFrames: 0,+ };++ expect(() => negotiateVideoConstraints({ numFrames: 25 }, capability))+ .toThrow(/cannot be satisfied/);+ });+});++describe('prepareRemoteMediaJob', () => {+ it('negotiates video constraints and attaches the negotiated request to remoteMedia', async () => {+ mockGetPeers.mockResolvedValue([{ id: 'peer-1', name: 'Render Box' }]);+ mockResolveFederatedMediaProvider.mockResolvedValue({+ capability: {+ kind: 'video',+ engine: 'local',+ modelId: 'wan22_t2v_a14b',+ ready: true,+ frameStride: 8,+ },+ });++ const result = await prepareRemoteMediaJob({+ peerId: 'peer-1',+ kind: 'video',+ request: {+ kind: 'video',+ engine: 'local',+ modelId: 'wan22_t2v_a14b',+ prompt: 'a scenic drive',+ numFrames: 40,+ },+ });++ expect(result.request.numFrames).toBe(33);+ expect(result.remoteMedia.request.numFrames).toBe(33);+ });+});