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(issue-2952): add TRELLIS.2 local runner scaffolding + install status

[._.]/ Adam Eivy7252f4ef4793
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a677b99ea4..4deef2aa54 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -3,6 +3,7 @@
## Internal
- **[issue-2951] Image-to-3D target registry (foundation)** — added a pluggable `server/services/imageTo3d/targets.js` registry (mirroring `imageGen/modes.js`) that models image→3D models as selectable targets with hardware-gated availability resolution, TRELLIS.2 registered as the first target, and a read-only `GET /api/image-to-3d/targets` endpoint. Backend groundwork for the forthcoming 3D page under Create (#2952 install/runner, #2953 page/viewer, #2954 CUDA lane); no user-visible surface yet.
+- **[issue-2952] TRELLIS.2 local runner scaffolding** — added `server/services/imageTo3d/trellis2.js`: on-disk install detection, pure install/generate command builders, a format-agnostic `generate.py` progress parser, and a guarded generate runner (throws unless installed; never auto-runs). `GET /api/image-to-3d/targets` now also reports each target's `installed` state. The real ~15 GB install + live GPU render are user-triggered and validated hands-on (remainder of #2952); no user-visible surface yet.
## Music studio
diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.js
index c14d3f26e8..6886e036b7 100644
--- a/server/routes/imageTo3d.js
+++ b/server/routes/imageTo3d.js
@@ -4,18 +4,31 @@ import {
listTargets,
detectHostCapabilities,
} from '../services/imageTo3d/targets.js';
+import { isTrellis2Installed } from '../services/imageTo3d/trellis2.js';
const router = Router();
+// 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;
+};
+
/**
* The selectable image→3D targets, each annotated with whether it can run on
- * this host (Apple Silicon / memory gating) so the client can render a target
- * selector with disabled / needs-install states. Read-only, no LLM/GPU work —
- * safe to call on load. Later phases add the create/generate/asset endpoints.
+ * 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.
*/
router.get('/targets', asyncHandler(async (_req, res) => {
const capabilities = detectHostCapabilities();
- res.json({ capabilities, targets: listTargets(capabilities) });
+ const targets = listTargets(capabilities).map((target) => ({
+ ...target,
+ installed: targetInstalled(target.id),
+ }));
+ res.json({ capabilities, targets });
}));
export default router;
diff --git a/server/routes/imageTo3d.test.js b/server/routes/imageTo3d.test.js
index bb1b4523ce..9816907704 100644
--- a/server/routes/imageTo3d.test.js
+++ b/server/routes/imageTo3d.test.js
@@ -19,6 +19,10 @@ vi.mock('../services/imageTo3d/targets.js', () => ({
]),
}));
+vi.mock('../services/imageTo3d/trellis2.js', () => ({
+ isTrellis2Installed: vi.fn(() => false),
+}));
+
import routes from './imageTo3d.js';
const makeApp = () => {
@@ -35,6 +39,6 @@ describe('image-to-3d routes', () => {
expect(res.status).toBe(200);
expect(res.body.capabilities).toMatchObject({ appleSilicon: true, unifiedMemoryGb: 128 });
expect(Array.isArray(res.body.targets)).toBe(true);
- expect(res.body.targets[0]).toMatchObject({ id: 'trellis2', available: true });
+ expect(res.body.targets[0]).toMatchObject({ id: 'trellis2', available: true, installed: false });
});
});
diff --git a/server/services/imageTo3d/trellis2.js b/server/services/imageTo3d/trellis2.js
new file mode 100644
index 0000000000..b101aabc27
--- /dev/null
+++ b/server/services/imageTo3d/trellis2.js
@@ -0,0 +1,169 @@
+/**
+ * TRELLIS.2 (local Apple Silicon / MPS) target — install detection, pure command
+ * builders, a robust progress parser, and a guarded generate runner.
+ *
+ * Phase 2a of #2951/#2952: the *scaffolding* the install SSE route and the 3D page
+ * will drive. Everything here is either pure (path/arg/step builders, the progress
+ * parser) or exercised only through injectable dependencies (`exists`, `spawnImpl`)
+ * so the wiring is unit-testable **without** downloading the ~15 GB model or running
+ * a live GPU render. `runTrellis2Generate` is the one real-subprocess boundary and
+ * NEVER auto-runs — it throws unless the model is installed and is only reached from
+ * an explicit user action (CLAUDE.md no-cold-bootstrap policy). The exact wording of
+ * `generate.py`'s progress output is refined during hands-on validation, so the
+ * parser keys on format-agnostic signals (a percentage, a `.glb` path) rather than
+ * guessing internal stage names.
+ *
+ * Install layout mirrors the FLUX.2 venv convention in `pythonSetup.js`
+ * (`~/.portos/...`): the `trellis-mac` repo is cloned to `~/.portos/trellis2` and its
+ * `setup.sh` builds a `.venv` inside it.
+ */
+
+import { existsSync } from 'node:fs';
+import { homedir, platform } from 'node:os';
+import { join } from 'node:path';
+import { spawn } from 'node:child_process';
+
+const HOME = homedir();
+const IS_WIN = platform() === 'win32';
+
+/** The Apple Silicon MPS port of Microsoft TRELLIS.2. */
+export const TRELLIS2_REPO = 'https://github.com/shivampkumar/trellis-mac';
+
+/** Clone/install root. `base` overridable for tests. */
+export function trellis2Root(base = join(HOME, '.portos')) {
+ return join(base, 'trellis2');
+}
+
+/** The venv Python the `setup.sh` script builds inside the clone. */
+export function trellis2VenvPython(base) {
+ const root = trellis2Root(base);
+ return IS_WIN
+ ? join(root, '.venv', 'Scripts', 'python.exe')
+ : join(root, '.venv', 'bin', 'python3');
+}
+
+/** The port's single-image entrypoint (`python generate.py <image>`). */
+export function trellis2GenerateScript(base) {
+ return join(trellis2Root(base), 'generate.py');
+}
+
+/**
+ * Installed ⇔ the venv Python AND the generate script both exist. `exists` is
+ * injectable so the check is deterministic in tests.
+ * @param {{base?: string, exists?: (p: string) => boolean}} [opts]
+ * @returns {boolean}
+ */
+export function isTrellis2Installed({ base, exists = existsSync } = {}) {
+ return exists(trellis2VenvPython(base)) && exists(trellis2GenerateScript(base));
+}
+
+/**
+ * The install as an ordered list of `{stage, command, args, cwd?}` steps: shallow-
+ * clone the port, then run its `setup.sh` (which builds the venv + fetches weights).
+ * Pure — the SSE install route executes these; keeping them a data structure makes
+ * the plan assertable without running it.
+ * @param {string} [base]
+ * @returns {Array<{stage: string, command: string, args: string[], cwd?: string}>}
+ */
+export function buildInstallSteps(base) {
+ const root = trellis2Root(base);
+ return [
+ { stage: 'clone', command: 'git', args: ['clone', '--depth', '1', TRELLIS2_REPO, root] },
+ { stage: 'setup', command: 'bash', args: ['setup.sh'], cwd: root },
+ ];
+}
+
+/**
+ * The generate invocation: `<venv-python> generate.py <image> [--output <glb>]`.
+ * Pure. Throws when no source image is given (a render with no input is a bug, not
+ * an empty run).
+ * @param {{imagePath: string, outputPath?: string, base?: string}} opts
+ * @returns {{command: string, args: string[]}}
+ */
+export function buildGenerateArgs({ imagePath, outputPath, base } = {}) {
+ if (!imagePath) throw new Error('buildGenerateArgs: imagePath is required');
+ const args = [trellis2GenerateScript(base), imagePath];
+ if (outputPath) args.push('--output', outputPath);
+ return { command: trellis2VenvPython(base), args };
+}
+
+/**
+ * Parse one line of `generate.py` output into a progress frame, or null when the
+ * line carries no signal. Format-agnostic on purpose (the port's exact wording is
+ * confirmed during hands-on validation): it extracts a percentage and/or a written
+ * `.glb` path rather than matching guessed internal stage names.
+ * @param {string} line
+ * @returns {{stage: string, percent?: number, assetPath?: string, message: string}|null}
+ */
+export function parseGenerateProgress(line) {
+ const text = String(line ?? '').trim();
+ if (!text) return null;
+ const pct = text.match(/(\d{1,3})\s*%/);
+ const glb = text.match(/(\S+\.glb)\b/i);
+ const frame = { message: text };
+ if (pct) frame.percent = Math.min(100, Number(pct[1]));
+ if (glb) {
+ frame.stage = 'export';
+ frame.assetPath = glb[1];
+ } else if (pct) {
+ frame.stage = 'generating';
+ } else {
+ return null;
+ }
+ return frame;
+}
+
+/**
+ * Run a single image→GLB generation. The one real-subprocess boundary — GUARDED:
+ * throws `TRELLIS2_NOT_INSTALLED` unless the model is present, so it can never run
+ * from a cold boot. `spawnImpl`/`exists` are injectable so the wiring (right command,
+ * progress streaming, resolve-with-asset) is unit-testable without a real render.
+ *
+ * @param {{imagePath: string, outputPath?: string, base?: string,
+ * onProgress?: (frame: object) => void,
+ * spawnImpl?: Function, exists?: (p: string) => boolean}} opts
+ * @returns {Promise<{assetPath: string}>}
+ */
+export function runTrellis2Generate({
+ imagePath,
+ outputPath,
+ base,
+ onProgress,
+ spawnImpl = spawn,
+ exists = existsSync,
+} = {}) {
+ if (!isTrellis2Installed({ base, exists })) {
+ const err = new Error('TRELLIS.2 is not installed — install it before generating.');
+ err.code = 'TRELLIS2_NOT_INSTALLED';
+ return Promise.reject(err);
+ }
+ const { command, args } = buildGenerateArgs({ imagePath, outputPath, base });
+ return new Promise((resolve, reject) => {
+ // Child-process boundary — errors surface via the 'error'/'close' events, not a
+ // throw into the request lifecycle (CLAUDE.md child-process exception).
+ const child = spawnImpl(command, args, { cwd: trellis2Root(base) });
+ let assetPath = outputPath || null;
+ const ingest = (buf) => {
+ for (const line of String(buf).split('\n')) {
+ const frame = parseGenerateProgress(line);
+ if (!frame) continue;
+ if (frame.assetPath) assetPath = frame.assetPath;
+ if (onProgress) onProgress(frame);
+ }
+ };
+ child.stdout?.on('data', ingest);
+ child.stderr?.on('data', ingest);
+ child.on('error', reject);
+ child.on('close', (code) => {
+ if (code === 0 && assetPath) {
+ resolve({ assetPath });
+ return;
+ }
+ const err = new Error(
+ code === 0 ? 'TRELLIS.2 finished but produced no .glb' : `TRELLIS.2 generate exited ${code}`,
+ );
+ err.code = 'TRELLIS2_GENERATE_FAILED';
+ reject(err);
+ });
+ });
+}
diff --git a/server/services/imageTo3d/trellis2.test.js b/server/services/imageTo3d/trellis2.test.js
new file mode 100644
index 0000000000..aa38c6f71d
--- /dev/null
+++ b/server/services/imageTo3d/trellis2.test.js
@@ -0,0 +1,165 @@
+import { EventEmitter } from 'node:events';
+import { describe, expect, it, vi } from 'vitest';
+import {
+ TRELLIS2_REPO,
+ trellis2Root,
+ trellis2VenvPython,
+ trellis2GenerateScript,
+ isTrellis2Installed,
+ buildInstallSteps,
+ buildGenerateArgs,
+ parseGenerateProgress,
+ runTrellis2Generate,
+} from './trellis2.js';
+
+const BASE = '/tmp/portos-test-home';
+
+describe('trellis2 path resolution', () => {
+ it('roots the install under the injected base', () => {
+ expect(trellis2Root(BASE)).toBe('/tmp/portos-test-home/trellis2');
+ expect(trellis2VenvPython(BASE)).toMatch(/trellis2\/\.venv\/(bin\/python3|Scripts\/python\.exe)$/);
+ expect(trellis2GenerateScript(BASE)).toBe('/tmp/portos-test-home/trellis2/generate.py');
+ });
+});
+
+describe('isTrellis2Installed', () => {
+ const venv = trellis2VenvPython(BASE);
+ const script = trellis2GenerateScript(BASE);
+
+ it('is installed only when BOTH the venv python and generate.py exist', () => {
+ expect(isTrellis2Installed({ base: BASE, exists: () => true })).toBe(true);
+ });
+
+ it('is not installed when the venv python is missing', () => {
+ expect(isTrellis2Installed({ base: BASE, exists: (p) => p !== venv })).toBe(false);
+ });
+
+ it('is not installed when generate.py is missing', () => {
+ expect(isTrellis2Installed({ base: BASE, exists: (p) => p !== script })).toBe(false);
+ });
+
+ it('is not installed on a clean host', () => {
+ expect(isTrellis2Installed({ base: BASE, exists: () => false })).toBe(false);
+ });
+});
+
+describe('buildInstallSteps', () => {
+ it('clones the MPS port then runs its setup.sh', () => {
+ const steps = buildInstallSteps(BASE);
+ expect(steps.map((s) => s.stage)).toEqual(['clone', 'setup']);
+ expect(steps[0]).toMatchObject({ command: 'git' });
+ expect(steps[0].args).toContain(TRELLIS2_REPO);
+ expect(steps[0].args).toContain(trellis2Root(BASE));
+ expect(steps[1]).toMatchObject({ command: 'bash', args: ['setup.sh'], cwd: trellis2Root(BASE) });
+ });
+});
+
+describe('buildGenerateArgs', () => {
+ it('invokes the venv python with generate.py and the image', () => {
+ const { command, args } = buildGenerateArgs({ imagePath: '/data/images/x.png', base: BASE });
+ expect(command).toBe(trellis2VenvPython(BASE));
+ expect(args).toEqual([trellis2GenerateScript(BASE), '/data/images/x.png']);
+ });
+
+ it('appends --output when an output path is given', () => {
+ const { args } = buildGenerateArgs({ imagePath: 'in.png', outputPath: 'out.glb', base: BASE });
+ expect(args).toEqual([trellis2GenerateScript(BASE), 'in.png', '--output', 'out.glb']);
+ });
+
+ it('throws when no source image is given', () => {
+ expect(() => buildGenerateArgs({ base: BASE })).toThrow(/imagePath is required/);
+ });
+});
+
+describe('parseGenerateProgress', () => {
+ it('extracts a percentage as a generating frame', () => {
+ expect(parseGenerateProgress('sampling 42%')).toMatchObject({ stage: 'generating', percent: 42 });
+ });
+
+ it('clamps an over-100 percentage', () => {
+ expect(parseGenerateProgress('999%').percent).toBe(100);
+ });
+
+ it('recognizes a written .glb as an export frame carrying the asset path', () => {
+ expect(parseGenerateProgress('saved /out/model.glb')).toMatchObject({
+ stage: 'export',
+ assetPath: '/out/model.glb',
+ });
+ });
+
+ it('returns null for lines with no signal, and for blank lines', () => {
+ expect(parseGenerateProgress('loading pipeline weights')).toBeNull();
+ expect(parseGenerateProgress(' ')).toBeNull();
+ expect(parseGenerateProgress(undefined)).toBeNull();
+ });
+});
+
+describe('runTrellis2Generate', () => {
+ const installed = () => true;
+
+ const makeChild = () => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ return child;
+ };
+
+ it('rejects without spawning when the model is not installed', async () => {
+ const spawnImpl = vi.fn();
+ await expect(
+ runTrellis2Generate({ imagePath: 'a.png', base: BASE, exists: () => false, spawnImpl }),
+ ).rejects.toMatchObject({ code: 'TRELLIS2_NOT_INSTALLED' });
+ expect(spawnImpl).not.toHaveBeenCalled();
+ });
+
+ it('wires the generate command, streams progress, and resolves with the produced asset', async () => {
+ const child = makeChild();
+ const spawnImpl = vi.fn(() => child);
+ const frames = [];
+ const promise = runTrellis2Generate({
+ imagePath: 'a.png',
+ base: BASE,
+ exists: installed,
+ spawnImpl,
+ onProgress: (f) => frames.push(f),
+ });
+ expect(spawnImpl).toHaveBeenCalledWith(
+ trellis2VenvPython(BASE),
+ [trellis2GenerateScript(BASE), 'a.png'],
+ { cwd: trellis2Root(BASE) },
+ );
+ child.stdout.emit('data', 'sampling 50%\n');
+ child.stdout.emit('data', 'saved /out/a.glb\n');
+ child.emit('close', 0);
+ await expect(promise).resolves.toEqual({ assetPath: '/out/a.glb' });
+ expect(frames).toEqual([
+ { stage: 'generating', percent: 50, message: 'sampling 50%' },
+ { stage: 'export', assetPath: '/out/a.glb', message: 'saved /out/a.glb' },
+ ]);
+ });
+
+ it('rejects on a non-zero exit', async () => {
+ const child = makeChild();
+ const promise = runTrellis2Generate({
+ imagePath: 'a.png',
+ outputPath: '/out/a.glb',
+ base: BASE,
+ exists: installed,
+ spawnImpl: () => child,
+ });
+ child.emit('close', 1);
+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_GENERATE_FAILED' });
+ });
+
+ it('rejects when it exits 0 but never reported a .glb', async () => {
+ const child = makeChild();
+ const promise = runTrellis2Generate({
+ imagePath: 'a.png',
+ base: BASE,
+ exists: installed,
+ spawnImpl: () => child,
+ });
+ child.emit('close', 0);
+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_GENERATE_FAILED' });
+ });
+});