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
feat: download Slotstream checkpoints from Models → LLMs (#6162)
Adam Eivy5ed5e843c4da
diff --git a/client/src/components/settings/LocalLlmRuntimesView.jsx b/client/src/components/settings/LocalLlmRuntimesView.jsxindex 9bc11d45ab..f0e2a8d0b7 100644--- a/client/src/components/settings/LocalLlmRuntimesView.jsx+++ b/client/src/components/settings/LocalLlmRuntimesView.jsx@@ -7,7 +7,7 @@ import BrailleSpinner from '../BrailleSpinner';import { formatBytes } from '../../utils/formatters';import useDownloadPreflightConfirm from '../../hooks/useDownloadPreflightConfirm';import useLocalLlmStatus from '../../hooks/useLocalLlmStatus';-import { migrateLocalLlmBackend, controlOllamaService, patchSettingsSlice, getLlamaServerStatus, getLlamaServerUpdateStatus, startLlamaServer, stopLlamaServer, installLlamaServer, upgradeLlamaServer, downloadSpecDecodeModel, cancelSpecDecodeModelDownload, previewLocalLlmDownload, controlLmStudioService, getMtplxServerStatus, startMtplxServer, stopMtplxServer, installMtplx, searchMtplxModels, pullMtplxModel, removeMtplxModel, getSlotstreamServerStatus, startSlotstreamServer, stopSlotstreamServer, installSlotstream, saveRuntimeStartupList } from '../../services/api';+import { migrateLocalLlmBackend, controlOllamaService, patchSettingsSlice, getLlamaServerStatus, getLlamaServerUpdateStatus, startLlamaServer, stopLlamaServer, installLlamaServer, upgradeLlamaServer, downloadSpecDecodeModel, cancelSpecDecodeModelDownload, previewLocalLlmDownload, controlLmStudioService, getMtplxServerStatus, startMtplxServer, stopMtplxServer, installMtplx, searchMtplxModels, pullMtplxModel, removeMtplxModel, getSlotstreamServerStatus, startSlotstreamServer, stopSlotstreamServer, installSlotstream, downloadSlotstreamModel, saveRuntimeStartupList } from '../../services/api';import socket from '../../services/socket';import SpecDecodeWeightRow from './SpecDecodeWeightRow.jsx';import RuntimeServersCard from './RuntimeServersCard.jsx';@@ -73,6 +73,7 @@ export default function LocalLlmRuntimesView() {// at a time on purpose: a checkpoint is tens of gigabytes, so two concurrent// pulls just make both slower.const [mtplxDownload, setMtplxDownload] = useState(null);+ const [slotstreamDownload, setSlotstreamDownload] = useState(null);const { confirm: downloadConfirm, request: requestWeightDownload, cancel: cancelDownloadConfirm, confirmRun: runDownloadConfirm } = useDownloadPreflightConfirm();const [llamaLoading, setLlamaLoading] = useState(false);// Anchor for the unified server card's "Configure" action — llama-server needs@@ -237,6 +238,31 @@ export default function LocalLlmRuntimesView() {return () => socket.off('mtplx:download', handleMtplxDownload);}, [loadMtplxStatus]);+ // Slotstream checkpoint download progress. Same contract as MTPLX above: a+ // 100 GB+ pull outlives the request that started it, so the socket's terminal+ // frame is what clears the bar and re-reads the cache — the list is then right+ // even if the request itself never comes back.+ useEffect(() => {+ const handleSlotstreamDownload = (frame) => {+ if (!frame) return;+ if (frame.event === 'complete' || frame.event === 'error' || frame.event === 'cancelled') {+ setSlotstreamDownload(null);+ loadSlotstreamStatus();+ return;+ }+ setSlotstreamDownload((prev) => ({+ model: frame.model || prev?.model || null,+ // A frame without byte counters (the resolving pass) must not reset a+ // bar that already has them — keep the last known numbers.+ received: Number.isFinite(frame.received) ? frame.received : (prev?.received ?? 0),+ total: Number.isFinite(frame.total) ? frame.total : (prev?.total ?? 0),+ message: frame.message || prev?.message || null,+ }));+ };+ socket.on('slotstream:download', handleSlotstreamDownload);+ return () => socket.off('slotstream:download', handleSlotstreamDownload);+ }, [loadSlotstreamStatus]);+// === Unified runtime-server controls ======================================// Every handler routes through `runAction` so one busy/spinner/refresh path// covers all four runtimes. The `runtime-<verb>-<id>` keys are what@@ -311,6 +337,25 @@ export default function LocalLlmRuntimesView() {() => patchSettingsSlice('localLlm.slotstream', { launch }),'Saved — Slotstream will start on these options when a request needs it').then(loadSlotstreamStatus);+ // The bar is driven by `slotstream:download` (subscribed above), so the button+ // spinner is not the progress indicator — it only covers the request itself.+ const startSlotstreamDownload = (model) => runAction(+ 'slotstream-download',+ () => downloadSlotstreamModel(model).then((r) => {+ if (r?.success === false) throw new Error(r.error || 'Download failed');+ return r;+ }),+ (r) => `${r?.repo || 'Checkpoint'} downloaded`,+ { onError: (err) => toast.error(`Slotstream download failed: ${err.message}`) },+ ).then(() => {+ setSlotstreamDownload(null);+ return loadSlotstreamStatus();+ });+ const slotstreamDownloadModel = (model) => requestWeightDownload({+ title: 'Download Slotstream checkpoint',+ preview: () => previewLocalLlmDownload({ kind: 'slotstream', model }, { silent: true }),+ run: () => startSlotstreamDownload(model),+ });const runtimeStopSlotstream = () => runAction('runtime-stop-slotstream',() => stopSlotstreamServer(),@@ -685,6 +730,8 @@ export default function LocalLlmRuntimesView() {onStart={runtimeStartSlotstream}onStop={runtimeStopSlotstream}onInstall={runtimeInstallSlotstream}+ onDownloadModel={slotstreamDownloadModel}+ download={slotstreamDownload}/></div>diff --git a/client/src/components/settings/SlotstreamServerCard.jsx b/client/src/components/settings/SlotstreamServerCard.jsxindex 63e1d9b83e..5ab3e1bf06 100644--- a/client/src/components/settings/SlotstreamServerCard.jsx+++ b/client/src/components/settings/SlotstreamServerCard.jsx@@ -1,19 +1,43 @@import { useEffect, useState } from 'react';import { HardDrive, RefreshCw, Save, Square, Download, Terminal } from 'lucide-react';import BrailleSpinner from '../BrailleSpinner';+import ProgressBar from '../ui/ProgressBar';+import { formatBytes } from '../../utils/formatters';/*** 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.+ * Weights are a later, explicit user action. A start never fetches them — but+ * the download IS in the app, from the picker below, because the alternative+ * was telling the user to hand-assemble a 100 GB+ checkpoint directory in the+ * middle of a lifecycle PortOS manages end to end. 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';+/**+ * A download reports byte counters as soon as the first shard moves; the+ * resolving pass before that has none, which is the shared bar's indeterminate+ * case rather than a misleading 0%.+ */+function DownloadProgress({ download }) {+ const { received = 0, total = 0, message } = download;+ const pct = total > 0 ? (received / total) * 100 : null;+ return (+ <div className="space-y-1">+ <ProgressBar percent={pct} track="border" label={`Downloading ${download.model || 'checkpoint'}`} />+ <p className="text-[11px] text-gray-500">+ {pct === null+ ? (message || 'Downloading…')+ : `${formatBytes(received)} of ${formatBytes(total)} (${Math.round(pct)}%)`}+ </p>+ </div>+ );+}+export default function SlotstreamServerCard({status,loading,@@ -24,8 +48,11 @@ export default function SlotstreamServerCard({onStart,onStop,onInstall,+ onDownloadModel,+ download,}) {const [model, setModel] = useState('');+ const [downloadModel, setDownloadModel] = useState('');const [port, setPort] = useState('');const [memoryGb, setMemoryGb] = useState('');const [seeded, setSeeded] = useState(false);@@ -49,6 +76,9 @@ export default function SlotstreamServerCard({const emptyCache = Boolean(status?.installed) && cached.length === 0 && !status?.cacheError;const external = status?.running && status?.managed === false;const plan = status?.memoryPlan;+ const catalog = status?.catalog || [];+ const downloading = Boolean(download);+ const selectedEntry = catalog.find((entry) => entry.id === downloadModel) || null;const launchPayload = () => ({model: model || null,@@ -128,7 +158,7 @@ export default function SlotstreamServerCard({<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.+ No checkpoint is cached, so a start would exit before it binds a port. A start never downloads weights — pick one below and download it, or place a checkpoint directory in <code className="text-gray-300">{status.cacheDir || '~/.slotstream/models'}</code> yourself.</p>) : (<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">@@ -171,6 +201,44 @@ export default function SlotstreamServerCard({</div></div>)}+ {catalog.length > 0 && onDownloadModel && (+ <div className="border-t border-port-border pt-3 space-y-2">+ <div className="grid grid-cols-1 sm:grid-cols-[1fr_auto] gap-2 sm:items-end">+ <div className="space-y-1">+ <label htmlFor="slotstream-download" className="block text-xs text-gray-400">Add a checkpoint</label>+ <select+ id="slotstream-download"+ value={downloadModel}+ onChange={(e) => setDownloadModel(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="">Choose a mixture-of-experts checkpoint…</option>+ {catalog.map((entry) => (+ <option key={entry.id} value={entry.id}>+ {entry.label} — {entry.params}, ~{formatBytes(entry.approxBytes)}+ </option>+ ))}+ </select>+ </div>+ <button+ onClick={() => onDownloadModel(downloadModel)}+ disabled={busy || downloading || !downloadModel}+ className={`${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent shrink-0`}+ title="Check the size and free disk, then download this checkpoint"+ >+ {actionInProgress === 'slotstream-download' ? <BrailleSpinner /> : <Download size={13} />}+ Download checkpoint+ </button>+ </div>+ {selectedEntry && (+ <p className="text-[11px] text-gray-500">{selectedEntry.note}</p>+ )}+ <p className="text-[11px] text-gray-500">+ Streaming only pays off on a mixture-of-experts checkpoint, where a few experts per token are read from SSD — so this is a curated list, not a Hugging Face search. PortOS shows the size and free disk before the transfer starts.+ </p>+ {download && <DownloadProgress download={download} />}+ </div>+ )}{status?.cacheError && (<p className="text-xs text-gray-500">Couldn't read Slotstream's model cache ({status.cacheError}).</p>)}diff --git a/client/src/components/settings/SlotstreamServerCard.test.jsx b/client/src/components/settings/SlotstreamServerCard.test.jsxindex ba53c5ec05..98309a2e88 100644--- a/client/src/components/settings/SlotstreamServerCard.test.jsx+++ b/client/src/components/settings/SlotstreamServerCard.test.jsx@@ -2,6 +2,11 @@ import { describe, it, expect, vi } from 'vitest';import { fireEvent, render, screen } from '@testing-library/react';import SlotstreamServerCard from './SlotstreamServerCard.jsx';+const CATALOG = [+ { id: 'small-moe', repo: 'someone/small-moe', label: 'Small MoE', params: '30B total / 3B active', approxBytes: 17 * 1024 ** 3, note: 'Small enough to verify the whole install end to end.' },+ { id: 'big-moe', repo: 'someone/big-moe', label: 'Big MoE', params: '235B total / 22B active', approxBytes: 132 * 1024 ** 3, note: 'The headline case.' },+];+const renderCard = (status, props = {}) => {const handlers = {onRefresh: vi.fn(),@@ -9,6 +14,7 @@ const renderCard = (status, props = {}) => {onStart: vi.fn(),onStop: vi.fn(),onInstall: vi.fn(),+ onDownloadModel: vi.fn(),};render(<SlotstreamServerCard status={status} loading={false} busy={false} actionInProgress={null} {...handlers} {...props} />,@@ -72,6 +78,48 @@ describe('SlotstreamServerCard', () => {expect(screen.queryByRole('button', { name: /Start Slotstream/ })).toBeNull();});+ it('offers a checkpoint to download when the cache is empty, instead of only a hand-placed directory', () => {+ // The empty cache used to be a dead end: the only way forward was to+ // assemble a 100 GB+ directory by hand outside the app.+ const handlers = renderCard({+ installed: true,+ running: false,+ supported: true,+ cachedModels: [],+ cacheDir: '/tmp/example-slotstream/models',+ catalog: CATALOG,+ });+ const picker = screen.getByLabelText('Add a checkpoint');+ expect(picker).toBeInTheDocument();++ const download = screen.getByRole('button', { name: /Download checkpoint/ });+ // Nothing chosen yet — a transfer this size never starts on an empty pick.+ expect(download).toBeDisabled();++ fireEvent.change(picker, { target: { value: 'small-moe' } });+ expect(screen.getByText(/verify the whole install/i)).toBeInTheDocument();+ fireEvent.click(download);+ expect(handlers.onDownloadModel).toHaveBeenCalledWith('small-moe');+ });++ it('renders download progress and blocks a second press while one is running', () => {+ renderCard(+ { installed: true, running: false, supported: true, cachedModels: [], catalog: CATALOG },+ { download: { model: 'someone/small-moe', received: 5 * 1024 ** 3, total: 20 * 1024 ** 3 } },+ );+ fireEvent.change(screen.getByLabelText('Add a checkpoint'), { target: { value: 'small-moe' } });+ expect(screen.getByRole('button', { name: /Download checkpoint/ })).toBeDisabled();+ expect(screen.getByText('5 GB of 20 GB (25%)')).toBeInTheDocument();+ });++ it('leaves the picker out when the runtime has no catalog to offer', () => {+ // An older status payload (a tab left open across an upgrade) carries no+ // catalog at all; the card must still render its launch controls.+ renderCard({ installed: true, running: false, supported: true, cachedModels: ['qwen-moe'] });+ expect(screen.queryByLabelText('Add a checkpoint')).toBeNull();+ expect(screen.getByLabelText('Checkpoint')).toBeInTheDocument();+ });+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();diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 41494b1cca..14ac4b199f 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, Slotstream) 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 their checkpoint catalogs — `searchMtplxModels` / `pullMtplxModel` / `removeMtplxModel` and `downloadSlotstreamModel`, 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 c30eb7fce5..d1b19e8795 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -103,6 +103,13 @@ export const stopSlotstreamServer = () =>export const installSlotstream = () =>request('/local-llm/slotstream/install', { method: 'POST' });+// Fetch one checkpoint into Slotstream's cache. `model` is a catalog id from+// the status payload, or a Hugging Face `owner/name`. Byte progress arrives on+// the `slotstream:download` socket event, not in this response — the transfer+// outlives the request.+export const downloadSlotstreamModel = (model) =>+ request('/local-llm/slotstream/models/download', { method: 'POST', body: JSON.stringify({ model }) });+// 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 0a304b8ac8..cb12bd3037 100644--- a/docs/API.md+++ b/docs/API.md@@ -651,7 +651,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, 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/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` (which also carries the curated checkpoint catalog), `POST .../start` (never downloads weights), `POST .../stop`, `POST .../install`, and `POST /api/local-llm/slotstream/models/download` — the separate, explicit action that fetches a checkpoint, with byte progress on the `slotstream:download` socket event. || `/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/server/lib/README.md b/server/lib/README.mdindex 58d27d2276..60caef6738 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -184,6 +184,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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. |+| `slotstreamCatalog.js` | `SLOTSTREAM_CATALOG` — the curated mixture-of-experts checkpoints worth streaming from SSD (the technique only pays off on MoE: a dense model of the same size would stream every layer for every token). `resolveSlotstreamRepo(idOrRepo)` maps a catalog id or an `owner/name` repo id to a repo (null for anything else), `slotstreamModelDirName(repo)` flattens it to the single-segment cache directory whose NAME is the id a start hands `--model`, and `selectSlotstreamRepoFiles(siblings)` picks the `.safetensors`/config/tokenizer files a checkpoint is made of while dropping mirrored `original/`, GGUF, ONNX, and PyTorch copies of the same weights (which can double a 100 GB+ pull) and any name that is not a plain relative path. || `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. || `recordedProjectDir.js` | Where PortOS remembers a container project it had to go and FIND — one `.env` line per stack in the INSTALL's root (`PATHS.installRoot`, so a worktree-booted server writes where the real install reads). `readRecordedProjectDir(envVar, envPath?)` / `recordProjectDir(envVar, dir, envPath?)` / `projectDirIsSettled(envVar, env?, envPath?)` / `resolveRecordedProjectDir(envVar, defaultDir, env?, envPath?)` are all keyed on the env-var NAME, so the vLLM and SGLang Qwen3.8-27B stacks share one implementation instead of drifting on the precedence rule — exported value (this run's decision) → the record (an earlier run's) → the stack's documented default. Read from the file on every call, never cached: a placement run writes it and the readiness poll in the same process must see it without a restart, and PortOS has no dotenv so `.env` reaches `process.env` for nobody. Writes are atomic and replace the key's line rather than appending (`upsertEnvLine`) — that file also holds the database password. `envPath` is a parameter so a test's sandbox answers instead of the developer's install. Written by `services/wslProjectPlacement.js`. || `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, as this stack's keyed view of `recordedProjectDir.js`: `readRecordedVllmProjectDir(envPath?)` / `recordVllmProjectDir(dir, envPath?)` / `vllmProjectDirIsSettled()`, resolving `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`. |diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 0150c5b07f..6285aa103f 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -9078,6 +9078,14 @@"server/routes/localLlm.js"]},+ {+ "method": "POST",+ "path": "/api/local-llm/slotstream/models/download",+ "mountPath": "/api/local-llm",+ "sources": [+ "server/routes/localLlm.js"+ ]+ },{"method": "POST","path": "/api/local-llm/slotstream/start",@@ -17513,8 +17521,8 @@],"stats": {"mounts": 147,- "operations": 2169,- "declarations": 2177,+ "operations": 2170,+ "declarations": 2178,"sourceFiles": 230}}diff --git a/server/lib/huggingfaceLora.js b/server/lib/huggingfaceLora.jsindex b82f5163c9..ba0ca6ff38 100644--- a/server/lib/huggingfaceLora.js+++ b/server/lib/huggingfaceLora.js@@ -119,15 +119,20 @@ export const buildHfResolveUrl = (repo, revision, file) =>// Fetch model metadata from the public HF API. Returns the parsed JSON with// `siblings` (file list), `tags`, and `cardData` (carries `base_model`).// fetchImpl is injectable for tests.-// The `blobs=true` expand isn't needed — siblings carry rfilename, and we-// size-rank via the resolve HEAD only if multiple LoRA files tie.-export const fetchHuggingfaceModel = async (repo, { token, revision, fetchImpl = fetch, signal } = {}) => {+// The LoRA picker doesn't need `blobs=true` — siblings carry rfilename, and it+// size-ranks via the resolve HEAD only if multiple LoRA files tie. Pass+// `blobs: true` when the caller needs per-file SIZES up front instead: a+// whole-repo download has to total them before it can preflight the disk, and+// one HEAD per file across a 30-shard checkpoint is 30 round trips for numbers+// this expand already carries.+export const fetchHuggingfaceModel = async (repo, { token, revision, fetchImpl = fetch, signal, blobs = false } = {}) => {if (!/^[^/\s]+\/[^/\s]+$/.test(String(repo))) {throw new ServerError(`Invalid HuggingFace repo id: ${repo}`, { status: 400, code: 'HF_BAD_URL' });}- const url = revision+ const path = revision? `${HF_API}/${repo}/revision/${encodeURIComponent(revision)}`: `${HF_API}/${repo}`;+ const url = blobs ? `${path}?blobs=true` : path;const res = await fetchImpl(url, { headers: { Accept: 'application/json', ...buildHfAuthHeaders(token) }, signal });if (!res.ok) {if (res.status === 404) {diff --git a/server/lib/index.js b/server/lib/index.jsindex c5327bbc11..2d1e4fbfe5 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -190,6 +190,7 @@ export * from './opencodeConfig.js';export * from './localProviderRuntime.js';export * from './mtplxModels.js';export * from './mtplxRuntime.js';+export * from './slotstreamCatalog.js';export * from './slotstreamModels.js';export * from './managedDaemon.js';export * from './recordedProjectDir.js';diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.jsindex 46bfffb02d..3658a581c5 100644--- a/server/lib/mediaValidation.js+++ b/server/lib/mediaValidation.js@@ -172,6 +172,13 @@ export const localLlmSlotstreamStartSchema = z.object({model: z.string().trim().max(300).optional().nullable(),memoryGb: z.coerce.number().min(6).max(512).optional().nullable(),});+// A checkpoint download. `model` is a curated catalog id (`qwen3-30b-a3b-4bit`)+// or a Hugging Face repo id — the service resolves which, and refuses anything+// that is neither. Unlike a start, this one field is never optional: PortOS has+// no "download whatever" default for a transfer this size.+export const localLlmSlotstreamDownloadSchema = z.object({+ model: z.string().trim().min(1).max(200),+});// 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({@@ -245,6 +252,10 @@ export const localLlmDownloadPreflightSchema = z.discriminatedUnion('kind', [kind: z.literal('mtplx'),model: mtplxRepoIdSchema.optional().nullable(),}),+ z.object({+ kind: z.literal('slotstream'),+ model: z.string().trim().min(1).max(200),+ }),z.object({kind: z.literal('install'),backend: localLlmBackendSchema,diff --git a/server/lib/slotstreamCatalog.js b/server/lib/slotstreamCatalog.jsnew file mode 100644index 0000000000..a21552cecb--- /dev/null+++ b/server/lib/slotstreamCatalog.js@@ -0,0 +1,123 @@+/**+ * Which checkpoints Slotstream is offered, and which files of one are fetched.+ *+ * `slotstreamModels.js` answers "what is on disk and how much memory will a+ * start want". This module answers the question before it: which mixture-of-+ * experts checkpoints are worth streaming from SSD at all, and — once one is+ * picked — which files of that Hugging Face repo actually belong in the cache.+ *+ * Pure on purpose: no network, no filesystem. `services/slotstreamModelManager.js`+ * does the fetching and the disk writing, so the selection rules stay testable+ * against a plain sibling list.+ */++/**+ * Curated streaming candidates.+ *+ * The technique only pays off on a mixture-of-experts checkpoint: the bytes are+ * dominated by routed experts, of which a handful are active per token, so a+ * fixed cache slot pool can serve a model many times larger than RAM. A dense+ * checkpoint of the same size would stream every byte of every layer for every+ * token and crawl — which is why this is a curated list rather than an open+ * Hugging Face search. `approxBytes` is a display hint only; the real size is+ * read from the Hub at preview time, so a repo that grows cannot make PortOS+ * under-reserve disk.+ */+export const SLOTSTREAM_CATALOG = Object.freeze([+ Object.freeze({+ id: 'qwen3-235b-a22b-4bit',+ repo: 'mlx-community/Qwen3-235B-A22B-Instruct-2507-4bit',+ label: 'Qwen3 235B-A22B Instruct (4-bit)',+ params: '235B total / 22B active',+ approxBytes: 132 * 1024 ** 3,+ note: 'The headline case: a 235B-class model on a machine with a fraction of that in RAM.',+ }),+ Object.freeze({+ id: 'gpt-oss-120b-mxfp4',+ repo: 'mlx-community/gpt-oss-120b-MXFP4-Q8',+ label: 'GPT-OSS 120B (MXFP4)',+ params: '120B total / 5B active',+ approxBytes: 64 * 1024 ** 3,+ note: 'Roughly half the disk of the 235B and a smaller resident trunk — the gentler first checkpoint.',+ }),+ Object.freeze({+ id: 'qwen3-30b-a3b-4bit',+ repo: 'mlx-community/Qwen3-30B-A3B-4bit',+ label: 'Qwen3 30B-A3B (4-bit)',+ params: '30B total / 3B active',+ approxBytes: 17 * 1024 ** 3,+ note: 'Small enough to verify the whole install end to end before committing to a 100 GB+ pull.',+ }),+]);++/**+ * `owner/name`, the only shape a download is given.+ *+ * Deliberately the same rule `mtplxRepoIdSchema` applies: each segment must+ * START alphanumeric, so neither `owner/..` nor a leading `-` (which an argv or+ * a path walk would read as something other than a name) can get through.+ */+const REPO_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._-]*$/;++export const isSlotstreamRepoId = (value) => typeof value === 'string' && REPO_ID_RE.test(value);++/** The catalog row for a catalog id or a repo id, or null for anything else. */+export function slotstreamCatalogEntry(value) {+ const key = typeof value === 'string' ? value.trim() : '';+ if (!key) return null;+ return SLOTSTREAM_CATALOG.find((row) => row.id === key || row.repo === key) || null;+}++/**+ * The Hugging Face repo a request names — a catalog id resolves to its repo,+ * and any other value must already be a repo id. Returns null when neither.+ */+export function resolveSlotstreamRepo(value) {+ const entry = slotstreamCatalogEntry(value);+ if (entry) return entry.repo;+ const trimmed = typeof value === 'string' ? value.trim() : '';+ return isSlotstreamRepoId(trimmed) ? trimmed : null;+}++/**+ * The cache subdirectory one repo occupies.+ *+ * A checkpoint's directory NAME is the id `listSlotstreamCachedModels` reports+ * and the value a start hands `--model`, so it must be ONE path segment:+ * `owner/name` written literally would nest two levels deep and make the cache+ * walk report the owner as the checkpoint. The repo id carries exactly one `/`+ * (the id rule permits no others), so flattening that single separator is+ * lossless and the same repo always maps to the same directory.+ */+export const slotstreamModelDirName = (repo) => String(repo).replace('/', '__');++// Formats a Slotstream/MLX-style checkpoint directory is made of. `.safetensors`+// is the weights; the rest is config and tokenizer, all small.+const KEEP_FILE_RE = /\.(safetensors|json|txt|model|jinja|tiktoken)$/i;++// Repos routinely mirror the SAME weights in formats this runtime never loads+// (PyTorch `.bin`/`.pth`, GGUF, ONNX) or ship an `original/` copy of them.+// Fetching those can double or triple a 100 GB+ pull for nothing, so they are+// dropped even though they'd pass the extension check on name alone.+const SKIP_PATH_RE = /(^|\/)(original|onnx|openvino|coreml)\//i;++/**+ * The repo-relative files a checkpoint download should fetch, in a stable order.+ *+ * Rejects any name that is not a plain relative path: an absolute path or a+ * `..` segment coming back from the Hub must not be able to steer a write out+ * of the checkpoint directory.+ *+ * @param {Array<string|{rfilename?: string}>} siblings+ * @returns {string[]}+ */+export function selectSlotstreamRepoFiles(siblings) {+ const names = (Array.isArray(siblings) ? siblings : [])+ .map((row) => (typeof row === 'string' ? row : row?.rfilename))+ .filter((name) => typeof name === 'string' && name);++ return names+ .filter((name) => !name.startsWith('/') && !name.split('/').includes('..'))+ .filter((name) => KEEP_FILE_RE.test(name) && !SKIP_PATH_RE.test(name))+ .sort();+}diff --git a/server/lib/slotstreamCatalog.test.js b/server/lib/slotstreamCatalog.test.jsnew file mode 100644index 0000000000..ade0c3955b--- /dev/null+++ b/server/lib/slotstreamCatalog.test.js@@ -0,0 +1,112 @@+import { describe, it, expect } from 'vitest';+import {+ SLOTSTREAM_CATALOG,+ isSlotstreamRepoId,+ resolveSlotstreamRepo,+ selectSlotstreamRepoFiles,+ slotstreamCatalogEntry,+ slotstreamModelDirName,+} from './slotstreamCatalog.js';++describe('SLOTSTREAM_CATALOG', () => {+ it('offers only well-formed repo ids with unique catalog ids', () => {+ const ids = SLOTSTREAM_CATALOG.map((row) => row.id);+ expect(new Set(ids).size).toBe(ids.length);+ for (const row of SLOTSTREAM_CATALOG) {+ expect(isSlotstreamRepoId(row.repo)).toBe(true);+ expect(row.approxBytes).toBeGreaterThan(0);+ }+ });+});++describe('resolveSlotstreamRepo', () => {+ it('maps a catalog id to its repo and passes a bare repo id through', () => {+ const entry = SLOTSTREAM_CATALOG[0];+ expect(resolveSlotstreamRepo(entry.id)).toBe(entry.repo);+ expect(resolveSlotstreamRepo(entry.repo)).toBe(entry.repo);+ expect(resolveSlotstreamRepo('someone/some-moe-4bit')).toBe('someone/some-moe-4bit');+ });++ it('refuses anything that is neither — including path and flag shapes', () => {+ // Each segment must START alphanumeric, so `..` traversal and a leading+ // dash (which a path walk or an argv slot would read as something other+ // than a name) never resolve.+ for (const bad of ['', ' ', null, 42, 'owner', 'owner/../etc', '../owner/name', '-flag/name', 'owner/name/extra']) {+ expect(resolveSlotstreamRepo(bad)).toBeNull();+ }+ });++ it('finds a catalog row by either id or repo', () => {+ const entry = SLOTSTREAM_CATALOG[1];+ expect(slotstreamCatalogEntry(entry.repo)).toBe(entry);+ expect(slotstreamCatalogEntry(' ' + entry.id + ' ')).toBe(entry);+ expect(slotstreamCatalogEntry('someone/unlisted')).toBeNull();+ });+});++describe('slotstreamModelDirName', () => {+ it('flattens the repo to ONE path segment', () => {+ // The directory NAME is the id the cache walk reports and a start hands+ // `--model`; a literal `owner/name` would nest two levels and make the walk+ // report the owner as the checkpoint.+ const name = slotstreamModelDirName('mlx-community/Qwen3-30B-A3B-4bit');+ expect(name).toBe('mlx-community__Qwen3-30B-A3B-4bit');+ expect(name).not.toContain('/');+ });+});++describe('selectSlotstreamRepoFiles', () => {+ const siblings = (...names) => names.map((rfilename) => ({ rfilename }));++ it('keeps the weights, config, and tokenizer of a checkpoint', () => {+ expect(selectSlotstreamRepoFiles(siblings(+ 'model-00002-of-00002.safetensors',+ 'model-00001-of-00002.safetensors',+ 'model.safetensors.index.json',+ 'config.json',+ 'tokenizer.json',+ 'merges.txt',+ 'chat_template.jinja',+ ))).toEqual([+ 'chat_template.jinja',+ 'config.json',+ 'merges.txt',+ 'model-00001-of-00002.safetensors',+ 'model-00002-of-00002.safetensors',+ 'model.safetensors.index.json',+ 'tokenizer.json',+ ]);+ });++ it('drops mirrored copies of the same weights in formats this runtime never loads', () => {+ // A repo that also ships PyTorch/GGUF/ONNX (or an `original/` copy) would+ // otherwise double or triple a 100 GB+ pull for files that are never read.+ expect(selectSlotstreamRepoFiles(siblings(+ 'model.safetensors',+ 'pytorch_model.bin',+ 'consolidated.pth',+ 'model-q4.gguf',+ 'onnx/model.onnx',+ 'original/consolidated.safetensors',+ 'README.md',+ '.gitattributes',+ 'preview.png',+ ))).toEqual(['model.safetensors']);+ });++ it('refuses a name that is not a plain relative path', () => {+ // A Hub response must not be able to steer a write out of the checkpoint+ // directory.+ expect(selectSlotstreamRepoFiles(siblings(+ '/etc/passwd.json',+ '../../escape.safetensors',+ 'nested/../../escape.json',+ 'good.safetensors',+ ))).toEqual(['good.safetensors']);+ });++ it('accepts bare strings and ignores rows with no filename', () => {+ expect(selectSlotstreamRepoFiles(['config.json', { size: 10 }, null, 'x.safetensors'])).toEqual(['config.json', 'x.safetensors']);+ expect(selectSlotstreamRepoFiles(null)).toEqual([]);+ });+});diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 2f9331f4f0..567a381268 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -35,6 +35,7 @@ import {localLlmLmStudioServiceSchema,localLlmMtplxStartSchema,localLlmSlotstreamStartSchema,+ localLlmSlotstreamDownloadSchema,localLlmMtplxSearchSchema,localLlmMtplxPullSchema,localLlmMtplxRemoveSchema,@@ -51,6 +52,7 @@ import {} 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 { downloadSlotstreamModel, previewSlotstreamDownload } from '../services/slotstreamModelManager.js'import { searchMtplxCatalog, pullMtplxModel, previewMtplxPull, removeMtplxModel } from '../services/mtplxModelManager.js'import { saveProcessList } from '../services/pm2.js'import { getSpecDecodePresetStatus, downloadSpecDecodeModel, previewSpecDecodeDownload, cancelSpecDecodeModelDownload } from '../services/specDecodeModels.js'@@ -329,6 +331,10 @@ router.post('/download-preflight', asyncHandler(async (req, res) => {res.json(await previewMtplxPull({ model: body.model }))return}+ if (body.kind === 'slotstream') {+ res.json(await previewSlotstreamDownload({ model: body.model }))+ return+ }res.json(await previewInstallModel(body.backend, body.modelId))}))@@ -911,6 +917,22 @@ router.post('/slotstream/install', asyncHandler(async (req, res) => {res.json(result)}))+// POST /api/local-llm/slotstream/models/download — fetch one checkpoint into+// Slotstream's cache. Byte progress streams over `slotstream:download`, which+// is what the card's bar trusts: a 100 GB+ transfer outlives the request that+// started it, so a terminal frame — not the HTTP response — is what clears the+// bar and re-reads the cache. A start still never downloads anything; this is+// the explicit, separate action that does.+router.post('/slotstream/models/download', asyncHandler(async (req, res) => {+ const { model } = validateRequest(localLlmSlotstreamDownloadSchema, req.body)+ const io = req.app.get('io')+ const result = await downloadSlotstreamModel({ model, onProgress: (frame) => io?.emit('slotstream:download', frame) })+ // A cache that just went from empty to servable is exactly what the readiness+ // probes remember as "Slotstream has no checkpoint".+ if (result.success) resetProviderReadinessCache()+ 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 — `pm2diff --git a/server/services/orphanedPartialGc.js b/server/services/orphanedPartialGc.jsindex 0c46530a6e..3132c8220b 100644--- a/server/services/orphanedPartialGc.js+++ b/server/services/orphanedPartialGc.js@@ -22,6 +22,8 @@ import {} from './specDecodeModels.js';import { getModelsDir as getOllamaModelsDir } from './ollamaManager.js';import { getModelsDir as getLmStudioModelsDir } from './lmStudioManager.js';+import { slotstreamCacheDir } from '../lib/slotstreamModels.js';+import { isSlotstreamDownloadInFlight } from './slotstreamModelManager.js';import { createSweepScheduler } from './sweepScheduler.js';export { ORPHANED_PARTIAL_MAX_AGE_MS };@@ -44,6 +46,10 @@ export async function collectPartialSweepDirs() {}dirs.add(getOllamaModelsDir());dirs.add(await getLmStudioModelsDir());+ // Slotstream writes one directory per checkpoint, each holding ~30 shards, so+ // an abandoned pull can strand tens of gigabytes of `.partial` a level down —+ // the sweep is recursive, so naming the cache root covers every checkpoint.+ dirs.add(slotstreamCacheDir());return [...dirs];}@@ -60,7 +66,7 @@ export async function sweepOrphanedDownloadPartials({return sweepOrphanedPartials(targets, {now,maxAgeMs,- isProtected: (path) => isSpecDecodeDownloadInFlight(path),+ isProtected: (path) => isSpecDecodeDownloadInFlight(path) || isSlotstreamDownloadInFlight(path),});}diff --git a/server/services/slotstreamModelManager.js b/server/services/slotstreamModelManager.jsnew file mode 100644index 0000000000..11f30a697d--- /dev/null+++ b/server/services/slotstreamModelManager.js@@ -0,0 +1,303 @@+/**+ * Slotstream weights — the one step of the runtime PortOS did not manage.+ *+ * `slotstreamServerManager.js` owns the process (install / start / stop / logs)+ * and it deliberately refuses to start without a cached checkpoint. Until this+ * module existed, the only answer it could offer was "place a checkpoint+ * directory in ~/.slotstream/models yourself" — a hand-assembled 100 GB++ * directory, which is a dead end inside an app that manages everything else+ * about the runtime.+ *+ * A download still never happens implicitly. It moves tens of gigabytes and+ * only ever runs from a button the user pressed that names what it will fetch,+ * and a START still never fetches anything — this is its own explicit action.+ *+ * The transfer is PortOS's own resumable HTTP path (`streamResumableDownload`),+ * not a Python helper: Slotstream is a single native binary, and requiring an+ * image-gen venv for a text runtime's weights would be a strange dependency to+ * take on. Each file lands under the checkpoint directory the cache walk reads,+ * so a completed download is servable with no restart.+ */++import { rm, stat } from 'fs/promises';+import { join } from 'path';+import { ServerError } from '../lib/errorHandler.js';+import {+ assessDownloadPreflight,+ assertDownloadFits,+ partialPathFor,+ siblingDownloadMeta,+ streamResumableDownload,+} from '../lib/downloadPreflight.js';+import { buildHfAuthHeaders, buildHfResolveUrl, fetchHuggingfaceModel } from '../lib/huggingfaceLora.js';+import {+ SLOTSTREAM_CATALOG,+ resolveSlotstreamRepo,+ selectSlotstreamRepoFiles,+ slotstreamCatalogEntry,+ slotstreamModelDirName,+} from '../lib/slotstreamCatalog.js';+import { slotstreamCacheDir } from '../lib/slotstreamModels.js';+import { getHfToken } from './hfToken.js';++export { SLOTSTREAM_CATALOG };++/** Frames are throttled so a fast link can't put one socket emit per chunk on the wire. */+const PROGRESS_INTERVAL_MS = 250;++/**+ * A silent connection is never useful — it holds the one download slot while+ * every later press queues behind it. Generous, because a checkpoint this size+ * legitimately runs for hours while it IS receiving bytes.+ */+const IDLE_STALL_TIMEOUT_MS = (() => {+ const raw = Number(process.env.SLOTSTREAM_IDLE_STALL_MS);+ return Number.isFinite(raw) && raw > 0 ? raw : 20 * 60 * 1000;+})();++/** A metadata lookup that only blocks the confirm modal needs its own bound. */+const METADATA_FETCH_TIMEOUT_MS = 15_000;++/** Downloads in flight, keyed by checkpoint directory. */+const inFlight = new Map();++const cacheDirFor = (cacheDir) => cacheDir || slotstreamCacheDir();++/** The absolute checkpoint directory a repo occupies in the cache. */+export const slotstreamModelPath = (repo, { cacheDir } = {}) =>+ join(cacheDirFor(cacheDir), slotstreamModelDirName(repo));++function requireRepo(model) {+ const repo = resolveSlotstreamRepo(model);+ if (!repo) {+ throw new ServerError(+ `"${model}" is not a Slotstream checkpoint. Pick one from the catalog, or name a Hugging Face repo as owner/name.`,+ { status: 400, code: 'SLOTSTREAM_INVALID_MODEL' },+ );+ }+ return repo;+}++const hfDownloadHttpError = (res) => {+ if (res.status === 401 || res.status === 403) {+ throw new ServerError(+ `Hugging Face rejected the download (${res.status}) — this repo is gated. Accept its license on Hugging Face and add your HF token in Image Gen settings, then retry.`,+ { status: res.status, code: 'HF_AUTH' },+ );+ }+ throw new ServerError(`Hugging Face download failed: ${res.status} ${res.statusText}`, { status: 502, code: 'HF_DOWNLOAD_FAILED' });+};++const fileSize = async (path) => stat(path).then((s) => (s.isFile() ? s.size : 0), () => 0);++/**+ * What this download would transfer, and what is already here.+ *+ * `bytesOnDisk` counts both finished files and any `.partial` left by an+ * interrupted attempt, because both credit against what a resume still has to+ * move. Reserving the full repo size again would make a nearly-full disk refuse+ * a resume it can actually complete.+ */+async function planRepoDownload({ repo, token, signal, cacheDir }) {+ const model = await fetchHuggingfaceModel(repo, { token, signal, blobs: true });+ const siblings = Array.isArray(model?.siblings) ? model.siblings : [];+ const files = selectSlotstreamRepoFiles(siblings);+ if (files.length === 0) {+ throw new ServerError(+ `Hugging Face repo ${repo} publishes no checkpoint files PortOS can stream (no .safetensors weights).`,+ { status: 422, code: 'SLOTSTREAM_NO_WEIGHTS' },+ );+ }++ const metaByFile = new Map(+ siblings+ .filter((row) => typeof row?.rfilename === 'string')+ .map((row) => [row.rfilename, siblingDownloadMeta(row)]),+ );+ const modelDir = slotstreamModelPath(repo, { cacheDir });++ let totalBytes = 0;+ let bytesOnDisk = 0;+ const plan = [];+ for (const file of files) {+ const meta = metaByFile.get(file) || { bytes: 0, sha256: null };+ const destPath = join(modelDir, file);+ const onDisk = (await fileSize(destPath)) || (await fileSize(partialPathFor(destPath)));+ totalBytes += meta.bytes;+ bytesOnDisk += Math.min(onDisk, meta.bytes || onDisk);+ plan.push({ file, destPath, url: buildHfResolveUrl(repo, 'main', file), ...meta });+ }++ return { modelDir, files: plan, totalBytes, bytesOnDisk };+}++/**+ * Size / destination / free-disk numbers for the confirm step. Starts nothing.+ *+ * `expectedBytes` is the WHOLE checkpoint (what the user is committing to)+ * while the verdict is computed on what is actually left to move, so a resume+ * reads as "Size 123 GB / Still needed 4 GB" rather than being refused on a+ * disk that can finish it.+ */+export async function previewSlotstreamDownload({ model = null, cacheDir } = {}) {+ const repo = requireRepo(model);+ const token = await getHfToken();+ const plan = await planRepoDownload({+ repo,+ token,+ signal: AbortSignal.timeout(METADATA_FETCH_TIMEOUT_MS),+ cacheDir,+ });+ const remaining = Math.max(0, plan.totalBytes - plan.bytesOnDisk);+ const assessment = await assessDownloadPreflight({ destPath: plan.modelDir, expectedBytes: remaining });++ return {+ kind: 'slotstream',+ ...assessment,+ // The confirm modal reads `expectedBytes` as "Size" and derives "Still+ // needed" from `requiredBytes`; reporting the remainder as the size would+ // hide how large the checkpoint actually is.+ expectedBytes: plan.totalBytes,+ destPath: plan.modelDir,+ repo,+ files: plan.files.length,+ alreadyDownloaded: plan.totalBytes > 0 && remaining === 0,+ };+}++/**+ * Download one checkpoint into Slotstream's cache.+ *+ * Never throws for a transfer failure the caller has already streamed progress+ * for: the outcome is a value the route reports. An invalid request (unknown+ * model, a second press while one is running) still throws, because nothing has+ * been streamed yet.+ *+ * @param {{ model?: string|null, cacheDir?: string, onProgress?: (frame: object) => void }} [options]+ */+export async function downloadSlotstreamModel({ model = null, cacheDir, onProgress = () => {} } = {}) {+ const repo = requireRepo(model);+ const modelDir = slotstreamModelPath(repo, { cacheDir });+ if (inFlight.has(modelDir)) {+ throw new ServerError(`${repo} is already downloading`, { status: 409, code: 'SLOTSTREAM_DOWNLOAD_IN_FLIGHT' });+ }+ // Claim the slot BEFORE the first await: resolving the repo is a round trip,+ // and a second press landing inside that window would clear the check above+ // and start a parallel copy of the same 100 GB+ transfer.+ const state = { repo, controller: new AbortController(), abortReason: null };+ inFlight.set(modelDir, state);++ const label = slotstreamCatalogEntry(repo)?.label || repo;+ let lastEmit = 0;+ try {+ const token = await getHfToken();+ const headers = buildHfAuthHeaders(token);+ onProgress({ event: 'start', model: repo, message: `Resolving ${repo} on Hugging Face…` });+ const plan = await planRepoDownload({ repo, token, signal: state.controller.signal, cacheDir });+ assertDownloadFits(await assessDownloadPreflight({+ destPath: plan.modelDir,+ expectedBytes: Math.max(0, plan.totalBytes - plan.bytesOnDisk),+ }));++ console.log(`⬇️ Slotstream checkpoint download started: ${repo} (${plan.files.length} files, ${plan.totalBytes} bytes)`);+ onProgress({+ event: 'progress',+ model: repo,+ received: plan.bytesOnDisk,+ total: plan.totalBytes,+ message: `Downloading ${label} — ${plan.files.length} files. This is a multi-gigabyte download and can take a while.`,+ });++ // Bytes finished in EARLIER files of this run, so the bar reports progress+ // through the whole checkpoint rather than restarting at each file.+ let completedBytes = plan.bytesOnDisk;+ for (const entry of plan.files) {+ const alreadyDone = await fileSize(entry.destPath);+ if (alreadyDone > 0 && (!entry.bytes || alreadyDone === entry.bytes)) continue;+ // A finished file of the WRONG length is a truncated leftover from an+ // attempt that died between the rename and the next file — a resume+ // would append to nothing, so start that one file over.+ if (alreadyDone > 0) await rm(entry.destPath, { force: true }).catch(() => {});++ const resumedFrom = await fileSize(partialPathFor(entry.destPath));+ const { bytes } = await streamResumableDownload({+ url: entry.url,+ headers,+ destPath: entry.destPath,+ expectedSha256: entry.sha256,+ signal: state.controller.signal,+ idleStallTimeoutMs: IDLE_STALL_TIMEOUT_MS,+ isCancelled: () => state.abortReason === 'cancelled',+ onIdleStall: () => {+ state.abortReason = 'stalled';+ state.controller.abort();+ },+ onHttpError: hfDownloadHttpError,+ onBytes: (received) => {+ const now = Date.now();+ if (now - lastEmit < PROGRESS_INTERVAL_MS) return;+ lastEmit = now;+ onProgress({+ event: 'progress',+ model: repo,+ received: completedBytes + Math.max(0, received - resumedFrom),+ total: plan.totalBytes,+ message: `Downloading ${entry.file}`,+ });+ },+ });+ completedBytes += Math.max(0, bytes - resumedFrom);+ }++ console.log(`✅ Slotstream checkpoint ready: ${repo} → ${plan.modelDir}`);+ onProgress({+ event: 'complete',+ model: repo,+ received: plan.totalBytes,+ total: plan.totalBytes,+ message: `${label} downloaded`,+ });+ return {+ success: true,+ model: slotstreamModelDirName(repo),+ repo,+ path: plan.modelDir,+ files: plan.files.length,+ sizeBytes: plan.totalBytes,+ };+ } catch (err) {+ const error = state.abortReason ? abortError(state) : err;+ const event = state.abortReason === 'cancelled' ? 'cancelled' : 'error';+ console.error(`❌ Slotstream checkpoint download failed for ${repo}: ${error.message}`);+ onProgress({ event, model: repo, message: error.message });+ return { success: false, model: repo, error: error.message, code: error.code || null };+ } finally {+ inFlight.delete(modelDir);+ }+}++function abortError(state) {+ if (state.abortReason === 'cancelled') {+ return new ServerError('Download cancelled', { status: 409, code: 'SLOTSTREAM_DOWNLOAD_CANCELLED' });+ }+ const minutes = Math.round(IDLE_STALL_TIMEOUT_MS / 60000);+ return new ServerError(+ `Download stalled — no bytes received for ${minutes} minute${minutes === 1 ? '' : 's'}; cancelled so another checkpoint can download`,+ { status: 504, code: 'SLOTSTREAM_DOWNLOAD_STALLED' },+ );+}++/** True while a checkpoint download is writing under `path` (or its `.partial`). */+export function isSlotstreamDownloadInFlight(path) {+ if (!path || inFlight.size === 0) return false;+ const target = String(path);+ for (const modelDir of inFlight.keys()) {+ if (target === modelDir || target.startsWith(`${modelDir}/`)) return true;+ }+ return false;+}++/** Clears in-flight download bookkeeping (used by test suites). */+export function _resetSlotstreamDownloadsForTests() {+ inFlight.clear();+}diff --git a/server/services/slotstreamModelManager.test.js b/server/services/slotstreamModelManager.test.jsnew file mode 100644index 0000000000..a85bc96d51--- /dev/null+++ b/server/services/slotstreamModelManager.test.js@@ -0,0 +1,192 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';++vi.mock('./hfToken.js', () => ({ getHfToken: async () => null }));++const { listSlotstreamCachedModels } = await import('../lib/slotstreamModels.js');+const {+ downloadSlotstreamModel,+ previewSlotstreamDownload,+ isSlotstreamDownloadInFlight,+ slotstreamModelPath,+ _resetSlotstreamDownloadsForTests,+} = await import('./slotstreamModelManager.js');++const REPO = 'mlx-community/Qwen3-30B-A3B-4bit';+const DIR_NAME = 'mlx-community__Qwen3-30B-A3B-4bit';++// Two files: one big enough to stand in for a weight shard, one config.+const SHARD = 'S'.repeat(4096);+const CONFIG = '{"model_type":"qwen3_moe"}';+const FILES = { 'model.safetensors': SHARD, 'config.json': CONFIG };+const TOTAL = SHARD.length + CONFIG.length;++const metadataResponse = () => new Response(JSON.stringify({+ id: REPO,+ siblings: [+ { rfilename: 'model.safetensors', lfs: { size: SHARD.length } },+ { rfilename: 'config.json', size: CONFIG.length },+ // A mirrored PyTorch copy the runtime never loads — must not be fetched+ // (and must not inflate the size the user is asked to approve).+ { rfilename: 'pytorch_model.bin', lfs: { size: 999_999 } },+ ],+}), { status: 200, headers: { 'content-type': 'application/json' } });++let cacheDir;+let fetched;++const installFetch = (fileBodies = FILES) => {+ fetched = [];+ globalThis.fetch = vi.fn(async (url) => {+ const href = String(url);+ fetched.push(href);+ if (href.startsWith('https://huggingface.co/api/models/')) return metadataResponse();+ const file = Object.keys(fileBodies).find((name) => href.endsWith(`/${name}`));+ if (!file) return new Response('nope', { status: 404, statusText: 'Not Found' });+ const body = fileBodies[file];+ return new Response(body, { status: 200, headers: { 'content-length': String(body.length) } });+ });+};++beforeEach(async () => {+ cacheDir = await mkdtemp(join(tmpdir(), 'slotstream-cache-'));+ _resetSlotstreamDownloadsForTests();+ installFetch();+});++afterEach(async () => {+ await rm(cacheDir, { recursive: true, force: true });+ vi.unstubAllGlobals();+ delete globalThis.fetch;+});++describe('previewSlotstreamDownload', () => {+ it('reports the whole checkpoint size, the destination, and a disk verdict', async () => {+ const preview = await previewSlotstreamDownload({ model: REPO, cacheDir });+ expect(preview.kind).toBe('slotstream');+ expect(preview.repo).toBe(REPO);+ expect(preview.destPath).toBe(join(cacheDir, DIR_NAME));+ // The mirrored `.bin` is excluded, so the user approves what is actually moved.+ expect(preview.expectedBytes).toBe(TOTAL);+ expect(preview.files).toBe(2);+ expect(preview.alreadyDownloaded).toBe(false);+ expect(preview.verdict).toBe('ok');+ });++ it('credits bytes already on disk so a resume is not refused for the full size', async () => {+ // `requiredBytes` is what a nearly-full disk is judged against; charging the+ // full checkpoint again would reject a resume the volume can finish.+ const modelDir = join(cacheDir, DIR_NAME);+ await mkdir(modelDir, { recursive: true });+ await writeFile(join(modelDir, 'config.json'), CONFIG);+ await writeFile(join(modelDir, 'model.safetensors.partial'), SHARD.slice(0, 1000));++ const preview = await previewSlotstreamDownload({ model: REPO, cacheDir });+ // Size stays the whole checkpoint (what the user is committing to) while+ // the space actually reserved drops to what is left, which is what the+ // confirm modal renders as "Still needed".+ expect(preview.expectedBytes).toBe(TOTAL);+ expect(preview.requiredBytes - preview.headroomBytes).toBe(SHARD.length - 1000);+ expect(preview.requiredBytes).toBeLessThan(preview.expectedBytes + preview.headroomBytes);+ });++ it('marks a fully cached checkpoint as already downloaded', async () => {+ const modelDir = join(cacheDir, DIR_NAME);+ await mkdir(modelDir, { recursive: true });+ for (const [name, body] of Object.entries(FILES)) await writeFile(join(modelDir, name), body);++ const preview = await previewSlotstreamDownload({ model: REPO, cacheDir });+ expect(preview.alreadyDownloaded).toBe(true);+ expect(preview.requiredBytes).toBe(0);+ });++ it('refuses an unknown model before it touches the network', async () => {+ await expect(previewSlotstreamDownload({ model: '../escape', cacheDir }))+ .rejects.toMatchObject({ code: 'SLOTSTREAM_INVALID_MODEL' });+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });+});++describe('downloadSlotstreamModel', () => {+ it('lands a servable checkpoint the cache walk reports, and skips mirrored formats', async () => {+ const frames = [];+ const result = await downloadSlotstreamModel({ model: REPO, cacheDir, onProgress: (f) => frames.push(f) });++ expect(result).toMatchObject({ success: true, repo: REPO, model: DIR_NAME, files: 2 });+ expect(await readFile(join(cacheDir, DIR_NAME, 'model.safetensors'), 'utf8')).toBe(SHARD);+ expect(await readFile(join(cacheDir, DIR_NAME, 'config.json'), 'utf8')).toBe(CONFIG);+ expect(fetched.some((url) => url.endsWith('pytorch_model.bin'))).toBe(false);++ // The whole point: a start can now resolve it with no restart.+ const cached = await listSlotstreamCachedModels({ cacheDir });+ expect(cached.error).toBeNull();+ expect(cached.models.map((m) => m.id)).toEqual([DIR_NAME]);+ expect(frames.at(-1)).toMatchObject({ event: 'complete', model: REPO });+ });++ it('accepts a catalog id as well as a repo id', async () => {+ const result = await downloadSlotstreamModel({ model: 'qwen3-30b-a3b-4bit', cacheDir });+ expect(result.success).toBe(true);+ expect(result.repo).toBe(REPO);+ });++ it('reports a transfer failure as a value with a terminal frame, not a rejection', async () => {+ // The route has already streamed progress by this point, so a thrown+ // rejection would leave the client's bar stuck with no terminal frame.+ installFetch({ 'config.json': CONFIG });+ const frames = [];+ const result = await downloadSlotstreamModel({ model: REPO, cacheDir, onProgress: (f) => frames.push(f) });++ expect(result.success).toBe(false);+ expect(result.error).toBeTruthy();+ expect(frames.at(-1).event).toBe('error');+ expect(isSlotstreamDownloadInFlight(join(cacheDir, DIR_NAME))).toBe(false);+ });++ it('refuses a second download of the same checkpoint while one is running', async () => {+ let release;+ const gate = new Promise((resolve) => { release = resolve; });+ const realFetch = globalThis.fetch;+ globalThis.fetch = vi.fn(async (url) => {+ if (String(url).endsWith('model.safetensors')) await gate;+ return realFetch(url);+ });++ const first = downloadSlotstreamModel({ model: REPO, cacheDir });+ // Let the first call claim its slot before the second one checks.+ await vi.waitFor(() => expect(isSlotstreamDownloadInFlight(join(cacheDir, DIR_NAME))).toBe(true));+ await expect(downloadSlotstreamModel({ model: REPO, cacheDir }))+ .rejects.toMatchObject({ code: 'SLOTSTREAM_DOWNLOAD_IN_FLIGHT' });++ release();+ expect((await first).success).toBe(true);+ });++ it('protects a live shard from the orphaned-partial sweep', async () => {+ // The sweep asks about the `.partial` path a SHARD is being written to, one+ // level below the checkpoint directory. Answering false there would let the+ // daily GC unlink a transfer that is still running.+ const shardPartial = join(cacheDir, DIR_NAME, 'model.safetensors.partial');+ expect(slotstreamModelPath(REPO, { cacheDir })).toBe(join(cacheDir, DIR_NAME));+ expect(isSlotstreamDownloadInFlight(shardPartial)).toBe(false);++ let release;+ const gate = new Promise((resolve) => { release = resolve; });+ const realFetch = globalThis.fetch;+ globalThis.fetch = vi.fn(async (url) => {+ if (String(url).endsWith('model.safetensors')) await gate;+ return realFetch(url);+ });++ const running = downloadSlotstreamModel({ model: REPO, cacheDir });+ await vi.waitFor(() => expect(isSlotstreamDownloadInFlight(shardPartial)).toBe(true));+ // A sibling checkpoint's partial is NOT protected by this one's transfer.+ expect(isSlotstreamDownloadInFlight(join(cacheDir, 'other__model', 'x.safetensors.partial'))).toBe(false);++ release();+ await running;+ expect(isSlotstreamDownloadInFlight(shardPartial)).toBe(false);+ });+});diff --git a/server/services/slotstreamServerManager.js b/server/services/slotstreamServerManager.jsindex 01f528996e..67ae8316b1 100644--- a/server/services/slotstreamServerManager.js+++ b/server/services/slotstreamServerManager.js@@ -34,6 +34,7 @@ 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 { SLOTSTREAM_CATALOG } from '../lib/slotstreamCatalog.js';import {listSlotstreamCachedModels,pickSlotstreamCachedModel,@@ -171,6 +172,10 @@ export async function getSlotstreamServerStatus() {cachedModels: (cache.models || []).map((m) => m?.id).filter(Boolean),cacheDir: slotstreamCacheDir(),cacheError: cache.error,+ // The download menu rides on the status payload rather than a route of its+ // own: it is three frozen rows, so a second fetch (and a second cache to+ // keep in step with the cached-checkpoint list beside it) would buy nothing.+ catalog: SLOTSTREAM_CATALOG,};}