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
add a Harnesses page so coding-agent CLIs can be updated from PortOS
[._.]/ Adam Eivycace949cce0b
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 0546f156c6..c054e29fb0 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -103,6 +103,7 @@ import {Clapperboard,PersonStanding,Box,+ Blocks,Boxes,Gamepad2,Waypoints,@@ -284,6 +285,7 @@ export const NAV_PRESENTATION = {'/meatspace/settings': { icon: Settings },'/models/3d': { icon: Boxes },'/models/embeddings': { icon: Braces },+ '/models/harnesses': { icon: Blocks },'/models/llms': { icon: Cpu },'/models/loras': { icon: Sparkles },'/models/media': { icon: HardDrive },diff --git a/client/src/components/models/HarnessesTab.jsx b/client/src/components/models/HarnessesTab.jsxnew file mode 100644index 0000000000..a38b157d1c--- /dev/null+++ b/client/src/components/models/HarnessesTab.jsx@@ -0,0 +1,310 @@+import { useCallback, useEffect, useState } from 'react';+import {+ AlertTriangle,+ ArrowUpCircle,+ CheckCircle2,+ Download,+ ExternalLink,+ Loader2,+ RefreshCw,+ Trash2,+} from 'lucide-react';+import { getHarnesses, refreshHarnessModels } from '../../services/api';+import { useConfirmDelete } from '../../hooks/useConfirmDelete';+import Banner from '../ui/Banner.jsx';+import Pill from '../ui/Pill';+import RuntimeInstallModal from '../install/RuntimeInstallModal';+import InlineConfirmRow from '../ui/InlineConfirmRow';++/**+ * Models → Harnesses: the coding-agent CLIs/TUIs this install drives.+ *+ * A harness is one binary — `opencode`, `claude`, `codex`, `agy`, `grok`,+ * `kimi`, `cursor-agent` — that several provider records share. The Providers+ * page could already install a MISSING one from its card, but nothing showed+ * which version was installed, whether it was stale, how to update it, or which+ * models this install of it actually knows about. So an OpenCode months behind+ * upstream looked identical to a current one, and the only fix was a terminal.+ *+ * This page owns that lifecycle end to end. Every action is a click here — none+ * of it runs on boot, and the model refresh reads the vendor's own catalog+ * rather than calling an AI provider (root AGENTS.md, AI Provider Usage Policy).+ */++// One row per action rather than two key-aligned tables, so a fourth action is+// one entry instead of two edits that must stay in step.+const ACTION_COPY = {+ install: {+ title: 'Install harness',+ description: 'Installing the CLI and putting it on PortOS\'s PATH…',+ },+ update: {+ title: 'Update harness',+ description: 'Updating the CLI in place. Providers using it keep their settings.',+ },+ uninstall: {+ title: 'Remove harness',+ description: 'Removing the CLI. Providers that use it will show as needing setup.',+ },+};++/** `1 provider` / `2 providers` — said three times on this page. */+const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;++/**+ * The one-line availability verdict. `Pill` rather than hand-rolled tone+ * classes, so this reads identically to the same fact on a provider card+ * (`ProviderRuntimeStatus`).+ */+function StatusBadge({ harness }) {+ if (!harness.installed) return <Pill tone="muted" size="xs" icon={AlertTriangle}>Not installed</Pill>;+ if (harness.updateAvailable) return <Pill tone="warning" size="xs" icon={ArrowUpCircle}>Update available</Pill>;+ return <Pill tone="success" size="xs" icon={CheckCircle2}>Installed</Pill>;+}++/**+ * The version line. `null` on either side means NOT KNOWN, never zero — an+ * offline install shows the version it has and simply says nothing about the+ * latest, rather than implying it is current or stale.+ */+function VersionLine({ harness }) {+ if (!harness.installed) return null;+ return (+ <div className="mt-1 flex flex-wrap items-center gap-x-3 text-[11px] text-gray-500">+ <span>Installed {harness.version || 'version unknown'}</span>+ {harness.latestVersion && <span>Latest {harness.latestVersion}</span>}+ {harness.package && <span className="font-mono">{harness.package}</span>}+ </div>+ );+}++/** Which provider records ride on this harness, and how many are switched on. */+function ProviderSummary({ providers }) {+ if (providers.length === 0) {+ return <p className="mt-2 text-[11px] text-gray-500">No providers use this harness.</p>;+ }+ const enabled = providers.filter((provider) => provider.enabled);+ return (+ <p className="mt-2 text-[11px] text-gray-500">+ {plural(providers.length, 'provider')}+ {enabled.length > 0 && <> · {enabled.length} enabled: {enabled.map((provider) => provider.name).join(', ')}</>}+ </p>+ );+}++function HarnessCard({ harness, onAction, onRefreshModels, refreshing, refreshResult }) {+ const canRefreshModels = harness.listsModels && harness.installed;+ // Removal takes providers offline, so the row asks first — inline, per the+ // no-`window.confirm` convention. `useConfirmDelete` is the shared+ // single-row-armed state this page would otherwise hand-roll.+ const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();+ return (+ <div className="rounded-lg border border-port-border bg-port-card p-4">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <h2 className="text-sm font-semibold text-white">{harness.label}</h2>+ <span className="rounded bg-port-bg px-1.5 py-0.5 font-mono text-[11px] text-gray-400">{harness.command}</span>+ </div>+ <VersionLine harness={harness} />+ <ProviderSummary providers={harness.providers} />+ {harness.docsUrl && (+ <a+ href={harness.docsUrl}+ target="_blank"+ rel="noreferrer"+ className="mt-2 inline-flex items-center gap-1 text-[11px] text-gray-500 hover:text-port-accent"+ >+ <ExternalLink className="h-3 w-3" /> Vendor docs+ </a>+ )}+ </div>++ <div className="flex shrink-0 flex-col items-end gap-2">+ <StatusBadge harness={harness} />+ <div className="flex flex-wrap justify-end gap-2">+ {!harness.installed && (+ <button+ type="button"+ disabled={!harness.installable}+ title={harness.installable ? undefined : harness.blockedReason}+ onClick={() => onAction(harness, 'install')}+ className="inline-flex items-center gap-1.5 rounded-md bg-port-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50"+ >+ <Download className="h-3.5 w-3.5" /> Install+ </button>+ )}+ {harness.installed && harness.updatable && (+ <button+ type="button"+ onClick={() => onAction(harness, 'update')}+ className="inline-flex items-center gap-1.5 rounded-md border border-port-border px-3 py-1.5 text-xs font-medium text-gray-200 hover:border-port-accent hover:text-white"+ >+ <ArrowUpCircle className="h-3.5 w-3.5" /> Update+ </button>+ )}+ {canRefreshModels && (+ <button+ type="button"+ disabled={refreshing}+ onClick={() => onRefreshModels(harness)}+ className="inline-flex items-center gap-1.5 rounded-md border border-port-border px-3 py-1.5 text-xs font-medium text-gray-200 hover:border-port-accent hover:text-white disabled:opacity-50"+ >+ {refreshing+ ? <Loader2 className="h-3.5 w-3.5 animate-spin" />+ : <RefreshCw className="h-3.5 w-3.5" />}+ Refresh models+ </button>+ )}+ {harness.installed && harness.removable && (+ <button+ type="button"+ onClick={() => requestDelete(harness.id)}+ className="inline-flex items-center gap-1.5 rounded-md border border-port-border px-3 py-1.5 text-xs font-medium text-gray-400 hover:border-port-error hover:text-port-error"+ >+ <Trash2 className="h-3.5 w-3.5" /> Remove+ </button>+ )}+ </div>+ </div>+ </div>++ {!harness.installable && harness.blockedReason && !harness.installed && (+ <Banner tone="warning" className="mt-3">{harness.blockedReason}</Banner>+ )}++ {isConfirming(harness.id) && (+ <InlineConfirmRow+ className="mt-3"+ autoFocus+ aria-label={`Remove ${harness.label}`}+ question={`Remove ${harness.label}? ${plural(harness.providers.length, 'provider')} use \`${harness.command}\` and will show as needing setup until it is reinstalled — their settings are kept.`}+ confirmText="Remove"+ onConfirm={() => confirmDelete(() => onAction(harness, 'uninstall'))}+ onCancel={cancelDelete}+ />+ )}++ {refreshResult && (+ <Banner tone={refreshResult.ok ? 'success' : 'warning'} className="mt-3">+ {refreshResult.message}+ </Banner>+ )}+ </div>+ );+}++export default function HarnessesTab() {+ const [harnesses, setHarnesses] = useState([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(null);+ // `{ harness, action }` while the SSE modal is open; null = closed.+ const [pendingAction, setPendingAction] = useState(null);+ const [refreshingId, setRefreshingId] = useState(null);+ // Keyed by harness id so one row's outcome cannot overwrite another's.+ const [refreshResults, setRefreshResults] = useState({});++ const load = useCallback(async ({ fresh = false } = {}) => {+ setError(null);+ // The server owns its own error toast suppression; this page renders the+ // failure inline with a Retry, so a thrown request must not blank the list.+ const data = await getHarnesses({ fresh, silent: true }).catch((err) => {+ setError(err?.message || 'Could not load harnesses.');+ return null;+ });+ if (data) setHarnesses(Array.isArray(data.harnesses) ? data.harnesses : []);+ setLoading(false);+ }, []);++ useEffect(() => { load(); }, [load]);++ const handleRefreshModels = async (harness) => {+ setRefreshingId(harness.id);+ const result = await refreshHarnessModels(harness.id, { silent: true })+ .then((data) => ({+ ok: true,+ message: `${data.models.length} models from ${harness.command} → ${plural(data.updated.length, 'provider')} updated.`,+ }))+ .catch((err) => ({ ok: false, message: err?.message || 'Could not read the model list.' }));+ setRefreshResults((prev) => ({ ...prev, [harness.id]: result }));+ setRefreshingId(null);+ // Deliberately no reload: the refresh writes `models` and `defaultModel`,+ // and this page shows neither — the banner above already reports what+ // changed. Re-reading would cost a probe sweep to render the same rows.+ };++ return (+ <div className="mx-auto max-w-4xl space-y-4">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <p className="max-w-2xl text-sm text-gray-400">+ The coding-agent CLIs and TUIs this install drives. Install, update, or remove one here,+ and refresh the model list a harness reports so the providers that use it offer the right models.+ </p>+ <button+ type="button"+ onClick={() => load({ fresh: true })}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-port-border px-3 py-1.5 text-xs font-medium text-gray-200 hover:border-port-accent hover:text-white"+ >+ <RefreshCw className="h-3.5 w-3.5" /> Re-check+ </button>+ </div>++ {loading && (+ <div className="flex items-center gap-2 text-sm text-gray-400">+ <Loader2 className="h-4 w-4 animate-spin" /> Loading harnesses…+ </div>+ )}++ {error && !loading && (+ <Banner tone="error" icon={AlertTriangle}>+ <div className="flex items-center justify-between gap-3">+ <span>{error}</span>+ <button+ type="button"+ onClick={() => load({ fresh: true })}+ className="shrink-0 rounded-md border border-port-error/50 px-3 py-1 text-xs hover:bg-port-error/20"+ >+ Retry+ </button>+ </div>+ </Banner>+ )}++ {!loading && !error && (+ <div className="space-y-3">+ {harnesses.length === 0 && <p className="text-sm text-gray-500">No harnesses are registered.</p>}+ {harnesses.map((harness) => (+ <HarnessCard+ key={harness.id}+ harness={harness}+ onAction={(target, action) => setPendingAction({ harness: target, action })}+ onRefreshModels={handleRefreshModels}+ refreshing={refreshingId === harness.id}+ refreshResult={refreshResults[harness.id]}+ />+ ))}+ </div>+ )}++ {/* Install, update and remove all stream through the shared modal — one+ child, one single-flight guard, and closing the modal cancels the run. */}+ <RuntimeInstallModal+ open={!!pendingAction}+ runtime={pendingAction?.harness?.id}+ label={pendingAction?.harness?.label}+ title={pendingAction ? ACTION_COPY[pendingAction.action].title : undefined}+ description={pendingAction ? ACTION_COPY[pendingAction.action].description : undefined}+ installUrlBase="/api/harnesses/action"+ params={pendingAction ? { action: pendingAction.action } : undefined}+ streamMethod="POST"+ onClose={() => setPendingAction(null)}+ // `load()`, not `load({ fresh: true })`: the stream already re-probed the+ // acted-on harness with `fresh` on the server and wrote that into the+ // status cache, and clicking Install cannot have changed what npm has+ // published — a fresh read here would spend five registry round trips to+ // render identical numbers.+ onComplete={() => { setPendingAction(null); load(); }}+ />+ </div>+ );+}diff --git a/client/src/components/models/HarnessesTab.test.jsx b/client/src/components/models/HarnessesTab.test.jsxnew file mode 100644index 0000000000..0f8fb87aae--- /dev/null+++ b/client/src/components/models/HarnessesTab.test.jsx@@ -0,0 +1,151 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import HarnessesTab from './HarnessesTab';++const getHarnesses = vi.fn();+const refreshHarnessModels = vi.fn();+vi.mock('../../services/api', () => ({+ getHarnesses: (...a) => getHarnesses(...a),+ refreshHarnessModels: (...a) => refreshHarnessModels(...a),+}));++// Stub the shared install modal — the real one opens a stream. Assert only the+// runtime and action it was opened with, which is the whole contract this page+// has with it.+vi.mock('../install/RuntimeInstallModal', () => ({+ default: ({ open, runtime, params, title, onComplete }) => (open ? (+ <div data-testid="install-modal">+ {title} · {runtime} · {params?.action}+ <button type="button" data-testid="complete" onClick={onComplete}>complete</button>+ </div>+ ) : null),+}));++const harness = (overrides = {}) => ({+ id: 'opencode',+ label: 'OpenCode CLI',+ command: 'opencode',+ installed: true,+ version: '1.18.27',+ latestVersion: '1.18.27',+ updateAvailable: false,+ updatable: true,+ removable: true,+ listsModels: true,+ installable: true,+ blockedReason: null,+ package: 'opencode-ai',+ docsUrl: 'https://example.invalid/docs',+ providers: [{ id: 'opencode-zen-cli', name: 'OpenCode Zen CLI', type: 'cli', enabled: true, usesHarnessCatalog: true }],+ ...overrides,+});++beforeEach(() => {+ vi.clearAllMocks();+ getHarnesses.mockResolvedValue({ harnesses: [harness()] });+});++describe('HarnessesTab', () => {+ it('shows the installed and latest versions', async () => {+ render(<HarnessesTab />);+ expect(await screen.findByText('OpenCode CLI')).toBeInTheDocument();+ expect(screen.getByText(/Installed 1\.18\.27/)).toBeInTheDocument();+ expect(screen.getByText(/Latest 1\.18\.27/)).toBeInTheDocument();+ });++ it('flags a stale install and still offers Update on a current one', async () => {+ getHarnesses.mockResolvedValue({ harnesses: [harness({ updateAvailable: true, latestVersion: '1.19.0' })] });+ render(<HarnessesTab />);+ expect(await screen.findByText('Update available')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /Update/ })).toBeInTheDocument();+ });++ // A version the banner could not parse must not read as "out of date" — the+ // row says what it knows and nothing more.+ it('says version unknown rather than implying staleness', async () => {+ getHarnesses.mockResolvedValue({ harnesses: [harness({ version: null, latestVersion: null })] });+ render(<HarnessesTab />);+ expect(await screen.findByText(/version unknown/)).toBeInTheDocument();+ expect(screen.queryByText('Update available')).not.toBeInTheDocument();+ });++ it('opens the shared stream modal with the chosen action', async () => {+ render(<HarnessesTab />);+ fireEvent.click(await screen.findByRole('button', { name: /Update/ }));+ expect(await screen.findByTestId('install-modal')).toHaveTextContent('opencode · update');+ });++ it('offers Install, not Update, when the harness is missing', async () => {+ getHarnesses.mockResolvedValue({ harnesses: [harness({ installed: false, version: null })] });+ render(<HarnessesTab />);+ expect(await screen.findByRole('button', { name: /Install/ })).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /Update/ })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /Refresh models/ })).not.toBeInTheDocument();+ });++ it('disables Install and explains why when the host cannot run one', async () => {+ getHarnesses.mockResolvedValue({ harnesses: [harness({+ installed: false, installable: false, blockedReason: 'npm is not on PortOS\'s PATH.',+ })] });+ render(<HarnessesTab />);+ expect(await screen.findByRole('button', { name: /Install/ })).toBeDisabled();+ expect(screen.getByText(/npm is not on PortOS/)).toBeInTheDocument();+ });++ // Removing a harness takes providers offline, so it asks first — inline, per+ // the no-`window.confirm` convention.+ it('confirms a removal inline before opening the stream', async () => {+ render(<HarnessesTab />);+ fireEvent.click(await screen.findByRole('button', { name: /Remove/ }));+ expect(screen.queryByTestId('install-modal')).not.toBeInTheDocument();+ expect(screen.getByText(/1 provider use/)).toBeInTheDocument();++ // Two "Remove" buttons are on screen once the row opens (the trigger and the+ // confirm) — take the one inside the confirmation row.+ const [, confirm] = screen.getAllByRole('button', { name: 'Remove' });+ fireEvent.click(confirm);+ expect(await screen.findByTestId('install-modal')).toHaveTextContent('opencode · uninstall');+ });++ it('reports how many providers a model refresh updated, without re-reading the list', async () => {+ refreshHarnessModels.mockResolvedValue({ models: ['opencode/a', 'opencode/b'], updated: ['opencode-zen-cli'] });+ render(<HarnessesTab />);++ fireEvent.click(await screen.findByRole('button', { name: /Refresh models/ }));++ expect(await screen.findByText(/2 models from opencode → 1 provider updated/)).toBeInTheDocument();+ // The refresh writes `models`/`defaultModel`; this page shows neither, so a+ // reload would spend a probe sweep to render identical rows.+ expect(getHarnesses).toHaveBeenCalledTimes(1);+ });++ it('re-reads the list after a lifecycle action, without forcing a registry read', async () => {+ render(<HarnessesTab />);+ fireEvent.click(await screen.findByRole('button', { name: /Update/ }));+ fireEvent.click(screen.getByTestId('complete'));++ // `fresh` bypasses the npm-registry cache too, and clicking Update cannot+ // have changed what npm has published.+ await waitFor(() => expect(getHarnesses).toHaveBeenCalledTimes(2));+ expect(getHarnesses).toHaveBeenLastCalledWith(expect.objectContaining({ fresh: false }));+ });++ it('renders a refusal reason verbatim instead of a generic failure', async () => {+ refreshHarnessModels.mockRejectedValue(new Error('Sign in to OpenCode CLI in a terminal.'));+ render(<HarnessesTab />);++ fireEvent.click(await screen.findByRole('button', { name: /Refresh models/ }));++ expect(await screen.findByText('Sign in to OpenCode CLI in a terminal.')).toBeInTheDocument();+ });++ it('renders a load failure with a retry', async () => {+ getHarnesses.mockRejectedValue(new Error('Could not reach the server.'));+ render(<HarnessesTab />);+ expect(await screen.findByText('Could not reach the server.')).toBeInTheDocument();++ getHarnesses.mockResolvedValue({ harnesses: [harness()] });+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByText('OpenCode CLI')).toBeInTheDocument();+ });+});diff --git a/client/src/components/models/ModelsTabsHeader.jsx b/client/src/components/models/ModelsTabsHeader.jsxindex e93bb185b2..1900247589 100644--- a/client/src/components/models/ModelsTabsHeader.jsx+++ b/client/src/components/models/ModelsTabsHeader.jsx@@ -26,6 +26,7 @@ export const TABS = [{ id: '3d', label: '3D', to: '/models/3d' },{ id: 'code-reviewers', label: 'Code Reviewers', to: '/models/code-reviewers' },{ id: 'embeddings', label: 'Embeddings', to: '/models/embeddings' },+ { id: 'harnesses', label: 'Harnesses', to: '/models/harnesses' },{ id: 'llms', label: 'LLMs', to: '/models/llms' },{ id: 'loras', label: 'LoRAs', to: '/models/loras' },{ id: 'media', label: 'Media', to: '/models/media' },diff --git a/client/src/components/providers/ProviderRuntimeStatus.jsx b/client/src/components/providers/ProviderRuntimeStatus.jsxindex 04532a9d44..7436042d12 100644--- a/client/src/components/providers/ProviderRuntimeStatus.jsx+++ b/client/src/components/providers/ProviderRuntimeStatus.jsx@@ -34,14 +34,23 @@ const ACTION_CLASS = 'inline-flex items-center gap-1 px-2 py-1 rounded bg-port-a*/export default function ProviderRuntimeStatus({ runtime, onInstall, optional = false, className = '' }) {if (!runtime) return null;- const { label, command, installed, installable, blockedReason, docsUrl, manageUrl } = runtime;+ const { label, command, installed, installable, blockedReason, docsUrl, manageUrl, version } = runtime;if (installed) {return (<div className={`flex flex-wrap items-center gap-2 ${className}`}><Pill tone="success" size="xs" icon={CheckCircle2} title={command ? `PortOS can run \`${command}\`.` : undefined}>- {label} installed+ {label} installed{version ? ` · ${version}` : ''}</Pill>+ {/* A card can say WHICH version is here, but not whether it is current or+ how to move it — that needs the registry read and the lifecycle+ actions the Harnesses page owns. Local-app runtimes keep their own+ `manageUrl` (Models → LLMs). */}+ {!manageUrl && (+ <Link to="/models/harnesses" className="text-[11px] text-gray-500 hover:text-port-accent">+ Manage harness+ </Link>+ )}</div>);}diff --git a/client/src/pages/Models.jsx b/client/src/pages/Models.jsxindex 812124cdfd..1fdb93eebd 100644--- a/client/src/pages/Models.jsx+++ b/client/src/pages/Models.jsx@@ -7,6 +7,7 @@ import ModelsTabsHeader from '../components/models/ModelsTabsHeader';import Image3dRuntimes from '../components/models/Image3dRuntimes';import ModelStatusTab from '../components/models/ModelStatusTab';import CodeReviewersTab from '../components/settings/CodeReviewersTab';+import HarnessesTab from '../components/models/HarnessesTab';import EmbeddingsTab from '../components/settings/EmbeddingsTab';import LocalModelAssessments from '../components/settings/LocalModelAssessments.jsx';import { LocalLlmTab } from '../components/settings/LocalLlmTab';@@ -30,6 +31,7 @@ const MediaModels = lazyWithReload(() => import('./MediaModels'));* - **3D** — image-to-3D runtime install/repair (TRELLIS.2, Pixal3D).* - **Code Reviewers** — the review-loop chain and its model/effort pins.* - **Embeddings** — the embedding model backing pgvector search.+ * - **Harnesses** — the coding-agent CLIs/TUIs, their versions and model lists.* - **LLMs** — focused runtime, model-library, and abuse-guard sub-routes.* - **LoRAs** — installed image/video adapters.* - **Media** — image/video checkpoints and the Hugging Face cache.@@ -50,6 +52,7 @@ const TAB_CONTENT = {'3d': Image3dRuntimes,'code-reviewers': CodeReviewersTab,embeddings: EmbeddingsTab,+ harnesses: HarnessesTab,llms: LocalLlmTab,loras: Loras,media: MediaModels,diff --git a/client/src/pages/Models.test.jsx b/client/src/pages/Models.test.jsxindex 18d88a6b9e..2283016974 100644--- a/client/src/pages/Models.test.jsx+++ b/client/src/pages/Models.test.jsx@@ -20,6 +20,7 @@ vi.mock('../components/settings/EmbeddingsTab', () => ({ default: () => <div>embvi.mock('../components/models/Image3dRuntimes', () => ({ default: () => <div>3d runtimes panel</div> }));vi.mock('../components/models/ModelStatusTab', () => ({ default: () => <div>status panel</div> }));vi.mock('../components/settings/CodeReviewersTab', () => ({ default: () => <div>code reviewers panel</div> }));+vi.mock('../components/models/HarnessesTab', () => ({ default: () => <div>harnesses panel</div> }));vi.mock('./Loras', () => ({ default: () => <div>loras panel</div> }));vi.mock('./LoraTraining', () => ({ default: () => <div>training panel</div> }));vi.mock('./MediaModels', () => ({ default: () => <div>media models panel</div> }));@@ -35,6 +36,7 @@ const PANEL_MARKER = {'3d': '3d runtimes panel','code-reviewers': 'code reviewers panel',embeddings: 'embeddings panel',+ harnesses: 'harnesses panel',llms: 'llms panel',loras: 'loras panel',media: 'media models panel',diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 790c846f6f..c8a3c87075 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -51,6 +51,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiHistory.js` | Historical logs / runs. || `apiLogs.js` | PM2 system logs: fetch a process's recent log tail (process list comes from `apiCommands.getProcessesList`). || `apiPorts.js` | Port scan/detect wrappers (no current UI callers; module kept for the catalog). |+| `apiHarnesses.js` | Coding-agent harness (CLI/TUI) inventory for Models → Harnesses: installed vs latest version, the providers riding on each, and the model-catalog refresh. Install/update/remove is an SSE stream driven by `RuntimeInstallModal`, not a call here. || `apiProviders.js` | AI provider configuration, plus provider-runtime (CLI) install readiness for the per-card Install buttons, and the Codex / ChatGPT-subscription account calls (`getCodexAccount`, `startCodexLogin`, `cancelCodexLogin`, `codexLogout`) — sign-in STATE only, never a token. || `apiPrompts.js` | Prompt Manager: stage templates, variables, and job-skill templates (providers list reuses `apiProviders.getProviders`). || `apiReferenceRepos.js` | Per-app reference-repo registry. |diff --git a/client/src/services/api.js b/client/src/services/api.jsindex d7c8ba13c8..aa8c274e52 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -9,6 +9,7 @@ export * from './apiWorkspaceContexts.js';export * from './apiReferenceRepos.js';export * from './apiPorts.js';export * from './apiScaffold.js';+export * from './apiHarnesses.js';export * from './apiProviders.js';export * from './apiPrompts.js';export * from './apiRuns.js';diff --git a/client/src/services/apiHarnesses.js b/client/src/services/apiHarnesses.jsnew file mode 100644index 0000000000..4b3b792cff--- /dev/null+++ b/client/src/services/apiHarnesses.js@@ -0,0 +1,31 @@+/**+ * Harnesses — the coding-agent CLIs/TUIs PortOS drives (Models → Harnesses).+ *+ * Read-side only. The install / update / remove stream is SSE and goes through+ * the shared `RuntimeInstallModal`, which owns its own fetch-stream reader —+ * pointing it at `/api/harnesses/action` with `runtime` and `action` in the+ * query string, the same shape every BYO-runtime installer already uses.+ */++import { request } from './apiCore.js';++/**+ * Every harness with its installed version, the latest published version, and+ * the provider records riding on it.+ *+ * `fresh` bypasses both the runtime-status TTL and the npm-registry cache —+ * what the page's Refresh button sends, and what it re-reads after an action so+ * a just-installed version shows without waiting a cache out.+ */+export const getHarnesses = ({ fresh = false, ...options } = {}) =>+ request(`/harnesses${fresh ? '?fresh=1' : ''}`, options);++/**+ * Re-read one harness's own model catalog and write it to every provider that+ * draws from it. Resolves `{ models, updated }`; rejects with the server's+ * reason when the harness cannot list models or is signed out.+ */+export const refreshHarnessModels = (id, options) => request(+ `/harnesses/models/refresh?runtime=${encodeURIComponent(id)}`,+ { method: 'POST', ...options },+);diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.jsindex c438375088..91f3f47952 100644--- a/client/src/utils/providers.test.js+++ b/client/src/utils/providers.test.js@@ -1132,6 +1132,12 @@ describe('supportsModelRefresh', () => {'opencode-orcarouter', 'opencode-orcarouter-tui','opencode-sglang', 'opencode-sglang-tui','opencode-vllm', 'opencode-vllm-tui',+ // The Zen API record is an ordinary OpenAI-compatible endpoint. Its CLI/TUI+ // wrappers are deliberately ABSENT: they carry no namespace marker, which+ // is what makes OpenCode resolve `opencode/*` through its own built-in+ // provider — nothing here can enumerate that, and Models → Harnesses+ // ("Refresh models") is where their catalog comes from instead.+ 'opencode-zen','openrouter', 'orcarouter',]);});diff --git a/data.reference/providers.json b/data.reference/providers.jsonindex c840b77e9c..dbfa649d8a 100644--- a/data.reference/providers.json+++ b/data.reference/providers.json@@ -490,6 +490,55 @@"tuiPromptDelayMs": 2500,"tuiIdleTimeoutMs": 180000},+ "opencode-zen": {+ "id": "opencode-zen",+ "name": "OpenCode Zen",+ "type": "api",+ "endpoint": "https://opencode.ai/zen/v1",+ "apiKey": "",+ "models": ["claude-opus-5", "claude-sonnet-5", "claude-haiku-4-5", "gpt-5.6-sol", "gpt-5.5", "grok-4.6", "kimi-k3", "qwen3.6-plus", "big-pickle", "deepseek-v4-flash-free"],+ "defaultModel": "claude-sonnet-5",+ "lightModel": "claude-haiku-4-5",+ "mediumModel": "claude-sonnet-5",+ "heavyModel": "claude-opus-5",+ "timeout": 300000,+ "enabled": false,+ "envVars": {},+ "secretEnvVars": []+ },+ "opencode-zen-cli": {+ "id": "opencode-zen-cli",+ "name": "OpenCode Zen CLI",+ "type": "cli",+ "command": "opencode",+ "args": ["run"],+ "models": ["opencode/big-pickle", "opencode/ling-3.0-flash-fin-free", "opencode/mimo-v2.5-free", "opencode/muse-spark-1.2-contributor-free", "opencode/muse-spark-1.3-contributor-free", "opencode/nemotron-3-ultra-free", "opencode/nemotron-3.5-lightning-free"],+ "defaultModel": "opencode/big-pickle",+ "timeout": 600000,+ "enabled": false,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\"}"+ },+ "secretEnvVars": ["OPENCODE_API_KEY"],+ "headlessArgs": []+ },+ "opencode-zen-tui": {+ "id": "opencode-zen-tui",+ "name": "OpenCode Zen TUI",+ "type": "tui",+ "command": "opencode",+ "args": [],+ "models": ["opencode/big-pickle", "opencode/ling-3.0-flash-fin-free", "opencode/mimo-v2.5-free", "opencode/muse-spark-1.2-contributor-free", "opencode/muse-spark-1.3-contributor-free", "opencode/nemotron-3-ultra-free", "opencode/nemotron-3.5-lightning-free"],+ "defaultModel": "opencode/big-pickle",+ "timeout": 600000,+ "enabled": false,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\"}"+ },+ "secretEnvVars": ["OPENCODE_API_KEY"],+ "tuiPromptDelayMs": 2500,+ "tuiIdleTimeoutMs": 180000+ },"antigravity-tui": {"id": "antigravity-tui","name": "Antigravity TUI",diff --git a/docs/API.md b/docs/API.mdindex 73dfef6915..0951616788 100644--- a/docs/API.md+++ b/docs/API.md@@ -125,6 +125,16 @@ own wire contract in [FEDERATED_MEDIA_PROVIDERS.md](./FEDERATED_MEDIA_PROVIDERS.| GET | `/providers/opencode/installation` | **Legacy alias**, kept so a stale client bundle still renders: `{ installed, npmAvailable }` for the `opencode` runtime. New code uses `/providers/runtimes`. || POST | `/providers/opencode/install` | **Legacy alias** for `/providers/runtimes/install?runtime=opencode`. |+### Harnesses++The coding-agent CLIs/TUIs PortOS drives (`opencode`, `claude`, `codex`, `agy`, `grok`, `kimi`, `cursor-agent`), managed as things in their own right rather than as a footnote on a provider card. Backs **Models → Harnesses**. Every response carries booleans, versions, and labels — never a resolved filesystem path, which would disclose the host account name.++| Method | Endpoint | Description |+|--------|----------|-------------|+| GET | `/harnesses?fresh=1` | Every harness with its installed version, the latest published version (npm-backed rows only), whether an update is available, which lifecycle actions it supports, and the provider records riding on it. `version`/`latestVersion` are `null` for NOT KNOWN, never `0.0.0` — `updateAvailable` is set only on a definite "installed < latest", so an offline host shows no false staleness badge. `fresh=1` bypasses both the 60s runtime-status TTL and the 6h registry cache. |+| POST | `/harnesses/action?runtime=<id>&action=install|update|uninstall` | Run one lifecycle action, streaming the child's output as SSE. `action` defaults to `install`. Update prefers the vendor's OWN updater (`opencode upgrade`, `claude update`) — the only path that refreshes the copy actually on PATH when the user installed it from Homebrew or a vendor script. Remove is offered only for npm-installed rows, and reports an error rather than success if the binary is still runnable afterwards. One action at a time process-wide (npm's global prefix is one directory); closing the stream cancels the child. Both values are table keys — nothing from the request reaches a shell word. |+| POST | `/harnesses/models/refresh?runtime=<id>` | Re-read a harness's own model catalog (`opencode models`, `agy models`, `grok models`) and write it to every provider that draws from that catalog — i.e. a wrapper with no local-runtime marker and no `gatewayBacked`, since a gateway- or Ollama-backed wrapper serves ids the harness never lists. Answers `{ ok, models, updated }`. A probe that runs but parses to nothing is a **409**, not an empty write: a signed-out CLI must not blank every picker. |+### AI Runs| Method | Endpoint | Description |@@ -709,6 +719,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom| `/api/browser` | Managed Chromium || `/api/creative-commission` | Creative commissions || `/api/midi-runtime` | MIDI runtime |+| `/api/harnesses` | Coding-agent CLI/TUI harness lifecycle |## WebSocket Eventsdiff --git a/scripts/migrations/336-opencode-zen-providers.js b/scripts/migrations/336-opencode-zen-providers.jsnew file mode 100644index 0000000000..50f395005c--- /dev/null+++ b/scripts/migrations/336-opencode-zen-providers.js@@ -0,0 +1,130 @@+/**+ * Ship disabled OpenCode Zen presets to existing installs.+ *+ * Every shipped OpenCode preset until now fronted something ELSE — a local+ * Ollama/vLLM/SGLang daemon, or a hosted gateway (OrcaRouter, OpenRouter). None+ * of them ran OpenCode on the models OpenCode itself ships with, so an install+ * that had the CLI on PATH still had no provider that used it out of the box.+ *+ * These three close that gap:+ * - `opencode-zen` — the OpenCode Zen HTTP API (an OpenAI-compatible+ * endpoint), for direct PortOS calls.+ * - `opencode-zen-cli` — headless `opencode run` on the harness's own catalog.+ * - `opencode-zen-tui` — the same, driven through the TUI.+ *+ * The two wrappers deliberately carry NO `gatewayBacked` / `*Backed` marker:+ * that absence is what tells `getOpencodeLocalProviderNamespace` there is no+ * custom provider entry to declare, so OpenCode resolves `opencode/*` models+ * through its own built-in provider and its own stored credential. It is also+ * what makes them the targets of the Harnesses page's model refresh — see+ * `usesHarnessCatalog` in `server/services/harnesses.js`.+ *+ * The seeded model list is OpenCode Zen's free tier, so a fresh install has+ * something runnable before any key is stored; Models → Harnesses → Refresh+ * models replaces it with whatever `opencode models` reports for the account+ * actually signed in.+ *+ * Kept in lockstep with data.reference/providers.json and+ * server/lib/aiToolkit/defaults/providers.sample.json. Later default changes+ * require a new migration.+ */++import { makeProviderSeedMigration } from './_lib.js';++// The API record's wire address. The CLI/TUI wrappers deliberately carry NO+// `endpoint`, matching every other harness-native record (`grok-cli`, `codex`,+// `cursor-cli`, `claude-code`): they declare no OpenCode provider entry, so+// nothing would read one, and a field that looks load-bearing and isn't is+// worse than an absent one. Only a gateway-backed wrapper mirrors its+// gateway's `baseURL` there.+const ZEN_ENDPOINT = 'https://opencode.ai/zen/v1';++// The unattended posture every seeded OpenCode record declares. It is the WHOLE+// config for these two: with no namespace there is no provider entry to declare+// and no key to inject, and `buildOpencodeEnvVars` preserves this as the base+// while pinning `small_model` to the model the run was dispatched with.+const OPENCODE_CONFIG_CONTENT = '{"permission":"allow"}';++// The harness's own namespaced spelling — exactly what `opencode models` prints+// and what `opencode --model` takes. These records declare no OpenCode provider+// entry, so nothing prefixes the id at spawn time and it must be stored whole.+const CLI_MODELS = [+ 'opencode/big-pickle',+ 'opencode/ling-3.0-flash-fin-free',+ 'opencode/mimo-v2.5-free',+ 'opencode/muse-spark-1.2-contributor-free',+ 'opencode/muse-spark-1.3-contributor-free',+ 'opencode/nemotron-3-ultra-free',+ 'opencode/nemotron-3.5-lightning-free',+];+const CLI_DEFAULT = 'opencode/big-pickle';++// The HTTP API takes BARE ids — there is no OpenCode namespace on the wire.+const API_MODELS = [+ 'claude-opus-5',+ 'claude-sonnet-5',+ 'claude-haiku-4-5',+ 'gpt-5.6-sol',+ 'gpt-5.5',+ 'grok-4.6',+ 'kimi-k3',+ 'qwen3.6-plus',+ 'big-pickle',+ 'deepseek-v4-flash-free',+];++const OPENCODE_ZEN_API = {+ id: 'opencode-zen',+ name: 'OpenCode Zen',+ type: 'api',+ endpoint: ZEN_ENDPOINT,+ apiKey: '',+ models: API_MODELS,+ defaultModel: 'claude-sonnet-5',+ lightModel: 'claude-haiku-4-5',+ mediumModel: 'claude-sonnet-5',+ heavyModel: 'claude-opus-5',+ timeout: 300000,+ enabled: false,+ envVars: {},+ secretEnvVars: [],+};++const OPENCODE_ZEN_CLI = {+ id: 'opencode-zen-cli',+ name: 'OpenCode Zen CLI',+ type: 'cli',+ command: 'opencode',+ args: ['run'],+ models: CLI_MODELS,+ defaultModel: CLI_DEFAULT,+ timeout: 600000,+ enabled: false,+ envVars: { OPENCODE_CONFIG_CONTENT },+ // Named, not stored: OpenCode holds its own Zen credential after+ // `opencode auth login`, and an install that would rather hand it over+ // explicitly fills this in from the provider editor.+ secretEnvVars: ['OPENCODE_API_KEY'],+ headlessArgs: [],+};++const OPENCODE_ZEN_TUI = {+ id: 'opencode-zen-tui',+ name: 'OpenCode Zen TUI',+ type: 'tui',+ command: 'opencode',+ args: [],+ models: CLI_MODELS,+ defaultModel: CLI_DEFAULT,+ timeout: 600000,+ enabled: false,+ envVars: { OPENCODE_CONFIG_CONTENT },+ secretEnvVars: ['OPENCODE_API_KEY'],+ tuiPromptDelayMs: 2500,+ tuiIdleTimeoutMs: 180000,+};++export default makeProviderSeedMigration({+ label: 'OpenCode Zen',+ defs: [OPENCODE_ZEN_API, OPENCODE_ZEN_CLI, OPENCODE_ZEN_TUI],+});diff --git a/scripts/migrations/336-opencode-zen-providers.test.js b/scripts/migrations/336-opencode-zen-providers.test.jsnew file mode 100644index 0000000000..c4e4e50de6--- /dev/null+++ b/scripts/migrations/336-opencode-zen-providers.test.js@@ -0,0 +1,95 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './336-opencode-zen-providers.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 336 — OpenCode Zen providers', () => {+ let rootDir;+ let providersPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-336-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ providersPath = join(rootDir, 'data/providers.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('adds the three disabled presets without changing the active provider', async () => {+ writeJson(providersPath, {+ activeProvider: 'claude-code',+ providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },+ });++ await migration.up({ rootDir });+ const out = readJson(providersPath);++ expect(out.providers['opencode-zen']).toMatchObject({+ type: 'api',+ endpoint: 'https://opencode.ai/zen/v1',+ apiKey: '',+ enabled: false,+ });+ expect(out.providers['opencode-zen-cli']).toMatchObject({ type: 'cli', command: 'opencode', enabled: false });+ expect(out.providers['opencode-zen-tui']).toMatchObject({ type: 'tui', command: 'opencode', enabled: false });+ expect(out.activeProvider).toBe('claude-code');+ });++ it('carries no backend marker, so the harness catalog owns these records', async () => {+ // The absence is load-bearing: a `*Backed` / `gatewayBacked` marker would+ // make OpenCode declare a custom provider entry and would exclude the+ // record from the Harnesses page's model refresh.+ writeJson(providersPath, { providers: {} });+ await migration.up({ rootDir });+ const out = readJson(providersPath);++ for (const id of ['opencode-zen-cli', 'opencode-zen-tui']) {+ const record = out.providers[id];+ expect(record.gatewayBacked).toBeUndefined();+ expect(record.ollamaBacked).toBeUndefined();+ expect(record.orcarouterBacked).toBeUndefined();+ // No `endpoint` either: these declare no OpenCode provider entry, so+ // nothing would read one — matching every other harness-native record.+ expect(record.endpoint).toBeUndefined();+ // The only thing the config declares is the unattended posture — no+ // provider entry, no key.+ expect(JSON.parse(record.envVars.OPENCODE_CONFIG_CONTENT)).toEqual({ permission: 'allow' });+ }+ });++ it('stores CLI models namespaced and API models bare', async () => {+ writeJson(providersPath, { providers: {} });+ await migration.up({ rootDir });+ const out = readJson(providersPath);++ // Nothing prefixes the id at spawn time for a namespace-less record, so the+ // stored spelling has to be the one `opencode --model` accepts.+ for (const id of out.providers['opencode-zen-cli'].models) expect(id.startsWith('opencode/')).toBe(true);+ expect(out.providers['opencode-zen-cli'].defaultModel).toBe('opencode/big-pickle');+ // The HTTP endpoint has no namespace on the wire.+ for (const id of out.providers['opencode-zen'].models) expect(id).not.toContain('/');+ expect(out.providers['opencode-zen'].models).toContain(out.providers['opencode-zen'].defaultModel);+ });++ it('preserves an existing OpenCode Zen record and its key', async () => {+ const existing = { id: 'opencode-zen', name: 'My Zen', type: 'api', apiKey: 'sk-zen-example', enabled: true };+ writeJson(providersPath, { providers: { 'opencode-zen': existing } });++ await migration.up({ rootDir });+ expect(readJson(providersPath).providers['opencode-zen']).toEqual(existing);+ });++ it('is a no-op on re-run', async () => {+ writeJson(providersPath, { activeProvider: 'claude-code', providers: {} });++ await migration.up({ rootDir });+ const first = readFileSync(providersPath, 'utf-8');+ await migration.up({ rootDir });+ expect(readFileSync(providersPath, 'utf-8')).toBe(first);+ });+});diff --git a/server/index.js b/server/index.jsindex 10da561e29..7c5a6fc073 100644--- a/server/index.js+++ b/server/index.js@@ -152,6 +152,7 @@ import openclawRoutes from './routes/openclaw.js';import sharingRoutes from './routes/sharing.js';import roundsRoutes from './routes/rounds.js';import midiRuntimeRoutes from './routes/midiRuntime.js';+import harnessRoutes from './routes/harnesses.js';import peerSyncRoutes from './routes/peerSync.js';import askRoutes from './routes/ask.js';import remoteDesktopRoutes from './routes/remoteDesktop.js';@@ -410,6 +411,7 @@ app.use('/api/openclaw', openclawRoutes);app.use('/api/sharing', sharingRoutes);app.use('/api/rounds', roundsRoutes);app.use('/api/midi-runtime', midiRuntimeRoutes);+app.use('/api/harnesses', harnessRoutes);app.use('/api/peer-sync', peerSyncRoutes);app.use('/api/ask', askRoutes);diff --git a/server/lib/README.md b/server/lib/README.mdindex 8cf6f2b37a..1aee901fe2 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -174,6 +174,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `credentialRegistry.js` | Pure catalog of PortOS credentials (`CREDENTIALS`, `CREDENTIAL_IDS`, `CREDENTIAL_TIERS`) — one entry per key/token an install can use (`id`, `label`, `unlocks`, `tier`, `getUrl`, `envVars`, `settingsPath`, `configurePath`, optional `feature`). Sits beside `instanceFeatureRegistry.js` so the two lists stay greppable together. Runtime resolution (settings / repo `.env` / inherited `process.env` / CLI / instance config) lives in `services/credentialInventory.js`. The Settings > Credentials page never receives a value or masked prefix. || `instanceFeatureRegistry.js` | The registry of optional per-install features (`INSTANCE_FEATURES`, `INSTANCE_FEATURE_IDS`, `APP_FEATURE_IDS`) — pure data, so `validation.js` derives its feature schemas from it and `navManifest.js` can be checked against it without a service→lib inversion. Runtime resolution (stored override → auto-detection → `defaultEnabled`) lives in `services/instanceFeatures.js`. A feature id tagged on a nav entry hides that page from ⌘K and the sidebar when the feature is off. || `providerFamilies.js` | Subscription-quota FAMILY identity — `PROVIDER_FAMILIES` (`{ id, label, matches }` for claude/codex/agy/grok), `PROVIDER_FAMILY_IDS`, `familyLabel`, `familyForProvider(config)` → family id or null (local-runtime wrappers and API-only providers belong to none). The pure half of the registry `services/providerUsage.js` attaches quota `fetch`ers to, so cost attribution and route validation can ask "which plan is this provider on?" without importing the PTY-scrape graph. Distinct from `providerVendors.js`, which is argv-shaped and includes vendors with no subscription quota. |+| `harnessOutput.js` | Parsers for what a coding-agent HARNESS prints about itself: `parseHarnessVersion(stdout)` (the one semver run in a `--version` banner, `null` when unparseable), `compareHarnessVersions(a, b)` (the null-guarding wrapper around `versionUtils.js#compareSemver` — `null` when either side is unparseable, so a version that did not parse never reads as "out of date"), `parseHarnessModels(harnessId, stdout)` + `HARNESS_MODEL_PARSER_IDS` (OpenCode's `provider/model` lines and Grok's bulleted list are parsed here; Antigravity and Cursor DELEGATE to `antigravity.js#parseAntigravityModelList` / `aiToolkit/internal/cursor.js#parseCursorModelList`, which the provider-card refresh has used for far longer), `MAX_MODELS`, and `parseNpmLatestVersion`. Pure: the service layer runs the child and hands the captured stdout here, so the vendor output shapes are pinned by table-driven tests instead of by running six real binaries in CI. Model ids come back in the exact spelling `--model` takes — namespaces kept where the vendor keeps them. Consumed by `services/providerRuntimeInstaller.js` and `services/harnesses.js`. || `providerGateways.js` | `PROVIDER_GATEWAYS` — one row per hosted OpenAI-compatible gateway an OpenCode CLI/TUI wrapper can front-end (`orcarouter`, `openrouter`), plus `PROVIDER_GATEWAY_IDS`, `gatewayById`, `isGatewayNamespace(ns)` and `gatewayForProvider(config)` → row or null. Each row's `id` is simultaneously the OpenCode provider namespace, the `gatewayBacked` marker value, and the id of the sibling `api` record that owns the key — so the sibling lookup is `providers[gateway.id]` and an OrcaRouter key can never satisfy an OpenRouter wrapper. Replaces the `orcarouterBacked` boolean + literal `'orcarouter'` that had been hand-copied across ~15 server and client files (namespace resolution, the OpenCode config builder, both zod schemas, the model-fetcher table, the sibling-key attach, the prerequisite check, and the two "not a local runtime" carve-outs in `cliChildEnv.js`/`localProviderRuntime.js`). Reads the legacy per-gateway boolean FOREVER, so stored records are never rewritten. Distinct from a local runtime (`ollamaBacked`, `vllmBacked`, …): remote, always authenticating, and no thinking toggle. Deliberately mirrored in `aiToolkit/internal/gateways.js` (the vendored toolkit may not import out) and `client/src/utils/providers.js` (the browser cannot import server code) — `providerGateways.parity.test.js` fails when the first two drift. Dependency-light: imports nothing. || `providerTranscriptUsage.js` | Parsers for the session files the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `parseGrokTurns`/`parseGrokChatHistory`/`decodeGrokSessionDir` (`~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/`), `parseAgyTranscript`/`parseAgyHistory` (`~/.gemini/antigravity-cli/`), `claudeProjectSlug`, `totalTranscriptTokens`. Each de-duplicates a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, Codex's `total_token_usage` is cumulative and repeated, grok's `turn_completed.usage` has shipped in both per-prompt and cumulative shapes (detected and delta'd, never summed raw) while its `_meta.totalTokens` is context occupancy and never billed. Antigravity writes no token fields at all, so its parser returns chars for the caller to estimate from. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. || `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring model ids under the namespace the provider's marker selects: a local runtime (`ollama` / `mtplx` / `llama` / `vllm` / `sglang`, bare ids) or a hosted gateway from `providerGateways.js` (`vendor/model` ids kept whole). Fixes --model rejection. Also attaches the key for a key-bearing namespace, and pins `small_model` to the run model for a gateway so OpenCode's own side calls (titles, summarization) can't land on its built-in default — a billed model the operator never chose. |@@ -277,7 +278,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `childProcess.js` | Drop-in `child_process` replacement that defaults every spawn to `windowsHide: true` — `spawn` / `spawnSync` / `fork` / `exec` / `execSync` / `execFile` / `execFileSync`, plus a `ChildProcess` re-export. **Server runtime code must import from here, never from `child_process` directly** (enforced by `childProcess.guards.test.js`): a console-less PM2 fork spawning a console child without `CREATE_NO_WINDOW` makes Windows hand the new console to Windows Terminal, which flashes a focus-stealing window. `exec`/`execFile` carry `util.promisify.custom` so `promisify(execFile)` still resolves to `{ stdout, stderr }`. An explicit `windowsHide: false` is respected. Background: `docs/WINDOWS_CONSOLE.md`. || `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `resolveWindowsExecutable`, `prepareWindowsSafeSpawn`, `prepareCliSpawn(command, args, env)` (composed resolve+wrap for a `spawn()`-safe pair), `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES`, `guardChildStdin(child)` (attach the no-op `stdin` `'error'` listener BEFORE any `stdin.write`/`stdin.end` — a child that dies before reading stdin makes the pipe emit `EPIPE`, and an unlistened stream `'error'` outside the Express request lifecycle takes the whole server process down; call it at every spawn that writes to a child's stdin) + `deliverChildStdin(child, payload, label)` (its other half: write-then-`end()` with a synchronously-throwing `write` caught, the pipe destroyed so a reading child sees EOF rather than hanging, and the failure logged so an empty-prompt run that exits 0 isn't filed as clean), `spawnFailureDetail(result, fallback)` (the most useful sentence from a failed result — prefers the spawn error, then a stderr line, then a stdout line that isn't bare JSON punctuation, because a `--json` CLI prints its payload to stdout even when it exits non-zero) — shared buffered-spawn machinery with capped stdout/stderr, timeout SIGTERM plus fire-and-forget SIGKILL escalation (`killGraceMs`, default 8s), Windows `.cmd`/`.bat` shim resolution, and `taskkill /T /F` tree-kill. `killProcessTree(child, signal, { processGroup })` takes the POSIX group down too when the child was spawned `detached` (Windows always tree-kills). A killable that is NOT a `ChildProcess` — a node-pty `IPty` TUI session — is killed through its own `.kill()`, with **no signal on Windows**: node-pty throws `Signals not supported on windows.` for any signal argument, so a signalled kill there killed nothing and threw past the caller. Used by `appBuilder.js`, `appUpdater.js`, the CoS agent spawners, and `setupScriptRunner.js`. || `setupScriptRunner.js` | `spawnSetupScript(envVars)` / `stopSetupScript(child)` / `SETUP_IMAGE_VIDEO_SCRIPT` — the one way to run `scripts/setup-image-video.sh` (shared by the Video Gen BYOV runtimes, the music engines and the MuScriptor venv). Runs it under `resolveBashBinary()` with a `toBashPath` script path, and on Windows presets the `PYTHON_BIN` the script would otherwise default to `python3` for. Cancel via `stopSetupScript`, which tree-kills so uv / pip / git die with bash. |-| `commandExists.js` | `commandExists(cmd, args = ['--version'], { timeoutMs = 5_000, env, cwd })` — does running `cmd args` succeed? A capability probe (`execFile`-based), not a PATH lookup like `processEnv.js`'s `whichFirst`; `env`/`cwd` let a caller check the exact child process configuration. Consolidates the two previously-private copies in `localLlm.js`/`ollamaManager.js`; callers probing a heavier CLI (e.g. `codeReview.js`'s reviewer-binary probe) pass a longer `timeoutMs`. |+| `commandExists.js` | `commandExists(cmd, args = ['--version'], { timeoutMs = 5_000, env, cwd })` — does running `cmd args` succeed? A capability probe (`execFile`-based), not a PATH lookup like `processEnv.js`'s `whichFirst`; `env`/`cwd` let a caller check the exact child process configuration. Consolidates the two previously-private copies in `localLlm.js`/`ollamaManager.js`; callers probing a heavier CLI (e.g. `codeReview.js`'s reviewer-binary probe) pass a longer `timeoutMs`. Sibling `commandOutput(cmd, args, opts)` runs the same probe but returns the trimmed stdout (or `null` when it could not run / exited non-zero), so a caller can read a `--version` banner or a `models` listing without spawning the same child twice. || `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `usesCreativeDirectorScratchCwd(task)` / `creativeDirectorScratchCwd(agentId)` / `removeCreativeDirectorScratchCwd(agentId)` / `resolveAgentCliCwd({ workspacePath, fallbackRoot, task, agentId })` — Creative Director no-worktree tasks get a per-agent scratch cwd under `os.tmpdir()/portos-cd-cwd/<id>` (outside the PortOS git tree) instead of the PortOS root, so native CLI AGENTS.md / CLAUDE.md discovery cannot walk up into the repo (#4650). `removeCreativeDirectorScratchCwd` is the matching finalize cleanup. `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every spawn that names its own cwd — the shared wrappers (`bufferedSpawn`, `spawnDetached`) already do, so their callers inherit it. `spawnCwd.test.js` discovers cwd-passing spawns across `server/` and fails on any that neither pins nor is listed exempt.| `commandSecurity.js` | Two allowlists, one parser. `validateCommand(cmd)` gates the OPERATOR-driven runner against `ALLOWED_COMMANDS` (+ `validatePm2Command(args)`, which rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateUnattendedCommand(cmd)` gates the UNATTENDED lane (Layered Intelligence `cmd` sources) against the far narrower `UNATTENDED_READONLY_COMMANDS` — read-only inspection binaries only, no `npx`/`node`/`python`/`pip`/`curl`/`wget`/`brew`, since those execute network code with no shell metacharacter — then applies a per-binary SUBCOMMAND gate to the multi-purpose survivors, so `git reset --hard` / `git commit`, `find -delete` / `-exec`, and `gh`/`glab` writes (`api -X POST`, `pr merge`) are rejected while `git log`, `find -name` and `gh pr list` pass. Both share one parse + `DANGEROUS_SHELL_CHARS` body. Mirrored by the `agentGuard/` PATH shim for agentic paths. || `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows has no double-fork (plain-spawn fallback), so its handle's `kill` delegates to `killProcessTree` (`taskkill /T /F`) — a cancel there takes the runner's children with it. Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart, `isDetachedRunning(controlDir, expectedProcess?)` with optional executable/argument validation for fixed-command control dirs, and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |diff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.jsonindex 29e2b96875..5e95d5ab39 100644--- a/server/lib/aiToolkit/defaults/providers.sample.json+++ b/server/lib/aiToolkit/defaults/providers.sample.json@@ -408,6 +408,55 @@"tuiPromptDelayMs": 2500,"tuiIdleTimeoutMs": 180000},+ "opencode-zen": {+ "id": "opencode-zen",+ "name": "OpenCode Zen",+ "type": "api",+ "endpoint": "https://opencode.ai/zen/v1",+ "apiKey": "",+ "models": ["claude-opus-5", "claude-sonnet-5", "claude-haiku-4-5", "gpt-5.6-sol", "gpt-5.5", "grok-4.6", "kimi-k3", "qwen3.6-plus", "big-pickle", "deepseek-v4-flash-free"],+ "defaultModel": "claude-sonnet-5",+ "lightModel": "claude-haiku-4-5",+ "mediumModel": "claude-sonnet-5",+ "heavyModel": "claude-opus-5",+ "timeout": 300000,+ "enabled": false,+ "envVars": {},+ "secretEnvVars": []+ },+ "opencode-zen-cli": {+ "id": "opencode-zen-cli",+ "name": "OpenCode Zen CLI",+ "type": "cli",+ "command": "opencode",+ "args": ["run"],+ "models": ["opencode/big-pickle", "opencode/ling-3.0-flash-fin-free", "opencode/mimo-v2.5-free", "opencode/muse-spark-1.2-contributor-free", "opencode/muse-spark-1.3-contributor-free", "opencode/nemotron-3-ultra-free", "opencode/nemotron-3.5-lightning-free"],+ "defaultModel": "opencode/big-pickle",+ "timeout": 600000,+ "enabled": false,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\"}"+ },+ "secretEnvVars": ["OPENCODE_API_KEY"],+ "headlessArgs": []+ },+ "opencode-zen-tui": {+ "id": "opencode-zen-tui",+ "name": "OpenCode Zen TUI",+ "type": "tui",+ "command": "opencode",+ "args": [],+ "models": ["opencode/big-pickle", "opencode/ling-3.0-flash-fin-free", "opencode/mimo-v2.5-free", "opencode/muse-spark-1.2-contributor-free", "opencode/muse-spark-1.3-contributor-free", "opencode/nemotron-3-ultra-free", "opencode/nemotron-3.5-lightning-free"],+ "defaultModel": "opencode/big-pickle",+ "timeout": 600000,+ "enabled": false,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\"}"+ },+ "secretEnvVars": ["OPENCODE_API_KEY"],+ "tuiPromptDelayMs": 2500,+ "tuiIdleTimeoutMs": 180000+ },"codex": {"id": "codex","name": "Codex CLI",diff --git a/server/lib/aiToolkit/internal/modelFetchers.test.js b/server/lib/aiToolkit/internal/modelFetchers.test.jsindex 60a7fe7e26..4775c658e9 100644--- a/server/lib/aiToolkit/internal/modelFetchers.test.js+++ b/server/lib/aiToolkit/internal/modelFetchers.test.js@@ -24,6 +24,12 @@ const SHIPPED_REFRESHABLE = [// Every hosted gateway refreshes through the same sibling `/models` probe —// one MODEL_FETCHERS row covers all of them (internal/gateways.js).'opencode-openrouter', 'opencode-openrouter-tui', 'openrouter',+ // OpenCode Zen's API record is an ordinary OpenAI-compatible endpoint, so it+ // refreshes through the same `/models` probe. Its CLI/TUI wrappers do NOT:+ // they carry no namespace marker at all, which is what makes OpenCode resolve+ // `opencode/*` through its own built-in provider — nothing here can enumerate+ // that, and Models → Harnesses ("Refresh models") is where it comes from.+ 'opencode-zen','opencode-vllm', 'opencode-vllm-tui',// SGLang publishes its served catalog through the same OpenAI-compatible// `/v1/models` contract as the vLLM pair, so its wrappers refresh too.@@ -36,6 +42,7 @@ const SHIPPED_REFRESHABLE = [const SHIPPED_NOT_REFRESHABLE = ['claude-code-tui', 'claude-code-tui-bedrock', 'codex', 'codex-tui','grok-cli', 'grok-tui', 'kimi-cli', 'kimi-tui',+ 'opencode-zen-cli', 'opencode-zen-tui',];describe('MODEL_FETCHERS — shipped catalog visibility is unchanged', () => {diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex d78e584336..d6ab449de7 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -59,6 +59,7 @@"/api/games","/api/git","/api/github",+ "/api/harnesses","/api/health","/api/history","/api/image-clean",@@ -7477,6 +7478,30 @@"server/routes/github.js"]},+ {+ "method": "GET",+ "path": "/api/harnesses",+ "mountPath": "/api/harnesses",+ "sources": [+ "server/routes/harnesses.js"+ ]+ },+ {+ "method": "POST",+ "path": "/api/harnesses/action",+ "mountPath": "/api/harnesses",+ "sources": [+ "server/routes/harnesses.js"+ ]+ },+ {+ "method": "POST",+ "path": "/api/harnesses/models/refresh",+ "mountPath": "/api/harnesses",+ "sources": [+ "server/routes/harnesses.js"+ ]+ },{"method": "GET","path": "/api/health/correlation",@@ -17455,9 +17480,9 @@}],"stats": {- "mounts": 146,- "operations": 2162,- "declarations": 2170,- "sourceFiles": 229+ "mounts": 147,+ "operations": 2165,+ "declarations": 2173,+ "sourceFiles": 230}}diff --git a/server/lib/commandExists.js b/server/lib/commandExists.jsindex 0ba6bb7d43..e5dc49c959 100644--- a/server/lib/commandExists.js+++ b/server/lib/commandExists.js@@ -3,6 +3,39 @@ import { promisify } from 'util';const execFileAsync = promisify(execFile);+/**+ * Run a bounded capability probe and return its trimmed stdout, or `null` when+ * the command could not run or exited non-zero.+ *+ * The child's stdin is closed immediately. `agy models` blocks on an open stdin+ * and prints NOTHING until it closes — with execFile's default pipe that is a+ * full timeout's hang ending in SIGTERM and empty output. (execFile ignores an+ * `stdio` option, so ending the stream is the way to do it.) Not every vendor+ * needs it, but it costs one FD close and makes every probe immune. Same+ * reasoning, and the same incident, as `_execCliModelList` in+ * `lib/aiToolkit/providers.js`.+ */+function probe(cmd, args, { timeoutMs, env, cwd, maxBuffer }) {+ const options = {+ timeout: timeoutMs,+ ...(env === undefined ? {} : { env }),+ ...(cwd === undefined ? {} : { cwd }),+ ...(maxBuffer === undefined ? {} : { maxBuffer }),+ };+ // Some spawn failures (notably ENOEXEC for a broken text shim on macOS)+ // are thrown synchronously by the child-process wrapper before it can+ // return a promise. Start the call in a microtask so those failures follow+ // the same null result as an ordinary rejected execFile promise.+ return Promise.resolve()+ .then(() => {+ const pending = execFileAsync(cmd, args, options);+ pending.child?.stdin?.end();+ return pending;+ })+ .then(({ stdout }) => String(stdout ?? '').trim())+ .catch(() => null);+}+/*** Does running `cmd args` succeed without error? A capability probe (not a* PATH lookup like `whichFirst` in processEnv.js) — it actually invokes the@@ -20,17 +53,25 @@ const execFileAsync = promisify(execFile);* @returns {Promise<boolean>}*/export async function commandExists(cmd, args = ['--version'], { timeoutMs = 5_000, env, cwd } = {}) {- const options = {- timeout: timeoutMs,- ...(env === undefined ? {} : { env }),- ...(cwd === undefined ? {} : { cwd }),- };- // Some spawn failures (notably ENOEXEC for a broken text shim on macOS)- // are thrown synchronously by the child-process wrapper before it can- // return a promise. Start the call in a microtask so those failures follow- // the same false result as an ordinary rejected execFile promise.- return Promise.resolve()- .then(() => execFileAsync(cmd, args, options))- .then(() => true)- .catch(() => false);+ return (await probe(cmd, args, { timeoutMs, env, cwd })) !== null;+}++/**+ * The stdout of `cmd args`, trimmed — or `null` when the command could not run+ * or exited non-zero. The output-returning sibling of {@link commandExists}:+ * same probe, same bounded timeout, but it hands back what the command SAID so+ * a caller can read a `--version` banner or a `models` listing instead of+ * re-spawning the same child twice to learn both.+ *+ * `null` is the NOT-KNOWN sentinel, distinct from `''` (ran, said nothing) —+ * the harness registry reads a null as "no version available", never as "out of+ * date".+ *+ * @param {string} cmd+ * @param {string[]} [args] - defaults to `['--version']`, the common probe+ * @param {{timeoutMs?: number, env?: object, cwd?: string, maxBuffer?: number}} [opts]+ * @returns {Promise<string|null>}+ */+export async function commandOutput(cmd, args = ['--version'], { timeoutMs = 5_000, env, cwd, maxBuffer } = {}) {+ return probe(cmd, args, { timeoutMs, env, cwd, maxBuffer });}diff --git a/server/lib/harnessOutput.js b/server/lib/harnessOutput.jsnew file mode 100644index 0000000000..2e0cea6e0a--- /dev/null+++ b/server/lib/harnessOutput.js@@ -0,0 +1,165 @@+/**+ * Parsers for what a coding-agent HARNESS prints about itself — its version+ * banner and its model catalog.+ *+ * A harness is the CLI/TUI binary a provider shells out to (`opencode`,+ * `claude`, `codex`, `agy`, `grok`, `kimi`, `cursor-agent`). PortOS could+ * already answer "is it on PATH?" (`services/providerRuntimeInstaller.js`); the+ * Harnesses page also needs "which version, and which models does THIS install+ * of it know about?" — and every vendor answers both in its own shape.+ *+ * Pure on purpose: no spawning, no filesystem, no network. The service layer+ * runs the child and hands the captured stdout here, which keeps the vendor+ * output shapes pinned by cheap table-driven tests instead of by running six+ * real binaries in CI.+ *+ * **Model ids come back in the exact spelling `--model` takes.** OpenCode names+ * its models `provider/model` and accepts that form verbatim, so the namespace+ * is KEPT; Antigravity and Grok name theirs bare and take them bare. Stripping+ * or adding a namespace here would produce a list the harness itself rejects.+ *+ * **A vendor whose stdout already has a parser DELEGATES to it.** Antigravity's+ * and Cursor's live in `antigravity.js` and `aiToolkit/internal/cursor.js`,+ * where the provider-card refresh has used them for far longer than this page+ * has existed. A second copy here would be a third and fourth transcription of+ * one vendor's output — and would have been wrong on arrival: the agy parser+ * accepts an older build's bare-id-per-line rows and drops the+ * `<configured-default>` sentinel, neither of which a fresh reading of today's+ * TAB-separated output would have known to do.+ */++import { parseAntigravityModelList } from './antigravity.js';+import { compareSemver } from './versionUtils.js';+import { parseCursorModelList } from './aiToolkit/internal/cursor.js';++/**+ * The first semver-looking token in a `--version` banner, or `null`.+ *+ * Every harness spells the banner differently — `1.18.27`, `2.1.259 (Claude+ * Code)`, `codex-cli 0.151.0`, `grok 1.0.13 (5e9a58528b76) [stable]` — and all+ * of them contain exactly one `x.y.z` run. Anchored on a word boundary so a+ * build hash (`5e9a58528b76`) or a date fragment inside a longer token cannot+ * be read as the version.+ *+ * `null` (not `''`) is the NOT-KNOWN sentinel: a harness whose banner we cannot+ * parse must not read as "version unknown, therefore out of date" — the+ * update-available comparison bails on a null on either side.+ *+ * @param {string|null|undefined} stdout+ * @returns {string|null}+ */+export function parseHarnessVersion(stdout) {+ if (typeof stdout !== 'string') return null;+ const match = stdout.match(/\b(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)\b/);+ return match ? match[1] : null;+}++/**+ * The null-guarding wrapper around {@link compareSemver}.+ *+ * The ORDERING is `versionUtils.js`'s job (prerelease precedence, build+ * metadata, the lot) — what is new here is the refusal: a version that did not+ * parse must yield `null`, not an ordering. `compareSemver` maps a+ * non-numeric segment to `NaN` and every NaN comparison to "equal", so feeding+ * it `'nightly'` would silently answer "same version" and a caller would render+ * a harness as current on no evidence. The caller renders "update available"+ * only for a definite `-1`.+ *+ * @param {string|null|undefined} a+ * @param {string|null|undefined} b+ * @returns {-1|0|1|null}+ */+export function compareHarnessVersions(a, b) {+ // Both sides must be a version this module would have accepted out of a+ // `--version` banner in the first place.+ const parsed = [a, b].map((v) => (typeof v === 'string' ? parseHarnessVersion(v.trim()) : null));+ if (parsed.some((v) => v === null)) return null;+ return compareSemver(parsed[0], parsed[1]);+}++/**+ * A line that is chatter rather than a model id.+ *+ * `agy models` prints `Fetching available models...` before its table and+ * `grok models` prints a sign-in banner plus a `Default model:` line — both on+ * stdout, interleaved with the real rows. Dropping a "model" whose id contains+ * whitespace or ends in a colon is enough to separate the two for every vendor+ * here without hand-listing each banner string.+ */+const isChatterLine = (line) => line === '' || line.endsWith(':') || line.endsWith('...') || /\s/.test(line);++/**+ * `opencode models` — one fully-qualified `provider/model` per line, no header.+ * The namespace is what `opencode --model` takes, so it is preserved.+ */+const parseOpencodeModels = (lines) => lines.filter((line) => !isChatterLine(line) && line.includes('/'));++/**+ * `grok models` — a sign-in banner, a `Default model: <id>` line, an `Available+ * models:` header, then bulleted rows: ` * grok-4.6 (default)` / ` - grok-4.5`.+ * Keep the bulleted rows only, dropping the bullet and the `(default)` marker,+ * so the `Default model:` line cannot be read as a model called `model:`.+ */+const parseGrokModels = (lines) => lines+ .filter((line) => /^[*-]\s/.test(line))+ .map((line) => line.replace(/^[*-]\s+/, '').replace(/\s*\(default\)\s*$/, '').trim())+ .filter((id) => id && !isChatterLine(id));++/**+ * One parser per harness whose binary can enumerate its own models. A vendor+ * absent from this table has no `models` subcommand, which the registry+ * declares by carrying no `modelsArgs` — the two are pinned together by+ * `providerRuntimeInstaller.test.js`.+ */+const MODEL_PARSERS = {+ opencode: parseOpencodeModels,+ grok: parseGrokModels,+ // Delegated — these two vendors' stdout shapes are already owned elsewhere.+ // Both take the raw stdout rather than the pre-split lines, so they are+ // adapted here instead of being called through the line pipeline.+ agy: (lines) => parseAntigravityModelList(lines.join('\n')),+ 'cursor-agent': (lines) => parseCursorModelList(lines.join('\n')),+};++/**+ * The harness ids {@link parseHarnessModels} can actually parse. Published so+ * the registry's `modelsArgs` rows and these parsers are pinned to each other:+ * a row claiming it can list models with no parser here would report an empty+ * catalog and refuse forever.+ */+export const HARNESS_MODEL_PARSER_IDS = Object.freeze(Object.keys(MODEL_PARSERS));++/** Upper bound on a parsed catalog, so a runaway vendor output cannot be stored wholesale. */+export const MAX_MODELS = 200;++/**+ * The model ids a harness reported, de-duplicated and in the order it listed+ * them (vendors sort newest-first, which is the order a picker wants).+ *+ * Returns `[]` for output that parsed to nothing — the caller distinguishes+ * "the probe never ran" from "it ran and found none" by whether it called this+ * at all, and refuses to overwrite a stored catalog with an empty result.+ *+ * @param {string} harnessId - the binary name (`opencode`, `agy`, `grok`)+ * @param {string|null|undefined} stdout+ * @returns {string[]}+ */+export function parseHarnessModels(harnessId, stdout) {+ const parse = Object.hasOwn(MODEL_PARSERS, harnessId) ? MODEL_PARSERS[harnessId] : null;+ if (!parse || typeof stdout !== 'string') return [];+ // Trailing whitespace goes unconditionally; a LEADING trim only on a row with+ // no tab, because a TAB-separated Antigravity row must keep its separator+ // intact while Grok's rows arrive indented under their header.+ const lines = stdout.split(/\r?\n/).map((line) => {+ const trimmed = line.replace(/\s+$/, '');+ return trimmed.includes('\t') ? trimmed : trimmed.trimStart();+ });+ // Every parser already drops blanks, so no second filter is needed here.+ return [...new Set(parse(lines))].slice(0, MAX_MODELS);+}++/**+ * `npm view <pkg> version` prints the bare version and nothing else, but a+ * registry warning can precede it on stdout. Reuse the banner parser.+ */+export const parseNpmLatestVersion = parseHarnessVersion;diff --git a/server/lib/harnessOutput.test.js b/server/lib/harnessOutput.test.jsnew file mode 100644index 0000000000..7ca65288c8--- /dev/null+++ b/server/lib/harnessOutput.test.js@@ -0,0 +1,135 @@+import { describe, it, expect } from 'vitest';+import {+ compareHarnessVersions,+ MAX_MODELS,+ parseHarnessModels,+ parseHarnessVersion,+} from './harnessOutput.js';++// Real banners, one per shipped harness — every vendor spells it differently+// and the parser has to survive all of them without a per-vendor branch.+describe('parseHarnessVersion', () => {+ it.each([+ ['1.18.27', '1.18.27'], // opencode+ ['2.1.259 (Claude Code)', '2.1.259'], // claude+ ['codex-cli 0.151.0', '0.151.0'], // codex+ ['1.1.25', '1.1.25'], // agy+ ['grok 1.0.13 (5e9a58528b76) [stable]', '1.0.13'], // grok — hash must not win+ ['0.32.0', '0.32.0'], // kimi+ ['2.0.0-beta.3', '2.0.0-beta.3'], // prerelease suffix kept+ ])('reads %j as %j', (banner, expected) => {+ expect(parseHarnessVersion(banner)).toBe(expected);+ });++ // `null` is NOT-KNOWN. Collapsing it to '0.0.0' would make every unparseable+ // banner read as "out of date" against any published version.+ it.each([null, undefined, '', 'no version here', '2026'])('returns null for %j', (input) => {+ expect(parseHarnessVersion(input)).toBeNull();+ });+});++describe('compareHarnessVersions', () => {+ it('orders numerically, not lexically', () => {+ // The whole point: '1.18.27' < '1.9.0' as strings, and > as versions.+ expect(compareHarnessVersions('1.18.27', '1.9.0')).toBe(1);+ expect(compareHarnessVersions('1.18.27', '1.19.0')).toBe(-1);+ expect(compareHarnessVersions('1.18.27', '1.18.27')).toBe(0);+ });++ // Prerelease precedence comes from `compareSemver`: someone on a beta with+ // the final published IS behind, and should see the update badge.+ it('orders a prerelease below its release', () => {+ expect(compareHarnessVersions('2.0.0-beta.3', '2.0.0')).toBe(-1);+ expect(compareHarnessVersions('2.0.0-beta.3', '2.0.0-beta.10')).toBe(-1);+ });++ it('ignores build metadata', () => {+ expect(compareHarnessVersions('2.0.0+abc', '2.0.0')).toBe(0);+ });++ // Both sides must be a version this module would have pulled out of a banner+ // in the first place — a two-segment string is not one, and answering an+ // ordering for it would be inventing the third segment.+ it('refuses a version it would not have parsed from a banner', () => {+ expect(compareHarnessVersions('2.1', '2.1.0')).toBeNull();+ });++ // An unparseable side must not decide "out of date" — the caller renders the+ // update badge only on a definite -1.+ it.each([[null, '1.0.0'], ['1.0.0', null], ['nightly', '1.0.0'], [undefined, undefined]])(+ 'returns null when a side is unparseable (%j, %j)',+ (a, b) => expect(compareHarnessVersions(a, b)).toBeNull(),+ );+});++describe('parseHarnessModels', () => {+ it('keeps the OpenCode namespace, which is what --model takes', () => {+ const stdout = 'opencode/big-pickle\nopencode/mimo-v2.5-free\nopencode/nemotron-3-ultra-free\n';+ expect(parseHarnessModels('opencode', stdout)).toEqual([+ 'opencode/big-pickle',+ 'opencode/mimo-v2.5-free',+ 'opencode/nemotron-3-ultra-free',+ ]);+ });++ it('takes the id column of Antigravity TAB rows and drops its preamble', () => {+ const stdout = [+ 'Fetching available models...',+ 'gemini-3.8-flash-high\tGemini 3.8 Flash (High)',+ 'claude-opus-4-6-thinking\tClaude Opus 4.6 (Thinking)',+ '',+ ].join('\n');+ expect(parseHarnessModels('agy', stdout)).toEqual([+ 'gemini-3.8-flash-high',+ 'claude-opus-4-6-thinking',+ ]);+ });++ // Delegated to `parseAntigravityModelList`, which is what makes these two+ // work: a fresh reading of today's TAB-separated output would have required a+ // tab and reported an older build's catalog as empty — surfacing as "sign in+ // to Antigravity", the wrong diagnosis for a signed-in CLI.+ it('still reads an older agy build\'s bare-id rows', () => {+ expect(parseHarnessModels('agy', 'gemini-3.8-flash-high\nclaude-opus-4-6-thinking\n'))+ .toEqual(['gemini-3.8-flash-high', 'claude-opus-4-6-thinking']);+ });++ it('drops the agy configured-default sentinel, which is not a model', () => {+ expect(parseHarnessModels('agy', 'antigravity-configured-default\ngemini-3.8-flash-high\n'))+ .toEqual(['gemini-3.8-flash-high']);+ });++ it('reads the Cursor catalog through the parser the provider card already uses', () => {+ const stdout = ['Available models:', ' auto - Auto', ' gpt-5.1 - GPT-5.1', ''].join('\n');+ expect(parseHarnessModels('cursor-agent', stdout)).toEqual(['auto', 'gpt-5.1']);+ });++ it('takes only Grok bullet rows, not its "Default model:" line', () => {+ const stdout = [+ 'You are logged in with example.invalid.',+ '',+ 'Default model: grok-4.6',+ '',+ 'Available models:',+ ' * grok-4.6 (default)',+ ' - grok-4.5',+ ].join('\n');+ // A naive line parser reads `Default model: grok-4.6` as a model and would+ // write `model:` (or the banner) into every provider's picker.+ expect(parseHarnessModels('grok', stdout)).toEqual(['grok-4.6', 'grok-4.5']);+ });++ it('de-duplicates while preserving the vendor order', () => {+ expect(parseHarnessModels('opencode', 'a/one\na/two\na/one\n')).toEqual(['a/one', 'a/two']);+ });++ it('caps a runaway catalog', () => {+ const stdout = Array.from({ length: MAX_MODELS + 50 }, (_, i) => `x/model-${i}`).join('\n');+ expect(parseHarnessModels('opencode', stdout)).toHaveLength(MAX_MODELS);+ });++ it('returns [] for a harness with no parser and for non-string output', () => {+ expect(parseHarnessModels('claude', 'claude-opus-5')).toEqual([]);+ expect(parseHarnessModels('opencode', null)).toEqual([]);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 9fb863e5ae..97add75af2 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -375,6 +375,7 @@ export * from './credentialRegistry.js';export * from './usageRange.js';export * from './subscriptionSavings.js';export * from './providerFamilies.js';+export * from './harnessOutput.js';export * from './providerGateways.js';export * from './personaTraitBlend.js';export * from './pipelineIssueOrder.js';diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex ba0d8f1e5e..19b2b69a1b 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -278,6 +278,7 @@ const RAW_NAV_COMMANDS = [// would orphan those entries — only the path, label and section move.{ id: 'nav.models.3d', path: '/models/3d', label: '3D', section: 'Models', aliases: ['3d-runtimes', 'image-to-3d-runtimes', 'trellis-install', 'pixal3d-install'], keywords: ['trellis', 'pixal3d', 'install', 'repair', 'runtime', 'mesh', 'image to 3d', 'on-device'] },{ id: 'nav.models.code-reviewers', path: '/models/code-reviewers', label: 'Code Reviewers', section: 'Models', previousPaths: ['/settings/code-reviewers'], aliases: ['code-reviewers', 'settings-code-reviewers', 'code-review', 'review-defaults', 'reviewers'], keywords: ['review loop', 'reviewer chain', 'codex', 'copilot', 'ollama', 'stop mode', 'max rounds', 'defaults'] },+ { id: 'nav.models.harnesses', path: '/models/harnesses', label: 'Harnesses', section: 'Models', aliases: ['harnesses', 'harness', 'agent-harnesses', 'coding-clis', 'cli-harnesses'], keywords: ['opencode', 'claude code', 'codex', 'antigravity', 'agy', 'grok', 'kimi', 'cursor', 'install cli', 'update cli', 'upgrade', 'version', 'refresh models'] },{ id: 'nav.settings.embeddings', path: '/models/embeddings', label: 'Embeddings', section: 'Models', previousPaths: ['/settings/embeddings'], aliases: ['settings-embeddings', 'embeddings', 'embedding'], keywords: ['vector', 'pgvector', 'semantic search', 'nomic', 'ollama', 'lm studio'] },{ id: 'nav.settings.local-llm', path: '/models/llms', label: 'LLMs', section: 'Models', previousPaths: ['/settings/local-llm'], aliases: ['local-llm', 'local-llms', 'llms', 'models-llms', 'ollama', 'lm-studio', 'lmstudio'], keywords: ['ollama', 'lm studio', 'local model', 'local llm', 'gguf', 'pull model', 'install model', 'migrate', 'switch backend', 'llama.cpp'] },{ id: 'nav.models.llms.abuse', path: '/models/llms/abuse', label: 'Abuse Guard', section: 'Models', aliases: ['abuse-guard', 'model-abuse', 'model-abuse-guard', 'prompt-guard', 'prompt guard'], keywords: ['classifier', 'prompt injection', 'security scan', 'llama prompt guard', 'install guard'] },diff --git a/server/lib/opencodeConfig.js b/server/lib/opencodeConfig.jsindex e98056332e..efa5371bf6 100644--- a/server/lib/opencodeConfig.js+++ b/server/lib/opencodeConfig.js@@ -236,22 +236,30 @@ export function buildAgentGeneration(generation, providerKey) {* @returns {object} OpenCode config object*/export function buildOpencodeConfig(models, base = null, providerKey = 'ollama', generation = null) {- const bareIds = toBareModelIds(models, providerKey);+ // `null` = the harness's OWN catalog (OpenCode Zen). There is no custom+ // provider entry to declare and no models map to fill — OpenCode already+ // knows those models and already holds the credential — so the provider half+ // of this builder is skipped and everything else (base preservation, the+ // agent generation block) applies unchanged. One path, not two.+ const named = providerKey !== null && providerKey !== undefined;+ const bareIds = named ? toBareModelIds(models, providerKey) : [];const config = (base && typeof base === 'object')? structuredClone(base)- : { permission: 'allow', provider: {} };- if (!config.provider || typeof config.provider !== 'object') config.provider = {};- if (!config.provider[providerKey] || typeof config.provider[providerKey] !== 'object') {- config.provider[providerKey] = structuredClone(localProviderBase(providerKey));- }- if (bareIds.length > 0) {- const existing = (config.provider[providerKey].models && typeof config.provider[providerKey].models === 'object')- ? config.provider[providerKey].models- : {};- config.provider[providerKey].models = {- ...existing,- ...Object.fromEntries(bareIds.map((id) => [id, { name: id, tool_call: true }])),- };+ : { permission: 'allow', ...(named ? { provider: {} } : {}) };+ if (named) {+ if (!config.provider || typeof config.provider !== 'object') config.provider = {};+ if (!config.provider[providerKey] || typeof config.provider[providerKey] !== 'object') {+ config.provider[providerKey] = structuredClone(localProviderBase(providerKey));+ }+ if (bareIds.length > 0) {+ const existing = (config.provider[providerKey].models && typeof config.provider[providerKey].models === 'object')+ ? config.provider[providerKey].models+ : {};+ config.provider[providerKey].models = {+ ...existing,+ ...Object.fromEntries(bareIds.map((id) => [id, { name: id, tool_call: true }])),+ };+ }}const build = buildAgentGeneration(generation, providerKey);if (build) {@@ -279,10 +287,13 @@ export function buildOpencodeConfigContent(models, base = null, providerKey = 'o}/**- * Build dynamic env vars for an OpenCode local-provider spawn. Returns an- * object with `OPENCODE_CONFIG_CONTENT` (models map declared) for Ollama-,- * MTPLX-, Llama-, vLLM-, or OrcaRouter-backed OpenCode providers, otherwise an empty object (caller keeps- * existing env).+ * Build dynamic env vars for an OpenCode spawn. Returns an object with+ * `OPENCODE_CONFIG_CONTENT` for a provider that names a backend namespace+ * (Ollama, MTPLX, llama.cpp, vLLM, SGLang, or a hosted gateway) — models map+ * declared — and for a NAMESPACE-LESS record that ships a stored config of its+ * own, which is how the seeded OpenCode Zen wrappers run on the harness's own+ * catalog: no provider entry to declare and no key to inject, just the base plus+ * the `small_model` pin. Otherwise an empty object (caller keeps existing env).** The provider's already-stored `OPENCODE_CONFIG_CONTENT` is used as the base and* PRESERVED — a customized `baseURL`, `permission`, or hand-maintained models@@ -297,7 +308,7 @@ export function buildOpencodeConfigContent(models, base = null, providerKey = 'o*/export function buildOpencodeEnvVars(provider, model) {const providerKey = getOpencodeLocalProviderNamespace(provider);- if (!isOpencodeCommand(provider?.command) || !providerKey) {+ if (!isOpencodeCommand(provider?.command)) {return {};}// Parse the provider's stored config as the base so any user customization@@ -312,6 +323,14 @@ export function buildOpencodeEnvVars(provider, model) {base = null; // unparseable stored config → fall back to the canonical default}}+ // A record with NO namespace and NO stored config is a hand-made plain+ // `opencode` provider: it has always run against the user's own+ // `~/.config/opencode`, and `OPENCODE_CONFIG_CONTENT` REPLACES that file+ // wholesale — synthesizing one here would silently drop every provider they+ // declared in it. The seeded Zen records ship `{"permission":"allow"}`, so+ // they take the path below and get the `small_model` pin merged into it.+ if (!providerKey && !base) return {};+const ids = [...(Array.isArray(provider?.models) ? provider.models : []),provider?.defaultModel,@@ -345,11 +364,14 @@ export function buildOpencodeEnvVars(provider, model) {// Keyed off the RESOLVED namespace, not the record's marker: a malformed// record carrying both a local marker and a gateway marker resolves to the// local namespace above, and must not then export a gateway key env var.- const gateway = gatewayById(providerKey);- const apiKey = KEY_BEARING_NAMESPACES.has(providerKey)+ // A null namespace declares no provider entry, so there is nowhere to attach a+ // key and nothing that needs one — OpenCode authenticates the harness's own+ // catalog itself.+ const gateway = providerKey ? gatewayById(providerKey) : null;+ const apiKey = providerKey && KEY_BEARING_NAMESPACES.has(providerKey)? (provider?.apiKey || (gateway?.legacyApiKeyField ? provider?.[gateway.legacyApiKeyField] : null)): null;- if (apiKey) {+ if (apiKey && providerKey) {config.provider[providerKey].options = {...config.provider[providerKey].options,apiKey,diff --git a/server/lib/opencodeConfig.test.js b/server/lib/opencodeConfig.test.jsindex 4be5c46463..e0ce01dec0 100644--- a/server/lib/opencodeConfig.test.js+++ b/server/lib/opencodeConfig.test.js@@ -156,13 +156,47 @@ describe('buildOpencodeEnvVars', () => {expect(buildOpencodeEnvVars({ command: 'claude' }, 'claude-opus-4')).toEqual({});});- it('returns empty object for OpenCode providers without ollamaBacked', () => {+ // `OPENCODE_CONFIG_CONTENT` REPLACES the user's own ~/.config/opencode, so a+ // hand-made plain `opencode` record that declares nothing must keep getting+ // nothing — synthesizing a config would drop every provider it defines.+ it('injects nothing for a namespace-less provider that stores no config', () => {expect(buildOpencodeEnvVars({ command: 'opencode', ollamaBacked: false },'anthropic/claude-sonnet',)).toEqual({});});+ // A namespace-less record that DOES ship a config is the harness's own catalog+ // (the seeded OpenCode Zen wrappers): nothing to declare and no key to inject,+ // but it still needs the `small_model` pin so OpenCode's own side work stays+ // on the dispatched model instead of its built-in default.+ it('declares no provider entry for a namespace-less OpenCode provider', () => {+ const result = buildOpencodeEnvVars(+ {+ command: 'opencode',+ envVars: { OPENCODE_CONFIG_CONTENT: '{"permission":"allow"}' },+ },+ 'opencode/big-pickle',+ );+ const cfg = JSON.parse(result.OPENCODE_CONFIG_CONTENT);+ expect(cfg).toEqual({ permission: 'allow', small_model: 'opencode/big-pickle' });+ expect(cfg.provider).toBeUndefined();+ // No gateway key env var rides along — OpenCode authenticates Zen itself.+ expect(Object.keys(result)).toEqual(['OPENCODE_CONFIG_CONTENT']);+ });++ it('preserves a stored config and its small_model pin for a namespace-less provider', () => {+ const stored = JSON.stringify({ permission: 'ask', small_model: 'opencode/mimo-v2.5-free' });+ const result = buildOpencodeEnvVars(+ { command: 'opencode', envVars: { OPENCODE_CONFIG_CONTENT: stored } },+ 'opencode/big-pickle',+ );+ expect(JSON.parse(result.OPENCODE_CONFIG_CONTENT)).toEqual({+ permission: 'ask',+ small_model: 'opencode/mimo-v2.5-free',+ });+ });+it('declares the run model (bare) under provider.ollama.models', () => {const result = buildOpencodeEnvVars({ command: 'opencode', ollamaBacked: true, models: [], temperature: 0.6, thinking: false }, 'qwen2.5:7b');expect(result.OPENCODE_CONFIG_CONTENT).toBeDefined();diff --git a/server/lib/validation.js b/server/lib/validation.jsindex ed8c017620..2a7463d17b 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -556,6 +556,20 @@ export const providerVisionSuiteSchema = z.object({model: z.preprocess(emptyToUndefined, z.string().trim().min(1).max(256).optional()),});+// POST /api/harnesses/action. Both values are TABLE KEYS, not free text: the+// service rejects a `runtime` that names no row and an `action` outside this+// enum before any child is spawned. This bounds the shape at the HTTP boundary+// so a malformed query fails as a 400 rather than as a lookup miss mid-stream.+export const harnessActionSchema = z.object({+ runtime: z.string().trim().min(1).max(64),+ action: z.enum(['install', 'update', 'uninstall']).optional().default('install'),+});++// POST /api/harnesses/models/refresh.+export const harnessRefreshSchema = z.object({+ runtime: z.string().trim().min(1).max(64),+});+// POST /api/uploads and POST /api/attachments. The shared upload helper// enforces decoded-byte limits and extension allowlists; this schema bounds// the JSON shape before the helper receives it.diff --git a/server/routes/harnesses.js b/server/routes/harnesses.jsnew file mode 100644index 0000000000..1f54ce8ac2--- /dev/null+++ b/server/routes/harnesses.js@@ -0,0 +1,70 @@+/**+ * Harnesses — manage the coding-agent CLIs/TUIs PortOS drives.+ *+ * GET /api/harnesses → every harness, its version, its providers+ * POST /api/harnesses/action?runtime=&action= → SSE stream of install/update/remove+ * POST /api/harnesses/models/refresh → re-read a harness's model catalog+ *+ * Backs **Models → Harnesses**. The AI Providers page could already install a+ * missing CLI (`POST /api/providers/runtimes/install`), but there was no way to+ * see which version was installed, update a stale one, remove one, or refresh+ * the model list a harness knows about — which is how an install goes months+ * out of date with nothing in the UI saying so.+ *+ * Every mutating endpoint names a harness *id* from the fixed table in+ * `services/providerRuntimeInstaller.js`; no request value reaches a shell word,+ * and no response carries a resolved filesystem path (a global bin directory+ * embeds the host account name — see the Sensitive Data rules in AGENTS.md).+ */++import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest, harnessActionSchema, harnessRefreshSchema } from '../lib/validation.js';+import { streamHarnessAction } from '../services/harnessActionStream.js';+import { listHarnesses, refreshHarnessModels } from '../services/harnesses.js';++const router = Router();++/**+ * The whole page in one round trip. `?fresh=1` bypasses both the runtime status+ * TTL and the npm-registry cache — what the page's Refresh button sends, and+ * what it re-reads after every action so a just-installed version shows without+ * waiting out a cache.+ */+router.get('/', asyncHandler(async (req, res) => {+ res.json({ harnesses: await listHarnesses({ fresh: req.query.fresh === '1' }) });+}));++/**+ * Install, update, or remove one harness, streaming the child's output as SSE.+ *+ * A POST because it mutates host state, and the shared `RuntimeInstallModal`+ * already appends `runtime` to the query string for every BYO-runtime+ * installer — `action` rides beside it for the same reason.+ */+router.post('/action', asyncHandler(async (req, res) => {+ const { runtime, action } = validateRequest(harnessActionSchema, {+ runtime: req.query.runtime,+ action: req.query.action,+ });+ await streamHarnessAction(req, res, { runtime, action });+}));++/**+ * Re-read a harness's own model catalog and write it to every provider that+ * draws from it.+ *+ * Refusals here are 409, not 500: "this harness cannot list its models" and+ * "sign in first" are states of the host, not server faults, and the page+ * renders the reason verbatim.+ */+router.post('/models/refresh', asyncHandler(async (req, res) => {+ const { runtime } = validateRequest(harnessRefreshSchema, { runtime: req.query.runtime });+ const result = await refreshHarnessModels(runtime);+ if (!result.ok) {+ throw new ServerError(result.reason, { status: 409, code: 'HARNESS_MODELS_UNAVAILABLE', context: { runtime } });+ }+ res.json(result);+}));++export default router;diff --git a/server/routes/harnesses.test.js b/server/routes/harnesses.test.jsnew file mode 100644index 0000000000..a5ad0b1af7--- /dev/null+++ b/server/routes/harnesses.test.js@@ -0,0 +1,92 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++const service = vi.hoisted(() => ({+ listHarnesses: vi.fn(),+ refreshHarnessModels: vi.fn(),+}));+vi.mock('../services/harnesses.js', () => service);++const stream = vi.hoisted(() => ({ streamHarnessAction: vi.fn(async (req, res) => res.json({ streamed: true })) }));+vi.mock('../services/harnessActionStream.js', () => stream);++import { errorMiddleware } from '../lib/errorHandler.js';+import harnessRoutes from './harnesses.js';++function makeApp() {+ const app = express();+ app.use(express.json());+ app.use('/api/harnesses', harnessRoutes);+ app.use(errorMiddleware);+ return app;+}++describe('harness routes', () => {+ let app;++ beforeEach(() => {+ vi.clearAllMocks();+ stream.streamHarnessAction.mockImplementation(async (req, res) => res.json({ streamed: true }));+ service.listHarnesses.mockResolvedValue([{ id: 'opencode', label: 'OpenCode CLI' }]);+ app = makeApp();+ });++ it('lists harnesses, passing ?fresh through to bypass both caches', async () => {+ expect((await request(app).get('/api/harnesses')).status).toBe(200);+ expect(service.listHarnesses).toHaveBeenCalledWith({ fresh: false });++ const res = await request(app).get('/api/harnesses?fresh=1');+ expect(res.status).toBe(200);+ expect(service.listHarnesses).toHaveBeenLastCalledWith({ fresh: true });+ expect(res.body.harnesses).toHaveLength(1);+ });++ it('defaults the action to install and forwards the named runtime', async () => {+ expect((await request(app).post('/api/harnesses/action?runtime=opencode')).status).toBe(200);+ expect(stream.streamHarnessAction).toHaveBeenCalledWith(+ expect.anything(), expect.anything(), { runtime: 'opencode', action: 'install' },+ );+ });++ it.each(['update', 'uninstall'])('forwards the %s action', async (action) => {+ const res = await request(app).post(`/api/harnesses/action?runtime=opencode&action=${action}`);+ expect(res.status).toBe(200);+ expect(stream.streamHarnessAction).toHaveBeenLastCalledWith(+ expect.anything(), expect.anything(), { runtime: 'opencode', action },+ );+ });++ it('rejects an action outside the enum without reaching the stream', async () => {+ // The enum is the boundary guard: an unvalidated verb would reach a table+ // lookup instead of failing as a plain 400.+ expect((await request(app).post('/api/harnesses/action?runtime=opencode&action=purge')).status).toBe(400);+ expect(stream.streamHarnessAction).not.toHaveBeenCalled();+ });++ it('rejects a missing runtime', async () => {+ expect((await request(app).post('/api/harnesses/action')).status).toBe(400);+ expect(stream.streamHarnessAction).not.toHaveBeenCalled();+ });++ it('returns the refreshed catalog', async () => {+ service.refreshHarnessModels.mockResolvedValue({ ok: true, models: ['opencode/a'], updated: ['opencode-zen-cli'] });++ const res = await request(app).post('/api/harnesses/models/refresh?runtime=opencode');++ expect(res.status).toBe(200);+ expect(service.refreshHarnessModels).toHaveBeenCalledWith('opencode');+ expect(res.body).toEqual({ ok: true, models: ['opencode/a'], updated: ['opencode-zen-cli'] });+ });++ it('surfaces a refusal as a 409 carrying the service reason verbatim', async () => {+ // "signed out" / "cannot list models" are host states, not server faults —+ // and the page renders the sentence, so it must survive the round trip.+ service.refreshHarnessModels.mockResolvedValue({ ok: false, reason: 'Sign in first.', models: [], updated: [] });++ const res = await request(app).post('/api/harnesses/models/refresh?runtime=opencode');++ expect(res.status).toBe(409);+ expect(JSON.stringify(res.body)).toContain('Sign in first.');+ });+});diff --git a/server/routes/providers.js b/server/routes/providers.jsindex 3f6b83acdc..2a3ae82acc 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -4,7 +4,6 @@ import { testVision, runVisionTestSuite, checkVisionHealth } from '../services/vimport { providerSchema, providerActiveSchema, validate } from '../lib/aiToolkit/validation.js';import { withRefreshCapability } from '../lib/aiToolkit/internal/modelFetchers.js';import { ALLOWED_COMMANDS } from '../cos-runner/allowedCommands.js';-import { createLineReader } from '../lib/streamLines.js';import { onClientDisconnect, openSseStream } from '../lib/sseDownload.js';import { createInstallLogger } from '../lib/installLogger.js';import {@@ -15,13 +14,10 @@ import {providerVisionSuiteSchema,} from '../lib/validation.js';import {- describeRuntimeInstall,- getProviderRuntime,getProviderRuntimeStatus,getProviderRuntimeStatuses,- spawnRuntimeInstaller,- stopRuntimeInstaller,} from '../services/providerRuntimeInstaller.js';+import { streamHarnessAction } from '../services/harnessActionStream.js';import { getProviderReadinessMap, resetProviderReadinessCache, servedModelId } from '../services/providerReadiness.js';import { getLlamaServerEndpoint, relaunchLlamaServerWithAlias } from '../services/llamaServerManager.js';import { claimHeavyLocalJob } from '../lib/heavyJobClaim.js';@@ -67,12 +63,6 @@ import {*/const RUNNER_ALLOWED_COMMANDS = [...ALLOWED_COMMANDS].sort();-// One global CLI install at a time — npm's global prefix and the vendor-// install scripts all write the same bin directory. This is a lightweight-// re-entrancy guard for a double-click or a second browser tab; its child stays-// in the route so a client disconnect can terminate it.-let runtimeInstallInFlight = null;-// Same re-entrancy guard for the local-daemon setup lane. Separate from the CLI// one because they install different things, but each is single-flight: two// concurrent `brew install`s (or two copies of one daemon racing for a port) is@@ -332,142 +322,11 @@ export function createPortOSProviderRoutes(aiToolkit) {res.json({ readiness: await codexLogout() });}));- /**- * Install one provider runtime, streaming the installer's output as SSE.- *- * Installing a global CLI mutates host state, so this stays a POST even- * though the response is SSE-encoded. The client reads it with fetch rather- * than EventSource: EventSource would auto-reconnect after a dropped stream- * and could launch another non-idempotent install.- *- * The request names a runtime *id* only. The command, package, and URL all- * come from the installer's fixed table, so no request input ever reaches a- * shell word.- */- const streamRuntimeInstall = async (req, res, runtimeId) => {- // Table lookup only (no I/O), so an unknown id is a plain 400 instead of a- // stream that only says "no" once the modal is up. The real probe waits- // until the disconnect handler is registered below.- const row = getProviderRuntime(runtimeId);- if (!row) {- throw new ServerError('Unknown provider runtime', { status: 400, code: 'UNKNOWN_RUNTIME', context: { runtime: String(runtimeId || '') } });- }-- const { send, safeEnd } = openSseStream(res);- const installLog = createInstallLogger({ installer: row.label, target: `${row.command} on PortOS's PATH` });- const emit = (event) => { installLog.onEvent(event); send(event); };- let child = null;- let finished = false;- let clientGone = false;- let reservation = null;-- // Register before the availability probe. If the modal closes while the- // probe is resolving, do not start an installer nobody can observe.- onClientDisconnect(req, res, () => {- clientGone = true;- installLog.cancel();- if (finished) return;- if (child) stopRuntimeInstaller(child);- if (reservation && runtimeInstallInFlight === reservation) runtimeInstallInFlight = null;- safeEnd();- });-- // Un-cached: the user may have just installed this CLI in a terminal, and a- // stale "not installed" would run a redundant install.- const runtime = await getProviderRuntimeStatus(row.id, { fresh: true });- if (clientGone) return safeEnd();- if (runtime.installed) {- send({ type: 'log', message: `${runtime.label} is already available to PortOS.` });- send({ type: 'complete', message: 'Already installed — nothing to do.' });- return safeEnd();- }- if (!runtime.installable) {- send({ type: 'error', message: runtime.blockedReason || `PortOS cannot install ${runtime.label} on this host.` });- return safeEnd();- }- if (runtimeInstallInFlight) {- send({ type: 'error', message: 'Another runtime install is already running. Wait for it to finish or restart PortOS.' });- return safeEnd();- }-- // Reserve synchronously before spawning so two requests that finish their- // status probe together cannot launch competing installs into the same bin- // directory.- reservation = {};- runtimeInstallInFlight = reservation;- if (clientGone) {- runtimeInstallInFlight = null;- return safeEnd();- }-- send({ type: 'stage', stage: 'install', message: `Installing ${runtime.label}.` });- emit({ type: 'log', message: `Running ${describeRuntimeInstall(runtime.id)}.` });- installLog.start();- // `spawn` can throw synchronously (a rejected argv shape, an OS-level spawn- // refusal). Two things must happen here that letting it bubble would not do:- // release the reservation — or every later install answers "another install- // is already running" until PortOS restarts — and report the failure as a- // terminal SSE frame, since the headers are already flushed and the error- // middleware can no longer send JSON to this response.- try {- child = spawnRuntimeInstaller(runtime.id);- } catch (err) {- finished = true;- if (runtimeInstallInFlight === reservation) runtimeInstallInFlight = null;- emit({ type: 'error', message: `${runtime.label} installer failed to start: ${err.message}` });- return safeEnd();- }- runtimeInstallInFlight = child;-- const onLine = (line) => {- const text = line.trimEnd();- if (text) emit({ type: 'log', message: text });- };- // npm runs with `--no-progress`, which suppresses its usual redraws. Keep- // the default newline-only reader as a defensive second layer: a lifecycle- // child (or a vendor install script's own progress bar) that still writes- // bare carriage returns cannot turn every redraw into a browser log frame- // and a full modal re-render.- const stdoutReader = createLineReader(onLine);- const stderrReader = createLineReader(onLine);- child.stdout.on('data', stdoutReader.push);- child.stderr.on('data', stderrReader.push);- child.on('error', (err) => {- if (finished) return;- finished = true;- if (runtimeInstallInFlight === child) runtimeInstallInFlight = null;- emit({ type: 'error', message: `${runtime.label} installer failed to start: ${err.message}` });- safeEnd();- });- // The post-install PATH check is deliberately stronger than the installer's- // exit code. A successful write whose bin directory is absent from PM2's- // PATH would otherwise recreate the same opaque agent-start failure.- child.on('close', async (code) => {- if (finished) return;- try {- stdoutReader.flush();- stderrReader.flush();- finished = true;- if (runtimeInstallInFlight === child) runtimeInstallInFlight = null;- // `fresh` is load-bearing: the pre-install probe cached "not installed"- // seconds ago, and re-reading it would fail a CLI that now works.- const installed = code === 0 && (await getProviderRuntimeStatus(runtime.id, { fresh: true })).installed;- if (installed) {- emit({ type: 'complete', message: `${runtime.label} is installed and available to PortOS.` });- } else if (code === 0) {- emit({ type: 'error', message: `The installer finished, but PortOS still cannot run \`${runtime.command}\`. npm wrote it to a bin directory that is not on this machine's PATH — run \`npm prefix -g\` in a terminal, add that directory (plus \`/bin\` off Windows) to your PATH, then restart PortOS.` });- } else {- emit({ type: 'error', message: `${runtime.label} installer exited with code ${code}.` });- }- safeEnd();- } catch (err) {- // Child-process completion runs outside Express's request lifecycle.- console.error(`❌ ${runtime.label} install completion check failed: ${err.message}`);- emit({ type: 'error', message: `${runtime.label} install completion check failed: ${err.message}` });- safeEnd();- }- });- };+ // Install-only: the update and remove lanes of the shared runner are reached+ // from `/api/harnesses`, which is where the Harnesses page drives them. See+ // `services/harnessActionStream.js` for the stream contract.+ const streamRuntimeInstall = (req, res, runtimeId) =>+ streamHarnessAction(req, res, { runtime: runtimeId, action: 'install' });/*** Install and/or start the LOCAL DAEMON one provider points at, streamingdiff --git a/server/routes/providers.runtimeInstall.test.js b/server/routes/providers.runtimeInstall.test.jsindex e078bd530b..cb6c3a3b80 100644--- a/server/routes/providers.runtimeInstall.test.js+++ b/server/routes/providers.runtimeInstall.test.js@@ -12,6 +12,9 @@ const RUNTIMES = {const statusOf = (id, overrides) => ({ ...RUNTIMES[id], installed: false, method: 'npm', installable: true, blockedReason: null, ...overrides });+// The SSE loop these routes drive lives in `services/harnessActionStream.js`+// (shared with Models → Harnesses); it reads the same registry, so mocking the+// registry still drives every branch through the real `/api/providers` route.const installer = vi.hoisted(() => ({getProviderRuntime: vi.fn(),getProviderRuntimeStatus: vi.fn(),@@ -19,11 +22,14 @@ const installer = vi.hoisted(() => ({spawnRuntimeInstaller: vi.fn(),stopRuntimeInstaller: vi.fn(),describeRuntimeInstall: vi.fn(),+ buildRuntimeActionCommand: vi.fn(),+ RUNTIME_ACTIONS: ['install', 'update', 'uninstall'],}));vi.mock('../services/providerRuntimeInstaller.js', () => installer);import { createPortOSProviderRoutes } from './providers.js';+import { __resetHarnessActionGuard } from '../services/harnessActionStream.js';const app = () => {const toolkit = { services: { providers: {} }, routes: { providers: Router() } };@@ -47,8 +53,15 @@ const makeChild = () => {describe('Provider runtime installer routes', () => {beforeEach(() => {vi.clearAllMocks();+ // The single-flight guard is module state shared with Models → Harnesses; a+ // case that ends mid-stream would otherwise fail every later one with+ // "another harness install is already running".+ __resetHarnessActionGuard();installer.getProviderRuntime.mockImplementation((id) => RUNTIMES[id] || null);installer.describeRuntimeInstall.mockImplementation((id) => `npm install --global ${RUNTIMES[id]?.install?.package}`);+ installer.buildRuntimeActionCommand.mockImplementation((id) => (RUNTIMES[id]+ ? { command: 'npm', args: ['install', '--global', RUNTIMES[id].install.package] }+ : null));});it('publishes every runtime status in one payload', async () => {@@ -68,7 +81,7 @@ describe('Provider runtime installer routes', () => {installer.spawnRuntimeInstaller.mockReturnValueOnce(child);const responsePromise = request(app()).post('/api/providers/runtimes/install?runtime=codex').then((response) => response);- await vi.waitFor(() => expect(installer.spawnRuntimeInstaller).toHaveBeenCalledWith('codex'));+ await vi.waitFor(() => expect(installer.spawnRuntimeInstaller).toHaveBeenCalledWith('codex', { action: 'install' }));child.stdout.end('added Codex\n');child.stderr.end();child.emit('close', 0);@@ -171,7 +184,7 @@ describe('Provider runtime installer routes', () => {installer.spawnRuntimeInstaller.mockReturnValueOnce(child);const responsePromise = request(app()).post('/api/providers/opencode/install').then((response) => response);- await vi.waitFor(() => expect(installer.spawnRuntimeInstaller).toHaveBeenCalledWith('opencode'));+ await vi.waitFor(() => expect(installer.spawnRuntimeInstaller).toHaveBeenCalledWith('opencode', { action: 'install' }));child.stdout.end();child.stderr.end();child.emit('close', 0);diff --git a/server/services/harnessActionStream.js b/server/services/harnessActionStream.jsnew file mode 100644index 0000000000..52d9001675--- /dev/null+++ b/server/services/harnessActionStream.js@@ -0,0 +1,247 @@+/**+ * The SSE runner behind every harness lifecycle action — install, update,+ * remove.+ *+ * Extracted from `routes/providers.js`, which owned the install stream inline,+ * so the Harnesses page can drive update and remove through the SAME single+ * child, single-flight guard, and disconnect-cancels contract. Two copies of+ * that loop would mean two independent guards, and npm's global prefix plus the+ * vendor install scripts all write ONE bin directory — an update racing an+ * install there is exactly the corruption the guard exists to prevent.+ *+ * Installing, updating, or removing a global CLI mutates host state, so every+ * caller is a POST even though the response is SSE-encoded, and the browser+ * reads it with fetch rather than EventSource (which auto-reconnects and would+ * relaunch non-idempotent work on a dropped stream).+ *+ * The request names a runtime *id* and an *action*, both table lookups. The+ * command, package and URL come from `providerRuntimeInstaller.js`'s fixed+ * table, so no request input ever reaches a shell word.+ */++import { createLineReader } from '../lib/streamLines.js';+import { onClientDisconnect, openSseStream } from '../lib/sseDownload.js';+import { createInstallLogger } from '../lib/installLogger.js';+import { ServerError } from '../lib/errorHandler.js';+import {+ buildRuntimeActionCommand,+ describeRuntimeInstall,+ getProviderRuntime,+ getProviderRuntimeStatus,+ RUNTIME_ACTIONS,+ spawnRuntimeInstaller,+ stopRuntimeInstaller,+} from './providerRuntimeInstaller.js';++/**+ * One global CLI action at a time — npm's global prefix and the vendor install+ * scripts all write the same bin directory. A lightweight re-entrancy guard for+ * a double-click or a second browser tab, shared by every action so an update+ * cannot start while an install is mid-write. The child stays owned by the+ * request so a client disconnect can terminate it.+ */+let actionInFlight = null;++/** Test-only: clear a guard left set by an aborted run. */+export function __resetHarnessActionGuard() {+ actionInFlight = null;+}++/**+ * Per-action copy. `skipWhenInstalled` carries both the short-circuit message+ * AND, by its absence, the "this action needs the harness present" rule — the+ * two are the same fact stated once: an action that has nothing to do when the+ * CLI is there is exactly the one that has something to do when it isn't.+ *+ * Install is the only action with that short-circuit. Update deliberately has+ * none: "you are on the latest" is the vendor updater's answer to give, not+ * ours to guess from a registry read that may be stale or unavailable.+ *+ * Keyed by the same strings as `RUNTIME_ACTIONS`; `providerRuntimeInstaller.test.js`+ * pins the two together, because a fourth action would otherwise reach+ * `ACTION_COPY[action]` as `undefined` and crash mid-stream.+ */+export const HARNESS_ACTION_COPY = Object.freeze({+ install: { verb: 'Installing', noun: 'installer', skipWhenInstalled: 'Already installed — nothing to do.' },+ update: { verb: 'Updating', noun: 'updater', skipWhenInstalled: null },+ uninstall: { verb: 'Removing', noun: 'uninstaller', skipWhenInstalled: null },+});++/**+ * Run one harness action, streaming the child's output to the browser as SSE.+ *+ * Resolves once the stream has ended. Throws only BEFORE the headers are+ * flushed (unknown id, unsupported action) — after that point every failure is+ * reported as a terminal SSE frame, because the error middleware can no longer+ * send a JSON body to this response.+ *+ * @param {import('express').Request} req+ * @param {import('express').Response} res+ * @param {{runtime: unknown, action?: string}} params+ */+export async function streamHarnessAction(req, res, { runtime: runtimeId, action = 'install' }) {+ if (!RUNTIME_ACTIONS.includes(action)) {+ throw new ServerError('Unknown harness action', { status: 400, code: 'UNKNOWN_HARNESS_ACTION', context: { action: String(action || '') } });+ }+ // Table lookups only (no I/O), so a bad request is a plain 400 instead of a+ // stream that only says "no" once the modal is up. The real probe waits until+ // the disconnect handler is registered below.+ const row = getProviderRuntime(runtimeId);+ if (!row) {+ throw new ServerError('Unknown provider runtime', { status: 400, code: 'UNKNOWN_RUNTIME', context: { runtime: String(runtimeId || '') } });+ }+ if (!buildRuntimeActionCommand(row.id, action)) {+ throw new ServerError(+ `PortOS cannot ${action} ${row.label} — it was not installed from a package manager PortOS drives. Follow the vendor instructions instead.`,+ { status: 400, code: 'UNSUPPORTED_HARNESS_ACTION', context: { runtime: row.id, action } },+ );+ }++ const copy = HARNESS_ACTION_COPY[action];+ const { send, safeEnd } = openSseStream(res);+ // The ledger line names the ACTION, not just the harness — three lanes share+ // this logger, and a bare label would file every removal as an install.+ const installLog = createInstallLogger({+ installer: action === 'install' ? row.label : `${row.label} ${action}`,+ target: `${row.command} on PortOS's PATH`,+ });+ const emit = (event) => { installLog.onEvent(event); send(event); };+ let child = null;+ let finished = false;+ let clientGone = false;+ let reservation = null;++ // Register before the availability probe. If the modal closes while the probe+ // is resolving, do not start work nobody can observe.+ onClientDisconnect(req, res, () => {+ clientGone = true;+ installLog.cancel();+ if (finished) return;+ if (child) stopRuntimeInstaller(child);+ if (reservation && actionInFlight === reservation) actionInFlight = null;+ safeEnd();+ });++ // Un-cached: the user may have just installed (or removed) this CLI in a+ // terminal, and a stale answer would run redundant or impossible work.+ const status = await getProviderRuntimeStatus(row.id, { fresh: true });+ if (clientGone) return safeEnd();+ if (status.installed && copy.skipWhenInstalled) {+ send({ type: 'log', message: `${status.label} is already available to PortOS.` });+ send({ type: 'complete', message: copy.skipWhenInstalled });+ return safeEnd();+ }+ if (!status.installed && !copy.skipWhenInstalled) {+ send({ type: 'error', message: `${status.label} is not installed on this host, so there is nothing to ${action}.` });+ return safeEnd();+ }+ // `installable` gates the tool an install/uninstall shells THROUGH (npm,+ // curl). A vendor self-updater runs the harness's own binary, which the+ // installed check above already proved runnable.+ const needsHostTool = action !== 'update' || !row.selfUpdate;+ if (needsHostTool && !status.installable) {+ send({ type: 'error', message: status.blockedReason || `PortOS cannot ${action} ${status.label} on this host.` });+ return safeEnd();+ }+ if (actionInFlight) {+ send({ type: 'error', message: 'Another harness install is already running. Wait for it to finish or restart PortOS.' });+ return safeEnd();+ }++ // Reserve synchronously before spawning so two requests that finish their+ // status probe together cannot launch competing writes into the same bin+ // directory.+ reservation = {};+ actionInFlight = reservation;+ if (clientGone) {+ actionInFlight = null;+ return safeEnd();+ }++ send({ type: 'stage', stage: action, message: `${copy.verb} ${status.label}.` });+ emit({ type: 'log', message: `Running ${describeRuntimeInstall(row.id, action)}.` });+ installLog.start();+ // `spawn` can throw synchronously (a rejected argv shape, an OS-level spawn+ // refusal). Two things must happen here that letting it bubble would not do:+ // release the reservation — or every later action answers "another install is+ // already running" until PortOS restarts — and report the failure as a+ // terminal SSE frame, since the headers are already flushed and the error+ // middleware can no longer send JSON to this response.+ try {+ child = spawnRuntimeInstaller(row.id, { action });+ } catch (err) {+ finished = true;+ if (actionInFlight === reservation) actionInFlight = null;+ emit({ type: 'error', message: `${status.label} ${copy.noun} failed to start: ${err.message}` });+ return safeEnd();+ }+ actionInFlight = child;++ const onLine = (line) => {+ const text = line.trimEnd();+ if (text) emit({ type: 'log', message: text });+ };+ // npm runs with `--no-progress`, which suppresses its usual redraws. Keep the+ // default newline-only reader as a defensive second layer: a lifecycle child+ // (or a vendor script's own progress bar) that still writes bare carriage+ // returns cannot turn every redraw into a browser log frame and a full modal+ // re-render.+ const stdoutReader = createLineReader(onLine);+ const stderrReader = createLineReader(onLine);+ child.stdout.on('data', stdoutReader.push);+ child.stderr.on('data', stderrReader.push);+ child.on('error', (err) => {+ if (finished) return;+ finished = true;+ if (actionInFlight === child) actionInFlight = null;+ emit({ type: 'error', message: `${status.label} ${copy.noun} failed to start: ${err.message}` });+ safeEnd();+ });+ child.on('close', async (code) => {+ if (finished) return;+ try {+ stdoutReader.flush();+ stderrReader.flush();+ finished = true;+ if (actionInFlight === child) actionInFlight = null;+ // The post-action PATH check is deliberately stronger than the exit code.+ // A successful write whose bin directory is absent from PM2's PATH would+ // otherwise recreate the same opaque agent-start failure — and for a+ // removal, "npm said ok" is not the same as "PortOS can no longer run it".+ //+ // `fresh` is load-bearing: the pre-action probe cached this runtime's+ // availability seconds ago, and re-reading it would report the state the+ // action just changed.+ const after = await getProviderRuntimeStatus(row.id, { fresh: true });+ emit(terminalFrame({ action, code, status: after, copy, command: row.command }));+ safeEnd();+ } catch (err) {+ // Child-process completion runs outside Express's request lifecycle.+ console.error(`❌ ${status.label} ${action} completion check failed: ${err.message}`);+ emit({ type: 'error', message: `${status.label} ${action} completion check failed: ${err.message}` });+ safeEnd();+ }+ });+}++/**+ * The one terminal SSE frame an action ends on, decided from the exit code AND+ * the re-probed availability.+ */+function terminalFrame({ action, code, status, copy, command }) {+ if (code !== 0) {+ return { type: 'error', message: `${status.label} ${copy.noun} exited with code ${code}.` };+ }+ if (action === 'uninstall') {+ return status.installed+ ? { type: 'error', message: `The uninstall finished, but PortOS can still run \`${command}\`. Another copy is on this machine's PATH — one installed by Homebrew or a vendor script, which PortOS did not write and will not delete.` }+ : { type: 'complete', message: `${status.label} has been removed. Providers that used it will show as needing setup.` };+ }+ if (!status.installed) {+ return { type: 'error', message: `The ${copy.noun} finished, but PortOS still cannot run \`${command}\`. npm wrote it to a bin directory that is not on this machine's PATH — run \`npm prefix -g\` in a terminal, add that directory (plus \`/bin\` off Windows) to your PATH, then restart PortOS.` };+ }+ const version = status.version ? ` (${status.version})` : '';+ return action === 'update'+ ? { type: 'complete', message: `${status.label} is up to date${version}.` }+ : { type: 'complete', message: `${status.label} is installed and available to PortOS${version}.` };+}diff --git a/server/services/harnessActionStream.test.js b/server/services/harnessActionStream.test.jsnew file mode 100644index 0000000000..dcc4b00d48--- /dev/null+++ b/server/services/harnessActionStream.test.js@@ -0,0 +1,182 @@+/**+ * The install half of this loop is covered end-to-end through the real+ * `/api/providers/runtimes/install` route (`routes/providers.runtimeInstall.test.js`).+ * These cases cover what the extraction ADDED: the update and remove lanes, and+ * the guards that keep them from doing an install's thing.+ */+import { EventEmitter } from 'node:events';+import { PassThrough } from 'node:stream';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { errorMiddleware } from '../lib/errorHandler.js';+import { request } from '../lib/testHelper.js';++const RUNTIMES = {+ opencode: { id: 'opencode', label: 'OpenCode CLI', command: 'opencode', install: { kind: 'npm', package: 'opencode-ai@latest' }, selfUpdate: ['upgrade'] },+ agy: { id: 'agy', label: 'Antigravity CLI', command: 'agy', install: { kind: 'script', url: 'https://example.invalid/i.sh' }, selfUpdate: ['update'] },+};++const statusOf = (id, overrides) => ({+ ...RUNTIMES[id], installed: true, version: '1.18.27', method: 'npm', installable: true, blockedReason: null, ...overrides,+});++const installer = vi.hoisted(() => ({+ getProviderRuntime: vi.fn(),+ getProviderRuntimeStatus: vi.fn(),+ spawnRuntimeInstaller: vi.fn(),+ stopRuntimeInstaller: vi.fn(),+ describeRuntimeInstall: vi.fn(),+ buildRuntimeActionCommand: vi.fn(),+ RUNTIME_ACTIONS: ['install', 'update', 'uninstall'],+}));+vi.mock('./providerRuntimeInstaller.js', () => installer);++import { streamHarnessAction, __resetHarnessActionGuard } from './harnessActionStream.js';++const makeChild = () => {+ const child = new EventEmitter();+ child.pid = 123;+ child.killed = false;+ child.stdout = new PassThrough();+ child.stderr = new PassThrough();+ child.kill = vi.fn();+ return child;+};++const app = () => {+ const server = express();+ server.post('/action', (req, res, next) => {+ streamHarnessAction(req, res, { runtime: req.query.runtime, action: req.query.action }).catch(next);+ });+ server.use(errorMiddleware);+ return server;+};++/** Drive one action to completion with a fake child that exits `code`. */+const runAction = async (query, { code = 0, stdout = '' } = {}) => {+ const child = makeChild();+ installer.spawnRuntimeInstaller.mockReturnValueOnce(child);+ const responsePromise = request(app()).post(`/action?${query}`).then((r) => r);+ await vi.waitFor(() => expect(installer.spawnRuntimeInstaller).toHaveBeenCalled());+ child.stdout.end(stdout);+ child.stderr.end();+ child.emit('close', code);+ return responsePromise;+};++beforeEach(() => {+ vi.clearAllMocks();+ __resetHarnessActionGuard();+ installer.getProviderRuntime.mockImplementation((id) => RUNTIMES[id] || null);+ installer.describeRuntimeInstall.mockImplementation((id, action) => `${id} ${action}`);+ installer.buildRuntimeActionCommand.mockImplementation((id) => (RUNTIMES[id] ? { command: id, args: [] } : null));+});++describe('streamHarnessAction — update', () => {+ it('runs the vendor updater and reports the version it landed on', async () => {+ installer.getProviderRuntimeStatus+ .mockResolvedValueOnce(statusOf('opencode'))+ .mockResolvedValueOnce(statusOf('opencode', { version: '1.19.0' }));++ const response = await runAction('runtime=opencode&action=update', { stdout: 'upgraded\n' });++ expect(installer.spawnRuntimeInstaller).toHaveBeenCalledWith('opencode', { action: 'update' });+ expect(response.text).toContain('OpenCode CLI is up to date (1.19.0).');+ expect(response.text).toContain('upgraded');+ });++ // An install short-circuits on "already there"; an update must NOT — that is+ // the whole point of the button, and "you are on the latest" is the vendor+ // updater's answer to give, not ours to guess from a cached registry read.+ it('does not short-circuit on an already-installed harness', async () => {+ installer.getProviderRuntimeStatus.mockResolvedValue(statusOf('opencode'));++ await runAction('runtime=opencode&action=update');++ expect(installer.spawnRuntimeInstaller).toHaveBeenCalledWith('opencode', { action: 'update' });+ });++ it('refuses to update a harness that is not installed', async () => {+ installer.getProviderRuntimeStatus.mockResolvedValueOnce(statusOf('opencode', { installed: false }));++ const response = await request(app()).post('/action?runtime=opencode&action=update');++ expect(response.text).toContain('nothing to update');+ expect(installer.spawnRuntimeInstaller).not.toHaveBeenCalled();+ });++ // A vendor self-updater runs the harness's OWN binary, which the installed+ // check already proved runnable — a missing `curl`/`npm` is irrelevant to it,+ // and blocking on that would strand a script-installed CLI with no update path.+ it('runs a vendor self-updater even when the host install tool is missing', async () => {+ installer.getProviderRuntimeStatus.mockResolvedValue(statusOf('agy', {+ method: 'script', installable: false, blockedReason: 'curl is not available.',+ }));++ await runAction('runtime=agy&action=update');++ expect(installer.spawnRuntimeInstaller).toHaveBeenCalledWith('agy', { action: 'update' });+ });+});++describe('streamHarnessAction — uninstall', () => {+ it('confirms removal only when the binary is really gone', async () => {+ installer.getProviderRuntimeStatus+ .mockResolvedValueOnce(statusOf('opencode'))+ .mockResolvedValueOnce(statusOf('opencode', { installed: false }));++ const response = await runAction('runtime=opencode&action=uninstall');++ expect(response.text).toContain('has been removed');+ });++ // "npm said ok" is not "PortOS can no longer run it": a Homebrew or vendor+ // script copy PortOS never wrote is still on PATH, and reporting success+ // would leave the user believing a removal that did not happen.+ it('reports a survivor on PATH as an error, not a success', async () => {+ installer.getProviderRuntimeStatus.mockResolvedValue(statusOf('opencode'));++ const response = await runAction('runtime=opencode&action=uninstall');++ expect(response.text).toContain('"type":"error"');+ expect(response.text).toContain('can still run');+ });+});++describe('streamHarnessAction — guards', () => {+ it('rejects an unknown action and an unknown runtime before the headers flush', async () => {+ expect((await request(app()).post('/action?runtime=opencode&action=purge')).status).toBe(400);+ expect((await request(app()).post('/action?runtime=nope&action=install')).status).toBe(400);+ expect(installer.spawnRuntimeInstaller).not.toHaveBeenCalled();+ });++ it('rejects an action this runtime does not support, naming the vendor path instead', async () => {+ // Antigravity ships no uninstall PortOS can run.+ installer.buildRuntimeActionCommand.mockReturnValueOnce(null);++ const response = await request(app()).post('/action?runtime=agy&action=uninstall');++ expect(response.status).toBe(400);+ expect(JSON.stringify(response.body)).toContain('vendor instructions');+ });++ it('holds one action at a time across every lane', async () => {+ // npm's global prefix is one directory; an update racing an install there is+ // exactly the corruption this guard exists to prevent.+ installer.getProviderRuntimeStatus.mockResolvedValue(statusOf('opencode'));+ const child = makeChild();+ installer.spawnRuntimeInstaller.mockReturnValueOnce(child);++ const first = request(app()).post('/action?runtime=opencode&action=update').then((r) => r);+ await vi.waitFor(() => expect(installer.spawnRuntimeInstaller).toHaveBeenCalled());++ const second = await request(app()).post('/action?runtime=opencode&action=uninstall');+ expect(second.text).toContain('Another harness install is already running');+ expect(installer.spawnRuntimeInstaller).toHaveBeenCalledTimes(1);++ child.stdout.end();+ child.stderr.end();+ child.emit('close', 0);+ await first;+ });+});diff --git a/server/services/harnesses.js b/server/services/harnesses.jsnew file mode 100644index 0000000000..6af36c3eda--- /dev/null+++ b/server/services/harnesses.js@@ -0,0 +1,250 @@+/**+ * Harnesses — the coding-agent CLIs/TUIs PortOS drives, seen as things you+ * MANAGE rather than as a footnote on a provider card.+ *+ * A harness is one binary (`opencode`, `claude`, `codex`, `agy`, `grok`,+ * `kimi`, `cursor-agent`) that several provider records share. Availability and+ * the fixed install/update/remove invocations live in+ * `providerRuntimeInstaller.js`; this module answers the two questions that+ * need the provider records too:+ *+ * - **Which providers ride on this harness, and are any of them enabled?**+ * Removing `opencode` takes eleven provider records offline at once, and a+ * page offering that button has to say so before the click.+ * - **Which models does this install of the harness know about?** Every+ * vendor that can answer prints it in its own shape+ * (`server/lib/harnessOutput.js` parses them), and the answer is only+ * useful once it reaches the providers whose picker it feeds.+ *+ * **The model refresh is deliberately narrow.** It rewrites the `models` list of+ * a provider only when that provider draws from the harness's OWN catalog — no+ * local-runtime marker (`ollamaBacked`, `vllmBacked`, …) and no `gatewayBacked`.+ * An OpenCode wrapper pointed at a local Ollama daemon serves `ollama/*` ids+ * that `opencode models` never reports, and overwriting its list with+ * `opencode/*` would leave it pointing at models its own config cannot resolve.+ *+ * **No AI provider call happens here.** `<harness> models` reads the vendor's+ * own catalog endpoint or local config; it does not generate anything, and it+ * runs only from an explicit click on the Harnesses page — nothing on the boot+ * path calls it (root AGENTS.md, AI Provider Usage Policy).+ */++import { prepareCliSpawn } from '../lib/bufferedSpawn.js';+import { commandOutput } from '../lib/commandExists.js';+import { compareHarnessVersions, parseHarnessModels, parseNpmLatestVersion } from '../lib/harnessOutput.js';+import { findCommandOnPath } from '../lib/processEnv.js';+import { getOpencodeLocalProviderNamespace } from '../lib/providerModels.js';+import { providerRuntimeKey } from '../lib/providerPrerequisites.js';+import { createStaleWhileRevalidate } from '../lib/staleWhileRevalidate.js';+import * as providerService from './providers.js';+import {+ PROVIDER_RUNTIMES,+ getProviderRuntime,+ getProviderRuntimeStatuses,+ getProviderRuntimeStatus,+} from './providerRuntimeInstaller.js';++/**+ * A vendor `models` subcommand can reach the vendor's catalog API, so it is+ * bounded well above the local `--version` probe but far below an agent run.+ */+const MODELS_PROBE_TIMEOUT_MS = 45_000;++/** `npm view` hits the registry; a slow or offline network must not hang the page. */+const REGISTRY_TIMEOUT_MS = 12_000;++/**+ * How long a registry answer stays good. The published version of a CLI changes+ * a few times a week at most, and the page re-reads the whole list after every+ * action — without this, four visits are four registry round trips per+ * npm-backed harness.+ *+ * `createStaleWhileRevalidate` rather than a hand-rolled TTL map, for the two+ * behaviors that matter on a page opened while a laptop is off the network: a+ * failed `npm view` keeps the last good answer and backs off instead of+ * re-spawning on every load, and a stale-but-real version renders immediately+ * while the refresh runs behind it. Keys are the five frozen package names in+ * `PROVIDER_RUNTIMES`, so the map needs no eviction.+ */+const latestVersions = createStaleWhileRevalidate({+ ttlMs: 6 * 60 * 60 * 1000,+ // One offline load must not mean six hours of no registry reads; a minute is+ // long enough that a page re-render doesn't re-spawn npm.+ failureBackoffMs: 60 * 1000,+});++/**+ * The latest published version of an npm-backed harness, or `null` when the+ * registry could not be reached or the row is not npm-backed.+ *+ * `null` is NOT-KNOWN, never "no update": `updateAvailable` below is computed+ * only from a definite comparison, so an offline install shows the version it+ * has and no false "out of date" badge.+ */+export async function getLatestPublishedVersion(packageName, { fresh = false, run = commandOutput } = {}) {+ if (typeof packageName !== 'string' || packageName === '') return null;+ return latestVersions.read(packageName, async () => {+ const stdout = await run('npm', ['view', packageName, 'version'], { timeoutMs: REGISTRY_TIMEOUT_MS });+ const version = parseNpmLatestVersion(stdout);+ // THROW, don't cache a null: an unreachable registry is a failure the+ // backoff should pace, not an answer worth remembering for six hours.+ if (!version) throw new Error(`npm view ${packageName} returned no version`);+ return version;+ }, fresh ? { wait: 'fresh' } : {}).catch(() => null);+}++/** Test-only: drop cached registry answers so the next read re-queries. */+export function __resetLatestVersionCache() {+ latestVersions.clear();+}++/**+ * Does this provider draw its models from the harness's own catalog?+ *+ * True only for a plain wrapper: one that resolves to NO backend namespace —+ * neither a local runtime nor a hosted gateway. That single check covers both+ * carve-outs because `getOpencodeLocalProviderNamespace` resolves the modern+ * `gatewayBacked` marker, every legacy per-runtime boolean, AND the legacy+ * `orcarouterBacked` alias — so a record written before any of those existed is+ * classified correctly with no migration.+ *+ * **This is a test for the ABSENCE of a marker, which is a class that grows on+ * its own** — every un-marked provider joins it. That is deliberate (a record+ * with no backend really does run the harness's own models) but it is not+ * self-policing, so `harnesses.test.js` walks the shipped seed and pins exactly+ * which records a refresh may rewrite. A new seeded provider, or a harness that+ * gains `modelsArgs`, has to move that list on purpose. The failure it guards+ * is silent in the worst direction: a refresh replacing a working `models` list+ * with ids that record's own backend cannot resolve.+ */+export const usesHarnessCatalog = (provider) => !getOpencodeLocalProviderNamespace(provider);++/**+ * Every provider record this harness's runtime row actually answers for.+ *+ * Keyed on `providerRuntimeKey`, the same helper the provider cards use, rather+ * than on a bare basename: it deliberately returns `null` for a provider+ * configured with an explicit path (`/opt/tools/opencode`) or carrying its own+ * `PATH` override, because the PATH-scanning runtime table says nothing about+ * those. Attributing them here would inflate the removal warning and — worse —+ * let a model refresh rewrite a record from a catalog printed by a DIFFERENT+ * binary than the one that record spawns.+ */+const providersForHarness = (providers, runtime) => {+ const names = new Set([runtime.id, ...runtime.aliases]);+ return providers.filter((provider) => names.has(providerRuntimeKey(provider)));+};++/**+ * Every harness, with its runtime status and the providers riding on it.+ *+ * Publishes counts and ids, never resolved filesystem paths — same rule as+ * `GET /api/providers/runtimes`, since a global bin directory embeds the host+ * account name.+ */+export async function listHarnesses({ fresh = false, run = commandOutput, ...probeDeps } = {}) {+ const [statuses, data] = await Promise.all([+ getProviderRuntimeStatuses({ ...probeDeps, fresh }),+ providerService.getAllProviders(),+ ]);+ const providers = Object.values(data?.providers || {});++ return Promise.all(PROVIDER_RUNTIMES.map(async (runtime) => {+ const status = statuses[runtime.id] || {};+ const linked = providersForHarness(providers, runtime);+ const latestVersion = runtime.npmPackage+ ? await getLatestPublishedVersion(runtime.npmPackage, { fresh, run })+ : null;+ return {+ ...status,+ id: runtime.id,+ label: runtime.label,+ command: runtime.command,+ vendor: runtime.vendor,+ package: runtime.npmPackage,+ latestVersion,+ // Only a DEFINITE "installed < latest" is an update prompt. A missing+ // version on either side leaves this false, and the row still offers the+ // Update button — the user can always ask for one.+ updateAvailable: compareHarnessVersions(status.version, latestVersion) === -1,+ providers: linked.map((provider) => ({+ id: provider.id,+ name: provider.name,+ type: provider.type,+ enabled: provider.enabled === true,+ // Which of these the model refresh would actually rewrite.+ usesHarnessCatalog: usesHarnessCatalog(provider),+ })),+ };+ }));+}++/**+ * Ask a harness which models it knows about, and write the answer to every+ * provider that draws from its own catalog.+ *+ * Refuses rather than guesses in three cases, each with its own reason string:+ * an id not in the table, a harness with no `models` subcommand, and a harness+ * that is not installed. A probe that RUNS but parses to nothing also refuses —+ * an empty catalog is far more likely to be a vendor output change or a+ * signed-out CLI than a real "this harness has zero models", and blanking every+ * picker on that guess is worse than reporting the probe as failed.+ *+ * @returns {Promise<{ok:boolean, reason?:string, models:string[], updated:string[]}>}+ */+export async function refreshHarnessModels(id, { run = commandOutput, ...probeDeps } = {}) {+ const runtime = getProviderRuntime(id);+ if (!runtime) return { ok: false, reason: 'Unknown harness.', models: [], updated: [] };+ if (!runtime.modelsArgs) {+ return {+ ok: false,+ reason: `${runtime.label} has no command for listing its models, so PortOS cannot refresh them from here.`,+ models: [],+ updated: [],+ };+ }+ // The SAME injected runner answers the availability probe, so a caller (and a+ // test) drives one child-process boundary rather than two. Cache-respecting:+ // the page rendered from a probe seconds ago, and re-spawning the binary for+ // a 15s worst case ahead of the 45s models probe would double the wait on a+ // user-facing button. A binary that broke since then still refuses below.+ const findCommand = probeDeps.findCommand || findCommandOnPath;+ const status = await getProviderRuntimeStatus(runtime.id, { ...probeDeps, probeCommand: run });+ if (!status?.installed) {+ return { ok: false, reason: `${runtime.label} is not installed on this host.`, models: [], updated: [] };+ }++ // Resolve and `prepareCliSpawn` exactly as the version probe does. An+ // npm-installed harness is a `.cmd` shim on Windows, which `execFile` under+ // `shell: false` refuses outright — the probe would answer nothing and the+ // page would tell a signed-in user to go sign in.+ const resolved = await findCommand(runtime.command);+ const probe = prepareCliSpawn(resolved || runtime.command, [...runtime.modelsArgs]);+ const stdout = await run(probe.command, probe.args, { timeoutMs: MODELS_PROBE_TIMEOUT_MS });+ const models = parseHarnessModels(runtime.id, stdout);+ if (models.length === 0) {+ return {+ ok: false,+ reason: `\`${runtime.command} ${runtime.modelsArgs.join(' ')}\` returned no models. Sign in to ${runtime.label} in a terminal, then try again.`,+ models: [],+ updated: [],+ };+ }++ const data = await providerService.getAllProviders();+ const targets = providersForHarness(Object.values(data?.providers || {}), runtime).filter(usesHarnessCatalog);+ const updated = [];+ for (const provider of targets) {+ // A stored default that the harness no longer lists would leave the record+ // pinned to a model its own picker cannot show. Keep it when it survived+ // the refresh, otherwise fall to the first id the vendor listed (vendors+ // list newest first).+ const defaultModel = models.includes(provider.defaultModel) ? provider.defaultModel : models[0];+ // Serialized rather than batched: each write is a read-modify-write of the+ // same providers.json, and Promise.all would have them clobber each other.+ await providerService.updateProvider(provider.id, { models, defaultModel });+ updated.push(provider.id);+ }+ console.log(`🔄 ${runtime.label}: ${models.length} models → ${updated.length} provider(s)`);+ return { ok: true, models, updated };+}diff --git a/server/services/harnesses.test.js b/server/services/harnesses.test.jsnew file mode 100644index 0000000000..e661df10db--- /dev/null+++ b/server/services/harnesses.test.js@@ -0,0 +1,213 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++// The npm-prefix probe shells out; PATH adoption is covered by lib/npmGlobalBin.test.js.+const npmGlobalBin = vi.hoisted(() => ({ adoptNpmGlobalBinDir: vi.fn(async () => null) }));+vi.mock('../lib/npmGlobalBin.js', () => npmGlobalBin);++const providerService = vi.hoisted(() => ({+ getAllProviders: vi.fn(),+ updateProvider: vi.fn(async () => ({})),+}));+vi.mock('./providers.js', () => providerService);++import {+ __resetLatestVersionCache,+ listHarnesses,+ refreshHarnessModels,+ usesHarnessCatalog,+} from './harnesses.js';+import { __resetRuntimeStatusCache, PROVIDER_RUNTIMES } from './providerRuntimeInstaller.js';+import { providerRuntimeKey } from '../lib/providerPrerequisites.js';++const OPENCODE_MODELS = 'opencode/big-pickle\nopencode/mimo-v2.5-free\n';++// PATH resolution is injected too, so these never depend on what is actually+// installed on the machine running the suite.+const found = { findCommand: async (command) => `/example/${command}` };++// A plain wrapper (harness catalog), a gateway-backed one, and a local-runtime+// one — the three classes the refresh has to tell apart.+const providers = {+ 'opencode-zen-cli': { id: 'opencode-zen-cli', name: 'OpenCode Zen CLI', type: 'cli', command: 'opencode', enabled: true, models: ['opencode/stale'], defaultModel: 'opencode/stale' },+ 'opencode-zen-tui': { id: 'opencode-zen-tui', name: 'OpenCode Zen TUI', type: 'tui', command: 'opencode', enabled: false, models: [], defaultModel: null },+ 'opencode-openrouter': { id: 'opencode-openrouter', name: 'OpenCode OpenRouter', type: 'cli', command: 'opencode', enabled: true, gatewayBacked: 'openrouter', models: ['openrouter/auto'], defaultModel: 'openrouter/auto' },+ 'opencode-ollama': { id: 'opencode-ollama', name: 'OpenCode Ollama', type: 'cli', command: 'opencode', enabled: false, ollamaBacked: true, models: ['ollama/qwen'], defaultModel: 'ollama/qwen' },+ 'claude-code': { id: 'claude-code', name: 'Claude Code CLI', type: 'cli', command: 'claude', enabled: true, models: [] },+};++beforeEach(() => {+ __resetRuntimeStatusCache();+ __resetLatestVersionCache();+ providerService.getAllProviders.mockResolvedValue({ providers });+ providerService.updateProvider.mockClear();+});++// `usesHarnessCatalog` keys on the ABSENCE of a backend marker, so the class it+// names grows whenever an un-marked provider is seeded. This is the gate that+// makes that growth deliberate: it walks the shipped catalog and states exactly+// which records a "Refresh models" click may rewrite. Adding a provider here is+// a decision; arriving here by accident is the bug — a refresh would replace a+// working `models` list with ids that record's own backend cannot resolve.+describe('the shipped records a harness refresh may rewrite', () => {+ it('is exactly this list', async () => {+ const seed = JSON.parse(+ await import('node:fs').then(({ readFileSync }) => readFileSync(+ new URL('../../data.reference/providers.json', import.meta.url), 'utf8',+ )),+ );+ const rewritable = Object.values(seed.providers)+ .filter((provider) => {+ const runtime = PROVIDER_RUNTIMES.find((row) => [row.id, ...row.aliases].includes(providerRuntimeKey(provider)));+ return Boolean(runtime?.modelsArgs) && usesHarnessCatalog(provider);+ })+ .map((provider) => provider.id)+ .sort();++ expect(rewritable).toEqual([+ // The three harnesses that can enumerate their own models, crossed with+ // the wrappers that run those models natively. Every OpenCode wrapper+ // pointed at a local daemon or a hosted gateway is correctly absent.+ 'antigravity-cli', 'antigravity-tui',+ 'cursor-cli', 'cursor-tui',+ 'grok-cli', 'grok-tui',+ 'opencode-zen-cli', 'opencode-zen-tui',+ ]);+ });+});++describe('usesHarnessCatalog', () => {+ it('is true only for a wrapper with no local runtime and no gateway', () => {+ expect(usesHarnessCatalog(providers['opencode-zen-cli'])).toBe(true);+ // A gateway wrapper serves `openrouter/*`; a local one serves `ollama/*`.+ // Neither id ever appears in `opencode models`, so overwriting their lists+ // would point them at models their own config cannot resolve.+ expect(usesHarnessCatalog(providers['opencode-openrouter'])).toBe(false);+ expect(usesHarnessCatalog(providers['opencode-ollama'])).toBe(false);+ });++ it('reads the legacy per-gateway boolean, so old records need no migration', () => {+ expect(usesHarnessCatalog({ command: 'opencode', orcarouterBacked: true })).toBe(false);+ });+});++describe('listHarnesses', () => {+ // Every child-process and registry boundary is injected: nothing here spawns+ // a real CLI or reaches npm.+ const deps = () => ({+ findCommand: async (command) => (command === 'opencode' || command === 'npm' ? `/example/${command}` : null),+ probeCommand: async () => '1.18.27',+ run: async () => '9.9.9',+ });++ it('links each harness to the providers that launch it', async () => {+ const rows = await listHarnesses(deps());+ const opencode = rows.find((row) => row.id === 'opencode');++ expect(opencode.providers.map((provider) => provider.id).sort()).toEqual([+ 'opencode-ollama', 'opencode-openrouter', 'opencode-zen-cli', 'opencode-zen-tui',+ ]);+ // The Claude wrapper launches `claude`, so it must not appear here.+ expect(opencode.providers.some((provider) => provider.id === 'claude-code')).toBe(false);+ expect(opencode.providers.find((p) => p.id === 'opencode-zen-cli').usesHarnessCatalog).toBe(true);+ expect(opencode.providers.find((p) => p.id === 'opencode-ollama').usesHarnessCatalog).toBe(false);+ });++ it('never publishes a resolved executable path', async () => {+ // A global bin directory embeds the host account name.+ expect(JSON.stringify(await listHarnesses(deps()))).not.toContain('/example/');+ });++ // `providerRuntimeKey` answers "does the BARE binary resolve on PortOS's+ // PATH?" — which is not the question for a record that pins its own path or+ // its own PATH. Attributing those here would inflate the removal warning and+ // let a refresh rewrite them from a catalog a different binary printed.+ it('does not claim a provider that pins its own path or PATH', async () => {+ providerService.getAllProviders.mockResolvedValue({+ providers: {+ pathed: { id: 'pathed', type: 'cli', command: '/opt/tools/opencode', name: 'Pathed' },+ envd: { id: 'envd', type: 'cli', command: 'opencode', name: 'Own PATH', envVars: { PATH: '/opt/tools' } },+ plain: { id: 'plain', type: 'cli', command: 'opencode', name: 'Plain' },+ },+ });++ const opencode = (await listHarnesses(deps())).find((row) => row.id === 'opencode');++ expect(opencode.providers.map((provider) => provider.id)).toEqual(['plain']);+ });+});++describe('refreshHarnessModels', () => {+ // An npm-installed harness is a `.cmd` shim on Windows, which `execFile`+ // under `shell: false` refuses outright — probing the bare name would answer+ // nothing and tell a signed-in user to go sign in.+ it('probes the RESOLVED executable, the way the version probe does', async () => {+ const run = vi.fn(async (command, args) => (args[0] === 'models' ? OPENCODE_MODELS : '1.18.27'));++ await refreshHarnessModels('opencode', { run, ...found });++ expect(run).toHaveBeenCalledWith('/example/opencode', ['models'], expect.anything());+ });++ it('writes the harness catalog only to providers that draw from it', async () => {+ const run = vi.fn(async (command, args) => (args[0] === 'models' ? OPENCODE_MODELS : '1.18.27'));++ const result = await refreshHarnessModels('opencode', { run, ...found });++ expect(result.ok).toBe(true);+ expect(result.models).toEqual(['opencode/big-pickle', 'opencode/mimo-v2.5-free']);+ expect(result.updated.sort()).toEqual(['opencode-zen-cli', 'opencode-zen-tui']);+ expect(providerService.updateProvider).toHaveBeenCalledTimes(2);+ for (const [, patch] of providerService.updateProvider.mock.calls) {+ expect(patch.models).toEqual(['opencode/big-pickle', 'opencode/mimo-v2.5-free']);+ }+ });++ it('repoints a default model the harness no longer lists, and keeps one it does', async () => {+ const run = vi.fn(async (command, args) => (args[0] === 'models' ? OPENCODE_MODELS : '1.18.27'));+ providerService.getAllProviders.mockResolvedValue({+ providers: {+ stale: { id: 'stale', type: 'cli', command: 'opencode', models: [], defaultModel: 'opencode/gone' },+ kept: { id: 'kept', type: 'cli', command: 'opencode', models: [], defaultModel: 'opencode/mimo-v2.5-free' },+ },+ });++ await refreshHarnessModels('opencode', { run, ...found });++ const patches = Object.fromEntries(providerService.updateProvider.mock.calls);+ // A pin the refresh orphaned would leave the record requesting a model its+ // own picker no longer shows.+ expect(patches.stale.defaultModel).toBe('opencode/big-pickle');+ expect(patches.kept.defaultModel).toBe('opencode/mimo-v2.5-free');+ });++ it('refuses an empty probe rather than blanking every picker', async () => {+ // A signed-out CLI or a changed output shape both parse to nothing. Writing+ // that through would erase working model lists on a guess.+ const run = vi.fn(async (command, args) => (args[0] === 'models' ? '' : '1.18.27'));++ const result = await refreshHarnessModels('opencode', { run, ...found });++ expect(result.ok).toBe(false);+ expect(result.reason).toMatch(/no models/i);+ expect(providerService.updateProvider).not.toHaveBeenCalled();+ });++ it('refuses a harness that cannot list models, without spawning it', async () => {+ const run = vi.fn(async () => '2.1.259 (Claude Code)');++ const result = await refreshHarnessModels('claude', { run, ...found });++ expect(result.ok).toBe(false);+ expect(result.reason).toMatch(/no command for listing/i);+ expect(run).not.toHaveBeenCalled();+ });++ it('refuses an uninstalled harness and an unknown id', async () => {+ // The version probe answering `null` is "cannot run this binary".+ const missing = await refreshHarnessModels('opencode', { run: vi.fn(async () => null), ...found });+ expect(missing.ok).toBe(false);+ expect(missing.reason).toMatch(/not installed/i);++ expect((await refreshHarnessModels('not-a-harness')).ok).toBe(false);+ });+});diff --git a/server/services/providerRuntimeInstaller.js b/server/services/providerRuntimeInstaller.jsindex 27a8ab17ab..602d75e1b9 100644--- a/server/services/providerRuntimeInstaller.js+++ b/server/services/providerRuntimeInstaller.js@@ -1,5 +1,7 @@/**- * Provider runtime (CLI) availability and installation.+ * Provider runtime (CLI) availability, installation, update and removal — the+ * registry behind **Models → Harnesses** (`services/harnesses.js` composes this+ * with the provider records that point at each one).** A CLI/TUI provider is only as usable as the binary it shells out to, so the* AI Providers page asks this module "is `codex` runnable, and can PortOS@@ -37,7 +39,8 @@import { spawn } from '../lib/childProcess.js';import { killProcessTree, prepareCliSpawn } from '../lib/bufferedSpawn.js';-import { commandExists } from '../lib/commandExists.js';+import { commandOutput } from '../lib/commandExists.js';+import { parseHarnessVersion } from '../lib/harnessOutput.js';import { adoptNpmGlobalBinDir } from '../lib/npmGlobalBin.js';import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';import { PROVIDER_VENDORS } from '../lib/providerVendors.js';@@ -82,7 +85,7 @@ const STATUS_TTL_MS = 60_000;/*** Matches `codeReview.js`'s `REVIEWER_CLI_PROBE_TIMEOUT_MS` for these same- * binaries: `commandExists`'s 5s default is sized for lightweight tools like+ * binaries: `commandOutput`'s 5s default is sized for lightweight tools like* `brew --version` and previously clocked the heavier agentic CLIs as falsely* uninstalled under a cold start — which here would offer an install for a CLI* that is already there.@@ -95,30 +98,37 @@ const RUNTIME_ROWS = [vendor: 'claude',label: 'Claude Code CLI',install: { kind: 'npm', package: '@anthropic-ai/claude-code@latest' },+ selfUpdate: ['update'],docsUrl: 'https://docs.claude.com/en/docs/claude-code/setup',},{vendor: 'codex',label: 'Codex CLI',install: { kind: 'npm', package: '@openai/codex@latest' },+ selfUpdate: ['update'],docsUrl: 'https://developers.openai.com/codex/cli',},{vendor: 'opencode',label: 'OpenCode CLI',install: { kind: 'npm', package: 'opencode-ai@latest' },+ selfUpdate: ['upgrade'],+ modelsArgs: ['models'],docsUrl: 'https://opencode.ai/docs',},{vendor: 'grok',label: 'Grok Build CLI',install: { kind: 'npm', package: '@xai-official/grok@latest' },+ selfUpdate: ['update'],+ modelsArgs: ['models'],docsUrl: 'https://x.ai/cli',},{vendor: 'kimi',label: 'Kimi Code CLI',install: { kind: 'npm', package: '@kimi-code/cli@latest' },+ selfUpdate: ['upgrade'],docsUrl: 'https://moonshotai.github.io/kimi-cli/',},{@@ -130,12 +140,19 @@ const RUNTIME_ROWS = [aliases: ['antigravity'],// Antigravity ships a single compiled binary, not an npm package.install: { kind: 'script', url: 'https://antigravity.google/cli/install.sh' },+ selfUpdate: ['update'],+ modelsArgs: ['models'],docsUrl: 'https://antigravity.google/docs/cli/install',},{vendor: 'cursor',label: 'Cursor Agent CLI',install: { kind: 'script', url: 'https://cursor.com/install' },+ selfUpdate: ['update'],+ // `cursor-agent models` prints the authoritative catalog for THIS account —+ // the toolkit's provider-card refresh has read it for far longer than this+ // page has existed (`_fetchCursorModels`), so the parser was already there.+ modelsArgs: ['models'],docsUrl: 'https://cursor.com/docs/cli/installation',},];@@ -151,10 +168,24 @@ const vendorCommand = (vendorId) => {/*** The runtime table the routes serve. `id` IS the binary name, so a provider* card looks its runtime up straight from its `command` with no second mapping.+ *+ * `selfUpdate`, `modelsArgs` and `npmPackage` are the harness-management half+ * (Models → Harnesses): `selfUpdate` is the vendor's OWN updater subcommand,+ * which is the only correct update path for a binary the user installed some+ * other way (Homebrew, the vendor script) — re-running `npm install --global`+ * would write a second copy that may not even win on PATH, which is exactly how+ * an install goes stale with no visible way to refresh it. `npmPackage` is+ * present only for `npm`-kind rows, and it is what makes a row REMOVABLE: a+ * script-installed binary has no vendor-published uninstall PortOS can run.*/export const PROVIDER_RUNTIMES = Object.freeze(RUNTIME_ROWS.map((row) => Object.freeze({aliases: [],+ selfUpdate: null,+ modelsArgs: null,...row,+ // `@latest` is an install-time tag, not part of the package identity, and+ // `npm view`/`npm uninstall` both want it gone.+ npmPackage: row.install.kind === 'npm' ? row.install.package.replace(/@latest$/, '') : null,id: vendorCommand(row.vendor),command: vendorCommand(row.vendor),})));@@ -189,8 +220,15 @@ async function probeRuntimeStatus(runtime, findCommand, probeCommand) {// `.cmd` wrapper on Windows. The filesystem resolver gives us the real// executable; prepareCliSpawn then probes that same safe launch shape.const versionProbe = resolved ? prepareCliSpawn(resolved, ['--version']) : null;- const installed = Boolean(versionProbe)- && Boolean(await probeCommand(versionProbe.command, versionProbe.args, { timeoutMs: PROBE_TIMEOUT_MS }));+ // ONE probe contract: `commandOutput` answers the `--version` banner, or+ // `null` when the binary could not run. Availability and version come from+ // that single child — `parseHarnessVersion` already answers `null` for a+ // banner it cannot read, which is NOT-KNOWN rather than "out of date".+ const probed = versionProbe+ ? await probeCommand(versionProbe.command, versionProbe.args, { timeoutMs: PROBE_TIMEOUT_MS })+ : null;+ const installed = probed !== null;+ const version = parseHarnessVersion(probed);// Windows-only gap: the script-installed vendors publish a PowerShell// installer there, which PortOS deliberately does not run for the user.@@ -206,10 +244,19 @@ async function probeRuntimeStatus(runtime, findCommand, probeCommand) {label: runtime.label,command: runtime.command,installed,+ // `null` = the banner did not parse (or the probe answered a bare boolean),+ // NOT "0.0.0". Every version comparison bails on it rather than reporting a+ // perfectly current harness as out of date.+ version,method: kind,installable,blockedReason,docsUrl: runtime.docsUrl,+ // Harness-management capabilities, published so the page can render a+ // button per row instead of keeping its own copy of this table.+ updatable: Boolean(runtime.selfUpdate) || (kind === 'npm' && Boolean(toolPath)),+ removable: Boolean(runtime.npmPackage) && Boolean(toolPath),+ listsModels: Boolean(runtime.modelsArgs),};}@@ -235,7 +282,7 @@ export async function getProviderRuntimeStatus(id, { findCommand, probeCommand,// instead of probing the same binary twice.const cached = statusCache.get(runtime.id);if (!fresh && cached && Date.now() - cached.at < STATUS_TTL_MS) return cached.status;- const status = await probeRuntimeStatus(runtime, findCommand || findCommandOnPath, probeCommand || commandExists);+ const status = await probeRuntimeStatus(runtime, findCommand || findCommandOnPath, probeCommand || commandOutput);statusCache.set(runtime.id, { at: Date.now(), status });return status;}@@ -319,9 +366,65 @@ export function buildRuntimeInstallCommand(id) {return { command: 'bash', args: ['-c', `curl -fsSL ${runtime.install.url} | bash`] };}+/**+ * The one supported UPDATE invocation for a runtime, as an argv pair, or `null`+ * for an id not in the table.+ *+ * The vendor's own updater wins whenever it ships one, because it is the only+ * path that refreshes the copy the user ACTUALLY has: PortOS can install+ * OpenCode from npm, but a user who installed it from Homebrew or the vendor+ * script has a binary npm has never heard of, and `npm install --global` would+ * write a second copy that may not even win on PATH — leaving the stale one+ * running and no visible way to refresh it (the gap this page exists to close).+ * `opencode upgrade` updates whichever copy is on PATH, whoever installed it.+ *+ * An npm-kind row with no self-updater falls back to re-running the pinned+ * `@latest` install, which IS an update for a package manager.+ */+export function buildRuntimeUpdateCommand(id) {+ const runtime = getProviderRuntime(id);+ if (!runtime) return null;+ if (runtime.selfUpdate) return { command: runtime.command, args: [...runtime.selfUpdate] };+ if (runtime.install.kind === 'npm') return buildRuntimeInstallCommand(id);+ return null;+}++/**+ * The one supported REMOVE invocation, or `null` when PortOS must not offer+ * one. Only npm-kind rows qualify: a script-installed binary (Antigravity,+ * Cursor) has no vendor-published uninstall PortOS could run, and guessing at+ * `rm` paths for a binary this module deliberately never discloses is not a+ * removal, it's a deletion of whatever happened to be at a path.+ */+export function buildRuntimeUninstallCommand(id) {+ const runtime = getProviderRuntime(id);+ if (!runtime?.npmPackage) return null;+ return { command: 'npm', args: ['uninstall', '--global', '--no-progress', runtime.npmPackage] };+}++/** The argv builder for each supported harness action. */+const ACTION_BUILDERS = Object.freeze({+ install: buildRuntimeInstallCommand,+ update: buildRuntimeUpdateCommand,+ uninstall: buildRuntimeUninstallCommand,+});++/** The harness actions the routes accept — anything else is rejected unspawned. */+export const RUNTIME_ACTIONS = Object.freeze(Object.keys(ACTION_BUILDERS));++/**+ * The fixed invocation for one runtime action, or `null` when the action is+ * unknown or this runtime does not support it. Every argv comes from the table+ * above; no request value reaches a shell word.+ */+export function buildRuntimeActionCommand(id, action = 'install') {+ const build = Object.hasOwn(ACTION_BUILDERS, action) ? ACTION_BUILDERS[action] : null;+ return build ? build(id) : null;+}+/** A human-readable one-liner for the install log ("Running npm install …"). */-export function describeRuntimeInstall(id) {- const invocation = buildRuntimeInstallCommand(id);+export function describeRuntimeInstall(id, action = 'install') {+ const invocation = buildRuntimeActionCommand(id, action);return invocation ? `${invocation.command} ${invocation.args.join(' ')}` : null;}@@ -329,9 +432,12 @@ export function describeRuntimeInstall(id) {* Start a runtime's fixed install command with no request input in its argv.* `prepareCliSpawn` handles npm's Windows .cmd shim without falling back to* unsafe `shell: true`, and the returned child stays owned by the SSE route.+ *+ * `action` selects install / update / uninstall from the table; an unsupported+ * pairing returns `null` rather than falling back to a different action.*/-export function spawnRuntimeInstaller(id, { spawnImpl = spawn } = {}) {- const invocation = buildRuntimeInstallCommand(id);+export function spawnRuntimeInstaller(id, { spawnImpl = spawn, action = 'install' } = {}) {+ const invocation = buildRuntimeActionCommand(id, action);if (!invocation) return null;const env = safeChildProcessEnv();const { command, args } = prepareCliSpawn(invocation.command, invocation.args, env);diff --git a/server/services/providerRuntimeInstaller.test.js b/server/services/providerRuntimeInstaller.test.jsindex a5bbb7056c..3638ccabca 100644--- a/server/services/providerRuntimeInstaller.test.js+++ b/server/services/providerRuntimeInstaller.test.js@@ -7,7 +7,11 @@ const npmGlobalBin = vi.hoisted(() => ({ adoptNpmGlobalBinDir: vi.fn(async () =>vi.mock('../lib/npmGlobalBin.js', () => npmGlobalBin);import {+ buildRuntimeActionCommand,buildRuntimeInstallCommand,+ buildRuntimeUninstallCommand,+ buildRuntimeUpdateCommand,+ RUNTIME_ACTIONS,getProviderRuntime,getProviderRuntimeStatus,getProviderRuntimeStatuses,@@ -28,7 +32,9 @@ describe('provider runtime installer', () => {it('reports runnable availability as booleans without returning local paths', async () => {const findCommand = vi.fn(async (command) => command === 'opencode' ? '/example/opencode' : '/example/npm');- const probeCommand = vi.fn(async () => true);+ // The default probe answers the `--version` banner; a boolean probe is+ // still accepted and simply carries no version.+ const probeCommand = vi.fn(async () => '1.18.27');const status = await getProviderRuntimeStatus('opencode', { findCommand, probeCommand });@@ -37,10 +43,14 @@ describe('provider runtime installer', () => {label: 'OpenCode CLI',command: 'opencode',installed: true,+ version: '1.18.27',method: 'npm',installable: true,blockedReason: null,docsUrl: expect.stringContaining('http'),+ updatable: true,+ removable: true,+ listsModels: true,});expect(findCommand).toHaveBeenCalledWith('opencode');expect(findCommand).toHaveBeenCalledWith('npm');@@ -51,7 +61,7 @@ describe('provider runtime installer', () => {// A cold agentic CLI can take seconds to answer; commandExists's 5s default// clocked these as uninstalled, which here would offer a redundant install.it('probes with the longer agentic-CLI timeout', async () => {- const probeCommand = vi.fn(async () => false);+ const probeCommand = vi.fn(async () => null);await getProviderRuntimeStatus('codex', { findCommand: async () => '/example/codex', probeCommand });expect(probeCommand).toHaveBeenCalledWith('/example/codex', ['--version'], { timeoutMs: 15_000 });@@ -62,7 +72,7 @@ describe('provider runtime installer', () => {// the probe reports a perfectly installed CLI as missing, and the card offers// an install that can never take.it('adopts the npm global bin directory before probing', async () => {- await getProviderRuntimeStatus('codex', { findCommand: async () => null, probeCommand: async () => false });+ await getProviderRuntimeStatus('codex', { findCommand: async () => null, probeCommand: async () => null });expect(npmGlobalBin.adoptNpmGlobalBinDir).toHaveBeenCalled();});@@ -70,7 +80,7 @@ describe('provider runtime installer', () => {it('reports a PATH-resolved but broken CLI as unavailable', async () => {const status = await getProviderRuntimeStatus('codex', {findCommand: async () => '/example/codex',- probeCommand: async () => false,+ probeCommand: async () => null,});expect(status.installed).toBe(false);@@ -80,7 +90,7 @@ describe('provider runtime installer', () => {it('blocks an npm-backed install with a reason when npm is missing', async () => {const status = await getProviderRuntimeStatus('claude', {findCommand: async (command) => command === 'npm' ? null : '/example/claude',- probeCommand: async () => true,+ probeCommand: async () => '1.2.3',});expect(status.installable).toBe(false);@@ -88,7 +98,7 @@ describe('provider runtime installer', () => {});it('gates a script-backed install on curl and the platform', async () => {- const probeCommand = vi.fn(async () => false);+ const probeCommand = vi.fn(async () => null);const withCurl = await getProviderRuntimeStatus('cursor-agent', { findCommand: async () => '/example/curl', probeCommand });const withoutCurl = await getProviderRuntimeStatus('cursor-agent', { fresh: true, findCommand: async () => null, probeCommand });@@ -103,12 +113,12 @@ describe('provider runtime installer', () => {expect(getProviderRuntime(undefined)).toBeNull();expect(buildRuntimeInstallCommand('rm-rf')).toBeNull();expect(spawnRuntimeInstaller('rm-rf', { spawnImpl: () => { throw new Error('must not spawn'); } })).toBeNull();- await expect(getProviderRuntimeStatus('rm-rf', { findCommand: async () => null, probeCommand: async () => false })).resolves.toBeNull();+ await expect(getProviderRuntimeStatus('rm-rf', { findCommand: async () => null, probeCommand: async () => null })).resolves.toBeNull();});it('answers every runtime in one keyed map, resolving each install tool once', async () => {const findCommand = vi.fn(async () => null);- const statuses = await getProviderRuntimeStatuses({ findCommand, probeCommand: async () => false });+ const statuses = await getProviderRuntimeStatuses({ findCommand, probeCommand: async () => null });const published = PROVIDER_RUNTIMES.flatMap((runtime) => [runtime.id, ...runtime.aliases]);expect(Object.keys(statuses).sort()).toEqual(published.sort());@@ -122,8 +132,8 @@ describe('provider runtime installer', () => {// miss costs a child process per runtime.it('serves repeat reads from the TTL cache and re-probes on demand', async () => {const findCommand = async () => '/example/bin';- const missing = vi.fn(async () => false);- const present = vi.fn(async () => true);+ const missing = vi.fn(async () => null);+ const present = vi.fn(async () => '1.2.3');const first = await getProviderRuntimeStatus('codex', { findCommand, probeCommand: missing });const second = await getProviderRuntimeStatus('codex', { findCommand, probeCommand: present });@@ -184,7 +194,7 @@ describe('provider runtime installer', () => {}}- const statuses = await getProviderRuntimeStatuses({ findCommand: async () => null, probeCommand: async () => false });+ const statuses = await getProviderRuntimeStatuses({ findCommand: async () => null, probeCommand: async () => null });// Same object under both spellings, and its id stays canonical so the// install POST names the runtime the table knows.expect(statuses.antigravity).toBe(statuses.agy);@@ -201,7 +211,7 @@ describe('provider runtime installer', () => {it('returns a probed runtime, under its aliases too, without probing again', async () => {const findCommand = vi.fn(async () => null);- await getProviderRuntimeStatus('agy', { findCommand, probeCommand: async () => false });+ await getProviderRuntimeStatus('agy', { findCommand, probeCommand: async () => null });findCommand.mockClear();const peeked = peekProviderRuntimeStatuses();@@ -216,7 +226,7 @@ describe('provider runtime installer', () => {// a CLI the user installed from a terminal stays skipped by routing until// something else happens to re-probe.it('drops a status once its TTL is up, so an expired negative reads as unprobed', async () => {- await getProviderRuntimeStatus('codex', { findCommand: async () => null, probeCommand: async () => false });+ await getProviderRuntimeStatus('codex', { findCommand: async () => null, probeCommand: async () => null });expect(peekProviderRuntimeStatuses().codex.installed).toBe(false);vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 61_000);@@ -238,3 +248,75 @@ describe('provider runtime installer', () => {}});});++describe('harness lifecycle actions', () => {+ // The vendor's own updater is the ONLY path that refreshes the copy actually+ // on PATH. A Homebrew- or script-installed OpenCode is invisible to npm, so+ // re-running `npm install --global` writes a second copy that may not win the+ // PATH race and leaves the stale binary running — the exact failure the+ // Harnesses page exists to fix.+ it('prefers a vendor self-updater over re-running the npm install', () => {+ expect(buildRuntimeUpdateCommand('opencode')).toEqual({ command: 'opencode', args: ['upgrade'] });+ expect(buildRuntimeUpdateCommand('agy')).toEqual({ command: 'agy', args: ['update'] });+ });++ it('exposes update and uninstall through the shared action builder', () => {+ expect(buildRuntimeActionCommand('opencode', 'install')).toEqual(buildRuntimeInstallCommand('opencode'));+ expect(buildRuntimeActionCommand('opencode', 'update')).toEqual(buildRuntimeUpdateCommand('opencode'));+ expect(buildRuntimeActionCommand('opencode', 'uninstall')).toEqual(buildRuntimeUninstallCommand('opencode'));+ });++ it('removes only what a package manager installed', () => {+ expect(buildRuntimeUninstallCommand('opencode')).toEqual({+ command: 'npm',+ args: ['uninstall', '--global', '--no-progress', 'opencode-ai'],+ });+ // Script-installed vendors publish no uninstall PortOS can run; guessing at+ // `rm` paths would delete whatever happens to sit at a path, not the binary.+ expect(buildRuntimeUninstallCommand('agy')).toBeNull();+ expect(buildRuntimeUninstallCommand('cursor-agent')).toBeNull();+ });++ it('refuses an unknown action and an unknown runtime rather than falling back', () => {+ // A silent fallback to `install` would turn a typo'd action into a global+ // package write.+ expect(buildRuntimeActionCommand('opencode', 'purge')).toBeNull();+ expect(buildRuntimeActionCommand('not-a-harness', 'install')).toBeNull();+ expect(spawnRuntimeInstaller('opencode', { action: 'purge', spawnImpl: () => 'spawned' })).toBeNull();+ });++ // Three places name this action set: the argv builders here, the SSE runner's+ // copy table, and the route's zod enum. They cannot import each other freely+ // (lib must not import services), so this is what keeps them from drifting —+ // a fourth action added to one alone would reach `HARNESS_ACTION_COPY[action]`+ // as `undefined` and crash mid-stream, or be refused at the boundary.+ it('publishes exactly the actions the routes accept', async () => {+ expect([...RUNTIME_ACTIONS].sort()).toEqual(['install', 'uninstall', 'update']);++ const { HARNESS_ACTION_COPY } = await import('./harnessActionStream.js');+ expect(Object.keys(HARNESS_ACTION_COPY).sort()).toEqual([...RUNTIME_ACTIONS].sort());++ const { harnessActionSchema } = await import('../lib/validation.js');+ expect([...harnessActionSchema.shape.action.unwrap().unwrap().options].sort())+ .toEqual([...RUNTIME_ACTIONS].sort());+ });++ it('strips the @latest install tag from the package identity', () => {+ // `npm view <pkg>@latest version` and `npm uninstall -g <pkg>@latest` both+ // want the bare name; the tag belongs only to the install invocation.+ for (const runtime of PROVIDER_RUNTIMES) {+ if (runtime.install.kind !== 'npm') { expect(runtime.npmPackage).toBeNull(); continue; }+ expect(runtime.npmPackage).not.toMatch(/@latest$/);+ expect(runtime.install.package).toBe(`${runtime.npmPackage}@latest`);+ }+ });++ // The parser table in lib/harnessOutput.js and the `modelsArgs` here are two+ // halves of one capability: a row claiming it can list models with no parser+ // would report an empty catalog and refuse forever.+ it('declares modelsArgs for exactly the harnesses harnessOutput can parse', async () => {+ const { HARNESS_MODEL_PARSER_IDS } = await import('../lib/harnessOutput.js');+ const declared = PROVIDER_RUNTIMES.filter((runtime) => runtime.modelsArgs).map((runtime) => runtime.id);+ expect(declared.sort()).toEqual([...HARNESS_MODEL_PARSER_IDS].sort());+ });+});