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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
test([pythonsetup-arch-tests]): cover arch-aware detectPython + /setup/check arch fields
[._.]/ Adam Eivy97043ef6a862
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex af17e81885..2e2cbd55d0 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Changed+- **[pythonsetup-arch-tests] Test coverage for the arch-aware Local Python detector.** Internal: locks in the macOS arm64-vs-x86_64 preference behavior and the `/setup/check` arch fields with mocked-platform unit tests, so future edits to interpreter detection can't silently regress mlx wheel loading. No user-visible behavior change.- **[mediajobqueue-resolve-live-params] Media job dispatch internals.** Internal refactor: the live-settings re-resolution step that picks the current Python interpreter before each video / local-image render moves into its own helper, giving future live-resolved fields a single seam. No user-visible behavior change.- **[patch-settings-slice-helper] Nested settings edits no longer risk clobbering sibling fields.** Saving a Python path from Video Gen, or an image-gen config from a pipeline / Writers Room stage, used to round-trip the entire current settings object — leaving unrelated top-level keys exposed to drift if the read raced a concurrent write elsewhere. These edits now scope themselves to the slice being changed.- **[client-use-previous-hook] Shared `usePrevious` hook.** Internal refactor: collapses two ad-hoc previous-render comparisons into one shared hook. No user-visible behavior change.diff --git a/PLAN.md b/PLAN.mdindex b9593a3401..fc052c0006 100644--- a/PLAN.md+++ b/PLAN.md@@ -6,7 +6,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel_Batch-cleared 2026-05-25: 23 Next Up items shipped together via parallel sub-agents (env-file helper, formatBytes migration, lazy voice UI text, voice long-term-memory routing, voice tool expansion + `ui_describe_visually`, three phosphene generate_ltx2.py hardenings, the peer-sync snapshot-coverage P1 refactor + ephemeralize-then-delete, per-record tombstone-ack clamp, MediaLightbox→MediaImage, global vitest peer mock, videoHistory sync category, reverse-sub UI broadcast, palette Health disambiguation, insertXxxWithId resurrection side-effects, importer tombstone detection, TUI finish-rejection note, mortalLoom errno widen, VideoGen stale-model toast, Universes sidebar grandchildren). See `git log` + `.changelog/NEXT.md`._-- [ ] [pythonsetup-arch-tests] **Test coverage for arch-aware `detectPython()` + `/setup/check` arch fields.** Added 2026-05-28 with the VideoGen inline Local Python setup fix. New helpers (`probePythonArch`, `isArchMismatch`, `detectArm64Python`, `HOST_ARCH`) and the new `/api/image-gen/setup/check` response fields (`interpreterArch`, `hostArch`, `archMismatch`, `suggestedArm64Python`) have no test coverage — the existing `server/routes/imageGen.test.js` skips all `/setup/*` routes entirely. Worth a `pythonSetup.test.js` that mocks `node:os` + `node:child_process` to verify: (1) on `darwin/arm64`, `detectPython` prefers arm64 candidates over x86_64; (2) `/setup/check` includes the new arch fields and only sets `archMismatch: true` when the host is arm64; (3) `suggestedArm64Python` is null when no viable arm64 candidate exists. Deferred from the fix because the `/setup/*` route family has zero existing test harness and adding one is its own piece of work.- [ ] [mediacard-use-mediaimage-for-syncing-assets] **`MediaCard.jsx` grid thumbnails still use a raw `<img src={previewUrl}>`.** Same peer-sync placeholder/live-swap gap that `[peer-sync-medialightbox-use-mediaimage-for-syncing-assets]` fixed for the lightbox — `client/src/components/media/MediaCard.jsx` (~line 42) doesn't get the "Syncing" placeholder or the `peerSync:asset-arrived` atomic swap. Swap the raw `<img>` for `MediaImage`. Surfaced by that item's cross-check during the batch-clear (2026-05-25); was outside its stated scope.- [ ] [chrome-canary-followups] **Hardening for the custom-Chrome-binary feature (xhigh code-review 2026-05-25).** _DONE in the v2.10.0 release review: (b) both `spawn()` calls now have `.on('error', …)` listeners; (d) `browser/server.js#loadConfig` now try/catches the `JSON.parse`; (e) `setup-browser.js#loadConfig` now warns + returns `null` and `applyCanaryToConfig` skips the save when the existing config is unreadable; (f) top-level `runCanarySetup()` is now `.catch()`-wrapped. (c) is tracked separately in `[setup-browser-canary-headless]`. Remaining: (a), (g)–(o)._ **High-severity:** (a) On macOS headed mode (the default), `browser/server.js:208` uses `macAppBundle` only and silently ignores `chromePath` — a UI user who fills in `chromePath` for Canary/Chromium/Brave but leaves `macAppBundle` empty gets stock Chrome and the log misreports the binary; couple the two fields in the UI (or auto-derive `macAppBundle` from `chromePath` when the latter is inside a `.app`). (b) Neither `spawn(chromePath, …)` (line 216) nor `spawn('/usr/bin/open', …)` (line 208) has an `.on('error', …)` listener — a typo in `chromePath` emits 'error' with no listener → `uncaughtException` → portos-browser PM2 child crashes and restart-loops. (c) `scripts/setup-browser.js#applyCanaryToConfig` writes `chromePath` + `macAppBundle` but doesn't flip `headless: false`; combined with the seed default of `headless: true` (`data.reference/browser-config.json`), a fresh install accepting Canary runs Canary invisibly. (d) `browser/server.js#loadConfig` does bare `JSON.parse(raw)` with no try/catch — combined with setup-browser's non-atomic `writeFileSync` and the `cachedConfig` race, a partial-file write crashes the supervisor on next start (PM2 restart-loop forever). **Medium-severity:** (e) `setup-browser.js#loadConfig` silently catches all JSON parse errors and returns `{}`, then `applyCanaryToConfig` saves `{chromePath, macAppBundle}` only — wiping every other user-customized key. (f) Top-level `await runCanarySetup()` has no try/catch — any EACCES on data/browser-config.json aborts `npm run setup` / `update.sh` at what was previously a no-op step. (g) Idempotency guard only checks `chromePath`: users who decline get re-prompted on every update, and users who set only `macAppBundle` keep getting re-prompted. (h) `PORTOS_USE_CANARY` only matches literal `'0'`/`'false'` (opt-out) or `'1'`/`'true'` (opt-in) — `'no'`/`'off'`/`'yes'`/`'on'`/`'True'` fall through both branches. (i) `spawnSync(install.cmd, …, { stdio: 'inherit' })` for brew/winget can hang on a sudo password prompt under non-TTY + `PORTOS_USE_CANARY=1` (update.sh stalls). (j) `cachedConfig` in `browserService.js` is stale relative to setup-browser's direct write — GET /api/browser/config returns pre-update values until process restart. (k) `saveConfig` uses bare `writeFileSync` — switch to the canonical `atomicWrite` pattern (`server/lib/fileUtils.js`). **Low-severity:** (l) `spawnSync` failure-status check `result.status !== 0` treats `status: null` (spawn-failure / signal kill) identically to a non-zero exit and never logs `result.error` — masks ENOENT/EPERM/SIGKILL. (m) `optionalPath` Zod schema accepts any string up to 1024 chars; no `.app`/`.exe` sanity check — user pastes the bundle into `chromePath` → spawn() EISDIR. (n) `launchBrowser`'s reuse-existing-Chrome early-return (line 167) fires BEFORE `headlessMode = config.headless === true` (line 170), leaving the module-level default `false` after a PM2 restart that reuses Chrome — /health reports wrong mode (pre-existing, but in a function touched by this change). (o) `detectCanary` on macOS only checks `/Applications/...`; misses per-user `~/Applications/Google Chrome Canary.app` installs (corporate Macs, `HOMEBREW_CASK_OPTS=--appdir=$HOME/Applications`).- [ ] [strip-malloc-env-ffmpeg-children] **Extend `stripDebugMallocEnv` coverage to ffmpeg child spawns if Pinokio users still see the warning.** The Malloc-strip PR (`[ref-watch-phosphene-strip-malloc-subprocess-env]`) routed every direct Node→Python spawn through `stripDebugMallocEnv`, but ffmpeg children (`server/lib/ffmpeg.js:81`, the ffmpeg/ffprobe calls in `server/services/mediaService.js`, `server/services/videoTimeline/local.js`, and the post-render thumbnail/optimize/upscale paths in `server/services/videoGen/local.js`) still inherit `process.env`. ffmpeg on macOS links libSystem (which includes libmalloc) so it can in principle emit the same `MallocStackLogging: can't turn off…` line — unverified whether it actually does. Trigger: if Pinokio-launched installs still report stderr noise after the Python-spawn fix lands, wrap each ffmpeg spawn `env` the same way. Surfaced by reuse-review subagent during the original PR (2026-05-29).diff --git a/server/lib/pythonSetup.test.js b/server/lib/pythonSetup.test.jsnew file mode 100644index 0000000000..0aba3e7538--- /dev/null+++ b/server/lib/pythonSetup.test.js@@ -0,0 +1,202 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mutable state read by the hoisted vi.mock factories below. Each test mutates+// it and then `vi.resetModules() + dynamic import` re-evaluates pythonSetup.js+// with the new platform/arch — `HOST_ARCH`, `IS_DARWIN`, and `PYTHON_CANDIDATES`+// are all computed at module-load time, so the only way to exercise both+// arm64 and x86_64 host paths is a fresh module per scenario.+const mockState = {+ arch: 'arm64',+ platform: 'darwin',+ homedir: '/Users/test',+ presentPaths: new Set(),+ archByPath: new Map(),+ execShouldFail: false,+};++vi.mock('node:os', async () => {+ const actual = await vi.importActual('node:os');+ return {+ ...actual,+ arch: () => mockState.arch,+ platform: () => mockState.platform,+ homedir: () => mockState.homedir,+ };+});++vi.mock('node:fs', async () => {+ const actual = await vi.importActual('node:fs');+ return { ...actual, existsSync: (p) => mockState.presentPaths.has(p) };+});++vi.mock('node:child_process', async () => {+ const actual = await vi.importActual('node:child_process');+ const util = await vi.importActual('node:util');+ // `promisify(execFile)` uses execFile's util.promisify.custom symbol so the+ // resolved value is `{ stdout, stderr }` (not a bare string). Honor that on+ // the mock or `probePythonArch`'s `.stdout` read returns undefined.+ const fakeExecFile = () => {};+ fakeExecFile[util.promisify.custom] = (bin, args) => new Promise((resolve, reject) => {+ if (mockState.execShouldFail) {+ reject(new Error('spawn failed'));+ return;+ }+ const probeArg = args?.[1] || '';+ if (probeArg.includes('platform.machine')) {+ const a = mockState.archByPath.get(bin) ?? mockState.arch;+ resolve({ stdout: `${a}\n`, stderr: '' });+ } else {+ resolve({ stdout: '', stderr: '' });+ }+ });+ return { ...actual, execFile: fakeExecFile };+});++vi.mock('./fileUtils.js', () => ({ PATHS: { data: '/data' } }));++const loadModule = async () => {+ vi.resetModules();+ return await import('./pythonSetup.js');+};++const resetState = () => {+ mockState.arch = 'arm64';+ mockState.platform = 'darwin';+ mockState.homedir = '/Users/test';+ mockState.presentPaths = new Set();+ mockState.archByPath = new Map();+ mockState.execShouldFail = false;+};++describe('HOST_ARCH', () => {+ beforeEach(resetState);++ it('reports arm64 on Apple Silicon Node', async () => {+ mockState.arch = 'arm64';+ const { HOST_ARCH } = await loadModule();+ expect(HOST_ARCH).toBe('arm64');+ });++ it('normalizes os.arch x64 → x86_64 so the Python convention matches', async () => {+ mockState.arch = 'x64';+ const { HOST_ARCH } = await loadModule();+ expect(HOST_ARCH).toBe('x86_64');+ });+});++describe('probePythonArch', () => {+ beforeEach(resetState);++ it('returns the trimmed platform.machine() output', async () => {+ mockState.archByPath.set('/x/python3', 'arm64');+ const { probePythonArch } = await loadModule();+ await expect(probePythonArch('/x/python3')).resolves.toBe('arm64');+ });++ it('returns null when the subprocess errors', async () => {+ mockState.execShouldFail = true;+ const { probePythonArch } = await loadModule();+ await expect(probePythonArch('/missing/python3')).resolves.toBeNull();+ });+});++describe('isArchMismatch', () => {+ beforeEach(resetState);++ it('returns false on non-darwin (mlx wheels are arm64-only on macOS; other OSes are out of scope)', async () => {+ mockState.platform = 'linux';+ mockState.archByPath.set('/x/python3', 'x86_64');+ const { isArchMismatch } = await loadModule();+ await expect(isArchMismatch('/x/python3')).resolves.toBe(false);+ });++ it('returns false when interpreter arch matches HOST_ARCH on darwin', async () => {+ mockState.archByPath.set('/x/python3', 'arm64');+ const { isArchMismatch } = await loadModule();+ await expect(isArchMismatch('/x/python3')).resolves.toBe(false);+ });++ it('returns true when interpreter arch differs from HOST_ARCH on darwin', async () => {+ mockState.archByPath.set('/x/python3', 'x86_64');+ const { isArchMismatch } = await loadModule();+ await expect(isArchMismatch('/x/python3')).resolves.toBe(true);+ });++ it('returns false when the probe fails (no interpreter to compare)', async () => {+ mockState.execShouldFail = true;+ const { isArchMismatch } = await loadModule();+ await expect(isArchMismatch('/x/python3')).resolves.toBe(false);+ });+});++describe('detectPython on darwin/arm64', () => {+ beforeEach(resetState);++ it('prefers an arm64 candidate over an earlier-listed x86_64 candidate', async () => {+ // /opt/anaconda3 (index 4 in PYTHON_CANDIDATES) is listed before+ // /opt/homebrew (index 9). The arm64-preference branch must override+ // first-present-wins so mlx wheels load correctly.+ mockState.presentPaths.add('/opt/anaconda3/bin/python3');+ mockState.presentPaths.add('/opt/homebrew/bin/python3');+ mockState.archByPath.set('/opt/anaconda3/bin/python3', 'x86_64');+ mockState.archByPath.set('/opt/homebrew/bin/python3', 'arm64');+ const { detectPython } = await loadModule();+ await expect(detectPython()).resolves.toBe('/opt/homebrew/bin/python3');+ });++ it('returns the sole present candidate without paying the arch-probe cost', async () => {+ // The `present.length > 1` guard skips the parallel probe when there is+ // nothing to choose between.+ mockState.presentPaths.add('/opt/anaconda3/bin/python3');+ mockState.archByPath.set('/opt/anaconda3/bin/python3', 'x86_64');+ const { detectPython } = await loadModule();+ await expect(detectPython()).resolves.toBe('/opt/anaconda3/bin/python3');+ });++ it('falls back to the first present candidate when no candidate is arm64', async () => {+ mockState.presentPaths.add('/opt/anaconda3/bin/python3');+ mockState.presentPaths.add('/usr/local/bin/python3');+ mockState.archByPath.set('/opt/anaconda3/bin/python3', 'x86_64');+ mockState.archByPath.set('/usr/local/bin/python3', 'x86_64');+ const { detectPython } = await loadModule();+ await expect(detectPython()).resolves.toBe('/opt/anaconda3/bin/python3');+ });+});++describe('detectArm64Python', () => {+ beforeEach(resetState);++ it('returns null on non-darwin', async () => {+ mockState.platform = 'linux';+ mockState.presentPaths.add('/usr/bin/python3');+ mockState.archByPath.set('/usr/bin/python3', 'arm64');+ const { detectArm64Python } = await loadModule();+ await expect(detectArm64Python()).resolves.toBeNull();+ });++ it('returns null on Intel macs (HOST_ARCH !== arm64)', async () => {+ mockState.arch = 'x64';+ mockState.presentPaths.add('/usr/local/bin/python3');+ mockState.archByPath.set('/usr/local/bin/python3', 'x86_64');+ const { detectArm64Python } = await loadModule();+ await expect(detectArm64Python()).resolves.toBeNull();+ });++ it('returns null when no present candidate reports arm64', async () => {+ mockState.presentPaths.add('/opt/anaconda3/bin/python3');+ mockState.archByPath.set('/opt/anaconda3/bin/python3', 'x86_64');+ const { detectArm64Python } = await loadModule();+ await expect(detectArm64Python()).resolves.toBeNull();+ });++ it('returns the first arm64 candidate by PYTHON_CANDIDATES order', async () => {+ mockState.presentPaths.add('/opt/anaconda3/bin/python3');+ mockState.presentPaths.add('/opt/homebrew/bin/python3');+ mockState.presentPaths.add('/usr/local/bin/python3');+ mockState.archByPath.set('/opt/anaconda3/bin/python3', 'x86_64');+ mockState.archByPath.set('/opt/homebrew/bin/python3', 'arm64');+ mockState.archByPath.set('/usr/local/bin/python3', 'arm64');+ const { detectArm64Python } = await loadModule();+ await expect(detectArm64Python()).resolves.toBe('/opt/homebrew/bin/python3');+ });+});diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex 28b93c4635..9ac6e8b480 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -1,4 +1,4 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import express from 'express';import { request } from '../lib/testHelper.js';import imageGenRoutes from './imageGen.js';@@ -681,4 +681,71 @@ describe('Image Gen Routes', () => {}});});++ describe('GET /setup/check (arch fields)', () => {+ // The route's archMismatch logic gates on `process.platform === 'darwin'` —+ // override it so the assertions run identically on Linux CI and a dev Mac.+ const originalPlatform = process.platform;+ let probePythonHealth, detectArm64Python;++ beforeEach(async () => {+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });+ const mod = await import('../lib/pythonSetup.js');+ probePythonHealth = mod.probePythonHealth;+ detectArm64Python = mod.detectArm64Python;+ mockStat.mockReset();+ mockStat.mockResolvedValue({ mtimeMs: 1_700_000_000_000 });+ });++ afterEach(() => {+ Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });+ });++ it('exposes hostArch + archMismatch + suggestedArm64Python on matched arch', async () => {+ const r = await request(app).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent('/arch-fields-match')}`);+ expect(r.status).toBe(200);+ expect(r.body).toMatchObject({+ hostArch: 'arm64',+ archMismatch: false,+ suggestedArm64Python: null,+ interpreterArch: 'arm64',+ });+ });++ it('flips archMismatch true and includes the suggested arm64 python on an x86_64 interpreter', async () => {+ probePythonHealth.mockResolvedValueOnce({+ installed: [], missing: [], missingPip: [],+ externallyManaged: false, interpreterArch: 'x86_64',+ });+ detectArm64Python.mockResolvedValueOnce('/opt/homebrew/bin/python3');+ const r = await request(app).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent('/arch-fields-x86')}`);+ expect(r.status).toBe(200);+ expect(r.body.archMismatch).toBe(true);+ expect(r.body.suggestedArm64Python).toBe('/opt/homebrew/bin/python3');+ });++ it('returns suggestedArm64Python null when no arm64 interpreter is available to suggest', async () => {+ probePythonHealth.mockResolvedValueOnce({+ installed: [], missing: [], missingPip: [],+ externallyManaged: false, interpreterArch: 'x86_64',+ });+ detectArm64Python.mockResolvedValueOnce(null);+ const r = await request(app).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent('/arch-fields-no-arm64')}`);+ expect(r.status).toBe(200);+ expect(r.body.archMismatch).toBe(true);+ expect(r.body.suggestedArm64Python).toBeNull();+ });++ it('does not flag archMismatch on non-darwin even when interpreter arch differs', async () => {+ Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });+ probePythonHealth.mockResolvedValueOnce({+ installed: [], missing: [], missingPip: [],+ externallyManaged: false, interpreterArch: 'x86_64',+ });+ const r = await request(app).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent('/arch-fields-linux')}`);+ expect(r.status).toBe(200);+ expect(r.body.archMismatch).toBe(false);+ expect(r.body.suggestedArm64Python).toBeNull();+ });+ });});