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: thin apps-list route and split imageGen setup into its own module (#2533)

[._.]/ Adam Eivy7814b3bd6a85
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 92aac3f67c..a093e70af2 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -8,6 +8,7 @@
## Changed
- **[issue-2530] Decompose `cos.js` `dequeueNextTask` and split `cosAgents.js` into focused modules.** The ~370-line `dequeueNextTask` scheduler is now a thin orchestrator that threads a shared `ctx` through five `spawnDequeuePriorityN(ctx)` tier helpers (mirroring `evaluateTasks`), with the pure per-cycle capacity tracker (`createDequeueCapacity`) and mission/idle tier-eligibility predicates extracted to a new `server/services/cosDequeue.js` — so the scheduler and its unit tests exercise the *same* guards instead of a local replica. The ~1090-line `cosAgents.js` is split into focused siblings — `cosAgentIndex.js` (date-bucket index / migration / prune / archive layout), `cosAgentLifecycle.js` (register / complete / output / terminate / pause / kill / BTW / zombie cleanup), `cosAgentFeedback.js` (feedback capture + classifier), `cosAgentArchive.js` (state-eviction sweeps) — with `cosAgents.js` kept as a thin barrel so every existing import path is unchanged. Pure mechanical refactor: no behavior change.
+- **[issue-2533] Thin the apps-list route and split the imageGen setup routes into their own module.** The `GET /api/apps` handler's ~80 lines of inline PM2 enrichment (one read per `pm2Home`, absent-vs-empty status classification, ecosystem-config process backfill, port derivation) moved into a new `server/services/appListEnrichment.js` (`enrichAppsWithPm2Status(apps)`), so the route just fetches the raw records and responds; the pure port/status helpers (`deriveUiPort`/`deriveAppPorts`/`computeOverallStatus`) live there too and are re-exported from `routes/apps/shared.js` so the detail/lifecycle routes keep one shared implementation. The `/api/image-gen/setup/*` handlers (python probe/venv bootstrap, FLUX.2 install/status, HuggingFace-token store, pip installer) split out of the large `routes/imageGen.js` render router into `routes/imageGenSetup.js`, with the setup-check cache and pip allowlist relocated to `services/imageGen/setup.js`. Pure mechanical refactor — no behavior change.
- **[issue-2531] Split the pipeline `issues.js` and `visualStages.js` monoliths along CRUD/stage/sync seams.** The ~1470-line `server/services/pipeline/issues.js` is now a thin barrel over `issuesShared.js` (store facade + per-series write queue + record sanitizers + `renumberInline`), `issueCrud.js` (create/read/list/update/delete + numbering/reassign), `issueStages.js` (per-stage merge/history/restore), and `issueSync.js` (peer-sync LWW merge + tombstone GC). The ~1760-line `visualStages.js` is now a thin barrel over `visualStageHelpers.js` (shared style/prompt composers + image-gen enqueue plumbing), `covers.js` (comic + volume front/back covers), `comicPages.js` (comic page renders + panel prompt refine), and `storyboards.js` (scene/shot renders + scene refine). Pure mechanical refactor — no behavior change; the single-tail-per-series write serialization (`queueSeriesIssuesWrite`) and the store's `queueTypeIndexWrite` merge snapshot are preserved, and every existing `from './issues.js'` / `from './visualStages.js'` import path still resolves through the barrels.
## Documentation
diff --git a/server/routes/apps/crud.js b/server/routes/apps/crud.js
index 1ac43da386..0654e73fe9 100644
--- a/server/routes/apps/crud.js
+++ b/server/routes/apps/crud.js
@@ -18,96 +18,21 @@ import { notifyAppsChanged, PORTOS_APP_ID } from '../../services/apps.js';
import * as pm2Service from '../../services/pm2.js';
import { validateRequest, appSchema, appUpdateSchema } from '../../lib/validation.js';
import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
-import { parseEcosystemFromPath, usesPm2 } from '../../services/streamingDetect.js';
+import { usesPm2 } from '../../services/streamingDetect.js';
import { detectAppIcon } from '../../services/appIconDetect.js';
import { hasDeployScript } from '../../services/appDeployer.js';
import { checkScripts } from '../../services/xcodeScripts.js';
import { applyEcosystemPortEdits } from '../../services/appPortConfig.js';
+import { enrichAppsWithPm2Status } from '../../services/appListEnrichment.js';
import { loadApp, pathExists, deriveAppPorts, computeOverallStatus } from './shared.js';
const router = Router();
-// GET /api/apps - List all apps
+// GET /api/apps - List all apps. The route fetches the raw records; the
+// appListEnrichment service owns the PM2 status/port/process enrichment.
router.get('/', asyncHandler(async (req, res) => {
const apps = await appsService.getAllApps();
-
- // Group apps by their PM2_HOME (null = default)
- const pm2HomeGroups = new Map();
- for (const app of apps) {
- const home = app.pm2Home || null;
- if (!pm2HomeGroups.has(home)) {
- pm2HomeGroups.set(home, []);
- }
- pm2HomeGroups.get(home).push(app);
- }
-
- // Fetch PM2 processes for each unique PM2_HOME.
- // listProcessesStrict returns `null` on a failed read (vs `[]` for a
- // successful read with no processes) — track those homes so we report
- // `unknown` (status unavailable) instead of `not_started` (confidently not
- // running) for their apps. See getAppStatuses() in the service for the same
- // absent-vs-empty distinction.
- const pm2Maps = new Map();
- const failedHomes = new Set();
- for (const pm2Home of pm2HomeGroups.keys()) {
- const processes = await pm2Service.listProcessesStrict(pm2Home);
- if (processes === null) {
- failedHomes.add(pm2Home);
- pm2Maps.set(pm2Home, new Map());
- } else {
- pm2Maps.set(pm2Home, new Map(processes.map(p => [p.name, p])));
- }
- }
-
- // Enrich with PM2 status and auto-populate processes if needed
- const enriched = await Promise.all(apps.map(async (app) => {
- // Non-PM2 apps skip PM2 enrichment entirely
- if (!usesPm2(app.type)) {
- return { ...app, pm2Status: {}, overallStatus: 'n/a', hasDeployScript: hasDeployScript(app), xcodeScripts: checkScripts(app) };
- }
-
- const pm2Home = app.pm2Home || null;
- const pm2Map = pm2Maps.get(pm2Home) || new Map();
- const homeFailed = failedHomes.has(pm2Home);
-
- const statuses = {};
- for (const processName of app.pm2ProcessNames || []) {
- const pm2Proc = pm2Map.get(processName);
- // A failed PM2 read leaves status genuinely unknown — don't claim
- // `not_found` (which the UI reads as "registered but never launched").
- statuses[processName] = pm2Proc
- ?? { name: processName, status: homeFailed ? 'unknown' : 'not_found', pm2_env: null };
- }
-
- // Compute overall status. A failed PM2 home short-circuits to `unknown`
- // with a `degraded` flag rather than collapsing to `not_started`.
- const overallStatus = computeOverallStatus(Object.values(statuses), homeFailed);
-
- // Auto-populate processes from ecosystem config if not already set
- let processes = app.processes;
- if ((!processes || processes.length === 0) && await pathExists(app.repoPath)) {
- const parsed = await parseEcosystemFromPath(app.repoPath).catch(() => ({ processes: [] }));
- processes = parsed.processes;
- }
-
- // Auto-derive uiPort/apiPort/devUiPort from processes when not explicitly set
- const { uiPort, apiPort, devUiPort } = deriveAppPorts(app, processes);
-
- return {
- ...app,
- processes,
- uiPort,
- devUiPort,
- apiPort,
- pm2Status: statuses,
- overallStatus,
- degraded: homeFailed,
- hasDeployScript: hasDeployScript(app),
- xcodeScripts: checkScripts(app)
- };
- }));
-
- res.json(enriched);
+ res.json(await enrichAppsWithPm2Status(apps));
}));
// GET /api/apps/:id - Get single app
diff --git a/server/routes/apps/shared.js b/server/routes/apps/shared.js
index 8a98e3d511..a32385c1ab 100644
--- a/server/routes/apps/shared.js
+++ b/server/routes/apps/shared.js
@@ -1,7 +1,11 @@
/**
- * Shared plumbing for the apps sub-routers: the `loadApp` param middleware,
- * the async `pathExists` guard, and the pure port/status-derivation helpers
- * used by both the list (`GET /`) and detail (`GET /:id`) endpoints.
+ * Shared plumbing for the apps sub-routers: the `loadApp` param middleware and
+ * the async `pathExists` guard.
+ *
+ * The pure port/status-derivation helpers (`deriveUiPort`, `deriveAppPorts`,
+ * `computeOverallStatus`) and the list enrichment now live in the
+ * `appListEnrichment` service; they are re-exported here so existing route
+ * imports (`crud.js`, `lifecycle.js`) keep a single import surface.
*
* Mirrors the pipeline sub-router `shared.js` pattern — one small module of
* common plumbing that every domain router imports, so the split preserves a
@@ -12,18 +16,11 @@ import { access } from 'fs/promises';
import * as appsService from '../../services/apps.js';
import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
+export { deriveUiPort, deriveAppPorts, computeOverallStatus } from '../../services/appListEnrichment.js';
+
/** Async equivalent of existsSync — returns true if the path is accessible */
export const pathExists = (p) => access(p).then(() => true).catch(() => false);
-/**
- * Derive uiPort from apiPort when app has dev UI but no dedicated prod UI port
- * (prod UI is served by the API server in these cases).
- */
-export function deriveUiPort(uiPort, apiPort, devUiPort) {
- if (!uiPort && apiPort && devUiPort) return apiPort;
- return uiPort;
-}
-
/**
* Middleware to load app by :id param and attach to req.loadedApp.
* Throws 404 if not found, eliminating repeated null checks across routes.
@@ -36,44 +33,3 @@ export const loadApp = asyncHandler(async (req, res, next) => {
req.loadedApp = app;
next();
});
-
-/**
- * Derive uiPort/apiPort/devUiPort from an app's process list when not
- * explicitly set on the app record. Shared by the list and detail endpoints so
- * the two never diverge. Returns the resolved trio (uiPort passed through
- * deriveUiPort for the served-by-API case).
- */
-export function deriveAppPorts(app, processes) {
- let { uiPort, apiPort, devUiPort } = app;
- const procs = processes || [];
- if (!uiPort && procs.length) {
- const uiProc = procs.find(p => p.ports?.ui);
- if (uiProc) uiPort = uiProc.ports.ui;
- }
- if (!apiPort && procs.length) {
- const apiProc = procs.find(p => p.ports?.api);
- if (apiProc) apiPort = apiProc.ports.api;
- }
- if (!devUiPort && procs.length) {
- const devUiProc = procs.find(p => p.ports?.devUi);
- if (devUiProc) devUiPort = devUiProc.ports.devUi;
- }
- uiPort = deriveUiPort(uiPort, apiPort, devUiPort);
- return { uiPort, apiPort, devUiPort };
-}
-
-/**
- * Compute the overall status from a set of per-process PM2 statuses. A degraded
- * (failed-read) home short-circuits to `unknown` rather than collapsing to a
- * confident `not_started`. Shared by the list and detail endpoints.
- */
-export function computeOverallStatus(statusValues, degraded) {
- // Mirrors the original inline logic exactly: an empty status set (an app with
- // no PM2 process names) satisfies the vacuous `every(...)` and resolves to
- // `not_started`, NOT `unknown`.
- if (degraded) return 'unknown';
- if (statusValues.some(s => s.status === 'online')) return 'online';
- if (statusValues.some(s => s.status === 'stopped')) return 'stopped';
- if (statusValues.every(s => s.status === 'not_found')) return 'not_started';
- return 'unknown';
-}
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 23e71d6c2e..80c3957e81 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -11,7 +11,7 @@
import { Router } from 'express';
import { z } from 'zod';
-import { unlink, stat, copyFile } from 'fs/promises';
+import { unlink, copyFile } from 'fs/promises';
import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
import {
validateRequest, imageEdgeSchema, refineImagePixelCap, PIXEL_CAP_MESSAGE,
@@ -19,20 +19,12 @@ import {
import { optionalUploadFields } from '../lib/multipart.js';
import * as imageGen from '../services/imageGen/index.js';
import { local, IMAGE_GEN_MODE, IMAGE_GEN_MODES } from '../services/imageGen/index.js';
+import setupRouter from './imageGenSetup.js';
import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';
-import { getSettings, updateSettingsWith } from '../services/settings.js';
-import { getHfToken, getHfTokenInfo, HF_TOKEN_REGEX } from '../lib/hfToken.js';
import { getImageModels, isFlux2, isEditOnly, repoForModel, requiredReposForModel } from '../lib/mediaModels.js';
import { usesDiffusersRunner } from '../lib/runners.js';
import { inspectModelCache, verifyModelCache, repairModelCache, aggregateVerifies } from '../lib/hfCache.js';
-import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
-import { createInstallLogger } from '../lib/installLogger.js';
-import {
- REQUIRED_PACKAGES, detectPython, installPackages,
- createVenv, isAllowedPython, pipNameFor,
- resolveFlux2Python, FLUX2_VENV_DEFAULT, installFlux2Venv, isFlux2VenvHealthy,
- detectArm64Python, HOST_ARCH, probePythonHealth,
-} from '../lib/pythonSetup.js';
+import { startHfDownloadStream } from '../lib/sseDownload.js';
import { PATHS, ensureDir, resolveGalleryImage } from '../lib/fileUtils.js';
import { prepareGenerateParams } from '../services/imageGen/prepareParams.js';
import { applyImageClean, applyWatermarkRemoval, applyLightRegenVariant } from '../services/imageGen/variants.js';
@@ -799,300 +791,8 @@ router.post('/:filename/regenerate', asyncHandler(async (req, res) => {
return res.json(queuedImageResponse({ ...queued, mode: IMAGE_GEN_MODE.LOCAL, model: backend.model.id }));
}));
-// --- Local-mode setup automation ---
-
-router.get('/setup/python', asyncHandler(async (_req, res) => {
- const path = await detectPython();
- res.json({ path });
-}));
-
-// SSE-driven FLUX.2 venv bootstrap. Replaces the "drop to a shell and run
-// INSTALL_FLUX2=1 bash scripts/setup-image-video.sh" friction with an in-app
-// install: the client opens an EventSource, gets staged progress events
-// (detect → venv → upgrade-pip → install → verify), and either finishes or
-// surfaces a clear error. Runs the install logic in-process via
-// installFlux2Venv() so we get structured `stage` events the UI can animate
-// against, instead of having to parse bash output.
-//
-// In-flight singleton: a rapid double-click would otherwise race two pip
-// processes against the same venv directory. resolveFlux2Python() can't
-// gate the second click — the first install hasn't created the python yet.
-let flux2InstallInFlight = null;
-
-router.get('/setup/flux2-install', asyncHandler(async (req, res) => {
- const { send, safeEnd } = openSseStream(res);
-
- // Skip only when the venv binary AND the import work — a half-broken venv
- // (binary present, packages missing from a killed mid-install) needs to
- // re-run the install, not be reported as ready.
- if (await isFlux2VenvHealthy()) {
- send({ type: 'stage', stage: 'verify', message: 'FLUX.2 venv already installed.' });
- send({ type: 'complete', message: 'Already installed — nothing to do.' });
- return safeEnd();
- }
- if (flux2InstallInFlight) {
- send({ type: 'error', message: 'Another FLUX.2 install is already running. Wait for it to finish or restart PortOS.' });
- return safeEnd();
- }
-
- // Server-console visibility for the multi-GB torch install (start / stage
- // milestones / outcome) — installFlux2Venv streams progress only to `send`.
- const installLog = createInstallLogger({ installer: 'FLUX.2 venv', target: FLUX2_VENV_DEFAULT });
- const emit = (ev) => { installLog.onEvent(ev); send(ev); };
- installLog.start();
-
- const { promise, kill } = installFlux2Venv(emit);
- flux2InstallInFlight = promise;
- promise
- // installFlux2Venv resolves { ok:false } on some pip failures without
- // emitting a terminal SSE event, so reconcile the outcome from the result
- // (a no-op if `onEvent` already logged a complete/error frame).
- .then((result) => {
- if (result?.ok) installLog.success(result?.pythonPath ? `ready: ${result.pythonPath}` : undefined);
- else installLog.failure(`failed at stage ${result?.stage || 'unknown'}`);
- })
- .catch((err) => emit({ type: 'error', message: err?.message || 'Unknown installer failure' }))
- .finally(() => {
- flux2InstallInFlight = null;
- safeEnd();
- });
-
- // Cancel the install if the client navigates away mid-bootstrap. A torch
- // install is a multi-GB download and would otherwise keep running invisibly.
- req.on('close', () => { installLog.cancel(); kill(); safeEnd(); });
-}));
-
-// Used by the FLUX.2 model picker: surface a banner when the gated repo's
-// license hasn't been accepted (HF_TOKEN missing) and the runner is set up.
-// `venvInstalled` reflects functional health (binary AND packages import) —
-// a half-broken venv would otherwise hide the install banner forever.
-router.get('/setup/flux2-status', asyncHandler(async (req, res) => {
- const [token, healthy] = await Promise.all([getHfToken(), isFlux2VenvHealthy()]);
- const venvPython = resolveFlux2Python();
- // The 9B (bf16) and 4B variants ship as separately-gated repos with
- // distinct HF license URLs. Use the active model's `licenseUrl` when the
- // client supplies a `modelId`; fall back to the 4B URL for callers that
- // pre-date the multi-variant registry.
- const FLUX2_DEFAULT_LICENSE = 'https://huggingface.co/black-forest-labs/FLUX.2-klein-4B';
- let licenseUrl = FLUX2_DEFAULT_LICENSE;
- if (typeof req.query?.modelId === 'string' && req.query.modelId.length > 0) {
- const model = getImageModels().find((m) => m.id === req.query.modelId);
- if (isFlux2(model) && typeof model?.licenseUrl === 'string' && model.licenseUrl.length > 0) {
- licenseUrl = model.licenseUrl;
- }
- }
- res.json({
- hfTokenPresent: !!token,
- venvInstalled: healthy,
- venvPath: venvPython,
- expectedVenvPath: FLUX2_VENV_DEFAULT,
- licenseUrl,
- });
-}));
-
-// Generic HF-token presence check for legacy mflux runners that don't need
-// the FLUX.2 venv. Any model entry with `requiresHfToken: true` in
-// data/media-models.json drives the banner through this endpoint.
-router.get('/setup/hf-token-status', asyncHandler(async (_req, res) => {
- const { token, source } = await getHfTokenInfo();
- res.json({ hfTokenPresent: !!token, source });
-}));
-
-// Save the HF token from the inline form on the Image Gen page. settings.json
-// is the canonical location (single-user app behind Tailscale — see CLAUDE.md).
-// Same endpoint serves FLUX.2 and legacy mflux gated models — the token is
-// global (HF_TOKEN env in spawn).
-const hfTokenSchema = z.object({
- token: z.string().regex(HF_TOKEN_REGEX, 'Token must look like `hf_…`').max(200),
-});
-router.post('/setup/hf-token', asyncHandler(async (req, res) => {
- const { token } = validateRequest(hfTokenSchema, req.body || {});
- await updateSettingsWith((settings) => ({
- ...settings,
- imageGen: { ...(settings.imageGen || {}), hfToken: token.trim() },
- }));
- res.json({ ok: true, hfTokenPresent: true, source: 'stored' });
-}));
-
-// Clear the stored HF token. Falls back to env / CLI tokens if present —
-// callers should re-fetch /setup/hf-token-status to see the post-clear state.
-router.delete('/setup/hf-token', asyncHandler(async (_req, res) => {
- await updateSettingsWith((settings) => {
- const { hfToken: _drop, ...restImageGen } = settings.imageGen || {};
- return { ...settings, imageGen: restImageGen };
- });
- const { token, source } = await getHfTokenInfo();
- res.json({ ok: true, hfTokenPresent: !!token, source });
-}));
-
-const checkSchema = z.object({ pythonPath: z.string().min(1) });
-
-// /setup/check is called on every keystroke in the python-path input (debounced
-// to 400ms), on mount, AND on the refresh button — each call spawns a python
-// subprocess (~0.5-1s warm) plus the optional `detectArm64Python` walk. A
-// modest in-memory cache, keyed by (pythonPath, stat.mtimeMs) and bounded by
-// SETUP_CHECK_TTL_MS, collapses the typing-flow repeats to memo hits without
-// risking stale data — the key changes the moment the interpreter is swapped
-// (venv create, brew upgrade) and the install path explicitly busts on
-// completion.
-const SETUP_CHECK_TTL_MS = 30_000;
-const setupCheckCache = new Map();
-
-const buildSetupCheck = async (pythonPath) => {
- const health = await probePythonHealth(pythonPath);
- // The arch warning is specifically about mlx wheels (arm64-only) on Apple
- // Silicon. A generic interpreterArch !== HOST_ARCH compare would false-
- // positive on Windows (Python reports `AMD64`, Node reports `x86_64`) and
- // on hypothetical arm64 Linux — where mlx isn't even in REQUIRED_PACKAGES.
- const archMismatch = process.platform === 'darwin'
- && HOST_ARCH === 'arm64'
- && health.interpreterArch === 'x86_64';
- const suggestedArm64Python = archMismatch ? await detectArm64Python() : null;
- return {
- pythonPath,
- required: REQUIRED_PACKAGES,
- hostArch: HOST_ARCH,
- archMismatch,
- suggestedArm64Python,
- ...health,
- };
-};
-
-const invalidateSetupCheck = (pythonPath) => {
- if (!pythonPath) {
- setupCheckCache.clear();
- return;
- }
- const prefix = `${pythonPath}|`;
- for (const key of setupCheckCache.keys()) {
- if (key.startsWith(prefix)) setupCheckCache.delete(key);
- }
-};
-
-router.get('/setup/check', asyncHandler(async (req, res) => {
- const { pythonPath } = validateRequest(checkSchema, req.query);
- if (!isAllowedPython(pythonPath)) {
- throw new ServerError('pythonPath must be a python interpreter (basename python/python3/python3.NN)', { status: 400 });
- }
- // mtime keys auto-bust when the interpreter binary itself changes (rare but
- // surfaces brew upgrades / re-symlinks). A stat() failure (path not found)
- // skips the cache rather than poisoning it with a `mtime=missing` entry.
- const mtimeMs = await stat(pythonPath).then((s) => s.mtimeMs).catch(() => null);
- const key = mtimeMs !== null ? `${pythonPath}|${mtimeMs}` : null;
- if (key) {
- const hit = setupCheckCache.get(key);
- if (hit && hit.expiresAt > Date.now()) return res.json(hit.result);
- }
- const result = await buildSetupCheck(pythonPath);
- if (key) {
- // Sweep expired entries on every write so a long-running process doesn't
- // accumulate stale (path, mtime) combos from intermediate keystrokes
- // (each typed character of a path string lands a unique key here).
- const now = Date.now();
- for (const [k, v] of setupCheckCache) {
- if (v.expiresAt <= now) setupCheckCache.delete(k);
- }
- setupCheckCache.set(key, { result, expiresAt: now + SETUP_CHECK_TTL_MS });
- }
- res.json(result);
-}));
-
-const venvSchema = z.object({
- basePython: z.string().min(1).optional(),
-});
-
-router.post('/setup/create-venv', asyncHandler(async (req, res) => {
- const { basePython } = validateRequest(venvSchema, req.body || {});
- if (basePython && !isAllowedPython(basePython)) {
- throw new ServerError('basePython must be a python interpreter (basename python/python3/python3.NN)', { status: 400 });
- }
- const base = basePython || (await detectPython());
- if (!base) {
- throw new ServerError('No base Python 3 found to bootstrap a venv. Install Python 3.10+ first.', { status: 400 });
- }
- const target = join(PATHS.data, 'python', 'venv');
- const venvPython = await createVenv(base, target);
- // Bust the setup-check cache for both the base interpreter and the new
- // venv python — the venv inherits the base's mtime-key but its packages
- // differ, and a subsequent /setup/check would otherwise return the base's
- // pre-venv snapshot.
- invalidateSetupCheck(base);
- invalidateSetupCheck(venvPython);
- res.json({ pythonPath: venvPython, target });
-}));
-
-// Allowlist: only PortOS's own required pip names (or their pinned variants
-// like `transformers<5`) are installable. Without this, the endpoint would
-// happily pip-install arbitrary PyPI packages — the install runs as the
-// PortOS user and pip itself executes setup.py from the package, so an
-// arbitrary package install is effectively arbitrary code execution.
-// Build the pip-spec allowlist from REQUIRED_PACKAGES via pipNameFor — that
-// translates import names (`cv2`) to their actual pip specs
-// (`opencv-python`). Without this mapping, the allowlist would contain
-// import-only names that can't actually be installed but ALSO don't appear
-// here as their pip specs, so the legitimate install request would 400.
-// Worse: an import name like `cv2` isn't a real PyPI package but if a
-// typosquat existed under that name it'd be installable.
-const REQUIRED_PIP_NAMES = new Set([
- ...REQUIRED_PACKAGES.map(pipNameFor),
- // Windows torch path also installs torch + diffusers, which are in
- // REQUIRED_PACKAGES on Windows but not on macOS — keep them allowlisted
- // unconditionally so a Windows install requested from a macOS server
- // (unlikely but possible) doesn't 400 unhelpfully.
- 'torch',
- 'diffusers',
- // Both the bare `transformers` and the macOS-pinned `transformers<5`
- // variant should be installable; pipNameFor only emits the pinned
- // variant on macOS, so list both unconditionally for safety.
- 'transformers',
- 'transformers<5',
-]);
-
-const installSchema = z.object({
- pythonPath: z.string().min(1),
- packages: z.array(z.string().min(1)).min(1).max(40),
-});
-
-// EventSource consumers re-run /setup/check on `complete` to refresh status.
-router.get('/setup/install', (req, res) => {
- const pythonPath = req.query.pythonPath;
- const packages = String(req.query.packages || '').split(',').filter(Boolean);
- const parsed = installSchema.safeParse({ pythonPath, packages });
- if (!parsed.success) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- return res.end(JSON.stringify({ error: parsed.error.message }));
- }
- if (!isAllowedPython(parsed.data.pythonPath)) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- return res.end(JSON.stringify({ error: 'pythonPath must be a python interpreter' }));
- }
- const disallowed = parsed.data.packages.filter((p) => !REQUIRED_PIP_NAMES.has(p));
- if (disallowed.length) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- return res.end(JSON.stringify({ error: `Packages not in allowlist: ${disallowed.join(', ')}` }));
- }
-
- // `send` and `safeEnd` from openSseStream no-op once the response has ended
- // so a late pip-output line (or the promise.then below) doesn't trigger
- // ERR_STREAM_WRITE_AFTER_END or double-end the response.
- const { send, safeEnd } = openSseStream(res);
- // Server-console visibility for the (multi-GB) local pip install — the SSE
- // stream otherwise surfaces progress only in the browser.
- const installLog = createInstallLogger({ installer: 'Image Gen packages', target: parsed.data.pythonPath });
- const emit = (ev) => { installLog.onEvent(ev); send(ev); };
- installLog.start();
- const { promise, kill } = installPackages(parsed.data.pythonPath, parsed.data.packages, emit);
- promise.then(() => {
- // Drop the now-stale setup-check snapshot before the client re-runs the
- // probe on `complete` — without this it would read the pre-install
- // missing-packages list back from cache.
- invalidateSetupCheck(parsed.data.pythonPath);
- safeEnd();
- });
-
- // Client navigation away should kill pip — a torch upgrade can run for
- // 10+ minutes and would otherwise keep going invisibly.
- req.on('close', () => { installLog.cancel(); kill(); safeEnd(); });
-});
+// Local-mode setup automation (python probe/venv, FLUX.2 install/status,
+// HF token store, pip installer) lives in its own router.
+router.use("/setup", setupRouter);
export default router;
diff --git a/server/routes/imageGenSetup.js b/server/routes/imageGenSetup.js
new file mode 100644
index 0000000000..a6e948f203
--- /dev/null
+++ b/server/routes/imageGenSetup.js
@@ -0,0 +1,237 @@
+/**
+ * Image Gen — local-mode setup routes (`/api/image-gen/setup/*`).
+ *
+ * Split out of `routes/imageGen.js` so the large generate/gallery/regen router
+ * stays focused on rendering. Covers the python-interpreter probe + venv
+ * bootstrap, the FLUX.2 venv install/status, the HuggingFace token store, and
+ * the pip package installer. Mounted at `/setup` by the parent router.
+ *
+ * Handlers validate + wire SSE/HTTP; the setup-check cache and the pip
+ * allowlist live in `services/imageGen/setup.js`.
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { join } from 'node:path';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import { getSettings, updateSettingsWith } from '../services/settings.js';
+import { getHfToken, getHfTokenInfo, HF_TOKEN_REGEX } from '../lib/hfToken.js';
+import { getImageModels, isFlux2 } from '../lib/mediaModels.js';
+import { createInstallLogger } from '../lib/installLogger.js';
+import {
+ detectPython, installPackages, createVenv, isAllowedPython,
+ resolveFlux2Python, FLUX2_VENV_DEFAULT, installFlux2Venv, isFlux2VenvHealthy,
+} from '../lib/pythonSetup.js';
+import { PATHS } from '../lib/fileUtils.js';
+import { openSseStream } from '../lib/sseDownload.js';
+import { getSetupCheck, invalidateSetupCheck, REQUIRED_PIP_NAMES } from '../services/imageGen/setup.js';
+
+const router = Router();
+
+router.get('/python', asyncHandler(async (_req, res) => {
+ const path = await detectPython();
+ res.json({ path });
+}));
+
+// SSE-driven FLUX.2 venv bootstrap. Replaces the "drop to a shell and run
+// INSTALL_FLUX2=1 bash scripts/setup-image-video.sh" friction with an in-app
+// install: the client opens an EventSource, gets staged progress events
+// (detect → venv → upgrade-pip → install → verify), and either finishes or
+// surfaces a clear error. Runs the install logic in-process via
+// installFlux2Venv() so we get structured `stage` events the UI can animate
+// against, instead of having to parse bash output.
+//
+// In-flight singleton: a rapid double-click would otherwise race two pip
+// processes against the same venv directory. resolveFlux2Python() can't
+// gate the second click — the first install hasn't created the python yet.
+let flux2InstallInFlight = null;
+
+router.get('/flux2-install', asyncHandler(async (req, res) => {
+ const { send, safeEnd } = openSseStream(res);
+
+ // Skip only when the venv binary AND the import work — a half-broken venv
+ // (binary present, packages missing from a killed mid-install) needs to
+ // re-run the install, not be reported as ready.
+ if (await isFlux2VenvHealthy()) {
+ send({ type: 'stage', stage: 'verify', message: 'FLUX.2 venv already installed.' });
+ send({ type: 'complete', message: 'Already installed — nothing to do.' });
+ return safeEnd();
+ }
+ if (flux2InstallInFlight) {
+ send({ type: 'error', message: 'Another FLUX.2 install is already running. Wait for it to finish or restart PortOS.' });
+ return safeEnd();
+ }
+
+ // Server-console visibility for the multi-GB torch install (start / stage
+ // milestones / outcome) — installFlux2Venv streams progress only to `send`.
+ const installLog = createInstallLogger({ installer: 'FLUX.2 venv', target: FLUX2_VENV_DEFAULT });
+ const emit = (ev) => { installLog.onEvent(ev); send(ev); };
+ installLog.start();
+
+ const { promise, kill } = installFlux2Venv(emit);
+ flux2InstallInFlight = promise;
+ promise
+ // installFlux2Venv resolves { ok:false } on some pip failures without
+ // emitting a terminal SSE event, so reconcile the outcome from the result
+ // (a no-op if `onEvent` already logged a complete/error frame).
+ .then((result) => {
+ if (result?.ok) installLog.success(result?.pythonPath ? `ready: ${result.pythonPath}` : undefined);
+ else installLog.failure(`failed at stage ${result?.stage || 'unknown'}`);
+ })
+ .catch((err) => emit({ type: 'error', message: err?.message || 'Unknown installer failure' }))
+ .finally(() => {
+ flux2InstallInFlight = null;
+ safeEnd();
+ });
+
+ // Cancel the install if the client navigates away mid-bootstrap. A torch
+ // install is a multi-GB download and would otherwise keep running invisibly.
+ req.on('close', () => { installLog.cancel(); kill(); safeEnd(); });
+}));
+
+// Used by the FLUX.2 model picker: surface a banner when the gated repo's
+// license hasn't been accepted (HF_TOKEN missing) and the runner is set up.
+// `venvInstalled` reflects functional health (binary AND packages import) —
+// a half-broken venv would otherwise hide the install banner forever.
+router.get('/flux2-status', asyncHandler(async (req, res) => {
+ const [token, healthy] = await Promise.all([getHfToken(), isFlux2VenvHealthy()]);
+ const venvPython = resolveFlux2Python();
+ // The 9B (bf16) and 4B variants ship as separately-gated repos with
+ // distinct HF license URLs. Use the active model's `licenseUrl` when the
+ // client supplies a `modelId`; fall back to the 4B URL for callers that
+ // pre-date the multi-variant registry.
+ const FLUX2_DEFAULT_LICENSE = 'https://huggingface.co/black-forest-labs/FLUX.2-klein-4B';
+ let licenseUrl = FLUX2_DEFAULT_LICENSE;
+ if (typeof req.query?.modelId === 'string' && req.query.modelId.length > 0) {
+ const model = getImageModels().find((m) => m.id === req.query.modelId);
+ if (isFlux2(model) && typeof model?.licenseUrl === 'string' && model.licenseUrl.length > 0) {
+ licenseUrl = model.licenseUrl;
+ }
+ }
+ res.json({
+ hfTokenPresent: !!token,
+ venvInstalled: healthy,
+ venvPath: venvPython,
+ expectedVenvPath: FLUX2_VENV_DEFAULT,
+ licenseUrl,
+ });
+}));
+
+// Generic HF-token presence check for legacy mflux runners that don't need
+// the FLUX.2 venv. Any model entry with `requiresHfToken: true` in
+// data/media-models.json drives the banner through this endpoint.
+router.get('/hf-token-status', asyncHandler(async (_req, res) => {
+ const { token, source } = await getHfTokenInfo();
+ res.json({ hfTokenPresent: !!token, source });
+}));
+
+// Save the HF token from the inline form on the Image Gen page. settings.json
+// is the canonical location (single-user app behind Tailscale — see CLAUDE.md).
+// Same endpoint serves FLUX.2 and legacy mflux gated models — the token is
+// global (HF_TOKEN env in spawn).
+const hfTokenSchema = z.object({
+ token: z.string().regex(HF_TOKEN_REGEX, 'Token must look like `hf_…`').max(200),
+});
+router.post('/hf-token', asyncHandler(async (req, res) => {
+ const { token } = validateRequest(hfTokenSchema, req.body || {});
+ await updateSettingsWith((settings) => ({
+ ...settings,
+ imageGen: { ...(settings.imageGen || {}), hfToken: token.trim() },
+ }));
+ res.json({ ok: true, hfTokenPresent: true, source: 'stored' });
+}));
+
+// Clear the stored HF token. Falls back to env / CLI tokens if present —
+// callers should re-fetch /setup/hf-token-status to see the post-clear state.
+router.delete('/hf-token', asyncHandler(async (_req, res) => {
+ await updateSettingsWith((settings) => {
+ const { hfToken: _drop, ...restImageGen } = settings.imageGen || {};
+ return { ...settings, imageGen: restImageGen };
+ });
+ const { token, source } = await getHfTokenInfo();
+ res.json({ ok: true, hfTokenPresent: !!token, source });
+}));
+
+const checkSchema = z.object({ pythonPath: z.string().min(1) });
+
+router.get('/check', asyncHandler(async (req, res) => {
+ const { pythonPath } = validateRequest(checkSchema, req.query);
+ if (!isAllowedPython(pythonPath)) {
+ throw new ServerError('pythonPath must be a python interpreter (basename python/python3/python3.NN)', { status: 400 });
+ }
+ res.json(await getSetupCheck(pythonPath));
+}));
+
+const venvSchema = z.object({
+ basePython: z.string().min(1).optional(),
+});
+
+router.post('/create-venv', asyncHandler(async (req, res) => {
+ const { basePython } = validateRequest(venvSchema, req.body || {});
+ if (basePython && !isAllowedPython(basePython)) {
+ throw new ServerError('basePython must be a python interpreter (basename python/python3/python3.NN)', { status: 400 });
+ }
+ const base = basePython || (await detectPython());
+ if (!base) {
+ throw new ServerError('No base Python 3 found to bootstrap a venv. Install Python 3.10+ first.', { status: 400 });
+ }
+ const target = join(PATHS.data, 'python', 'venv');
+ const venvPython = await createVenv(base, target);
+ // Bust the setup-check cache for both the base interpreter and the new
+ // venv python — the venv inherits the base's mtime-key but its packages
+ // differ, and a subsequent /setup/check would otherwise return the base's
+ // pre-venv snapshot.
+ invalidateSetupCheck(base);
+ invalidateSetupCheck(venvPython);
+ res.json({ pythonPath: venvPython, target });
+}));
+
+const installSchema = z.object({
+ pythonPath: z.string().min(1),
+ packages: z.array(z.string().min(1)).min(1).max(40),
+});
+
+// EventSource consumers re-run /setup/check on `complete` to refresh status.
+router.get('/install', (req, res) => {
+ const pythonPath = req.query.pythonPath;
+ const packages = String(req.query.packages || '').split(',').filter(Boolean);
+ const parsed = installSchema.safeParse({ pythonPath, packages });
+ if (!parsed.success) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ return res.end(JSON.stringify({ error: parsed.error.message }));
+ }
+ if (!isAllowedPython(parsed.data.pythonPath)) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ return res.end(JSON.stringify({ error: 'pythonPath must be a python interpreter' }));
+ }
+ const disallowed = parsed.data.packages.filter((p) => !REQUIRED_PIP_NAMES.has(p));
+ if (disallowed.length) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ return res.end(JSON.stringify({ error: `Packages not in allowlist: ${disallowed.join(', ')}` }));
+ }
+
+ // `send` and `safeEnd` from openSseStream no-op once the response has ended
+ // so a late pip-output line (or the promise.then below) doesn't trigger
+ // ERR_STREAM_WRITE_AFTER_END or double-end the response.
+ const { send, safeEnd } = openSseStream(res);
+ // Server-console visibility for the (multi-GB) local pip install — the SSE
+ // stream otherwise surfaces progress only in the browser.
+ const installLog = createInstallLogger({ installer: 'Image Gen packages', target: parsed.data.pythonPath });
+ const emit = (ev) => { installLog.onEvent(ev); send(ev); };
+ installLog.start();
+ const { promise, kill } = installPackages(parsed.data.pythonPath, parsed.data.packages, emit);
+ promise.then(() => {
+ // Drop the now-stale setup-check snapshot before the client re-runs the
+ // probe on `complete` — without this it would read the pre-install
+ // missing-packages list back from cache.
+ invalidateSetupCheck(parsed.data.pythonPath);
+ safeEnd();
+ });
+
+ // Client navigation away should kill pip — a torch upgrade can run for
+ // 10+ minutes and would otherwise keep going invisibly.
+ req.on('close', () => { installLog.cancel(); kill(); safeEnd(); });
+});
+
+export default router;
diff --git a/server/services/appListEnrichment.js b/server/services/appListEnrichment.js
new file mode 100644
index 0000000000..0822b05951
--- /dev/null
+++ b/server/services/appListEnrichment.js
@@ -0,0 +1,154 @@
+/**
+ * App-list PM2 status enrichment.
+ *
+ * Owns the orchestration that turns the raw `apps.json` records into the
+ * PM2-status-enriched list the `GET /api/apps` route responds with: one PM2
+ * read per unique `pm2Home`, absent-vs-empty (`unknown` vs `not_started`)
+ * status classification, ecosystem-config process backfill, and port
+ * derivation. The route just fetches the apps and responds — this module is
+ * the single home for the enrichment logic.
+ *
+ * The pure port/status derivation helpers (`deriveUiPort`, `deriveAppPorts`,
+ * `computeOverallStatus`) live here too and are re-exported from
+ * `routes/apps/shared.js` so the detail (`GET /:id`) and lifecycle routes keep
+ * a single shared implementation without importing a service from a route.
+ */
+
+import { usesPm2, parseEcosystemFromPath } from './streamingDetect.js';
+import { listProcessesStrict } from './pm2.js';
+import { hasDeployScript } from './appDeployer.js';
+import { checkScripts } from './xcodeScripts.js';
+import { pathExists } from '../lib/fileUtils.js';
+
+/**
+ * Derive uiPort from apiPort when app has dev UI but no dedicated prod UI port
+ * (prod UI is served by the API server in these cases).
+ */
+export function deriveUiPort(uiPort, apiPort, devUiPort) {
+ if (!uiPort && apiPort && devUiPort) return apiPort;
+ return uiPort;
+}
+
+/**
+ * Derive uiPort/apiPort/devUiPort from an app's process list when not
+ * explicitly set on the app record. Shared by the list and detail endpoints so
+ * the two never diverge. Returns the resolved trio (uiPort passed through
+ * deriveUiPort for the served-by-API case).
+ */
+export function deriveAppPorts(app, processes) {
+ let { uiPort, apiPort, devUiPort } = app;
+ const procs = processes || [];
+ if (!uiPort && procs.length) {
+ const uiProc = procs.find(p => p.ports?.ui);
+ if (uiProc) uiPort = uiProc.ports.ui;
+ }
+ if (!apiPort && procs.length) {
+ const apiProc = procs.find(p => p.ports?.api);
+ if (apiProc) apiPort = apiProc.ports.api;
+ }
+ if (!devUiPort && procs.length) {
+ const devUiProc = procs.find(p => p.ports?.devUi);
+ if (devUiProc) devUiPort = devUiProc.ports.devUi;
+ }
+ uiPort = deriveUiPort(uiPort, apiPort, devUiPort);
+ return { uiPort, apiPort, devUiPort };
+}
+
+/**
+ * Compute the overall status from a set of per-process PM2 statuses. A degraded
+ * (failed-read) home short-circuits to `unknown` rather than collapsing to a
+ * confident `not_started`. Shared by the list and detail endpoints.
+ */
+export function computeOverallStatus(statusValues, degraded) {
+ // Mirrors the original inline logic exactly: an empty status set (an app with
+ // no PM2 process names) satisfies the vacuous `every(...)` and resolves to
+ // `not_started`, NOT `unknown`.
+ if (degraded) return 'unknown';
+ if (statusValues.some(s => s.status === 'online')) return 'online';
+ if (statusValues.some(s => s.status === 'stopped')) return 'stopped';
+ if (statusValues.every(s => s.status === 'not_found')) return 'not_started';
+ return 'unknown';
+}
+
+/**
+ * Enrich a list of app records with live PM2 status, backfilled processes, and
+ * derived ports. Reads PM2 once per unique `pm2Home`.
+ *
+ * `listProcessesStrict` returns `null` on a failed read (vs `[]` for a
+ * successful read with no processes) — those homes are tracked so their apps
+ * report `unknown` (status unavailable) + `degraded: true` instead of
+ * `not_started` (confidently not running). See `getAppStatuses()` in
+ * `apps.js` for the same absent-vs-empty distinction.
+ *
+ * @param {Array<object>} apps - raw app records (e.g. from `getAllApps()`)
+ * @returns {Promise<Array<object>>} PM2-status-enriched app records
+ */
+export async function enrichAppsWithPm2Status(apps) {
+ // Group apps by their PM2_HOME (null = default) so each unique home is
+ // queried at most once.
+ const pm2HomeGroups = new Map();
+ for (const app of apps) {
+ const home = app.pm2Home || null;
+ if (!pm2HomeGroups.has(home)) pm2HomeGroups.set(home, []);
+ pm2HomeGroups.get(home).push(app);
+ }
+
+ const pm2Maps = new Map();
+ const failedHomes = new Set();
+ for (const pm2Home of pm2HomeGroups.keys()) {
+ const processes = await listProcessesStrict(pm2Home);
+ if (processes === null) {
+ failedHomes.add(pm2Home);
+ pm2Maps.set(pm2Home, new Map());
+ } else {
+ pm2Maps.set(pm2Home, new Map(processes.map(p => [p.name, p])));
+ }
+ }
+
+ return Promise.all(apps.map(async (app) => {
+ // Non-PM2 apps skip PM2 enrichment entirely.
+ if (!usesPm2(app.type)) {
+ return { ...app, pm2Status: {}, overallStatus: 'n/a', hasDeployScript: hasDeployScript(app), xcodeScripts: checkScripts(app) };
+ }
+
+ const pm2Home = app.pm2Home || null;
+ const pm2Map = pm2Maps.get(pm2Home) || new Map();
+ const homeFailed = failedHomes.has(pm2Home);
+
+ const statuses = {};
+ for (const processName of app.pm2ProcessNames || []) {
+ const pm2Proc = pm2Map.get(processName);
+ // A failed PM2 read leaves status genuinely unknown — don't claim
+ // `not_found` (which the UI reads as "registered but never launched").
+ statuses[processName] = pm2Proc
+ ?? { name: processName, status: homeFailed ? 'unknown' : 'not_found', pm2_env: null };
+ }
+
+ // A failed PM2 home short-circuits to `unknown` with a `degraded` flag
+ // rather than collapsing to `not_started`.
+ const overallStatus = computeOverallStatus(Object.values(statuses), homeFailed);
+
+ // Auto-populate processes from ecosystem config if not already set.
+ let processes = app.processes;
+ if ((!processes || processes.length === 0) && await pathExists(app.repoPath)) {
+ const parsed = await parseEcosystemFromPath(app.repoPath).catch(() => ({ processes: [] }));
+ processes = parsed.processes;
+ }
+
+ // Auto-derive uiPort/apiPort/devUiPort from processes when not explicitly set.
+ const { uiPort, apiPort, devUiPort } = deriveAppPorts(app, processes);
+
+ return {
+ ...app,
+ processes,
+ uiPort,
+ devUiPort,
+ apiPort,
+ pm2Status: statuses,
+ overallStatus,
+ degraded: homeFailed,
+ hasDeployScript: hasDeployScript(app),
+ xcodeScripts: checkScripts(app)
+ };
+ }));
+}
diff --git a/server/services/imageGen/setup.js b/server/services/imageGen/setup.js
new file mode 100644
index 0000000000..348d2a652b
--- /dev/null
+++ b/server/services/imageGen/setup.js
@@ -0,0 +1,113 @@
+/**
+ * Image Gen — local-mode setup orchestration.
+ *
+ * The non-HTTP logic behind the `/api/image-gen/setup/*` routes: the
+ * python-interpreter health-check cache and the pip-install allowlist. The
+ * route module (`routes/imageGenSetup.js`) validates input and wires SSE/HTTP;
+ * this module owns the caching + allowlist so those concerns live in the
+ * service layer rather than inline in the route.
+ */
+
+import { stat } from 'fs/promises';
+import {
+ REQUIRED_PACKAGES, detectArm64Python, HOST_ARCH, probePythonHealth, pipNameFor,
+} from '../../lib/pythonSetup.js';
+
+// /setup/check is called on every keystroke in the python-path input (debounced
+// to 400ms), on mount, AND on the refresh button — each call spawns a python
+// subprocess (~0.5-1s warm) plus the optional `detectArm64Python` walk. A
+// modest in-memory cache, keyed by (pythonPath, stat.mtimeMs) and bounded by
+// SETUP_CHECK_TTL_MS, collapses the typing-flow repeats to memo hits without
+// risking stale data — the key changes the moment the interpreter is swapped
+// (venv create, brew upgrade) and the install path explicitly busts on
+// completion.
+const SETUP_CHECK_TTL_MS = 30_000;
+const setupCheckCache = new Map();
+
+async function buildSetupCheck(pythonPath) {
+ const health = await probePythonHealth(pythonPath);
+ // The arch warning is specifically about mlx wheels (arm64-only) on Apple
+ // Silicon. A generic interpreterArch !== HOST_ARCH compare would false-
+ // positive on Windows (Python reports `AMD64`, Node reports `x86_64`) and
+ // on hypothetical arm64 Linux — where mlx isn't even in REQUIRED_PACKAGES.
+ const archMismatch = process.platform === 'darwin'
+ && HOST_ARCH === 'arm64'
+ && health.interpreterArch === 'x86_64';
+ const suggestedArm64Python = archMismatch ? await detectArm64Python() : null;
+ return {
+ pythonPath,
+ required: REQUIRED_PACKAGES,
+ hostArch: HOST_ARCH,
+ archMismatch,
+ suggestedArm64Python,
+ ...health,
+ };
+}
+
+/** Drop cached setup-check results for a python path (or all when omitted). */
+export function invalidateSetupCheck(pythonPath) {
+ if (!pythonPath) {
+ setupCheckCache.clear();
+ return;
+ }
+ const prefix = `${pythonPath}|`;
+ for (const key of setupCheckCache.keys()) {
+ if (key.startsWith(prefix)) setupCheckCache.delete(key);
+ }
+}
+
+/**
+ * Resolve the setup-check payload for a python interpreter, memoized by
+ * (path, mtime) for SETUP_CHECK_TTL_MS. Callers must have already validated
+ * that `pythonPath` is an allowed interpreter.
+ */
+export async function getSetupCheck(pythonPath) {
+ // mtime keys auto-bust when the interpreter binary itself changes (rare but
+ // surfaces brew upgrades / re-symlinks). A stat() failure (path not found)
+ // skips the cache rather than poisoning it with a `mtime=missing` entry.
+ const mtimeMs = await stat(pythonPath).then((s) => s.mtimeMs).catch(() => null);
+ const key = mtimeMs !== null ? `${pythonPath}|${mtimeMs}` : null;
+ if (key) {
+ const hit = setupCheckCache.get(key);
+ if (hit && hit.expiresAt > Date.now()) return hit.result;
+ }
+ const result = await buildSetupCheck(pythonPath);
+ if (key) {
+ // Sweep expired entries on every write so a long-running process doesn't
+ // accumulate stale (path, mtime) combos from intermediate keystrokes
+ // (each typed character of a path string lands a unique key here).
+ const now = Date.now();
+ for (const [k, v] of setupCheckCache) {
+ if (v.expiresAt <= now) setupCheckCache.delete(k);
+ }
+ setupCheckCache.set(key, { result, expiresAt: now + SETUP_CHECK_TTL_MS });
+ }
+ return result;
+}
+
+// Allowlist: only PortOS's own required pip names (or their pinned variants
+// like `transformers<5`) are installable. Without this, the endpoint would
+// happily pip-install arbitrary PyPI packages — the install runs as the
+// PortOS user and pip itself executes setup.py from the package, so an
+// arbitrary package install is effectively arbitrary code execution.
+// Build the pip-spec allowlist from REQUIRED_PACKAGES via pipNameFor — that
+// translates import names (`cv2`) to their actual pip specs
+// (`opencv-python`). Without this mapping, the allowlist would contain
+// import-only names that can't actually be installed but ALSO don't appear
+// here as their pip specs, so the legitimate install request would 400.
+// Worse: an import name like `cv2` isn't a real PyPI package but if a
+// typosquat existed under that name it'd be installable.
+export const REQUIRED_PIP_NAMES = new Set([
+ ...REQUIRED_PACKAGES.map(pipNameFor),
+ // Windows torch path also installs torch + diffusers, which are in
+ // REQUIRED_PACKAGES on Windows but not on macOS — keep them allowlisted
+ // unconditionally so a Windows install requested from a macOS server
+ // (unlikely but possible) doesn't 400 unhelpfully.
+ 'torch',
+ 'diffusers',
+ // Both the bare `transformers` and the macOS-pinned `transformers<5`
+ // variant should be installable; pipNameFor only emits the pinned
+ // variant on macOS, so list both unconditionally for safety.
+ 'transformers',
+ 'transformers<5',
+]);