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
find the OpenCode preset again — getAllProviders returns an envelope, not a list
[._.]/ Adam Eivydac779d0c6e9
diff --git a/client/src/components/settings/LocalModelAssessments.jsx b/client/src/components/settings/LocalModelAssessments.jsxindex 434a62094d..2ead2ebc42 100644--- a/client/src/components/settings/LocalModelAssessments.jsx+++ b/client/src/components/settings/LocalModelAssessments.jsx@@ -956,20 +956,13 @@ export function LocalModelAssessments() {return (<div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-4">- <div className="flex items-center justify-between gap-2 flex-wrap">- <div className="flex items-center gap-2">- <Gauge size={16} className="text-port-accent" />- <h2 className="text-sm font-medium text-gray-300">Measured Model Assessments</h2>- </div>- <button- onClick={() => load(intent)}- disabled={loading}- className="p-1.5 text-gray-400 hover:text-white transition-colors"- title="Refresh"- aria-label="Refresh model assessments"- >- <RefreshCw size={14} className={loading ? 'animate-spin' : ''} />- </button>+ {/* No refresh control: the report loads with the tab and reloads itself+ after every run, sweep and discard, so a manual refresh only ever+ re-fetched what was already on screen. */}+ <div className="flex items-center gap-2">+ <Gauge size={16} className="text-port-accent" />+ <h2 className="text-sm font-medium text-gray-300">Measured Model Assessments</h2>+ {loading && <BrailleSpinner />}</div><p className="text-xs text-gray-500">diff --git a/client/src/components/settings/ModelCapabilityTests.jsx b/client/src/components/settings/ModelCapabilityTests.jsxindex 198b52e03c..b99d07fca3 100644--- a/client/src/components/settings/ModelCapabilityTests.jsx+++ b/client/src/components/settings/ModelCapabilityTests.jsx@@ -24,6 +24,7 @@*/import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { Link } from 'react-router';import {FlaskConical, Play, RefreshCw, Trash2, Check, X, AlertTriangle, Terminal, Eye, BookOpen, Wrench,} from 'lucide-react';@@ -679,14 +680,29 @@ export default function ModelCapabilityTests({ report, loading, onReload, disabl</div>)}- {/* A runtime whose model list could not be read is missing from the matrix- entirely — without this the table silently under-reports rather than- saying it could not look. */}+ {/* A runtime PortOS could not reach. Every line carries the fix: for the+ runtimes PortOS can start, a link to the page that starts them; for the+ ones it cannot (vLLM and SGLang are containers the user runs), the+ docs. When PortOS listed the weights on disk anyway, it says so — those+ models ARE in the table below, just not runnable yet. */}{report?.listErrors?.length > 0 && (- <p className="text-xs text-port-warning flex items-start gap-1.5" role="alert">- <AlertTriangle size={12} className="mt-0.5 shrink-0" />- Could not list models for {report.listErrors.map((r) => r.label).join(', ')} — models there are missing from this table.- </p>+ <div className="border border-port-warning/30 rounded p-2.5 space-y-1.5" role="alert">+ {report.listErrors.map((runtime) => (+ <p key={runtime.id} className="text-[11px] text-gray-400 flex items-start gap-1.5 leading-snug">+ <AlertTriangle size={12} className="mt-0.5 shrink-0 text-port-warning" />+ <span>+ <span className="text-gray-300">{runtime.label}</span>{' '}+ {runtime.offline ? 'is not running' : 'could not be listed'}+ {runtime.recovered > 0+ ? ` — showing the ${runtime.recovered} model${runtime.recovered === 1 ? '' : 's'} PortOS has on disk for it. Start it to run anything against them.`+ : ' — any models it serves are missing from this table.'}+ {runtime.manageUrl+ ? <> <Link to={runtime.manageUrl} className="text-port-accent hover:underline">Start {runtime.label}</Link></>+ : (runtime.docsUrl && <> <a href={runtime.docsUrl} target="_blank" rel="noreferrer" className="text-port-accent hover:underline">How to start it</a></>)}+ </span>+ </p>+ ))}+ </div>)}{report?.readError && (@@ -720,6 +736,11 @@ export default function ModelCapabilityTests({ report, loading, onReload, disabl<div className="flex items-center gap-2 flex-wrap"><span className="text-xs text-gray-200 font-mono break-all">{m.modelId}</span><span className="text-[10px] text-gray-500">{m.runtimeLabel}</span>+ {m.offline && (+ <Pill tone="bare" size="xs" className="border-port-warning/40 text-port-warning" title={`Found on disk — ${m.runtimeLabel} is not running, so nothing can be run against it yet.`}>+ not running+ </Pill>+ )}</div><div className="flex items-center gap-1 mt-1 flex-wrap"><CapabilityBadges capabilities={m.capabilities} />diff --git a/client/src/components/settings/ModelCapabilityTests.test.jsx b/client/src/components/settings/ModelCapabilityTests.test.jsxindex 5fc897fbb9..fa156f2c72 100644--- a/client/src/components/settings/ModelCapabilityTests.test.jsx+++ b/client/src/components/settings/ModelCapabilityTests.test.jsx@@ -361,3 +361,43 @@ describe('running everything that applies to one model', () => {expect(screen.queryByRole('button', { name: /^run \d/i })).not.toBeInTheDocument();});});++describe('a runtime that could not be listed', () => {+ const withListError = (over) => report({+ listErrors: [{+ id: 'llama', label: 'llama.cpp', error: 'not reachable at http://127.0.0.1:5568/v1 (ECONNREFUSED)',+ offline: true, recovered: 2, manageUrl: '/models/llms', docsUrl: null, ...over,+ }],+ });++ it('says what is wrong and links to where it is fixed', () => {+ renderPanel({ report: withListError() });+ expect(screen.getByRole('alert')).toHaveTextContent(/llama\.cpp is not running/);+ expect(screen.getByRole('link', { name: /start llama\.cpp/i })).toHaveAttribute('href', '/models/llms');+ });++ it('says the models below came off disk, so they are real but unrunnable', () => {+ renderPanel({ report: withListError() });+ expect(screen.getByRole('alert')).toHaveTextContent(/showing the 2 models PortOS has on disk/);+ });++ it('falls back to the docs for a runtime PortOS cannot start', () => {+ renderPanel({+ report: withListError({+ id: 'vllm', label: 'vLLM', recovered: 0, manageUrl: null, docsUrl: 'https://docs.vllm.ai/',+ }),+ });+ expect(screen.getByRole('alert')).toHaveTextContent(/missing from this table/);+ expect(screen.getByRole('link', { name: /how to start it/i })).toHaveAttribute('href', 'https://docs.vllm.ai/');+ });++ it('marks an offline model as installed-but-not-running', () => {+ renderPanel({+ report: report({+ models: [model({ backend: 'llama', runtimeLabel: 'llama.cpp', offline: true })],+ listErrors: [],+ }),+ });+ expect(screen.getByText('not running')).toBeInTheDocument();+ });+});diff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.jsindex be79a9046b..72a127b296 100644--- a/server/services/localModelAssessments.js+++ b/server/services/localModelAssessments.js@@ -87,7 +87,7 @@ import { claimHeavyLocalJob } from '../lib/heavyJobClaim.js';import { isEmbeddingModel } from '../lib/localModelHeuristics.js';import { ServerError } from '../lib/errorHandler.js';import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';-import { getAllProviders } from './providers.js';+import { listProviders } from './providers.js';import { runEndpointLlmTest, runLocalLlmTest } from './localLlmPlayground.js';import {captureLlamaServerConfig,@@ -95,7 +95,8 @@ import {relaunchLlamaServerWithTuning,restoreLlamaServerConfig,} from './llamaServerManager.js';-import { getMtplxServerEndpoint, relaunchMtplxServerWithTuning } from './mtplxServerManager.js';+import { getMtplxServerEndpoint, getMtplxServerStatus, relaunchMtplxServerWithTuning } from './mtplxServerManager.js';+import { getSpecDecodePresetStatus } from './specDecodeModels.js';import { listModels } from './localLlm.js';import {getLoadedModels as getLoadedOllamaModels,@@ -196,8 +197,11 @@ export async function runtimeEndpoint(runtime) {* provider backs which runtime.*/export async function runtimeApiKey(runtime) {- const providers = await getAllProviders().catch(() => []);- const match = (Array.isArray(providers) ? providers : [])+ // `listProviders`, not `getAllProviders`: the latter resolves an ENVELOPE+ // (`{ activeProvider, providers }`), so the `Array.isArray` guard this used to+ // carry was never true and every runtime silently resolved to no key — a vLLM+ // behind VLLM_API_KEY then 401'd on every sample.+ const match = (await listProviders()).find((p) => localRuntimeKind(p) === runtime && typeof p?.apiKey === 'string' && p.apiKey !== '');return match?.apiKey || '';}@@ -217,6 +221,36 @@ export async function runtimeApiKey(runtime) {* `models: null` means the list could not be read; `[]` means it was read and* is genuinely empty.*/+/**+ * What PortOS knows is installed for a runtime WITHOUT asking the daemon.+ *+ * An endpoint runtime that is not running reports nothing over HTTP, but the+ * weights are still on disk and PortOS already lists them elsewhere (Models →+ * LLMs). Showing "could not list models" and an empty table hides installed+ * models behind a daemon the user just needs to start.+ *+ * Only consulted when the live probe FAILED, so a healthy install never pays+ * for it. Every other runtime returns `[]` — vLLM and SGLang are containers the+ * user runs themselves, and PortOS holds no catalog for them, which is a real+ * answer rather than a gap to paper over.+ */+export async function durableRuntimeModels(runtime) {+ if (runtime === 'llama') {+ // A preset whose target GGUF is on disk is a model llama.cpp can serve, and+ // the preset id IS the alias PortOS starts it under — so this is the same+ // id a running server would report from /v1/models.+ const presets = await getSpecDecodePresetStatus().catch(() => []);+ return presets+ .filter((preset) => preset?.model?.exists)+ .map((preset) => ({ id: preset.id, params: null, quantization: preset.model.quant ?? null }));+ }+ if (runtime === 'mtplx') {+ const status = await getMtplxServerStatus().catch(() => null);+ return (status?.cachedModels || []).map((id) => ({ id, params: null, quantization: null }));+ }+ return [];+}+export async function listRuntimeModels(runtime) {if (MANAGED_ASSESSMENT_BACKENDS.includes(runtime)) {const models = await listModels(runtime).catch((err) => ({ error: err?.message || 'model list failed' }));@@ -229,10 +263,21 @@ export async function listRuntimeModels(runtime) {}const endpoint = await runtimeEndpoint(runtime);- if (!endpoint) return { models: null, error: 'no endpoint is configured for this runtime' };+ if (!endpoint) return { models: null, error: 'no endpoint is configured for this runtime', offline: true };++ // A daemon that is down is the common case here, and it is FIXABLE — so fall+ // back to what is on disk and mark the listing `offline`, rather than+ // reporting a bare failure that hides installed models. `offline` is what+ // tells a consumer these came from disk: they are installed, but nothing can+ // be run against them until the runtime is started.+ const offlineListing = async (error) => {+ const models = await durableRuntimeModels(runtime).catch(() => []);+ return { models: models.length ? models : null, error, offline: true };+ };+const probe = await probeOpenAiModels(endpoint, { timeoutMs: 2500, apiKey: await runtimeApiKey(runtime) });- if (!probe.reachable) return { models: null, error: `not reachable at ${endpoint} (${probe.error})` };- if (!probe.models) return { models: null, error: probe.error || 'model listing was not readable' };+ if (!probe.reachable) return offlineListing(`not reachable at ${endpoint} (${probe.error})`);+ if (!probe.models) return offlineListing(probe.error || 'model listing was not readable');// An endpoint runtime reports ids only — no params, no quantization. `null`// there is honest: the capability axis simply goes unscored rather than being// guessed from the id.@@ -831,6 +876,11 @@ export async function getAssessmentReport({ intent = 'balanced' } = {}) {const assessedModels = new Set(assessments.map((a) => assessmentKey(a?.backend, a?.modelId)));const unassessed = [];for (const runtime of ASSESSABLE_RUNTIMES) {+ // An OFFLINE listing came off disk, not from the daemon. Those models are+ // installed but cannot be measured until the runtime is running, so they are+ // not offered here — a Measure button that can only fail is worse than no+ // row. The capability matrix lists them instead, with the fix attached.+ if (listed[runtime].offline) continue;for (const model of listed[runtime].models || []) {// Embedding-only models are excluded from the MEASURABLE list, not from// the runtime's catalog above: they serve `/api/embed`, neverdiff --git a/server/services/localModelAssessments.test.js b/server/services/localModelAssessments.test.jsindex 1eb9cf23fa..868f331c2f 100644--- a/server/services/localModelAssessments.test.js+++ b/server/services/localModelAssessments.test.js@@ -33,8 +33,20 @@ vi.mock('../lib/openAiModelsProbe.js', () => ({ probeOpenAiModels: (...args) =>// `runtimeApiKey` reads the provider registry to authenticate a key-gated// runtime (a vLLM container started behind VLLM_API_KEY).-const getAllProviders = vi.fn();-vi.mock('./providers.js', () => ({ getAllProviders: (...args) => getAllProviders(...args) }));+//+// `getAllProviders` resolves the toolkit ENVELOPE (`{ activeProvider, providers }`)+// and `listProviders` is the wrapper that unwraps it — mocked in that shape on+// purpose. A bare-array mock here is what let `runtimeApiKey`'s+// `Array.isArray(providers)` guard read as satisfied in tests while never being+// true in production, so a key-gated vLLM silently got no key.+const getAllProviders = vi.fn(async () => ({ activeProvider: null, providers: [] }));+vi.mock('./providers.js', () => ({+ getAllProviders: (...args) => getAllProviders(...args),+ listProviders: async () => {+ const data = await getAllProviders().catch(() => null);+ return Array.isArray(data?.providers) ? data.providers : [];+ },+}));const getLlamaServerEndpoint = vi.fn();const relaunchLlamaServerWithTuning = vi.fn();@@ -52,11 +64,20 @@ vi.mock('./llamaServerManager.js', () => ({// and probe their real :8000 — the same reason llama-server is mocked above.const getMtplxServerEndpoint = vi.fn(async () => 'http://127.0.0.1:8000/v1');const relaunchMtplxServerWithTuning = vi.fn(async () => ({ applied: true, reason: null, config: null }));+// Consulted only when the live probe fails, to list what is on disk for a+// runtime that is not running.+const getMtplxServerStatus = vi.fn(async () => ({ cachedModels: [] }));vi.mock('./mtplxServerManager.js', () => ({getMtplxServerEndpoint: (...args) => getMtplxServerEndpoint(...args),+ getMtplxServerStatus: (...args) => getMtplxServerStatus(...args),relaunchMtplxServerWithTuning: (...args) => relaunchMtplxServerWithTuning(...args),}));+const getSpecDecodePresetStatus = vi.fn(async () => []);+vi.mock('./specDecodeModels.js', () => ({+ getSpecDecodePresetStatus: (...args) => getSpecDecodePresetStatus(...args),+}));+const listModels = vi.fn();vi.mock('./localLlm.js', () => ({ listModels: (...args) => listModels(...args) }));@@ -1034,14 +1055,14 @@ describe('key-gated runtimes', () => {// an unauthenticated request. Without the key the listing reads as// "unreadable" and every sample fails auth — recorded as a fit verdict.it('authenticates the model listing with the provider record\'s key', async () => {- getAllProviders.mockResolvedValue([vllmProvider]);+ getAllProviders.mockResolvedValue({ activeProvider: null, providers: [vllmProvider] });probeOpenAiModels.mockResolvedValue({ reachable: true, models: ['qwen'], error: null });await svc.listRuntimeModels('vllm');expect(probeOpenAiModels).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ apiKey: 'secret-key' }));});it('authenticates the measurement with the same key', async () => {- getAllProviders.mockResolvedValue([vllmProvider]);+ getAllProviders.mockResolvedValue({ activeProvider: null, providers: [vllmProvider] });probeOpenAiModels.mockResolvedValue({ reachable: true, models: ['qwen'], error: null });runEndpointLlmTest.mockResolvedValue(okRun());await svc.runAssessment({ backend: 'vllm', modelId: 'qwen', contextTokens: [512] });@@ -1051,7 +1072,7 @@ describe('key-gated runtimes', () => {// The usual loopback daemon is unauthenticated; attaching a key from an// unrelated provider would be worse than sending none.it('sends no key when no provider for that runtime carries one', async () => {- getAllProviders.mockResolvedValue([{ id: 'ollama', ollamaBacked: true, endpoint: 'http://localhost:11434/v1', apiKey: 'not-mine' }]);+ getAllProviders.mockResolvedValue({ activeProvider: null, providers: [{ id: 'ollama', ollamaBacked: true, endpoint: 'http://localhost:11434/v1', apiKey: 'not-mine' }] });probeOpenAiModels.mockResolvedValue({ reachable: true, models: [], error: null });await svc.listRuntimeModels('mtplx');expect(probeOpenAiModels).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ apiKey: '' }));diff --git a/server/services/modelCapabilityTests.js b/server/services/modelCapabilityTests.jsindex e3f4f8a513..87ffb81337 100644--- a/server/services/modelCapabilityTests.js+++ b/server/services/modelCapabilityTests.js@@ -58,7 +58,7 @@ import {} from '../lib/modelCapabilityTests.js';import { listRuntimeModels, runtimeEndpoint, runtimeApiKey } from './localModelAssessments.js';import { runLocalLlmTest, runEndpointLlmTest } from './localLlmPlayground.js';-import { getAllProviders } from './providers.js';+import { listProviders } from './providers.js';import { resolveOpencodeTuiProvider, runOpencodeTask } from './opencodeTask.js';import { ollamaBadgeCapabilities } from './localLlm.js';import * as ollamaManager from './ollamaManager.js';@@ -434,7 +434,7 @@ export async function runCapabilityTest({ backend, modelId, testId, signal, onPremit({ event: 'complete', cancelled: true, message: `${test.label}: cancelled — nothing recorded` });return { backend, modelId, testId: test.id, cancelled: true };}- const providers = test.driver === 'tui' ? await getAllProviders().catch(() => null) : null;+ const providers = test.driver === 'tui' ? await listProviders() : null;outcome = await RUNNERS[test.id]({ backend, modelId, testId: test.id, signal, emit, runId, providers });} catch (err) {// A terminal frame either way, or the page's banner sits on the last@@ -509,7 +509,7 @@ export async function getCapabilityTestResult(backend, modelId, testId) {* has proved. Disk plus cached loopback capability probes; zero LLM calls.*/export async function getCapabilityTestReport() {- const providers = await getAllProviders().catch(() => null);+ const providers = await listProviders();const [{ index, readError }, listed, drivers] = await Promise.all([indexResults(),Promise.all(ASSESSABLE_RUNTIMES.map(async (runtime) => [runtime, await listRuntimeModels(runtime)]))@@ -521,6 +521,8 @@ export async function getCapabilityTestReport() {// Capability resolution costs one cached `/api/show` per un-probed Ollama// model. Sequentially that is one round trip per model on the page-load path;// they are independent, so they go together.+ const offline = Object.fromEntries(ASSESSABLE_RUNTIMES.map((id) => [id, Boolean(listed[id].offline)]));+const models = (await Promise.all(ASSESSABLE_RUNTIMES.flatMap((runtime) =>(listed[runtime].models || []).filter((m) => m?.id).map(async (model) => {const capabilities = await resolveModelCapabilities(runtime, model);@@ -530,18 +532,30 @@ export async function getCapabilityTestReport() {// can make an otherwise-applicable test unrunnable. Surfaced as its own// state so the UI explains "PortOS cannot drive this" rather than// implying the model is at fault.- const blocked = test.driver === 'tui' && state === 'applicable' && !drivers[runtime].available;+ // Two things can make an otherwise-applicable test unrunnable, and both+ // are properties of the RUNTIME rather than of the model — so they are+ // surfaced as `unavailable` with the reason, never as a failure the+ // model earned. A stopped daemon wins the explanation: starting it is+ // the fix, and the missing agent preset may not even be missing once it+ // is up.+ const runtimeDown = offline[runtime] && state !== 'not-applicable';+ const noDriver = test.driver === 'tui' && state === 'applicable' && !drivers[runtime].available;return {testId: test.id,- state: blocked ? 'unavailable' : state,+ state: runtimeDown || noDriver ? 'unavailable' : state,missing,- reason: blocked ? drivers[runtime].reason : reason,+ reason: runtimeDown+ ? `${runtimeLabel(runtime)} is not running`+ : (noDriver ? drivers[runtime].reason : reason),result: summarizeResult(stored),};});return {backend: runtime,runtimeLabel: runtimeLabel(runtime),+ // These came off disk rather than from the daemon: installed, but+ // nothing can run against them until the runtime is started.+ offline: Boolean(offline[runtime]),// `null` = nothing authoritative reported a badge set. The UI must say// "unverified", never render it as an empty badge row.capabilities,@@ -566,12 +580,22 @@ export async function getCapabilityTestReport() {passed: countTests((t) => t.result?.verdict === 'passed'),failed: countTests((t) => t.result?.verdict === 'failed'),},- // Runtimes whose model list could not be trusted — distinct from "listed and- // legitimately empty". Without this the matrix silently under-reports: a- // model that failed to list simply is not there.+ // Runtimes whose model list could not be read live — distinct from "listed+ // and legitimately empty". `manageUrl` is what makes this actionable rather+ // than just a complaint: for the runtimes PortOS can start, it points at the+ // page that starts them. `recovered` says PortOS listed what is on disk+ // anyway, so the user knows the models below are real and merely unreachable.listErrors: ASSESSABLE_RUNTIMES.filter((id) => listed[id].error)- .map((id) => ({ id, label: runtimeLabel(id), error: listed[id].error })),+ .map((id) => ({+ id,+ label: runtimeLabel(id),+ error: listed[id].error,+ offline: Boolean(listed[id].offline),+ recovered: Array.isArray(listed[id].models) ? listed[id].models.length : 0,+ manageUrl: LOCAL_RUNTIMES[id]?.manageUrl || null,+ docsUrl: LOCAL_RUNTIMES[id]?.docsUrl || null,+ })),readError,};}diff --git a/server/services/modelCapabilityTests.test.js b/server/services/modelCapabilityTests.test.jsindex 04fd793b5e..e83bb4bbdd 100644--- a/server/services/modelCapabilityTests.test.js+++ b/server/services/modelCapabilityTests.test.js@@ -19,7 +19,20 @@ vi.mock('./localLlmPlayground.js', () => ({runLocalLlmTest: vi.fn(),runEndpointLlmTest: vi.fn(),}));-vi.mock('./providers.js', () => ({ getAllProviders: vi.fn(async () => []) }));+// `getAllProviders` resolves the toolkit ENVELOPE (`{ activeProvider, providers }`),+// and `listProviders` is the wrapper that unwraps it. Mocked in that shape on+// purpose: a bare-array mock is exactly what let the matcher ship returning null+// for every runtime while this suite stayed green.+vi.mock('./providers.js', () => {+ const getAllProviders = vi.fn(async () => ({ activeProvider: null, providers: [] }));+ return {+ getAllProviders,+ listProviders: async () => {+ const data = await getAllProviders().catch(() => null);+ return Array.isArray(data?.providers) ? data.providers : [];+ },+ };+});vi.mock('./ollamaManager.js', () => ({ getModelCapabilities: vi.fn(async () => null) }));vi.mock('./localLlm.js', () => ({ ollamaBadgeCapabilities: (raw) => raw }));vi.mock('../lib/bufferedSpawn.js', () => ({@@ -67,7 +80,7 @@ beforeEach(async () => {await rm(join(TEST_ROOT, 'local-llm'), { recursive: true, force: true });await rm(join(TEST_ROOT, 'model-tests'), { recursive: true, force: true });listRuntimeModels.mockResolvedValue({ models: [], error: null });- getAllProviders.mockResolvedValue([]);+ getAllProviders.mockResolvedValue({ activeProvider: null, providers: [] });claimHeavyLocalJob.mockResolvedValue({ ok: true, holder: null, release: async () => {} });__resetFixtureCaches();});@@ -119,7 +132,7 @@ describe('getCapabilityTestReport', () => {});it('offers the tool-use test once a matching TUI provider exists', async () => {- getAllProviders.mockResolvedValue([OPENCODE_LLAMA]);+ getAllProviders.mockResolvedValue({ activeProvider: null, providers: [OPENCODE_LLAMA] });installOn('llama', [{ id: 'qwen-local' }]);const report = await getCapabilityTestReport();const model = report.models.find((m) => m.modelId === 'qwen-local');@@ -200,7 +213,7 @@ describe('runCapabilityTest — story outline', () => {describe('runCapabilityTest — sandbox repair', () => {beforeEach(() => {- getAllProviders.mockResolvedValue([OPENCODE_LLAMA]);+ getAllProviders.mockResolvedValue({ activeProvider: null, providers: [OPENCODE_LLAMA] });});// The agent is simulated by having the spawn mock edit the sandbox the way a@@ -278,7 +291,7 @@ export function cartTotal({ items, region, discount = 0 }) {});it('refuses when no agent driver can reach the runtime', async () => {- getAllProviders.mockResolvedValue([]);+ getAllProviders.mockResolvedValue({ activeProvider: null, providers: [] });await expect(runCapabilityTest({ backend: 'lmstudio', modelId: 'x', testId: 'sandbox-repair' })).rejects.toThrow(/OpenCode/);});@@ -372,14 +385,16 @@ describe('what the report ships', () => {: { models: [], error: null }));const report = await getCapabilityTestReport();// Missing models must read as "could not look", not as "none installed".- expect(report.listErrors).toEqual([{ id: 'ollama', label: 'Ollama', error: 'not reachable at http://127.0.0.1:11434/v1' }]);+ expect(report.listErrors).toEqual([expect.objectContaining({+ id: 'ollama', label: 'Ollama', error: 'not reachable at http://127.0.0.1:11434/v1',+ })]);});});describe('sandbox housekeeping', () => {it('keeps the newest sandboxes and prunes the rest', async () => {const { mkdir, readdir } = await import('fs/promises');- getAllProviders.mockResolvedValue([OPENCODE_LLAMA]);+ getAllProviders.mockResolvedValue({ activeProvider: null, providers: [OPENCODE_LLAMA] });const root = join(TEST_ROOT, 'model-tests', 'sandboxes');// 25 older runs, named the way runCapabilityTest names them (a base36// timestamp of fixed width, so a plain sort is chronological).@@ -396,3 +411,51 @@ describe('sandbox housekeeping', () => {expect(left.some((name) => !name.endsWith('-old'))).toBe(true);});});++describe('a runtime that is not running', () => {+ const offlineListing = (models) => {+ listRuntimeModels.mockImplementation(async (id) => (id === 'llama'+ ? { models, error: 'not reachable at http://127.0.0.1:5568/v1 (ECONNREFUSED)', offline: true }+ : { models: [], error: null }));+ };++ it('still lists what PortOS has on disk, rather than hiding it', async () => {+ offlineListing([{ id: 'qwen3.8-27b-dspark', params: null, quantization: 'Q4_K_M' }]);+ const report = await getCapabilityTestReport();+ const model = report.models.find((m) => m.modelId === 'qwen3.8-27b-dspark');++ expect(model).toBeTruthy();+ expect(model.offline).toBe(true);+ });++ it('blocks its tests with the daemon as the reason, not the model', async () => {+ offlineListing([{ id: 'qwen3.8-27b-dspark' }]);+ const report = await getCapabilityTestReport();+ const model = report.models.find((m) => m.modelId === 'qwen3.8-27b-dspark');++ // Nothing can run until it is started — but that is never scored as a+ // failure the model earned.+ for (const slot of model.tests) {+ expect(slot.state).toBe('unavailable');+ expect(slot.reason).toBe('llama.cpp is not running');+ }+ });++ it('carries the fix: where to start it, and how many models it recovered', async () => {+ offlineListing([{ id: 'a' }, { id: 'b' }]);+ const report = await getCapabilityTestReport();++ expect(report.listErrors).toEqual([expect.objectContaining({+ id: 'llama', label: 'llama.cpp', offline: true, recovered: 2, manageUrl: '/models/llms',+ })]);+ });++ it('says nothing was recovered when PortOS holds no catalog for it', async () => {+ // vLLM and SGLang are containers the user runs — an honest zero, not a gap.+ listRuntimeModels.mockImplementation(async (id) => (id === 'vllm'+ ? { models: null, error: 'not reachable at http://127.0.0.1:18020/v1 (ECONNREFUSED)', offline: true }+ : { models: [], error: null }));+ const report = await getCapabilityTestReport();+ expect(report.listErrors[0]).toMatchObject({ id: 'vllm', recovered: 0, manageUrl: null });+ });+});diff --git a/server/services/opencodeTask.js b/server/services/opencodeTask.jsindex 7e85779259..db5acce13c 100644--- a/server/services/opencodeTask.js+++ b/server/services/opencodeTask.js@@ -22,7 +22,7 @@ import { prepareCliSpawn } from '../lib/bufferedSpawn.js';import { buildCliChildEnv } from '../lib/cliChildEnv.js';import { isOpencodeCommand, prefixOpencodeModel, getOpencodeLocalProviderNamespace } from '../lib/providerModels.js';import { parseAgentLine } from '../lib/opencodeStream.js';-import { getAllProviders } from './providers.js';+import { listProviders } from './providers.js';/*** The configured OpenCode TUI provider that drives a given local runtime.@@ -33,12 +33,12 @@ import { getAllProviders } from './providers.js';* real answer rather than a failure to look harder.** @param {string} runtime a local runtime id (`llama`, `ollama`, `mtplx`, …)- * @param {Array<object>} [providers] pass the already-loaded list when resolving- * several runtimes at once — otherwise every call re-scans it.+ * @param {Array<object>} [providers] the already-loaded RECORDS (see+ * `listProviders`), passed in when resolving several runtimes at once so the+ * list is read once rather than per runtime.*/export async function resolveOpencodeTuiProvider(runtime, providers) {- const list = providers ?? await getAllProviders().catch(() => null);- if (!Array.isArray(list)) return null;+ const list = Array.isArray(providers) ? providers : await listProviders();return list.find((p) => p?.type === 'tui'&& isOpencodeCommand(p.command)&& getOpencodeLocalProviderNamespace(p) === runtime) || null;diff --git a/server/services/opencodeTask.test.js b/server/services/opencodeTask.test.jsnew file mode 100644index 0000000000..cd0c5580ae--- /dev/null+++ b/server/services/opencodeTask.test.js@@ -0,0 +1,113 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// The REAL toolkit envelope, deliberately: `getAllProviders()` resolves+// `{ activeProvider, providers: [...] }`, not a bare array. Mocking it as an+// array is exactly what let `resolveOpencodeTuiProvider` ship returning null for+// every runtime while its suite stayed green — the capability matrix said "no+// OpenCode TUI provider is configured" for models that had one.+const toolkitProviders = vi.fn();+vi.mock('./providers.js', async () => {+ const getAllProviders = (...args) => toolkitProviders(...args);+ return {+ getAllProviders,+ // Mirrors the real wrapper: unwrap the envelope, [] on a failed read.+ listProviders: async () => {+ const data = await getAllProviders().catch(() => null);+ return Array.isArray(data?.providers) ? data.providers : [];+ },+ };+});+vi.mock('../lib/streamingSpawn.js', () => ({ runStreamingCommand: vi.fn() }));+vi.mock('../lib/cliChildEnv.js', () => ({ buildCliChildEnv: vi.fn(() => ({ PATH: '/example/bin' })) }));++const { runStreamingCommand } = await import('../lib/streamingSpawn.js');+const { resolveOpencodeTuiProvider, runOpencodeTask } = await import('./opencodeTask.js');++const OPENCODE_OLLAMA_TUI = {+ id: 'opencode-ollama-tui', name: 'OpenCode Ollama TUI', type: 'tui', command: 'opencode', args: [], ollamaBacked: true,+};+const OPENCODE_OLLAMA_CLI = { id: 'opencode-ollama', type: 'cli', command: 'opencode', ollamaBacked: true };+const CLAUDE_OLLAMA_TUI = { id: 'claude-ollama-tui', type: 'tui', command: 'claude', ollamaBacked: true };+const OPENCODE_LLAMA_TUI = { id: 'opencode-llama-tui', type: 'tui', command: 'opencode', args: [], llamaBacked: true };++const envelope = (providers) => ({ activeProvider: 'opencode-ollama-tui', providers });++beforeEach(() => {+ vi.clearAllMocks();+ toolkitProviders.mockResolvedValue(envelope([+ OPENCODE_OLLAMA_CLI, CLAUDE_OLLAMA_TUI, OPENCODE_OLLAMA_TUI, OPENCODE_LLAMA_TUI,+ ]));+});++describe('resolveOpencodeTuiProvider', () => {+ it('finds the preset through the envelope getAllProviders actually returns', async () => {+ expect((await resolveOpencodeTuiProvider('ollama')).id).toBe('opencode-ollama-tui');+ expect((await resolveOpencodeTuiProvider('llama')).id).toBe('opencode-llama-tui');+ });++ it('matches on the provider marker, not on a hardcoded id', async () => {+ const renamed = { ...OPENCODE_OLLAMA_TUI, id: 'my-own-ollama-agent', name: 'Renamed' };+ toolkitProviders.mockResolvedValue(envelope([renamed]));+ expect((await resolveOpencodeTuiProvider('ollama')).id).toBe('my-own-ollama-agent');+ });++ it('ignores a CLI preset and a non-OpenCode TUI for the same runtime', async () => {+ toolkitProviders.mockResolvedValue(envelope([OPENCODE_OLLAMA_CLI, CLAUDE_OLLAMA_TUI]));+ expect(await resolveOpencodeTuiProvider('ollama')).toBeNull();+ });++ it('reports none for a runtime OpenCode has no namespace for', async () => {+ // LM Studio genuinely has no OpenCode preset — that is an answer, not a miss.+ expect(await resolveOpencodeTuiProvider('lmstudio')).toBeNull();+ });++ it('reads the list once when the caller already has it', async () => {+ const list = [OPENCODE_OLLAMA_TUI, OPENCODE_LLAMA_TUI];+ await resolveOpencodeTuiProvider('ollama', list);+ await resolveOpencodeTuiProvider('llama', list);+ expect(toolkitProviders).not.toHaveBeenCalled();+ });++ it('reports none rather than throwing when the provider service is unavailable', async () => {+ toolkitProviders.mockRejectedValue(new Error('toolkit not initialized'));+ expect(await resolveOpencodeTuiProvider('ollama')).toBeNull();+ });+});++describe('runOpencodeTask', () => {+ it('qualifies the model with the provider namespace so a bare id cannot route to the cloud', async () => {+ runStreamingCommand.mockResolvedValue({ success: true });+ await runOpencodeTask({+ provider: OPENCODE_OLLAMA_TUI, modelId: 'qwen2.5-coder:32b', cwd: '/tmp/sandbox', prompt: 'fix it', timeoutMs: 1000,+ });+ const [, args] = runStreamingCommand.mock.calls[0];+ expect(args).toContain('--model');+ expect(args[args.indexOf('--model') + 1]).toBe('ollama/qwen2.5-coder:32b');+ // The agent is confined to the sandbox it was given.+ expect(args[args.indexOf('--dir') + 1]).toBe('/tmp/sandbox');+ });++ it('streams parsed frames and returns them for aggregation', async () => {+ runStreamingCommand.mockImplementation(async (_cmd, _args, onLine) => {+ onLine(JSON.stringify({ type: 'text', part: { type: 'text', text: 'Reading.' } }));+ onLine('not json');+ onLine(JSON.stringify({ type: 'tool', part: { type: 'tool', tool: 'write' } }));+ return { success: true };+ });+ const seen = [];+ const result = await runOpencodeTask({+ provider: OPENCODE_OLLAMA_TUI, modelId: 'm', cwd: '/tmp/s', prompt: 'p', timeoutMs: 1000,+ onEvent: (e) => seen.push(e),+ });+ expect(seen).toHaveLength(2);+ expect(result.events).toHaveLength(2);+ expect(result.success).toBe(true);+ });++ it('refuses a provider that is not an OpenCode TUI', async () => {+ await expect(runOpencodeTask({ provider: CLAUDE_OLLAMA_TUI, modelId: 'm', cwd: '/tmp/s', prompt: 'p', timeoutMs: 1 }))+ .rejects.toThrow(/not an OpenCode TUI provider/);+ await expect(runOpencodeTask({ provider: null, modelId: 'm', cwd: '/tmp/s', prompt: 'p', timeoutMs: 1 }))+ .rejects.toThrow(/No OpenCode TUI provider/);+ });+});diff --git a/server/services/providers.js b/server/services/providers.jsindex 9a7288608e..2ccd991d6f 100644--- a/server/services/providers.js+++ b/server/services/providers.js@@ -30,6 +30,26 @@ export async function getAllProviders() {return requireToolkit().services.providers.getAllProviders();}+/**+ * Just the provider records, as an array.+ *+ * `getAllProviders()` resolves `{ activeProvider, providers: [...] }` — an+ * ENVELOPE, not a list. Callers that forgot kept writing+ * `Array.isArray(providers) ? providers : []`, which is never true and so+ * silently yields an empty list: the capability suite reported "no OpenCode TUI+ * provider is configured" for every runtime, and `runtimeApiKey` never found a+ * key for an authenticated vLLM. Both were green in tests that mocked the call+ * as a bare array.+ *+ * A caller that only wants the records should use this and never see the+ * envelope. `[]` on a failed read is deliberate: no provider is reachable, which+ * is what an empty list means here.+ */+export async function listProviders() {+ const data = await getAllProviders().catch(() => null);+ return Array.isArray(data?.providers) ? data.providers : [];+}+export async function getProviderById(id) {return requireToolkit().services.providers.getProviderById(id);}diff --git a/server/services/providers.shape.test.js b/server/services/providers.shape.test.jsnew file mode 100644index 0000000000..9a3d1bec92--- /dev/null+++ b/server/services/providers.shape.test.js@@ -0,0 +1,76 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'fs';+import { join } from 'path';+import { collectServerSources, readServerSource, SERVER_DIR } from '../lib/testHelper.js';++/**+ * `getAllProviders()` resolves an ENVELOPE — `{ activeProvider, providers: [] }`+ * — not a bare array. Callers that forgot wrote `Array.isArray(providers)`+ * guards that are never true, and so silently resolved to an empty list:+ *+ * - the capability matrix reported "no OpenCode TUI provider is configured"+ * for every runtime, on installs that had one;+ * - `runtimeApiKey` never found a key, so a vLLM behind VLLM_API_KEY 401'd on+ * every sample.+ *+ * Both shipped green, because their suites mocked the call as a bare array. This+ * guard pins the envelope so a future reader cannot re-derive the wrong shape+ * from a mock, and points anyone who just wants the records at `listProviders`.+ */+describe('getAllProviders returns an envelope, not a list', () => {+ it('is documented as such at the definition', () => {+ const src = readFileSync(join(SERVER_DIR, 'lib/aiToolkit/providers.js'), 'utf8');+ // The toolkit builds the envelope inline; if this shape ever changes, every+ // `listProviders` consumer has to be revisited.+ expect(src).toMatch(/return \{\s*activeProvider: data\.activeProvider,\s*providers: Object\.values\(data\.providers\)/);+ });++ it('has a wrapper that unwraps it, so callers never need to know', async () => {+ const { listProviders } = await import('./providers.js');+ expect(typeof listProviders).toBe('function');+ });++ it('has no caller treating the envelope as an array', () => {+ // The mistake is narrow and specific: bind the RESULT to a name, then use+ // that name as a list — `Array.isArray(x)`, `x.find(`, `x.map(`, `x.filter(`.+ // Assigning the envelope and reading `x.providers` a few lines later is the+ // correct shape and must not be flagged, so the window looks at how the bound+ // name is actually USED rather than at the assignment alone.+ const WINDOW = 8;+ const offenders = [];+ for (const rel of collectServerSources()) {+ const src = readServerSource(rel);+ if (!src.includes('getAllProviders()')) continue;+ const lines = src.split('\n');+ lines.forEach((line, i) => {+ const bind = line.match(/(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*await getAllProviders\(\)/);+ if (!bind) return;+ const name = bind[1];+ const window = lines.slice(i, i + WINDOW).join('\n');+ // Reading `.providers` off it anywhere in the window means the caller+ // knows it is an envelope.+ if (new RegExp(`\\b${name}[?.]*\\.providers\\b`).test(window)) return;+ const asList = new RegExp(`Array\\.isArray\\(\\s*${name}\\s*\\)|\\b${name}[?.]*\\.(?:find|map|filter|forEach|some|every)\\(`);+ if (asList.test(window)) offenders.push(`${rel}:${i + 1} — ${name}`);+ });+ }+ expect(+ offenders,+ 'These bind getAllProviders() and then use it as a list. It resolves '+ + '{ activeProvider, providers } — use `listProviders()` from '+ + 'server/services/providers.js when you only want the records.',+ ).toEqual([]);+ });++ it('catches the mistake it is written to catch', () => {+ // A bypass probe: the guard above passing is only meaningful if this shape+ // would actually fail it.+ const bad = [+ 'const providers = await getAllProviders().catch(() => []);',+ 'const match = (Array.isArray(providers) ? providers : []).find((p) => p.id === x);',+ ].join('\n');+ const name = bad.match(/const\s+([\w$]+)\s*=\s*await getAllProviders\(\)/)[1];+ expect(new RegExp(`Array\\.isArray\\(\\s*${name}\\s*\\)`).test(bad)).toBe(true);+ expect(new RegExp(`\\b${name}[?.]*\\.providers\\b`).test(bad)).toBe(false);+ });+});