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([issue-4912]): make spec model downloads cancellable
[._.]/ Adam Eivy289789046560
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex 2c5e45d2f8..86f444b099 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -11,7 +11,7 @@ import {getLocalLlmStatus, getLocalLlmCatalog, getLocalLlmHuggingFaceSearch, installLocalLlmModel,deleteLocalLlmModel, migrateLocalLlmBackend, installLocalLlmBackend, upgradeLocalLlmBackend, controlOllamaService,installAudioModel, patchSettingsSlice, getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaServer,- downloadSpecDecodeModel, controlLmStudioService, getMtplxServerStatus, stopMtplxServer, installMtplx,+ downloadSpecDecodeModel, cancelSpecDecodeModelDownload, controlLmStudioService, getMtplxServerStatus, stopMtplxServer, installMtplx,searchMtplxModels, pullMtplxModel, removeMtplxModel,saveRuntimeStartupList} from '../../services/api';@@ -335,7 +335,7 @@ export function LocalLlmTab() {const handleDownloadProgress = (frame) => {if (!frame?.presetId || !frame?.role) return;const key = downloadKey(frame.presetId, frame.role);- if (frame.event === 'complete' || frame.event === 'error') {+ if (frame.event === 'complete' || frame.event === 'error' || frame.event === 'cancelled') {setLlamaDownloads((prev) => {if (!prev[key]) return prev;const next = { ...prev };@@ -800,7 +800,9 @@ export function LocalLlmTab() {const status = await loadLlamaStatus();const stillRunning = status?.presets?.find((p) => p.id === presetId)?.[role]?.downloading;- if (stillRunning) {+ if (err?.code === 'SPEC_DOWNLOAD_CANCELLED') {+ toast.info('Download cancelled');+ } else if (stillRunning) {toast.warning('Download still running in the background — this page lost the request, not the transfer.');} else {toast.error(err?.message || 'Download failed');@@ -815,6 +817,17 @@ export function LocalLlmTab() {}};+ const handleCancelSpecModelDownload = async (role) => {+ try {+ const res = await cancelSpecDecodeModelDownload(llamaPresetId, role, { silent: true });+ if (res.cancelled) toast.info('Cancelling model download…');+ } catch (err) {+ toast.error(err?.message || 'Could not cancel the model download');+ } finally {+ loadLlamaStatus();+ }+ };+const handleStartLlama = async (e) => {e?.preventDefault?.();// Submitting with Enter bypasses the disabled button, so re-check here.@@ -1190,6 +1203,7 @@ export function LocalLlmTab() {entry={entry}progress={llamaDownloads[downloadKey(llamaPresetId, entry.role)]}onDownload={handleDownloadSpecModel}+ onCancel={handleCancelSpecModelDownload}disabled={llamaLoading}/>))}diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsxindex 93e1163e68..61a747663e 100644--- a/client/src/components/settings/LocalLlmTab.test.jsx+++ b/client/src/components/settings/LocalLlmTab.test.jsx@@ -30,6 +30,7 @@ vi.mock('../../services/api', () => ({stopLlamaServer: vi.fn(),installLlamaServer: vi.fn().mockResolvedValue({ success: true }),downloadSpecDecodeModel: vi.fn(),+ cancelSpecDecodeModelDownload: vi.fn(),}));vi.mock('../../services/socket', () => ({default: { on: vi.fn(), off: vi.fn() },@@ -779,6 +780,21 @@ describe('LocalLlmTab llama-server management', () => {await waitFor(() => expect(getLlamaServerStatus).toHaveBeenCalledTimes(3));});+ it('offers Cancel for a running preset download and calls the cancel endpoint', async () => {+ const { getLlamaServerStatus, cancelSpecDecodeModelDownload } = await import('../../services/api');+ const downloading = specPresets({ baseExists: false });+ downloading[0].model.downloading = true;+ getLlamaServerStatus.mockResolvedValue(llamaReady({ presets: downloading }));+ cancelSpecDecodeModelDownload.mockResolvedValue({ success: true, cancelled: true });++ await renderTab();+ fireEvent.click(await screen.findByRole('button', { name: /^Cancel$/ }));++ await waitFor(() => {+ expect(cancelSpecDecodeModelDownload).toHaveBeenCalledWith('qwen3.8-27b-dspark', 'model', { silent: true });+ });+ });+it('blocks Start while a preset GGUF is missing and names the fix', async () => {const { getLlamaServerStatus, startLlamaServer } = await import('../../services/api');getLlamaServerStatus.mockResolvedValue(llamaReady({ presets: specPresets({ baseExists: false }) }));diff --git a/client/src/components/settings/SpecDecodeWeightRow.jsx b/client/src/components/settings/SpecDecodeWeightRow.jsxindex d17ddb56f5..1e96513e03 100644--- a/client/src/components/settings/SpecDecodeWeightRow.jsx+++ b/client/src/components/settings/SpecDecodeWeightRow.jsx@@ -1,4 +1,4 @@-import { Check, Download, ExternalLink } from 'lucide-react';+import { Check, Download, ExternalLink, X } from 'lucide-react';import BrailleSpinner from '../BrailleSpinner';import { formatBytes } from '../../utils/formatters';@@ -13,7 +13,7 @@ const ROLE_LABELS = { model: 'Target base model', draftModel: 'Drafter' };* this row is what turns "The base model was not found at `models/…`" into a* thing the user can act on without leaving the page.*/-export default function SpecDecodeWeightRow({ entry, progress, onDownload, disabled }) {+export default function SpecDecodeWeightRow({ entry, progress, onDownload, onCancel, disabled }) {if (!entry?.path) return null;const label = ROLE_LABELS[entry.role] || entry.role;const downloading = Boolean(progress) || entry.downloading;@@ -37,10 +37,21 @@ export default function SpecDecodeWeightRow({ entry, progress, onDownload, disabDownloaded{entry.sizeBytes ? ` (${formatBytes(entry.sizeBytes)})` : ''}</span>) : downloading ? (- <span className="flex items-center gap-1.5 text-[11px] text-gray-400">- <BrailleSpinner />- {percent === null ? formatBytes(received) : `${percent}%`}- </span>+ <>+ <span className="flex items-center gap-1.5 text-[11px] text-gray-400">+ <BrailleSpinner />+ {percent === null ? formatBytes(received) : `${percent}%`}+ </span>+ <button+ type="button"+ onClick={() => onCancel(entry.role)}+ className="flex items-center gap-1 px-2 py-1 text-[11px] text-port-warning hover:bg-port-warning/10 rounded transition-colors"+ title={`Cancel download of ${label.toLowerCase()}`}+ >+ <X size={11} />+ Cancel+ </button>+ </>) : entry.downloadable ? (<><adiff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex fea81ceb62..674594946d 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -121,6 +121,13 @@ export const downloadSpecDecodeModel = (presetId, role, options) =>...options,});+export const cancelSpecDecodeModelDownload = (presetId, role, options) =>+ request('/local-llm/llama-server/download-model/cancel', {+ method: 'POST',+ body: JSON.stringify({ presetId, role }),+ ...options,+ });+// Set the default backend (which one PortOS routes local runs to) — does not move models.export const switchLocalLlmBackend = (to) =>request('/local-llm/switch', { method: 'POST', body: JSON.stringify({ to }) });diff --git a/server/lib/huggingfaceLora.js b/server/lib/huggingfaceLora.jsindex e139514b0a..44108b0cfd 100644--- a/server/lib/huggingfaceLora.js+++ b/server/lib/huggingfaceLora.js@@ -118,7 +118,7 @@ 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.-export const fetchHuggingfaceModel = async (repo, { token, revision, fetchImpl = fetch } = {}) => {+export const fetchHuggingfaceModel = async (repo, { token, revision, fetchImpl = fetch, signal } = {}) => {if (!/^[^/\s]+\/[^/\s]+$/.test(String(repo))) {throw new ServerError(`Invalid HuggingFace repo id: ${repo}`, { status: 400, code: 'HF_BAD_URL' });}@@ -127,7 +127,7 @@ export const fetchHuggingfaceModel = async (repo, { token, revision, fetchImpl =const url = revision? `${HF_API}/${repo}/revision/${encodeURIComponent(revision)}`: `${HF_API}/${repo}`;- const res = await fetchImpl(url, { headers: { Accept: 'application/json', ...buildHfAuthHeaders(token) } });+ const res = await fetchImpl(url, { headers: { Accept: 'application/json', ...buildHfAuthHeaders(token) }, signal });if (!res.ok) {if (res.status === 404) {throw new ServerError(`HuggingFace repo ${repo} not found`, { status: 404, code: 'HF_NOT_FOUND' });diff --git a/server/lib/huggingfaceLora.test.js b/server/lib/huggingfaceLora.test.jsindex cc85d790ae..29a52ff768 100644--- a/server/lib/huggingfaceLora.test.js+++ b/server/lib/huggingfaceLora.test.js@@ -276,4 +276,12 @@ describe('fetchHuggingfaceModel', () => {const fetchImpl = async () => ({ ok: true, text: async () => JSON.stringify(body) });await expect(fetchHuggingfaceModel('fal/x', { fetchImpl })).resolves.toEqual(body);});+ it('forwards a caller cancellation signal to the metadata fetch', async () => {+ const controller = new AbortController();+ const fetchImpl = vi.fn(async () => ({ ok: true, text: async () => '{}' }));++ await fetchHuggingfaceModel('fal/x', { fetchImpl, signal: controller.signal });++ expect(fetchImpl).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ signal: controller.signal }));+ });});diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 36ceefff02..6744715554 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -43,7 +43,7 @@ import { getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaSeimport { MTPLX_APP, getMtplxServerStatus, startMtplxServer, stopMtplxServer, installMtplx } from '../services/mtplxServerManager.js'import { searchMtplxCatalog, pullMtplxModel, removeMtplxModel } from '../services/mtplxModelManager.js'import { saveProcessList } from '../services/pm2.js'-import { getSpecDecodePresetStatus, downloadSpecDecodeModel } from '../services/specDecodeModels.js'+import { getSpecDecodePresetStatus, downloadSpecDecodeModel, cancelSpecDecodeModelDownload } from '../services/specDecodeModels.js'import { SPEC_TYPE_SUGGESTIONS } from '../lib/specDecodePresets.js'import { resetProviderReadinessCache } from '../services/providerReadiness.js'import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'@@ -641,6 +641,15 @@ router.post('/llama-server/download-model', asyncHandler(async (req, res) => {res.json(result)}))+// POST /api/local-llm/llama-server/download-model/cancel — a download is+// server-owned so it survives navigation, but must still be explicitly+// stoppable to release its single transfer slot and remove its partial file.+router.post('/llama-server/download-model/cancel', asyncHandler(async (req, res) => {+ const { presetId, role } = validateRequest(localLlmSpecModelDownloadSchema, req.body)+ const cancelled = cancelSpecDecodeModelDownload({ presetId, role })+ res.json({ success: true, cancelled })+}))+// Each of the three actions below changes exactly what the provider-readiness// probes remember — is the binary there, is something answering — so each drops// those caches. Without it the Providers page keeps reporting "llama.cpp setupdiff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.jsindex ace891ab6f..53f28c8416 100644--- a/server/routes/localLlm.test.js+++ b/server/routes/localLlm.test.js@@ -97,6 +97,7 @@ vi.mock('../services/llamaServerManager.js', () => ({vi.mock('../services/specDecodeModels.js', () => ({getSpecDecodePresetStatus: vi.fn(async () => ([{ id: 'test-preset', label: 'Test', specType: 'draft-dspark', model: null, draftModel: null }])),downloadSpecDecodeModel: vi.fn(async () => ({ success: true, path: 'models/base.gguf', file: 'base.gguf' })),+ cancelSpecDecodeModelDownload: vi.fn(() => true),}));// /loaded reads getSettings() to honor a user's intentionally-disabled backends,@@ -700,6 +701,17 @@ describe('llama-server routes', () => {expect(res.status).toBe(400);});+ it('POST /api/local-llm/llama-server/download-model/cancel cancels one active preset download', async () => {+ const { cancelSpecDecodeModelDownload } = await import('../services/specDecodeModels.js');+ const res = await request(makeApp())+ .post('/api/local-llm/llama-server/download-model/cancel')+ .send({ presetId: 'test-preset', role: 'model' });++ expect(res.status).toBe(200);+ expect(res.body).toEqual({ success: true, cancelled: true });+ expect(cancelSpecDecodeModelDownload).toHaveBeenCalledWith({ presetId: 'test-preset', role: 'model' });+ });+it('POST /api/local-llm/llama-server/start launches server with valid payload', async () => {const res = await request(makeApp()).post('/api/local-llm/llama-server/start')diff --git a/server/services/specDecodeModels.js b/server/services/specDecodeModels.jsindex 8438b4a4c1..ec2fcbe125 100644--- a/server/services/specDecodeModels.js+++ b/server/services/specDecodeModels.js@@ -35,6 +35,15 @@ import {// 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).@@ -150,39 +159,80 @@ export function pickGgufSibling(model, { file, quant, repo }) {);}-const streamToFile = async ({ url, headers, destPath, onBytes }) => {- const res = await fetch(url, { headers, redirect: 'follow' });- if (!res.ok || !res.body) {- 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' },- );+const streamToFile = async ({ url, headers, destPath, onBytes, signal, onIdleStall }) => {+ let idleTimer = null;+ const clearIdleTimer = () => {+ if (!idleTimer) return;+ clearTimeout(idleTimer);+ idleTimer = null;+ };+ const resetIdleTimer = () => {+ clearIdleTimer();+ idleTimer = setTimeout(() => {+ // This callback is outside Express's error lifecycle, so never permit a+ // timer failure to take down the server.+ try {+ onIdleStall();+ } catch (err) {+ console.error(`❌ Speculative-decoding download watchdog failed: ${err.message}`);+ }+ }, IDLE_STALL_TIMEOUT_MS);+ idleTimer.unref?.();+ };++ resetIdleTimer();+ try {+ const res = await fetch(url, { headers, redirect: 'follow', signal });+ if (!res.ok || !res.body) {+ 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' });}- throw new ServerError(`Hugging Face download failed: ${res.status} ${res.statusText}`, { status: 502, code: 'HF_DOWNLOAD_FAILED' });+ const total = Number(res.headers?.get?.('content-length')) || 0;+ // A random temp suffix keeps a crashed transfer's leftovers from being+ // mistaken for this one's, and keeps the half-written file out of the+ // launcher's existence check until it is complete.+ const tmpPath = `${destPath}.${randomBytes(6).toString('hex')}.partial`;+ await ensureDir(dirname(destPath));+ let received = 0;+ // Count bytes in a passthrough Transform, NOT a bare `.on('data')` listener —+ // that flips the source into flowing mode and defeats pipeline backpressure.+ const counter = new Transform({+ transform(chunk, _enc, cb) {+ received += chunk.length;+ resetIdleTimer();+ onBytes(received, total);+ cb(null, chunk);+ },+ });+ await pipeline(Readable.fromWeb(res.body), counter, createWriteStream(tmpPath)).catch(async (err) => {+ await rm(tmpPath, { force: true }).catch(() => {});+ throw err;+ });+ await rename(tmpPath, destPath);+ return { bytes: received || total };+ } finally {+ clearIdleTimer();+ }+};++const downloadAbortError = (state) => {+ if (state.abortReason === 'cancelled') {+ return new ServerError('Download cancelled', { status: 409, code: 'SPEC_DOWNLOAD_CANCELLED' });}- const total = Number(res.headers?.get?.('content-length')) || 0;- // A random temp suffix keeps a crashed transfer's leftovers from being- // mistaken for this one's, and keeps the half-written file out of the- // launcher's existence check until it is complete.- const tmpPath = `${destPath}.${randomBytes(6).toString('hex')}.partial`;- await ensureDir(dirname(destPath));- let received = 0;- // Count bytes in a passthrough Transform, NOT a bare `.on('data')` listener —- // that flips the source into flowing mode and defeats pipeline backpressure.- const counter = new Transform({- transform(chunk, _enc, cb) {- received += chunk.length;- onBytes(received, total);- cb(null, chunk);- },- });- await pipeline(Readable.fromWeb(res.body), counter, createWriteStream(tmpPath)).catch(async (err) => {- await rm(tmpPath, { force: true }).catch(() => {});- throw err;- });- await rename(tmpPath, destPath);- return { bytes: received || total };+ 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);};/**@@ -215,21 +265,35 @@ export async function downloadSpecDecodeModel({ presetId, role, onProgress = ()// window would clear the check above 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 };+ const state = {+ presetId,+ role,+ received: 0,+ total: 0,+ controller: new AbortController(),+ abortReason: null,+ };inFlight.set(destPath, state);let lastEmit = 0;try {const token = await getHfToken();const headers = buildHfAuthHeaders(token);+ throwIfAborted(state);onProgress({ event: 'start', presetId, role, path: source.path, message: `Resolving ${source.repo} on Hugging Face…` });- const model = await fetchHuggingfaceModel(source.repo, { token });+ const model = await fetchHuggingfaceModel(source.repo, { token, signal: state.controller.signal });+ throwIfAborted(state);const file = pickGgufSibling(model, { file: source.file, quant: source.quant, repo: source.repo });console.log(`⬇️ Downloading speculative-decoding weights ${source.repo}/${file} → ${source.path}`);const { bytes } = await streamToFile({url: buildHfResolveUrl(source.repo, 'main', file),headers,destPath,+ signal: state.controller.signal,+ onIdleStall: () => {+ state.abortReason = 'stalled';+ state.controller.abort();+ },onBytes: (received, total) => {state.received = received;state.total = total;@@ -243,14 +307,34 @@ export async function downloadSpecDecodeModel({ presetId, role, onProgress = ()console.log(`✅ Speculative-decoding weights ready: ${source.path} (${bytes} bytes)`);return { success: true, path: source.path, repo: source.repo, file, sizeBytes: bytes };} catch (err) {- onProgress({ event: 'error', presetId, role, path: source.path, message: err.message });- console.error(`❌ Speculative-decoding download failed for ${source.path}: ${err.message}`);- throw err;+ const error = state.abortReason ? downloadAbortError(state) : err;+ const event = state.abortReason === 'cancelled' ? 'cancelled' : 'error';+ onProgress({ event, presetId, role, path: source.path, message: error.message });+ if (state.abortReason === '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);}}+/** Cancel one active curated GGUF download. Returns false when none is active. */+export function cancelSpecDecodeModelDownload({ presetId, role }) {+ if (!SPEC_MODEL_ROLES.includes(role)) {+ throw new ServerError(`Unknown model role "${role}"`, { status: 400 });+ }+ 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;+}+/** Clears in-flight download bookkeeping (used by test suites). */export function _resetSpecDecodeDownloadsForTests() {inFlight.clear();diff --git a/server/services/specDecodeModels.test.js b/server/services/specDecodeModels.test.jsindex 23fe12f4b5..3729711110 100644--- a/server/services/specDecodeModels.test.js+++ b/server/services/specDecodeModels.test.js@@ -5,6 +5,7 @@ import { isAbsolute, join } from 'path';import { Readable } from 'stream';import {downloadSpecDecodeModel,+ cancelSpecDecodeModelDownload,getSpecDecodePresetStatus,pickGgufSibling,resolveSpecModelPath,@@ -195,6 +196,60 @@ describe('downloadSpecDecodeModel', () => {expect(await readdir(dir)).toEqual([]);});+ it('cancels an active transfer, emits a terminal frame, and removes its partial file', async () => {+ stubPreset();+ vi.spyOn(huggingfaceLora, 'fetchHuggingfaceModel').mockResolvedValue(siblings('Example-Q4_K_M.gguf'));+ let signal;+ const stream = new Readable({ read() {} });+ stream.push(Buffer.from('gg'));+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, options) => {+ signal = options.signal;+ signal.addEventListener('abort', () => stream.destroy(new Error('aborted')));+ return {+ ok: true,+ status: 200,+ headers: { get: () => '99' },+ body: Readable.toWeb(stream),+ };+ });+ const frames = [];+ const download = downloadSpecDecodeModel({+ presetId: 'test-preset', role: 'model', onProgress: (frame) => frames.push(frame),+ });++ await vi.waitFor(() => expect(signal).toBeDefined());+ expect(cancelSpecDecodeModelDownload({ presetId: 'test-preset', role: 'model' })).toBe(true);+ await expect(download).rejects.toMatchObject({ code: 'SPEC_DOWNLOAD_CANCELLED' });++ const { readdir } = await import('fs/promises');+ expect(await readdir(dir)).toEqual([]);+ expect(frames.at(-1)).toMatchObject({ event: 'cancelled', message: 'Download cancelled' });+ });++ it('aborts a byte-silent transfer when its idle watchdog expires', async () => {+ vi.useFakeTimers();+ stubPreset();+ vi.spyOn(huggingfaceLora, 'fetchHuggingfaceModel').mockResolvedValue(siblings('Example-Q4_K_M.gguf'));+ let signal;+ const stream = new Readable({ read() {} });+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, options) => {+ signal = options.signal;+ signal.addEventListener('abort', () => stream.destroy(new Error('aborted')));+ return {+ ok: true,+ status: 200,+ headers: { get: () => '99' },+ body: Readable.toWeb(stream),+ };+ });++ const download = downloadSpecDecodeModel({ presetId: 'test-preset', role: 'model' });+ await vi.waitFor(() => expect(signal).toBeDefined());+ await vi.advanceTimersByTimeAsync(20 * 60 * 1000);+ await expect(download).rejects.toMatchObject({ code: 'SPEC_DOWNLOAD_STALLED' });+ vi.useRealTimers();+ });+// The slot is claimed before the Hugging Face round trip: a second click// landing inside that window would otherwise clear the in-flight check and// start a parallel multi-gigabyte transfer of the same file.