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

33.9 KB
Raw Blame
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { posixPath } from './testHelper.js';

// 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,
  pathPython: null,
  // Directory names under uv python root, as readdirSync would return them.
  uvPythonDirs: null,
  // Controls the `from diffusers import Flux2KleinPipeline` probe independently
  // of execShouldFail (which also drives the unrelated arch probe).
  fluxImportShouldFail: false,
  fluxImportCalls: 0,
  missingPipeline: null,
  // `sys.version_info` answers per interpreter path, for the MIN_VENV_PYTHON
  // gate. Unlisted paths answer with `defaultVersion`.
  versionByPath: new Map(),
  defaultVersion: '3.12.4',
  // Exit codes for the pip/venv children installFlux2Venv spawns, keyed by a
  // substring of the joined argv ('pip install --upgrade pip' etc). Anything
  // unmatched exits 0.
  spawnExitByArgs: new Map(),
  // Every [bin, ...args] installFlux2Venv spawned, in order.
  spawnCalls: [],
  // Every [bin, '-m', 'venv', …] createVenv ran, in order.
  venvCalls: [],
};

// pythonSetup composes paths with path.join, which is backslashed on a Windows
// runner while every fixture below is written POSIX-style. One normalizer,
// shared by the fs and childProcess mocks.
const toPosix = (p) => String(p).split('\\').join('/');

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');
  // pythonSetup composes its candidate paths with path.join/dirname, so on a
  // Windows host they arrive backslash-separated while presentPaths is seeded
  // with the POSIX spellings the tests read. Normalize the probe, not the
  // fixtures — the module's own platform is pinned via mockState.platform.
  return {
    ...actual,
    existsSync: (p) => mockState.presentPaths.has(toPosix(p)),
    // uv's install root is enumerated rather than listed, so the candidate
    // builder readdirs it. `null` means "uv not installed" — the common case —
    // and must throw the way the real readdirSync does so the builder swallows
    // it instead of crashing module load.
    readdirSync: () => {
      if (!mockState.uvPythonDirs) throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' });
      return mockState.uvPythonDirs;
    },
  };
});

vi.mock('./childProcess.js', async () => {
  const actual = await vi.importActual('./childProcess.js');
  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 (args?.[0] === '-m' && probeArg === 'venv') {
      // Mimic `python -m venv`: record the invocation and make the resulting
      // interpreter exist, so createVenv's post-condition check passes.
      mockState.venvCalls.push([bin, ...args]);
      // presentPaths holds POSIX spellings; `join` gives the mock a
      // backslashed targetDir on a Windows runner, so normalize like the
      // existsSync mock does or the created interpreter never "exists".
      mockState.presentPaths.add(toPosix(`${args[args.length - 1]}/bin/python3`));
      resolve({ stdout: '', stderr: '' });
    } else if (probeArg.includes('sys.version_info')) {
      const key = toPosix(bin);
      const version = mockState.versionByPath.has(key)
        ? mockState.versionByPath.get(key)
        : mockState.defaultVersion;
      if (!version) reject(new Error('not an interpreter'));
      else resolve({ stdout: `${version}\n`, stderr: '' });
    } else if (probeArg.includes('platform.machine')) {
      const a = mockState.archByPath.get(bin) ?? mockState.arch;
      resolve({ stdout: `${a}\n`, stderr: '' });
    } else if (probeArg.includes('Flux2KleinPipeline')) {
      mockState.fluxImportCalls += 1;
      if (mockState.fluxImportShouldFail || (mockState.missingPipeline && args[2] === mockState.missingPipeline)) reject(new Error('ModuleNotFoundError'));
      else resolve({ stdout: '', stderr: '' });
    } else {
      resolve({ stdout: '', stderr: '' });
    }
  });
  const { EventEmitter } = await vi.importActual('node:events');
  // streamSpawn only needs stdout/stderr emitters plus a 'close' event.
  const fakeSpawn = (bin, args) => {
    mockState.spawnCalls.push([bin, ...args]);
    const proc = new EventEmitter();
    proc.stdout = new EventEmitter();
    proc.stderr = new EventEmitter();
    proc.kill = () => { proc.killed = true; };
    const joined = args.join(' ');
    const hit = [...mockState.spawnExitByArgs.entries()].find(([needle]) => joined.includes(needle));
    setImmediate(() => proc.emit('close', hit ? hit[1] : 0));
    return proc;
  };
  return { ...actual, execFile: fakeExecFile, spawn: fakeSpawn };
});

// The PATH fallbacks shell out for real; stub them so a test box's own Python
// can't decide the result. safeChildProcessEnv stays real (probePythonArch uses it).
vi.mock('./processEnv.js', async (importOriginal) => ({
  ...(await importOriginal()),
  whichFirst: async () => mockState.pathPython,
  whichFirstSync: () => mockState.pathPython,
}));

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;
  mockState.pathPython = null;
  mockState.uvPythonDirs = null;
  mockState.fluxImportShouldFail = false;
  mockState.fluxImportCalls = 0;
  mockState.missingPipeline = null;
  mockState.versionByPath = new Map();
  mockState.defaultVersion = '3.12.4';
  mockState.spawnExitByArgs = new Map();
  mockState.spawnCalls = [];
  mockState.venvCalls = [];
};

describe('REQUIRED_PACKAGES', () => {
  beforeEach(resetState);

  it('includes the diffusers CUDA stack on Linux', async () => {
    mockState.platform = 'linux';
    const { REQUIRED_PACKAGES } = await loadModule();
    expect(REQUIRED_PACKAGES).toEqual(expect.arrayContaining(['torch', 'diffusers']));
  });
});

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('isAllowedPython (#9015 — a caller-supplied path must not reach any file merely named python*)', () => {
  beforeEach(resetState);

  it('accepts a bare basename and a plausible absolute interpreter path', async () => {
    const { isAllowedPython } = await loadModule();
    expect(isAllowedPython('python3')).toBe(true);
    expect(isAllowedPython('python')).toBe(true);
    expect(isAllowedPython('/usr/bin/python3')).toBe(true);
    expect(isAllowedPython('/Users/test/.venv/bin/python3.12')).toBe(true);
  });

  it('rejects a UNC path even though its basename looks like an interpreter', async () => {
    const { isAllowedPython } = await loadModule();
    // Windows-style UNC share.
    expect(isAllowedPython('\\\\host\\share\\python.exe')).toBe(false);
    // The POSIX-typed twin of a UNC share.
    expect(isAllowedPython('//host/share/python3')).toBe(false);
  });

  it('rejects a relative path with directory components', async () => {
    const { isAllowedPython } = await loadModule();
    expect(isAllowedPython('./venv/bin/python3')).toBe(false);
    expect(isAllowedPython('subdir/python3')).toBe(false);
    expect(isAllowedPython('../../tmp/python3')).toBe(false);
  });

  it('still rejects a path whose basename is not a python interpreter', async () => {
    const { isAllowedPython } = await loadModule();
    expect(isAllowedPython('/usr/bin/bash')).toBe(false);
    expect(isAllowedPython('')).toBe(false);
    expect(isAllowedPython(null)).toBe(false);
  });

  it('accepts a Windows absolute interpreter path and still rejects UNC on win32', async () => {
    mockState.platform = 'win32';
    const { isAllowedPython } = await loadModule();
    expect(isAllowedPython('C:\\Users\\test\\venv\\Scripts\\python.exe')).toBe(true);
    expect(isAllowedPython('\\\\host\\share\\python.exe')).toBe(false);
  });
});

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('detectPythonSync', () => {
  beforeEach(resetState);

  it('returns the first present candidate without probing arch', async () => {
    mockState.presentPaths.add('/opt/anaconda3/bin/python3');
    mockState.presentPaths.add('/opt/homebrew/bin/python3');
    const { detectPythonSync } = await loadModule();
    expect(detectPythonSync()).toBe('/opt/anaconda3/bin/python3');
  });

  it('falls back to PATH when no candidate path exists — a scoop / chocolatey / custom-dir install still counts', async () => {
    mockState.platform = 'win32';
    mockState.pathPython = 'C:/tools/python311/python.exe';
    const { detectPythonSync } = await loadModule();
    expect(detectPythonSync()).toBe('C:/tools/python311/python.exe');
  });

  it('rejects the WindowsApps alias — it opens the Microsoft Store instead of building a venv', async () => {
    mockState.platform = 'win32';
    mockState.pathPython = 'C:\\Users\\example\\AppData\\Local\\Microsoft\\WindowsApps\\python.exe';
    const { detectPythonSync } = await loadModule();
    expect(detectPythonSync()).toBeNull();
  });

  it('returns null when there is no Python anywhere', async () => {
    const { detectPythonSync } = await loadModule();
    expect(detectPythonSync()).toBeNull();
  });
});

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');
  });
});

describe('hasMfluxTrain', () => {
  beforeEach(resetState);

  it('is false for a null/empty path', async () => {
    const { hasMfluxTrain } = await loadModule();
    expect(hasMfluxTrain(null)).toBe(false);
    expect(hasMfluxTrain('')).toBe(false);
  });

  it('is true when mflux-train sits beside the python', async () => {
    mockState.presentPaths.add('/opt/homebrew/bin/mflux-train');
    const { hasMfluxTrain } = await loadModule();
    expect(hasMfluxTrain('/opt/homebrew/bin/python3')).toBe(true);
  });

  it('is false when mflux-train is absent beside the python', async () => {
    const { hasMfluxTrain } = await loadModule();
    expect(hasMfluxTrain('/opt/homebrew/bin/python3')).toBe(false);
  });
});

describe('resolveMfluxPython', () => {
  beforeEach(resetState);
  // darwin homedir is /Users/test → dedicated venv python is
  // /Users/test/.portos/venv-mflux/bin/python3, mflux-train beside it.
  const VENV_PY = '/Users/test/.portos/venv-mflux/bin/python3';
  const VENV_TRAIN = '/Users/test/.portos/venv-mflux/bin/mflux-train';

  it('prefers the configured python when it ships mflux-train (existing --user layout)', async () => {
    mockState.presentPaths.add('/opt/homebrew/bin/mflux-train');
    mockState.presentPaths.add(VENV_TRAIN); // even when the venv also exists, configured wins
    const { resolveMfluxPython } = await loadModule();
    expect(posixPath(resolveMfluxPython('/opt/homebrew/bin/python3'))).toBe('/opt/homebrew/bin/python3');
  });

  it('falls back to the dedicated venv when the configured python lacks mflux-train', async () => {
    mockState.presentPaths.add(VENV_TRAIN);
    const { resolveMfluxPython } = await loadModule();
    expect(posixPath(resolveMfluxPython('/opt/homebrew/bin/python3'))).toBe(VENV_PY);
  });

  it('discovers the dedicated venv even when no python is configured', async () => {
    mockState.presentPaths.add(VENV_TRAIN);
    const { resolveMfluxPython } = await loadModule();
    expect(posixPath(resolveMfluxPython(null))).toBe(VENV_PY);
  });

  it('returns the configured path unchanged when neither ships mflux-train (honest "not installed")', async () => {
    const { resolveMfluxPython } = await loadModule();
    expect(posixPath(resolveMfluxPython('/opt/homebrew/bin/python3'))).toBe('/opt/homebrew/bin/python3');
  });

  it('returns null when nothing is configured and no venv exists', async () => {
    const { resolveMfluxPython } = await loadModule();
    expect(resolveMfluxPython(null)).toBeNull();
    expect(resolveMfluxPython()).toBeNull();
  });
});
describe('detectVenvBasePythonSync', () => {
  beforeEach(resetState);

  const WIN_UV = 'C:/Users/example/AppData/Roaming/uv/python';

  it('prefers a uv standalone build over conda — a conda-based venv cannot import torch', async () => {
    // Regression: on a box whose only listed Python was miniconda, every torch
    // venv the installer built died at `import torch` with
    // "WinError 1114 ... c10.dll initialization routine failed".
    mockState.platform = 'win32';
    mockState.homedir = 'C:/Users/example';
    mockState.uvPythonDirs = ['cpython-3.10-windows-x86_64-none'];
    mockState.presentPaths.add(`${WIN_UV}/cpython-3.10-windows-x86_64-none/python.exe`);
    mockState.presentPaths.add('C:/Users/example/miniconda3/python.exe');
    const { detectVenvBasePythonSync, detectPythonSync } = await loadModule();
    expect(posixPath(detectVenvBasePythonSync())).toBe(`${WIN_UV}/cpython-3.10-windows-x86_64-none/python.exe`);
    // ...and the pip-target picker is deliberately unchanged: uv Pythons are
    // PEP 668 externally-managed, so installPackages must not be sent there.
    expect(posixPath(detectPythonSync())).toBe('C:/Users/example/miniconda3/python.exe');
  });

  it('prefers the newest uv version, and 3.9 does not beat 3.10', async () => {
    mockState.platform = 'win32';
    mockState.homedir = 'C:/Users/example';
    mockState.uvPythonDirs = [
      'cpython-3.9.21-windows-x86_64-none',
      'cpython-3.13.12-windows-x86_64-none',
      'cpython-3.10.19-windows-x86_64-none',
    ];
    for (const d of mockState.uvPythonDirs) mockState.presentPaths.add(`${WIN_UV}/${d}/python.exe`);
    const { detectVenvBasePythonSync } = await loadModule();
    expect(posixPath(detectVenvBasePythonSync())).toContain('cpython-3.13.12');
  });

  it('ignores non-cpython entries under the uv root and falls through to python.org', async () => {
    mockState.platform = 'win32';
    mockState.homedir = 'C:/Users/example';
    mockState.uvPythonDirs = ['.temp', 'pypy-3.10-windows-x86_64-none'];
    mockState.presentPaths.add('C:/Users/example/AppData/Local/Programs/Python/Python312/python.exe');
    mockState.presentPaths.add('C:/Users/example/miniconda3/python.exe');
    const { detectVenvBasePythonSync } = await loadModule();
    expect(posixPath(detectVenvBasePythonSync()))
      .toBe('C:/Users/example/AppData/Local/Programs/Python/Python312/python.exe');
  });

  it('falls back to the pip-target answer when no standalone build exists — a conda venv beats no venv', async () => {
    mockState.platform = 'win32';
    mockState.homedir = 'C:/Users/example';
    mockState.uvPythonDirs = null; // uv not installed: readdir throws
    mockState.presentPaths.add('C:/Users/example/miniconda3/python.exe');
    const { detectVenvBasePythonSync } = await loadModule();
    expect(posixPath(detectVenvBasePythonSync())).toBe('C:/Users/example/miniconda3/python.exe');
  });

  it('finds uv under its Linux install root too', async () => {
    mockState.platform = 'linux';
    mockState.homedir = '/home/example';
    mockState.uvPythonDirs = ['cpython-3.12.8-linux-x86_64-gnu'];
    mockState.presentPaths.add('/home/example/.local/share/uv/python/cpython-3.12.8-linux-x86_64-gnu/bin/python3');
    mockState.presentPaths.add('/opt/miniconda3/bin/python3');
    const { detectVenvBasePythonSync } = await loadModule();
    expect(posixPath(detectVenvBasePythonSync()))
      .toBe('/home/example/.local/share/uv/python/cpython-3.12.8-linux-x86_64-gnu/bin/python3');
  });

  it('returns null when there is no Python at all', async () => {
    const { detectVenvBasePythonSync } = await loadModule();
    expect(detectVenvBasePythonSync()).toBeNull();
  });

  it('never picks PortOS\'s own image-gen venv as a venv-creation base when a system Python is also present (#5980)', async () => {
    // Regression: PYTHON_CANDIDATES ranks `data/python/venv` first because it's
    // the best PIP TARGET (non-externally-managed) — but building a *second*
    // venv from an already-provisioned venv is what broke on some Homebrew
    // point-release upgrades. An app-managed venv present alongside a system
    // Python must not win.
    mockState.presentPaths.add('/data/python/venv/bin/python3');
    mockState.presentPaths.add('/opt/homebrew/bin/python3');
    const { detectVenvBasePythonSync, detectPythonSync } = await loadModule();
    expect(posixPath(detectVenvBasePythonSync())).toBe('/opt/homebrew/bin/python3');
    // detectPythonSync (the pip-target picker) is unchanged: it still prefers
    // the app-managed venv for installing packages.
    expect(posixPath(detectPythonSync())).toBe('/data/python/venv/bin/python3');
  });

  it('excludes all three app-managed venvs, not just the image-gen one', async () => {
    mockState.presentPaths.add('/Users/test/.portos/venv/bin/python3');
    mockState.presentPaths.add('/Users/test/.pixie-forge/venv/bin/python3');
    mockState.presentPaths.add('/usr/bin/python3');
    const { detectVenvBasePythonSync } = await loadModule();
    expect(posixPath(detectVenvBasePythonSync())).toBe('/usr/bin/python3');
  });

  it('falls back to an app-managed venv only when nothing non-app-managed exists anywhere', async () => {
    mockState.presentPaths.add('/data/python/venv/bin/python3');
    const { detectVenvBasePythonSync } = await loadModule();
    expect(posixPath(detectVenvBasePythonSync())).toBe('/data/python/venv/bin/python3');
  });
});

describe('venvBaseCandidatesSync', () => {
  beforeEach(resetState);

  it('orders standalone builds first, excludes app-managed venvs, and lists every present fallback for retry', async () => {
    mockState.presentPaths.add('/data/python/venv/bin/python3');
    mockState.presentPaths.add('/opt/miniconda3/bin/python3');
    mockState.presentPaths.add('/opt/homebrew/bin/python3');
    const { venvBaseCandidatesSync } = await loadModule();
    expect(venvBaseCandidatesSync()).toEqual(['/opt/miniconda3/bin/python3', '/opt/homebrew/bin/python3']);
  });

  it('returns an empty list when only app-managed venvs exist', async () => {
    mockState.presentPaths.add('/data/python/venv/bin/python3');
    mockState.presentPaths.add('/Users/test/.portos/venv/bin/python3');
    const { venvBaseCandidatesSync } = await loadModule();
    expect(venvBaseCandidatesSync()).toEqual([]);
  });
});

describe('isFlux2VenvHealthy', () => {
  beforeEach(resetState);
  afterEach(() => vi.useRealTimers());

  it('re-probes after a short TTL instead of caching a failure forever', async () => {
    mockState.presentPaths.add('/Users/test/.portos/venv-flux2/bin/python3');
    mockState.fluxImportShouldFail = true;
    vi.useFakeTimers();
    const { isFlux2VenvHealthy } = await loadModule();

    await expect(isFlux2VenvHealthy()).resolves.toBe(false);
    expect(mockState.fluxImportCalls).toBe(1);

    // The package now imports fine (e.g. the user finished installing it by
    // hand), but the cached negative result must not re-probe immediately.
    mockState.fluxImportShouldFail = false;
    await expect(isFlux2VenvHealthy()).resolves.toBe(false);
    expect(mockState.fluxImportCalls).toBe(1);

    // Once the negative-result TTL elapses, the next call re-probes and picks
    // up the fixed state without requiring a server restart.
    await vi.advanceTimersByTimeAsync(60_001);
    await expect(isFlux2VenvHealthy()).resolves.toBe(true);
    expect(mockState.fluxImportCalls).toBe(2);
  });

  it('keeps selected-pipeline readiness separate and refreshes it after runtime repair', async () => {
    mockState.presentPaths.add('/Users/test/.portos/venv-flux2/bin/python3');
    mockState.missingPipeline = 'QwenImage21Pipeline';
    const { isFlux2VenvHealthy, invalidateFlux2Health } = await loadModule();
    await expect(isFlux2VenvHealthy()).resolves.toBe(true);
    await expect(isFlux2VenvHealthy('QwenImage21Pipeline')).resolves.toBe(false);
    await expect(isFlux2VenvHealthy()).resolves.toBe(true);
    mockState.missingPipeline = null;
    invalidateFlux2Health();
    await expect(isFlux2VenvHealthy('QwenImage21Pipeline')).resolves.toBe(true);
  });

  it('reports the install as unsatisfied when a verified pipeline class is missing', async () => {
    // The bug this pins: the installer's readiness GATE probed only the base
    // FLUX.2 pipeline, so a venv whose diffusers predates QwenImage21Pipeline
    // answered the Install button with "already installed — nothing to do"
    // while the per-model banner said the runtime was unavailable.
    mockState.presentPaths.add('/Users/test/.portos/venv-flux2/bin/python3');
    mockState.missingPipeline = 'QwenImage21Pipeline';
    const { isFlux2InstallSatisfied, isFlux2VenvHealthy } = await loadModule();
    await expect(isFlux2VenvHealthy()).resolves.toBe(true);
    await expect(isFlux2InstallSatisfied()).resolves.toBe(false);
  });

  it('also requires the selected model pipeline class the verify stage does not cover', async () => {
    mockState.presentPaths.add('/Users/test/.portos/venv-flux2/bin/python3');
    mockState.missingPipeline = 'ErnieImagePipeline';
    const { isFlux2InstallSatisfied } = await loadModule();
    await expect(isFlux2InstallSatisfied()).resolves.toBe(true);
    await expect(isFlux2InstallSatisfied('ErnieImagePipeline')).resolves.toBe(false);
  });

  it('caches a healthy result indefinitely', async () => {
    mockState.presentPaths.add('/Users/test/.portos/venv-flux2/bin/python3');
    vi.useFakeTimers();
    const { isFlux2VenvHealthy } = await loadModule();

    await expect(isFlux2VenvHealthy()).resolves.toBe(true);
    mockState.fluxImportShouldFail = true; // must not matter — already cached true
    await vi.advanceTimersByTimeAsync(10 * 60_000);
    await expect(isFlux2VenvHealthy()).resolves.toBe(true);
    expect(mockState.fluxImportCalls).toBe(1);
  });
});

describe('classifyVenvBases', () => {
  beforeEach(resetState);

  it('splits candidates on the MIN_VENV_PYTHON floor, keeping the ranked order', async () => {
    mockState.presentPaths.add('/opt/anaconda3/bin/python3');
    mockState.presentPaths.add('/opt/homebrew/bin/python3');
    mockState.presentPaths.add('/usr/bin/python3');
    mockState.versionByPath.set('/opt/anaconda3/bin/python3', '3.8.5');
    mockState.versionByPath.set('/opt/homebrew/bin/python3', '3.12.7');
    mockState.versionByPath.set('/usr/bin/python3', '3.9.6');

    const { classifyVenvBases } = await loadModule();
    const { supported, rejected } = await classifyVenvBases();

    expect(supported.map(posixPath)).toEqual(['/opt/homebrew/bin/python3']);
    expect(rejected.map(({ path, version }) => `${posixPath(path)} ${version}`))
      .toEqual(['/opt/anaconda3/bin/python3 3.8.5', '/usr/bin/python3 3.9.6']);
  });

  it('rejects an interpreter whose version probe fails — "can\'t tell" is not "new enough"', async () => {
    mockState.presentPaths.add('/opt/homebrew/bin/python3');
    mockState.versionByPath.set('/opt/homebrew/bin/python3', null);

    const { classifyVenvBases } = await loadModule();
    const { supported, rejected } = await classifyVenvBases();

    expect(supported).toEqual([]);
    expect(rejected).toEqual([{ path: '/opt/homebrew/bin/python3', version: 'unknown' }]);
  });
});

// A stock /opt/anaconda3 ships Python 3.8, and it outranks Homebrew in the
// candidate list (conda is not PEP 668 externally-managed). Building the FLUX.2
// venv from it downloads the whole multi-GB torch tree and only THEN dies
// building sdnq's wheel, because pip's build isolation resolves a setuptools
// too old to parse PEP 639's string `project.license`. The gate has to happen
// at detect time, on the base interpreter.
describe('installFlux2Venv base-interpreter floor', () => {
  beforeEach(resetState);

  const runInstall = async (mod) => {
    const events = [];
    const { promise } = mod.installFlux2Venv((ev) => events.push(ev));
    return { result: await promise, events };
  };

  it('skips a too-old base that outranks a supported one', async () => {
    mockState.presentPaths.add('/opt/anaconda3/bin/python3');
    mockState.presentPaths.add('/opt/homebrew/bin/python3');
    mockState.versionByPath.set('/opt/anaconda3/bin/python3', '3.8.5');
    mockState.versionByPath.set('/opt/homebrew/bin/python3', '3.12.7');

    const mod = await loadModule();
    const { result } = await runInstall(mod);

    expect(result.ok).toBe(true);
    expect(mockState.venvCalls.map(([bin]) => posixPath(bin))).toEqual(['/opt/homebrew/bin/python3']);
  });

  it('fails at detect naming the versions it found, instead of downloading torch first', async () => {
    mockState.presentPaths.add('/opt/anaconda3/bin/python3');
    mockState.versionByPath.set('/opt/anaconda3/bin/python3', '3.8.5');

    const mod = await loadModule();
    const { result, events } = await runInstall(mod);

    expect(result).toEqual({ ok: false, stage: 'detect' });
    expect(mockState.venvCalls).toEqual([]);
    expect(mockState.spawnCalls).toEqual([]);
    const error = events.find((ev) => ev.type === 'error');
    expect(error.message).toContain('/opt/anaconda3/bin/python3 (3.8.5)');
    expect(error.message).toContain('3.10+');
  });

  it('rebuilds a venv left behind by an earlier run against a too-old base', async () => {
    mockState.presentPaths.add('/opt/homebrew/bin/python3');
    mockState.presentPaths.add('/Users/test/.portos/venv-flux2/bin/python3');
    mockState.versionByPath.set('/opt/homebrew/bin/python3', '3.12.7');
    mockState.versionByPath.set('/Users/test/.portos/venv-flux2/bin/python3', '3.8.5');

    const mod = await loadModule();
    const { result } = await runInstall(mod);

    expect(result.ok).toBe(true);
    // Without --clear, `python -m venv` reuses the 3.8 interpreter in place and
    // every retry fails identically.
    expect(mockState.venvCalls[0]).toContain('--clear');
  });

  it('reuses a venv that already clears the floor', async () => {
    mockState.presentPaths.add('/opt/homebrew/bin/python3');
    mockState.presentPaths.add('/Users/test/.portos/venv-flux2/bin/python3');
    mockState.versionByPath.set('/opt/homebrew/bin/python3', '3.12.7');
    mockState.versionByPath.set('/Users/test/.portos/venv-flux2/bin/python3', '3.12.7');

    const mod = await loadModule();
    const { result } = await runInstall(mod);

    expect(result.ok).toBe(true);
    expect(mockState.venvCalls).toEqual([]);
  });
});

// The SSE client reads a stream that closes without a terminal frame as
// "Connection to installer lost. Restart PortOS or try again." — so a pip step
// that exits non-zero used to surface as a phantom transport error with the
// real cause buried in the scrollback.
describe('installFlux2Venv failure reporting', () => {
  beforeEach(resetState);

  const failingStage = async (needle) => {
    mockState.presentPaths.add('/opt/homebrew/bin/python3');
    mockState.spawnExitByArgs.set(needle, 1);
    const mod = await loadModule();
    const events = [];
    const { promise } = mod.installFlux2Venv((ev) => events.push(ev));
    return { result: await promise, events };
  };

  it('emits a terminal error frame when the pip install exits non-zero', async () => {
    const { result, events } = await failingStage('--progress-bar');

    expect(result).toEqual({ ok: false, stage: 'install' });
    const error = events.find((ev) => ev.type === 'error');
    expect(error.message).toContain('Installing the FLUX.2 packages failed');
    expect(error.message).toContain('exit code 1');
  });

  it('fails the install when refreshing same-version diffusers code fails', async () => {
    const { result, events } = await failingStage('--force-reinstall --no-deps');
    expect(result).toEqual({ ok: false, stage: 'install' });
    expect(events.find((ev) => ev.type === 'error').message).toContain('Refreshing the diffusers pipeline code failed');
  });

  it('emits a terminal error frame when the pip bootstrap exits non-zero', async () => {
    const { result, events } = await failingStage('--upgrade pip wheel setuptools');

    expect(result).toEqual({ ok: false, stage: 'upgrade-pip' });
    expect(events.find((ev) => ev.type === 'error').message)
      .toContain('Could not upgrade pip/wheel/setuptools');
  });
});