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

feat(media): finish image-to-3D workspace with upload picker, detail route, and record library (#2953)

[._.]/ Adam Eivy87e47e4f2246
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ff036ed27b..af627a69a6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -159,3 +159,4 @@
- **Render the sprite turnaround sheet as a large square instead of a wasteful strip** — the locked "identity root" turnaround preview in the Reference workflow used a fixed 192×128 landscape box, but the sheet is a square PNG (four figures in a 1:1 canvas); `object-contain` letterboxed it into a ~128px center strip and wasted the sides. It now renders as a large responsive square (`w-full max-w-sm aspect-square`, stacking the "frozen · identity root" caption below it on mobile), so the four-view sheet is shown as big as its column allows. The candidate thumbnails and locked directional-anchor previews (also square PNGs previously fit into short `h-24` boxes) switch to `aspect-square` too, so every reference image in the panel fills its cell instead of floating in a center band.
- **[claude-default-opus-5] Default Claude CLI/TUI and Bedrock providers now use `claude-opus-5`.** The seeded `claude-code`, `claude-code-tui`, `claude-code-bedrock`, and `claude-code-tui-bedrock` providers ship the new opus tier as their default/heavy model (`claude-opus-5`; Bedrock: `global.anthropic.claude-opus-5[1m]`), and `claude-opus-5` leads the Anthropic API model-refresh list. The Bedrock `[1m]` long-context variant is carried forward and mapped like-for-like — a box pinned to `…opus-4-8[1m]` lands on `…opus-5[1m]`, one pinned to the plain id lands on the plain id — so the bump never silently changes which context tier a Bedrock request asks for. `data.reference/providers.json`, the aiToolkit sample defaults, and the PortOS scaffolder are updated together, and migration `206-claude-default-opus-5.js` rewrites existing installs' `data/providers.json` on the next `update.sh` — conservatively, matching migration 058/153: only an exact match on the prior seeded model list is rewritten (a curated list is left alone), a tier pointer still parked on a now-absent opus-4-8 id is repaired on its own, and still-current haiku/sonnet pins are preserved. `claude-opus-5` is added to the usage cost table at Opus-tier rates ($5/$25 per MTok), and the `/opus/i` family rule now reports it as the tier's rate anchor.
- **[issue-2991] Support portless desktop managed processes and an app→sprite reverse lookup** — a managed app can now describe a GUI/desktop process (`type: 'desktop'`, e.g. a Godot game binary) with no HTTP port, and the port-dependent surfaces degrade gracefully instead of faking a port. Start now launches a desktop app from its own `startCommands` with PM2 `autorestart` OFF (a window closing is a normal exit, not a crash to loop on — `startWithCommand` gained an `{ autorestart }` option), skips the web-server ecosystem path, and refuses to spawn a second instance when the process is already online. Status reports from the supervisor alone (a clean quit renders as *stopped*, never "unreachable"), and the null-tolerant reserved-port collection already excludes absent ports. The "Open UI" launcher stays hidden for a portless app (`getLaunchUrls` returns all-null) rather than linking to `undefined`. New `GET /api/apps/:id/sprite-bindings` reverse-lookup lists the sprite records whose `publishBinding.appId` targets an app, surfaced on the app Overview tab as "Published Sprite Assets" with their destination paths — making "PortOS is the creative source for this app" legible from the app side. Publishing itself still resolves purely from `repoPath`, with no dependency on registered processes.
+- **[issue-2953] Finish the image-to-3D workspace: file-upload picker, a per-record detail route, and a records library** — the `/media/3d` page now doubles as a library, listing every `image_to_3d_models` record (newest-first) as a deep-link card into a new `/media/3d/:id` detail view. The detail page mounts the reusable `GlbViewer` (with **Download .glb**) once a render lands `ready`, polls while `generating`, surfaces the runner's actionable error on `failed`, and offers re-render + delete (inline-confirm) — the URL is the source of truth for what's open, per the ID-based deep-linking convention. `GalleryImagePicker` gains an optional `allowUpload` prop: an "Upload" control saves a file off disk into the gallery via the existing peer-syncable `POST /api/image-gen/upload`, then selects it exactly like a gallery image, so an uploaded photo feeds `createImageTo3dModel` the same way a render-history pick does. No new backend surface — everything runs against the endpoints that landed in #2973.
diff --git a/client/src/App.jsx b/client/src/App.jsx
index d874afbd29..edd85e4960 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -52,6 +52,7 @@ const SyncView = lazyWithReload(() => import('./pages/SyncView'));
const MediaModels = lazyWithReload(() => import('./pages/MediaModels'));
const ThreejsModels = lazyWithReload(() => import('./pages/ThreejsModels'));
const Media3D = lazyWithReload(() => import('./pages/Media3D'));
+const Media3DDetail = lazyWithReload(() => import('./pages/Media3DDetail'));
const ThreejsModelDetail = lazyWithReload(() => import('./pages/ThreejsModelDetail'));
const Loras = lazyWithReload(() => import('./pages/Loras'));
const LoraTraining = lazyWithReload(() => import('./pages/LoraTraining'));
@@ -346,6 +347,7 @@ export default function App() {
<Route path="threejs" element={<ThreejsModels />} />
<Route path="threejs/:id" element={<ThreejsModelDetail />} />
<Route path="3d" element={<Media3D />} />
+ <Route path="3d/:id" element={<Media3DDetail />} />
<Route path="loras" element={<Loras />} />
<Route path="training" element={<LoraTraining />} />
<Route path="training/:datasetId" element={<LoraDatasetDetail />} />
diff --git a/client/src/components/imageGen/GalleryImagePicker.jsx b/client/src/components/imageGen/GalleryImagePicker.jsx
index 5c12a86be0..706f9b40b2 100644
--- a/client/src/components/imageGen/GalleryImagePicker.jsx
+++ b/client/src/components/imageGen/GalleryImagePicker.jsx
@@ -5,19 +5,29 @@
// same as MediaHistory) and click a thumbnail to pick it. Calls `onSelect(item)`
// with the normalized media item (item.filename + item.previewUrl) then closes.
//
+// With `allowUpload`, a header "Upload" button lets the user pick a file off
+// disk: it's saved into the gallery via POST /api/image-gen/upload (so the
+// stored `/data/images/<f>` URL syncs to peers, unlike a generic upload) and
+// then selected exactly like a gallery image — the same source-image flow the
+// image→3D page feeds to createImageTo3dModel.
+//
// Local gallery only — no external/web search (deliberate, see plan).
import { useEffect, useMemo, useState } from 'react';
-import { Search, X, RefreshCw } from 'lucide-react';
+import { Search, X, RefreshCw, Upload } from 'lucide-react';
import Modal from '../ui/Modal';
import MediaCard from '../media/MediaCard';
import { normalizeImage } from '../media/normalize';
import { listImageGallery } from '../../services/apiImageVideo';
+import { uploadGalleryImage } from '../../services/apiSystem';
+import { readFileAsBase64 } from '../../utils/fileUpload';
import { buildMediaHaystack, tokenizeQuery, matchHaystack } from '../../lib/mediaSearch';
+import toast from '../ui/Toast';
-export default function GalleryImagePicker({ open, onClose, onSelect }) {
+export default function GalleryImagePicker({ open, onClose, onSelect, allowUpload = false }) {
const [items, setItems] = useState([]);
const [loading, setLoading] = useState(false);
+ const [uploading, setUploading] = useState(false);
const [query, setQuery] = useState('');
// Fetch the gallery each time the picker opens so newly generated images show
@@ -49,6 +59,26 @@ export default function GalleryImagePicker({ open, onClose, onSelect }) {
[items, haystacks, tokens],
);
+ // Upload a file off disk into the gallery, then select it like any gallery
+ // image. Saving goes through the peer-syncable `/data/images/` upload so the
+ // resulting `filename` resolves for createImageTo3dModel.
+ const handleUpload = async (event) => {
+ const file = event.target.files?.[0];
+ event.target.value = ''; // allow re-picking the same file after an error
+ if (!file) return;
+ setUploading(true);
+ const base64 = await readFileAsBase64(file).catch(() => null);
+ if (!base64) { setUploading(false); toast.error(`Failed to read ${file.name}`); return; }
+ const saved = await uploadGalleryImage(base64, { silent: true }).catch((err) => {
+ toast.error(err?.message || 'Upload failed');
+ return null;
+ });
+ setUploading(false);
+ if (!saved?.filename) return;
+ onSelect?.(normalizeImage({ filename: saved.filename, path: saved.path }));
+ onClose?.();
+ };
+
return (
<Modal
open={open}
@@ -87,6 +117,23 @@ export default function GalleryImagePicker({ open, onClose, onSelect }) {
</button>
)}
</div>
+ {allowUpload && (
+ <label
+ className={`inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-port-border bg-port-bg px-2.5 py-1.5 text-xs text-gray-300 ${uploading ? 'cursor-wait opacity-60' : 'cursor-pointer hover:border-port-accent hover:text-white'}`}
+ title="Upload an image from your device"
+ >
+ {uploading
+ ? <><RefreshCw className="h-3.5 w-3.5 animate-spin" /> Uploading…</>
+ : <><Upload className="h-3.5 w-3.5" /> Upload</>}
+ <input
+ type="file"
+ accept="image/png,image/jpeg,image/webp,image/gif"
+ className="hidden"
+ disabled={uploading}
+ onChange={handleUpload}
+ />
+ </label>
+ )}
<button
type="button"
onClick={onClose}
diff --git a/client/src/components/imageGen/GalleryImagePicker.test.jsx b/client/src/components/imageGen/GalleryImagePicker.test.jsx
index d941127893..d2373ec867 100644
--- a/client/src/components/imageGen/GalleryImagePicker.test.jsx
+++ b/client/src/components/imageGen/GalleryImagePicker.test.jsx
@@ -7,6 +7,17 @@ vi.mock('../../services/apiImageVideo', () => ({
listImageGallery: (...args) => listImageGallery(...args),
}));
+const uploadGalleryImage = vi.fn();
+vi.mock('../../services/apiSystem', () => ({
+ uploadGalleryImage: (...args) => uploadGalleryImage(...args),
+}));
+
+vi.mock('../../utils/fileUpload', () => ({
+ readFileAsBase64: vi.fn().mockResolvedValue('ZmFrZS1iYXNlNjQ='),
+}));
+
+vi.mock('../ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));
+
const GALLERY = [
{ filename: 'neon.png', path: '/data/images/neon.png', prompt: 'a neon sunset', modelId: 'flux2', seed: 1 },
{ filename: 'forest.png', path: '/data/images/forest.png', prompt: 'a quiet forest', modelId: 'sdxl', seed: 2 },
@@ -55,4 +66,26 @@ describe('GalleryImagePicker', () => {
render(<GalleryImagePicker open onClose={vi.fn()} onSelect={vi.fn()} />);
expect(await screen.findByText(/No images in your gallery yet/i)).toBeTruthy();
});
+
+ it('hides the Upload control unless allowUpload is set', async () => {
+ render(<GalleryImagePicker open onClose={vi.fn()} onSelect={vi.fn()} />);
+ await screen.findByAltText('a neon sunset');
+ expect(screen.queryByText(/Upload/i)).toBeNull();
+ });
+
+ it('uploads a picked file into the gallery, then selects it and closes', async () => {
+ uploadGalleryImage.mockResolvedValue({ filename: 'upload-abcd1234.png', path: '/data/images/upload-abcd1234.png' });
+ const onSelect = vi.fn();
+ const onClose = vi.fn();
+ render(<GalleryImagePicker open allowUpload onSelect={onSelect} onClose={onClose} />);
+ await screen.findByAltText('a neon sunset');
+ // Modal portals to <body>, so query the whole document for the file input.
+ const fileInput = document.querySelector('input[type="file"]');
+ const file = new File(['x'], 'photo.png', { type: 'image/png' });
+ fireEvent.change(fileInput, { target: { files: [file] } });
+ await waitFor(() => expect(uploadGalleryImage).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(onSelect).toHaveBeenCalledTimes(1));
+ expect(onSelect.mock.calls[0][0]).toMatchObject({ filename: 'upload-abcd1234.png', previewUrl: '/data/images/upload-abcd1234.png' });
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/client/src/pages/Media3D.jsx b/client/src/pages/Media3D.jsx
index 7f3aa945db..afdadeee3d 100644
--- a/client/src/pages/Media3D.jsx
+++ b/client/src/pages/Media3D.jsx
@@ -1,10 +1,10 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
-import { useSearchParams } from 'react-router-dom';
+import { Link, useSearchParams } from 'react-router-dom';
import { Boxes, CheckCircle2, Download, AlertTriangle, Loader2, ExternalLink, ImagePlus, Sparkles, KeyRound } from 'lucide-react';
-import { getImageTo3dTargets, createImageTo3dModel, getImageTo3dModel } from '../services/api';
+import { getImageTo3dTargets, createImageTo3dModel, getImageTo3dModel, listImageTo3dModels } from '../services/api';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
import useMounted from '../hooks/useMounted';
-import { nameFromImageFilename } from '../utils/formatters';
+import { nameFromImageFilename, timeAgo } from '../utils/formatters';
import RuntimeInstallModal from '../components/install/RuntimeInstallModal';
import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';
import GlbViewer from '../components/media/GlbViewer';
@@ -60,6 +60,15 @@ 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)',
@@ -164,6 +173,9 @@ export default function Media3D() {
const [genError, setGenError] = useState(null);
const [genPercent, setGenPercent] = useState(null);
const [modelId, setModelId] = useState(null);
+ // Existing image-to-3D records (newest-first) so the page doubles as a library:
+ // each links to its `/media/3d/:id` detail view.
+ const [records, setRecords] = useState([]);
const mountedRef = useMounted(); // gate setState after the create/poll awaits
const load = useCallback(() => {
@@ -174,7 +186,14 @@ export default function Media3D() {
.finally(() => setLoading(false));
}, []);
+ const loadRecords = useCallback(() => {
+ listImageTo3dModels({ silent: true })
+ .then((data) => { if (mountedRef.current) setRecords(Array.isArray(data) ? data : []); })
+ .catch(() => { /* the library section just stays empty on a transient failure */ });
+ }, [mountedRef]);
+
useEffect(() => { load(); }, [load]);
+ useEffect(() => { loadRecords(); }, [loadRecords]);
const selectedImage = useMemo(
() => (imageFromRoute
@@ -227,13 +246,13 @@ export default function Media3D() {
const latest = Array.isArray(model.runs) && model.runs.length ? model.runs[model.runs.length - 1] : null;
if (Number.isFinite(latest?.percent)) setGenPercent(latest.percent);
if (model.status === 'ready' && model.assetPath) {
- setGenPercent(100); setParam('glb', model.assetPath); setGenerating(false);
+ setGenPercent(100); setParam('glb', model.assetPath); setGenerating(false); loadRecords();
} 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);
+ setGenError(model.error || 'The render did not finish.'); setGenerating(false); loadRecords();
}
// else still draft/generating → the hook re-polls after POLL_INTERVAL_MS.
- }, [modelId, setParam, mountedRef]);
+ }, [modelId, setParam, mountedRef, loadRecords]);
useAutoRefetch(pollTick, POLL_INTERVAL_MS, { pollOnly: true, enabled: generating && !!modelId });
@@ -248,8 +267,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); }
- }, [selectedImage, selectedTarget, setParam, mountedRef]);
+ if (created && mountedRef.current) { setModelId(created.id); setGenerating(true); loadRecords(); }
+ }, [selectedImage, selectedTarget, setParam, mountedRef, loadRecords]);
// 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
@@ -367,6 +386,49 @@ export default function Media3D() {
</section>
)}
+ {/* Library of existing renders — each opens its `/media/3d/:id` detail
+ view (GLB viewer + download). URL is the source of truth for what's
+ open, so every card is a deep link. */}
+ {records.length > 0 && (
+ <section className="mb-6">
+ <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;
+ return (
+ <Link
+ key={record.id}
+ to={`/media/3d/${record.id}`}
+ className="group overflow-hidden rounded-lg border border-port-border bg-port-card hover:border-port-accent"
+ >
+ <div className="relative aspect-square bg-port-bg">
+ {record.sourceImage?.path && (
+ <MediaImage
+ src={record.sourceImage.path}
+ alt={record.name || 'Source image'}
+ className="h-full w-full object-cover opacity-90 group-hover:opacity-100"
+ />
+ )}
+ {record.status === 'ready' && (
+ <span className="absolute right-1.5 top-1.5 rounded bg-black/80 p-1 text-port-success">
+ <Boxes className="h-3.5 w-3.5" />
+ </span>
+ )}
+ </div>
+ <div className="p-2">
+ <p className="truncate text-xs font-medium text-white" title={record.name}>{record.name || 'Untitled'}</p>
+ <div className="mt-0.5 flex items-center justify-between gap-1">
+ <span className={`text-[11px] ${status.className}`}>{status.label}</span>
+ <span className="text-[11px] text-gray-500">{timeAgo(record.updatedAt)}</span>
+ </div>
+ </div>
+ </Link>
+ );
+ })}
+ </div>
+ </section>
+ )}
+
<h2 className="mb-2 text-xs font-medium uppercase tracking-wide text-gray-400">Models &amp; runtimes</h2>
{loading && (
@@ -397,7 +459,7 @@ export default function Media3D() {
{/* Searchable render-history picker (reused from Image Gen). Selecting an
image drives `?image=` so the choice is deep-linkable. */}
- <GalleryImagePicker open={pickerOpen} onClose={() => setPickerOpen(false)} onSelect={handlePick} />
+ <GalleryImagePicker open={pickerOpen} onClose={() => setPickerOpen(false)} onSelect={handlePick} allowUpload />
{/* TRELLIS.2 (and any future local-install target) streams its clone +
setup.sh install through the shared runtime-install modal. */}
diff --git a/client/src/pages/Media3D.test.jsx b/client/src/pages/Media3D.test.jsx
index 7e64e90400..ed5d4f938d 100644
--- a/client/src/pages/Media3D.test.jsx
+++ b/client/src/pages/Media3D.test.jsx
@@ -6,10 +6,12 @@ import Media3D from './Media3D';
const getImageTo3dTargets = vi.fn();
const createImageTo3dModel = vi.fn();
const getImageTo3dModel = vi.fn();
+const listImageTo3dModels = vi.fn();
vi.mock('../services/api', () => ({
getImageTo3dTargets: (...a) => getImageTo3dTargets(...a),
createImageTo3dModel: (...a) => createImageTo3dModel(...a),
getImageTo3dModel: (...a) => getImageTo3dModel(...a),
+ listImageTo3dModels: (...a) => listImageTo3dModels(...a),
}));
// Stub the shared install modal so the test doesn't open a real EventSource;
@@ -63,7 +65,7 @@ function renderAt(entry = '/media/3d', extra = null) {
}
describe('Media3D — models & install', () => {
- beforeEach(() => vi.clearAllMocks());
+ beforeEach(() => { vi.clearAllMocks(); listImageTo3dModels.mockResolvedValue([]); });
it('shows an Install button for an available, not-installed target and opens the modal', async () => {
getImageTo3dTargets.mockResolvedValue({ capabilities: {}, targets: [target()] });
@@ -103,6 +105,7 @@ describe('Media3D — models & install', () => {
describe('Media3D — generation workspace', () => {
beforeEach(() => {
vi.clearAllMocks();
+ listImageTo3dModels.mockResolvedValue([]);
getImageTo3dTargets.mockResolvedValue({ targets: [target({ installed: true })] });
});
@@ -183,4 +186,13 @@ describe('Media3D — generation workspace', () => {
renderAt('/media/3d?image=example-robot.png&glb=%2Fdata%2Fmodels3d%2Frobot.glb');
expect(await screen.findByTestId('glb-viewer')).toHaveTextContent('/data/models3d/robot.glb');
});
+
+ it('lists existing 3D records as deep links to their detail route', async () => {
+ listImageTo3dModels.mockResolvedValue([
+ { id: 'image3d-abc', name: 'Example Beacon', status: 'ready', updatedAt: new Date(0).toISOString(), sourceImage: { path: '/data/images/beacon.png' } },
+ ]);
+ renderAt();
+ const link = await screen.findByRole('link', { name: /Example Beacon/i });
+ expect(link.getAttribute('href')).toBe('/media/3d/image3d-abc');
+ });
});
diff --git a/client/src/pages/Media3DDetail.jsx b/client/src/pages/Media3DDetail.jsx
new file mode 100644
index 0000000000..9fdd710695
--- /dev/null
+++ b/client/src/pages/Media3DDetail.jsx
@@ -0,0 +1,184 @@
+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 useMounted from '../hooks/useMounted';
+import { timeAgo } from '../utils/formatters';
+import GlbViewer from '../components/media/GlbViewer';
+import MediaImage from '../components/MediaImage';
+import InlineConfirmRow from '../components/ui/InlineConfirmRow';
+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`),
+// with a Download .glb, and offers re-render / delete. Polls while generating.
+export default function Media3DDetail() {
+ const { id } = useParams();
+ const navigate = useNavigate();
+ const mountedRef = useMounted();
+ const [record, setRecord] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [notFound, setNotFound] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [confirmingDelete, setConfirmingDelete] = useState(false);
+
+ const load = useCallback(async ({ initial = false } = {}) => {
+ const next = await getImageTo3dModel(id, { silent: true }).catch((err) => {
+ if (err?.status === 404) { if (mountedRef.current) setNotFound(true); }
+ else if (initial) toast.error(err?.message || 'Failed to load 3D model');
+ return null;
+ });
+ if (next && mountedRef.current) { setRecord(next); setNotFound(false); }
+ if (initial && mountedRef.current) setLoading(false);
+ return next;
+ }, [id, mountedRef]);
+
+ 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]);
+
+ const handleRegenerate = useCallback(async () => {
+ if (busy || record?.status === 'generating') return;
+ setBusy(true);
+ const next = await generateImageTo3dModel(id, { silent: true }).catch((err) => {
+ toast.error(err?.message || 'Could not start the render.');
+ return null;
+ });
+ if (mountedRef.current) setBusy(false);
+ if (next && mountedRef.current) setRecord(next);
+ }, [busy, record?.status, id, mountedRef]);
+
+ const handleDelete = useCallback(async () => {
+ const ok = await deleteImageTo3dModel(id, { silent: true }).then(() => true).catch((err) => {
+ toast.error(err?.message || 'Delete failed');
+ return false;
+ });
+ if (ok) navigate('/media/3d');
+ }, [id, navigate]);
+
+ if (loading) {
+ return (
+ <div className="mx-auto flex max-w-4xl items-center gap-2 py-16 text-sm text-gray-400">
+ <Loader2 className="h-4 w-4 animate-spin" /> Loading 3D model…
+ </div>
+ );
+ }
+
+ if (notFound || !record) {
+ return (
+ <div className="mx-auto max-w-4xl py-16 text-center">
+ <p className="text-sm text-gray-400">This 3D model no longer exists.</p>
+ <Link to="/media/3d" className="mt-3 inline-flex items-center gap-1.5 text-sm text-port-accent hover:underline">
+ <ArrowLeft className="h-4 w-4" /> Back to 3D
+ </Link>
+ </div>
+ );
+ }
+
+ 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">
+ <header className="mb-4">
+ <Link to="/media/3d" className="inline-flex items-center gap-1.5 text-xs text-gray-400 hover:text-white">
+ <ArrowLeft className="h-3.5 w-3.5" /> Back to 3D
+ </Link>
+ <div className="mt-2 flex flex-wrap items-center justify-between gap-3">
+ <div className="flex items-center gap-2">
+ <Boxes className="h-5 w-5 text-port-accent" />
+ <h1 className="text-lg font-semibold text-white">{record.name || 'Untitled 3D model'}</h1>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={handleRegenerate}
+ disabled={busy || isGenerating}
+ className="inline-flex items-center gap-1.5 rounded-md border border-port-border px-3 py-1.5 text-xs text-gray-300 hover:border-port-accent hover:text-white disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ <RefreshCw className={`h-3.5 w-3.5 ${busy ? 'animate-spin' : ''}`} /> {record.status === 'ready' ? 'Re-render' : 'Retry'}
+ </button>
+ <button
+ type="button"
+ onClick={() => setConfirmingDelete(true)}
+ className="inline-flex items-center gap-1.5 rounded-md border border-port-error/40 px-3 py-1.5 text-xs text-port-error hover:bg-port-error/10"
+ >
+ <Trash2 className="h-3.5 w-3.5" /> Delete
+ </button>
+ </div>
+ </div>
+ <p className="mt-1 text-xs text-gray-500">
+ {STATUS_LABEL[record.status] || record.status}
+ {isGenerating && percent !== null ? ` · ${percent}%` : ''} · updated {timeAgo(record.updatedAt)}
+ </p>
+ </header>
+
+ {confirmingDelete && (
+ <InlineConfirmRow
+ className="mb-4"
+ question={`Delete "${record.name || 'this model'}"?`}
+ onConfirm={handleDelete}
+ onCancel={() => setConfirmingDelete(false)}
+ />
+ )}
+
+ {record.status === 'failed' && record.error && (
+ <div className="mb-4 flex items-start gap-1.5 rounded-lg border border-port-error/30 bg-port-error/10 px-3 py-2 text-sm text-port-error">
+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" /> {record.error}
+ </div>
+ )}
+
+ <section className="grid gap-4 sm:grid-cols-[200px_1fr]">
+ <div>
+ <span className="mb-1 block text-xs text-gray-400">Source image</span>
+ <div className="aspect-square overflow-hidden rounded-lg border border-port-border bg-port-bg">
+ {record.sourceImage?.path && (
+ <MediaImage src={record.sourceImage.path} alt="Source image" className="h-full w-full object-cover" />
+ )}
+ </div>
+ </div>
+
+ <div>
+ <span className="mb-1 block text-xs text-gray-400">Mesh</span>
+ {record.status === 'ready' && record.assetPath ? (
+ <GlbViewer src={record.assetPath} downloadName={downloadName} />
+ ) : (
+ <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 ? (
+ <span className="inline-flex items-center gap-2 text-port-accent">
+ <Loader2 className="h-4 w-4 animate-spin" /> Rendering{percent !== null ? ` ${percent}%` : '…'}
+ </span>
+ ) : (
+ 'No mesh yet — run a render to generate one.'
+ )}
+ </div>
+ )}
+ </div>
+ </section>
+ </div>
+ );
+}
diff --git a/client/src/pages/Media3DDetail.test.jsx b/client/src/pages/Media3DDetail.test.jsx
new file mode 100644
index 0000000000..b8d80aa2d9
--- /dev/null
+++ b/client/src/pages/Media3DDetail.test.jsx
@@ -0,0 +1,80 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor, within } from '@testing-library/react';
+import { MemoryRouter, Routes, Route } from 'react-router-dom';
+import Media3DDetail from './Media3DDetail';
+
+const getImageTo3dModel = vi.fn();
+const generateImageTo3dModel = vi.fn();
+const deleteImageTo3dModel = vi.fn();
+vi.mock('../services/api', () => ({
+ getImageTo3dModel: (...a) => getImageTo3dModel(...a),
+ generateImageTo3dModel: (...a) => generateImageTo3dModel(...a),
+ deleteImageTo3dModel: (...a) => deleteImageTo3dModel(...a),
+}));
+
+// GlbViewer wraps a WebGL canvas jsdom can't render — stub to a marker echoing src.
+vi.mock('../components/media/GlbViewer', () => ({
+ default: ({ src }) => <div data-testid="glb-viewer">{src}</div>,
+}));
+vi.mock('../components/MediaImage', () => ({ default: ({ alt, src }) => <img alt={alt} src={src} /> }));
+vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));
+
+const record = (over = {}) => ({
+ id: 'image3d-1',
+ name: 'Example Beacon',
+ status: 'ready',
+ assetPath: '/data/image-to-3d/image3d-1/model.glb',
+ error: null,
+ runs: [],
+ sourceImage: { filename: 'beacon.png', path: '/data/images/beacon.png' },
+ updatedAt: new Date(0).toISOString(),
+ ...over,
+});
+
+function renderAt(id = 'image3d-1') {
+ return render(
+ <MemoryRouter initialEntries={[`/media/3d/${id}`]}>
+ <Routes>
+ <Route path="/media/3d" element={<div>3D index</div>} />
+ <Route path="/media/3d/:id" element={<Media3DDetail />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+}
+
+describe('Media3DDetail', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('renders the mesh viewer and source image for a ready record', async () => {
+ getImageTo3dModel.mockResolvedValue(record());
+ renderAt();
+ expect(await screen.findByText('Example Beacon')).toBeInTheDocument();
+ expect(screen.getByTestId('glb-viewer')).toHaveTextContent('/data/image-to-3d/image3d-1/model.glb');
+ expect(screen.getByAltText('Source image')).toBeInTheDocument();
+ });
+
+ it('surfaces the render error for a failed record', async () => {
+ getImageTo3dModel.mockResolvedValue(record({ status: 'failed', assetPath: null, error: 'Accept the Hugging Face terms first.' }));
+ renderAt();
+ expect(await screen.findByText(/Accept the Hugging Face terms first/i)).toBeInTheDocument();
+ expect(screen.queryByTestId('glb-viewer')).toBeNull();
+ });
+
+ it('shows a not-found fallback for a stale id', async () => {
+ getImageTo3dModel.mockRejectedValue(Object.assign(new Error('nope'), { status: 404 }));
+ renderAt('gone');
+ expect(await screen.findByText(/no longer exists/i)).toBeInTheDocument();
+ });
+
+ it('deletes and navigates back to the index', async () => {
+ getImageTo3dModel.mockResolvedValue(record());
+ deleteImageTo3dModel.mockResolvedValue({ ok: true });
+ renderAt();
+ fireEvent.click(await screen.findByRole('button', { name: /delete/i }));
+ // The inline confirm row appears; click its Confirm button.
+ const confirmRow = await screen.findByText(/Delete "Example Beacon"\?/i);
+ fireEvent.click(within(confirmRow.parentElement).getByRole('button', { name: /^delete$/i }));
+ await waitFor(() => expect(deleteImageTo3dModel).toHaveBeenCalledWith('image3d-1', { silent: true }));
+ expect(await screen.findByText('3D index')).toBeInTheDocument();
+ });
+});