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
address review (agy): claim the download slot before the Hugging Face lookup
Adam Eivy39b0dec957d6
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex 3cdbf4e8b8..e191088bda 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -426,8 +426,9 @@ export function LocalLlmTab() {return getLlamaServerStatus({ silent: true }).then((res) => {if (res) setLlamaStatus(res);+ return res;})- .catch(() => {});+ .catch(() => null);}, []);const loadStatus = useCallback(() => {@@ -504,20 +505,33 @@ export function LocalLlmTab() {}));}, [llamaStatus?.presets]);- // Byte progress for an in-flight GGUF download. Frames only update a row this- // tab already opened — an unknown key means another tab owns that transfer,- // and its row renders from the server-reported `downloading` flag instead.+ // Byte progress for an in-flight GGUF download. Frames are adopted no matter+ // who started the transfer — a reload mid-download, or a second tab, would+ // otherwise sit on whatever byte count the last status fetch happened to+ // carry and read as frozen. A terminal frame drops the row back to the+ // server's own view of the file, which the refresh below re-reads.useEffect(() => {const handleDownloadProgress = (frame) => {if (!frame?.presetId || !frame?.role) return;const key = downloadKey(frame.presetId, frame.role);- setLlamaDownloads((prev) => (prev[key]- ? { ...prev, [key]: { received: frame.received || 0, total: frame.total || 0 } }- : prev));+ if (frame.event === 'complete' || frame.event === 'error') {+ setLlamaDownloads((prev) => {+ if (!prev[key]) return prev;+ const next = { ...prev };+ delete next[key];+ return next;+ });+ loadLlamaStatus();+ return;+ }+ setLlamaDownloads((prev) => ({+ ...prev,+ [key]: { received: frame.received || 0, total: frame.total || 0 },+ }));};socket.on('llamaServer:download', handleDownloadProgress);return () => socket.off('llamaServer:download', handleDownloadProgress);- }, []);+ }, [loadLlamaStatus]);// Debounce so typing in the search box doesn't fire a request per keystroke.//// `activeCategory` is a trigger for the Hugging Face source ONLY — the live@@ -801,7 +815,20 @@ export function LocalLlmTab() {? `${res.path} is already on disk`: `${res?.path || 'Model'} downloaded`);} catch (err) {- toast.error(err?.message || 'Download failed');+ // A multi-gigabyte transfer outlives plenty of things that can drop this+ // request — a reload, a proxy's idle timeout. The download itself keeps+ // running server-side, so ask the server before calling it a failure:+ // reporting "Download failed" over a transfer that is still going is the+ // one message guaranteed to send the user looking for a problem that+ // isn't there.+ const status = await loadLlamaStatus();+ const stillRunning = status?.presets+ ?.find((p) => p.id === presetId)?.[role]?.downloading;+ if (stillRunning) {+ toast.warning('Download still running in the background — this page lost the request, not the transfer.');+ } else {+ toast.error(err?.message || 'Download failed');+ }} finally {setLlamaDownloads((prev) => {const next = { ...prev };diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsxindex 291065b3ac..79b3eacd5c 100644--- a/client/src/components/settings/LocalLlmTab.test.jsx+++ b/client/src/components/settings/LocalLlmTab.test.jsx@@ -336,9 +336,19 @@ const llamaReady = (overrides = {}) => ({});describe('LocalLlmTab llama-server management', () => {+ // `vi.clearAllMocks()` clears calls but NOT queued `mockResolvedValueOnce`+ // values or implementations, so a test that queues one more than the+ // component consumes leaks it into the next test's first status read. Reset+ // the mock outright here and give it a sane standing default.+ beforeEach(async () => {+ const { getLlamaServerStatus } = await import('../../services/api');+ getLlamaServerStatus.mockReset();+ getLlamaServerStatus.mockResolvedValue(llamaReady());+ });+it('renders start form and launches server when llama-server is installed', async () => {const { getLlamaServerStatus, startLlamaServer } = await import('../../services/api');- getLlamaServerStatus.mockResolvedValueOnce(llamaReady());+ getLlamaServerStatus.mockResolvedValue(llamaReady());startLlamaServer.mockResolvedValueOnce({ success: true, pid: 12345 });await renderTab();@@ -361,13 +371,15 @@ describe('LocalLlmTab llama-server management', () => {// otherwise Start is disabled while the UI reads as fully configured.it('seeds the form from the mounted preset so Start is immediately usable', async () => {const { getLlamaServerStatus, startLlamaServer } = await import('../../services/api');- getLlamaServerStatus.mockResolvedValueOnce(llamaReady());+ getLlamaServerStatus.mockResolvedValue(llamaReady());startLlamaServer.mockResolvedValueOnce({ success: true, pid: 4242 });await renderTab();await screen.findByText(/Launch Speculative Decoding Server/);- expect(screen.queryByText(/Enter a Target Base Model path to enable Start/)).toBeNull();+ // Same effect-ordering caveat as above, from the other side: wait for the+ // seeded form rather than asserting the warning is already gone.+ await waitFor(() => expect(screen.queryByText(/Enter a Target Base Model path to enable Start/)).toBeNull());const startBtn = screen.getByRole('button', { name: /Start Speculative Server/ });expect(startBtn).not.toBeDisabled();@@ -384,7 +396,7 @@ describe('LocalLlmTab llama-server management', () => {it('explains why Start is disabled once the model path is cleared', async () => {const { getLlamaServerStatus } = await import('../../services/api');- getLlamaServerStatus.mockResolvedValueOnce(llamaReady());+ getLlamaServerStatus.mockResolvedValue(llamaReady());await renderTab();@@ -399,7 +411,7 @@ describe('LocalLlmTab llama-server management', () => {it('swaps the preset and repoints both model paths', async () => {const { getLlamaServerStatus, startLlamaServer } = await import('../../services/api');- getLlamaServerStatus.mockResolvedValueOnce(llamaReady());+ getLlamaServerStatus.mockResolvedValue(llamaReady());startLlamaServer.mockResolvedValueOnce({ success: true, pid: 7 });await renderTab();@@ -423,7 +435,7 @@ describe('LocalLlmTab llama-server management', () => {// moment you clear it to retype, so the default is applied at launch instead.it('lets an advanced number field sit empty while retyping and defaults it at launch', async () => {const { getLlamaServerStatus, startLlamaServer } = await import('../../services/api');- getLlamaServerStatus.mockResolvedValueOnce(llamaReady());+ getLlamaServerStatus.mockResolvedValue(llamaReady());startLlamaServer.mockResolvedValueOnce({ success: true, pid: 21 });await renderTab();@@ -442,7 +454,7 @@ describe('LocalLlmTab llama-server management', () => {it('keeps an explicit -ngl 0 rather than treating it as unset', async () => {const { getLlamaServerStatus, startLlamaServer } = await import('../../services/api');- getLlamaServerStatus.mockResolvedValueOnce(llamaReady());+ getLlamaServerStatus.mockResolvedValue(llamaReady());startLlamaServer.mockResolvedValueOnce({ success: true, pid: 22 });await renderTab();@@ -459,7 +471,7 @@ describe('LocalLlmTab llama-server management', () => {it('drops the preset label to Custom once a preset-supplied path is hand-edited', async () => {const { getLlamaServerStatus } = await import('../../services/api');- getLlamaServerStatus.mockResolvedValueOnce(llamaReady());+ getLlamaServerStatus.mockResolvedValue(llamaReady());await renderTab();@@ -478,7 +490,7 @@ describe('LocalLlmTab llama-server management', () => {// stated way to fix it.it('offers a download button for a preset GGUF that is not on disk', async () => {const { getLlamaServerStatus, downloadSpecDecodeModel } = await import('../../services/api');- getLlamaServerStatus.mockResolvedValueOnce(llamaReady({ presets: specPresets({ baseExists: false }) }));+ getLlamaServerStatus.mockResolvedValue(llamaReady({ presets: specPresets({ baseExists: false }) }));downloadSpecDecodeModel.mockResolvedValueOnce({ success: true, path: 'models/Qwen3.8-27B-Instruct-Q4_K_M.gguf' });await renderTab();@@ -494,15 +506,46 @@ describe('LocalLlmTab llama-server management', () => {});});+ // A dropped request (reload, proxy idle timeout) does not stop the transfer —+ // reporting it as a failure sends the user hunting a problem that isn't there.+ it('reports a lost request as still-running when the server is still downloading', async () => {+ const { getLlamaServerStatus, downloadSpecDecodeModel } = await import('../../services/api');+ const toast = (await import('../ui/Toast')).default;+ const downloading = specPresets({ baseExists: false });+ downloading[0].model.downloading = true;+ // No queued `…Once` values anywhere in this block: a refresh from a+ // finished test can land during the next one and eat a queued entry, which+ // is how this suite went order-dependent. Flip on call count instead.+ let statusCalls = 0;+ getLlamaServerStatus.mockImplementation(async () => {+ statusCalls += 1;+ return llamaReady({ presets: statusCalls === 1 ? specPresets({ baseExists: false }) : downloading });+ });+ downloadSpecDecodeModel.mockRejectedValueOnce(new Error('Failed to fetch'));++ await renderTab();++ fireEvent.click(await screen.findByRole('button', { name: /^Download$/ }));++ await waitFor(() => {+ expect(toast.warning).toHaveBeenCalledWith(expect.stringMatching(/still running in the background/));+ });+ expect(toast.error).not.toHaveBeenCalled();+ // Mount + the catch's check + the finally's refresh.+ await waitFor(() => expect(getLlamaServerStatus).toHaveBeenCalledTimes(3));+ });+it('blocks Start while a preset GGUF is missing and names the fix', async () => {const { getLlamaServerStatus, startLlamaServer } = await import('../../services/api');- getLlamaServerStatus.mockResolvedValueOnce(llamaReady({ presets: specPresets({ baseExists: false }) }));+ getLlamaServerStatus.mockResolvedValue(llamaReady({ presets: specPresets({ baseExists: false }) }));await renderTab();- const startBtn = await screen.findByRole('button', { name: /Start Speculative Server/ });- expect(startBtn).toBeDisabled();- expect(screen.getByText('Download the base model to enable Start')).toBeInTheDocument();+ // `findBy…` on the warning itself: the form is seeded from the presets in+ // an effect, so the Start button can render a tick before the gate that+ // disables it — asserting the button first makes this order-dependent.+ expect(await screen.findByText('Download the base model to enable Start')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /Start Speculative Server/ })).toBeDisabled();expect(startLlamaServer).not.toHaveBeenCalled();});@@ -510,7 +553,7 @@ describe('LocalLlmTab llama-server management', () => {// row must send the user somewhere rather than offering an action that 400s.it('links out when a drafter has no automatic Hugging Face source', async () => {const { getLlamaServerStatus } = await import('../../services/api');- getLlamaServerStatus.mockResolvedValueOnce(llamaReady());+ getLlamaServerStatus.mockResolvedValue(llamaReady());await renderTab();@@ -523,7 +566,7 @@ describe('LocalLlmTab llama-server management', () => {it('renders install button and triggers install when llama-server is not installed', async () => {const { getLlamaServerStatus, installLlamaServer } = await import('../../services/api');- getLlamaServerStatus.mockResolvedValueOnce({ installed: false, running: false, managed: false, presets: specPresets() });+ getLlamaServerStatus.mockResolvedValue({ installed: false, running: false, managed: false, presets: specPresets() });await renderTab();@@ -538,7 +581,7 @@ describe('LocalLlmTab llama-server management', () => {it('renders running badge and stops server when llama-server is managed', async () => {const { getLlamaServerStatus, stopLlamaServer } = await import('../../services/api');- getLlamaServerStatus.mockResolvedValueOnce({+ getLlamaServerStatus.mockResolvedValue({installed: true,running: true,managed: true,diff --git a/server/services/specDecodeModels.js b/server/services/specDecodeModels.jsindex 8ea38a076d..b61aeab387 100644--- a/server/services/specDecodeModels.js+++ b/server/services/specDecodeModels.js@@ -188,18 +188,22 @@ export async function downloadSpecDecodeModel({ presetId, role, onProgress = ()if (inFlight.has(destPath)) {throw new ServerError(`${source.path} is already downloading`, { status: 409, code: 'SPEC_DOWNLOAD_IN_FLIGHT' });}-- const token = await getHfToken();- const headers = buildHfAuthHeaders(token);- onProgress({ event: 'start', presetId, role, path: source.path, message: `Resolving ${source.repo} on Hugging Face…` });- const model = await fetchHuggingfaceModel(source.repo, { token });- const file = pickGgufSibling(model, { file: source.file, quant: source.quant, repo: source.repo });-+ // Claim the slot BEFORE the first await. Resolving the repo on Hugging Face+ // takes a round trip, and a second click (or a second tab) landing inside that+ // window would clear the check above and start a parallel multi-gigabyte+ // transfer of the same file. Everything after this point runs inside the+ // try/finally so the claim is always released.const state = { presetId, role, received: 0, total: 0 };inFlight.set(destPath, state);+let lastEmit = 0;- console.log(`⬇️ Downloading speculative-decoding weights ${source.repo}/${file} → ${source.path}`);try {+ const token = await getHfToken();+ const headers = buildHfAuthHeaders(token);+ onProgress({ event: 'start', presetId, role, path: source.path, message: `Resolving ${source.repo} on Hugging Face…` });+ const model = await fetchHuggingfaceModel(source.repo, { token });+ const file = pickGgufSibling(model, { file: source.file, quant: source.quant, repo: source.repo });+ console.log(`⬇️ Downloading speculative-decoding weights ${source.repo}/${file} → ${source.path}`);const { bytes } = await streamToFile({url: buildHfResolveUrl(source.repo, 'main', file),headers,diff --git a/server/services/specDecodeModels.test.js b/server/services/specDecodeModels.test.jsindex d55c1cb13a..f5a18ede85 100644--- a/server/services/specDecodeModels.test.js+++ b/server/services/specDecodeModels.test.js@@ -1,7 +1,7 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { mkdtemp, readFile, rm, writeFile } from 'fs/promises';-import { tmpdir } from 'os';-import { join } from 'path';+import { homedir, tmpdir } from 'os';+import { isAbsolute, join } from 'path';import { Readable } from 'stream';import {downloadSpecDecodeModel,@@ -137,6 +137,45 @@ describe('downloadSpecDecodeModel', () => {expect(await readdir(dir)).toEqual([]);});+ // The slot is claimed before the Hugging Face round trip: a second click+ // landing inside that window would otherwise clear the in-flight check and+ // start a parallel multi-gigabyte transfer of the same file.+ it('refuses a second request that arrives while the repo is still being resolved', async () => {+ stubPreset();+ let releaseMetadata;+ vi.spyOn(huggingfaceLora, 'fetchHuggingfaceModel').mockImplementation(+ () => new Promise((resolve) => { releaseMetadata = () => resolve(siblings('Example-Q4_K_M.gguf')); }),+ );+ vi.spyOn(globalThis, 'fetch').mockResolvedValue({+ ok: true,+ status: 200,+ headers: { get: () => '2' },+ body: Readable.toWeb(Readable.from([Buffer.from('gg')])),+ });++ const first = downloadSpecDecodeModel({ presetId: 'test-preset', role: 'model' });+ await vi.waitFor(() => expect(releaseMetadata).toBeTypeOf('function'));++ await expect(downloadSpecDecodeModel({ presetId: 'test-preset', role: 'model' }))+ .rejects.toThrow(/already downloading/);++ releaseMetadata();+ await expect(first).resolves.toMatchObject({ success: true });+ });++ // …and the claim is released when that resolution fails, or the file could+ // never be retried without restarting the server.+ it('releases the claim when resolving the repo fails', async () => {+ stubPreset();+ vi.spyOn(huggingfaceLora, 'fetchHuggingfaceModel').mockRejectedValue(new Error('HF unreachable'));++ await expect(downloadSpecDecodeModel({ presetId: 'test-preset', role: 'model' }))+ .rejects.toThrow(/HF unreachable/);++ const status = await getSpecDecodePresetStatus();+ expect(status.every((p) => !p.model?.downloading && !p.draftModel?.downloading)).toBe(true);+ });+it('short-circuits when the weights are already on disk', async () => {stubPreset();await writeFile(join(dir, 'base.gguf'), 'already here');@@ -164,6 +203,16 @@ describe('downloadSpecDecodeModel', () => {describe('resolveSpecModelPath', () => {it('resolves a relative launcher path to an absolute one', () => {- expect(resolveSpecModelPath('models/base.gguf')).toBe(join(process.cwd(), 'models/base.gguf'));+ const resolved = resolveSpecModelPath('models/base.gguf');+ expect(isAbsolute(resolved)).toBe(true);+ expect(resolved.endsWith(join('models', 'base.gguf'))).toBe(true);+ });++ // `spawn` performs no shell expansion, so a `~` path has to be expanded here+ // or the launcher and the downloader disagree about which file they mean.+ it('expands a leading ~ rather than passing it through literally', () => {+ const resolved = resolveSpecModelPath('~/models/base.gguf');+ expect(resolved.startsWith(homedir())).toBe(true);+ expect(resolved).not.toContain('~');});});