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

feat([setup-check-cache]): cache /api/image-gen/setup/check per (pythonPath, mtime) for 30 s

[._.]/ Adam Eivy2af65a85937f
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 71c56c5a0e..0944dbdcac 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -35,7 +35,7 @@ import {
} from '../lib/pythonSetup.js';
import { PATHS, ensureDir, resolveGalleryImage } from '../lib/fileUtils.js';
import { join } from 'node:path';
-import { readFile, writeFile } from 'fs/promises';
+import { readFile, writeFile, stat } from 'fs/promises';
import { STYLE_PRESETS } from '../lib/writersRoomStylePresets.js';
import { cleanImageBuffer } from '../lib/imageClean.js';
import { purgeImageRefFromAllUniverses } from '../services/universeCanon.js';
@@ -740,11 +740,18 @@ router.delete('/setup/hf-token', asyncHandler(async (_req, res) => {
const checkSchema = z.object({ pythonPath: z.string().min(1) });
-router.get('/setup/check', asyncHandler(async (req, res) => {
- const { pythonPath } = validateRequest(checkSchema, req.query);
- if (!isAllowedPython(pythonPath)) {
- return res.status(400).json({ error: 'pythonPath must be a python interpreter (basename python/python3/python3.NN)' });
- }
+// /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-
@@ -754,14 +761,46 @@ router.get('/setup/check', asyncHandler(async (req, res) => {
&& HOST_ARCH === 'arm64'
&& health.interpreterArch === 'x86_64';
const suggestedArm64Python = archMismatch ? await detectArm64Python() : null;
- res.json({
+ 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)) {
+ return res.status(400).json({ error: 'pythonPath must be a python interpreter (basename python/python3/python3.NN)' });
+ }
+ // 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) {
+ setupCheckCache.set(key, { result, expiresAt: Date.now() + SETUP_CHECK_TTL_MS });
+ }
+ res.json(result);
}));
const venvSchema = z.object({
@@ -779,6 +818,12 @@ router.post('/setup/create-venv', asyncHandler(async (req, res) => {
}
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 });
}));
@@ -847,7 +892,13 @@ router.get('/setup/install', (req, res) => {
const safeEnd = () => { if (!res.writableEnded) res.end(); };
const { promise, kill } = installPackages(parsed.data.pythonPath, parsed.data.packages, send);
- promise.then(safeEnd);
+ 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.
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index c3b2318c4f..b09f314b77 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -46,6 +46,33 @@ vi.mock('../services/mediaJobQueue/index.js', () => ({
listJobs: vi.fn(() => []),
}));
+vi.mock('../lib/pythonSetup.js', () => ({
+ REQUIRED_PACKAGES: ['mflux', 'mlx'],
+ HOST_ARCH: 'arm64',
+ isAllowedPython: vi.fn(() => true),
+ probePythonHealth: vi.fn(async () => ({
+ installed: ['mflux', 'mlx'], missing: [], missingPip: [],
+ externallyManaged: false, interpreterArch: 'arm64',
+ })),
+ detectPython: vi.fn(async () => '/usr/bin/python3'),
+ detectArm64Python: vi.fn(async () => null),
+ installPackages: vi.fn(() => ({ promise: Promise.resolve(), kill: vi.fn() })),
+ createVenv: vi.fn(async () => '/fake/venv/python'),
+ pipNameFor: (n) => n,
+ resolveFlux2Python: vi.fn(() => null),
+ FLUX2_VENV_DEFAULT: '/fake/flux2-venv',
+ installFlux2Venv: vi.fn(),
+ isFlux2VenvHealthy: vi.fn(async () => true),
+}));
+
+// Stat the python binary to key the cache. Override per-test for mtime
+// changes; default to a stable mtime so the cache HIT path works.
+const mockStat = vi.fn(async () => ({ mtimeMs: 1_700_000_000_000 }));
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, stat: (path) => mockStat(path) };
+});
+
import * as imageGen from '../services/imageGen/index.js';
import * as mediaJobQueue from '../services/mediaJobQueue/index.js';
import { getSettings } from '../services/settings.js';
@@ -549,4 +576,72 @@ describe('Image Gen Routes', () => {
expect(mediaJobQueue.cancelJob.mock.calls[0][0]).toBe('middle');
});
});
+
+ describe('GET /setup/check (cache behavior)', () => {
+ // Each test uses a unique pythonPath so the module-scope cache from one
+ // test doesn't bleed into the next (vi.clearAllMocks() resets call counts
+ // but not the cache Map).
+ let probePythonHealth, createVenv;
+ beforeEach(async () => {
+ const mod = await import('../lib/pythonSetup.js');
+ probePythonHealth = mod.probePythonHealth;
+ createVenv = mod.createVenv;
+ mockStat.mockReset();
+ mockStat.mockResolvedValue({ mtimeMs: 1_700_000_000_000 });
+ });
+
+ it('returns the same payload on a cache hit and only spawns python once', async () => {
+ const p = '/usr/bin/python3-cache-hit-test';
+ const r1 = await request(app).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(p)}`);
+ const r2 = await request(app).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(p)}`);
+ expect(r1.status).toBe(200);
+ expect(r2.status).toBe(200);
+ expect(r1.body).toEqual(r2.body);
+ expect(probePythonHealth).toHaveBeenCalledTimes(1);
+ });
+
+ it('busts the cache when the python interpreter mtime changes', async () => {
+ const p = '/usr/bin/python3-mtime-test';
+ mockStat.mockResolvedValueOnce({ mtimeMs: 1_700_000_000_000 });
+ await request(app).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(p)}`);
+ mockStat.mockResolvedValueOnce({ mtimeMs: 1_700_000_000_001 });
+ await request(app).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(p)}`);
+ expect(probePythonHealth).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not cache when stat fails (broken / missing path)', async () => {
+ const p = '/usr/bin/python3-stat-fail-test';
+ mockStat.mockRejectedValue(new Error('ENOENT'));
+ await request(app).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(p)}`);
+ await request(app).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(p)}`);
+ expect(probePythonHealth).toHaveBeenCalledTimes(2);
+ });
+
+ it('cache for distinct pythonPaths are independent', async () => {
+ const p1 = '/usr/bin/python3-distinct-a';
+ const p2 = '/opt/homebrew/bin/python3-distinct-b';
+ await request(app).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(p1)}`);
+ await request(app).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(p2)}`);
+ // Two distinct paths → two probe spawns; both then cached for repeats.
+ expect(probePythonHealth).toHaveBeenCalledTimes(2);
+ await request(app).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(p1)}`);
+ expect(probePythonHealth).toHaveBeenCalledTimes(2);
+ });
+
+ it('POST /setup/create-venv invalidates the base AND new venv cache entries', async () => {
+ const base = '/usr/bin/python3-venv-test';
+ // Warm cache for the base python.
+ await request(app).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(base)}`);
+ expect(probePythonHealth).toHaveBeenCalledTimes(1);
+
+ // Create venv (mocked to return /fake/venv/python).
+ const created = await request(app).post('/api/image-gen/setup/create-venv').send({ basePython: base });
+ expect(created.status).toBe(200);
+ expect(createVenv).toHaveBeenCalled();
+
+ // Next probe of the base python re-spawns (cache busted).
+ await request(app).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(base)}`);
+ expect(probePythonHealth).toHaveBeenCalledTimes(2);
+ });
+ });
});