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: persist local image execution provenance (#5072)
[._.]/ Adam Eivy571949fd42e2
diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsxindex ee6074db37..ec900fbc24 100644--- a/client/src/components/media/MediaLightbox.jsx+++ b/client/src/components/media/MediaLightbox.jsx@@ -80,6 +80,15 @@ function describeCleanedLineage(item) {return null;}+function describeImageExecution(item) {+ const execution = item.executionProvenance || item.raw?.result?.executionProvenance;+ if (!execution) return item.kind === 'image' ? 'Unknown (legacy runner)' : null;+ if (execution.state === 'malformed') return 'Unknown (invalid runner marker)';+ if (execution.state === 'confirmed') return `Confirmed · ${execution.effectiveDevice}${execution.placement !== execution.effectiveDevice ? ` (${execution.placement})` : ''}`;+ if (execution.state === 'degraded') return `Degraded · CPU fallback${execution.requestedDevice !== 'cpu' ? ` (requested ${execution.requestedDevice})` : ''}`;+ return 'Unknown';+}+// onClean(item) — optional. Returning a rejected promise keeps the lightbox// open (e.g. on error) so the user can retry.//@@ -206,6 +215,7 @@ export default function MediaLightbox({// the server contract; users shouldn't see the wire tokens.const entryKindLabel = ({ canon: 'Canon entry', variation: 'Category variation', sheet: 'Composite sheet' })[item.entryKind] || item.entryKind;const cleanedLabel = describeCleanedLineage(item);+ const executionLabel = describeImageExecution(item);// Speed profile (#4875). The REQUESTED schedule, annotated with whatever the// runner could not actually apply. Without this the degraded case exists only@@ -249,6 +259,7 @@ export default function MediaLightbox({['Seed', item.seed ?? (isCodex ? 'n/a (gpt-image-2)' : null)],['Codex session', item.codexSessionId],['Cleaned', cleanedLabel],+ ['Execution', executionLabel],['Frames', item.numFrames],['FPS', item.fps],// What the conditioning image promised (#4874). Recorded on the render onlydiff --git a/client/src/components/media/MediaLightbox.test.jsx b/client/src/components/media/MediaLightbox.test.jsxindex f0516e525d..b242a1497e 100644--- a/client/src/components/media/MediaLightbox.test.jsx+++ b/client/src/components/media/MediaLightbox.test.jsx@@ -228,3 +228,22 @@ describe('MediaLightbox — i2v reference provenance (#4874)', () => {expect(screen.queryByText('Reference')).toBeNull();});});++describe('MediaLightbox — local image execution provenance', () => {+ it('distinguishes confirmed, degraded, and unknown legacy image execution', () => {+ const { rerender } = render(<MediaLightbox item={{ ...imageItem, executionProvenance: { state: 'confirmed', effectiveDevice: 'cuda', placement: 'cuda+offload' } }} onClose={() => {}} />);+ expect(screen.getByText('Execution')).toBeTruthy();+ expect(screen.getByText('Confirmed · cuda (cuda+offload)')).toBeTruthy();++ rerender(<MediaLightbox item={{ ...imageItem, executionProvenance: { state: 'degraded', requestedDevice: 'mps' } }} onClose={() => {}} />);+ expect(screen.getByText('Degraded · CPU fallback (requested mps)')).toBeTruthy();++ rerender(<MediaLightbox item={imageItem} onClose={() => {}} />);+ expect(screen.getByText('Unknown (legacy runner)')).toBeTruthy();+ });++ it('does not mistake a malformed marker for confirmed execution', () => {+ render(<MediaLightbox item={{ ...imageItem, executionProvenance: { state: 'malformed' } }} onClose={() => {}} />);+ expect(screen.getByText('Unknown (invalid runner marker)')).toBeTruthy();+ });+});diff --git a/scripts/_runner_common.py b/scripts/_runner_common.pyindex ac6e402ad4..5f1178ecab 100644--- a/scripts/_runner_common.py+++ b/scripts/_runner_common.py@@ -204,6 +204,63 @@ def emit_runtime_fingerprint(runtime_id: str, packages, extra_versions=None) ->return {}+def build_image_execution_marker(+ runtime_id: str,+ requested_device: str,+ effective_device: str,+ placement: str,+ packages,+ extra_versions=None,+) -> dict:+ """Return the bounded execution evidence emitted by local image runners.++ A successful PNG is not evidence that an accelerator actually ran it. Keep+ this marker deliberately small and portable: it records the caller's+ request, the resolved device/placement, and only the runtime's allowlisted+ package versions. Host paths, prompts, environment, and stderr never+ belong in durable gallery metadata.+ """+ fingerprint = build_runtime_fingerprint(runtime_id, packages, extra_versions)+ cpu_fallback = effective_device == "cpu"+ return {+ "version": 1,+ "state": "degraded" if cpu_fallback else "confirmed",+ "requestedDevice": requested_device,+ "effectiveDevice": effective_device,+ "placement": placement,+ "cpuFallback": cpu_fallback,+ "runtime": {+ "runtime": fingerprint["runtime"],+ "versions": fingerprint["versions"],+ },+ }+++def emit_image_execution_marker(+ runtime_id: str,+ requested_device: str,+ effective_device: str,+ placement: str,+ packages,+ extra_versions=None,+) -> dict:+ """Print one parseable image-execution marker after placement resolves."""+ try:+ marker = build_image_execution_marker(+ runtime_id,+ requested_device,+ effective_device,+ placement,+ packages,+ extra_versions,+ )+ print(f"IMAGE_EXECUTION:{json.dumps(marker)}", file=sys.stderr, flush=True)+ return marker+ except Exception as err: # pragma: no cover - defensive+ print(f"⚠️ image execution marker failed: {err}", file=sys.stderr, flush=True)+ return {}++class _ClipTruncationFilter(logging.Filter):_MARKER = "input was truncated because CLIP can only handle"diff --git a/scripts/flux2_macos.py b/scripts/flux2_macos.pyindex 1ec34d5c9e..eb1e8f8bf7 100755--- a/scripts/flux2_macos.py+++ b/scripts/flux2_macos.py@@ -37,6 +37,7 @@ from PIL import Imagesys.path.insert(0, str(Path(__file__).resolve().parent))from _runner_common import ( # noqa: E402apply_memory_optimizations,+ emit_image_execution_marker,heartbeat,install_hf_error_handler,make_generator,@@ -429,6 +430,15 @@ def main() -> None:else:print(f"❌ unknown quantization: {args.quantization}", file=sys.stderr)sys.exit(64)+ # The runner only reports accelerator evidence after the pipeline has been+ # placed. A successful image alone must not be read as GPU confirmation.+ emit_image_execution_marker(+ "flux2",+ args.device,+ device,+ device,+ ["torch", "diffusers", "transformers", "accelerate"],+ )suppress_cosmetic_clip_truncation()apply_memory_optimizations(pipe, width=args.width, height=args.height)diff --git a/scripts/image_execution_marker.test.js b/scripts/image_execution_marker.test.jsnew file mode 100644index 0000000000..c637df40e7--- /dev/null+++ b/scripts/image_execution_marker.test.js@@ -0,0 +1,30 @@+import { execFileSync } from 'child_process';+import { fileURLToPath } from 'url';+import { dirname } from 'path';+import { describe, expect, it } from 'vitest';++const scriptsDir = dirname(fileURLToPath(import.meta.url));++describe('local image execution marker', () => {+ it('records a CPU fallback as degraded without host or prompt data', () => {+ const program = [+ 'import json, sys',+ `sys.path.insert(0, ${JSON.stringify(scriptsDir)})`,+ 'from _runner_common import build_image_execution_marker',+ "print(json.dumps(build_image_execution_marker('flux2', 'cuda', 'cpu', 'cpu', [])))",+ ].join('; ');+ const marker = JSON.parse(execFileSync('python3', ['-c', program], { encoding: 'utf8' }));++ expect(marker).toMatchObject({+ version: 1,+ state: 'degraded',+ requestedDevice: 'cuda',+ effectiveDevice: 'cpu',+ placement: 'cpu',+ cpuFallback: true,+ runtime: { runtime: 'flux2', versions: {} },+ });+ expect(marker).not.toHaveProperty('prompt');+ expect(marker).not.toHaveProperty('path');+ });+});diff --git a/scripts/z_image_turbo.py b/scripts/z_image_turbo.pyindex 0dbcc3b116..6a3f23bf32 100644--- a/scripts/z_image_turbo.py+++ b/scripts/z_image_turbo.py@@ -33,6 +33,7 @@ from PIL import Imagesys.path.insert(0, str(Path(__file__).resolve().parent))from _runner_common import ( # noqa: E402apply_memory_optimizations,+ emit_image_execution_marker,heartbeat,install_hf_error_handler,make_generator,@@ -171,8 +172,8 @@ def load_pipeline()print("STAGE:move-to-device", file=sys.stderr, flush=True)with heartbeat("move-to-device"):- place_pipeline(pipe, device)- return pipe+ placement = place_pipeline(pipe, device)+ return pipe, placementdef to_i2i_pipeline(pipe):@@ -217,7 +218,7 @@ def main() -> None:device = pick_device(args.device)dtype = torch.bfloat16 if device in ("mps", "cuda") else torch.float32- pipe = load_pipeline(+ pipe, placement = load_pipeline(args.repo,device,dtype,@@ -226,6 +227,13 @@ def main() -> None:text_encoder_class=args.text_encoder_class,tokenizer_class=args.tokenizer_class,)+ emit_image_execution_marker(+ "diffusers-image",+ args.device,+ device,+ placement,+ ["torch", "diffusers", "transformers", "accelerate"],+ )init_image = Noneif args.image_path:diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 8742abaf0b..b2c6cbde05 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -488,6 +488,48 @@ export function resolveOutputPlacement(outputTarget) {return { outputDir, skipSidecar, isGallery };}+const IMAGE_EXECUTION_MARKER = 'IMAGE_EXECUTION:';+const IMAGE_EXECUTION_DEVICES = new Set(['auto', 'mps', 'cuda', 'cpu']);+const IMAGE_EXECUTION_EFFECTIVE_DEVICES = new Set(['mps', 'cuda', 'cpu']);+const IMAGE_EXECUTION_PLACEMENTS = new Set(['mps', 'cuda', 'cuda+offload', 'cpu']);+const IMAGE_EXECUTION_RUNTIMES = new Set(['flux2', 'diffusers-image']);+const IMAGE_EXECUTION_PACKAGES = new Set(['torch', 'diffusers', 'transformers', 'accelerate']);++const boundedString = (value, max = 80) => (typeof value === 'string' && value.length > 0 && value.length <= max ? value : null);++// A malformed marker is evidence of neither GPU nor CPU execution. Keep it+// distinct from an older runner that emitted no marker at all, while refusing+// to persist arbitrary subprocess JSON into a gallery sidecar.+export function parseImageExecutionMarker(line) {+ if (typeof line !== 'string' || !line.startsWith(IMAGE_EXECUTION_MARKER)) return null;+ let value;+ try {+ value = JSON.parse(line.slice(IMAGE_EXECUTION_MARKER.length));+ } catch {+ return { state: 'malformed' };+ }+ if (!value || value.version !== 1+ || !IMAGE_EXECUTION_DEVICES.has(value.requestedDevice)+ || !IMAGE_EXECUTION_EFFECTIVE_DEVICES.has(value.effectiveDevice)+ || !IMAGE_EXECUTION_PLACEMENTS.has(value.placement)+ || !IMAGE_EXECUTION_RUNTIMES.has(value.runtime?.runtime)+ || typeof value.cpuFallback !== 'boolean') return { state: 'malformed' };+ const expectedState = value.effectiveDevice === 'cpu' ? 'degraded' : 'confirmed';+ if (value.state !== expectedState || value.cpuFallback !== (expectedState === 'degraded')) return { state: 'malformed' };+ const versions = Object.fromEntries(Object.entries(value.runtime.versions || {})+ .filter(([name, version]) => IMAGE_EXECUTION_PACKAGES.has(name) && boundedString(version))+ .map(([name, version]) => [name, version]));+ return {+ version: 1,+ state: expectedState,+ requestedDevice: value.requestedDevice,+ effectiveDevice: value.effectiveDevice,+ placement: value.placement,+ cpuFallback: value.cpuFallback,+ runtime: { runtime: value.runtime.runtime, versions },+ };+}+export async function generateImage({ pythonPath, prompt = '', negativePrompt = '', modelId = LOCAL_IMAGEGEN_DEFAULT_MODEL, width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null, referenceImagePaths = [], referenceImageStrengths = [], jobId: providedJobId = null, cleanC2PA = false, denoise = false, regenOf = null, upscaleTo = null, outputTarget = null }) {// Empty prompt is allowed: img2img / edit / unconditional renders are driven// by the init image (or run unconditionally), so text isn't required. The@@ -727,6 +769,14 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =// tqdm is slow to update during connection-establishment.imageGenEvents.emit('activity', { generationId: jobId });+ const execution = parseImageExecutionMarker(trimmed);+ if (execution) {+ meta.executionProvenance = execution;+ job.executionProvenance = execution;+ if (activeJob?.generationId === jobId) activeJob.executionProvenance = execution;+ return true;+ }+if (trimmed.startsWith('STAGE:')) {const rest = trimmed.slice(6); // strip 'STAGE:'const colon = rest.indexOf(':');@@ -969,7 +1019,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =// A non-gallery render has no `/data/images` mount — carry the absolute// `outputPath` so the queue/route can read the finished bytes; `path`// stays null so nothing treats it as a gallery URL.- const result = { filename, seed: actualSeed, path: publicPath, outputPath };+ const result = { filename, seed: actualSeed, path: publicPath, outputPath, ...(meta.executionProvenance ? { executionProvenance: meta.executionProvenance } : {}) };broadcastSse(job, { type: 'complete', result });// Include `seed` so /sdapi/v1/txt2img can surface the actual seed used// (mflux generates a random one if the client didn't pass one). Emit the@@ -978,11 +1028,11 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =// federated. The queue's own `completed` handler still fires off the// return value below, so the job settles either way.if (!skipSidecar) {- imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, path: publicPath, filename, seed: actualSeed });+ imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, path: publicPath, filename, seed: actualSeed, ...(meta.executionProvenance ? { executionProvenance: meta.executionProvenance } : {}) });} else {// `temp: true` tells the media-asset-index + peer-sync hooks to ignore// this render — there's no gallery file or sidecar to index/federate.- imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, path: null, filename, seed: actualSeed, outputPath, temp: true });+ imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, path: null, filename, seed: actualSeed, outputPath, temp: true, ...(meta.executionProvenance ? { executionProvenance: meta.executionProvenance } : {}) });}}closeJobAfterDelay(jobs, jobId);diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.jsindex 5eb0debcf8..4944ac2207 100644--- a/server/services/imageGen/local.test.js+++ b/server/services/imageGen/local.test.js@@ -23,6 +23,7 @@ let priorRegistryEnv;let buildArgs;let buildSidecarMeta;let resolveOutputPlacement;+let parseImageExecutionMarker;let PATHS;beforeAll(async () => {@@ -30,10 +31,47 @@ beforeAll(async () => {priorRegistryEnv = process.env.PORTOS_MEDIA_MODELS_FILE;process.env.PORTOS_MEDIA_MODELS_FILE = join(tmpRegistryDir, 'media-models.json');vi.resetModules();- ({ buildArgs, buildSidecarMeta, resolveOutputPlacement } = await import('./local.js'));+ ({ buildArgs, buildSidecarMeta, resolveOutputPlacement, parseImageExecutionMarker } = await import('./local.js'));({ PATHS } = await import('../../lib/fileUtils.js'));});+describe('imageGen local.parseImageExecutionMarker', () => {+ const marker = (value) => `IMAGE_EXECUTION:${JSON.stringify(value)}`;+ const confirmed = {+ version: 1,+ state: 'confirmed',+ requestedDevice: 'auto',+ effectiveDevice: 'cuda',+ placement: 'cuda+offload',+ cpuFallback: false,+ runtime: { runtime: 'diffusers-image', versions: { torch: '2.7.0', prompt: 'must not persist' } },+ };++ it('accepts only the bounded runtime evidence after marker chunks are reassembled', () => {+ expect(parseImageExecutionMarker(marker(confirmed))).toEqual({+ ...confirmed,+ runtime: { runtime: 'diffusers-image', versions: { torch: '2.7.0' } },+ });+ });++ it('keeps malformed and absent markers distinct from confirmed execution', () => {+ expect(parseImageExecutionMarker('IMAGE_EXECUTION:{not-json}')).toEqual({ state: 'malformed' });+ expect(parseImageExecutionMarker(marker({ ...confirmed, cpuFallback: true }))).toEqual({ state: 'malformed' });+ expect(parseImageExecutionMarker('RUNTIME:{"runtime":"diffusers-image"}')).toBeNull();+ });++ it('marks an explicit CPU path as degraded rather than accelerator-confirmed', () => {+ expect(parseImageExecutionMarker(marker({+ ...confirmed,+ state: 'degraded',+ requestedDevice: 'cuda',+ effectiveDevice: 'cpu',+ placement: 'cpu',+ cpuFallback: true,+ }))).toMatchObject({ state: 'degraded', effectiveDevice: 'cpu', cpuFallback: true });+ });+});+afterAll(() => {if (priorRegistryEnv === undefined) delete process.env.PORTOS_MEDIA_MODELS_FILE;else process.env.PORTOS_MEDIA_MODELS_FILE = priorRegistryEnv;diff --git a/server/services/mediaJobQueue/sanitizeJob.js b/server/services/mediaJobQueue/sanitizeJob.jsindex 5246f8bad5..8bff0cc92c 100644--- a/server/services/mediaJobQueue/sanitizeJob.js+++ b/server/services/mediaJobQueue/sanitizeJob.js@@ -20,6 +20,31 @@ const MUSIC_STUDIO_KEYS = new Set(['trackId', 'title', 'artistId', 'artist', 'albumId', 'lyricsEnabled', 'lyricsProvided', 'instrumentalOnly',]);+const EXECUTION_RUNTIME_KEYS = new Set(['torch', 'diffusers', 'transformers', 'accelerate']);+const executionProvenance = (value) => {+ if (!value || typeof value !== 'object') return undefined;+ if (value.state === 'malformed') return { state: 'malformed' };+ if (!['confirmed', 'degraded'].includes(value.state)+ || !['auto', 'mps', 'cuda', 'cpu'].includes(value.requestedDevice)+ || !['mps', 'cuda', 'cpu'].includes(value.effectiveDevice)+ || !['mps', 'cuda', 'cuda+offload', 'cpu'].includes(value.placement)+ || typeof value.cpuFallback !== 'boolean'+ || !['flux2', 'diffusers-image'].includes(value.runtime?.runtime)) return undefined;+ return {+ version: 1,+ state: value.state,+ requestedDevice: value.requestedDevice,+ effectiveDevice: value.effectiveDevice,+ placement: value.placement,+ cpuFallback: value.cpuFallback,+ runtime: {+ runtime: value.runtime.runtime,+ versions: Object.fromEntries(Object.entries(value.runtime.versions || {})+ .filter(([key, version]) => EXECUTION_RUNTIME_KEYS.has(key) && typeof version === 'string' && version.length <= 80)),+ },+ };+};+export function sanitizeJob(job) {if (!job) return job;const safeParams = job.params@@ -38,6 +63,11 @@ export function sanitizeJob(job) {// Rebuild the prompt for the public projection without exposing private peer// routing state.const remotePrompt = effectiveJobPrompt(job);+ const safeExecution = executionProvenance(job.result?.executionProvenance);+ const { executionProvenance: _executionProvenance, ...resultWithoutExecution } = job.result && typeof job.result === 'object' ? job.result : {};+ const safeResult = job.result && typeof job.result === 'object'+ ? { ...resultWithoutExecution, ...(safeExecution ? { executionProvenance: safeExecution } : {}) }+ : job.result;// The model id is nulled in top-level params for the same reason (#4683), so// rebuild it from the marker too — the Render Queue's model badge reads// `params.modelId`, and every routed kind (audio included: routes/music.js@@ -73,7 +103,7 @@ export function sanitizeJob(job) {render: job.render,etaMs: job.etaMs,error: job.error,- result: job.result,+ result: safeResult,params: safeParams,};}diff --git a/server/services/mediaJobQueue/sanitizeJob.test.js b/server/services/mediaJobQueue/sanitizeJob.test.jsindex 81b2a041ed..e7a27bcd89 100644--- a/server/services/mediaJobQueue/sanitizeJob.test.js+++ b/server/services/mediaJobQueue/sanitizeJob.test.js@@ -2,6 +2,40 @@ import { describe, expect, it } from 'vitest';import { sanitizeJob } from './sanitizeJob.js';describe('sanitizeJob', () => {+ it('projects only validated image execution provenance from a completed result', () => {+ const sanitized = sanitizeJob({+ id: 'image-job',+ kind: 'image',+ status: 'completed',+ result: {+ filename: 'image.png',+ executionProvenance: {+ version: 1,+ state: 'confirmed',+ requestedDevice: 'auto',+ effectiveDevice: 'cuda',+ placement: 'cuda+offload',+ cpuFallback: false,+ runtime: { runtime: 'diffusers-image', versions: { torch: '2.7.0', prompt: 'private' } },+ },+ },+ });+ expect(sanitized.result.executionProvenance).toEqual({+ version: 1,+ state: 'confirmed',+ requestedDevice: 'auto',+ effectiveDevice: 'cuda',+ placement: 'cuda+offload',+ cpuFallback: false,+ runtime: { runtime: 'diffusers-image', versions: { torch: '2.7.0' } },+ });+ });++ it('does not leak an invalid execution marker into the public queue result', () => {+ const sanitized = sanitizeJob({ id: 'image-job', kind: 'image', status: 'completed', result: { executionProvenance: { state: 'confirmed', prompt: 'private' } } });+ expect(sanitized.result).not.toHaveProperty('executionProvenance');+ });+it('exposes safe video retry configuration fields', () => {const sanitized = sanitizeJob({id: 'video-job',