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
address review (codex): make the unreadable-settings sentinel real, unbreak the first route
[._.]/ Adam Eivy45ef39712b32
diff --git a/client/src/components/instances/UnattendedRenderRouting.jsx b/client/src/components/instances/UnattendedRenderRouting.jsxindex 0837a181ed..3d26b93c4e 100644--- a/client/src/components/instances/UnattendedRenderRouting.jsx+++ b/client/src/components/instances/UnattendedRenderRouting.jsx@@ -116,13 +116,17 @@ export default function UnattendedRenderRouting({ peers }) {// the wrong instinct: it is not "better than sending {}", it is a write of// known-stale state over whatever is actually on the server, which is how a// newer mediaProvider or strictPullAuthorization gets silently reverted.+ // A SUCCESSFUL response with no `federation` key is a fresh install that has+ // simply never opted into anything — the correct base is `{}`, and treating+ // it as unreadable would make the very first route unsavable on every+ // install. Only a failed request (`null`) aborts.const fresh = await getSettings({ silent: true }).catch(() => null);- if (!isRecord(fresh?.federation)) {+ if (fresh === null) {setSaving(false);toast.error('Could not read current settings — routing not saved');return;}- const base = fresh.federation;+ const base = isRecord(fresh.federation) ? fresh.federation : {};// Merge onto the freshest routing too, so a kind another surface set in the// meantime isn't reverted by this one's stale copy.const baseRouting = isRecord(base.mediaRouting) ? base.mediaRouting : routing;diff --git a/client/src/components/instances/UnattendedRenderRouting.test.jsx b/client/src/components/instances/UnattendedRenderRouting.test.jsxindex f924e445d2..2494468c65 100644--- a/client/src/components/instances/UnattendedRenderRouting.test.jsx+++ b/client/src/components/instances/UnattendedRenderRouting.test.jsx@@ -223,3 +223,21 @@ describe('UnattendedRenderRouting — tailnet gate', () => {expect(await screen.findByLabelText('Image')).toBeInTheDocument();});});++describe('UnattendedRenderRouting — an absent federation slice is not a failed read', () => {+ // The whole feature is unreachable on a fresh install if this regresses: no+ // install has a `federation` key until something writes one, so treating its+ // absence as unreadable makes the FIRST route unsavable, always.+ it('creates the slice when a successful response has no federation key', async () => {+ getSettings.mockResolvedValue({});+ render(<UnattendedRenderRouting peers={[peerWith()]} />);++ const select = await screen.findByLabelText('Image');+ fireEvent.change(select, { target: { value: JSON.stringify(['peer-1', 'comfy', 'sdxl-base']) } });++ await waitFor(() => expect(updateSettings).toHaveBeenCalledWith({+ federation: { mediaRouting: { image: { peerId: 'peer-1', engine: 'comfy', modelId: 'sdxl-base' } } },+ }, { silent: true }));+ expect(toast.error).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/settings/SharingTab.jsx b/client/src/components/settings/SharingTab.jsxindex 3b7c2db644..4c0f8402b7 100644--- a/client/src/components/settings/SharingTab.jsx+++ b/client/src/components/settings/SharingTab.jsx@@ -58,9 +58,9 @@ export function SharingTab() {const [saving, setSaving] = useState(false);const [strictPull, setStrictPull] = useState(false);const [strictPullSaving, setStrictPullSaving] = useState(false);- // The settings PATCH shallow-merges top-level keys, so `federation` is- // replaced wholesale — carry the rest of the slice forward on every write.- const [federationSettings, setFederationSettings] = useState({});+ // No mount-time copy of the `federation` slice is kept: PATCH replaces that+ // key wholesale, so every write here re-reads it immediately beforehand rather+ // than carrying a snapshot that another surface may have superseded.const [authEnabled, setAuthEnabled] = useState(false);const [musicEngines, setMusicEngines] = useState([]);const [providerSettings, setProviderSettings] = useState({});@@ -106,7 +106,6 @@ export function SharingTab() {setSavedDisplayName(display);setSavedBio(b);const federation = settings?.federation && typeof settings.federation === 'object' ? settings.federation : {};- setFederationSettings(federation);setStrictPull(federation.strictPullAuthorization === true);setAuthEnabled(auth?.enabled === true);const provider = federation.mediaProvider && typeof federation.mediaProvider === 'object'@@ -158,12 +157,16 @@ export function SharingTab() {setStrictPullSaving(true);// Same whole-slice replacement hazard as the provider save below.const fresh = await getSettings({ silent: true }).catch(() => null);- const base = isRecord(fresh?.federation) ? fresh.federation : federationSettings;+ if (fresh === null) {+ setStrictPullSaving(false);+ toast.error('Could not read current settings — not saved');+ return;+ }+ const base = isRecord(fresh.federation) ? fresh.federation : {};const federation = { ...base, strictPullAuthorization: next };const merged = await updateSettings({ federation }).catch(() => null);setStrictPullSaving(false);if (!merged) return;- setFederationSettings(federation);setStrictPull(next);toast.success(next ? 'Strict pull authorization on' : 'Strict pull authorization off');};@@ -216,8 +219,18 @@ export function SharingTab() {// owns `mediaRouting`, and a Settings tab left open across a routing change// would otherwise write back the slice as it looked before, silently// clearing the route and sending unattended renders back to local.+ // A failed read ABORTS: PUT /api/settings replaces the whole `federation`+ // key, so writing the mount-time snapshot over it can erase a route the+ // Instances page added while this tab sat open. A successful response with+ // no `federation` key is a different thing entirely — a fresh install — and+ // correctly bases on `{}`.const fresh = await getSettings({ silent: true }).catch(() => null);- const base = isRecord(fresh?.federation) ? fresh.federation : federationSettings;+ if (fresh === null) {+ setProviderSaving(false);+ toast.error('Could not read current settings — provider not saved');+ return;+ }+ const base = isRecord(fresh.federation) ? fresh.federation : {};const federation = { ...base, mediaProvider };const merged = await updateSettings({ federation }, { silent: true }).catch(() => null);setProviderSaving(false);@@ -225,7 +238,6 @@ export function SharingTab() {toast.error('Failed to save media provider settings');return;}- setFederationSettings(federation);setProviderSettings(mediaProvider);setProviderMaxQueuedJobs(maxQueuedJobs);setSavedProviderEnabled(providerEnabled);@@ -320,8 +332,11 @@ export function SharingTab() {<h3 className="text-lg font-semibold text-white">Federated media provider</h3></div><p className="text-sm text-gray-400 mb-4">- Let registered PortOS peers submit allowlisted audio renders to this machine's durable media queue.- Prompts and job details stay out of capability status, and completed downloads include a SHA-256 integrity hash.+ Let registered PortOS peers submit allowlisted audio, image, and video renders to this+ machine's durable media queue. Only models you allowlist below can be requested.+ Capability status never carries prompts or job details, and completed downloads include a+ SHA-256 integrity hash. An image or video peer sends the prompt it wants rendered; an audio+ peer can only send a fixed musical profile, never free text or lyrics.</p>{!authEnabled && (@@ -340,7 +355,7 @@ export function SharingTab() {onChange={(event) => setProviderEnabled(event.target.checked)}className="mt-1 h-4 w-4 accent-port-accent disabled:opacity-40"/>- <span className="text-sm text-white">Accept audio generation jobs from authenticated registered peers</span>+ <span className="text-sm text-white">Accept media generation jobs from authenticated registered peers</span></label><div>diff --git a/client/src/components/settings/SharingTab.test.jsx b/client/src/components/settings/SharingTab.test.jsxindex e78676f4ab..7872dc5898 100644--- a/client/src/components/settings/SharingTab.test.jsx+++ b/client/src/components/settings/SharingTab.test.jsx@@ -18,6 +18,7 @@ vi.mock('../ui/Toast', () => ({}));import { getAuthStatus, getMediaShareCandidates, getSettings, listMusicEngines, updateSettings } from '../../services/api';+import toast from '../ui/Toast';import { SharingTab } from './SharingTab';const strictToggle = () => screen.getByLabelText(/Enforce per-peer sharing settings/i);@@ -32,7 +33,7 @@ beforeEach(() => {});describe('SharingTab — federated media provider (#4348)', () => {- const providerToggle = () => screen.getByLabelText(/Accept audio generation jobs/i);+ const providerToggle = () => screen.getByLabelText(/Accept media generation jobs/i);it('keeps provider opt-in disabled until an instance password exists', async () => {render(<SharingTab />);@@ -230,7 +231,7 @@ describe('SharingTab — writes against the freshest federation slice', () => {});render(<SharingTab />);- const toggle = await screen.findByLabelText(/Accept audio generation jobs/i);+ const toggle = await screen.findByLabelText(/Accept media generation jobs/i);// The Instances page saves a route while this tab is sitting open.const route = { peerId: 'peer-1', engine: 'comfy', modelId: 'sdxl-base' };@@ -280,3 +281,30 @@ describe('SharingTab — a failed candidate fetch is not an empty catalog', () =expect(await screen.findByText(/No local image models are installed/i)).toBeInTheDocument();});});++describe('SharingTab — an absent federation slice is not a failed read', () => {+ it('aborts a provider save only when the read actually failed', async () => {+ getMediaShareCandidates.mockResolvedValue({ image: [], video: [] });+ getAuthStatus.mockResolvedValue({ enabled: true });+ getSettings.mockResolvedValueOnce({+ sharingDisplayName: '', sharingBio: '',+ federation: {+ mediaProvider: {+ enabled: true, maxQueuedJobs: 2,+ audioModels: [{ engine: 'minimax-music3', modelId: 'minimax-music3' }],+ },+ },+ });++ render(<SharingTab />);+ const toggle = await screen.findByLabelText(/Accept media generation jobs/i);++ getSettings.mockRejectedValueOnce(new Error('offline'));+ fireEvent.click(toggle);+ fireEvent.click(screen.getByRole('button', { name: 'Save provider' }));++ await waitFor(() => expect(toast.error)+ .toHaveBeenCalledWith('Could not read current settings — provider not saved'));+ expect(updateSettings).not.toHaveBeenCalled();+ });+});diff --git a/server/services/audioGen/remote.js b/server/services/audioGen/remote.jsindex 364912c221..df1bdf64e9 100644--- a/server/services/audioGen/remote.js+++ b/server/services/audioGen/remote.js@@ -23,6 +23,10 @@ const remoteMediaMarkerSchema = z.object({peerId: z.string().uuid(),reconcile: z.boolean().optional(),cancelRequested: z.boolean().optional(),+ // Set by the unattended (standing) router, never by an interactive render.+ // Optional so a marker already queued by an older build still validates; its+ // absence means "interactive", which is the correct reading of history.+ standingRoute: z.boolean().optional(),profile: federatedMediaAudioProfileSchema,// Free-form prompt/lyrics are deliberately absent from persisted routing// state. The adapter renders a fixed-vocabulary instrumental prompt from thediff --git a/server/services/creative/tools/media.test.js b/server/services/creative/tools/media.test.jsindex 9c9741df77..f41c8128ed 100644--- a/server/services/creative/tools/media.test.js+++ b/server/services/creative/tools/media.test.js@@ -4,7 +4,21 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';// boundary — every assertion here is about the params that land on it, because// `job.params.mode` is the ONLY thing mediaJobQueue routes the backend on.vi.mock('../../mediaJobQueue/index.js', () => ({ enqueueJob: vi.fn(() => ({ jobId: 'mj-test' })) }));-vi.mock('../../settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));+const getSettings = vi.fn(async () => ({}));+vi.mock('../../settings.js', () => ({+ getSettings: (...args) => getSettings(...args),+ // getSettings() hands back {} for a corrupt settings.json rather than+ // rejecting, so the router reads through this failure-aware wrapper instead.+ // Deriving it from the same mock keeps every existing setup working and makes+ // a mockRejectedValue model a corrupt read, which is what those tests mean.+ getSettingsWithStatus: async (...args) => {+ try {+ return { corrupt: false, settings: await getSettings(...args) };+ } catch {+ return { corrupt: true, settings: null };+ }+ },+}));vi.mock('../../creativeDirector/local.js', () => ({ getProject: vi.fn(async () => null) }));const getCommissionMusicContextForProject = vi.fn(async () => null);vi.mock('../../creativeCommissions/store.js', () => ({@@ -16,7 +30,6 @@ vi.mock('../../federatedMedia/remoteSubmission.js', () => ({}));import { enqueueJob } from '../../mediaJobQueue/index.js';-import { getSettings } from '../../settings.js';import { getProject } from '../../creativeDirector/local.js';import { MEDIA_TOOLS, reconcileVideoParamsWithModel } from './media.js';diff --git a/server/services/creativeDirector/firstPassGen.test.js b/server/services/creativeDirector/firstPassGen.test.jsindex 0d063605c6..ffcfa7a437 100644--- a/server/services/creativeDirector/firstPassGen.test.js+++ b/server/services/creativeDirector/firstPassGen.test.js@@ -7,6 +7,13 @@ vi.mock('../mediaJobQueue/index.js', () => ({}));vi.mock('../settings.js', () => ({getSettings: vi.fn(),+ getSettingsWithStatus: async (...args) => {+ try {+ return { corrupt: false, settings: await getSettings(...args) };+ } catch {+ return { corrupt: true, settings: null };+ }+ },}));vi.mock('../imageGen/index.js', () => ({resolveImageCleaners: vi.fn(() => ({ cleanC2PA: true, denoise: false })),diff --git a/server/services/creativeDirector/sceneRunner.backend.test.js b/server/services/creativeDirector/sceneRunner.backend.test.jsindex cf99094185..9d8f9d1096 100644--- a/server/services/creativeDirector/sceneRunner.backend.test.js+++ b/server/services/creativeDirector/sceneRunner.backend.test.js@@ -18,7 +18,16 @@ vi.mock('../mediaJobQueue/index.js', () => ({enqueueJob: vi.fn(() => ({ jobId: 'job-1' })),mediaJobEvents: { on: vi.fn(), off: vi.fn() },}));-vi.mock('../settings.js', () => ({ getSettings: vi.fn() }));+vi.mock('../settings.js', () => ({+ getSettings: vi.fn(),+ getSettingsWithStatus: async (...args) => {+ try {+ return { corrupt: false, settings: await getSettings(...args) };+ } catch {+ return { corrupt: true, settings: null };+ }+ },+}));vi.mock('./local.js', () => ({updateScene: vi.fn(async () => {}),updateProject: vi.fn(async () => {}),diff --git a/server/services/federatedMedia/defaultRouting.js b/server/services/federatedMedia/defaultRouting.jsindex 583a3344cc..179088cdc1 100644--- a/server/services/federatedMedia/defaultRouting.js+++ b/server/services/federatedMedia/defaultRouting.js@@ -27,17 +27,13 @@import { ServerError } from '../../lib/errorHandler.js';import { buildFederatedMediaRequest } from '../../lib/federatedMediaRequest.js';-import { getSettings } from '../settings.js';+import { getSettingsWithStatus } from '../settings.js';import { isTailnetPeer } from '../../lib/tailnetPeer.js';import { CLOUD_VIDEO_GEN_MODES, VIDEO_GEN_MODES } from '../videoGen/modes.js';// Only the visual kinds. See the audio note in the module docblock.export const ROUTABLE_MEDIA_KINDS = Object.freeze(['image', 'video']);-// Distinct from both `null` and `{}` so a failed settings read can never be-// mistaken for "settings say nothing is routed".-const UNREADABLE_SETTINGS = Symbol('unreadable-settings');-const isRecord = (value) => value && typeof value === 'object' && !Array.isArray(value);const trimmed = (value) => (typeof value === 'string' ? value.trim() : '');@@ -164,8 +160,13 @@ export async function hasConfiguredMediaRoute(kind) {// a local-readiness verdict may skip the render, and skipping is the one// outcome that silently discards work. Saying "routed" defers the decision to// resolveDefaultMediaRoute, which fails loudly with MEDIA_ROUTING_UNREADABLE.- const settings = await getSettings().catch(() => UNREADABLE_SETTINGS);- if (settings === UNREADABLE_SETTINGS) return true;+ //+ // `getSettingsWithStatus`, not `getSettings`: the latter hands back an empty+ // object for a corrupt settings.json rather than rejecting, so a `.catch()`+ // here would never fire and a configured route would read as absent — exactly+ // the collapse this is guarding against.+ const { corrupt, settings } = await getSettingsWithStatus().catch(() => ({ corrupt: true, settings: null }));+ if (corrupt) return true;return !!normalizeMediaRoutingConfig(settings)[kind];}@@ -188,11 +189,12 @@ export async function resolveDefaultMediaRoute({ kind, params }) {// another backend's quota) on work they deliberately sent elsewhere. That is// exactly the collapse the project's sentinel rule forbids, so a failed read// gets its own typed error rather than a null.- const settings = await getSettings().catch((error) => {+ const { corrupt, settings } = await getSettingsWithStatus().catch((error) => {console.error(`❌ Federated media routing could not read settings: ${error.message}`);- return UNREADABLE_SETTINGS;+ return { corrupt: true, settings: null };});- if (settings === UNREADABLE_SETTINGS) {+ if (corrupt) {+ console.error('❌ Federated media routing: settings.json is unreadable or malformed');throw new ServerError('Could not read this instance\'s media routing configuration',{ status: 503, code: 'MEDIA_ROUTING_UNREADABLE' },@@ -250,7 +252,12 @@ export async function resolveDefaultMediaRoute({ kind, params }) {// typed `WAN22_INVALID_FRAME_COUNT` — loud and fail-closed, but it makes that// pairing unusable until the capability contract carries the constraint. That// negotiation is its own slice; see the follow-up issue.- return { peer, request, remoteMedia };+ // 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, remoteMedia: { ...remoteMedia, standingRoute: true } };}/**diff --git a/server/services/federatedMedia/defaultRouting.test.js b/server/services/federatedMedia/defaultRouting.test.jsindex 5229e766bf..e5c3fdf2e3 100644--- a/server/services/federatedMedia/defaultRouting.test.js+++ b/server/services/federatedMedia/defaultRouting.test.js@@ -3,7 +3,20 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';const getSettings = vi.fn();const prepareRemoteMediaJob = vi.fn();-vi.mock('../settings.js', () => ({ getSettings: (...args) => getSettings(...args) }));+vi.mock('../settings.js', () => ({+ getSettings: (...args) => getSettings(...args),+ // getSettings() hands back {} for a corrupt settings.json rather than+ // rejecting, so the router reads through this failure-aware wrapper instead.+ // Deriving it from the same mock keeps every existing setup working and makes+ // a mockRejectedValue model a corrupt read, which is what those tests mean.+ getSettingsWithStatus: async (...args) => {+ try {+ return { corrupt: false, settings: await getSettings(...args) };+ } catch {+ return { corrupt: true, settings: null };+ }+ },+}));vi.mock('./remoteSubmission.js', () => ({prepareRemoteMediaJob: (...args) => prepareRemoteMediaJob(...args),}));@@ -377,3 +390,22 @@ describe('standing routes are gated on a tailnet peer', () => {.resolves.toMatchObject({ peer: { id: 'peer-1' } });});});++describe('a corrupt settings.json is not "no route"', () => {+ // getSettings() hands back {} for a corrupt file rather than rejecting, which+ // is why this reads through getSettingsWithStatus. A .catch() would never fire.+ it('fails the enqueue when the settings read reports corruption', async () => {+ getSettings.mockRejectedValue(new Error('malformed JSON'));+ await expect(resolveDefaultMediaRoute({ kind: 'image', params: { prompt: 'p' } }))+ .rejects.toMatchObject({ code: 'MEDIA_ROUTING_UNREADABLE' });+ });++ it('stamps the standing-route bit so the boundary survives the enqueue', async () => {+ getSettings.mockResolvedValue({+ federation: { mediaRouting: { image: { peerId: 'peer-1', engine: 'comfy', modelId: 'sdxl-remote' } } },+ });+ const resolved = await resolveDefaultMediaRoute({ kind: 'image', params: { prompt: 'p' } });+ expect(resolved.remoteMedia.standingRoute).toBe(true);+ expect(routedJobParams({ prompt: 'p' }, resolved).remoteMedia.standingRoute).toBe(true);+ });+});diff --git a/server/services/federatedMedia/remoteExecutor.js b/server/services/federatedMedia/remoteExecutor.jsindex 29bc99d5cc..2c3ed8359e 100644--- a/server/services/federatedMedia/remoteExecutor.js+++ b/server/services/federatedMedia/remoteExecutor.js@@ -32,6 +32,7 @@ import { peerBaseUrl } from '../../lib/peerUrl.js';import { readResponseJson } from '../../lib/readResponseJson.js';import { resolveFederatedMediaProvider } from '../federatedMediaConsumer.js';import { getPeers } from '../instances.js';+import { isTailnetPeer } from '../../lib/tailnetPeer.js';const RETRYABLE_HTTP_STATUSES = new Set([408, 425, 429]);const PERMANENT_SELECTION_CODES = new Set([@@ -132,7 +133,7 @@ export function createRemoteMediaExecutor({}}- async function findPeer(peerId) {+ async function findPeer(peerId, { standingRoute = false } = {}) {const peers = await getPeers();const peer = peers.find((candidate) => candidate.id === peerId);if (!peer || peer.enabled === false) {@@ -140,11 +141,23 @@ export function createRemoteMediaExecutor({code: 'MEDIA_PROVIDER_PEER_UNAVAILABLE',});}+ // A standing route's tailnet gate is checked at enqueue, but the peer record+ // it checked can change while the job sits queued or reconciles across a+ // restart — a host edited from a .ts.net name to a LAN address would+ // otherwise carry the visual prompt over an unauthenticated hop on the very+ // next request. Every request path (submit, poll, cancel, result) resolves+ // its peer here, so re-checking at this one chokepoint covers all of them.+ // ADR docs/decisions/2026-08-20-federated-visual-prompts.md, rule 5.+ if (standingRoute && !isTailnetPeer(peer)) {+ throw remoteMediaError('Media provider peer is no longer a Tailscale host', {+ code: 'MEDIA_ROUTING_PEER_NOT_TAILNET',+ });+ }return peer;}async function requestJson(state, path, options = {}, requestOptions = {}) {- const peer = await findPeer(state.peerId);+ const peer = await findPeer(state.peerId, { standingRoute: state.standingRoute });const { response, body } = await withRequest(state,async (signal) => {@@ -182,7 +195,7 @@ export function createRemoteMediaExecutor({async function preflight(state, selection) {while (true) {if (state.cancelRequested) throw canceledError();- const peer = await findPeer(state.peerId);+ const peer = await findPeer(state.peerId, { standingRoute: state.standingRoute });try {await withRequest(state,@@ -333,7 +346,7 @@ export function createRemoteMediaExecutor({if (await existingResultMatches(finalPath, metadata)) return { filename, dir, path: finalPath };await unlink(partialPath).catch(() => {});- const peer = await findPeer(state.peerId);+ const peer = await findPeer(state.peerId, { standingRoute: state.standingRoute });// Keep the controller live for the body stream so cancel()/the queue// watchdog can interrupt a stalled transfer. There is intentionally no// fixed wall-clock timeout: large renders over a slow Tailnet are valid@@ -460,6 +473,9 @@ export function createRemoteMediaExecutor({cancelRequested: marker.data.cancelRequested === true,cancelSent: false,submissionMayExist: marker.data.reconcile === true,+ // Absent on an interactive marker (and on any marker queued before this+ // shipped), which reads correctly as "not a standing route".+ standingRoute: marker.data.standingRoute === true,requestController: null,wake: null,};diff --git a/server/services/imageGen/remote.js b/server/services/imageGen/remote.jsindex c5521d5bf9..ef29a00604 100644--- a/server/services/imageGen/remote.js+++ b/server/services/imageGen/remote.js@@ -25,6 +25,10 @@ const remoteImageMarkerSchema = z.object({peerId: z.string().uuid(),reconcile: z.boolean().optional(),cancelRequested: z.boolean().optional(),+ // Set by the unattended (standing) router, never by an interactive render.+ // Optional so a marker already queued by an older build still validates; its+ // absence means "interactive", which is the correct reading of history.+ standingRoute: z.boolean().optional(),// The full wire submission, re-validated on every replay. Persisted queue// state is user-editable, so the body that actually leaves this machine is// the one this schema accepted — not whatever the file happens to contain.diff --git a/server/services/imageGen/remote.test.js b/server/services/imageGen/remote.test.jsindex 6ad817c551..217f939f11 100644--- a/server/services/imageGen/remote.test.js+++ b/server/services/imageGen/remote.test.js@@ -236,3 +236,21 @@ describe('federated image consumer adapter', () => {expect(transport.fetch).not.toHaveBeenCalled();});});++// #4348 / ADR 2026-08-20-federated-visual-prompts rule 5. The enqueue-time+// tailnet gate checked the peer record as it looked THEN; a queued or+// reconciling job re-resolves its peer on every request, and that record can+// change underneath it. The fixture peer is a plain LAN address — and every+// OTHER test in this file drives that same peer with an interactive (no+// standing bit) marker and still passes, which is what pins the other half of+// this contract: interactive routing is explicitly out of scope for rule 5.+describe('standing-route tailnet boundary survives the enqueue', () => {+ it('refuses to submit when a standing route peer is no longer a tailnet host', async () => {+ const base = params();+ const settled = captureTerminal(LOCAL_JOB_ID);+ await generateImage({ ...base, remoteMedia: { ...base.remoteMedia, standingRoute: true } });+ const outcome = await settled;+ expect(outcome.type).toBe('failed');+ expect(outcome.event.error).toMatch(/no longer a Tailscale host/i);+ });+});diff --git a/server/services/settings.js b/server/services/settings.jsindex 37584992bb..7a9545aafa 100644--- a/server/services/settings.js+++ b/server/services/settings.js@@ -211,7 +211,20 @@ const save = async (settings) => {return cleaned;};-export const getSettings = async () => {+/**+ * `getSettings`, but reporting whether the snapshot came from a CORRUPT read.+ *+ * `getSettings()` deliberately hands back an empty object when settings.json is+ * malformed or unreadable, which makes "corrupt" indistinguishable from "fresh+ * install with nothing configured". That is the right default for most readers —+ * they want a usable object — but it is wrong for any caller whose decision is+ * spend-bearing or privacy-bearing, where guessing "nothing is configured" can+ * silently do the opposite of what the user set up (see the federated media+ * router, which must fail loudly rather than render locally).+ *+ * @returns {Promise<{corrupt: boolean, settings: object}>}+ */+export const getSettingsWithStatus = async () => {if (settingsCache === null) {// Route the cold read through the STRICT reader so a corrupt/unreadable// settings.json does NOT poison the cache with `{}` (issue #2684). Caching a@@ -225,17 +238,19 @@ export const getSettings = async () => {// A save()/reloadSettings() may have populated the cache via the// settings:updated listener while this cold read was awaiting the disk read.// Prefer that fresher in-memory value over our (older) on-disk snapshot.- if (settingsCache !== null) return structuredClone(settingsCache);+ if (settingsCache !== null) return { corrupt: false, settings: structuredClone(settingsCache) };// On a corrupt read, hand back the empty snapshot WITHOUT caching it, so the// very next call re-reads and picks up a repair immediately.- if (corrupt) return structuredClone(loaded);+ if (corrupt) return { corrupt: true, settings: structuredClone(loaded) };settingsCache = loaded;}// Hand out a private deep copy so a caller mutating nested settings in place// can't corrupt the shared cache — matching the prior per-call// `stripStoreKeys(await loadRaw())` deep-copy semantics, minus the I/O.- return structuredClone(settingsCache);+ return { corrupt: false, settings: structuredClone(settingsCache) };};++export const getSettings = async () => (await getSettingsWithStatus()).settings;export const saveSettings = (settings) => queueWrite(() => save(settings));// Merge against the unstripped on-disk snapshot so save() sees everydiff --git a/server/services/videoGen/remote.js b/server/services/videoGen/remote.jsindex ff36171531..4044db64c2 100644--- a/server/services/videoGen/remote.js+++ b/server/services/videoGen/remote.js@@ -27,6 +27,10 @@ const remoteVideoMarkerSchema = z.object({peerId: z.string().uuid(),reconcile: z.boolean().optional(),cancelRequested: z.boolean().optional(),+ // Set by the unattended (standing) router, never by an interactive render.+ // Optional so a marker already queued by an older build still validates; its+ // absence means "interactive", which is the correct reading of history.+ standingRoute: z.boolean().optional(),// Re-validated on every replay — persisted queue state is user-editable, so// the body that leaves this machine is the one this schema accepted.request: federatedMediaVideoJobSubmissionSchema,