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
Manage Slotstream as a PM2 local runtime on Models → LLMs (#5815)
[._.]/ Adam Eivy38d5483002e7
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex aaab770311..f8a8d2cac3 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -13,6 +13,7 @@ import {installAudioModel, patchSettingsSlice, getLlamaServerStatus, getLlamaServerUpdateStatus, startLlamaServer, stopLlamaServer, installLlamaServer, upgradeLlamaServer,downloadSpecDecodeModel, cancelSpecDecodeModelDownload, controlLmStudioService, getMtplxServerStatus, startMtplxServer, stopMtplxServer, installMtplx,searchMtplxModels, pullMtplxModel, removeMtplxModel,+ getSlotstreamServerStatus, startSlotstreamServer, stopSlotstreamServer, installSlotstream,saveRuntimeStartupList} from '../../services/api';import socket from '../../services/socket';@@ -20,6 +21,7 @@ import CapabilityBadges from '../models/CapabilityBadges.jsx';import SpecDecodeWeightRow from './SpecDecodeWeightRow.jsx';import RuntimeServersCard from './RuntimeServersCard.jsx';import MtplxServerCard from './MtplxServerCard.jsx';+import SlotstreamServerCard from './SlotstreamServerCard.jsx';import LocalLlmBackendCard from './LocalLlmBackendCard.jsx';import LocalLlmInstalledModels from './LocalLlmInstalledModels.jsx';import ModelAbuseGuardPanel from '../models/ModelAbuseGuardPanel.jsx';@@ -197,6 +199,7 @@ export function LocalLlmTab({ view }) {const [llamaStatus, setLlamaStatus] = useState(null);const [mtplxStatus, setMtplxStatus] = useState(null);+ const [slotstreamStatus, setSlotstreamStatus] = useState(null);// Live byte progress for an in-flight `mtplx pull`, driven by the socket. One// at a time on purpose: a checkpoint is tens of gigabytes, so two concurrent// pulls just make both slower.@@ -206,6 +209,7 @@ export function LocalLlmTab({ view }) {// a model path, so its Start lives in the launcher rather than in that row.const llamaSectionRef = useRef(null);const mtplxSectionRef = useRef(null);+ const slotstreamSectionRef = useRef(null);const [llamaPresetId, setLlamaPresetId] = useState(DEFAULT_SPEC_PRESET_ID);const [llamaForm, setLlamaForm] = useState({model: '',@@ -269,6 +273,15 @@ export function LocalLlmTab({ view }) {.catch(() => null)), []);+ const loadSlotstreamStatus = useCallback(() => (+ getSlotstreamServerStatus({ silent: true })+ .then((res) => {+ if (res) setSlotstreamStatus(res);+ return res;+ })+ .catch(() => null)+ ), []);+const loadStatus = useCallback(() => {const requestId = ++statusRequestId.current;if (activeView === 'abuse') {@@ -279,6 +292,7 @@ export function LocalLlmTab({ view }) {if (activeView === 'runtimes') {loadLlamaStatus();loadMtplxStatus();+ loadSlotstreamStatus();}return getLocalLlmStatus({ silent: true }).then((s) => {@@ -296,7 +310,7 @@ export function LocalLlmTab({ view }) {.finally(() => {if (requestId === statusRequestId.current) setLoading(false);});- }, [activeView, loadLlamaStatus, loadMtplxStatus]);+ }, [activeView, loadLlamaStatus, loadMtplxStatus, loadSlotstreamStatus]);// `source` and `category` are required rather than defaulted from state: a// state default would put them in the dep list, so `loadCatalog`'s identity@@ -544,16 +558,37 @@ export function LocalLlmTab({ view }) {'Saved — MTPLX will start on these options when a request needs it').then(loadMtplxStatus);- // The idle window is a plain settings write for both daemons; only what- // happens when it elapses differs (llama.cpp unloads in place on its next- // start, MTPLX is stopped and lazily restarted).+ // The idle window is a plain settings write for the PM2-managed daemons;+ // only what happens when it elapses differs (llama.cpp unloads in place on+ // its next start; MTPLX and Slotstream are stopped and lazily restarted).+ const idleRuntimeLabel = { llama: 'llama.cpp', mtplx: 'MTPLX', slotstream: 'Slotstream' };const saveIdleWindow = (runtime, minutes) => runAction(`runtime-idle-${runtime}`,() => patchSettingsSlice(`localLlm.${runtime}`, { idleMinutes: minutes }),minutes === 0- ? `${runtime === 'llama' ? 'llama.cpp' : 'MTPLX'} will stay loaded while idle`- : `${runtime === 'llama' ? 'llama.cpp' : 'MTPLX'} releases its model after ${minutes} idle minute${minutes === 1 ? '' : 's'}`- ).then(runtime === 'llama' ? loadLlamaStatus : loadMtplxStatus);+ ? `${idleRuntimeLabel[runtime] || runtime} will stay loaded while idle`+ : `${idleRuntimeLabel[runtime] || runtime} releases its model after ${minutes} idle minute${minutes === 1 ? '' : 's'}`+ ).then(runtime === 'llama' ? loadLlamaStatus : runtime === 'slotstream' ? loadSlotstreamStatus : loadMtplxStatus);+ const runtimeInstallSlotstream = () => runAction(+ 'runtime-install-slotstream',+ () => installSlotstream(),+ 'Slotstream installed'+ ).then(loadSlotstreamStatus);+ const runtimeStartSlotstream = (launch = {}) => runAction(+ 'runtime-start-slotstream',+ () => startSlotstreamServer(launch),+ (r) => r?.online ? 'Slotstream is running' : 'Slotstream is loading its checkpoint'+ ).then(loadSlotstreamStatus);+ const saveSlotstreamLaunch = (launch) => runAction(+ 'runtime-save-slotstream-launch',+ () => patchSettingsSlice('localLlm.slotstream', { launch }),+ 'Saved — Slotstream will start on these options when a request needs it'+ ).then(loadSlotstreamStatus);+ const runtimeStopSlotstream = () => runAction(+ 'runtime-stop-slotstream',+ () => stopSlotstreamServer(),+ (r) => r?.message || 'Slotstream stopped'+ ).then(loadSlotstreamStatus);const runtimeStopMtplx = () => runAction('runtime-stop-mtplx',() => stopMtplxServer(),@@ -596,7 +631,7 @@ export function LocalLlmTab({ view }) {'runtime-save-startup',() => saveRuntimeStartupList(),'Saved — the PM2 processes running now will come back after a reboot'- ).then(() => { loadLlamaStatus(); loadMtplxStatus(); });+ ).then(() => { loadLlamaStatus(); loadMtplxStatus(); loadSlotstreamStatus(); });const scrollTo = (ref) => ref.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });const selectedData = status?.[selected];const selectedOllamaStartupAction = selectedData?.service?.supported ? 'enable' : 'start';@@ -983,6 +1018,7 @@ export function LocalLlmTab({ view }) {status={status}llamaStatus={llamaStatus}mtplxStatus={mtplxStatus}+ slotstreamStatus={slotstreamStatus}loading={loading}busy={busy}actionInProgress={actionInProgress}@@ -998,6 +1034,10 @@ export function LocalLlmTab({ view }) {onInstallMtplx={runtimeInstallMtplx}onStartMtplx={runtimeStartMtplx}onStopMtplx={runtimeStopMtplx}+ onConfigureSlotstream={() => scrollTo(slotstreamSectionRef)}+ onInstallSlotstream={runtimeInstallSlotstream}+ onStartSlotstream={runtimeStartSlotstream}+ onStopSlotstream={runtimeStopSlotstream}onSaveStartup={saveRuntimeStartup}onSaveIdleWindow={saveIdleWindow}/>@@ -1106,6 +1146,21 @@ export function LocalLlmTab({ view }) {)}</div>+ {/* Slotstream — PM2-managed SSD-streaming MoE runtime (Apple Silicon) */}+ <div ref={slotstreamSectionRef}>+ <SlotstreamServerCard+ status={slotstreamStatus}+ loading={loading}+ busy={busy}+ actionInProgress={actionInProgress}+ onRefresh={loadSlotstreamStatus}+ onSaveLaunch={saveSlotstreamLaunch}+ onStart={runtimeStartSlotstream}+ onStop={runtimeStopSlotstream}+ onInstall={runtimeInstallSlotstream}+ />+ </div>+{/* MTPLX — PM2-managed native-MTP runtime (Apple Silicon) */}<div ref={mtplxSectionRef}><MtplxServerCarddiff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsxindex 1063a3a170..47f990db75 100644--- a/client/src/components/settings/LocalLlmTab.test.jsx+++ b/client/src/components/settings/LocalLlmTab.test.jsx@@ -18,6 +18,10 @@ vi.mock('../../services/api', () => ({startMtplxServer: vi.fn(),stopMtplxServer: vi.fn(),installMtplx: vi.fn(),+ getSlotstreamServerStatus: vi.fn().mockResolvedValue({ installed: false, running: false, supported: true, cachedModels: [], memoryPlan: { targetGb: 22, expectedPeakGb: 22, expectedWarmDecodeToks: 8, auto: true } }),+ startSlotstreamServer: vi.fn(),+ stopSlotstreamServer: vi.fn(),+ installSlotstream: vi.fn(),// The MTPLX card's checkpoint panel loads upstream's default listing on mount.searchMtplxModels: vi.fn().mockResolvedValue({ models: [], error: null }),pullMtplxModel: vi.fn(),@@ -131,7 +135,7 @@ describe('LocalLlmTab information architecture', () => {});it('gives model installation its own panel without mounting runtime management', async () => {- const { getLlamaServerStatus, getMtplxServerStatus } = await import('../../services/api');+ const { getLlamaServerStatus, getMtplxServerStatus, getSlotstreamServerStatus } = await import('../../services/api');await renderTab('library');@@ -139,6 +143,7 @@ describe('LocalLlmTab information architecture', () => {expect(screen.queryByRole('heading', { name: 'Local Runtime Servers' })).not.toBeInTheDocument();expect(getLlamaServerStatus).not.toHaveBeenCalled();expect(getMtplxServerStatus).not.toHaveBeenCalled();+ expect(getSlotstreamServerStatus).not.toHaveBeenCalled();await waitFor(() => expect(getLocalLlmCatalog).toHaveBeenCalled());});diff --git a/client/src/components/settings/RuntimeServersCard.jsx b/client/src/components/settings/RuntimeServersCard.jsxindex 03b6405641..51e7a896ec 100644--- a/client/src/components/settings/RuntimeServersCard.jsx+++ b/client/src/components/settings/RuntimeServersCard.jsx@@ -1,6 +1,6 @@import { useEffect, useState } from 'react';import { Link } from 'react-router';-import { Cpu, Box, Zap, Gauge, Play, Square, Download, ArrowUpCircle, Power, PowerOff, RefreshCw, Save, Settings2, ExternalLink } from 'lucide-react';+import { Cpu, Box, Zap, Gauge, HardDrive, Play, Square, Download, ArrowUpCircle, Power, PowerOff, RefreshCw, Save, Settings2, ExternalLink } from 'lucide-react';import BrailleSpinner from '../BrailleSpinner';/**@@ -274,6 +274,7 @@ export default function RuntimeServersCard({status,llamaStatus,mtplxStatus,+ slotstreamStatus,loading,busy,actionInProgress,@@ -289,13 +290,21 @@ export default function RuntimeServersCard({onInstallMtplx,onStartMtplx,onStopMtplx,+ onConfigureSlotstream,+ onInstallSlotstream,+ onStartSlotstream,+ onStopSlotstream,onSaveStartup,onSaveIdleWindow,}) {// Read off each daemon's own status payload — the same place `runAtStartup`// and Ollama's `disabled` come from — so there is no second settings fetch on// this tab to keep in sync.- const idleWindows = { llama: llamaStatus?.idleMinutes ?? 0, mtplx: mtplxStatus?.idleMinutes ?? 0 };+ const idleWindows = {+ llama: llamaStatus?.idleMinutes ?? 0,+ mtplx: mtplxStatus?.idleMinutes ?? 0,+ slotstream: slotstreamStatus?.idleMinutes ?? 0,+ };const ollamaService = status?.ollama?.service;const ollamaRunsAtStartup = Boolean(ollamaService?.runAtStartup);@@ -352,6 +361,32 @@ export default function RuntimeServersCard({? `${mtplxStatus.cachedModels.length} checkpoint${mtplxStatus.cachedModels.length === 1 ? '' : 's'} cached`: null,}),+ pm2Row({+ id: 'slotstream',+ label: 'Slotstream',+ icon: HardDrive,+ status: slotstreamStatus,+ platformReason: slotstreamStatus?.supported === false ? 'macOS with Apple Silicon only' : null,+ onInstall: onInstallSlotstream,+ onStart: slotstreamStatus?.cachedModels?.length ? onStartSlotstream : null,+ onStop: onStopSlotstream,+ // An unreadable cache also leaves `cachedModels` empty, so it withholds+ // Start too — it must say WHY, or the row renders "stopped" with nothing+ // to click and no explanation.+ startBlockedReason: slotstreamStatus?.installed && !slotstreamStatus?.running+ ? (slotstreamStatus?.cacheError+ ? `Checkpoint cache unreadable — ${slotstreamStatus.cacheError}`+ : (slotstreamStatus?.cachedModels?.length === 0+ ? 'No checkpoint yet — a start never fetches weights'+ : null))+ : null,+ detail: [+ slotstreamStatus?.memoryPlan+ && `target ${slotstreamStatus.memoryPlan.targetGb} GB${slotstreamStatus.memoryPlan.auto ? ' (auto)' : ''} · peak ${slotstreamStatus.memoryPlan.expectedPeakGb} GB · ~${slotstreamStatus.memoryPlan.expectedWarmDecodeToks} tok/s`,+ slotstreamStatus?.cachedModels?.length+ && `${slotstreamStatus.cachedModels.length} checkpoint${slotstreamStatus.cachedModels.length === 1 ? '' : 's'} cached`,+ ].filter(Boolean).join(' · ') || null,+ }),];return (@@ -388,7 +423,7 @@ export default function RuntimeServersCard({{ollamaRunsAtStartup ? 'Disable at login' : 'Run at login'}</button>)}- {(row.id === 'llama' || row.id === 'mtplx') && row.state !== 'unsupported' && row.state !== 'missing' && (+ {(row.id === 'llama' || row.id === 'mtplx' || row.id === 'slotstream') && row.state !== 'unsupported' && row.state !== 'missing' && (<IdleWindowFieldid={row.id}value={idleWindows[row.id] ?? 0}@@ -396,12 +431,14 @@ export default function RuntimeServersCard({onSave={(minutes) => onSaveIdleWindow?.(row.id, minutes)}note={row.id === 'llama'? 'Minutes of PortOS inactivity after which llama.cpp unloads the model in place and reloads it on the next request. 0 = keep it resident. Applies from the next start.'- : 'Minutes of PortOS inactivity after which MTPLX is stopped. The next PortOS request starts it again on the same checkpoint. 0 = keep it running.'}+ : row.id === 'slotstream'+ ? 'Minutes of PortOS inactivity after which Slotstream is stopped. The next PortOS request starts it again on the same checkpoint and memory cap. 0 = keep it running.'+ : 'Minutes of PortOS inactivity after which MTPLX is stopped. The next PortOS request starts it again on the same checkpoint. 0 = keep it running.'}/>)}- {(row.id === 'llama' || row.id === 'mtplx') && row.state !== 'unsupported' && (+ {(row.id === 'llama' || row.id === 'mtplx' || row.id === 'slotstream') && row.state !== 'unsupported' && (<button- onClick={row.id === 'llama' ? onConfigureLlama : onConfigureMtplx}+ onClick={row.id === 'llama' ? onConfigureLlama : row.id === 'slotstream' ? onConfigureSlotstream : onConfigureMtplx}className={neutralBtn}title={`Jump to the ${row.label} launcher below`}>@@ -414,7 +451,7 @@ export default function RuntimeServersCard({</div><p className="text-xs text-gray-500">- <span className="text-gray-400">Idle release</span> puts a model down when nothing has used it for that many minutes — llama.cpp unloads it in place and reloads it on the next request; MTPLX is stopped and restarted on demand. <span className="text-gray-400">Only PortOS traffic counts.</span> A client hitting these ports directly is invisible to the timer and cannot lazily start a stopped server, so set <code className="text-gray-400">0</code> for a daemon you drive from outside PortOS.+ <span className="text-gray-400">Idle release</span> puts a model down when nothing has used it for that many minutes — llama.cpp unloads it in place and reloads it on the next request; MTPLX and Slotstream are stopped and restarted on demand. <span className="text-gray-400">Only PortOS traffic counts.</span> A client hitting these ports directly is invisible to the timer and cannot lazily start a stopped server, so set <code className="text-gray-400">0</code> for a daemon you drive from outside PortOS.</p><div className="flex flex-col sm:flex-row sm:items-center gap-2 pt-1">@@ -423,7 +460,7 @@ export default function RuntimeServersCard({Save PM2 list for reboot</button><p className="text-xs text-gray-500">- llama.cpp and MTPLX run as PM2 processes (<code className="text-gray-400">portos-llama-server</code>, <code className="text-gray-400">portos-mtplx</code>). Saving snapshots what is running now so it comes back after a reboot — this needs <code className="text-gray-400">pm2 startup</code> to have been run once in a terminal, which is a privileged one-time step PortOS deliberately leaves to you. <span className="text-gray-400">MTPLX is deliberately left out of that snapshot</span>: it starts on demand when a request needs it, so resurrecting it at boot would only pin its checkpoint on an idle machine. Ollama and LM Studio manage their own launch-at-login.+ llama.cpp, MTPLX and Slotstream run as PM2 processes (<code className="text-gray-400">portos-llama-server</code>, <code className="text-gray-400">portos-mtplx</code>, <code className="text-gray-400">portos-slotstream</code>). Saving snapshots what is running now so it comes back after a reboot — this needs <code className="text-gray-400">pm2 startup</code> to have been run once in a terminal, which is a privileged one-time step PortOS deliberately leaves to you. <span className="text-gray-400">MTPLX and Slotstream are deliberately left out of that snapshot</span>: they start on demand when a request needs them, so resurrecting them at boot would only pin a checkpoint on an idle machine. Ollama and LM Studio manage their own launch-at-login.</p></div></div>diff --git a/client/src/components/settings/RuntimeServersCard.test.jsx b/client/src/components/settings/RuntimeServersCard.test.jsxindex 0ce53ece97..8fb133e033 100644--- a/client/src/components/settings/RuntimeServersCard.test.jsx+++ b/client/src/components/settings/RuntimeServersCard.test.jsx@@ -22,6 +22,10 @@ const renderCard = (props = {}) => {onStartMtplx: vi.fn(),onSaveIdleWindow: vi.fn(),onStopMtplx: vi.fn(),+ onConfigureSlotstream: vi.fn(),+ onInstallSlotstream: vi.fn(),+ onStartSlotstream: vi.fn(),+ onStopSlotstream: vi.fn(),onSaveStartup: vi.fn(),};render(@@ -44,7 +48,7 @@ const renderCard = (props = {}) => {describe('RuntimeServersCard', () => {it('lists every local runtime PortOS can run, not just the two catalog backends', () => {renderCard();- for (const label of ['Ollama', 'LM Studio', 'llama.cpp', 'MTPLX']) {+ for (const label of ['Ollama', 'LM Studio', 'llama.cpp', 'MTPLX', 'Slotstream']) {expect(screen.getByText(label)).toBeInTheDocument();}});@@ -168,6 +172,49 @@ describe('RuntimeServersCard', () => {expect(handlers.onInstallBackend).toHaveBeenCalledWith('ollama');});+ it('offers Slotstream Start when a checkpoint is cached and shows the memory plan', () => {+ const handlers = renderCard({+ slotstreamStatus: {+ installed: true,+ running: false,+ supported: true,+ cachedModels: ['qwen-moe'],+ memoryPlan: { targetGb: 22, expectedPeakGb: 22, expectedWarmDecodeToks: 8, auto: false },+ },+ });+ const slotstream = row('Slotstream');+ expect(within(slotstream).getByText(/target 22 GB/)).toBeInTheDocument();+ fireEvent.click(within(slotstream).getByRole('button', { name: /^Start/ }));+ expect(handlers.onStartSlotstream).toHaveBeenCalledWith();+ });++ it('keeps Slotstream Start unavailable when no checkpoint is cached', () => {+ renderCard({+ slotstreamStatus: { installed: true, running: false, supported: true, cachedModels: [], cacheError: null },+ });+ const slotstream = row('Slotstream');+ expect(within(slotstream).queryByRole('button', { name: /^Start/ })).toBeNull();+ expect(within(slotstream).getByText(/a start never fetches weights/i)).toBeInTheDocument();+ });++ it('says why Slotstream cannot start when its checkpoint cache is unreadable', () => {+ // An unreadable cache also reports zero checkpoints, so it withholds Start+ // too — without its own reason the row renders "stopped" with nothing to+ // click and no explanation of what to fix.+ renderCard({+ slotstreamStatus: {+ installed: true,+ running: false,+ supported: true,+ cachedModels: [],+ cacheError: 'could not read Slotstream cache (EACCES)',+ },+ });+ const slotstream = row('Slotstream');+ expect(within(slotstream).queryByRole('button', { name: /^Start/ })).toBeNull();+ expect(within(slotstream).getByText(/cache unreadable/i)).toHaveTextContent('EACCES');+ });+it('points at the in-app download when the MTPLX cache is empty', () => {// Nothing downloads weights on its own, and `mtplx serve` exits before it// binds on an empty cache — so the row names the in-app fix (the Configurediff --git a/client/src/components/settings/SlotstreamServerCard.jsx b/client/src/components/settings/SlotstreamServerCard.jsxnew file mode 100644index 0000000000..22d19034f2--- /dev/null+++ b/client/src/components/settings/SlotstreamServerCard.jsx@@ -0,0 +1,222 @@+import { useEffect, useState } from 'react';+import { HardDrive, RefreshCw, Save, Square, Download, Terminal } from 'lucide-react';+import BrailleSpinner from '../BrailleSpinner';++/**+ * Slotstream launcher — the same shape as the MTPLX launcher above it: a PM2+ * process (`portos-slotstream`) PortOS starts, stops, logs, and can idle-stop.+ *+ * Weights are a later, explicit user action. A start never fetches them. The+ * memory plan (target / peak / warm decode) is shown here rather than hidden,+ * and an explicit memory-cap override is saved onto the launch line an+ * on-demand start replays.+ */++const btnClass = 'flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium rounded-lg transition-colors disabled:opacity-50';++export default function SlotstreamServerCard({+ status,+ loading,+ busy,+ actionInProgress,+ onRefresh,+ onSaveLaunch,+ onStart,+ onStop,+ onInstall,+}) {+ const [model, setModel] = useState('');+ const [port, setPort] = useState('');+ const [memoryGb, setMemoryGb] = useState('');+ const [seeded, setSeeded] = useState(false);+ const [showLogs, setShowLogs] = useState(false);++ // Seed the form from the saved launch line ONCE the status arrives.+ // Without this the memory cap the user saved is invisible on the next visit,+ // and re-saving after any other edit silently drops it — `launchPayload`+ // omits an empty field. Guarded by `seeded` rather than keyed on `status`, so+ // a refresh mid-edit does not overwrite what the user is typing.+ const launch = status?.launch;+ useEffect(() => {+ if (seeded || !launch) return;+ setModel(launch.model || '');+ setPort(launch.port == null ? '' : String(launch.port));+ setMemoryGb(launch.memoryGb == null ? '' : String(launch.memoryGb));+ setSeeded(true);+ }, [launch, seeded]);++ const cached = status?.cachedModels || [];+ const emptyCache = Boolean(status?.installed) && cached.length === 0 && !status?.cacheError;+ const external = status?.running && status?.managed === false;+ const plan = status?.memoryPlan;++ const launchPayload = () => ({+ model: model || null,+ ...(port ? { port: Number(port) } : {}),+ ...(memoryGb ? { memoryGb: Number(memoryGb) } : {}),+ });++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-4">+ <div className="flex items-center justify-between flex-wrap gap-2">+ <div className="flex items-center gap-2">+ <HardDrive size={16} className="text-port-accent" />+ <h2 className="text-sm font-medium text-gray-300">Slotstream (SSD-streaming MoE)</h2>+ </div>+ <button+ onClick={onRefresh}+ disabled={loading}+ className="p-1 text-gray-400 hover:text-white transition-colors"+ title="Refresh Slotstream status"+ aria-label="Refresh Slotstream status"+ >+ <RefreshCw size={13} className={loading ? 'animate-spin' : ''} />+ </button>+ </div>++ <p className="text-xs text-gray-400 leading-relaxed">+ Slotstream runs a mixture-of-experts checkpoint larger than this Mac's RAM by keeping a small dense trunk resident and streaming experts from SSD into a fixed cache. Cache size trades speed against memory and never changes output. PortOS manages it as a PM2 process on a dedicated loopback port — never 11434, which is a PortOS-managed Ollama.+ </p>++ {plan && (+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-2 text-xs bg-port-bg border border-port-border rounded-lg px-3 py-2">+ <p><span className="text-gray-500">Target</span> <span className="text-white">{plan.targetGb} GB{plan.auto ? ' (auto)' : ''}</span></p>+ <p><span className="text-gray-500">Expected peak</span> <span className="text-white">{plan.expectedPeakGb} GB</span></p>+ <p><span className="text-gray-500">Warm decode</span> <span className="text-white">~{plan.expectedWarmDecodeToks} tok/s</span></p>+ </div>+ )}++ {!status ? (+ <p className="text-xs text-gray-500">Checking for Slotstream…</p>+ ) : status.supported === false ? (+ <p className="text-xs text-gray-500">{status.unsupportedReason || 'Slotstream runs only on macOS with Apple Silicon.'}</p>+ ) : !status.installed ? (+ <div className="bg-port-warning/10 border border-port-warning/30 rounded-lg p-3 text-xs text-port-warning flex flex-col sm:flex-row sm:items-center justify-between gap-3">+ <div className="space-y-1">+ <p className="font-semibold">Slotstream was not detected on this machine.</p>+ <p className="text-gray-300">Installs the Apple Silicon release into ~/.slotstream/bin. Does not download model weights.</p>+ </div>+ <button onClick={onInstall} disabled={busy} className={`${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent shrink-0`}>+ {actionInProgress === 'runtime-install-slotstream' ? <BrailleSpinner /> : <Download size={13} />}+ Install Slotstream+ </button>+ </div>+ ) : status.running ? (+ <div className="bg-port-bg border border-port-success/30 rounded-lg p-3 space-y-3">+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">+ <div className="text-xs text-gray-300 space-y-1">+ <p><span className="text-gray-500">Endpoint:</span> <code className="text-port-success">{status.endpoint}</code></p>+ {status.config?.model && (+ <p><span className="text-gray-500">Model:</span> <code className="text-gray-300">{status.config.model}</code></p>+ )}+ {status.config?.memoryGb && (+ <p><span className="text-gray-500">Memory cap:</span> <code className="text-gray-300">{status.config.memoryGb} GB</code></p>+ )}+ {external && (+ <p className="text-blue-300">Started outside PortOS — stop it where you started it.</p>+ )}+ </div>+ {!external && (+ <button onClick={onStop} disabled={busy} className={`${btnClass} bg-port-warning/20 hover:bg-port-warning/30 text-port-warning shrink-0`}>+ {actionInProgress === 'runtime-stop-slotstream' ? <BrailleSpinner /> : <Square size={13} />}+ Stop Slotstream+ </button>+ )}+ </div>+ </div>+ ) : (+ <div className="bg-port-bg border border-port-border rounded-lg p-3 space-y-3">+ {emptyCache ? (+ <p className="text-xs text-port-warning">+ No checkpoint is cached, so a start would exit before it binds a port. A start never downloads weights — place a checkpoint directory in <code className="text-gray-300">{status.cacheDir || '~/.slotstream/models'}</code>, then start Slotstream again.+ </p>+ ) : (+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">+ <div className="space-y-1">+ <label htmlFor="slotstream-model" className="block text-xs text-gray-400">Checkpoint</label>+ <select+ id="slotstream-model"+ value={model}+ onChange={(e) => setModel(e.target.value)}+ className="w-full bg-port-card border border-port-border rounded px-2 py-1.5 text-xs text-white"+ >+ <option value="">Auto — first checkpoint in the cache</option>+ {cached.map((id) => <option key={id} value={id}>{id}</option>)}+ </select>+ </div>+ <div className="space-y-1">+ <label htmlFor="slotstream-port" className="block text-xs text-gray-400">Port</label>+ <input+ id="slotstream-port"+ type="number"+ value={port}+ placeholder={String(status?.port ?? 5564)}+ onChange={(e) => setPort(e.target.value)}+ className="w-full bg-port-card border border-port-border rounded px-2 py-1.5 text-xs text-white"+ />+ <p className="text-[11px] text-gray-500">Dedicated loopback port. Never 11434.</p>+ </div>+ <div className="space-y-1">+ <label htmlFor="slotstream-memory" className="block text-xs text-gray-400">Memory cap (GB)</label>+ <input+ id="slotstream-memory"+ type="number"+ min="6"+ value={memoryGb}+ placeholder={plan ? String(plan.targetGb) : 'auto'}+ onChange={(e) => setMemoryGb(e.target.value)}+ className="w-full bg-port-card border border-port-border rounded px-2 py-1.5 text-xs text-white"+ />+ <p className="text-[11px] text-gray-500">Empty = auto-size from this Mac's RAM.</p>+ </div>+ </div>+ )}+ {status?.cacheError && (+ <p className="text-xs text-gray-500">Couldn't read Slotstream's model cache ({status.cacheError}).</p>+ )}+ <p className="text-[11px] text-gray-500">+ Slotstream starts on demand when a request needs it. You can also start it now with a cached checkpoint; its idle window (set under Local Runtime Servers) stops it again. Neither path downloads weights.+ </p>+ {!emptyCache && onStart && (+ <button+ onClick={() => onStart(launchPayload())}+ disabled={busy}+ className={`${btnClass} bg-port-success/20 hover:bg-port-success/30 text-port-success`}+ title="Start Slotstream with the cached checkpoint; no weights are downloaded"+ >+ {actionInProgress === 'runtime-start-slotstream' ? <BrailleSpinner /> : <Terminal size={13} />}+ Start Slotstream+ </button>+ )}+ <button+ onClick={() => onSaveLaunch(launchPayload())}+ disabled={busy || emptyCache}+ className={`${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent`}+ title={emptyCache ? 'Add a checkpoint first — a start never fetches weights' : 'Remember these options for the next on-demand start'}+ >+ {actionInProgress === 'runtime-save-slotstream-launch' ? <BrailleSpinner /> : <Save size={13} />}+ Save configuration+ </button>+ </div>+ )}++ {status?.recentLogs?.length > 0 && (+ <div className="space-y-1">+ <button+ type="button"+ onClick={() => setShowLogs((prev) => !prev)}+ className="text-[11px] text-gray-500 hover:text-gray-300 flex items-center gap-1"+ >+ <Terminal size={11} />+ {showLogs ? 'Hide server logs' : `View server logs (${status.recentLogs.length} lines)`}+ </button>+ {showLogs && (+ <pre className="text-[10px] text-gray-400 bg-port-bg border border-port-border/60 p-2.5 rounded max-h-40 overflow-y-auto font-mono whitespace-pre-wrap">+ {status.recentLogs.join('\n')}+ </pre>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/settings/SlotstreamServerCard.test.jsx b/client/src/components/settings/SlotstreamServerCard.test.jsxnew file mode 100644index 0000000000..ba53c5ec05--- /dev/null+++ b/client/src/components/settings/SlotstreamServerCard.test.jsx@@ -0,0 +1,80 @@+import { describe, it, expect, vi } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';+import SlotstreamServerCard from './SlotstreamServerCard.jsx';++const renderCard = (status, props = {}) => {+ const handlers = {+ onRefresh: vi.fn(),+ onSaveLaunch: vi.fn(),+ onStart: vi.fn(),+ onStop: vi.fn(),+ onInstall: vi.fn(),+ };+ render(+ <SlotstreamServerCard status={status} loading={false} busy={false} actionInProgress={null} {...handlers} {...props} />,+ );+ return handlers;+};++describe('SlotstreamServerCard', () => {+ it('surfaces the memory plan instead of hiding it', () => {+ renderCard({+ installed: true,+ running: false,+ supported: true,+ cachedModels: ['qwen-moe'],+ memoryPlan: { targetGb: 22, expectedPeakGb: 22, expectedWarmDecodeToks: 8, auto: false },+ });+ expect(screen.getByText('Target').closest('p')).toHaveTextContent('22 GB');+ expect(screen.getByText('Expected peak').closest('p')).toHaveTextContent('22 GB');+ expect(screen.getByText('Warm decode').closest('p')).toHaveTextContent('~8 tok/s');+ });++ it('saves checkpoint, port, and memory-cap override', () => {+ const handlers = renderCard({+ installed: true,+ running: false,+ supported: true,+ port: 5564,+ cachedModels: ['qwen-moe'],+ memoryPlan: { targetGb: 32, expectedPeakGb: 32, expectedWarmDecodeToks: 12, auto: true },+ });+ fireEvent.change(screen.getByLabelText('Checkpoint'), { target: { value: 'qwen-moe' } });+ fireEvent.change(screen.getByLabelText('Port'), { target: { value: '5565' } });+ fireEvent.change(screen.getByLabelText('Memory cap (GB)'), { target: { value: '22' } });+ fireEvent.click(screen.getByRole('button', { name: /Save configuration/ }));+ expect(handlers.onSaveLaunch).toHaveBeenCalledWith({ model: 'qwen-moe', port: 5565, memoryGb: 22 });+ });++ it('seeds the form from the saved launch line so a saved cap survives a reload', () => {+ // Without this the memory cap the user saved is invisible on the next+ // visit, and re-saving after any other edit drops it — `launchPayload`+ // omits an empty field.+ const handlers = renderCard({+ installed: true,+ running: false,+ supported: true,+ cachedModels: ['qwen-moe'],+ launch: { model: 'qwen-moe', port: 5565, memoryGb: 22 },+ memoryPlan: { targetGb: 22, expectedPeakGb: 22, expectedWarmDecodeToks: 8, auto: false },+ });+ expect(screen.getByLabelText('Memory cap (GB)')).toHaveValue(22);+ fireEvent.change(screen.getByLabelText('Port'), { target: { value: '5566' } });+ fireEvent.click(screen.getByRole('button', { name: /Save configuration/ }));+ expect(handlers.onSaveLaunch).toHaveBeenCalledWith({ model: 'qwen-moe', port: 5566, memoryGb: 22 });+ });++ it('does not name a terminal command when the cache is empty', () => {+ renderCard({ installed: true, running: false, supported: true, cachedModels: [], cacheError: null });+ expect(screen.getByText(/never downloads weights/i)).toBeInTheDocument();+ expect(screen.queryByText(/in a terminal/i)).toBeNull();+ expect(screen.getByRole('button', { name: /Save configuration/ })).toBeDisabled();+ expect(screen.queryByRole('button', { name: /Start Slotstream/ })).toBeNull();+ });++ it('disables the row copy on a non-Apple-Silicon host', () => {+ renderCard({ supported: false, unsupportedReason: 'Slotstream runs only on macOS with Apple Silicon.' });+ expect(screen.getByText(/macOS with Apple Silicon/)).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /Install Slotstream/ })).toBeNull();+ });+});diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 4e486dce79..9dc448f9fa 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -45,7 +45,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiCommands.js` | CLI command dispatch. || `apiDashboard.js` | Dashboard state. || `apiDatabase.js` | Database introspection. |-| `apiLocalLlm.js` | Local LLM backends (Ollama / LM Studio): status (incl. installed models), catalog, model install/delete, the managed Prompt Guard model-abuse classifier lifecycle, backend install (Homebrew/script), switch/migrate, playground test/compare, and measured per-model assessments (run + persisted results + intent ranking + the server-side "measure everything" sweep). Also the PM2-managed runtime servers (llama.cpp, MTPLX) and MTPLX's checkpoint catalog — `searchMtplxModels` / `pullMtplxModel` / `removeMtplxModel`, so weights are managed in-app rather than from a terminal. |+| `apiLocalLlm.js` | Local LLM backends (Ollama / LM Studio): status (incl. installed models), catalog, model install/delete, the managed Prompt Guard model-abuse classifier lifecycle, backend install (Homebrew/script), switch/migrate, playground test/compare, and measured per-model assessments (run + persisted results + intent ranking + the server-side "measure everything" sweep). Also the PM2-managed runtime servers (llama.cpp, MTPLX, Slotstream) and MTPLX's checkpoint catalog — `searchMtplxModels` / `pullMtplxModel` / `removeMtplxModel`, so weights are managed in-app rather than from a terminal. || `apiGit.js` | Git operations. || `apiGithub.js` | GitHub repo metadata. || `apiHistory.js` | Historical logs / runs. |diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex 141b70722d..5cd23b10ee 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -89,6 +89,20 @@ export const stopMtplxServer = () =>export const installMtplx = () =>request('/local-llm/mtplx/install', { method: 'POST' });+// Slotstream (SSD-streaming MoE on Apple Silicon) — a PM2-managed process,+// same lifecycle shape as MTPLX. A start never downloads weights.+export const getSlotstreamServerStatus = (options) =>+ request('/local-llm/slotstream/status', options);++export const startSlotstreamServer = (config = {}) =>+ request('/local-llm/slotstream/start', { method: 'POST', body: JSON.stringify(config) });++export const stopSlotstreamServer = () =>+ request('/local-llm/slotstream/stop', { method: 'POST' });++export const installSlotstream = () =>+ request('/local-llm/slotstream/install', { method: 'POST' });+// MTPLX model catalog — search, download, and remove MTP checkpoints in-app.// `mtplx forge discover` is upstream's index of MTPLX-branded models, which is// exactly the set `mtplx serve` can run; an empty query returns its default list.diff --git a/docs/API.md b/docs/API.mdindex 06a8625605..9ee52528cf 100644--- a/docs/API.md+++ b/docs/API.md@@ -641,7 +641,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom| `/api/messages` | Messages (email) integration || `/api/digital-twin/social-accounts`, `/api/digital-twin/identity`, `/api/digital-twin/autobiography` | Digital-twin sub-domains || `/api/meatspace` | MeatSpace (health, POST, genome) |-| `/api/lmstudio`, `/api/local-llm` | Local LLM backends and the local runtime servers PortOS can start/stop (Ollama, LM Studio, `llama-server`, MTPLX — the last two as PM2 processes; `POST /api/local-llm/save-startup` is `pm2 save`), plus MTPLX's checkpoint catalog — `GET /api/local-llm/mtplx/models/search`, `POST .../models/pull` (byte progress on the `mtplx:download` socket event), `POST .../models/remove` |+| `/api/lmstudio`, `/api/local-llm` | Local LLM backends and the local runtime servers PortOS can start/stop (Ollama, LM Studio, `llama-server`, MTPLX, Slotstream — the last three as PM2 processes; `POST /api/local-llm/save-startup` is `pm2 save`), plus MTPLX's checkpoint catalog — `GET /api/local-llm/mtplx/models/search`, `POST .../models/pull` (byte progress on the `mtplx:download` socket event), `POST .../models/remove`. Slotstream lifecycle is `GET /api/local-llm/slotstream/status`, `POST .../start` (never downloads weights), `POST .../stop`, `POST .../install`. || `/api/code-review` | Code review runs || `/api/voice`, `/api/voice/public` | Voice assistant || `/api/api-docs` | Generated HTTP/event catalogs, OpenAPI 3.0.3 documents, AsyncAPI 3 document, and the minimized semantic tool resource |diff --git a/docs/PORTS.md b/docs/PORTS.mdindex b1add2ed33..9599440bc7 100644--- a/docs/PORTS.md+++ b/docs/PORTS.md@@ -36,6 +36,7 @@ Common port labels:| 5561 | portos-db (Docker container) | - | Infrastructure dependency: PostgreSQL Docker container provisioned by `scripts/setup-db.js` / Docker Compose (not a PM2 process in `server/services/apps.js`; native mode uses system pg on 5432). || 5562 | portos-whisper | whisper-server | Loopback whisper.cpp speech-to-text server. || 5563 | portos-server | eidoverse-host | Optional HTTPS/WebSocket bridge for the embedded Eidoverse Worlds page. Starts on demand and forwards to the managed app on loopback `:8940`. |+| 5564 | portos-slotstream | - | Loopback SSD-streaming MoE runtime. Optional PM2 process, started/stopped from Models → LLMs. Never 11434 — that port is a PortOS-managed Ollama. || 5568 | portos-llama-server | - | Loopback llama.cpp speculative-decoding server. Optional PM2 process, started/stopped from Models → LLMs. || 8000 | portos-mtplx | - | Loopback MTPLX OpenAI-compatible API (upstream's own default, kept so the shipped provider presets match). Optional PM2 process, started/stopped from Models → LLMs. See [features/mtplx.md](./features/mtplx.md). || 18020 | vLLM (Docker) | - | Loopback vLLM Qwen3.8-27B / DFlash 2 container on an RTX 3090 host. Operator-started (`docker compose --profile single up -d`) — PortOS never brings it up on boot. See [features/qwen38-rtx3090.md](./features/qwen38-rtx3090.md). |@@ -146,7 +147,7 @@ PortOS automatically detects ports from env vars:> without an error, PortOS logged `🌐 Eidoverse host listening`, and the Eidoverse page> served the other app's admin UI. Nothing in either process reported a problem.>-> The on-demand ports (5563, 5568) are the easiest to get wrong, because they are free+> The on-demand ports (5563, 5564, 5568) are the easiest to get wrong, because they are free> at boot and only bind once a user opens the relevant page — so a port scan taken at> install time shows them available. Treat the whole band as taken regardless.>diff --git a/ecosystem.config.cjs b/ecosystem.config.cjsindex 391d37f0b7..ca0af4e881 100644--- a/ecosystem.config.cjs+++ b/ecosystem.config.cjs@@ -122,6 +122,7 @@ const PORTS = {POSTGRES_DOCKER: 5561, // PostgreSQL Docker container (host port mapping)WHISPER: 5562, // Loopback whisper.cpp speech-to-text serverEIDOVERSE_HOST: 5563, // Optional HTTPS/WebSocket bridge to Eidoverse Worlds on :8940+ SLOTSTREAM: 5564, // Loopback SSD-streaming MoE runtime (never 11434 — that collides with Ollama)LLAMA_SERVER: 5568, // Loopback llama.cpp speculative-decoding serverVLLM_QWEN: 18020, // Loopback vLLM Qwen3.8-27B (DFlash 2) container — started by the operator, never by PortOSSGLANG_QWEN: 18021, // Loopback SGLang Qwen3.8-27B container (Hopper/Blackwell) — started by the operator, never by PortOSdiff --git a/server/lib/README.md b/server/lib/README.mdindex f752a63726..fd1f597fde 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -175,9 +175,10 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `providerTranscriptUsage.js` | Parsers for the real per-message token counts the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Both de-duplicate a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, and Codex's `total_token_usage` is cumulative and repeated. 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. || `localProviderRuntime.js` | Which LOCAL daemon a provider talks to, and where — `LOCAL_RUNTIMES` (llama.cpp / Ollama / LM Studio / MTPLX / vLLM: label, binary, canonical base URL read from `opencodeConfig.js` rather than re-typed, manage/docs links, model-download hint), `localBackendForProvider` + `localEndpointPort` + `isLocalInstanceHost` (moved here from `services/localModelHealing.js`, which re-exports them, so the healing path and the readiness checklist classify a provider identically — loopback/bind-all only, so a LAN/Tailscale peer on port 11434 is NOT claimed as a local daemon), `localRuntimeKind(provider)` (the `*Backed` markers first, then that classifier; `orcarouter` excluded as a remote API), `localRuntimeForProvider(provider)` → the row with the endpoint the provider ITSELF configures (`OPENCODE_CONFIG_CONTENT`'s `baseURL`, `ANTHROPIC_BASE_URL`, or `endpoint`), then the `OLLAMA_URL`/`OLLAMA_HOST`/`LM_STUDIO_URL` override the backend managers read, then the canonical default — and `null` when that resolved endpoint fails `isLocalInstanceEndpoint` (an API provider on another machine has no local daemon to check, whatever its name says) — plus `normalizeOpenAiBaseUrl`. Pure; the probing half is `services/providerReadiness.js`. Optional `setupStateDetail` overrides `providerReadiness`'s per-state prose for a runtime whose local setup is not a model cache (vLLM's is a compose project); `standbyWhenStopped` marks an installed runtime such as llama.cpp whose stopped state is intentional standby rather than incomplete setup. |-| `managedDaemon.js` | Shared mechanism for the local daemons PortOS runs as optional PM2 processes (`services/llamaServerManager.js` → `portos-llama-server`, `services/mtplxServerManager.js` → `portos-mtplx`). Owns their PM2 process names — `LLAMA_APP`, `MTPLX_APP`, and the `isModelServerProcess(name)` predicate over them — so a caller like the CoS health monitor can recognize a model server without importing a manager; the managers re-export the two names. `createDaemonWatcher({...})` supplies the common PM2 launch-line re-adoption, endpoint probe, status skeleton, bounded log view, and port-release wait while managers retain daemon-specific parsing and lifecycle policy. `createDaemonLogBuffer({maxLines?})` is the bounded timestamped ring buffer of what PortOS logged around a launch, plus `withPm2Logs(output)` → that buffer followed by anything `pm2 logs` has which it doesn't already hold, deduped and re-capped (PM2's lines are a VIEW, never folded into the buffer — PM2 owns them and re-reads them every status call). `pm2ArgValue(args, flag)` reads one value back out of a PM2 process's recorded argv so a manager can recover a still-online daemon's launch config after a PortOS restart; `null` means the flag was absent, which a relaunch must leave off rather than defaulting. Also the shared **idle reaper**, for a daemon that cannot release its weights any other way: `registerIdleDaemon({name, getIdleMs, stop})` (seeds `lastUsedAt` to NOW, so a hand-started daemon gets a full window), `markDaemonUsed(name)` — call on real traffic, NEVER on a status poll — `daemonLastUsedAt(name)`, `idleWindowMs(minutes)` (minutes → ms; `0` = never, `null` = not configured, kept distinct), `reapIdleDaemons(now?)` → the names stopped, and `startIdleReaper({intervalMs?})` / `stopIdleReaper()` (ONE interval for all registrants, `unref`'d, idempotent). `mtplxServerManager` is the only registrant: llama.cpp releases its checkpoint in place via `--sleep-idle-seconds` and must NOT be stopped for it. Deliberately mechanism only — what a launch line means and when a daemon may start is exactly what differs between the two. |+| `managedDaemon.js` | Shared mechanism for the local daemons PortOS runs as optional PM2 processes (`services/llamaServerManager.js` → `portos-llama-server`, `services/mtplxServerManager.js` → `portos-mtplx`, `services/slotstreamServerManager.js` → `portos-slotstream`). Owns their PM2 process names — `LLAMA_APP`, `MTPLX_APP`, `SLOTSTREAM_APP`, and the `isModelServerProcess(name)` predicate over them — so a caller like the CoS health monitor can recognize a model server without importing a manager; the managers re-export those names. `createDaemonWatcher({...})` supplies the common PM2 launch-line re-adoption, endpoint probe, status skeleton, bounded log view, and port-release wait while managers retain daemon-specific parsing and lifecycle policy. `createDaemonLogBuffer({maxLines?})` is the bounded timestamped ring buffer of what PortOS logged around a launch, plus `withPm2Logs(output)` → that buffer followed by anything `pm2 logs` has which it doesn't already hold, deduped and re-capped (PM2's lines are a VIEW, never folded into the buffer — PM2 owns them and re-reads them every status call). `pm2ArgValue(args, flag)` reads one value back out of a PM2 process's recorded argv so a manager can recover a still-online daemon's launch config after a PortOS restart; `null` means the flag was absent, which a relaunch must leave off rather than defaulting. Also the shared **idle reaper**, for a daemon that cannot release its weights any other way: `registerIdleDaemon({name, getIdleMs, stop})` (seeds `lastUsedAt` to NOW, so a hand-started daemon gets a full window), `markDaemonUsed(name)` — call on real traffic, NEVER on a status poll — `daemonLastUsedAt(name)`, `idleWindowMs(minutes)` (minutes → ms; `0` = never, `null` = not configured, kept distinct), `reapIdleDaemons(now?)` → the names stopped, and `startIdleReaper({intervalMs?})` / `stopIdleReaper()` (ONE interval for all registrants, `unref`'d, idempotent). `mtplxServerManager` and `slotstreamServerManager` register: llama.cpp releases its checkpoint in place via `--sleep-idle-seconds` and must NOT be stopped for it. Deliberately mechanism only — what a launch line means and when a daemon may start is exactly what differs between the two. || `mtplxModels.js` | `listMtplxCachedModels({command?})` → `{models, error}` from `mtplx models --json` (walks local directories — pulls no weights, loads no model, but see `mtplxRuntime.js`: on an un-warmed Homebrew wrapper the spawn ITSELF is a several-hundred-megabyte runtime download, so poll callers must gate on `describeMtplxRuntime().ready` first) and `pickMtplxCachedModel(models)` → the repo id to hand `mtplx serve --model`. `models: null` means the cache could not be READ (no binary, command failed, unparseable) and is deliberately distinct from `[]` (read, and empty), because `services/localRuntimeSetup.js` starts MTPLX on its own default in the first case and refuses with the `mtplx pull` command in the second. Exists because `mtplx serve` defaults `--model` to one hard-coded checkpoint and exits 1 before binding when that repo is not cached — even on a host holding a different MTP model that serves fine. Picks only entries MTPLX itself calls complete (`validation.ok !== false`, so a half-finished pull is not served), preferring one with a recorded `mtplx_runtime.json` exactness contract. `describeMtplxCache(cache)` → `{state: 'unknown'\|'empty'\|'partial'\|'ready', model, count, error}` folds both into the one value `services/providerReadiness.js` puts on the checklist and `describeRuntimeSetup` picks a button from — so an empty cache is named up front instead of only inside the failure of a Start that could never work. || `mtplxRuntime.js` | `describeMtplxRuntime(binaryPath, {env?})` → `{ready, wrapper, venvPath}` — is MTPLX's own Python runtime on disk, decided by READING the binary rather than running it. Homebrew's `mtplx` is a shell wrapper that lazily bootstraps a version-keyed Python venv (a multi-hundred-megabyte pip install) on its first invocation, and `brew upgrade` re-arms it, so a status poll or an 8s-judged PM2 start is really a package download. This parses the wrapper's own `VENV=` assignment, honours `$MTPLX_BREW_VENV` the way `${MTPLX_BREW_VENV:-…}` does, and tests `<venv>/bin/mtplx` for executability — the wrapper's own `[ ! -x … ]` guard, so the two cannot disagree. Anything unrecognisable (a pip install, a compiled binary, an unparseable script) reports `ready: true, wrapper: false`, i.e. the status quo — never a block over a parse failure. |+| `slotstreamModels.js` | `listSlotstreamCachedModels({cacheDir?})` → `{models, error}` from a local directory walk of the SSD-streaming MoE cache (no network, no model load), `pickSlotstreamCachedModel(models, requested?)` → the checkpoint id to hand `slotstream serve --model`, and `planSlotstreamMemory({totalBytes?, overrideGb?})` → `{targetGb, expectedPeakGb, expectedWarmDecodeToks, auto}` so the LLMs row can show the memory plan instead of hiding it. `models: null` means the cache could not be READ and is deliberately distinct from `[]` (read, and empty), because a start never fetches weights. || `vllmQwenProject.js` | `resolveVllmProjectDir()` / `inspectVllmQwenProject()` → `{dir, hasProject, composeFile, hasWeights, weightsRoot}` for the syv-ai/qwen38-27b-rtx3090 compose project, plus `vllmStartBlockedReason(project)` → the prose refusal (or `null`), and `vllmProjectSetupState(project)` → `ready`/`empty`/`unknown` for the readiness checklist. `hasWeights` is tri-state: `true` found / `false` caches read and empty / `null` no cache readable (a docker-volume cache is invisible from a native-Win32 PortOS), and `services/localRuntimeSetup.js` refuses to `docker compose up` on anything but `true` so the start button can never kick off the ~20 GB prepare. Also owns WHERE the project lives: `readRecordedVllmProjectDir(envPath?)` / `recordVllmProjectDir(dir, envPath?)` keep PortOS's auto-detected directory as one line in the INSTALL's `.env` (`PATHS.installRoot`, so a worktree-booted server writes where the real install reads), and `vllmProjectDirIsSettled()` answers "is detection still worth a subprocess?" so the manager never re-lists the precedence. That order is `VLLM_QWEN_PROJECT_DIR` (this run's decision) → the record → `~/qwen-serving`; `envPath` is a parameter so a test's sandbox answers instead of the developer's install. Directory reads plus that one config line — never docker, never a registry. Other override: `VLLM_QWEN_WEIGHTS_DIR`. || `wslDistro.js` | Which WSL2 distro a native-Win32 PortOS should put Linux-side work in. `detectWslProjectDir(leaf)` → `{dir, distro, home}` or `{dir: null, reason}` (`no-wsl` / `no-distro` / `internal-distro` / `unreadable-share`), built from `wsl.exe -e sh -c 'echo "$WSL_DISTRO_NAME"; echo "$HOME"'` — the distro's OWN shell, because `wsl --list` prints UTF-16LE that a UTF-8 reader mangles while an executed program's stdout passes through byte for byte. Verifies the derived `\\wsl.localhost\…` path is readable from Windows before returning it (WSL running and its share answering are separate facts) and refuses a container engine's own distro (`docker-desktop` and friends are recreated on a reset). `parseWslProbe` / `parseWslDistroList` (NUL-stripping the UTF-16 bytes, for an error message only) are exported for their own tests; `WSL_UNC_PREFIX` names the share root for callers writing refusal prose. Exists so the vLLM stack places its ~20 GB of weights on the distro filesystem instead of asking a human to fill in a UNC template — every read from a `C:\` checkout would cross a 9p share. || `qwenAgentParsers.js` | The tool-call / reasoning parser flags a local runtime MUST carry to serve a Qwen3-family model to a coding agent — one table PortOS owns instead of three docs. `QWEN_AGENT_PARSERS` maps runtime → `{toolCallParser, reasoningParser, enableAutoToolChoice}` (vLLM `qwen3_xml` + `--enable-auto-tool-choice`, SGLang `qwen3_coder` + `--reasoning-parser qwen3`, llama both `null` — a positive "no such flag today", not a placeholder). `parserFlagsFor(runtime)` returns the argv fragment (always an array, so no caller type-checks) and `vllmExtraArgs()` its string form for the compose project's `.env` `EXTRA_ARGS`; an unknown runtime THROWS, because the failure it prevents is silent — a parser-less server answers fluently and returns tool markup as ordinary text with `tool_calls: null`, so the agent never touches a file. Spellings are empirical (`docs/research/2026-08-21-qwen38-rtx3090-vllm.md`, `…-sglang-qwen38-27b.md`); never auto-detect one from the chat template — that is how `hermes` got picked. Pure. |diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 3175eb41a1..84f6ebc4a6 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -9054,6 +9054,38 @@"server/routes/localLlm.js"]},+ {+ "method": "POST",+ "path": "/api/local-llm/slotstream/install",+ "mountPath": "/api/local-llm",+ "sources": [+ "server/routes/localLlm.js"+ ]+ },+ {+ "method": "POST",+ "path": "/api/local-llm/slotstream/start",+ "mountPath": "/api/local-llm",+ "sources": [+ "server/routes/localLlm.js"+ ]+ },+ {+ "method": "GET",+ "path": "/api/local-llm/slotstream/status",+ "mountPath": "/api/local-llm",+ "sources": [+ "server/routes/localLlm.js"+ ]+ },+ {+ "method": "POST",+ "path": "/api/local-llm/slotstream/stop",+ "mountPath": "/api/local-llm",+ "sources": [+ "server/routes/localLlm.js"+ ]+ },{"method": "GET","path": "/api/local-llm/status",@@ -17433,8 +17465,8 @@],"stats": {"mounts": 147,- "operations": 2159,- "declarations": 2163,+ "operations": 2163,+ "declarations": 2167,"sourceFiles": 229}}diff --git a/server/lib/index.js b/server/lib/index.jsindex 0befd98879..ced6270bcb 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -183,6 +183,7 @@ export * from './opencodeConfig.js';export * from './localProviderRuntime.js';export * from './mtplxModels.js';export * from './mtplxRuntime.js';+export * from './slotstreamModels.js';export * from './managedDaemon.js';export * from './vllmQwenProject.js';export * from './wslDistro.js';diff --git a/server/lib/localProviderRuntime.js b/server/lib/localProviderRuntime.jsindex 5ddd90bb9e..286265c00d 100644--- a/server/lib/localProviderRuntime.js+++ b/server/lib/localProviderRuntime.js@@ -12,7 +12,7 @@** This module is the pure half of the answer: given a provider record, which* local runtime backs it (`llama` / `ollama` / `lmstudio` / `mtplx` / `vllm` /- * `sglang`) and what+ * `sglang` / `slotstream`) and what* base URL should be probed. `services/providerReadiness.js` does the probing.* Kept side-effect-free so both the readiness service and its tests can reason* about the mapping without a daemon on the host.@@ -31,6 +31,7 @@import { getOpencodeLocalProviderNamespace, isOpencodeCommand } from './providerModels.js';import { opencodeLocalBaseUrl } from './opencodeConfig.js';import { isGatewayNamespace } from './providerGateways.js';+import { PORTS } from './ports.js';import { isLocalInstanceHost, isLocalInstanceEndpoint, localEndpointPort } from './localEndpoint.js';export { isLocalInstanceHost, isLocalInstanceEndpoint, localEndpointPort } from './localEndpoint.js';@@ -180,6 +181,19 @@ export const LOCAL_RUNTIMES = Object.freeze({// the card class, so there is no per-model rename for PortOS to offer.servesOneModel: true,}),+ slotstream: Object.freeze({+ id: 'slotstream',+ label: 'Slotstream',+ command: 'slotstream',+ // Dedicated loopback port — never 11434, which is a PortOS-managed Ollama.+ defaultBaseUrl: `http://127.0.0.1:${PORTS.SLOTSTREAM}/v1`,+ manageUrl: '/models/llms',+ docsUrl: 'https://github.com/carloslfu/slotstream',+ modelsHint: 'A start never fetches weights — add a checkpoint on Models → LLMs, then start Slotstream there.',+ servesOneModel: true,+ standbyWhenStopped: true,+ standbyDetail: 'No streaming runtime is running, which is a valid idle state. Start it from Models → LLMs when you want a model larger than this machine\'s RAM; with idle release configured, PortOS stops it and starts it again on the next request.',+ }),mtplx: Object.freeze({id: 'mtplx',label: 'MTPLX',@@ -215,7 +229,7 @@ export const LOCAL_RUNTIMES = Object.freeze({* launcher) started. Its "installed models" are whatever `GET /v1/models`* reports right now, and a measurement talks to the endpoint directly.*/-export const ASSESSABLE_RUNTIMES = Object.freeze(['ollama', 'lmstudio', 'llama', 'mtplx', 'vllm', 'sglang']);+export const ASSESSABLE_RUNTIMES = Object.freeze(['ollama', 'lmstudio', 'llama', 'mtplx', 'vllm', 'sglang', 'slotstream']);/** Assessable runtimes PortOS holds a provider record and model catalog for. */export const MANAGED_ASSESSMENT_BACKENDS = Object.freeze(['ollama', 'lmstudio']);@@ -276,7 +290,7 @@ function opencodeConfiguredBaseUrl(provider, namespace) {* local daemon to check.** @param {object|null|undefined} provider- * @returns {'llama'|'ollama'|'lmstudio'|'mtplx'|'vllm'|'sglang'|null}+ * @returns {'llama'|'ollama'|'lmstudio'|'mtplx'|'vllm'|'sglang'|'slotstream'|null}*/export function localRuntimeKind(provider) {if (!provider || typeof provider !== 'object') return null;@@ -284,6 +298,8 @@ export function localRuntimeKind(provider) {// carries `ollamaBacked` without being an OpenCode provider.const namespace = getOpencodeLocalProviderNamespace(provider);if (namespace && !isGatewayNamespace(namespace)) return namespace;+ if (provider?.id === 'slotstream' || /slotstream/i.test(provider?.name || '')) return 'slotstream';+ if (Number(localEndpointPort(provider?.endpoint)) === PORTS.SLOTSTREAM) return 'slotstream';return localBackendForProvider(provider);}diff --git a/server/lib/localProviderRuntime.test.js b/server/lib/localProviderRuntime.test.jsindex 4dc3c27b07..bf49755770 100644--- a/server/lib/localProviderRuntime.test.js+++ b/server/lib/localProviderRuntime.test.js@@ -8,6 +8,7 @@ import {normalizeOpenAiBaseUrl,} from './localProviderRuntime.js';import { opencodeLocalBaseUrl } from './opencodeConfig.js';+import { PORTS } from './ports.js';afterEach(() => {vi.unstubAllEnvs();@@ -89,6 +90,13 @@ describe('localRuntimeKind', () => {expect(localRuntimeKind(null)).toBeNull();expect(localRuntimeKind('nope')).toBeNull();});++ it('recognizes Slotstream by id, name, and dedicated port — never 11434', () => {+ expect(localRuntimeKind({ id: 'slotstream' })).toBe('slotstream');+ expect(localRuntimeKind({ name: 'Slotstream (local)' })).toBe('slotstream');+ expect(localRuntimeKind({ endpoint: `http://127.0.0.1:${PORTS.SLOTSTREAM}/v1` })).toBe('slotstream');+ expect(localRuntimeKind({ endpoint: 'http://127.0.0.1:11434/v1' })).toBe('ollama');+ });});describe('localRuntimeForProvider', () => {@@ -184,6 +192,8 @@ describe('localRuntimeForProvider', () => {expect(LOCAL_RUNTIMES.ollama.defaultBaseUrl).toBe(opencodeLocalBaseUrl('ollama'));expect(LOCAL_RUNTIMES.mtplx.defaultBaseUrl).toBe(opencodeLocalBaseUrl('mtplx'));expect(LOCAL_RUNTIMES.vllm.defaultBaseUrl).toBe(opencodeLocalBaseUrl('vllm'));+ expect(LOCAL_RUNTIMES.slotstream.defaultBaseUrl).toBe(`http://127.0.0.1:${PORTS.SLOTSTREAM}/v1`);+ expect(LOCAL_RUNTIMES.slotstream.defaultBaseUrl).not.toMatch(/11434/);});it('honors the env override the backend managers themselves read', () => {diff --git a/server/lib/managedDaemon.js b/server/lib/managedDaemon.jsindex 9f89b8b14e..f63d24250c 100644--- a/server/lib/managedDaemon.js+++ b/server/lib/managedDaemon.js@@ -1,7 +1,7 @@/*** Shared plumbing for a local daemon PortOS runs as an optional PM2 process* (`llamaServerManager.js` → `portos-llama-server`, `mtplxServerManager.js` →- * `portos-mtplx`).+ * `portos-mtplx`, `slotstreamServerManager.js` → `portos-slotstream`).** Both managers answer the same two questions the same way, and the answers are* fiddly enough that two copies drift:@@ -21,22 +21,25 @@*//**- * The PM2 process names of the two local model servers PortOS manages.+ * The PM2 process names of the local model servers PortOS manages.** Declared here rather than in each manager so the health monitor can recognize* them without importing a manager (and its whole PM2/model-probe dependency- * chain); `llamaServerManager.js` and `mtplxServerManager.js` re-export these as- * `LLAMA_APP` / `MTPLX_APP`.+ * chain); `llamaServerManager.js`, `mtplxServerManager.js`, and+ * `slotstreamServerManager.js` re-export these as `LLAMA_APP` / `MTPLX_APP` /+ * `SLOTSTREAM_APP`.*/export const LLAMA_APP = 'portos-llama-server';export const MTPLX_APP = 'portos-mtplx';-const MODEL_SERVER_APPS = [LLAMA_APP, MTPLX_APP];+export const SLOTSTREAM_APP = 'portos-slotstream';+const MODEL_SERVER_APPS = [LLAMA_APP, MTPLX_APP, SLOTSTREAM_APP];/*** Whether a PM2 process is one of those model servers.*- * A model server's resident size IS the checkpoint it loaded — llama.cpp and- * MTPLX hold multi-GB weights for as long as they are up, by design. Measuring+ * A model server's resident size IS the checkpoint it loaded — llama.cpp,+ * MTPLX, and Slotstream hold multi-GB weights for as long as they are up, by+ * design. Measuring* them against a generic per-process memory cap produces a warning the user can* never clear (a 24GB llama-server against a 2GB cap is a correctly-running* server, not a leak), so callers policing per-process memory skip them. Genuinediff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.jsindex 152b5e257d..9c6676fcfe 100644--- a/server/lib/mediaValidation.js+++ b/server/lib/mediaValidation.js@@ -181,6 +181,14 @@ export const localLlmMtplxStartSchema = z.object({'model must be a Hugging Face repo id',).optional().nullable(),});+// Slotstream launch. Every field is optional: with none of them PortOS serves+// the first cached checkpoint on the dedicated loopback port. `memoryGb` is the+// explicit cache-size cap persisted on the saved launch line; absent = auto.+export const localLlmSlotstreamStartSchema = z.object({+ port: z.coerce.number().int().min(1).max(65535).optional(),+ model: z.string().trim().max(300).optional().nullable(),+ memoryGb: z.coerce.number().min(6).max(512).optional().nullable(),+});// MTPLX model catalog. `mtplx forge discover` is upstream's own index of// MTPLX-branded MTP checkpoints; an empty query means its default listing.export const localLlmMtplxSearchSchema = z.object({diff --git a/server/lib/ports.js b/server/lib/ports.jsindex cf0147e289..40ec42f54e 100644--- a/server/lib/ports.js+++ b/server/lib/ports.js@@ -17,6 +17,7 @@ export const PORTS = {POSTGRES_DOCKER: 5561, // PostgreSQL Docker container (host port mapping)WHISPER: 5562, // Loopback whisper.cpp speech-to-text serverEIDOVERSE_HOST: 5563, // Optional HTTPS/WebSocket bridge to Eidoverse Worlds on :8940+ SLOTSTREAM: 5564, // Loopback SSD-streaming MoE runtime (never 11434 — that collides with Ollama)LLAMA_SERVER: 5568, // Loopback llama.cpp speculative-decoding serverVLLM_QWEN: 18020, // Loopback vLLM Qwen3.8-27B (DFlash 2) container — operator-started, never by PortOSSGLANG_QWEN: 18021, // Loopback SGLang Qwen3.8-27B container (Hopper/Blackwell) — operator-started, never by PortOSdiff --git a/server/lib/slotstreamModels.js b/server/lib/slotstreamModels.jsnew file mode 100644index 0000000000..d92a2f328b--- /dev/null+++ b/server/lib/slotstreamModels.js@@ -0,0 +1,105 @@+/**+ * What an SSD-streaming MoE runtime has on disk, and the memory plan PortOS+ * shows before a start.+ *+ * A start never downloads weights — an empty cache is reported rather than+ * silently filled. Listing is a local directory walk (no network, no model+ * load). `models: null` means the cache could NOT be read, which is+ * deliberately not the same as `[]` (read, and empty).+ */++import { readdir, stat } from 'fs/promises';+import { homedir, totalmem } from 'os';+import { join } from 'path';++/** Floor of the technique: a dense trunk plus a tiny expert pool still runs. */+export const SLOTSTREAM_MEMORY_FLOOR_GB = 6;++/** Measured ~12 tok/s warm decode at a 32 GB target on a 48 GB machine. */+const WARM_DECODE_REF_GB = 32;+const WARM_DECODE_REF_TOKS = 12;++const round1 = (n) => Math.round(n * 10) / 10;++/**+ * Default on-disk cache. Override with `SLOTSTREAM_MODEL_DIR` or the `cacheDir`+ * test seam — never invent a second location in the manager.+ */+export function slotstreamCacheDir() {+ return process.env.SLOTSTREAM_MODEL_DIR || join(homedir(), '.slotstream', 'models');+}++/** Where a GitHub-release install drops the `slotstream` binary. */+export function slotstreamBinDir() {+ return join(homedir(), '.slotstream', 'bin');+}++/**+ * Auto-size the expert-cache target from host RAM, or honour an explicit cap.+ *+ * Cache size trades speed against memory and never changes output. The default+ * leaves headroom so the rest of PortOS is not paged out; an override skips+ * that check (the user asked for a specific cap).+ *+ * @param {{totalBytes?: number, overrideGb?: number|null}} [options]+ * @returns {{totalRamGb: number, targetGb: number, expectedPeakGb: number, expectedWarmDecodeToks: number, auto: boolean}}+ */+export function planSlotstreamMemory({ totalBytes, overrideGb } = {}) {+ const totalRamGb = (Number.isFinite(totalBytes) ? totalBytes : totalmem()) / (1024 ** 3);+ const autoTarget = Math.max(+ SLOTSTREAM_MEMORY_FLOOR_GB,+ Math.min(totalRamGb * 0.67, Math.max(SLOTSTREAM_MEMORY_FLOOR_GB, totalRamGb - 8)),+ );+ const parsed = Number(overrideGb);+ const hasOverride = Number.isFinite(parsed) && parsed > 0;+ const targetGb = hasOverride ? Math.max(SLOTSTREAM_MEMORY_FLOOR_GB, parsed) : autoTarget;+ return {+ totalRamGb: round1(totalRamGb),+ targetGb: round1(targetGb),+ expectedPeakGb: round1(targetGb),+ expectedWarmDecodeToks: Math.max(1, Math.round(WARM_DECODE_REF_TOKS * (targetGb / WARM_DECODE_REF_GB))),+ auto: !hasOverride,+ };+}++/**+ * Cached checkpoints on disk.+ *+ * Each subdirectory of the cache is one checkpoint; the directory name is the+ * id handed to `slotstream serve --model`. No network.+ *+ * @param {{cacheDir?: string}} [options]+ * @returns {Promise<{models: object[]|null, error: string|null}>}+ */+export async function listSlotstreamCachedModels({ cacheDir } = {}) {+ const dir = cacheDir || slotstreamCacheDir();+ const entries = await readdir(dir).catch((err) => err);+ if (entries instanceof Error) {+ if (entries.code === 'ENOENT') return { models: [], error: null };+ return { models: null, error: `could not read Slotstream cache (${entries.code || entries.message})` };+ }++ const models = [];+ for (const name of entries) {+ const full = join(dir, name);+ const info = await stat(full).catch(() => null);+ if (!info?.isDirectory()) continue;+ models.push({ id: name, path: full });+ }+ return { models, error: null };+}++/**+ * The checkpoint id a start should hand `--model`, or null when nothing is+ * servable. Prefers an explicit request; otherwise the first cached directory.+ *+ * @param {object[]|null|undefined} models+ * @param {string|null} [requested]+ * @returns {string|null}+ */+export function pickSlotstreamCachedModel(models, requested = null) {+ if (typeof requested === 'string' && requested.trim()) return requested.trim();+ if (!Array.isArray(models) || models.length === 0) return null;+ const first = models.find((row) => typeof row?.id === 'string' && row.id);+ return first?.id ?? null;+}diff --git a/server/lib/slotstreamModels.test.js b/server/lib/slotstreamModels.test.jsnew file mode 100644index 0000000000..6474ea184d--- /dev/null+++ b/server/lib/slotstreamModels.test.js@@ -0,0 +1,68 @@+import { mkdir, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { afterEach, describe, expect, it } from 'vitest';+import {+ listSlotstreamCachedModels,+ pickSlotstreamCachedModel,+ planSlotstreamMemory,+ SLOTSTREAM_MEMORY_FLOOR_GB,+} from './slotstreamModels.js';++describe('planSlotstreamMemory', () => {+ it('auto-sizes below total RAM and reports peak plus warm decode', () => {+ const plan = planSlotstreamMemory({ totalBytes: 48 * 1024 ** 3 });+ expect(plan.auto).toBe(true);+ expect(plan.totalRamGb).toBe(48);+ expect(plan.targetGb).toBeGreaterThanOrEqual(SLOTSTREAM_MEMORY_FLOOR_GB);+ expect(plan.targetGb).toBeLessThan(48);+ expect(plan.expectedPeakGb).toBe(plan.targetGb);+ expect(plan.expectedWarmDecodeToks).toBeGreaterThanOrEqual(1);+ });++ it('honours an explicit memory-cap override instead of hiding it', () => {+ const plan = planSlotstreamMemory({ totalBytes: 48 * 1024 ** 3, overrideGb: 22 });+ expect(plan.auto).toBe(false);+ expect(plan.targetGb).toBe(22);+ expect(plan.expectedPeakGb).toBe(22);+ });++ it('does not drop below the technique floor even on a small host', () => {+ const plan = planSlotstreamMemory({ totalBytes: 8 * 1024 ** 3 });+ expect(plan.targetGb).toBeGreaterThanOrEqual(SLOTSTREAM_MEMORY_FLOOR_GB);+ });+});++describe('listSlotstreamCachedModels', () => {+ let dir = null;++ afterEach(async () => {+ if (dir) await rm(dir, { recursive: true, force: true });+ dir = null;+ });++ it('treats a missing cache directory as empty, not unreadable', async () => {+ const cache = await listSlotstreamCachedModels({ cacheDir: join(tmpdir(), 'portos-slotstream-missing-cache') });+ expect(cache).toEqual({ models: [], error: null });+ });++ it('lists checkpoint directories and ignores files', async () => {+ dir = join(tmpdir(), `portos-slotstream-cache-${Date.now()}`);+ await mkdir(join(dir, 'qwen-moe'), { recursive: true });+ await writeFile(join(dir, 'notes.txt'), 'not a checkpoint');+ const cache = await listSlotstreamCachedModels({ cacheDir: dir });+ expect(cache.error).toBeNull();+ expect(cache.models).toEqual([expect.objectContaining({ id: 'qwen-moe' })]);+ });+});++describe('pickSlotstreamCachedModel', () => {+ it('prefers an explicit request over the cache order', () => {+ expect(pickSlotstreamCachedModel([{ id: 'a' }, { id: 'b' }], 'b')).toBe('b');+ });++ it('returns null when the cache was unreadable or empty', () => {+ expect(pickSlotstreamCachedModel(null)).toBeNull();+ expect(pickSlotstreamCachedModel([])).toBeNull();+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 7d5dd501a0..abb7865aa3 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1932,6 +1932,14 @@ export const localLlmSettingsSchema = z.object({port: z.number().int().min(1).max(65535).optional(),}).strict().optional(),}).strict().optional(),+ slotstream: z.object({+ idleMinutes: z.number().int().min(0).max(1440).optional(),+ launch: z.object({+ model: z.string().trim().max(300).nullable().optional(),+ port: z.number().int().min(1).max(65535).optional(),+ memoryGb: z.number().min(6).max(512).nullable().optional(),+ }).strict().optional(),+ }).strict().optional(),}).strict();// =============================================================================diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 06aa3c8d99..aa20475057 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -34,6 +34,7 @@ import {localLlmLlamaServerStartSchema,localLlmLmStudioServiceSchema,localLlmMtplxStartSchema,+ localLlmSlotstreamStartSchema,localLlmMtplxSearchSchema,localLlmMtplxPullSchema,localLlmMtplxRemoveSchema,@@ -48,6 +49,7 @@ import {upgradeLlamaServer,} from '../services/llamaServerManager.js'import { MTPLX_APP, getMtplxServerStatus, startMtplxServer, stopMtplxServer, installMtplx } from '../services/mtplxServerManager.js'+import { SLOTSTREAM_APP, getSlotstreamServerStatus, startSlotstreamServer, stopSlotstreamServer, installSlotstream } from '../services/slotstreamServerManager.js'import { searchMtplxCatalog, pullMtplxModel, removeMtplxModel } from '../services/mtplxModelManager.js'import { saveProcessList } from '../services/pm2.js'import { getSpecDecodePresetStatus, downloadSpecDecodeModel, cancelSpecDecodeModelDownload } from '../services/specDecodeModels.js'@@ -852,19 +854,58 @@ router.post('/mtplx/models/remove', asyncHandler(async (req, res) => {res.json(result)}))+// GET /api/local-llm/slotstream/status — binary, process, memory plan, cache, logs.+router.get('/slotstream/status', asyncHandler(async (_req, res) => {+ res.json(await getSlotstreamServerStatus())+}))++// POST /api/local-llm/slotstream/start — launch `slotstream serve` under PM2.+// Never downloads weights; an empty cache is a 400, not a silent fetch.+router.post('/slotstream/start', asyncHandler(async (req, res) => {+ const options = validateRequest(localLlmSlotstreamStartSchema, req.body)+ const emit = emitter(req)+ emit('start', 'Starting Slotstream…')+ const result = await startSlotstreamServer({ ...options, onProgress: (line) => emit('start', line) })+ .catch((err) => {+ emit('error', err.message)+ throw err+ })+ resetProviderReadinessCache()+ emit('complete', `Slotstream is running at ${result.endpoint}`)+ res.json(result)+}))++router.post('/slotstream/stop', asyncHandler(async (_req, res) => {+ const result = await stopSlotstreamServer()+ resetProviderReadinessCache()+ res.json(result)+}))++router.post('/slotstream/install', asyncHandler(async (req, res) => {+ const emit = emitter(req)+ const result = await installSlotstream({ onProgress: ({ event, message }) => emit(event, message) })+ .catch((err) => {+ emit('error', `Install failed: ${err.message}`)+ throw err+ })+ resetProviderReadinessCache()+ emit('complete', 'Slotstream installed')+ res.json(result)+}))+// POST /api/local-llm/save-startup — `pm2 save`, so the PM2-managed local// runtime servers currently running (llama-server, PortOS itself) are in the// dump a boot-time `pm2 resurrect` replays. The privileged half — `pm2// startup`, which writes the launchd/systemd unit — is deliberately blocked and// stays a one-time operator command.//-// MTPLX is deliberately EXCLUDED. It is started on demand by the first request-// that needs it and stopped again when idle, so resurrecting it at boot would-// pin its multi-gigabyte checkpoint on a machine nobody has asked anything of-// yet — the exact waste the idle stop exists to end. The running process is-// left alone; only the boot list drops it.+// MTPLX and Slotstream are deliberately EXCLUDED. Both are started on demand+// by the first request that needs them and stopped again when idle, so+// resurrecting them at boot would pin a multi-gigabyte checkpoint on a machine+// nobody has asked anything of yet — the exact waste the idle stop exists to+// end. The running process is left alone; only the boot list drops it.router.post('/save-startup', asyncHandler(async (_req, res) => {- res.json(await saveProcessList(null, { exclude: [MTPLX_APP] }))+ res.json(await saveProcessList(null, { exclude: [MTPLX_APP, SLOTSTREAM_APP] }))}))export default routerdiff --git a/server/services/aiProvider.js b/server/services/aiProvider.jsindex 3f120a5d38..751d2449ad 100644--- a/server/services/aiProvider.js+++ b/server/services/aiProvider.js@@ -7,6 +7,7 @@ import { getAllProviders } from './providers.js';import { startAIOp } from './aiStatusEvents.js';import { ensureProviderReady as ensureOllamaProviderReady, isOllamaProvider } from './ollamaManager.js';import { ensureMtplxProviderReady, isMtplxProvider } from './mtplxServerManager.js';+import { ensureSlotstreamProviderReady, isSlotstreamProvider } from './slotstreamServerManager.js';// localModelHealing is lazy-imported at its (rare, error-recovery) call site// below — a static import here pulls its notifications/providers deps (which// eagerly import fileUtils `PATHS`) into every aiProvider consumer's module@@ -515,6 +516,19 @@ export async function callProviderAISimple(provider, model, prompt, options = {}}}+ // Same bargain for Slotstream: this is the only place a simple call refreshes+ // its idle clock, so without this branch the reaper would stop the daemon+ // mid-session and the next call would get a bare connection refusal.+ if (isSlotstreamProvider(provider)) {+ statusOp.update('provider:starting', 'Starting Slotstream if needed…', { providerId: provider.id });+ const ready = await ensureSlotstreamProviderReady(provider).catch((err) => ({ success: false, error: err.message }));+ if (!ready.success) {+ const error = `Slotstream is not running and PortOS could not start it: ${ready.error || 'unknown error'}`;+ statusOp.error(error);+ return { error };+ }+ }+const first = await postChatCompletion(provider, model, body, opts);if (!first.error) {statusOp.complete(`${doneLabel} done (${elapsedSec()}s)`, throughput(first.tokens));diff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.jsindex f1386b6279..2e1e013ee7 100644--- a/server/services/localModelAssessments.js+++ b/server/services/localModelAssessments.js@@ -96,6 +96,7 @@ import {restoreLlamaServerConfig,} from './llamaServerManager.js';import { getMtplxServerEndpoint, getMtplxServerStatus, relaunchMtplxServerWithTuning } from './mtplxServerManager.js';+import { getSlotstreamServerEndpoint } from './slotstreamServerManager.js';import { getSpecDecodePresetStatus } from './specDecodeModels.js';import { listModels } from './localLlm.js';import {@@ -176,7 +177,7 @@ export async function runtimeEndpoint(runtime) {// The endpoint-only accessors, NOT the `get*Status` calls — those pay for a// network probe and an `execPm2 logs` subprocess, and this path runs on every// Performance page load only to learn a port number.- const resolver = { llama: getLlamaServerEndpoint, mtplx: getMtplxServerEndpoint }[runtime];+ const resolver = { llama: getLlamaServerEndpoint, mtplx: getMtplxServerEndpoint, slotstream: getSlotstreamServerEndpoint }[runtime];if (resolver) {const endpoint = await resolver().catch(() => null);if (endpoint) return endpoint;diff --git a/server/services/localModelAssessments.test.js b/server/services/localModelAssessments.test.jsindex 5ccd7842c2..c5960fa9ee 100644--- a/server/services/localModelAssessments.test.js+++ b/server/services/localModelAssessments.test.js@@ -1078,7 +1078,7 @@ describe('tuning', () => {describe('runtime roster', () => {it('reports every assessable runtime with its knob catalog', async () => {const report = await svc.getAssessmentReport();- expect(report.runtimes.map((r) => r.id)).toEqual(['ollama', 'lmstudio', 'llama', 'mtplx', 'vllm', 'sglang']);+ expect(report.runtimes.map((r) => r.id)).toEqual(['ollama', 'lmstudio', 'llama', 'mtplx', 'vllm', 'sglang', 'slotstream']);expect(report.runtimes.find((r) => r.id === 'llama').tuningSpecs.some((s) => s.id === 'ubatchSize')).toBe(true);});diff --git a/server/services/localRuntimeSetup.js b/server/services/localRuntimeSetup.jsindex ad6cbe9782..fccd96cdcb 100644--- a/server/services/localRuntimeSetup.js+++ b/server/services/localRuntimeSetup.js@@ -57,6 +57,7 @@import { LOCAL_RUNTIMES, localEndpointPort } from '../lib/localProviderRuntime.js';import { describeMtplxCache, listMtplxCachedModels } from '../lib/mtplxModels.js';import { describeMtplxRuntime } from '../lib/mtplxRuntime.js';+import { listSlotstreamCachedModels } from '../lib/slotstreamModels.js';import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';import { inspectSglangQwenProject, sglangStartBlockedReason } from '../lib/sglangQwenProject.js';import { sglangUnsupportedReason } from '../lib/sglangQwenRecipe.js';@@ -65,6 +66,7 @@ import { findCommandOnPath } from '../lib/processEnv.js';import { runStreamingCommand } from '../lib/streamingSpawn.js';import { installLlamaServer } from './llamaServerManager.js';import { installMtplx, startMtplxServer, MTPLX_UNSUPPORTED_REASON } from './mtplxServerManager.js';+import { installSlotstream, startSlotstreamServer, SLOTSTREAM_UNSUPPORTED_REASON } from './slotstreamServerManager.js';import { controlOllamaServer, installBackend } from './localLlm.js';import { isAppInstalled as isLmStudioAppInstalled } from './lmStudioManager.js';import { provisionVllmQwenProject, readVllmQwenSetupState, startVllmQwenProject } from './vllmQwenManager.js';@@ -319,6 +321,38 @@ const SETUP_ROWS = Object.freeze({},}),+ slotstream: Object.freeze({+ platforms: ['darwin'],+ unsupportedReason: SLOTSTREAM_UNSUPPORTED_REASON,+ async install({ emit }) {+ return installSlotstream({ onProgress: (p) => { if (p?.message) emit(p.message); } })+ .catch((err) => ({ success: false, error: err.message }));+ },+ /**+ * What Slotstream's cache holds, WITHOUT starting it — a local directory+ * walk. There is deliberately no `provision` row beside it: PortOS does not+ * fetch weights for this runtime, so the checklist reports an empty cache+ * rather than offering a download button.+ *+ * This row is what keeps `standbyWhenStopped` honest. Without it+ * `readRuntimeWeights('slotstream')` answers `'unknown'`, and a stopped+ * Slotstream with an empty cache reads as "a valid idle state" — pointing+ * the user at a start that cannot succeed.+ */+ async weights() {+ const cache = await listSlotstreamCachedModels();+ if (cache.models === null) return 'unknown';+ return cache.models.length > 0 ? 'ready' : 'empty';+ },+ async start({ emit, endpoint, isCancelled }) {+ if (isCancelled()) return { success: false, error: 'Cancelled before the server was started.' };+ const port = Number(localEndpointPort(endpoint)) || undefined;+ return startSlotstreamServer({ port, waitMs: START_TIMEOUT_MS, onProgress: emit })+ .then(() => ({ success: true }))+ .catch((err) => ({ success: false, error: err.message }));+ },+ }),+vllm: Object.freeze({// CUDA + Marlin + FlashInfer in a Linux container. On macOS there is no card// to give it, and DFlash 2 on Apple Silicon is unproven in this project —diff --git a/server/services/localRuntimeSetup.test.js b/server/services/localRuntimeSetup.test.jsindex 35530da0f0..ad757dc7d3 100644--- a/server/services/localRuntimeSetup.test.js+++ b/server/services/localRuntimeSetup.test.js@@ -98,7 +98,7 @@ afterEach(() => {describe('describeRuntimeSetup', () => {it('covers every runtime the readiness checklist can report', () => {- expect([...SETUP_RUNTIME_KINDS].sort()).toEqual(['llama', 'lmstudio', 'mtplx', 'ollama', 'sglang', 'vllm']);+ expect([...SETUP_RUNTIME_KINDS].sort()).toEqual(['llama', 'lmstudio', 'mtplx', 'ollama', 'sglang', 'slotstream', 'vllm']);});it('offers install AND start when nothing is there yet', () => {diff --git a/server/services/providerExecutionReadiness.js b/server/services/providerExecutionReadiness.jsindex 867fe9094d..9440c5106e 100644--- a/server/services/providerExecutionReadiness.js+++ b/server/services/providerExecutionReadiness.js@@ -14,6 +14,7 @@import { describeMissingPrerequisites, providerPrerequisites } from '../lib/providerPrerequisites.js';import { ensureProviderReady as ensureOllamaProviderReady, isOllamaProvider } from './ollamaManager.js';import { ensureMtplxProviderReady, isMtplxProvider } from './mtplxServerManager.js';+import { ensureSlotstreamProviderReady, isSlotstreamProvider } from './slotstreamServerManager.js';const failedReadiness = (runtime, result) => ({...result,@@ -44,5 +45,10 @@ export async function ensureProviderReadyForExecution(provider) {return result.success ? result : failedReadiness('MTPLX', result);}+ if (isSlotstreamProvider(provider)) {+ const result = await ensureSlotstreamProviderReady(provider);+ return result.success ? result : failedReadiness('Slotstream', result);+ }+return { success: true };}diff --git a/server/services/providerExecutionReadiness.test.js b/server/services/providerExecutionReadiness.test.jsindex 2bd5c8faed..e1e4fef825 100644--- a/server/services/providerExecutionReadiness.test.js+++ b/server/services/providerExecutionReadiness.test.js@@ -5,6 +5,8 @@ const mocks = vi.hoisted(() => ({ensureMtplx: vi.fn(),isOllama: vi.fn(),isMtplx: vi.fn(),+ ensureSlotstream: vi.fn(),+ isSlotstream: vi.fn(),}));vi.mock('./ollamaManager.js', () => ({@@ -17,6 +19,11 @@ vi.mock('./mtplxServerManager.js', () => ({isMtplxProvider: mocks.isMtplx,}));+vi.mock('./slotstreamServerManager.js', () => ({+ ensureSlotstreamProviderReady: mocks.ensureSlotstream,+ isSlotstreamProvider: mocks.isSlotstream,+}));+const { ensureProviderReadyForExecution } = await import('./providerExecutionReadiness.js');describe('provider execution readiness', () => {@@ -26,6 +33,8 @@ describe('provider execution readiness', () => {mocks.ensureMtplx.mockResolvedValue({ success: true });mocks.isOllama.mockReturnValue(false);mocks.isMtplx.mockReturnValue(false);+ mocks.ensureSlotstream.mockResolvedValue({ success: true });+ mocks.isSlotstream.mockReturnValue(false);});it('leaves configured providers without a managed local daemon alone', async () => {@@ -77,6 +86,16 @@ describe('provider execution readiness', () => {expect(mocks.ensureOllama).not.toHaveBeenCalled();});+ it('wakes Slotstream for a Slotstream provider the idle reaper stopped', async () => {+ const provider = { id: 'slotstream', type: 'api', endpoint: 'http://127.0.0.1:5564/v1' };+ mocks.isSlotstream.mockReturnValue(true);++ await expect(ensureProviderReadyForExecution(provider)).resolves.toEqual({ success: true });+ expect(mocks.ensureSlotstream).toHaveBeenCalledWith(provider);+ expect(mocks.ensureOllama).not.toHaveBeenCalled();+ expect(mocks.ensureMtplx).not.toHaveBeenCalled();+ });+it('keeps the failing runtime in the error shown by the runner', async () => {const provider = { id: 'mtplx', type: 'api', endpoint: 'http://127.0.0.1:8000/v1' };mocks.isMtplx.mockReturnValue(true);diff --git a/server/services/slotstreamServerManager.js b/server/services/slotstreamServerManager.jsnew file mode 100644index 0000000000..01f528996e--- /dev/null+++ b/server/services/slotstreamServerManager.js@@ -0,0 +1,525 @@+/**+ * SSD-streaming MoE process manager+ *+ * Lifecycle management (status probe, install, start, stop, recent logs) for a+ * local `slotstream serve` OpenAI-compatible API server, managed as an optional+ * PM2 process (`portos-slotstream`) — the same shape as `mtplxServerManager.js`.+ *+ * A start never downloads weights. An absent checkpoint is reported, not+ * silently fetched. The memory plan (target GB, expected peak, expected warm+ * decode) is part of the status payload so the LLMs row can show it, and an+ * explicit memory-cap override is persisted on the saved launch line the+ * on-demand start replays.+ *+ * Always passes `--port` explicitly. Upstream's default (11434) collides with+ * a PortOS-managed Ollama, so that port is refused.+ */++import { chmod, mkdir, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { commandExists } from '../lib/commandExists.js';+import { ServerError } from '../lib/errorHandler.js';+import { sleep } from '../lib/fileUtils.js';+import { LOCAL_RUNTIMES, localEndpointPort, localRuntimeKind, isLocalInstanceEndpoint } from '../lib/localProviderRuntime.js';+import {+ createDaemonWatcher,+ pm2ArgValue,+ idleWindowMs,+ markDaemonUsed,+ registerIdleDaemon,+ SLOTSTREAM_APP,+} from '../lib/managedDaemon.js';+import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';+import { isAppleSilicon, isPortInUse } from '../lib/platform.js';+import { PORTS } from '../lib/ports.js';+import { findCommandOnPath } from '../lib/processEnv.js';+import {+ listSlotstreamCachedModels,+ pickSlotstreamCachedModel,+ planSlotstreamMemory,+ slotstreamBinDir,+ slotstreamCacheDir,+} from '../lib/slotstreamModels.js';+import { runStreamingCommand } from '../lib/streamingSpawn.js';+import { execPm2, getAppStatusStrict, clearJlistCache, getSavedProcessNames } from './pm2.js';++export { SLOTSTREAM_APP };++const PROBE_TIMEOUT_MS = 1500;+const INSTALL_TIMEOUT_MS = 20 * 60 * 1000;+const OLLAMA_COLLISION_PORT = 11434;++let startupWaitMs = 8_000;+let startupPollMs = 1500;+let relaunchReadyTimeoutMs = 300_000;+let relaunchPollMs = 1000;++const DEFAULT_HOST = '127.0.0.1';+const DEFAULT_PORT = Number(localEndpointPort(LOCAL_RUNTIMES.slotstream.defaultBaseUrl)) || PORTS.SLOTSTREAM;++export const SLOTSTREAM_UNSUPPORTED_REASON = 'Slotstream runs only on macOS with Apple Silicon.';+const slotstreamNoModelError = () => `Slotstream has no model weights cached, so its server would exit before it binds a port. A start never downloads weights — place a checkpoint directory in ${slotstreamCacheDir()}, then start it again.`;+const SLOTSTREAM_OLLAMA_PORT_ERROR = `Port ${OLLAMA_COLLISION_PORT} is Ollama's default and a PortOS-managed Ollama already uses it. Point Slotstream at its dedicated loopback port (${DEFAULT_PORT}) instead.`;++const DEFAULT_SLOTSTREAM_LOG_FILES = {+ stdout: join(tmpdir(), 'portos-slotstream-out.log'),+ stderr: join(tmpdir(), 'portos-slotstream-error.log'),+};++let slotstreamLogFiles = DEFAULT_SLOTSTREAM_LOG_FILES;++const resetSlotstreamLogs = async () => {+ const results = await Promise.all(+ Object.entries(slotstreamLogFiles).map(([stream, path]) => (+ writeFile(path, '')+ .then(() => true)+ .catch((error) => {+ console.error(`❌ Slotstream: could not reset ${stream} startup log (${error?.code || 'unknown'}); bootstrap diagnosis disabled for this launch`);+ return false;+ })+ )),+ );+ return results.every(Boolean);+};++let currentConfig = null;+let lastExitError = null;++const probeEndpoint = async (endpoint) =>+ (await probeOpenAiModels(endpoint, { timeoutMs: PROBE_TIMEOUT_MS })).reachable;++const endpointFor = (config) =>+ `http://${DEFAULT_HOST}:${config?.port ?? DEFAULT_PORT}/v1`;++const daemon = createDaemonWatcher({+ appName: SLOTSTREAM_APP,+ defaultHost: DEFAULT_HOST,+ defaultPort: DEFAULT_PORT,+ endpointFor,+ parseConfigFromArgs,+ probe: probeEndpoint,+ isPortInUse: (...args) => isPortInUse(...args),+ sleep,+ getConfig: () => currentConfig,+ setConfig: (config) => { currentConfig = config; },+ getLastExitError: () => lastExitError,+ getAppStatus: (...args) => getAppStatusStrict(...args),+ getSavedProcessNames: (...args) => getSavedProcessNames(...args),+ execPm2: (...args) => execPm2(...args),+});+const appendLog = daemon.appendLog;++/**+ * Reconstructs the launch config from PM2 process args when PortOS restarted+ * while the PM2 process stayed online.+ */+function parseConfigFromArgs(args) {+ if (!args) return null;+ const list = Array.isArray(args) ? args : String(args).split(' ');+ if (!list.includes('serve')) return null;+ const port = pm2ArgValue(list, '--port');+ const memoryGb = pm2ArgValue(list, '--memory-gb');+ return {+ port: port ? Number(port) : DEFAULT_PORT,+ model: pm2ArgValue(list, '--model'),+ memoryGb: memoryGb && Number.isFinite(Number(memoryGb)) ? Number(memoryGb) : null,+ };+}++const resolveStartPort = (requested) => {+ const port = Number.isFinite(Number(requested)) ? Number(requested) : DEFAULT_PORT;+ if (port === OLLAMA_COLLISION_PORT) {+ throw new ServerError(SLOTSTREAM_OLLAMA_PORT_ERROR, { status: 400, code: 'SLOTSTREAM_PORT_COLLISION' });+ }+ return port;+};++/** Resolve the `slotstream` executable on PATH, then the release-install location. */+export const resolveSlotstreamBinary = () =>+ findCommandOnPath('slotstream') || findCommandOnPath(join(slotstreamBinDir(), 'slotstream'));++export async function getSlotstreamServerEndpoint() {+ if (!currentConfig) {+ await daemon.readLaunch();+ }+ return daemon.endpoint();+}++/**+ * Current Slotstream state: binary, process, endpoint, memory plan, cache, logs.+ */+export async function getSlotstreamServerStatus() {+ const binaryPath = resolveSlotstreamBinary();+ const installed = Boolean(binaryPath);+ const supported = installed || isAppleSilicon();+ const base = await daemon.getStatusBase({ installed });+ const saved = await savedLaunchConfig();+ const cache = installed ? await listSlotstreamCachedModels() : { models: null, error: null };+ // The SAVED override, never the running config: `--memory-gb` is always on+ // the launch line, so reading the target back off it would report every+ // auto-sized start as an explicit cap and `auto` would never be true.+ const memoryPlan = planSlotstreamMemory({ overrideGb: saved.memoryGb });++ return {+ ...base,+ supported,+ unsupportedReason: supported ? null : SLOTSTREAM_UNSUPPORTED_REASON,+ idleMinutes: await configuredIdleMinutes(),+ launch: saved,+ memoryPlan,+ cachedModels: (cache.models || []).map((m) => m?.id).filter(Boolean),+ cacheDir: slotstreamCacheDir(),+ cacheError: cache.error,+ };+}++/**+ * Install the Apple Silicon Slotstream binary from GitHub Releases into+ * `~/.slotstream/bin`. Never pipes a remote script to a shell, and never+ * fetches model weights.+ */+export async function installSlotstream({ onProgress = () => {} } = {}) {+ const emit = (message) => onProgress({ event: 'progress', message });+ if (!isAppleSilicon()) {+ throw new ServerError(SLOTSTREAM_UNSUPPORTED_REASON, { status: 400, code: 'SLOTSTREAM_UNSUPPORTED_PLATFORM' });+ }++ const binDir = slotstreamBinDir();+ await mkdir(binDir, { recursive: true });++ if (!(await commandExists('gh', ['--version']))) {+ throw new ServerError(+ 'PortOS could not install Slotstream because GitHub CLI is not available on this machine.',+ { status: 400, code: 'SLOTSTREAM_INSTALL_UNAVAILABLE' },+ );+ }++ emit('Downloading Slotstream from GitHub Releases…');+ const download = await runStreamingCommand('gh', [+ 'release', 'download',+ '--repo', 'carloslfu/slotstream',+ '--pattern', 'slotstream-arm64.tar.gz',+ '--dir', binDir,+ '--clobber',+ ], emit, { timeoutMs: INSTALL_TIMEOUT_MS });+ if (!download.success) throw new ServerError(`Slotstream install failed: ${download.error}`, { status: 500 });++ const archive = join(binDir, 'slotstream-arm64.tar.gz');+ emit('Extracting Slotstream…');+ const extract = await runStreamingCommand('tar', ['-xzf', archive, '-C', binDir], emit, { timeoutMs: 60_000 });+ if (!extract.success) throw new ServerError(`Slotstream extract failed: ${extract.error}`, { status: 500 });++ const binary = join(binDir, 'slotstream');+ await chmod(binary, 0o755).catch(() => {});+ if (!resolveSlotstreamBinary() && !findCommandOnPath(binary)) {+ throw new ServerError('Slotstream downloaded but the binary was not found in ~/.slotstream/bin.', { status: 500 });+ }+ return { success: true, message: 'Slotstream installed' };+}++/**+ * The checkpoint a start hands `--model`, always resolved against the on-disk+ * cache.+ *+ * An explicitly requested checkpoint is verified to be cached rather than+ * passed straight through: `slotstream serve` treats an uncached name as+ * something to fetch, so trusting the request would be the one path that+ * downloads weights on a start.+ */+async function resolveStartModel(requested, emit) {+ const cache = await listSlotstreamCachedModels();+ if (cache.models === null) {+ emit(`Could not read Slotstream's model cache (${cache.error}) — refusing to start rather than fetching weights.`);+ return { error: slotstreamNoModelError() };+ }+ if (cache.models.length === 0) return { error: slotstreamNoModelError() };+ const model = pickSlotstreamCachedModel(cache.models, requested);+ if (!model) return { error: slotstreamNoModelError() };+ if (!cache.models.some((row) => row?.id === model)) {+ return {+ error: `Slotstream has no cached checkpoint named "${model}". A start never downloads weights — pick one of the cached checkpoints (${cache.models.map((row) => row.id).join(', ')}) instead.`,+ };+ }+ return { model };+}++/**+ * Start `slotstream serve` under PM2.+ *+ * @param {{port?: number, model?: string, memoryGb?: number, waitMs?: number, onProgress?: (line: string) => void}} options+ */+export async function startSlotstreamServer(options = {}) {+ const { port: requestedPort, model: requestedModel = null, memoryGb = null, waitMs, onProgress = () => {} } = options;+ const port = resolveStartPort(requestedPort ?? DEFAULT_PORT);+ const emit = (line) => { appendLog(line); onProgress(line); };++ if (!isAppleSilicon()) {+ throw new ServerError(SLOTSTREAM_UNSUPPORTED_REASON, { status: 400, code: 'SLOTSTREAM_UNSUPPORTED_PLATFORM' });+ }++ const binaryPath = resolveSlotstreamBinary();+ if (!binaryPath) {+ throw new ServerError(+ 'The Slotstream binary was not found. Install it from this card, then try again.',+ { status: 400, code: 'SLOTSTREAM_NOT_INSTALLED' },+ );+ }++ const pm2Status = await getAppStatusStrict(SLOTSTREAM_APP);+ if (pm2Status && pm2Status.status === 'online') {+ throw new ServerError(`Slotstream is already running with PID ${pm2Status.pid}`, { status: 409 });+ }++ const endpoint = `http://${DEFAULT_HOST}:${port}/v1`;+ if (await probeEndpoint(endpoint)) {+ throw new ServerError(`Port ${port} is already in use by an active server at ${endpoint}`, { status: 409 });+ }+ if (await isPortInUse(port)) {+ throw new ServerError(+ `Port ${port} is already in use on ${DEFAULT_HOST}. Point Slotstream at a different port before starting it.`,+ { status: 409, code: 'SLOTSTREAM_PORT_IN_USE' },+ );+ }++ daemon.resetLogs();+ lastExitError = null;++ const resolved = await resolveStartModel(requestedModel, emit);+ if (resolved.error) throw new ServerError(resolved.error, { status: 400, code: 'SLOTSTREAM_NO_CACHED_MODEL' });+ const model = resolved.model;+ if (model) emit(`Serving the cached Slotstream checkpoint ${model}.`);++ const plan = planSlotstreamMemory({ overrideGb: memoryGb });+ const args = [+ 'serve',+ '--port', String(port),+ '--memory-gb', String(plan.targetGb),+ ...(model ? ['--model', model] : []),+ ];+ // `config.memoryGb` is the resolved target actually in effect — the same+ // number `parseConfigFromArgs` reads back off the PM2 launch line. The+ // user's *override* (null when PortOS sized it) is a separate fact, kept on+ // the saved launch below, because the launch line alone cannot tell an+ // auto-sized 85.8 GB from one the user typed.+ currentConfig = { port, model, memoryGb: plan.targetGb };+ appendLog(`Starting: slotstream ${args.join(' ')}`);++ await execPm2(['delete', SLOTSTREAM_APP]).catch(() => {});+ clearJlistCache();++ console.log(`🌊 Slotstream starting on ${DEFAULT_HOST}:${port}${model ? ` (model ${model})` : ''} (memory ${plan.targetGb} GB${plan.auto ? ', auto' : ''})`);+ const logsReset = await resetSlotstreamLogs();+ await execPm2([+ 'start', binaryPath,+ '--name', SLOTSTREAM_APP,+ '--interpreter', 'none',+ '--no-autorestart',+ '--output', slotstreamLogFiles.stdout,+ '--error', slotstreamLogFiles.stderr,+ '--',+ ...args,+ ]);+ clearJlistCache();++ const deadline = Date.now() + (Number.isFinite(waitMs) ? waitMs : startupWaitMs);+ let online = false;+ let currentProc = null;+ while (Date.now() < deadline) {+ await sleep(startupPollMs);+ clearJlistCache();+ currentProc = await getAppStatusStrict(SLOTSTREAM_APP);+ if (currentProc && ['errored', 'stopped', 'not_found'].includes(currentProc.status)) break;+ online = await probeEndpoint(endpoint);+ if (online) break;+ }++ if (currentProc && ['errored', 'stopped', 'not_found'].includes(currentProc.status)) {+ const pm2Logs = await execPm2(['logs', SLOTSTREAM_APP, '--nostream', '--lines', '15']).catch(() => null);+ // Only trust the tail when the startup logs were actually truncated —+ // otherwise this launch's diagnosis would be the PREVIOUS launch's output,+ // sending the user after an error they already fixed.+ const lines = logsReset+ ? `${pm2Logs?.stderr || pm2Logs?.stdout || ''}`.split('\n').map((l) => l.trimEnd()).filter(Boolean)+ : [];+ for (const line of lines) appendLog(line);+ const tail = (lines.length ? lines : daemon.snapshotLogs()).slice(-4).join(' | ');+ lastExitError = `PM2 status: ${currentProc.status}`;+ await execPm2(['delete', SLOTSTREAM_APP]).catch(() => {});+ clearJlistCache();+ currentConfig = null;+ throw new ServerError(+ `Slotstream exited immediately (${lastExitError}).${tail ? ` Last output: ${tail}` : ''}`,+ { status: 500, code: 'SLOTSTREAM_EXITED' },+ );+ }++ await persistLaunchConfig({ port, model, memoryGb: plan.auto ? null : plan.targetGb });++ const finalProc = await getAppStatusStrict(SLOTSTREAM_APP);+ return {+ success: true,+ running: true,+ managed: true,+ pid: finalProc?.pid || null,+ endpoint,+ online,+ config: currentConfig,+ memoryPlan: plan,+ };+}++/** Stop the managed Slotstream process. */+export async function stopSlotstreamServer() {+ const pm2Status = await getAppStatusStrict(SLOTSTREAM_APP);+ const isManaged = Boolean(pm2Status && pm2Status.status === 'online');++ if (!isManaged) {+ const endpoint = endpointFor(currentConfig);+ if (await probeEndpoint(endpoint)) {+ return {+ success: false,+ message: `An external process is listening on ${endpoint}. It was not started by PortOS and cannot be stopped here.`,+ };+ }+ return { success: true, message: 'Slotstream is not running' };+ }++ appendLog(`Stopping ${SLOTSTREAM_APP}`);+ await execPm2(['delete', SLOTSTREAM_APP]).catch((err) => {+ throw new ServerError(`Failed to stop Slotstream: ${err.message}`, { status: 500 });+ });+ clearJlistCache();+ currentConfig = null;+ return { success: true, message: 'Slotstream stopped' };+}++export function _resetSlotstreamServerStateForTests({+ startupWait,+ startupPoll,+ relaunchReadyTimeout,+ relaunchPoll,+ idleMinutes = 0,+ logFiles,+} = {}) {+ idleMinutesOverride = idleMinutes;+ slotstreamLogFiles = logFiles ? {+ stdout: logFiles.stdout || DEFAULT_SLOTSTREAM_LOG_FILES.stdout,+ stderr: logFiles.stderr || DEFAULT_SLOTSTREAM_LOG_FILES.stderr,+ } : DEFAULT_SLOTSTREAM_LOG_FILES;+ currentConfig = null;+ daemon.resetLogs();+ lastExitError = null;+ startupWaitMs = Number.isFinite(startupWait) ? startupWait : 8_000;+ startupPollMs = Number.isFinite(startupPoll) ? startupPoll : 1500;+ relaunchReadyTimeoutMs = Number.isFinite(relaunchReadyTimeout) ? relaunchReadyTimeout : 300_000;+ relaunchPollMs = Number.isFinite(relaunchPoll) ? relaunchPoll : 1000;+}++const readSettings = () => import('./settings.js').then((m) => m.getSettings()).catch(() => null);+let idleMinutesOverride = null;++async function configuredIdleMinutes() {+ if (idleMinutesOverride !== null) return idleMinutesOverride;+ const settings = await readSettings();+ const raw = Number(settings?.localLlm?.slotstream?.idleMinutes);+ return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 0;+}++registerIdleDaemon({+ name: SLOTSTREAM_APP,+ getIdleMs: async () => idleWindowMs(await configuredIdleMinutes()),+ stop: () => stopSlotstreamServer(),+});++async function savedLaunchConfig() {+ const settings = await readSettings();+ const launch = settings?.localLlm?.slotstream?.launch;+ return {+ model: typeof launch?.model === 'string' && launch.model.trim() ? launch.model.trim() : null,+ port: Number.isFinite(Number(launch?.port)) ? Number(launch.port) : null,+ memoryGb: Number.isFinite(Number(launch?.memoryGb)) ? Number(launch.memoryGb) : null,+ };+}++/**+ * Record the launch a start actually used, so the on-demand restart after an+ * idle release replays it.+ *+ * Without this an explicit memory cap lives only in `currentConfig`, which+ * `stopSlotstreamServer` clears — so the reaper would silently trade the cap+ * the user chose for an auto-sized target on the next request. `memoryGb` stays+ * the user's *override* (null when PortOS sized it), never the resolved target,+ * so a later status still knows which of the two it is looking at.+ */+async function persistLaunchConfig({ port, model, memoryGb }) {+ const settings = await import('./settings.js').catch(() => null);+ if (!settings?.updateSettingsWith) return;+ await settings.updateSettingsWith((current) => ({+ ...current,+ localLlm: {+ ...current?.localLlm,+ slotstream: {+ ...current?.localLlm?.slotstream,+ launch: { port, model, memoryGb },+ },+ },+ })).catch((error) => {+ console.error(`❌ Slotstream: could not persist the launch line (${error?.message || 'unknown'}); an idle restart will re-size from host RAM`);+ });+}++export const markSlotstreamUsed = () => markDaemonUsed(SLOTSTREAM_APP);++/**+ * Bring Slotstream up if the idle reaper (or the user) stopped it.+ *+ * @returns {Promise<{ready: boolean, reason: string|null}>}+ */+export async function ensureSlotstreamRunning() {+ markSlotstreamUsed();++ const pm2Status = await getAppStatusStrict(SLOTSTREAM_APP);+ if (pm2Status?.status === 'online') return { ready: true, reason: null };++ const saved = await savedLaunchConfig();+ const config = {+ port: currentConfig?.port ?? saved.port ?? DEFAULT_PORT,+ model: currentConfig?.model ?? saved.model ?? null,+ memoryGb: currentConfig?.memoryGb ?? saved.memoryGb ?? null,+ };++ const endpoint = endpointFor(config);+ if (await probeEndpoint(endpoint)) return { ready: true, reason: null };++ console.log(`🌊 Slotstream is stopped — starting it for an incoming request`);+ const started = await startSlotstreamServer(config).catch((err) => ({ error: err }));+ if (started.error) return { ready: false, reason: started.error.message };+ if (started.online) return { ready: true, reason: null };++ const deadline = Date.now() + relaunchReadyTimeoutMs;+ while (Date.now() < deadline) {+ if (await probeEndpoint(started.endpoint ?? endpoint)) return { ready: true, reason: null };+ clearJlistCache();+ const proc = await getAppStatusStrict(SLOTSTREAM_APP);+ if (proc && ['errored', 'stopped', 'not_found'].includes(proc.status)) {+ return { ready: false, reason: `Slotstream exited while loading (PM2 status: ${proc.status})` };+ }+ await sleep(relaunchPollMs);+ }+ return { ready: false, reason: 'Slotstream relaunched but never answered on its port' };+}++export function isSlotstreamProvider(provider) {+ if (!provider || !['api', 'tui'].includes(provider.type)) return false;+ if (!isLocalInstanceEndpoint(provider.endpoint)) return false;+ if (localRuntimeKind(provider) === 'slotstream') return true;+ const managedPort = currentConfig?.port;+ return Boolean(managedPort) && Number(localEndpointPort(provider.endpoint)) === managedPort;+}++export async function ensureSlotstreamProviderReady(provider) {+ if (!isSlotstreamProvider(provider)) return { success: true };+ const { ready, reason } = await ensureSlotstreamRunning();+ return ready ? { success: true } : { success: false, error: reason };+}diff --git a/server/services/slotstreamServerManager.test.js b/server/services/slotstreamServerManager.test.jsnew file mode 100644index 0000000000..32906cbfd1--- /dev/null+++ b/server/services/slotstreamServerManager.test.js@@ -0,0 +1,312 @@+import { mkdtemp, rm } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++// The manager reaches settings through a dynamic `import('./settings.js')` for+// both the saved launch line and the idle window. Backing it with an in-memory+// store keeps the launch-line round-trip (start → persist → status) assertable+// without the suite reading or writing an install's real settings file.+const settingsStore = vi.hoisted(() => ({ current: {} }));+vi.mock('./settings.js', () => ({+ getSettings: async () => settingsStore.current,+ updateSettingsWith: async (mutate) => {+ settingsStore.current = await mutate(settingsStore.current);+ return settingsStore.current;+ },+}));++import {+ getSlotstreamServerStatus,+ startSlotstreamServer,+ stopSlotstreamServer,+ installSlotstream,+ _resetSlotstreamServerStateForTests,+ ensureSlotstreamRunning,+ isSlotstreamProvider,+ SLOTSTREAM_APP,+} from './slotstreamServerManager.js';+import * as processEnv from '../lib/processEnv.js';+import * as platform from '../lib/platform.js';+import * as openAiModelsProbe from '../lib/openAiModelsProbe.js';+import * as slotstreamModels from '../lib/slotstreamModels.js';+import * as pm2Module from './pm2.js';+import * as commandExistsModule from '../lib/commandExists.js';+import * as streamingSpawn from '../lib/streamingSpawn.js';+import { PORTS } from '../lib/ports.js';++const BINARY = '/opt/homebrew/bin/slotstream';+const cachedModel = (id) => ({ id, path: `/tmp/${id}` });+const FAST_TIMING = {+ startupWait: 50,+ startupPoll: 0,+ relaunchReadyTimeout: 30,+ relaunchPoll: 0,+};+const resetForTest = (overrides = {}) => {+ _resetSlotstreamServerStateForTests({ ...FAST_TIMING, ...overrides });+};++describe('slotstreamServerManager', () => {+ let pm2State = null;+ let execPm2Calls = [];+ let testLogDir = null;++ beforeEach(async () => {+ testLogDir = await mkdtemp(join(tmpdir(), 'portos-slotstream-test-'));+ resetForTest({+ logFiles: {+ stdout: join(testLogDir, 'portos-slotstream-out.log'),+ stderr: join(testLogDir, 'portos-slotstream-error.log'),+ },+ });+ vi.restoreAllMocks();+ pm2State = null;+ execPm2Calls = [];+ settingsStore.current = {};++ vi.spyOn(platform, 'isPortInUse').mockResolvedValue(false);+ vi.spyOn(openAiModelsProbe, 'probeOpenAiModels')+ .mockImplementation(async () => ({ reachable: pm2State?.status === 'online' }));+ vi.spyOn(platform, 'isAppleSilicon').mockReturnValue(true);+ vi.spyOn(pm2Module, 'getSavedProcessNames').mockResolvedValue([]);+ vi.spyOn(slotstreamModels, 'listSlotstreamCachedModels').mockResolvedValue({+ models: [cachedModel('qwen-moe')],+ error: null,+ });++ vi.spyOn(pm2Module, 'execPm2').mockImplementation(async (args) => {+ execPm2Calls.push(args);+ if (args[0] === 'start') {+ const nameIdx = args.indexOf('--name');+ const dashIdx = args.indexOf('--');+ pm2State = {+ name: nameIdx !== -1 ? args[nameIdx + 1] : args[1],+ status: 'online',+ pid: 4242,+ args: dashIdx !== -1 ? args.slice(dashIdx + 1) : [],+ };+ }+ if (args[0] === 'delete') pm2State = null;+ return { stdout: '', stderr: '' };+ });+ vi.spyOn(pm2Module, 'getAppStatusStrict').mockImplementation(async (name) => (+ pm2State && pm2State.name === name ? pm2State : { name, status: 'not_found', pm2_env: null }+ ));+ vi.spyOn(pm2Module, 'clearJlistCache').mockImplementation(() => {});+ });++ afterEach(async () => {+ _resetSlotstreamServerStateForTests();+ vi.restoreAllMocks();+ await rm(testLogDir, { recursive: true, force: true });+ testLogDir = null;+ });++ describe('getSlotstreamServerStatus', () => {+ it('reports not installed when the binary is not on PATH', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(null);+ const status = await getSlotstreamServerStatus();+ expect(status.installed).toBe(false);+ expect(status.running).toBe(false);+ expect(status.cacheError).toBeNull();+ expect(status.memoryPlan).toEqual(expect.objectContaining({+ targetGb: expect.any(Number),+ expectedPeakGb: expect.any(Number),+ expectedWarmDecodeToks: expect.any(Number),+ }));+ });++ it('surfaces the cached checkpoints an installed Slotstream can be started on', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ const status = await getSlotstreamServerStatus();+ expect(status.installed).toBe(true);+ expect(status.cachedModels).toEqual(['qwen-moe']);+ expect(status.endpoint).toBe(`http://127.0.0.1:${PORTS.SLOTSTREAM}/v1`);+ });++ it('reports the platform gate only when nothing is installed here', async () => {+ vi.spyOn(platform, 'isAppleSilicon').mockReturnValue(false);+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(null);+ expect((await getSlotstreamServerStatus()).supported).toBe(false);++ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ const installed = await getSlotstreamServerStatus();+ expect(installed.supported).toBe(true);+ expect(installed.unsupportedReason).toBeNull();+ });++ it('flags the process as boot-persisted only when the PM2 dump names it', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ expect((await getSlotstreamServerStatus()).runAtStartup).toBe(false);+ vi.spyOn(pm2Module, 'getSavedProcessNames').mockResolvedValue([SLOTSTREAM_APP]);+ expect((await getSlotstreamServerStatus()).runAtStartup).toBe(true);+ });+ });++ describe('startSlotstreamServer', () => {+ beforeEach(() => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ });++ it('starts `slotstream serve` under PM2 on a cached checkpoint with an explicit port', async () => {+ const result = await startSlotstreamServer();+ expect(result.success).toBe(true);+ expect(result.managed).toBe(true);+ expect(result.endpoint).toBe(`http://127.0.0.1:${PORTS.SLOTSTREAM}/v1`);++ const start = execPm2Calls.find((args) => args[0] === 'start');+ expect(start[start.indexOf('--name') + 1]).toBe(SLOTSTREAM_APP);+ const launch = start.slice(start.indexOf('--') + 1);+ expect(launch[0]).toBe('serve');+ expect(launch[launch.indexOf('--port') + 1]).toBe(String(PORTS.SLOTSTREAM));+ expect(launch).toContain('--memory-gb');+ expect(launch).toContain('--model');+ expect(launch[launch.indexOf('--model') + 1]).toBe('qwen-moe');+ });++ it('persists an explicit memory-cap override on the launch line', async () => {+ const result = await startSlotstreamServer({ memoryGb: 22 });+ const launch = execPm2Calls.find((a) => a[0] === 'start');+ expect(launch[launch.indexOf('--memory-gb') + 1]).toBe('22');+ expect(result.config.memoryGb).toBe(22);+ expect(result.memoryPlan.auto).toBe(false);+ });++ it('saves the cap an explicit start used, so the on-demand restart replays it', async () => {+ // Started from the card WITHOUT pressing "Save configuration": before the+ // launch line was persisted here, the idle reaper's restart re-sized from+ // host RAM and silently discarded the cap the user chose.+ await startSlotstreamServer({ memoryGb: 22 });+ expect(settingsStore.current.localLlm.slotstream.launch.memoryGb).toBe(22);++ await stopSlotstreamServer();+ execPm2Calls = [];+ await ensureSlotstreamRunning();+ const relaunch = execPm2Calls.find((a) => a[0] === 'start');+ expect(relaunch[relaunch.indexOf('--memory-gb') + 1]).toBe('22');+ });++ it('records an auto-sized start as auto, not as a cap the user chose', async () => {+ // `--memory-gb` is on the launch line either way, so the saved override is+ // the only thing that can tell them apart — reading the arg back would+ // report every auto start as an explicit cap.+ await startSlotstreamServer();+ expect(settingsStore.current.localLlm.slotstream.launch.memoryGb).toBeNull();+ expect((await getSlotstreamServerStatus()).memoryPlan.auto).toBe(true);+ });++ it('refuses Ollama\'s default port instead of colliding with a managed Ollama', async () => {+ const err = await startSlotstreamServer({ port: 11434 }).catch((e) => e);+ expect(err.message).toMatch(/11434/);+ expect(err.message).toMatch(/Ollama/);+ expect(execPm2Calls.some((args) => args[0] === 'start')).toBe(false);+ });++ it('refuses with an in-app fix when the cache was read and is empty', async () => {+ vi.spyOn(slotstreamModels, 'listSlotstreamCachedModels').mockResolvedValue({ models: [], error: null });+ const err = await startSlotstreamServer().catch((e) => e);+ expect(err.message).toMatch(/never downloads weights|no model weights cached/i);+ expect(err.message).not.toMatch(/terminal/);+ expect(execPm2Calls.some((args) => args[0] === 'start')).toBe(false);+ });++ it('refuses an explicit checkpoint that is not cached, rather than letting the runtime fetch it', async () => {+ const err = await startSlotstreamServer({ model: 'not-on-disk' }).catch((e) => e);+ expect(err.message).toMatch(/never downloads weights/i);+ expect(err.message).toMatch(/qwen-moe/);+ expect(execPm2Calls.some((args) => args[0] === 'start')).toBe(false);+ });++ it('refuses to start on a host the runtime does not support', async () => {+ vi.spyOn(platform, 'isAppleSilicon').mockReturnValue(false);+ await expect(startSlotstreamServer()).rejects.toThrow(/Apple Silicon/);+ expect(execPm2Calls.some((args) => args[0] === 'start')).toBe(false);+ });++ it('refuses rather than launching onto a bound port', async () => {+ vi.spyOn(platform, 'isPortInUse').mockResolvedValue(true);+ await expect(startSlotstreamServer()).rejects.toThrow(/already in use/);+ });++ it('refuses when the binary is not installed', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(null);+ await expect(startSlotstreamServer()).rejects.toThrow(/not found/);+ });+ });++ describe('installSlotstream', () => {+ beforeEach(() => {+ vi.spyOn(streamingSpawn, 'runStreamingCommand').mockResolvedValue({ success: true });+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ vi.spyOn(slotstreamModels, 'slotstreamBinDir').mockReturnValue(testLogDir);+ });++ it('installs the Apple Silicon release via GitHub CLI, never a remote shell script', async () => {+ vi.spyOn(commandExistsModule, 'commandExists').mockResolvedValue(true);+ const result = await installSlotstream();+ expect(result.success).toBe(true);+ const [cmd, args] = streamingSpawn.runStreamingCommand.mock.calls[0];+ expect(cmd).toBe('gh');+ expect(args).toEqual(expect.arrayContaining(['release', 'download', '--repo', 'carloslfu/slotstream']));+ expect(streamingSpawn.runStreamingCommand.mock.calls.flat().join(' ')).not.toMatch(/install\.sh/);+ });++ it('refuses on a host that cannot run it', async () => {+ vi.spyOn(platform, 'isAppleSilicon').mockReturnValue(false);+ await expect(installSlotstream()).rejects.toThrow(/macOS with Apple Silicon/);+ expect(streamingSpawn.runStreamingCommand).not.toHaveBeenCalled();+ });+ });++ describe('stopSlotstreamServer', () => {+ it('deletes the PM2 process it manages', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ await startSlotstreamServer();+ const result = await stopSlotstreamServer();+ expect(result.success).toBe(true);+ expect(pm2State).toBeNull();+ });++ it('will not claim to stop a server PortOS did not start', async () => {+ vi.spyOn(openAiModelsProbe, 'probeOpenAiModels').mockResolvedValue({ reachable: true });+ const result = await stopSlotstreamServer();+ expect(result.success).toBe(false);+ expect(result.message).toMatch(/external process/i);+ });+ });++ describe('ensureSlotstreamRunning', () => {+ it('is a no-op when the daemon is already online', async () => {+ pm2State = { name: SLOTSTREAM_APP, status: 'online', pid: 777, args: ['serve', '--port', String(PORTS.SLOTSTREAM)] };+ const result = await ensureSlotstreamRunning();+ expect(result).toEqual({ ready: true, reason: null });+ expect(execPm2Calls.filter((c) => c[0] === 'start')).toHaveLength(0);+ });++ it('reports the reason rather than throwing when the start fails', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(null);+ const result = await ensureSlotstreamRunning();+ expect(result.ready).toBe(false);+ expect(result.reason).toMatch(/not found/);+ });+ });++ describe('isSlotstreamProvider', () => {+ it('matches a local Slotstream endpoint on the dedicated port', () => {+ expect(isSlotstreamProvider({+ type: 'api',+ endpoint: `http://127.0.0.1:${PORTS.SLOTSTREAM}/v1`,+ id: 'slotstream',+ })).toBe(true);+ });++ it('does not match a Slotstream on another machine', () => {+ expect(isSlotstreamProvider({+ type: 'api',+ endpoint: `http://192.0.2.10:${PORTS.SLOTSTREAM}/v1`,+ id: 'slotstream',+ })).toBe(false);+ });+ });+});