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: eight findings from an independent claude review, restore a rebase mis-resolution
[._.]/ Adam Eivy843fccd23f96
diff --git a/client/src/components/models/DownloadPreflightConfirm.jsx b/client/src/components/models/DownloadPreflightConfirm.jsxindex 0fe586f720..a043c45fb8 100644--- a/client/src/components/models/DownloadPreflightConfirm.jsx+++ b/client/src/components/models/DownloadPreflightConfirm.jsx@@ -27,6 +27,14 @@ export default function DownloadPreflightConfirm({const warning = VERDICT_COPY[assessment?.verdict] || null;const sizeKnown = Number(assessment?.expectedBytes) > 0;const freeKnown = Number.isFinite(assessment?.freeBytes);+ // A leftover .partial credits its own bytes toward the space this download+ // still needs, so `requiredBytes` (+ headroom) can read well under the full+ // `expectedBytes` size shown above — without calling that out, "Size 20 GB+ // / Free disk 4 GB" with Confirm enabled reads as a broken check rather+ // than a resume that only needs a few GB more.+ const requiredBytes = Number(assessment?.requiredBytes) || 0;+ const headroomBytes = Number(assessment?.headroomBytes) || 0;+ const resuming = sizeKnown && requiredBytes > 0 && requiredBytes < (assessment.expectedBytes + headroomBytes);return (<Modal@@ -75,9 +83,19 @@ export default function DownloadPreflightConfirm({{freeKnown ? formatBytes(assessment.freeBytes) : 'Unavailable'}</dd></div>+ {resuming && (+ <div className="flex items-baseline justify-between gap-3">+ <dt className="text-gray-500">Still needed</dt>+ <dd className="font-medium tabular-nums text-white">{formatBytes(requiredBytes)}</dd>+ </div>+ )}</dl>)}+ {resuming && (+ <p className="text-xs text-gray-500">Resuming — part of this download is already on disk.</p>+ )}+{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" />diff --git a/client/src/components/models/DownloadPreflightConfirm.test.jsx b/client/src/components/models/DownloadPreflightConfirm.test.jsxindex 0f7e2ae110..950649d99e 100644--- a/client/src/components/models/DownloadPreflightConfirm.test.jsx+++ b/client/src/components/models/DownloadPreflightConfirm.test.jsx@@ -42,6 +42,24 @@ describe('DownloadPreflightConfirm', () => {expect(screen.getByText(/not enough free disk/i)).toBeInTheDocument();});+ // A leftover .partial credits its own bytes toward requiredBytes, so it+ // can read well under expectedBytes + headroom — without calling that out,+ // "Size 2 GB / Free disk 20 GB" next to an enabled Confirm reads the same+ // whether or not a resume is actually shrinking the real ask.+ it('calls out a resumed download\'s smaller remaining requirement', () => {+ render(+ <DownloadPreflightConfirm+ open+ assessment={{ ...assessment, requiredBytes: 300 * 1024 * 1024 }}+ onConfirm={() => {}}+ onCancel={() => {}}+ />,+ );+ expect(screen.getByText(/resuming/i)).toBeInTheDocument();+ expect(screen.getByText('Still needed')).toBeInTheDocument();+ expect(screen.getByText('300 MB')).toBeInTheDocument();+ });+it('calls onConfirm from the Download button', () => {const onConfirm = vi.fn();render(diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsxindex e5476f46d4..32d802ef2b 100644--- a/client/src/pages/Loras.jsx+++ b/client/src/pages/Loras.jsx@@ -177,6 +177,9 @@ export default function Loras() {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.' });+ // No confirm modal opens for a `handled` rejection, so nothing else+ // will clear a suggestion card's spinner for this attempt.+ setInstallingSuggestion(null);const handled = new Error(err.message);handled.handled = true;throw handled;@@ -186,6 +189,15 @@ export default function Loras() {run,}), [requestDownloadConfirm]);+ // Dismissing the confirm modal without confirming ends a suggestion card's+ // install attempt before startCivitaiInstall/startVideoSuggestionInstall+ // ever run — clear its spinner here too, or it sticks until another card+ // is clicked. A no-op for every other caller of the shared modal.+ const handleCancelDownloadConfirm = useCallback(() => {+ cancelDownloadConfirm();+ setInstallingSuggestion(null);+ }, [cancelDownloadConfirm]);+const startCivitaiInstall = useCallback(async (url) => {if (!url || installing) return;setInstalling(true);@@ -208,7 +220,9 @@ export default function Loras() {toast.error(err?.message || 'Install failed');}})- .finally(() => setInstalling(false));+ // Clears whichever suggestion card (if any) triggered this install —+ // a no-op for the manual-form submit, which never sets it.+ .finally(() => { setInstalling(false); setInstallingSuggestion(null); });}, [installing, refresh]);const performInstall = useCallback((url) => {@@ -484,14 +498,19 @@ export default function Loras() {videoInstallBusy={hfInstalling}onRefresh={() => refreshSuggestions({ force: true })}onInstallVideo={installVideoSuggestion}- onInstall={async (card, url, versionId) => {+ onInstall={(card, url, versionId) => {// Curated cards pass a family-specific (url, versionId); non-curated// cards omit versionId and we fall back to the card's primary.const vid = versionId ?? card.versionId;const key = suggestionKey(card.modelId, vid);setInstallingSuggestion(key);- await performInstall(url || card.installUrl);- setInstallingSuggestion(null);+ // performInstall() resolves once the PREVIEW is ready (the confirm+ // modal is now showing) — the actual install can run far later, so+ // clearing this card's spinner belongs to that install's own+ // lifecycle (startCivitaiInstall's finally) and the cancel/auth-+ // redirect paths that can end this attempt before it ever starts,+ // not to this promise settling.+ performInstall(url || card.installUrl);}}/>@@ -529,7 +548,7 @@ export default function Loras() {error={downloadConfirm?.error}assessment={downloadConfirm?.assessment}confirmLabel="Start download"- onCancel={cancelDownloadConfirm}+ onCancel={handleCancelDownloadConfirm}onConfirm={runDownloadConfirm}/></div>diff --git a/client/src/pages/Loras.test.jsx b/client/src/pages/Loras.test.jsxindex 31c1c10d7b..9fb134c159 100644--- a/client/src/pages/Loras.test.jsx+++ b/client/src/pages/Loras.test.jsx@@ -9,7 +9,7 @@ import { MemoryRouter } from 'react-router';import Loras from './Loras';import {listLorasFull, deleteLoraFull, installLoraFromHuggingfaceStream, probeLoraEffect,- previewLoraInstall, getCivitaiSuggestions,+ previewLoraInstall, getCivitaiSuggestions, installLoraFromCivitai,} from '../services/api';vi.mock('../services/api', () => ({@@ -167,6 +167,49 @@ describe('Loras Civitai auth recovery through preflight', () => {});});+// performInstall() now returns once the PREVIEW resolves (the confirm modal+// is showing), not once the download finishes — the suggestion card's own+// "Installing…" spinner must track the real install lifecycle instead of+// that promise settling, or it flips back to "Quick install" the moment the+// confirm dialog opens while a multi-GB transfer is still ahead of it.+describe('Loras suggestion card busy state', () => {+ const SUGGESTION_CARD = { modelId: 42, versionId: 7, name: 'Example LoRA', installUrl: 'https://civitai.com/models/42' };++ beforeEach(() => {+ vi.clearAllMocks();+ listLorasFull.mockResolvedValue([]);+ getCivitaiSuggestions.mockResolvedValue({ runners: { mflux: [SUGGESTION_CARD] }, video: [], fetchedAt: null });+ });++ it('keeps the card "Installing…" through the confirm step and clears only once the install settles', async () => {+ let resolveInstall;+ installLoraFromCivitai.mockReturnValue(new Promise((resolve) => { resolveInstall = resolve; }));+ renderPage();++ fireEvent.click(await screen.findByRole('button', { name: 'Quick install' }));+ // Preview resolved (the confirm modal opened) — the card must still read+ // "Installing…", not have reverted to "Quick install" already.+ expect(await screen.findByRole('button', { name: 'Installing…' })).toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Start download' }));+ expect(await screen.findByRole('button', { name: 'Installing…' })).toBeInTheDocument();++ resolveInstall({ name: 'lora-example.safetensors' });+ expect(await screen.findByRole('button', { name: 'Quick install' })).toBeInTheDocument();+ });++ it('clears the spinner when the confirm is cancelled instead of leaving it stuck', async () => {+ renderPage();+ fireEvent.click(await screen.findByRole('button', { name: 'Quick install' }));+ await screen.findByRole('button', { name: 'Start download' });++ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));++ expect(await screen.findByRole('button', { name: 'Quick install' })).toBeInTheDocument();+ expect(installLoraFromCivitai).not.toHaveBeenCalled();+ });+});+// 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 owndiff --git a/server/lib/README.md b/server/lib/README.mdindex 98800f1fd6..a0fa7be4d3 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -220,7 +220,7 @@ 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). `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). `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`. || `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. |diff --git a/server/lib/downloadPreflight.js b/server/lib/downloadPreflight.jsindex e4eea98782..4ea18421ca 100644--- a/server/lib/downloadPreflight.js+++ b/server/lib/downloadPreflight.js@@ -14,7 +14,7 @@*/import { createWriteStream } from 'fs';-import { rm, stat, statfs, rename } from 'fs/promises';+import { readFile, rm, stat, statfs, rename, writeFile } from 'fs/promises';import { dirname } from 'path';import { Readable, Transform } from 'stream';import { pipeline } from 'stream/promises';@@ -37,6 +37,11 @@ const PARTIAL_SUFFIX = '.partial';export const partialPathFor = (destPath) => `${destPath}${PARTIAL_SUFFIX}`;+// Sidecar recording the ETag of the object that produced a `.partial`, so a+// later resume can send `If-Range` and detect a same-length replacement+// object instead of silently splicing its bytes onto our stale prefix.+const etagPathFor = (destPath) => `${partialPathFor(destPath)}.etag`;+export function normalizeSha256(value) {if (typeof value !== 'string') return null;const hex = value.trim().toLowerCase().replace(/^sha256:/, '').replace(/['"]/g, '');@@ -155,10 +160,16 @@ export function assertDownloadFits(assessment) {*/export async function probeRemoteSize(url, { headers = {}, fetchImpl = fetch, signal } = {}) {const empty = { bytes: 0, sha256: null };- const readMeta = (res) => {+ // `content-length` on a 206 describes the PARTIAL body (1 byte for our own+ // `bytes=0-0` probe), not the resource — only trust it on a response that+ // isn't itself a range (a HEAD, or a GET the origin answered with the+ // whole body because it ignored our Range). A genuine partial's total+ // comes from `Content-Range` alone; when that carries no total (`bytes+ // 0-0/*`) the size is unknown, which correctly falls through to `empty`.+ const readMeta = (res, { trustContentLength = true } = {}) => {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 length = trustContentLength ? (Number(res.headers.get('content-length')) || 0) : 0;const sha256 = normalizeSha256(res.headers.get('x-linked-etag') || res.headers.get('etag') || '',);@@ -180,7 +191,7 @@ export async function probeRemoteSize(url, { headers = {}, fetchImpl = fetch, siif (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 readMeta(ranged, { trustContentLength: ranged.status !== 206 });}return empty;}@@ -224,13 +235,26 @@ export async function streamResumableDownload({onHttpError = null,} = {}) {const tmpPath = partialPathFor(destPath);+ const etagPath = etagPathFor(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}-`;+ if (resumeFrom > 0) {+ reqHeaders.Range = `bytes=${resumeFrom}-`;+ // Makes the resume conditional on the remote object being UNCHANGED+ // since the attempt that produced this partial: an origin honoring+ // If-Range returns 200 (not 206) for a moved object, which the+ // Range-ignored branch below already treats as "discard and restart" —+ // without it, a same-length replacement silently splices its bytes onto+ // our old prefix. No saved etag (server never sent one, or this is the+ // first resume of a partial from before this guard existed) just means+ // no conditional — same as today.+ const savedEtag = await readFile(etagPath, 'utf8').catch(() => null);+ if (savedEtag) reqHeaders['If-Range'] = savedEtag;+ }let idleTimer = null;const clearIdleTimer = () => {@@ -256,10 +280,21 @@ export async function streamResumableDownload({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.+ // Partial is past what the server has (or the object changed) —+ // start clean. A 416 conventionally reports the real size as+ // `Content-Range: bytes */<total>`; recheck capacity against it+ // before the restart, same as the Range-ignored (200) branch below —+ // the original preflight only reserved the bytes this discarded+ // partial was short by, not the full payload the restart now needs.await rm(tmpPath, { force: true }).catch(() => {});+ await rm(etagPath, { force: true }).catch(() => {});resumeFrom = 0;delete reqHeaders.Range;+ delete reqHeaders['If-Range'];+ const totalFromRange = parseContentRangeTotal(res.headers?.get?.('content-range'));+ if (totalFromRange > 0) {+ assertDownloadFits(await assessDownloadPreflight({ destPath, expectedBytes: totalFromRange }));+ }return streamResumableDownload({url, destPath, headers, fetchImpl, onBytes, signal, onIdleStall,idleStallTimeoutMs, isCancelled, expectedSha256, finalize, onHttpError,@@ -272,13 +307,15 @@ export async function streamResumableDownload({throw new ServerError('Download returned no body', { status: 502, code: 'DOWNLOAD_FAILED' });}- // Server ignored Range and sent the whole file — discard the leftover- // prefix. The preflight the caller ran before starting only reserved the- // REMAINING bytes (crediting the partial already on disk); now the FULL- // payload is about to land instead, so recheck capacity against this- // response's own Content-Length before writing over the freed space.+ // Server ignored Range (or If-Range caught the object changing under us)+ // and sent the whole file — discard the leftover prefix. The preflight+ // the caller ran before starting only reserved the REMAINING bytes+ // (crediting the partial already on disk); now the FULL payload is+ // about to land instead, so recheck capacity against this response's+ // own Content-Length before writing over the freed space.if (resumeFrom > 0 && res.status === 200) {await rm(tmpPath, { force: true }).catch(() => {});+ await rm(etagPath, { force: true }).catch(() => {});resumeFrom = 0;const freshLength = Number(res.headers?.get?.('content-length')) || 0;if (freshLength > 0) {@@ -292,6 +329,16 @@ export async function streamResumableDownload({let received = resumeFrom;const flags = resumeFrom > 0 ? 'a' : 'w';+ // Starting a fresh write (first attempt, or just discarded above) —+ // record this response's ETag so a LATER resume of it can send+ // If-Range. Best-effort: no ETag, or a write failure, just means the+ // next resume attempt has nothing to validate against (today's behavior).+ if (flags === 'w') {+ const etag = res.headers?.get?.('etag') || null;+ if (etag) await writeFile(etagPath, etag).catch(() => {});+ else await rm(etagPath, { force: true }).catch(() => {});+ }+const counter = new Transform({transform(chunk, _enc, cb) {received += chunk.length;@@ -302,17 +349,24 @@ export async function streamResumableDownload({});await pipeline(Readable.fromWeb(res.body), counter, createWriteStream(tmpPath, { flags })).catch(async (err) => {- if (isCancelled()) await rm(tmpPath, { force: true }).catch(() => {});+ if (isCancelled()) {+ await rm(tmpPath, { force: true }).catch(() => {});+ await rm(etagPath, { force: true }).catch(() => {});+ }throw err;});const check = await verifyDownloadHash(tmpPath, expectedSha256);if (!check.ok) {await rm(tmpPath, { force: true }).catch(() => {});+ await rm(etagPath, { force: true }).catch(() => {});throw hashMismatchError(destPath, check);}- if (finalize) await rename(tmpPath, destPath);+ if (finalize) {+ await rename(tmpPath, destPath);+ await rm(etagPath, { force: true }).catch(() => {});+ }return { bytes: received || total, tmpPath, resumed: resumeFrom > 0 };} finally {clearIdleTimer();diff --git a/server/lib/downloadPreflight.test.js b/server/lib/downloadPreflight.test.jsindex 3cd6f611f1..e194ccdeb2 100644--- a/server/lib/downloadPreflight.test.js+++ b/server/lib/downloadPreflight.test.js@@ -319,6 +319,76 @@ describe('streamResumableDownload', () => {expect(await readFile(destPath, 'utf8')).toBe('full');});+ // A resume with no validation could splice a NEW object's bytes onto an+ // OLD partial's prefix if the remote file changed between attempts (same+ // length, different content) — a server honoring If-Range instead returns+ // 200 for that case, which the Range-ignored branch already restarts+ // cleanly on. Two attempts here: the first records the ETag; the second+ // (simulating a fresh process, e.g. after a restart) reads it back and+ // sends it as If-Range.+ it('records the first response ETag and sends it as If-Range on a later resume', async () => {+ const destPath = await makeDir();+ let firstCallHeaders;+ await streamResumableDownload({+ url: 'https://example.com/w.gguf',+ destPath,+ finalize: false,+ fetchImpl: async (_url, opts) => {+ firstCallHeaders = opts.headers;+ return {+ ok: true,+ status: 200,+ headers: { get: (name) => ({ 'content-length': '6', etag: '"abc123"' }[name] || null) },+ body: webBody('gg', 'ufgg'),+ };+ },+ });+ expect(firstCallHeaders.Range).toBeUndefined();+ expect(await readFile(`${partialPathFor(destPath)}.etag`, 'utf8').catch(() => null)).toBe('"abc123"');++ // Simulate a transport drop leaving the .partial short, then resume.+ await writeFile(partialPathFor(destPath), 'gg');+ let secondCallHeaders;+ await streamResumableDownload({+ url: 'https://example.com/w.gguf',+ destPath,+ fetchImpl: async (_url, opts) => {+ secondCallHeaders = opts.headers;+ return {+ ok: true,+ status: 206,+ headers: { get: (name) => ({ 'content-length': '4', 'content-range': 'bytes 2-5/6' }[name] || null) },+ body: webBody('ufgg'),+ };+ },+ });+ expect(secondCallHeaders.Range).toBe('bytes=2-');+ expect(secondCallHeaders['If-Range']).toBe('"abc123"');+ });++ // The 416 restart path deletes the partial and recurses with resumeFrom+ // reset to 0 — the recursive call's own "Range ignored" recheck never+ // fires (resumeFrom is already 0 there), so without an explicit recheck+ // here a preflight sized for the SHORTFALL only never gets rerun against+ // the FULL payload the restart is about to fetch.+ it('refuses a 416 restart the disk cannot hold, using the 416 response\'s own total', async () => {+ const destPath = await makeDir();+ await writeFile(partialPathFor(destPath), 'X'.repeat(9));+ const fetchImpl = async (_url, opts) => {+ if (opts.headers.Range) {+ return {+ ok: false,+ status: 416,+ headers: { get: (name) => (name === 'content-range' ? `bytes */${Number.MAX_SAFE_INTEGER}` : null) },+ };+ }+ throw new Error('unreachable: recheck should reject before the clean-restart GET');+ };+ await expect(streamResumableDownload({+ url: 'https://example.com/w.gguf', destPath, fetchImpl,+ })).rejects.toMatchObject({ code: 'DISK_INSUFFICIENT' });+ });+// The caller's own preflight only reserved space for the bytes still// missing (crediting the .partial already on disk) — once the server// ignores Range and the FULL payload is about to land instead, refusediff --git a/server/lib/localLlmCatalog.js b/server/lib/localLlmCatalog.jsindex be9cf444f2..dc01422f73 100644--- a/server/lib/localLlmCatalog.js+++ b/server/lib/localLlmCatalog.js@@ -893,6 +893,32 @@ const entryIdsForBackend = (entry, backend) => [const entryMatchesBackendId = (entry, backend, normalizedId) =>entryIdsForBackend(entry, backend).some((id) => normalizeFor(backend, id) === normalizedId);+const SIZE_UNIT_BYTES = { KB: 1024, MB: 1024 ** 2, GB: 1024 ** 3, TB: 1024 ** 4 };++/** Parse a catalog `size` string ('4.9 GB', '301 MB') to bytes; 0 if unparseable. */+const parseCatalogSizeBytes = (size) => {+ const match = /^([\d.]+)\s*(KB|MB|GB|TB)$/i.exec(String(size || '').trim());+ if (!match) return 0;+ return Math.round(Number(match[1]) * SIZE_UNIT_BYTES[match[2].toUpperCase()]);+};++/**+ * Bytes for a curated catalog entry's advertised download size, resolved by+ * the backend-specific install id (matched the same alias-aware way+ * `getOllamaImportSpec`/`getCatalog` match ids). 0 for an unrecognized id or+ * an entry whose `size` string doesn't parse — the disk preflight already+ * treats 0 as "unknown, never refuse," so a miss here fails open rather than+ * blocking an install PortOS just can't size.+ */+export function catalogSizeBytes(backend, modelId) {+ if (!isBackend(backend)) return 0;+ const normalizedId = normalizeFor(backend, modelId);+ const entry = LOCAL_LLM_CATALOG.find((candidate) => (+ candidate[backend] && entryMatchesBackendId(candidate, backend, normalizedId)+ ));+ return entry ? parseCatalogSizeBytes(entry.size) : 0;+}+/*** Return the trusted local-Safetensors import recipe for a curated Ollama id.* Unknown/free-text ids return null and continue through the normal pull path.diff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex a84bbb35bb..5e8616ae2d 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -36,7 +36,7 @@ import { PATHS, atomicWrite, ensureDir, pathExists, sleep } from '../lib/fileUtiimport { 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 { getCatalog, isBackend, mapModelToBackend, getOllamaImportSpec, catalogSizeBytes } from '../lib/localLlmCatalog.js'import { sanitizeOllamaName } from '../lib/localLlmDisk.js'import { recommendEditorialModel, isVisionModel, isVisionCapableCliProvider, isToolUseModel } from '../lib/localModelHeuristics.js'import { captureSystemCapabilities, withHardwareCompatibility } from '../lib/systemCapabilities.js'@@ -918,7 +918,9 @@ export async function previewInstallModel(backend, modelId) {throw new ServerError(`Unknown backend: ${backend}`, { status: 400 })}const destPath = await localInstallDest(backend)- const preflight = await assessDownloadPreflight({ destPath, expectedBytes: 0 })+ // 0 for a free-text/uncurated model id (e.g. a bare Ollama tag the user+ // typed) — the preflight already treats that as "unknown, never refuse."+ const preflight = await assessDownloadPreflight({ destPath, expectedBytes: catalogSizeBytes(backend, modelId) })return {kind: 'install',backend,@@ -933,7 +935,7 @@ export async function installModel(backend, modelId, onProgress, { force = falseif (!isBackend(backend)) return { success: false, error: `Unknown backend: ${backend}` }assertDownloadFits(await assessDownloadPreflight({destPath: await localInstallDest(backend),- expectedBytes: 0,+ expectedBytes: catalogSizeBytes(backend, modelId),}))if (backend === 'ollama') {const importSpec = getOllamaImportSpec(modelId)diff --git a/server/services/mtplxModelManager.js b/server/services/mtplxModelManager.jsindex abec518b71..075485ee93 100644--- a/server/services/mtplxModelManager.js+++ b/server/services/mtplxModelManager.js@@ -21,11 +21,11 @@* 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 { getHfCacheRoot } from '../lib/hfCache.js';import { fetchHuggingfaceModel } from '../lib/huggingfaceLora.js';import { listMtplxCachedModels } from '../lib/mtplxModels.js';import { findCommandOnPath } from '../lib/processEnv.js';@@ -61,7 +61,13 @@ 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();+// MTPLX's own Python venv pulls checkpoints via huggingface_hub (see+// docs/features/mtplx.md), landing them in the standard HF hub cache — NOT+// necessarily the boot disk. getHfCacheRoot() honors the same+// HF_HUB_CACHE/HF_HOME overrides ollamaManager/lmStudioManager already do,+// so a "weights on an external SSD" setup gets checked against the volume+// the pull actually lands on.+const mtplxCachePath = () => getHfCacheRoot();async function expectedMtplxBytes(repo) {if (!repo) return 0;diff --git a/server/services/specDecodeModels.test.js b/server/services/specDecodeModels.test.jsindex d6cb997c73..5508ef6986 100644--- a/server/services/specDecodeModels.test.js+++ b/server/services/specDecodeModels.test.js@@ -193,7 +193,9 @@ 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(['base.gguf.partial']);+ // The partial survives for a Range-resume, alongside the ETag sidecar+ // recorded up front so that resume can send If-Range.+ expect((await readdir(dir)).sort()).toEqual(['base.gguf.partial', 'base.gguf.partial.etag']);});it('cancels an active transfer, emits a terminal frame, and removes its partial file', async () => {