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-3080): make image-to-3D target registration own install and runner dispatch
[._.]/ Adam Eivy86eaf8f3561f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3e9583daac..c41c3f5724 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -29,6 +29,7 @@## Internal+- **[issue-3080] Image-to-3D target registration now owns install and render dispatch** — availability, installed-state, install, and render for every image→3D target now resolve through one adapter registry (`server/services/imageTo3d/adapters.js`), keyed by target id. Previously the TRELLIS.2 install route and the model-render dispatcher each hard-coded `trellis2`-specific branches, and the registry's descriptor pointed at a nonexistent `trellis2Install.js` module. `GET /api/image-to-3d/trellis2/install` keeps working as a compatibility alias for the new generic `GET /api/image-to-3d/targets/:targetId/install`, and the 3D page no longer hard-codes a TRELLIS-specific install URL. Registering a second target is now one adapter entry, not new branches in the route or model service — proven with tests that register a lightweight fake target and drive list/install/render through it.- **[issue-3034] Hugging Face-backed child processes now build their environment through one shared helper** — local image, video, music, MIDI, LoRA, and 3D workflows consistently preserve required system variables while applying resolved Hugging Face credentials.- **Agent guidance split into per-directory and on-demand files — the root `CLAUDE.md` drops from 51k to 32k characters** — the root memory file loads in full on every session, and it had grown past the size where Claude Code warns about a single memory file (~40k characters), so a third of what every session paid for was guidance that only applies in one directory or during one task. Content the codebase already answers on its own is gone: the `server/`/`client/src/` directory tour (`ls` shows it), the Tailwind design-token list (defined in `client/src/index.css`, and the copy had gone stale — it omitted `--port-accent-2`), the standard `npm start`/`npm run dev`/pm2 invocations (in `package.json` scripts), and the slashdo submodule mechanics (in `.gitmodules`). One stale claim was corrected rather than moved: the architecture intro still said data persists to JSON files in `data/`, contradicting the Storage backend policy further down the same file. The rest moved to where it loads on demand — `client/src/CLAUDE.md` (UI conventions, routing/deep-linking, the shared `Drawer` convention) and `server/CLAUDE.md` (schema parity, write serialization, peer fan-out in tests, prompt-template migrations) load only when working in those trees, while three new project skills (`portos-add-page`, `portos-socket-ui`, `portos-file-issue`) keep just a one-line description resident and load their bodies on invocation. The backup service's rsync-anchoring failure mode moved into `docs/BACKUP.md` beside the exclude-tier documentation it belongs with. Every safety-critical prohibition, the Security Model, the Storage backend policy, the AI Provider Usage Policy, and the Sensitive Data & Privacy rules stay in the always-loaded root file — a "never do X" rule must never move somewhere it might not be loaded when it matters. Each migrated block was moved verbatim, with a one-line pointer left behind at the source.- **[issue-3016] The sprite atlas grid can now pack multiple animation tracks of differing lengths** — the runtime grid was walk-shaped by construction: `atlasColumns()` was literally `['idle', ...walkLabels]`, and the compiler refused any set whose directions disagreed on frame count. Both were right for a one-animation world and both blocked a second track — a four-frame action beside a twelve-frame walk needs variable-length column spans. A new sharp-free leaf, `server/services/sprites/atlasGrid.js`, owns the grid the compiler (`atlas.js`, which imports sharp) and the published sidecar (`atlasLayout.js`, which must not) now share: `buildAtlasGrid` emits `idle` first and then each track's contiguous span in registry-registration order, returning the flat `columns` list and the `{ start, count }` `tracks` descriptor together so the two can never drift; `resolveTrackUniformity` resolves one track's frame count and fps from its per-direction rows, asserting the 8 facings agree while **never** comparing one track to another and range-checking against the *named track's* #3015 registry row rather than the global walk-shaped 6–16 / 4–24 constants. That within-track-not-between-track rule is the central semantic change. The compiler persists `geometry.tracks` into the manifest and pointer, `buildAtlasLayout` republishes it, and the pre-pixel idempotency check (which #2986 already taught to compare the column list) now compares the **track set** too, so re-partitioning the same columns into different tracks correctly invalidates instead of reading as up to date. Legacy is fully preserved: a grid with no `tracks` field falls back to the historical column-name derivation — so pre-#3016 atlases stay idempotent instead of recompiling their pixels forever — a pre-#2986 `scanner` placeholder still describes itself honestly, and walk keeps its exact historical column labels. Absent and present-but-empty stay distinct: `{}` is a descriptor that fails to describe the grid and is refused, never silently re-derived. No migration is needed (the field is additive and every reader has a fallback), and no second track is registered here — the multi-track paths are proven against a synthetic registry TABLE (the injected-table idiom `assertAnimationTrackRows` already uses, so a synthetic row flows through exactly the lookup, ordering and unknown-id boundary a real one would), since shipping a real second track is #3018's job.diff --git a/client/src/pages/Media3D.jsx b/client/src/pages/Media3D.jsxindex 64efeb63ca..f49c8de1ac 100644--- a/client/src/pages/Media3D.jsx+++ b/client/src/pages/Media3D.jsx@@ -516,7 +516,7 @@ export default function Media3D() {open={!!installTarget}runtime={installTarget?.id}label={installTarget?.label}- installUrlBase="/api/image-to-3d/trellis2/install"+ installUrlBase={installTarget ? `/api/image-to-3d/targets/${installTarget.id}/install` : undefined}// Repairing an already-installed target must re-run setup.sh rather than// short-circuit on "already installed" — that re-run is what rebuilds the// Metal texture-baking backends once the Metal Toolchain is present (#2952).diff --git a/server/routes/imageTo3d.genericDispatch.test.js b/server/routes/imageTo3d.genericDispatch.test.jsnew file mode 100644index 0000000000..5e88202f0f--- /dev/null+++ b/server/routes/imageTo3d.genericDispatch.test.js@@ -0,0 +1,99 @@+import { describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// Proves GET /targets and the install SSE route dispatch purely through the+// target-descriptor (targets.js) + adapter-registry (adapters.js) contracts — a+// second, unrelated target needs zero new branches in routes/imageTo3d.js+// (#3080). These fakes deliberately share no code with TRELLIS.2.++const FAKE_TARGET = Object.freeze({+ id: 'fakegen',+ label: 'FakeGen',+ executionLane: 'hosted-api',+ outputKind: 'glb-mesh',+ available: true,+ unavailableReason: null,+});++vi.mock('../services/imageTo3d/targets.js', () => ({+ detectHostCapabilities: vi.fn(() => ({ appleSilicon: true, unifiedMemoryGb: 128, cuda: false })),+ getTarget: vi.fn((id) => (id === 'fakegen' ? FAKE_TARGET : null)),+ listTargets: vi.fn(() => [FAKE_TARGET]),+ isTargetAvailable: vi.fn(() => true),+ unavailableReason: vi.fn(() => null),+ IMAGE_TO_3D_TARGET_IDS: ['fakegen'],+}));++const fakeIsInstalled = vi.fn(() => false);+const fakeInstall = vi.fn(({ onEvent }) => {+ onEvent({ type: 'stage', stage: 'fake-step', message: 'installing FakeGen…' });+ onEvent({ type: 'complete', message: 'FakeGen installed.' });+ return { promise: Promise.resolve({ ok: true }), kill: vi.fn() };+});+const fakeDescribeInstallState = vi.fn(async () => ({ fields: { fakeDiag: 'ok' }, warnings: [] }));++vi.mock('../services/imageTo3d/adapters.js', () => ({+ getTargetAdapter: vi.fn((id) => (id === 'fakegen' ? {+ isInstalled: fakeIsInstalled,+ install: fakeInstall,+ run: vi.fn(),+ describeInstallState: fakeDescribeInstallState,+ } : null)),+}));++vi.mock('../lib/hfToken.js', () => ({ hfChildEnv: vi.fn(async () => ({})) }));++vi.mock('../services/imageTo3d/models.js', () => ({+ listModels: vi.fn(),+ getModel: vi.fn(),+ createModel: vi.fn(),+ startGeneration: vi.fn(),+ deleteModel: vi.fn(),+ getModelAsset: vi.fn(),+}));++import routes from './imageTo3d.js';++const makeApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/image-to-3d', routes);+ app.use(errorMiddleware);+ return app;+};++const sseFrames = (text) => text+ .split('\n')+ .filter((l) => l.startsWith('data: '))+ .map((l) => JSON.parse(l.slice(6)));++describe('image-to-3d generic target dispatch (#3080)', () => {+ it('GET /targets resolves installed-state through the adapter registry alone', async () => {+ const res = await request(makeApp()).get('/api/image-to-3d/targets');+ expect(res.status).toBe(200);+ expect(res.body.targets[0]).toMatchObject({ id: 'fakegen', installed: false });+ expect(fakeDescribeInstallState).not.toHaveBeenCalled();+ });++ it('GET /targets merges describeInstallState fields once installed', async () => {+ fakeIsInstalled.mockReturnValueOnce(true);+ const res = await request(makeApp()).get('/api/image-to-3d/targets');+ expect(res.body.targets[0]).toMatchObject({ installed: true, fakeDiag: 'ok' });+ });++ it('GET /targets/:targetId/install dispatches to the registered adapter', async () => {+ const res = await request(makeApp()).get('/api/image-to-3d/targets/fakegen/install');+ const frames = sseFrames(res.text);+ expect(frames).toContainEqual({ type: 'stage', stage: 'fake-step', message: 'installing FakeGen…' });+ expect(frames.at(-1)).toMatchObject({ type: 'complete' });+ expect(fakeInstall).toHaveBeenCalled();+ });++ it('errors on install for a target id with no registered adapter', async () => {+ const res = await request(makeApp()).get('/api/image-to-3d/targets/nope/install');+ const frames = sseFrames(res.text);+ expect(frames.at(-1)).toMatchObject({ type: 'error', message: expect.stringMatching(/Unknown/) });+ });+});diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.jsindex 0f7cfe8e95..141d5bcbcf 100644--- a/server/routes/imageTo3d.js+++ b/server/routes/imageTo3d.js@@ -4,19 +4,14 @@ import { z } from 'zod';import { asyncHandler, ServerError, sendErrorResponse } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import {+ getTarget,listTargets,detectHostCapabilities,isTargetAvailable,unavailableReason,IMAGE_TO_3D_TARGET_IDS,} from '../services/imageTo3d/targets.js';-import {- isTrellis2Installed,- installTrellis2,- trellis2Root,- probeTrellis2TextureBake,- probeMetalToolchain,-} from '../services/imageTo3d/trellis2.js';+import { getTargetAdapter } from '../services/imageTo3d/adapters.js';import {listModels,getModel,@@ -40,125 +35,101 @@ const createModelSchema = z.object({target: z.enum([...IMAGE_TO_3D_TARGET_IDS]).optional(),});-// In-flight singleton — a rapid double-click would otherwise race two clone/setup-// processes against the same install dir. isTrellis2Installed() can't gate the-// second click (the first install hasn't produced the venv yet). Mirrors-// imageGenSetup.js's flux2InstallInFlight.-let trellis2InstallInFlight = null;--// Per-target local-install probe. Targets with no local install concept (hosted-// APIs) report null. Single dispatch point so the route stays thin as targets grow.-const targetInstalled = (targetId) => {- if (targetId === 'trellis2') return isTrellis2Installed();- return null;-};+// In-flight installs, keyed by target id — a rapid double-click would otherwise+// race two clone/setup processes against the same install dir. isInstalled() can't+// gate the second click (the first install hasn't produced the venv yet). Mirrors+// imageGenSetup.js's flux2InstallInFlight, generalized per-target.+const installsInFlight = new Map();/*** The selectable image→3D targets, each annotated with whether it can run on* this host (Apple Silicon / memory gating) and whether its local model is* installed — so the client can render a target selector with disabled /* needs-install / ready states. Read-only, no LLM/GPU work — safe to call on- * load. Later phases add the create/generate/asset endpoints.+ * load. Availability/installed-state/extra diagnostics resolve through each+ * target's adapter (`services/imageTo3d/adapters.js`) — adding a target needs no+ * new branch here.*/router.get('/targets', asyncHandler(async (_req, res) => {const capabilities = detectHostCapabilities();- const targets = listTargets(capabilities).map((target) => ({- ...target,- installed: targetInstalled(target.id),+ const targets = await Promise.all(listTargets(capabilities).map(async (target) => {+ const adapter = getTargetAdapter(target.id);+ const installed = adapter ? adapter.isInstalled() : null;+ // An installed target can still be silently degraded (e.g. TRELLIS.2's Metal+ // texture bake — #2952); a target's adapter opts into reporting that via+ // `describeInstallState()`. Only probed once installed — there is nothing to+ // report before then.+ const state = installed && adapter?.describeInstallState ? await adapter.describeInstallState() : null;+ return { ...target, installed, ...state?.fields };}));- // An installed TRELLIS.2 can still be silently degraded: `setup.sh` swallows a- // failed Metal-backend build and exits 0, after which every render bakes a- // scrambled surface. Surface that here so the target card can warn instead of- // reporting a flat "Ready" (#2952). Skipped when it isn't installed — there is- // nothing to probe, and the venv Python doesn't exist yet.- const trellis2 = targets.find((t) => t.id === 'trellis2');- if (trellis2?.installed) {- const bake = await probeTrellis2TextureBake();- // A degraded bake has two very different remedies, and the card must not offer- // the wrong one: when the Metal Toolchain is merely missing, Repair install- // fetches it and rebuilds (#3041); when only the Command Line Tools are active- // there is nothing PortOS can run, and the user has to install Xcode first.- // Only probe the toolchain when degraded — a healthy install needs no remedy.- const toolchain = bake.quality === 'fallback' ? await probeMetalToolchain() : null;- trellis2.textureBake = toolchain?.blocker- ? { ...bake, repairable: false, blocker: toolchain.blocker, help: toolchain.hint }- : { ...bake, ...(bake.quality === 'fallback' ? { repairable: true } : {}) };- }res.json({ capabilities, targets });}));/**- * SSE-driven TRELLIS.2 local install. The client opens an EventSource and gets- * staged progress (`stage` → `log` → `complete` / `error`) while the ~15 GB clone- * + `setup.sh` runs. Gated on hardware support (Apple Silicon + memory) and- * single-flighted; killed if the client navigates away. Only fires the real- * install on this explicit user request — never from boot (CLAUDE.md no-cold-- * bootstrap policy). Mirrors imageGenSetup.js's `/flux2-install`.+ * SSE-driven target install/repair, shared by every registered target. The+ * client opens an EventSource and gets staged progress (`stage` → `log` →+ * `complete` / `error`) while the target's adapter installs. Gated on hardware+ * support and single-flighted per target; killed if the client navigates away.+ * Only fires the real install on this explicit user request — never from boot+ * (CLAUDE.md no-cold-bootstrap policy). Mirrors imageGenSetup.js's `/flux2-install`.*/-router.get('/trellis2/install', asyncHandler(async (req, res) => {+async function handleTargetInstall(targetId, req, res) {const { send, safeEnd } = openSseStream(res);- // `repair=1` re-runs `setup.sh` over an existing install. That is the documented- // fix for a degraded Metal texture bake: the clone step self-skips (the repo is- // present) and setup.sh's pip installs re-attempt the Metal packages that failed- // to compile the first time, while its `if [ ! -d ]` guards keep the ~15 GB of- // already-downloaded weights. Without this the "Repair install" button would hit- // the already-installed short-circuit below and do nothing (#2952).+ const target = getTarget(targetId);+ const adapter = getTargetAdapter(targetId);+ if (!target || !adapter?.install) {+ send({ type: 'error', message: `Unknown or non-installable image-to-3D target: ${targetId}` });+ return safeEnd();+ }++ // `repair=1` re-runs setup over an existing install. That is the documented fix+ // for a degraded install (e.g. TRELLIS.2's Metal texture bake — #2952): without+ // it, "Repair install" would hit the already-installed short-circuit below and+ // do nothing.const repair = req.query.repair === '1';- if (isTrellis2Installed() && !repair) {- send({ type: 'stage', stage: 'verify', message: 'TRELLIS.2 already installed.' });- // "Installed" is not the same as "installed well" — tell the user when this one- // needs repairing rather than a bare "nothing to do".- const bake = await probeTrellis2TextureBake();- if (bake.quality === 'fallback') {- send({ type: 'log', stage: 'verify', message: `⚠️ ${bake.help}` });- }+ if (adapter.isInstalled() && !repair) {+ send({ type: 'stage', stage: 'verify', message: `${target.label} already installed.` });+ // "Installed" is not the same as "installed well" — surface any adapter+ // warning (e.g. a degraded TRELLIS.2 texture bake) instead of a bare+ // "nothing to do".+ const state = adapter.describeInstallState ? await adapter.describeInstallState() : null;+ (state?.warnings || []).forEach((message) => send({ type: 'log', stage: 'verify', message: `⚠️ ${message}` }));send({ type: 'complete', message: 'Already installed — nothing to do.' });return safeEnd();}- // Refuse on unsupported hardware rather than clone 15 GB that can never run.+ // Refuse on unsupported hardware rather than clone a multi-GB install that can+ // never run.const capabilities = detectHostCapabilities();- if (!isTargetAvailable('trellis2', capabilities)) {+ if (!isTargetAvailable(targetId, capabilities)) {send({type: 'error',- message: `This host cannot run TRELLIS.2 (${unavailableReason('trellis2', capabilities)}). Install skipped.`,+ message: `This host cannot run ${target.label} (${unavailableReason(targetId, capabilities)}). Install skipped.`,});return safeEnd();}- if (trellis2InstallInFlight) {- send({ type: 'error', message: 'A TRELLIS.2 install is already running. Wait for it to finish or restart PortOS.' });+ if (installsInFlight.has(targetId)) {+ send({ type: 'error', message: `A ${target.label} install is already running. Wait for it to finish or restart PortOS.` });return safeEnd();}+ // Claim the in-flight slot synchronously, before any await, so two+ // near-simultaneous requests for the same target can't both pass the check above.+ installsInFlight.set(targetId, true);// Server-console visibility for the multi-GB install (start / stages / outcome).- const installLog = createInstallLogger({ installer: 'TRELLIS.2', target: trellis2Root() });+ const installLog = createInstallLogger({ installer: target.label, target: targetId });const emit = (event) => { installLog.onEvent(event); send(event); };installLog.start();- // Resolve the Metal Toolchain situation before spawning anything. `setup.sh`- // compiles its texture-baking backends from `.metal` sources but swallows each- // failure and still exits 0, so a host missing the toolchain would otherwise- // finish "successfully" and render scrambled surfaces forever (#2952). When it's- // missing but fetchable, the install downloads it as a leading optional step- // (#3041); when only the Command Line Tools are active nothing we can run fixes- // it, so warn and install anyway — geometry is unaffected and the `verify` step- // reports the degraded bake.- const toolchain = await probeMetalToolchain();- if (toolchain.blocker) emit({ type: 'log', stage: 'preflight', message: `⚠️ ${toolchain.hint}` });- const installMetalToolchain = toolchain.available === false && toolchain.installable === true;- if (installMetalToolchain) {- emit({ type: 'log', stage: 'preflight', message: `ℹ️ ${toolchain.hint}` });- }-// Disconnect bookkeeping wired BEFORE the token-resolution await below (the// same hazard `lib/sseDownload.js` documents): that await does a settings read// plus a token-file read, and a client closing during it would otherwise land- // with no listener — the handler would go on to spawn a ~15 GB clone with no- // kill path, leaving `trellis2InstallInFlight` pinned until it finished on its- // own and blocking every later Install click.+ // with no listener — the handler would go on to spawn a multi-GB clone with no+ // kill path, leaving the in-flight slot pinned until it finished on its own and+ // blocking every later Install click.let currentKill = null;let aborted = false;req.on('close', () => {@@ -167,42 +138,41 @@ router.get('/trellis2/install', asyncHandler(async (req, res) => {// `close` also fires on normal completion; only a live handle means an// install was actually mid-flight.if (currentKill) currentKill();+ installsInFlight.delete(targetId);safeEnd();});- // Carry the stored HF token into the install too: setup.sh doesn't pull gated- // weights today, but a future prefetch step would, and one env source beats two.- // Guarded because the SSE headers are already flushed by this point — a throw- // here (e.g. an unparseable settings.json) can't reach the error middleware as- // JSON, so it has to surface as a terminal `error` frame or the client hangs on- // a half-open stream.+ // Carry the stored HF token into the install too: not every target needs it,+ // but a target that pulls gated weights does, and one env source beats two per+ // adapter. Guarded because the SSE headers are already flushed by this point —+ // a throw here (e.g. an unparseable settings.json) can't reach the error+ // middleware as JSON, so it has to surface as a terminal `error` frame or the+ // client hangs on a half-open stream.let installEnv;try {installEnv = await hfChildEnv();} catch (err) {- console.error(`❌ TRELLIS.2 install could not resolve the Hugging Face token env: ${err.message}`);+ console.error(`❌ ${target.label} install could not resolve the Hugging Face token env: ${err.message}`);emit({ type: 'error', message: `Could not read settings to resolve the Hugging Face token: ${err.message}` });+ installsInFlight.delete(targetId);return safeEnd();}// The client hung up during the await — don't start a multi-GB install nobody// is listening to.if (aborted) return safeEnd();- const { promise, kill } = installTrellis2({- onEvent: emit,- env: installEnv,- installMetalToolchain,- });+ const { promise, kill } = await adapter.install({ onEvent: emit, env: installEnv });+ // The client may have hung up while the adapter ran its own async preflight+ // (e.g. a toolchain probe) — terminate whatever it just spawned rather than+ // let an orphaned install run unattended.+ if (aborted) return kill();currentKill = kill;- trellis2InstallInFlight = promise;promise- // `installTrellis2` emits its own post-install `verify` frame (Metal bake- // present or degraded) before the terminal `complete` — see #2952..then(() => installLog.success()).catch((err) => {- // A transient network drop that survived the in-install retries: the partial- // clones on disk are idempotent (setup.sh's `if [ ! -d ]` guards + git's- // failed-clone cleanup), so re-running Install resumes rather than restarts.+ // A transient network drop that survived the in-install retries: partial+ // clones on disk are typically idempotent (resumable), so re-running Install+ // resumes rather than restarts.const hint = err?.transient? ' This looks like a network hiccup — click Install again to resume (already-downloaded pieces are kept).': '';@@ -210,10 +180,16 @@ router.get('/trellis2/install', asyncHandler(async (req, res) => {}).finally(() => {currentKill = null;- trellis2InstallInFlight = null;+ installsInFlight.delete(targetId);safeEnd();});-}));+}++router.get('/targets/:targetId/install', asyncHandler((req, res) => handleTargetInstall(req.params.targetId, req, res)));++// Compatibility alias for the pre-#3080 TRELLIS.2-specific install URL — existing+// client bookmarks/links keep working.+router.get('/trellis2/install', asyncHandler((req, res) => handleTargetInstall('trellis2', req, res)));// ── Image-to-3D model records ─────────────────────────────────────────────// Namespaced under /models so `/:id` never shadows the `/targets` anddiff --git a/server/routes/imageTo3d.test.js b/server/routes/imageTo3d.test.jsindex fd18a0ebf7..777be3e889 100644--- a/server/routes/imageTo3d.test.js+++ b/server/routes/imageTo3d.test.js@@ -8,24 +8,26 @@ import { errorMiddleware } from '../lib/errorHandler.js';// Mock the services so the route test is deterministic regardless of the test// host's real arch/memory and never touches a real subprocess.+const TRELLIS2_TARGET = {+ id: 'trellis2',+ label: 'TRELLIS.2',+ executionLane: 'local-mps',+ outputKind: 'glb-mesh',+ unavailableReason: null,+ gatedRepos: [+ {+ label: 'facebook/dinov3-vitl16-pretrain-lvd1689m',+ url: 'https://huggingface.co/facebook/dinov3-vitl16-pretrain-lvd1689m',+ },+ { label: 'briaai/RMBG-2.0', url: 'https://huggingface.co/briaai/RMBG-2.0' },+ ],+};+vi.mock('../services/imageTo3d/targets.js', () => ({detectHostCapabilities: vi.fn(() => ({ appleSilicon: true, unifiedMemoryGb: 128, cuda: false })),+ getTarget: vi.fn((id) => (id === 'trellis2' ? TRELLIS2_TARGET : null)),listTargets: vi.fn((caps) => [- {- id: 'trellis2',- label: 'TRELLIS.2',- executionLane: 'local-mps',- outputKind: 'glb-mesh',- available: caps.appleSilicon && caps.unifiedMemoryGb >= 24,- unavailableReason: null,- gatedRepos: [- {- label: 'facebook/dinov3-vitl16-pretrain-lvd1689m',- url: 'https://huggingface.co/facebook/dinov3-vitl16-pretrain-lvd1689m',- },- { label: 'briaai/RMBG-2.0', url: 'https://huggingface.co/briaai/RMBG-2.0' },- ],- },+ { ...TRELLIS2_TARGET, available: caps.appleSilicon && caps.unifiedMemoryGb >= 24 },]),isTargetAvailable: vi.fn(() => true),unavailableReason: vi.fn(() => 'requires-apple-silicon'),@@ -40,6 +42,10 @@ vi.mock('../services/imageTo3d/trellis2.js', () => ({onEvent({ type: 'complete', message: 'TRELLIS.2 installed.' });return { promise: Promise.resolve({ ok: true }), kill: vi.fn() };}),+ // Not exercised by these route-level tests (render dispatch is covered in+ // models.test.js), but the adapter registry imports it — an incomplete mock+ // here would 'no export defined' at import time.+ runTrellis2Generate: vi.fn(),// Both probes shell out (venv python / `xcrun metal`). Mocked to the healthy// result so the suite never touches the host toolchain; individual tests below// override them to drive the degraded-install branches (#2952).diff --git a/server/services/imageTo3d/adapters.js b/server/services/imageTo3d/adapters.jsnew file mode 100644index 0000000000..95231e519c--- /dev/null+++ b/server/services/imageTo3d/adapters.js@@ -0,0 +1,81 @@+/**+ * Image-to-3D — target adapter registry.+ *+ * The single wiring point between a target's pure descriptor (`targets.js`) and+ * its actual install/runner implementation. `targets.js` stays a dependency-light+ * set of descriptors with no imported runners; this module is the impure boundary+ * that resolves a target id to real functions. Availability comes from+ * `targets.js`; installed-state, install dispatch, and render dispatch for every+ * target all resolve through `getTargetAdapter()` here — adding a second target is+ * one registration in this file (plus its descriptor in `targets.js`), not new+ * branches in `routes/imageTo3d.js` or `models.js` (#3080).+ *+ * Adapter contract:+ * - `isInstalled()` — boolean; is the target's local runtime present? A target+ * with no local-install concept (a future hosted-API target) would return true.+ * The caller (the install route) uses this to short-circuit an "already+ * installed" request before ever calling `install()`.+ * - `install({ onEvent, env })` — installs (or repairs, when the caller decides+ * an already-installed target should re-run setup — see the route). Returns+ * `{ promise, kill }`. Omit for a target with no install step.+ * - `run({ imagePath, outputPath, onProgress, env })` — renders; returns+ * `{ promise, kill }`, `promise` resolving `{ assetPath }`.+ * - `describeInstallState?()` — optional extra per-target diagnostics: async,+ * returns `{ warnings?: string[], fields?: object }`. `warnings` are generic+ * user-facing strings the route can surface (e.g. on an "already installed"+ * short-circuit) without knowing what they're about; `fields` are extra keys+ * merged onto the target in `GET /targets` (e.g. TRELLIS.2's texture-bake+ * quality). Omit when a target has nothing extra to report.+ */++import {+ isTrellis2Installed,+ installTrellis2,+ runTrellis2Generate,+ probeTrellis2TextureBake,+ probeMetalToolchain,+} from './trellis2.js';++export const TARGET_ADAPTERS = Object.freeze({+ trellis2: Object.freeze({+ isInstalled: isTrellis2Installed,+ async install({ onEvent = () => {}, env } = {}) {+ // `setup.sh` compiles its texture-baking backends from `.metal` sources but+ // swallows each failure and still exits 0, so a host missing the toolchain+ // would otherwise finish "successfully" and render scrambled surfaces+ // forever (#2952). Resolve it before spawning anything so the fetch can be+ // added as a leading install step (#3041), or at least warned about.+ const toolchain = await probeMetalToolchain();+ if (toolchain.blocker) onEvent({ type: 'log', stage: 'preflight', message: `⚠️ ${toolchain.hint}` });+ const installMetalToolchain = toolchain.available === false && toolchain.installable === true;+ if (installMetalToolchain) onEvent({ type: 'log', stage: 'preflight', message: `ℹ️ ${toolchain.hint}` });+ return installTrellis2({ onEvent, env, installMetalToolchain });+ },+ run: runTrellis2Generate,+ async describeInstallState() {+ const bake = await probeTrellis2TextureBake();+ const toolchain = bake.quality === 'fallback' ? await probeMetalToolchain() : null;+ // A degraded bake has two very different remedies, and the card must not+ // offer the wrong one: when the Metal Toolchain is merely missing, Repair+ // install fetches it and rebuilds (#3041); when only the Command Line Tools+ // are active there is nothing PortOS can run, and the user has to install+ // Xcode first.+ const textureBake = toolchain?.blocker+ ? { ...bake, repairable: false, blocker: toolchain.blocker, help: toolchain.hint }+ : { ...bake, ...(bake.quality === 'fallback' ? { repairable: true } : {}) };+ return {+ fields: { textureBake },+ warnings: textureBake.quality === 'fallback' ? [textureBake.help] : [],+ };+ },+ }),+});++/**+ * Look up a target's adapter by id.+ * @param {string} id+ * @returns {object|null} the frozen adapter, or null when unknown.+ */+export function getTargetAdapter(id) {+ return (id && TARGET_ADAPTERS[id]) || null;+}diff --git a/server/services/imageTo3d/models.genericDispatch.test.js b/server/services/imageTo3d/models.genericDispatch.test.jsnew file mode 100644index 0000000000..edb8f92e77--- /dev/null+++ b/server/services/imageTo3d/models.genericDispatch.test.js@@ -0,0 +1,87 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++// Proves models.js dispatches create/render purely through the adapter registry+// (adapters.js) — registering an additional target needs no `if (targetId === …)`+// branch in models.js. Deliberately mocks `./adapters.js` directly (not+// `./trellis2.js`, as models.test.js does) with a target that shares no code with+// TRELLIS.2, so a passing test here can't be explained by TRELLIS.2-specific+// wiring (#3080).++vi.mock('node:fs/promises', async (importOriginal) => ({+ ...(await importOriginal()),+ rm: vi.fn(() => Promise.resolve()),+}));++vi.mock('../../lib/fileUtils.js', () => ({+ PATHS: { imageTo3d: '/mock/data/image-to-3d' },+ resolveGalleryImage: vi.fn((filename) => `/mock/data/images/${filename}`),+ ensureDir: vi.fn(() => Promise.resolve()),+}));++vi.mock('./targets.js', () => ({+ DEFAULT_IMAGE_TO_3D_TARGET: 'trellis2',+ detectHostCapabilities: vi.fn(() => ({ appleSilicon: true, unifiedMemoryGb: 128, cuda: false })),+ resolveTarget: vi.fn((id) => ({+ targetId: id, target: { id, label: id }, available: true, reason: null,+ })),+}));++vi.mock('../../lib/hfToken.js', () => ({+ hfChildEnv: vi.fn(async () => ({ HF_TOKEN: 'hf_test' })),+}));++vi.mock('./db.js', () => ({+ listModels: vi.fn(),+ getModel: vi.fn(),+ createModel: vi.fn(),+ mutateModel: vi.fn(),+ deleteModel: vi.fn(),+ recoverInterruptedModels: vi.fn(),+}));++const fakeIsInstalled = vi.fn(() => true);+const fakeRun = vi.fn(() => ({+ promise: Promise.resolve({ assetPath: '/mock/data/image-to-3d/x/model.glb' }),+ kill: vi.fn(),+}));++vi.mock('./adapters.js', () => ({+ getTargetAdapter: vi.fn((id) => (id === 'second-target' ? { isInstalled: fakeIsInstalled, run: fakeRun } : null)),+}));++import * as store from './db.js';+import { createModel } from './models.js';++describe('models.js target dispatch is adapter-registry-driven (#3080)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ fakeIsInstalled.mockReturnValue(true);+ fakeRun.mockReturnValue({+ promise: Promise.resolve({ assetPath: '/mock/data/image-to-3d/x/model.glb' }),+ kill: vi.fn(),+ });+ store.getModel.mockResolvedValue(null);+ });++ it('renders through a newly-registered adapter with no target-specific branch in models.js', async () => {+ let current = { id: 'image3d-2', target: 'second-target', status: 'draft', runs: [] };+ store.createModel.mockImplementation(async () => current);+ store.mutateModel.mockImplementation(async (_id, mutate) => {+ const next = mutate(current);+ if (next) current = next;+ return current;+ });++ const started = await createModel({ name: 'Second', filename: 'shot.png', target: 'second-target' });+ expect(started.status).toBe('generating');++ await vi.waitFor(() => expect(fakeRun).toHaveBeenCalled());+ expect(fakeIsInstalled).toHaveBeenCalled();+ });++ it('501s a target the adapter registry has no adapter for', async () => {+ await expect(createModel({ name: 'Unregistered', filename: 'shot.png', target: 'unregistered' }))+ .rejects.toMatchObject({ status: 501, code: 'TARGET_NO_RUNNER' });+ expect(store.createModel).not.toHaveBeenCalled();+ });+});diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.jsindex 5dc0ac2dcd..76e6ea98c7 100644--- a/server/services/imageTo3d/models.js+++ b/server/services/imageTo3d/models.js@@ -11,7 +11,7 @@* The render NEVER auto-runs: it is only reached from an explicit user create /* generate request, and it is gated on the target being installed + runnable on* this host (CLAUDE.md no-cold-bootstrap AI policy + the host's sensitivity to- * sustained GPU load). Adding a second target is a registration in `TARGET_RUNNERS`,+ * sustained GPU load). Adding a second target is a registration in `adapters.js`,* not a rewrite here.*/@@ -23,7 +23,7 @@ import { hfChildEnv } from '../../lib/hfToken.js';import { PATHS, resolveGalleryImage, ensureDir } from '../../lib/fileUtils.js';import { slugifyForFilename } from '../../lib/civitai.js';import { detectHostCapabilities, resolveTarget, DEFAULT_IMAGE_TO_3D_TARGET } from './targets.js';-import { isTrellis2Installed, runTrellis2Generate } from './trellis2.js';+import { getTargetAdapter } from './adapters.js';import * as store from './db.js';const MAX_RUNS = 30;@@ -33,21 +33,6 @@ const activeOperations = new Set();// spawns (executeRender) and drained in its `finally`.const activeRenders = new Map();-/**- * Per-target install-probe + runner. One dispatch point so registering a new- * image→3D backend is an entry here, not new branches through create/generate.- * A runner takes `{ imagePath, outputPath, onProgress, env }` and returns a- * `{ promise, kill }` pair — `promise` resolves `{ assetPath }`; `kill` SIGTERMs the- * render so a mid-flight delete can terminate it (see `runTrellis2Generate`).- * `env` is a LOCAL-lane concern (the child-process environment, carrying the HF- * token); a future hosted-API runner should ignore it, and when one lands this is- * the seam to generalize into a per-runner credential declaration rather than a- * spawn-shaped bag every target receives.- */-const TARGET_RUNNERS = {- trellis2: { isInstalled: isTrellis2Installed, run: runTrellis2Generate },-};-const trimRuns = (runs) => runs.slice(-MAX_RUNS);const cleanError = (error) => String(error?.message || error || 'Render failed').slice(0, 2_000);@@ -84,7 +69,7 @@ function assertTargetReady(targetId, caps) {{ status: 409, code: 'TARGET_UNAVAILABLE', context: { reason } },);}- const runner = TARGET_RUNNERS[targetId];+ const runner = getTargetAdapter(targetId);if (!runner) {throw new ServerError(`Target ${target.label} has no runner wired`, { status: 501, code: 'TARGET_NO_RUNNER' });}diff --git a/server/services/imageTo3d/targets.js b/server/services/imageTo3d/targets.jsindex 3efeb42d36..55eebe48eb 100644--- a/server/services/imageTo3d/targets.js+++ b/server/services/imageTo3d/targets.js@@ -11,10 +11,10 @@* capabilities as an injected argument rather than probing hardware themselves.* Only `detectHostCapabilities()` touches the real machine, so it's the one* impure boundary (mirroring `platform.js`'s "detect at the route boundary and- * pass into pure services" contract). Runner/installer wiring for a target is- * referenced by module path and lands in later phases (see issue #2951); keeping- * those out of the import graph is what lets this stay a pure, no-side-effect- * registry that boot and tests can import for free.+ * pass into pure services" contract). A target's actual installer/runner is+ * wired separately, in `adapters.js` — keeping runner imports out of this file+ * is what lets it stay a pure, no-side-effect registry that boot and tests can+ * import for free (#3080).*/import os from 'os';@@ -45,8 +45,8 @@ export const OUTPUT_KINDS = Object.freeze(Object.values(OUTPUT_KIND));* no side effects — so a new model is one object added here.** `requires` states the hardware floor for the target's declared lane; the pure- * resolvers below read it. `installerModule`/`runnerModule` are the module paths- * later phases wire up (they are not imported here — see the file header).+ * resolvers below read it. A target's installer/runner is wired in `adapters.js`,+ * keyed by this registry's `id` (not imported here — see the file header).*/export const IMAGE_TO_3D_TARGETS = Object.freeze({trellis2: Object.freeze({@@ -82,9 +82,6 @@ export const IMAGE_TO_3D_TARGETS = Object.freeze({url: 'https://huggingface.co/briaai/RMBG-2.0',}),]),- // Wired in later phases (issue #2951); referenced by path, never imported here.- installerModule: 'server/services/imageTo3d/trellis2Install.js',- runnerModule: 'server/services/imageTo3d/trellis2.js',}),});