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-2952): add TRELLIS.2 SSE install endpoint
[._.]/ Adam Eivyd8cb8ec4122d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 4deef2aa54..6d6c9ea561 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -4,6 +4,7 @@- **[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.+- **[issue-2952] TRELLIS.2 SSE install endpoint** — added `GET /api/image-to-3d/trellis2/install` and `installTrellis2()`, which clone the Apple Silicon MPS port and run its `setup.sh` while streaming staged progress (stage → log → complete/error). Gated on hardware support (refuses on non-Apple-Silicon / insufficient memory), single-flighted against double-clicks, and canceled if the client disconnects. The real ~15 GB download only fires on this explicit user request (never at boot); the orchestration is mock-tested. No user-visible surface yet (the install button lands with the 3D page, #2953).## Music studiodiff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.jsindex 6886e036b7..4f1d7d3e85 100644--- a/server/routes/imageTo3d.js+++ b/server/routes/imageTo3d.js@@ -3,11 +3,21 @@ import { asyncHandler } from '../lib/errorHandler.js';import {listTargets,detectHostCapabilities,+ isTargetAvailable,+ unavailableReason,} from '../services/imageTo3d/targets.js';-import { isTrellis2Installed } from '../services/imageTo3d/trellis2.js';+import { isTrellis2Installed, installTrellis2, trellis2Root } from '../services/imageTo3d/trellis2.js';+import { createInstallLogger } from '../lib/installLogger.js';+import { openSseStream } from '../lib/sseDownload.js';const router = Router();+// 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) => {@@ -31,4 +41,55 @@ router.get('/targets', asyncHandler(async (_req, res) => {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`.+ */+router.get('/trellis2/install', asyncHandler(async (req, res) => {+ const { send, safeEnd } = openSseStream(res);++ if (isTrellis2Installed()) {+ send({ type: 'stage', stage: 'verify', message: 'TRELLIS.2 already installed.' });+ send({ type: 'complete', message: 'Already installed — nothing to do.' });+ return safeEnd();+ }++ // Refuse on unsupported hardware rather than clone 15 GB that can never run.+ const capabilities = detectHostCapabilities();+ if (!isTargetAvailable('trellis2', capabilities)) {+ send({+ type: 'error',+ message: `This host cannot run TRELLIS.2 (${unavailableReason('trellis2', 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.' });+ return safeEnd();+ }++ // Server-console visibility for the multi-GB install (start / stages / outcome).+ const installLog = createInstallLogger({ installer: 'TRELLIS.2', target: trellis2Root() });+ const emit = (event) => { installLog.onEvent(event); send(event); };+ installLog.start();++ const { promise, kill } = installTrellis2({ onEvent: emit });+ trellis2InstallInFlight = promise;+ promise+ .then(() => installLog.success())+ .catch((err) => emit({ type: 'error', message: err?.message || 'Install failed', stage: err?.stage }))+ .finally(() => {+ trellis2InstallInFlight = null;+ safeEnd();+ });++ // Cancel the (multi-GB) install if the client navigates away mid-bootstrap.+ req.on('close', () => { installLog.cancel(); kill(); safeEnd(); });+}));+export default router;diff --git a/server/routes/imageTo3d.test.js b/server/routes/imageTo3d.test.jsindex 9816907704..91bcbd572c 100644--- a/server/routes/imageTo3d.test.js+++ b/server/routes/imageTo3d.test.js@@ -3,8 +3,8 @@ import express from 'express';import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';-// Mock the service so the route test is deterministic regardless of the test-// host's real arch/memory.+// Mock the services so the route test is deterministic regardless of the test+// host's real arch/memory and never touches a real subprocess.vi.mock('../services/imageTo3d/targets.js', () => ({detectHostCapabilities: vi.fn(() => ({ appleSilicon: true, unifiedMemoryGb: 128, cuda: false })),listTargets: vi.fn((caps) => [@@ -17,12 +17,22 @@ vi.mock('../services/imageTo3d/targets.js', () => ({unavailableReason: null,},]),+ isTargetAvailable: vi.fn(() => true),+ unavailableReason: vi.fn(() => 'requires-apple-silicon'),}));vi.mock('../services/imageTo3d/trellis2.js', () => ({isTrellis2Installed: vi.fn(() => false),+ trellis2Root: vi.fn(() => '/tmp/trellis2'),+ installTrellis2: vi.fn(({ onEvent }) => {+ onEvent({ type: 'stage', stage: 'clone', message: 'git clone …' });+ onEvent({ type: 'complete', message: 'TRELLIS.2 installed.' });+ return { promise: Promise.resolve({ ok: true }), kill: vi.fn() };+ }),}));+import * as targets from '../services/imageTo3d/targets.js';+import * as trellis2 from '../services/imageTo3d/trellis2.js';import routes from './imageTo3d.js';const makeApp = () => {@@ -33,6 +43,12 @@ const makeApp = () => {return app;};+// Parse `data: {json}\n\n` SSE frames out of a buffered response body.+const sseFrames = (text) => text+ .split('\n')+ .filter((l) => l.startsWith('data: '))+ .map((l) => JSON.parse(l.slice(6)));+describe('image-to-3d routes', () => {it('GET /targets returns host capabilities and annotated targets', async () => {const res = await request(makeApp()).get('/api/image-to-3d/targets');@@ -42,3 +58,35 @@ describe('image-to-3d routes', () => {expect(res.body.targets[0]).toMatchObject({ id: 'trellis2', available: true, installed: false });});});++describe('GET /trellis2/install (SSE)', () => {+ it('streams stage → complete on the happy path', async () => {+ trellis2.isTrellis2Installed.mockReturnValueOnce(false);+ targets.isTargetAvailable.mockReturnValueOnce(true);+ const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ const frames = sseFrames(res.text);+ expect(frames).toContainEqual({ type: 'stage', stage: 'clone', message: 'git clone …' });+ expect(frames.at(-1)).toMatchObject({ type: 'complete' });+ expect(trellis2.installTrellis2).toHaveBeenCalled();+ });++ it('short-circuits with complete when already installed (no install spawned)', async () => {+ trellis2.installTrellis2.mockClear();+ trellis2.isTrellis2Installed.mockReturnValueOnce(true);+ const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ const frames = sseFrames(res.text);+ expect(frames.at(-1)).toMatchObject({ type: 'complete', message: expect.stringMatching(/already/i) });+ expect(trellis2.installTrellis2).not.toHaveBeenCalled();+ });++ it('refuses on unsupported hardware', async () => {+ trellis2.installTrellis2.mockClear();+ trellis2.isTrellis2Installed.mockReturnValueOnce(false);+ targets.isTargetAvailable.mockReturnValueOnce(false);+ targets.unavailableReason.mockReturnValueOnce('requires-apple-silicon');+ const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ const frames = sseFrames(res.text);+ expect(frames.at(-1)).toMatchObject({ type: 'error', message: expect.stringMatching(/requires-apple-silicon/) });+ expect(trellis2.installTrellis2).not.toHaveBeenCalled();+ });+});diff --git a/server/services/imageTo3d/trellis2.js b/server/services/imageTo3d/trellis2.jsindex b101aabc27..5b5381d4d2 100644--- a/server/services/imageTo3d/trellis2.js+++ b/server/services/imageTo3d/trellis2.js@@ -113,6 +113,69 @@ export function parseGenerateProgress(line) {return frame;}+/**+ * Run the install as a killable, event-emitting job: execute `buildInstallSteps()`+ * sequentially (clone the MPS port → run its `setup.sh`, ~15 GB), emitting a+ * `{ type:'stage' }` per step, `{ type:'log' }` for subprocess output, and a+ * terminal `{ type:'complete' }` on success (it throws on a failed/canceled step so+ * the SSE route can emit `{ type:'error' }`). Real subprocesses — user-triggered+ * only. `spawnImpl` injectable so the step sequencing / cancel / failure paths are+ * unit-testable without a real 15 GB install.+ *+ * @param {{base?: string, onEvent?: (ev: object) => void, spawnImpl?: Function}} [opts]+ * @returns {{promise: Promise<{ok: true}>, kill: () => void}}+ */+export function installTrellis2({ base, onEvent = () => {}, spawnImpl = spawn } = {}) {+ const steps = buildInstallSteps(base);+ let currentChild = null;+ let canceled = false;++ const runStep = (step) => new Promise((resolve, reject) => {+ onEvent({ type: 'stage', stage: step.stage, message: `${step.command} ${step.args.join(' ')}` });+ // Child-process boundary — outcomes flow through events, not a throw into the+ // request lifecycle (CLAUDE.md child-process exception).+ const child = spawnImpl(step.command, step.args, step.cwd ? { cwd: step.cwd } : {});+ currentChild = child;+ const log = (buf) => {+ const message = String(buf).trim();+ if (message) onEvent({ type: 'log', stage: step.stage, message });+ };+ child.stdout?.on('data', log);+ child.stderr?.on('data', log);+ child.on('error', reject);+ child.on('close', (code) => {+ if (code === 0) {+ resolve();+ return;+ }+ const err = new Error(`TRELLIS.2 install step '${step.stage}' exited ${code}`);+ err.code = 'TRELLIS2_INSTALL_FAILED';+ err.stage = step.stage;+ reject(err);+ });+ });++ const promise = (async () => {+ for (const step of steps) {+ if (canceled) {+ const err = new Error('TRELLIS.2 install canceled');+ err.code = 'TRELLIS2_INSTALL_CANCELED';+ throw err;+ }+ await runStep(step);+ }+ onEvent({ type: 'complete', message: 'TRELLIS.2 installed.' });+ return { ok: true };+ })();++ const kill = () => {+ canceled = true;+ if (currentChild && typeof currentChild.kill === 'function') currentChild.kill('SIGTERM');+ };++ return { promise, kill };+}+/*** 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 rundiff --git a/server/services/imageTo3d/trellis2.test.js b/server/services/imageTo3d/trellis2.test.jsindex aa38c6f71d..a44a4bc511 100644--- a/server/services/imageTo3d/trellis2.test.js+++ b/server/services/imageTo3d/trellis2.test.js@@ -10,6 +10,7 @@ import {buildGenerateArgs,parseGenerateProgress,runTrellis2Generate,+ installTrellis2,} from './trellis2.js';const BASE = '/tmp/portos-test-home';@@ -163,3 +164,60 @@ describe('runTrellis2Generate', () => {await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_GENERATE_FAILED' });});});++describe('installTrellis2', () => {+ const makeChild = () => {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.kill = vi.fn();+ return child;+ };++ it('runs each install step in order and emits stage + complete events', async () => {+ const children = [makeChild(), makeChild()];+ let i = 0;+ const spawnImpl = vi.fn(() => children[i++]);+ const events = [];+ const { promise } = installTrellis2({ base: BASE, spawnImpl, onEvent: (e) => events.push(e) });++ // step 1 (clone) — first spawn call, then close it 0 to advance to step 2+ expect(spawnImpl).toHaveBeenNthCalledWith(1, 'git', expect.arrayContaining(['clone']), {});+ children[0].emit('close', 0);+ await Promise.resolve(); // let the await in the loop advance+ expect(spawnImpl).toHaveBeenNthCalledWith(2, 'bash', ['setup.sh'], { cwd: trellis2Root(BASE) });+ children[1].emit('close', 0);+ await expect(promise).resolves.toEqual({ ok: true });++ expect(events.filter((e) => e.type === 'stage').map((e) => e.stage)).toEqual(['clone', 'setup']);+ expect(events.at(-1)).toMatchObject({ type: 'complete' });+ });++ it('forwards subprocess output as log events', async () => {+ const child = makeChild();+ const events = [];+ const { promise } = installTrellis2({ base: BASE, spawnImpl: () => child, onEvent: (e) => events.push(e) });+ child.stdout.emit('data', 'Cloning into trellis2...\n');+ child.emit('error', Object.assign(new Error('boom'), {})); // abort so the promise settles+ await promise.catch(() => {});+ expect(events).toContainEqual({ type: 'log', stage: 'clone', message: 'Cloning into trellis2...' });+ });++ it('rejects with the failing stage when a step exits non-zero', async () => {+ const child = makeChild();+ const { promise } = installTrellis2({ base: BASE, spawnImpl: () => child });+ child.emit('close', 1);+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_INSTALL_FAILED', stage: 'clone' });+ });++ it('kill() SIGTERMs the running child and cancels before the next step', async () => {+ const children = [makeChild(), makeChild()];+ let i = 0;+ const { promise, kill } = installTrellis2({ base: BASE, spawnImpl: () => children[i++] });+ kill();+ expect(children[0].kill).toHaveBeenCalledWith('SIGTERM');+ children[0].emit('close', 0); // step 1 finishes, but canceled flag stops step 2+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_INSTALL_CANCELED' });+ expect(i).toBe(1); // the second step never spawned+ });+});