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: add persistent code animation gallery
[._.]/ Adam Eivy8019f3fc2929
diff --git a/client/src/App.jsx b/client/src/App.jsxindex 931fccaa6a..eeb12a1c53 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -594,6 +594,7 @@ export default function App() {<Route path="catalog/ingest" element={<CatalogIngest />} /><Route path="catalog/:type/:id" element={<CatalogIngredient />} /><Route path="code-animation" element={<CodeAnimation />} />+ <Route path="code-animation/:jobId" element={<CodeAnimation />} /><Route path="mood-boards" element={<MoodBoards />} /><Route path="mood-boards/:id" element={<MoodBoardDetail />} /><Route path="decks" element={<Decks />} />diff --git a/client/src/pages/CodeAnimation.jsx b/client/src/pages/CodeAnimation.jsxindex 934b08bd5f..35468aaaca 100644--- a/client/src/pages/CodeAnimation.jsx+++ b/client/src/pages/CodeAnimation.jsx@@ -1,6 +1,6 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { Copy, FileCode2, Globe, ImagePlus, LoaderCircle, Music2, PenLine, Sparkles, Wand2, X } from 'lucide-react';-import { Link, useSearchParams } from 'react-router';+import { AlertTriangle, CheckCircle2, Clock3, Copy, FileCode2, Globe, ImagePlus, LoaderCircle, Music2, PenLine, Sparkles, Wand2, X } from 'lucide-react';+import { Link, useNavigate, useParams, useSearchParams } from 'react-router';import PageHeader from '../components/PageHeader';import ProviderModelSelector from '../components/ProviderModelSelector';import CodeAnimationPreview from '../components/codeAnimation/CodeAnimationPreview';@@ -12,6 +12,7 @@ import {generateCodeAnimationBrief,getCodeAnimationJob,getCodeAnimationOptions,+ listCodeAnimationJobs,listMoodBoardNames,listUniverseNames,listUniverseStyles,@@ -21,9 +22,11 @@ import {import { copyToClipboard } from '../lib/clipboard';import { safeReadJsonStorage, safeWriteJsonStorage } from '../lib/safeStorage';import { readFileAsBase64, UPLOAD_IMAGE_ACCEPT, validateImageFile } from '../utils/fileUpload';+import { formatCount, timeAgo } from '../utils/formatters';const DRAFT_KEY = 'portos.codeAnimation.draft';const JOB_POLL_MS = 3_000;+const GALLERY_POLL_MS = 10_000;// Mood-board choice sentinels: follow the universe's linked board, or none.const BOARD_FOLLOW_UNIVERSE = 'universe';const BOARD_NONE = 'none';@@ -98,6 +101,52 @@ function toBriefIdeaInput(draft) {};}+function draftFromJob(job) {+ const input = job?.input || {};+ const moodBoardChoice = input.moodBoardId === undefined+ ? BOARD_FOLLOW_UNIVERSE+ : input.moodBoardId+ ? input.moodBoardId+ : BOARD_NONE;+ return {+ ...DEFAULT_DRAFT,+ title: input.title || '',+ seedIdea: input.seedIdea || '',+ concept: input.concept || '',+ onScreenText: input.onScreenText || '',+ styleNotes: input.styleNotes || '',+ universeId: input.universeId || '',+ moodBoardChoice,+ includeMoodBoardImages: input.includeMoodBoardImages !== false,+ referenceImages: (Array.isArray(input.referenceImages) ? input.referenceImages : []).map((image) => ({+ ...image,+ url: `/api/uploads/${encodeURIComponent(image.filename)}`,+ })),+ audio: input.audio+ ? { ...input.audio, url: `/api/uploads/${encodeURIComponent(input.audio.filename)}` }+ : null,+ soundtrack: input.soundtrack || 'none',+ format: { ...DEFAULT_DRAFT.format, ...(input.format || {}) },+ renderer: input.renderer || 'auto',+ interactive: input.interactive === true,+ };+}++function galleryJob(job) {+ return {+ id: job.id,+ status: job.status,+ title: job.title,+ concept: job.concept || job.input?.concept || '',+ providerId: job.providerId,+ model: job.model,+ error: job.error,+ createdAt: job.createdAt,+ startedAt: job.startedAt,+ completedAt: job.completedAt,+ };+}+const readAudioDuration = (file) => new Promise((resolve) => {const url = URL.createObjectURL(file);const audio = new Audio();@@ -128,8 +177,10 @@ async function uploadOrToast(file) {}export default function CodeAnimation() {- const [searchParams, setSearchParams] = useSearchParams();- const jobId = searchParams.get('job') || '';+ const [searchParams] = useSearchParams();+ const routeParams = useParams();+ const navigate = useNavigate();+ const jobId = routeParams.jobId || searchParams.get('job') || '';const [options, setOptions] = useState(null);const [universes, setUniverses] = useState([]);const [universeStyles, setUniverseStyles] = useState({});@@ -142,11 +193,16 @@ export default function CodeAnimation() {const [built, setBuilt] = useState(null);const [starting, setStarting] = useState(false);const [job, setJob] = useState(null);+ const [savedJobs, setSavedJobs] = useState([]);+ const [galleryLoaded, setGalleryLoaded] = useState(false);+ const [galleryError, setGalleryError] = useState('');const [effort, setEffort] = useState('');const [briefEffort, setBriefEffort] = useState('');const [pastedHtml, setPastedHtml] = useState('');const [preview, setPreview] = useState(null);const jobIdRef = useRef(jobId);+ const hydratedJobIdRef = useRef('');+ const galleryRequestRef = useRef(0);const {providers,selectedProviderId,@@ -169,6 +225,22 @@ export default function CodeAnimation() {const update = (patch) => setDraft((prev) => ({ ...prev, ...patch }));const updateFormat = (patch) => setDraft((prev) => ({ ...prev, format: { ...prev.format, ...patch } }));+ const refreshGallery = useCallback(async () => {+ const requestId = ++galleryRequestRef.current;+ const rows = await listCodeAnimationJobs({ silent: true }).catch((error) => {+ if (requestId !== galleryRequestRef.current) return null;+ setGalleryError(error.message || 'Failed to load animation gallery');+ setGalleryLoaded(true);+ return null;+ });+ if (requestId !== galleryRequestRef.current) return;+ if (!Array.isArray(rows)) return;+ setSavedJobs(rows);+ setGalleryError('');+ setGalleryLoaded(true);+ }, []);+ useAutoRefetch(refreshGallery, GALLERY_POLL_MS, { enabled: true, pollOnly: true });+useEffect(() => { safeWriteJsonStorage(DRAFT_KEY, draft); }, [draft]);useEffect(() => {@@ -193,10 +265,18 @@ export default function CodeAnimation() {// blank-slate idea generator.const briefSeeds = !!(draft.universeId || draft.seedIdea.trim() || draft.concept.trim() || draft.title.trim());const canWriteBrief = briefSeeds && !writingBrief;+ const inProgressCount = savedJobs.filter((item) => item.status === 'running').length;+ const completedCount = savedJobs.filter((item) => item.status === 'completed').length;// Poll the generation job named in the URL until it settles. The ref drops a// response for a job the user has since replaced.- useEffect(() => { jobIdRef.current = jobId; }, [jobId]);+ useEffect(() => {+ jobIdRef.current = jobId;+ hydratedJobIdRef.current = '';+ setJob(null);+ setPreview(null);+ setBuilt(null);+ }, [jobId]);const jobSettled = job?.id === jobId && job.status !== 'running';const pollJob = useCallback(async () => {const requested = jobId;@@ -209,6 +289,28 @@ export default function CodeAnimation() {if (jobIdRef.current !== requested) return;setJob(next);if (next.status === 'completed' && next.html) setPreview({ html: next.html, audioUrl: next.audioUrl, frame: next.frame });+ else setPreview(null);+ if (next.status !== 'missing') {+ galleryRequestRef.current += 1;+ setSavedJobs((previous) => [galleryJob(next), ...previous.filter((item) => item.id !== requested)]+ .sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || '')));+ }+ if (hydratedJobIdRef.current !== requested && next.input) {+ hydratedJobIdRef.current = requested;+ const restoredDraft = draftFromJob(next);+ setDraft(restoredDraft);+ setSelectedProviderId(next.input.providerId || '');+ setSelectedModel(next.input.model || '');+ setEffort(next.input.effort || '');+ setBuilt(next.prompt ? {+ prompt: next.prompt,+ attachments: next.attachments || [],+ frame: next.frame,+ audioUrl: next.audioUrl,+ moodBoardId: next.moodBoardId,+ briefKey: JSON.stringify(toBrief(restoredDraft)),+ } : null);+ }}, [jobId]);useAutoRefetch(pollJob, JOB_POLL_MS, { enabled: !!jobId && !jobSettled, pollOnly: true });@@ -289,6 +391,7 @@ export default function CodeAnimation() {setStarting(true);const started = await startCodeAnimationGeneration({...brief,+ seedIdea: draft.seedIdea,providerId: selectedProviderId,model: selectedModel || undefined,effort: effort || undefined,@@ -301,9 +404,9 @@ export default function CodeAnimation() {setBuilt({ prompt: started.prompt, attachments: started.attachments, frame: started.frame, audioUrl: started.audioUrl, moodBoardId: started.moodBoardId, briefKey });setJob(started);setPreview(null);- const next = new URLSearchParams(searchParams);- next.set('job', started.id);- setSearchParams(next);+ galleryRequestRef.current += 1;+ setSavedJobs((previous) => [galleryJob(started), ...previous.filter((item) => item.id !== started.id)]);+ navigate(`/code-animation/${encodeURIComponent(started.id)}`);};const handlePreviewPasted = () => {@@ -322,6 +425,58 @@ export default function CodeAnimation() {className="rounded-xl border border-port-border bg-port-card"/>+ <section className="space-y-3 rounded-xl border border-port-border bg-port-card p-4" aria-labelledby="ca-gallery-heading">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div>+ <h2 id="ca-gallery-heading" className="text-sm font-semibold text-white">Animation gallery</h2>+ <p className="mt-1 text-xs text-gray-500">+ {formatCount(inProgressCount)} in progress · {formatCount(completedCount)} completed+ </p>+ </div>+ <Link to="/code-animation" className={buttonSecondary}>+ <Sparkles className="h-4 w-4" /> New animation+ </Link>+ </div>+ {galleryError && <p role="status" className="text-xs text-port-error">{galleryError}</p>}+ {!galleryLoaded && <p className="text-xs text-gray-500">Loading animations…</p>}+ {galleryLoaded && savedJobs.length === 0 && !galleryError && (+ <p className="text-xs text-gray-500">Generated animations will appear here so you can reopen them later.</p>+ )}+ {savedJobs.length > 0 && (+ <div className="grid max-h-64 grid-cols-1 gap-2 overflow-y-auto pr-1 sm:grid-cols-2 xl:grid-cols-3">+ {savedJobs.map((item) => {+ const StatusIcon = item.status === 'running'+ ? Clock3+ : item.status === 'completed'+ ? CheckCircle2+ : AlertTriangle;+ const statusLabel = item.status === 'running'+ ? 'In progress'+ : item.status === 'completed'+ ? 'Completed'+ : 'Failed';+ return (+ <Link+ key={item.id}+ to={`/code-animation/${encodeURIComponent(item.id)}`}+ aria-current={jobId === item.id ? 'page' : undefined}+ className={`min-w-0 rounded-lg border p-3 transition-colors hover:border-port-accent ${jobId === item.id ? 'border-port-accent bg-port-accent/10' : 'border-port-border bg-port-bg/60'}`}+ >+ <div className="flex items-center gap-2">+ <StatusIcon className={`h-4 w-4 shrink-0 ${item.status === 'failed' ? 'text-port-error' : item.status === 'completed' ? 'text-port-success' : 'text-port-accent'}`} />+ <p className="min-w-0 flex-1 truncate text-sm font-medium text-white">{item.title || item.concept || 'Untitled animation'}</p>+ </div>+ <div className="mt-2 flex items-center justify-between gap-2 text-xs text-gray-500">+ <span>{statusLabel}{item.model ? ` · ${item.model}` : ''}</span>+ <span className="shrink-0">{timeAgo(item.createdAt)}</span>+ </div>+ </Link>+ );+ })}+ </div>+ )}+ </section>+<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]"><div className="space-y-4"><section className="space-y-3 rounded-xl border border-port-border bg-port-card p-4" aria-labelledby="ca-style-heading">@@ -556,7 +711,7 @@ export default function CodeAnimation() {{generating ? 'Generating…' : 'Generate animation'}</button>{job?.status === 'failed' && <span className="text-xs text-port-error">Generation failed: {job.error}</span>}- {job?.status === 'missing' && <span className="text-xs text-gray-500">That generation is no longer available (it expired or the server restarted).</span>}+ {job?.status === 'missing' && <span className="text-xs text-gray-500">That generation is no longer available.</span>}</div><details className="text-xs text-gray-400"><summary className="cursor-pointer select-none">Preview HTML from another LLM</summary>diff --git a/client/src/pages/CodeAnimation.test.jsx b/client/src/pages/CodeAnimation.test.jsxindex 844bdcc135..6ce8993261 100644--- a/client/src/pages/CodeAnimation.test.jsx+++ b/client/src/pages/CodeAnimation.test.jsx@@ -8,6 +8,7 @@ vi.mock('../services/api', () => ({generateCodeAnimationBrief: vi.fn(),getCodeAnimationJob: vi.fn(),getCodeAnimationOptions: vi.fn(),+ listCodeAnimationJobs: vi.fn().mockResolvedValue([]),listMoodBoardNames: vi.fn(),listUniverseNames: vi.fn(),listUniverseStyles: vi.fn(),diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 46ae12f591..a919f2f87d 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -114,7 +114,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiContinuousVideo.js` | Continuous-video episode generation: client-side-callable lint preview of a scene draft, queue-episode submit, and the SSE progress-events URL. || `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), directional walk and per-track generation/approval, animation-type definition CRUD (#3153), trim/postprocess, and per-run source-frame listing for the Loop Trimmer's re-derive (#2980), and animation render-provider readiness (#4876). || `apiShell.js` | Shell sessions over HTTP: hand a photo (plus a message) to the agent TUI running in a session. Keystrokes/output stay on the `shell:*` socket protocol. |-| `apiCodeAnimation.js` | Code Animation: host-contract options, LLM-written briefs from a universe, universe-styled LLM prompt building for a procedurally coded animation film, and provider generation jobs (start + poll for the HTML). |+| `apiCodeAnimation.js` | Code Animation: host-contract options, LLM-written briefs from a universe, universe-styled LLM prompt building, a persistent generation gallery, and provider jobs (start + poll for the HTML). || `apiThreejsModels.js` | Procedural Three.js model workspaces: gallery-image generation, refinement, source export, deletion, and the subject-family checklist options. || `apiImageTo3d.js` | Image-to-3D (`/3d`): selectable targets (TRELLIS.2) with host availability/install status, and per-image model records — create/list/get/generate/delete + GLB asset URL, the full-resolution OBJ download URL, and the AR Quick Look USDZ upload/download pair. || `apiPipeline.js` | Pipeline (issues + stages + canon; series names and index summaries). |diff --git a/client/src/services/apiCodeAnimation.js b/client/src/services/apiCodeAnimation.jsindex 0a694839e7..fd5eac3f1d 100644--- a/client/src/services/apiCodeAnimation.js+++ b/client/src/services/apiCodeAnimation.js@@ -26,5 +26,7 @@ export const startCodeAnimationGeneration = (brief, options) => request('/code-a...options,});+export const listCodeAnimationJobs = (options) => request('/code-animation/jobs', options);+export const getCodeAnimationJob = (id, options) =>request(`/code-animation/generate/${encodeURIComponent(id)}`, options);diff --git a/docs/API.md b/docs/API.mdindex 3111b8f153..c79eac39f7 100644--- a/docs/API.md+++ b/docs/API.md@@ -763,7 +763,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom| `/api/games` | Game projects || `/api/sprites` | Sprite catalog / export || `/api/threejs-models` | Procedural Three.js models |-| `/api/code-animation` | Code Animation: LLM-written briefs from a universe, universe-styled prompt for an LLM-coded animation film, plus provider generation jobs (start + poll for the HTML) |+| `/api/code-animation` | Code Animation: LLM-written briefs, prompt building, persistent jobs gallery, and generated HTML retrieval || `/api/image-to-3d` | Image-to-3D conversion || `/api/rigging` | Auto-skin rigging and animation retargeting for image-to-3D models || `/api/privacy` | PII vault / trusted-org / broker opt-out |diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex d6def5c119..f6c2832e21 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -48,6 +48,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- `games` — Game studio workspaces (#3177): one row per managed-app asset plan, with the full reusable sprite/music binding set, current compiled-manifest pointer, compile history, and user-requested AI feedback history in `data` JSONB; `app_id`/`name`/`updated_at` are mirrored for list and relationship queries. The record is **machine-local** because managed-app registration, sprite atlases, and music-library bytes are machine-local; there is no peer-sync cursor or tombstone, and deletes are hard deletes. Compiled manifests are immutable, SHA-256-addressed artifacts under `data/games/{id}/manifests/`; their pointers and hashes live in the DB record. Adapter: `server/services/games/db.js`, selected pg-vs-collectionStore by `server/services/games/store.js` (collectionStore is test/unsupported file escape hatch only).- `fableloom_stories` — FableLoom branching narratives: one row per loom (a branching-narrative story), with episodes, scene-node graphs, and intent transitions in `data` JSONB; `name`/`universe_id`/`series_id`/`updated_at` are mirrored for list and relationship queries (both refs are soft — no FK). `db-primary` because looms relate to universes and series and the index queries by recency. Federates through the opt-in per-record `fableLoom` category: whole-record LWW merges carry soft-delete tombstones, conflict-journal recovery, and hashed manifests for scene images/videos; there is no snapshot cursor or `sync_sequence`. Adapter: `server/services/fableLoom/db.js`, selected pg-vs-collectionStore by `server/services/fableLoom/store.js` (collectionStore is the test/unsupported file escape hatch only). Feature doc: [FableLoom](./features/fableloom.md).- `threejs_models` — generated procedural 3D-model workspaces: one row per model with gallery-image lineage, provider/model attribution, generation/refinement status, and the validated declarative scene spec in `data` JSONB. The referenced image bytes remain under `data/images/`; deterministic Three.js source is derived from the stored spec rather than persisted as a second mutable artifact. The table is local-only in this first slice, with soft-delete columns retained so federation can be added without a record-shape migration.+- `code_animation_jobs` — Code Animation generation history (`db-primary` record with a managed HTML output asset): job status/title and the generation brief/provider details are stored in PostgreSQL so the gallery can list and reopen jobs after navigation or restart. The generated HTML is kept as a managed file at `data/code-animations/<id>.html`; PostgreSQL stores only its job record, not the output bytes. Jobs are machine-local and never federated. The database dump covers records and the normal filesystem backup includes the HTML assets.- `ai_connections` / `ai_harness_bindings` / `ai_route_bindings` — AI **services** (instances a harness is pointed at) and the graph the **presets** derived from them are projected through (#6367 → #7561; user guide [AI_PROVIDERS.md](./AI_PROVIDERS.md), design record [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md)): the backend a harness talks to, each harness configuration bound to it, and the executable route each one projects. `db-primary` because it is a real graph — a connection has many bindings, a binding has one route per mode, and the uniqueness rules (`UNIQUE(binding_id, mode)`, `UNIQUE(connection_id, harness_id, variant_key)` plus a partial index for null-harness API bindings) are integrity constraints a set of JSON files cannot hold. `data/providers.json` REMAINS the execution contract and stays fully materialized: every connection-owned value is projected back into it, so a downgraded release runs unchanged with these tables simply idle. **Intentionally machine-local — never federated**: rows carry endpoints, credential material and this host's execution environment (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)). No `sync_sequence`, no tombstones, no `PORTOS_SCHEMA_VERSIONS` entry, no `dataSync` category; deletes are hard deletes and are refused while a binding still references the row. `ai_route_bindings.projected` / `.pending` are the projection snapshots that make an interrupted file write recoverable — as private as the credentials, and covered by the Postgres dump like every other db-primary table. Adapters: `server/services/providerGraphStore.js` (rows) and `server/services/providerGraph.js` (import, reconciliation, link/unlink), over the pure `server/lib/providerGraphRecords.js`. Since #7563 an `ai_connections` row is also one SERVICE INSTANCE of a `server/lib/serviceDefinitions.js` entry: additive `slug` (unique, the address a composite provider id will carry), `definition_id`, `plan` (`free` / `paid` / `subscription` / `local`), `enabled` and `credential_via` (`stored` / `env` / `cli-login` / `bootstrap` — only `stored` holds a secret), with `catalog` gaining optional per-model `capabilities` and `refreshedAt`. The columns are backfilled from `kind` by the boot reconcile pass (`planServiceColumnBackfill` in `server/lib/providerServiceInstances.js`) — derived from the install's own rows, never seeded, idempotent — and managed through `server/services/providerServices.js` (`/api/providers/services*`), which refreshes a catalog through the definition's listing strategy without needing an executable route. Since #7565 a `data/providers.json` record may name the instance it is DERIVED from (`harnessId` / `method` / `serviceId`, plus `catalogNarrowing` and `credentialBootstrapId`): its connection-owned values are re-materialized from that row on every save and on every service edit, while the file stays the fully materialized execution contract — an older release runs the record unchanged and its schema strips the keys it never saw. The stamping of existing records rides the same boot reconcile pass (`planPresetBackfill` in `server/lib/providerPresets.js`), additive and idempotent; see `docs/PROVIDER_COMPOSITION.md` § Presets.- `privacy_subjects` / `privacy_vault_records` / `privacy_consents` / `privacy_orgs` / `privacy_org_holdings` / `privacy_change_events` / `privacy_brokers` / `privacy_broker_cases` — the Privacy Center (epic #2138): the household subjects the suite works on behalf of (`self` plus consenting partners/children/parents — every other table carries a `subject_id` FK defaulted to the seeded `self` row, #3658), the encrypted PII vault, the trusted-organization registry with per-field holdings, the change-of-address inventory, and the data-broker opt-out ledger. Relational by nature (org ↔ holdings ↔ vault records ↔ change events ↔ broker cases), which is why they are `db-primary`. Vault *values* are AES-256-GCM ciphertext (`v1:<iv>:<tag>:<ct>`, key from `PRIVACY_VAULT_KEY`) — the DB holds bytes of ciphertext, never plaintext PII, and plaintext never appears in logs (`server/lib/vaultCrypto.js`). **Intentionally machine-local — never federated**, and this is a product *guarantee*, not a deferred feature (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), #2148). NO `sync_sequence`, NO peer-sync record kind, NO `dataSync` category, NO `PORTOS_SCHEMA_VERSIONS` entry, and no `deleted`/`deleted_at` tombstones — deletes are hard deletes, mirroring `tribe`. The reasoning is the same class as the Tribe graph but stronger: the peer-sync **pull** path (`GET /api/peer-sync/record`) carries no peer identity, `masked_value` is plaintext by design so even ciphertext-only sync would leak a PII fingerprint, and a shared `PRIVACY_VAULT_KEY` would widen the at-rest blast radius to every peer's `.env`. A second machine gets the vault by restoring a backup and copying the key by hand — a deliberate act, not continuous replication. Enforced by `server/services/sharing/privacyNeverFederates.test.js`. Adapters: `server/services/privacySubjects.js`, `privacyVault.js`, `privacyOrgs.js`, `privacyChanges.js`, `privacyBrokers.js`, `privacyOptOut.js`.diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.mdindex 1ed2b184ae..5771517ddb 100644--- a/server/lib/db/schema/README.md+++ b/server/lib/db/schema/README.md@@ -33,7 +33,7 @@ init-db.sql, each with a one-line reason.| `cosAgentFeedback.js` | `cosAgentFeedbackDdl` | Durable machine-local references to completed manual CoS runs awaiting a rating (agent id + archive locator only) || `aiGraph.js` | `aiGraphDdl` | AI provider connection graph — connections, harness bindings, executable route bindings (machine-local) || `catalog.js` | `catalogDdl`, `catalogUserTypesDdl` | Catalog scraps/ingredients/tags/media + user-defined types |-| `media.js` | `mediaDdl` | Creative-director / music-video projects, mood boards, media assets |+| `media.js` | `mediaDdl` | Creative-director / music-video projects, mood boards, media assets, and Code Animation jobs || `universes.js` | `universesDdl` | Universes, machine-local character voice profiles/renders, + universe run history || `library.js` | `libraryDdl` | Authors, artists, albums, tracks || `pipeline.js` | `pipelineDdl` | Pipeline series, issues, story-builder sessions |diff --git a/server/lib/db/schema/audit.js b/server/lib/db/schema/audit.jsindex 46d48d1c15..430fd02af3 100644--- a/server/lib/db/schema/audit.js+++ b/server/lib/db/schema/audit.js@@ -2,8 +2,8 @@// trigger function, the list of audited tables, and the trigger builder.// Extracted verbatim from ensureSchemaImpl() in server/lib/db.js (#2832) with// zero behavior change. Parity-locked against server/scripts/init-db.sql by-// db.ddlParity.test.js — keep auditedTables in sync with the-// AUDITED_RECORD_TABLES list there.+// db.ddlParity.test.js — keep auditedTables in sync with the audit triggers+// in init-db.sql.export const auditDdl = [// ─── Deletion audit log (incident #1248-follow-up) ──────────────────────// Append-only forensic trail of EVERY tombstone (soft-delete), un-tombstone@@ -84,12 +84,12 @@ export const auditDdl = [// Attach the audit trigger to every user-authored-content table. Adding a// table here is all it takes to audit its deletions. (Keep in sync with the-// AUDITED_RECORD_TABLES list in init-db.sql.)+// audit triggers in init-db.sql.)export const auditedTables = ['universes', 'universe_runs', 'pipeline_series', 'pipeline_issues','story_builder_sessions', 'writers_room_works', 'writers_room_folders','writers_room_draft_versions', 'catalog_ingredients', 'catalog_scraps',- 'catalog_user_types', 'creative_director_projects', 'threejs_models', 'image_to_3d_models', 'sprite_records', 'games', 'mood_boards', 'fableloom_stories',+ 'catalog_user_types', 'creative_director_projects', 'threejs_models', 'image_to_3d_models', 'sprite_records', 'games', 'code_animation_jobs', 'mood_boards', 'fableloom_stories','lora_training_runs', 'authors', 'artists', 'albums', 'tracks', 'tribe_people', 'tribe_touchpoints','tribe_identities',];diff --git a/server/lib/db/schema/media.js b/server/lib/db/schema/media.jsindex 2ecf43ba4a..47eef114f4 100644--- a/server/lib/db/schema/media.js+++ b/server/lib/db/schema/media.js@@ -174,4 +174,22 @@ export const mediaDdl = [// images-vs-videos. A composite (kind, created_at DESC) serves both.`CREATE INDEX IF NOT EXISTS idx_media_assets_kind_created ON media_assets (kind, created_at DESC)`,+ // Code Animation jobs. The searchable gallery fields are mirrored into+ // columns; the full brief/provider/status record lives in JSONB, while the+ // generated HTML is a managed file at data/code-animations/<id>.html.+ // Machine-local generated work: it has no peer-sync cursor or tombstone.+ `CREATE TABLE IF NOT EXISTS code_animation_jobs (+ id TEXT PRIMARY KEY,+ status VARCHAR(16) NOT NULL,+ title TEXT NOT NULL DEFAULT '',+ concept TEXT NOT NULL DEFAULT '',+ provider_id TEXT,+ model TEXT,+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+ )`,+ `CREATE INDEX IF NOT EXISTS idx_code_animation_jobs_created ON code_animation_jobs (created_at DESC, id DESC)`,+ `CREATE INDEX IF NOT EXISTS idx_code_animation_jobs_status_created ON code_animation_jobs (status, created_at DESC)`,+];diff --git a/server/routes/codeAnimation.js b/server/routes/codeAnimation.jsindex da1e88ec96..bd2e6b5fe6 100644--- a/server/routes/codeAnimation.js+++ b/server/routes/codeAnimation.js@@ -6,6 +6,7 @@* POST /api/code-animation/brief write a brief from the universe → { brief }* POST /api/code-animation/prompt resolve configurations → { prompt, attachments, frame }* POST /api/code-animation/generate start a provider run → 202 job+ * GET /api/code-animation/jobs list saved jobs for the gallery* GET /api/code-animation/generate/:id poll a job (html once completed)*/@@ -19,6 +20,7 @@ import {buildCodeAnimationRequest,generateCodeAnimationBrief,getCodeAnimationJob,+ listCodeAnimationJobs,getCodeAnimationOptions,startCodeAnimationGeneration,} from '../services/codeAnimation/index.js';@@ -72,6 +74,7 @@ const briefSchema = z.object({}).strict();const generateSchema = briefSchema.extend({+ seedIdea: z.string().trim().max(L.seedIdeaMax).default(''),providerId: z.string().trim().min(1).max(128),model: z.string().trim().max(256).optional(),effort: z.preprocess(emptyToNull, z.enum(EFFORT_LEVELS).nullable().optional()),@@ -117,9 +120,13 @@ router.post('/generate', asyncHandler(async (req, res) => {res.status(202).json(await startCodeAnimationGeneration(input));}));+router.get('/jobs', asyncHandler(async (_req, res) => {+ res.json(await listCodeAnimationJobs());+}));+router.get('/generate/:id', asyncHandler(async (req, res) => {- const job = getCodeAnimationJob(req.params.id);- if (!job) throw new ServerError('Generation job not found (it may have expired or the server restarted)', { status: 404, code: 'NOT_FOUND' });+ const job = await getCodeAnimationJob(req.params.id);+ if (!job) throw new ServerError('Generation job not found', { status: 404, code: 'NOT_FOUND' });res.json(job);}));diff --git a/server/routes/codeAnimation.test.js b/server/routes/codeAnimation.test.jsindex e85c215578..2c2374dfdd 100644--- a/server/routes/codeAnimation.test.js+++ b/server/routes/codeAnimation.test.js@@ -6,8 +6,21 @@ import { request } from '../lib/testHelper.js';import { errorMiddleware, ServerError } from '../lib/errorHandler.js';import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';+const { codeAnimationRecords, codeAnimationHtml } = vi.hoisted(() => ({+ codeAnimationRecords: new Map(),+ codeAnimationHtml: new Map(),+}));+vi.mock('../lib/paths.js', async (importOriginal) =>makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-code-animation-') }));+vi.mock('../services/codeAnimation/jobStore.js', () => ({+ getCodeAnimationJobRecord: vi.fn(async (id) => codeAnimationRecords.get(id) ?? null),+ isCodeAnimationJobId: (id) => /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(id),+ listCodeAnimationJobRecords: vi.fn(async () => [...codeAnimationRecords.values()]),+ readCodeAnimationHtml: vi.fn(async (id) => codeAnimationHtml.get(id)),+ saveCodeAnimationHtml: vi.fn(async (id, html) => codeAnimationHtml.set(id, html)),+ saveCodeAnimationJobRecord: vi.fn(async (job) => codeAnimationRecords.set(job.id, job)),+}));vi.mock('../services/universeBuilder/crud.js', () => ({ getUniverse: vi.fn() }));vi.mock('../services/moodBoard/db.js', () => ({ getBoard: vi.fn() }));vi.mock('../services/providers.js', () => ({ getProviderById: vi.fn() }));@@ -71,6 +84,8 @@ afterAll(cleanupTempDataRoots);beforeEach(() => {vi.clearAllMocks();+ codeAnimationRecords.clear();+ codeAnimationHtml.clear();getUniverse.mockResolvedValue(UNIVERSE);getBoard.mockResolvedValue(BOARD);resolveProviderAndModel.mockResolvedValue({ provider: { id: 'api-1', type: 'api' }, selectedModel: 'example-model' });diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex f9e2ed8eec..0a52e036aa 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -946,6 +946,23 @@ CREATE TABLE IF NOT EXISTS media_assets (-- images-vs-videos. A composite (kind, created_at DESC) serves both.CREATE INDEX IF NOT EXISTS idx_media_assets_kind_created ON media_assets (kind, created_at DESC);+-- Code Animation jobs. Gallery status/title and the full brief/provider record+-- live in PostgreSQL; generated HTML stays in data/code-animations/<id>.html.+-- Machine-local generated work with no peer-sync cursor or tombstone.+CREATE TABLE IF NOT EXISTS code_animation_jobs (+ id TEXT PRIMARY KEY,+ status VARCHAR(16) NOT NULL,+ title TEXT NOT NULL DEFAULT '',+ concept TEXT NOT NULL DEFAULT '',+ provider_id TEXT,+ model TEXT,+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);+CREATE INDEX IF NOT EXISTS idx_code_animation_jobs_created ON code_animation_jobs (created_at DESC, id DESC);+CREATE INDEX IF NOT EXISTS idx_code_animation_jobs_status_created ON code_animation_jobs (status, created_at DESC);+-- Catalog user-defined types (Phase 4 lead-in, issue #1001). One row per-- user-defined ingredient type — the registry that defines catalog row-- semantics, moved out of data/settings.json (`catalogUserTypes`) so type@@ -1921,7 +1938,7 @@ END;$$ LANGUAGE plpgsql;-- Audit trigger on every user-authored-content table. AUDITED_RECORD_TABLES —--- keep in sync with the auditedTables list in server/lib/db.js.+-- keep in sync with auditedTables in server/lib/db/schema/audit.js.DROP TRIGGER IF EXISTS trg_universes_audit ON universes;CREATE TRIGGER trg_universes_audit AFTER UPDATE OR DELETE ON universes FOR EACH ROW EXECUTE FUNCTION record_audit_log();DROP TRIGGER IF EXISTS trg_universe_runs_audit ON universe_runs;@@ -1954,6 +1971,8 @@ DROP TRIGGER IF EXISTS trg_sprite_records_audit ON sprite_records;CREATE TRIGGER trg_sprite_records_audit AFTER UPDATE OR DELETE ON sprite_records FOR EACH ROW EXECUTE FUNCTION record_audit_log();DROP TRIGGER IF EXISTS trg_games_audit ON games;CREATE TRIGGER trg_games_audit AFTER UPDATE OR DELETE ON games FOR EACH ROW EXECUTE FUNCTION record_audit_log();+DROP TRIGGER IF EXISTS trg_code_animation_jobs_audit ON code_animation_jobs;+CREATE TRIGGER trg_code_animation_jobs_audit AFTER UPDATE OR DELETE ON code_animation_jobs FOR EACH ROW EXECUTE FUNCTION record_audit_log();DROP TRIGGER IF EXISTS trg_fableloom_stories_audit ON fableloom_stories;CREATE TRIGGER trg_fableloom_stories_audit AFTER UPDATE OR DELETE ON fableloom_stories FOR EACH ROW EXECUTE FUNCTION record_audit_log();DROP TRIGGER IF EXISTS trg_mood_boards_audit ON mood_boards;diff --git a/server/services/codeAnimation/index.js b/server/services/codeAnimation/index.jsindex 261920ba3d..5bcefad1d4 100644--- a/server/services/codeAnimation/index.js+++ b/server/services/codeAnimation/index.js@@ -3,11 +3,10 @@* mood board, reference uploads, audio) into prompt inputs, builds the prompt,* and optionally runs it through an AI provider to get the animation's HTML.*- * Nothing is persisted: the prompt is returned for the user to copy, and a- * generation is a short-lived in-memory job the page polls until the HTML is- * ready. The page then previews, records, and saves the result through the- * existing gallery-video upload path, which is where the durable artifact- * lives. A server restart simply forgets in-flight jobs.+ * Generated jobs are persisted locally: PostgreSQL stores gallery metadata+ * and the generation brief, while the completed HTML is a managed file asset.+ * The page can reopen completed work after navigation or restart; a job that+ * was still running when the server restarted is marked interrupted on read.** The heavy dependencies (provider runner, universe + mood-board stores) are* imported lazily so the options/prompt path and its tests stay light.@@ -20,6 +19,14 @@ import { makePathResolver, resolveGalleryImage, resolveImageRef } from '../../liimport { universeVisualStyleTokens } from '../../lib/universeVisualStyle.js';import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';import { UPLOAD_AUDIO_EXTENSIONS } from '../../lib/mimeTypes.js';+import {+ getCodeAnimationJobRecord,+ isCodeAnimationJobId,+ listCodeAnimationJobRecords,+ readCodeAnimationHtml,+ saveCodeAnimationHtml,+ saveCodeAnimationJobRecord,+} from './jobStore.js';import {buildCodeAnimationPrompt,extractAnimationHtml,@@ -36,9 +43,10 @@ const IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'webp', 'gif'];const resolveUploadImage = makePathResolver(() => PATHS.uploads, { extensions: IMAGE_EXTENSIONS });const resolveUploadAudio = makePathResolver(() => PATHS.uploads, { extensions: UPLOAD_AUDIO_EXTENSIONS });-const JOB_TTL_MS = 60 * 60 * 1000;-const JOBS_MAX = 20;-const jobs = new Map();+// This process-local set distinguishes live work from persisted jobs left+// running by a previous server process. Those are marked interrupted when the+// gallery or job detail is next read.+const activeJobs = new Set();export function getCodeAnimationOptions() {return {@@ -277,27 +285,44 @@ export async function generateCodeAnimationBrief(input) {return { brief };}-// Drop settled jobs past their TTL, then the oldest settled ones past the cap.-// A running job is never evicted — its result would have nowhere to land.-function pruneJobs() {- const now = Date.now();- const settled = [...jobs.values()].filter((job) => job.status !== 'running')- .sort((a, b) => a.updatedAtMs - b.updatedAtMs);- let overflow = jobs.size - JOBS_MAX;- for (const job of settled) {- if (overflow > 0 || now - job.updatedAtMs > JOB_TTL_MS) {- jobs.delete(job.id);- overflow -= 1;- }- }+const jobTitle = (input) => input.title?.trim() || input.concept.slice(0, 120);++function summaryJob(job) {+ return {+ id: job.id,+ status: job.status,+ title: job.title,+ concept: job.concept || job.input?.concept || '',+ providerId: job.providerId,+ model: job.model,+ error: job.error,+ createdAt: job.createdAt,+ startedAt: job.startedAt,+ completedAt: job.completedAt,+ };}-const publicJob = ({ updatedAtMs: _updatedAtMs, ...job }) => job;+async function reconcileJob(job) {+ if (job.status !== 'running' || activeJobs.has(job.id)) return job;+ const now = new Date().toISOString();+ const interrupted = {+ ...job,+ status: 'failed',+ error: 'Generation was interrupted by a server restart',+ completedAt: now,+ updatedAt: now,+ };+ await saveCodeAnimationJobRecord(interrupted);+ return interrupted;+}-function settleJob(id, patch) {- const job = jobs.get(id);- if (!job) return;- jobs.set(id, { ...job, ...patch, completedAt: new Date().toISOString(), updatedAtMs: Date.now() });+export async function listCodeAnimationJobs() {+ const records = await listCodeAnimationJobRecords();+ return Promise.all(records.map(async (job) => {+ if (job.status !== 'running' || activeJobs.has(job.id)) return summaryJob(job);+ const record = await getCodeAnimationJobRecord(job.id);+ return record ? summaryJob(await reconcileJob(record)) : summaryJob(job);+ }));}async function runGeneration({ provider, model, effort, prompt, referencePaths }) {@@ -332,39 +357,81 @@ export async function startCodeAnimationGeneration(input) {throw new ServerError('Choose an enabled AI provider', { status: 400, code: 'PROVIDER_UNAVAILABLE' });}const built = await buildCodeAnimationRequest(input, { delivery: provider.type === 'api' ? 'api' : 'cli' });- pruneJobs();const id = randomUUID();const now = new Date().toISOString();- jobs.set(id, {+ const job = {id,status: 'running',+ title: jobTitle(input),+ input,providerId: provider.id,model: input.model || null,frame: built.frame,audioUrl: built.audioUrl,- html: null,+ prompt: built.copyPrompt,+ attachments: built.attachments,+ moodBoardId: built.moodBoardId,error: null,runId: null,+ createdAt: now,startedAt: now,completedAt: null,- updatedAtMs: Date.now(),+ updatedAt: now,+ };+ activeJobs.add(id);+ await saveCodeAnimationJobRecord(job).catch((error) => {+ activeJobs.delete(id);+ throw error;});console.log(`🎞️ Code animation generation ${id.slice(0, 8)} started on ${provider.id}`);runGeneration({ provider, model: input.model, effort: input.effort, prompt: built.prompt, referencePaths: built.referencePaths })- .then(({ html, provider: ranOn, model, runId }) => {- settleJob(id, { status: 'completed', html, providerId: ranOn, model, runId });+ .then(async ({ html, provider: ranOn, model, runId }) => {+ await saveCodeAnimationHtml(id, html);+ const completedAt = new Date().toISOString();+ await saveCodeAnimationJobRecord({+ ...job,+ status: 'completed',+ providerId: ranOn,+ model,+ runId,+ completedAt,+ updatedAt: completedAt,+ });+ activeJobs.delete(id);console.log(`✅ Code animation generation ${id.slice(0, 8)} completed (${html.length} chars)`);})- .catch((error) => {+ .catch(async (error) => {const message = String(error?.message || error || 'Generation failed').slice(0, 2_000);- settleJob(id, { status: 'failed', error: message });+ const completedAt = new Date().toISOString();+ const failed = { ...job, status: 'failed', error: message, completedAt, updatedAt: completedAt };+ await saveCodeAnimationJobRecord(failed).catch((persistError) => {+ console.error(`❌ Code animation generation ${id.slice(0, 8)} status could not be saved: ${persistError.message}`);+ });+ activeJobs.delete(id);console.error(`❌ Code animation generation ${id.slice(0, 8)} failed: ${message}`);});- return { ...publicJob(jobs.get(id)), prompt: built.copyPrompt, attachments: built.attachments, moodBoardId: built.moodBoardId };+ return job;}-export function getCodeAnimationJob(id) {- const job = jobs.get(id);- return job ? publicJob(job) : null;+export async function getCodeAnimationJob(id) {+ if (!isCodeAnimationJobId(id)) return null;+ const record = await getCodeAnimationJobRecord(id);+ if (!record) return null;+ let job = await reconcileJob(record);+ if (job.status !== 'completed') return { ...job, html: null };+ try {+ return { ...job, html: await readCodeAnimationHtml(job.id) };+ } catch (error) {+ if (error?.code !== 'CODE_ANIMATION_OUTPUT_MISSING') throw error;+ const completedAt = new Date().toISOString();+ job = {+ ...job,+ status: 'failed',+ error: 'Generated animation file is missing from this installation',+ completedAt,+ updatedAt: completedAt,+ };+ await saveCodeAnimationJobRecord(job);+ return { ...job, html: null };+ }}-diff --git a/server/services/codeAnimation/jobStore.js b/server/services/codeAnimation/jobStore.jsnew file mode 100644index 0000000000..ef74ec060e--- /dev/null+++ b/server/services/codeAnimation/jobStore.js@@ -0,0 +1,78 @@+/**+ * Durable Code Animation job records. PostgreSQL indexes the gallery metadata;+ * the generated HTML stays in its managed data directory as a file asset.+ */++import { readFile } from 'fs/promises';+import { join } from 'path';+import { query } from '../../lib/db.js';+import { PATHS } from '../../lib/paths.js';+import { atomicWrite } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';++const JOB_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;+const ANIMATIONS_DIR = join(PATHS.data, 'code-animations');++export function isCodeAnimationJobId(id) {+ return typeof id === 'string' && JOB_ID_RE.test(id);+}++function htmlPath(id) {+ if (!isCodeAnimationJobId(id)) {+ throw new ServerError('Code Animation job not found', { status: 404, code: 'NOT_FOUND' });+ }+ return join(ANIMATIONS_DIR, `${id}.html`);+}++export async function listCodeAnimationJobRecords() {+ const { rows } = await query(+ `SELECT id, status, title, concept, provider_id AS "providerId", model,+ created_at AS "createdAt"+ FROM code_animation_jobs+ ORDER BY created_at DESC, id DESC`,+ );+ return rows;+}++export async function getCodeAnimationJobRecord(id) {+ if (!isCodeAnimationJobId(id)) return null;+ const { rows } = await query('SELECT data FROM code_animation_jobs WHERE id = $1', [id]);+ return rows[0]?.data ?? null;+}++export async function saveCodeAnimationJobRecord(job) {+ await query(+ `INSERT INTO code_animation_jobs+ (id, status, title, concept, provider_id, model, data, created_at, updated_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8, $9)+ ON CONFLICT (id) DO UPDATE SET+ status = EXCLUDED.status,+ title = EXCLUDED.title,+ concept = EXCLUDED.concept,+ provider_id = EXCLUDED.provider_id,+ model = EXCLUDED.model,+ data = EXCLUDED.data,+ updated_at = EXCLUDED.updated_at`,+ [job.id, job.status, job.title, job.input?.concept || '', job.providerId, job.model, JSON.stringify(job), job.createdAt, job.updatedAt],+ );+ return job;+}++export async function saveCodeAnimationHtml(id, html) {+ const destination = htmlPath(id);+ await atomicWrite(destination, html);+}++export async function readCodeAnimationHtml(id) {+ try {+ return await readFile(htmlPath(id), 'utf8');+ } catch (error) {+ if (error?.code === 'ENOENT') {+ throw new ServerError('The generated animation file is missing', {+ status: 500,+ code: 'CODE_ANIMATION_OUTPUT_MISSING',+ });+ }+ throw error;+ }+}