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
fix: make a routed media job unrenderable by a downgraded build (#4683)
[._.]/ Adam Eivy2a70cce8f81e
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsxindex 09f187498d..00298cd69a 100644--- a/client/src/components/media/MediaJobsQueue.jsx+++ b/client/src/components/media/MediaJobsQueue.jsx@@ -55,7 +55,8 @@ const codexEffortOf = (raw) => (typeof raw === 'string' ? raw.trim() : '');// Compact "engine / model" badge so a failed row tells the user *what* failed,// not just that it failed. Codex jobs carry `params.model`; local image/video-// jobs carry `params.modelId`; training jobs carry a runtime + character.+// jobs carry `params.modelId`; training jobs carry a runtime + character. A+// federated job is badged `remote` off the server-projected `renderer` field.// Trims long HF repo paths to the tail segment.function modelLabel(params) {if (!params) return null;@@ -87,9 +88,13 @@ function modelLabel(params) {: 'agy / configured default';}const id = (params.modelId || '').trim();- if (!id) return 'local';+ // A federated render ran on a peer, so it must not wear the local badge. The+ // server projects `renderer` (and rebuilds `modelId` off the wire request)+ // for exactly this — the raw job nulls both to fail closed on a downgrade.+ const where = params.renderer === 'remote' ? 'remote' : 'local';+ if (!id) return where;const tail = id.includes('/') ? id.slice(id.lastIndexOf('/') + 1) : id;- return `local / ${tail}`;+ return `${where} / ${tail}`;}// Embeds the live render queue inline on the Image / Video gen pages so thediff --git a/client/src/components/media/MediaJobsQueue.test.jsx b/client/src/components/media/MediaJobsQueue.test.jsxindex fe3fc0a56c..a6b2ca0ccd 100644--- a/client/src/components/media/MediaJobsQueue.test.jsx+++ b/client/src/components/media/MediaJobsQueue.test.jsx@@ -113,6 +113,33 @@ describe('MediaJobsQueue — Creative Director renders', () => {});});+describe('MediaJobsQueue — federated render badge', () => {+ it('badges a peer-rendered job remote instead of claiming a local render', async () => {+ // The server projects `renderer` and rebuilds `modelId` off the wire+ // request — the raw job nulls both so a rolled-back build fails closed.+ listMediaJobs.mockResolvedValue([{+ id: 'remotejob0000beef',+ kind: 'image',+ status: 'running',+ queuedAt: '2026-06-19T10:00:00Z',+ params: { prompt: 'a lighthouse at dusk', modelId: 'dev', renderer: 'remote' },+ }]);++ render(<MediaJobsQueue kind="image" />);++ expect(await screen.findByText(/remote \/ dev/)).toBeInTheDocument();+ expect(screen.queryByText(/local \/ dev/)).not.toBeInTheDocument();+ });++ it('keeps the local badge on a job with no renderer projection', async () => {+ listMediaJobs.mockResolvedValue([{ ...failedLocalJob, status: 'running', error: undefined }]);++ render(<MediaJobsQueue kind="image" />);++ expect(await screen.findByText(/local \/ z-image-turbo/)).toBeInTheDocument();+ });+});+describe('MediaJobsQueue — Codex reasoning-effort retry control', () => {it('surfaces the job effort in the row label', async () => {const user = userEvent.setup();diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 74d83f9e54..3d9b0580fc 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -44,6 +44,7 @@ import { buildUniverseRunTag } from '../services/universeRunTag.js';import { getSettings } from '../services/settings.js';import { federatedMediaImageJobSubmissionSchema } from '../lib/validation.js';import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';+import { routedJobParams } from '../services/federatedMedia/routedJobParams.js';const router = Router();@@ -478,13 +479,14 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {mediaProviderPeerId: _peerId, mediaProviderEngine: _engine,mode: _mode, cloudModel: _cloudModel, ...jobParams} = params;- // The conditioning prompt rides ONLY inside the versioned marker. An older- // build that cannot route `remoteMedia` therefore falls through to a local- // render with no prompt and no configured backend, rather than quietly- // re-rendering this job for real on local hardware.+ // The conditioning prompt and the model id ride ONLY inside the versioned+ // marker. `routedJobParams` nulls every top-level field a LOCAL dispatcher+ // would render from, so an older build that cannot route `remoteMedia`+ // fails closed on its own model guard rather than quietly re-rendering this+ // job for real on local hardware. See that module for the full contract.const queued = enqueueJob({kind: 'image',- params: { ...jobParams, prompt: '', remoteMedia },+ params: routedJobParams({ params: jobParams, remoteMedia }),});return res.json(queuedImageResponse({...queued,diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex 55970383a0..a17592993e 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -1465,11 +1465,16 @@ describe('Image Gen Routes', () => {});const [{ params }] = mediaJobQueue.enqueueJob.mock.calls[0];- // Blank top-level prompt + no routing fields: an older build that cannot- // read `remoteMedia` falls through to a local render with nothing to- // render, rather than quietly re-running this job on local hardware.+ // Blank top-level prompt, nulled model + interpreter, no routing fields:+ // an older build that cannot read `remoteMedia` falls through to a local+ // render it has to refuse, rather than quietly re-running this job on+ // local hardware. The shape contract itself lives in+ // services/federatedMedia/routedJobParams.test.js.expect(params.prompt).toBe('');+ expect(params.modelId).toBeNull();+ expect(params.pythonPath).toBeNull();expect(params.remoteMedia.request.prompt).toBe('a lighthouse at dusk');+ expect(params.remoteMedia.request.modelId).toBe('dev');expect(params).not.toHaveProperty('mediaProviderPeerId');expect(params).not.toHaveProperty('mediaProviderEngine');});diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.jsindex 85796d9caf..c7c6251623 100644--- a/server/routes/mediaJobs.js+++ b/server/routes/mediaJobs.js@@ -15,6 +15,7 @@ import { promptFromMedia } from '../services/mediaPromptFromMedia.js';import { CODEX_EFFORT_LEVELS } from '../lib/providerModels.js';import { sanitizeJob } from '../services/mediaJobQueue/sanitizeJob.js';import { validateVideoRetryParams } from '../services/videoGen/prepareParams.js';+import { routedJobParams } from '../services/federatedMedia/routedJobParams.js';const router = Router();@@ -293,7 +294,15 @@ router.post('/:id/retry', asyncHandler(async (req, res) => {// fallback (CODEX_IMAGEGEN_DEFAULT_EFFORT) take over, which a merged sentinel// string could not do (it would fail the CODEX_EFFORT_LEVELS validation).if (clearEffort) delete params.effort;- const result = enqueueJob({ kind: job.kind, params, owner: job.owner });+ // A retried federated job must keep the downgrade-safe shape (#4683). The+ // remote executor renders from `remoteMedia.request`, so a merged `prompt` /+ // `modelId` override never reached the peer anyway — but leaving one on+ // top-level params would hand a rolled-back build a locally-renderable job.+ // Re-normalize instead of trusting the merge.+ const retryParams = params.remoteMedia !== undefined+ ? routedJobParams({ params, remoteMedia: params.remoteMedia })+ : params;+ const result = enqueueJob({ kind: job.kind, params: retryParams, owner: job.owner });// Drop the original failed/canceled row from archive — the new job inherits// its work, and leaving both visible just lets users keep clicking Retry on// the dead row and stacking duplicate jobs. If the prune returns false thediff --git a/server/routes/mediaJobs.test.js b/server/routes/mediaJobs.test.jsindex 1faad27d59..09da274589 100644--- a/server/routes/mediaJobs.test.js+++ b/server/routes/mediaJobs.test.js@@ -166,6 +166,33 @@ describe('mediaJobs routes', () => {expect(call.params.steps).toBe(40);});+ it('POST /:id/retry re-normalizes a federated job so an override cannot restore a locally-renderable shape', async () => {+ // The remote executor renders from `remoteMedia.request`, so these+ // overrides never reached the peer anyway — but leaving them on top-level+ // params would hand a build rolled back before `remoteMedia` a job it could+ // render locally for real (#4683).+ const remoteMedia = {+ wireVersion: 1,+ peerId: '00000000-0000-4000-8000-0000000004f1',+ request: { kind: 'image', engine: 'local', modelId: 'dev', prompt: 'a lighthouse at dusk' },+ };+ jobStore.set('j-remote', {+ id: 'j-remote', kind: 'image', owner: null, status: 'failed',+ params: { prompt: '', modelId: null, pythonPath: null, width: 512, remoteMedia },+ });+ const r = await request(makeApp())+ .post('/api/media-jobs/j-remote/retry')+ .send({ params: { prompt: 'something else', modelId: 'sdxl-base' } });+ expect(r.status).toBe(200);+ const { params } = stubs.enqueueJob.mock.calls[0][0];+ expect(params.prompt).toBe('');+ expect(params.modelId).toBeNull();+ expect(params.pythonPath).toBeNull();+ // The marker (and the surviving job params) still ride through untouched.+ expect(params.remoteMedia).toEqual(remoteMedia);+ expect(params.width).toBe(512);+ });+it('POST /:id/retry accepts the editable video generation controls', async () => {jobStore.set('j-video-edit', {id: 'j-video-edit', kind: 'video', owner: null, status: 'failed',diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 3c52bd7716..9b01b57a60 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 { routedJobParams } from '../services/federatedMedia/routedJobParams.js';const router = Router();@@ -1068,13 +1069,14 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {kind: 'video',request,});- // Prompt and dials ride ONLY inside the versioned marker, and the job- // carries no pythonPath. An older build that can't route `remoteMedia`- // therefore hits generateVideo's "Prompt is required" guard and fails- // closed instead of re-rendering this job locally.+ // Prompt, dials, and model id ride ONLY inside the versioned marker.+ // `routedJobParams` is shared with the routed image path so the two shapes+ // cannot drift: an older build that can't route `remoteMedia` hits+ // generateVideo's "Prompt is required" guard, and its `Unknown video model`+ // guard behind that, instead of re-rendering this job locally.const { jobId, position, status } = enqueueJob({kind: 'video',- params: { prompt: '', modelId: request.modelId, remoteMedia },+ params: routedJobParams({ remoteMedia }),});return res.json({jobId,diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex e7b7f906ce..d25448d57a 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -2293,12 +2293,16 @@ describe('videoGen routes', () => {});const [{ params }] = mediaJobQueue.enqueueJob.mock.calls[0];- // Blank top-level prompt + no pythonPath: an older build that cannot read- // `remoteMedia` hits generateVideo's "Prompt is required" guard and fails- // closed instead of re-rendering this job on local hardware.+ // Blank top-level prompt, nulled model + interpreter: an older build that+ // cannot read `remoteMedia` hits generateVideo's "Prompt is required"+ // guard (and its model guard behind that) instead of re-rendering this+ // job on local hardware. Shape contract:+ // services/federatedMedia/routedJobParams.test.js.expect(params.prompt).toBe('');- expect(params).not.toHaveProperty('pythonPath');+ expect(params.modelId).toBeNull();+ expect(params.pythonPath).toBeNull();expect(params.remoteMedia.request.prompt).toBe('a slow pan across a harbour');+ expect(params.remoteMedia.request.modelId).toBe('ltx2');});it('requires an explicit provider model instead of falling back to a local default', async () => {diff --git a/server/services/federatedMedia/routedJobParams.js b/server/services/federatedMedia/routedJobParams.jsnew file mode 100644index 0000000000..93a1447eea--- /dev/null+++ b/server/services/federatedMedia/routedJobParams.js@@ -0,0 +1,52 @@+/**+ * The persisted params shape for a media job that renders on a federated peer.+ *+ * Both routed generate paths (`routes/imageGen.js`, `routes/videoGen.js`) build+ * their queue params through this one helper so the two cannot drift: the+ * downgrade contract below only holds if every routed job carries the same+ * shape.+ *+ * ## Downgrade contract (#4683)+ *+ * PortOS is distributed software — one machine of a federated pair can be+ * rolled back to a build that predates `remoteMedia` while the other keeps+ * queueing routed jobs. A legacy build ignores the unknown `remoteMedia` key+ * and dispatches the job to its LOCAL renderer, so the top-level params must be+ * unrenderable there:+ *+ * - `prompt: ''` — the conditioning text rides only inside the versioned+ * marker. `generateVideo` refuses a blank prompt outright; `generateImage`+ * deliberately allows one (img2img / regen), so it needs the guard below.+ * - `modelId: null` — NOT a deleted key. `generateImage` and `generateVideo`+ * both declare `modelId` as a default parameter (`= 'dev'` /+ * `= defaultVideoModelId()`), and a JS default fires on `undefined` only —+ * dropping the key would silently select the local default and render for+ * real wherever that model happens to be installed. An explicit `null`+ * suppresses the default and lands on the `Unknown or unsupported model`+ * guard every time, whatever is installed.+ * - `pythonPath: null` — belt and braces for the legacy mflux/imagine_win path,+ * which refuses an unconfigured interpreter (`IMAGE_GEN_NOT_CONFIGURED`).+ *+ * A persisted `renderer: 'remote'` discriminator was considered and rejected:+ * an older build has no such check, so it would ignore the field entirely and+ * buy no protection. The remote/local distinction is surfaced for DISPLAY+ * instead, off the marker, in `mediaJobQueue/sanitizeJob.js`.+ *+ * Nothing a current build reads is lost — the remote adapters+ * (`imageGen/remote.js`, `videoGen/remote.js`) take the prompt and the model id+ * from `remoteMedia.request`, which is the same body that goes over the wire.+ *+ * @param {object} args+ * @param {object} [args.params] - Job params that survive routing (destination+ * tags, dimensions, seed). Local-only routing/backend selectors are stripped+ * by the caller before they get here.+ * @param {object} args.remoteMedia - The versioned marker from prepareRemoteMediaJob.+ * @returns {object} Params to persist on the queued proxy job.+ */+export const routedJobParams = ({ params = {}, remoteMedia }) => ({+ ...params,+ prompt: '',+ modelId: null,+ pythonPath: null,+ remoteMedia,+});diff --git a/server/services/federatedMedia/routedJobParams.test.js b/server/services/federatedMedia/routedJobParams.test.jsnew file mode 100644index 0000000000..3255ab54ea--- /dev/null+++ b/server/services/federatedMedia/routedJobParams.test.js@@ -0,0 +1,119 @@+import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import { routedJobParams } from './routedJobParams.js';++const PEER_ID = '00000000-0000-4000-8000-0000000004f1';++const remoteMedia = {+ wireVersion: 1,+ peerId: PEER_ID,+ reconcile: false,+ cancelRequested: false,+ request: {+ kind: 'image',+ engine: 'local',+ modelId: 'dev',+ prompt: 'a lighthouse at dusk',+ width: 512,+ height: 512,+ },+};++describe('routedJobParams', () => {+ it('nulls every top-level field a local dispatcher would render from', () => {+ const params = routedJobParams({+ params: { prompt: 'a lighthouse at dusk', modelId: 'dev', width: 512, height: 512 },+ remoteMedia,+ });++ expect(params.prompt).toBe('');+ // `null`, NOT absent — generateImage/generateVideo declare `modelId` as a+ // default parameter, which fires on `undefined` only.+ expect(params.modelId).toBeNull();+ expect(params).toHaveProperty('modelId');+ expect(params.pythonPath).toBeNull();+ expect(params).toHaveProperty('pythonPath');+ });++ it('keeps the versioned marker and the destination tags a completion hook needs', () => {+ const params = routedJobParams({+ params: { universeRun: 'run-1', catalogAttach: true, width: 512 },+ remoteMedia,+ });++ expect(params.remoteMedia).toEqual(remoteMedia);+ expect(params.universeRun).toBe('run-1');+ expect(params.catalogAttach).toBe(true);+ expect(params.width).toBe(512);+ });++ it('still produces the guarded shape when the caller passes no params at all', () => {+ // The video route routes without carrying any surviving job params.+ const params = routedJobParams({ remoteMedia });++ expect(params).toEqual({ prompt: '', modelId: null, pythonPath: null, remoteMedia });+ });+});++// The point of the shape above: a machine rolled back to a build that predates+// `remoteMedia` ignores the marker and dispatches the job to its LOCAL renderer.+// These feed the routed params straight to the real local entry points — the+// surface a legacy dispatcher would land on — and assert they refuse.+describe('downgrade to a pre-remoteMedia build', () => {+ let tmpRegistryDir;+ let priorRegistryEnv;+ let generateImage;+ let generateVideo;+ let getImageModels;+ let LOCAL_IMAGEGEN_DEFAULT_MODEL;++ beforeAll(async () => {+ // Same guard local.test.js uses: point the model registry at a temp file so+ // the seed-on-read path can't write into the repo's data dir.+ tmpRegistryDir = mkdtempSync(join(tmpdir(), 'portos-routed-params-test-'));+ priorRegistryEnv = process.env.PORTOS_MEDIA_MODELS_FILE;+ process.env.PORTOS_MEDIA_MODELS_FILE = join(tmpRegistryDir, 'media-models.json');+ vi.resetModules();+ ({ generateImage } = await import('../imageGen/local.js'));+ ({ generateVideo } = await import('../videoGen/local.js'));+ ({ getImageModels } = await import('../../lib/mediaModels.js'));+ ({ LOCAL_IMAGEGEN_DEFAULT_MODEL } = await import('../imageGen/modes.js'));+ });++ afterAll(() => {+ if (priorRegistryEnv === undefined) delete process.env.PORTOS_MEDIA_MODELS_FILE;+ else process.env.PORTOS_MEDIA_MODELS_FILE = priorRegistryEnv;+ rmSync(tmpRegistryDir, { recursive: true, force: true });+ });++ // Bypass probe for the two guards below — without it they could pass for the+ // wrong reason. The shipped default model IS registered, so the "just delete+ // the modelId key" variant of this fix would have resolved a real model and+ // rendered for real wherever its weights are installed. That is precisely why+ // the routed params carry an explicit `null` instead of dropping the key.+ it('would have resolved the shipped default if modelId were merely absent', () => {+ expect(getImageModels().map((m) => m.id)).toContain(LOCAL_IMAGEGEN_DEFAULT_MODEL);+ });++ it('refuses a routed image job — generateImage permits a blank prompt, so the model guard is the one that fires', async () => {+ const params = routedJobParams({+ params: { width: 512, height: 512, seed: 42 },+ remoteMedia,+ });++ await expect(generateImage(params)).rejects.toThrow(/Unknown or unsupported model/);+ });++ it('refuses a routed video job on the prompt guard, and on the model guard behind it', async () => {+ const params = routedJobParams({ remoteMedia });++ await expect(generateVideo(params)).rejects.toThrow(/Prompt is required/);+ // Second, independent guard: even a build whose prompt check ever loosened+ // has nothing to render with.+ await expect(generateVideo({ ...params, prompt: 'a lighthouse at dusk' }))+ .rejects.toThrow(/Unknown video model/);+ });+});diff --git a/server/services/mediaJobQueue/sanitizeJob.js b/server/services/mediaJobQueue/sanitizeJob.jsindex 2300af3d4d..8e681b7a2b 100644--- a/server/services/mediaJobQueue/sanitizeJob.js+++ b/server/services/mediaJobQueue/sanitizeJob.js@@ -41,6 +41,21 @@ export function sanitizeJob(job) {if (safeParams && remotePrompt) {safeParams.prompt = remotePrompt;}+ // Same reasoning for the model id: it is nulled in top-level params so a+ // downgraded build cannot render the job locally (#4683), so rebuild it from+ // the marker here — the Render Queue card's model badge reads+ // `params.modelId`. Audio carries no wire model id and keeps whatever the+ // local engine recorded.+ const remoteModelId = job.params?.remoteMedia?.request?.modelId;+ if (safeParams && typeof remoteModelId === 'string' && remoteModelId) {+ safeParams.modelId = remoteModelId;+ }+ // Display-only discriminator, never persisted in job params: a routed job+ // renders on a peer, so labelling it with the local-render badge ("local /+ // flux") would misreport where the pixels came from.+ if (safeParams && job.params?.remoteMedia !== undefined) {+ safeParams.renderer = 'remote';+ }return {id: job.id,kind: job.kind,diff --git a/server/services/mediaJobQueue/sanitizeJob.test.js b/server/services/mediaJobQueue/sanitizeJob.test.jsindex c7e7e8ac0b..0cc4348ce5 100644--- a/server/services/mediaJobQueue/sanitizeJob.test.js+++ b/server/services/mediaJobQueue/sanitizeJob.test.js@@ -78,20 +78,22 @@ describe('sanitizeJob', () => {expect(sanitized.params).toEqual({prompt: 'Instrumental orchestral music with a triumphant mood, moderate tempo, high energy, featuring brass and strings. No vocals or spoken words.',modelId: 'example/model',+ renderer: 'remote',});expect(sanitized.params).not.toHaveProperty('remoteMedia');});- it('restores an image/video remote job prompt from its marker, not from params', () => {+ it('restores an image/video remote job prompt and model from its marker, not from params', () => {const sanitized = sanitizeJob({id: 'job-image',kind: 'image',status: 'running',params: {- // Blank on purpose: the prompt lives only inside the versioned marker so- // an older build that cannot route it fails closed instead of rendering.+ // Blank/nulled on purpose: the prompt and the model live only inside+ // the versioned marker so an older build that cannot route it fails+ // closed instead of rendering (#4683).prompt: '',- modelId: 'dev',+ modelId: null,width: 512,height: 512,remoteMedia: {@@ -114,7 +116,22 @@ describe('sanitizeJob', () => {modelId: 'dev',width: 512,height: 512,+ // Display-only: the Render Queue badges this 'remote / dev' rather than+ // claiming a local render produced it.+ renderer: 'remote',});expect(sanitized.params).not.toHaveProperty('remoteMedia');});++ it('leaves a local job unbadged so it keeps the local render label', () => {+ const sanitized = sanitizeJob({+ id: 'job-local',+ kind: 'image',+ status: 'running',+ params: { prompt: 'a lighthouse at dusk', modelId: 'dev' },+ });++ expect(sanitized.params).toEqual({ prompt: 'a lighthouse at dusk', modelId: 'dev' });+ expect(sanitized.params).not.toHaveProperty('renderer');+ });});