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: centralize Hugging Face child environments (#3034)

[._.]/ Adam Eivy36684d4b3a81
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8bedaa4034..436244cf8e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -28,6 +28,7 @@
## Internal
+- **[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.
- **[issue-3015] Per-track animation registry — frame-count/fps bounds stop being walk-shaped** — the authoring range (`6–16` frames, `4–24` fps) was global and defined once in `server/services/sprites/walkBounds.js`, so it described *every* animation as if it were a walk cycle; a 3-frame ambient loop or a 4-frame scanner action sits below walk's floor of 6 and was literally unrepresentable. A new sharp-free leaf, `server/services/sprites/animationTracks.js`, holds one row per known track (`{ id, label, directional, min/max/defaultFrameCount, min/max/defaultFps, contractFrameCountField, contractFpsField }`), with `walk` as its only row carrying today's exact values. `walkBounds.js` keeps every historical export as a thin re-read of that row, so `walkPostprocess`, `atlas`, `walk`, `server/lib/validation.js`, and the client mirror need no changes. `resolveAnimationTarget` / `targetDrift` / `withTrackTarget` now range-check against the *named track's* row (and read the app rung through the field names that row declares, instead of hard-coded `walkFrameCount`), and the Zod ranges are built by `spriteTrackFrameCountSchema(track)` / `spriteTrackFpsSchema(track)` factories. An absent track resolves to `walk` — which is what keeps every existing call site identical — while an *unrecognized* one throws rather than silently validating against walk's range. The registry validates its own rows at module load (the `navManifest.js` / `catalogTypes.js` idiom), so a half-declared track blocks boot with a message naming the field instead of surfacing later as a `NaN` frame count. #2985's invariant is preserved: an unrecognized sibling track key still round-trips untouched on write, even though writing to an unknown track is now refused. Pure refactor — walk behaves identically end to end; no second track is added here.
diff --git a/server/lib/README.md b/server/lib/README.md
index ef8fa4894b..8856462e8e 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -112,7 +112,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `codexCliOutput.js` | Network/system error patterns for `agentErrorAnalysis.js`. |
| `contextBudget.js` | Context-window budgeter for editorial passes. `estimateTokens`/`estimateTokensFromChars` (chars/4), `usableInputTokens`, `manuscriptContentBudgetChars` (single-block content cap floored at a manuscript minimum so a standalone stage trims to fit a small window instead of overflowing a fixed 48–60K floor, #1488), `planManuscriptPass({ contextWindow, sections })` → `{ mode: 'whole' \| 'chunked', chunks }`. Also `fitContextToManuscriptFloor`/`capContextOverhead`/`trimContextToBudget` — trim a re-sent context block (scene map, character arcs, …) so a large reverse outline on a small window can't starve the manuscript chunk below a budget floor (#1459). Decides whole-manuscript vs chunked given a model's window. |
| `ansiStrip.js` | Streaming ANSI / control-byte stripper. |
-| `hfToken.js` | HuggingFace token resolution (settings > env > CLI). |
+| `hfToken.js` | HuggingFace token resolution (settings > env > CLI): `getHfToken` / `getHfTokenInfo` / `hfTokenEnv`, plus `hfChildEnv(extra?)` for a complete Malloc-stripped child environment that preserves inherited variables while injecting the resolved token. |
| `hfErrors.js` | Parse huggingface_hub gated-access errors: `isGatedRepoError(text)` classifies a failure as gated (403/restricted), `extractGatedRepo(text)` → `owner/name` (or null) for the UI's license deep-link. Shared by the image runner and MIDI transcription (LoRA trainer keeps its own regex to also match bare 401). Pure. |
| `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId)` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. Also `verifyModelCache(repoId,{deep})` (structural safetensors-header + optional sha256 integrity check) and `repairModelCache(repoId,{deep})` (delete corrupt weight files so the download path re-fetches them) — power the "Repair model" banner. `verifySafetensorsStructure(path,size)` is the reusable header/size structural check (reads only the header region) — also used by the Civitai/HF LoRA install path to reject truncated downloads. |
| `hfDownload.js` | `downloadHfRepo({repo,onEvent})` returning `{promise,kill}` — spawns `scripts/hf_download_repo.py` in the FLUX.2 venv (fallback: mflux pythonPath) and emits SSE-friendly stage/progress/complete events. Powers the inline "Download" button next to the model picker. |
diff --git a/server/lib/hfToken.js b/server/lib/hfToken.js
index 4baa3fa3d4..a717087d6c 100644
--- a/server/lib/hfToken.js
+++ b/server/lib/hfToken.js
@@ -8,6 +8,7 @@
import { homedir } from 'node:os';
import { join } from 'node:path';
import { tryReadFile } from './fileUtils.js';
+import { safeChildProcessEnv } from './processEnv.js';
import { getSettings } from '../services/settings.js';
const HF_CLI_TOKEN_PATH = join(homedir(), '.cache', 'huggingface', 'token');
@@ -55,6 +56,13 @@ export async function hfTokenEnv() {
};
}
+// Build a complete, Malloc-stripped child environment with the resolved HF
+// token vars. Passing hfTokenEnv() directly as spawn's `env` would otherwise
+// discard PATH and every other inherited process variable.
+export async function hfChildEnv(extra = {}) {
+ return safeChildProcessEnv({ ...(await hfTokenEnv()), ...extra });
+}
+
// HF tokens are `hf_` + ~36 alphanumeric chars. Exported as a Zod-friendly
// regex so route schemas validate at the boundary instead of post-parse.
export const HF_TOKEN_REGEX = /^hf_[A-Za-z0-9_-]+$/;
diff --git a/server/lib/hfToken.test.js b/server/lib/hfToken.test.js
new file mode 100644
index 0000000000..52fbe9d17a
--- /dev/null
+++ b/server/lib/hfToken.test.js
@@ -0,0 +1,46 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { mockGetSettings, mockTryReadFile } = vi.hoisted(() => ({
+ mockGetSettings: vi.fn(),
+ mockTryReadFile: vi.fn(),
+}));
+
+vi.mock('../services/settings.js', () => ({ getSettings: mockGetSettings }));
+vi.mock('./fileUtils.js', () => ({ tryReadFile: mockTryReadFile }));
+
+import { hfChildEnv } from './hfToken.js';
+
+const TOKEN_ENV_KEYS = ['HF_TOKEN', 'HUGGINGFACE_HUB_TOKEN', 'HUGGINGFACEHUB_API_TOKEN'];
+
+describe('hfChildEnv', () => {
+ let originalEnv;
+
+ beforeEach(() => {
+ originalEnv = Object.fromEntries(['PATH', ...TOKEN_ENV_KEYS].map((key) => [key, process.env[key]]));
+ process.env.PATH = '/portos/test-path';
+ for (const key of TOKEN_ENV_KEYS) delete process.env[key];
+ mockGetSettings.mockResolvedValue({ imageGen: {} });
+ mockTryReadFile.mockResolvedValue(null);
+ });
+
+ afterEach(() => {
+ for (const [key, value] of Object.entries(originalEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ });
+
+ it('preserves PATH when no Hugging Face token resolves', async () => {
+ const env = await hfChildEnv();
+
+ expect(env.PATH).toBe('/portos/test-path');
+ for (const key of TOKEN_ENV_KEYS) expect(env[key]).toBeUndefined();
+ });
+
+ it('merges explicit child overrides after the resolved token environment', async () => {
+ const env = await hfChildEnv({ PYTHONUNBUFFERED: '1' });
+
+ expect(env.PATH).toBe('/portos/test-path');
+ expect(env.PYTHONUNBUFFERED).toBe('1');
+ });
+});
diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.js
index 499e9654be..0f7cfe8e95 100644
--- a/server/routes/imageTo3d.js
+++ b/server/routes/imageTo3d.js
@@ -26,8 +26,7 @@ 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 { hfChildEnv } from '../lib/hfToken.js';
import { openSseStream } from '../lib/sseDownload.js';
const router = Router();
@@ -179,7 +178,7 @@ router.get('/trellis2/install', asyncHandler(async (req, res) => {
// a half-open stream.
let installEnv;
try {
- installEnv = safeChildProcessEnv(await hfTokenEnv());
+ installEnv = await hfChildEnv();
} catch (err) {
console.error(`❌ TRELLIS.2 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}` });
diff --git a/server/routes/imageTo3d.test.js b/server/routes/imageTo3d.test.js
index 1bfa91bc25..fd18a0ebf7 100644
--- a/server/routes/imageTo3d.test.js
+++ b/server/routes/imageTo3d.test.js
@@ -49,11 +49,11 @@ vi.mock('../services/imageTo3d/trellis2.js', () => ({
probeMetalToolchain: vi.fn(async () => ({ available: true })),
}));
-// The install route resolves the central HF token into the child env (#3032).
+// The install route resolves the central HF child env (#3032).
// Mock it so the suite never reads the host's real settings.json or
// ~/.cache/huggingface/token, and so the resolution-failure branch is drivable.
vi.mock('../lib/hfToken.js', () => ({
- hfTokenEnv: vi.fn(async () => ({ HF_TOKEN: 'hf_test', HUGGINGFACE_HUB_TOKEN: 'hf_test' })),
+ hfChildEnv: vi.fn(async () => ({ HF_TOKEN: 'hf_test', HUGGINGFACE_HUB_TOKEN: 'hf_test' })),
}));
vi.mock('../services/imageTo3d/models.js', () => ({
@@ -68,7 +68,7 @@ vi.mock('../services/imageTo3d/models.js', () => ({
import * as targets from '../services/imageTo3d/targets.js';
import * as trellis2 from '../services/imageTo3d/trellis2.js';
import * as models from '../services/imageTo3d/models.js';
-import { hfTokenEnv } from '../lib/hfToken.js';
+import { hfChildEnv } from '../lib/hfToken.js';
import routes from './imageTo3d.js';
const makeApp = () => {
@@ -256,7 +256,7 @@ describe('GET /trellis2/install (SSE)', () => {
trellis2.installTrellis2.mockClear();
trellis2.isTrellis2Installed.mockReturnValueOnce(false);
targets.isTargetAvailable.mockReturnValueOnce(true);
- hfTokenEnv.mockRejectedValueOnce(new Error('settings.json is not valid JSON'));
+ hfChildEnv.mockRejectedValueOnce(new Error('settings.json is not valid JSON'));
const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');
const frames = sseFrames(res.text);
expect(frames.at(-1)).toMatchObject({
diff --git a/server/services/audioMidiTranscription.js b/server/services/audioMidiTranscription.js
index c103de3b7a..2cdd33b27d 100644
--- a/server/services/audioMidiTranscription.js
+++ b/server/services/audioMidiTranscription.js
@@ -31,8 +31,7 @@ import { tmpdir } from 'os';
import { PATHS, shortId, importFileToDir } from '../lib/fileUtils.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';
import { killWithEscalation } from '../lib/killWithEscalation.js';
-import { safeChildProcessEnv } from '../lib/processEnv.js';
-import { hfTokenEnv } from '../lib/hfToken.js';
+import { hfChildEnv } from '../lib/hfToken.js';
import { isGatedRepoError, extractGatedRepo } from '../lib/hfErrors.js';
import { resolveMuscriptorPython, isMuscriptorRuntimeReady, MUSCRIPTOR_VENV_DEFAULT } from '../lib/pythonSetup.js';
import { runSidecarProcess, parseSidecarResult } from '../lib/sidecarProcess.js';
@@ -172,7 +171,7 @@ export async function startMidiTranscription({ audioPath, outputName = 'transcri
// so pass the user's HF token through for the first download to
// authenticate. Without an accepted license the sidecar 403s and we
// classify that into a typed gated_repo frame below.
- const env = safeChildProcessEnv(await hfTokenEnv());
+ const env = await hfChildEnv();
// A cancel can land while the env was resolving (no child to SIGTERM yet)
// — honor the flag before spawning anything.
if (job.cancelRequested) {
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 3643539b86..748dc6f4a0 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -25,9 +25,8 @@ import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { imageGenEvents } from '../imageGenEvents.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
import { resolveFlux2Python, FLUX2_VENV_DEFAULT } from '../../lib/pythonSetup.js';
-import { hfTokenEnv } from '../../lib/hfToken.js';
+import { hfChildEnv } from '../../lib/hfToken.js';
import { extractGatedRepo, isGatedRepoError } from '../../lib/hfErrors.js';
-import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { createLineReader } from '../../lib/streamLines.js';
import { IMAGE_GEN_MODE, LOCAL_IMAGEGEN_DEFAULT_MODEL } from './modes.js';
@@ -547,7 +546,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
imageGenEvents.emit('started', { generationId: jobId, totalSteps: actualSteps });
activeJob = { ...meta, generationId: jobId, totalSteps: actualSteps, step: 0, progress: 0, currentImage: null, mode: IMAGE_GEN_MODE.LOCAL };
- const proc = spawn(bin, args, { env: safeChildProcessEnv(await hfTokenEnv()), stdio: ['ignore', 'pipe', 'pipe'] });
+ const proc = spawn(bin, args, { env: await hfChildEnv(), stdio: ['ignore', 'pipe', 'pipe'] });
activeProcess = proc;
// Spawn ENOENT (missing/non-executable pythonPath) fires BOTH 'error' and
// 'close' on Node — without this guard, a typo'd pythonPath emits two
diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.js
index c3fcd68792..5dc0ac2dcd 100644
--- a/server/services/imageTo3d/models.js
+++ b/server/services/imageTo3d/models.js
@@ -19,8 +19,7 @@ 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 { 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';
@@ -136,7 +135,7 @@ async function executeRender({ id, operationId, runner, sourcePath }) {
// 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());
+ const env = await hfChildEnv();
// 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.
diff --git a/server/services/imageTo3d/models.test.js b/server/services/imageTo3d/models.test.js
index 6b784c9a1c..27948f9053 100644
--- a/server/services/imageTo3d/models.test.js
+++ b/server/services/imageTo3d/models.test.js
@@ -32,11 +32,11 @@ vi.mock('./trellis2.js', () => ({
})),
}));
-// The render spawns with the central HF token in its env (#3032). Mock the resolver
+// The render spawns with the central HF child 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' })),
+ hfChildEnv: vi.fn(async () => ({ HF_TOKEN: 'hf_from_store', HUGGINGFACE_HUB_TOKEN: 'hf_from_store' })),
}));
vi.mock('./db.js', () => ({
diff --git a/server/services/imageTo3d/trellis2.js b/server/services/imageTo3d/trellis2.js
index a189e31ac4..b4b5264317 100644
--- a/server/services/imageTo3d/trellis2.js
+++ b/server/services/imageTo3d/trellis2.js
@@ -529,7 +529,7 @@ export const isTransientInstallError = textMatcher([
* 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
+ * it (PortOS passes `await hfChildEnv()` 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.
*
@@ -733,7 +733,7 @@ const HF_AUTH_HELP = 'TRELLIS.2 could not download a gated model dependency from
*
* **`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
+ * (`await hfChildEnv()` 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.
*
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index a23a03a27d..fd79148220 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -9,7 +9,7 @@
* trained-LoRA registration into `data/loras/`.
*
* Spawn/cancel mirrors videoGen/local.js: SIGTERM → 8s SIGKILL escalation,
- * PYTHONUNBUFFERED, safeChildProcessEnv + hfTokenEnv, caffeinate on darwin.
+ * PYTHONUNBUFFERED, hfChildEnv, caffeinate on darwin.
* The trainers checkpoint on SIGTERM, so a cancel keeps its progress.
*/
@@ -21,8 +21,7 @@ import { platform } from 'os';
import { PATHS, ensureDir, atomicWrite, shortId } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { v4 as uuidv4 } from '../../lib/uuid.js';
-import { hfTokenEnv } from '../../lib/hfToken.js';
-import { safeChildProcessEnv } from '../../lib/processEnv.js';
+import { hfChildEnv } from '../../lib/hfToken.js';
import { spawnDetached, reapDetached, reattachDetached, isReattachable } from '../../lib/detachedSpawn.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { getImageModels } from '../../lib/mediaModels.js';
@@ -619,9 +618,8 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
await runsDb.updateRun(runId, { status: 'running', startedAt: new Date().toISOString() });
trainingEvents.emit('status', { generationId: jobId, message: `Starting ${run.runtime} training (${run.params.steps} steps)` });
- const childEnv = safeChildProcessEnv(await hfTokenEnv());
+ const childEnv = await hfChildEnv({ PYTHONUNBUFFERED: '1' });
delete childEnv.PYTHONPATH;
- childEnv.PYTHONUNBUFFERED = '1';
console.log(`🏋️ training [${shortId(jobId)}] spawn ${basename(bin)} ${run.runtime} steps=${run.params.steps} rank=${run.params.rank} images=${manifest.images.length}${resumeCheckpoint ? ` resume=${basename(resumeCheckpoint)}` : ''}`);
// `spawnDetached` double-forks the trainer so it reparents to init (PPID=1)
diff --git a/server/services/pipeline/musicGen.js b/server/services/pipeline/musicGen.js
index 6aba46fb43..1b215f1c76 100644
--- a/server/services/pipeline/musicGen.js
+++ b/server/services/pipeline/musicGen.js
@@ -33,8 +33,7 @@ import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { randomUUID } from 'crypto';
import { PATHS, ensureDir } from '../../lib/fileUtils.js';
-import { safeChildProcessEnv } from '../../lib/processEnv.js';
-import { hfTokenEnv } from '../../lib/hfToken.js';
+import { hfChildEnv } from '../../lib/hfToken.js';
import { runSidecarProcess, parseSidecarResult } from '../../lib/sidecarProcess.js';
import {
resolveMusicgenPython, MUSICGEN_RUNTIME_DIR, MUSICGEN_VENV_DEFAULT,
@@ -289,7 +288,7 @@ export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT
// The default backends use ungated HF weights (facebook/* and cvssp/*), so a
// token isn't required — but pass it through when the user has one set so the
// first download doesn't hit anonymous HF rate limits.
- const env = safeChildProcessEnv(await hfTokenEnv());
+ const env = await hfChildEnv();
// STAGE: lines are echoed to pm2 logs so a stuck first-run model download is
// visible, and fire onActivity so the media-job queue's idle watchdog resets
// (see the doc block above).
@@ -322,4 +321,3 @@ export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT
engine: engine.id,
};
}
-
diff --git a/server/services/pipeline/musicGen.test.js b/server/services/pipeline/musicGen.test.js
index 7e5d5e660e..fbb6d87a4f 100644
--- a/server/services/pipeline/musicGen.test.js
+++ b/server/services/pipeline/musicGen.test.js
@@ -301,7 +301,7 @@ vi.mock('../../lib/fileUtils.js', async () => {
};
});
-vi.mock('../../lib/hfToken.js', () => ({ hfTokenEnv: async () => ({}) }));
+vi.mock('../../lib/hfToken.js', () => ({ hfChildEnv: async () => ({}) }));
// Venv resolvers — flip readiness per engine per test.
vi.mock('../../lib/pythonSetup.js', async () => {
diff --git a/server/services/videoGen/deleteHistoryItem.test.js b/server/services/videoGen/deleteHistoryItem.test.js
index 1d5c1ac76c..215ca9d652 100644
--- a/server/services/videoGen/deleteHistoryItem.test.js
+++ b/server/services/videoGen/deleteHistoryItem.test.js
@@ -56,7 +56,7 @@ vi.mock('../../lib/ffmpeg.js', () => ({
}));
vi.mock('../../lib/hfToken.js', () => ({
- hfTokenEnv: vi.fn(async () => ({})),
+ hfChildEnv: vi.fn(async () => ({})),
getHfToken: vi.fn(async () => null),
}));
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index c96889698f..6b02159c30 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -26,7 +26,7 @@ import { videoGenEvents } from './events.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../../lib/mediaModels.js';
import { findFfmpeg, safeUnder, generateThumbnail, optimizeForStreaming, upscaleVideo2x, extractEvaluationFrames } from '../../lib/ffmpeg.js';
-import { hfTokenEnv } from '../../lib/hfToken.js';
+import { hfChildEnv } from '../../lib/hfToken.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { makeVideoGenLineHandler, finalizeGeneratedVideo, isWatchdogSuccess } from './generateVideoHelpers.js';
import { assertSafeLoraFilename } from '../loras.js';
@@ -850,11 +850,11 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// of the parent shell's PYTHONPATH. Setting to `undefined` in a spread does
// NOT unset the var — Node coerces it to the literal string "undefined" —
// so build the env explicitly and `delete`.
- // Merge HF_TOKEN/HF_HOME via hfTokenEnv() so the Wan 2.2 / HunyuanVideo
+ // Build the complete HF child env so the Wan 2.2 / HunyuanVideo
// python helpers can authenticate snapshot_download() against gated repos
// (mirrors the imageGen child-spawn pattern). LTX-2 doesn't currently use
// a gated repo, but the merge is harmless when no token is configured.
- const childEnv = safeChildProcessEnv(await hfTokenEnv());
+ const childEnv = await hfChildEnv();
delete childEnv.PYTHONPATH;
// Force unbuffered Python I/O so tqdm + loguru + our own STAGE: prints flush
// immediately. Without this, child stdio is line-buffered against a pipe and
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index ae28607e05..44a41fe81d 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -63,11 +63,11 @@ vi.mock('../../lib/ffmpeg.js', () => ({
extractEvaluationFrames: vi.fn(async () => []),
}));
-// hfTokenEnv() resolves to {} when no token is configured; mocking here
+// hfChildEnv() carries the resolved token over the inherited child env; mocking here
// avoids touching the real settings layer (which would await an unmocked
// `getSettings()` chain and hang the spawn-mock-driven tests).
vi.mock('../../lib/hfToken.js', () => ({
- hfTokenEnv: vi.fn(async () => ({})),
+ hfChildEnv: vi.fn(async () => ({})),
getHfToken: vi.fn(async () => null),
}));