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
fix: correct Slotstream download byte accounting and hide unfinished checkpoints
Adam Eivyec32dd77f892
diff --git a/.env.example b/.env.exampleindex ae0783973d..7883c2ded6 100644--- a/.env.example+++ b/.env.example@@ -194,6 +194,12 @@ PGPASSWORD=portos# ~/.slotstream/models). The binary always lives in ~/.slotstream/bin.# SLOTSTREAM_MODEL_DIR=/path/to/slotstream/models+# Abandon a Slotstream checkpoint download after this many milliseconds with no+# bytes received (slotstreamModelManager.js; default: 1200000 / 20 minutes). A+# transfer that is still receiving bytes is never cut off by this, and an+# abandoned one keeps its progress so a retry resumes rather than restarts.+# SLOTSTREAM_IDLE_STALL_MS=1200000+# Abort a speculative-decoding model download after this many milliseconds with# no bytes received (specDecodeModels.js; default: 1200000 / 20 minutes). Raise# it for a slow Hugging Face/CDN handshake; a download still receiving bytes isdiff --git a/client/src/components/settings/LocalLlmRuntimesView.jsx b/client/src/components/settings/LocalLlmRuntimesView.jsxindex f0e2a8d0b7..a876f56ce4 100644--- a/client/src/components/settings/LocalLlmRuntimesView.jsx+++ b/client/src/components/settings/LocalLlmRuntimesView.jsx@@ -337,8 +337,10 @@ 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.+ // The route awaits the whole transfer, so this request runs for as long as the+ // download does; the bar is driven by `slotstream:download` (subscribed above)+ // rather than by the spinner, and the terminal frame clears it first. The+ // clear below is the belt for a socket that dropped mid-transfer.const startSlotstreamDownload = (model) => runAction('slotstream-download',() => downloadSlotstreamModel(model).then((r) => {diff --git a/client/src/components/settings/SlotstreamServerCard.jsx b/client/src/components/settings/SlotstreamServerCard.jsxindex 5ab3e1bf06..a8678ca2f7 100644--- a/client/src/components/settings/SlotstreamServerCard.jsx+++ b/client/src/components/settings/SlotstreamServerCard.jsx@@ -201,44 +201,6 @@ 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>)}@@ -268,6 +230,45 @@ export default function SlotstreamServerCard({</div>)}+ {status?.installed && status?.supported !== false && catalog.length > 0 && onDownloadModel && (+ <div className="bg-port-bg border border-port-border rounded-lg p-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?.recentLogs?.length > 0 && (<div className="space-y-1"><buttondiff --git a/client/src/components/settings/SlotstreamServerCard.test.jsx b/client/src/components/settings/SlotstreamServerCard.test.jsxindex 98309a2e88..24d64c1d94 100644--- a/client/src/components/settings/SlotstreamServerCard.test.jsx+++ b/client/src/components/settings/SlotstreamServerCard.test.jsx@@ -112,6 +112,25 @@ describe('SlotstreamServerCard', () => {expect(screen.getByText('5 GB of 20 GB (25%)')).toBeInTheDocument();});+ it('offers a download while the server is running, so a second checkpoint needs no stop', () => {+ renderCard({+ installed: true,+ running: true,+ supported: true,+ endpoint: 'http://127.0.0.1:5564/v1',+ cachedModels: ['qwen-moe'],+ catalog: CATALOG,+ });+ expect(screen.getByLabelText('Add a checkpoint')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /Stop Slotstream/ })).toBeInTheDocument();+ });++ it('leaves the picker out when the runtime is not installed', () => {+ renderCard({ installed: false, running: false, supported: true, catalog: CATALOG });+ expect(screen.queryByLabelText('Add a checkpoint')).toBeNull();+ expect(screen.getByRole('button', { name: /Install Slotstream/ })).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.diff --git a/server/lib/huggingfaceLora.js b/server/lib/huggingfaceLora.jsindex ba0ca6ff38..4955b13e89 100644--- a/server/lib/huggingfaceLora.js+++ b/server/lib/huggingfaceLora.js@@ -31,6 +31,17 @@ export const HF_LORA_FAMILIES = Object.freeze([]);export const HF_API = 'https://huggingface.co/api/models';++/**+ * `owner/name` — the only shape PortOS hands to an HF download or an argv slot.+ *+ * Each segment must START alphanumeric, so neither `owner/..` (which a path+ * walk would follow out of a cache directory) nor a leading `-` (which an+ * argument parser would read as a flag) can get through. One definition because+ * two copies of a security rule drift: the MTPLX pull/remove schema and the+ * Slotstream checkpoint catalog both validate against this.+ */+export const HF_REPO_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._-]*$/;const HF_HOSTS = new Set(['huggingface.co', 'www.huggingface.co']);// Parse any HuggingFace ref shape into `{ repo, revision, file }`:diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.jsindex 3658a581c5..56b23c299b 100644--- a/server/lib/mediaValidation.js+++ b/server/lib/mediaValidation.js@@ -13,6 +13,7 @@ import { PORTS } from './ports.js';import { ASSESSABLE_RUNTIMES } from './localProviderRuntime.js';import { SWEEP_SCOPES } from './localModelAssessment.js';import { CAPABILITY_TEST_IDS } from './modelCapabilityTests.js';+import { HF_REPO_ID_RE } from './huggingfaceLora.js';// iMessage ingestion config (#2151) — the `settings.imessage` slice. Sync is OFF// by default and only reads chat.db when enabled (needs macOS Full Disk Access).@@ -176,9 +177,8 @@ export const localLlmSlotstreamStartSchema = z.object({// 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),-});+const slotstreamModelSchema = z.string().trim().min(1).max(200);+export const localLlmSlotstreamDownloadSchema = z.object({ model: slotstreamModelSchema });// 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({@@ -190,7 +190,7 @@ export const localLlmMtplxSearchSchema = z.object({// the same one the provider-readiness checklist pulls — so the two surfaces// cannot fetch different weights. A named model must be a Hugging Face repo id.const mtplxRepoIdSchema = z.string().trim().min(1).max(200).regex(- /^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._-]*$/,+ HF_REPO_ID_RE,'model must be a Hugging Face repo id (owner/name)',);export const localLlmMtplxPullSchema = z.object({@@ -254,7 +254,7 @@ export const localLlmDownloadPreflightSchema = z.discriminatedUnion('kind', [}),z.object({kind: z.literal('slotstream'),- model: z.string().trim().min(1).max(200),+ model: slotstreamModelSchema,}),z.object({kind: z.literal('install'),diff --git a/server/lib/slotstreamCatalog.js b/server/lib/slotstreamCatalog.jsindex a21552cecb..069f6e1005 100644--- a/server/lib/slotstreamCatalog.js+++ b/server/lib/slotstreamCatalog.js@@ -11,6 +11,8 @@* against a plain sibling list.*/+import { HF_REPO_ID_RE } from './huggingfaceLora.js';+/*** Curated streaming candidates.*@@ -50,16 +52,8 @@ export const SLOTSTREAM_CATALOG = Object.freeze([}),]);-/**- * `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);+/** `owner/name`, the only shape a download is given — see `HF_REPO_ID_RE`. */+export const isSlotstreamRepoId = (value) => typeof value === 'string' && HF_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) {@@ -116,8 +110,14 @@ export function selectSlotstreamRepoFiles(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();+ // De-duplicated: a repeated sibling would otherwise be counted twice toward+ // the size the user approves and fetched twice.+ return [...new Set(+ names+ // Split on BOTH separators: a `..\` segment is not a traversal on the+ // supported platform, but the guard should not be the thing that depends+ // on which platform this runs on.+ .filter((name) => !/^[/\\]/.test(name) && !name.split(/[/\\]/).includes('..'))+ .filter((name) => KEEP_FILE_RE.test(name) && !SKIP_PATH_RE.test(name)),+ )].sort();}diff --git a/server/lib/slotstreamModels.js b/server/lib/slotstreamModels.jsindex d92a2f328b..f771c363c2 100644--- a/server/lib/slotstreamModels.js+++ b/server/lib/slotstreamModels.js@@ -62,6 +62,23 @@ export function planSlotstreamMemory({ totalBytes, overrideGb } = {}) {};}+/**+ * Whether a cache subdirectory holds something a start could actually serve.+ *+ * A `.partial` (or its `.etag` sidecar) means a download is running or was+ * abandoned mid-file, so the directory is NOT a checkpoint yet — listing it+ * would clear the card's empty-cache warning and offer `--model` a directory+ * that exits before binding a port. A directory with no completed file at all+ * is the same story. A hand-placed checkpoint never carries a `.partial`, so+ * this cannot hide one.+ */+async function isServableCheckpoint(dir) {+ const entries = await readdir(dir).catch(() => null);+ if (!entries) return false;+ const complete = entries.filter((name) => !name.endsWith('.partial') && !name.endsWith('.partial.etag'));+ return complete.length > 0 && complete.length === entries.length;+}+/*** Cached checkpoints on disk.*@@ -84,6 +101,7 @@ export async function listSlotstreamCachedModels({ cacheDir } = {}) {const full = join(dir, name);const info = await stat(full).catch(() => null);if (!info?.isDirectory()) continue;+ if (!(await isServableCheckpoint(full))) continue;models.push({ id: name, path: full });}return { models, error: null };diff --git a/server/lib/slotstreamModels.test.js b/server/lib/slotstreamModels.test.jsindex 6474ea184d..59907e27f7 100644--- a/server/lib/slotstreamModels.test.js+++ b/server/lib/slotstreamModels.test.js@@ -49,11 +49,30 @@ describe('listSlotstreamCachedModels', () => {it('lists checkpoint directories and ignores files', async () => {dir = join(tmpdir(), `portos-slotstream-cache-${Date.now()}`);await mkdir(join(dir, 'qwen-moe'), { recursive: true });+ await writeFile(join(dir, 'qwen-moe', 'model.safetensors'), 'weights');await writeFile(join(dir, 'notes.txt'), 'not a checkpoint');const cache = await listSlotstreamCachedModels({ cacheDir: dir });expect(cache.error).toBeNull();expect(cache.models).toEqual([expect.objectContaining({ id: 'qwen-moe' })]);});++ it('hides a directory a download has not finished filling', async () => {+ // Reporting one would clear the card's empty-cache warning and offer+ // `--model` a directory that exits before it binds a port.+ dir = join(tmpdir(), `portos-slotstream-cache-partial-${Date.now()}`);+ await mkdir(join(dir, 'in-progress'), { recursive: true });+ await writeFile(join(dir, 'in-progress', 'config.json'), '{}');+ await writeFile(join(dir, 'in-progress', 'model.safetensors.partial'), 'half');+ await mkdir(join(dir, 'abandoned'), { recursive: true });+ await writeFile(join(dir, 'abandoned', 'model.safetensors.partial'), 'half');+ await mkdir(join(dir, 'empty'), { recursive: true });+ await mkdir(join(dir, 'complete'), { recursive: true });+ await writeFile(join(dir, 'complete', 'model.safetensors'), 'weights');++ const cache = await listSlotstreamCachedModels({ cacheDir: dir });+ expect(cache.error).toBeNull();+ expect(cache.models.map((m) => m.id)).toEqual(['complete']);+ });});describe('pickSlotstreamCachedModel', () => {diff --git a/server/services/slotstreamModelManager.js b/server/services/slotstreamModelManager.jsindex c2e624a871..c2bf1df4b6 100644--- a/server/services/slotstreamModelManager.js+++ b/server/services/slotstreamModelManager.js@@ -20,7 +20,7 @@*/import { rm, stat } from 'fs/promises';-import { join } from 'path';+import { join, resolve, sep } from 'path';import { ServerError } from '../lib/errorHandler.js';import {assessDownloadPreflight,@@ -90,13 +90,31 @@ const hfDownloadHttpError = (res) => {const fileSize = async (path) => stat(path).then((s) => (s.isFile() ? s.size : 0), () => 0);+/**+ * Whether a file already at `destPath` can be trusted as finished.+ *+ * Only a length matching what the Hub advertises counts. A file of any other+ * length is a dead mid-file write — appending to it would corrupt the shard —+ * and a file whose size the Hub never reported cannot be checked at all, so+ * both are re-fetched rather than assumed complete. The plan and the download+ * loop ask this same question, so what is credited and what is skipped cannot+ * disagree.+ */+const isFinishedOnDisk = async (destPath, expectedBytes) =>+ expectedBytes > 0 && (await fileSize(destPath)) === expectedBytes;+/*** 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.+ * Two counts, deliberately kept apart. `finishedBytes` is files whose length+ * MATCHES what the Hub advertises — the only evidence a file is done, since a+ * leftover of any other length is a write that died mid-file and gets re-fetched+ * from scratch. `partialBytes` is what a `.partial` can resume from. Both credit+ * against the disk a run still needs (reserving the full repo again would make a+ * nearly-full volume refuse a resume it can actually finish), but only+ * `finishedBytes` may say a checkpoint is already downloaded: a full-size+ * `.partial` is a crash between the last byte and the rename, and calling that+ * "already on disk" would disable the very button that completes it.*/async function planRepoDownload({ repo, token, signal, cacheDir }) {const model = await fetchHuggingfaceModel(repo, { token, signal, blobs: true });@@ -120,18 +138,27 @@ async function planRepoDownload({ repo, token, signal, cacheDir }) {const modelDir = slotstreamModelPath(repo, { cacheDir });let totalBytes = 0;- let bytesOnDisk = 0;+ let finishedBytes = 0;+ let partialBytes = 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)));+ // Belt to the name filter's braces: whatever the Hub called this file, the+ // path it resolves to has to stay inside the checkpoint directory.+ if (!resolve(destPath).startsWith(`${resolve(modelDir)}${sep}`)) {+ throw new ServerError(+ `Hugging Face repo ${repo} lists a file whose path escapes the checkpoint directory.`,+ { status: 422, code: 'SLOTSTREAM_UNSAFE_FILENAME' },+ );+ }totalBytes += meta.bytes;- bytesOnDisk += Math.min(onDisk, meta.bytes || onDisk);+ if (await isFinishedOnDisk(destPath, meta.bytes)) finishedBytes += meta.bytes;+ else partialBytes += Math.min(await fileSize(partialPathFor(destPath)), meta.bytes);plan.push({ file, destPath, url: buildHfResolveUrl(repo, 'main', file), ...meta });}- return { modelDir, files: plan, totalBytes, bytesOnDisk };+ return { modelDir, files: plan, totalBytes, finishedBytes, partialBytes };}/**@@ -151,7 +178,7 @@ export async function previewSlotstreamDownload({ model = null, cacheDir } = {})signal: AbortSignal.timeout(METADATA_FETCH_TIMEOUT_MS),cacheDir,});- const remaining = Math.max(0, plan.totalBytes - plan.bytesOnDisk);+ const remaining = Math.max(0, plan.totalBytes - plan.finishedBytes - plan.partialBytes);const assessment = await assessDownloadPreflight({ destPath: plan.modelDir, expectedBytes: remaining });return {@@ -164,7 +191,9 @@ export async function previewSlotstreamDownload({ model = null, cacheDir } = {})destPath: plan.modelDir,repo,files: plan.files.length,- alreadyDownloaded: plan.totalBytes > 0 && remaining === 0,+ // Finished files only — see planRepoDownload. This flag DISABLES Confirm,+ // so counting a `.partial` here would strand a resumable download.+ alreadyDownloaded: plan.totalBytes > 0 && plan.finishedBytes === plan.totalBytes,};}@@ -181,13 +210,22 @@ export async function previewSlotstreamDownload({ model = null, cacheDir } = {})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' });+ // ONE checkpoint at a time, not one per checkpoint: 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.+ 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(), abortReason: null };+ const state = { repo, controller: new AbortController(), stalled: false };inFlight.set(modelDir, state);const label = slotstreamCatalogEntry(repo)?.label || repo;@@ -197,30 +235,31 @@ export async function downloadSlotstreamModel({ model = null, cacheDir, onProgreconst 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 });+ const carried = plan.finishedBytes + plan.partialBytes;assertDownloadFits(await assessDownloadPreflight({destPath: plan.modelDir,- expectedBytes: Math.max(0, plan.totalBytes - plan.bytesOnDisk),+ expectedBytes: Math.max(0, plan.totalBytes - carried),}));console.log(`⬇️ Slotstream checkpoint download started: ${repo} (${plan.files.length} files, ${plan.totalBytes} bytes)`);onProgress({event: 'progress',model: repo,- received: plan.bytesOnDisk,+ received: carried,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;+ // Bytes already accounted for, so the bar reports progress through the whole+ // checkpoint rather than restarting at each file.+ let completedBytes = carried;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(() => {});+ if (await isFinishedOnDisk(entry.destPath, entry.bytes)) continue;+ // Anything else at the destination is a dead mid-file write (or a file+ // whose size the Hub never reported, so completeness is unknowable) —+ // a resume would append to the wrong prefix, so start that one over.+ // `force` makes this a no-op when nothing is there.+ await rm(entry.destPath, { force: true }).catch(() => {});const resumedFrom = await fileSize(partialPathFor(entry.destPath));const { bytes } = await streamResumableDownload({@@ -230,9 +269,8 @@ export async function downloadSlotstreamModel({ model = null, cacheDir, onProgreexpectedSha256: entry.sha256,signal: state.controller.signal,idleStallTimeoutMs: IDLE_STALL_TIMEOUT_MS,- isCancelled: () => state.abortReason === 'cancelled',onIdleStall: () => {- state.abortReason = 'stalled';+ state.stalled = true;state.controller.abort();},onHttpError: hfDownloadHttpError,@@ -243,8 +281,8 @@ export async function downloadSlotstreamModel({ model = null, cacheDir, onProgreonProgress({event: 'progress',model: repo,- // Clamped: a shard discarded for being the wrong length is credited- // once in `bytesOnDisk` and again as it re-transfers, which would+ // 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)),total: plan.totalBytes,@@ -272,23 +310,25 @@ export async function downloadSlotstreamModel({ model = null, cacheDir, onProgresizeBytes: plan.totalBytes,};} catch (err) {- const error = state.abortReason ? abortError(state) : err;- const event = state.abortReason === 'cancelled' ? 'cancelled' : 'error';+ const error = state.stalled ? stalledError() : err;console.error(`❌ Slotstream checkpoint download failed for ${repo}: ${error.message}`);- onProgress({ event, model: repo, message: error.message });+ onProgress({ event: 'error', 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' });- }+/**+ * 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.+ */+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'}; cancelled so another checkpoint can download`,+ `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' },);}diff --git a/server/services/slotstreamModelManager.test.js b/server/services/slotstreamModelManager.test.jsindex f8f571dae7..79369625be 100644--- a/server/services/slotstreamModelManager.test.js+++ b/server/services/slotstreamModelManager.test.js@@ -39,7 +39,7 @@ let fetched;const installFetch = (fileBodies = FILES) => {fetched = [];- globalThis.fetch = vi.fn(async (url) => {+ vi.stubGlobal('fetch', vi.fn(async (url) => {const href = String(url);fetched.push(href);if (href.startsWith('https://huggingface.co/api/models/')) return metadataResponse();@@ -47,7 +47,7 @@ const installFetch = (fileBodies = FILES) => {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 () => {@@ -59,7 +59,6 @@ beforeEach(async () => {afterEach(async () => {await rm(cacheDir, { recursive: true, force: true });vi.unstubAllGlobals();- delete globalThis.fetch;});describe('previewSlotstreamDownload', () => {@@ -92,6 +91,33 @@ describe('previewSlotstreamDownload', () => {expect(preview.requiredBytes).toBeLessThan(preview.expectedBytes + preview.headroomBytes);});+ it('does not credit a truncated leftover — the whole shard is re-fetched', async () => {+ // Crediting it would under-reserve the disk by exactly the bytes the run is+ // about to move again, so the modal could say "fits" on a volume that then+ // fills mid-transfer.+ const modelDir = join(cacheDir, DIR_NAME);+ await mkdir(modelDir, { recursive: true });+ await writeFile(join(modelDir, 'config.json'), CONFIG);+ await writeFile(join(modelDir, 'model.safetensors'), SHARD.slice(0, 2048));++ const preview = await previewSlotstreamDownload({ model: REPO, cacheDir });+ expect(preview.requiredBytes - preview.headroomBytes).toBe(SHARD.length);+ expect(preview.alreadyDownloaded).toBe(false);+ });++ it('does not call a full-size .partial "already downloaded"', async () => {+ // That flag DISABLES Confirm. A partial the size of the whole file is a+ // crash between the last byte and the rename — calling it done would strand+ // the download with no way to finish it from the UI.+ 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);++ const preview = await previewSlotstreamDownload({ model: REPO, cacheDir });+ expect(preview.alreadyDownloaded).toBe(false);+ });+it('marks a fully cached checkpoint as already downloaded', async () => {const modelDir = join(cacheDir, DIR_NAME);await mkdir(modelDir, { recursive: true });@@ -105,10 +131,10 @@ describe('previewSlotstreamDownload', () => {it('refuses a repo that publishes no weights it can stream', async () => {// Config and tokenizer alone would make a checkpoint directory the cache// walk reports as servable and a start then fails on.- globalThis.fetch = vi.fn(async () => new Response(JSON.stringify({+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({id: REPO,siblings: [{ rfilename: 'config.json', size: 10 }, { rfilename: 'pytorch_model.bin', lfs: { size: 999 } }],- }), { status: 200, headers: { 'content-type': 'application/json' } }));+ }), { status: 200, headers: { 'content-type': 'application/json' } })));await expect(previewSlotstreamDownload({ model: REPO, cacheDir })).rejects.toMatchObject({ code: 'SLOTSTREAM_NO_WEIGHTS' });@@ -161,10 +187,10 @@ describe('downloadSlotstreamModel', () => {let release;const gate = new Promise((resolve) => { release = resolve; });const realFetch = globalThis.fetch;- globalThis.fetch = vi.fn(async (url) => {+ vi.stubGlobal('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.@@ -172,6 +198,10 @@ describe('downloadSlotstreamModel', () => {await expect(downloadSlotstreamModel({ model: REPO, cacheDir })).rejects.toMatchObject({ code: 'SLOTSTREAM_DOWNLOAD_IN_FLIGHT' });+ // A DIFFERENT checkpoint is refused too: one disk, one progress bar.+ await expect(downloadSlotstreamModel({ model: 'someone/other-moe', cacheDir }))+ .rejects.toMatchObject({ code: 'SLOTSTREAM_DOWNLOAD_IN_FLIGHT' });+release();expect((await first).success).toBe(true);});@@ -187,10 +217,10 @@ describe('downloadSlotstreamModel', () => {let release;const gate = new Promise((resolve) => { release = resolve; });const realFetch = globalThis.fetch;- globalThis.fetch = vi.fn(async (url) => {+ vi.stubGlobal('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));