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(peer-sync): add videoHistory snapshot category + receiver-side video thumbnail gen
Adam Eivy77f8d8182da7
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex 572d59135f..2bc4bd6430 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -424,7 +424,8 @@ const SYNC_CATEGORY_META = [{ key: 'meatspace', label: 'Meatspace', icon: HeartPulse, description: 'Daily logs, blood tests, body metrics, eyes' },{ key: 'universe', label: 'Universe', icon: Sparkles, description: 'Universe Builder canon: characters, places, objects' },{ key: 'pipeline', label: 'Pipeline', icon: Film, description: 'Series + issues record state (no image/video blobs)' },- { key: 'mediaCollections', label: 'Media Collections', icon: Images, description: 'Per-universe/series image + video buckets' }+ { key: 'mediaCollections', label: 'Media Collections', icon: Images, description: 'Per-universe/series image + video buckets' },+ { key: 'videoHistory', label: 'Video History', icon: Film, description: 'Generated-video metadata rows (so synced collection videos render)' }];// Snapshot categories (excludes delta-based brain/memory)diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex c66f5eb84a..e016601e57 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -36,6 +36,11 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({pipelineIssues: 1,pipelineSeries: 1,mediaCollections: 1,+ // v1 = the flat `data/video-history.json` array of generation rows synced+ // by the `videoHistory` sync category (rows ride the snapshot loop so a+ // synced collection's video items aren't filtered out as "missing" on the+ // receiver). The shape has been stable since video gen shipped.+ videoHistory: 1,});/**diff --git a/server/routes/dataSync.js b/server/routes/dataSync.jsindex 1d369b7f3b..0f2e6b725c 100644--- a/server/routes/dataSync.js+++ b/server/routes/dataSync.js@@ -13,7 +13,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';const router = Router();-const categoryParam = z.enum(['goals', 'character', 'digitalTwin', 'meatspace', 'universe', 'pipeline', 'mediaCollections']);+const categoryParam = z.enum(['goals', 'character', 'digitalTwin', 'meatspace', 'universe', 'pipeline', 'mediaCollections', 'videoHistory']);// Tombstone GC manual trigger. Declared BEFORE `/:category/*` so the literal// "tombstones" segment wins Express's first-match lookup (categoryParam'sdiff --git a/server/routes/instances.js b/server/routes/instances.jsindex 848f716599..a852b33aed 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -53,7 +53,8 @@ const syncCategoriesSchema = z.object({// here — otherwise PATCH/PUT updates from the Instances UI silently// no-op for the missing category. Same regression class as the// universe + pipeline omission tracked in .changelog/NEXT.md.- mediaCollections: z.boolean().optional()+ mediaCollections: z.boolean().optional(),+ videoHistory: z.boolean().optional()}).optional();const updatePeerSchema = z.object({diff --git a/server/services/dataSync.js b/server/services/dataSync.jsindex af14b8573d..0e09079474 100644--- a/server/services/dataSync.js+++ b/server/services/dataSync.js@@ -41,6 +41,7 @@ const PIPELINE_ISSUES_DIR = join(PATHS.data, 'pipeline-issues');// fingerprint walker descends into the dir so per-record edits invalidate.const UNIVERSE_BUILDER_DIR = join(PATHS.data, 'universes');const MEDIA_COLLECTIONS_FILE = join(PATHS.data, 'media-collections.json');+const VIDEO_HISTORY_FILE = join(PATHS.data, 'video-history.json');const MEATSPACE_FILES = {'daily-log.json': { arrayKey: 'entries', idField: 'date' },@@ -525,6 +526,88 @@ async function applyMediaCollectionsRemote(remoteData) {return result;}+// --- Category: Video History ---++// `data/video-history.json` is a FLAT array of video-generation rows+// (`{ id, prompt, filename, createdAt, thumbnail, ... }`). MediaCollectionDetail's+// `hydrate()` looks every `{ kind:'video', ref }` collection item up in a+// `videosById` map built from this list — so a synced collection's video items+// are silently filtered out as "missing" on the receiver until the matching row+// arrives. This category rides the same 60s snapshot loop as mediaCollections+// so the rows propagate alongside the collection JSON.+//+// **No exclude-set / `{forPeerId}` filtering applies.** Unlike mediaCollections+// (whose getter drops rows linked to an ephemeral universe/series), video rows+// carry no ephemeral linkage — a video is identified by its bare id, with no+// parent record to opt out of sync. The whole flat list is union-merged.+// (The `.mp4` bytes themselves still flow via the per-record asset-pull worker+// in peerSync.js — this category carries only the JSON metadata row.)++// Read/write the flat history array directly (matching the goals/character+// categories' `readJSONFile`+`atomicWrite` pattern) rather than importing+// videoGen/local.js — that module drags in ffmpeg/spawn machinery we don't+// need on the sync read path, and the on-disk shape is a plain array.+async function getVideoHistorySnapshot() {+ const raw = await readJSONFile(VIDEO_HISTORY_FILE, []);+ const rows = Array.isArray(raw) ? raw : [];+ // Canonicalize ordering for the wire so two peers holding identical sets+ // produce identical checksums regardless of insertion (newest-first) order.+ // Mirrors getMediaCollectionsSnapshot's sort-by-id rationale. Rows without a+ // string id sort last (and won't merge — see applyVideoHistoryRemote's guard).+ const data = {+ videos: [...rows].sort((a, b) =>+ String(a?.id ?? '').localeCompare(String(b?.id ?? ''))),+ };+ return { data, checksum: computeChecksum(data) };+}++async function applyVideoHistoryRemote(remoteData) {+ if (!remoteData) return { applied: false, count: 0 };+ const incoming = Array.isArray(remoteData.videos) ? remoteData.videos : [];+ if (incoming.length === 0) return { applied: false, count: 0 };++ const localRaw = await readJSONFile(VIDEO_HISTORY_FILE, []);+ const local = Array.isArray(localRaw) ? localRaw : [];++ // Union by `id`, LWW on `createdAt` when both sides know the same row.+ // Video-history rows are append-mostly and immutable once written, so+ // `createdAt` is a sufficient (and the only) freshness signal — there's no+ // `updatedAt`. A row with no string id can't be keyed and is skipped (a+ // hand-edited or corrupt entry shouldn't clobber a real row at key+ // `undefined`).+ const hasId = (r) => typeof r?.id === 'string' && r.id;+ const keyed = local.filter(hasId);+ const before = new Map(keyed.map((r) => [r.id, r]));+ const { merged, changed } = mergeArraysByKey(+ keyed,+ incoming.filter(hasId),+ 'id',+ 'createdAt',+ );+ if (!changed) return { applied: false, count: 0 };++ // `count` reports rows actually added/updated by this merge (not total+ // post-merge size — that would over-report when callers sum across+ // categories or compare cycle deltas). Matches the pipeline category's+ // `count` contract.+ let changedCount = 0;+ for (const row of merged) {+ const prev = before.get(row.id);+ if (!prev || prev !== row) changedCount++;+ }++ // Preserve any local rows that lacked an id (the merge dropped them from its+ // keyed map) — don't let a sync silently delete un-keyable local history.+ const idless = local.filter((r) => !hasId(r));+ // Newest-first to match how generateVideo unshifts new rows + how the+ // Media History grid expects them.+ const next = [...merged, ...idless].sort((a, b) =>+ String(b?.createdAt ?? '').localeCompare(String(a?.createdAt ?? '')));+ await atomicWrite(VIDEO_HISTORY_FILE, next);+ console.log(`🔄 VideoHistory sync: merged ${changedCount} video row(s)`);+ return { applied: true, count: changedCount };+}+// --- Public API ---// Files each category reads, used to keep the in-process checksum cache@@ -549,6 +632,9 @@ const CHECKSUM_PATHS = {// must re-checksum the collections snapshot even though// media-collections.json itself didn't move. Same goes for un-ephemeral.mediaCollections: [MEDIA_COLLECTIONS_FILE, UNIVERSE_BUILDER_DIR, PIPELINE_SERIES_DIR],+ // videoHistory is a flat history file with no parent-record dependency —+ // its checksum invalidates only when video-history.json itself moves.+ videoHistory: [VIDEO_HISTORY_FILE],};const CATEGORIES = {@@ -558,7 +644,8 @@ const CATEGORIES = {meatspace: { getSnapshot: getMeatspaceSnapshot, applyRemote: applyMeatspaceRemote },universe: { getSnapshot: getUniverseSnapshot, applyRemote: applyUniverseRemote },pipeline: { getSnapshot: getPipelineSnapshot, applyRemote: applyPipelineRemote },- mediaCollections: { getSnapshot: getMediaCollectionsSnapshot, applyRemote: applyMediaCollectionsRemote }+ mediaCollections: { getSnapshot: getMediaCollectionsSnapshot, applyRemote: applyMediaCollectionsRemote },+ videoHistory: { getSnapshot: getVideoHistorySnapshot, applyRemote: applyVideoHistoryRemote }};// Per-category `{ fingerprints, checksum }` cache. The orchestrator hitsdiff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex cf1632ff74..70a5835adf 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -27,6 +27,7 @@ const SERIES_DIR = join(tempRoot, 'pipeline-series');const ISSUES_DIR = join(tempRoot, 'pipeline-issues');const UNIVERSES_DIR = join(tempRoot, 'universes');const MEDIA_COLLECTIONS_PATH = join(tempRoot, 'media-collections.json');+const VIDEO_HISTORY_PATH = join(tempRoot, 'video-history.json');function writeJSON(path, obj) {mkdirSync(tempRoot, { recursive: true });@@ -513,3 +514,104 @@ describe('dataSync — mediaCollections category', () => {expect(b.checksum).toBe(a.checksum);});});++describe('dataSync — videoHistory category', () => {+ const row = (id, overrides = {}) => ({+ id,+ prompt: `prompt ${id}`,+ filename: `${id}.mp4`,+ thumbnail: `${id}.jpg`,+ createdAt: '2026-05-22T00:00:00Z',+ ...overrides,+ });++ it('is registered alongside the other categories', () => {+ expect(dataSync.getSupportedCategories()).toContain('videoHistory');+ });++ it('snapshot returns the videos array under a stable key', async () => {+ writeJSON(VIDEO_HISTORY_PATH, [row('v1'), row('v2')]);+ const snap = await dataSync.getSnapshot('videoHistory');+ expect(snap.data.videos).toHaveLength(2);+ expect(snap.data.videos.map((v) => v.id).sort()).toEqual(['v1', 'v2']);+ expect(snap.checksum).toBeTruthy();+ });++ it('snapshot handles a missing file gracefully', async () => {+ const snap = await dataSync.getSnapshot('videoHistory');+ expect(snap.data.videos).toEqual([]);+ expect(snap.checksum).toBeTruthy();+ });++ it('snapshot checksum is order-insensitive (rows sorted by id on the wire)', async () => {+ writeJSON(VIDEO_HISTORY_PATH, [row('v-b'), row('v-a')]);+ const a = await dataSync.getSnapshot('videoHistory');+ await new Promise((r) => setTimeout(r, 5)); // ensure mtime changes+ writeJSON(VIDEO_HISTORY_PATH, [row('v-a'), row('v-b')]);+ const b = await dataSync.getSnapshot('videoHistory');+ expect(b.checksum).toBe(a.checksum);+ });++ it('applyRemote inserts new rows (union by id)', async () => {+ writeJSON(VIDEO_HISTORY_PATH, [row('v1')]);+ const result = await dataSync.applyRemote('videoHistory', {+ videos: [row('v2')],+ });+ expect(result.applied).toBe(true);+ expect(result.count).toBe(1);+ const persisted = readJSON(VIDEO_HISTORY_PATH);+ expect(persisted.map((v) => v.id).sort()).toEqual(['v1', 'v2']);+ });++ it('applyRemote keeps local rows the remote does not carry (no data loss)', async () => {+ writeJSON(VIDEO_HISTORY_PATH, [row('local-only'), row('shared')]);+ await dataSync.applyRemote('videoHistory', {+ videos: [row('shared'), row('remote-only')],+ });+ const persisted = readJSON(VIDEO_HISTORY_PATH);+ expect(persisted.map((v) => v.id).sort()).toEqual(['local-only', 'remote-only', 'shared']);+ });++ it('applyRemote LWW: newer remote createdAt wins for the same id', async () => {+ writeJSON(VIDEO_HISTORY_PATH, [row('v1', { createdAt: '2026-05-22T00:00:00Z', prompt: 'old' })]);+ await dataSync.applyRemote('videoHistory', {+ videos: [row('v1', { createdAt: '2026-05-22T05:00:00Z', prompt: 'new' })],+ });+ const persisted = readJSON(VIDEO_HISTORY_PATH);+ expect(persisted).toHaveLength(1);+ expect(persisted[0].prompt).toBe('new');+ });++ it('applyRemote is a no-op when nothing is newer or new', async () => {+ writeJSON(VIDEO_HISTORY_PATH, [row('v1')]);+ const result = await dataSync.applyRemote('videoHistory', { videos: [row('v1')] });+ expect(result.applied).toBe(false);+ expect(result.count).toBe(0);+ });++ it('applyRemote skips rows without a string id (cannot clobber real rows)', async () => {+ writeJSON(VIDEO_HISTORY_PATH, [row('v1')]);+ const result = await dataSync.applyRemote('videoHistory', {+ videos: [{ prompt: 'no id', filename: 'x.mp4', createdAt: '2026-05-22T09:00:00Z' }],+ });+ expect(result.applied).toBe(false);+ const persisted = readJSON(VIDEO_HISTORY_PATH);+ expect(persisted.map((v) => v.id)).toEqual(['v1']);+ });++ it('applyRemote preserves an id-less LOCAL row instead of dropping it', async () => {+ writeJSON(VIDEO_HISTORY_PATH, [{ prompt: 'legacy', filename: 'legacy.mp4' }]);+ await dataSync.applyRemote('videoHistory', { videos: [row('v-new')] });+ const persisted = readJSON(VIDEO_HISTORY_PATH);+ expect(persisted.some((v) => v.prompt === 'legacy')).toBe(true);+ expect(persisted.some((v) => v.id === 'v-new')).toBe(true);+ });++ it('checksum changes after applyRemote mutates the file', async () => {+ writeJSON(VIDEO_HISTORY_PATH, [row('v1')]);+ const before = await dataSync.getChecksum('videoHistory');+ await dataSync.applyRemote('videoHistory', { videos: [row('v2')] });+ const after = await dataSync.getChecksum('videoHistory');+ expect(after.checksum).not.toBe(before.checksum);+ });+});diff --git a/server/services/instances.js b/server/services/instances.jsindex b7f4cd8e42..ad10681583 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -166,7 +166,8 @@ const DEFAULT_SYNC_CATEGORIES = {meatspace: false,universe: false,pipeline: false,- mediaCollections: false+ mediaCollections: false,+ videoHistory: false};export { DEFAULT_SYNC_CATEGORIES };diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 85ef4ed5b6..49e3aa8338 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -44,6 +44,7 @@ import { isPlainObject } from '../../lib/objects.js';import { peerBaseUrl } from '../../lib/peerUrl.js';import { peerFetch } from '../../lib/peerHttpClient.js';import { getOrComputeImageSha256, sidecarGenParamsHash } from '../../lib/assetHash.js';+import { generateThumbnail } from '../../lib/ffmpeg.js';import { sanitizeRecordForWire } from '../../lib/syncWire.js';import { collectAssetReferences } from './exporter.js';import { imageSidecarName, sanitizeAssetFilename } from './buckets.js';@@ -1625,6 +1626,20 @@ async function doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName)if (entry.kind === 'image') {await pullSidecarForImage(peer, base, safeName).catch(() => {});}+ // After a video pull, regenerate the thumbnail LOCALLY rather than pulling it+ // as a sibling asset. Cheaper end-to-end: no new asset kind / URL-prefix /+ // manifest-diff plumbing, and the thumbnail filename is deterministic+ // (`<jobId>.jpg`, where jobId === the video filename minus `.mp4`). The+ // synced video-history row already carries `thumbnail: '<jobId>.jpg'`, so+ // once this file exists on disk `normalizeVideo` renders the collection+ // tile. Best-effort: if ffmpeg is missing the row still syncs (the item+ // stops being filtered as "missing"); the tile just falls back to no+ // preview. Mirrors generateThumbnail's null-on-failure contract.+ if (entry.kind === 'video') {+ const jobId = safeName.replace(/\.[a-z0-9]+$/i, '');+ const videoPath = join(localDir, safeName);+ await generateThumbnail(videoPath, jobId).catch(() => null);+ }}// --- Listener install + debounced trigger -------------------------------