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

fix([issue-3032]): route the stored HF token into TRELLIS.2 renders and offer inline entry

[._.]/ Adam Eivyce2dce00357d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 96320fccba..796bd538b4 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## 3D
+- **[issue-3032] The 3D page now uses the Hugging Face token you already saved — and lets you add one right there** — if you'd already given PortOS a Hugging Face token (for gated image models or local model downloads), the 3D page ignored it: it never handed the token to the render, so TRELLIS.2's first run still failed on the two gated models it downloads, and the page kept telling you to go authenticate in a terminal. Your saved token now travels into the render, and the notice reads your actual setup: with a token in place it collapses to a one-line confirmation telling you where that token came from, and with none it offers a paste-and-save field instead of terminal instructions. Either way the two gated models stay linked, since their terms still have to be accepted on your Hugging Face account — a token alone doesn't grant access.
- **[issue-2981] Generate a 3D mesh from the 3D page — with a heads-up about Hugging Face access** — the **Generate 3D** button on the 3D page is now live: pick a source image, click Generate, watch on-device progress, and the finished `.glb` renders right there in the interactive viewer (its URL is shareable and reload-safe). If a render fails, the reason now shows inline — including the exact steps when TRELLIS.2 needs Hugging Face access. And before you ever hit that wall, the page and installer now tell you up front that TRELLIS.2 downloads two **gated** Hugging Face models on first render (DINOv3 and RMBG-2.0) and links you to accept their terms and sign in (`huggingface-cli login` or an `HF_TOKEN`).
- **[issue-2952] Turn a rendered image into a downloadable 3D mesh (create/render backend)** — once TRELLIS.2 is installed, PortOS can now take one of your gallery images and render it into a real 3D model (a `.glb` mesh with PBR textures) entirely on-device. Each render is saved as its own record you can list, re-render, download, or delete, and it tracks live status (generating → ready, with progress) and its render history — the backend "create a 3D model" path the 3D page's UI drives. The render only ever runs when you ask for it (never in the background), and is refused with a clear reason if the model isn't installed or your hardware can't run it.
- **[issue-2953] Install image-to-3D models from a new 3D page** — a new **3D** page under Create lists the available image-to-3D models (starting with Microsoft TRELLIS.2) and shows each one's state at a glance: **Ready**, an **Install** button, or a note explaining why your hardware can't run it (e.g. needs an Apple Silicon Mac with enough memory). Installing runs entirely on-device with a live progress log — the same in-app install experience as the image generators — so you never touch a terminal. Reachable from the sidebar, ⌘K, and voice. (Turning one of your rendered images into a 3D mesh from this page lands next.)
diff --git a/client/src/components/imageGen/HfTokenBanner.jsx b/client/src/components/imageGen/HfTokenBanner.jsx
index 19e36b2fcf..7f83fea4b8 100644
--- a/client/src/components/imageGen/HfTokenBanner.jsx
+++ b/client/src/components/imageGen/HfTokenBanner.jsx
@@ -11,11 +11,20 @@
*/
import { useState } from 'react';
-import { Key, Loader2 } from 'lucide-react';
+import { ExternalLink, Key, Loader2 } from 'lucide-react';
import toast from '../ui/Toast';
import apiCore from '../../services/apiCore';
-export default function HfTokenBanner({ modelLabel, licenseUrl, onSaved }) {
+/**
+ * @param {object} props
+ * @param {string} [props.modelLabel] Single gated model's display name.
+ * @param {string} [props.licenseUrl] That model's HF license page.
+ * @param {{label: string, url: string}[]} [props.models] Several gated repos (the
+ * 3D page's TRELLIS.2 pulls two). Takes precedence over modelLabel/licenseUrl —
+ * the terms must be accepted on EACH repo, so all of them are listed.
+ * @param {() => void} [props.onSaved] Re-check token status after a successful save.
+ */
+export default function HfTokenBanner({ modelLabel, licenseUrl, models, onSaved }) {
const [token, setToken] = useState('');
const [saving, setSaving] = useState(false);
@@ -34,20 +43,41 @@ export default function HfTokenBanner({ modelLabel, licenseUrl, onSaved }) {
};
const licenseLinkText = licenseUrl?.replace(/^https?:\/\//, '');
+ const multi = Array.isArray(models) && models.length > 0;
+
+ const tokenLink = (
+ <a href="https://huggingface.co/settings/tokens" target="_blank" rel="noreferrer" className="underline text-white">
+ huggingface.co/settings/tokens
+ </a>
+ );
return (
<div className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-3 text-xs text-port-warning space-y-2">
- <div>
- {modelLabel} is a gated model. Accept the license at{' '}
- <a href={licenseUrl} target="_blank" rel="noreferrer" className="underline text-white">
- {licenseLinkText}
- </a>
- , then create a read token at{' '}
- <a href="https://huggingface.co/settings/tokens" target="_blank" rel="noreferrer" className="underline text-white">
- huggingface.co/settings/tokens
- </a>{' '}
- and paste it below.
- </div>
+ {multi ? (
+ <div>
+ <div>
+ This needs a free Hugging Face account. Accept the terms for each gated model below (signed in to
+ Hugging Face), then create a read token at {tokenLink} and paste it here.
+ </div>
+ <ul className="mt-1.5 space-y-1">
+ {models.map((m) => (
+ <li key={m.url}>
+ <a href={m.url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 underline text-white">
+ <ExternalLink className="h-3 w-3" /> {m.label}
+ </a>
+ </li>
+ ))}
+ </ul>
+ </div>
+ ) : (
+ <div>
+ {modelLabel} is a gated model. Accept the license at{' '}
+ <a href={licenseUrl} target="_blank" rel="noreferrer" className="underline text-white">
+ {licenseLinkText}
+ </a>
+ , then create a read token at {tokenLink} and paste it below.
+ </div>
+ )}
<div className="flex flex-col sm:flex-row gap-2 items-stretch sm:items-center">
<div className="flex items-center gap-1.5 flex-1 bg-port-bg border border-port-border rounded-lg px-2 py-1.5 focus-within:border-port-accent">
<Key size={14} className="text-gray-400 flex-shrink-0" />
diff --git a/client/src/pages/Media3D.jsx b/client/src/pages/Media3D.jsx
index 318445d28e..e9c56f861e 100644
--- a/client/src/pages/Media3D.jsx
+++ b/client/src/pages/Media3D.jsx
@@ -1,13 +1,14 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import { Boxes, CheckCircle2, Download, AlertTriangle, Loader2, ExternalLink, ImagePlus, Sparkles, KeyRound } from 'lucide-react';
-import { getImageTo3dTargets, createImageTo3dModel, getImageTo3dModel, listImageTo3dModels } from '../services/api';
+import { getImageTo3dTargets, createImageTo3dModel, getImageTo3dModel, listImageTo3dModels, getHfTokenStatus } from '../services/api';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
import useMounted from '../hooks/useMounted';
import { nameFromImageFilename, timeAgo } from '../utils/formatters';
import RuntimeInstallModal from '../components/install/RuntimeInstallModal';
import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';
import GlbViewer from '../components/media/GlbViewer';
+import HfTokenBanner from '../components/imageGen/HfTokenBanner';
import MediaImage from '../components/MediaImage';
import { imageTo3dStatusMeta } from '../components/media/imageTo3dStatus';
@@ -25,19 +26,41 @@ const HF_GATED_MODELS = {
],
};
-// Prerequisite notice for a target that needs gated Hugging Face access. Shown once
-// the gated target is selectable so the user accepts terms + signs in up front.
-function HfAccessNotice({ models }) {
+// How the resolved token reached us, for the "already configured" line. PortOS
+// injects whichever one it found into the render's environment, so all three are
+// equally good — naming the source just tells the user where to change it.
+const HF_SOURCE_LABEL = {
+ stored: 'saved in PortOS',
+ env: 'from the HF_TOKEN environment variable',
+ cli: 'from huggingface-cli login',
+};
+
+// Prerequisite notice for a target that needs gated Hugging Face access. Driven by
+// the CENTRAL token store (GET /image-gen/setup/hf-token-status) — the same one the
+// Image Gen page writes — so a user who already pasted a token isn't told to go set
+// one up in a terminal. With no token, the inline paste-and-save banner appears
+// instead of instructions. Either way the gated repos stay listed: a token doesn't
+// grant access until their terms are accepted on the user's HF account.
+function HfAccessNotice({ models, tokenPresent, tokenSource, onSaved }) {
if (!models?.length) return null;
+ // Status still loading (null) — don't flash a "needs setup" banner at a user who
+ // already has a token.
+ if (tokenPresent === null) return null;
+
+ if (!tokenPresent) {
+ return <HfTokenBanner models={models} onSaved={onSaved} />;
+ }
+
return (
- <div className="rounded-lg border border-port-warning/40 bg-port-warning/10 p-3 text-xs text-gray-300">
- <div className="mb-1 flex items-center gap-1.5 font-medium text-port-warning">
- <KeyRound className="h-3.5 w-3.5" /> Needs a free Hugging Face account
+ <div className="rounded-lg border border-port-border bg-port-bg/40 p-3 text-xs text-gray-400">
+ <div className="flex items-center gap-1.5 font-medium text-port-success">
+ <KeyRound className="h-3.5 w-3.5" />
+ Hugging Face token configured
+ {HF_SOURCE_LABEL[tokenSource] ? ` (${HF_SOURCE_LABEL[tokenSource]})` : ''}
</div>
- <p className="text-gray-400">
- On first render this downloads two <strong>gated</strong> models. Accept their terms (signed in to Hugging Face), then
- authenticate the machine with <code className="rounded bg-port-bg px-1">huggingface-cli login</code> or an{' '}
- <code className="rounded bg-port-bg px-1">HF_TOKEN</code>:
+ <p className="mt-1">
+ Accept the terms for these gated models on your Hugging Face account if you haven’t — a token alone
+ doesn’t grant access:
</p>
<ul className="mt-1.5 space-y-1">
{models.map((m) => (
@@ -168,6 +191,10 @@ export default function Media3D() {
// Existing image-to-3D records (newest-first) so the page doubles as a library:
// each links to its `/media/3d/:id` detail view.
const [records, setRecords] = useState([]);
+ // Central HF-token status (stored / env / cli), for the gated-model notice.
+ // `null` = not fetched yet — distinct from `false` (fetched, genuinely absent), so
+ // a slow status call can't flash the "add a token" banner at a user who has one.
+ const [hfToken, setHfToken] = useState({ present: null, source: null });
const mountedRef = useMounted(); // gate setState after the create/poll awaits
const load = useCallback(() => {
@@ -193,8 +220,20 @@ export default function Media3D() {
: [record, ...prev]));
}, [mountedRef]);
+ // Read-only presence check against the shared store — no LLM/provider call, so it
+ // is safe to run on mount. A failure leaves `present: null`, which renders nothing
+ // rather than nagging on a transient blip.
+ const loadHfToken = useCallback(() => {
+ getHfTokenStatus()
+ .then((data) => {
+ if (mountedRef.current) setHfToken({ present: !!data?.hfTokenPresent, source: data?.source || null });
+ })
+ .catch(() => { /* leave unknown — the notice stays hidden rather than lying */ });
+ }, [mountedRef]);
+
useEffect(() => { load(); }, [load]);
useEffect(() => { loadRecords(); }, [loadRecords]);
+ useEffect(() => { loadHfToken(); }, [loadHfToken]);
const selectedImage = useMemo(
() => (imageFromRoute
@@ -354,7 +393,14 @@ export default function Media3D() {
)}
</div>
- {gatedHfModels && <HfAccessNotice models={gatedHfModels} />}
+ {gatedHfModels && (
+ <HfAccessNotice
+ models={gatedHfModels}
+ tokenPresent={hfToken.present}
+ tokenSource={hfToken.source}
+ onSaved={loadHfToken}
+ />
+ )}
<div className="mt-auto flex flex-col items-start gap-2">
<button
@@ -472,7 +518,7 @@ export default function Media3D() {
runtime={installTarget?.id}
label={installTarget?.label}
installUrlBase="/api/image-to-3d/trellis2/install"
- description="Cloning the TRELLIS.2 (Apple Silicon) port and installing its Python environment (~15 GB on first run). It also pulls two gated Hugging Face models on first render — accept their terms and sign in with huggingface-cli login / HF_TOKEN (see the note on the 3D page)."
+ description="Cloning the TRELLIS.2 (Apple Silicon) port and installing its Python environment (~15 GB on first run). It also pulls two gated Hugging Face models on first render — accept their terms and add a Hugging Face token above (see the note on the 3D page)."
onClose={() => setInstallTarget(null)}
onComplete={() => { setInstallTarget(null); load(); }}
/>
diff --git a/client/src/pages/Media3D.test.jsx b/client/src/pages/Media3D.test.jsx
index ed5d4f938d..fbe5d5d3f0 100644
--- a/client/src/pages/Media3D.test.jsx
+++ b/client/src/pages/Media3D.test.jsx
@@ -7,11 +7,13 @@ const getImageTo3dTargets = vi.fn();
const createImageTo3dModel = vi.fn();
const getImageTo3dModel = vi.fn();
const listImageTo3dModels = vi.fn();
+const getHfTokenStatus = vi.fn();
vi.mock('../services/api', () => ({
getImageTo3dTargets: (...a) => getImageTo3dTargets(...a),
createImageTo3dModel: (...a) => createImageTo3dModel(...a),
getImageTo3dModel: (...a) => getImageTo3dModel(...a),
listImageTo3dModels: (...a) => listImageTo3dModels(...a),
+ getHfTokenStatus: (...a) => getHfTokenStatus(...a),
}));
// Stub the shared install modal so the test doesn't open a real EventSource;
@@ -65,7 +67,11 @@ function renderAt(entry = '/media/3d', extra = null) {
}
describe('Media3D — models & install', () => {
- beforeEach(() => { vi.clearAllMocks(); listImageTo3dModels.mockResolvedValue([]); });
+ beforeEach(() => {
+ vi.clearAllMocks();
+ listImageTo3dModels.mockResolvedValue([]);
+ getHfTokenStatus.mockResolvedValue({ hfTokenPresent: false, source: 'none' });
+ });
it('shows an Install button for an available, not-installed target and opens the modal', async () => {
getImageTo3dTargets.mockResolvedValue({ capabilities: {}, targets: [target()] });
@@ -107,6 +113,7 @@ describe('Media3D — generation workspace', () => {
vi.clearAllMocks();
listImageTo3dModels.mockResolvedValue([]);
getImageTo3dTargets.mockResolvedValue({ targets: [target({ installed: true })] });
+ getHfTokenStatus.mockResolvedValue({ hfTokenPresent: false, source: 'none' });
});
it('shows the source image from the ?image= deep link', async () => {
@@ -144,13 +151,40 @@ describe('Media3D — generation workspace', () => {
expect(screen.queryByTestId('glb-viewer')).toBeNull();
});
- it('shows the Hugging Face gated-model prerequisite for the TRELLIS.2 target', async () => {
+ it('offers inline token entry, not terminal instructions, when no HF token is stored', async () => {
renderAt('/media/3d?image=example-robot.png');
expect(await screen.findByText(/needs a free Hugging Face account/i)).toBeInTheDocument();
+ // The fix for #3032: a paste-and-save field, not a "run huggingface-cli login" nag.
+ expect(screen.getByPlaceholderText('hf_…')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /save token/i })).toBeInTheDocument();
+ expect(screen.queryByText(/huggingface-cli login/i)).toBeNull();
+ // Both gated repos stay linked — terms acceptance is separate from having a token.
expect(screen.getByRole('link', { name: /dinov3-vitl16-pretrain-lvd1689m/i })).toBeInTheDocument();
expect(screen.getByRole('link', { name: /RMBG-2\.0/i })).toBeInTheDocument();
});
+ it('collapses to a confirmation naming the source when a token already exists', async () => {
+ // The user's real complaint: an HF_TOKEN set for imagegen/local-LLM downloads was
+ // ignored here, so the page kept demanding a terminal login.
+ getHfTokenStatus.mockResolvedValue({ hfTokenPresent: true, source: 'env' });
+ renderAt('/media/3d?image=example-robot.png');
+ expect(await screen.findByText(/Hugging Face token configured/i)).toBeInTheDocument();
+ expect(screen.getByText(/HF_TOKEN environment variable/i)).toBeInTheDocument();
+ expect(screen.queryByPlaceholderText('hf_…')).toBeNull();
+ // Terms links persist — a token alone doesn't grant gated access.
+ expect(screen.getByRole('link', { name: /dinov3-vitl16-pretrain-lvd1689m/i })).toBeInTheDocument();
+ });
+
+ it('shows neither the banner nor the confirmation while token status is still unknown', async () => {
+ // Absent-vs-failed: a pending/failed status must not flash "add a token" at a user
+ // who has one (nor claim one is configured).
+ getHfTokenStatus.mockRejectedValue(new Error('offline'));
+ renderAt('/media/3d?image=example-robot.png');
+ await screen.findByRole('button', { name: /Generate 3D/i });
+ expect(screen.queryByPlaceholderText('hf_…')).toBeNull();
+ expect(screen.queryByText(/Hugging Face token configured/i)).toBeNull();
+ });
+
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 });
diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.js
index a046158e87..b7cda6847f 100644
--- a/server/routes/imageTo3d.js
+++ b/server/routes/imageTo3d.js
@@ -20,6 +20,8 @@ import {
getModelAsset,
} from '../services/imageTo3d/models.js';
import { createInstallLogger } from '../lib/installLogger.js';
+import { hfTokenEnv } from '../lib/hfToken.js';
+import { safeChildProcessEnv } from '../lib/processEnv.js';
import { openSseStream } from '../lib/sseDownload.js';
const router = Router();
@@ -99,7 +101,12 @@ router.get('/trellis2/install', asyncHandler(async (req, res) => {
const emit = (event) => { installLog.onEvent(event); send(event); };
installLog.start();
- const { promise, kill } = installTrellis2({ onEvent: emit });
+ // 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.
+ const { promise, kill } = installTrellis2({
+ onEvent: emit,
+ env: safeChildProcessEnv(await hfTokenEnv()),
+ });
trellis2InstallInFlight = promise;
promise
.then(() => installLog.success())
diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.js
index b12108e74a..ba0e9ea4ed 100644
--- a/server/services/imageTo3d/models.js
+++ b/server/services/imageTo3d/models.js
@@ -19,6 +19,8 @@ import { randomUUID } from 'crypto';
import { join } from 'node:path';
import { rm } from 'node:fs/promises';
import { ServerError } from '../../lib/errorHandler.js';
+import { hfTokenEnv } from '../../lib/hfToken.js';
+import { safeChildProcessEnv } from '../../lib/processEnv.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';
@@ -35,7 +37,7 @@ 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 }` and returns a
+ * 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`).
*/
@@ -126,12 +128,18 @@ async function executeRender({ id, operationId, runner, sourcePath }) {
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 = safeChildProcessEnv(await hfTokenEnv());
// 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({
imagePath: sourcePath,
outputPath,
+ env,
onProgress: (frame) => {
// Sparse, low-frequency render progress — persist only when the whole
// percent actually advances so a chatty parser can't hot-write the row.
diff --git a/server/services/imageTo3d/models.test.js b/server/services/imageTo3d/models.test.js
index c22c8b7f2e..6b784c9a1c 100644
--- a/server/services/imageTo3d/models.test.js
+++ b/server/services/imageTo3d/models.test.js
@@ -32,6 +32,13 @@ vi.mock('./trellis2.js', () => ({
})),
}));
+// The render spawns with the central HF token in its env (#3032). Mock the resolver
+// so the suite doesn't pull in the real settings store (which needs PATHS.data, and
+// this suite mocks fileUtils down to `imageTo3d` alone).
+vi.mock('../../lib/hfToken.js', () => ({
+ hfTokenEnv: vi.fn(async () => ({ HF_TOKEN: 'hf_from_store', HUGGINGFACE_HUB_TOKEN: 'hf_from_store' })),
+}));
+
vi.mock('./db.js', () => ({
listModels: vi.fn(),
getModel: vi.fn(),
@@ -126,6 +133,9 @@ describe('image-to-3D model orchestration', () => {
expect(runTrellis2Generate).toHaveBeenCalledWith(expect.objectContaining({
imagePath: '/mock/data/images/example.png',
outputPath: expect.stringMatching(/image-to-3d\/image3d-example\/model\.glb$/),
+ // #3032: the resolved HF token (settings-stored included) rides into the child,
+ // merged over process.env — without it, gated DINOv3/RMBG-2.0 pulls 401.
+ env: expect.objectContaining({ HF_TOKEN: 'hf_from_store', HUGGINGFACE_HUB_TOKEN: 'hf_from_store' }),
}));
expect(current.assetPath).toBe('/data/image-to-3d/image3d-example/model.glb');
expect(current.generationOperationId).toBeNull();
diff --git a/server/services/imageTo3d/trellis2.js b/server/services/imageTo3d/trellis2.js
index 8fb6e00fc0..f720039b0e 100644
--- a/server/services/imageTo3d/trellis2.js
+++ b/server/services/imageTo3d/trellis2.js
@@ -248,8 +248,14 @@ export const isTransientInstallError = textMatcher([
* A non-transient failure (bad config, unsupported host, real setup error) is NOT
* retried — it fails fast. `sleep` is injectable so tests don't wait on real backoff.
*
+ * **`env`** (optional) is the child environment to spawn under — the caller resolves
+ * it (PortOS passes `safeChildProcessEnv(await hfTokenEnv())` so a token stored in
+ * settings reaches the child, not just one exported into the server's own env).
+ * Omitted → the child inherits `process.env` as before.
+ *
* @param {{base?: string, onEvent?: (ev: object) => void, spawnImpl?: Function,
- * maxRetries?: number, sleep?: (ms: number) => Promise<void>}} [opts]
+ * maxRetries?: number, sleep?: (ms: number) => Promise<void>,
+ * env?: NodeJS.ProcessEnv}} [opts]
* @returns {{promise: Promise<{ok: true}>, kill: () => void}}
*/
export function installTrellis2({
@@ -259,6 +265,7 @@ export function installTrellis2({
maxRetries = 3,
sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
exists = existsSync,
+ env,
} = {}) {
// `exists` lets the clone step be skipped when the repo is already on disk (resume
// after a setup-stage failure) — see buildInstallSteps.
@@ -270,7 +277,10 @@ export function installTrellis2({
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 } : {});
+ const child = spawnImpl(step.command, step.args, {
+ ...(step.cwd ? { cwd: step.cwd } : {}),
+ ...(env ? { env } : {}),
+ });
currentChild = child;
// Retain a bounded tail of combined output so a non-zero exit can be classified
// as transient-network vs. a real failure (the clue is in the subprocess text,
@@ -368,11 +378,18 @@ export const isHfAuthError = textMatcher([
'401 Client Error', 'Invalid user token', 'Repo .* is gated',
]);
-/** Human-actionable guidance for the gated-dependency failure above. */
+/**
+ * Human-actionable guidance for the gated-dependency failure above. Points at the
+ * in-app token field first — PortOS injects its stored Hugging Face token into the
+ * render's environment (see `runTrellis2Generate`'s `env`), so pasting one on the 3D
+ * page is the fix; the CLI/env route is the fallback for someone already set up that
+ * way. Terms acceptance is a separate step a token alone doesn't cover.
+ */
const HF_AUTH_HELP = 'TRELLIS.2 could not download a gated model dependency from '
+ 'Hugging Face. Accept the terms for facebook/dinov3-vitl16-pretrain-lvd1689m at '
- + 'https://huggingface.co/facebook/dinov3-vitl16-pretrain-lvd1689m, then authenticate '
- + '(set HF_TOKEN or run `huggingface-cli login`) and try again.';
+ + 'https://huggingface.co/facebook/dinov3-vitl16-pretrain-lvd1689m, then add your '
+ + 'Hugging Face token on the 3D page (or set HF_TOKEN / run `huggingface-cli login`) '
+ + 'and try again.';
/**
* Run a single image→GLB generation. The one real-subprocess boundary — GUARDED:
@@ -386,9 +403,16 @@ const HF_AUTH_HELP = 'TRELLIS.2 could not download a gated model dependency from
* `killWithEscalation` (SIGTERM, then SIGKILL after a grace window if the child
* ignored it), the same cancel convention every other spawn-based media job uses.
*
+ * **`env`** (optional) is the child environment to spawn under. The pipeline pulls
+ * gated Hugging Face repos at load time, so the caller resolves the token env
+ * (`safeChildProcessEnv(await hfTokenEnv())` in `models.js#executeRender`) and passes
+ * it in — this function stays synchronous so its `{ promise, kill }` contract holds.
+ * Omitted → the child inherits `process.env` as before.
+ *
* @param {{imagePath: string, outputPath?: string, base?: string,
* onProgress?: (frame: object) => void,
- * spawnImpl?: Function, exists?: (p: string) => boolean}} opts
+ * spawnImpl?: Function, exists?: (p: string) => boolean,
+ * env?: NodeJS.ProcessEnv}} opts
* @returns {{promise: Promise<{assetPath: string}>, kill: () => void}}
*/
export function runTrellis2Generate({
@@ -398,6 +422,7 @@ export function runTrellis2Generate({
onProgress,
spawnImpl = spawn,
exists = existsSync,
+ env,
} = {}) {
if (!isTrellis2Installed({ base, exists })) {
const err = new Error('TRELLIS.2 is not installed — install it before generating.');
@@ -407,7 +432,7 @@ export function runTrellis2Generate({
const { command, args } = buildGenerateArgs({ imagePath, outputPath, base });
// 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) });
+ const child = spawnImpl(command, args, { cwd: trellis2Root(base), ...(env ? { env } : {}) });
let assetPath = outputPath || null;
// Retain a bounded tail of combined output so a non-zero exit can be classified
// (HF auth/gated-repo vs. a real crash) — the clue is in the text, not the code.
diff --git a/server/services/imageTo3d/trellis2.test.js b/server/services/imageTo3d/trellis2.test.js
index d95f6587a2..a27b04ca71 100644
--- a/server/services/imageTo3d/trellis2.test.js
+++ b/server/services/imageTo3d/trellis2.test.js
@@ -268,6 +268,34 @@ describe('runTrellis2Generate', () => {
await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_GENERATE_FAILED' });
});
+ it('spawns under the caller-supplied env so the stored HF token reaches the child', async () => {
+ // The pipeline pulls gated HF repos at load time. models.js resolves the token
+ // env (settings-stored token included) and hands it down — assert it lands on the
+ // spawn instead of relying on the server process having HF_TOKEN exported.
+ const child = makeChild();
+ const spawnImpl = vi.fn(() => child);
+ const env = { PATH: '/usr/bin', HF_TOKEN: 'hf_test', HUGGINGFACE_HUB_TOKEN: 'hf_test' };
+ const { promise } = runTrellis2Generate({ imagePath: 'a.png', base: BASE, exists: installed, spawnImpl, env });
+ expect(spawnImpl).toHaveBeenCalledWith(
+ trellis2VenvPython(BASE),
+ [trellis2GenerateScript(BASE), 'a.png'],
+ { cwd: trellis2Root(BASE), env },
+ );
+ child.emit('close', null); // settle the run so its rejection isn't left dangling
+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_GENERATE_FAILED' });
+ });
+
+ it('omits env entirely when the caller passes none, so the child inherits process.env', async () => {
+ // Back-compat: an absent token must not degrade to `env: {}`, which would strip
+ // PATH and a CLI-authenticated ~/.cache/huggingface/token from the child.
+ const child = makeChild();
+ const spawnImpl = vi.fn(() => child);
+ const { promise } = runTrellis2Generate({ imagePath: 'a.png', base: BASE, exists: installed, spawnImpl });
+ expect(spawnImpl.mock.calls[0][2]).toEqual({ cwd: trellis2Root(BASE) });
+ child.emit('close', null);
+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_GENERATE_FAILED' });
+ });
+
it('kill() SIGTERMs the running child so a deleted render terminates promptly', async () => {
const child = makeChild();
const { promise, kill } = runTrellis2Generate({
@@ -371,6 +399,22 @@ describe('installTrellis2', () => {
expect(events.at(-1)).toMatchObject({ type: 'complete' });
});
+ it('spawns install steps under the caller-supplied env, alongside each step cwd', async () => {
+ const children = [makeChild(), makeChild()];
+ let i = 0;
+ const spawnImpl = vi.fn(() => children[i++]);
+ const env = { PATH: '/usr/bin', HF_TOKEN: 'hf_test' };
+ const { promise } = installTrellis2({ base: BASE, spawnImpl, env });
+
+ // The clone step has no cwd — env must still be applied, and must not invent one.
+ expect(spawnImpl).toHaveBeenNthCalledWith(1, 'git', expect.arrayContaining(['clone']), { env });
+ children[0].emit('close', 0);
+ await flush();
+ expect(spawnImpl).toHaveBeenNthCalledWith(2, 'bash', ['setup.sh'], { cwd: trellis2Root(BASE), env });
+ children[1].emit('close', 0);
+ await expect(promise).resolves.toEqual({ ok: true });
+ });
+
it('forwards subprocess output as log events', async () => {
const child = makeChild();
const events = [];