Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: close preflight gaps codex review found in the download confirm flow
[._.]/ Adam Eivybed1916b4087
diff --git a/client/src/hooks/useDownloadPreflightConfirm.js b/client/src/hooks/useDownloadPreflightConfirm.jsindex c463a0e3e0..190dedc38f 100644--- a/client/src/hooks/useDownloadPreflightConfirm.js+++ b/client/src/hooks/useDownloadPreflightConfirm.js@@ -1,4 +1,4 @@-import { useCallback, useState } from 'react';+import { useCallback, useRef, useState } from 'react';// Shared "preview a weight download, then confirm" state machine. Two near-// identical copies (LocalLlmTab's model/spec-decode/MTPLX downloads, Loras'@@ -16,14 +16,29 @@ import { useCallback, useState } from 'react';// <DownloadPreflightConfirm open={Boolean(confirm)} {...confirm} onCancel={cancel} onConfirm={confirmRun} />export default function useDownloadPreflightConfirm() {const [confirm, setConfirm] = useState(null);+ // Bumped on every request() and every cancel() so a preview that resolves+ // after the user already cancelled — or after a newer request superseded+ // it — can tell it's stale and skip reopening/overwriting the modal.+ const requestId = useRef(0);const request = useCallback(({ title, preview, run }) => {+ const id = ++requestId.current;setConfirm({ title, loading: true, error: null, assessment: null, run: null });return preview().then((assessment) => {+ if (requestId.current !== id) return;setConfirm({ title, loading: false, error: null, assessment, run });}).catch((err) => {+ if (requestId.current !== id) return;+ // A caller can mark a preview rejection `handled` (e.g. it already+ // routed a CIVITAI_AUTH failure into its own key-entry prompt) —+ // close this modal silently instead of layering a second, generic+ // error dialog on top of the one the caller just opened.+ if (err?.handled) {+ setConfirm(null);+ return;+ }setConfirm({title,loading: false,@@ -34,13 +49,19 @@ export default function useDownloadPreflightConfirm() {});}, []);- const cancel = useCallback(() => setConfirm(null), []);- const confirmRun = useCallback(() => {- setConfirm((prev) => {- prev?.run?.();- return null;- });+ const cancel = useCallback(() => {+ requestId.current += 1;+ setConfirm(null);}, []);+ // Read `run` before clearing state and invoke it outside the setState+ // updater — React StrictMode double-invokes an updater function in dev to+ // surface impure ones, so a `setConfirm(prev => { prev.run(); ... })` shape+ // would start the download twice.+ const confirmRun = useCallback(() => {+ const run = confirm?.run;+ setConfirm(null);+ run?.();+ }, [confirm]);return { confirm, request, cancel, confirmRun };}diff --git a/client/src/hooks/useDownloadPreflightConfirm.test.js b/client/src/hooks/useDownloadPreflightConfirm.test.jsnew file mode 100644index 0000000000..f47c1c65bc--- /dev/null+++ b/client/src/hooks/useDownloadPreflightConfirm.test.js@@ -0,0 +1,88 @@+import { act, renderHook } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';+import useDownloadPreflightConfirm from './useDownloadPreflightConfirm.js';++describe('useDownloadPreflightConfirm', () => {+ it('shows the assessment once preview resolves, then runs the callback exactly once on confirm', async () => {+ const { result } = renderHook(() => useDownloadPreflightConfirm());+ const run = vi.fn();+ const assessment = { verdict: 'ok', destPath: 'model.gguf' };++ await act(async () => {+ await result.current.request({ title: 'Install', preview: async () => assessment, run });+ });+ expect(result.current.confirm).toMatchObject({ title: 'Install', loading: false, assessment, error: null });++ act(() => { result.current.confirmRun(); });+ expect(run).toHaveBeenCalledOnce();+ expect(result.current.confirm).toBeNull();+ });++ it('closes silently on a `handled` rejection instead of layering a generic error dialog', async () => {+ const { result } = renderHook(() => useDownloadPreflightConfirm());+ const handled = Object.assign(new Error('routed elsewhere'), { handled: true });++ await act(async () => {+ await result.current.request({ title: 'Install', preview: async () => { throw handled; }, run: vi.fn() });+ });++ expect(result.current.confirm).toBeNull();+ });++ it('shows a generic error for an un-marked rejection', async () => {+ const { result } = renderHook(() => useDownloadPreflightConfirm());++ await act(async () => {+ await result.current.request({+ title: 'Install',+ preview: async () => { throw new Error('disk check failed'); },+ run: vi.fn(),+ });+ });++ expect(result.current.confirm).toMatchObject({ loading: false, error: 'disk check failed', assessment: null });+ });++ // A preview that resolves after the user already cancelled must not reopen+ // the modal — codex review flagged this race on the shared confirm state.+ it('ignores a preview that resolves after cancel()', async () => {+ const { result } = renderHook(() => useDownloadPreflightConfirm());+ let resolvePreview;+ const pending = new Promise((resolve) => { resolvePreview = resolve; });++ let requestPromise;+ act(() => {+ requestPromise = result.current.request({ title: 'Install', preview: () => pending, run: vi.fn() });+ });+ expect(result.current.confirm).toMatchObject({ loading: true });++ act(() => { result.current.cancel(); });+ expect(result.current.confirm).toBeNull();++ await act(async () => {+ resolvePreview({ verdict: 'ok' });+ await requestPromise;+ });+ expect(result.current.confirm).toBeNull();+ });++ // confirmRun() must read `run` and clear state, then invoke `run` OUTSIDE+ // the setState updater — React StrictMode double-invokes an updater+ // function passed to setState in dev, so a `run()` call living inside one+ // would fire the download twice.+ it('invokes run only once even if its updater were called twice (StrictMode simulation)', async () => {+ const { result } = renderHook(() => useDownloadPreflightConfirm());+ const run = vi.fn();+ await act(async () => {+ await result.current.request({ title: 'Install', preview: async () => ({ verdict: 'ok' }), run });+ });++ act(() => { result.current.confirmRun(); });+ // A second confirmRun() after state already cleared is a no-op — there is+ // no `run` left to read, simulating what a double-invoked-but-otherwise-+ // pure updater would produce.+ act(() => { result.current.confirmRun(); });++ expect(run).toHaveBeenCalledOnce();+ });+});diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsxindex 5d1bc7ce01..e5476f46d4 100644--- a/client/src/pages/Loras.jsx+++ b/client/src/pages/Loras.jsx@@ -165,9 +165,24 @@ 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 requestLoraDownload = useCallback((title, url, source, run) => requestDownloadConfirm({+ //+ // A gated Civitai model can already fail with CIVITAI_AUTH at the PREVIEW+ // step (previewCivitaiInstall fetches the model metadata, which needs the+ // same key the download does) — before startCivitaiInstall ever runs. Catch+ // it here and route it into the existing key-entry prompt instead of+ // letting the hook's generic error land inside the preflight modal, which+ // has no path back to that prompt.+ const requestLoraDownload = useCallback((title, url, source, run, extra = {}) => requestDownloadConfirm({title,- preview: () => previewLoraInstall({ url, source, silent: true }),+ preview: () => previewLoraInstall({ url, source, ...extra, silent: true }).catch((err) => {+ if (source === 'civitai' && err?.code === 'CIVITAI_AUTH') {+ setAuthPrompt({ url, message: err.message || 'This LoRA needs an API key.' });+ const handled = new Error(err.message);+ handled.handled = true;+ throw handled;+ }+ throw err;+ }),run,}), [requestDownloadConfirm]);@@ -251,7 +266,7 @@ export default function Loras() {// installer (not the Civitai one) with the card's known family. Tracks the// in-flight repo in its own state because the Civitai `installingSuggestion`// key is modelId/versionId-based — video installs have neither.- const installVideoSuggestion = useCallback(async (card) => {+ const startVideoSuggestionInstall = useCallback(async (card) => {// Cross-guard against the form install (see runHfInstall) — one HF install// at a time so they don't clobber the shared hfProgress.if (!card?.installUrl || installingVideoKey || hfInstalling) return;@@ -271,6 +286,19 @@ export default function Loras() {.finally(() => { setInstallingVideoKey(null); setHfProgress(null); });}, [installingVideoKey, hfInstalling, refresh]);+ // Card carries its own family/file, so the preview forwards them and shows+ // the exact file "Quick install" is about to fetch — not a re-guess.+ const installVideoSuggestion = useCallback((card) => {+ if (!card?.installUrl || installingVideoKey || hfInstalling) return undefined;+ return requestLoraDownload(+ 'Install video LoRA',+ card.installUrl,+ 'huggingface',+ () => startVideoSuggestionInstall(card),+ { family: card.runnerFamily, file: card.file },+ );+ }, [installingVideoKey, hfInstalling, requestLoraDownload, startVideoSuggestionInstall]);+// The measurement lives in the LIST, not in the card. The Installed section// swaps between LoraGrid and InstalledGroups when the media filter changes,// which unmounts every card — a badge held only in card state would vanish@@ -398,7 +426,13 @@ export default function Loras() {<buttonkey={family}type="button"- onClick={() => runHfInstall(hfFamilyPrompt, family)}+ onClick={() => requestLoraDownload(+ 'Install HuggingFace LoRA',+ hfFamilyPrompt,+ 'huggingface',+ () => runHfInstall(hfFamilyPrompt, family),+ { family },+ )}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">diff --git a/client/src/pages/Loras.test.jsx b/client/src/pages/Loras.test.jsxindex 9f021c56d2..31c1c10d7b 100644--- a/client/src/pages/Loras.test.jsx+++ b/client/src/pages/Loras.test.jsx@@ -7,7 +7,10 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import { render, screen, waitFor, fireEvent } from '@testing-library/react';import { MemoryRouter } from 'react-router';import Loras from './Loras';-import { listLorasFull, deleteLoraFull, installLoraFromHuggingfaceStream, probeLoraEffect } from '../services/api';+import {+ listLorasFull, deleteLoraFull, installLoraFromHuggingfaceStream, probeLoraEffect,+ previewLoraInstall, getCivitaiSuggestions,+} from '../services/api';vi.mock('../services/api', () => ({listLorasFull: vi.fn(),@@ -139,6 +142,75 @@ describe('Loras HuggingFace family picker', () => {});});+// A gated Civitai model can fail with CIVITAI_AUTH at the disk-preflight+// PREVIEW step (before any download starts) — the same code the download+// itself would hit. That must still surface the key-entry modal, not a+// dead-end error inside the disk-preflight confirm dialog.+describe('Loras Civitai auth recovery through preflight', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ listLorasFull.mockResolvedValue([]);+ getCivitaiSuggestions.mockResolvedValue({ runners: {}, video: [], fetchedAt: null });+ });++ it('routes a preflight CIVITAI_AUTH rejection into the key-entry modal, not a generic error', async () => {+ previewLoraInstall.mockRejectedValueOnce(+ Object.assign(new Error('This LoRA needs an API key.'), { code: 'CIVITAI_AUTH' }),+ );+ renderPage();+ const input = await screen.findByLabelText('Civitai model URL');+ fireEvent.change(input, { target: { value: 'https://civitai.com/models/123/gated' } });+ fireEvent.submit(input.closest('form'));++ expect(await screen.findByText('Civitai API key')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Start download' })).not.toBeInTheDocument();+ });+});++// The curated video suggestion "Quick install" used to call the HF streaming+// installer directly, skipping the disk-preflight confirm every other install+// path now shows. It must go through the same modal, with the card's own+// family/file forwarded so the preview matches the file the install picks.+describe('Loras video suggestion quick-install preflight', () => {+ const VIDEO_CARD = {+ repo: 'fal/ltx2.3-audio-reactive-lora',+ file: 'pytorch_lora_weights.safetensors',+ installUrl: 'https://huggingface.co/fal/ltx2.3-audio-reactive-lora',+ runnerFamily: 'ltx-video',+ name: 'Audio-Reactive LTX LoRA',+ };++ beforeEach(() => {+ vi.clearAllMocks();+ listLorasFull.mockResolvedValue([]);+ getCivitaiSuggestions.mockResolvedValue({ runners: {}, video: [VIDEO_CARD], fetchedAt: null });+ previewLoraInstall.mockResolvedValue({+ kind: 'huggingface', destPath: 'lora-fal-ltx-hf.safetensors', expectedBytes: 2048,+ freeBytes: 1e12, requiredBytes: 2048, headroomBytes: 0, verdict: 'ok',+ });+ installLoraFromHuggingfaceStream.mockResolvedValue({ name: 'lora-fal-ltx-hf.safetensors' });+ });++ it('shows the disk-preflight confirm before starting the stream install', async () => {+ renderPage();+ fireEvent.click(await screen.findByRole('button', { name: 'Quick install' }));++ expect(await screen.findByRole('button', { name: 'Start download' })).toBeInTheDocument();+ expect(previewLoraInstall).toHaveBeenCalledWith(expect.objectContaining({+ url: VIDEO_CARD.installUrl,+ source: 'huggingface',+ family: VIDEO_CARD.runnerFamily,+ file: VIDEO_CARD.file,+ }));+ expect(installLoraFromHuggingfaceStream).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', { name: 'Start download' }));+ await waitFor(() => expect(installLoraFromHuggingfaceStream).toHaveBeenCalledWith(+ expect.objectContaining({ url: VIDEO_CARD.installUrl, family: VIDEO_CARD.runnerFamily, file: VIDEO_CARD.file }),+ ));+ });+});+// Adapter-effect diagnostic (#4872). The card seeds from the server's CACHED// report and re-measures on demand; only a measured all-zero adapter is the// alarming one, and the badge must never echo itself when there is no summary.diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex 4e14e19b3f..83c399a25a 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -430,9 +430,12 @@ export const installLoraFromCivitai = ({ url, silent = false } = {}) => request(silent,});-export const previewLoraInstall = ({ url, source = 'civitai', silent = false } = {}) => request('/loras/install/preflight', {+// `family`/`file` are optional overrides — pass them when the caller already+// knows the exact target (a curated video suggestion card) so the previewed+// file matches what the HF install will actually pick.+export const previewLoraInstall = ({ url, source = 'civitai', family, file, silent = false } = {}) => request('/loras/install/preflight', {method: 'POST',- body: JSON.stringify({ url, source }),+ body: JSON.stringify({ url, source, family, file }),silent,});diff --git a/server/routes/loras.js b/server/routes/loras.jsindex f72eee9ba0..94e61ceeb5 100644--- a/server/routes/loras.js+++ b/server/routes/loras.js@@ -144,10 +144,16 @@ router.post('/install', asyncHandler(async (req, res) => {// Confirm-step disk preflight for a LoRA install. `source` picks Civitai vs// HuggingFace; the URL is the same shape the install endpoints already take.+// `family`/`file` are the same optional overrides `hfInstallSchema` takes —+// a caller that already knows them (the curated video quick-install cards)+// forwards them so the previewed file matches what installFromHuggingface+// will actually pick, rather than re-guessing from the bare URL.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(),+ family: z.enum(HF_LORA_FAMILIES).optional(),+ file: z.string().min(1).max(512).regex(/\.safetensors$/i).optional(),});router.post('/install/preflight', asyncHandler(async (req, res) => {const data = validateRequest(installPreflightSchema, req.body);diff --git a/server/services/localRuntimeSetup.js b/server/services/localRuntimeSetup.jsindex fccd96cdcb..82f1bdbbc1 100644--- a/server/services/localRuntimeSetup.js+++ b/server/services/localRuntimeSetup.js@@ -67,6 +67,8 @@ import { runStreamingCommand } from '../lib/streamingSpawn.js';import { installLlamaServer } from './llamaServerManager.js';import { installMtplx, startMtplxServer, MTPLX_UNSUPPORTED_REASON } from './mtplxServerManager.js';import { installSlotstream, startSlotstreamServer, SLOTSTREAM_UNSUPPORTED_REASON } from './slotstreamServerManager.js';+import { previewMtplxPull } from './mtplxModelManager.js';+import { assertDownloadFits } from '../lib/downloadPreflight.js';import { controlOllamaServer, installBackend } from './localLlm.js';import { isAppInstalled as isLmStudioAppInstalled } from './lmStudioManager.js';import { provisionVllmQwenProject, readVllmQwenSetupState, startVllmQwenProject } from './vllmQwenManager.js';@@ -232,6 +234,13 @@ const rowProvisionAction = (row) => row?.provision?.action || null;async function pullMtplxDefaultCheckpoint({ emit, isCancelled }) {const binary = findCommandOnPath('mtplx');if (!binary) return { success: false, error: '`mtplx` was not found on PortOS\'s PATH. Restart PortOS so it picks up the new bin directory, then try again.' };+ // Same disk-space guard the Models → LLMs MTPLX card runs before its own+ // pull — this readiness-checklist button reaches the same `mtplx pull`+ // with no repo id, so it shares previewMtplxPull's cache path and its+ // (unknown-size, so effectively best-effort) preflight. A refusal throws;+ // the SSE route above already treats an unexpected throw from this step as+ // a clean `{success:false}` termination, not a 500.+ assertDownloadFits(await previewMtplxPull({}));emit('Downloading MTPLX\'s default verified checkpoint. This is a multi-gigabyte download and can take a long while — leave this window open to watch it.');// `mtplx pull` redraws one progress line with a bare `\r`; splitting on// newlines alone would leave the stream silent for the whole download.diff --git a/server/services/loras.js b/server/services/loras.jsindex 753be8351e..a3b9a2bcc3 100644--- a/server/services/loras.js+++ b/server/services/loras.js@@ -650,13 +650,14 @@ export const previewCivitaiInstall = async (input, { fetchImpl = fetch } = {}) =// video families). Used to validate a user-supplied `family` override.const HF_LORA_FAMILY_VALUES = new Set(HF_LORA_FAMILIES);-// Install a LoRA from a HuggingFace repo (Flux.2 Klein image adapters, fal /-// Lightricks LTX video LoRAs, MiniMax H3). Mirrors installFromCivitai: parse-// the ref → fetch repo metadata → pick the .safetensors → stream-download →-// write the sidecar. The family is auto-detected from the repo id / tags /-// base_model / filenames, or taken from an explicit `input.family` override-// (validated against the known image + video families). Returns the new sidecar.-export const installFromHuggingface = async (input, { fetchImpl = fetch, onProgress = null, signal = null } = {}) => {+// Shared by installFromHuggingface and previewHuggingfaceInstall so a preview+// can never show a different file/filename than the install it precedes.+// `family` is resolved (override → autodetection → null) but NOT required —+// it only narrows `pickHfLoraFile`'s pick among flux2 variant files; the+// generated filename depends only on `repo` + the picked `file`. Preview+// therefore never throws HF_UNKNOWN_FAMILY: that check belongs to the actual+// install, which needs a concrete family for the sidecar metadata.+const resolveHfLoraInstallPlan = async (input, { fetchImpl = fetch } = {}) => {const { repo, revision, file: parsedFile } = 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).@@ -665,28 +666,8 @@ export const installFromHuggingface = async (input, { fetchImpl = fetch, onProgrconst preferredFile = input?.file || parsedFile || null;const detected = detectHfLoraFamily({ repo, model, file: preferredFile });- // Family: explicit override (validated) wins over autodetection so a user- // can correct a mis-detected repo from the UI. An unrecognized repo with no- // override is refused rather than silently tagged — a wrongly-tagged LoRA- // would surface under a model it can't actually load against.- let family = null;- if (input?.family) {- if (!HF_LORA_FAMILY_VALUES.has(input.family)) {- throw new ServerError(- `Unknown LoRA family "${input.family}" — expected one of ${[...HF_LORA_FAMILY_VALUES].join(', ')}`,- { status: 400, code: 'HF_BAD_FAMILY' },- );- }- family = input.family;- } else {- family = detected?.family || null;- }- if (!family) {- throw new ServerError(- `Couldn't determine a supported model for HuggingFace repo "${repo}". PortOS can install Flux 2, Flux 1, Z-Image, ERNIE, HiDream, Qwen, LTX-Video, and MiniMax H3 LoRAs — pass an explicit family if you know which one this targets.`,- { status: 422, code: 'HF_UNKNOWN_FAMILY' },- );- }+ // Family: explicit override (validated by the caller) wins over autodetection.+ const family = input?.family || detected?.family || null;const file = pickHfLoraFile(model,@@ -714,22 +695,47 @@ export const installFromHuggingface = async (input, { fetchImpl = fetch, onProgr: (fileStemSlug === repoNameSlug ? '' : fileStemSlug));const filename = `lora-${slug}${explicitVariant ? `-${explicitVariant}` : ''}-hf.safetensors`;const destPath = join(PATHS.loras, filename);- if (existsSync(destPath)) {+ const hfSibling = (Array.isArray(model?.siblings) ? model.siblings : []).find((row) => row?.rfilename === file);++ return { repo, revision, token, model, family, fluxVariant, file, filename, destPath, expectedBytes: siblingDownloadMeta(hfSibling).bytes };+};++// Install a LoRA from a HuggingFace repo (Flux.2 Klein image adapters, fal /+// Lightricks LTX video LoRAs, MiniMax H3). Mirrors installFromCivitai: parse+// the ref → fetch repo metadata → pick the .safetensors → stream-download →+// write the sidecar. The family is auto-detected from the repo id / tags /+// base_model / filenames, or taken from an explicit `input.family` override+// (validated against the known image + video families). Returns the new sidecar.+export const installFromHuggingface = async (input, { fetchImpl = fetch, onProgress = null, signal = null } = {}) => {+ // An unrecognized override is refused before the network round trip — a+ // wrongly-tagged LoRA would surface under a model it can't actually load.+ if (input?.family && !HF_LORA_FAMILY_VALUES.has(input.family)) {throw new ServerError(- `Already installed: ${filename}. Delete it first to reinstall.`,+ `Unknown LoRA family "${input.family}" — expected one of ${[...HF_LORA_FAMILY_VALUES].join(', ')}`,+ { status: 400, code: 'HF_BAD_FAMILY' },+ );+ }+ const plan = await resolveHfLoraInstallPlan(input, { fetchImpl });+ if (!plan.family) {+ throw new ServerError(+ `Couldn't determine a supported model for HuggingFace repo "${plan.repo}". PortOS can install Flux 2, Flux 1, Z-Image, ERNIE, HiDream, Qwen, LTX-Video, and MiniMax H3 LoRAs — pass an explicit family if you know which one this targets.`,+ { status: 422, code: 'HF_UNKNOWN_FAMILY' },+ );+ }+ if (existsSync(plan.destPath)) {+ throw new ServerError(+ `Already installed: ${plan.filename}. Delete it first to reinstall.`,{ status: 409, code: 'HF_ALREADY_INSTALLED' },);}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, {+ assertDownloadFits(await assessDownloadPreflight({ destPath: plan.destPath, expectedBytes: plan.expectedBytes }));+ console.log(`📥 Installing HuggingFace LoRA: ${plan.repo} (${plan.file}) → ${plan.filename} [family=${plan.family}]`);+ await downloadToFile(buildHfResolveUrl(plan.repo, plan.revision, plan.file), plan.destPath, {fetchImpl,- headers: { 'User-Agent': 'PortOS/hf-lora-installer', ...buildHfAuthHeaders(token) },- hasApiKey: !!token,+ headers: { 'User-Agent': 'PortOS/hf-lora-installer', ...buildHfAuthHeaders(plan.token) },+ hasApiKey: !!plan.token,source: 'huggingface',onProgress,signal,@@ -737,31 +743,27 @@ export const installFromHuggingface = async (input, { fetchImpl = fetch, onProgr// HF's model metadata doesn't expose a per-file digest through pickHfLoraFile,// so the structural header/size check is the integrity guard here (no deep// sha256 compare available for this path).- await verifyDownloadedLora(destPath, { source: 'huggingface' });+ await verifyDownloadedLora(plan.destPath, { source: 'huggingface' });const sidecar = await withKeyLayout(- buildHfLoraSidecar({ repo, revision, file, model, family, filename, fluxVariant }),- destPath,+ buildHfLoraSidecar({ repo: plan.repo, revision: plan.revision, file: plan.file, model: plan.model, family: plan.family, filename: plan.filename, fluxVariant: plan.fluxVariant }),+ plan.destPath,);- await writeLoraSidecar(filename, sidecar);- console.log(`✅ Installed HuggingFace LoRA: ${filename} [layout=${sidecar.keyLayout || 'unknown'}]`);+ await writeLoraSidecar(plan.filename, sidecar);+ console.log(`✅ Installed HuggingFace LoRA: ${plan.filename} [layout=${sidecar.keyLayout || 'unknown'}]`);return sidecar;};+/** Size / dest / free-disk numbers for the HF LoRA confirm step — mirrors the+ * exact file/filename installFromHuggingface will write, so the number shown+ * never disagrees with what installs. No transfer starts. */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,- });+ const plan = await resolveHfLoraInstallPlan(input, { fetchImpl });+ const preflight = await assessDownloadPreflight({ destPath: plan.destPath, expectedBytes: plan.expectedBytes });return {kind: 'huggingface',...preflight,- destPath: file,- alreadyDownloaded: false,+ destPath: plan.filename,+ alreadyDownloaded: existsSync(plan.destPath),};};