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

refactor: generalize target env resolution and simplify_-review cleanups

[._.]/ Adam Eivyfff634bfc472
diff --git a/server/routes/imageTo3d.genericDispatch.test.js b/server/routes/imageTo3d.genericDispatch.test.js
index 5e88202f0f..5eaadf6da6 100644
--- a/server/routes/imageTo3d.genericDispatch.test.js
+++ b/server/routes/imageTo3d.genericDispatch.test.js
@@ -54,6 +54,7 @@ vi.mock('../services/imageTo3d/models.js', () => ({
getModelAsset: vi.fn(),
}));
+import { hfChildEnv } from '../lib/hfToken.js';
import routes from './imageTo3d.js';
const makeApp = () => {
@@ -91,6 +92,15 @@ describe('image-to-3d generic target dispatch (#3080)', () => {
expect(fakeInstall).toHaveBeenCalled();
});
+ // #3080: env/credential resolution is adapter-owned (`resolveEnv`), not a
+ // dispatch-layer assumption that every target wants a Hugging Face token —
+ // a target that declares no `resolveEnv` must never trigger one.
+ it('never resolves the Hugging Face token env for a target with no resolveEnv hook', async () => {
+ await request(makeApp()).get('/api/image-to-3d/targets/fakegen/install');
+ expect(hfChildEnv).not.toHaveBeenCalled();
+ expect(fakeInstall).toHaveBeenCalledWith(expect.objectContaining({ env: undefined }));
+ });
+
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);
diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.js
index 141d5bcbcf..7d258e031b 100644
--- a/server/routes/imageTo3d.js
+++ b/server/routes/imageTo3d.js
@@ -21,7 +21,6 @@ import {
getModelAsset,
} from '../services/imageTo3d/models.js';
import { createInstallLogger } from '../lib/installLogger.js';
-import { hfChildEnv } from '../lib/hfToken.js';
import { openSseStream } from '../lib/sseDownload.js';
const router = Router();
@@ -35,11 +34,12 @@ const createModelSchema = z.object({
target: z.enum([...IMAGE_TO_3D_TARGET_IDS]).optional(),
});
-// 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();
+// Target ids with an install currently running — 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 Set();
/**
* The selectable image→3D targets, each annotated with whether it can run on
@@ -117,19 +117,19 @@ async function handleTargetInstall(targetId, req, res) {
}
// 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);
+ installsInFlight.add(targetId);
// Server-console visibility for the multi-GB install (start / stages / outcome).
const installLog = createInstallLogger({ installer: target.label, target: targetId });
const emit = (event) => { installLog.onEvent(event); send(event); };
installLog.start();
- // 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 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.
+ // Disconnect bookkeeping wired BEFORE the env-resolution await below (the same
+ // hazard `lib/sseDownload.js` documents): that await can do a settings read plus
+ // a token-file read (e.g. TRELLIS.2's `resolveEnv`), and a client closing during
+ // it would otherwise land 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', () => {
@@ -142,18 +142,17 @@ async function handleTargetInstall(targetId, req, res) {
safeEnd();
});
- // 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.
+ // Each target declares its own credential/env needs via `resolveEnv` — omit it
+ // for a target with nothing to resolve. 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();
+ installEnv = adapter.resolveEnv ? await adapter.resolveEnv() : undefined;
} catch (err) {
- 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}` });
+ console.error(`❌ ${target.label} install could not resolve its environment: ${err.message}`);
+ emit({ type: 'error', message: `Could not prepare the ${target.label} install environment: ${err.message}` });
installsInFlight.delete(targetId);
return safeEnd();
}
diff --git a/server/routes/imageTo3d.test.js b/server/routes/imageTo3d.test.js
index 777be3e889..1c097c7eff 100644
--- a/server/routes/imageTo3d.test.js
+++ b/server/routes/imageTo3d.test.js
@@ -256,7 +256,7 @@ describe('GET /trellis2/install (SSE)', () => {
}));
});
- it('emits a terminal error frame — not a half-open stream — when the token env cannot be resolved', async () => {
+ it('emits a terminal error frame — not a half-open stream — when the env cannot be resolved', async () => {
// The SSE headers are already flushed by this point, so a throw here can't
// reach the error middleware as JSON; it has to surface as an error frame.
trellis2.installTrellis2.mockClear();
@@ -267,7 +267,7 @@ describe('GET /trellis2/install (SSE)', () => {
const frames = sseFrames(res.text);
expect(frames.at(-1)).toMatchObject({
type: 'error',
- message: expect.stringMatching(/Hugging Face token/i),
+ message: expect.stringMatching(/could not prepare.*install environment.*settings\.json is not valid JSON/i),
});
// And no multi-GB install is started on a failed resolve.
expect(trellis2.installTrellis2).not.toHaveBeenCalled();
diff --git a/server/services/imageTo3d/adapters.js b/server/services/imageTo3d/adapters.js
index 95231e519c..c931982738 100644
--- a/server/services/imageTo3d/adapters.js
+++ b/server/services/imageTo3d/adapters.js
@@ -15,6 +15,12 @@
* 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()`.
+ * - `resolveEnv?()` — optional async credential/env resolver, called by the
+ * install route and the render dispatcher before `install()`/`run()`. Each
+ * target declares its own needs here (TRELLIS.2 resolves the stored Hugging
+ * Face token) instead of the dispatch layer assuming every target wants one.
+ * Omit for a target with nothing to resolve — its `env` argument is then
+ * `undefined` and the child process just inherits `process.env`.
* - `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.
@@ -28,6 +34,7 @@
* quality). Omit when a target has nothing extra to report.
*/
+import { hfChildEnv } from '../../lib/hfToken.js';
import {
isTrellis2Installed,
installTrellis2,
@@ -39,6 +46,10 @@ import {
export const TARGET_ADAPTERS = Object.freeze({
trellis2: Object.freeze({
isInstalled: isTrellis2Installed,
+ // The pipeline pulls gated HF repos (DINOv3, RMBG-2.0) at load time, so both
+ // install and render need the resolved token — settings.imageGen.hfToken
+ // first, then the env/CLI fallbacks.
+ resolveEnv: hfChildEnv,
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
diff --git a/server/services/imageTo3d/models.genericDispatch.test.js b/server/services/imageTo3d/models.genericDispatch.test.js
index edb8f92e77..3b7e7b11da 100644
--- a/server/services/imageTo3d/models.genericDispatch.test.js
+++ b/server/services/imageTo3d/models.genericDispatch.test.js
@@ -49,6 +49,7 @@ vi.mock('./adapters.js', () => ({
getTargetAdapter: vi.fn((id) => (id === 'second-target' ? { isInstalled: fakeIsInstalled, run: fakeRun } : null)),
}));
+import { hfChildEnv } from '../../lib/hfToken.js';
import * as store from './db.js';
import { createModel } from './models.js';
@@ -77,6 +78,11 @@ describe('models.js target dispatch is adapter-registry-driven (#3080)', () => {
await vi.waitFor(() => expect(fakeRun).toHaveBeenCalled());
expect(fakeIsInstalled).toHaveBeenCalled();
+ // #3080: env/credential resolution is adapter-owned (`resolveEnv`) — a
+ // target that declares no `resolveEnv` must never trigger the Hugging Face
+ // token lookup or receive an env it never asked for.
+ expect(hfChildEnv).not.toHaveBeenCalled();
+ expect(fakeRun).toHaveBeenCalledWith(expect.objectContaining({ env: undefined }));
});
it('501s a target the adapter registry has no adapter for', async () => {
diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.js
index 76e6ea98c7..c70a920c74 100644
--- a/server/services/imageTo3d/models.js
+++ b/server/services/imageTo3d/models.js
@@ -19,7 +19,6 @@ import { randomUUID } from 'crypto';
import { join } from 'node:path';
import { rm } from 'node:fs/promises';
import { ServerError } from '../../lib/errorHandler.js';
-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';
@@ -55,8 +54,8 @@ async function cleanupRenderDir(id) {
/**
* Verify a target can actually run on this host right now — unknown target →
* 400, hardware-unsupported → 409 (reason surfaced), not-installed → 409 so the
- * UI can open the install flow. Returns the resolved runner entry. Pure w.r.t.
- * the DB; `caps` is injected so the check is deterministic.
+ * UI can open the install flow. Returns the resolved adapter. Pure w.r.t. the DB;
+ * `caps` is injected so the check is deterministic.
*/
function assertTargetReady(targetId, caps) {
const { target, available, reason } = resolveTarget(targetId, caps);
@@ -69,17 +68,17 @@ function assertTargetReady(targetId, caps) {
{ status: 409, code: 'TARGET_UNAVAILABLE', context: { reason } },
);
}
- const runner = getTargetAdapter(targetId);
- if (!runner) {
+ const adapter = getTargetAdapter(targetId);
+ if (!adapter) {
throw new ServerError(`Target ${target.label} has no runner wired`, { status: 501, code: 'TARGET_NO_RUNNER' });
}
- if (!runner.isInstalled()) {
+ if (!adapter.isInstalled()) {
throw new ServerError(
`${target.label} is not installed. Install it before generating.`,
{ status: 409, code: 'TARGET_NOT_INSTALLED' },
);
}
- return runner;
+ return adapter;
}
function updateRun(runs, operationId, patch) {
@@ -111,20 +110,20 @@ async function failGeneration(id, operationId, error) {
});
}
-async function executeRender({ id, operationId, runner, sourcePath }) {
+async function executeRender({ id, operationId, adapter, sourcePath }) {
const outputPath = assetDiskPath(id);
let lastPersistedPercent = -1;
try {
await ensureDir(join(PATHS.imageTo3d, id));
- // The pipeline pulls gated HF repos (DINOv3, RMBG-2.0) at load time, so hand the
- // child our resolved token — settings.imageGen.hfToken first, then the env/CLI
- // fallbacks. Resolving HERE (an async caller) keeps the runner synchronous so its
- // { promise, kill } contract holds.
- const env = await hfChildEnv();
+ // Resolve this target's own credential/env needs via its adapter (e.g.
+ // TRELLIS.2 resolves the stored Hugging Face token) — omitted for a target
+ // with nothing to resolve. Resolving HERE (an async caller) keeps `run`
+ // synchronous so its { promise, kill } contract holds.
+ const env = adapter.resolveEnv ? await adapter.resolveEnv() : undefined;
// The runner returns a { promise, kill } pair (see runTrellis2Generate) — retain
// the kill handle so deleteModel can SIGTERM this render if the record is deleted
// mid-flight.
- const { promise, kill } = runner.run({
+ const { promise, kill } = adapter.run({
imagePath: sourcePath,
outputPath,
env,
@@ -219,13 +218,13 @@ export async function createModel(input, { caps = detectHostCapabilities() } = {
const targetId = input.target || DEFAULT_IMAGE_TO_3D_TARGET;
// Validate the target is runnable BEFORE persisting a record so we never leave
// a dangling draft when the host can't render / the model isn't installed.
- const runner = assertTargetReady(targetId, caps);
+ const adapter = assertTargetReady(targetId, caps);
const created = await store.createModel({ ...input, target: targetId });
- // Thread the already-validated runner + resolved source straight into the
+ // Thread the already-validated adapter + resolved source straight into the
// render — createModel and startGeneration share `beginRender`, so the create
// path does NOT re-resolve the gallery image, re-assert readiness, or re-fetch
// the row it just wrote.
- return beginRender(created, runner, sourcePath);
+ return beginRender(created, adapter, sourcePath);
}
export async function startGeneration(id, { caps = detectHostCapabilities() } = {}) {
@@ -236,22 +235,22 @@ export async function startGeneration(id, { caps = detectHostCapabilities() } =
throw new ServerError('This model is already generating', { status: 409, code: 'MODEL_BUSY' });
}
- const runner = assertTargetReady(current.target, caps);
+ const adapter = assertTargetReady(current.target, caps);
const sourcePath = resolveGalleryImage(current.sourceImage?.filename);
if (!sourcePath) {
throw new ServerError('The source gallery image is no longer available', { status: 409, code: 'GALLERY_IMAGE_NOT_FOUND' });
}
- return beginRender(current, runner, sourcePath);
+ return beginRender(current, adapter, sourcePath);
}
/**
* Flip a validated record to `generating`, append a run, and dispatch the async
* render. The single write path shared by create + regenerate — callers do the
* validation (target readiness, gallery-image resolution) and pass the resolved
- * runner + source through. The transactional `status==='generating'` guard here
+ * adapter + source through. The transactional `status==='generating'` guard here
* is the authoritative race check (the callers' pre-check is just a fast 409).
*/
-async function beginRender(record, runner, sourcePath) {
+async function beginRender(record, adapter, sourcePath) {
const { id } = record;
const operationId = randomUUID();
const startedAt = new Date().toISOString();
@@ -281,7 +280,7 @@ async function beginRender(record, runner, sourcePath) {
activeOperations.add(operationId);
setImmediate(() => {
- void executeRender({ id, operationId, runner, sourcePath });
+ void executeRender({ id, operationId, adapter, sourcePath });
});
return next;
}