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

stream HuggingFace LoRA install progress over SSE and group installed LoRAs by media type

[._.]/ Adam Eivy4c1494cd042d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b899251bc8..a1a444e776 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -12,6 +12,8 @@
## Media
+- **Installing a video LoRA from HuggingFace now shows live download progress.** The LoRA Manager's "Install video LoRA from HuggingFace" form (and the curated video quick-install buttons) used to freeze on a static "Downloading…" label with no indication of how far along a multi-GB LoRA was — unlike image-model downloads, which show a percentage. The install now streams byte-level progress over SSE: the button shows `Downloading 42%` and a progress bar with `received / total` bytes fills as it downloads (an indeterminate pulse when the server can't read a Content-Length). Errors — including the "couldn't detect the model family" case that offers the inline "Install as LTX-Video" retry — still surface exactly as before.
+- **The LoRA Manager's Installed list is now grouped by Video / Image.** The curated "Video LoRAs" suggestion cards sat directly above a single flat "Installed" grid, so installed *image* LoRAs looked like they belonged to the video section. The Installed section is now visually divided from the suggestions and, in the "All" view, splits into labeled **Video LoRAs** / **Image LoRAs** subsections (mirroring the suggestion panel) so it's obvious which renders each LoRA applies to. The Image/Video filter still collapses it to a single scoped list.
- **[issue-2036] Sketch & Annotation Canvas (phase 2): re-render an image guided by your annotations.** The annotate page (`/media/annotate/:mediaKey`) gained a "Re-render" action: draw over a generated image, then feed your markup back through local img2img so the marks reshape the render. A confirmation dialog names the exact local model it will run (no surprise AI calls) and lets you add an optional prompt and tune how much to change before it starts; the new render is queued and appears in Media History. Requires a local FLUX img2img runner — the action explains when one isn't available. Phase 3 (blank-canvas storyboard) remains open on #2036.
## MeatSpace POST
diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsx
index ee0168a666..07e22d1e5a 100644
--- a/client/src/pages/Loras.jsx
+++ b/client/src/pages/Loras.jsx
@@ -19,7 +19,7 @@ import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES, isVideoLoraFamily } from '../lib/
import {
listLorasFull,
installLoraFromCivitai,
- installLoraFromHuggingface,
+ installLoraFromHuggingfaceStream,
deleteLoraFull,
getCivitaiAuth,
setCivitaiAuth,
@@ -62,6 +62,12 @@ const MEDIA_FILTERS = [
const suggestionKey = (modelId, versionId) => `${modelId}-${versionId}`;
const cardKey = (card) => suggestionKey(card.modelId, card.versionId);
+// Integer download percent (0..100) from an SSE progress frame, or null when
+// the frame carries no numeric ratio (server sent no Content-Length → the UI
+// shows an indeterminate bar). Shared by the HF install form button, the
+// progress bar, and the curated video quick-install button.
+const pctOf = (progress) => (progress && typeof progress.progress === 'number' ? Math.round(progress.progress * 100) : null);
+
export default function Loras() {
const [loras, setLoras] = useState([]);
const [loading, setLoading] = useState(true);
@@ -72,6 +78,10 @@ export default function Loras() {
// the Civitai installer above because video LoRAs live on HF.
const [hfUrl, setHfUrl] = useState('');
const [hfInstalling, setHfInstalling] = useState(false);
+ // Byte-level download progress for the in-flight HF install (form OR curated
+ // quick-install — only one runs at a time). `{ received, total, progress }`
+ // where progress is 0..1, or null when the server had no Content-Length.
+ const [hfProgress, setHfProgress] = useState(null);
// When autodetection can't classify the repo (HF_UNKNOWN_FAMILY), hold the
// URL here to render an inline "install as LTX-Video?" confirm row — the API
// supports an explicit family override, so a valid LTX LoRA with an
@@ -158,7 +168,8 @@ export default function Loras() {
const runHfInstall = useCallback(async (url, family) => {
if (!url || hfInstalling) return;
setHfInstalling(true);
- await installLoraFromHuggingface({ url, family, silent: true })
+ setHfProgress(null);
+ await installLoraFromHuggingfaceStream({ url, family, onProgress: setHfProgress })
.then((sidecar) => {
toast.success(`Installed ${sidecar.name}`);
setHfUrl('');
@@ -175,7 +186,7 @@ export default function Loras() {
toast.error(err?.message || 'HuggingFace install failed');
}
})
- .finally(() => setHfInstalling(false));
+ .finally(() => { setHfInstalling(false); setHfProgress(null); });
}, [hfInstalling, refresh]);
const handleHfInstall = useCallback((e) => {
@@ -191,13 +202,14 @@ export default function Loras() {
const installVideoSuggestion = useCallback(async (card) => {
if (!card?.installUrl || installingVideoRepo) return;
setInstallingVideoRepo(card.repo);
- await installLoraFromHuggingface({ url: card.installUrl, family: card.runnerFamily, silent: true })
+ setHfProgress(null);
+ await installLoraFromHuggingfaceStream({ url: card.installUrl, family: card.runnerFamily, onProgress: setHfProgress })
.then((sidecar) => {
toast.success(`Installed ${sidecar.name}`);
refresh();
})
.catch((err) => toast.error(err?.message || 'HuggingFace install failed'))
- .finally(() => setInstallingVideoRepo(null));
+ .finally(() => { setInstallingVideoRepo(null); setHfProgress(null); });
}, [installingVideoRepo, refresh]);
const handleDelete = async (filename) => {
@@ -220,6 +232,10 @@ export default function Loras() {
return true;
});
+ // Download percent for the in-flight HF install (drives the form button label
+ // and progress bar), or null when the total is unknown.
+ const hfPct = pctOf(hfProgress);
+
return (
<div className="space-y-6">
<div>
@@ -287,9 +303,10 @@ export default function Loras() {
disabled={hfInstalling || !hfUrl.trim()}
className="bg-port-accent text-white px-4 py-2 rounded text-sm font-medium hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
>
- {hfInstalling ? 'Downloading…' : 'Install'}
+ {hfInstalling ? (hfPct != null ? `Downloading ${hfPct}%` : 'Downloading…') : 'Install'}
</button>
</div>
+ {hfInstalling && <HfDownloadProgress progress={hfProgress} />}
<p className="text-xs text-gray-500">
Paste a <code className="bg-port-bg px-1 rounded">huggingface.co</code> repo URL — or an{' '}
<code className="bg-port-bg px-1 rounded">org/name</code> id — for an LTX-Video LoRA
@@ -308,7 +325,7 @@ export default function Loras() {
disabled={hfInstalling}
className="bg-port-accent text-white px-3 py-1 rounded text-xs font-medium hover:bg-port-accent/90 disabled:opacity-50"
>
- {hfInstalling ? 'Installing…' : 'Install as LTX-Video'}
+ {hfInstalling ? (hfPct != null ? `Installing ${hfPct}%` : 'Installing…') : 'Install as LTX-Video'}
</button>
<button
type="button"
@@ -351,6 +368,7 @@ export default function Loras() {
installedHfRepos={new Set(loras.map((l) => l.huggingface?.repo).filter(Boolean))}
installingSuggestionKey={installingSuggestion}
installingVideoRepo={installingVideoRepo}
+ installingVideoProgress={hfProgress}
onRefresh={() => refreshSuggestions({ force: true })}
onInstallVideo={installVideoSuggestion}
onInstall={async (card, url, versionId) => {
@@ -364,7 +382,11 @@ export default function Loras() {
}}
/>
- <div>
+ {/* Border-top divides "Installed" from the suggestion panel above — the
+ curated "Video LoRAs" suggestions used to butt straight up against a
+ flat Installed grid, making installed image LoRAs read as if they were
+ part of the video section. */}
+ <div className="border-t border-port-border pt-6">
<h2 className="text-lg font-semibold text-white mb-3">Installed</h2>
{loading && <div className="text-sm text-gray-500">Loading…</div>}
{error && (
@@ -377,14 +399,41 @@ export default function Loras() {
: `No ${mediaFilter} LoRAs installed.`}
</div>
)}
+ {/* On "All", split installed LoRAs into Video/Image subsections (with the
+ same header style as the suggestion panel) so it's self-evident which
+ renders each applies to. A specific filter already scopes the list, so
+ render it flat. */}
{visibleLoras.length > 0 && (
- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
- {visibleLoras.map((lora) => (
- <LoraCard key={lora.filename} lora={lora} onDelete={() => handleDelete(lora.filename)} deleting={deleting === lora.filename} />
- ))}
- </div>
+ mediaFilter === 'all'
+ ? <InstalledGroups loras={visibleLoras} deleting={deleting} onDelete={handleDelete} />
+ : <LoraGrid loras={visibleLoras} deleting={deleting} onDelete={handleDelete} />
+ )}
+ </div>
+ </div>
+ );
+}
+
+// Byte-level download progress bar for an in-flight HuggingFace LoRA install.
+// `progress` is `{ received, total, progress }` (progress 0..1) or null. When
+// the server had no Content-Length (total 0 / progress null) the bar renders an
+// indeterminate pulse instead of a fill.
+function HfDownloadProgress({ progress }) {
+ const pct = pctOf(progress);
+ const total = progress?.total || 0;
+ return (
+ <div className="space-y-1">
+ <div className="flex items-center justify-between text-[11px] text-gray-400">
+ <span>{pct != null ? `Downloading… ${pct}%` : 'Downloading…'}</span>
+ {total > 0 && (
+ <span className="font-mono text-gray-500">{formatBytes(progress.received)} / {formatBytes(total)}</span>
)}
</div>
+ <div className="h-1.5 w-full overflow-hidden rounded-full bg-port-bg" role="progressbar" aria-valuenow={pct ?? undefined} aria-valuemin={0} aria-valuemax={100}>
+ <div
+ className={`h-full bg-port-accent ${pct != null ? 'transition-[width] duration-200' : 'w-1/3 animate-pulse'}`}
+ style={pct != null ? { width: `${pct}%` } : undefined}
+ />
+ </div>
</div>
);
}
@@ -417,7 +466,7 @@ function MediaFilter({ value, onChange }) {
);
}
-function SuggestionsPanel({ suggestions, loading, mediaFilter = 'all', installedFilenames, installedHfRepos, installingSuggestionKey, installingVideoRepo, onRefresh, onInstall, onInstallVideo }) {
+function SuggestionsPanel({ suggestions, loading, mediaFilter = 'all', installedFilenames, installedHfRepos, installingSuggestionKey, installingVideoRepo, installingVideoProgress, onRefresh, onInstall, onInstallVideo }) {
const curated = suggestions?.curated || [];
const runners = suggestions?.runners || {};
const video = suggestions?.video || [];
@@ -479,6 +528,7 @@ function SuggestionsPanel({ suggestions, loading, mediaFilter = 'all', installed
cards={video}
installedHfRepos={installedHfRepos}
installingVideoRepo={installingVideoRepo}
+ installingVideoProgress={installingVideoProgress}
onInstall={onInstallVideo}
/>
)}
@@ -490,7 +540,7 @@ function SuggestionsPanel({ suggestions, loading, mediaFilter = 'all', installed
// like the Civitai sections — it's a small hand-picked list installed via the
// HF path. Installed-state matches on the repo (HF installs carry no
// modelId/versionId).
-function VideoSuggestionsSection({ cards, installedHfRepos, installingVideoRepo, onInstall }) {
+function VideoSuggestionsSection({ cards, installedHfRepos, installingVideoRepo, installingVideoProgress, onInstall }) {
const list = cards || [];
return (
<div>
@@ -512,6 +562,7 @@ function VideoSuggestionsSection({ cards, installedHfRepos, installingVideoRepo,
card={card}
installed={installedHfRepos?.has(card.repo)}
installing={installingVideoRepo === card.repo}
+ progress={installingVideoRepo === card.repo ? installingVideoProgress : null}
onInstall={onInstall}
/>
))}
@@ -521,7 +572,8 @@ function VideoSuggestionsSection({ cards, installedHfRepos, installingVideoRepo,
);
}
-function VideoSuggestionCard({ card, installed, installing, onInstall }) {
+function VideoSuggestionCard({ card, installed, installing, progress, onInstall }) {
+ const pct = pctOf(progress);
return (
<div className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col">
{card.previewImageUrl ? (
@@ -557,7 +609,7 @@ function VideoSuggestionCard({ card, installed, installing, onInstall }) {
disabled={installing}
className="flex-1 bg-port-accent text-white px-3 py-1.5 rounded text-xs font-medium hover:bg-port-accent/90 disabled:opacity-50"
>
- {installing ? 'Installing…' : 'Quick install'}
+ {installing ? (pct != null ? `Installing ${pct}%` : 'Installing…') : 'Quick install'}
</button>
)}
</div>
@@ -953,6 +1005,45 @@ function CivitaiAuthModal({ pendingUrl, message, auth, onClose, onSaved, onRetry
);
}
+// Responsive grid of installed LoRA cards. Extracted so the Installed section
+// can render either one flat grid (filtered view) or several grouped grids
+// (the "All" view) without duplicating the grid markup.
+function LoraGrid({ loras, deleting, onDelete }) {
+ return (
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
+ {loras.map((lora) => (
+ <LoraCard key={lora.filename} lora={lora} onDelete={() => onDelete(lora.filename)} deleting={deleting === lora.filename} />
+ ))}
+ </div>
+ );
+}
+
+// Installed LoRAs split into Video / Image subsections for the "All" view, each
+// with a labeled header mirroring the suggestion panel's grouping. Empty groups
+// are omitted. Video is listed first (fewer, and the source of the layout
+// confusion this grouping resolves).
+function InstalledGroups({ loras, deleting, onDelete }) {
+ const video = loras.filter((l) => isVideoLoraFamily(l.runnerFamily));
+ const image = loras.filter((l) => !isVideoLoraFamily(l.runnerFamily));
+ const groups = [
+ { key: 'video', label: 'Video LoRAs', items: video },
+ { key: 'image', label: 'Image LoRAs', items: image },
+ ].filter((g) => g.items.length > 0);
+ return (
+ <div className="space-y-5">
+ {groups.map((g) => (
+ <div key={g.key}>
+ <div className="flex items-baseline gap-3 mb-2">
+ <h3 className="text-sm font-medium text-gray-300">{g.label}</h3>
+ <span className="text-xs text-gray-600">{g.items.length}</span>
+ </div>
+ <LoraGrid loras={g.items} deleting={deleting} onDelete={onDelete} />
+ </div>
+ ))}
+ </div>
+ );
+}
+
function LoraCard({ lora, onDelete, deleting }) {
const family = lora.runnerFamily;
const familyLabel = family ? (RUNNER_LABEL[family] || family) : 'Unsupported base';
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 48bc800d68..2aa987a060 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -281,6 +281,42 @@ export const installLoraFromHuggingface = ({ url, family, silent = false } = {})
silent,
});
+// Streaming HF LoRA install — same install as installLoraFromHuggingface but
+// over an EventSource so the caller gets byte-level download progress. Resolves
+// with the new sidecar on the `complete` frame; rejects with an Error carrying
+// `.code` (e.g. 'HF_UNKNOWN_FAMILY', 'HF_ALREADY_INSTALLED') on `error`, so the
+// page can drive the same inline family-confirm retry it does for the POST path.
+// `onProgress({ received, total, progress })` fires per throttled download tick
+// — `progress` is 0..1, or null when the server had no Content-Length to divide.
+export function installLoraFromHuggingfaceStream({ url, family, onProgress } = {}) {
+ const params = new URLSearchParams({ url });
+ if (family) params.set('family', family);
+ const es = new EventSource(`/api/loras/install/huggingface/stream?${params.toString()}`);
+ return new Promise((resolve, reject) => {
+ es.onmessage = (evt) => {
+ let data;
+ try { data = JSON.parse(evt.data); } catch { return; }
+ if (data.type === 'progress') { onProgress?.(data); return; }
+ if (data.type === 'complete') { es.close(); resolve(data.sidecar); return; }
+ if (data.type === 'error') {
+ es.close();
+ const err = new Error(data.message || 'HuggingFace install failed');
+ err.code = data.code || null;
+ reject(err);
+ }
+ };
+ es.onerror = () => {
+ // A normal completion/error already closed the ES above; this only fires
+ // on a real transport failure (non-2xx open, dropped stream), which
+ // EventSource surfaces as readyState CLOSED with no auto-retry. Reject so
+ // the caller's spinner clears instead of hanging forever.
+ if (es.readyState === EventSource.CLOSED) {
+ reject(new Error('Download stream closed before completing'));
+ }
+ };
+ });
+}
+
// Civitai LoRA suggestions per runner family. Cached server-side for 1h.
// Pass `force: true` to bust the cache and re-fetch from Civitai.
export const getCivitaiSuggestions = ({ force = false } = {}) =>
diff --git a/server/routes/loras.js b/server/routes/loras.js
index 01d8d7009d..e62219f00e 100644
--- a/server/routes/loras.js
+++ b/server/routes/loras.js
@@ -25,6 +25,7 @@ import { getVideoSuggestions } from '../services/videoLoraSuggestions.js';
import { findLorasByCharacter } from '../services/characterLoraResolver.js';
import { getSettings, updateSettingsWith } from '../services/settings.js';
import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES } from '../lib/runners.js';
+import { openSseStream } from '../lib/sseDownload.js';
const router = Router();
@@ -140,6 +141,41 @@ router.post('/install/huggingface', asyncHandler(async (req, res) => {
res.status(201).json(sidecar);
}));
+// Streaming variant of the HF install for the manager UI. Same install, but
+// emits byte-level download `progress` frames over SSE so the form can show a
+// percentage instead of a static "Downloading…" (matching the image/video
+// model download badge UX). EventSource is GET-only, so url/family ride in the
+// query string; the HF token always comes from settings/env (never the query,
+// to keep it out of URLs and access logs). Terminal frames:
+// `{type:'complete', sidecar}` or `{type:'error', message, code}` — the client
+// re-uses `code` (e.g. HF_UNKNOWN_FAMILY) to drive the inline family-confirm
+// retry, exactly as the POST path's thrown error does.
+const hfInstallStreamSchema = z.object({
+ url: z.string().min(1).max(1024),
+ family: z.enum(Object.values(VIDEO_LORA_FAMILIES)).optional(),
+});
+router.get('/install/huggingface/stream', asyncHandler(async (req, res) => {
+ const data = validateRequest(hfInstallStreamSchema, req.query);
+ const { send, safeEnd } = openSseStream(res);
+ // Headers are already flushed once the stream is open, so an install failure
+ // must NOT bubble to the error middleware (it would try to re-set status on a
+ // committed response). Catch and forward as an SSE `error` frame instead —
+ // the sanctioned SSE-boundary exception to the no-try/catch rule.
+ let aborted = false;
+ req.on('close', () => { aborted = true; });
+ await installFromHuggingface(data, {
+ onProgress: ({ received, total }) => {
+ if (aborted) return;
+ send({ type: 'progress', received, total, progress: total > 0 ? received / total : null });
+ },
+ })
+ .then((sidecar) => { if (!aborted) send({ type: 'complete', sidecar }); })
+ .catch((err) => {
+ if (!aborted) send({ type: 'error', message: err?.message || 'HuggingFace install failed', code: err?.code || null });
+ });
+ safeEnd();
+}));
+
// Trained LoRAs linked to a universe character — used by the character card
// chip in the universe editor + catalog detail page. 2-segment path keeps it
// off the `/:filename` wildcard below.
diff --git a/server/routes/loras.test.js b/server/routes/loras.test.js
index cf038aa218..32aef09224 100644
--- a/server/routes/loras.test.js
+++ b/server/routes/loras.test.js
@@ -9,6 +9,11 @@ vi.mock('../services/loras.js', () => ({
deleteLora: vi.fn(),
getLora: vi.fn(),
installFromCivitai: vi.fn(),
+ installFromHuggingface: vi.fn(async (_input, { onProgress } = {}) => {
+ onProgress?.({ received: 4, total: 8 });
+ onProgress?.({ received: 8, total: 8 });
+ return { filename: 'lora-x-hf.safetensors', name: 'X', runnerFamily: 'ltx-video' };
+ }),
listLoras: vi.fn(async () => []),
patchLoraSidecar: vi.fn(),
resolveCivitaiKey: vi.fn(async () => null),
@@ -35,6 +40,13 @@ vi.mock('../services/settings.js', () => ({
const { default: lorasRoutes } = await import('./loras.js');
const { searchLorasInFamily } = await import('../services/civitaiSuggestions.js');
+const { installFromHuggingface } = await import('../services/loras.js');
+
+// Parse an SSE response body into an array of decoded frame objects.
+const parseSseFrames = (text) => text
+ .split('\n\n')
+ .filter((b) => b.startsWith('data: '))
+ .map((b) => JSON.parse(b.slice('data: '.length)));
const makeApp = () => {
const app = express();
@@ -44,6 +56,42 @@ const makeApp = () => {
return app;
};
+describe('GET /api/loras/install/huggingface/stream', () => {
+ it('streams byte-progress frames then a complete frame carrying the sidecar', async () => {
+ const res = await request(makeApp())
+ .get('/api/loras/install/huggingface/stream?url=fal/ltx2.3-audio-reactive-lora');
+ expect(res.status).toBe(200);
+ const frames = parseSseFrames(res.text);
+ // The service double emitted 4/8 then 8/8 → progress 0.5 then 1.
+ expect(frames.filter((f) => f.type === 'progress').map((f) => f.progress)).toEqual([0.5, 1]);
+ const complete = frames.find((f) => f.type === 'complete');
+ expect(complete?.sidecar?.runnerFamily).toBe('ltx-video');
+ // Family override rides the query string through to the service.
+ expect(installFromHuggingface).toHaveBeenCalledWith(
+ expect.objectContaining({ url: 'fal/ltx2.3-audio-reactive-lora' }),
+ expect.objectContaining({ onProgress: expect.any(Function) }),
+ );
+ });
+
+ it('forwards an install failure as an SSE error frame (not a thrown 500)', async () => {
+ installFromHuggingface.mockRejectedValueOnce(
+ Object.assign(new Error('could not classify'), { code: 'HF_UNKNOWN_FAMILY' }),
+ );
+ const res = await request(makeApp())
+ .get('/api/loras/install/huggingface/stream?url=someone/mystery');
+ expect(res.status).toBe(200); // headers already flushed — error is a frame, not a status
+ const err = parseSseFrames(res.text).find((f) => f.type === 'error');
+ expect(err.code).toBe('HF_UNKNOWN_FAMILY');
+ expect(err.message).toBe('could not classify');
+ });
+
+ it('rejects an invalid family override before opening the stream', async () => {
+ const res = await request(makeApp())
+ .get('/api/loras/install/huggingface/stream?url=x/y&family=bogus');
+ expect(res.status).toBe(400);
+ });
+});
+
describe('GET /api/loras/search', () => {
it('dispatches a valid runner + keyword + cursor to the service', async () => {
const res = await request(makeApp())
diff --git a/server/services/loras.js b/server/services/loras.js
index 3f5ae45c43..2c3d4586d5 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -21,7 +21,7 @@ import { existsSync } from 'fs';
import { link, readFile, rename, rm, stat, unlink } from 'fs/promises';
import { createWriteStream } from 'fs';
import { randomBytes } from 'crypto';
-import { Readable } from 'stream';
+import { Readable, Transform } from 'stream';
import { pipeline } from 'stream/promises';
import { basename, join } from 'path';
import { ServerError } from '../lib/errorHandler.js';
@@ -257,7 +257,12 @@ export const resolveCivitaiKey = async () => {
// `.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.
-const downloadToFile = async (url, destPath, { fetchImpl = fetch, headers = {} , hasApiKey = false, source = 'civitai' } = {}) => {
+// `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 } = {}) => {
const tmpPath = `${destPath}.${randomBytes(6).toString('hex')}.partial`;
const res = await fetchImpl(url, { headers, redirect: 'follow' });
if (!res.ok) {
@@ -291,7 +296,30 @@ const downloadToFile = async (url, destPath, { fetchImpl = fetch, headers = {} ,
// On stream failure (network drop, disk full) the .partial would otherwise
// accumulate in PATHS.loras across retries.
const writer = createWriteStream(tmpPath);
- await pipeline(Readable.fromWeb(res.body), writer).catch(async (err) => {
+ 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.
+ 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;
});
@@ -418,7 +446,7 @@ const VIDEO_LORA_FAMILY_VALUES = new Set(Object.values(VIDEO_LORA_FAMILIES));
// sidecar. The family is auto-detected from the repo id / tags / base_model,
// or taken from an explicit `input.family` override (validated against the
// known video families). Returns the new sidecar JSON.
-export const installFromHuggingface = async (input, { fetchImpl = fetch } = {}) => {
+export const installFromHuggingface = async (input, { fetchImpl = fetch, onProgress = null } = {}) => {
const { repo, revision } = parseHuggingfaceLoraRef(input?.url);
// Stored/env/CLI HF token — only needed for gated repos, but harmless to
// send on public ones (HF ignores a bearer it doesn't require).
@@ -469,6 +497,7 @@ export const installFromHuggingface = async (input, { fetchImpl = fetch } = {})
headers: { 'User-Agent': 'PortOS/hf-lora-installer', ...buildHfAuthHeaders(token) },
hasApiKey: !!token,
source: 'huggingface',
+ onProgress,
});
const sidecar = buildHfLoraSidecar({ repo, revision, file, model, family, filename });
diff --git a/server/services/loras.test.js b/server/services/loras.test.js
index b74a0e66df..5e41ed488c 100644
--- a/server/services/loras.test.js
+++ b/server/services/loras.test.js
@@ -455,6 +455,56 @@ describe('installFromHuggingface', () => {
).rejects.toMatchObject({ code: 'HF_UNKNOWN_FAMILY' });
});
+ it('reports byte-level download progress via onProgress', async () => {
+ const fetchImpl = async (url) => {
+ if (url.startsWith('https://huggingface.co/api/models/')) {
+ return mockJsonResponse(HF_MODEL);
+ }
+ if (url.includes('/resolve/main/pytorch_lora_weights.safetensors')) {
+ const stream = new ReadableStream({
+ start(c) {
+ c.enqueue(new Uint8Array(Buffer.from('abcd')));
+ c.enqueue(new Uint8Array(Buffer.from('efgh')));
+ c.close();
+ },
+ });
+ // Carry a Content-Length so the total is known (8 bytes).
+ return { ok: true, status: 200, body: stream, headers: { get: (h) => (h === 'content-length' ? '8' : null) } };
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ };
+ const ticks = [];
+ await lorasService.installFromHuggingface(
+ { url: 'https://huggingface.co/fal/ltx2.3-audio-reactive-lora', token: 'hf_test' },
+ { fetchImpl, onProgress: (p) => ticks.push(p) },
+ );
+ expect(ticks.length).toBeGreaterThan(0);
+ // The flush tick always fires last with the full byte count.
+ const last = ticks[ticks.length - 1];
+ expect(last.received).toBe(8);
+ expect(last.total).toBe(8);
+ });
+
+ it('tolerates a missing Content-Length (total 0, still completes)', async () => {
+ const fetchImpl = async (url) => {
+ if (url.startsWith('https://huggingface.co/api/models/')) {
+ return mockJsonResponse(HF_MODEL);
+ }
+ if (url.includes('/resolve/main/pytorch_lora_weights.safetensors')) {
+ const stream = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(Buffer.from('weights'))); c.close(); } });
+ return { ok: true, status: 200, body: stream }; // no headers
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ };
+ const ticks = [];
+ const sidecar = await lorasService.installFromHuggingface(
+ { url: 'https://huggingface.co/fal/ltx2.3-audio-reactive-lora', token: 'hf_test' },
+ { fetchImpl, onProgress: (p) => ticks.push(p) },
+ );
+ expect(sidecar.runnerFamily).toBe('ltx-video');
+ expect(ticks[ticks.length - 1]).toEqual({ received: 7, total: 0 });
+ });
+
it('accepts an explicit family override', async () => {
const fetchImpl = async (url) => {
if (url.startsWith('https://huggingface.co/api/models/')) {