Skip to content

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

refactor: extract one shared weight-download slot, and give Slotstream the cancel it lacked (#6168)

[._.]/ Adam Eivy7bb30b6fa25c
diff --git a/client/src/components/settings/LocalLlmRuntimesView.jsx b/client/src/components/settings/LocalLlmRuntimesView.jsx
index a876f56ce4..a2333e6d5a 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, downloadSlotstreamModel, 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, cancelSlotstreamModelDownload, saveRuntimeStartupList } from '../../services/api';
import socket from '../../services/socket';
import SpecDecodeWeightRow from './SpecDecodeWeightRow.jsx';
import RuntimeServersCard from './RuntimeServersCard.jsx';
@@ -358,6 +358,15 @@ export default function LocalLlmRuntimesView() {
preview: () => previewLocalLlmDownload({ kind: 'slotstream', model }, { silent: true }),
run: () => startSlotstreamDownload(model),
});
+ // A 100 GB+ transfer that is merely SLOW never trips the idle watchdog, so
+ // without this the only way out was to wait it out. The bar comes down on the
+ // 'cancelled' frame the server emits, not here.
+ const cancelSlotstreamDownload = (model) => runAction(
+ 'slotstream-download-cancel',
+ () => cancelSlotstreamModelDownload(model ?? null, { silent: true }),
+ (r) => (r?.cancelled ? 'Cancelling checkpoint download…' : 'No checkpoint download is running'),
+ { onError: (err) => toast.error(err?.message || 'Could not cancel the checkpoint download') },
+ );
const runtimeStopSlotstream = () => runAction(
'runtime-stop-slotstream',
() => stopSlotstreamServer(),
@@ -733,6 +742,7 @@ export default function LocalLlmRuntimesView() {
onStop={runtimeStopSlotstream}
onInstall={runtimeInstallSlotstream}
onDownloadModel={slotstreamDownloadModel}
+ onCancelDownload={cancelSlotstreamDownload}
download={slotstreamDownload}
/>
</div>
diff --git a/client/src/components/settings/SlotstreamServerCard.jsx b/client/src/components/settings/SlotstreamServerCard.jsx
index a8678ca2f7..d2d4b694a9 100644
--- a/client/src/components/settings/SlotstreamServerCard.jsx
+++ b/client/src/components/settings/SlotstreamServerCard.jsx
@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
-import { HardDrive, RefreshCw, Save, Square, Download, Terminal } from 'lucide-react';
+import { HardDrive, RefreshCw, Save, Square, Download, Terminal, X } from 'lucide-react';
import BrailleSpinner from '../BrailleSpinner';
import ProgressBar from '../ui/ProgressBar';
import { formatBytes } from '../../utils/formatters';
@@ -23,12 +23,28 @@ const btnClass = 'flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium ro
* resolving pass before that has none, which is the shared bar's indeterminate
* case rather than a misleading 0%.
*/
-function DownloadProgress({ download }) {
+function DownloadProgress({ download, onCancel, cancelling }) {
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'}`} />
+ <div className="flex items-center gap-2">
+ <div className="flex-1 min-w-0">
+ <ProgressBar percent={pct} track="border" label={`Downloading ${download.model || 'checkpoint'}`} />
+ </div>
+ {onCancel && (
+ <button
+ type="button"
+ onClick={onCancel}
+ disabled={cancelling}
+ className={`${btnClass} bg-port-warning/20 hover:bg-port-warning/30 text-port-warning shrink-0`}
+ title="Stop this transfer — what has landed is kept, so downloading again resumes"
+ >
+ {cancelling ? <BrailleSpinner /> : <X size={13} />}
+ Cancel
+ </button>
+ )}
+ </div>
<p className="text-[11px] text-gray-500">
{pct === null
? (message || 'Downloading…')
@@ -49,6 +65,7 @@ export default function SlotstreamServerCard({
onStop,
onInstall,
onDownloadModel,
+ onCancelDownload,
download,
}) {
const [model, setModel] = useState('');
@@ -265,7 +282,13 @@ export default function SlotstreamServerCard({
<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} />}
+ {download && (
+ <DownloadProgress
+ download={download}
+ onCancel={onCancelDownload ? () => onCancelDownload(download.model) : null}
+ cancelling={actionInProgress === 'slotstream-download-cancel'}
+ />
+ )}
</div>
)}
diff --git a/client/src/components/settings/SlotstreamServerCard.test.jsx b/client/src/components/settings/SlotstreamServerCard.test.jsx
index 24d64c1d94..2badfac9ba 100644
--- a/client/src/components/settings/SlotstreamServerCard.test.jsx
+++ b/client/src/components/settings/SlotstreamServerCard.test.jsx
@@ -15,6 +15,7 @@ const renderCard = (status, props = {}) => {
onStop: vi.fn(),
onInstall: vi.fn(),
onDownloadModel: vi.fn(),
+ onCancelDownload: vi.fn(),
};
render(
<SlotstreamServerCard status={status} loading={false} busy={false} actionInProgress={null} {...handlers} {...props} />,
@@ -112,6 +113,22 @@ describe('SlotstreamServerCard', () => {
expect(screen.getByText('5 GB of 20 GB (25%)')).toBeInTheDocument();
});
+ // Without this the only way out of a 100 GB+ transfer that is slow rather
+ // than stalled was to wait out the 20-minute idle watchdog.
+ it('offers a cancel beside the bar while a checkpoint is transferring', () => {
+ const handlers = renderCard(
+ { installed: true, running: false, supported: true, cachedModels: [], catalog: CATALOG },
+ { download: { model: 'someone/small-moe', received: 5 * 1024 ** 3, total: 20 * 1024 ** 3 } },
+ );
+ fireEvent.click(screen.getByRole('button', { name: /Cancel/ }));
+ expect(handlers.onCancelDownload).toHaveBeenCalledWith('someone/small-moe');
+ });
+
+ it('hides the cancel when nothing is transferring', () => {
+ renderCard({ installed: true, running: false, supported: true, cachedModels: [], catalog: CATALOG });
+ expect(screen.queryByRole('button', { name: /Cancel/ })).not.toBeInTheDocument();
+ });
+
it('offers a download while the server is running, so a second checkpoint needs no stop', () => {
renderCard({
installed: true,
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 001b5e6d19..8f522e597e 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 their checkpoint catalogs — `searchMtplxModels` / `pullMtplxModel` / `removeMtplxModel` and `downloadSlotstreamModel`, 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` / `cancelSlotstreamModelDownload`, 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.js
index d1b19e8795..1a5c9a09e3 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -110,6 +110,15 @@ export const installSlotstream = () =>
export const downloadSlotstreamModel = (model) =>
request('/local-llm/slotstream/models/download', { method: 'POST', body: JSON.stringify({ model }) });
+// Stop the checkpoint download in progress. `model` is optional — one transfers
+// at a time — and the partial files are kept, so a later download resumes.
+export const cancelSlotstreamModelDownload = (model, options) =>
+ request('/local-llm/slotstream/models/download/cancel', {
+ method: 'POST',
+ body: JSON.stringify({ model: model ?? null }),
+ ...options,
+ });
+
// 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/server/lib/README.md b/server/lib/README.md
index 21cb99dff0..751e82d3cb 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -230,7 +230,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record loop — the peer:online convergence push and every base-hash-evicting `pruneTombstoned*` loop — collapses N `sync_base_hashes.json` rewrites into one terminal write (depth-counted, so concurrent batches merge too; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned, so those paths don't let the side store grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |
| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |
| `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `resolveCodeRootForModule(moduleUrl)` is the single source of truth for the "two directories above this file" depth assumption — `paths.js`'s `CODE_ROOT` and `services/userActions.js`'s data-root guard both derive through it so they cannot silently drift apart. `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |
-| `downloadPreflight.js` | Free-disk preflight + resumable weight download. `assessDownloadPreflight({ destPath, expectedBytes })` → `{ freeBytes, requiredBytes, headroomBytes, verdict: ok\|tight\|insufficient }`; `assertDownloadFits` throws typed `DISK_INSUFFICIENT` (507) when the volume cannot hold the payload. `streamResumableDownload` Range-resumes a `.partial` on transport failure, discards it on user cancel, and verifies a published sha256 before rename. `sweepOrphanedPartials(dirs, { maxAgeMs })` unlinks leftover `.partial` (+ `.partial.etag`) files older than 7 days (default) and skips recent/in-flight dests; missing dirs are a no-op. `probeRemoteSize` / `siblingDownloadMeta` / `verifyDownloadHash` are the size+digest helpers the four weight-download entry points share. |
+| `downloadPreflight.js` | Free-disk preflight + resumable weight download. `assessDownloadPreflight({ destPath, expectedBytes })` → `{ freeBytes, requiredBytes, headroomBytes, verdict: ok\|tight\|insufficient }`; `assertDownloadFits` throws typed `DISK_INSUFFICIENT` (507) when the volume cannot hold the payload. `streamResumableDownload` Range-resumes a `.partial` on transport failure, discards it on user cancel, and verifies a published sha256 before rename. `sweepOrphanedPartials(dirs, { maxAgeMs })` unlinks leftover `.partial` (+ `.partial.etag`) files older than 7 days (default) and skips recent/in-flight dests; missing dirs are a no-op. `probeRemoteSize` / `siblingDownloadMeta` / `verifyDownloadHash` are the size+digest helpers the four weight-download entry points share. `createDownloadSlot({ codePrefix, exclusive, matchNested, keepPartialOnCancel })` is the one transfer-slot registry every entry point claims before its first await — in-flight map, abort controller with cancel/stall reasons, typed `<PREFIX>_DOWNLOAD_IN_FLIGHT`/`_STALLED`/`_CANCELLED` errors, progress throttle, and an `isInFlight(path)` predicate; `isAnyDownloadInFlight` answers for every slot at once, which is what the orphaned-partial GC protects live transfers with. |
| `agentInstructionsFile.js` | The `AGENTS.md` + bridge `CLAUDE.md` pair a repo carries (#4852). `writeAgentInstructions(repoPath, content)` writes the body to `AGENTS.md` and the one-line `@AGENTS.md` import beside it — use it in scaffolders instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)`, since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: `AGENT_INSTRUCTIONS_FILENAME`, `CLAUDE_BRIDGE_FILENAME`, `AGENT_INSTRUCTIONS_IMPORT`. |
| `fileCore.js` | Cross-cutting filesystem primitives (`atomicWrite`, directory helpers, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers. |
| `fileUtils.js` | Backward-compatible facade re-exporting the focused file utility modules so existing deep imports need no caller changes. |
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index 6285aa103f..3ee8975ea2 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -9086,6 +9086,14 @@
"server/routes/localLlm.js"
]
},
+ {
+ "method": "POST",
+ "path": "/api/local-llm/slotstream/models/download/cancel",
+ "mountPath": "/api/local-llm",
+ "sources": [
+ "server/routes/localLlm.js"
+ ]
+ },
{
"method": "POST",
"path": "/api/local-llm/slotstream/start",
@@ -17521,8 +17529,8 @@
],
"stats": {
"mounts": 147,
- "operations": 2170,
- "declarations": 2178,
+ "operations": 2171,
+ "declarations": 2179,
"sourceFiles": 230
}
}
diff --git a/server/lib/downloadPreflight.js b/server/lib/downloadPreflight.js
index 7ca7091c14..57dfd7be96 100644
--- a/server/lib/downloadPreflight.js
+++ b/server/lib/downloadPreflight.js
@@ -15,7 +15,7 @@
import { createWriteStream } from 'fs';
import { readFile, readdir, rm, stat, statfs, rename, writeFile } from 'fs/promises';
-import { dirname, join } from 'path';
+import { dirname, join, sep } from 'path';
import { Readable, Transform } from 'stream';
import { pipeline } from 'stream/promises';
import { ServerError } from './errorHandler.js';
@@ -510,3 +510,251 @@ function rejectDownloadStatus(res) {
{ status: 502, code: 'DOWNLOAD_FAILED' },
);
}
+
+// === Shared download slot ====================================================
+// Every weight-download entry point (llama.cpp spec-decode GGUFs, Slotstream
+// checkpoints) needs the same five things around `streamResumableDownload`: an
+// in-flight registry claimed BEFORE the first await, an AbortController with a
+// reason so the catch can say "cancelled" rather than "AbortError", an
+// idle-stall watchdog, a progress-frame throttle, and one predicate the
+// orphaned-partial GC can ask whether a path belongs to a live transfer.
+//
+// Keeping one copy per service is how they drift: Slotstream shipped with
+// `'cancelled'` branches nothing could ever set, because the cancel lived in
+// the caller instead of the slot. Here the cancel comes WITH the slot, and the
+// GC gets one predicate per slot rather than one more `||` clause per runtime.
+
+/** Progress frames are throttled to this interval so a fast link can't emit one frame per chunk. */
+export const DEFAULT_PROGRESS_INTERVAL_MS = 250;
+
+/**
+ * A download still receiving bytes may legitimately run for hours, but a silent
+ * connection is never useful: it holds a transfer slot and leaves every later
+ * press queued. Generous by default, per-runtime overridable by env.
+ */
+export const DEFAULT_IDLE_STALL_TIMEOUT_MS = 20 * 60 * 1000;
+
+const positiveNumber = (value) => {
+ const raw = Number(value);
+ return Number.isFinite(raw) && raw > 0 ? raw : null;
+};
+
+/**
+ * Every slot ever created, so one predicate can answer for all of them.
+ *
+ * The orphaned-partial GC used to OR one `isXDownloadInFlight` per runtime, which
+ * meant a new download path was unprotected until somebody remembered to add
+ * that clause. Registering here makes protection the default and forgetting it
+ * impossible — the only thing a new runtime must still do is BE LOADED, which
+ * `orphanedPartialGc.test.js` pins.
+ */
+const downloadSlots = new Set();
+
+/** True while ANY registered download slot is writing `path` (or its `.partial`). */
+export function isAnyDownloadInFlight(path) {
+ for (const slot of downloadSlots) {
+ if (slot.isInFlight(path)) return true;
+ }
+ return false;
+}
+
+const defaultStalledMessage = (minutes) => (
+ `Download stalled — no bytes received for ${minutes} minute${minutes === 1 ? '' : 's'}, so it was abandoned. Its progress is kept: pressing download again resumes from where it stopped.`
+);
+
+/**
+ * One transfer-slot registry for a family of downloads.
+ *
+ * @param {object} opts
+ * @param {string} opts.codePrefix Error-code namespace: `<PREFIX>_DOWNLOAD_IN_FLIGHT` / `_STALLED` / `_CANCELLED`.
+ * @param {string} [opts.idleStallEnvVar] Env var overriding the stall timeout (ms).
+ * @param {number} [opts.idleStallTimeoutMs] Fallback stall timeout when the env var is unset/invalid.
+ * @param {number} [opts.progressIntervalMs] Progress-frame throttle interval.
+ * @param {boolean} [opts.exclusive] When true, ANY active download blocks a claim on a different key.
+ * @param {boolean} [opts.matchNested] When true, `isInFlight` also matches paths BELOW a claimed key (a directory of shards).
+ * @param {(minutes: number) => string} [opts.stalledMessage] Message for the typed stalled error.
+ * @param {string} [opts.cancelledMessage] Message for the typed cancelled error.
+ * @param {boolean} [opts.keepPartialOnCancel] Keep the `.partial` a cancel interrupted, so a later attempt resumes it.
+ */
+export function createDownloadSlot({
+ codePrefix,
+ idleStallEnvVar = null,
+ idleStallTimeoutMs = DEFAULT_IDLE_STALL_TIMEOUT_MS,
+ progressIntervalMs = DEFAULT_PROGRESS_INTERVAL_MS,
+ exclusive = false,
+ matchNested = false,
+ stalledMessage = defaultStalledMessage,
+ cancelledMessage = 'Download cancelled',
+ keepPartialOnCancel = false,
+} = {}) {
+ const stallMs = (idleStallEnvVar ? positiveNumber(process.env[idleStallEnvVar]) : null)
+ ?? positiveNumber(idleStallTimeoutMs)
+ ?? DEFAULT_IDLE_STALL_TIMEOUT_MS;
+ const inFlight = new Map();
+
+ const stalledError = () => {
+ const minutes = Math.round(stallMs / 60000);
+ return new ServerError(stalledMessage(minutes), {
+ status: 504,
+ code: `${codePrefix}_DOWNLOAD_STALLED`,
+ });
+ };
+
+ const cancelledError = () => new ServerError(cancelledMessage, {
+ status: 409,
+ code: `${codePrefix}_DOWNLOAD_CANCELLED`,
+ });
+
+ const abortErrorFor = (record) => {
+ if (record.abortReason === 'cancelled') return cancelledError();
+ if (record.abortReason === 'stalled') return stalledError();
+ return null;
+ };
+
+ const cancelRecord = (record) => {
+ if (!record) return false;
+ record.abortReason = 'cancelled';
+ record.controller.abort();
+ return true;
+ };
+
+ const slot = {
+ idleStallTimeoutMs: stallMs,
+ progressIntervalMs,
+ stalledError,
+ cancelledError,
+
+ /** How many transfers this slot is currently running. */
+ get size() { return inFlight.size; },
+
+ /** Public state of the transfer on `key`, or null. Reflects live byte counters. */
+ get: (key) => inFlight.get(key)?.state ?? null,
+
+ /** Every live transfer's public state — for a status surface listing them. */
+ entries: () => [...inFlight.entries()].map(([key, record]) => [key, record.state]),
+
+ /**
+ * Reserve `key`. Call this BEFORE the first await of the download: resolving
+ * a repo is a round trip, and a second press landing inside that window
+ * would otherwise clear the caller's own check and start a parallel copy of
+ * a multi-gigabyte transfer.
+ *
+ * @param {string} key
+ * @param {{ busyMessage?: string, otherBusyMessage?: string, meta?: object }} [opts]
+ * @returns {object} handle — release it in a `finally`.
+ */
+ claim(key, { busyMessage, otherBusyMessage, meta = {} } = {}) {
+ const held = inFlight.has(key);
+ if (held || (exclusive && inFlight.size > 0)) {
+ throw new ServerError(
+ (held ? busyMessage : otherBusyMessage || busyMessage) || `${key} is already downloading`,
+ { status: 409, code: `${codePrefix}_DOWNLOAD_IN_FLIGHT` },
+ );
+ }
+ const record = {
+ key,
+ controller: new AbortController(),
+ abortReason: null,
+ state: { received: 0, total: 0, ...meta },
+ };
+ inFlight.set(key, record);
+
+ let lastEmit = 0;
+ return {
+ key,
+ state: record.state,
+ signal: record.controller.signal,
+ get cancelled() { return record.abortReason === 'cancelled'; },
+ get stalled() { return record.abortReason === 'stalled'; },
+
+ /** Record byte counters so a status read can report this transfer's progress. */
+ track(received, total) {
+ record.state.received = received;
+ if (Number.isFinite(total)) record.state.total = total;
+ },
+
+ /** Wrap a progress emitter so it fires at most once per interval. */
+ throttle(fn) {
+ return (...args) => {
+ const now = Date.now();
+ if (now - lastEmit < progressIntervalMs) return;
+ lastEmit = now;
+ fn(...args);
+ };
+ },
+
+ /**
+ * The abort/stall bundle `streamResumableDownload` takes. Spread it into
+ * the call so a slot's cancel and watchdog cannot be wired only halfway.
+ */
+ downloadOptions() {
+ return {
+ signal: record.controller.signal,
+ idleStallTimeoutMs: stallMs,
+ // `isCancelled` is what tells the stream to DISCARD the `.partial`
+ // it was mid-write on. A slot that resumes on the next attempt
+ // withholds it, so the bytes already moved survive the cancel.
+ isCancelled: keepPartialOnCancel
+ ? () => false
+ : () => record.abortReason === 'cancelled',
+ onIdleStall: () => {
+ record.abortReason = 'stalled';
+ record.controller.abort();
+ },
+ };
+ },
+
+ /**
+ * The typed error for however this transfer ended: a cancel/stall abort
+ * surfaces as a generic `AbortError`, which tells the user nothing.
+ */
+ wrapError: (err) => abortErrorFor(record) || err,
+ abortError: () => abortErrorFor(record),
+
+ /** Throw the typed abort error if this slot was aborted while awaiting. */
+ throwIfAborted() {
+ if (record.controller.signal.aborted) throw abortErrorFor(record) || cancelledError();
+ },
+
+ /** Cancel THIS transfer (from inside the owning call). */
+ cancel: () => cancelRecord(record),
+
+ release() {
+ // Only drop our own record: a later claim on the same key must not be
+ // evicted by a straggling release from the transfer that preceded it.
+ if (inFlight.get(key) === record) inFlight.delete(key);
+ },
+ };
+ },
+
+ /** Cancel the transfer on `key`. False when none is active. */
+ cancel: (key) => cancelRecord(inFlight.get(key)),
+
+ /**
+ * True while a transfer is writing `path` — its destination, its `.partial`,
+ * or (with `matchNested`) anything under a claimed directory. This is what
+ * the orphaned-partial GC asks before unlinking.
+ */
+ isInFlight(path) {
+ if (!path || inFlight.size === 0) return false;
+ const target = String(path);
+ if (inFlight.has(target)) return true;
+ const dest = destPathForPartial(target);
+ if (dest !== target && inFlight.has(dest)) return true;
+ if (!matchNested) return false;
+ for (const key of inFlight.keys()) {
+ // `sep`, not `/`: the sweep hands us paths built with `join`, so on
+ // Windows a hardcoded slash would never match and the GC would be free
+ // to unlink a shard that is still transferring.
+ if (target.startsWith(`${key}${sep}`)) return true;
+ }
+ return false;
+ },
+
+ /** Clears in-flight bookkeeping (used by test suites). */
+ reset: () => inFlight.clear(),
+ };
+
+ downloadSlots.add(slot);
+ return slot;
+}
diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.js
index 56b23c299b..94c6aeafab 100644
--- a/server/lib/mediaValidation.js
+++ b/server/lib/mediaValidation.js
@@ -179,6 +179,13 @@ export const localLlmSlotstreamStartSchema = z.object({
// no "download whatever" default for a transfer this size.
const slotstreamModelSchema = z.string().trim().min(1).max(200);
export const localLlmSlotstreamDownloadSchema = z.object({ model: slotstreamModelSchema });
+// Cancelling the checkpoint download in progress. `model` is optional because
+// only one checkpoint transfers at a time — an omitted model means "whatever is
+// running", which is what the card's Cancel button next to the one progress bar
+// actually knows.
+export const localLlmSlotstreamCancelSchema = z.object({
+ model: slotstreamModelSchema.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/routes/localLlm.js b/server/routes/localLlm.js
index 567a381268..2a6eaab37d 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -36,6 +36,7 @@ import {
localLlmMtplxStartSchema,
localLlmSlotstreamStartSchema,
localLlmSlotstreamDownloadSchema,
+ localLlmSlotstreamCancelSchema,
localLlmMtplxSearchSchema,
localLlmMtplxPullSchema,
localLlmMtplxRemoveSchema,
@@ -52,7 +53,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 { cancelSlotstreamModelDownload, 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'
@@ -933,6 +934,16 @@ router.post('/slotstream/models/download', asyncHandler(async (req, res) => {
res.json(result)
}))
+// POST /api/local-llm/slotstream/models/download/cancel — a checkpoint download
+// is server-owned so it survives navigation, but a 100 GB+ transfer that is
+// merely SLOW never trips the idle watchdog, and waiting one out is the only
+// other way to release the single transfer slot. Partial files are kept, so a
+// later download resumes rather than restarting.
+router.post('/slotstream/models/download/cancel', asyncHandler(async (req, res) => {
+ const { model } = validateRequest(localLlmSlotstreamCancelSchema, req.body)
+ res.json({ success: true, cancelled: cancelSlotstreamModelDownload({ model }) })
+}))
+
// 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
diff --git a/server/services/orphanedPartialGc.js b/server/services/orphanedPartialGc.js
index 3132c8220b..72066e2ae7 100644
--- a/server/services/orphanedPartialGc.js
+++ b/server/services/orphanedPartialGc.js
@@ -14,16 +14,17 @@
import { dirname } from 'path';
import { PATHS } from '../lib/fileUtils.js';
-import { sweepOrphanedPartials, ORPHANED_PARTIAL_MAX_AGE_MS } from '../lib/downloadPreflight.js';
+import { isAnyDownloadInFlight, sweepOrphanedPartials, ORPHANED_PARTIAL_MAX_AGE_MS } from '../lib/downloadPreflight.js';
import { SPEC_DECODE_PRESETS, SPEC_MODEL_ROLES } from '../lib/specDecodePresets.js';
-import {
- resolveSpecModelPath,
- isSpecDecodeDownloadInFlight,
-} from './specDecodeModels.js';
+import { resolveSpecModelPath } 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';
+// Side-effect import: constructing the module is what registers its download
+// slot with `isAnyDownloadInFlight`, and an unregistered slot's live shards are
+// unprotected from the sweep below. `orphanedPartialGc.test.js` fails if a
+// module calling `createDownloadSlot` stops being reachable from here.
+import './slotstreamModelManager.js';
import { createSweepScheduler } from './sweepScheduler.js';
export { ORPHANED_PARTIAL_MAX_AGE_MS };
@@ -63,11 +64,10 @@ export async function sweepOrphanedDownloadPartials({
dirs = null,
} = {}) {
const targets = dirs || await collectPartialSweepDirs();
- return sweepOrphanedPartials(targets, {
- now,
- maxAgeMs,
- isProtected: (path) => isSpecDecodeDownloadInFlight(path) || isSlotstreamDownloadInFlight(path),
- });
+ // One predicate for every runtime: each download slot registers itself, so a
+ // new weight-download path is protected the moment it exists rather than when
+ // somebody remembers to add a clause here.
+ return sweepOrphanedPartials(targets, { now, maxAgeMs, isProtected: isAnyDownloadInFlight });
}
const runSweep = async () => {
diff --git a/server/services/orphanedPartialGc.test.js b/server/services/orphanedPartialGc.test.js
new file mode 100644
index 0000000000..a39c63215e
--- /dev/null
+++ b/server/services/orphanedPartialGc.test.js
@@ -0,0 +1,118 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtemp, mkdir, readdir, rm, utimes, writeFile } from 'fs/promises';
+import { readFileSync, readdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { dirname, join, resolve } from 'path';
+import { fileURLToPath } from 'url';
+import { staticImportClosure } from '../lib/staticImportGraph.js';
+
+vi.mock('./hfToken.js', () => ({ getHfToken: async () => null }));
+
+const { sweepOrphanedDownloadPartials } = await import('./orphanedPartialGc.js');
+const { downloadSlotstreamModel, _resetSlotstreamDownloadsForTests } = await import('./slotstreamModelManager.js');
+
+const SERVER_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const GC_ENTRY = join(SERVER_DIR, 'services', 'orphanedPartialGc.js');
+
+const REPO = 'mlx-community/Qwen3-30B-A3B-4bit';
+const DIR_NAME = 'mlx-community__Qwen3-30B-A3B-4bit';
+const SHARD = 'S'.repeat(4096);
+
+const ANCIENT = Date.now() - 30 * 24 * 60 * 60 * 1000;
+
+let sweepDir;
+
+beforeEach(async () => {
+ sweepDir = await mkdtemp(join(tmpdir(), 'partial-gc-'));
+ _resetSlotstreamDownloadsForTests();
+});
+
+afterEach(async () => {
+ await rm(sweepDir, { recursive: true, force: true });
+ vi.unstubAllGlobals();
+});
+
+const writeAgedPartial = async (path) => {
+ await mkdir(dirname(path), { recursive: true });
+ await writeFile(path, 'leftover');
+ await utimes(path, new Date(ANCIENT), new Date(ANCIENT));
+};
+
+describe('sweepOrphanedDownloadPartials', () => {
+ it('unlinks an abandoned partial nobody is downloading', async () => {
+ await writeAgedPartial(join(sweepDir, 'weights.gguf.partial'));
+ expect(await sweepOrphanedDownloadPartials({ dirs: [sweepDir] })).toMatchObject({ deleted: 1 });
+ expect(await readdir(sweepDir)).toEqual([]);
+ });
+
+ // The regression this uniquely catches: the sweep used to consult one
+ // `isXDownloadInFlight` clause per runtime, so a runtime whose clause nobody
+ // added had its live transfer unlinked mid-write. The shared predicate makes
+ // protection automatic — this proves it covers a slot the GC never names.
+ it('protects a shard a live Slotstream download is writing, without naming Slotstream', async () => {
+ const shardPartial = join(sweepDir, DIR_NAME, 'model.safetensors.partial');
+ let release;
+ const gate = new Promise((r) => { release = r; });
+ vi.stubGlobal('fetch', vi.fn(async (url) => {
+ const href = String(url);
+ if (href.startsWith('https://huggingface.co/api/models/')) {
+ return new Response(JSON.stringify({
+ id: REPO,
+ siblings: [{ rfilename: 'model.safetensors', lfs: { size: SHARD.length } }],
+ }), { status: 200, headers: { 'content-type': 'application/json' } });
+ }
+ const body = new ReadableStream({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode(SHARD.slice(0, 512)));
+ gate.then(() => controller.error(new Error('aborted')));
+ },
+ });
+ return new Response(body, { status: 200, headers: { 'content-length': String(SHARD.length) } });
+ }));
+
+ const download = downloadSlotstreamModel({ model: REPO, cacheDir: sweepDir });
+ await vi.waitFor(async () => expect(await readdir(join(sweepDir, DIR_NAME))).toContain('model.safetensors.partial'));
+ // Age it past the gate so ONLY the in-flight protection can save it.
+ await utimes(shardPartial, new Date(ANCIENT), new Date(ANCIENT));
+
+ expect(await sweepOrphanedDownloadPartials({ dirs: [sweepDir] }))
+ .toMatchObject({ deleted: 0, keptProtected: 1 });
+ expect(await readdir(join(sweepDir, DIR_NAME))).toContain('model.safetensors.partial');
+
+ release();
+ await download;
+ });
+});
+
+const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
+const serverSourceFiles = (dir = SERVER_DIR, out = []) => {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ if (entry.isDirectory()) {
+ if (SKIP_DIRS.has(entry.name) || entry.name.startsWith('.')) continue;
+ serverSourceFiles(join(dir, entry.name), out);
+ } else if (entry.name.endsWith('.js') && !entry.name.endsWith('.test.js')) {
+ out.push(join(dir, entry.name));
+ }
+ }
+ return out;
+};
+
+describe('download-slot registration', () => {
+ // `isAnyDownloadInFlight` can only answer for slots that have been
+ // CONSTRUCTED, and a module's slot is constructed when the module is loaded.
+ // So the one thing a new weight-download path must still do is be reachable
+ // from the GC — which is exactly the wiring the shared predicate was meant to
+ // stop people forgetting. Assert it structurally rather than by convention.
+ it('reaches every module that creates a download slot', () => {
+ const owners = serverSourceFiles().filter((file) => readFileSync(file, 'utf8').includes('createDownloadSlot('));
+ // Positive control: a resolver gap must not make this guard look clean.
+ expect(owners.length).toBeGreaterThanOrEqual(2);
+
+ const reached = staticImportClosure(GC_ENTRY).files;
+ for (const owner of owners) {
+ // `downloadPreflight.js` declares the factory; the rest call it.
+ if (owner.endsWith(join('lib', 'downloadPreflight.js'))) continue;
+ expect(reached.has(owner), `${owner} creates a download slot but orphanedPartialGc.js never loads it, so its live transfers are unprotected`).toBe(true);
+ }
+ });
+});
diff --git a/server/services/slotstreamModelManager.js b/server/services/slotstreamModelManager.js
index b420d6f6ac..00e651393c 100644
--- a/server/services/slotstreamModelManager.js
+++ b/server/services/slotstreamModelManager.js
@@ -25,6 +25,7 @@ import { ServerError } from '../lib/errorHandler.js';
import {
assessDownloadPreflight,
assertDownloadFits,
+ createDownloadSlot,
partialPathFor,
siblingDownloadMeta,
streamResumableDownload,
@@ -42,24 +43,34 @@ 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();
+/**
+ * The one download slot, keyed by checkpoint directory.
+ *
+ * `exclusive`: these are 100 GB+ reads of the same disk, and the card renders a
+ * single progress bar fed by a single `slotstream:download` event — two
+ * concurrent transfers would interleave frames on it and the first terminal
+ * frame would tear down the other's bar. `matchNested`: the orphaned-partial
+ * sweep asks about a SHARD one level below the checkpoint directory, so the
+ * predicate has to match a path under a claimed key, not only the key itself.
+ *
+ * The stall watchdog is generous — a checkpoint this size legitimately runs for
+ * hours while it IS receiving bytes — and env-overridable.
+ */
+const downloadSlot = createDownloadSlot({
+ codePrefix: 'SLOTSTREAM',
+ idleStallEnvVar: 'SLOTSTREAM_IDLE_STALL_MS',
+ exclusive: true,
+ matchNested: true,
+ // A cancel here abandons a 100 GB+ multi-shard transfer, not one file: the
+ // whole point of stopping a slow-but-alive download is to pick it back up, so
+ // the shard in flight keeps its `.partial` the way a stall already does.
+ // (Spec-decode deliberately discards instead — one GGUF the user gave up on.)
+ keepPartialOnCancel: true,
+ cancelledMessage: 'Download cancelled. Its progress is kept: pressing download again resumes from where it stopped.',
+});
const cacheDirFor = (cacheDir) => cacheDir || slotstreamCacheDir();
@@ -214,27 +225,24 @@ export async function downloadSlotstreamModel({ model = null, cacheDir, onProgre
// the same disk, and the card renders a single progress bar fed by a single
// `slotstream:download` event — two concurrent transfers would interleave
// frames on it and the first terminal frame would tear down the other's bar.
- if (inFlight.size > 0) {
- throw new ServerError(
- inFlight.has(modelDir)
- ? `${repo} is already downloading.`
- : 'Another Slotstream checkpoint is already downloading — PortOS fetches one at a time.',
- { 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(), stalled: false };
- inFlight.set(modelDir, state);
+ // and a second press landing inside that window would clear the in-flight
+ // check and start a parallel copy of the same 100 GB+ transfer.
+ const slot = downloadSlot.claim(modelDir, {
+ busyMessage: `${repo} is already downloading.`,
+ otherBusyMessage: 'Another Slotstream checkpoint is already downloading — PortOS fetches one at a time.',
+ meta: { repo },
+ });
const label = slotstreamCatalogEntry(repo)?.label || repo;
- let lastEmit = 0;
+ const emitProgress = slot.throttle(onProgress);
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 });
+ slot.throwIfAborted();
+ const plan = await planRepoDownload({ repo, token, signal: slot.signal, cacheDir });
+ slot.throwIfAborted();
const carried = plan.finishedBytes + plan.partialBytes;
assertDownloadFits(await assessDownloadPreflight({
destPath: plan.modelDir,
@@ -267,24 +275,18 @@ export async function downloadSlotstreamModel({ model = null, cacheDir, onProgre
headers,
destPath: entry.destPath,
expectedSha256: entry.sha256,
- signal: state.controller.signal,
- idleStallTimeoutMs: IDLE_STALL_TIMEOUT_MS,
- onIdleStall: () => {
- state.stalled = true;
- state.controller.abort();
- },
onHttpError: hfDownloadHttpError,
+ ...slot.downloadOptions(),
onBytes: (received) => {
- const now = Date.now();
- if (now - lastEmit < PROGRESS_INTERVAL_MS) return;
- lastEmit = now;
- onProgress({
+ // Clamped: a file whose size the Hub never reported contributes
+ // nothing to `total` but real bytes as it lands, which would
+ // otherwise walk the bar past 100%.
+ const done = Math.min(plan.totalBytes, completedBytes + Math.max(0, received - resumedFrom));
+ slot.track(done, plan.totalBytes);
+ emitProgress({
event: 'progress',
model: repo,
- // Clamped: a file whose size the Hub never reported contributes
- // nothing to `total` but real bytes as it lands, which would
- // otherwise walk the bar past 100%.
- received: Math.min(plan.totalBytes, completedBytes + Math.max(0, received - resumedFrom)),
+ received: done,
total: plan.totalBytes,
message: `Downloading ${entry.file}`,
});
@@ -310,43 +312,45 @@ export async function downloadSlotstreamModel({ model = null, cacheDir, onProgre
sizeBytes: plan.totalBytes,
};
} catch (err) {
- const error = state.stalled ? stalledError() : err;
- console.error(`❌ Slotstream checkpoint download failed for ${repo}: ${error.message}`);
- onProgress({ event: 'error', model: repo, message: error.message });
- return { success: false, model: repo, error: error.message, code: error.code || null };
+ const error = slot.wrapError(err);
+ if (slot.cancelled) {
+ console.log(`⏹️ Slotstream checkpoint download cancelled: ${repo}`);
+ } else {
+ console.error(`❌ Slotstream checkpoint download failed for ${repo}: ${error.message}`);
+ }
+ // A cancel is not a failure the user needs a red toast for, but the bar
+ // still has to come down — the card clears on any terminal frame, and
+ // 'cancelled' is what tells it which happened.
+ onProgress({
+ event: slot.cancelled ? 'cancelled' : 'error',
+ model: repo,
+ message: error.message,
+ });
+ return { success: false, model: repo, cancelled: slot.cancelled, error: error.message, code: error.code || null };
} finally {
- inFlight.delete(modelDir);
+ slot.release();
}
}
/**
- * The watchdog's abort reaches the catch as a generic AbortError, which says
- * nothing useful; this is what the user is told instead. There is deliberately
- * no user-facing cancel yet — the stall watchdog is the only thing that aborts
- * a transfer, so `state.stalled` is the only reason this fires.
+ * Stop the checkpoint download in progress. Returns false when none is running.
+ *
+ * A 100 GB+ transfer that is merely SLOW rather than silent never trips the idle
+ * watchdog, so without this the only way out was to wait it out. The partial
+ * files are kept — `streamResumableDownload` discards only the shard it was
+ * mid-write on — so pressing download again resumes.
+ *
+ * `model` is optional: the slot holds one transfer at a time, so an omitted
+ * model cancels whatever is running. A named model that is NOT the running one
+ * cancels nothing rather than stopping someone else's transfer.
*/
-function stalledError() {
- const minutes = Math.round(IDLE_STALL_TIMEOUT_MS / 60000);
- return new ServerError(
- `Download stalled — no bytes received for ${minutes} minute${minutes === 1 ? '' : 's'}, so it was abandoned. Its progress is kept: pressing download again resumes from where it stopped.`,
- { status: 504, code: 'SLOTSTREAM_DOWNLOAD_STALLED' },
- );
+export function cancelSlotstreamModelDownload({ model = null, cacheDir } = {}) {
+ if (model == null) return downloadSlot.entries().some(([key]) => downloadSlot.cancel(key));
+ return downloadSlot.cancel(slotstreamModelPath(requireRepo(model), { cacheDir }));
}
/** 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()) {
- // `sep`, not `/`: the sweep hands us paths built with `join`, so on Windows
- // a hardcoded slash would never match and the GC would be free to unlink a
- // shard that is still transferring.
- if (target === modelDir || target.startsWith(`${modelDir}${sep}`)) return true;
- }
- return false;
-}
+export const isSlotstreamDownloadInFlight = (path) => downloadSlot.isInFlight(path);
/** Clears in-flight download bookkeeping (used by test suites). */
-export function _resetSlotstreamDownloadsForTests() {
- inFlight.clear();
-}
+export const _resetSlotstreamDownloadsForTests = () => downloadSlot.reset();
diff --git a/server/services/slotstreamModelManager.test.js b/server/services/slotstreamModelManager.test.js
index 79369625be..7a7ebacde9 100644
--- a/server/services/slotstreamModelManager.test.js
+++ b/server/services/slotstreamModelManager.test.js
@@ -7,6 +7,7 @@ vi.mock('./hfToken.js', () => ({ getHfToken: async () => null }));
const { listSlotstreamCachedModels } = await import('../lib/slotstreamModels.js');
const {
+ cancelSlotstreamModelDownload,
downloadSlotstreamModel,
previewSlotstreamDownload,
isSlotstreamDownloadInFlight,
@@ -206,6 +207,55 @@ describe('downloadSlotstreamModel', () => {
expect((await first).success).toBe(true);
});
+ // Before the shared download slot, Slotstream had no cancel at all: the idle
+ // watchdog was the only thing that could abort a transfer, so a 100 GB+ pull
+ // that was merely SLOW could only be waited out.
+ it('cancels a running checkpoint download and keeps its partial for a resume', async () => {
+ let release;
+ const gate = new Promise((resolve) => { release = resolve; });
+ vi.stubGlobal('fetch', vi.fn(async (url) => {
+ const href = String(url);
+ if (href.startsWith('https://huggingface.co/api/models/')) return metadataResponse();
+ if (href.endsWith('/config.json')) {
+ return new Response(CONFIG, { status: 200, headers: { 'content-length': String(CONFIG.length) } });
+ }
+ // The shard streams its first chunk, then hangs until the cancel aborts it.
+ const body = new ReadableStream({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode(SHARD.slice(0, 512)));
+ gate.then(() => controller.error(new Error('aborted')));
+ },
+ });
+ return new Response(body, { status: 200, headers: { 'content-length': String(SHARD.length) } });
+ }));
+
+ const frames = [];
+ const download = downloadSlotstreamModel({ model: REPO, cacheDir, onProgress: (f) => frames.push(f) });
+ // Wait until the shard is genuinely mid-write: the slot is claimed before
+ // the metadata round trip, so an in-flight check alone would cancel before
+ // any bytes exist and prove nothing about what a cancel preserves.
+ const shardPartial = join(cacheDir, DIR_NAME, 'model.safetensors.partial');
+ await vi.waitFor(async () => expect((await readFile(shardPartial, 'utf8')).length).toBeGreaterThan(0));
+
+ expect(cancelSlotstreamModelDownload({ model: REPO, cacheDir })).toBe(true);
+ release();
+ const result = await download;
+
+ expect(result.success).toBe(false);
+ expect(result.cancelled).toBe(true);
+ expect(result.code).toBe('SLOTSTREAM_DOWNLOAD_CANCELLED');
+ expect(frames.at(-1).event).toBe('cancelled');
+ expect(isSlotstreamDownloadInFlight(join(cacheDir, DIR_NAME))).toBe(false);
+ // The bytes that landed are kept, so pressing download again resumes rather
+ // than restarting a multi-gigabyte shard from zero.
+ expect((await readFile(shardPartial, 'utf8')).length).toBeGreaterThan(0);
+ });
+
+ it('reports no cancellation when nothing is downloading', () => {
+ expect(cancelSlotstreamModelDownload({ model: REPO, cacheDir })).toBe(false);
+ expect(cancelSlotstreamModelDownload()).toBe(false);
+ });
+
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
diff --git a/server/services/specDecodeModels.js b/server/services/specDecodeModels.js
index 8666e23046..909f51bde7 100644
--- a/server/services/specDecodeModels.js
+++ b/server/services/specDecodeModels.js
@@ -20,6 +20,7 @@ import { ServerError } from '../lib/errorHandler.js';
import {
assessDownloadPreflight,
assertDownloadFits,
+ createDownloadSlot,
probeRemoteSize,
siblingDownloadMeta,
streamResumableDownload,
@@ -34,23 +35,17 @@ import {
specDecodeSource,
} from '../lib/specDecodePresets.js';
-// Progress frames are throttled to this interval so a fast link can't flood the
-// socket with a frame per chunk.
-const PROGRESS_INTERVAL_MS = 250;
-
-// A download that is still receiving bytes may legitimately run for hours, but
-// a silent connection is never useful: it holds the one transfer slot and
-// leaves every later click permanently queued. Keep this intentionally
-// generous and configurable for slow Hugging Face/CDN handshakes.
-const IDLE_STALL_TIMEOUT_MS = (() => {
- const raw = Number(process.env.SPEC_DECODE_IDLE_STALL_MS);
- return Number.isFinite(raw) && raw > 0 ? raw : 20 * 60 * 1000;
-})();
-
// Downloads in flight, keyed by RESOLVED destination path (two presets can name
// the same base model, and both must show the one transfer rather than starting
-// a second copy of it).
-const inFlight = new Map();
+// a second copy of it). The stall timeout stays intentionally generous and
+// env-configurable for slow Hugging Face/CDN handshakes.
+const downloadSlot = createDownloadSlot({
+ codePrefix: 'SPEC',
+ idleStallEnvVar: 'SPEC_DECODE_IDLE_STALL_MS',
+ stalledMessage: (minutes) => (
+ `Download stalled — no bytes received for ${minutes} minute${minutes === 1 ? '' : 's'}; cancelled so another model can download`
+ ),
+});
/**
* Absolute path a launcher field refers to. Relative paths resolve against the
@@ -70,7 +65,7 @@ const describeEntry = async (presetId, role) => {
if (!entry?.path) return null;
const destPath = resolveSpecModelPath(entry.path);
const stats = await stat(destPath).catch(() => null);
- const active = inFlight.get(destPath);
+ const active = downloadSlot.get(destPath);
return {
role,
path: entry.path,
@@ -172,18 +167,15 @@ const hfDownloadHttpError = (res) => {
throw new ServerError(`Hugging Face download failed: ${res.status} ${res.statusText}`, { status: 502, code: 'HF_DOWNLOAD_FAILED' });
};
-const streamToFile = async ({ url, headers, destPath, onBytes, signal, onIdleStall, expectedSha256, isCancelled }) => (
+const streamToFile = async ({ url, headers, destPath, onBytes, expectedSha256, slot }) => (
streamResumableDownload({
url,
headers,
destPath,
onBytes,
- signal,
- onIdleStall,
- idleStallTimeoutMs: IDLE_STALL_TIMEOUT_MS,
expectedSha256,
- isCancelled,
onHttpError: hfDownloadHttpError,
+ ...slot.downloadOptions(),
})
);
@@ -213,21 +205,6 @@ const resolveSpecDownloadPlan = async ({ source, destPath, token, signal }) => {
return { file, url, headers, meta, preflight };
};
-const downloadAbortError = (state) => {
- if (state.abortReason === 'cancelled') {
- return new ServerError('Download cancelled', { status: 409, code: 'SPEC_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 model can download`,
- { status: 504, code: 'SPEC_DOWNLOAD_STALLED' },
- );
-};
-
-const throwIfAborted = (state) => {
- if (state.controller.signal.aborted) throw downloadAbortError(state);
-};
-
/**
* Download one preset role's GGUF into the path the launcher expects.
*
@@ -250,36 +227,30 @@ export async function downloadSpecDecodeModel({ presetId, role, onProgress = ()
if (existing) {
return { success: true, alreadyDownloaded: true, path: source.path, sizeBytes: existing.size };
}
- if (inFlight.has(destPath)) {
- throw new ServerError(`${source.path} is already downloading`, { status: 409, code: 'SPEC_DOWNLOAD_IN_FLIGHT' });
- }
// Claim the slot BEFORE the first await. Resolving the repo on Hugging Face
// takes a round trip, and a second click (or a second tab) landing inside that
- // window would clear the check above and start a parallel multi-gigabyte
+ // window would clear the in-flight check and start a parallel multi-gigabyte
// transfer of the same file. Everything after this point runs inside the
// try/finally so the claim is always released.
- const state = {
- presetId,
- role,
- received: 0,
- total: 0,
- controller: new AbortController(),
- abortReason: null,
- };
- inFlight.set(destPath, state);
+ const slot = downloadSlot.claim(destPath, {
+ busyMessage: `${source.path} is already downloading`,
+ meta: { presetId, role },
+ });
- let lastEmit = 0;
+ const emitProgress = slot.throttle((received, total) => {
+ onProgress({ event: 'progress', presetId, role, path: source.path, received, total });
+ });
try {
const token = await getHfToken();
- throwIfAborted(state);
+ slot.throwIfAborted();
onProgress({ event: 'start', presetId, role, path: source.path, message: `Resolving ${source.repo} on Hugging Face…` });
const plan = await resolveSpecDownloadPlan({
source,
destPath,
token,
- signal: state.controller.signal,
+ signal: slot.signal,
});
- throwIfAborted(state);
+ slot.throwIfAborted();
assertDownloadFits(plan.preflight);
console.log(`⬇️ Downloading speculative-decoding weights ${source.repo}/${plan.file} → ${source.path}`);
const { bytes } = await streamToFile({
@@ -287,36 +258,27 @@ export async function downloadSpecDecodeModel({ presetId, role, onProgress = ()
headers: plan.headers,
destPath,
expectedSha256: plan.meta.sha256,
- signal: state.controller.signal,
- isCancelled: () => state.abortReason === 'cancelled',
- onIdleStall: () => {
- state.abortReason = 'stalled';
- state.controller.abort();
- },
+ slot,
onBytes: (received, total) => {
- state.received = received;
- state.total = total;
- const now = Date.now();
- if (now - lastEmit < PROGRESS_INTERVAL_MS) return;
- lastEmit = now;
- onProgress({ event: 'progress', presetId, role, path: source.path, received, total });
+ slot.track(received, total);
+ emitProgress(received, total);
},
});
onProgress({ event: 'complete', presetId, role, path: source.path, received: bytes, total: bytes, message: `${source.path} downloaded` });
console.log(`✅ Speculative-decoding weights ready: ${source.path} (${bytes} bytes)`);
return { success: true, path: source.path, repo: source.repo, file: plan.file, sizeBytes: bytes };
} catch (err) {
- const error = state.abortReason ? downloadAbortError(state) : err;
- const event = state.abortReason === 'cancelled' ? 'cancelled' : 'error';
+ const error = slot.wrapError(err);
+ const event = slot.cancelled ? 'cancelled' : 'error';
onProgress({ event, presetId, role, path: source.path, message: error.message });
- if (state.abortReason === 'cancelled') {
+ if (slot.cancelled) {
console.log(`⏹️ Speculative-decoding download cancelled: ${source.path}`);
} else {
console.error(`❌ Speculative-decoding download failed for ${source.path}: ${error.message}`);
}
throw error;
} finally {
- inFlight.delete(destPath);
+ slot.release();
}
}
@@ -370,24 +332,11 @@ export function cancelSpecDecodeModelDownload({ presetId, role }) {
}
const source = specDecodeSource(presetId, role);
if (!source) return false;
- const state = inFlight.get(resolveSpecModelPath(source.path));
- if (!state) return false;
- state.abortReason = 'cancelled';
- state.controller.abort();
- return true;
+ return downloadSlot.cancel(resolveSpecModelPath(source.path));
}
/** True while a curated GGUF download is writing `destPath` (or its `.partial`). */
-export function isSpecDecodeDownloadInFlight(destPath) {
- if (!destPath) return false;
- if (inFlight.has(destPath)) return true;
- if (String(destPath).endsWith('.partial')) {
- return inFlight.has(destPath.slice(0, -'.partial'.length));
- }
- return false;
-}
+export const isSpecDecodeDownloadInFlight = (destPath) => downloadSlot.isInFlight(destPath);
/** Clears in-flight download bookkeeping (used by test suites). */
-export function _resetSpecDecodeDownloadsForTests() {
- inFlight.clear();
-}
+export const _resetSpecDecodeDownloadsForTests = () => downloadSlot.reset();