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([issue-1325]): stamp a runtime fingerprint on each video render + surface it on /status
[._.]/ Adam Eivy35126d4e844e
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex 743f974150..8b487c348d 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -1344,6 +1344,39 @@ export default function VideoGen() {</div></div>+ {/* Runtime fingerprint — host chip/OS + resolved ltx/mlx/torch versions+ per installed runtime. Lets a user (or a bug report for garbled+ output) see the exact numerical stack without running a render. */}+ {status?.runtime && (() => {+ const host = status.runtime.host || {};+ const runtimes = status.runtime.runtimes || {};+ const ids = Object.keys(runtimes);+ if (!host.chip && !host.os && ids.length === 0) return null;+ return (+ <div className="text-[10px] text-gray-500 flex flex-wrap items-center gap-x-2 gap-y-0.5">+ {host.chip && <span title="Host chip">{host.chip}</span>}+ {host.os && <span title="Operating system">· {host.os}</span>}+ {ids.map((id) => {+ const fp = runtimes[id] || {};+ if (fp.error) {+ return (+ <span key={id} className="text-port-warning/70" title={`Version probe failed: ${fp.error}`}>+ · {id}: version probe failed+ </span>+ );+ }+ const versions = fp.versions && typeof fp.versions === 'object' ? fp.versions : {};+ const vers = Object.keys(versions).length+ ? Object.entries(versions).map(([k, v]) => `${k} ${v}`).join(', ')+ : 'no versions resolved';+ return (+ <span key={id} title={`${id} runtime`}>· {id}: {vers}</span>+ );+ })}+ </div>+ );+ })()}+{status && status.connected === false && (() => {const missingCount = status.missingPackages?.length || 0;const hasPath = !!status.pythonPath;diff --git a/scripts/_runner_common.py b/scripts/_runner_common.pyindex 8505050aa4..d134e15584 100644--- a/scripts/_runner_common.py+++ b/scripts/_runner_common.py@@ -21,6 +21,8 @@ walker that turns a buried `GatedRepoError` into a friendly link — belongs herimport jsonimport loggingimport os+import platform+import subprocessimport sysimport threadingfrom contextlib import contextmanager@@ -99,6 +101,80 @@ def parse_user_loras(raw: "str | None") -> "list[tuple[str, float]]":return specs+def _mac_chip() -> str:+ """Human chip name on macOS ('Apple M5 Max'). Falls back to+ platform.processor()/machine() so the field is never empty."""+ try:+ out = subprocess.run(+ ["sysctl", "-n", "machdep.cpu.brand_string"],+ capture_output=True, text=True, timeout=2,+ )+ if out.returncode == 0 and out.stdout.strip():+ return out.stdout.strip()+ except (OSError, subprocess.SubprocessError):+ pass+ return platform.processor() or platform.machine() or "unknown"+++def _resolve_pkg_version(pkg: str) -> "str | None":+ """importlib.metadata.version for `pkg`, tolerant of the+ underscore/dash skew between import names and distribution names+ (callers pass whichever they know). Returns None when not installed."""+ from importlib.metadata import PackageNotFoundError, version as _version+ for candidate in (pkg, pkg.replace("_", "-"), pkg.replace("-", "_")):+ try:+ return _version(candidate)+ except PackageNotFoundError:+ continue+ except Exception:+ return None+ return None+++def build_runtime_fingerprint(runtime_id: str, packages, extra=None) -> dict:+ """Build a runtime-fingerprint dict — which runtime + resolved package+ versions + chip/os/python — so a render (or a bug report) self-documents the+ exact numerical stack it ran on. Garbled/"mosaic" video output is often a+ per-chip/per-runtime numerical bug rather than a crash, and the version trio+ is what makes those reports actionable (see issue #1325).++ Pure (no printing) so the on-demand /status probe (scripts/runtime_fingerprint.py)+ and the inline render-time emit share one definition. Best-effort: a package+ that isn't installed is simply omitted from `versions` rather than raising.+ """+ versions = {}+ for pkg in packages or []:+ v = _resolve_pkg_version(pkg)+ if v is not None:+ versions[pkg] = v+ fp = {+ "runtime": runtime_id,+ "versions": versions,+ "chip": _mac_chip() if sys.platform == "darwin"+ else (platform.processor() or platform.machine() or "unknown"),+ "os": platform.platform(),+ "python": platform.python_version(),+ }+ if extra:+ fp.update({k: v for k, v in extra.items() if v is not None})+ return fp+++def emit_runtime_fingerprint(runtime_id: str, packages, extra=None) -> dict:+ """Print a single `RUNTIME:<json>` line to stderr — the channel PortOS's+ videoGen line handler (makeVideoGenLineHandler) parses to stamp the+ fingerprint onto the render job + history record. Best-effort: never raises+ (a fingerprint failure must not abort a render). Returns the dict it emitted+ (or {} on failure) so callers can also log it locally if they want."""+ try:+ fp = build_runtime_fingerprint(runtime_id, packages, extra)+ print(f"RUNTIME:{json.dumps(fp)}", file=sys.stderr, flush=True)+ return fp+ except Exception as err: # pragma: no cover - defensive+ print(f"⚠️ runtime fingerprint 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/generate_av_lora.py b/scripts/generate_av_lora.pyindex 8dd3e585c5..3feb2a20b6 100644--- a/scripts/generate_av_lora.py+++ b/scripts/generate_av_lora.py@@ -39,7 +39,7 @@ from pathlib import Path# insert defensively (mirrors generate_hunyuan.py). _runner_common is# stdlib-only at import time, so this is safe from the MLX venv.sys.path.insert(0, str(Path(__file__).resolve().parent))-from _runner_common import parse_user_loras # noqa: E402+from _runner_common import emit_runtime_fingerprint, parse_user_loras # noqa: E402def emit_status(msg: str) -> None:@@ -130,6 +130,10 @@ def main() -> None:parser.add_argument("--user-loras", default=None)ns, passthrough = parser.parse_known_args()+ # Runtime fingerprint for the mlx_video LoRA path — stamped onto the render+ # record so output can be tied to a specific mlx_video/mlx stack.+ emit_runtime_fingerprint("mlx_video", ["mlx_video", "mlx", "mlx_metal"])+specs = parse_user_loras(ns.user_loras)if not specs:raise SystemExit(diff --git a/scripts/generate_hunyuan.py b/scripts/generate_hunyuan.pyindex bc1b6e99b2..fff757e0af 100644--- a/scripts/generate_hunyuan.py+++ b/scripts/generate_hunyuan.py@@ -24,7 +24,7 @@ import unittest.mockfrom pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parent))-from _runner_common import heartbeat, install_hf_error_handler # noqa: E402+from _runner_common import emit_runtime_fingerprint, heartbeat, install_hf_error_handler # noqa: E402def parse_args() -> argparse.Namespace:@@ -239,6 +239,10 @@ def stage_hunyuan_model_base(repo_dir, snapshot_dir):def main() -> int:cli = parse_args()+ # Runtime fingerprint at startup — recorded by PortOS so garbled output can+ # be tied to a specific torch/diffusers/mlx stack on this chip.+ emit_runtime_fingerprint("hunyuan", ["torch", "diffusers", "transformers", "mlx"])+repo_dir = Path(cli.repo_dir).expanduser().resolve()if not repo_dir.is_dir():print(f"❌ HunyuanVideo MLX repo not found at {repo_dir}", file=sys.stderr)diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.pyindex 8ee746104b..26cc157f3b 100644--- a/scripts/generate_ltx2.py+++ b/scripts/generate_ltx2.py@@ -69,7 +69,7 @@ os.environ.setdefault("LTX2_GEMMA_EVAL_EVERY", "1")# (mirrors generate_hunyuan.py). _runner_common is stdlib-only at import time, so# this is safe from the ltx-2-mlx venv (no torch pulled in).sys.path.insert(0, str(Path(__file__).resolve().parent))-from _runner_common import parse_user_loras # noqa: E402+from _runner_common import emit_runtime_fingerprint, parse_user_loras # noqa: E402def emit_status(msg: str) -> None:@@ -810,6 +810,9 @@ def maybe_strip_audio(output_path: str) -> None:def main() -> NoReturn:args = parse_args()+ # One-line runtime fingerprint at startup — captured by PortOS onto the+ # render record so garbled output can be tied to a specific ltx/mlx stack.+ emit_runtime_fingerprint("ltx2", ["ltx_pipelines_mlx", "ltx_core_mlx", "mlx", "mlx_metal"])Path(args.output).parent.mkdir(parents=True, exist_ok=True)# Parse user LoRAs once up-front (strict validation surfaces bad input# before any model load). Each run_* sets pipe._pending_loras from this.diff --git a/scripts/generate_wan22.py b/scripts/generate_wan22.pyindex 5d9ebf36a2..270960dcee 100644--- a/scripts/generate_wan22.py+++ b/scripts/generate_wan22.py@@ -26,6 +26,11 @@ import subprocessimport sysfrom pathlib import Path+# Same-dir sibling import (mirrors generate_ltx2.py). _runner_common is+# stdlib-only at import time, so this is safe from the wan2.2-mlx venv.+sys.path.insert(0, str(Path(__file__).resolve().parent))+from _runner_common import emit_runtime_fingerprint # noqa: E402+def parse_args() -> argparse.Namespace:p = argparse.ArgumentParser(description="PortOS Wan 2.2 MLX helper")@@ -47,6 +52,10 @@ def parse_args() -> argparse.Namespace:def main() -> int:args = parse_args()+ # Runtime fingerprint at startup — recorded by PortOS so output can be tied+ # to a specific wan/mlx/torch stack on this chip.+ emit_runtime_fingerprint("wan22", ["wan", "mlx", "mlx_metal", "torch"])+repo_dir = Path(args.repo_dir).expanduser().resolve()if not repo_dir.is_dir():print(f"❌ Wan 2.2 repo not found at {repo_dir}", file=sys.stderr)diff --git a/scripts/generate_win.py b/scripts/generate_win.pyindex 73b69c295b..3db7745125 100644--- a/scripts/generate_win.py+++ b/scripts/generate_win.py@@ -17,6 +17,11 @@ import numpy as npimport cv2from PIL import Image+# Same-dir sibling import (mirrors generate_ltx2.py). _runner_common is+# stdlib-only at import time, so this is safe even on a partial install.+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from _runner_common import emit_runtime_fingerprint # noqa: E402+# ---------------------------------------------------------------------------# Helpers# ---------------------------------------------------------------------------@@ -74,6 +79,13 @@ def main():'consume two keyframes; flag is accepted for forward ''compatibility with multi-keyframe pipelines.')args = p.parse_args()++ # Runtime fingerprint at startup — recorded by PortOS so output can be tied+ # to a specific torch+CUDA/diffusers stack on this GPU.+ emit_runtime_fingerprint(+ 'win', ['torch', 'diffusers', 'transformers'],+ extra={'cuda': getattr(torch.version, 'cuda', None)},+ )# The current LTX-Video 0.9.5 diffusers pipelines only accept a single# conditioning image, so --last-image is forward-compat only. Tailor the# STATUS log to the actual branch the script will take based on whetherdiff --git a/scripts/runtime_fingerprint.py b/scripts/runtime_fingerprint.pynew file mode 100644index 0000000000..6460f20b40--- /dev/null+++ b/scripts/runtime_fingerprint.py@@ -0,0 +1,37 @@+#!/usr/bin/env python3+"""Standalone runtime-fingerprint probe.++Prints a single JSON object describing the runtime environment of the venv it is+run in — the resolved package versions (ltx/mlx/torch/…) plus chip/os/python —+WITHOUT running a render. Invoked per installed bring-your-own-venv runtime by+`GET /api/video-gen/status` (server/services/videoGen/local.js+resolveRuntimeFingerprint) so the UI can show "what am I running" on demand.++The same fingerprint is emitted inline at render time by the generate_* helpers+via `_runner_common.emit_runtime_fingerprint`; this script is the no-render path+and reuses the identical `build_runtime_fingerprint` definition so the two never+drift.++Usage: python runtime_fingerprint.py <runtime_id> [distribution_name ...]+"""+from __future__ import annotations++import json+import sys+from pathlib import Path++# Same-dir sibling import (mirrors generate_ltx2.py / generate_av_lora.py).+# _runner_common is stdlib-only at import time, so this is safe from any venv.+sys.path.insert(0, str(Path(__file__).resolve().parent))+from _runner_common import build_runtime_fingerprint # noqa: E402+++def main() -> int:+ runtime_id = sys.argv[1] if len(sys.argv) > 1 else "unknown"+ packages = sys.argv[2:]+ print(json.dumps(build_runtime_fingerprint(runtime_id, packages)))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 4c02e755ea..754ed185ce 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -29,6 +29,8 @@ import {isByovRuntimeInstalled,isByovRuntimeReady,invalidateByovReadyCache,+ invalidateRuntimeFingerprintCache,+ resolveRuntimeFingerprint,loadHistory,deleteHistoryItem,setHistoryItemHidden,@@ -202,6 +204,12 @@ router.get('/status', asyncHandler(async (_req, res) => {// back-solve so it can reject out-of-budget keyframe indices before// submit instead of letting the worker 400 mid-render.fflfLtx2PixelBudget: resolveFflfLtx2PixelBudget(),+ // Runtime fingerprint — host chip/os + resolved ltx/mlx/torch versions per+ // installed BYOV runtime — so the UI can show the exact numerical stack and+ // bug reports for garbled/"mosaic" output carry the version info that makes+ // them actionable (#1325). Best-effort: a venv that fails to probe reports+ // `{ error }` and never blocks the rest of the status payload.+ runtime: await resolveRuntimeFingerprint(),});}));@@ -279,8 +287,10 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {}// The install may add/remove packages; drop any cached "ready" so the// post-install /runtime-status response reflects the new state instead of- // a stale "true" from before a deliberate cleanup.+ // a stale "true" from before a deliberate cleanup. Same for the cached+ // runtime fingerprint — a reinstall can bump ltx/mlx/torch versions.invalidateByovReadyCache(info.id);+ invalidateRuntimeFingerprintCache(info.id);const scriptPath = join(PATHS.root, 'scripts', 'setup-image-video.sh');if (!existsSync(scriptPath)) {diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 5ff04f7177..7b44dc63ef 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -50,6 +50,13 @@ vi.mock('../services/videoGen/local.js', () => ({isByovRuntimeInstalled: vi.fn(() => false),isByovRuntimeReady: vi.fn(async () => false),invalidateByovReadyCache: vi.fn(),+ invalidateRuntimeFingerprintCache: vi.fn(),+ // /status now surfaces a runtime block (host chip/os + per-runtime versions).+ // Mock returns a fixed shape so the status test can assert it's wired through.+ resolveRuntimeFingerprint: vi.fn(async () => ({+ host: { chip: 'Apple M5 Max', os: 'Darwin 25.5.0', platform: 'darwin', arch: 'arm64', node: 'v22' },+ runtimes: { ltx2: { runtime: 'ltx2', versions: { mlx: '0.22.0' }, chip: 'Apple M5 Max' } },+ })),}));// Render submissions go through the mediaJobQueue. Mock its surface so the@@ -197,6 +204,10 @@ describe('videoGen routes', () => {// clamp without hardcoding the constant. Pin presence + type.expect(typeof r.body.fflfLtx2PixelBudget).toBe('number');expect(r.body.fflfLtx2PixelBudget).toBeGreaterThan(0);+ // runtime fingerprint block — host chip/os + per-runtime resolved+ // versions so the UI (and bug reports) can show the exact stack (#1325).+ expect(r.body.runtime?.host?.chip).toBe('Apple M5 Max');+ expect(r.body.runtime?.runtimes?.ltx2?.versions?.mlx).toBe('0.22.0');});it('reports disconnected with reason + missingPackages when packages fail to import', async () => {diff --git a/server/services/videoGen/generateVideoHelpers.js b/server/services/videoGen/generateVideoHelpers.jsindex e51de9ec05..e1415e7a21 100644--- a/server/services/videoGen/generateVideoHelpers.js+++ b/server/services/videoGen/generateVideoHelpers.js@@ -32,6 +32,26 @@ export function makeVideoGenLineHandler({ job, jobId, pythonNoiseRe }) {const line = raw.trim();if (!line) return true;if (pythonNoiseRe.test(line)) return true;+ // Runtime fingerprint emitted once at child startup (RUNTIME:<json> — see+ // scripts/_runner_common.py emit_runtime_fingerprint). Stamp it onto the+ // job so finalizeGeneratedVideo can persist it on the history record, and+ // log a single self-documenting line so a render that produced garbled+ // output can be tied to a specific ltx/mlx/torch + chip + OS stack.+ if (line.startsWith('RUNTIME:')) {+ try {+ const fp = JSON.parse(line.slice('RUNTIME:'.length));+ job.runtime = fp;+ const vers = fp.versions && typeof fp.versions === 'object'+ ? Object.entries(fp.versions).map(([k, v]) => `${k} ${v}`).join(', ')+ : '';+ console.log(`🏷️ runtime [${jobId.slice(0, 8)}] ${fp.runtime || '?'}${vers ? ` | ${vers}` : ''}${fp.chip ? ` | ${fp.chip}` : ''}${fp.os ? ` | ${fp.os}` : ''}`);+ return true;+ } catch {+ // Malformed fingerprint line — fall through to raw-logging so the+ // broken payload is visible rather than silently swallowed.+ return false;+ }+ }// Heartbeat for the queue's idle watchdog (see imageGen/local.js).videoGenEvents.emit('activity', { generationId: jobId });if (line.startsWith('STATUS:')) {@@ -138,7 +158,12 @@ export async function finalizeGeneratedVideo({ job, jobId, outputPath, filename,await optimizeForStreaming(outputPath);const thumbnail = await generateThumbnail(outputPath, jobId);const history = await loadHistory();- history.unshift({ ...meta, thumbnail });+ // Persist the runtime fingerprint captured from the child's startup RUNTIME:+ // line (set on `job` by makeVideoGenLineHandler) so each history record+ // self-documents the exact ltx/mlx/torch + chip + OS stack it rendered on.+ // Absent (sentinel) when the runtime didn't emit one — e.g. the bare+ // `mlx_video.generate_av` path we don't control.+ history.unshift({ ...meta, thumbnail, ...(job.runtime ? { runtime: job.runtime } : {}) });await saveHistory(history);console.log(`✅ Video generated [${jobId.slice(0, 8)}]: ${filename}`);broadcastSse(job, { type: 'complete', result: { filename, seed: actualSeed, thumbnail, path: `/data/videos/${filename}` } });diff --git a/server/services/videoGen/generateVideoHelpers.test.js b/server/services/videoGen/generateVideoHelpers.test.jsindex f5d7de13f8..e56b92471e 100644--- a/server/services/videoGen/generateVideoHelpers.test.js+++ b/server/services/videoGen/generateVideoHelpers.test.js@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import { writeFileSync, rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-import { makeVideoGenLineHandler, isWatchdogSuccess } from './generateVideoHelpers.js';+import { makeVideoGenLineHandler, isWatchdogSuccess, finalizeGeneratedVideo } from './generateVideoHelpers.js';// broadcastSse + videoGenEvents are the two output sinks the line handler// writes to; capture both so we can assert the parse → frame mapping.@@ -88,6 +88,55 @@ describe('makeVideoGenLineHandler', () => {it('returns false for an unrecognized line (caller raw-logs it)', () => {expect(handle('🐍 some unexpected diagnostic')).toBe(false);});++ it('RUNTIME:<json> → stamps job.runtime and suppresses raw logging', () => {+ const fp = { runtime: 'ltx2', versions: { mlx: '0.22.0' }, chip: 'Apple M5 Max', os: 'macOS-15.4-arm64' };+ expect(handle(`RUNTIME:${JSON.stringify(fp)}`)).toBe(true);+ expect(job.runtime).toEqual(fp);+ // It's a one-shot metadata line, not progress/status — no SSE frame.+ expect(sse).not.toHaveBeenCalled();+ });++ it('malformed RUNTIME: line falls through to raw-logging and leaves job.runtime unset', () => {+ expect(handle('RUNTIME:{not json')).toBe(false);+ expect(job.runtime).toBeUndefined();+ });+});++describe('finalizeGeneratedVideo runtime persistence', () => {+ const baseCtx = (job) => ({+ job,+ jobId: 'job-abcdef12',+ outputPath: '/tmp/out.mp4',+ filename: 'out.mp4',+ meta: { id: 'job-abcdef12', prompt: 'hi', modelId: 'ltx2_unified' },+ actualSeed: 7,+ });++ it('persists job.runtime onto the saved history record', async () => {+ const fp = { runtime: 'ltx2', versions: { mlx: '0.22.0' }, chip: 'Apple M5 Max' };+ const job = { id: 'job-abcdef12', clients: [], runtime: fp };+ let saved = null;+ await finalizeGeneratedVideo({+ ...baseCtx(job),+ loadHistory: async () => [],+ saveHistory: async (h) => { saved = h; },+ });+ expect(saved).toHaveLength(1);+ expect(saved[0].runtime).toEqual(fp);+ });++ it('omits runtime when the child never emitted a fingerprint (absent sentinel)', async () => {+ const job = { id: 'job-abcdef12', clients: [] };+ let saved = null;+ await finalizeGeneratedVideo({+ ...baseCtx(job),+ loadHistory: async () => [],+ saveHistory: async (h) => { saved = h; },+ });+ expect(saved).toHaveLength(1);+ expect('runtime' in saved[0]).toBe(false);+ });});describe('isWatchdogSuccess', () => {diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex 4f46afc174..4bd5cfa456 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -14,7 +14,7 @@ import { execFile, spawn } from 'child_process';import { existsSync, statSync } from 'fs';import { unlink, writeFile, copyFile } from 'fs/promises';import { join, basename } from 'path';-import { homedir, tmpdir, totalmem } from 'os';+import { homedir, tmpdir, totalmem, cpus, type as osType, release as osRelease } from 'os';import { randomUUID } from 'crypto';import { promisify } from 'util';import { ensureDir, PATHS, readJSONFile, atomicWrite, UUID_RE } from '../../lib/fileUtils.js';@@ -63,6 +63,12 @@ const HUNYUAN_VENV_PYTHON = join(homedir(), '.portos', 'hunyuan-video-mlx', '.veconst HUNYUAN_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'generate_hunyuan.py');const HUNYUAN_REPO_DIR = join(homedir(), '.portos', 'hunyuan-video-mlx');+// Standalone runtime-fingerprint probe (scripts/runtime_fingerprint.py). Run in+// each installed BYOV venv by resolveRuntimeFingerprint() to surface resolved+// package versions on GET /api/video-gen/status without running a render. Shares+// its fingerprint definition with the inline render-time emit (_runner_common).+const RUNTIME_FINGERPRINT_SCRIPT = join(PATHS.root, 'scripts', 'runtime_fingerprint.py');+const execFileAsync = promisify(execFile);const IS_WIN = process.platform === 'win32';@@ -118,6 +124,9 @@ export const BYOV_RUNTIME_INFO = Object.freeze({// `hyvideo` isn't pip-installed — mirror the runner's sys.path prepend so// the probe walks the same transitive import chain (loguru, diffusers, …).importProbe: `import sys; sys.path.insert(0, ${JSON.stringify(HUNYUAN_REPO_DIR)}); import hyvideo.inference`,+ // Distributions the /status runtime-fingerprint probe resolves versions for+ // (must match scripts/generate_hunyuan.py's emit_runtime_fingerprint call).+ fingerprintPackages: ['torch', 'diffusers', 'transformers', 'mlx'],},wan22: {id: 'wan22',@@ -130,6 +139,8 @@ export const BYOV_RUNTIME_INFO = Object.freeze({// upstream's pyproject.toml (e.g. einops, imported by wan/modules/vae2_1.py)// fail the probe instead of slipping past a flat torch/transformers check.importProbe: 'import wan',+ // Mirror scripts/generate_wan22.py's emit_runtime_fingerprint package list.+ fingerprintPackages: ['wan', 'mlx', 'mlx_metal', 'torch'],},ltx2: {id: 'ltx2',@@ -142,6 +153,8 @@ export const BYOV_RUNTIME_INFO = Object.freeze({// `uv sync` (`import ltx_pipelines_mlx` is the canonical health signal// for this venv).importProbe: 'import ltx_pipelines_mlx',+ // Mirror scripts/generate_ltx2.py's emit_runtime_fingerprint package list.+ fingerprintPackages: ['ltx_pipelines_mlx', 'ltx_core_mlx', 'mlx', 'mlx_metal'],},});@@ -197,6 +210,70 @@ export function assertByovRuntimeInstalled(runtimeId) {);}+// Cache successful runtime fingerprints per BYOV runtime for the life of the+// process. Package versions only change on a reinstall, so a hit is stable;+// errors (timeout / spawn-fail / unparseable) are NOT cached so a freshly+// finished install reflects on the next /status. invalidate on (re)install.+const fingerprintCache = new Map();+export function invalidateRuntimeFingerprintCache(runtimeId) {+ if (runtimeId) fingerprintCache.delete(runtimeId); else fingerprintCache.clear();+}++// Run the standalone probe in one installed BYOV venv → its fingerprint object+// ({ runtime, versions, chip, os, python }) or { error } on any failure.+// Best-effort and bounded (15s SIGKILL) so a wedged venv can't hang /status.+async function probeRuntimeFingerprint(runtimeId) {+ const info = BYOV_RUNTIME_INFO[runtimeId];+ if (!info || !existsSync(info.venvPython)) return null;+ if (fingerprintCache.has(runtimeId)) return fingerprintCache.get(runtimeId);+ const result = await new Promise((resolve) => {+ let out = '';+ const child = spawn(+ info.venvPython,+ [RUNTIME_FINGERPRINT_SCRIPT, runtimeId, ...(info.fingerprintPackages || [])],+ { env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'ignore'] },+ );+ const timer = setTimeout(() => { if (!child.killed) child.kill('SIGKILL'); resolve({ error: 'timeout' }); }, 15000);+ child.stdout.on('data', (c) => { out += c.toString(); });+ child.on('close', (code) => {+ clearTimeout(timer);+ if (code !== 0) return resolve({ error: `exit ${code}` });+ // The probe prints exactly one JSON line; take the last non-empty line+ // defensively in case a venv import prints a stray warning to stdout.+ const lastLine = out.trim().split('\n').filter(Boolean).pop() || '';+ try { resolve(JSON.parse(lastLine)); } catch { resolve({ error: 'unparseable' }); }+ });+ child.on('error', () => { clearTimeout(timer); resolve({ error: 'spawn-failed' }); });+ });+ if (result && !result.error) fingerprintCache.set(runtimeId, result);+ return result;+}++// Host runtime fingerprint computed in Node — cheap, always present (no python).+// chip/os/arch are useful even before any BYOV runtime is installed.+export function hostRuntimeFingerprint() {+ return {+ chip: cpus()?.[0]?.model || 'unknown',+ os: `${osType()} ${osRelease()}`,+ platform: process.platform,+ arch: process.arch,+ node: process.version,+ };+}++// Full runtime block for GET /api/video-gen/status: the Node-side host info plus+// per-installed-BYOV-runtime resolved package versions (probed in parallel,+// cached, best-effort). Surfaces "what am I running" so a garbled-output bug+// report carries the exact numerical stack without running a render (#1325).+export async function resolveRuntimeFingerprint() {+ const ids = Object.keys(BYOV_RUNTIME_INFO).filter(isByovRuntimeInstalled);+ const entries = await Promise.all(ids.map(async (id) => [id, await probeRuntimeFingerprint(id)]));+ return {+ host: hostRuntimeFingerprint(),+ runtimes: Object.fromEntries(entries.filter(([, v]) => v)),+ };+}+export const listVideoModels = () => getVideoModels();export const defaultVideoModelId = () => getDefaultVideoModelId();diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex b3aae6ed52..a1854ddd60 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -1067,3 +1067,39 @@ describe('generateVideo — close-handler resilience (issue #1334)', () => {vi.doUnmock('./generateVideoHelpers.js');});});++describe('runtime fingerprint (/status)', () => {+ it('hostRuntimeFingerprint reports chip/os/platform/arch/node', async () => {+ const { hostRuntimeFingerprint } = await import('./local.js');+ const fp = hostRuntimeFingerprint();+ expect(typeof fp.chip).toBe('string');+ expect(fp.chip.length).toBeGreaterThan(0);+ expect(typeof fp.os).toBe('string');+ expect(fp.platform).toBe(process.platform);+ expect(fp.arch).toBe(process.arch);+ expect(fp.node).toBe(process.version);+ });++ it('resolveRuntimeFingerprint returns a host block + a per-runtime map', async () => {+ // `runtimes` only contains BYOV runtimes whose venv is installed; whether+ // any are present depends on the machine (CI: none; a dev box may have+ // some). Assert the shape — host always present, every runtime entry is+ // either a resolved fingerprint or a best-effort `{ error }` — rather than+ // a specific machine's install set.+ const { resolveRuntimeFingerprint } = await import('./local.js');+ const block = await resolveRuntimeFingerprint();+ expect(block.host).toBeDefined();+ expect(typeof block.host.chip).toBe('string');+ expect(block.runtimes && typeof block.runtimes === 'object').toBe(true);+ for (const [id, fp] of Object.entries(block.runtimes)) {+ expect(typeof id).toBe('string');+ expect(fp.error !== undefined || typeof fp.versions === 'object').toBe(true);+ }+ });++ it('invalidateRuntimeFingerprintCache is callable for a single id and for all', async () => {+ const { invalidateRuntimeFingerprintCache } = await import('./local.js');+ expect(() => invalidateRuntimeFingerprintCache('ltx2')).not.toThrow();+ expect(() => invalidateRuntimeFingerprintCache()).not.toThrow();+ });+});