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([issue-2953]): image-to-3D workspace — source picker, deep-linking, GLB viewer
[._.]/ Adam Eivy7c42252b4835
diff --git a/client/src/components/media/GlbViewer.jsx b/client/src/components/media/GlbViewer.jsxnew file mode 100644index 0000000000..4f9562d4a0--- /dev/null+++ b/client/src/components/media/GlbViewer.jsx@@ -0,0 +1,63 @@+import { Suspense, useEffect } from 'react';+import { Canvas } from '@react-three/fiber';+import { Bounds, OrbitControls, useGLTF } from '@react-three/drei';+import { Download, Rotate3d } from 'lucide-react';++// Reusable viewer for a generated `.glb` mesh: drei `useGLTF` loads the model,+// `Bounds fit` frames it regardless of the source's scale, `OrbitControls` lets+// the user rotate/zoom, and a Download button saves the raw `.glb`. Deliberately+// backend-agnostic — it takes a plain `src` URL, so the image→3D generate flow+// (#2952) and any future detail route can mount it by pointing at the landed+// asset. Renders nothing without a `src`.++// Derive a friendly download filename from the asset URL when the caller doesn't+// supply one (`/data/models3d/robot-a1b2.glb` → `robot-a1b2.glb`).+function filenameFromSrc(src) {+ const tail = String(src || '').split('?')[0].split('#')[0].split('/').pop();+ return tail && tail.toLowerCase().endsWith('.glb') ? tail : 'model.glb';+}++function GlbModel({ src }) {+ const { scene } = useGLTF(src);+ // drei caches loaded GLTFs globally; clear this entry on unmount/src-change so a+ // re-render after a new generation doesn't show the stale cached mesh.+ useEffect(() => () => useGLTF.clear(src), [src]);+ return <primitive object={scene} />;+}++export default function GlbViewer({ src, downloadName, className = '' }) {+ if (!src) return null;+ const download = 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">+ {/* No environment/HDR preset here on purpose — those fetch from a CDN and+ would fail on an offline / air-gapped install. Two plain lights are+ enough to read an untextured or PBR mesh. */}+ <Canvas camera={{ position: [0, 0, 3], fov: 45 }} dpr={[1, 2]}>+ <ambientLight intensity={0.9} />+ <directionalLight position={[4, 6, 5]} intensity={1.1} />+ <directionalLight position={[-4, -2, -5]} intensity={0.4} />+ <Suspense fallback={null}>+ <Bounds fit clip observe margin={1.2}>+ <GlbModel src={src} />+ </Bounds>+ </Suspense>+ <OrbitControls makeDefault enablePan enableZoom enableRotate />+ </Canvas>+ </div>+ <div className="flex items-center justify-between gap-2 border-t border-port-border px-3 py-2">+ <span className="inline-flex items-center gap-1.5 text-xs text-gray-500">+ <Rotate3d className="h-3.5 w-3.5" /> Drag to orbit · scroll to zoom+ </span>+ <a+ href={src}+ 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"+ >+ <Download className="h-3.5 w-3.5" /> Download .glb+ </a>+ </div>+ </div>+ );+}diff --git a/client/src/components/media/GlbViewer.test.jsx b/client/src/components/media/GlbViewer.test.jsxnew file mode 100644index 0000000000..6a7cf29a49--- /dev/null+++ b/client/src/components/media/GlbViewer.test.jsx@@ -0,0 +1,42 @@+import { render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++// The three.js stack can't run in jsdom (no WebGL context) and none of it is+// under test here — this file covers the chrome AROUND the canvas (the download+// link + the empty-src guard). The Canvas stub deliberately drops `children`:+// mounting <primitive>/<mesh> would surface unknown DOM elements and r3f hands+// back HTMLElement refs without the three.js API.+vi.mock('@react-three/fiber', () => ({ Canvas: () => <div data-testid="glb-canvas" /> }));+vi.mock('@react-three/drei', () => ({+ Canvas: () => null,+ OrbitControls: () => null,+ Bounds: ({ children }) => children,+ useGLTF: Object.assign(() => ({ scene: {} }), { clear: vi.fn() }),+}));++import GlbViewer from './GlbViewer';++describe('GlbViewer', () => {+ it('renders nothing without a src', () => {+ const { container } = render(<GlbViewer src="" />);+ expect(container).toBeEmptyDOMElement();+ });++ it('renders the canvas and a download link derived from the src filename', () => {+ render(<GlbViewer src="/data/models3d/robot-a1b2.glb" />);+ expect(screen.getByTestId('glb-canvas')).toBeInTheDocument();+ const link = screen.getByRole('link', { name: /Download \.glb/i });+ expect(link).toHaveAttribute('href', '/data/models3d/robot-a1b2.glb');+ expect(link).toHaveAttribute('download', 'robot-a1b2.glb');+ });++ it('honors an explicit downloadName over the derived one', () => {+ render(<GlbViewer src="/data/models3d/x.glb?v=2" downloadName="my-mesh.glb" />);+ expect(screen.getByRole('link', { name: /Download \.glb/i })).toHaveAttribute('download', 'my-mesh.glb');+ });++ it('falls back to model.glb when the src has no .glb tail', () => {+ render(<GlbViewer src="/data/models3d/streaming-endpoint" />);+ expect(screen.getByRole('link', { name: /Download \.glb/i })).toHaveAttribute('download', 'model.glb');+ });+});diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex a17a5905d7..a491f9f322 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -1049,9 +1049,11 @@ export default function ImageGen() {setInitImageStrength(0.4);};+ // "Send to 3D" opens the image-to-3D workspace (/media/3d) with this render as+ // the source image — deep-linked via ?image= (URL is the source of truth).const handleSendToThreejs = (img) => {if (!img?.filename) return;- navigate(`/media/threejs?image=${encodeURIComponent(img.filename)}`);+ navigate(`/media/3d?image=${encodeURIComponent(img.filename)}`);};const notConnected = status && status.connected === false;diff --git a/client/src/pages/Media3D.jsx b/client/src/pages/Media3D.jsxindex 424bc8b94f..eceb8b4707 100644--- a/client/src/pages/Media3D.jsx+++ b/client/src/pages/Media3D.jsx@@ -1,7 +1,11 @@-import { useCallback, useEffect, useState } from 'react';-import { Boxes, CheckCircle2, Download, AlertTriangle, Loader2, ExternalLink } from 'lucide-react';+import { useCallback, useEffect, useMemo, useState } from 'react';+import { useSearchParams } from 'react-router-dom';+import { Boxes, CheckCircle2, Download, AlertTriangle, Loader2, ExternalLink, ImagePlus, Sparkles } from 'lucide-react';import { getImageTo3dTargets } from '../services/api';import RuntimeInstallModal from '../components/install/RuntimeInstallModal';+import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';+import GlbViewer from '../components/media/GlbViewer';+import MediaImage from '../components/MediaImage';// Human-readable reasons a target can't run on this host, keyed by the stable// reason code the registry returns (server/services/imageTo3d/targets.js).@@ -18,6 +22,11 @@ const LANE_LABEL = {'hosted-api': 'Hosted API',};+// A target is generation-ready when it can run on this host and its local model+// is present (installed:null means "no install concept" — a hosted target that's+// ready as soon as it's available).+const isTargetReady = (t) => !!t && t.available && t.installed !== false;+function StatusBadge({ target }) {if (!target.available) {return (@@ -91,11 +100,19 @@ function TargetCard({ target, onInstall }) {}export default function Media3D() {+ const [searchParams, setSearchParams] = useSearchParams();+ // URL is the source of truth for what's open: the source image, the chosen+ // target, and (once the runner lands #2952) the generated mesh to preview.+ const imageFromRoute = searchParams.get('image') || '';+ const targetFromRoute = searchParams.get('target') || '';+ const glbFromRoute = searchParams.get('glb') || '';+const [targets, setTargets] = useState([]);const [loading, setLoading] = useState(true);const [error, setError] = useState(null);// The target whose install modal is open (only local-install targets); null = closed.const [installTarget, setInstallTarget] = useState(null);+ const [pickerOpen, setPickerOpen] = useState(false);const load = useCallback(() => {setLoading(true);@@ -107,6 +124,53 @@ export default function Media3D() {useEffect(() => { load(); }, [load]);+ const selectedImage = useMemo(+ () => (imageFromRoute+ ? { filename: imageFromRoute, previewUrl: `/data/images/${encodeURIComponent(imageFromRoute)}` }+ : null),+ [imageFromRoute],+ );++ // The active target: an explicit `?target=` when it matches a known target,+ // else the first generation-ready one, else the first registered.+ const selectedTarget = useMemo(() => {+ if (!targets.length) return null;+ return targets.find((t) => t.id === targetFromRoute)+ || targets.find(isTargetReady)+ || targets[0];+ }, [targets, targetFromRoute]);++ // Keep the URL honest: if a bare `/media/3d` resolved a default target, reflect+ // it so the selection is shareable/reload-safe (URL as source of truth).+ useEffect(() => {+ if (!selectedTarget || targetFromRoute === selectedTarget.id) return;+ const next = new URLSearchParams(searchParams);+ next.set('target', selectedTarget.id);+ setSearchParams(next, { replace: true });+ }, [selectedTarget, targetFromRoute, searchParams, setSearchParams]);++ const setParam = useCallback((key, value) => {+ const next = new URLSearchParams(searchParams);+ if (value) next.set(key, value); else next.delete(key);+ setSearchParams(next);+ }, [searchParams, setSearchParams]);++ const handlePick = (item) => { setParam('image', item.filename); setPickerOpen(false); };++ const ready = isTargetReady(selectedTarget);+ // The image→mesh runner (POST generate + landed .glb) lands with #2952; until+ // then the workspace lets the user stage the source image + target and preview+ // any produced mesh, but the Generate action stays gated rather than pretending.+ const generateGatedReason = !selectedImage+ ? 'Pick a source image to continue.'+ : !selectedTarget+ ? 'No image-to-3D model is registered.'+ : !selectedTarget.available+ ? (REASON_LABEL[selectedTarget.unavailableReason] || 'This model can’t run on this host.')+ : selectedTarget.installed === false+ ? `Install ${selectedTarget.label} below before generating.`+ : 'Generation lands with the on-device runner — coming next.';+return (<div className="mx-auto max-w-4xl"><header className="mb-5">@@ -115,11 +179,91 @@ export default function Media3D() {<h1 className="text-lg font-semibold text-white">3D</h1></div><p className="mt-1 text-sm text-gray-400">- Turn a rendered image into a 3D mesh. Install and manage the image-to-3D models here;- generation from an image lands next.+ Turn a rendered image into a 3D mesh. Pick a source image and model here, then install+ and manage the image-to-3D runtimes below.</p></header>+ {/* Generation workspace — source image + target selection + preview. The+ create/generate call is wired when the runner (#2952) lands. */}+ <section className="mb-6 grid gap-4 rounded-xl border border-port-border bg-port-card p-4 sm:grid-cols-[200px_1fr]">+ <button+ type="button"+ onClick={() => setPickerOpen(true)}+ className="group relative aspect-square overflow-hidden rounded-lg border border-dashed border-port-border bg-port-bg hover:border-port-accent"+ >+ {selectedImage ? (+ <MediaImage+ src={selectedImage.previewUrl}+ alt="Selected source image"+ className="h-full w-full object-cover"+ />+ ) : (+ <span className="flex h-full flex-col items-center justify-center gap-2 text-sm text-gray-500 group-hover:text-port-accent">+ <ImagePlus className="h-7 w-7" /> Pick source image+ </span>+ )}+ {selectedImage && (+ <span className="absolute inset-x-2 bottom-2 rounded bg-black/70 px-2 py-1 text-center text-xs text-white">+ Change image+ </span>+ )}+ </button>++ <div className="flex flex-col gap-3">+ <div>+ <span className="mb-1 block text-xs text-gray-400">Model</span>+ {loading ? (+ <span className="text-xs text-gray-500">Loading models…</span>+ ) : targets.length === 0 ? (+ <span className="text-xs text-gray-500">No image-to-3D models registered.</span>+ ) : (+ <div className="flex flex-wrap gap-2">+ {targets.map((t) => {+ const active = selectedTarget?.id === t.id;+ return (+ <button+ key={t.id}+ type="button"+ onClick={() => setParam('target', t.id)}+ className={`rounded-lg border px-3 py-1.5 text-xs ${active+ ? 'border-port-accent bg-port-accent/10 text-white'+ : 'border-port-border bg-port-bg text-gray-300 hover:border-port-accent'}`}+ >+ {t.label}+ {isTargetReady(t) && <CheckCircle2 className="ml-1.5 inline h-3 w-3 text-port-success" />}+ </button>+ );+ })}+ </div>+ )}+ </div>++ <div className="mt-auto flex flex-col items-start gap-2">+ <button+ type="button"+ disabled={!ready || !selectedImage}+ title={generateGatedReason}+ className="inline-flex items-center gap-2 rounded-lg bg-port-accent px-4 py-2 text-sm text-white hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"+ >+ <Sparkles className="h-4 w-4" /> Generate 3D+ </button>+ <p className="text-xs text-gray-500">{generateGatedReason}</p>+ </div>+ </div>+ </section>++ {/* Generated-mesh preview. Driven by `?glb=` so a finished render (#2952)+ is a shareable, reload-safe deep link; empty until one lands. */}+ {glbFromRoute && (+ <section className="mb-6">+ <h2 className="mb-2 text-xs font-medium uppercase tracking-wide text-gray-400">Mesh preview</h2>+ <GlbViewer src={glbFromRoute} />+ </section>+ )}++ <h2 className="mb-2 text-xs font-medium uppercase tracking-wide text-gray-400">Models & runtimes</h2>+{loading && (<div className="flex items-center gap-2 text-sm text-gray-400"><Loader2 className="h-4 w-4 animate-spin" /> Loading models…@@ -146,6 +290,10 @@ export default function Media3D() {</div>)}+ {/* 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} />+{/* TRELLIS.2 (and any future local-install target) streams its clone +setup.sh install through the shared runtime-install modal. */}<RuntimeInstallModaldiff --git a/client/src/pages/Media3D.test.jsx b/client/src/pages/Media3D.test.jsxindex c9426887a4..43b640180f 100644--- a/client/src/pages/Media3D.test.jsx+++ b/client/src/pages/Media3D.test.jsx@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, fireEvent } from '@testing-library/react';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { MemoryRouter, useLocation } from 'react-router-dom';import Media3D from './Media3D';const getImageTo3dTargets = vi.fn();@@ -13,6 +14,21 @@ vi.mock('../components/install/RuntimeInstallModal', () => ({default: ({ open, runtime }) => (open ? <div data-testid="install-modal">installing {runtime}</div> : null),}));+// GlbViewer wraps a WebGL canvas jsdom can't render — stub to a marker that+// echoes the src so the ?glb= deep-link wiring is assertable without three.js.+vi.mock('../components/media/GlbViewer', () => ({+ default: ({ src }) => <div data-testid="glb-viewer">{src}</div>,+}));++// Minimal gallery picker that hands back a fixed selection on click.+vi.mock('../components/imageGen/GalleryImagePicker', () => ({+ default: ({ open, onSelect }) => open ? (+ <button type="button" onClick={() => onSelect({ filename: 'picked-hero.png' })}>Pick hero</button>+ ) : null,+}));++vi.mock('../components/MediaImage', () => ({ default: ({ alt }) => <img alt={alt} /> }));+const target = (over = {}) => ({id: 'trellis2',label: 'TRELLIS.2',@@ -27,12 +43,27 @@ const target = (over = {}) => ({...over,});-describe('Media3D', () => {+function LocationProbe() {+ return <output aria-label="Current query">{useLocation().search}</output>;+}++// Media3D reads the source image / target / glb from the URL, so every render+// needs a router. The path is irrelevant to useSearchParams — only the query is.+function renderAt(entry = '/media/3d', extra = null) {+ return render(+ <MemoryRouter initialEntries={[entry]}>+ <Media3D />+ {extra}+ </MemoryRouter>,+ );+}++describe('Media3D — models & install', () => {beforeEach(() => vi.clearAllMocks());it('shows an Install button for an available, not-installed target and opens the modal', async () => {getImageTo3dTargets.mockResolvedValue({ capabilities: {}, targets: [target()] });- render(<Media3D />);+ renderAt();const btn = await screen.findByRole('button', { name: /install/i });fireEvent.click(btn);expect(await screen.findByTestId('install-modal')).toHaveTextContent('trellis2');@@ -40,7 +71,7 @@ describe('Media3D', () => {it('shows Ready and no Install button when the target is installed', async () => {getImageTo3dTargets.mockResolvedValue({ targets: [target({ installed: true })] });- render(<Media3D />);+ renderAt();expect(await screen.findByText(/ready/i)).toBeInTheDocument();expect(screen.queryByRole('button', { name: /install/i })).toBeNull();});@@ -49,14 +80,14 @@ describe('Media3D', () => {getImageTo3dTargets.mockResolvedValue({targets: [target({ available: false, unavailableReason: 'requires-apple-silicon' })],});- render(<Media3D />);- expect(await screen.findByText(/requires an apple silicon mac/i)).toBeInTheDocument();+ renderAt();+ expect(await screen.findAllByText(/requires an apple silicon mac/i)).not.toHaveLength(0);expect(screen.queryByRole('button', { name: /install/i })).toBeNull();});it('surfaces a load error with Retry, and recovers on retry', async () => {getImageTo3dTargets.mockRejectedValueOnce(new Error('boom'));- render(<Media3D />);+ renderAt();expect(await screen.findByText('boom')).toBeInTheDocument();getImageTo3dTargets.mockResolvedValueOnce({ targets: [target({ installed: true })] });@@ -64,3 +95,57 @@ describe('Media3D', () => {expect(await screen.findByText(/ready/i)).toBeInTheDocument();});});++describe('Media3D — generation workspace', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getImageTo3dTargets.mockResolvedValue({ targets: [target({ installed: true })] });+ });++ it('shows the source image from the ?image= deep link', async () => {+ renderAt('/media/3d?image=example-robot.png');+ expect(await screen.findByAltText('Selected source image')).toBeInTheDocument();+ expect(screen.queryByText(/Pick a source image to continue/i)).not.toBeInTheDocument();+ });++ it('enables Generate when an image is chosen and the target is ready', async () => {+ renderAt('/media/3d?image=example-robot.png');+ expect(await screen.findByRole('button', { name: /Generate 3D/i })).toBeEnabled();+ });++ it('keeps Generate disabled and explains why when no image is picked', async () => {+ renderAt('/media/3d');+ const btn = await screen.findByRole('button', { name: /Generate 3D/i });+ expect(btn).toBeDisabled();+ expect(screen.getByText(/Pick a source image to continue/i)).toBeInTheDocument();+ });++ it('gates Generate when the chosen target still needs installing', async () => {+ getImageTo3dTargets.mockResolvedValue({ targets: [target({ installed: false })] });+ renderAt('/media/3d?image=example-robot.png');+ const btn = await screen.findByRole('button', { name: /Generate 3D/i });+ expect(btn).toBeDisabled();+ expect(screen.getByText(/Install TRELLIS\.2 below before generating/i)).toBeInTheDocument();+ });++ it('writes a picked image into the shareable URL', async () => {+ renderAt('/media/3d', <LocationProbe />);+ fireEvent.click(await screen.findByRole('button', { name: /Pick source image/i }));+ fireEvent.click(screen.getByRole('button', { name: 'Pick hero' }));+ await waitFor(() => {+ expect(screen.getByLabelText('Current query')).toHaveTextContent('image=picked-hero.png');+ });+ });++ it('reflects the resolved default target back into the URL', async () => {+ renderAt('/media/3d', <LocationProbe />);+ await waitFor(() => {+ expect(screen.getByLabelText('Current query')).toHaveTextContent('target=trellis2');+ });+ });++ it('renders the mesh preview from a ?glb= deep link', async () => {+ renderAt('/media/3d?image=example-robot.png&glb=%2Fdata%2Fmodels3d%2Frobot.glb');+ expect(await screen.findByTestId('glb-viewer')).toHaveTextContent('/data/models3d/robot.glb');+ });+});diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsxindex c4b345c7fc..d4ef35d232 100644--- a/client/src/pages/MediaHistory.jsx+++ b/client/src/pages/MediaHistory.jsx@@ -155,9 +155,11 @@ export default function MediaHistory() {}};+ // "Send to 3D" opens the image-to-3D workspace (/media/3d) with this render as+ // the source image — deep-linked via ?image= (URL is the source of truth).const handleSendToThreejs = (item) => {if (item?.kind !== 'image' || !item.filename) return;- navigate(`/media/threejs?image=${encodeURIComponent(item.filename)}`);+ navigate(`/media/3d?image=${encodeURIComponent(item.filename)}`);};return (