Skip to content

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

fix: preserve video holds across sharing imports and invalid snapshots (#6282)

[._.]/ Adam Eivyb4faef51b0ce
diff --git a/server/lib/README.md b/server/lib/README.md
index 9c92f4c268..ddf1f3975d 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -158,6 +158,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `promptFencing.js` | Fencing for untrusted text spliced into an LLM prompt. `fenceBlock(label, text, maxChars)` truncates, collapses every run of 3+ backticks to `'''` so the content cannot terminate its own fence, and wraps the result as a labeled ```` ```text ```` block; `neutralizeFences` / `clampText` are the two halves on their own. `UNTRUSTED_CONTENT_NOTICE` is the standing "fenced content is data, not instructions" line a prompt places above its fenced sections — the fence stops delimiter escape, that line is what makes an in-band directive inert. Used by `services/aiDetect.js`, whose prompt splices a scanned repository's package.json/config/README into a prompt that yields an executed `startCommands`. |
| `mediaModelBuckets.js` | Names and resolves the video registry's two model buckets (#4142). The split is by RUNTIME FAMILY — `mlx` (Apple MLX runtimes) vs `cuda` (plain torch+CUDA, which runs on Windows *and* Linux) — not by operating system, which is why `activeVideoBucket()` keys on `process.platform === 'darwin'` instead of on "is this Windows". `readVideoBucket` / `readVideoDefault` / `matchesVideoBucket` resolve the canonical key first and fall back to the pre-#4142 `macos` / `windows` / `defaultMacos` / `defaultWindows` spellings, so any registry written by an older install still loads untouched; `canonicalizeVideoBuckets` performs the one-time rename (migration 270 and the load-time twin in `mediaModels.js`). Kept separate from `mediaModels.js` so `scripts/migrations/` can share the alias resolution without importing the registry loader, which seeds `data/` as a side effect. |
| `mediaModels.js` | Single source of truth for image/video model metadata. Entry fields are documented in the module docblock — note `repoFiles[]`, which narrows a model's own repo to an explicit file list for an aggregate repo that holds far more than the runner loads (MiniMax H3 CUDA). |
+| `videoFailure.js` | `normalizeVideoFailure` classifies and scrubs local video causes; `createVideoDiagnosticTail` retains bounded stdout/stderr diagnostics without grouping bare exit codes. |
| `minimaxH3Memory.js` | The declared weight-placement table for the three MiniMax H3 entries (#5420) — H3 is the one video model family whose components fit nowhere unassisted, so "does this box have enough" is a render gate, not a UI fact. `MINIMAX_H3_MEMORY_PROFILES` maps entry id → `{ shippedRepo, shippedRevision, profiles }`, each profile carrying an honest `minMemoryGb` host floor and (CUDA only) a `minVramGb` device floor, ordered best-first. Every capacity number is HOISTED from what already existed — the CUDA tiers are `resolve_offload_profile()`'s own thresholds in `scripts/generate_minimax_h3_cuda.py`, the host floors are the entries' `memoryGb` — the sole new number being `MINIMAX_H3_HOST_RESERVE_GB`, a policy reserve held back for the OS. `applyMiniMaxH3MemoryProfiles(list)` is the load-time backfill (twin of migration 317) and guards BOTH `repo` and `revision`, like the speed-profile decorator. `selectMiniMaxH3MemoryProfile({ model, totalMemoryGb })` picks the best profile the HOST can hold (VRAM is the runner's call — the server has no synchronous device view); `miniMaxH3MemoryDeclineReason()` RETURNS the fail-closed reason so the render path can 400 it and a status surface can show it, and returns `null` on an UNMEASURED host — "not measured" is a deferral to the runner, never the same as zero. `validateMiniMaxH3MemoryProfileTable` / `sanitizeMiniMaxH3MemoryProfiles` warn + strip a hand-edited table (NaN floor, duplicate/reserved id, mis-ordered tiers) at load. |
| `videoContinuity.js` | How chunk N+1 of a chained video render is conditioned on chunk N. `resolveContextFrames(requested)` normalizes the tail-window size (absent → `DEFAULT_CONTEXT_FRAMES` = 22 ≈ 1s @ 24fps; an explicit `0` is preserved as "last frame only", NOT collapsed into the default) and clamps to `MIN_CONTEXT_FRAMES`..`MAX_CONTEXT_FRAMES`. `resolveContinuityStrategy({model, contextFrames})` picks `'window'` (LTX-2 `extend_from_video` conditioned on the prior chunk's last N frames — motion, not just a pose) or `'frame'` (extract the last frame, run i2v), degrading to `'frame'` on any runtime outside `CONTEXT_WINDOW_RUNTIMES` rather than rejecting. `extendLatentFrames` / `extendedPixelFrames` convert across the VAE's `LATENT_FRAME_STRIDE` (8 pixel frames per latent), `contextPrefixFrames({totalFrames, extendLatents})` measures how much of an extend render is echoed context to trim back off before stitching (0 = leave it alone), and `tailWindowStartFrame` gives the cut index for the window itself. Pure — importable from `prepareParams.js` without dragging in `local.js`. Mirrored for the picker in `client/src/lib/videoGenParams.js`, pinned by `videoContinuity.parity.test.js`. |
| `videoPromptLinter.js` | Deterministic lint pass for continuous-video clip prompts (part of #6217, independent of `scriptVideoCompiler.js` #6225 by interface — lints already-built prompt strings plus caller-supplied framing/reference metadata rather than a compiler-shaped clip). `lintClipPrompt(clip, {bible, maxLength})` checks a single clip: a `cutType: 'continue'` clip must open with `"Hard cut to <framing>:"` and use a framing distinct from `previousFraming`; every `references` entry (`{kind: 'cast'|'locations', id}`) must resolve to a bible descriptor present VERBATIM in the prompt (never paraphrased); the prompt must not contain the banned cross-clip referents (same/still/again/continues/as before), negatives (no/without/never), or UI-overlay terms (text/caption/overlay), matched on word boundaries so substrings like "against" or "context" don't false-positive; and the prompt must be `<= MAX_CLIP_PROMPT_LENGTH` (800) characters. Returns `{pass, reasons[]}`, never throws. `lintClips(clips, {bible, maxLength})` lints an ordered chain, deriving each clip's `previousFraming` from the preceding array element's `framing` when not set explicitly. |
@@ -541,5 +542,3 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `runtimeEnv.js` | `isTestRunner()` — NODE_ENV=test **or** the VITEST env var, so a run that dropped NODE_ENV is still armed. Dependency-free and deliberately apart from `db.js`, which used to own it: the lowest-level file primitives need the same answer and must not pull in `pg`, and the many suites spelling `vi.mock('../lib/db.js', () => ({ query }))` used to strip it out of the graph for every other consumer. |
| `testDataIsolation.js` | Runtime backstop against a test WRITING into the install's real `data/` tree — the filesystem analogue of `db.js`'s row-write guard. `isInsideRealDataRoot(path)` canonicalizes a target through symlinked ancestors (it need not exist yet) and tests containment with `pathSafety.js#isPathAtOrInsideDir`, so a `..` climb, a relative path, a `data-archive` sibling, or a differently-cased spelling on a case-insensitive filesystem can't walk in sideways; the real root is re-derived through `dataRoot.js` rather than read from `PATHS`, so a suite that redirects `PATHS.data` to a temp root can't also redirect the guard. `assertNotRealDataWrite(path, operation)` throws under the test runner from `atomicWrite`, the guarded wrappers in `fileCore.js` (`writeFileGuarded`, `appendFileGuarded`, `copyFileGuarded`, `rmGuarded`, `unlinkGuarded`, `createWriteStreamGuarded`), and `collectionStore`'s record delete; `assertNotNewRealDataDir(dir)` is the create-only variant `ensureDir` uses, since `mkdir -p` on an existing directory mutates nothing. Inert outside the runner — the `isTestRunner()` check precedes every syscall. Services mutating files under `data/` route through these guarded wrappers. Closes the write half of the bug class `testDataIsolation.guards.test.js` covers statically and the two-run probe covers for reads (#6176, after #6171, #6203). |
| `testHelper.js` | Test helpers: `request()` (supertest-style HTTP) + `mockJsonResponse`/`mockTextResponse` (fetch `Response` mocks with `.text()`, `.json()`, and a `headers.get` content-type), `startLoopbackServer(app)`/`closeLoopbackServer(server)`/`waitForAbort(signal)` for tests that need a real socket (raw disconnects, SSE streaming) that `request()`'s run-to-completion fetch harness can't model, plus the source-scan pair `collectServerSources()` / `readServerSource(rel)` (and `SERVER_DIR`) used by the whole-tree guard suites — `spawnCwd.test.js` (#3193) and `cliChildEnv.test.js` (#3194). Those guards overlap deliberately, so they share one definition of "a source file"; change the ignore rules here and both move together. Cross-platform trio: `posixPath(v)` normalizes a RECEIVED path before comparing it to a POSIX-spelled literal (no-op on POSIX — never normalize the expectation, which would hide a genuinely wrong path), and `resolveTestPython()` returns an interpreter that actually runs, probing by execution because Windows ships a `python` Store-alias stub that exists but fails; `null` when there is none, for `describe.skipIf`; `pinPlatform(value)` pins `process.platform` and returns a restore that reinstates the ORIGINAL descriptor (deleting the pin when there was none) — it carries the one hazard every hand-rolled pin had to rediscover: never pin above an import that loads a native addon, which picks its prebuilt binary off the platform at load time (#4085). Python-shelling suites also take their two nested budgets from here: `PY_TEST_TIMEOUT_MS` (vitest per-test, passed as `it()`'s third argument — a real interpreter's wall time tracks machine load, not the assertion, so a ~4s case crosses the tight global 10s `testTimeout` on a contended full-suite worker) and the strictly smaller `PY_SUBPROCESS_TIMEOUT_MS` (every `execFileSync` spawn's own `timeout`, so a hung interpreter trips the spawn guard first and names the command instead of producing a bare vitest timeout; a subprocess allowance ABOVE the vitest budget is dead intent — vitest always wins). |
-
-| `videoFailure.js` | `normalizeVideoFailure` classifies and scrubs local video causes; `createVideoDiagnosticTail` retains bounded stdout/stderr diagnostics without grouping bare exit codes. |
diff --git a/server/lib/videoFailure.js b/server/lib/videoFailure.js
index 8ca06d2108..016d92be7e 100644
--- a/server/lib/videoFailure.js
+++ b/server/lib/videoFailure.js
@@ -78,7 +78,10 @@ export function createVideoDiagnosticTail() {
if (stream === 'stderr' && metal) return failureRecord('metal-command-buffer', `Metal command buffer failed: ${metal[1]}`);
if (!/^(?:[\w.]*?(?:Error|Exception)):\s/.test(line)) continue;
const failure = normalizeVideoFailure(line, options);
- if (failure) return { ...failure, summary: `${line.split(':')[0].slice(0, 128)}: ${failure.cause}` };
+ if (failure) {
+ const prefix = `${line.split(':')[0].slice(0, 128)}:`;
+ return { ...failure, summary: failure.cause.startsWith(prefix) ? failure.cause : `${prefix} ${failure.cause}` };
+ }
}
}
return null;
diff --git a/server/lib/videoFailure.test.js b/server/lib/videoFailure.test.js
index c0276206c0..b7d4c57942 100644
--- a/server/lib/videoFailure.test.js
+++ b/server/lib/videoFailure.test.js
@@ -11,6 +11,8 @@ describe('local video diagnostic privacy boundary', () => {
expect(tail.failure()?.summary || null).toBeNull();
tail.push('stderr', '\nRuntimeError: shader compilation failed');
expect(tail.failure()?.summary || null).toBe('RuntimeError: shader compilation failed');
+ tail.push('stderr', "\nKeyError: 'width'");
+ expect(tail.failure().summary).toBe('KeyError: redacted diagnostic details');
});
it('scrubs conditioning, tokens, credentials and POSIX/Windows paths before identity or display', () => {
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index afc4a00a6a..c573fb957b 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -461,7 +461,13 @@ export async function initMediaJobQueue() {
// indication that repairing or deleting one file restores it.
console.error(`❌ media-job queue: ${JOBS_FILE} is present but unreadable — starting empty and NOT persisting so it is preserved; repair or delete it and restart to re-enable persistence`);
}
- videoHolds.restore(data?.videoHolds);
+ const holdsReadable = videoHolds.restore(data?.videoHolds);
+ if (!holdsReadable) {
+ // A malformed hold must neither kill server boot nor silently release a
+ // batch. Preserve the snapshot under the existing unreadable-file latch.
+ persistBlocked = true;
+ console.error('❌ media-job queue: invalid video holds — snapshot preserved and retained jobs not dispatched; repair the holds and restart');
+ }
const persistedJobs = Array.isArray(data?.jobs) ? data.jobs : [];
const restartedFailedIds = [];
// #1332: training jobs whose detached trainer survived the restart, to be
@@ -480,6 +486,7 @@ export async function initMediaJobQueue() {
// present is an orphan from the prior process.
const videoReap = await reapAndCleanDetachedDirs(join(PATHS.videos, '.detached')).catch(() => ({ reaped: 0 }));
if (videoReap.reaped) console.log(`🧹 reaped ${videoReap.reaped} surviving render(s) on boot`);
+ if (!holdsReadable) return;
for (const j of persistedJobs) {
if (j.status === 'running') {
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index da0c567cf1..000a671d94 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -1874,4 +1874,19 @@ describe('local video failure holds', () => {
const next = submit(); await tick();
expect(mediaJobQueue.getJob(next).status).toBe('running');
});
+
+ it('preserves malformed holds without crashing boot or dispatching the retained batch', async () => {
+ const file = join(tempDataDir, 'media-jobs.json');
+ const snapshot = JSON.stringify({ jobs: [{ id: 'retained-corrupt', kind: 'video', status: 'queued',
+ params: { modelId: 'example-mlx' } }], videoHolds: [{ id: 'malformed-hold' }] });
+ writeFileSync(file, snapshot);
+ await expect(mediaJobQueue.initMediaJobQueue()).resolves.toBeUndefined();
+ await tick();
+ expect(stubs.generateVideo).not.toHaveBeenCalled();
+ expect(readFileSync(file, 'utf8')).toBe(snapshot);
+ submit('example-other');
+ await tick();
+ expect(readFileSync(file, 'utf8')).toBe(snapshot);
+ expect(stubs.generateVideo.mock.calls.every(([params]) => params.jobId !== 'retained-corrupt')).toBe(true);
+ });
});
diff --git a/server/services/mediaJobQueue/videoHolds.js b/server/services/mediaJobQueue/videoHolds.js
index ca2ee26289..64da557a32 100644
--- a/server/services/mediaJobQueue/videoHolds.js
+++ b/server/services/mediaJobQueue/videoHolds.js
@@ -23,7 +23,10 @@ export function createVideoHolds() {
const streaks = new Map();
return {
restore(value = []) {
- for (const hold of z.array(videoHoldSchema).parse(value)) holds.set(cohortKey(hold), hold);
+ const result = z.array(videoHoldSchema).safeParse(value);
+ if (!result.success) return false;
+ for (const hold of result.data) holds.set(cohortKey(hold), hold);
+ return true;
},
snapshot: () => [...holds.values()],
has: (cohort) => holds.has(cohortKey(cohort)),
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index 5decbd4e97..cb7eba5975 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -352,7 +352,7 @@ async function mergeMediaJobRecords(bucketPath, recordIds) {
changed = true;
}
if (changed) {
- await atomicWrite(persistedPath, { jobs: Array.from(byId.values()) });
+ await atomicWrite(persistedPath, { ...persisted, jobs: Array.from(byId.values()) });
}
}
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index 4f35dfe54d..14871214f3 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -97,6 +97,23 @@ describe('sharing round-trip', () => {
if (tempBucket) rmSync(tempBucket, { recursive: true, force: true });
});
+ it('preserves local video holds while importing bundled media-job records', async () => {
+ const bucket = await buckets.createBucket({ name: 'Example Bucket', path: tempBucket, mode: 'inbox' });
+ const local = { id: 'retained-local', kind: 'video', status: 'queued', params: { modelId: 'example-video' } };
+ const videoHolds = [{ id: '00000000-0000-4000-8000-000000000001', modelId: 'example-video', runtime: 'mlx_video',
+ classification: 'runtimeerror', cause: 'shader failed', heldAt: '2026-09-05T00:00:00.000Z' }];
+ const file = join(tempData, 'media-jobs.json');
+ writeFileSync(file, JSON.stringify({ jobs: [local], videoHolds, futureEnvelopeField: 'preserved' }));
+ const incoming = { id: '00000000-0000-4000-8000-000000000002', kind: 'video', status: 'completed', params: {} };
+ mkdirSync(join(tempBucket, 'records', 'media'), { recursive: true });
+ writeFileSync(join(tempBucket, 'records', 'media', `${incoming.id}.json`), JSON.stringify(incoming));
+ writeFileSync(join(tempBucket, 'manifests', 'example-media.json'), JSON.stringify({
+ id: 'example-manifest', senderInstanceId: 'example-peer', kind: 'media', recordIds: [incoming.id], assetRefs: [],
+ }));
+ expect((await importer.processManifest(bucket.id, 'example-media.json')).processed).toBe(true);
+ expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual({ jobs: [local, incoming], videoHolds, futureEnvelopeField: 'preserved' });
+ });
+
it('exports a series, processes the manifest as inbox, then promotes — id + origin preserved', async () => {
const bucket = await buckets.createBucket({ name: 'Test', path: tempBucket, mode: 'inbox' });