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

refactor(media): simplify pass — shared status map, useAutoRefetch poll, reactive record updates, server-owned .glb download (#2953)

[._.]/ Adam Eivy99b9cef5f542
diff --git a/PLAN.md b/PLAN.md
index 4a093008ef..d7a8a81f2b 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -315,3 +315,7 @@ is not reliably announced.
- [ ] `scripts/migrations/206-claude-default-opus-5.js` is the fourth hand-copy of the same shape (032 → 058 → 153 → 206): `diff 153-claude-default-sonnet-5.js 206-claude-default-opus-5.js` is identical apart from the data and comment prose — `POINTER_KEYS`, `sameArray`, the pointer-swap helper, and the entire `up()` body (read → ENOENT skip → `JSON.parse` guard → providers-map guard → three-way `touched`/`alreadyCurrent`/`customized` classification → conditional write → log) are byte-for-byte the same. Their co-located test files are ~200 structurally identical lines each. `scripts/migrations/_lib.js` is the documented home for exactly this — it already exports `makePromptReplaceMigration` ("every one from 003 onward collapses onto ~50 lines") and `makeSplitMigration` ("034/035/036/059 share the same skeleton and differ only in a handful of config values"), with `_testHelpers.js#runPromptMigrationTests` supplying the shared test cases. Add a `makeSeededProviderTierMigration({ targets, tierLabel })` plus a matching shared test runner so the *next* model bump is a ~25-line data table instead of ~370 re-cloned lines. Skipped in the opus-5 PR because migrations are append-only and frozen (a shipped migration must keep working against the shape it was written for), so this pays off from the migration *after* 206 forward and should not retro-edit 032/058/153 — which put it well outside that diff. Surfaced by two independent `/simplify` reviewers on the opus-5 change.
- [ ] `server/lib/modelPricing.js` — all five `claude-opus-*` rows in `EXACT_RATES` carry an identical `[5.0, 25.0]`, so the `{ test: /opus/i, rateModel: '<latest opus>' }` line in `FAMILY_RULES` must be re-pointed at every model bump for zero behavioral effect (it only relabels the reported `rateModel` for *unrecognized* opus ids). A shared `const OPUS_TIER_RATES = [5.0, 25.0]`, or letting a family rule yield rates directly instead of pointing at a peer `EXACT_RATES` key, would retire that per-bump edit. Low value, listed for completeness.
+
+### Migrate the bespoke gallery-upload callers onto `GalleryImagePicker allowUpload`
+
+- [ ] `client/src/components/imageGen/GalleryImagePicker.jsx` gained an `allowUpload` prop (#2953) that encapsulates the file → `readFileAsBase64` → `uploadGalleryImage` → normalize → select flow inside the shared picker. Three existing callers still roll their own upload path with a separate file `<input>` + `toast` alongside the picker: `client/src/components/music/AlbumsManager.jsx:177`, `client/src/components/music/ArtistsManager.jsx:147`, and `client/src/pages/Authors.jsx:167`. Migrate each to `<GalleryImagePicker allowUpload>` and delete the bespoke upload handlers so the duplication the prop was designed to end actually collapses. Deferred from #2953 (adjacent files outside that issue's scope). Surfaced by the /simplify altitude review.
diff --git a/client/src/components/media/GlbViewer.jsx b/client/src/components/media/GlbViewer.jsx
index a280ea150e..83f0588636 100644
--- a/client/src/components/media/GlbViewer.jsx
+++ b/client/src/components/media/GlbViewer.jsx
@@ -26,9 +26,16 @@ function GlbModel({ src }) {
return <primitive object={scene} />;
}
-export default function GlbViewer({ src, downloadName, className = '' }) {
+// `downloadHref` (optional) overrides where the Download button points — pass a
+// dedicated asset endpoint that sets its own `Content-Disposition` filename, so
+// the server owns the name instead of the client re-deriving it. Falls back to
+// `src` with a filename inferred from the URL.
+export default function GlbViewer({ src, downloadHref, downloadName, className = '' }) {
if (!src) return null;
- const download = downloadName || filenameFromSrc(src);
+ const href = downloadHref || src;
+ // With an explicit download endpoint the server's Content-Disposition wins, so
+ // a bare `download` attribute is enough; otherwise infer a name from the URL.
+ const download = downloadHref ? '' : (downloadName || filenameFromSrc(src));
return (
<div className={`overflow-hidden rounded-xl border border-port-border bg-port-bg ${className}`}>
<div className="relative aspect-square w-full">
@@ -52,7 +59,7 @@ export default function GlbViewer({ src, downloadName, className = '' }) {
<Rotate3d className="h-3.5 w-3.5" /> Drag to orbit · scroll to zoom
</span>
<a
- href={src}
+ href={href}
download={download}
className="inline-flex items-center gap-1.5 rounded-md bg-port-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-blue-600"
>
diff --git a/client/src/components/media/imageTo3dStatus.js b/client/src/components/media/imageTo3dStatus.js
new file mode 100644
index 0000000000..bbb35a446e
--- /dev/null
+++ b/client/src/components/media/imageTo3dStatus.js
@@ -0,0 +1,18 @@
+// Single source of truth for the image-to-3D record status enum's display.
+// The server owns the status values (`server/services/imageTo3d/` — draft →
+// generating → ready | failed | canceled); this maps each to one label +
+// text-color className so the list card (Media3D) and the detail view
+// (Media3DDetail) can't drift out of sync (they already had, before this).
+// Mirrors the `sceneStatus.js` precedent for the creative-director runner.
+
+export const IMAGE_TO_3D_STATUS = Object.freeze({
+ ready: { label: 'Ready', className: 'text-port-success' },
+ generating: { label: 'Rendering on-device…', className: 'text-port-accent' },
+ draft: { label: 'Queued', className: 'text-gray-400' },
+ failed: { label: 'Render failed', className: 'text-port-error' },
+ canceled: { label: 'Canceled', className: 'text-gray-500' },
+});
+
+// Resolve a record's status to its display meta, falling back to `draft` for an
+// unknown/absent status so callers never render an empty label.
+export const imageTo3dStatusMeta = (status) => IMAGE_TO_3D_STATUS[status] || IMAGE_TO_3D_STATUS.draft;
diff --git a/client/src/pages/Media3D.jsx b/client/src/pages/Media3D.jsx
index afdadeee3d..318445d28e 100644
--- a/client/src/pages/Media3D.jsx
+++ b/client/src/pages/Media3D.jsx
@@ -9,6 +9,7 @@ import RuntimeInstallModal from '../components/install/RuntimeInstallModal';
import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';
import GlbViewer from '../components/media/GlbViewer';
import MediaImage from '../components/MediaImage';
+import { imageTo3dStatusMeta } from '../components/media/imageTo3dStatus';
// Poll cadence while a render is in flight (a real TRELLIS.2 render is multi-minute).
const POLL_INTERVAL_MS = 2500;
@@ -60,15 +61,6 @@ const REASON_LABEL = {
'unknown-target': 'Unavailable',
};
-// Per-record status pill for the "Your 3D models" library grid.
-const RECORD_STATUS = {
- ready: { label: 'Ready', className: 'text-port-success' },
- generating: { label: 'Rendering…', className: 'text-port-accent' },
- draft: { label: 'Queued', className: 'text-gray-400' },
- failed: { label: 'Failed', className: 'text-port-error' },
- canceled: { label: 'Canceled', className: 'text-gray-500' },
-};
-
const LANE_LABEL = {
'local-mps': 'Runs on-device (Apple Silicon)',
'local-cuda': 'Runs on-device (CUDA)',
@@ -192,6 +184,15 @@ export default function Media3D() {
.catch(() => { /* the library section just stays empty on a transient failure */ });
}, [mountedRef]);
+ // Reactively fold a created/updated record into the library instead of
+ // re-fetching the whole list (we already hold the fresh row).
+ const patchRecord = useCallback((record) => {
+ if (!record?.id || !mountedRef.current) return;
+ setRecords((prev) => (prev.some((r) => r.id === record.id)
+ ? prev.map((r) => (r.id === record.id ? { ...r, ...record } : r))
+ : [record, ...prev]));
+ }, [mountedRef]);
+
useEffect(() => { load(); }, [load]);
useEffect(() => { loadRecords(); }, [loadRecords]);
@@ -245,14 +246,17 @@ export default function Media3D() {
if (!mountedRef.current) return;
const latest = Array.isArray(model.runs) && model.runs.length ? model.runs[model.runs.length - 1] : null;
if (Number.isFinite(latest?.percent)) setGenPercent(latest.percent);
+ // Patch the just-polled record into the library in place — we already hold
+ // the fresh row, so re-fetching the whole list would be wasted I/O (the
+ // repo's reactive-update convention).
if (model.status === 'ready' && model.assetPath) {
- setGenPercent(100); setParam('glb', model.assetPath); setGenerating(false); loadRecords();
+ setGenPercent(100); setParam('glb', model.assetPath); setGenerating(false); patchRecord(model);
} else if (model.status === 'failed' || model.status === 'canceled') {
// model.error carries the runner's actionable message (e.g. the HF-auth guidance).
- setGenError(model.error || 'The render did not finish.'); setGenerating(false); loadRecords();
+ setGenError(model.error || 'The render did not finish.'); setGenerating(false); patchRecord(model);
}
// else still draft/generating → the hook re-polls after POLL_INTERVAL_MS.
- }, [modelId, setParam, mountedRef, loadRecords]);
+ }, [modelId, setParam, mountedRef, patchRecord]);
useAutoRefetch(pollTick, POLL_INTERVAL_MS, { pollOnly: true, enabled: generating && !!modelId });
@@ -267,8 +271,8 @@ export default function Media3D() {
if (mountedRef.current) setGenError(err?.message || 'Could not start the render.');
return null;
});
- if (created && mountedRef.current) { setModelId(created.id); setGenerating(true); loadRecords(); }
- }, [selectedImage, selectedTarget, setParam, mountedRef, loadRecords]);
+ if (created && mountedRef.current) { setModelId(created.id); setGenerating(true); patchRecord(created); }
+ }, [selectedImage, selectedTarget, setParam, mountedRef, patchRecord]);
// Why the Generate action is blocked, or null when it's ready to run. The runner
// (POST create → on-device render → landed .glb) is wired, so the terminal state
@@ -394,7 +398,7 @@ export default function Media3D() {
<h2 className="mb-2 text-xs font-medium uppercase tracking-wide text-gray-400">Your 3D models</h2>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4">
{records.map((record) => {
- const status = RECORD_STATUS[record.status] || RECORD_STATUS.draft;
+ const status = imageTo3dStatusMeta(record.status);
return (
<Link
key={record.id}
diff --git a/client/src/pages/Media3DDetail.jsx b/client/src/pages/Media3DDetail.jsx
index 9fdd710695..d214ee78d4 100644
--- a/client/src/pages/Media3DDetail.jsx
+++ b/client/src/pages/Media3DDetail.jsx
@@ -1,30 +1,19 @@
import { useCallback, useEffect, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { ArrowLeft, Boxes, AlertTriangle, Loader2, RefreshCw, Trash2 } from 'lucide-react';
-import { getImageTo3dModel, generateImageTo3dModel, deleteImageTo3dModel } from '../services/api';
+import { getImageTo3dModel, generateImageTo3dModel, deleteImageTo3dModel, imageTo3dAssetUrl } from '../services/api';
import useMounted from '../hooks/useMounted';
+import { useAutoRefetch } from '../hooks/useAutoRefetch';
import { timeAgo } from '../utils/formatters';
import GlbViewer from '../components/media/GlbViewer';
import MediaImage from '../components/MediaImage';
import InlineConfirmRow from '../components/ui/InlineConfirmRow';
+import { imageTo3dStatusMeta } from '../components/media/imageTo3dStatus';
import toast from '../components/ui/Toast';
-// Friendly `.glb` download filename from the record name (mirrors the server's
-// slugifyForFilename so the download matches the asset endpoint's attachment).
-const slugifyName = (s) =>
- String(s || 'model').toLowerCase().trim().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 64) || 'model';
-
// Poll cadence while a render is in flight (a real TRELLIS.2 render is multi-minute).
const POLL_INTERVAL_MS = 2500;
-const STATUS_LABEL = {
- ready: 'Ready',
- generating: 'Rendering on-device…',
- draft: 'Queued',
- failed: 'Render failed',
- canceled: 'Canceled',
-};
-
// Per-record detail view for an image-to-3D model (`/media/3d/:id`). The record
// id is the URL, so a finished mesh is a shareable, reload-safe deep link. Mounts
// the reusable GlbViewer once the render lands (status `ready` + `assetPath`),
@@ -52,12 +41,13 @@ export default function Media3DDetail() {
useEffect(() => { load({ initial: true }); }, [load]);
- // Poll only while generating; a terminal state stops the interval.
- useEffect(() => {
- if (record?.status !== 'generating') return undefined;
- const handle = setInterval(() => { void load(); }, POLL_INTERVAL_MS);
- return () => clearInterval(handle);
- }, [record?.status, load]);
+ // Poll only while generating (the initial fetch above owns the first load, so
+ // immediate:false); `load` owns its own state + error handling, so pollOnly.
+ useAutoRefetch(load, POLL_INTERVAL_MS, {
+ pollOnly: true,
+ immediate: false,
+ enabled: record?.status === 'generating',
+ });
const handleRegenerate = useCallback(async () => {
if (busy || record?.status === 'generating') return;
@@ -100,7 +90,6 @@ export default function Media3DDetail() {
const isGenerating = record.status === 'generating';
const latestRun = Array.isArray(record.runs) && record.runs.length ? record.runs[record.runs.length - 1] : null;
const percent = Number.isFinite(latestRun?.percent) ? Math.round(latestRun.percent) : null;
- const downloadName = `${slugifyName(record.name)}.glb`;
return (
<div className="mx-auto max-w-4xl">
@@ -132,7 +121,7 @@ export default function Media3DDetail() {
</div>
</div>
<p className="mt-1 text-xs text-gray-500">
- {STATUS_LABEL[record.status] || record.status}
+ {imageTo3dStatusMeta(record.status).label}
{isGenerating && percent !== null ? ` · ${percent}%` : ''} · updated {timeAgo(record.updatedAt)}
</p>
</header>
@@ -165,7 +154,7 @@ export default function Media3DDetail() {
<div>
<span className="mb-1 block text-xs text-gray-400">Mesh</span>
{record.status === 'ready' && record.assetPath ? (
- <GlbViewer src={record.assetPath} downloadName={downloadName} />
+ <GlbViewer src={record.assetPath} downloadHref={imageTo3dAssetUrl(record.id)} />
) : (
<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/pages/Media3DDetail.test.jsx b/client/src/pages/Media3DDetail.test.jsx
index b8d80aa2d9..f7d613a54d 100644
--- a/client/src/pages/Media3DDetail.test.jsx
+++ b/client/src/pages/Media3DDetail.test.jsx
@@ -10,6 +10,7 @@ vi.mock('../services/api', () => ({
getImageTo3dModel: (...a) => getImageTo3dModel(...a),
generateImageTo3dModel: (...a) => generateImageTo3dModel(...a),
deleteImageTo3dModel: (...a) => deleteImageTo3dModel(...a),
+ imageTo3dAssetUrl: (id) => `/api/image-to-3d/models/${id}/asset`,
}));
// GlbViewer wraps a WebGL canvas jsdom can't render — stub to a marker echoing src.