Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: stabilize OpenCode installer and TUI startup failures (#4403)

[._.]/ Adam Eivy44859e64e76a
diff --git a/.changelog/next/added-main.md b/.changelog/next/added-main.md
new file mode 100644
index 0000000000..0e7facfc10
--- /dev/null
+++ b/.changelog/next/added-main.md
@@ -0,0 +1 @@
+- Add a self-service OpenCode CLI installer in AI Providers
diff --git a/.changelog/next/fixed-main.md b/.changelog/next/fixed-main.md
new file mode 100644
index 0000000000..b3343e6769
--- /dev/null
+++ b/.changelog/next/fixed-main.md
@@ -0,0 +1,2 @@
+- OpenCode installation no longer replays or rapidly redraws the Providers page.
+- Unavailable or broken CoS TUI provider CLIs now show actionable startup errors instead of a blank failure.
diff --git a/client/src/components/install/RuntimeInstallModal.jsx b/client/src/components/install/RuntimeInstallModal.jsx
index 8b2433c14d..5d124dd65b 100644
--- a/client/src/components/install/RuntimeInstallModal.jsx
+++ b/client/src/components/install/RuntimeInstallModal.jsx
@@ -3,8 +3,8 @@
* from a setup endpoint (SSE) and shows raw bash output line-by-line so the
* user sees git/uv/pip progress while scripts/setup-image-video.sh runs.
*
- * Closing the modal mid-install terminates the EventSource, which the server
- * interprets as a cancel and SIGTERMs the underlying bash child.
+ * Closing the modal mid-install terminates its EventSource or fetch stream,
+ * which the server interprets as a cancel and SIGTERMs the underlying child.
*/
import { useEffect, useState } from 'react';
@@ -26,13 +26,18 @@ export default function RuntimeInstallModal({
// (e.g. TRELLIS.2's `repair=1`, which re-runs setup.sh over an existing install
// to rebuild backends that failed to compile the first time — #2952).
params,
+ // EventSource is GET-only. Installers that mutate host state use POST via the
+ // hook's fetch-stream mode so a dropped connection cannot auto-retry work.
+ streamMethod = 'GET',
+ // Chatty installers keep the rendered log stable by batching lines.
+ flushMs = 100,
}) {
const [confirmingCancel, setConfirmingCancel] = useState(false);
const query = new URLSearchParams({ runtime: runtime ?? '', ...(params || {}) });
const url = open && runtime ? `${installUrlBase}?${query}` : null;
const { logs, done, error, streamStarted, logsEndRef, close } = useInstallStream(
url,
- { enabled: open && !!runtime, onComplete, maxLogLines: MAX_LOG_LINES, flushMs: 100 },
+ { enabled: open && !!runtime, onComplete, maxLogLines: MAX_LOG_LINES, flushMs, method: streamMethod },
);
useEffect(() => { if (!open || !runtime) setConfirmingCancel(false); }, [open, runtime]);
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 3bf7ac3205..f1f1d262ef 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -38,7 +38,7 @@ grep -i "what you want to do" client/src/hooks/README.md
|---|---|---|
| `useSseProgress` | Generic JSON-frame EventSource subscriber. | New SSE progress stream — start here, build on top. |
| `useSseJobSlot` | Generic single-slot SSE job: `pending`/`job` state, terminal-frame handling (`complete`/`error`/`canceled`), and `sse.closed`-without-terminal-frame recovery in one place. Returns `{ active, percent, stage, context, start, cancel }`; pass `startRequest`/`eventsUrl`/`cancelRequest` + per-feature toast copy. | Any "kick off a job → stream SSE → settle on terminal frame" hook. The reference-audio/YouTube/video-download/MIDI hooks all wrap this — don't re-roll the terminal-frame + lost-connection dance. |
-| `useInstallStream` | BYO-runtime install-log EventSource lifecycle: `stage`/`log`/`complete`/`error` frame dispatch, capped + optionally-debounced log accumulation, "connection lost" handling, ref-stashed `onComplete`, auto-scroll. | A streamed install/setup modal that shows live SSE log lines (FLUX.2, video runtimes). Don't re-roll the EventSource teardown/onComplete-ref dance. |
+| `useInstallStream` | BYO-runtime install-log stream lifecycle: `stage`/`log`/`complete`/`error` frame dispatch, capped + optionally-debounced log accumulation, "connection lost" handling, ref-stashed `onComplete`, auto-scroll. `method: 'GET'` uses EventSource; `method: 'POST'` reads one fetch stream for a non-idempotent install. | A streamed install/setup modal that shows live SSE log lines (FLUX.2, video runtimes, OpenCode). Don't re-roll the teardown/onComplete-ref dance. |
| `useModelDownloadStatus` | Image/video model cache-status + SSE pre-download. `start(id)` commands a pull; `startWhenIdle(id)` requests one — it waits for the cache verdict, skips an already-resident repo, and queues behind whatever owns the single EventSource lane (`queuedModelId` while it waits, falsy id to retract). | Surfacing "Available" vs "Download" badge inline in the gen form; `startWhenIdle` for a picker where choosing an option IS the request for its weights. |
| `useAgyModels` | Live `agy models` probe (the AGENT models `--model` accepts) with `models`/`error`/`loading`/`refresh`; opt-in via an `enabled` flag so it never spawns for a disabled backend. | Any Agy model picker — the Settings default or the per-render override. Don't hardcode a model list: agy exits non-zero on an id outside this catalog. |
| `useSpritePendingRenders` | Sprite-workflow in-flight render map: queue rehydrate + 4s poll keyed by a media-job tag field, `'submitting'` double-render guard, 404-only drop, deferred `onChanged` sweeps. | A sprite workflow tracking `queued/running` media jobs by tag (reference renders, walk videos, phase-4 publish) — don't re-roll the rehydrate/poll dance. |
diff --git a/client/src/hooks/useInstallStream.js b/client/src/hooks/useInstallStream.js
index 01c81091fb..1a167ec57f 100644
--- a/client/src/hooks/useInstallStream.js
+++ b/client/src/hooks/useInstallStream.js
@@ -1,8 +1,9 @@
import { useEffect, useRef, useState } from 'react';
import { safeParseJSON } from '../lib/genUtils';
+import { maybeRedirectToLogin } from '../services/apiCore';
/**
- * Shared EventSource lifecycle for the BYO runtime install modals
+ * Shared streaming lifecycle for the BYO runtime install modals
* (Flux2InstallModal, RuntimeInstallModal). Both streamed the same shape of
* SSE install log — open on `open`, dispatch `stage`/`log`/`complete`/`error`
* frames, cap the retained log, surface a "connection lost" error when the
@@ -16,8 +17,9 @@ import { safeParseJSON } from '../lib/genUtils';
* { type: 'complete', message } → done=true, onComplete(), closes
* { type: 'error', message } → error set, closes
*
- * Closing the EventSource (via `close()` on cancel, or unmount/disable) is what
- * the server interprets as a cancel — it SIGTERMs the underlying pip/bash child.
+ * Closing the EventSource or aborting the fetch stream (via `close()` on
+ * cancel, or unmount/disable) is what the server interprets as a cancel — it
+ * SIGTERMs the underlying pip/bash child.
*
* Deliberately NOT built on `useSseProgress`: this needs kind-tagged log
* accumulation with a cap + optional debounced flush, stage tracking, a
@@ -36,6 +38,8 @@ import { safeParseJSON } from '../lib/genUtils';
* @param {() => void} [opts.onComplete] - fired once on the `complete` frame.
* @param {number} [opts.maxLogLines=500] - cap on retained log lines.
* @param {number} [opts.flushMs=0] - 0 = per-line flush; >0 = debounce window.
+ * @param {'GET'|'POST'} [opts.method='GET'] - GET uses EventSource; POST uses
+ * a single fetch-read SSE response for a non-idempotent install.
* @returns {{ logs, currentStage, done, error, streamStarted, logsEndRef, close }}
*/
@@ -47,6 +51,7 @@ export function useInstallStream(url, {
onComplete,
maxLogLines = DEFAULT_MAX_LOG_LINES,
flushMs = 0,
+ method = 'GET',
} = {}) {
const [logs, setLogs] = useState([]);
const [currentStage, setCurrentStage] = useState(null);
@@ -55,6 +60,7 @@ export function useInstallStream(url, {
const [streamStarted, setStreamStarted] = useState(false);
const logsEndRef = useRef(null);
const esRef = useRef(null);
+ const abortRef = useRef(null);
// Mirror `done` into a ref so es.onerror reads the latest value — the effect
// closure captures the initial done=false and never refreshes, so without
// this the modal can flash "Connection lost" when the server cleanly closes
@@ -99,6 +105,7 @@ export function useInstallStream(url, {
};
const closeStream = () => {
if (esRef.current) { esRef.current.close(); esRef.current = null; }
+ if (abortRef.current) { abortRef.current.abort(); abortRef.current = null; }
};
if (!enabled || !url) {
@@ -123,17 +130,7 @@ export function useInstallStream(url, {
doneRef.current = false;
setError(null);
setStreamStarted(true);
- const es = new EventSource(url);
- esRef.current = es;
- // Close the instance that fired this event, not whatever esRef currently
- // points at — so a late callback from a superseded stream can't tear down
- // (or null out) a newer one after a url/enabled change.
- const closeThis = () => { if (esRef.current === es) esRef.current = null; es.close(); };
-
- es.onmessage = (ev) => {
- if (esRef.current !== es) return; // stale callback from a superseded stream
- const msg = safeParseJSON(ev.data);
- if (!msg) return;
+ const handleMessage = (msg, closeThis) => {
if (msg.type === 'stage') {
setCurrentStage(msg.stage);
appendLog({ kind: 'stage', text: msg.message || msg.stage });
@@ -147,13 +144,98 @@ export function useInstallStream(url, {
closeThis();
onCompleteRef.current?.();
} else if (msg.type === 'error') {
- setError(msg.message);
- appendLog({ kind: 'error', text: msg.message });
+ const message = msg.message || 'Installer failed.';
+ setError(message);
+ appendLog({ kind: 'error', text: message });
flush();
closeThis();
}
};
+ // A global CLI install changes host state. EventSource transparently
+ // reconnects after a transport drop, which would replay a non-idempotent
+ // request. POST callers use exactly one fetch stream instead. Delay the
+ // fetch one task turn so React's development-only strict-effect probe
+ // tears down before any request leaves the browser; otherwise its setup →
+ // cleanup → setup cycle can briefly start and cancel the same install.
+ if (String(method).toUpperCase() === 'POST') {
+ const controller = new AbortController();
+ abortRef.current = controller;
+ const isCurrent = () => abortRef.current === controller && !controller.signal.aborted;
+ const closeThis = () => {
+ if (abortRef.current === controller) abortRef.current = null;
+ controller.abort();
+ };
+ const startTimer = setTimeout(() => {
+ if (!isCurrent()) return;
+ const run = async () => {
+ let reader = null;
+ try {
+ const response = await fetch(url, { method: 'POST', signal: controller.signal });
+ if (!response.ok || !response.body?.getReader) {
+ const err = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));
+ maybeRedirectToLogin(response, err);
+ throw new Error(err.error || `HTTP ${response.status}`);
+ }
+
+ reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = '';
+ let terminalFrame = false;
+ const consumeFrame = (frame) => {
+ const dataLine = frame.split(/\r?\n/).find(line => line.startsWith('data:'));
+ if (!dataLine || !isCurrent()) return;
+ const msg = safeParseJSON(dataLine.slice('data:'.length).trim());
+ if (!msg) return;
+ terminalFrame ||= msg.type === 'complete' || msg.type === 'error';
+ handleMessage(msg, closeThis);
+ };
+
+ for (;;) {
+ const { done: streamDone, value } = await reader.read();
+ if (streamDone) break;
+ buffer += decoder.decode(value, { stream: true });
+ const frames = buffer.split(/\r?\n\r?\n/);
+ buffer = frames.pop() || '';
+ for (const frame of frames) consumeFrame(frame);
+ if (!isCurrent()) break;
+ }
+ buffer += decoder.decode();
+ if (isCurrent() && buffer.trim()) consumeFrame(buffer);
+ if (isCurrent() && !terminalFrame && !doneRef.current) {
+ setError((prev) => prev ?? CONNECTION_LOST_MESSAGE);
+ }
+ } catch (err) {
+ if (isCurrent()) setError((prev) => prev ?? (err?.message || CONNECTION_LOST_MESSAGE));
+ } finally {
+ if (reader) await reader.cancel().catch(() => {});
+ if (abortRef.current === controller) abortRef.current = null;
+ }
+ };
+ run();
+ }, 0);
+
+ return () => {
+ clearTimeout(startTimer);
+ clearFlush();
+ closeThis();
+ };
+ }
+
+ const es = new EventSource(url);
+ esRef.current = es;
+ // Close the instance that fired this event, not whatever esRef currently
+ // points at — so a late callback from a superseded stream can't tear down
+ // (or null out) a newer one after a url/enabled change.
+ const closeThis = () => { if (esRef.current === es) esRef.current = null; es.close(); };
+
+ es.onmessage = (ev) => {
+ if (esRef.current !== es) return; // stale callback from a superseded stream
+ const msg = safeParseJSON(ev.data);
+ if (!msg) return;
+ handleMessage(msg, closeThis);
+ };
+
es.onerror = () => {
if (esRef.current !== es) return; // stale callback from a superseded stream
// Network drop or server killed the stream. If we already saw `complete`
@@ -168,7 +250,7 @@ export function useInstallStream(url, {
closeThis();
};
// onComplete intentionally excluded — it lives in onCompleteRef.
- }, [url, enabled, maxLogLines, flushMs]);
+ }, [url, enabled, maxLogLines, flushMs, method]);
// Auto-scroll on every new line. behavior:'auto' (instant) avoids queueing
// hundreds of smooth-scroll animations during a chatty install.
@@ -180,6 +262,7 @@ export function useInstallStream(url, {
const close = () => {
if (esRef.current) { esRef.current.close(); esRef.current = null; }
+ if (abortRef.current) { abortRef.current.abort(); abortRef.current = null; }
};
return { logs, currentStage, done, error, streamStarted, logsEndRef, close };
diff --git a/client/src/hooks/useInstallStream.test.jsx b/client/src/hooks/useInstallStream.test.jsx
index 92435b3c32..70cf8eaf47 100644
--- a/client/src/hooks/useInstallStream.test.jsx
+++ b/client/src/hooks/useInstallStream.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { renderHook, act } from '@testing-library/react';
+import { renderHook, act, waitFor } from '@testing-library/react';
import { useInstallStream } from './useInstallStream';
import { MockEventSource, lastEventSource as last } from '../test/mockEventSource';
@@ -11,6 +11,7 @@ beforeEach(() => {
});
afterEach(() => {
+ vi.unstubAllGlobals();
delete global.EventSource;
vi.useRealTimers();
});
@@ -32,6 +33,41 @@ describe('useInstallStream', () => {
expect(result.current.streamStarted).toBe(true);
});
+ it('reads a POST installer stream with fetch instead of a reconnecting EventSource', async () => {
+ const encoder = new TextEncoder();
+ const read = vi.fn()
+ .mockResolvedValueOnce({
+ done: false,
+ value: encoder.encode('data: {"type":"log","message":"Installing"}\n\ndata: {"type":"complete","message":"Ready"}\n\n'),
+ })
+ .mockResolvedValueOnce({ done: true });
+ const cancel = vi.fn().mockResolvedValue(undefined);
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ body: { getReader: () => ({ read, cancel }) },
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const { result } = renderHook(() => useInstallStream('/api/providers/opencode/install', {
+ enabled: true,
+ method: 'POST',
+ }));
+
+ await waitFor(() => expect(result.current.done).toBe(true));
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/api/providers/opencode/install',
+ expect.objectContaining({ method: 'POST' }),
+ );
+ expect(MockEventSource.instances).toHaveLength(0);
+ expect(result.current.logs).toEqual([
+ { kind: 'log', text: 'Installing' },
+ { kind: 'success', text: 'Ready' },
+ ]);
+ await waitFor(() => expect(cancel).toHaveBeenCalledOnce());
+ });
+
it('tracks stages and logs them', () => {
const { result } = renderHook(() => useInstallStream('/x', { enabled: true }));
act(() => { last().emit({ type: 'stage', stage: 'venv', message: 'Creating venv' }); });
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index fe48703feb..5653ea76a1 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -22,6 +22,7 @@ import CodeReviewDefaultsPanel from '../components/providers/CodeReviewDefaultsP
import EffortSelect from '../components/cos/EffortSelect';
import Modal from '../components/ui/Modal';
import { FormField } from '../components/ui/FormField';
+import RuntimeInstallModal from '../components/install/RuntimeInstallModal';
// One phrasing for "this command isn't on the CoS Agent Runner's allowlist",
// shared by the provider-card badge tooltip and the editor's inline banner.
@@ -68,6 +69,10 @@ export default function AIProviders() {
const [sampleProviders, setSampleProviders] = useState([]);
const [loadingSamples, setLoadingSamples] = useState(false);
const [addingSample, setAddingSample] = useState({});
+ // `null` means the availability endpoint was not reached (for example, an
+ // older server during an upgrade), distinct from a confirmed missing CLI.
+ const [opencodeInstallStatus, setOpenCodeInstallStatus] = useState(null);
+ const [showOpenCodeInstaller, setShowOpenCodeInstaller] = useState(false);
useEffect(() => {
loadData();
@@ -103,14 +108,15 @@ export default function AIProviders() {
setLoading(true);
setLoadError(false);
let providersFailed = false;
- const [providersData, appsData, runsData, statusData] = await Promise.all([
+ const [providersData, appsData, runsData, statusData, opencodeData] = await Promise.all([
api.getProviders().catch(() => {
providersFailed = true;
return null;
}),
api.getApps().catch(() => []),
api.getRuns(20).catch(() => ({ runs: [] })),
- api.getProviderStatuses().catch(() => ({ providers: {} }))
+ api.getProviderStatuses().catch(() => ({ providers: {} })),
+ api.getOpenCodeInstallStatus({ silent: true }).catch(() => null),
]);
if (providersFailed || !providersData) {
setLoadError(true);
@@ -129,6 +135,9 @@ export default function AIProviders() {
setApps(appsData);
setRuns(runsData.runs || []);
setStatuses(statusData.providers || {});
+ setOpenCodeInstallStatus(opencodeData && typeof opencodeData.installed === 'boolean'
+ ? opencodeData
+ : null);
setLoading(false);
};
@@ -281,6 +290,11 @@ export default function AIProviders() {
}
};
+ const handleOpenCodeInstallComplete = () => {
+ toast.success('OpenCode CLI installed and ready to test');
+ loadData();
+ };
+
const selectedRunProvider = providers.find(p => p.id === activeProviderId);
const runProviderIsTui = isTuiProvider(selectedRunProvider);
@@ -332,6 +346,39 @@ export default function AIProviders() {
</div>
</div>
+ {opencodeInstallStatus && (
+ <div className={`rounded-xl border p-4 flex flex-col sm:flex-row sm:items-center justify-between gap-4 ${
+ opencodeInstallStatus.installed
+ ? 'border-port-success/40 bg-port-success/5'
+ : 'border-port-warning/40 bg-port-warning/5'
+ }`}>
+ <div className="min-w-0">
+ <h2 className="text-base font-semibold text-white">OpenCode CLI</h2>
+ {opencodeInstallStatus.installed ? (
+ <p className="mt-1 text-sm text-port-success">Available on PortOS&apos;s PATH. OpenCode CLI and TUI providers can run.</p>
+ ) : (
+ <>
+ <p className="mt-1 text-sm text-gray-300">Required by OpenCode CLI and TUI providers. Install it here before sending an OpenCode agent task.</p>
+ {!opencodeInstallStatus.npmAvailable && (
+ <p className="mt-1 text-xs text-port-warning">npm is not available on PortOS&apos;s PATH, so this host cannot install OpenCode from the page.</p>
+ )}
+ </>
+ )}
+ </div>
+ {!opencodeInstallStatus.installed && (
+ <button
+ type="button"
+ onClick={() => setShowOpenCodeInstaller(true)}
+ disabled={!opencodeInstallStatus.npmAvailable}
+ className="min-h-[44px] shrink-0 px-4 py-2 rounded-lg text-sm font-medium bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"
+ title={opencodeInstallStatus.npmAvailable ? 'Install OpenCode CLI with npm' : 'npm is required to install OpenCode from this page'}
+ >
+ Install OpenCode
+ </button>
+ )}
+ </div>
+ )}
+
{/* Sample Providers Panel */}
{showSamples && (
<div className="bg-port-card border border-port-border rounded-xl p-4 space-y-4">
@@ -782,6 +829,17 @@ export default function AIProviders() {
onSave={() => { setShowForm(false); setEditingProvider(null); loadData(); }}
/>
)}
+ <RuntimeInstallModal
+ open={showOpenCodeInstaller}
+ runtime="opencode"
+ label="OpenCode CLI"
+ onClose={() => setShowOpenCodeInstaller(false)}
+ onComplete={handleOpenCodeInstallComplete}
+ installUrlBase="/api/providers/opencode/install"
+ streamMethod="POST"
+ flushMs={250}
+ description="Installing the OpenCode CLI with npm. This downloads the current OpenCode package."
+ />
</div>
</div>
);
diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsx
index 8c782a21b2..21ff2e27e5 100644
--- a/client/src/pages/AIProviders.test.jsx
+++ b/client/src/pages/AIProviders.test.jsx
@@ -7,6 +7,7 @@ const api = vi.hoisted(() => ({
getApps: vi.fn(),
getRuns: vi.fn(),
getProviderStatuses: vi.fn(),
+ getOpenCodeInstallStatus: vi.fn(),
getSampleProviders: vi.fn(),
createProvider: vi.fn(),
updateProvider: vi.fn(),
@@ -38,6 +39,9 @@ vi.mock('../components/settings/SettingsTabsHeader', () => ({
vi.mock('../components/providers/CodeReviewDefaultsPanel', () => ({
default: () => <div data-testid="code-review-defaults-panel" />,
}));
+vi.mock('../components/install/RuntimeInstallModal', () => ({
+ default: ({ open, streamMethod, flushMs }) => open ? <div data-testid="opencode-install-modal" data-stream-method={streamMethod} data-flush-ms={flushMs} /> : null,
+}));
import AIProviders from './AIProviders';
@@ -53,6 +57,41 @@ describe('AIProviders page load error handling', () => {
api.getApps.mockResolvedValue([]);
api.getRuns.mockResolvedValue({ runs: [] });
api.getProviderStatuses.mockResolvedValue({ providers: {} });
+ api.getOpenCodeInstallStatus.mockResolvedValue({ installed: false, npmAvailable: true });
+ });
+
+ it('offers an in-page OpenCode install when the CLI is missing', async () => {
+ api.getProviders.mockResolvedValue({ providers: [], activeProvider: null });
+
+ renderPage();
+
+ expect(await screen.findByText('OpenCode CLI')).toBeInTheDocument();
+ const install = screen.getByRole('button', { name: 'Install OpenCode' });
+ expect(install).toBeEnabled();
+ fireEvent.click(install);
+ const modal = screen.getByTestId('opencode-install-modal');
+ expect(modal).toHaveAttribute('data-stream-method', 'POST');
+ expect(modal).toHaveAttribute('data-flush-ms', '250');
+ });
+
+ it('reports OpenCode as ready instead of offering another install', async () => {
+ api.getProviders.mockResolvedValue({ providers: [], activeProvider: null });
+ api.getOpenCodeInstallStatus.mockResolvedValue({ installed: true, npmAvailable: true });
+
+ renderPage();
+
+ expect(await screen.findByText(/Available on PortOS's PATH/)).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Install OpenCode' })).not.toBeInTheDocument();
+ });
+
+ it('explains why the install action is unavailable without npm', async () => {
+ api.getProviders.mockResolvedValue({ providers: [], activeProvider: null });
+ api.getOpenCodeInstallStatus.mockResolvedValue({ installed: false, npmAvailable: false });
+
+ renderPage();
+
+ expect(await screen.findByText(/npm is not available on PortOS's PATH/)).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Install OpenCode' })).toBeDisabled();
});
it('renders provider list when api.getProviders succeeds with data', async () => {
@@ -120,6 +159,7 @@ describe('handleAddSample error handling', () => {
api.getApps.mockResolvedValue([]);
api.getRuns.mockResolvedValue({ runs: [] });
api.getProviderStatuses.mockResolvedValue({ providers: {} });
+ api.getOpenCodeInstallStatus.mockResolvedValue({ installed: false, npmAvailable: true });
api.getProviders.mockResolvedValue({
providers: [],
activeProvider: null,
@@ -156,6 +196,7 @@ describe('handleAddAllSamples partial failure handling', () => {
api.getApps.mockResolvedValue([]);
api.getRuns.mockResolvedValue({ runs: [] });
api.getProviderStatuses.mockResolvedValue({ providers: {} });
+ api.getOpenCodeInstallStatus.mockResolvedValue({ installed: false, npmAvailable: true });
api.getProviders.mockResolvedValue({
providers: [],
activeProvider: null,
@@ -201,6 +242,7 @@ describe('CoS Agent Runner allowlist warning', () => {
api.getApps.mockResolvedValue([]);
api.getRuns.mockResolvedValue({ runs: [] });
api.getProviderStatuses.mockResolvedValue({ providers: {} });
+ api.getOpenCodeInstallStatus.mockResolvedValue({ installed: false, npmAvailable: true });
});
it('badges a provider whose command is off the published allowlist', async () => {
@@ -300,6 +342,7 @@ describe('Local num_ctx field', () => {
api.getApps.mockResolvedValue([]);
api.getRuns.mockResolvedValue({ runs: [] });
api.getProviderStatuses.mockResolvedValue({ providers: {} });
+ api.getOpenCodeInstallStatus.mockResolvedValue({ installed: false, npmAvailable: true });
});
const openEditorFor = async (provider) => {
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 7f4ef424e3..ce5fb956f9 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -51,7 +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 forwarding / allocation. |
-| `apiProviders.js` | AI provider config. |
+| `apiProviders.js` | AI provider configuration and safe OpenCode CLI installation readiness. |
| `apiPrompts.js` | Prompt Manager: stage templates, variables, and job-skill templates (providers list reuses `apiProviders.getProviders`). |
| `apiReferenceRepos.js` | Per-app reference-repo registry. |
| `apiReview.js` | Review hub. |
diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.js
index 220f14791c..24c352d481 100644
--- a/client/src/services/apiProviders.js
+++ b/client/src/services/apiProviders.js
@@ -22,6 +22,9 @@ export const deleteProvider = (id) => request(`/providers/${id}`, { method: 'DEL
export const getSampleProviders = () => request('/providers/samples');
export const testProvider = (id) => request(`/providers/${id}/test`, { method: 'POST' });
export const refreshProviderModels = (id, options) => request(`/providers/${id}/refresh-models`, { method: 'POST', ...options });
+// OpenCode is installed only after an explicit Providers-page click. The
+// status endpoint carries booleans only — never local executable paths.
+export const getOpenCodeInstallStatus = (options) => request('/providers/opencode/installation', options);
// Provider status (usage limits, availability)
export const getProviderStatuses = () => request('/providers/status');
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index b67870172e..5ef20998af 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -20,6 +20,8 @@ import { ensureDir, PATHS, sleep } from '../lib/fileUtils.js';
import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
import { prepareCliPrompt } from '../lib/cliProviderArgs.js';
+import { commandExists } from '../lib/commandExists.js';
+import { findCommandOnPath } from '../lib/processEnv.js';
import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';
import { createStreamJsonParser } from './streamJsonParser.js';
import { loadState, saveState, withState } from './runnerState.js';
@@ -49,6 +51,11 @@ const SIGKILL_GRACE_MS = 5000; // wait after SIGTERM before forcing SIGKIL
const ORPHAN_CLEANUP_DELAY_MS = 3000; // delay on boot before reaping orphaned agents
const SHUTDOWN_DRAIN_MS = 5000; // SIGTERM drain window before closing the server
const TUI_DONE_POLL_MS = 2000;
+// Agentic CLIs can spend several seconds loading config/plugins before their
+// lightweight version command returns. Keep this aligned with commandExists'
+// documented heavy-CLI probe budget so a cold but runnable provider is not
+// rejected before its PTY opens.
+const TUI_CAPABILITY_PROBE_TIMEOUT_MS = 15 * 1000;
// Path + listen constants. These lived adjacent to the command allowlist before
// it was extracted to ./allowedCommands.js; they must stay here — they're
@@ -62,6 +69,12 @@ const HOST = process.env.HOST || '127.0.0.1';
// Active agent processes (in memory)
const activeAgents = new Map();
+// `tui:output` is live telemetry, so an immediate process exit can beat its
+// socket delivery. Keep a small terminal tail with the exit event: the PortOS
+// spawner owns failure analysis and can persist it when no ordinary TUI chunk
+// arrived. This is deliberately much smaller than the runner's 512 KiB live
+// buffer and is enough to carry a CLI's startup diagnostic.
+const TUI_EXIT_OUTPUT_TAIL_CHARS = 16 * 1024;
const TUI_SIGNALS = new Set(['SIGTERM', 'SIGKILL', 'SIGINT']);
const terminateRunnerProcess = (agent, signal = 'SIGTERM') => {
@@ -169,11 +182,34 @@ app.post('/spawn-tui', async (req, res) => {
const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : ROOT_DIR;
const childEnv = buildCliChildEnv({ before: envVars, cwd });
- // Windows coding CLIs are commonly npm .cmd shims. ConPTY cannot execute a
- // batch shim directly, so keep it behind cmd.exe; POSIX can own the CLI
- // process directly.
- const ptyCommand = process.platform === 'win32' ? (process.env.COMSPEC || 'cmd.exe') : command;
- const ptyArgs = process.platform === 'win32' ? ['/d', '/s', '/c', command, ...args] : args;
+ // node-pty reports a missing executable as an immediate exit with no data.
+ // Check the exact child PATH first so the caller gets a usable configuration
+ // error instead of a generic startup-failure after a blank PTY transcript.
+ // Keep the resolved path private: it may include the local account name.
+ const executable = findCommandOnPath(command, { env: childEnv, cwd });
+ if (!executable) {
+ return res.status(422).json({
+ error: `Command executable unavailable: ${basename(command)} is not on the CoS Runner PATH. Install it or update the provider command.`
+ });
+ }
+ // A PATH hit can still be a broken npm shim or an incomplete CLI install.
+ // Probe the same launch shape that the PTY will use: on Windows a .cmd/.bat
+ // shim must run through cmd.exe, while on POSIX it remains the direct binary.
+ // That prevents node-pty from reducing an immediate CLI error to a blank exit.
+ const versionProbe = prepareCliSpawn(executable, ['--version'], childEnv);
+ const runnable = await commandExists(versionProbe.command, versionProbe.args, {
+ timeoutMs: TUI_CAPABILITY_PROBE_TIMEOUT_MS,
+ env: childEnv,
+ cwd,
+ });
+ if (!runnable) {
+ return res.status(422).json({
+ error: `Command executable unavailable: ${basename(command)} did not pass the CoS Runner capability check. Reinstall it or update the provider command.`
+ });
+ }
+ // Use the same safe wrapper for the actual PTY launch. In particular, this
+ // preserves the shared escaping contract for paths/args passed to cmd.exe.
+ const { command: ptyCommand, args: ptyArgs } = prepareCliSpawn(executable, args, childEnv);
const tuiProcess = pty.spawn(ptyCommand, ptyArgs, {
name: 'xterm-256color',
cols,
@@ -217,7 +253,14 @@ app.post('/spawn-tui', async (req, res) => {
const success = current.completedBySentinel;
const effectiveExitCode = success ? 0 : exitCode;
const effectiveSignal = success ? 0 : signal;
- io.emit('tui:exit', { sessionId, agentId, exitCode: effectiveExitCode, signal: effectiveSignal });
+ const outputTail = current.outputBuffer.slice(-TUI_EXIT_OUTPUT_TAIL_CHARS);
+ io.emit('tui:exit', {
+ sessionId,
+ agentId,
+ exitCode: effectiveExitCode,
+ signal: effectiveSignal,
+ ...(outputTail ? { outputTail } : {}),
+ });
emitToServer('agent:completed', {
agentId,
taskId,
diff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.js
index a5a92a4a8a..c6732b7627 100644
--- a/server/cos-runner/index.test.js
+++ b/server/cos-runner/index.test.js
@@ -91,12 +91,46 @@ describe('cos-runner termination — Windows tree-kill for cmd.exe-wrapped shims
});
describe('cos-runner durable TUI ownership (#3202)', () => {
- it('spawns the PTY in the runner and keeps Windows npm shims behind cmd.exe', () => {
+ it('checks the TUI executable against its child PATH before opening a PTY', () => {
+ // node-pty otherwise turns a missing binary into exit 1 with no transcript,
+ // which loses the real configuration error to a generic startup failure.
+ expect(RUNNER_SRC).toMatch(
+ /import\s*\{[^}]*\bfindCommandOnPath\b[^}]*\}\s*from\s*'\.\.\/lib\/processEnv\.js';/
+ );
+ expect(RUNNER_SRC).toMatch(
+ /import\s*\{[^}]*\bcommandExists\b[^}]*\}\s*from\s*'\.\.\/lib\/commandExists\.js';/
+ );
+ const childEnvIdx = RUNNER_SRC.indexOf('const childEnv = buildCliChildEnv({ before: envVars, cwd });');
+ const resolveIdx = RUNNER_SRC.indexOf('const executable = findCommandOnPath(command, { env: childEnv, cwd });');
+ const prepareProbeIdx = RUNNER_SRC.indexOf("const versionProbe = prepareCliSpawn(executable, ['--version'], childEnv);");
+ const probeIdx = RUNNER_SRC.indexOf('const runnable = await commandExists(versionProbe.command, versionProbe.args, {');
+ const spawnIdx = RUNNER_SRC.indexOf('pty.spawn(ptyCommand, ptyArgs');
+ expect(resolveIdx, 'runner must resolve the command against childEnv').toBeGreaterThan(childEnvIdx);
+ expect(prepareProbeIdx, 'runner must prepare a Windows-safe version probe').toBeGreaterThan(resolveIdx);
+ expect(probeIdx, 'runner must capability-check the prepared command').toBeGreaterThan(prepareProbeIdx);
+ expect(spawnIdx, 'runner must open the PTY after the executable probe').toBeGreaterThan(probeIdx);
+ expect(RUNNER_SRC).toContain('const TUI_CAPABILITY_PROBE_TIMEOUT_MS = 15 * 1000;');
+ expect(RUNNER_SRC).toMatch(/timeoutMs:\s*TUI_CAPABILITY_PROBE_TIMEOUT_MS/);
+ expect(RUNNER_SRC).toContain('Command executable unavailable: ${basename(command)} is not on the CoS Runner PATH');
+ expect(RUNNER_SRC).toContain('Command executable unavailable: ${basename(command)} did not pass the CoS Runner capability check');
+ expect(RUNNER_SRC).toContain('const { command: ptyCommand, args: ptyArgs } = prepareCliSpawn(executable, args, childEnv);');
+ });
+
+ it('spawns the PTY through the shared Windows-safe CLI wrapper', () => {
expect(RUNNER_SRC).toMatch(/app\.post\('\/spawn-tui'/);
- expect(RUNNER_SRC).toMatch(/const ptyCommand = process\.platform === 'win32'/);
+ expect(RUNNER_SRC).toMatch(/prepareCliSpawn\(executable, args, childEnv\)/);
expect(RUNNER_SRC).toMatch(/pty\.spawn\(ptyCommand,\s*ptyArgs/);
expect(RUNNER_SRC).toMatch(/io\.emit\('tui:output'/);
expect(RUNNER_SRC).toMatch(/parseSentinelPayload\(contents\)/);
expect(RUNNER_SRC).toMatch(/emitToServer\('agent:completed'/);
});
+
+ it('includes a bounded terminal output tail with TUI exit telemetry', () => {
+ // The live tui:output event can lose a race to an immediate process exit.
+ // Its terminal companion must retain a diagnostic tail for the spawner's
+ // raw-transcript failure analysis path.
+ expect(RUNNER_SRC).toContain('const TUI_EXIT_OUTPUT_TAIL_CHARS = 16 * 1024;');
+ expect(RUNNER_SRC).toMatch(/const outputTail = current\.outputBuffer\.slice\(-TUI_EXIT_OUTPUT_TAIL_CHARS\);/);
+ expect(RUNNER_SRC).toMatch(/io\.emit\('tui:exit',[\s\S]{0,350}?\.\.\.\(outputTail \? \{ outputTail \} : \{\}\)/);
+ });
});
diff --git a/server/lib/README.md b/server/lib/README.md
index 24d4126b5a..29fc4d6c96 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -192,7 +192,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` — shared buffered-spawn machinery with capped stdout/stderr, timeout-kill, 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). 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 })` — does running `cmd args` succeed? A capability probe (`execFile`-based), not a PATH lookup like `processEnv.js`'s `whichFirst`. 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`. |
| `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). `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` | Allowlist of safe shell commands + `validatePm2Command(args)` (rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateCommand` runs the pm2 check for `pm2` base commands. 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 (boot re-attach, #1332) and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |
@@ -207,7 +207,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `gitRemote.js` | `getOriginInfo`, `parseGitRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — classifies the local `origin` remote vs the upstream atomantic/PortOS repo. Used by the update flow to detect forks. |
| `githubRepoUrl.js` | `parseGitHubUrl(url)` → `{ owner, repo }` / `isGitHubRepoUrl(url)` — authoritative "is this a clonable GitHub repo URL?" rule, re-exported by `services/githubCloner.js`. Mirrored to `client/src/lib/githubRepoUrl.js` (parity pinned by `githubRepoUrl.mirror.test.js`) so the Brain capture boxes reveal the post-clone agent options for exactly the URLs the server will clone. |
| `killWithEscalation.js` | `killWithEscalation(proc, {label, stillRunning, delayMs=8000})` — shared SIGTERM→grace→SIGKILL cancel-escalation for spawn-based media jobs. Sends SIGTERM, then escalates to SIGKILL after `delayMs` only when `stillRunning()` holds and the child hasn't exited (`exitCode===null && signalCode===null`). The timer is unref'd and the callback is try/catch-wrapped (runs outside the request lifecycle). Converges musicVideo/render, videoTimeline, imageGen local+codex, videoGen, loraTraining, and the yt-dlp track import cancel paths. |
-| `processEnv.js` | `stripDebugMallocEnv(env)` / `safeChildProcessEnv(extra)` — drop macOS `Malloc*` debug env vars before spawning a child. `safeChildProcessOptions(options)` adds that sanitized environment plus `windowsHide: true`, preventing detached PM2 subprocesses from opening transient Windows console UI; route Node→Python and other background CLI spawns through it. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (safe options, 5s timeout) returning the absolute binary path or `null`; `whichFirstSync(name)` provides the same contract without the await. |
+| `processEnv.js` | `stripDebugMallocEnv(env)` / `safeChildProcessEnv(extra)` — drop macOS `Malloc*` debug env vars before spawning a child. `safeChildProcessOptions(options)` adds that sanitized environment plus `windowsHide: true`, preventing detached PM2 subprocesses from opening transient Windows console UI; route Node→Python and other background CLI spawns through it. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (safe options, 5s timeout) returning the absolute binary path or `null`; `whichFirstSync(name)` provides the same contract without the await; `findCommandOnPath(name, { env, cwd })` resolves an executable from the exact child environment without needing `which` itself on that PATH. |
| `branchUpstreamGuard.js` | `enforceSafeBranchUpstream(repo, branch)` / `readBranchUpstream` / `isSafeBranchUpstream` — the agent-branch upstream invariant (#4172): a branch handed to a CoS agent tracks either NOTHING or its OWN ref, never `refs/heads/main`. `git worktree add -b <b> <path> origin/main` does not leave the branch untracked — `branch.autoSetupMerge` records `merge=refs/heads/main` — and `/do:pr` derives its push destination from that config (`git push <remote> HEAD:<merge>`), so the agent's work lands straight on the default branch with no PR. Prevention is `--no-track` at the `worktreeManager.js` creation sites; this is the backstop that also REPAIRS branches created before the fix (drops the bogus upstream, logs it) and throws only if the repair doesn't take. Fails CLOSED: `readBranchUpstream` returns `null` for could-not-read (distinct from `''` = genuinely unset), and an unverifiable upstream is refused rather than waved through — `worktreeManager.js` undoes the `worktree add` on refusal so the throw can't strand a tree. Pairs with `primaryCheckoutGuard.js`, which catches the other way agent work reaches `main`. |
| `primaryCheckoutGuard.js` | `capturePrimaryCheckoutState(path)` / `detectPrimaryCheckoutDrift(baseline, {agentBranch})` + `PRIMARY_CHECKOUT_MUTATED_REASON`/`_CATEGORY` — the branch-jack detector (#3680): stamps the PRIMARY checkout's branch + HEAD onto a worktree agent's metadata at spawn (`agentLifecycle.js`) and re-reads it in the shared finalize path (`agentFinalization.js`), so a worktree-isolated agent that commits to the primary is recorded as a FAILURE naming the drifted branch, the commit count, and the `git reset --hard` recovery — instead of a silent "completed". Detect-and-report only: the reset discards commits, so it stays a human decision. Non-throwing (runs outside the request lifecycle); an unreadable checkout reports no drift rather than inventing one. |
| `pythonSetup.js` | Python venv / runner setup helpers. |
diff --git a/server/lib/commandExists.js b/server/lib/commandExists.js
index 1f2f791e99..2dba163bd1 100644
--- a/server/lib/commandExists.js
+++ b/server/lib/commandExists.js
@@ -16,9 +16,14 @@ const execFileAsync = promisify(execFile);
*
* @param {string} cmd
* @param {string[]} [args] - defaults to `['--version']`, the common probe
- * @param {{timeoutMs?: number}} [opts]
+ * @param {{timeoutMs?: number, env?: object, cwd?: string}} [opts]
* @returns {Promise<boolean>}
*/
-export async function commandExists(cmd, args = ['--version'], { timeoutMs = 5_000 } = {}) {
- return execFileAsync(cmd, args, { timeout: timeoutMs }).then(() => true).catch(() => false);
+export async function commandExists(cmd, args = ['--version'], { timeoutMs = 5_000, env, cwd } = {}) {
+ const options = {
+ timeout: timeoutMs,
+ ...(env === undefined ? {} : { env }),
+ ...(cwd === undefined ? {} : { cwd }),
+ };
+ return execFileAsync(cmd, args, options).then(() => true).catch(() => false);
}
diff --git a/server/lib/commandExists.test.js b/server/lib/commandExists.test.js
index 8ab1aae5a7..2637005532 100644
--- a/server/lib/commandExists.test.js
+++ b/server/lib/commandExists.test.js
@@ -41,4 +41,14 @@ describe('commandExists', () => {
await commandExists('codex', undefined, { timeoutMs: 15_000 })
expect(seenOpts.timeout).toBe(15_000)
})
+
+ it('uses the supplied child environment and working directory', async () => {
+ let seenOpts = null
+ execFileMock.impl = (_cmd, _args, opts, cb) => { seenOpts = opts; cb(null, { stdout: '', stderr: '' }) }
+ const env = { PATH: '/example/bin' }
+
+ await commandExists('opencode', undefined, { env, cwd: '/example/workspace' })
+
+ expect(seenOpts).toEqual({ timeout: 5_000, env, cwd: '/example/workspace' })
+ })
})
diff --git a/server/lib/processEnv.js b/server/lib/processEnv.js
index faeb9ab96b..88be91921b 100644
--- a/server/lib/processEnv.js
+++ b/server/lib/processEnv.js
@@ -12,6 +12,8 @@
// stripping the prefix is a no-op on Linux/Windows.
import { execFile, execFileSync } from './childProcess.js';
import { promisify } from 'util';
+import { accessSync, constants, statSync } from 'fs';
+import { delimiter, isAbsolute, join, resolve } from 'path';
const execFileAsync = promisify(execFile);
const IS_WIN = process.platform === 'win32';
@@ -61,3 +63,62 @@ export async function whichFirst(name) {
.catch(() => ({ stdout: '' }));
return stdout.trim().split(/\r?\n/)[0] || null;
}
+
+const canExecute = (candidate) => {
+ try {
+ if (!statSync(candidate).isFile()) return false;
+ // Windows does not use POSIX execute bits. Its command processor decides
+ // launchability from the extension, which the caller checks below.
+ if (!IS_WIN) accessSync(candidate, constants.X_OK);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * Resolve an executable using the exact PATH a child process will receive.
+ *
+ * Unlike `whichFirst`, this does not launch `which`/`where`: a provider may
+ * deliberately override PATH with only its own bin directory, leaving no
+ * system `which` binary available to perform the probe. It returns an absolute
+ * path suitable for a direct spawn, or null when the command cannot run.
+ *
+ * @param {string} name
+ * @param {{env?: NodeJS.ProcessEnv|object, cwd?: string}} [options]
+ * @returns {string|null}
+ */
+export function findCommandOnPath(name, { env = process.env, cwd = process.cwd() } = {}) {
+ if (!name || typeof name !== 'string') return null;
+
+ // An explicit path is resolved relative to the child cwd (matching spawn),
+ // not this server's cwd. This branch also avoids splitting a Windows path on
+ // the platform's PATH delimiter.
+ if (isAbsolute(name) || /[\\/]/.test(name)) {
+ const candidate = isAbsolute(name) ? name : resolve(cwd, name);
+ return canExecute(candidate) ? candidate : null;
+ }
+
+ const pathValue = env.PATH || env.Path || '';
+ const pathDirs = pathValue.split(delimiter);
+ const hasExtension = /\.[^./\\]+$/.test(name);
+ const extensions = IS_WIN && !hasExtension
+ // Do not test an extensionless sibling first: npm installs one for POSIX
+ // shells next to its Windows .cmd shim, but it is not natively launchable
+ // by a Windows PTY. PATHEXT names exactly the candidates cmd.exe can run.
+ ? (env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean)
+ : [''];
+
+ for (const rawDir of pathDirs) {
+ const configuredDir = rawDir.replace(/^"(.*)"$/, '$1') || cwd;
+ // A relative PATH entry is relative to the child process's cwd, not the
+ // server's own cwd. Return an absolute path so the following probe and PTY
+ // launch use the same executable regardless of the runner's cwd.
+ const dir = isAbsolute(configuredDir) ? configuredDir : resolve(cwd, configuredDir);
+ for (const extension of extensions) {
+ const candidate = join(dir, `${name}${extension}`);
+ if (canExecute(candidate)) return candidate;
+ }
+ }
+ return null;
+}
diff --git a/server/lib/processEnv.test.js b/server/lib/processEnv.test.js
index 5aeedadcaa..fa7c7c66f2 100644
--- a/server/lib/processEnv.test.js
+++ b/server/lib/processEnv.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest';
-import { basename } from 'path';
-import { safeChildProcessEnv, stripDebugMallocEnv, whichFirst } from './processEnv.js';
+import { basename, dirname } from 'path';
+import { findCommandOnPath, safeChildProcessEnv, stripDebugMallocEnv, whichFirst } from './processEnv.js';
describe('stripDebugMallocEnv', () => {
it('drops every key that starts with "Malloc"', () => {
@@ -85,3 +85,27 @@ describe('whichFirst', () => {
expect(resolved).toBeNull();
});
});
+
+describe('findCommandOnPath', () => {
+ it('resolves against the supplied child PATH without needing which/where', () => {
+ const nodePath = process.execPath;
+ const resolved = findCommandOnPath(basename(nodePath), {
+ env: { PATH: dirname(nodePath), Path: dirname(nodePath) },
+ });
+ expect(resolved).toBe(nodePath);
+ });
+
+ it('returns null when the child PATH excludes the command', () => {
+ const resolved = findCommandOnPath(basename(process.execPath), { env: { PATH: '', Path: '' } });
+ expect(resolved).toBeNull();
+ });
+
+ it('resolves a relative child PATH entry from the child working directory', () => {
+ const nodePath = process.execPath;
+ const resolved = findCommandOnPath(basename(nodePath), {
+ env: { PATH: '.' },
+ cwd: dirname(nodePath),
+ });
+ expect(resolved).toBe(nodePath);
+ });
+});
diff --git a/server/routes/providers.js b/server/routes/providers.js
index 9353af9849..d2f3b9af20 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -4,6 +4,15 @@ import { testVision, runVisionTestSuite, checkVisionHealth } from '../services/v
import { 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 {
+ getOpenCodeInstallStatus,
+ OPENCODE_NPM_PACKAGE,
+ spawnOpenCodeInstaller,
+ stopOpenCodeInstaller,
+} from '../services/opencodeInstaller.js';
/**
* The CoS Agent Runner's exec allowlist, published read-only so the AI
@@ -22,6 +31,11 @@ import { ALLOWED_COMMANDS } from '../cos-runner/allowedCommands.js';
*/
const RUNNER_ALLOWED_COMMANDS = [...ALLOWED_COMMANDS].sort();
+// One npm global install may write the same package prefix at a time. 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 opencodeInstallInFlight = null;
+
/**
* Sanitize a provider object for client responses.
* Strips apiKey (replaces with hasApiKey boolean) and redacts secretEnvVars values.
@@ -107,6 +121,119 @@ export function createPortOSProviderRoutes(aiToolkit) {
res.json({ providers: providers.map(presentProvider) });
}));
+ // OpenCode is a local coding CLI, not an LLM service PortOS can silently
+ // bootstrap. These endpoints only expose availability and service an
+ // explicit click from the Providers page. They intentionally return no
+ // resolved filesystem paths, which could disclose the host account name.
+ router.get('/opencode/installation', asyncHandler(async (_req, res) => {
+ res.json(await getOpenCodeInstallStatus());
+ }));
+
+ // 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 npm install.
+ //
+ // The fixed command is npm install --global opencode-ai@latest; no request
+ // input reaches a shell or package argument.
+ router.post('/opencode/install', asyncHandler(async (req, res) => {
+ const { send, safeEnd } = openSseStream(res);
+ const installLog = createInstallLogger({ installer: 'OpenCode CLI', target: 'npm global prefix' });
+ 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) stopOpenCodeInstaller(child);
+ if (reservation && opencodeInstallInFlight === reservation) opencodeInstallInFlight = null;
+ safeEnd();
+ });
+
+ const status = await getOpenCodeInstallStatus();
+ if (clientGone) return safeEnd();
+ if (status.installed) {
+ send({ type: 'log', message: 'OpenCode is already available to PortOS.' });
+ send({ type: 'complete', message: 'Already installed — nothing to do.' });
+ return safeEnd();
+ }
+ if (!status.npmAvailable) {
+ send({ type: 'error', message: 'npm is not available on PortOS\'s PATH, so OpenCode cannot be installed from this page.' });
+ return safeEnd();
+ }
+ if (opencodeInstallInFlight) {
+ send({ type: 'error', message: 'Another OpenCode 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 global npm installs.
+ reservation = {};
+ opencodeInstallInFlight = reservation;
+ if (clientGone) {
+ opencodeInstallInFlight = null;
+ return safeEnd();
+ }
+
+ send({ type: 'stage', stage: 'install', message: 'Installing OpenCode CLI with npm.' });
+ emit({ type: 'log', message: `Running npm install --global ${OPENCODE_NPM_PACKAGE}.` });
+ installLog.start();
+ child = spawnOpenCodeInstaller();
+ opencodeInstallInFlight = child;
+
+ const onLine = (line) => {
+ const text = line.trimEnd();
+ if (text) emit({ type: 'log', message: text });
+ };
+ // `--no-progress` suppresses npm's usual redraws. Keep the default
+ // newline-only reader as a defensive second layer: a lifecycle child 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 (opencodeInstallInFlight === child) opencodeInstallInFlight = null;
+ emit({ type: 'error', message: `OpenCode installer failed to start: ${err.message}` });
+ safeEnd();
+ });
+ // The post-install PATH check is deliberately stronger than npm's exit
+ // code. A successful global 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 (opencodeInstallInFlight === child) opencodeInstallInFlight = null;
+ const installed = code === 0 && (await getOpenCodeInstallStatus()).installed;
+ if (installed) {
+ emit({ type: 'complete', message: 'OpenCode is installed and available to PortOS.' });
+ } else if (code === 0) {
+ emit({ type: 'error', message: 'npm completed, but OpenCode is not runnable by PortOS. Restart PortOS or reinstall OpenCode so its postinstall script can complete, then try again.' });
+ } else {
+ emit({ type: 'error', message: `OpenCode installer exited with code ${code}.` });
+ }
+ safeEnd();
+ } catch (err) {
+ // Child-process completion runs outside Express's request lifecycle.
+ console.error(`❌ OpenCode install completion check failed: ${err.message}`);
+ emit({ type: 'error', message: `OpenCode install completion check failed: ${err.message}` });
+ safeEnd();
+ }
+ });
+ }));
+
// Provider status routes MUST be defined before toolkit routes,
// because the toolkit has a GET /:id route that would catch /status
router.get('/status', asyncHandler(async (req, res) => {
diff --git a/server/routes/providers.opencodeInstall.test.js b/server/routes/providers.opencodeInstall.test.js
new file mode 100644
index 0000000000..0fba5ea28f
--- /dev/null
+++ b/server/routes/providers.opencodeInstall.test.js
@@ -0,0 +1,100 @@
+import { EventEmitter } from 'node:events';
+import { PassThrough } from 'node:stream';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express, { Router } from 'express';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { request } from '../lib/testHelper.js';
+
+const installer = vi.hoisted(() => ({
+ getOpenCodeInstallStatus: vi.fn(),
+ spawnOpenCodeInstaller: vi.fn(),
+ stopOpenCodeInstaller: vi.fn(),
+ OPENCODE_NPM_PACKAGE: 'opencode-ai@latest',
+}));
+
+vi.mock('../services/opencodeInstaller.js', () => installer);
+
+import { createPortOSProviderRoutes } from './providers.js';
+
+const app = () => {
+ const toolkit = { services: { providers: {} }, routes: { providers: Router() } };
+ const server = express();
+ server.use(express.json());
+ server.use('/api/providers', createPortOSProviderRoutes(toolkit));
+ server.use(errorMiddleware);
+ return server;
+};
+
+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;
+};
+
+describe('OpenCode Providers installer routes', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('returns only install readiness booleans', async () => {
+ installer.getOpenCodeInstallStatus.mockResolvedValueOnce({ installed: false, npmAvailable: true });
+
+ const response = await request(app()).get('/api/providers/opencode/installation');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({ installed: false, npmAvailable: true });
+ });
+
+ it('streams a verified completion after the fixed installer exits', async () => {
+ const child = makeChild();
+ installer.getOpenCodeInstallStatus
+ .mockResolvedValueOnce({ installed: false, npmAvailable: true })
+ .mockResolvedValueOnce({ installed: true, npmAvailable: true });
+ installer.spawnOpenCodeInstaller.mockReturnValueOnce(child);
+
+ const responsePromise = request(app()).post('/api/providers/opencode/install').then((response) => response);
+ await vi.waitFor(() => expect(installer.spawnOpenCodeInstaller).toHaveBeenCalledOnce());
+ child.stdout.end('added OpenCode\n');
+ child.stderr.end();
+ child.emit('close', 0);
+ const response = await responsePromise;
+
+ expect(response.status).toBe(200);
+ expect(response.headers['content-type']).toContain('text/event-stream');
+ expect(response.text).toContain('Running npm install --global opencode-ai@latest.');
+ expect(response.text).toContain('added OpenCode');
+ expect(response.text).toContain('OpenCode is installed and available to PortOS.');
+ });
+
+ it('reports an unusable CLI after npm exits successfully', async () => {
+ const child = makeChild();
+ installer.getOpenCodeInstallStatus
+ .mockResolvedValueOnce({ installed: false, npmAvailable: true })
+ .mockResolvedValueOnce({ installed: false, npmAvailable: true });
+ installer.spawnOpenCodeInstaller.mockReturnValueOnce(child);
+
+ const responsePromise = request(app()).post('/api/providers/opencode/install').then((response) => response);
+ await vi.waitFor(() => expect(installer.spawnOpenCodeInstaller).toHaveBeenCalledOnce());
+ child.stdout.end();
+ child.stderr.end();
+ child.emit('close', 0);
+ const response = await responsePromise;
+
+ expect(response.status).toBe(200);
+ expect(response.text).toContain('OpenCode is not runnable by PortOS');
+ });
+
+ it('fails the stream without spawning when npm is absent', async () => {
+ installer.getOpenCodeInstallStatus.mockResolvedValueOnce({ installed: false, npmAvailable: false });
+
+ const response = await request(app()).post('/api/providers/opencode/install');
+
+ expect(response.status).toBe(200);
+ expect(response.text).toContain('npm is not available');
+ expect(installer.spawnOpenCodeInstaller).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 53375d3f7c..79583c1009 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -737,6 +737,12 @@ export async function spawnTuiAgent({
let firstOutputAt = null;
let lastOutputAt = Date.now();
let sessionId = null;
+ // The runner's `tui:output` socket messages are live telemetry. An OpenCode
+ // CLI that prints one startup error and exits can race that delivery, while
+ // its `tui:exit` arrives reliably enough to finish the session. Track whether
+ // we received any ordinary chunk so the runner-provided exit tail is spooled
+ // only as a recovery path, never duplicated into raw.txt.
+ let receivedTuiOutput = false;
// The paste-attempt / max-runtime / wrap-up-grace machinery (postPasteBuffer,
// pasteEnterTimer, pasteVerifyTimer, submitEnterTimer, maxRuntimeTimer,
@@ -1123,6 +1129,7 @@ export async function spawnTuiAgent({
// The String(...) coerces defensively in case a future caller wires
// a Buffer-emitting encoding.
const text = typeof data === 'string' ? data : String(data);
+ if (text) receivedTuiOutput = true;
const stripped = streamingStrip(text);
pushRaw(text);
// Accumulate the ANSI-STRIPPED chunk (not the raw text): the paste marker
@@ -1205,8 +1212,16 @@ export async function spawnTuiAgent({
}
};
- const handleExit = async ({ exitCode, killed, signal = null }) => {
+ const handleExit = async ({ exitCode, killed, signal = null, outputTail = '' }) => {
if (finalized) return;
+ // A durable runner can retain a startup error even when its matching
+ // `tui:output` socket event lost the race with process exit. Preserve its
+ // bounded tail before finish() drains raw.txt for error analysis. Cap again
+ // at this trust boundary so a malformed runner event cannot grow the spool.
+ if (!receivedTuiOutput && typeof outputTail === 'string' && outputTail) {
+ receivedTuiOutput = true;
+ pushRaw(outputTail.slice(-16 * 1024));
+ }
// A host restart reaches here as a plain PTY exit (pm2's TreeKill walks
// portos-server's descendants), which the `success` reading below would
// record as a completed run. finish() intercepts that case — see its
@@ -1281,16 +1296,33 @@ export async function spawnTuiAgent({
} catch (err) {
const message = err?.message || String(err);
appendLine(`❌ Failed to start ${provider.name || provider.id} TUI: ${message}`);
+ // The durable runner probes the configured executable before it opens a
+ // PTY. Distinguish that deterministic configuration failure from a runner
+ // outage/refusal so it is blocked with the existing actionable
+ // command-not-found guidance rather than retried as a transient rejection.
+ const reason = useDurableRunner && /^Command executable unavailable:/i.test(message)
+ ? 'command-not-found'
+ : useDurableRunner ? 'spawn-rejected' : 'spawn-error';
await finish({
success: false,
exitCode: 1,
error: `Failed to start TUI session: ${message}`,
- reason: useDurableRunner ? 'spawn-rejected' : 'spawn-error',
+ reason,
});
return null;
}
sessionId = session.sessionId;
+ // A durable runner can emit tui:exit before its spawn POST response reaches
+ // this process. handleExit() then finalizes the run while createAgentTuiSession
+ // is still awaiting that response. Do not revive the finalized agent by
+ // registering its returned session, timers, or active-agent record; release
+ // the external shell session that was registered during the late response.
+ if (finalized) {
+ if (sessionId && shellService.getSession(sessionId)) shellService.killSession(sessionId);
+ return null;
+ }
+
if (!sessionId) {
await finish({ success: false, exitCode: 1, error: 'Failed to create TUI shell session', reason: 'spawn-error' });
return null;
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index a1ed29b5c7..eaac65aa62 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -1628,6 +1628,55 @@ describe('spawnTuiAgent runtime', () => {
);
});
+ it('spools the runner exit tail when an immediate exit beat live TUI output', async () => {
+ const { appendFile } = await import('fs/promises');
+ const spawnPromise = runSpawn({ useDurableRunner: true });
+ await flushMicrotasks();
+
+ await capturedOnExit({
+ exitCode: 1,
+ killed: false,
+ outputTail: 'OpenCode startup error: configured model is unavailable',
+ });
+ await flushMicrotasks();
+ await spawnPromise;
+
+ const rawTail = vi.mocked(appendFile).mock.calls.find(
+ ([path, contents]) => typeof path === 'string' && path.endsWith('raw.txt') && String(contents).includes('OpenCode startup error'),
+ );
+ expect(rawTail).toBeDefined();
+ });
+
+ it('does not revive an agent when the durable runner exits before its spawn response', async () => {
+ let resolveRunnerSession;
+ let exitPromise;
+ const session = {
+ sessionId: SESSION_ID,
+ pid: 4321,
+ ptyProcess: { pid: 4321, kill: vi.fn() },
+ };
+ vi.mocked(spawnTuiSessionViaRunner).mockImplementationOnce((options) => {
+ capturedOnData = options.onData;
+ capturedOnExit = options.onExit;
+ // The socket relay registers this callback before its POST resolves, so
+ // a CLI that exits immediately can finalize while the response is held.
+ exitPromise = options.onExit({ exitCode: 1, killed: false, outputTail: 'startup failed' });
+ return new Promise((resolve) => { resolveRunnerSession = resolve; });
+ });
+
+ const spawnPromise = runSpawn({ useDurableRunner: true });
+ await flushMicrotasks();
+ resolveRunnerSession(session);
+
+ await spawnPromise;
+ await exitPromise;
+
+ expect(activeAgents.has('agent-1')).toBe(false);
+ expect(vi.getTimerCount()).toBe(0);
+ expect(shellService.killSession).toHaveBeenCalledWith(SESSION_ID);
+ expect(cosAgentLifecycle.updateAgent).not.toHaveBeenCalled();
+ });
+
// ── 4. Killed / user-terminated path ────────────────────────────────────────
it('user-terminated: finalizeAgent receives terminatedByUser:true + error=Agent terminated by user', async () => {
// Mark agent as user-terminated before the exit fires
@@ -2026,6 +2075,23 @@ describe('spawnTuiAgent runtime', () => {
);
});
+ it('classifies a runner executable preflight failure as command-not-found', async () => {
+ vi.mocked(spawnTuiSessionViaRunner).mockRejectedValueOnce(
+ new Error('Command executable unavailable: opencode did not pass the CoS Runner capability check. Reinstall it or update the provider command.'),
+ );
+
+ await expect(runSpawn({ useDurableRunner: true })).resolves.toBeNull();
+
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ success: false,
+ completionReason: 'command-not-found',
+ error: expect.stringContaining('did not pass the CoS Runner capability check'),
+ })
+ );
+ });
+
it('keeps the actionable spawn-error when the local PTY path throws', async () => {
vi.mocked(shellService.createShellSession).mockImplementationOnce(() => {
throw new Error('posix_spawnp failed');
diff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.js
index ae2f389811..b1394f1444 100644
--- a/server/services/cosRunnerClient.js
+++ b/server/services/cosRunnerClient.js
@@ -44,7 +44,11 @@ const dispatchTuiEvent = (event, data) => {
try {
const result = handler(event === 'tui:output'
? data.data
- : { exitCode: data.exitCode, signal: data.signal });
+ : {
+ exitCode: data.exitCode,
+ signal: data.signal,
+ ...(typeof data.outputTail === 'string' && data.outputTail ? { outputTail: data.outputTail } : {}),
+ });
if (result && typeof result.then === 'function') {
result.catch(err => console.error(`🔌 CoS runner ${event} handler rejected: ${err.message}`));
}
diff --git a/server/services/cosRunnerClient.test.js b/server/services/cosRunnerClient.test.js
index ebd7b074c2..f9025bf3fe 100644
--- a/server/services/cosRunnerClient.test.js
+++ b/server/services/cosRunnerClient.test.js
@@ -297,10 +297,19 @@ describe('cosRunnerClient', () => {
capturedSocketListeners['tui:output']({ sessionId: session.sessionId, data: 'working' });
session.ptyProcess.write('hello');
session.ptyProcess.resize(120, 40);
- capturedSocketListeners['tui:exit']({ sessionId: session.sessionId, exitCode: 0, signal: 0 });
+ capturedSocketListeners['tui:exit']({
+ sessionId: session.sessionId,
+ exitCode: 0,
+ signal: 0,
+ outputTail: 'immediate startup error',
+ });
expect(onData).toHaveBeenCalledWith('working');
- expect(onExit).toHaveBeenCalledWith({ exitCode: 0, signal: 0 });
+ expect(onExit).toHaveBeenCalledWith({
+ exitCode: 0,
+ signal: 0,
+ outputTail: 'immediate startup error',
+ });
expect(capturedSocket.emit).toHaveBeenCalledWith('tui:input', {
sessionId: 'agent-tui-1',
data: 'hello',
diff --git a/server/services/opencodeInstaller.js b/server/services/opencodeInstaller.js
new file mode 100644
index 0000000000..c258705371
--- /dev/null
+++ b/server/services/opencodeInstaller.js
@@ -0,0 +1,72 @@
+/**
+ * OpenCode CLI availability and installation.
+ *
+ * The Providers page owns the user gesture; this module deliberately exposes
+ * only one fixed npm invocation, never a user-supplied package or command.
+ * That keeps the install surface as narrow as the agent runner's command
+ * allowlist while letting a missing OpenCode provider become self-service.
+ */
+
+import { spawn } from '../lib/childProcess.js';
+import { killProcessTree, prepareCliSpawn } from '../lib/bufferedSpawn.js';
+import { commandExists } from '../lib/commandExists.js';
+import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';
+
+const IS_WIN = process.platform === 'win32';
+
+export const OPENCODE_COMMAND = 'opencode';
+export const OPENCODE_NPM_PACKAGE = 'opencode-ai@latest';
+export const OPENCODE_NPM_INSTALL_ARGS = Object.freeze([
+ 'install',
+ '--global',
+ // npm's carriage-return progress renderer can emit hundreds of repaint
+ // frames per second. The installer streams stdout to the browser, so keep
+ // the useful package messages without turning the modal into a re-render
+ // storm.
+ '--no-progress',
+ OPENCODE_NPM_PACKAGE,
+]);
+
+/**
+ * Report only runnable availability, never the discovered absolute paths.
+ * Paths can contain the machine account name and are not useful to the browser;
+ * the boolean is the exact question the Providers page needs to answer.
+ */
+export async function getOpenCodeInstallStatus({ findCommand = findCommandOnPath, probeCommand = commandExists } = {}) {
+ const [opencode, npm] = await Promise.all([
+ findCommand(OPENCODE_COMMAND),
+ findCommand('npm'),
+ ]);
+ // `where opencode` can select npm's extensionless POSIX shim before the
+ // working `.cmd` wrapper on Windows. The filesystem resolver gives us the
+ // real executable; prepareCliSpawn then probes that same safe launch shape.
+ const versionProbe = opencode ? prepareCliSpawn(opencode, ['--version']) : null;
+ return {
+ installed: Boolean(versionProbe) && Boolean(await probeCommand(versionProbe.command, versionProbe.args)),
+ npmAvailable: Boolean(npm),
+ };
+}
+
+/**
+ * Start the one supported OpenCode install command with no shell interpolation.
+ * `prepareCliSpawn` handles npm's Windows .cmd shim without falling back to
+ * unsafe `shell: true`, and the returned child stays owned by the SSE route.
+ */
+export function spawnOpenCodeInstaller({ spawnImpl = spawn } = {}) {
+ const env = safeChildProcessEnv();
+ const { command, args } = prepareCliSpawn('npm', OPENCODE_NPM_INSTALL_ARGS, env);
+ return spawnImpl(command, args, safeChildProcessOptions({
+ env,
+ shell: false,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ // npm can run package lifecycle children. Give the POSIX install its own
+ // group so closing the modal stops that entire install, not just npm.
+ detached: !IS_WIN,
+ }));
+}
+
+/** Terminate the npm child and descendants when the installer modal closes. */
+export function stopOpenCodeInstaller(child) {
+ if (!child?.pid || child.killed) return;
+ killProcessTree(child, 'SIGTERM', { processGroup: !IS_WIN });
+}
diff --git a/server/services/opencodeInstaller.test.js b/server/services/opencodeInstaller.test.js
new file mode 100644
index 0000000000..7b64e602e3
--- /dev/null
+++ b/server/services/opencodeInstaller.test.js
@@ -0,0 +1,49 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ getOpenCodeInstallStatus,
+ OPENCODE_NPM_INSTALL_ARGS,
+ spawnOpenCodeInstaller,
+} from './opencodeInstaller.js';
+
+describe('OpenCode installer', () => {
+ it('reports runnable availability as booleans without returning local paths', async () => {
+ const findCommand = vi.fn(async (command) => command === 'opencode' ? '/example/opencode' : null);
+ const probeCommand = vi.fn(async () => true);
+
+ await expect(getOpenCodeInstallStatus({ findCommand, probeCommand })).resolves.toEqual({
+ installed: true,
+ npmAvailable: false,
+ });
+ expect(findCommand).toHaveBeenCalledWith('opencode');
+ expect(findCommand).toHaveBeenCalledWith('npm');
+ expect(probeCommand).toHaveBeenCalledWith('/example/opencode', ['--version']);
+ });
+
+ it('reports a PATH-resolved but broken OpenCode CLI as unavailable', async () => {
+ const findCommand = vi.fn(async (command) => command === 'opencode' ? '/example/opencode' : '/example/npm');
+ const probeCommand = vi.fn(async () => false);
+
+ await expect(getOpenCodeInstallStatus({ findCommand, probeCommand })).resolves.toEqual({
+ installed: false,
+ npmAvailable: true,
+ });
+ expect(probeCommand).toHaveBeenCalledWith('/example/opencode', ['--version']);
+ });
+
+ it('spawns only the fixed npm global package install without a shell', () => {
+ const spawnImpl = vi.fn(() => ({ pid: 123 }));
+
+ spawnOpenCodeInstaller({ spawnImpl });
+
+ expect(spawnImpl).toHaveBeenCalledWith(
+ 'npm',
+ OPENCODE_NPM_INSTALL_ARGS,
+ expect.objectContaining({
+ shell: false,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ detached: process.platform !== 'win32',
+ }),
+ );
+ expect(OPENCODE_NPM_INSTALL_ARGS).toContain('--no-progress');
+ });
+});