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

fix: make abuse guard setup diagnosable and prefer uv repairs

Adam Eivyf6e9a1782f63
diff --git a/client/src/components/models/ModelAbuseGuardPanel.jsx b/client/src/components/models/ModelAbuseGuardPanel.jsx
index 07195e8e66..fef76eecf8 100644
--- a/client/src/components/models/ModelAbuseGuardPanel.jsx
+++ b/client/src/components/models/ModelAbuseGuardPanel.jsx
@@ -35,6 +35,7 @@ export default function ModelAbuseGuardPanel() {
const [statusError, setStatusError] = useState(false);
const [installing, setInstalling] = useState(false);
const [progressMsg, setProgressMsg] = useState('');
+ const [installError, setInstallError] = useState('');
const [installingStage, setInstallingStage] = useState(null);
const progressTimer = useRef(null);
const { present: tokenPresent, source: tokenSource, refresh: refreshToken } = useHfTokenStatus();
@@ -64,7 +65,7 @@ export default function ModelAbuseGuardPanel() {
}
if (data?.event === 'error') {
setInstalling(false);
- progressTimer.current = setTimeout(() => setProgressMsg(''), 5000);
+ setInstallError(data.message || 'Installation failed. Refresh status for diagnostics.');
loadGuardStatus();
}
};
@@ -76,14 +77,16 @@ export default function ModelAbuseGuardPanel() {
}, [loadGuardStatus]);
const installGuard = () => {
+ setInstallError('');
+ setInstallingStage(null);
setInstalling(true);
setProgressMsg('Installing the dedicated guard…');
- return installModelAbuseGuard()
+ return installModelAbuseGuard({ silent: true })
.then((result) => {
if (result?.ready === true) toast.success('Model-abuse guard installed and ready');
return loadGuardStatus();
})
- .catch(() => loadGuardStatus())
+ .catch((error) => { setInstallError(error.message || 'Installation failed.'); return loadGuardStatus(); })
.finally(() => {
setInstalling(false);
setInstallingStage(null);
@@ -240,6 +243,14 @@ export default function ModelAbuseGuardPanel() {
<span className="text-[11px] text-gray-500">{progressMsg}</span>
)}
</div>
+ {(installError || guardStatus?.lastInstallFailure) && (
+ <div role="alert" className="text-xs text-port-warning space-y-1 break-words">
+ {installError && <p>{installError}</p>}
+ {guardStatus?.lastInstallFailure && <p>{guardStatus.lastInstallFailure.stage}: {guardStatus.lastInstallFailure.code}{Number.isInteger(guardStatus.lastInstallFailure.exitCode) ? ` (exit ${guardStatus.lastInstallFailure.exitCode})` : ''}. {guardStatus.lastInstallFailure.message} {guardStatus.lastInstallFailure.action}</p>}
+ </div>
+ )}
+ {guardStatus?.runtimeIssue && <p className="text-xs text-port-warning">{guardStatus.runtimeIssue.message} {guardStatus.runtimeIssue.action}</p>}
+ {guardStatus?.expectedPackages && <details className="text-xs text-gray-400 break-words"><summary>Expected classifier packages</summary><p>{guardStatus.expectedPackages.join(', ')}</p></details>}
{incomplete && <p role="status" className="text-xs text-port-warning">A partial or failed installation blocks screening, including sources with an optional classifier. Repair the setup before retrying those tasks.</p>}
<p className="text-xs text-gray-400">Install downloads Python packages and model weights. Accept the model terms and add a read token first.</p>
</div>
diff --git a/client/src/components/models/ModelAbuseGuardPanel.test.jsx b/client/src/components/models/ModelAbuseGuardPanel.test.jsx
index 6d431b40c0..033f332e06 100644
--- a/client/src/components/models/ModelAbuseGuardPanel.test.jsx
+++ b/client/src/components/models/ModelAbuseGuardPanel.test.jsx
@@ -102,3 +102,13 @@ describe('ModelAbuseGuardPanel', () => {
await act(async () => { deferred({ ok: true, ready: true }); });
});
});
+
+it('keeps a failed installation actionable after refresh and remount', async () => {
+ getModelAbuseGuardStatus.mockResolvedValue({ ready: false, pythonAvailable: true, venvReady: true, setupState: 'incomplete', stages: STAGES, lastInstallFailure: { stage: 'packages', code: 'network-failed', exitCode: 1, message: 'Package server unreachable.', action: 'Check the Python package index connection.' } });
+ await renderPanel();
+ expect(screen.getByRole('alert')).toHaveTextContent('packages: network-failed (exit 1)');
+ expect(screen.getByRole('alert')).toHaveTextContent('Check the Python package index connection.');
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh status' }));
+ await waitFor(() => expect(getModelAbuseGuardStatus).toHaveBeenCalledTimes(2));
+ expect(screen.getByRole('alert')).toHaveTextContent('Package server unreachable.');
+});
diff --git a/docs/PROMPT_GUARD_SETUP.md b/docs/PROMPT_GUARD_SETUP.md
new file mode 100644
index 0000000000..5e78adb2d2
--- /dev/null
+++ b/docs/PROMPT_GUARD_SETUP.md
@@ -0,0 +1,37 @@
+# Prompt Guard setup and recovery
+
+Models → LLMs → Abuse Guard shows the failed runtime check, expected package
+versions, and the last failed installation stage, diagnosis, and pip exit code.
+The last install failure is retained for the server process lifetime; after a
+restart, Refresh status still probes the installed packages without inference
+or downloads. Repair prefers an already installed `uv` package installer, falling back to
+Python pip when uv is unavailable. This supports machines where uv can reach
+the package index but Python pip cannot. Repair retries the dedicated runtime without changing the image
+or video environments or relaxing screening policy.
+
+For unattended local diagnosis, run from the PortOS checkout:
+
+```sh
+node scripts/setup-prompt-guard.js --status
+node scripts/setup-prompt-guard.js --install
+```
+
+Both commands print JSON to stdout and exit 0 only when ready (1 otherwise).
+Install progress goes to stderr. `--status` never installs or runs inference;
+`--install` explicitly downloads the pinned packages and model and runs the
+benign end-to-end verification. It uses the same locally configured Hugging
+Face token as the UI, without putting the token in command arguments. Run these commands from the primary installation after updating it. CoS
+worktrees deliberately use isolated data and ignore `PORTOS_DATA_ROOT`.
+
+Failure codes include `package-missing`, `package-version-mismatch`,
+`network-failed`, `certificate-failed`, `wheel-unavailable`, `dependency-conflict`,
+and `disk-full`. The first recognized pip error is retained so a connection
+failure is not hidden by pip's later “No matching distribution” summary.
+Subprocess output is mapped to static messages: tokens, authenticated index
+URLs, and local filesystem paths are never returned in setup diagnostics.
+
+For `network-failed`, check Python's access to the configured package index;
+a browser or curl succeeding does not prove Python can connect. Restore that
+connection and rerun `--install`. For `certificate-failed`, repair certificate
+trust rather than disabling TLS verification. Gated Hugging Face access still
+requires account approval; a stored token alone does not grant it.
diff --git a/scripts/setup-prompt-guard.js b/scripts/setup-prompt-guard.js
new file mode 100644
index 0000000000..bf871b0e39
--- /dev/null
+++ b/scripts/setup-prompt-guard.js
@@ -0,0 +1,15 @@
+#!/usr/bin/env node
+/** Non-interactive, machine-readable access to the same installer as the UI. */
+import { getModelAbuseGuardStatus, installModelAbuseGuard } from '../server/services/modelAbuseGuard.js';
+
+const mode = process.argv[2];
+if (!['--status', '--install'].includes(mode) || process.argv.length !== 3) {
+ console.error('Usage: node scripts/setup-prompt-guard.js --status | --install');
+ process.exit(2);
+}
+
+const result = await (mode === '--status'
+ ? getModelAbuseGuardStatus()
+ : installModelAbuseGuard({ onEvent: (event) => console.error(JSON.stringify(event)) }));
+console.log(JSON.stringify(result, null, 2));
+process.exit(result.ready === true ? 0 : 1);
diff --git a/server/lib/pythonSetup.install.test.js b/server/lib/pythonSetup.install.test.js
new file mode 100644
index 0000000000..988ac481d1
--- /dev/null
+++ b/server/lib/pythonSetup.install.test.js
@@ -0,0 +1,30 @@
+import { EventEmitter } from 'node:events';
+import { beforeEach, expect, it, vi } from 'vitest';
+
+const mock = vi.hoisted(() => ({ spawn: vi.fn(), uv: null }));
+vi.mock('./childProcess.js', async (original) => ({ ...await original(), spawn: mock.spawn }));
+vi.mock('./processEnv.js', async (original) => ({ ...await original(), whichFirstSync: () => mock.uv }));
+const { installPackages } = await import('./pythonSetup.js');
+
+beforeEach(() => {
+ mock.uv = null;
+ mock.spawn.mockReset().mockImplementation(() => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.kill = vi.fn(() => child.emit('close', null));
+ queueMicrotask(() => child.emit('close', 0));
+ return child;
+ });
+});
+
+it('uses uv only when requested and present, keeping the dedicated interpreter and pins', async () => {
+ mock.uv = '/tools/uv';
+ await expect(installPackages('/guard/python', ['torch==2.14.0'], vi.fn(), { preferUv: true }).promise).resolves.toEqual({ ok: true, code: 0 });
+ expect(mock.spawn).toHaveBeenLastCalledWith('/tools/uv', ['pip', 'install', '--python', '/guard/python', '--upgrade', 'torch==2.14.0'], expect.any(Object));
+ await installPackages('/image/python', ['torch'], vi.fn()).promise;
+ expect(mock.spawn.mock.calls.at(-1)[0]).toBe('/image/python');
+ mock.uv = null;
+ await installPackages('/guard/python', ['torch==2.14.0'], vi.fn(), { preferUv: true }).promise;
+ expect(mock.spawn).toHaveBeenLastCalledWith('/guard/python', ['-m', 'pip', 'install', '--upgrade', '--progress-bar', 'on', 'torch==2.14.0'], expect.any(Object));
+});
diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.js
index 8dc607c4ad..1ad3af1dd2 100644
--- a/server/lib/pythonSetup.js
+++ b/server/lib/pythonSetup.js
@@ -771,14 +771,21 @@ function streamSpawn(bin, args, onLog, onProc) {
// Returns `{ promise, kill }` so the route can SIGTERM the pip child if the
// SSE client disconnects mid-install — a 10-minute torch upgrade would
// otherwise keep running invisibly.
-export function installPackages(pythonPath, importNames, onLog) {
+export function installPackages(pythonPath, importNames, onLog, { preferUv = false } = {}) {
+ const uv = preferUv ? whichFirstSync('uv') : null;
const pipSpecs = importNames.map(pipNameFor);
const conflicts = [...new Set(pipSpecs.flatMap((s) => PIP_PRE_UNINSTALL[s] || []))];
let currentProc = null;
let killed = false;
const trackProc = (p) => { currentProc = p; };
- const runPip = (args) => streamSpawn(pythonPath, ['-m', 'pip', ...args], onLog, trackProc);
+ const runPip = (args) => {
+ if (!uv) return streamSpawn(pythonPath, ['-m', 'pip', ...args], onLog, trackProc);
+ // uv does not accept pip's progress-bar/yes options. Keep the same
+ // exact target interpreter and package specifications in both paths.
+ const uvArgs = args.filter((arg, index) => arg !== '--yes' && arg !== '--progress-bar' && args[index - 1] !== '--progress-bar');
+ return streamSpawn(uv, ['pip', uvArgs[0], '--python', pythonPath, ...uvArgs.slice(1)], onLog, trackProc);
+ };
const promise = (async () => {
if (conflicts.length) {
@@ -789,13 +796,13 @@ export function installPackages(pythonPath, importNames, onLog) {
await runPip(['uninstall', '--yes', ...conflicts]);
if (killed) return { ok: false, code: -1 };
}
- onLog({ type: 'log', message: `pip install ${pipSpecs.join(' ')}` });
+ onLog({ type: 'log', message: `${uv ? 'uv pip' : 'pip'} install ${pipSpecs.join(' ')}` });
const code = await runPip(['install', '--upgrade', '--progress-bar', 'on', ...pipSpecs]);
if (code === 0) {
onLog({ type: 'complete', message: 'All packages installed successfully.' });
return { ok: true, code: 0 };
}
- onLog({ type: 'error', message: `pip exited with code ${code}` });
+ onLog({ type: 'error', message: `${uv ? 'uv pip' : 'pip'} exited with code ${code}` });
return { ok: false, code };
})();
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index 9ed74824cf..63216fc999 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -240,8 +240,10 @@ router.post('/security-guard/install', asyncHandler(async (req, res) => {
: code === 'security-guard-runtime-install-failed'
? 'Classifier package installation failed. Check internet access and Python compatibility, then retry from Models > LLMs > Abuse Guard.'
: code
- emit('error', message, { scope: 'security-guard' })
- throw new ServerError(message, { status: 502, code })
+ const detail = result?.diagnostic
+ const actionableMessage = detail ? `${message} ${detail.message} ${detail.action}` : message
+ emit('error', actionableMessage, { scope: 'security-guard', stage: detail?.stage })
+ throw new ServerError(actionableMessage, { status: 502, code })
}
res.json(result)
}))
diff --git a/server/services/modelAbuseGuard.js b/server/services/modelAbuseGuard.js
index 68c7a61600..337f096c07 100644
--- a/server/services/modelAbuseGuard.js
+++ b/server/services/modelAbuseGuard.js
@@ -77,6 +77,8 @@ let cachedRuntime = null;
let selfTestFailed = false;
let installInFlight = null;
let installKill = null;
+let runtimeIssue = null;
+let lastInstallFailure = null;
const failure = (code, extra = {}) => ({ ok: false, passed: false, safe: false, code, ...extra });
// What a report names as its guard model when only the deterministic layer ran.
@@ -324,6 +326,24 @@ function availableGuardPython() {
return null;
}
+// Never return raw subprocess output: it can contain tokens, private paths,
+// or authenticated package-index URLs. Match evidence to static diagnoses.
+function setupIssue(text, fallback = 'runtime-check-failed') {
+ const missing = MODEL_ABUSE_GUARD_PYTHON_IMPORTS.find((name) => String(text || '').includes(`No module named '${name}'`));
+ if (missing) return { code: 'package-missing', package: missing, message: `The classifier package ${missing} is missing.`, action: 'Repair model-abuse guard to install the pinned packages.' };
+ const diagnoses = [
+ [/No module named/, 'package-missing', 'A classifier package or dependency is missing.', 'Repair model-abuse guard to install the pinned packages.'],
+ [/CERTIFICATE_VERIFY_FAILED|certificate verify failed/i, 'certificate-failed', 'Python could not verify the package server certificate.', 'Repair Python certificate trust, then retry installation.'],
+ [/No matching distribution|Could not find a version that satisfies/i, 'wheel-unavailable', 'A pinned package has no matching distribution for this Python and platform.', 'Use a Python version and platform supported by the pinned packages, then repair the runtime.'],
+ [/ResolutionImpossible|conflicting dependencies/i, 'dependency-conflict', 'The classifier dependencies could not be resolved.', 'Check the pinned package compatibility before retrying.'],
+ [/No space left on device/i, 'disk-full', 'There is not enough disk space for the classifier.', 'Free disk space, then retry installation.'],
+ [/timed? ?out|ReadTimeout|ConnectionError|NameResolution|Temporary failure|Network is unreachable|No route to host|connection error|NewConnectionError/i, 'network-failed', 'The download could not reach its server.', 'Check this machine’s network and Python connection to the download server, then retry.'],
+ ];
+ const match = diagnoses.find(([pattern]) => pattern.test(String(text || '')));
+ if (match) return { code: match[1], message: match[2], action: match[3] };
+ return { code: fallback, message: 'The dedicated classifier runtime could not be verified.', action: 'Repair model-abuse guard and inspect the reported install stage and exit code.' };
+}
+
function probeScript() {
const imports = MODEL_ABUSE_GUARD_PYTHON_IMPORTS
.map((name) => `import ${name}`)
@@ -348,8 +368,9 @@ async function isBasePythonSupported(pythonPath) {
const RUNTIME_CANARY_TEXT = 'The quick brown fox jumps over the lazy dog.';
async function isRuntimeReady(pythonPath) {
- if (!pythonPath) return false;
+ if (!pythonPath) { runtimeIssue = null; return false; }
if (cachedRuntime?.pythonPath === pythonPath && Date.now() - cachedRuntime.checkedAt < 60_000) return true;
+ runtimeIssue = null;
const importsReady = await execFileAsync(
pythonPath,
['-c', probeScript()],
@@ -359,7 +380,8 @@ async function isRuntimeReady(pythonPath) {
maxBuffer: 4_000,
}),
).then(({ stdout }) => stdout.trim().split(/\r?\n/).pop() === '{"ready":true}')
- .catch(() => false);
+ .catch((error) => { runtimeIssue = setupIssue(error.stderr || error.message); return false; });
+ if (!importsReady && !runtimeIssue) runtimeIssue = { code: 'package-version-mismatch', message: 'Installed classifier package versions do not match the pinned runtime.', action: 'Repair model-abuse guard to install the expected versions.' };
if (importsReady) cachedRuntime = { pythonPath, checkedAt: Date.now() };
return importsReady;
}
@@ -410,6 +432,9 @@ export async function getModelAbuseGuardStatus() {
stages,
ready,
selfTestFailed,
+ runtimeIssue,
+ lastInstallFailure,
+ expectedPackages: [...MODEL_ABUSE_GUARD_PYTHON_PACKAGES],
setupState: ready ? 'ready' : installationPresent ? 'incomplete' : 'not-installed',
classifierMode: 'required',
minBenignScore: MODEL_ABUSE_GUARD_MIN_BENIGN_SCORE,
@@ -424,14 +449,22 @@ export async function getModelAbuseGuardStatus() {
*/
export function installModelAbuseGuard({ onEvent } = {}) {
if (installInFlight) return installInFlight;
+ lastInstallFailure = null;
+ let activeStage = 'huggingface-token';
+ const failInstall = (code, diagnostic = setupIssue('', code)) => {
+ lastInstallFailure = { ...diagnostic, stage: activeStage };
+ return failure(code, { diagnostic: lastInstallFailure });
+ };
installInFlight = (async () => {
// Do this before creating a venv or installing packages. The model is gated
// on Hugging Face, so a missing token is an operator prerequisite—not a
// reason to leave a half-useful runtime behind and discover the problem
// only after setup has changed the install.
- if (!(await getHfToken())) return failure('security-guard-huggingface-token-required');
+ if (!(await getHfToken())) return failInstall('security-guard-huggingface-token-required');
+ activeStage = 'python';
const basePython = detectVenvBasePythonSync();
- if (!await isBasePythonSupported(basePython)) return failure('security-guard-python-unavailable');
+ if (!await isBasePythonSupported(basePython)) return failInstall('security-guard-python-unavailable');
+ activeStage = 'venv';
await ensureDir(dirname(GUARD_VENV_DIR));
emitInstall(onEvent, 'stage', 'Preparing the dedicated Prompt Guard runtime…', 'venv');
const clear = existsSync(GUARD_PYTHON) && !await isBasePythonSupported(GUARD_PYTHON);
@@ -439,17 +472,28 @@ export function installModelAbuseGuard({ onEvent } = {}) {
cachedRuntime = null;
selfTestFailed = false;
+ activeStage = 'packages';
+ let packageIssue = null;
emitInstall(onEvent, 'stage', 'Installing the fixed classifier runtime packages…', 'packages');
const packageRun = installPackages(pythonPath, [...MODEL_ABUSE_GUARD_PYTHON_PACKAGES], ({ type, message }) => {
+ const issue = setupIssue(message);
+ if (issue.code !== 'runtime-check-failed' && !packageIssue) {
+ packageIssue = issue;
+ emitInstall(onEvent, 'stage', `${issue.message} ${issue.action}`, 'packages');
+ }
if (type === 'complete') emitInstall(onEvent, 'stage', 'Classifier runtime packages are ready.', 'packages');
else if (type === 'error') emitInstall(onEvent, 'error', 'Classifier runtime package installation failed.', 'packages');
else if (message && /install|uninstall/i.test(message)) emitInstall(onEvent, 'stage', 'Installing classifier runtime packages…', 'packages');
- });
+ }, { preferUv: true });
installKill = packageRun.kill;
const packageResult = await packageRun.promise;
installKill = null;
- if (!packageResult?.ok) return failure('security-guard-runtime-install-failed');
+ if (!packageResult?.ok) return failInstall('security-guard-runtime-install-failed', {
+ ...(packageIssue || setupIssue('', 'package-install-failed')),
+ ...(Number.isInteger(packageResult?.code) ? { exitCode: packageResult.code } : {}),
+ });
+ activeStage = 'model';
emitInstall(onEvent, 'stage', 'Downloading the pinned Prompt Guard model snapshot…', 'model');
const download = downloadHfRepo({
repo: MODEL_ABUSE_GUARD.repository,
@@ -465,22 +509,23 @@ export function installModelAbuseGuard({ onEvent } = {}) {
installKill = download.kill;
const downloadResult = await download.promise;
installKill = null;
- if (!downloadResult?.ok) return failure(downloadResult?.errorKind === 'gated_repo'
+ if (!downloadResult?.ok) return failInstall(downloadResult?.errorKind === 'gated_repo'
? 'security-guard-huggingface-access-required'
- : 'security-guard-model-download-failed');
+ : 'security-guard-model-download-failed', setupIssue(downloadResult?.errorMessage, 'model-download-failed'));
+ activeStage = 'verification';
const status = await getModelAbuseGuardStatus();
- if (!status.ready) return failure('security-guard-install-incomplete');
+ if (!status.ready) return failInstall('security-guard-install-incomplete', runtimeIssue || undefined);
const files = await findCachedRepoFiles(MODEL_ABUSE_GUARD.repository, MODEL_ABUSE_GUARD_REQUIRED_FILES, { revision: MODEL_ABUSE_GUARD.revision });
if (!files?.[0] || !await canaryPasses(pythonPath, dirname(files[0]))) {
cachedRuntime = null;
selfTestFailed = true;
- return failure('security-guard-self-test-failed');
+ return failInstall('security-guard-self-test-failed');
}
emitInstall(onEvent, 'complete', 'Prompt Guard is ready for model-abuse screening.');
return { ok: true, ...status };
})()
- .catch(() => failure('security-guard-install-failed'))
+ .catch((error) => failInstall('security-guard-install-failed', setupIssue(error.stderr || error.message)))
.finally(() => {
installKill = null;
installInFlight = null;
diff --git a/server/services/modelAbuseGuard.runtime.test.js b/server/services/modelAbuseGuard.runtime.test.js
index f46940d0d2..fb59d7dd96 100644
--- a/server/services/modelAbuseGuard.runtime.test.js
+++ b/server/services/modelAbuseGuard.runtime.test.js
@@ -53,7 +53,7 @@ describe('Prompt Guard runtime lifecycle', () => {
it('installs the dedicated versioned packages and verifies the full runner only on request', async () => {
const { installModelAbuseGuard } = await import('./modelAbuseGuard.js');
await expect(installModelAbuseGuard()).resolves.toMatchObject({ ok: true, ready: true });
- expect(mock.installPackages).toHaveBeenCalledWith('/example/venv/bin/python3', [...MODEL_ABUSE_GUARD_PYTHON_PACKAGES], expect.any(Function));
+ expect(mock.installPackages).toHaveBeenCalledWith('/example/venv/bin/python3', [...MODEL_ABUSE_GUARD_PYTHON_PACKAGES], expect.any(Function), { preferUv: true });
expect(mock.downloadHfRepo).toHaveBeenCalledWith(expect.objectContaining({ revision: expect.stringMatching(/^[a-f0-9]{40}$/), only: expect.not.arrayContaining(['modeling.py']) }));
expect(mock.spawn).toHaveBeenCalledOnce();
});
@@ -77,3 +77,35 @@ describe('Prompt Guard runtime lifecycle', () => {
expect(mock.spawn).toHaveBeenCalledOnce();
});
});
+
+describe('Prompt Guard setup diagnostics', () => {
+ it('reports an import failure on status without exposing subprocess secrets or starting a repair', async () => {
+ mock.execFile.mockImplementation((...args) => {
+ if (args[1][1].startsWith('import sys;')) return args.at(-1)(null, { stdout: 'supported' });
+ const error = Object.assign(new Error('private runtime path'), { stderr: "ModuleNotFoundError: No module named 'torch' hf_private_token" });
+ args.at(-1)(error);
+ });
+ const { getModelAbuseGuardStatus } = await import('./modelAbuseGuard.js');
+ const status = await getModelAbuseGuardStatus();
+ expect(status).toMatchObject({ ready: false, runtimeIssue: { code: 'package-missing', action: expect.stringContaining('Repair') }, expectedPackages: MODEL_ABUSE_GUARD_PYTHON_PACKAGES });
+ expect(JSON.stringify(status)).not.toMatch(/private runtime path|hf_private_token/);
+ expect(mock.installPackages).not.toHaveBeenCalled();
+ });
+
+ it('retains the first package failure cause and exit code across status refreshes, then clears it on repair', async () => {
+ mock.installPackages.mockImplementationOnce((_python, _packages, onLog) => {
+ onLog({ type: 'log', message: 'ReadTimeout https://user:[email protected] hf_private_token' });
+ onLog({ type: 'error', message: 'No matching distribution found' });
+ return { promise: Promise.resolve({ ok: false, code: 1 }), kill: vi.fn() };
+ });
+ const { installModelAbuseGuard, getModelAbuseGuardStatus } = await import('./modelAbuseGuard.js');
+ const onEvent = vi.fn();
+ const result = await installModelAbuseGuard({ onEvent });
+ expect(result).toMatchObject({ ok: false, diagnostic: { stage: 'packages', code: 'network-failed', exitCode: 1 } });
+ expect(JSON.stringify([result, onEvent.mock.calls])).not.toMatch(/password|private.example|hf_private_token/);
+ expect((await getModelAbuseGuardStatus()).lastInstallFailure).toEqual(result.diagnostic);
+ expect(mock.downloadHfRepo).not.toHaveBeenCalled();
+ await expect(installModelAbuseGuard()).resolves.toMatchObject({ ok: true });
+ expect((await getModelAbuseGuardStatus()).lastInstallFailure).toBeNull();
+ });
+});