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
expose the TRELLIS.2 full-resolution mesh and keep it out of backups
Adam Eivy59e49d61d640
diff --git a/client/src/pages/Media3DDetail.jsx b/client/src/pages/Media3DDetail.jsxindex 74b0ea73c1..2c19d05c04 100644--- a/client/src/pages/Media3DDetail.jsx+++ b/client/src/pages/Media3DDetail.jsx@@ -1,7 +1,7 @@import { useCallback, useEffect, useRef, useState } from 'react';import { Link, useNavigate, useParams } from 'react-router';import { ArrowLeft, Boxes, AlertTriangle, Loader2, RefreshCw, Trash2 } from 'lucide-react';-import { getImageTo3dModel, generateImageTo3dModel, deleteImageTo3dModel, imageTo3dAssetUrl } from '../services/api';+import { getImageTo3dModel, generateImageTo3dModel, deleteImageTo3dModel, imageTo3dAssetUrl, imageTo3dFullMeshUrl } from '../services/api';import useMounted from '../hooks/useMounted';import { useAutoRefetch } from '../hooks/useAutoRefetch';import { timeAgo } from '../utils/formatters';@@ -208,11 +208,23 @@ export default function Media3DDetail() {<div><span className="mb-1 block text-xs text-gray-400">Mesh</span>{record.status === 'ready' && record.assetPath ? (- <GlbViewer- src={meshSrc}- downloadHref={imageTo3dAssetUrl(record.id)}- forceOpaque- />+ <>+ <GlbViewer+ src={meshSrc}+ downloadHref={imageTo3dAssetUrl(record.id)}+ forceOpaque+ />+ {/* The viewer loads the decimated GLB because that is what a browser+ can render; the decoder's full mesh is an order of magnitude+ larger. Offer it, but say what it actually is so nobody downloads+ several hundred MB expecting a textured model. */}+ <a+ href={imageTo3dFullMeshUrl(record.id)}+ className="mt-2 inline-block text-xs text-gray-400 underline decoration-dotted hover:text-gray-200"+ >+ Download full-resolution mesh (.obj — geometry only, no textures)+ </a>+ </>) : (<div className="flex aspect-square items-center justify-center rounded-xl border border-dashed border-port-border bg-port-bg text-center text-sm text-gray-500">{isGenerating ? (diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 19a25fb343..379e618971 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -107,7 +107,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `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). || `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. || `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. |+| `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 and the full-resolution OBJ download URL. || `apiPipeline.js` | Pipeline (issues + stages + canon). || `apiUniverseBuilder.js` | Universe Builder (generate + edit + commit). || `apiAuthors.js` | Author personas (name, writing style, bio, headshot description/style). |diff --git a/client/src/services/apiImageTo3d.js b/client/src/services/apiImageTo3d.jsindex 80dade006c..41b3ba79f1 100644--- a/client/src/services/apiImageTo3d.js+++ b/client/src/services/apiImageTo3d.js@@ -42,3 +42,11 @@ export const deleteImageTo3dModel = (id, options) =>// GlbViewer renders; this URL is for an explicit "download the file" action.export const imageTo3dAssetUrl = (id) =>`/api/image-to-3d/models/${encodeURIComponent(id)}/asset`;++// The decoder's pre-decimation mesh, as written by upstream `generate.py` next to+// the GLB. A separate endpoint rather than a query on `asset` because it is a+// different artifact: plain `v`/`f` OBJ with no UVs, normals or material, often+// several hundred MB, and absent on renders that never wrote the sidecar (a plain+// 404 — not a sign the record is broken). The GLB stays the thing the viewer loads.+export const imageTo3dFullMeshUrl = (id) =>+ `/api/image-to-3d/models/${encodeURIComponent(id)}/full-mesh`;diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.jsindex f7686e75f1..b9bf847dab 100644--- a/server/routes/imageTo3d.js+++ b/server/routes/imageTo3d.js@@ -12,6 +12,7 @@ import {startGeneration,deleteModel,getModelAsset,+ getModelFullMesh,} from '../services/imageTo3d/models.js';import {RENDER_STEPS_MIN, RENDER_STEPS_MAX, RENDER_SEED_MAX,@@ -268,14 +269,22 @@ router.post('/models', asyncHandler(async (req, res) => {res.status(202).json(withRenderSupport(model));}));-router.get('/models/:id/asset', asyncHandler(async (req, res) => {- const { path, filename } = await getModelAsset(req.params.id);- res.set('Content-Type', 'model/gltf-binary');+/**+ * Stream a resolved mesh file as an attachment.+ *+ * Shared by the GLB and full-mesh OBJ downloads: the error handling below is the+ * whole reason this is a function rather than two copies. The 'error' event fires+ * OUTSIDE the asyncHandler promise chain, so a throw there would crash the+ * process — it has to go through sendErrorResponse (shared envelope ++ * headers-sent guard).+ *+ * @param {import('express').Response} res+ * @param {{path: string, filename: string}} file+ * @param {string} contentType+ */+function streamMeshDownload(res, { path, filename }, contentType) {+ res.set('Content-Type', contentType);res.set('Content-Disposition', `attachment; filename="${filename}"`);- // The 'error' event fires outside the asyncHandler promise chain, so a throw- // here would crash the process — route it through sendErrorResponse (the shared- // envelope + headers-sent guard) instead. A file removed between the readiness- // check and the stream just 404s the download.const stream = createReadStream(path);stream.on('error', (err) => {console.warn(`⚠️ Image-to-3D asset stream error: ${err.code || err.message}`);@@ -285,13 +294,25 @@ router.get('/models/:id/asset', asyncHandler(async (req, res) => {if (res.headersSent) {res.destroy(err);} else {- // Drop the GLB download headers set above so the JSON error body isn't- // offered to the browser as a "<name>.glb" attachment.+ // Drop the download headers set above so the JSON error body isn't offered+ // to the browser as an attachment named like a mesh file.res.removeHeader('Content-Disposition');sendErrorResponse(res, new ServerError('Mesh file not found', { status: 404, code: 'ASSET_MISSING' }));}});stream.pipe(res);+}++router.get('/models/:id/asset', asyncHandler(async (req, res) => {+ streamMeshDownload(res, await getModelAsset(req.params.id), 'model/gltf-binary');+}));++// The decoder's pre-decimation mesh. Registered before `/models/:id` so the more+// specific path wins, and kept off `/asset` because it is a different artifact+// with a different failure mode (see getModelFullMesh) rather than a variant of+// the served GLB.+router.get('/models/:id/full-mesh', asyncHandler(async (req, res) => {+ streamMeshDownload(res, await getModelFullMesh(req.params.id), 'model/obj');}));router.get('/models/:id', asyncHandler(async (req, res) => {diff --git a/server/routes/imageTo3d.test.js b/server/routes/imageTo3d.test.jsindex a95e18877c..ba5a439604 100644--- a/server/routes/imageTo3d.test.js+++ b/server/routes/imageTo3d.test.js@@ -73,6 +73,7 @@ vi.mock('../services/imageTo3d/models.js', () => ({startGeneration: vi.fn(),deleteModel: vi.fn(),getModelAsset: vi.fn(),+ getModelFullMesh: vi.fn(),}));import * as targets from '../services/imageTo3d/targets.js';@@ -493,4 +494,35 @@ describe('image-to-3d model records', () => {const res = await request(makeApp()).get('/api/image-to-3d/models/image3d-1/asset');expect(res.status).toBe(409);});++ it('GET /models/:id/full-mesh streams the pre-decimation OBJ', async () => {+ const tmp = join(tmpdir(), `it-full-${process.pid}.obj`);+ await writeFile(tmp, 'v 0 0 0\nf 1 1 1\n');+ models.getModelFullMesh.mockResolvedValue({ path: tmp, filename: 'beacon-full.obj' });+ const res = await request(makeApp()).get('/api/image-to-3d/models/image3d-1/full-mesh');+ expect(res.status).toBe(200);+ expect(res.headers['content-type']).toMatch(/model\/obj/);+ expect(res.headers['content-disposition']).toMatch(/beacon-full\.obj/);+ await rm(tmp, { force: true });+ });++ it('GET /models/:id/full-mesh 404s when the sidecar was never written', async () => {+ // A missing OBJ is NOT a broken record — older renders simply have none, so it+ // must not read as the model being unavailable.+ const { ServerError } = await import('../lib/errorHandler.js');+ models.getModelFullMesh.mockRejectedValue(+ new ServerError('no full mesh', { status: 404, code: 'FULL_MESH_MISSING' }),+ );+ const res = await request(makeApp()).get('/api/image-to-3d/models/image3d-1/full-mesh');+ expect(res.status).toBe(404);+ expect(res.body?.error?.code || res.body?.code).toBe('FULL_MESH_MISSING');+ });++ it('does not let /full-mesh be swallowed by the /models/:id route', async () => {+ // Route-order regression: `/models/:id` would happily match `full-mesh` as an+ // id and return JSON instead of a download.+ models.getModelFullMesh.mockRejectedValue(new Error('boom'));+ await request(makeApp()).get('/api/image-to-3d/models/image3d-1/full-mesh');+ expect(models.getModelFullMesh).toHaveBeenCalledWith('image3d-1');+ });});diff --git a/server/services/backup.js b/server/services/backup.jsindex 0105f15f80..4a2f16cfb5 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -69,7 +69,18 @@ export const DEFAULT_EXCLUDES = [// frames, strips, manifests, and runtime atlases ARE backed up. `runs/` is// the live (vendor-neutral) layout; `grok/` covers pre-migration-202 runs.{ path: '/sprites/*/grok/*/generated/raw/', reason: 'Sprite walk-run raw extracted frames — regenerable from the archived source video', overridable: true },- { path: '/sprites/*/runs/*/generated/raw/', reason: 'Imported sprite-run raw extracted frames — regenerable from the archived source video', overridable: true }+ { path: '/sprites/*/runs/*/generated/raw/', reason: 'Imported sprite-run raw extracted frames — regenerable from the archived source video', overridable: true },+ // Anchored with a leading `/` like every entry here — an unanchored `model.obj`+ // would match at any depth and silently drop unrelated user data.+ //+ // TRELLIS.2's `generate.py` writes this full-resolution OBJ next to the GLB it+ // exports: the decoder's mesh before bake-time decimation, measured at 930 MB /+ // 22.7M faces for one 1024_cascade render. It is regenerable by re-rendering the+ // same source at the same seed, it is not what the 3D page loads (that is+ // model.glb, which IS backed up), and at ~1 GB per render it would otherwise+ // dominate every snapshot. Overridable, because it is the only copy of the+ // discarded detail and someone archiving finished work may want it.+ { path: '/image-to-3d/*/model.obj', reason: 'TRELLIS.2 full-resolution mesh sidecar — ~1 GB per render, regenerable by re-rendering at the same seed. The exported model.glb and keyed source ARE backed up.', overridable: true }// NOTE: legacy file→Postgres migration artifacts (`.imported` / `.bak-NNN`)// are intentionally NOT excluded here. They are deleted on disk by the// boot-time prune (pruneImportedLegacyFiles.js) the same boot the migrationdiff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex 596f73b5f1..a5ac66df5d 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -109,6 +109,38 @@ const flush = () => new Promise((r) => setTimeout(r, 0));const overridable = DEFAULT_EXCLUDES.filter(e => e.overridable).map(e => e.path);const nonOverridable = DEFAULT_EXCLUDES.filter(e => !e.overridable).map(e => e.path);+describe('DEFAULT_EXCLUDES anchoring', () => {+ // These are rsync FILTER patterns, not globs: an unanchored pattern matches at+ // ANY depth, so `model.obj` would drop a file of that name anywhere under data/.+ // That is a silent data-loss bug rather than a style nit, which is why it gets a+ // test rather than a convention.+ it('anchors every default exclude at the data root', () => {+ const unanchored = DEFAULT_EXCLUDES.filter((e) => !e.path.startsWith('/'));+ expect(unanchored.map((e) => e.path)).toEqual([]);+ });++ it('gives every default exclude a reason a user can act on', () => {+ // The reason string is surfaced in the backup UI; a blank one makes an+ // overridable exclude undecidable for whoever is looking at the toggle.+ for (const entry of DEFAULT_EXCLUDES) {+ expect(entry.reason, entry.path).toBeTruthy();+ expect(typeof entry.overridable, entry.path).toBe('boolean');+ }+ });++ it('excludes the TRELLIS.2 full-resolution mesh sidecar, overridably', () => {+ // ~1 GB per render of a file PortOS never serves. Overridable because it is+ // the only copy of the geometry the bake decimation discards.+ const entry = DEFAULT_EXCLUDES.find((e) => e.path === '/image-to-3d/*/model.obj');+ expect(entry).toBeDefined();+ expect(entry.overridable).toBe(true);+ // Scoped to the sidecar only — the served GLB and keyed source stay backed up.+ const paths = DEFAULT_EXCLUDES.map((e) => e.path);+ expect(paths).not.toContain('/image-to-3d/');+ expect(paths.some((x) => x.includes('model.glb'))).toBe(false);+ });+});+describe('computeEffectiveExcludes', () => {it('includes every DEFAULT_EXCLUDES path when nothing is disabled', () => {const result = computeEffectiveExcludes({ excludePaths: [], disabledDefaultExcludes: [] });diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.jsindex 2c19934932..2ec037359c 100644--- a/server/services/imageTo3d/models.js+++ b/server/services/imageTo3d/models.js@@ -17,7 +17,7 @@import { randomUUID } from 'crypto';import { join } from 'node:path';-import { rm } from 'node:fs/promises';+import { rm, access } from 'node:fs/promises';import { ServerError } from '../../lib/errorHandler.js';import { PATHS, resolveGalleryImage, ensureDir } from '../../lib/fileUtils.js';import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';@@ -40,6 +40,9 @@ const activeOperations = new Set();// spawns (executeRender) and drained in its `finally`.const activeRenders = new Map();+/** Injectable existence probe — `access` resolves/rejects rather than returning. */+const pathExists = (p) => access(p).then(() => true, () => false);+const trimRuns = (runs) => runs.slice(-MAX_RUNS);const cleanError = (error) => String(error?.message || error || 'Render failed').slice(0, 2_000);@@ -49,6 +52,17 @@ const assetUrl = (id) => `/data/image-to-3d/${id}/model.glb`;const recordDir = (id) => join(PATHS.imageTo3d, id);/** The on-disk destination the runner writes the GLB to. */const assetDiskPath = (id) => join(recordDir(id), 'model.glb');+/**+ * The full-resolution mesh `generate.py` writes alongside the GLB.+ *+ * This is the decoder's mesh BEFORE the bake-time decimation — 22.7M faces on a+ * `1024_cascade` render where the GLB carries ~1M — so it is the only place the+ * discarded detail still exists. It is plain `v`/`f` OBJ: no UVs, no normals, no+ * material, and often several hundred MB. That is why it is a separate download+ * rather than the served asset: the 3D page has to load something a browser can+ * actually render.+ */+const fullMeshDiskPath = (id) => join(recordDir(id), 'model.obj');/** Where a background-keyed copy of the source lands (never the gallery file). */const keyedSourcePath = (id) => join(recordDir(id), 'source-keyed.png');@@ -380,6 +394,34 @@ export async function getModelAsset(id) {return { path: assetDiskPath(id), filename: `${slugifyForFilename(model.name)}.glb` };}+/**+ * Resolve a ready record's full-resolution OBJ for download.+ *+ * Separate from `getModelAsset` because its absence is NOT an error state of the+ * record: every readiness check the GLB passes can pass while the OBJ is missing,+ * since it is an upstream side-effect file rather than something PortOS's pipeline+ * guarantees. A render from before this was exposed, a `--no-texture` run, or an+ * upstream that stops writing it all land here — and each is a plain 404 on the+ * download, not a sign the model is broken. Hence the explicit `exists` probe+ * rather than reusing the record's `status`.+ */+export async function getModelFullMesh(id, { exists = pathExists } = {}) {+ const model = await store.getModel(id);+ if (!model) throw new ServerError('Image-to-3D model not found', { status: 404, code: 'NOT_FOUND' });+ if (model.status !== 'ready' || !model.assetPath) {+ throw new ServerError('This model has no generated mesh yet', { status: 409, code: 'MODEL_NOT_READY' });+ }+ const path = fullMeshDiskPath(id);+ if (!await exists(path)) {+ throw new ServerError(+ 'This render has no full-resolution mesh on disk. Only renders that kept the '+ + 'upstream OBJ sidecar have one; re-render to produce it.',+ { status: 404, code: 'FULL_MESH_MISSING' },+ );+ }+ return { path, filename: `${slugifyForFilename(model.name)}-full.obj` };+}+export async function recoverInterruptedModels() {const result = await store.recoverInterruptedModels();if (result.recovered > 0) {diff --git a/server/services/imageTo3d/models.test.js b/server/services/imageTo3d/models.test.jsindex fadceb3d73..9a27bea8dd 100644--- a/server/services/imageTo3d/models.test.js+++ b/server/services/imageTo3d/models.test.js@@ -72,7 +72,7 @@ import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';import { prepareSourceImage } from './sourceKeying.js';import * as store from './db.js';import {- createModel, startGeneration, getModelAsset, recoverInterruptedModels, deleteModel,+ createModel, startGeneration, getModelAsset, getModelFullMesh, recoverInterruptedModels, deleteModel,} from './models.js';const draftRecord = () => ({@@ -292,6 +292,45 @@ describe('image-to-3D model orchestration', () => {expect(posixPath(asset.path)).toMatch(/image-to-3d\/image3d-example\/model\.glb$/);expect(asset.filename).toBe('my-beacon.glb');});++ describe('getModelFullMesh', () => {+ const ready = () => ({+ ...draftRecord(),+ status: 'ready',+ name: 'My Beacon',+ assetPath: '/data/image-to-3d/image3d-example/model.glb',+ });++ it('returns the OBJ sidecar when it is on disk', async () => {+ store.getModel.mockResolvedValueOnce(ready());+ const mesh = await getModelFullMesh('image3d-example', { exists: async () => true });+ expect(posixPath(mesh.path)).toMatch(/image-to-3d\/image3d-example\/model\.obj$/);+ expect(mesh.filename).toBe('my-beacon-full.obj');+ });++ it('404s when the sidecar was never written, rather than claiming the record is broken', async () => {+ // Every readiness check the GLB passes can pass while the OBJ is absent — it+ // is an upstream side-effect file, not something the pipeline guarantees. So+ // this has to be its own probe rather than a read of `status`.+ store.getModel.mockResolvedValueOnce(ready());+ await expect(getModelFullMesh('image3d-example', { exists: async () => false }))+ .rejects.toMatchObject({ status: 404, code: 'FULL_MESH_MISSING' });+ });++ it('409s before a render has produced anything, without probing disk', async () => {+ store.getModel.mockResolvedValueOnce({ ...draftRecord(), status: 'generating' });+ const exists = vi.fn(async () => true);+ await expect(getModelFullMesh('image3d-example', { exists }))+ .rejects.toMatchObject({ status: 409, code: 'MODEL_NOT_READY' });+ expect(exists).not.toHaveBeenCalled();+ });++ it('404s on an unknown record', async () => {+ store.getModel.mockResolvedValueOnce(null);+ await expect(getModelFullMesh('nope', { exists: async () => true }))+ .rejects.toMatchObject({ status: 404, code: 'NOT_FOUND' });+ });+ });});describe('render options and source keying', () => {