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

feat: refuse-before-you-download disk preflight and resumable weight downloads (#5817)

[._.]/ Adam Eivy5e293c77e9f1
diff --git a/client/src/components/models/DownloadPreflightConfirm.jsx b/client/src/components/models/DownloadPreflightConfirm.jsx
new file mode 100644
index 0000000000..0fe586f720
--- /dev/null
+++ b/client/src/components/models/DownloadPreflightConfirm.jsx
@@ -0,0 +1,113 @@
+import { AlertTriangle, Download, HardDrive } from 'lucide-react';
+import Modal from '../ui/Modal';
+import { formatBytes } from '../../utils/formatters';
+
+const VERDICT_COPY = {
+ ok: null,
+ tight: 'This will fit, but it will leave little free disk afterward.',
+ insufficient: 'There is not enough free disk for this download. Free space and try again.',
+};
+
+/**
+ * Confirm a multi-gigabyte weight download with the numbers in front of the
+ * user: size, destination, and free disk. Confirm is disabled when the
+ * preflight verdict is `insufficient` so a doomed transfer cannot start.
+ */
+export default function DownloadPreflightConfirm({
+ open,
+ title = 'Download model weights',
+ loading = false,
+ error = null,
+ assessment = null,
+ confirmLabel = 'Download',
+ onConfirm,
+ onCancel,
+}) {
+ const insufficient = assessment?.verdict === 'insufficient';
+ const warning = VERDICT_COPY[assessment?.verdict] || null;
+ const sizeKnown = Number(assessment?.expectedBytes) > 0;
+ const freeKnown = Number.isFinite(assessment?.freeBytes);
+
+ return (
+ <Modal
+ open={open}
+ onClose={onCancel}
+ size="sm"
+ ariaLabel={title}
+ usePortal
+ >
+ <div className="rounded-xl border border-port-border bg-port-card p-4 sm:p-5 space-y-4">
+ <div className="flex items-start gap-3">
+ <div className="rounded-lg bg-port-accent/10 p-2 text-port-accent shrink-0">
+ <HardDrive size={18} />
+ </div>
+ <div className="min-w-0">
+ <h2 className="text-sm font-semibold text-white">{title}</h2>
+ <p className="mt-1 text-xs text-gray-400">
+ Check the size, destination, and free disk before the transfer starts.
+ </p>
+ </div>
+ </div>
+
+ {loading && (
+ <p className="text-sm text-gray-400">Checking size and free disk…</p>
+ )}
+
+ {error && (
+ <p className="text-sm text-port-error" role="alert">{error}</p>
+ )}
+
+ {!loading && !error && assessment && (
+ <dl className="grid grid-cols-1 gap-2 text-sm">
+ <div className="flex items-baseline justify-between gap-3">
+ <dt className="text-gray-500">Size</dt>
+ <dd className="font-medium tabular-nums text-white">
+ {sizeKnown ? formatBytes(assessment.expectedBytes) : 'Unknown until the transfer starts'}
+ </dd>
+ </div>
+ <div className="flex items-baseline justify-between gap-3">
+ <dt className="text-gray-500">Destination</dt>
+ <dd className="font-medium text-gray-200 break-all text-right">{assessment.destPath || '—'}</dd>
+ </div>
+ <div className="flex items-baseline justify-between gap-3">
+ <dt className="text-gray-500">Free disk</dt>
+ <dd className="font-medium tabular-nums text-white">
+ {freeKnown ? formatBytes(assessment.freeBytes) : 'Unavailable'}
+ </dd>
+ </div>
+ </dl>
+ )}
+
+ {warning && (
+ <p className={`flex items-start gap-2 text-xs ${insufficient ? 'text-port-error' : 'text-port-warning'}`}>
+ <AlertTriangle size={14} className="mt-0.5 shrink-0" />
+ <span>{warning}</span>
+ </p>
+ )}
+
+ {assessment?.alreadyDownloaded && (
+ <p className="text-xs text-port-success">This file is already on disk.</p>
+ )}
+
+ <div className="flex flex-wrap justify-end gap-2 pt-1">
+ <button
+ type="button"
+ onClick={onCancel}
+ className="min-h-[36px] rounded-lg border border-port-border px-3 py-1.5 text-sm text-gray-300 hover:bg-port-border/40"
+ >
+ Cancel
+ </button>
+ <button
+ type="button"
+ onClick={onConfirm}
+ disabled={loading || Boolean(error) || insufficient || assessment?.alreadyDownloaded}
+ className="inline-flex min-h-[36px] items-center gap-1.5 rounded-lg bg-port-accent px-3 py-1.5 text-sm font-medium text-white hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ <Download size={14} />
+ {confirmLabel}
+ </button>
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/client/src/components/models/DownloadPreflightConfirm.test.jsx b/client/src/components/models/DownloadPreflightConfirm.test.jsx
new file mode 100644
index 0000000000..0f7e2ae110
--- /dev/null
+++ b/client/src/components/models/DownloadPreflightConfirm.test.jsx
@@ -0,0 +1,58 @@
+import { describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen } from '@testing-library/react';
+import DownloadPreflightConfirm from './DownloadPreflightConfirm.jsx';
+
+const assessment = {
+ destPath: 'models/example.gguf',
+ expectedBytes: 2 * 1024 * 1024 * 1024,
+ freeBytes: 20 * 1024 * 1024 * 1024,
+ requiredBytes: 2.5 * 1024 * 1024 * 1024,
+ headroomBytes: 512 * 1024 * 1024,
+ verdict: 'ok',
+};
+
+describe('DownloadPreflightConfirm', () => {
+ it('shows size, destination, and free disk before the transfer starts', () => {
+ render(
+ <DownloadPreflightConfirm
+ open
+ assessment={assessment}
+ onConfirm={() => {}}
+ onCancel={() => {}}
+ />,
+ );
+ expect(screen.getByText('Size')).toBeInTheDocument();
+ expect(screen.getByText('2 GB')).toBeInTheDocument();
+ expect(screen.getByText('models/example.gguf')).toBeInTheDocument();
+ expect(screen.getByText('Free disk')).toBeInTheDocument();
+ expect(screen.getByText('20 GB')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Download' })).toBeEnabled();
+ });
+
+ it('disables Confirm when the disk cannot hold the download', () => {
+ render(
+ <DownloadPreflightConfirm
+ open
+ assessment={{ ...assessment, verdict: 'insufficient', freeBytes: 100 }}
+ onConfirm={() => {}}
+ onCancel={() => {}}
+ />,
+ );
+ expect(screen.getByRole('button', { name: 'Download' })).toBeDisabled();
+ expect(screen.getByText(/not enough free disk/i)).toBeInTheDocument();
+ });
+
+ it('calls onConfirm from the Download button', () => {
+ const onConfirm = vi.fn();
+ render(
+ <DownloadPreflightConfirm
+ open
+ assessment={assessment}
+ onConfirm={onConfirm}
+ onCancel={() => {}}
+ />,
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Download' }));
+ expect(onConfirm).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index f8a8d2cac3..64a56b29a8 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -7,11 +7,12 @@ import BrailleSpinner from '../BrailleSpinner';
import { formatAgeDays, formatBytes, formatContextLength, timeAgo, recommendedRamGb, formatDateNumeric } from '../../utils/formatters';
import { localLlmTargetKey } from '../../lib/localLlmTargetKey';
import { useConfirmDelete } from '../../hooks/useConfirmDelete';
+import useDownloadPreflightConfirm from '../../hooks/useDownloadPreflightConfirm';
import {
getLocalLlmStatus, getLocalLlmCatalog, getLocalLlmHuggingFaceSearch, installLocalLlmModel,
deleteLocalLlmModel, migrateLocalLlmBackend, installLocalLlmBackend, upgradeLocalLlmBackend, controlOllamaService,
installAudioModel, patchSettingsSlice, getLlamaServerStatus, getLlamaServerUpdateStatus, startLlamaServer, stopLlamaServer, installLlamaServer, upgradeLlamaServer,
- downloadSpecDecodeModel, cancelSpecDecodeModelDownload, controlLmStudioService, getMtplxServerStatus, startMtplxServer, stopMtplxServer, installMtplx,
+ downloadSpecDecodeModel, cancelSpecDecodeModelDownload, previewLocalLlmDownload, controlLmStudioService, getMtplxServerStatus, startMtplxServer, stopMtplxServer, installMtplx,
searchMtplxModels, pullMtplxModel, removeMtplxModel,
getSlotstreamServerStatus, startSlotstreamServer, stopSlotstreamServer, installSlotstream,
saveRuntimeStartupList
@@ -25,6 +26,7 @@ import SlotstreamServerCard from './SlotstreamServerCard.jsx';
import LocalLlmBackendCard from './LocalLlmBackendCard.jsx';
import LocalLlmInstalledModels from './LocalLlmInstalledModels.jsx';
import ModelAbuseGuardPanel from '../models/ModelAbuseGuardPanel.jsx';
+import DownloadPreflightConfirm from '../models/DownloadPreflightConfirm.jsx';
import TabPills from '../ui/TabPills.jsx';
const BACKENDS = [
@@ -204,6 +206,7 @@ export function LocalLlmTab({ view }) {
// at a time on purpose: a checkpoint is tens of gigabytes, so two concurrent
// pulls just make both slower.
const [mtplxDownload, setMtplxDownload] = useState(null);
+ const { confirm: downloadConfirm, request: requestWeightDownload, cancel: cancelDownloadConfirm, confirmRun: runDownloadConfirm } = useDownloadPreflightConfirm();
const [llamaLoading, setLlamaLoading] = useState(false);
// Anchor for the unified server card's "Configure" action — llama-server needs
// a model path, so its Start lives in the launcher rather than in that row.
@@ -606,7 +609,7 @@ export function LocalLlmTab({ view }) {
// The pull resolves only when the weights are on disk; byte progress arrives
// on `mtplx:download` (subscribed above), so the button spinner is not the
// only sign of life during a multi-gigabyte transfer.
- const mtplxPull = (model) => runAction(
+ const startMtplxPull = (model) => runAction(
model ? `mtplx-pull-${model}` : 'mtplx-pull',
// A failed download RESOLVES `{success: false, error}` rather than throwing
// (its progress already streamed), so convert it to the rejection
@@ -622,6 +625,11 @@ export function LocalLlmTab({ view }) {
setMtplxDownload(null);
return loadMtplxStatus();
});
+ const mtplxPull = (model) => requestWeightDownload({
+ title: 'Download MTPLX checkpoint',
+ preview: () => previewLocalLlmDownload({ kind: 'mtplx', model: model || null }, { silent: true }),
+ run: () => startMtplxPull(model),
+ });
const mtplxRemove = (model) => runAction(
`mtplx-remove-${model}`,
() => removeMtplxModel(model),
@@ -686,7 +694,7 @@ export function LocalLlmTab({ view }) {
// queued, not finished — so don't claim "installed" in that case. Install is
// silent so an OLLAMA_OUTDATED failure can take over the UI with the upgrade
// banner instead of stacking a useless toast with the auto-upgrade flow.
- const install = (modelId, { force = false } = {}) => runAction(
+ const startInstall = (modelId, { force = false } = {}) => runAction(
`install-${modelId}`,
() => installLocalLlmModel(selected, modelId, { silent: true, force }),
(r) => r?.pending ? `${modelId} download started` : `${modelId} ${force ? 'redownloaded' : 'installed'}`,
@@ -710,6 +718,11 @@ export function LocalLlmTab({ view }) {
clearConfirm: false
}
);
+ const install = (modelId, opts = {}) => requestWeightDownload({
+ title: opts.force ? 'Redownload local model' : 'Install local model',
+ preview: () => previewLocalLlmDownload({ kind: 'install', backend: selected, modelId }, { silent: true }),
+ run: () => startInstall(modelId, opts),
+ });
// Audio/music models don't run on Ollama/LM Studio — they install into the
// shared audio-model registry (server/services/audioModels.js) via the Music
// studio's streaming HF-download endpoint, so the Music studio picks them up.
@@ -779,7 +792,7 @@ export function LocalLlmTab({ view }) {
).then((r) => {
if (r?.success && modelId) {
setUpgradeFlow({ modelId, phase: 'retrying' });
- install(modelId);
+ startInstall(modelId);
// install() either succeeds (its own success toast + status reload covers
// it) or re-enters the OLLAMA_OUTDATED branch above and resets the flow.
// Clear after a beat so the banner doesn't linger past the retry kickoff.
@@ -854,7 +867,7 @@ export function LocalLlmTab({ view }) {
? 'Download the drafter, or clear the field to run without it'
: '';
- const handleDownloadSpecModel = async (role) => {
+ const startSpecDownload = async (role) => {
const presetId = llamaPresetId;
const key = downloadKey(presetId, role);
setLlamaDownloads((prev) => ({ ...prev, [key]: { received: 0, total: 0 } }));
@@ -892,6 +905,15 @@ export function LocalLlmTab({ view }) {
}
};
+ const handleDownloadSpecModel = (role) => requestWeightDownload({
+ title: 'Download speculative-decoding weights',
+ preview: () => previewLocalLlmDownload(
+ { kind: 'spec-decode', presetId: llamaPresetId, role },
+ { silent: true },
+ ),
+ run: () => startSpecDownload(role),
+ });
+
const handleCancelSpecModelDownload = async (role) => {
try {
const res = await cancelSpecDecodeModelDownload(llamaPresetId, role, { silent: true });
@@ -1949,6 +1971,16 @@ export function LocalLlmTab({ view }) {
</div>
</section>
)}
+ <DownloadPreflightConfirm
+ open={Boolean(downloadConfirm)}
+ title={downloadConfirm?.title}
+ loading={Boolean(downloadConfirm?.loading)}
+ error={downloadConfirm?.error}
+ assessment={downloadConfirm?.assessment}
+ confirmLabel="Start download"
+ onCancel={cancelDownloadConfirm}
+ onConfirm={runDownloadConfirm}
+ />
</div>
);
}
diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsx
index 47f990db75..5a73c4e495 100644
--- a/client/src/components/settings/LocalLlmTab.test.jsx
+++ b/client/src/components/settings/LocalLlmTab.test.jsx
@@ -36,6 +36,15 @@ vi.mock('../../services/api', () => ({
installLlamaServer: vi.fn().mockResolvedValue({ success: true }),
upgradeLlamaServer: vi.fn().mockResolvedValue({ success: true, note: 'updated' }),
downloadSpecDecodeModel: vi.fn(),
+ previewLocalLlmDownload: vi.fn(async () => ({
+ kind: 'spec-decode',
+ destPath: 'models/example.gguf',
+ expectedBytes: 6,
+ freeBytes: 1e12,
+ requiredBytes: 6,
+ headroomBytes: 0,
+ verdict: 'ok',
+ })),
cancelSpecDecodeModelDownload: vi.fn(),
}));
vi.mock('../../services/socket', () => ({
@@ -285,6 +294,7 @@ describe('LocalLlmTab runtime servers', () => {
await renderTab();
fireEvent.click(screen.getByRole('button', { name: /Download default checkpoint/ }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Start download' }));
await waitFor(() => expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/no space left on device/)));
expect(toast.success).not.toHaveBeenCalled();
@@ -299,6 +309,7 @@ describe('LocalLlmTab runtime servers', () => {
await renderTab();
fireEvent.click(screen.getByRole('button', { name: /Download default checkpoint/ }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Start download' }));
// `null` (not a repo id the card invented) = MTPLX's own verified default.
await waitFor(() => expect(pullMtplxModel).toHaveBeenCalledWith(null));
@@ -348,6 +359,7 @@ describe('LocalLlmTab installed models', () => {
installLocalLlmModel.mockResolvedValue({ success: true });
await renderTab('library');
fireEvent.click(screen.getByRole('button', { name: `Redownload ${LONG_ID}` }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Start download' }));
await waitFor(() => expect(installLocalLlmModel).toHaveBeenCalledWith(
'ollama',
LONG_ID,
@@ -414,6 +426,7 @@ describe('LocalLlmTab installed models', () => {
);
await waitFor(() => expect(screen.getByText(/Installed on LM Studio/)).toBeTruthy());
fireEvent.click(screen.getByRole('button', { name: 'Redownload Qwen3.8 27B' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Start download' }));
await waitFor(() => expect(installLocalLlmModel).toHaveBeenCalledWith(
'lmstudio',
'unsloth/Qwen3.8-27B-GGUF@UD-Q4_K_M',
@@ -516,6 +529,7 @@ describe('LocalLlmTab recommendations', () => {
await renderTab('library');
expect(await screen.findByText('Qwen3.8 27B')).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: /^Redownload$/ }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Start download' }));
await waitFor(() => expect(installLocalLlmModel).toHaveBeenCalledWith(
'ollama',
'hf.co/unsloth/Qwen3.8-27B-GGUF:UD-Q4_K_M',
@@ -906,6 +920,7 @@ describe('LocalLlmTab llama-server management', () => {
expect(screen.getByText(/Downloaded \(1\.1 GB\)/)).toBeInTheDocument();
const downloadBtn = screen.getByRole('button', { name: /^Download$/ });
fireEvent.click(downloadBtn);
+ fireEvent.click(await screen.findByRole('button', { name: 'Start download' }));
await waitFor(() => {
expect(downloadSpecDecodeModel).toHaveBeenCalledWith('qwen3.8-27b-dspark', 'model', { silent: true });
@@ -932,6 +947,7 @@ describe('LocalLlmTab llama-server management', () => {
await renderTab();
fireEvent.click(await screen.findByRole('button', { name: /^Download$/ }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Start download' }));
await waitFor(() => {
expect(toast.warning).toHaveBeenCalledWith(expect.stringMatching(/still running in the background/));
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 1e5ed4ef2d..19b67f637c 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -106,6 +106,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useContainerWidth` | `[ref, width]` via ResizeObserver. | Layout responds to a specific container's width. |
| `useCooldownTick` | 1-second ticker over a `{ id: epochMs }` cooldown map; fires `onAllExpired` once when every deadline passes. | Rate-limit countdown labels that need to refetch when the last cooldown clears (agents tabs pattern). |
| `useDrawerTab` | Deep-linkable `[activeTab, setActiveTab]` for a tabbed `<Drawer>`, backed by a caller-named URL search param (falls back to a default on stale/missing). | A tabbed config drawer whose open section should be shareable/bookmarkable — use with `<Drawer tabs>`; don't re-roll the search-param plumbing. |
+| `useDownloadPreflightConfirm` | `{ confirm, request({ title, preview, run }), cancel, confirmRun }` — shows a loading modal, resolves a disk-preflight assessment, and holds `run` until confirmed. | Any weight/LoRA download confirm step — pair with `<DownloadPreflightConfirm>`. |
| `useFieldDraft` | Local input draft that commits on blur. | Bible-editor-style single-field input that must dedupe sibling races. |
| `useStoryImportIntake` | Story Builder "Import a finished work" intake: the form fields plus the analyze → commit → create-session workflow, in one `{ ...state, patch, analyze, retryIssues, importAndBuild }` bag. | Call from the always-mounted Story Builder index and pass down as `intake` — holding this in the panel loses the manuscript and analysis on an intake tab flip (#3904). |
| `useRowDraft` | Multi-column row draft (analogue of `useFieldDraft`). | Multi-column row that commits as a unit. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 29985fe422..4b03b6fe03 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -158,6 +158,7 @@ export * from './useAutoRefetch.js';
export * from './useCmdKSearch.js';
export * from './useCooldownTick.js';
export { default as useDrawerTab } from './useDrawerTab.js';
+export { default as useDownloadPreflightConfirm } from './useDownloadPreflightConfirm.js';
export { default as useChordPlayer } from './useChordPlayer.js';
export { default as useDrumPlayer } from './useDrumPlayer.js';
export * from './useHfTokenStatus.js';
diff --git a/client/src/hooks/useDownloadPreflightConfirm.js b/client/src/hooks/useDownloadPreflightConfirm.js
new file mode 100644
index 0000000000..c463a0e3e0
--- /dev/null
+++ b/client/src/hooks/useDownloadPreflightConfirm.js
@@ -0,0 +1,46 @@
+import { useCallback, useState } from 'react';
+
+// Shared "preview a weight download, then confirm" state machine. Two near-
+// identical copies (LocalLlmTab's model/spec-decode/MTPLX downloads, Loras'
+// Civitai/HuggingFace installs) collapsed to one hook: request() shows a
+// loading modal, resolves the disk-preflight assessment, and holds the
+// caller's `run` callback until confirmRun() fires it.
+//
+// Usage:
+// const { confirm, request, cancel, confirmRun } = useDownloadPreflightConfirm();
+// const install = (modelId) => request({
+// title: 'Install local model',
+// preview: () => previewLocalLlmDownload({ kind: 'install', backend, modelId }, { silent: true }),
+// run: () => startInstall(modelId),
+// });
+// <DownloadPreflightConfirm open={Boolean(confirm)} {...confirm} onCancel={cancel} onConfirm={confirmRun} />
+export default function useDownloadPreflightConfirm() {
+ const [confirm, setConfirm] = useState(null);
+
+ const request = useCallback(({ title, preview, run }) => {
+ setConfirm({ title, loading: true, error: null, assessment: null, run: null });
+ return preview()
+ .then((assessment) => {
+ setConfirm({ title, loading: false, error: null, assessment, run });
+ })
+ .catch((err) => {
+ setConfirm({
+ title,
+ loading: false,
+ error: err?.message || 'Could not check disk space',
+ assessment: null,
+ run: null,
+ });
+ });
+ }, []);
+
+ const cancel = useCallback(() => setConfirm(null), []);
+ const confirmRun = useCallback(() => {
+ setConfirm((prev) => {
+ prev?.run?.();
+ return null;
+ });
+ }, []);
+
+ return { confirm, request, cancel, confirmRun };
+}
diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsx
index c3cbbe63ed..5d1bc7ce01 100644
--- a/client/src/pages/Loras.jsx
+++ b/client/src/pages/Loras.jsx
@@ -14,17 +14,20 @@ import BrailleSpinner from '../components/BrailleSpinner';
import PageSkeleton from '../components/ui/PageSkeleton';
import toast from '../components/ui/Toast';
import Modal from '../components/ui/Modal';
+import DownloadPreflightConfirm from '../components/models/DownloadPreflightConfirm.jsx';
import Banner from '../components/ui/Banner';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
import ProgressBar from '../components/ui/ProgressBar';
import { FormField } from '../components/ui/FormField';
import { useConfirmDelete } from '../hooks/useConfirmDelete';
+import useDownloadPreflightConfirm from '../hooks/useDownloadPreflightConfirm';
import { formatBytes } from '../utils/formatters';
import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES, isVideoLoraFamily } from '../lib/runnerFamilies';
import { LORA_EFFECT_STATUSES, formatLoraEffect, loraEffectBadge } from '../lib/loraEffect';
import {
listLorasFull,
installLoraFromCivitai,
+ previewLoraInstall,
installLoraFromHuggingfaceStream,
deleteLoraFull,
getCivitaiAuth,
@@ -127,6 +130,7 @@ export default function Loras() {
const [suggestions, setSuggestions] = useState(null);
const [loadingSuggestions, setLoadingSuggestions] = useState(true);
const [installingSuggestion, setInstallingSuggestion] = useState(null);
+ const { confirm: downloadConfirm, request: requestDownloadConfirm, cancel: cancelDownloadConfirm, confirmRun: runDownloadConfirm } = useDownloadPreflightConfirm();
// Repo+file key of the video suggestion currently installing. A single HF
// repo can publish multiple versions that must remain independently selectable.
const [installingVideoKey, setInstallingVideoKey] = useState(null);
@@ -161,7 +165,13 @@ export default function Loras() {
// silent:true so the auth-error path goes through the modal instead of a
// one-shot toast the user can't act on. Shared by the initial install
// submit and the post-key-save retry so both behave identically.
- const performInstall = useCallback(async (url) => {
+ const requestLoraDownload = useCallback((title, url, source, run) => requestDownloadConfirm({
+ title,
+ preview: () => previewLoraInstall({ url, source, silent: true }),
+ run,
+ }), [requestDownloadConfirm]);
+
+ const startCivitaiInstall = useCallback(async (url) => {
if (!url || installing) return;
setInstalling(true);
await installLoraFromCivitai({ url, silent: true })
@@ -184,7 +194,12 @@ export default function Loras() {
}
})
.finally(() => setInstalling(false));
- }, [installing]);
+ }, [installing, refresh]);
+
+ const performInstall = useCallback((url) => {
+ if (!url || installing) return undefined;
+ return requestLoraDownload('Install LoRA', url, 'civitai', () => startCivitaiInstall(url));
+ }, [installing, requestLoraDownload, startCivitaiInstall]);
const handleInstall = (e) => {
e?.preventDefault?.();
@@ -227,8 +242,10 @@ export default function Loras() {
const handleHfInstall = useCallback((e) => {
e?.preventDefault?.();
setHfFamilyPrompt(null);
- return runHfInstall(hfUrl.trim(), undefined);
- }, [hfUrl, runHfInstall]);
+ const url = hfUrl.trim();
+ if (!url) return undefined;
+ return requestLoraDownload('Install HuggingFace LoRA', url, 'huggingface', () => runHfInstall(url, undefined));
+ }, [hfUrl, runHfInstall, requestLoraDownload]);
// Quick-install a curated video LoRA suggestion. Routes through the HF
// installer (not the Civitai one) with the card's known family. Tracks the
@@ -471,6 +488,16 @@ export default function Loras() {
: <LoraGrid loras={visibleLoras} deleting={deleting} onDelete={handleDelete} onMeasured={handleMeasured} deleteConfirm={deleteConfirm} />
)}
</div>
+ <DownloadPreflightConfirm
+ open={Boolean(downloadConfirm)}
+ title={downloadConfirm?.title}
+ loading={Boolean(downloadConfirm?.loading)}
+ error={downloadConfirm?.error}
+ assessment={downloadConfirm?.assessment}
+ confirmLabel="Start download"
+ onCancel={cancelDownloadConfirm}
+ onConfirm={runDownloadConfirm}
+ />
</div>
);
}
diff --git a/client/src/pages/Loras.test.jsx b/client/src/pages/Loras.test.jsx
index a8dcd97318..9f021c56d2 100644
--- a/client/src/pages/Loras.test.jsx
+++ b/client/src/pages/Loras.test.jsx
@@ -12,6 +12,9 @@ import { listLorasFull, deleteLoraFull, installLoraFromHuggingfaceStream, probeL
vi.mock('../services/api', () => ({
listLorasFull: vi.fn(),
installLoraFromCivitai: vi.fn(),
+ previewLoraInstall: vi.fn(async () => ({
+ kind: 'civitai', destPath: 'lora-x.safetensors', expectedBytes: 1024, freeBytes: 1e12, requiredBytes: 1024, headroomBytes: 0, verdict: 'ok',
+ })),
installLoraFromHuggingfaceStream: vi.fn(),
deleteLoraFull: vi.fn(),
getCivitaiAuth: vi.fn(async () => ({ hasKey: false, source: 'none' })),
@@ -128,6 +131,7 @@ describe('Loras HuggingFace family picker', () => {
const input = await screen.findByLabelText('HuggingFace LoRA URL');
fireEvent.change(input, { target: { value: 'https://huggingface.co/Alissonerdx/CharacterSheet' } });
fireEvent.submit(input.closest('form'));
+ fireEvent.click(await screen.findByRole('button', { name: 'Start download' }));
expect(await screen.findByRole('button', { name: 'Install as Flux 2' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Install as Flux 1' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Install as LTX-Video' })).toBeInTheDocument();
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index fb307904fb..4e14e19b3f 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -430,6 +430,12 @@ export const installLoraFromCivitai = ({ url, silent = false } = {}) => request(
silent,
});
+export const previewLoraInstall = ({ url, source = 'civitai', silent = false } = {}) => request('/loras/install/preflight', {
+ method: 'POST',
+ body: JSON.stringify({ url, source }),
+ silent,
+});
+
// Streaming HF LoRA install — reads a byte-level progress stream. Resolves
// with the new sidecar on the `complete` frame; rejects with an Error carrying
// `.code` (e.g. 'HF_UNKNOWN_FAMILY', 'HF_ALREADY_INSTALLED') on an `error`
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index 5cd23b10ee..6f8ab494b0 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -157,6 +157,13 @@ export const upgradeLlamaServer = () =>
// from Hugging Face into the path the launcher passes llama.cpp. Byte progress
// arrives on the `llamaServer:download` socket event, not in this response —
// a multi-GB transfer resolves only when the file is on disk.
+export const previewLocalLlmDownload = (body, options) =>
+ request('/local-llm/download-preflight', {
+ method: 'POST',
+ body: JSON.stringify(body),
+ ...options,
+ });
+
export const downloadSpecDecodeModel = (presetId, role, options) =>
request('/local-llm/llama-server/download-model', {
method: 'POST',
diff --git a/server/lib/README.md b/server/lib/README.md
index f9381d1a0b..98800f1fd6 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -220,7 +220,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `saveOneNow` / `listIds` / `loadAll` / `loadAllResult` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. `loadAll` silently drops corrupt records; `loadAllResult()` → `{ records, failedIds }` keeps the "which ids failed to load" signal so a caller can tell a partial set from a complete one. Per-id write queue means writes to different records don't serialize; `saveOneNow` is for callers already inside a collection write queue. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. **Type-index `config` slot** holds cross-record state (see the `TypeIndexConfig` typedef + header convention): `{ runs?: [], featureFlags?: {}, lockPolicies?: {} }` — `runs` is the shipped slot (universeBuilder's capped history log), the other two are reserved names; consumers may add their own keys but should reuse a reserved name when it fits and document the shape next to the consumer. `saveTypeIndex({ config })` shallow-merges `config` one level deep (a patched `runs` replaces the whole array), so a read-modify-write of a slot must load → mutate a copy → write inside `queueTypeIndexWrite(fn)`. |
| `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`. |
+| `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). `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. `probeRemoteSize` / `siblingDownloadMeta` / `verifyDownloadHash` are the size+digest helpers the four weight-download entry points share. |
| `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 fbd3a76608..c363efd736 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -8838,6 +8838,14 @@
"server/routes/localLlm.js"
]
},
+ {
+ "method": "POST",
+ "path": "/api/local-llm/download-preflight",
+ "mountPath": "/api/local-llm",
+ "sources": [
+ "server/routes/localLlm.js"
+ ]
+ },
{
"method": "GET",
"path": "/api/local-llm/huggingface-search",
@@ -9550,6 +9558,14 @@
"server/routes/loras.js"
]
},
+ {
+ "method": "POST",
+ "path": "/api/loras/install/preflight",
+ "mountPath": "/api/loras",
+ "sources": [
+ "server/routes/loras.js"
+ ]
+ },
{
"method": "GET",
"path": "/api/loras/search",
@@ -17457,8 +17473,8 @@
],
"stats": {
"mounts": 147,
- "operations": 2162,
- "declarations": 2166,
+ "operations": 2164,
+ "declarations": 2168,
"sourceFiles": 229
}
}
diff --git a/server/lib/downloadPreflight.js b/server/lib/downloadPreflight.js
new file mode 100644
index 0000000000..5f6647f496
--- /dev/null
+++ b/server/lib/downloadPreflight.js
@@ -0,0 +1,316 @@
+/**
+ * Free-disk preflight, hash verification, and resumable streaming for large
+ * weight downloads.
+ *
+ * A multi-gigabyte GGUF/safetensors pull is a decision the user makes with
+ * numbers in front of them: before transferring anything we report size,
+ * destination, and free disk, and refuse outright when the volume cannot hold
+ * it. An interrupted transfer keeps its `.partial` so a retry can Range-resume
+ * rather than restart; a completed file is checked against a published hash
+ * before it is allowed to become a selectable model.
+ *
+ * `statfs` is already used for health/resources — this is the same reading,
+ * consulted before spending tens of gigabytes.
+ */
+
+import { createWriteStream } from 'fs';
+import { rm, stat, statfs, rename } from 'fs/promises';
+import { dirname } from 'path';
+import { Readable, Transform } from 'stream';
+import { pipeline } from 'stream/promises';
+import { ServerError } from './errorHandler.js';
+import { ensureDir, sha256File } from './fileCore.js';
+
+/** Spare room kept on top of the advertised payload so a full disk isn't a photo-finish. */
+export const DOWNLOAD_HEADROOM_BYTES = 512 * 1024 * 1024;
+
+export const DOWNLOAD_VERDICTS = Object.freeze({
+ OK: 'ok',
+ TIGHT: 'tight',
+ INSUFFICIENT: 'insufficient',
+});
+
+/** After the download, remaining free space below this share of current free is "tight". */
+const TIGHT_REMAINING_RATIO = 0.1;
+
+const PARTIAL_SUFFIX = '.partial';
+
+export const partialPathFor = (destPath) => `${destPath}${PARTIAL_SUFFIX}`;
+
+export function normalizeSha256(value) {
+ if (typeof value !== 'string') return null;
+ const hex = value.trim().toLowerCase().replace(/^sha256:/, '').replace(/['"]/g, '');
+ return /^[0-9a-f]{64}$/.test(hex) ? hex : null;
+}
+
+/** Size + digest a Hugging Face sibling object actually carries (often via LFS). */
+export function siblingDownloadMeta(sibling) {
+ if (!sibling || typeof sibling !== 'object') return { bytes: 0, sha256: null };
+ const bytes = Number(sibling.lfs?.size ?? sibling.size) || 0;
+ return { bytes, sha256: normalizeSha256(sibling.lfs?.sha256 || sibling.lfs?.oid) };
+}
+
+const parseContentRangeTotal = (header) => {
+ const match = String(header || '').match(/\/(\d+)\s*$/);
+ return match ? Number(match[1]) : 0;
+};
+
+async function freeBytesForPath(destPath, statfsImpl) {
+ let probe = destPath || '/';
+ for (let i = 0; i < 8; i += 1) {
+ const stats = await statfsImpl(probe).catch(() => null);
+ if (stats && Number.isFinite(stats.bavail) && Number.isFinite(stats.bsize)) {
+ return stats.bavail * stats.bsize;
+ }
+ const parent = dirname(probe);
+ if (!parent || parent === probe) break;
+ probe = parent;
+ }
+ return null;
+}
+
+/**
+ * Given a destination path and an expected byte total, report free bytes,
+ * required bytes (payload + headroom), and a verdict.
+ *
+ * `freeBytes: null` means statfs was unavailable — the verdict is `ok` so a
+ * failed reading cannot block a download that would have fit. `expectedBytes`
+ * of 0 means the size is unknown: we never refuse (cannot know it will fail)
+ * and never mark tight.
+ *
+ * @param {{ destPath?: string, expectedBytes?: number, headroomBytes?: number, statfsImpl?: typeof statfs }} opts
+ */
+export async function assessDownloadPreflight({
+ destPath,
+ expectedBytes = 0,
+ headroomBytes = DOWNLOAD_HEADROOM_BYTES,
+ statfsImpl = statfs,
+} = {}) {
+ const expected = Math.max(0, Number(expectedBytes) || 0);
+ const headroom = Math.max(0, Number(headroomBytes) || 0);
+ const requiredBytes = expected > 0 ? expected + headroom : 0;
+ const freeBytes = await freeBytesForPath(destPath, statfsImpl);
+
+ let verdict = DOWNLOAD_VERDICTS.OK;
+ if (freeBytes != null && expected > 0 && freeBytes < expected) {
+ verdict = DOWNLOAD_VERDICTS.INSUFFICIENT;
+ } else if (
+ freeBytes != null
+ && expected > 0
+ && freeBytes - expected < Math.max(headroom, freeBytes * TIGHT_REMAINING_RATIO)
+ ) {
+ verdict = DOWNLOAD_VERDICTS.TIGHT;
+ }
+
+ return {
+ destPath: destPath || null,
+ expectedBytes: expected,
+ requiredBytes,
+ headroomBytes: headroom,
+ freeBytes,
+ verdict,
+ };
+}
+
+export function diskInsufficientError(assessment) {
+ const free = assessment.freeBytes == null ? 'unknown' : `${assessment.freeBytes}`;
+ return new ServerError(
+ `Not enough free disk to download ${assessment.expectedBytes} bytes to ${assessment.destPath} (free: ${free}, need ${assessment.requiredBytes} including headroom)`,
+ {
+ status: 507,
+ code: 'DISK_INSUFFICIENT',
+ context: {
+ destPath: assessment.destPath,
+ expectedBytes: assessment.expectedBytes,
+ requiredBytes: assessment.requiredBytes,
+ headroomBytes: assessment.headroomBytes,
+ freeBytes: assessment.freeBytes,
+ verdict: assessment.verdict,
+ },
+ },
+ );
+}
+
+/** Throw DISK_INSUFFICIENT when the verdict is insufficient; otherwise return the assessment. */
+export function assertDownloadFits(assessment) {
+ if (assessment?.verdict === DOWNLOAD_VERDICTS.INSUFFICIENT) {
+ throw diskInsufficientError(assessment);
+ }
+ return assessment;
+}
+
+/**
+ * HEAD (then a 0-byte Range GET) a URL for Content-Length / LFS sha.
+ * Returns `{ bytes: 0, sha256: null }` when the server will not say — never throws
+ * for a probe miss, so a CDN that refuses HEAD cannot block the download.
+ */
+export async function probeRemoteSize(url, { headers = {}, fetchImpl = fetch, signal } = {}) {
+ const empty = { bytes: 0, sha256: null };
+ const readMeta = (res) => {
+ if (!res || typeof res.headers?.get !== 'function') return empty;
+ const length = Number(res.headers.get('content-length')) || 0;
+ const rangeTotal = parseContentRangeTotal(res.headers.get('content-range'));
+ const sha256 = normalizeSha256(
+ res.headers.get('x-linked-etag') || res.headers.get('etag') || '',
+ );
+ return { bytes: rangeTotal || length, sha256 };
+ };
+
+ const head = await fetchImpl(url, { method: 'HEAD', headers, redirect: 'follow', signal }).catch(() => null);
+ if (head?.ok) {
+ const meta = readMeta(head);
+ if (meta.bytes > 0 || meta.sha256) return meta;
+ }
+
+ const ranged = await fetchImpl(url, {
+ method: 'GET',
+ headers: { ...headers, Range: 'bytes=0-0' },
+ redirect: 'follow',
+ signal,
+ }).catch(() => null);
+ if (ranged?.ok || ranged?.status === 206) {
+ // Drain a 1-byte body so the socket can close; ignore failure.
+ await ranged.body?.cancel?.().catch(() => {});
+ return readMeta(ranged);
+ }
+ return empty;
+}
+
+export async function verifyDownloadHash(filePath, expectedSha256) {
+ const want = normalizeSha256(expectedSha256);
+ if (!want) return { ok: true, skipped: true };
+ const actual = (await sha256File(filePath)).toLowerCase();
+ if (actual !== want) return { ok: false, expected: want, actual };
+ return { ok: true, expected: want, actual };
+}
+
+const hashMismatchError = (destPath, check) => new ServerError(
+ `Download failed SHA-256 verification for ${destPath} (expected ${check.expected.slice(0, 12)}…, got ${check.actual.slice(0, 12)}…) — the file was deleted`,
+ {
+ status: 502,
+ code: 'DOWNLOAD_HASH_MISMATCH',
+ context: { destPath, expected: check.expected, actual: check.actual },
+ },
+);
+
+/**
+ * Stream `url` into `${destPath}.partial`, Range-resuming when a leftover
+ * partial exists. Transport/stall failures keep the partial; a user cancel
+ * discards it. Optionally verifies a published sha256 and renames into place.
+ *
+ * @returns {Promise<{ bytes: number, tmpPath: string, resumed: boolean }>}
+ */
+export async function streamResumableDownload({
+ url,
+ destPath,
+ headers = {},
+ fetchImpl = fetch,
+ onBytes = () => {},
+ signal,
+ onIdleStall,
+ idleStallTimeoutMs = 0,
+ isCancelled = () => false,
+ expectedSha256 = null,
+ finalize = true,
+ onHttpError = null,
+} = {}) {
+ const tmpPath = partialPathFor(destPath);
+ await ensureDir(dirname(destPath));
+
+ const existing = await stat(tmpPath).catch(() => null);
+ let resumeFrom = existing?.isFile() ? existing.size : 0;
+
+ const reqHeaders = { ...headers };
+ if (resumeFrom > 0) reqHeaders.Range = `bytes=${resumeFrom}-`;
+
+ let idleTimer = null;
+ const clearIdleTimer = () => {
+ if (!idleTimer) return;
+ clearTimeout(idleTimer);
+ idleTimer = null;
+ };
+ const resetIdleTimer = () => {
+ if (!idleStallTimeoutMs || !onIdleStall) return;
+ clearIdleTimer();
+ idleTimer = setTimeout(() => {
+ try {
+ onIdleStall();
+ } catch (err) {
+ console.error(`❌ Download stall watchdog failed: ${err.message}`);
+ }
+ }, idleStallTimeoutMs);
+ idleTimer.unref?.();
+ };
+
+ resetIdleTimer();
+ try {
+ const res = await fetchImpl(url, { headers: reqHeaders, redirect: 'follow', signal });
+ if (!res.ok && res.status !== 206) {
+ if (res.status === 416 && resumeFrom > 0) {
+ // Partial is past what the server has — start clean.
+ await rm(tmpPath, { force: true }).catch(() => {});
+ resumeFrom = 0;
+ delete reqHeaders.Range;
+ return streamResumableDownload({
+ url, destPath, headers, fetchImpl, onBytes, signal, onIdleStall,
+ idleStallTimeoutMs, isCancelled, expectedSha256, finalize, onHttpError,
+ });
+ }
+ if (onHttpError) onHttpError(res);
+ return rejectDownloadStatus(res);
+ }
+ if (!res.body) {
+ throw new ServerError('Download returned no body', { status: 502, code: 'DOWNLOAD_FAILED' });
+ }
+
+ // Server ignored Range and sent the whole file — discard the leftover prefix.
+ if (resumeFrom > 0 && res.status === 200) {
+ await rm(tmpPath, { force: true }).catch(() => {});
+ resumeFrom = 0;
+ }
+
+ const rangeTotal = parseContentRangeTotal(res.headers?.get?.('content-range'));
+ const contentLength = Number(res.headers?.get?.('content-length')) || 0;
+ const total = rangeTotal || (resumeFrom > 0 ? resumeFrom + contentLength : contentLength);
+ let received = resumeFrom;
+ const flags = resumeFrom > 0 ? 'a' : 'w';
+
+ 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, { flags })).catch(async (err) => {
+ if (isCancelled()) await rm(tmpPath, { force: true }).catch(() => {});
+ throw err;
+ });
+
+ const check = await verifyDownloadHash(tmpPath, expectedSha256);
+ if (!check.ok) {
+ await rm(tmpPath, { force: true }).catch(() => {});
+ throw hashMismatchError(destPath, check);
+ }
+
+ if (finalize) await rename(tmpPath, destPath);
+ return { bytes: received || total, tmpPath, resumed: resumeFrom > 0 };
+ } finally {
+ clearIdleTimer();
+ }
+}
+
+function rejectDownloadStatus(res) {
+ if (res.status === 401 || res.status === 403) {
+ throw new ServerError(
+ `Download rejected (${res.status})`,
+ { status: res.status, code: 'DOWNLOAD_AUTH' },
+ );
+ }
+ throw new ServerError(
+ `Download failed: ${res.status} ${res.statusText || ''}`.trim(),
+ { status: 502, code: 'DOWNLOAD_FAILED' },
+ );
+}
diff --git a/server/lib/downloadPreflight.test.js b/server/lib/downloadPreflight.test.js
new file mode 100644
index 0000000000..b12a0b7b48
--- /dev/null
+++ b/server/lib/downloadPreflight.test.js
@@ -0,0 +1,324 @@
+import { createHash } from 'crypto';
+import { mkdtemp, readFile, rm, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { Readable } from 'stream';
+import { describe, it, expect, afterEach } from 'vitest';
+import {
+ DOWNLOAD_HEADROOM_BYTES,
+ DOWNLOAD_VERDICTS,
+ assessDownloadPreflight,
+ assertDownloadFits,
+ normalizeSha256,
+ siblingDownloadMeta,
+ streamResumableDownload,
+ verifyDownloadHash,
+ partialPathFor,
+ probeRemoteSize,
+} from './downloadPreflight.js';
+
+const GiB = 1024 ** 3;
+
+describe('normalizeSha256 / siblingDownloadMeta', () => {
+ it('accepts bare, prefixed, and quoted sha256 hex', () => {
+ const hex = 'a'.repeat(64);
+ expect(normalizeSha256(hex)).toBe(hex);
+ expect(normalizeSha256(`sha256:${hex}`)).toBe(hex);
+ expect(normalizeSha256(`"${hex}"`)).toBe(hex);
+ expect(normalizeSha256('nope')).toBeNull();
+ expect(normalizeSha256(null)).toBeNull();
+ });
+
+ it('reads size and digest from an LFS sibling', () => {
+ expect(siblingDownloadMeta({
+ rfilename: 'model.gguf',
+ size: 12,
+ lfs: { size: 99, sha256: 'B'.repeat(64) },
+ })).toEqual({ bytes: 99, sha256: 'b'.repeat(64) });
+ });
+
+ it('falls back to the sibling size when LFS is absent', () => {
+ expect(siblingDownloadMeta({ rfilename: 'model.gguf', size: 12 })).toEqual({
+ bytes: 12,
+ sha256: null,
+ });
+ });
+});
+
+describe('assessDownloadPreflight', () => {
+ const statfsImpl = async () => ({ bavail: 10, bsize: GiB }); // 10 GiB free
+
+ it('reports ok when free space covers the payload plus headroom', async () => {
+ const result = await assessDownloadPreflight({
+ destPath: '/models/example.gguf',
+ expectedBytes: 2 * GiB,
+ statfsImpl,
+ });
+ expect(result).toMatchObject({
+ destPath: '/models/example.gguf',
+ expectedBytes: 2 * GiB,
+ requiredBytes: 2 * GiB + DOWNLOAD_HEADROOM_BYTES,
+ freeBytes: 10 * GiB,
+ verdict: DOWNLOAD_VERDICTS.OK,
+ });
+ expect(assertDownloadFits(result)).toBe(result);
+ });
+
+ it('marks tight when the download would leave less than the headroom', async () => {
+ const result = await assessDownloadPreflight({
+ destPath: '/models/example.gguf',
+ expectedBytes: 9.6 * GiB,
+ statfsImpl,
+ });
+ expect(result.verdict).toBe(DOWNLOAD_VERDICTS.TIGHT);
+ expect(() => assertDownloadFits(result)).not.toThrow();
+ });
+
+ it('refuses with DISK_INSUFFICIENT when free space cannot hold the payload', async () => {
+ const result = await assessDownloadPreflight({
+ destPath: '/models/example.gguf',
+ expectedBytes: 12 * GiB,
+ statfsImpl,
+ });
+ expect(result.verdict).toBe(DOWNLOAD_VERDICTS.INSUFFICIENT);
+ expect(result.requiredBytes).toBe(12 * GiB + DOWNLOAD_HEADROOM_BYTES);
+ try {
+ assertDownloadFits(result);
+ throw new Error('expected throw');
+ } catch (err) {
+ expect(err.code).toBe('DISK_INSUFFICIENT');
+ expect(err.status).toBe(507);
+ expect(err.context.freeBytes).toBe(10 * GiB);
+ expect(err.context.expectedBytes).toBe(12 * GiB);
+ }
+ });
+
+ it('does not refuse when the advertised size is unknown', async () => {
+ const result = await assessDownloadPreflight({
+ destPath: '/models/example.gguf',
+ expectedBytes: 0,
+ statfsImpl: async () => ({ bavail: 1, bsize: 1024 }),
+ });
+ expect(result.verdict).toBe(DOWNLOAD_VERDICTS.OK);
+ expect(result.requiredBytes).toBe(0);
+ });
+
+ it('fails open when statfs is unavailable', async () => {
+ const result = await assessDownloadPreflight({
+ destPath: '/models/example.gguf',
+ expectedBytes: 50 * GiB,
+ statfsImpl: async () => { throw new Error('statfs unavailable'); },
+ });
+ expect(result.freeBytes).toBeNull();
+ expect(result.verdict).toBe(DOWNLOAD_VERDICTS.OK);
+ });
+});
+
+describe('probeRemoteSize', () => {
+ it('prefers HEAD Content-Length and an LFS etag', async () => {
+ const fetchImpl = async (_url, opts) => {
+ expect(opts.method).toBe('HEAD');
+ return {
+ ok: true,
+ headers: {
+ get: (name) => ({
+ 'content-length': '12345',
+ 'x-linked-etag': `"${'c'.repeat(64)}"`,
+ }[name] || null),
+ },
+ };
+ };
+ await expect(probeRemoteSize('https://example.com/w.gguf', { fetchImpl }))
+ .resolves.toEqual({ bytes: 12345, sha256: 'c'.repeat(64) });
+ });
+
+ it('falls back to a 0-byte Range GET when HEAD is silent', async () => {
+ const fetchImpl = async (_url, opts) => {
+ if (opts.method === 'HEAD') return { ok: false, status: 405, headers: { get: () => null } };
+ expect(opts.headers.Range).toBe('bytes=0-0');
+ return {
+ ok: true,
+ status: 206,
+ headers: { get: (name) => (name === 'content-range' ? 'bytes 0-0/999' : null) },
+ body: { cancel: async () => {} },
+ };
+ };
+ await expect(probeRemoteSize('https://example.com/w.gguf', { fetchImpl }))
+ .resolves.toEqual({ bytes: 999, sha256: null });
+ });
+});
+
+describe('streamResumableDownload', () => {
+ let dir;
+
+ const makeDir = async () => {
+ dir = await mkdtemp(join(tmpdir(), 'portos-dl-preflight-'));
+ return join(dir, 'weights.gguf');
+ };
+
+ afterEach(async () => {
+ if (dir) await rm(dir, { recursive: true, force: true });
+ dir = null;
+ });
+
+ const webBody = (...chunks) => Readable.toWeb(Readable.from(chunks.map((c) => Buffer.from(c))));
+
+ it('writes the full body and renames the partial into place', async () => {
+ const destPath = await makeDir();
+ const fetchImpl = async () => ({
+ ok: true,
+ status: 200,
+ headers: { get: (name) => (name === 'content-length' ? '6' : null) },
+ body: webBody('gg', 'ufgg'),
+ });
+ const ticks = [];
+ const result = await streamResumableDownload({
+ url: 'https://example.com/w.gguf',
+ destPath,
+ fetchImpl,
+ onBytes: (received, total) => ticks.push({ received, total }),
+ });
+ expect(result.bytes).toBe(6);
+ expect(result.resumed).toBe(false);
+ expect(await readFile(destPath, 'utf8')).toBe('ggufgg');
+ expect(await readFile(partialPathFor(destPath)).catch(() => null)).toBeNull();
+ expect(ticks.at(-1)).toEqual({ received: 6, total: 6 });
+ });
+
+ it('keeps the .partial on a transport failure so a retry can resume', async () => {
+ const destPath = await makeDir();
+ const fetchImpl = async () => ({
+ ok: true,
+ status: 200,
+ headers: { get: () => '99' },
+ body: Readable.toWeb(new Readable({
+ read() { this.destroy(new Error('connection reset')); },
+ })),
+ });
+ await expect(streamResumableDownload({
+ url: 'https://example.com/w.gguf', destPath, fetchImpl,
+ })).rejects.toThrow(/connection reset/);
+ // The file may be empty if the reset happened before the first chunk, but
+ // it must still be there for Range resume — not unlinked.
+ const leftover = await readFile(partialPathFor(destPath)).catch(() => null);
+ expect(leftover).not.toBeNull();
+ expect(await readFile(destPath).catch(() => null)).toBeNull();
+ });
+
+ it('discards the partial when the caller reports a user cancel', async () => {
+ const destPath = await makeDir();
+ const fetchImpl = async () => ({
+ ok: true,
+ status: 200,
+ headers: { get: () => '99' },
+ body: Readable.toWeb(new Readable({
+ read() { this.destroy(new Error('aborted')); },
+ })),
+ });
+ await expect(streamResumableDownload({
+ url: 'https://example.com/w.gguf',
+ destPath,
+ fetchImpl,
+ isCancelled: () => true,
+ })).rejects.toThrow(/aborted/);
+ expect(await readFile(partialPathFor(destPath)).catch(() => null)).toBeNull();
+ });
+
+ it('resumes with Range from the leftover partial and appends', async () => {
+ const destPath = await makeDir();
+ await writeFile(partialPathFor(destPath), 'gg');
+ const fetchImpl = async (_url, opts) => {
+ expect(opts.headers.Range).toBe('bytes=2-');
+ return {
+ ok: true,
+ status: 206,
+ headers: {
+ get: (name) => ({
+ 'content-length': '4',
+ 'content-range': 'bytes 2-5/6',
+ }[name] || null),
+ },
+ body: webBody('ufgg'),
+ };
+ };
+ const result = await streamResumableDownload({
+ url: 'https://example.com/w.gguf', destPath, fetchImpl,
+ });
+ expect(result.resumed).toBe(true);
+ expect(result.bytes).toBe(6);
+ expect(await readFile(destPath, 'utf8')).toBe('ggufgg');
+ });
+
+ it('restarts cleanly when the server ignores Range and sends 200', async () => {
+ const destPath = await makeDir();
+ await writeFile(partialPathFor(destPath), 'XX');
+ const fetchImpl = async (_url, opts) => {
+ expect(opts.headers.Range).toBe('bytes=2-');
+ return {
+ ok: true,
+ status: 200,
+ headers: { get: (name) => (name === 'content-length' ? '4' : null) },
+ body: webBody('full'),
+ };
+ };
+ await streamResumableDownload({
+ url: 'https://example.com/w.gguf', destPath, fetchImpl,
+ });
+ expect(await readFile(destPath, 'utf8')).toBe('full');
+ });
+
+ it('deletes a completed download that does not match the published hash', async () => {
+ const destPath = await makeDir();
+ const payload = Buffer.from('ggufgg');
+ const fetchImpl = async () => ({
+ ok: true,
+ status: 200,
+ headers: { get: (name) => (name === 'content-length' ? String(payload.length) : null) },
+ body: webBody(payload),
+ });
+ await expect(streamResumableDownload({
+ url: 'https://example.com/w.gguf',
+ destPath,
+ fetchImpl,
+ expectedSha256: 'a'.repeat(64),
+ })).rejects.toMatchObject({ code: 'DOWNLOAD_HASH_MISMATCH' });
+ expect(await readFile(destPath).catch(() => null)).toBeNull();
+ expect(await readFile(partialPathFor(destPath)).catch(() => null)).toBeNull();
+ });
+
+ it('accepts a matching published hash', async () => {
+ const destPath = await makeDir();
+ const payload = Buffer.from('ggufgg');
+ const digest = createHash('sha256').update(payload).digest('hex');
+ const fetchImpl = async () => ({
+ ok: true,
+ status: 200,
+ headers: { get: (name) => (name === 'content-length' ? String(payload.length) : null) },
+ body: webBody(payload),
+ });
+ await streamResumableDownload({
+ url: 'https://example.com/w.gguf', destPath, fetchImpl, expectedSha256: digest,
+ });
+ expect(await readFile(destPath)).toEqual(payload);
+ });
+});
+
+describe('verifyDownloadHash', () => {
+ let dir;
+ afterEach(async () => {
+ if (dir) await rm(dir, { recursive: true, force: true });
+ });
+
+ it('skips when no digest was published', async () => {
+ expect(await verifyDownloadHash('/nope', null)).toEqual({ ok: true, skipped: true });
+ });
+
+ it('compares the on-disk digest case-insensitively', async () => {
+ dir = await mkdtemp(join(tmpdir(), 'portos-dl-hash-'));
+ const path = join(dir, 'f.bin');
+ const payload = Buffer.from('abc');
+ await writeFile(path, payload);
+ const digest = createHash('sha256').update(payload).digest('hex').toUpperCase();
+ await expect(verifyDownloadHash(path, digest)).resolves.toMatchObject({ ok: true });
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index ced6270bcb..f87a18b527 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -210,6 +210,7 @@ export * from './projectStoreKit.js';
export * from './createKeyCachedQueue.js';
export * from './createNewestWinsGuard.js';
export * from './dataRoot.js';
+export * from './downloadPreflight.js';
export * from './agentInstructionsFile.js';
export * from './fileCore.js';
export * as fileUtils from './fileUtils.js';
diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.js
index 9c6676fcfe..d82e30dcf8 100644
--- a/server/lib/mediaValidation.js
+++ b/server/lib/mediaValidation.js
@@ -247,6 +247,27 @@ export const localLlmSpecModelDownloadSchema = z.object({
presetId: z.string().trim().min(1).max(100),
role: z.enum(['model', 'draftModel']),
});
+// Confirm-step disk preflight for a weight download. Discriminated on `kind`
+// so the server resolves dest + expected size — the client never supplies a
+// path. `insufficient` is returned as a verdict, not thrown, so the confirm
+// UI can disable the button instead of toasting a failure the user hasn't
+// committed to yet. The download endpoints still throw DISK_INSUFFICIENT.
+export const localLlmDownloadPreflightSchema = z.discriminatedUnion('kind', [
+ z.object({
+ kind: z.literal('spec-decode'),
+ presetId: z.string().trim().min(1).max(100),
+ role: z.enum(['model', 'draftModel']),
+ }),
+ z.object({
+ kind: z.literal('mtplx'),
+ model: mtplxRepoIdSchema.optional().nullable(),
+ }),
+ z.object({
+ kind: z.literal('install'),
+ backend: localLlmBackendSchema,
+ modelId: localLlmModelIdSchema,
+ }),
+]);
export const localLlmHuggingFaceSearchSchema = z.object({
backend: localLlmBackendSchema,
q: z.string().max(160).optional().default(''),
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index aa20475057..2f9331f4f0 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -38,7 +38,8 @@ import {
localLlmMtplxSearchSchema,
localLlmMtplxPullSchema,
localLlmMtplxRemoveSchema,
- localLlmSpecModelDownloadSchema
+ localLlmSpecModelDownloadSchema,
+ localLlmDownloadPreflightSchema,
} from '../lib/validation.js'
import {
getLlamaServerStatus,
@@ -50,9 +51,9 @@ 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 { searchMtplxCatalog, pullMtplxModel, removeMtplxModel } from '../services/mtplxModelManager.js'
+import { searchMtplxCatalog, pullMtplxModel, previewMtplxPull, removeMtplxModel } from '../services/mtplxModelManager.js'
import { saveProcessList } from '../services/pm2.js'
-import { getSpecDecodePresetStatus, downloadSpecDecodeModel, cancelSpecDecodeModelDownload } from '../services/specDecodeModels.js'
+import { getSpecDecodePresetStatus, downloadSpecDecodeModel, previewSpecDecodeDownload, cancelSpecDecodeModelDownload } from '../services/specDecodeModels.js'
import { SPEC_TYPE_SUGGESTIONS } from '../lib/specDecodePresets.js'
import { resetProviderReadinessCache } from '../services/providerReadiness.js'
import { MODEL_ABUSE_GUARD } from '../lib/modelAbuseGuard.js'
@@ -66,7 +67,7 @@ import {
import { searchHuggingFaceModels, enrichCatalogWithVariants, applyMeasuredFit } from '../services/huggingFaceCatalog.js'
import { getMeasuredFits } from '../services/localModelAssessmentStore.js'
import {
- getStatus, listModels, listVisionModels, listToolUseModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend, upgradeBackend, controlOllamaServer,
+ getStatus, listModels, listVisionModels, listToolUseModels, installModel, previewInstallModel, deleteModel, switchBackend, migrateBackend, installBackend, upgradeBackend, controlOllamaServer,
describeInstallProgress
} from '../services/localLlm.js'
import { getModelAbuseGuardStatus, installModelAbuseGuard, cancelModelAbuseGuardInstall } from '../services/modelAbuseGuard.js'
@@ -314,6 +315,23 @@ router.post('/lmstudio-service', asyncHandler(async (req, res) => {
res.json(result)
}))
+// POST /api/local-llm/download-preflight — size / dest / free-disk numbers for
+// the confirm step. Does not start a transfer. An `insufficient` verdict is
+// returned in the body so the UI can disable Confirm; the download endpoints
+// still throw DISK_INSUFFICIENT if the confirm is skipped.
+router.post('/download-preflight', asyncHandler(async (req, res) => {
+ const body = validateRequest(localLlmDownloadPreflightSchema, req.body)
+ if (body.kind === 'spec-decode') {
+ res.json(await previewSpecDecodeDownload({ presetId: body.presetId, role: body.role }))
+ return
+ }
+ if (body.kind === 'mtplx') {
+ res.json(await previewMtplxPull({ model: body.model }))
+ return
+ }
+ res.json(await previewInstallModel(body.backend, body.modelId))
+}))
+
// POST /api/local-llm/install — pull/download a model (streams progress)
router.post('/install', asyncHandler(async (req, res) => {
const { backend, modelId, force } = validateRequest(localLlmInstallSchema, req.body)
diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.js
index 2c916197f2..e64fd20aa7 100644
--- a/server/routes/localLlm.test.js
+++ b/server/routes/localLlm.test.js
@@ -30,6 +30,9 @@ vi.mock('../services/localLlm.js', () => ({
listVisionModels: vi.fn(async () => []),
listToolUseModels: vi.fn(async () => []),
installModel: vi.fn(),
+ previewInstallModel: vi.fn(async () => ({
+ kind: 'install', verdict: 'ok', destPath: '/tmp/models', expectedBytes: 0, freeBytes: 1e12, requiredBytes: 0, headroomBytes: 0,
+ })),
describeInstallProgress: vi.fn((p) => p?.status || null),
deleteModel: vi.fn(),
switchBackend: vi.fn(),
@@ -115,6 +118,9 @@ 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' })),
+ previewSpecDecodeDownload: vi.fn(async () => ({
+ kind: 'spec-decode', verdict: 'ok', destPath: 'models/base.gguf', expectedBytes: 6, freeBytes: 1e12, requiredBytes: 6, headroomBytes: 0, alreadyDownloaded: false,
+ })),
cancelSpecDecodeModelDownload: vi.fn(() => true),
}));
@@ -800,6 +806,25 @@ describe('llama-server routes', () => {
expect(res.status).toBe(400);
});
+ it('POST /api/local-llm/download-preflight returns size, dest, and free disk without starting a transfer', async () => {
+ const { previewSpecDecodeDownload, downloadSpecDecodeModel } = await import('../services/specDecodeModels.js');
+ downloadSpecDecodeModel.mockClear();
+ const res = await request(makeApp())
+ .post('/api/local-llm/download-preflight')
+ .send({ kind: 'spec-decode', presetId: 'test-preset', role: 'model' });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({
+ kind: 'spec-decode',
+ destPath: 'models/base.gguf',
+ expectedBytes: 6,
+ freeBytes: 1e12,
+ verdict: 'ok',
+ });
+ expect(previewSpecDecodeDownload).toHaveBeenCalledWith({ presetId: 'test-preset', role: 'model' });
+ expect(downloadSpecDecodeModel).not.toHaveBeenCalled();
+ });
+
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())
diff --git a/server/routes/loras.js b/server/routes/loras.js
index 8bc884b013..f72eee9ba0 100644
--- a/server/routes/loras.js
+++ b/server/routes/loras.js
@@ -17,6 +17,8 @@ import {
getLora,
installFromCivitai,
installFromHuggingface,
+ previewCivitaiInstall,
+ previewHuggingfaceInstall,
listLoras,
patchLoraSidecar,
} from '../services/loras.js';
@@ -140,6 +142,21 @@ router.post('/install', asyncHandler(async (req, res) => {
res.status(201).json(sidecar);
}));
+// Confirm-step disk preflight for a LoRA install. `source` picks Civitai vs
+// HuggingFace; the URL is the same shape the install endpoints already take.
+const installPreflightSchema = z.object({
+ url: z.string().min(1).max(1024),
+ source: z.enum(['civitai', 'huggingface']).optional().default('civitai'),
+ apiKey: z.string().min(1).max(256).optional(),
+});
+router.post('/install/preflight', asyncHandler(async (req, res) => {
+ const data = validateRequest(installPreflightSchema, req.body);
+ const preview = data.source === 'huggingface'
+ ? await previewHuggingfaceInstall(data)
+ : await previewCivitaiInstall(data);
+ res.json(preview);
+}));
+
// Install an image or video LoRA from a HuggingFace repo (Flux.2 Klein,
// fal / Lightricks LTX, MiniMax H3). `family` is an optional override;
// absence auto-detects from the repo id / tags / filenames.
diff --git a/server/routes/loras.test.js b/server/routes/loras.test.js
index 071ee1b858..342eb5ce2c 100644
--- a/server/routes/loras.test.js
+++ b/server/routes/loras.test.js
@@ -9,6 +9,12 @@ vi.mock('../services/loras.js', () => ({
deleteLora: vi.fn(),
getLora: vi.fn(),
installFromCivitai: vi.fn(),
+ previewCivitaiInstall: vi.fn(async () => ({
+ kind: 'civitai', verdict: 'ok', destPath: 'lora-x.safetensors', expectedBytes: 1024, freeBytes: 1e12, requiredBytes: 1024, headroomBytes: 0,
+ })),
+ previewHuggingfaceInstall: vi.fn(async () => ({
+ kind: 'huggingface', verdict: 'ok', destPath: 'weights.safetensors', expectedBytes: 1024, freeBytes: 1e12, requiredBytes: 1024, headroomBytes: 0,
+ })),
installFromHuggingface: vi.fn(async (_input, { onProgress } = {}) => {
onProgress?.({ received: 4, total: 8 });
onProgress?.({ received: 8, total: 8 });
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
index 0225b07063..a84bbb35bb 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -33,6 +33,8 @@ import { tmpdir } from 'os'
import { pipeline } from 'stream/promises'
import { Readable } from 'stream'
import { PATHS, atomicWrite, ensureDir, pathExists, sleep } from '../lib/fileUtils.js'
+import { ServerError } from '../lib/errorHandler.js'
+import { assessDownloadPreflight, assertDownloadFits } from '../lib/downloadPreflight.js'
import { compareSemver } from '../lib/versionUtils.js'
import { getCatalog, isBackend, mapModelToBackend, getOllamaImportSpec } from '../lib/localLlmCatalog.js'
import { sanitizeOllamaName } from '../lib/localLlmDisk.js'
@@ -907,8 +909,32 @@ export function describeInstallProgress(p) {
* files first so `lms get` actually re-fetches in-place GGUF replacements.
* Ollama's pull already re-checks the registry digest, so force is a no-op there.
*/
+async function localInstallDest(backend) {
+ return backend === 'ollama' ? ollamaManager.getModelsDir() : lmStudioManager.getModelsDir()
+}
+
+export async function previewInstallModel(backend, modelId) {
+ if (!isBackend(backend)) {
+ throw new ServerError(`Unknown backend: ${backend}`, { status: 400 })
+ }
+ const destPath = await localInstallDest(backend)
+ const preflight = await assessDownloadPreflight({ destPath, expectedBytes: 0 })
+ return {
+ kind: 'install',
+ backend,
+ modelId,
+ ...preflight,
+ destPath,
+ alreadyDownloaded: false,
+ }
+}
+
export async function installModel(backend, modelId, onProgress, { force = false } = {}) {
if (!isBackend(backend)) return { success: false, error: `Unknown backend: ${backend}` }
+ assertDownloadFits(await assessDownloadPreflight({
+ destPath: await localInstallDest(backend),
+ expectedBytes: 0,
+ }))
if (backend === 'ollama') {
const importSpec = getOllamaImportSpec(modelId)
const result = importSpec
diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.js
index 8701fc8436..7101c26cd9 100644
--- a/server/services/localLlm.test.js
+++ b/server/services/localLlm.test.js
@@ -36,6 +36,7 @@ const mocks = vi.hoisted(() => ({
deleteModel: vi.fn(async (id) => ({ success: true, modelId: id })),
getLoadedModels: vi.fn(async () => []),
getLastLoadedModelsError: vi.fn(() => null),
+ getModelsDir: vi.fn(() => '/tmp/portos-ollama-models'),
getStatus: vi.fn(async () => ({ available: true, baseUrl: 'x', version: '1', modelCount: 0, models: [] })),
startServer: vi.fn(async () => ({ success: true, running: true })),
stopServer: vi.fn(async () => ({ success: true, running: false })),
@@ -54,6 +55,7 @@ const mocks = vi.hoisted(() => ({
=== String(right).split('/').pop().replace(/-GGUF$/i, '').toLowerCase()),
deleteModel: vi.fn(async (id) => ({ success: true, modelId: id })),
evictDownloadedQuant: vi.fn(async (id) => ({ success: true, modelId: id })),
+ getModelsDir: vi.fn(async () => '/tmp/portos-lmstudio-models'),
downloadModel: vi.fn(async (id) => ({ success: true, modelId: id })),
getStatus: vi.fn(async () => ({ available: false, baseUrl: 'y', loadedModels: 0 })),
resetCache: vi.fn(),
diff --git a/server/services/loras.js b/server/services/loras.js
index b316ea21ba..753be8351e 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -11,20 +11,21 @@
* thing is one POST; progress is reported through the existing image-gen
* SSE channel (TBD — for v1 the client polls).
*
- * No try/catch — errors bubble. Stream-failure cleanup is handled inline by
- * downloadToFile's pipeline().catch (the .partial gets unlinked on network
- * drops, disk full, etc.); only a process crash or power loss can leave a
- * .partial behind, and listLoras() filters those out by extension.
+ * No try/catch — errors bubble. `downloadToFile` Range-resumes a leftover
+ * `.partial` after a transport drop; a user-cancelled SSE disconnect still
+ * discards it. listLoras() filters `.partial` files out by extension.
*/
import { existsSync } from 'fs';
import { link, readFile, rename, rm, stat, unlink } from 'fs/promises';
-import { createWriteStream } from 'fs';
-import { randomBytes } from 'crypto';
-import { Readable, Transform } from 'stream';
-import { pipeline } from 'stream/promises';
import { basename, join } from 'path';
import { ServerError } from '../lib/errorHandler.js';
+import {
+ assessDownloadPreflight,
+ assertDownloadFits,
+ siblingDownloadMeta,
+ streamResumableDownload,
+} from '../lib/downloadPreflight.js';
import { atomicWrite, assertSafeFilename, ensureDir, listDirectoryByExtension, sha256File, PATHS } from '../lib/fileUtils.js';
import { verifySafetensorsStructure } from '../lib/hfCache.js';
import { isPlainObject } from '../lib/objects.js';
@@ -414,40 +415,24 @@ export const resolveCivitaiKey = async () => {
return fromSettings || env || '';
};
-// Stream-download a URL to a temp file in PATHS.loras then rename into place.
-// The temp suffix prevents the listLoras endpoint from picking up a
-// half-downloaded file. The random suffix avoids clobbering a leftover
-// `.partial` from a previous crashed install (and prevents two concurrent
-// installs of the same target from racing on the same temp path).
-// fetchImpl is injectable for tests.
+// Stream-download a URL to `${destPath}.partial` then link/rename into place.
+// A leftover `.partial` is Range-resumed on retry; a user-cancelled SSE
+// disconnect still discards it. The `.partial` suffix keeps listLoras from
+// picking up a half-written file. fetchImpl is injectable for tests.
// `onProgress({ received, total })` (optional) fires with byte counts during
// the stream download — the manager's streaming install endpoint forwards these
// as SSE `progress` frames so the UI can show a percentage. `total` is 0 when
// the response carries no Content-Length (chunked / some CDN redirects), in
// which case the client renders an indeterminate bar.
const downloadToFile = async (url, destPath, { fetchImpl = fetch, headers = {} , hasApiKey = false, source = 'civitai', onProgress = null, signal = null } = {}) => {
- const tmpPath = `${destPath}.${randomBytes(6).toString('hex')}.partial`;
- // `signal` (optional) aborts the fetch + stream mid-download — the streaming
- // install route passes it so an SSE client disconnect actually cancels a
- // multi-GB transfer instead of letting it run to completion unwatched. On
- // abort the fetch rejects (or the body stream errors), the pipeline().catch
- // below unlinks the .partial, and the throw propagates before any sidecar is
- // written — so a cancelled install leaves nothing behind.
- const res = await fetchImpl(url, { headers, redirect: 'follow', signal });
- if (!res.ok) {
+ const onHttpError = (res) => {
if (res.status === 401 || res.status === 403) {
- // HuggingFace LoRAs: a 401/403 means the repo is gated and the token is
- // missing/insufficient — point the user at the license + HF token UI.
if (source === 'huggingface') {
const message = hasApiKey
? `HuggingFace rejected the download (${res.status}) even with your saved token — accept the model's license on its HF page, or the token may be expired/scoped.`
: `HuggingFace download rejected (${res.status}) — this LoRA's repo is gated. Accept its license on HuggingFace and add your HF token in Image Gen settings, then retry.`;
throw new ServerError(message, { status: res.status, code: 'HF_AUTH' });
}
- // When a key was supplied and Civitai still rejects, the cause is
- // almost always early-access content or a deactivated/scoped key —
- // not a missing key. Don't tell the user to set a key they've
- // already set; surface both possibilities instead.
const message = hasApiKey
? `Civitai rejected the download (${res.status}) even with your saved API key. The LoRA is likely in early-access (Civitai supporters only) or your key has expired/been revoked.`
: `Civitai download rejected (${res.status}) — this LoRA may require an API key. Configure a Civitai API key in PortOS Settings (or set the CIVITAI_API_KEY env var) and retry.`;
@@ -456,42 +441,30 @@ const downloadToFile = async (url, destPath, { fetchImpl = fetch, headers = {} ,
const label = source === 'huggingface' ? 'HuggingFace' : 'Civitai';
const code = source === 'huggingface' ? 'HF_DOWNLOAD_FAILED' : 'CIVITAI_DOWNLOAD_FAILED';
throw new ServerError(`${label} download failed: ${res.status} ${res.statusText}`, { status: 502, code });
- }
- if (!res.body) {
- throw new ServerError('Civitai download returned no body', { status: 502, code: 'CIVITAI_DOWNLOAD_FAILED' });
- }
- // Node 18+ fetch returns a web ReadableStream; pipeline accepts it directly
- // when wrapped in Readable.fromWeb (also handles backpressure correctly).
- // On stream failure (network drop, disk full) the .partial would otherwise
- // accumulate in PATHS.loras across retries.
- const writer = createWriteStream(tmpPath);
- const stages = [Readable.fromWeb(res.body)];
- if (onProgress) {
- // Count bytes via a passthrough Transform — NOT a bare `.on('data')`
- // listener, which flips the source into flowing mode and defeats pipeline's
- // backpressure. `res.headers?.get?.` is defensive: injected test fetch
- // mocks return a bare `{ ok, body }` with no headers object.
- const total = Number(res.headers?.get?.('content-length')) || 0;
- let received = 0;
- let lastEmit = 0;
- stages.push(new Transform({
- transform(chunk, _enc, cb) {
- received += chunk.length;
- // Throttle to ~150ms so a fast link doesn't flood the SSE stream.
+ };
+
+ let lastEmit = 0;
+ let lastTick = { received: 0, total: 0 };
+ const { tmpPath } = await streamResumableDownload({
+ url,
+ destPath,
+ headers,
+ fetchImpl,
+ signal,
+ finalize: false,
+ isCancelled: () => Boolean(signal?.aborted),
+ onHttpError,
+ onBytes: onProgress
+ ? (received, total) => {
+ lastTick = { received, total };
const now = Date.now();
- if (now - lastEmit >= 150) { lastEmit = now; onProgress({ received, total }); }
- cb(null, chunk);
- },
- // Final flush guarantees a 100% (received === total) tick even if the
- // last data chunk landed inside the throttle window.
- flush(cb) { onProgress({ received, total }); cb(); },
- }));
- }
- stages.push(writer);
- await pipeline(...stages).catch(async (err) => {
- await rm(tmpPath, { force: true }).catch(() => {});
- throw err;
+ if (now - lastEmit < 150) return;
+ lastEmit = now;
+ onProgress({ received, total });
+ }
+ : undefined,
});
+ if (onProgress) onProgress(lastTick);
// Atomic no-clobber finalize: `link` is POSIX-atomic and fails with EEXIST
// when destPath already exists (concurrent install that snuck past our
// pre-check). On success we unlink the tmp; on EEXIST we clean up and
@@ -622,6 +595,8 @@ const performCivitaiInstall = async (input, { modelId, versionId, fetchImpl }) =
}
await ensureDir(PATHS.loras);
+ const expectedBytes = Number(file.sizeKB) > 0 ? Number(file.sizeKB) * 1024 : 0;
+ assertDownloadFits(await assessDownloadPreflight({ destPath, expectedBytes }));
console.log(`📥 Installing Civitai LoRA: ${model.name} v${version.id} → ${filename} (${file.sizeKB ? Math.round(file.sizeKB / 1024) + ' MB' : 'size unknown'})`);
// Authenticate downloads via `?token=` only — the Authorization header
@@ -651,6 +626,26 @@ export const installFromCivitai = async (input, { fetchImpl = fetch } = {}) => {
);
};
+/** Size / dest / free-disk numbers for the LoRA confirm step — no transfer. */
+export const previewCivitaiInstall = async (input, { fetchImpl = fetch } = {}) => {
+ const { modelId, versionId } = parseCivitaiUrl(input?.url);
+ const apiKey = (typeof input?.apiKey === 'string' && input.apiKey.trim()) || (await resolveCivitaiKey());
+ const model = await fetchCivitaiModel(modelId, { apiKey, fetchImpl });
+ const version = pickVersion(model, versionId);
+ const file = pickPrimaryFile(version);
+ const slug = slugifyForFilename(model.name || file.name?.replace(/\.safetensors$/i, ''));
+ const filename = `lora-${slug}-v${version.id}.safetensors`;
+ const destPath = join(PATHS.loras, filename);
+ const expectedBytes = Number(file.sizeKB) > 0 ? Number(file.sizeKB) * 1024 : 0;
+ const preflight = await assessDownloadPreflight({ destPath, expectedBytes });
+ return {
+ kind: 'civitai',
+ ...preflight,
+ destPath: filename,
+ alreadyDownloaded: existsSync(destPath),
+ };
+};
+
// Set of recognized LoRA families an HF import may target (image runners +
// video families). Used to validate a user-supplied `family` override.
const HF_LORA_FAMILY_VALUES = new Set(HF_LORA_FAMILIES);
@@ -727,6 +722,9 @@ export const installFromHuggingface = async (input, { fetchImpl = fetch, onProgr
}
await ensureDir(PATHS.loras);
+ const hfSibling = (Array.isArray(model?.siblings) ? model.siblings : []).find((row) => row?.rfilename === file);
+ const expectedBytes = siblingDownloadMeta(hfSibling).bytes;
+ assertDownloadFits(await assessDownloadPreflight({ destPath, expectedBytes }));
console.log(`📥 Installing HuggingFace LoRA: ${repo} (${file}) → ${filename} [family=${family}]`);
await downloadToFile(buildHfResolveUrl(repo, revision, file), destPath, {
fetchImpl,
@@ -749,3 +747,21 @@ export const installFromHuggingface = async (input, { fetchImpl = fetch, onProgr
console.log(`✅ Installed HuggingFace LoRA: ${filename} [layout=${sidecar.keyLayout || 'unknown'}]`);
return sidecar;
};
+
+export const previewHuggingfaceInstall = async (input, { fetchImpl = fetch } = {}) => {
+ const { repo, revision, file: parsedFile } = parseHuggingfaceLoraRef(input?.url);
+ const token = (typeof input?.token === 'string' && input.token.trim()) || (await getHfToken()) || '';
+ const model = await fetchHuggingfaceModel(repo, { token, revision, fetchImpl });
+ const file = pickHfLoraFile(model, parsedFile || input?.file || null);
+ const sibling = (Array.isArray(model?.siblings) ? model.siblings : []).find((row) => row?.rfilename === file);
+ const preflight = await assessDownloadPreflight({
+ destPath: PATHS.loras,
+ expectedBytes: siblingDownloadMeta(sibling).bytes,
+ });
+ return {
+ kind: 'huggingface',
+ ...preflight,
+ destPath: file,
+ alreadyDownloaded: false,
+ };
+};
diff --git a/server/services/mtplxModelManager.js b/server/services/mtplxModelManager.js
index f58f4ccec2..abec518b71 100644
--- a/server/services/mtplxModelManager.js
+++ b/server/services/mtplxModelManager.js
@@ -21,12 +21,16 @@
* so. What changed is that the button now exists.
*/
+import { homedir } from 'os';
import { bufferedSpawn, spawnFailureDetail } from '../lib/bufferedSpawn.js';
import { ServerError } from '../lib/errorHandler.js';
+import { assessDownloadPreflight, assertDownloadFits } from '../lib/downloadPreflight.js';
import { safeJSONParse } from '../lib/fileUtils.js';
+import { fetchHuggingfaceModel } from '../lib/huggingfaceLora.js';
import { listMtplxCachedModels } from '../lib/mtplxModels.js';
import { findCommandOnPath } from '../lib/processEnv.js';
import { fetchRepoPublishedDates } from './huggingFaceCatalog.js';
+import { getHfToken } from './hfToken.js';
import { runStreamingCommand } from '../lib/streamingSpawn.js';
/** A Hugging Face search is one API call — short, and worth failing fast. */
@@ -57,6 +61,24 @@ const REPO_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._-]*$/;
export const isMtplxRepoId = (value) => typeof value === 'string' && REPO_ID_RE.test(value);
+const mtplxCachePath = () => homedir();
+
+async function expectedMtplxBytes(repo) {
+ if (!repo) return 0;
+ const token = await getHfToken();
+ const model = await fetchHuggingfaceModel(repo, { token }).catch(() => null);
+ return Number(model?.usedStorage) || 0;
+}
+
+export async function previewMtplxPull({ model = null } = {}) {
+ const repo = model ? requireRepoId(model) : null;
+ const preflight = await assessDownloadPreflight({
+ destPath: mtplxCachePath(),
+ expectedBytes: await expectedMtplxBytes(repo),
+ });
+ return { kind: 'mtplx', ...preflight, destPath: repo || 'MTPLX cache', alreadyDownloaded: false };
+}
+
/** Resolve `mtplx`, or say why the operation cannot run at all. */
function requireBinary() {
const binary = findCommandOnPath('mtplx');
@@ -179,6 +201,10 @@ export async function pullMtplxModel({ model = null, onProgress = () => {} } = {
const binary = requireBinary();
const repo = model ? requireRepoId(model) : null;
const label = repo || 'MTPLX\'s default verified checkpoint';
+ assertDownloadFits(await assessDownloadPreflight({
+ destPath: mtplxCachePath(),
+ expectedBytes: await expectedMtplxBytes(repo),
+ }));
onProgress({ event: 'start', model: repo, message: `Downloading ${label}. This is a multi-gigabyte download and can take a while.` });
console.log(`⬇️ MTPLX pull started for ${label}`);
diff --git a/server/services/mtplxModelManager.test.js b/server/services/mtplxModelManager.test.js
index c504faff7b..94226aa6a4 100644
--- a/server/services/mtplxModelManager.test.js
+++ b/server/services/mtplxModelManager.test.js
@@ -11,6 +11,8 @@ import * as mtplxModels from '../lib/mtplxModels.js';
import * as processEnv from '../lib/processEnv.js';
import * as streamingSpawn from '../lib/streamingSpawn.js';
import * as hfCatalog from './huggingFaceCatalog.js';
+import * as huggingfaceLora from '../lib/huggingfaceLora.js';
+import * as hfToken from './hfToken.js';
const BINARY = '/opt/homebrew/bin/mtplx';
@@ -23,6 +25,8 @@ describe('mtplxModelManager', () => {
vi.spyOn(mtplxModels, 'listMtplxCachedModels').mockResolvedValue({ models: [], error: null });
// Publish dates come from the Hub — no suite may reach it.
vi.spyOn(hfCatalog, 'fetchRepoPublishedDates').mockResolvedValue({});
+ vi.spyOn(hfToken, 'getHfToken').mockResolvedValue(null);
+ vi.spyOn(huggingfaceLora, 'fetchHuggingfaceModel').mockResolvedValue({ usedStorage: 0 });
vi.spyOn(console, 'log').mockImplementation(() => {});
vi.spyOn(console, 'error').mockImplementation(() => {});
});
diff --git a/server/services/specDecodeModels.js b/server/services/specDecodeModels.js
index b2441a82f3..32b6da1ab7 100644
--- a/server/services/specDecodeModels.js
+++ b/server/services/specDecodeModels.js
@@ -12,15 +12,18 @@
* about which file a relative or `~`-prefixed path means.
*/
-import { createWriteStream } from 'fs';
-import { rename, rm, stat } from 'fs/promises';
-import { dirname, resolve } from 'path';
-import { randomBytes } from 'crypto';
-import { Readable, Transform } from 'stream';
-import { pipeline } from 'stream/promises';
-import { ensureDir, expandHome } from '../lib/fileUtils.js';
+import { stat } from 'fs/promises';
+import { resolve } from 'path';
+import { expandHome } from '../lib/fileUtils.js';
import { isProjectorName, isShardedGguf } from '../lib/localLlmDisk.js';
import { ServerError } from '../lib/errorHandler.js';
+import {
+ assessDownloadPreflight,
+ assertDownloadFits,
+ probeRemoteSize,
+ siblingDownloadMeta,
+ streamResumableDownload,
+} from '../lib/downloadPreflight.js';
import { buildHfAuthHeaders, buildHfResolveUrl, fetchHuggingfaceModel, modelSiblingFilenames } from '../lib/huggingfaceLora.js';
import { getHfToken } from './hfToken.js';
import {
@@ -159,65 +162,48 @@ export function pickGgufSibling(model, { file, quant, repo }) {
);
}
-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?.();
- };
+const hfDownloadHttpError = (res) => {
+ if (res.status === 401 || res.status === 403) {
+ throw new ServerError(
+ `Hugging Face rejected the download (${res.status}) — this repo is gated. Accept its license on Hugging Face and add your HF token in Image Gen settings, then retry.`,
+ { status: res.status, code: 'HF_AUTH' },
+ );
+ }
+ throw new ServerError(`Hugging Face download failed: ${res.status} ${res.statusText}`, { status: 502, code: 'HF_DOWNLOAD_FAILED' });
+};
- 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' });
- }
- 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 streamToFile = async ({ url, headers, destPath, onBytes, signal, onIdleStall, expectedSha256, isCancelled }) => (
+ streamResumableDownload({
+ url,
+ headers,
+ destPath,
+ onBytes,
+ signal,
+ onIdleStall,
+ idleStallTimeoutMs: IDLE_STALL_TIMEOUT_MS,
+ expectedSha256,
+ isCancelled,
+ onHttpError: hfDownloadHttpError,
+ })
+);
+
+const siblingFor = (model, filename) => {
+ const siblings = Array.isArray(model?.siblings) ? model.siblings : [];
+ return siblings.find((row) => row?.rfilename === filename) || null;
+};
+
+const resolveSpecDownloadPlan = async ({ source, destPath, token, signal }) => {
+ const headers = buildHfAuthHeaders(token);
+ const model = await fetchHuggingfaceModel(source.repo, { token, signal });
+ const file = pickGgufSibling(model, { file: source.file, quant: source.quant, repo: source.repo });
+ const url = buildHfResolveUrl(source.repo, 'main', file);
+ let meta = siblingDownloadMeta(siblingFor(model, file));
+ if (!meta.bytes) {
+ const probed = await probeRemoteSize(url, { headers, signal });
+ meta = { bytes: probed.bytes || meta.bytes, sha256: meta.sha256 || probed.sha256 };
}
+ const preflight = await assessDownloadPreflight({ destPath, expectedBytes: meta.bytes });
+ return { file, url, headers, meta, preflight };
};
const downloadAbortError = (state) => {
@@ -278,18 +264,24 @@ export async function downloadSpecDecodeModel({ presetId, role, onProgress = ()
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, signal: state.controller.signal });
+ const plan = await resolveSpecDownloadPlan({
+ source,
+ destPath,
+ 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}`);
+ assertDownloadFits(plan.preflight);
+ console.log(`⬇️ Downloading speculative-decoding weights ${source.repo}/${plan.file} → ${source.path}`);
const { bytes } = await streamToFile({
- url: buildHfResolveUrl(source.repo, 'main', file),
- headers,
+ url: plan.url,
+ headers: plan.headers,
destPath,
+ expectedSha256: plan.meta.sha256,
signal: state.controller.signal,
+ isCancelled: () => state.abortReason === 'cancelled',
onIdleStall: () => {
state.abortReason = 'stalled';
state.controller.abort();
@@ -305,7 +297,7 @@ export async function downloadSpecDecodeModel({ presetId, role, onProgress = ()
});
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, sizeBytes: 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';
@@ -321,6 +313,49 @@ export async function downloadSpecDecodeModel({ presetId, role, onProgress = ()
}
}
+/**
+ * Size / dest / free-disk numbers for the confirm step — no transfer starts.
+ * `alreadyDownloaded` short-circuits the confirm; `verdict: insufficient`
+ * is returned rather than thrown so the UI can disable Confirm instead of
+ * toasting a failure the user hasn't committed to yet.
+ */
+export async function previewSpecDecodeDownload({ presetId, role }) {
+ if (!SPEC_MODEL_ROLES.includes(role)) {
+ throw new ServerError(`Unknown model role "${role}"`, { status: 400 });
+ }
+ const source = specDecodeSource(presetId, role);
+ if (!source) {
+ throw new ServerError(
+ `No Hugging Face source is registered for that preset's ${role === 'model' ? 'base model' : 'drafter'} — download it manually and point the field at the file.`,
+ { status: 400, code: 'SPEC_NO_SOURCE' },
+ );
+ }
+ const destPath = resolveSpecModelPath(source.path);
+ const existing = await fileStat(source.path);
+ if (existing) {
+ return {
+ kind: 'spec-decode',
+ destPath: source.path,
+ expectedBytes: existing.size,
+ requiredBytes: 0,
+ headroomBytes: 0,
+ freeBytes: null,
+ verdict: 'ok',
+ alreadyDownloaded: true,
+ file: null,
+ };
+ }
+ const token = await getHfToken();
+ const plan = await resolveSpecDownloadPlan({ source, destPath, token });
+ return {
+ kind: 'spec-decode',
+ file: plan.file,
+ alreadyDownloaded: false,
+ ...plan.preflight,
+ destPath: source.path,
+ };
+}
+
/** Cancel one active curated GGUF download. Returns false when none is active. */
export function cancelSpecDecodeModelDownload({ presetId, role }) {
if (!SPEC_MODEL_ROLES.includes(role)) {
diff --git a/server/services/specDecodeModels.test.js b/server/services/specDecodeModels.test.js
index 3b6ff2d0ad..d6cb997c73 100644
--- a/server/services/specDecodeModels.test.js
+++ b/server/services/specDecodeModels.test.js
@@ -15,7 +15,7 @@ import * as specDecodePresets from '../lib/specDecodePresets.js';
import * as hfToken from './hfToken.js';
import * as huggingfaceLora from '../lib/huggingfaceLora.js';
-const siblings = (...names) => ({ siblings: names.map((rfilename) => ({ rfilename })) });
+const siblings = (...names) => ({ siblings: names.map((rfilename) => ({ rfilename, size: 6 })) });
describe('pickGgufSibling', () => {
it('matches a quant hint across the naming styles repos actually publish', () => {
@@ -178,7 +178,7 @@ describe('downloadSpecDecodeModel', () => {
expect(frames.at(-1)).toMatchObject({ event: 'complete', role: 'model' });
});
- it('leaves no .partial behind when the transfer fails mid-stream', async () => {
+ it('keeps the .partial on a transport failure so a retry can Range-resume', async () => {
stubPreset();
vi.spyOn(huggingfaceLora, 'fetchHuggingfaceModel').mockResolvedValue(siblings('Example-Q4_K_M.gguf'));
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
@@ -193,7 +193,7 @@ describe('downloadSpecDecodeModel', () => {
await expect(downloadSpecDecodeModel({ presetId: 'test-preset', role: 'model' }))
.rejects.toThrow(/connection reset/);
const { readdir } = await import('fs/promises');
- expect(await readdir(dir)).toEqual([]);
+ expect(await readdir(dir)).toEqual(['base.gguf.partial']);
});
it('cancels an active transfer, emits a terminal frame, and removes its partial file', async () => {
@@ -244,9 +244,15 @@ describe('downloadSpecDecodeModel', () => {
});
const download = downloadSpecDecodeModel({ presetId: 'test-preset', role: 'model' });
+ // Attach the rejection assertion before advancing timers — the extra
+ // promise hop the resumable-download refactor added means the real
+ // stream-destroy → pipeline-reject chain can settle a tick after
+ // advanceTimersByTimeAsync returns, so subscribing afterward races an
+ // "unhandled rejection" against Node's own handler-attached check.
+ const assertion = expect(download).rejects.toMatchObject({ code: 'SPEC_DOWNLOAD_STALLED' });
await vi.waitFor(() => expect(signal).toBeDefined());
await vi.advanceTimersByTimeAsync(20 * 60 * 1000);
- await expect(download).rejects.toMatchObject({ code: 'SPEC_DOWNLOAD_STALLED' });
+ await assertion;
vi.useRealTimers();
});