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

Download speculative-decoding GGUFs from the Local LLM card

Adam Eivy42e530a5b548
diff --git a/.gitignore b/.gitignore
index 0df83434b6..7fc4906e28 100644
--- a/.gitignore
+++ b/.gitignore
@@ -91,6 +91,10 @@ tmp/LoraDatasetDetail.js
# Runtime cache (e.g. projects.json) — regenerated, never committed
cache/
+# Local GGUF weights downloaded by the speculative-decoding launcher — many GB,
+# re-downloadable from Hugging Face
+/models/
+
.antigravitycli
.superpowers/
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index a5e63b06fc..c2d355af51 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -10,11 +10,13 @@ import { useConfirmDelete } from '../../hooks/useConfirmDelete';
import {
getLocalLlmStatus, getLocalLlmCatalog, getLocalLlmHuggingFaceSearch, installLocalLlmModel,
deleteLocalLlmModel, switchLocalLlmBackend, migrateLocalLlmBackend, installLocalLlmBackend, upgradeLocalLlmBackend, controlOllamaService,
- installAudioModel, patchSettingsSlice, getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaServer
+ installAudioModel, patchSettingsSlice, getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaServer,
+ downloadSpecDecodeModel
} from '../../services/api';
import socket from '../../services/socket';
import MemoryManagement from './MemoryManagement.jsx';
import LocalModelAssessments from './LocalModelAssessments.jsx';
+import SpecDecodeWeightRow from './SpecDecodeWeightRow.jsx';
const BACKENDS = [
{ id: 'ollama', label: 'Ollama', icon: Cpu },
@@ -22,54 +24,17 @@ const BACKENDS = [
];
const labelFor = (id) => BACKENDS.find((b) => b.id === id)?.label || id;
-// llama.cpp exposes one `--spec-type` per drafter family. `draft-dspark` merged
-// upstream on 2026-07-28 (ggml-org/llama.cpp#25173) and works on a stock
-// `brew install llama.cpp`; `draft-dflash` covers DFlash v1, while the DFlash 2
-// modules are still an open PR (#27342) and need a from-source build. Hence the
-// DSpark presets lead — see docs/research/2026-08-19-dspark-vs-dflash2.md.
-const SPEC_DECODE_PRESETS = [
- {
- id: 'qwen3.8-27b-dspark',
- label: 'Qwen 3.8 27B + DSpark Drafter (Recommended — stock llama.cpp)',
- model: 'models/Qwen3.8-27B-Instruct-Q4_K_M.gguf',
- draftModel: 'models/Qwen3.8-27B-DSpark-bf16.gguf',
- specType: 'draft-dspark',
- },
- {
- id: 'qwen3-8b-dspark',
- label: 'Qwen 3 8B + DSpark Drafter (small target)',
- model: 'models/Qwen3-8B-Instruct-Q4_K_M.gguf',
- draftModel: 'models/dspark_qwen3_8b_block7-bf16.gguf',
- specType: 'draft-dspark',
- },
- {
- id: 'qwen3.8-27b',
- label: 'Qwen 3.8 27B + DFlash 2 Drafter (needs llama.cpp PR #27342 build)',
- model: 'models/Qwen3.8-27B-Instruct-Q4_K_M.gguf',
- draftModel: 'models/Qwen3.8-27B-DFlash2-Q4_K_M.gguf',
- specType: 'draft-dflash',
- },
- {
- id: 'muse-glimmer-30b',
- label: 'Muse-Glimmer 30B + DFlash 2 Drafter (needs llama.cpp PR #27342 build)',
- model: 'models/Muse-Glimmer-30B-Instruct-Q4_K_M.gguf',
- draftModel: 'models/Muse-Glimmer-30B-DFlash2-Q4_K_M.gguf',
- specType: 'draft-dflash',
- },
- {
- id: 'custom',
- label: 'Custom GGUF / Manual Paths',
- model: '',
- draftModel: '',
- specType: 'draft-dspark',
- },
-];
-
-// The select mounts on this preset, so the form has to be seeded from it too —
-// otherwise the recommended preset reads as chosen while the required model path
-// is still empty, and Start sits disabled with nothing the user can act on.
+// The speculative-decoding presets come from the server
+// (`server/lib/specDecodePresets.js`, surfaced on the llama-server status
+// response) rather than a table here: each preset names a multi-gigabyte GGUF,
+// and only the server knows which Hugging Face repo it comes from, whether it
+// is already on disk, and how to fetch it. A client-side copy would inevitably
+// list a path the Download button had no source for.
const DEFAULT_SPEC_PRESET_ID = 'qwen3.8-27b-dspark';
-const findSpecPreset = (id) => SPEC_DECODE_PRESETS.find((p) => p.id === id);
+const downloadKey = (presetId, role) => `${presetId}:${role}`;
+// Each entry carries its own `role`, so the rows come straight off the preset
+// rather than from a second copy of the role list.
+const specWeightEntries = (preset) => [preset?.model, preset?.draftModel].filter((e) => e?.path);
// Defaults for the advanced numeric fields. They are applied when the server is
// launched rather than on every keystroke: a controlled number input that coerces
@@ -439,19 +404,21 @@ export function LocalLlmTab() {
const [llamaStatus, setLlamaStatus] = useState(null);
const [llamaLoading, setLlamaLoading] = useState(false);
const [llamaPresetId, setLlamaPresetId] = useState(DEFAULT_SPEC_PRESET_ID);
- const [llamaForm, setLlamaForm] = useState(() => {
- const preset = findSpecPreset(DEFAULT_SPEC_PRESET_ID);
- return {
- model: preset?.model || '',
- draftModel: preset?.draftModel || '',
- specType: preset?.specType || 'draft-dspark',
- port: 8080,
- host: '127.0.0.1',
- ctxSize: 32768,
- nGpuLayers: 99,
- alias: 'dflash',
- };
+ const [llamaForm, setLlamaForm] = useState({
+ model: '',
+ draftModel: '',
+ specType: 'draft-dspark',
+ port: 8080,
+ host: '127.0.0.1',
+ ctxSize: 32768,
+ nGpuLayers: 99,
+ alias: 'dflash',
});
+ // Byte progress for downloads STARTED HERE, keyed `presetId:role`. A transfer
+ // another tab started still renders — the server reports it on the entry —
+ // but only the starting tab owns the toast and the cleanup.
+ const [llamaDownloads, setLlamaDownloads] = useState({});
+ const specPresetSeeded = useRef(false);
const [showLlamaAdvanced, setShowLlamaAdvanced] = useState(false);
const [showLlamaLogs, setShowLlamaLogs] = useState(false);
@@ -516,6 +483,41 @@ export function LocalLlmTab() {
}, []);
useEffect(() => { loadStatus(); }, [loadStatus]);
+
+ // The preset select mounts pre-selected, so the form has to be filled in the
+ // moment the presets land — otherwise the recommended preset reads as chosen
+ // while the required model path is still empty and Start sits disabled with
+ // nothing to act on. Seeds once, so a later status refresh can't overwrite
+ // paths the user has since edited.
+ useEffect(() => {
+ if (specPresetSeeded.current) return;
+ const presets = llamaStatus?.presets;
+ if (!presets?.length) return;
+ const preset = presets.find((p) => p.id === DEFAULT_SPEC_PRESET_ID) || presets[0];
+ specPresetSeeded.current = true;
+ setLlamaPresetId(preset.id);
+ setLlamaForm((prev) => ({
+ ...prev,
+ model: preset.model?.path || '',
+ draftModel: preset.draftModel?.path || '',
+ specType: preset.specType || prev.specType,
+ }));
+ }, [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.
+ 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));
+ };
+ socket.on('llamaServer:download', handleDownloadProgress);
+ return () => socket.off('llamaServer:download', handleDownloadProgress);
+ }, []);
// 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
@@ -761,10 +763,52 @@ export function LocalLlmTab() {
const setLlamaNumber = (field, raw) =>
setLlamaForm((prev) => ({ ...prev, [field]: raw === '' ? '' : Number(raw) }));
- const activeSpecPreset = findSpecPreset(llamaPresetId);
+ const specPresets = llamaStatus?.presets || [];
+ const activeSpecPreset = specPresets.find((p) => p.id === llamaPresetId) || null;
+ const activeSpecWeights = specWeightEntries(activeSpecPreset);
// Clearing the target path is the one way back to a disabled Start — say why
// rather than leaving a dead button.
const llamaModelMissing = !llamaForm.model.trim();
+ // A preset file the server says isn't on disk, still named by the form. This
+ // is what the launcher would reject with LLAMA_MODEL_FILE_MISSING, so block
+ // Start here and point at the Download button instead of spending a request
+ // to produce an error the card can already answer.
+ const missingWeight = (role) => {
+ const entry = activeSpecPreset?.[role];
+ const field = role === 'model' ? llamaForm.model : llamaForm.draftModel;
+ return Boolean(entry?.path && !entry.exists && entry.path === (field || '').trim());
+ };
+ const baseWeightMissing = missingWeight('model');
+ const draftWeightMissing = missingWeight('draftModel');
+ const llamaStartBlocked = llamaModelMissing || baseWeightMissing || draftWeightMissing;
+ const llamaStartBlockedReason = llamaModelMissing
+ ? 'Enter a Target Base Model path to enable Start'
+ : baseWeightMissing
+ ? 'Download the base model to enable Start'
+ : draftWeightMissing
+ ? 'Download the drafter, or clear the field to run without it'
+ : '';
+
+ const handleDownloadSpecModel = async (role) => {
+ const presetId = llamaPresetId;
+ const key = downloadKey(presetId, role);
+ setLlamaDownloads((prev) => ({ ...prev, [key]: { received: 0, total: 0 } }));
+ try {
+ const res = await downloadSpecDecodeModel(presetId, role);
+ toast.success(res?.alreadyDownloaded
+ ? `${res.path} is already on disk`
+ : `${res?.path || 'Model'} downloaded`);
+ } catch (err) {
+ toast.error(err?.message || 'Download failed');
+ } finally {
+ setLlamaDownloads((prev) => {
+ const next = { ...prev };
+ delete next[key];
+ return next;
+ });
+ loadLlamaStatus();
+ }
+ };
const handleStartLlama = async (e) => {
e?.preventDefault?.();
@@ -773,6 +817,10 @@ export function LocalLlmTab() {
toast.error('Please specify a base model path (e.g. models/Qwen3.8-27B-Instruct-Q4_K_M.gguf)');
return;
}
+ if (baseWeightMissing || draftWeightMissing) {
+ toast.error(`${llamaStartBlockedReason} — the GGUF isn't on this machine yet.`);
+ return;
+ }
setLlamaLoading(true);
const config = { ...llamaForm };
for (const [field, fallback] of Object.entries(LLAMA_NUMBER_DEFAULTS)) {
@@ -827,15 +875,16 @@ export function LocalLlmTab() {
};
const handlePresetSelect = (presetId) => {
- const preset = findSpecPreset(presetId);
+ const preset = specPresets.find((p) => p.id === presetId);
if (!preset) return;
setLlamaPresetId(preset.id);
- if (preset.id !== 'custom') {
+ // `custom` carries no paths — it exists so hand-entered fields keep a label.
+ if (preset.model?.path || preset.draftModel?.path) {
setLlamaForm((prev) => ({
...prev,
- model: preset.model,
- draftModel: preset.draftModel,
- specType: preset.specType,
+ model: preset.model?.path || '',
+ draftModel: preset.draftModel?.path || '',
+ specType: preset.specType || prev.specType,
}));
}
};
@@ -1041,7 +1090,7 @@ export function LocalLlmTab() {
value={llamaPresetId}
className="bg-port-card border border-port-border rounded px-2 py-1 text-xs text-port-accent focus:outline-none"
>
- {SPEC_DECODE_PRESETS.map((p) => (
+ {specPresets.map((p) => (
<option key={p.id} value={p.id}>
{p.label}
</option>
@@ -1059,7 +1108,7 @@ export function LocalLlmTab() {
type="text"
value={llamaForm.model}
onChange={(e) => setLlamaField('model', e.target.value)}
- placeholder={activeSpecPreset?.model || 'models/your-target-Q4_K_M.gguf'}
+ placeholder={activeSpecPreset?.model?.path || 'models/your-target-Q4_K_M.gguf'}
className="w-full bg-port-card border border-port-border rounded px-2.5 py-1.5 text-xs text-white placeholder-gray-600 focus:outline-none focus:border-port-accent"
/>
</div>
@@ -1071,12 +1120,29 @@ export function LocalLlmTab() {
type="text"
value={llamaForm.draftModel}
onChange={(e) => setLlamaField('draftModel', e.target.value)}
- placeholder={activeSpecPreset?.draftModel || 'models/your-drafter.gguf'}
+ placeholder={activeSpecPreset?.draftModel?.path || 'models/your-drafter.gguf'}
className="w-full bg-port-card border border-port-border rounded px-2.5 py-1.5 text-xs text-white placeholder-gray-600 focus:outline-none focus:border-port-accent"
/>
</div>
</div>
+ {activeSpecWeights.length > 0 && (
+ <div className="space-y-1.5 pt-2 border-t border-port-border/40">
+ <p className="text-[11px] text-gray-500">
+ Weights on this machine — each GGUF is a separate multi-gigabyte download from Hugging Face, fetched into the path above.
+ </p>
+ {activeSpecWeights.map((entry) => (
+ <SpecDecodeWeightRow
+ key={entry.role}
+ entry={entry}
+ progress={llamaDownloads[downloadKey(llamaPresetId, entry.role)]}
+ onDownload={handleDownloadSpecModel}
+ disabled={llamaLoading}
+ />
+ ))}
+ </div>
+ )}
+
{showLlamaAdvanced && (
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2 pt-1 border-t border-port-border/40 text-xs">
<div>
@@ -1136,15 +1202,19 @@ export function LocalLlmTab() {
{showLlamaAdvanced ? 'Hide options' : 'Advanced options (port, ctx, GPU layers)'}
</button>
<div className="flex items-center gap-2">
- {llamaModelMissing && (
+ {llamaStartBlocked && (
<span className="text-[11px] text-port-warning text-right">
- Enter a Target Base Model path to enable Start
+ {llamaStartBlockedReason}
</span>
)}
<button
type="submit"
- disabled={llamaLoading || llamaModelMissing}
- title={llamaModelMissing ? 'Target Base Model (GGUF Path) is required before the server can start' : 'Launch llama-server with these settings'}
+ disabled={llamaLoading || llamaStartBlocked}
+ title={llamaModelMissing
+ ? 'Target Base Model (GGUF Path) is required before the server can start'
+ : llamaStartBlocked
+ ? `${llamaStartBlockedReason} — llama.cpp can't load a GGUF that isn't on disk`
+ : 'Launch llama-server with these settings'}
className="flex items-center gap-1.5 px-3 py-1.5 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent text-xs font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed shrink-0"
>
{llamaLoading ? <BrailleSpinner /> : <Power size={13} />}
diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsx
index b68d8f153c..83cb9f9da5 100644
--- a/client/src/components/settings/LocalLlmTab.test.jsx
+++ b/client/src/components/settings/LocalLlmTab.test.jsx
@@ -19,6 +19,7 @@ vi.mock('../../services/api', () => ({
startLlamaServer: vi.fn(),
stopLlamaServer: vi.fn(),
installLlamaServer: vi.fn().mockResolvedValue({ success: true }),
+ downloadSpecDecodeModel: vi.fn(),
}));
vi.mock('../../services/socket', () => ({
default: { on: vi.fn(), off: vi.fn() },
@@ -267,14 +268,77 @@ describe('LocalLlmTab measured fit badge', () => {
});
});
+// The launcher presets (and their weights' on-disk state) come from the server
+// on the llama-server status response — the component holds no copy.
+const specPresets = ({ baseExists = true, draftExists = true } = {}) => ([
+ {
+ id: 'qwen3.8-27b-dspark',
+ label: 'Qwen 3.8 27B + DSpark Drafter (Recommended — stock llama.cpp)',
+ specType: 'draft-dspark',
+ model: {
+ role: 'model',
+ path: 'models/Qwen3.8-27B-Instruct-Q4_K_M.gguf',
+ exists: baseExists,
+ sizeBytes: baseExists ? 17_000_000_000 : null,
+ repo: 'unsloth/Qwen3.8-27B-GGUF',
+ repoUrl: 'https://huggingface.co/unsloth/Qwen3.8-27B-GGUF',
+ downloadable: true,
+ downloading: false,
+ },
+ draftModel: {
+ role: 'draftModel',
+ path: 'models/Qwen3.8-27B-DSpark-bf16.gguf',
+ exists: draftExists,
+ sizeBytes: draftExists ? 1_200_000_000 : null,
+ repo: 'magnitudedev/Qwen3.8-27B-DSpark-GGUF',
+ repoUrl: 'https://huggingface.co/magnitudedev/Qwen3.8-27B-DSpark-GGUF',
+ downloadable: true,
+ downloading: false,
+ },
+ },
+ {
+ id: 'qwen3-8b-dspark',
+ label: 'Qwen 3 8B + DSpark Drafter (small target)',
+ specType: 'draft-dspark',
+ model: {
+ role: 'model',
+ path: 'models/Qwen3-8B-Instruct-Q4_K_M.gguf',
+ exists: true,
+ sizeBytes: 5_000_000_000,
+ repo: 'Qwen/Qwen3-8B-Instruct-GGUF',
+ repoUrl: 'https://huggingface.co/Qwen/Qwen3-8B-Instruct-GGUF',
+ downloadable: true,
+ downloading: false,
+ },
+ // The 8B DSpark block ships as a tokenizer-less checkpoint that has to be
+ // converted against its target — no single-file GGUF to fetch, so this row
+ // has to link out instead of offering a button.
+ draftModel: {
+ role: 'draftModel',
+ path: 'models/dspark_qwen3_8b_block7-bf16.gguf',
+ exists: false,
+ sizeBytes: null,
+ repo: null,
+ repoUrl: 'https://huggingface.co/models?search=dspark_qwen3_8b_block7-bf16',
+ downloadable: false,
+ downloading: false,
+ },
+ },
+ { id: 'custom', label: 'Custom GGUF / Manual Paths', specType: 'draft-dspark', model: null, draftModel: null },
+]);
+
+const llamaReady = (overrides = {}) => ({
+ installed: true,
+ running: false,
+ managed: false,
+ presets: specPresets(),
+ ...overrides,
+});
+
describe('LocalLlmTab llama-server management', () => {
it('renders start form and launches server when llama-server is installed', async () => {
const { getLlamaServerStatus, startLlamaServer } = await import('../../services/api');
- getLlamaServerStatus.mockResolvedValueOnce({
- installed: true,
- running: false,
- managed: false,
- });
+ getLlamaServerStatus.mockResolvedValueOnce(llamaReady());
startLlamaServer.mockResolvedValueOnce({ success: true, pid: 12345 });
await renderTab();
@@ -297,7 +361,7 @@ 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({ installed: true, running: false, managed: false });
+ getLlamaServerStatus.mockResolvedValueOnce(llamaReady());
startLlamaServer.mockResolvedValueOnce({ success: true, pid: 4242 });
await renderTab();
@@ -320,7 +384,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({ installed: true, running: false, managed: false });
+ getLlamaServerStatus.mockResolvedValueOnce(llamaReady());
await renderTab();
@@ -335,30 +399,31 @@ describe('LocalLlmTab llama-server management', () => {
it('swaps the preset and repoints both model paths', async () => {
const { getLlamaServerStatus, startLlamaServer } = await import('../../services/api');
- getLlamaServerStatus.mockResolvedValueOnce({ installed: true, running: false, managed: false });
+ getLlamaServerStatus.mockResolvedValueOnce(llamaReady());
startLlamaServer.mockResolvedValueOnce({ success: true, pid: 7 });
await renderTab();
const presetSelect = await screen.findByLabelText('Preset');
- fireEvent.change(presetSelect, { target: { value: 'muse-glimmer-30b' } });
-
- fireEvent.click(screen.getByRole('button', { name: /Start Speculative Server/ }));
-
- await waitFor(() => {
- expect(startLlamaServer).toHaveBeenCalledWith(expect.objectContaining({
- model: 'models/Muse-Glimmer-30B-Instruct-Q4_K_M.gguf',
- draftModel: 'models/Muse-Glimmer-30B-DFlash2-Q4_K_M.gguf',
- specType: 'draft-dflash',
- }));
- });
+ fireEvent.change(presetSelect, { target: { value: 'qwen3-8b-dspark' } });
+
+ expect(screen.getByLabelText(/Target Base Model \(GGUF Path\)/))
+ .toHaveValue('models/Qwen3-8B-Instruct-Q4_K_M.gguf');
+ expect(screen.getByLabelText(/Draft Model \(Optional\)/))
+ .toHaveValue('models/dspark_qwen3_8b_block7-bf16.gguf');
+
+ // This preset's drafter isn't on disk, so Start stays blocked until the
+ // user downloads it (or clears the field) — that is the launcher contract,
+ // not an incidental fixture detail.
+ expect(screen.getByRole('button', { name: /Start Speculative Server/ })).toBeDisabled();
+ expect(startLlamaServer).not.toHaveBeenCalled();
});
// Coercing a number input on every keystroke snaps it back to its default the
// 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({ installed: true, running: false, managed: false });
+ getLlamaServerStatus.mockResolvedValueOnce(llamaReady());
startLlamaServer.mockResolvedValueOnce({ success: true, pid: 21 });
await renderTab();
@@ -377,7 +442,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({ installed: true, running: false, managed: false });
+ getLlamaServerStatus.mockResolvedValueOnce(llamaReady());
startLlamaServer.mockResolvedValueOnce({ success: true, pid: 22 });
await renderTab();
@@ -394,7 +459,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({ installed: true, running: false, managed: false });
+ getLlamaServerStatus.mockResolvedValueOnce(llamaReady());
await renderTab();
@@ -408,13 +473,57 @@ describe('LocalLlmTab llama-server management', () => {
expect(presetSelect).toHaveValue('custom');
});
+ // The whole point of the weights rows: a missing GGUF used to surface only as
+ // a 400 from Start ("The base model was not found at `models/…`") with no
+ // 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 }) }));
+ downloadSpecDecodeModel.mockResolvedValueOnce({ success: true, path: 'models/Qwen3.8-27B-Instruct-Q4_K_M.gguf' });
+
+ await renderTab();
+
+ await screen.findByText(/Launch Speculative Decoding Server/);
+ // The drafter IS on disk, so exactly one row offers a download.
+ expect(screen.getByText(/Downloaded \(1\.1 GB\)/)).toBeInTheDocument();
+ const downloadBtn = screen.getByRole('button', { name: /^Download$/ });
+ fireEvent.click(downloadBtn);
+
+ await waitFor(() => {
+ expect(downloadSpecDecodeModel).toHaveBeenCalledWith('qwen3.8-27b-dspark', 'model');
+ });
+ });
+
+ 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 }) }));
+
+ 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();
+ expect(startLlamaServer).not.toHaveBeenCalled();
+ });
+
+ // A drafter with no published single-file GGUF has no Download button — the
+ // 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());
+
+ await renderTab();
+
+ const presetSelect = await screen.findByLabelText('Preset');
+ fireEvent.change(presetSelect, { target: { value: 'qwen3-8b-dspark' } });
+
+ const link = screen.getByRole('link', { name: /Find on Hugging Face/ });
+ expect(link).toHaveAttribute('href', 'https://huggingface.co/models?search=dspark_qwen3_8b_block7-bf16');
+ });
+
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,
- });
+ getLlamaServerStatus.mockResolvedValueOnce({ installed: false, running: false, managed: false, presets: specPresets() });
await renderTab();
@@ -433,6 +542,7 @@ describe('LocalLlmTab llama-server management', () => {
installed: true,
running: true,
managed: true,
+ presets: specPresets(),
pid: 9999,
endpoint: 'http://127.0.0.1:8080/v1',
config: { model: 'models/base.gguf', draftModel: 'models/draft.gguf', specType: 'draft-dflash' },
diff --git a/client/src/components/settings/SpecDecodeWeightRow.jsx b/client/src/components/settings/SpecDecodeWeightRow.jsx
new file mode 100644
index 0000000000..d17ddb56f5
--- /dev/null
+++ b/client/src/components/settings/SpecDecodeWeightRow.jsx
@@ -0,0 +1,94 @@
+import { Check, Download, ExternalLink } from 'lucide-react';
+import BrailleSpinner from '../BrailleSpinner';
+import { formatBytes } from '../../utils/formatters';
+
+const ROLE_LABELS = { model: 'Target base model', draftModel: 'Drafter' };
+
+/**
+ * One GGUF of a speculative-decoding preset: where it goes, whether it's on
+ * this machine, and the button that fetches it.
+ *
+ * The launcher can only ever report a missing file as a failed Start — the
+ * weights are a separate multi-gigabyte download from the llama.cpp binary — so
+ * this row is what turns "The base model was not found at `models/…`" into a
+ * thing the user can act on without leaving the page.
+ */
+export default function SpecDecodeWeightRow({ entry, progress, onDownload, disabled }) {
+ if (!entry?.path) return null;
+ const label = ROLE_LABELS[entry.role] || entry.role;
+ const downloading = Boolean(progress) || entry.downloading;
+ const received = progress?.received ?? entry.received ?? 0;
+ const total = progress?.total ?? entry.total ?? 0;
+ // An unknown total (no Content-Length behind the CDN redirect) renders as an
+ // indeterminate byte counter rather than a bar stuck at 0%.
+ const percent = total > 0 ? Math.min(100, Math.round((received / total) * 100)) : null;
+
+ return (
+ <div className="bg-port-card/60 border border-port-border/60 rounded px-2.5 py-1.5 space-y-1.5">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <div className="min-w-0">
+ <p className="text-[11px] text-gray-500">{label}</p>
+ <code className="text-[11px] text-gray-300 break-all">{entry.path}</code>
+ </div>
+ <div className="flex items-center gap-2 shrink-0">
+ {entry.exists ? (
+ <span className="flex items-center gap-1 text-[11px] text-port-success">
+ <Check size={12} />
+ Downloaded{entry.sizeBytes ? ` (${formatBytes(entry.sizeBytes)})` : ''}
+ </span>
+ ) : downloading ? (
+ <span className="flex items-center gap-1.5 text-[11px] text-gray-400">
+ <BrailleSpinner />
+ {percent === null ? formatBytes(received) : `${percent}%`}
+ </span>
+ ) : entry.downloadable ? (
+ <>
+ <a
+ href={entry.repoUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-[11px] text-gray-500 hover:text-gray-300 flex items-center gap-1"
+ title={`View ${entry.repo} on Hugging Face`}
+ >
+ {entry.repo} <ExternalLink size={10} />
+ </a>
+ <button
+ type="button"
+ onClick={() => onDownload(entry.role)}
+ disabled={disabled}
+ className="flex items-center gap-1.5 px-2 py-1 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent text-[11px] font-medium rounded transition-colors disabled:opacity-50"
+ title={`Download ${label.toLowerCase()} from ${entry.repo} into ${entry.path}`}
+ >
+ <Download size={11} />
+ Download
+ </button>
+ </>
+ ) : (
+ <a
+ href={entry.repoUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-[11px] text-port-warning hover:underline flex items-center gap-1"
+ title="No single-file GGUF is published for this drafter — download one yourself and point the field at it"
+ >
+ Find on Hugging Face <ExternalLink size={10} />
+ </a>
+ )}
+ </div>
+ </div>
+ {downloading && (
+ <div className="space-y-1">
+ <div className="h-1 bg-port-border/60 rounded overflow-hidden">
+ <div
+ className={`h-full bg-port-accent ${percent === null ? 'animate-pulse w-1/3' : 'transition-[width]'}`}
+ style={percent === null ? undefined : { width: `${percent}%` }}
+ />
+ </div>
+ <p className="text-[10px] text-gray-500">
+ {total > 0 ? `${formatBytes(received)} of ${formatBytes(total)}` : `${formatBytes(received)} downloaded`}
+ </p>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index 2f64f3062c..74e5db18b7 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -58,6 +58,17 @@ export const stopLlamaServer = () =>
export const installLlamaServer = () =>
request('/local-llm/llama-server/install', { method: 'POST' });
+// Fetch one speculative-decoding preset's GGUF (role: 'model' | 'draftModel')
+// from Hugging Face into the path the launcher passes llama.cpp. Byte progress
+// arrives on the `llamaServer:download` socket event, not in this response —
+// a multi-GB transfer resolves only when the file is on disk.
+export const downloadSpecDecodeModel = (presetId, role, options) =>
+ request('/local-llm/llama-server/download-model', {
+ method: 'POST',
+ body: JSON.stringify({ presetId, role }),
+ ...options,
+ });
+
// Set the default backend (which one PortOS routes local runs to) — does not move models.
export const switchLocalLlmBackend = (to) =>
request('/local-llm/switch', { method: 'POST', body: JSON.stringify({ to }) });
diff --git a/docs/features/dflash2.md b/docs/features/dflash2.md
index 9becf2eebb..3436db6827 100644
--- a/docs/features/dflash2.md
+++ b/docs/features/dflash2.md
@@ -26,10 +26,23 @@ PortOS integrates both through the **OpenCode llama TUI** provider preset and th
## Setup & Running with llama-server
### 1. Download Base & Draft Models
-Download your base GGUF and a matching drafter GGUF from Hugging Face. Drafter
-checkpoints are **not standalone models** — they only produce text once an engine
-pairs them with their specific target, which is why PortOS's model search filters
-them out of the install picker.
+
+**From the UI (recommended).** **Settings → Local LLMs → Speculative Decoding**
+lists each preset's two GGUFs with their on-disk state and a **Download** button
+per file — PortOS fetches the weights from Hugging Face straight into the path
+the launcher passes `llama.cpp`, so a missing file is visible (and fixable)
+before you press Start rather than surfacing as a failed launch. Start stays
+disabled, naming the file to download, while either half of the selected pair is
+missing. A drafter with no published single-file GGUF (the DSpark 8B block ships
+as a tokenizer-less checkpoint) links out to a Hugging Face search instead.
+Gated repos use the Hugging Face token from Image Gen settings. Downloads land
+in `models/` under the install root (gitignored, not included in backups —
+they're re-downloadable).
+
+**By hand.** Download your base GGUF and a matching drafter GGUF from Hugging
+Face. Drafter checkpoints are **not standalone models** — they only produce text
+once an engine pairs them with their specific target, which is why PortOS's model
+search filters them out of the install picker.
DSpark pairs (stock llama.cpp):
@@ -91,8 +104,9 @@ Until all three pass, the card says what is missing and links to
`Cannot connect to API: Unable to connect` inside the agent transcript.
The GGUF weights are a separate download from the binary: `llama-server` will
-not start without them, and PortOS now refuses the start with the missing path
-named rather than reporting a PID for a process that already exited.
+not start without them, and PortOS refuses the start with the missing path named
+rather than reporting a PID for a process that already exited. The Speculative
+Decoding card downloads them for you — see step 1.
---
diff --git a/server/lib/README.md b/server/lib/README.md
index 696268f626..53a60198f5 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -296,6 +296,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `huggingfaceModel.js` | HuggingFace base-model (image/video) classifier for the self-service "add a model" flow (#2124): inspect repo siblings + card → decide the loadable runtime/runner, STRICTLY refuse GGUF-only / wan / hunyuan / unclassifiable repos (so a bad add can't wedge the picker), build the `media-models.json` entry (`source:'user'`), + a `searchHuggingfaceModels` Hub-search helper. Pure. |
| `localLlmCatalog.js` | Curated cross-backend (Ollama↔LM Studio) local-LLM catalog + install-id mapping for the migrate flow. Pure. |
| `localLlmDisk.js` | Pure on-disk reasoning for the migrate "copy GGUF locally instead of re-downloading" fast-path (Ollama manifest/blob parsing, LM Studio path layout, MLX/projector/shard detection) plus the Hugging Face registry addressing used to finish an abandoned Ollama pull. |
+| `specDecodePresets.js` | Curated llama-server speculative-decoding presets (target + drafter GGUF paths, `--spec-type`, and the Hugging Face repo/quant each file comes from) plus `findSpecDecodePreset` / `specDecodeSource` / `hfSearchUrl`. Server-owned so the launcher card can offer a Download button per file. Pure. |
| `ollamaContext.js` | Ollama runtime context-window reasoning. `resolveOllamaContextLength(provider, env)` → the window PortOS should hold the daemon at (`provider.numCtx`, then `OLLAMA_CONTEXT_LENGTH`, then `null` = leave Ollama's VRAM-based auto-pick alone); `withOllamaContextEnv(env, n)` builds the `ollama serve` child env; `parseOllamaContextOverflow(text)` recognizes the `exceed_context_size_error` rejection and pulls `{ promptTokens, contextLength }` out of either the JSON body or the human message; `describeOllamaContextOverflow` / `describeOllamaContextTooSmall` render the actionable one-liners; `isSameOllamaDaemon(providerBase, managedBase)` compares host+port so a provider pointed at a *remote* Ollama never triggers a local-daemon reload; `OLLAMA_AGENT_MIN_CONTEXT` is the window below which an agent harness is warned. Pure — the daemon side lives in `services/ollamaManager.js` (`ensureContextWindow`), the pre-spawn enforcement in `services/ollamaAgentContext.js`. |
| `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models, { measured })` ranks installed models for editorial review/editing, dropping any a fresh measurement proved cannot run here. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. |
| `localModelAssessment.js` | Scoring for MEASURED local-model assessments (recorded by `services/localModelAssessments.js`): `classifyFitVerdict` (`fits`/`does-not-fit`/`incompatible`/`unknown`), `summarizePerformance` (mean/peak chars-per-second, TTFT, max working context, cross-context degradation), `scoreAssessment` + `scoreForIntent` + `rankByIntent` for the balanced/smartest/fastest/lightweight pickers, `explainAssessment`, `compareEnvironments`/`describeStaleness` (is a stored reading still valid for THIS machine?), and `measuredFitVerdict`/`reconcileFit` (fold a measurement into the catalog's size-estimate fit badge, keeping the disagreement). Pure. `null` strictly means NOT MEASURED — never 0, never "failed". |
diff --git a/server/lib/index.js b/server/lib/index.js
index 673dfa7e2b..036de806e7 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -275,6 +275,7 @@ export * from './huggingfaceLora.js';
export * from './huggingfaceModel.js';
export * from './localLlmCatalog.js';
export * from './localLlmDisk.js';
+export * from './specDecodePresets.js';
export * from './localModelHeuristics.js';
export * from './localModelAssessment.js';
export * from './ollamaContext.js';
diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.js
index 7dafdd733e..9c272a83b5 100644
--- a/server/lib/mediaValidation.js
+++ b/server/lib/mediaValidation.js
@@ -168,6 +168,13 @@ export const localLlmLlamaServerStartSchema = z.object({
nGpuLayers: z.coerce.number().int().min(0).max(999).optional().default(99),
alias: z.string().trim().max(100).optional().default('dflash'),
});
+// Speculative-decoding weight download: which curated preset, and which half of
+// the pair. Both are enum-ish server-owned ids — no path or repo ever arrives
+// from the client, so a request can only ever write to a curated `models/` file.
+export const localLlmSpecModelDownloadSchema = z.object({
+ presetId: z.string().trim().min(1).max(100),
+ role: z.enum(['model', 'draftModel']),
+});
export const localLlmHuggingFaceSearchSchema = z.object({
backend: localLlmBackendSchema,
q: z.string().max(160).optional().default(''),
diff --git a/server/lib/specDecodePresets.js b/server/lib/specDecodePresets.js
new file mode 100644
index 0000000000..ed53ad7a49
--- /dev/null
+++ b/server/lib/specDecodePresets.js
@@ -0,0 +1,114 @@
+/**
+ * Speculative-decoding launcher presets (llama-server target + drafter pairs).
+ *
+ * Server-owned because the paths are only half the story: each preset also
+ * carries the Hugging Face repo the GGUF comes from, so PortOS can report
+ * "downloaded / not downloaded" per file and fetch the missing ones itself.
+ * The client renders this list — it holds no copy of its own, so a preset can
+ * never name a path the downloader has no source for.
+ *
+ * `quant` is a HINT, not a filename: repos rename their builds
+ * (`…-Q4_K_M.gguf`, `…-instruct-q4_k_m.gguf`, `….Q4_K_M.gguf`) and a hard-coded
+ * filename rots the moment one of them re-uploads. `file`, when present, wins.
+ *
+ * A file with no published single-file GGUF (the DSpark 8B block ships as a
+ * tokenizer-less checkpoint that has to be converted against its target) simply
+ * carries no `repo` — the UI then links out to a Hugging Face search instead of
+ * offering a Download button that cannot work. Pairs are the ones documented in
+ * docs/features/dflash2.md; see also docs/research/2026-08-19-dspark-vs-dflash2.md.
+ */
+
+// llama.cpp exposes one `--spec-type` per drafter family. `draft-dspark` merged
+// upstream on 2026-07-28 (ggml-org/llama.cpp#25173) and works on a stock
+// `brew install llama.cpp`; `draft-dflash` covers DFlash v1, while the DFlash 2
+// modules are still an open PR (#27342) and need a from-source build. Hence the
+// DSpark presets lead.
+export const SPEC_DECODE_PRESETS = Object.freeze([
+ {
+ id: 'qwen3.8-27b-dspark',
+ label: 'Qwen 3.8 27B + DSpark Drafter (Recommended — stock llama.cpp)',
+ specType: 'draft-dspark',
+ model: {
+ path: 'models/Qwen3.8-27B-Instruct-Q4_K_M.gguf',
+ repo: 'Qwen/Qwen3.8-27B-Instruct-GGUF',
+ quant: 'Q4_K_M',
+ },
+ draftModel: {
+ path: 'models/Qwen3.8-27B-DSpark-bf16.gguf',
+ repo: 'magnitudedev/Qwen3.8-27B-DSpark-GGUF',
+ quant: 'BF16',
+ },
+ },
+ {
+ id: 'qwen3-8b-dspark',
+ label: 'Qwen 3 8B + DSpark Drafter (small target)',
+ specType: 'draft-dspark',
+ model: {
+ path: 'models/Qwen3-8B-Instruct-Q4_K_M.gguf',
+ repo: 'Qwen/Qwen3-8B-Instruct-GGUF',
+ quant: 'Q4_K_M',
+ },
+ draftModel: {
+ path: 'models/dspark_qwen3_8b_block7-bf16.gguf',
+ },
+ },
+ {
+ id: 'qwen3.8-27b',
+ label: 'Qwen 3.8 27B + DFlash 2 Drafter (needs llama.cpp PR #27342 build)',
+ specType: 'draft-dflash',
+ model: {
+ path: 'models/Qwen3.8-27B-Instruct-Q4_K_M.gguf',
+ repo: 'Qwen/Qwen3.8-27B-Instruct-GGUF',
+ quant: 'Q4_K_M',
+ },
+ draftModel: {
+ path: 'models/Qwen3.8-27B-DFlash2-Q4_K_M.gguf',
+ repo: 'incoai/Qwen3.8-27B-DFlash2-GGUF',
+ quant: 'Q4_K_M',
+ },
+ },
+ {
+ id: 'muse-glimmer-30b',
+ label: 'Muse-Glimmer 30B + DFlash 2 Drafter (needs llama.cpp PR #27342 build)',
+ specType: 'draft-dflash',
+ model: {
+ path: 'models/Muse-Glimmer-30B-Instruct-Q4_K_M.gguf',
+ repo: 'meta-models/Muse-Glimmer-30B-GGUF',
+ quant: 'Q4_K_M',
+ },
+ draftModel: {
+ path: 'models/Muse-Glimmer-30B-DFlash2-Q4_K_M.gguf',
+ repo: 'z-lab/Muse-Glimmer-30B-DFlash2-GGUF',
+ quant: 'Q4_K_M',
+ },
+ },
+ {
+ id: 'custom',
+ label: 'Custom GGUF / Manual Paths',
+ specType: 'draft-dspark',
+ model: { path: '' },
+ draftModel: { path: '' },
+ },
+]);
+
+// The preset the launcher mounts on, and the roles a download request may name.
+export const DEFAULT_SPEC_PRESET_ID = 'qwen3.8-27b-dspark';
+export const SPEC_MODEL_ROLES = Object.freeze(['model', 'draftModel']);
+
+export const findSpecDecodePreset = (id) =>
+ SPEC_DECODE_PRESETS.find((preset) => preset.id === id) || null;
+
+/**
+ * The download source for one preset role, or null when the preset has no
+ * published GGUF for it (`custom`, or a drafter that ships safetensors only).
+ */
+export const specDecodeSource = (presetId, role) => {
+ const entry = findSpecDecodePreset(presetId)?.[role];
+ return entry?.repo && entry?.path ? entry : null;
+};
+
+// Where to send a user whose preset has no automatic source. Searching by the
+// filename (minus its extension) is what actually finds these — the drafter
+// repos are named after the file, not the target model.
+export const hfSearchUrl = (path) =>
+ `https://huggingface.co/models?search=${encodeURIComponent(String(path).split('/').pop().replace(/\.gguf$/i, ''))}`;
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index 1fe3440fc9..4fc0946a21 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -26,9 +26,11 @@ import {
localLlmAssessmentRunSchema,
localLlmAssessmentIntentSchema,
localLlmAssessmentDeleteSchema,
- localLlmLlamaServerStartSchema
+ localLlmLlamaServerStartSchema,
+ localLlmSpecModelDownloadSchema
} from '../lib/validation.js'
import { getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaServer } from '../services/llamaServerManager.js'
+import { getSpecDecodePresetStatus, downloadSpecDecodeModel } from '../services/specDecodeModels.js'
import { resetProviderReadinessCache } from '../services/providerReadiness.js'
import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'
import { isAppleSilicon } from '../lib/platform.js'
@@ -464,9 +466,29 @@ router.post('/assessments/delete', asyncHandler(async (req, res) => {
}))
// === llama-server (DFlash 2 / Speculative Decoding) ==========================
-// GET /api/local-llm/llama-server/status — binary availability, process state, logs
+// GET /api/local-llm/llama-server/status — binary availability, process state,
+// logs, and the curated target/drafter presets with each GGUF's on-disk state.
+// The presets ride along on the status call the launcher already makes so the
+// card can render "not downloaded + Download" instead of making the user press
+// Start to discover a missing file. Disk-only: no Hugging Face call here.
router.get('/llama-server/status', asyncHandler(async (_req, res) => {
- res.json(await getLlamaServerStatus())
+ const [status, presets] = await Promise.all([getLlamaServerStatus(), getSpecDecodePresetStatus()])
+ res.json({ ...status, presets })
+}))
+
+// POST /api/local-llm/llama-server/download-model — fetch one preset's GGUF from
+// Hugging Face into the exact path the launcher will pass llama.cpp. Byte
+// progress streams over `llamaServer:download`; the card renders it as a bar on
+// the row that started it.
+router.post('/llama-server/download-model', asyncHandler(async (req, res) => {
+ const { presetId, role } = validateRequest(localLlmSpecModelDownloadSchema, req.body)
+ const io = req.app.get('io')
+ const result = await downloadSpecDecodeModel({
+ presetId,
+ role,
+ onProgress: (frame) => io?.emit('llamaServer:download', frame),
+ })
+ res.json(result)
}))
// Each of the three actions below changes exactly what the provider-readiness
diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.js
index 24b68fe41b..16f5be7dfe 100644
--- a/server/routes/localLlm.test.js
+++ b/server/routes/localLlm.test.js
@@ -77,6 +77,13 @@ vi.mock('../services/llamaServerManager.js', () => ({
installLlamaServer: vi.fn(async () => ({ success: true, message: 'installed' })),
}));
+// The launcher's curated presets (and their weights' on-disk state) ride along
+// on the status response so the card can offer a Download button per GGUF.
+vi.mock('../services/specDecodeModels.js', () => ({
+ getSpecDecodePresetStatus: vi.fn(async () => ([{ id: 'test-preset', label: 'Test', specType: 'draft-dspark', model: null, draftModel: null }])),
+ downloadSpecDecodeModel: vi.fn(async () => ({ success: true, path: 'models/base.gguf', file: 'base.gguf' })),
+}));
+
// /loaded reads getSettings() to honor a user's intentionally-disabled backends,
// so mock it (defaults to no backends disabled; the disabled-case test flips it).
vi.mock('../services/settings.js', () => ({
@@ -473,10 +480,33 @@ describe('measured assessments wiring', () => {
});
describe('llama-server routes', () => {
- it('GET /api/local-llm/llama-server/status returns status', async () => {
+ it('GET /api/local-llm/llama-server/status returns status with the weight presets', async () => {
const res = await request(makeApp()).get('/api/local-llm/llama-server/status');
expect(res.status).toBe(200);
- expect(res.body).toEqual({ installed: true, running: false });
+ expect(res.body).toEqual({
+ installed: true,
+ running: false,
+ presets: [{ id: 'test-preset', label: 'Test', specType: 'draft-dspark', model: null, draftModel: null }],
+ });
+ });
+
+ it('POST /api/local-llm/llama-server/download-model fetches one preset GGUF', async () => {
+ const { downloadSpecDecodeModel } = await import('../services/specDecodeModels.js');
+ const res = await request(makeApp())
+ .post('/api/local-llm/llama-server/download-model')
+ .send({ presetId: 'test-preset', role: 'model' });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ success: true, path: 'models/base.gguf' });
+ expect(downloadSpecDecodeModel).toHaveBeenCalledWith(expect.objectContaining({ presetId: 'test-preset', role: 'model' }));
+ });
+
+ it('POST /api/local-llm/llama-server/download-model rejects an unknown role', async () => {
+ const res = await request(makeApp())
+ .post('/api/local-llm/llama-server/download-model')
+ .send({ presetId: 'test-preset', role: 'sneaky' });
+
+ expect(res.status).toBe(400);
});
it('POST /api/local-llm/llama-server/start launches server with valid payload', async () => {
diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.js
index 2d67b742fa..39fdea5a93 100644
--- a/server/services/llamaServerManager.js
+++ b/server/services/llamaServerManager.js
@@ -6,12 +6,12 @@
*/
import { stat } from 'fs/promises';
-import { resolve } from 'path';
import { spawn } from '../lib/childProcess.js';
import { commandExists } from '../lib/commandExists.js';
import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';
import { killProcessTree } from '../lib/bufferedSpawn.js';
import { expandHome, sleep } from '../lib/fileUtils.js';
+import { resolveSpecModelPath } from './specDecodeModels.js';
import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';
import { ServerError } from '../lib/errorHandler.js';
@@ -74,16 +74,16 @@ function resolveLlamaServerBinary() {
* reports "started (PID …)" from a process that is already gone; the real cause
* is one line deep in the server log.
*
- * Relative paths resolve against the server's cwd, which is the cwd the child
- * inherits, and `~` is expanded here AND in the argv below — `spawn` does no
- * shell expansion, so a tilde path must be expanded once for both or the check
- * and the launch disagree about which file they mean.
+ * Path resolution goes through `resolveSpecModelPath` — the same helper the
+ * downloader writes through — so the check and the download can never disagree
+ * about which file a relative or `~`-prefixed path means. (`spawn` does no shell
+ * expansion, hence the matching `expandHome` on the argv below.)
*/
async function assertModelFileExists(label, modelPath) {
- const stats = await stat(resolve(expandHome(modelPath))).catch(() => null);
+ const stats = await stat(resolveSpecModelPath(modelPath)).catch(() => null);
if (stats?.isFile()) return;
throw new ServerError(
- `${label} was not found at \`${modelPath}\`. Download the GGUF first — the Local LLM tab lists the base/drafter pairs — or point this field at a file you already have.`,
+ `${label} was not found at \`${modelPath}\`. Use the Download button next to this preset in the Speculative Decoding card to fetch it, or point this field at a file you already have.`,
{ status: 400, code: 'LLAMA_MODEL_FILE_MISSING' }
);
}
diff --git a/server/services/specDecodeModels.js b/server/services/specDecodeModels.js
new file mode 100644
index 0000000000..8ea38a076d
--- /dev/null
+++ b/server/services/specDecodeModels.js
@@ -0,0 +1,231 @@
+/**
+ * Speculative-decoding weights: on-disk state + one-click Hugging Face download.
+ *
+ * The llama-server launcher names GGUF files it cannot produce — the weights are
+ * a separate multi-gigabyte download — so before this module the only way to
+ * learn a preset's file was missing was to press Start and read the 400. This
+ * reports per-preset "downloaded / not downloaded" from disk and fetches the
+ * missing file straight into the path the launcher will hand llama.cpp.
+ *
+ * Path resolution is shared with llamaServerManager (`resolveSpecModelPath`) so
+ * the download target and the launcher's existence check can never disagree
+ * about which file a relative or `~`-prefixed path means.
+ */
+
+import { createWriteStream } from 'fs';
+import { rename, rm, stat } from 'fs/promises';
+import { dirname, resolve } from 'path';
+import { randomBytes } from 'crypto';
+import { Readable, Transform } from 'stream';
+import { pipeline } from 'stream/promises';
+import { ensureDir, expandHome } from '../lib/fileUtils.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { buildHfAuthHeaders, buildHfResolveUrl, fetchHuggingfaceModel, modelSiblingFilenames } from '../lib/huggingfaceLora.js';
+import { getHfToken } from '../lib/hfToken.js';
+import {
+ SPEC_DECODE_PRESETS,
+ SPEC_MODEL_ROLES,
+ findSpecDecodePreset,
+ hfSearchUrl,
+ specDecodeSource,
+} from '../lib/specDecodePresets.js';
+
+// Progress frames are throttled to this interval so a fast link can't flood the
+// socket with a frame per chunk.
+const PROGRESS_INTERVAL_MS = 250;
+
+// Downloads in flight, keyed by RESOLVED destination path (two presets can name
+// the same base model, and both must show the one transfer rather than starting
+// a second copy of it).
+const inFlight = new Map();
+
+/**
+ * Absolute path a launcher field refers to. Relative paths resolve against the
+ * server's cwd — the cwd llama-server inherits — and `~` is expanded here
+ * because `spawn` performs no shell expansion.
+ */
+export const resolveSpecModelPath = (path) => resolve(expandHome(String(path || '').trim()));
+
+const fileStat = async (path) => {
+ const stats = await stat(resolveSpecModelPath(path)).catch(() => null);
+ return stats?.isFile() ? stats : null;
+};
+
+/** State of one preset role (base or drafter) for the UI. */
+const describeEntry = async (presetId, role) => {
+ const entry = findSpecDecodePreset(presetId)?.[role];
+ if (!entry?.path) return null;
+ const destPath = resolveSpecModelPath(entry.path);
+ const stats = await stat(destPath).catch(() => null);
+ const active = inFlight.get(destPath);
+ return {
+ role,
+ path: entry.path,
+ exists: Boolean(stats?.isFile()),
+ sizeBytes: stats?.isFile() ? stats.size : null,
+ repo: entry.repo || null,
+ repoUrl: entry.repo ? `https://huggingface.co/${entry.repo}` : hfSearchUrl(entry.path),
+ downloadable: Boolean(entry.repo),
+ downloading: Boolean(active),
+ received: active?.received ?? null,
+ total: active?.total ?? null,
+ };
+};
+
+/**
+ * Every preset with its weights' on-disk state. Disk + in-memory only — listing
+ * the launcher must never reach out to Hugging Face (or any provider) on its own.
+ */
+export async function getSpecDecodePresetStatus() {
+ return Promise.all(SPEC_DECODE_PRESETS.map(async (preset) => ({
+ id: preset.id,
+ label: preset.label,
+ specType: preset.specType,
+ model: await describeEntry(preset.id, 'model'),
+ draftModel: await describeEntry(preset.id, 'draftModel'),
+ })));
+}
+
+// A quant hint matches loosely: repos publish `…-Q4_K_M.gguf`, `….q4_k_m.gguf`
+// and `…-Q4_K_M-00001-of-00002.gguf` for the same build.
+const normalize = (text) => String(text).toLowerCase().replace(/[^a-z0-9]/g, '');
+const isShard = (filename) => /-\d{5}-of-\d{5}\.gguf$/i.test(filename);
+
+/**
+ * Choose which `.gguf` sibling of the repo to fetch.
+ *
+ * Sharded (multi-part) builds are refused rather than half-downloaded: llama.cpp
+ * wants every part, and a lone `-00001-of-00003.gguf` on disk would satisfy the
+ * launcher's existence check and then fail at load time — the exact confusion
+ * this whole module exists to remove.
+ */
+export function pickGgufSibling(model, { file, quant, repo }) {
+ const ggufs = modelSiblingFilenames(model).filter((name) => /\.gguf$/i.test(name));
+ if (!ggufs.length) {
+ throw new ServerError(`Hugging Face repo ${repo} publishes no .gguf file`, { status: 422, code: 'SPEC_NO_GGUF' });
+ }
+ if (file) {
+ const exact = ggufs.find((name) => name === file);
+ if (exact) return exact;
+ }
+ const whole = ggufs.filter((name) => !isShard(name));
+ const wanted = quant ? normalize(quant) : null;
+ const matches = wanted ? whole.filter((name) => normalize(name).includes(wanted)) : whole;
+ if (matches.length) {
+ // Shortest name wins among equals: `Qwen3.8-27B-Q4_K_M.gguf` over a
+ // `…-Q4_K_M-abliterated.gguf` variant that also carries the quant.
+ return [...matches].sort((a, b) => a.length - b.length)[0];
+ }
+ if (whole.length) {
+ throw new ServerError(
+ `Hugging Face repo ${repo} has no ${quant} build — available: ${whole.slice(0, 6).join(', ')}`,
+ { status: 422, code: 'SPEC_QUANT_MISSING' },
+ );
+ }
+ throw new ServerError(
+ `Hugging Face repo ${repo} publishes only sharded (multi-part) GGUFs, which PortOS can't assemble. Download it manually from https://huggingface.co/${repo}.`,
+ { status: 422, code: 'SPEC_SHARDED_GGUF' },
+ );
+}
+
+const streamToFile = async ({ url, headers, destPath, onBytes }) => {
+ const res = await fetch(url, { headers, redirect: 'follow' });
+ if (!res.ok || !res.body) {
+ if (res.status === 401 || res.status === 403) {
+ throw new ServerError(
+ `Hugging Face rejected the download (${res.status}) — this repo is gated. Accept its license on Hugging Face and add your HF token in Image Gen settings, then retry.`,
+ { status: res.status, code: 'HF_AUTH' },
+ );
+ }
+ throw new ServerError(`Hugging Face download failed: ${res.status} ${res.statusText}`, { status: 502, code: 'HF_DOWNLOAD_FAILED' });
+ }
+ const total = Number(res.headers?.get?.('content-length')) || 0;
+ // A random temp suffix keeps a crashed transfer's leftovers from being
+ // mistaken for this one's, and keeps the half-written file out of the
+ // launcher's existence check until it is complete.
+ const tmpPath = `${destPath}.${randomBytes(6).toString('hex')}.partial`;
+ await ensureDir(dirname(destPath));
+ let received = 0;
+ // Count bytes in a passthrough Transform, NOT a bare `.on('data')` listener —
+ // that flips the source into flowing mode and defeats pipeline backpressure.
+ const counter = new Transform({
+ transform(chunk, _enc, cb) {
+ received += chunk.length;
+ onBytes(received, total);
+ cb(null, chunk);
+ },
+ });
+ await pipeline(Readable.fromWeb(res.body), counter, createWriteStream(tmpPath)).catch(async (err) => {
+ await rm(tmpPath, { force: true }).catch(() => {});
+ throw err;
+ });
+ await rename(tmpPath, destPath);
+ return { bytes: received || total };
+};
+
+/**
+ * Download one preset role's GGUF into the path the launcher expects.
+ *
+ * @param {{ presetId: string, role: string, onProgress?: (frame: object) => void }} params
+ */
+export async function downloadSpecDecodeModel({ presetId, role, onProgress = () => {} }) {
+ if (!SPEC_MODEL_ROLES.includes(role)) {
+ throw new ServerError(`Unknown model role "${role}"`, { status: 400 });
+ }
+ const source = specDecodeSource(presetId, role);
+ if (!source) {
+ throw new ServerError(
+ `No Hugging Face source is registered for that preset's ${role === 'model' ? 'base model' : 'drafter'} — download it manually and point the field at the file.`,
+ { status: 400, code: 'SPEC_NO_SOURCE' },
+ );
+ }
+
+ const destPath = resolveSpecModelPath(source.path);
+ const existing = await fileStat(source.path);
+ if (existing) {
+ return { success: true, alreadyDownloaded: true, path: source.path, sizeBytes: existing.size };
+ }
+ 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 });
+
+ 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 { bytes } = await streamToFile({
+ url: buildHfResolveUrl(source.repo, 'main', file),
+ headers,
+ destPath,
+ onBytes: (received, total) => {
+ state.received = received;
+ state.total = total;
+ const now = Date.now();
+ if (now - lastEmit < PROGRESS_INTERVAL_MS) return;
+ lastEmit = now;
+ onProgress({ event: 'progress', presetId, role, path: source.path, received, total });
+ },
+ });
+ onProgress({ event: 'complete', presetId, role, path: source.path, received: bytes, total: bytes, message: `${source.path} downloaded` });
+ console.log(`✅ Speculative-decoding weights ready: ${source.path} (${bytes} bytes)`);
+ return { success: true, path: source.path, repo: source.repo, file, sizeBytes: bytes };
+ } catch (err) {
+ onProgress({ event: 'error', presetId, role, path: source.path, message: err.message });
+ console.error(`❌ Speculative-decoding download failed for ${source.path}: ${err.message}`);
+ throw err;
+ } finally {
+ inFlight.delete(destPath);
+ }
+}
+
+/** Clears in-flight download bookkeeping (used by test suites). */
+export function _resetSpecDecodeDownloadsForTests() {
+ inFlight.clear();
+}
diff --git a/server/services/specDecodeModels.test.js b/server/services/specDecodeModels.test.js
new file mode 100644
index 0000000000..d55c1cb13a
--- /dev/null
+++ b/server/services/specDecodeModels.test.js
@@ -0,0 +1,169 @@
+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 { Readable } from 'stream';
+import {
+ downloadSpecDecodeModel,
+ getSpecDecodePresetStatus,
+ pickGgufSibling,
+ resolveSpecModelPath,
+ _resetSpecDecodeDownloadsForTests,
+} from './specDecodeModels.js';
+import * as specDecodePresets from '../lib/specDecodePresets.js';
+import * as hfToken from '../lib/hfToken.js';
+import * as huggingfaceLora from '../lib/huggingfaceLora.js';
+
+const siblings = (...names) => ({ siblings: names.map((rfilename) => ({ rfilename })) });
+
+describe('pickGgufSibling', () => {
+ it('matches a quant hint across the naming styles repos actually publish', () => {
+ const model = siblings('README.md', 'Qwen3.8-27B-q4_k_m.gguf', 'Qwen3.8-27B-Q8_0.gguf');
+ expect(pickGgufSibling(model, { quant: 'Q4_K_M', repo: 'o/r' })).toBe('Qwen3.8-27B-q4_k_m.gguf');
+ });
+
+ it('prefers the plainest name when several builds carry the quant', () => {
+ const model = siblings('Qwen3.8-27B-Q4_K_M-abliterated.gguf', 'Qwen3.8-27B-Q4_K_M.gguf');
+ expect(pickGgufSibling(model, { quant: 'Q4_K_M', repo: 'o/r' })).toBe('Qwen3.8-27B-Q4_K_M.gguf');
+ });
+
+ it('honours an exact filename over the quant hint', () => {
+ const model = siblings('pinned.gguf', 'Qwen3.8-27B-Q4_K_M.gguf');
+ expect(pickGgufSibling(model, { file: 'pinned.gguf', quant: 'Q4_K_M', repo: 'o/r' })).toBe('pinned.gguf');
+ });
+
+ // A lone shard on disk would satisfy the launcher's existence check and then
+ // fail at load — the exact confusion this module exists to remove.
+ it('refuses a sharded-only repo instead of fetching part one', () => {
+ const model = siblings('Qwen3.8-27B-Q4_K_M-00001-of-00003.gguf', 'Qwen3.8-27B-Q4_K_M-00002-of-00003.gguf');
+ expect(() => pickGgufSibling(model, { quant: 'Q4_K_M', repo: 'o/r' })).toThrow(/sharded/i);
+ });
+
+ it('names the available builds when the requested quant is absent', () => {
+ const model = siblings('Qwen3.8-27B-Q8_0.gguf');
+ expect(() => pickGgufSibling(model, { quant: 'Q4_K_M', repo: 'o/r' })).toThrow(/Q8_0/);
+ });
+
+ it('rejects a repo with no GGUF at all', () => {
+ expect(() => pickGgufSibling(siblings('model.safetensors'), { quant: 'Q4_K_M', repo: 'o/r' })).toThrow(/no \.gguf/i);
+ });
+});
+
+describe('getSpecDecodePresetStatus', () => {
+ it('reports each preset file as on-disk or not, without reaching Hugging Face', async () => {
+ const fetchSpy = vi.spyOn(globalThis, 'fetch');
+ const presets = await getSpecDecodePresetStatus();
+
+ const recommended = presets.find((p) => p.id === 'qwen3.8-27b-dspark');
+ expect(recommended.model.path).toMatch(/\.gguf$/);
+ expect(recommended.model.exists).toBe(false);
+ expect(recommended.model.downloadable).toBe(true);
+ expect(recommended.model.repoUrl).toContain('huggingface.co');
+ // `custom` carries no paths, so it has no weights rows to render.
+ expect(presets.find((p) => p.id === 'custom').model).toBeNull();
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+});
+
+describe('downloadSpecDecodeModel', () => {
+ let dir;
+
+ beforeEach(async () => {
+ dir = await mkdtemp(join(tmpdir(), 'portos-spec-decode-'));
+ _resetSpecDecodeDownloadsForTests();
+ vi.spyOn(hfToken, 'getHfToken').mockResolvedValue(null);
+ });
+
+ afterEach(async () => {
+ _resetSpecDecodeDownloadsForTests();
+ vi.restoreAllMocks();
+ await rm(dir, { recursive: true, force: true });
+ });
+
+ const stubPreset = (overrides = {}) => {
+ const preset = {
+ id: 'test-preset',
+ label: 'Test',
+ specType: 'draft-dspark',
+ model: { path: join(dir, 'base.gguf'), repo: 'acme/Example-GGUF', quant: 'Q4_K_M' },
+ draftModel: { path: join(dir, 'draft.gguf') },
+ ...overrides,
+ };
+ vi.spyOn(specDecodePresets, 'specDecodeSource').mockImplementation((id, role) => {
+ if (id !== preset.id) return null;
+ const entry = preset[role];
+ return entry?.repo && entry?.path ? entry : null;
+ });
+ return preset;
+ };
+
+ it('streams the resolved GGUF into the launcher path', async () => {
+ stubPreset();
+ vi.spyOn(huggingfaceLora, 'fetchHuggingfaceModel').mockResolvedValue(siblings('Example-Q4_K_M.gguf'));
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: true,
+ status: 200,
+ headers: { get: () => '6' },
+ body: Readable.toWeb(Readable.from([Buffer.from('gg'), Buffer.from('ufgg')])),
+ });
+ const frames = [];
+
+ const result = await downloadSpecDecodeModel({
+ presetId: 'test-preset',
+ role: 'model',
+ onProgress: (frame) => frames.push(frame),
+ });
+
+ expect(result.file).toBe('Example-Q4_K_M.gguf');
+ expect(await readFile(join(dir, 'base.gguf'), 'utf8')).toBe('ggufgg');
+ expect(frames.at(-1)).toMatchObject({ event: 'complete', role: 'model' });
+ });
+
+ it('leaves no .partial behind when the transfer fails mid-stream', async () => {
+ stubPreset();
+ vi.spyOn(huggingfaceLora, 'fetchHuggingfaceModel').mockResolvedValue(siblings('Example-Q4_K_M.gguf'));
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: true,
+ status: 200,
+ headers: { get: () => '99' },
+ body: Readable.toWeb(new Readable({
+ read() { this.destroy(new Error('connection reset')); },
+ })),
+ });
+
+ await expect(downloadSpecDecodeModel({ presetId: 'test-preset', role: 'model' }))
+ .rejects.toThrow(/connection reset/);
+ const { readdir } = await import('fs/promises');
+ expect(await readdir(dir)).toEqual([]);
+ });
+
+ it('short-circuits when the weights are already on disk', async () => {
+ stubPreset();
+ await writeFile(join(dir, 'base.gguf'), 'already here');
+ const fetchSpy = vi.spyOn(globalThis, 'fetch');
+
+ const result = await downloadSpecDecodeModel({ presetId: 'test-preset', role: 'model' });
+
+ expect(result).toMatchObject({ success: true, alreadyDownloaded: true });
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ // The drafter half of some pairs ships safetensors only — the UI links out
+ // rather than offering a button, and the route has to agree.
+ it('refuses a role with no registered Hugging Face source', async () => {
+ stubPreset();
+ await expect(downloadSpecDecodeModel({ presetId: 'test-preset', role: 'draftModel' }))
+ .rejects.toThrow(/No Hugging Face source/);
+ });
+
+ it('rejects an unknown role outright', async () => {
+ await expect(downloadSpecDecodeModel({ presetId: 'test-preset', role: 'sneaky' }))
+ .rejects.toThrow(/Unknown model role/);
+ });
+});
+
+describe('resolveSpecModelPath', () => {
+ it('resolves a relative launcher path to an absolute one', () => {
+ expect(resolveSpecModelPath('models/base.gguf')).toBe(join(process.cwd(), 'models/base.gguf'));
+ });
+});