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
feat: add OpenCode llama TUI provider and surface DFlash2 speculative decoding (#4570)
[._.]/ Adam Eivy0cd820fc3c49
diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsxindex 3c570ec68f..a669b767e2 100644--- a/client/src/components/cos/TaskAddForm.jsx+++ b/client/src/components/cos/TaskAddForm.jsx@@ -748,7 +748,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa)}{apiOnlyProviders && (<div className="px-3 py-2 bg-port-warning/10 border border-port-warning/40 rounded-lg text-xs text-port-warning">- Your enabled providers are HTTP API providers with no file-writing harness, so they can't run agent tasks. Enable <span className="font-semibold">Claude Ollama</span> for Ollama, or <span className="font-semibold">OpenCode MTPLX</span> for a separately running MTPLX server, on the AI Providers page to run file-writing tasks on a local model.+ Your enabled providers are HTTP API providers with no file-writing harness, so they can't run agent tasks. Enable <span className="font-semibold">Claude Ollama</span> for Ollama, <span className="font-semibold">OpenCode llama TUI</span> for llama.cpp / DFlash, or <span className="font-semibold">OpenCode MTPLX</span> for a separately running MTPLX server, on the AI Providers page to run file-writing tasks on a local model.</div>)}{/* Screenshot and Attachment Upload */}diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex 18f6a338ed..9197b7a6f7 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -1,6 +1,6 @@import { useState, useEffect, useRef, useCallback, useMemo } from 'react';import { Link, useNavigate } from 'react-router';-import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy, Play, Square, Power, PowerOff, Eye, Wrench, Brain, Code2, MessageSquare, Boxes, AlertTriangle, FlaskConical, Music, ArrowUpCircle } from 'lucide-react';+import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy, Play, Square, Power, PowerOff, Eye, Wrench, Brain, Code2, MessageSquare, Boxes, AlertTriangle, FlaskConical, Music, ArrowUpCircle, Zap, ChevronDown, ChevronUp, Terminal } from 'lucide-react';import toast from '../ui/Toast';import ConfirmButtonPair from '../ui/ConfirmButtonPair';import BrailleSpinner from '../BrailleSpinner';@@ -10,7 +10,7 @@ import { useConfirmDelete } from '../../hooks/useConfirmDelete';import {getLocalLlmStatus, getLocalLlmCatalog, getLocalLlmHuggingFaceSearch, installLocalLlmModel,deleteLocalLlmModel, switchLocalLlmBackend, migrateLocalLlmBackend, installLocalLlmBackend, upgradeLocalLlmBackend, controlOllamaService,- installAudioModel, patchSettingsSlice+ installAudioModel, patchSettingsSlice, getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaServer} from '../../services/api';import socket from '../../services/socket';import MemoryManagement from './MemoryManagement.jsx';@@ -22,6 +22,30 @@ const BACKENDS = [];const labelFor = (id) => BACKENDS.find((b) => b.id === id)?.label || id;+const DFLASH_PRESETS = [+ {+ id: 'qwen3.8-27b',+ label: 'Qwen 3.8 27B + DFlash 2 Drafter (Recommended)',+ 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',+ 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-dflash',+ },+];+const btnClass = 'flex items-center gap-1.5 px-2 py-1 text-xs font-medium rounded transition-colors disabled:opacity-50';const CATEGORY_LABELS = {@@ -382,9 +406,33 @@ export function LocalLlmTab() {const catalogRequestId = useRef(0);const selectedInitialized = useRef(false);+ const [llamaStatus, setLlamaStatus] = useState(null);+ const [llamaLoading, setLlamaLoading] = useState(false);+ const [llamaForm, setLlamaForm] = useState({+ model: '',+ draftModel: '',+ specType: 'draft-dflash',+ port: 8080,+ host: '127.0.0.1',+ ctxSize: 32768,+ nGpuLayers: 99,+ alias: 'dflash',+ });+ const [showLlamaAdvanced, setShowLlamaAdvanced] = useState(false);+ const [showLlamaLogs, setShowLlamaLogs] = useState(false);++ const loadLlamaStatus = useCallback(() => {+ return getLlamaServerStatus({ silent: true })+ .then((res) => {+ if (res) setLlamaStatus(res);+ })+ .catch(() => {});+ }, []);+const loadStatus = useCallback(() => {const requestId = ++statusRequestId.current;setLoading(true);+ loadLlamaStatus();return getLocalLlmStatus({ silent: true }).then((s) => {if (requestId !== statusRequestId.current) return;@@ -401,7 +449,7 @@ export function LocalLlmTab() {.finally(() => {if (requestId === statusRequestId.current) setLoading(false);});- }, []);+ }, [loadLlamaStatus]);// `source` and `category` are required rather than defaulted from state: a// state default would put them in the dep list, so `loadCatalog`'s identity@@ -667,6 +715,74 @@ export function LocalLlmTab() {});};+ const handleStartLlama = async (e) => {+ e?.preventDefault?.();+ if (!llamaForm.model?.trim()) {+ toast.error('Please specify a base model path (e.g. models/Qwen3.8-27B-Instruct-Q4_K_M.gguf)');+ return;+ }+ setLlamaLoading(true);+ try {+ const res = await startLlamaServer(llamaForm);+ if (res?.success) {+ toast.success(`llama-server started (PID ${res.pid}) on port ${llamaForm.port || 8080}`);+ }+ loadLlamaStatus();+ } catch (err) {+ toast.error(err?.message || 'Failed to start llama-server');+ loadLlamaStatus();+ } finally {+ setLlamaLoading(false);+ }+ };++ const handleStopLlama = async () => {+ setLlamaLoading(true);+ try {+ const res = await stopLlamaServer();+ if (res?.success) {+ toast.success(res.message || 'llama-server stopped');+ } else {+ toast.error(res?.message || 'Could not stop server');+ }+ loadLlamaStatus();+ } catch (err) {+ toast.error(err?.message || 'Failed to stop llama-server');+ loadLlamaStatus();+ } finally {+ setLlamaLoading(false);+ }+ };++ const handleInstallLlama = async () => {+ setLlamaLoading(true);+ try {+ const res = await installLlamaServer();+ if (res?.success) {+ toast.success(res.message || 'llama.cpp installed successfully');+ }+ loadLlamaStatus();+ } catch (err) {+ toast.error(err?.message || 'Failed to install llama.cpp');+ loadLlamaStatus();+ } finally {+ setLlamaLoading(false);+ }+ };++ const handlePresetSelect = (presetId) => {+ const preset = DFLASH_PRESETS.find((p) => p.id === presetId);+ if (!preset) return;+ if (preset.id !== 'custom') {+ setLlamaForm((prev) => ({+ ...prev,+ model: preset.model,+ draftModel: preset.draftModel,+ specType: preset.specType,+ }));+ }+ };+return (<div className="space-y-4"><MemoryManagement />@@ -775,6 +891,241 @@ export function LocalLlmTab() {)}</div>+ {/* Speculative Decoding & Custom Runtimes (DFlash 2 / llama.cpp) */}+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-4">+ <div className="flex items-center justify-between flex-wrap gap-2">+ <div className="flex items-center gap-2">+ <Zap size={16} className="text-port-accent" />+ <h2 className="text-sm font-medium text-gray-300">Speculative Decoding & Custom Runtimes (DFlash 2 / llama.cpp)</h2>+ {llamaStatus?.running && llamaStatus?.managed && (+ <span className="px-2 py-0.5 text-xs rounded bg-port-success/20 text-port-success flex items-center gap-1.5">+ <span className="w-2 h-2 rounded-full bg-port-success animate-pulse" />+ Running (PID {llamaStatus.pid})+ </span>+ )}+ {llamaStatus?.running && !llamaStatus?.managed && (+ <span className="px-2 py-0.5 text-xs rounded bg-blue-500/20 text-blue-300 flex items-center gap-1.5">+ <span className="w-2 h-2 rounded-full bg-blue-400" />+ Active on {llamaStatus.endpoint} (External)+ </span>+ )}+ {!llamaStatus?.running && llamaStatus?.installed && (+ <span className="px-2 py-0.5 text-xs rounded bg-gray-500/20 text-gray-400">+ Stopped+ </span>+ )}+ {!llamaStatus?.installed && (+ <span className="px-2 py-0.5 text-xs rounded bg-port-warning/20 text-port-warning" title="Install via Homebrew: brew install llama.cpp or compile with DFlash2 support">+ llama-server not found on PATH+ </span>+ )}+ </div>+ <div className="flex items-center gap-3">+ <button+ onClick={loadLlamaStatus}+ disabled={llamaLoading}+ className="p-1 text-gray-400 hover:text-white transition-colors"+ title="Refresh llama-server status"+ aria-label="Refresh llama-server status"+ >+ <RefreshCw size={13} className={llamaLoading ? 'animate-spin' : ''} />+ </button>+ <Link+ to="/ai"+ className="text-xs text-port-accent hover:underline flex items-center gap-1"+ >+ OpenCode llama TUI in AI Providers <ExternalLink size={11} />+ </Link>+ </div>+ </div>++ <p className="text-xs text-gray-400 leading-relaxed">+ DFlash 2 enables multi-token speculative drafting (yielding 2.5–3× speedups on local models like Qwen 2.5 / Qwen 3.8 and Muse-Glimmer). You can launch and manage a local <code className="text-gray-300">llama-server</code> with DFlash 2 speculative drafting directly from PortOS and connect using the <strong className="text-white">OpenCode llama TUI</strong> provider.+ </p>++ {llamaStatus?.running ? (+ <div className="bg-port-bg border border-port-success/30 rounded-lg p-3 space-y-3">+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">+ <div className="text-xs text-gray-300 space-y-1">+ <p><span className="text-gray-500">Endpoint:</span> <code className="text-port-success">{llamaStatus.endpoint}</code></p>+ {llamaStatus.config?.model && (+ <p><span className="text-gray-500">Base Model:</span> <code className="text-gray-300">{llamaStatus.config.model}</code></p>+ )}+ {llamaStatus.config?.draftModel && (+ <p><span className="text-gray-500">DFlash Drafter:</span> <code className="text-port-accent">{llamaStatus.config.draftModel}</code> ({llamaStatus.config.specType || 'draft-dflash'})</p>+ )}+ </div>+ {llamaStatus.managed ? (+ <button+ onClick={handleStopLlama}+ disabled={llamaLoading}+ className="flex items-center gap-1.5 px-3 py-1.5 bg-port-error/20 hover:bg-port-error/30 text-port-error text-xs font-medium rounded-lg transition-colors disabled:opacity-50 shrink-0"+ >+ {llamaLoading ? <BrailleSpinner /> : <PowerOff size={13} />}+ Stop Server+ </button>+ ) : (+ <span className="text-xs text-gray-500 italic">+ Running as external process+ </span>+ )}+ </div>+ </div>+ ) : llamaStatus?.installed ? (+ <form onSubmit={handleStartLlama} className="bg-port-bg border border-port-border/70 rounded-lg p-3 space-y-3">+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">+ <span className="text-xs font-medium text-gray-300">Launch Speculative Decoding Server</span>+ <div className="flex items-center gap-1.5">+ <label htmlFor="llama-preset-select" className="text-[11px] text-gray-500">Preset:</label>+ <select+ id="llama-preset-select"+ aria-label="Preset"+ onChange={(e) => handlePresetSelect(e.target.value)}+ defaultValue="qwen3.8-27b"+ className="bg-port-card border border-port-border rounded px-2 py-1 text-xs text-port-accent focus:outline-none"+ >+ {DFLASH_PRESETS.map((p) => (+ <option key={p.id} value={p.id}>+ {p.label}+ </option>+ ))}+ </select>+ </div>+ </div>++ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">+ <div>+ <label htmlFor="llama-base-model" className="text-[11px] text-gray-400 block mb-1">Target Base Model (GGUF Path) *</label>+ <input+ id="llama-base-model"+ aria-label="Target Base Model (GGUF Path)"+ type="text"+ value={llamaForm.model}+ onChange={(e) => setLlamaForm((prev) => ({ ...prev, model: e.target.value }))}+ placeholder="models/Qwen3.8-27B-Instruct-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>+ <div>+ <label htmlFor="llama-draft-model" className="text-[11px] text-gray-400 block mb-1">DFlash 2 Draft Model (Optional)</label>+ <input+ id="llama-draft-model"+ aria-label="DFlash 2 Draft Model (Optional)"+ type="text"+ value={llamaForm.draftModel}+ onChange={(e) => setLlamaForm((prev) => ({ ...prev, draftModel: e.target.value }))}+ placeholder="models/Qwen3.8-27B-DFlash2-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>+ </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>+ <label htmlFor="llama-port" className="text-[11px] text-gray-400 block mb-1">Port</label>+ <input+ id="llama-port"+ aria-label="Port"+ type="number"+ value={llamaForm.port}+ onChange={(e) => setLlamaForm((prev) => ({ ...prev, port: parseInt(e.target.value, 10) || 8080 }))}+ className="w-full bg-port-card border border-port-border rounded px-2 py-1 text-xs text-white"+ />+ </div>+ <div>+ <label htmlFor="llama-ctx-size" className="text-[11px] text-gray-400 block mb-1">Context Size</label>+ <input+ id="llama-ctx-size"+ aria-label="Context Size"+ type="number"+ value={llamaForm.ctxSize}+ onChange={(e) => setLlamaForm((prev) => ({ ...prev, ctxSize: parseInt(e.target.value, 10) || 32768 }))}+ className="w-full bg-port-card border border-port-border rounded px-2 py-1 text-xs text-white"+ />+ </div>+ <div>+ <label htmlFor="llama-gpu-layers" className="text-[11px] text-gray-400 block mb-1">GPU Layers (-ngl)</label>+ <input+ id="llama-gpu-layers"+ aria-label="GPU Layers (-ngl)"+ type="number"+ value={llamaForm.nGpuLayers}+ onChange={(e) => setLlamaForm((prev) => ({ ...prev, nGpuLayers: parseInt(e.target.value, 10) ?? 99 }))}+ className="w-full bg-port-card border border-port-border rounded px-2 py-1 text-xs text-white"+ />+ </div>+ <div>+ <label htmlFor="llama-spec-type" className="text-[11px] text-gray-400 block mb-1">Spec Type</label>+ <input+ id="llama-spec-type"+ aria-label="Spec Type"+ type="text"+ value={llamaForm.specType}+ onChange={(e) => setLlamaForm((prev) => ({ ...prev, specType: e.target.value }))}+ className="w-full bg-port-card border border-port-border rounded px-2 py-1 text-xs text-white"+ />+ </div>+ </div>+ )}++ <div className="flex items-center justify-between gap-2 pt-1">+ <button+ type="button"+ onClick={() => setShowLlamaAdvanced((prev) => !prev)}+ className="text-[11px] text-gray-500 hover:text-gray-300 flex items-center gap-1"+ >+ {showLlamaAdvanced ? <ChevronUp size={12} /> : <ChevronDown size={12} />}+ {showLlamaAdvanced ? 'Hide options' : 'Advanced options (port, ctx, GPU layers)'}+ </button>+ <button+ type="submit"+ disabled={llamaLoading || !llamaForm.model.trim()}+ 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"+ >+ {llamaLoading ? <BrailleSpinner /> : <Power size={13} />}+ Start Speculative Server+ </button>+ </div>+ </form>+ ) : (+ <div className="bg-port-warning/10 border border-port-warning/30 rounded-lg p-3 text-xs text-port-warning flex flex-col sm:flex-row sm:items-center justify-between gap-3">+ <div className="space-y-1">+ <p className="font-semibold">llama-server was not detected on system PATH.</p>+ <p className="text-gray-300">+ Install via Homebrew or compile the DFlash 2-enabled branch from source.+ </p>+ </div>+ <button+ onClick={handleInstallLlama}+ disabled={llamaLoading}+ 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 shrink-0"+ >+ {llamaLoading ? <BrailleSpinner /> : <Download size={13} />}+ Install llama.cpp+ </button>+ </div>+ )}++ {llamaStatus?.recentLogs?.length > 0 && (+ <div className="space-y-1">+ <button+ type="button"+ onClick={() => setShowLlamaLogs((prev) => !prev)}+ className="text-[11px] text-gray-500 hover:text-gray-300 flex items-center gap-1"+ >+ <Terminal size={11} />+ {showLlamaLogs ? 'Hide server logs' : `View server logs (${llamaStatus.recentLogs.length} lines)`}+ </button>+ {showLlamaLogs && (+ <pre className="text-[10px] text-gray-400 bg-port-bg border border-port-border/60 p-2.5 rounded max-h-40 overflow-y-auto font-mono whitespace-pre-wrap">+ {llamaStatus.recentLogs.join('\n')}+ </pre>+ )}+ </div>+ )}+ </div>+{/* Models — backend picker + catalog/install + installed list */}<div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-4"><div className="flex items-center justify-between gap-3 flex-wrap">diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsxindex c01eead609..a592279912 100644--- a/client/src/components/settings/LocalLlmTab.test.jsx+++ b/client/src/components/settings/LocalLlmTab.test.jsx@@ -15,6 +15,10 @@ vi.mock('../../services/api', () => ({controlOllamaService: vi.fn(),installAudioModel: vi.fn(),patchSettingsSlice: vi.fn(),+ getLlamaServerStatus: vi.fn().mockResolvedValue({ installed: false, running: false }),+ startLlamaServer: vi.fn(),+ stopLlamaServer: vi.fn(),+ installLlamaServer: vi.fn().mockResolvedValue({ success: true }),}));vi.mock('../../services/socket', () => ({default: { on: vi.fn(), off: vi.fn() },@@ -262,3 +266,72 @@ describe('LocalLlmTab measured fit badge', () => {expect(await screen.findByText(/backend refused it \(measured\)/)).toBeInTheDocument();});});++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,+ });+ startLlamaServer.mockResolvedValueOnce({ success: true, pid: 12345 });++ await renderTab();++ expect(await screen.findByText(/Launch Speculative Decoding Server/)).toBeInTheDocument();+ const modelInput = screen.getByPlaceholderText(/models\/Qwen3\.8-27B-Instruct/);+ fireEvent.change(modelInput, { target: { value: 'models/my-model.gguf' } });++ const startBtn = screen.getByRole('button', { name: /Start Speculative Server/ });+ fireEvent.click(startBtn);++ await waitFor(() => {+ expect(startLlamaServer).toHaveBeenCalledWith(expect.objectContaining({+ model: 'models/my-model.gguf',+ }));+ });+ });++ 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,+ });++ await renderTab();++ const installBtn = await screen.findByRole('button', { name: /Install llama\.cpp/ });+ expect(installBtn).toBeInTheDocument();+ fireEvent.click(installBtn);++ await waitFor(() => {+ expect(installLlamaServer).toHaveBeenCalled();+ });+ });++ it('renders running badge and stops server when llama-server is managed', async () => {+ const { getLlamaServerStatus, stopLlamaServer } = await import('../../services/api');+ getLlamaServerStatus.mockResolvedValueOnce({+ installed: true,+ running: true,+ managed: true,+ pid: 9999,+ endpoint: 'http://127.0.0.1:8080/v1',+ config: { model: 'models/base.gguf', draftModel: 'models/draft.gguf', specType: 'draft-dflash' },+ });+ stopLlamaServer.mockResolvedValueOnce({ success: true });++ await renderTab();++ expect(await screen.findByText(/Running \(PID 9999\)/)).toBeInTheDocument();+ const stopBtn = screen.getByRole('button', { name: /Stop Server/ });+ fireEvent.click(stopBtn);++ await waitFor(() => {+ expect(stopLlamaServer).toHaveBeenCalled();+ });+ });+});diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsxindex 3b74d166db..a37ef9d445 100644--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@ -421,6 +421,16 @@ export default function AIProviders() {<span className={`text-xs px-2 py-0.5 rounded ${providerTypeClass(provider.type)}`}>{provider.type.toUpperCase()}</span>+ {provider.llamaBacked && (+ <span className="text-xs px-2 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30">+ LLAMA.CPP / DFLASH+ </span>+ )}+ {provider.mtplxBacked && (+ <span className="text-xs px-2 py-0.5 rounded bg-blue-500/20 text-blue-300 border border-blue-500/30">+ MTPLX+ </span>+ )}{!provider.enabled && (<span className="text-xs px-2 py-0.5 rounded bg-gray-500/20 text-gray-400">DISABLED@@ -580,6 +590,16 @@ export default function AIProviders() {DEFAULT</span>)}+ {provider.llamaBacked && (+ <span className="text-xs px-2 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30">+ LLAMA.CPP / DFLASH+ </span>+ )}+ {provider.mtplxBacked && (+ <span className="text-xs px-2 py-0.5 rounded bg-blue-500/20 text-blue-300 border border-blue-500/30">+ MTPLX+ </span>+ )}{!provider.enabled && (<span className="text-xs px-2 py-0.5 rounded bg-gray-500/20 text-gray-400">DISABLED@@ -631,6 +651,11 @@ export default function AIProviders() {)}<div className="mt-2 text-sm text-gray-400 space-y-1">+ {provider.llamaBacked && (+ <p className="text-xs text-purple-300/90">+ Local llama.cpp / llama-server harness (endpoint: <code className="text-purple-200">{provider.endpoint}</code>) — supports DFlash 2 speculative drafting.+ </p>+ )}{isProcessProvider(provider) && (<p className="break-words">Command: <code className="text-gray-300 break-all">{provider.command} {provider.args?.join(' ')}</code></p>)}diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex 0b26c60fea..2f64f3062c 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -45,6 +45,19 @@ export const upgradeLocalLlmBackend = (backend) =>export const controlOllamaService = (action) =>request('/local-llm/ollama-service', { method: 'POST', body: JSON.stringify({ action }) });+// llama-server (DFlash 2 / Speculative Decoding) process controls+export const getLlamaServerStatus = (options) =>+ request('/local-llm/llama-server/status', options);++export const startLlamaServer = (config) =>+ request('/local-llm/llama-server/start', { method: 'POST', body: JSON.stringify(config) });++export const stopLlamaServer = () =>+ request('/local-llm/llama-server/stop', { method: 'POST' });++export const installLlamaServer = () =>+ request('/local-llm/llama-server/install', { method: 'POST' });+// 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/client/src/utils/providers.js b/client/src/utils/providers.jsindex 353ebe7471..ac1803c339 100644--- a/client/src/utils/providers.js+++ b/client/src/utils/providers.js@@ -514,7 +514,7 @@ export const isVisionCapableCliProvider = (provider) =>export const isToolUseModel = (id) =>typeof id === 'string' && id.length > 0 &&// Mirror of TOOL_USE_RE in server/lib/localModelHeuristics.js — keep in lockstep.- /qwen|llama-?3\.[1-9]|llama-?4|mistral|mixtral|ministral|codestral|devstral|magistral|command-?r|command-?a|north-mini-code|firefunction|functionary|watt-tool|hermes|functiongemma|glm-?4|granite-?[34]|(?:^|[-_/:])gemma-?4|gpt-oss|nemotron|olmo-?3|lfm2|ornith|muse-glimmer|nex-n2|smollm2|deepseek-v3|deepseek-r1|deepseek-v4/i.test(id);+ /qwen|llama-?3\.[1-9]|llama-?4|mistral|mixtral|ministral|codestral|devstral|magistral|command-?r|command-?a|north-mini-code|firefunction|functionary|watt-tool|hermes|functiongemma|glm-?4|granite-?[34]|(?:^|[-_/:])gemma-?4|gpt-oss|nemotron|olmo-?3|lfm2|ornith|muse-glimmer|nex-n2|smollm2|dflash|deepseek-v3|deepseek-r1|deepseek-v4/i.test(id);/*** Agent-picker tool-use annotation for a model id. Agent / CoS tasks (the CD@@ -562,7 +562,7 @@ export const isToolUseModel = (id) =>* @returns {{toolCapable:boolean}|null}*/export const localToolUseHint = (id, provider, toolUseIdsByProvider = null) =>- (localBackendForProvider(provider) || isOllamaBackedProvider(provider))+ (localBackendForProvider(provider) || isOllamaBackedProvider(provider) || provider?.mtplxBacked === true || provider?.llamaBacked === true)&& typeof id === 'string' && id.length > 0? { toolCapable: toolUseIdsByProvider?.[provider?.id]?.has(id) === true || isToolUseModel(id) }: null;diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.jsindex 0d684fbc28..d5fa16ff84 100644--- a/client/src/utils/providers.test.js+++ b/client/src/utils/providers.test.js@@ -853,6 +853,7 @@ describe('supportsModelRefresh', () => {'antigravity-cli', 'antigravity-tui', 'cerebras', 'claude-code','claude-code-bedrock', 'claude-ollama', 'claude-ollama-tui', 'cursor-cli','cursor-tui', 'grok', 'lmstudio', 'mtplx', 'nvidia-kimi', 'ollama',+ 'opencode-llama-tui','opencode-mtplx', 'opencode-mtplx-tui', 'opencode-ollama','opencode-ollama-tui', 'opencode-orcarouter', 'opencode-orcarouter-tui','orcarouter',diff --git a/data.reference/providers.json b/data.reference/providers.jsonindex 21e665638d..a308f45a96 100644--- a/data.reference/providers.json+++ b/data.reference/providers.json@@ -230,6 +230,25 @@"secretEnvVars": [],"tuiPromptDelayMs": 2500},+ "opencode-llama-tui": {+ "id": "opencode-llama-tui",+ "name": "OpenCode llama TUI",+ "type": "tui",+ "command": "opencode",+ "args": [],+ "endpoint": "http://127.0.0.1:8080/v1",+ "models": ["dflash", "qwen3.8-27b-dflash2", "Muse-Glimmer-30B-DFlash2"],+ "defaultModel": "dflash",+ "llamaBacked": true,+ "timeout": 600000,+ "enabled": true,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"llama\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"llama.cpp (local)\",\"options\":{\"baseURL\":\"http://127.0.0.1:8080/v1\"}}}}"+ },+ "secretEnvVars": [],+ "tuiPromptDelayMs": 2500,+ "tuiIdleTimeoutMs": 180000+ },"orcarouter": {"id": "orcarouter","name": "OrcaRouter",diff --git a/docs/README.md b/docs/README.mdindex 10a3deb87a..e346d10a1f 100644--- a/docs/README.md+++ b/docs/README.md@@ -34,7 +34,7 @@ Start with the [product surface map](./features/product-surfaces.md) for a complApp management: [app-wizard](./features/app-wizard.md) · [autofixer](./features/autofixer.md) · [browser](./features/browser.md) · [error-handling](./features/error-handling.md) · [jira-sprint-manager](./features/jira-sprint-manager.md)-Chief of Staff: [chief-of-staff](./features/chief-of-staff.md) · [cos-agent-runner](./features/cos-agent-runner.md) · [cos-enhancement](./features/cos-enhancement.md) · [agent-context](./features/agent-context.md) · [agent-skills](./features/agent-skills.md) · [memory-system](./features/memory-system.md) · [claude-ollama](./features/claude-ollama.md) · [mtplx](./features/mtplx.md) · [prompt-manager](./features/prompt-manager.md)+Chief of Staff: [chief-of-staff](./features/chief-of-staff.md) · [cos-agent-runner](./features/cos-agent-runner.md) · [cos-enhancement](./features/cos-enhancement.md) · [agent-context](./features/agent-context.md) · [agent-skills](./features/agent-skills.md) · [memory-system](./features/memory-system.md) · [claude-ollama](./features/claude-ollama.md) · [mtplx](./features/mtplx.md) · [dflash2](./features/dflash2.md) · [prompt-manager](./features/prompt-manager.md)Identity & self: [digital-twin](./features/digital-twin.md) · [identity-system](./features/identity-system.md) · [soul-system](./features/soul-system.md) · [privacy-center](./features/privacy-center.md) · [post](./features/post.md) (insights design spike: [plans/2026-06-03](./plans/2026-06-03-cross-domain-insights-engine.md))diff --git a/docs/features/dflash2.md b/docs/features/dflash2.mdnew file mode 100644index 0000000000..8a3d032d70--- /dev/null+++ b/docs/features/dflash2.md@@ -0,0 +1,53 @@+# DFlash 2 Speculative Decoding — llama.cpp & OpenCode llama TUI++[DFlash 2](https://huggingface.co/z-lab) provides deep, ultra-fast block-level speculative drafting for large language models (such as Qwen 2.5, Qwen 3.8, and Muse-Glimmer). By pairing a small speculative drafter model (typically 1.5–3 GB) with a target foundation model (e.g. 27B–30B), DFlash 2 achieves 2.5–3× end-to-end token generation speedups without sacrificing output quality.++PortOS provides direct integration with DFlash 2 through the **OpenCode llama TUI** provider preset and local OpenAI-compatible inference servers like `llama-server`.++---++## What PortOS Adds++1. **OpenCode llama TUI Provider**:+ - An attachable `tui` coding-agent provider preset (`opencode-llama-tui`) configured to connect to `http://127.0.0.1:8080/v1`.+ - Seeded with default model aliases `["dflash", "qwen3.8-27b-dflash2", "Muse-Glimmer-30B-DFlash2"]` with default `dflash`.+ - Fully enabled by default and equipped with OpenCode's agentic file-writing harness, tool calling, and session persistence.+2. **Model Refresh**:+ - Support for dynamic model discovery via the **Refresh Models** button on AI Providers, querying the local `llama-server` `/v1/models` endpoint.+3. **Local LLMs & AI Providers Guidance**:+ - UI instructions, command templates, and copyable run lines surfaced in **Settings → Local LLMs** and **AI Providers**.++---++## Setup & Running with llama-server++### 1. Download Base & Draft Models+Download your base GGUF and corresponding DFlash 2 drafter GGUF from Hugging Face:++- **Qwen 3.8 27B Draft Pair**:+ - Base: `Qwen/Qwen3.8-27B-Instruct-GGUF` (e.g. `Qwen3.8-27B-Instruct-Q4_K_M.gguf`)+ - Drafter: `incoai/Qwen3.8-27B-DFlash2-GGUF` (e.g. `Qwen3.8-27B-DFlash2-Q4_K_M.gguf`)+- **Muse-Glimmer 30B Draft Pair**:+ - Base: `meta-models/Muse-Glimmer-30B-GGUF`+ - Drafter: `z-lab/Muse-Glimmer-30B-DFlash2-GGUF`++### 2. Launch llama-server+Start `llama-server` on loopback port `8080` with speculative decoding enabled:++```bash+llama-server \+ -m models/Qwen3.8-27B-Instruct-Q4_K_M.gguf \+ --draft-model models/Qwen3.8-27B-DFlash2-Q4_K_M.gguf \+ --spec-type draft-dflash \+ --port 8080 \+ --host 127.0.0.1 \+ --alias dflash \+ --ctx-size 32768 \+ --n-gpu-layers 99+```++### 3. Use in PortOS+1. Navigate to **AI Providers** (`/ai`) or **Settings → Local LLMs**.+2. Verify **OpenCode llama TUI** is enabled.+3. Click **Refresh Models** to pull the live aliases from `llama-server`, or use the default `dflash` model.+4. Select **OpenCode llama TUI** in the CoS task creator or terminal runner to execute coding and agent tasks with speculative acceleration.diff --git a/scripts/migrations/280-opencode-llama-tui-provider.js b/scripts/migrations/280-opencode-llama-tui-provider.jsnew file mode 100644index 0000000000..3b7417cdb0--- /dev/null+++ b/scripts/migrations/280-opencode-llama-tui-provider.js@@ -0,0 +1,37 @@+/**+ * Ship enabled OpenCode llama TUI provider preset to existing installs.+ *+ * Provides a TUI coding-agent harness for local llama.cpp / llama-server+ * instances, including speculative decoding with DFlash 2.+ *+ * Kept in lockstep with data.reference/providers.json and+ * server/lib/aiToolkit/defaults/providers.sample.json. Later default changes+ * require a new migration.+ */++import { makeProviderSeedMigration } from './_lib.js';++const OPENCODE_CONFIG_CONTENT = '{"permission":"allow","provider":{"llama":{"npm":"@ai-sdk/openai-compatible","name":"llama.cpp (local)","options":{"baseURL":"http://127.0.0.1:8080/v1"}}}}';++const OPENCODE_LLAMA_TUI = {+ id: 'opencode-llama-tui',+ name: 'OpenCode llama TUI',+ type: 'tui',+ command: 'opencode',+ args: [],+ endpoint: 'http://127.0.0.1:8080/v1',+ models: ['dflash', 'qwen3.8-27b-dflash2', 'Muse-Glimmer-30B-DFlash2'],+ defaultModel: 'dflash',+ llamaBacked: true,+ timeout: 600000,+ enabled: true,+ envVars: { OPENCODE_CONFIG_CONTENT },+ secretEnvVars: [],+ tuiPromptDelayMs: 2500,+ tuiIdleTimeoutMs: 180000,+};++export default makeProviderSeedMigration({+ label: 'OpenCode llama TUI',+ defs: [OPENCODE_LLAMA_TUI],+});diff --git a/scripts/migrations/280-opencode-llama-tui-provider.test.js b/scripts/migrations/280-opencode-llama-tui-provider.test.jsnew file mode 100644index 0000000000..ca99d47ce9--- /dev/null+++ b/scripts/migrations/280-opencode-llama-tui-provider.test.js@@ -0,0 +1,61 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './280-opencode-llama-tui-provider.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 280 — OpenCode llama TUI provider', () => {+ let rootDir;+ let providersPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-280-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ providersPath = join(rootDir, 'data/providers.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('adds enabled OpenCode llama TUI preset without changing the active provider', async () => {+ writeJson(providersPath, {+ activeProvider: 'claude-code',+ providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },+ });++ await migration.up({ rootDir });+ const out = readJson(providersPath);+ const tui = out.providers['opencode-llama-tui'];++ expect(tui).toMatchObject({+ name: 'OpenCode llama TUI',+ type: 'tui',+ command: 'opencode',+ endpoint: 'http://127.0.0.1:8080/v1',+ models: ['dflash', 'qwen3.8-27b-dflash2', 'Muse-Glimmer-30B-DFlash2'],+ defaultModel: 'dflash',+ llamaBacked: true,+ enabled: true,+ tuiIdleTimeoutMs: 180000,+ });+ expect(JSON.parse(tui.envVars.OPENCODE_CONFIG_CONTENT).provider.llama.options.baseURL).toBe('http://127.0.0.1:8080/v1');+ expect(out.activeProvider).toBe('claude-code');+ });++ it('preserves an existing custom OpenCode llama TUI configuration', async () => {+ const existing = {+ id: 'opencode-llama-tui',+ name: 'Custom Llama TUI',+ type: 'tui',+ endpoint: 'http://custom-host:8080/v1',+ enabled: false,+ };+ writeJson(providersPath, { providers: { 'opencode-llama-tui': existing } });++ await migration.up({ rootDir });+ expect(readJson(providersPath).providers['opencode-llama-tui']).toEqual(existing);+ });+});diff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.jsonindex 4be39766f0..fde81f66b3 100644--- a/server/lib/aiToolkit/defaults/providers.sample.json+++ b/server/lib/aiToolkit/defaults/providers.sample.json@@ -150,6 +150,25 @@"secretEnvVars": [],"tuiPromptDelayMs": 2500},+ "opencode-llama-tui": {+ "id": "opencode-llama-tui",+ "name": "OpenCode llama TUI",+ "type": "tui",+ "command": "opencode",+ "args": [],+ "endpoint": "http://127.0.0.1:8080/v1",+ "models": ["dflash", "qwen3.8-27b-dflash2", "Muse-Glimmer-30B-DFlash2"],+ "defaultModel": "dflash",+ "llamaBacked": true,+ "timeout": 600000,+ "enabled": true,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"llama\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"llama.cpp (local)\",\"options\":{\"baseURL\":\"http://127.0.0.1:8080/v1\"}}}}"+ },+ "secretEnvVars": [],+ "tuiPromptDelayMs": 2500,+ "tuiIdleTimeoutMs": 180000+ },"orcarouter": {"id": "orcarouter","name": "OrcaRouter",diff --git a/server/lib/aiToolkit/internal/modelFetchers.js b/server/lib/aiToolkit/internal/modelFetchers.jsindex d1dc45f600..4a8fcbf9a8 100644--- a/server/lib/aiToolkit/internal/modelFetchers.js+++ b/server/lib/aiToolkit/internal/modelFetchers.js@@ -70,6 +70,14 @@ export const MODEL_FETCHERS = [tuiMatch: (p) => p?.mtplxBacked === true,fetch: '_fetchMtplxModels',},+ {+ key: 'llama',+ // llama.cpp / llama-server exposes its active models through its OpenAI-compatible+ // `/v1/models` endpoint.+ cliMatch: (p) => p?.llamaBacked === true,+ tuiMatch: (p) => p?.llamaBacked === true,+ fetch: '_fetchLlamaModels',+ },{key: 'orcarouter',// OrcaRouter-backed OpenCode wrappers probe the sibling API provider'sdiff --git a/server/lib/aiToolkit/internal/modelFetchers.test.js b/server/lib/aiToolkit/internal/modelFetchers.test.jsindex 490eb339df..85e716eddb 100644--- a/server/lib/aiToolkit/internal/modelFetchers.test.js+++ b/server/lib/aiToolkit/internal/modelFetchers.test.js@@ -18,6 +18,7 @@ const SHIPPED_REFRESHABLE = ['antigravity-cli', 'antigravity-tui', 'cerebras', 'claude-code','claude-code-bedrock', 'claude-ollama', 'claude-ollama-tui', 'cursor-cli','cursor-tui', 'grok', 'lmstudio', 'mtplx', 'nvidia-kimi', 'ollama',+ 'opencode-llama-tui','opencode-mtplx', 'opencode-mtplx-tui', 'opencode-ollama', 'opencode-ollama-tui','opencode-orcarouter', 'opencode-orcarouter-tui', 'orcarouter',];@@ -130,6 +131,11 @@ describe('resolveModelFetcher — the ordering the old chains encoded in prose',expect(resolveModelFetcher(p).fetch).toBe('_fetchMtplxModels');});+ it('routes a llama-backed OpenCode TUI to the llama endpoint fetcher', () => {+ const p = { id: 'opencode-llama-tui', type: 'tui', command: 'opencode', llamaBacked: true };+ expect(resolveModelFetcher(p).fetch).toBe('_fetchLlamaModels');+ });+it('lets a command beat a display name — a renamed cursor still reaches cursor-agent', () => {// Renaming a cursor provider "Cursor Claude Opus" must not persist// Anthropic ids that cursor-agent will reject.diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex fa232553a6..ddca966527 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -151,6 +151,7 @@ const TOOL_USE_RE = new RegExp(['olmo-?3','lfm2', 'ornith', 'muse-glimmer', 'nex-n2','smollm2',+ 'dflash','deepseek-v3', 'deepseek-r1', 'deepseek-v4',].join('|'), 'i');@@ -604,6 +605,7 @@ export function createProviderService(config = {}) {// backend. Preserve this marker so OpenCode receives the `mtplx/`// namespace and model refresh probes its local endpoint....(providerData.mtplxBacked === true ? { mtplxBacked: true } : {}),+ ...(providerData.llamaBacked === true ? { llamaBacked: true } : {}),...(providerData.orcarouterBacked === true ? { orcarouterBacked: true } : {}),// Explicit opt-in to send the API key to an arbitrary (non-local,// non-allowlisted) endpoint — see internal/endpointGuard.js. Only@@ -1089,6 +1091,11 @@ export function createProviderService(config = {}) {return this._refreshAPIProviderModels(provider);},+ /** Fetch the llama-server catalog for OpenCode llama CLI/TUI wrappers. */+ async _fetchLlamaModels(provider) {+ return this._refreshAPIProviderModels(provider);+ },+/** Fetch the OrcaRouter catalog for its OpenCode CLI/TUI wrappers. */async _fetchOrcaRouterModels(provider) {return this._refreshAPIProviderModels(provider);diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.jsindex 2c1e2a1394..d8eaf54bb9 100644--- a/server/lib/aiToolkit/validation.js+++ b/server/lib/aiToolkit/validation.js@@ -104,6 +104,9 @@ export const providerSchema = z.object({// server. This is intentionally distinct from `ollamaBacked`: model weights// and runtime protocol configuration are not interchangeable.mtplxBacked: z.boolean().optional(),+ // Marks an OpenCode CLI/TUI wrapper for a separately started local llama.cpp+ // server (e.g. DFlash 2 speculative decoding).+ llamaBacked: z.boolean().optional(),// Marks an OpenCode CLI/TUI wrapper for the OrcaRouter OpenAI-compatible// gateway. Its API key is read from the sibling `orcarouter` API record at// spawn/refresh time and is never stored in this wrapper's config.diff --git a/server/lib/cliChildEnv.js b/server/lib/cliChildEnv.jsindex 9a4813d2d1..86859f5395 100644--- a/server/lib/cliChildEnv.js+++ b/server/lib/cliChildEnv.js@@ -75,7 +75,7 @@ function claudeOllamaEnvDefaults(provider) {* @param {object} options* @param {object|null} [options.before] - layered first, so `provider.envVars`* overrides it (forgeTokenEnv, claudeSettingsEnv).- * @param {{command?:string, envVars?:object, models?:string[], defaultModel?:string|null, ollamaBacked?:boolean, mtplxBacked?:boolean, orcarouterBacked?:boolean, thinking?:boolean}|null} [options.provider]+ * @param {{command?:string, envVars?:object, models?:string[], defaultModel?:string|null, ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, orcarouterBacked?:boolean, thinking?:boolean}|null} [options.provider]* @param {string|null} [options.model] - the model being run this invocation,* unioned into the OpenCode declared-models map. Omit when the site has no* per-call model — `provider.defaultModel` is always declared regardless.diff --git a/server/lib/localModelHeuristics.js b/server/lib/localModelHeuristics.jsindex 24cfe8d058..07190c3ee6 100644--- a/server/lib/localModelHeuristics.js+++ b/server/lib/localModelHeuristics.js@@ -143,6 +143,7 @@ const TOOL_USE_RE = new RegExp(['olmo-?3','lfm2', 'ornith', 'muse-glimmer', 'nex-n2','smollm2',+ 'dflash','deepseek-v3', 'deepseek-r1', 'deepseek-v4',].join('|'), 'i');diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.jsindex bb746a8821..fbb6b1dcc6 100644--- a/server/lib/mediaValidation.js+++ b/server/lib/mediaValidation.js@@ -158,6 +158,16 @@ export const localLlmMigrateSchema = z.object({});export const localLlmInstallBackendSchema = z.object({ backend: localLlmBackendSchema });export const localLlmOllamaServiceSchema = z.object({ action: z.enum(['start', 'stop', 'enable', 'disable']) });+export const localLlmLlamaServerStartSchema = z.object({+ model: z.string().trim().min(1).max(500),+ draftModel: z.string().trim().max(500).optional().nullable(),+ specType: z.string().trim().max(100).optional().default('draft-dflash'),+ port: z.coerce.number().int().min(1).max(65535).optional().default(8080),+ host: z.string().trim().max(100).optional().default('127.0.0.1'),+ ctxSize: z.coerce.number().int().min(512).max(1048576).optional().default(32768),+ nGpuLayers: z.coerce.number().int().min(0).max(999).optional().default(99),+ alias: z.string().trim().max(100).optional().default('dflash'),+});export const localLlmHuggingFaceSearchSchema = z.object({backend: localLlmBackendSchema,q: z.string().max(160).optional().default(''),diff --git a/server/lib/modelPricing.js b/server/lib/modelPricing.jsindex 898524ca22..c7c68cf134 100644--- a/server/lib/modelPricing.js+++ b/server/lib/modelPricing.js@@ -297,7 +297,7 @@ export function isFreeProvider(providerOrId) {if (providerOrId == null) return false;if (typeof providerOrId === 'string') return FREE_ID.test(providerOrId);const p = providerOrId;- if (p.ollamaBacked === true || p.mtplxBacked === true) return true;+ if (p.ollamaBacked === true || p.mtplxBacked === true || p.llamaBacked === true) return true;if (FREE_ID.test(p.id || '') || FREE_ID.test(p.command || '')) return true;if (typeof p.endpoint === 'string' && LOCALHOST_ENDPOINT.test(p.endpoint.trim())) return true;return false;diff --git a/server/lib/opencodeConfig.js b/server/lib/opencodeConfig.jsindex 0799defdc3..7ef07c059e 100644--- a/server/lib/opencodeConfig.js+++ b/server/lib/opencodeConfig.js@@ -36,6 +36,11 @@ const OPENCODE_LOCAL_BASE_PROVIDERS = {name: 'MTPLX (local MTP)',options: { baseURL: 'http://127.0.0.1:8000/v1' },},+ llama: {+ npm: '@ai-sdk/openai-compatible',+ name: 'llama.cpp (local)',+ options: { baseURL: 'http://127.0.0.1:8080/v1' },+ },orcarouter: {npm: '@ai-sdk/openai-compatible',name: 'OrcaRouter',@@ -63,7 +68,7 @@ const stripProviderPrefix = (id, providerKey) =>* Normalize an id or list of ids to the unique, non-empty, prefix-stripped bare* model ids that key the OpenCode `models` map.* @param {string|string[]|null|undefined} models- * @param {'ollama'|'mtplx'|'orcarouter'} [providerKey='ollama']+ * @param {'ollama'|'mtplx'|'llama'|'orcarouter'} [providerKey='ollama']* @returns {string[]}*/export function toBareModelIds(models, providerKey = 'ollama') {@@ -92,7 +97,7 @@ export function toBareModelIds(models, providerKey = 'ollama') {** @param {string|string[]|null|undefined} models* @param {object|null} [base] - existing config to merge into (a fresh clone is made)- * @param {'ollama'|'mtplx'|'orcarouter'} [providerKey='ollama']+ * @param {'ollama'|'mtplx'|'llama'|'orcarouter'} [providerKey='ollama']* @returns {object} OpenCode config object*/export function buildOpencodeConfig(models, base = null, providerKey = 'ollama', generation = null) {@@ -148,7 +153,7 @@ export function buildOpencodeConfig(models, base = null, providerKey = 'ollama',** @param {string|string[]|null|undefined} models* @param {object|null} [base] - existing config to merge into- * @param {'ollama'|'mtplx'} [providerKey='ollama']+ * @param {'ollama'|'mtplx'|'llama'|'orcarouter'} [providerKey='ollama']* @returns {string} JSON string for OPENCODE_CONFIG_CONTENT*/export function buildOpencodeConfigContent(models, base = null, providerKey = 'ollama', generation = null) {@@ -158,7 +163,7 @@ export function buildOpencodeConfigContent(models, base = null, providerKey = 'o/*** Build dynamic env vars for an OpenCode local-provider spawn. Returns an* object with `OPENCODE_CONFIG_CONTENT` (models map declared) for Ollama-,- * MTPLX-, or OrcaRouter-backed OpenCode providers, otherwise an empty object (caller keeps+ * MTPLX-, Llama-, or OrcaRouter-backed OpenCode providers, otherwise an empty object (caller keeps* existing env).** The provider's already-stored `OPENCODE_CONFIG_CONTENT` is used as the base and@@ -168,7 +173,7 @@ export function buildOpencodeConfigContent(models, base = null, providerKey = 'o* model, and the model being run this invocation — so whichever namespaced* `--model` the spawner passes is always accepted.*- * @param {{command?:string, ollamaBacked?:boolean, mtplxBacked?:boolean, orcarouterBacked?:boolean, models?:string[], defaultModel?:string|null, apiKey?:string, orcarouterApiKey?:string, envVars?:object}} provider+ * @param {{command?:string, ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, orcarouterBacked?:boolean, models?:string[], defaultModel?:string|null, apiKey?:string, orcarouterApiKey?:string, envVars?:object}} provider* @param {string|null|undefined} model - the model being run (may differ from defaultModel)* @returns {{OPENCODE_CONFIG_CONTENT?: string}} env vars to merge*/diff --git a/server/lib/opencodeConfig.test.js b/server/lib/opencodeConfig.test.jsindex c57e8f458d..df1cd53dde 100644--- a/server/lib/opencodeConfig.test.js+++ b/server/lib/opencodeConfig.test.js@@ -103,6 +103,20 @@ describe('buildOpencodeConfig', () => {});});+ it('declares llama models under provider.llama with its local endpoint', () => {+ const cfg = buildOpencodeConfig(['llama/dflash', 'llama/qwen3.8-27b-dflash2'], null, 'llama');+ expect(cfg.provider.ollama).toBeUndefined();+ expect(cfg.provider.llama).toMatchObject({+ npm: '@ai-sdk/openai-compatible',+ name: 'llama.cpp (local)',+ options: { baseURL: 'http://127.0.0.1:8080/v1' },+ });+ expect(cfg.provider.llama.models).toEqual({+ dflash: { name: 'dflash', tool_call: true },+ 'qwen3.8-27b-dflash2': { name: 'qwen3.8-27b-dflash2', tool_call: true },+ });+ });+it('declares OrcaRouter models under unchanged keys and its gateway endpoint', () => {const cfg = buildOpencodeConfig(['orcarouter/auto', 'anthropic/claude-sonnet-4.6'], null, 'orcarouter');expect(cfg.provider.orcarouter).toMatchObject({diff --git a/server/lib/providerFamilies.js b/server/lib/providerFamilies.jsindex 16e2d0ba9f..a6a0f49fd0 100644--- a/server/lib/providerFamilies.js+++ b/server/lib/providerFamilies.js@@ -57,6 +57,6 @@ export const familyLabel = (id) => PROVIDER_FAMILIES.find((f) => f.id === id)?.l* provider's spend to the subscription that actually covered it.*/export function familyForProvider(provider) {- if (!provider || provider.ollamaBacked === true || provider.mtplxBacked === true) return null;+ if (!provider || provider.ollamaBacked === true || provider.mtplxBacked === true || provider.llamaBacked === true) return null;return PROVIDER_FAMILIES.find((f) => f.matches(provider))?.id ?? null;}diff --git a/server/lib/providerModels.js b/server/lib/providerModels.jsindex a42f0c85ab..3c91f29b99 100644--- a/server/lib/providerModels.js+++ b/server/lib/providerModels.js@@ -560,7 +560,7 @@ export function isOpencodeCommand(command) {* already-qualified id (`openai/gpt-4o`, `anthropic/claude-sonnet`), and blindly* prefixing `ollama/` would route it to the wrong backend. No-op for* non-local / non-OpenCode providers and empty models.- * @param {{command?:string, ollamaBacked?:boolean, mtplxBacked?:boolean, orcarouterBacked?:boolean}} provider+ * @param {{command?:string, ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, orcarouterBacked?:boolean}} provider* @param {string|null|undefined} model* @returns {string|null|undefined}*/@@ -579,12 +579,13 @@ export function prefixOpencodeModel(provider, model) {* opted into one. Structural markers avoid deriving a backend from an editable* display name or endpoint and preserve the legacy Ollama outcome if a malformed* record carries both markers.- * @param {{ollamaBacked?:boolean, mtplxBacked?:boolean, orcarouterBacked?:boolean}|null|undefined} provider- * @returns {'ollama'|'mtplx'|'orcarouter'|null}+ * @param {{ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, orcarouterBacked?:boolean}|null|undefined} provider+ * @returns {'ollama'|'mtplx'|'llama'|'orcarouter'|null}*/export function getOpencodeLocalProviderNamespace(provider) {if (provider?.ollamaBacked === true) return 'ollama';if (provider?.mtplxBacked === true) return 'mtplx';+ if (provider?.llamaBacked === true) return 'llama';if (provider?.orcarouterBacked === true) return 'orcarouter';return null;}diff --git a/server/lib/providerModels.test.js b/server/lib/providerModels.test.jsindex 7640c9386d..51ec7b060e 100644--- a/server/lib/providerModels.test.js+++ b/server/lib/providerModels.test.js@@ -145,6 +145,12 @@ describe('providerModels', () => {expect(prefixOpencodeModel(mtplx, 'mtplx/mtplx')).toBe('mtplx/mtplx');});+ it('namespaces a bare llama id under llama/ for llama-backed OpenCode providers', () => {+ const llama = { command: 'opencode', llamaBacked: true };+ expect(prefixOpencodeModel(llama, 'dflash')).toBe('llama/dflash');+ expect(prefixOpencodeModel(llama, 'llama/dflash')).toBe('llama/dflash');+ });+it('keeps the OrcaRouter stored id in the models map but double-prefixes the OpenCode argv id', () => {const orca = { command: 'opencode', orcarouterBacked: true };expect(prefixOpencodeModel(orca, 'orcarouter/auto')).toBe('orcarouter/orcarouter/auto');@@ -184,6 +190,7 @@ describe('providerModels', () => {it('uses explicit markers and keeps Ollama as the malformed dual-marker fallback', () => {expect(getOpencodeLocalProviderNamespace({ ollamaBacked: true })).toBe('ollama');expect(getOpencodeLocalProviderNamespace({ mtplxBacked: true })).toBe('mtplx');+ expect(getOpencodeLocalProviderNamespace({ llamaBacked: true })).toBe('llama');expect(getOpencodeLocalProviderNamespace({ orcarouterBacked: true })).toBe('orcarouter');expect(getOpencodeLocalProviderNamespace({ ollamaBacked: true, mtplxBacked: true })).toBe('ollama');expect(getOpencodeLocalProviderNamespace({})).toBeNull();diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 3fe357a444..099b4facf5 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -411,6 +411,9 @@ export const providerSchema = z.object({// Kept in schema parity with aiToolkit's provider schema. Marks OpenCode// wrappers for a separately started local MTPLX native-MTP server.mtplxBacked: z.boolean().optional(),+ // Marks an OpenCode CLI/TUI wrapper for a separately started local llama.cpp+ // server (e.g. DFlash 2 speculative decoding).+ llamaBacked: z.boolean().optional(),// Marks an OpenCode CLI/TUI wrapper for the OrcaRouter OpenAI-compatible// gateway; the sibling API record owns its key.orcarouterBacked: z.boolean().optional(),diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 2695b7729e..f6d58542cb 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -25,8 +25,10 @@ import {localLlmCompareSchema,localLlmAssessmentRunSchema,localLlmAssessmentIntentSchema,- localLlmAssessmentDeleteSchema+ localLlmAssessmentDeleteSchema,+ localLlmLlamaServerStartSchema} from '../lib/validation.js'+import { getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaServer } from '../services/llamaServerManager.js'import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'import { isAppleSilicon } from '../lib/platform.js'import { searchHuggingFaceModels, enrichCatalogWithVariants, applyMeasuredFit } from '../services/huggingFaceCatalog.js'@@ -460,4 +462,28 @@ router.post('/assessments/delete', asyncHandler(async (req, res) => {res.json({ success: true, backend, modelId })}))+// === llama-server (DFlash 2 / Speculative Decoding) ==========================+// GET /api/local-llm/llama-server/status — binary availability, process state, logs+router.get('/llama-server/status', asyncHandler(async (_req, res) => {+ res.json(await getLlamaServerStatus())+}))++// POST /api/local-llm/llama-server/start — launch llama-server+router.post('/llama-server/start', asyncHandler(async (req, res) => {+ const options = validateRequest(localLlmLlamaServerStartSchema, req.body)+ res.json(await startLlamaServer(options))+}))++// POST /api/local-llm/llama-server/stop — stop managed llama-server+router.post('/llama-server/stop', asyncHandler(async (_req, res) => {+ res.json(await stopLlamaServer())+}))++// POST /api/local-llm/llama-server/install — install llama.cpp via Homebrew+router.post('/llama-server/install', asyncHandler(async (req, res) => {+ const io = req.app.get('io')+ const onProgress = (data) => io?.emit('localLlm:progress', data)+ res.json(await installLlamaServer({ onProgress }))+}))+export default routerdiff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.jsindex e447a2dacb..24b68fe41b 100644--- a/server/routes/localLlm.test.js+++ b/server/routes/localLlm.test.js@@ -70,6 +70,13 @@ vi.mock('../services/localModelAssessments.js', () => ({deleteAssessment: vi.fn(async () => ({ deleted: true })),}));+vi.mock('../services/llamaServerManager.js', () => ({+ getLlamaServerStatus: vi.fn(async () => ({ installed: true, running: false })),+ startLlamaServer: vi.fn(async () => ({ success: true, pid: 123 })),+ stopLlamaServer: vi.fn(async () => ({ success: true })),+ installLlamaServer: vi.fn(async () => ({ success: true, message: 'installed' })),+}));+// /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', () => ({@@ -464,3 +471,38 @@ describe('measured assessments wiring', () => {});});});++describe('llama-server routes', () => {+ it('GET /api/local-llm/llama-server/status returns status', 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 });+ });++ it('POST /api/local-llm/llama-server/start launches server with valid payload', async () => {+ const res = await request(makeApp())+ .post('/api/local-llm/llama-server/start')+ .send({ model: 'models/Qwen3.8-27B.gguf', draftModel: 'models/DFlash.gguf' });+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ success: true, pid: 123 });+ });++ it('POST /api/local-llm/llama-server/start rejects invalid payload', async () => {+ const res = await request(makeApp())+ .post('/api/local-llm/llama-server/start')+ .send({});+ expect(res.status).toBe(400);+ });++ it('POST /api/local-llm/llama-server/stop stops server', async () => {+ const res = await request(makeApp()).post('/api/local-llm/llama-server/stop');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ success: true });+ });++ it('POST /api/local-llm/llama-server/install triggers install', async () => {+ const res = await request(makeApp()).post('/api/local-llm/llama-server/install');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ success: true, message: 'installed' });+ });+});diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.jsnew file mode 100644index 0000000000..e71d421806--- /dev/null+++ b/server/services/llamaServerManager.js@@ -0,0 +1,285 @@+/**+ * llama-server process manager+ *+ * Provides lifecycle management (status probe, start, stop, recent logs)+ * for a local `llama-server` instance running speculative decoding (e.g. DFlash 2).+ */++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 { fetchWithTimeout } from '../lib/fetchWithTimeout.js';+import { sleep } from '../lib/fileUtils.js';+import { ServerError } from '../lib/errorHandler.js';++const IS_WIN = process.platform === 'win32';+const MAX_LOG_LINES = 100;+const PROBE_TIMEOUT_MS = 1500;+const STARTUP_WAIT_TIMEOUT_MS = 4000;++let managedChild = null;+let currentConfig = null;+let recentLogs = [];+let lastExitError = null;++function appendLog(line) {+ if (!line) return;+ const text = String(line).trimEnd();+ if (!text) return;+ recentLogs.push(`[${new Date().toISOString()}] ${text}`);+ if (recentLogs.length > MAX_LOG_LINES) {+ recentLogs = recentLogs.slice(-MAX_LOG_LINES);+ }+}++/**+ * Probes whether an OpenAI-compatible endpoint responds at the given host/port.+ */+async function probeEndpoint(endpoint) {+ try {+ const url = `${endpoint.replace(/\/+$/, '')}/models`;+ const res = await fetchWithTimeout(url, { method: 'GET', timeout: PROBE_TIMEOUT_MS });+ return res.ok;+ } catch {+ return false;+ }+}++/**+ * Returns current status of llama-server (binary availability, running state, config, logs).+ */+export async function getLlamaServerStatus() {+ const binaryPath = await findCommandOnPath('llama-server');+ const installed = Boolean(binaryPath) && await commandExists(binaryPath);++ const host = currentConfig?.host || '127.0.0.1';+ const port = currentConfig?.port || 8080;+ const endpoint = `http://${host}:${port}/v1`;++ const isManagedActive = Boolean(managedChild && !managedChild.killed && managedChild.exitCode === null);+ const reachable = await probeEndpoint(endpoint);++ return {+ installed,+ running: isManagedActive || reachable,+ managed: isManagedActive,+ pid: isManagedActive ? managedChild.pid : null,+ host,+ port,+ endpoint,+ config: isManagedActive ? currentConfig : null,+ recentLogs: [...recentLogs],+ lastExitError,+ };+}++/**+ * Starts llama-server with the specified model and options.+ */+export async function startLlamaServer(options = {}) {+ const binaryPath = await findCommandOnPath('llama-server');+ if (!binaryPath || !(await commandExists(binaryPath))) {+ throw new ServerError(+ 'llama-server binary was not found on PATH. Install it via Homebrew (`brew install llama.cpp`) or build from source.',+ { status: 400 }+ );+ }++ if (managedChild && !managedChild.killed && managedChild.exitCode === null) {+ throw new ServerError(`llama-server is already running with PID ${managedChild.pid}`, { status: 409 });+ }++ const {+ model,+ draftModel,+ specType = 'draft-dflash',+ port = 8080,+ host = '127.0.0.1',+ ctxSize = 32768,+ nGpuLayers = 99,+ alias = 'dflash',+ } = options;++ if (!model || typeof model !== 'string') {+ throw new ServerError('model path is required to start llama-server', { status: 400 });+ }++ const endpoint = `http://${host}:${port}/v1`;+ const reachable = await probeEndpoint(endpoint);+ if (reachable) {+ throw new ServerError(`Port ${port} is already in use by an active server at ${endpoint}`, { status: 409 });+ }++ const args = ['-m', model.trim()];+ if (draftModel && typeof draftModel === 'string' && draftModel.trim()) {+ args.push('--draft-model', draftModel.trim());+ if (specType) args.push('--spec-type', specType.trim());+ }+ if (port) args.push('--port', String(port));+ if (host) args.push('--host', host);+ if (ctxSize) args.push('--ctx-size', String(ctxSize));+ if (nGpuLayers !== undefined && nGpuLayers !== null) args.push('-ngl', String(nGpuLayers));+ if (alias) args.push('--alias', alias);++ lastExitError = null;+ recentLogs = [];+ appendLog(`Starting: llama-server ${args.join(' ')}`);++ const env = safeChildProcessEnv();+ const spawnOpts = safeChildProcessOptions({+ env,+ shell: false,+ stdio: ['ignore', 'pipe', 'pipe'],+ detached: !IS_WIN,+ });++ const child = spawn(binaryPath, args, spawnOpts);+ managedChild = child;+ currentConfig = {+ model,+ draftModel: draftModel || null,+ specType,+ port,+ host,+ ctxSize,+ nGpuLayers,+ alias,+ };++ child.stdout?.on('data', (chunk) => {+ const lines = chunk.toString().split('\n');+ for (const line of lines) appendLog(line);+ });++ child.stderr?.on('data', (chunk) => {+ const lines = chunk.toString().split('\n');+ for (const line of lines) appendLog(line);+ });++ child.on('error', (err) => {+ appendLog(`Process error: ${err.message}`);+ lastExitError = err.message;+ if (managedChild === child) managedChild = null;+ });++ child.on('exit', (code, signal) => {+ appendLog(`Process exited with code ${code}${signal ? ` (signal ${signal})` : ''}`);+ if (code !== 0 && code !== null) {+ lastExitError = `Exited with code ${code}`;+ }+ if (managedChild === child) managedChild = null;+ });++ // Wait a short beat and verify probe+ const startTime = Date.now();+ let online = false;+ while (Date.now() - startTime < STARTUP_WAIT_TIMEOUT_MS) {+ if (child.exitCode !== null) break;+ await sleep(500);+ online = await probeEndpoint(endpoint);+ if (online) break;+ }++ return {+ success: true,+ running: true,+ managed: true,+ pid: child.pid,+ endpoint,+ online,+ config: currentConfig,+ };+}++/**+ * Stops the managed llama-server process.+ */+export async function stopLlamaServer() {+ if (!managedChild || managedChild.killed || managedChild.exitCode !== null) {+ const host = currentConfig?.host || '127.0.0.1';+ const port = currentConfig?.port || 8080;+ const endpoint = `http://${host}:${port}/v1`;+ const reachable = await probeEndpoint(endpoint);+ if (reachable) {+ return {+ success: false,+ message: `An external process is listening on ${endpoint}. It was not started by PortOS and cannot be stopped here.`,+ };+ }+ return { success: true, message: 'llama-server is not running' };+ }++ const childToKill = managedChild;+ managedChild = null;+ currentConfig = null;++ appendLog(`Stopping llama-server (PID ${childToKill.pid})`);+ killProcessTree(childToKill, 'SIGTERM', { processGroup: !IS_WIN });++ await sleep(600);+ if (!childToKill.killed && childToKill.exitCode === null) {+ killProcessTree(childToKill, 'SIGKILL', { processGroup: !IS_WIN });+ }++ return { success: true, message: 'llama-server stopped' };+}++/**+ * Installs llama.cpp via Homebrew.+ */+export async function installLlamaServer({ onProgress = () => {} } = {}) {+ const brewExists = await commandExists('brew', ['--version']);+ if (!brewExists) {+ throw new ServerError(+ 'Homebrew was not found. Please install Homebrew from https://brew.sh or build llama.cpp from source.',+ { status: 400 }+ );+ }++ onProgress({ event: 'start', message: 'Installing llama.cpp via Homebrew…' });+ const env = safeChildProcessEnv();+ const spawnOpts = safeChildProcessOptions({+ env,+ shell: false,+ stdio: ['ignore', 'pipe', 'pipe'],+ });++ const child = spawn('brew', ['install', 'llama.cpp'], spawnOpts);++ return new Promise((resolve, reject) => {+ child.stdout?.on('data', (d) => {+ onProgress({ event: 'progress', message: d.toString().trim() });+ });+ child.stderr?.on('data', (d) => {+ onProgress({ event: 'progress', message: d.toString().trim() });+ });+ child.on('error', (err) => {+ reject(new ServerError(`Failed to run brew: ${err.message}`, { status: 500 }));+ });+ child.on('exit', async (code) => {+ const binaryPath = await findCommandOnPath('llama-server');+ const installed = Boolean(binaryPath) && await commandExists(binaryPath);+ if (installed) {+ onProgress({ event: 'complete', message: 'llama.cpp installed successfully' });+ resolve({ success: true, message: 'llama.cpp installed successfully' });+ } else {+ const msg = code === 0 ? 'brew completed but llama-server was not found on PATH' : `brew install llama.cpp failed (exit code ${code})`;+ reject(new ServerError(msg, { status: 500 }));+ }+ });+ });+}++/**+ * Clears in-memory test state (used by test suites).+ */+export function _resetLlamaServerStateForTests() {+ if (managedChild && !managedChild.killed && managedChild.exitCode === null) {+ try { managedChild.kill('SIGKILL'); } catch {}+ }+ managedChild = null;+ currentConfig = null;+ recentLogs = [];+ lastExitError = null;+}diff --git a/server/services/llamaServerManager.test.js b/server/services/llamaServerManager.test.jsnew file mode 100644index 0000000000..659787953e--- /dev/null+++ b/server/services/llamaServerManager.test.js@@ -0,0 +1,140 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import {+ getLlamaServerStatus,+ startLlamaServer,+ stopLlamaServer,+ installLlamaServer,+ _resetLlamaServerStateForTests,+} from './llamaServerManager.js';+import * as processEnv from '../lib/processEnv.js';+import * as commandExistsModule from '../lib/commandExists.js';+import * as childProcess from '../lib/childProcess.js';+import { EventEmitter } from 'events';++describe('llamaServerManager', () => {+ beforeEach(() => {+ _resetLlamaServerStateForTests();+ vi.restoreAllMocks();+ });++ afterEach(() => {+ _resetLlamaServerStateForTests();+ vi.restoreAllMocks();+ });++ it('reports installed: false when binary is not found on PATH', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockResolvedValue(null);++ const status = await getLlamaServerStatus();+ expect(status.installed).toBe(false);+ expect(status.running).toBe(false);+ expect(status.managed).toBe(false);+ });++ it('reports installed: true when binary is found on PATH', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockResolvedValue('/opt/homebrew/bin/llama-server');+ vi.spyOn(commandExistsModule, 'commandExists').mockResolvedValue(true);++ const status = await getLlamaServerStatus();+ expect(status.installed).toBe(true);+ });++ it('rejects start when binary is missing', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockResolvedValue(null);++ await expect(startLlamaServer({ model: '/path/to/model.gguf' })).rejects.toThrow(+ /llama-server binary was not found/i+ );+ });++ it('spawns llama-server with draftModel and specType arguments', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockResolvedValue('/usr/local/bin/llama-server');+ vi.spyOn(commandExistsModule, 'commandExists').mockResolvedValue(true);++ const fakeChild = new EventEmitter();+ fakeChild.pid = 12345;+ fakeChild.killed = false;+ fakeChild.exitCode = null;+ fakeChild.stdout = new EventEmitter();+ fakeChild.stderr = new EventEmitter();++ let spawnArgs = null;+ vi.spyOn(childProcess, 'spawn').mockImplementation((cmd, args) => {+ spawnArgs = { cmd, args };+ return fakeChild;+ });++ const result = await startLlamaServer({+ model: 'models/Qwen3.8-27B.gguf',+ draftModel: 'models/Qwen3.8-DFlash2.gguf',+ specType: 'draft-dflash',+ port: 8080,+ host: '127.0.0.1',+ alias: 'dflash',+ });++ expect(result.success).toBe(true);+ expect(result.pid).toBe(12345);+ expect(spawnArgs.cmd).toBe('/usr/local/bin/llama-server');+ expect(spawnArgs.args).toEqual([+ '-m', 'models/Qwen3.8-27B.gguf',+ '--draft-model', 'models/Qwen3.8-DFlash2.gguf',+ '--spec-type', 'draft-dflash',+ '--port', '8080',+ '--host', '127.0.0.1',+ '--ctx-size', '32768',+ '-ngl', '99',+ '--alias', 'dflash',+ ]);++ const status = await getLlamaServerStatus();+ expect(status.running).toBe(true);+ expect(status.managed).toBe(true);+ expect(status.pid).toBe(12345);+ });++ it('stops managed process cleanly', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockResolvedValue('/usr/local/bin/llama-server');+ vi.spyOn(commandExistsModule, 'commandExists').mockResolvedValue(true);++ const fakeChild = new EventEmitter();+ fakeChild.pid = 54321;+ fakeChild.killed = false;+ fakeChild.exitCode = null;+ fakeChild.stdout = new EventEmitter();+ fakeChild.stderr = new EventEmitter();+ fakeChild.kill = vi.fn();++ vi.spyOn(childProcess, 'spawn').mockReturnValue(fakeChild);++ await startLlamaServer({ model: 'models/model.gguf' });+ const stopResult = await stopLlamaServer();+ expect(stopResult.success).toBe(true);++ const status = await getLlamaServerStatus();+ expect(status.managed).toBe(false);+ });++ it('installs llama.cpp via Homebrew when brew is available', async () => {+ vi.spyOn(commandExistsModule, 'commandExists').mockImplementation(async (cmd) => true);+ vi.spyOn(processEnv, 'findCommandOnPath').mockResolvedValue('/opt/homebrew/bin/llama-server');++ const fakeChild = new EventEmitter();+ fakeChild.stdout = new EventEmitter();+ fakeChild.stderr = new EventEmitter();++ vi.spyOn(childProcess, 'spawn').mockImplementation(() => {+ setTimeout(() => fakeChild.emit('exit', 0), 10);+ return fakeChild;+ });++ const result = await installLlamaServer();+ expect(result.success).toBe(true);+ });++ it('rejects install when Homebrew is missing', async () => {+ vi.spyOn(commandExistsModule, 'commandExists').mockResolvedValue(false);++ await expect(installLlamaServer()).rejects.toThrow(/Homebrew was not found/i);+ });+});diff --git a/server/services/providerUsage.js b/server/services/providerUsage.jsindex a32085380d..2e27ad2866 100644--- a/server/services/providerUsage.js+++ b/server/services/providerUsage.js@@ -614,7 +614,7 @@ const FAMILIES = PROVIDER_FAMILIES.map((family) => ({ ...family, fetch: FAMILY_F* wrapper its family's card).*/export function resolveEnabledFamilies(providers) {- const enabled = (providers || []).filter((p) => p?.enabled && p.ollamaBacked !== true && p.mtplxBacked !== true);+ const enabled = (providers || []).filter((p) => p?.enabled && p.ollamaBacked !== true && p.mtplxBacked !== true && p.llamaBacked !== true);return FAMILIES.filter((family) => enabled.some((p) => family.matches(p)));}@@ -651,7 +651,7 @@ const fetchFamilyQuota = (family, { wait, providers }) =>export async function getProviderQuotas({ wait = WAIT.CACHED, family = null } = {}) {const result = await getAllProviders();const providers = Array.isArray(result) ? result : (result?.providers || []);- const enabled = providers.filter((p) => p?.enabled && p.ollamaBacked !== true && p.mtplxBacked !== true);+ const enabled = providers.filter((p) => p?.enabled && p.ollamaBacked !== true && p.mtplxBacked !== true && p.llamaBacked !== true);const families = resolveEnabledFamilies(providers).filter((f) => !family || f.id === family);const familyCards = await Promise.all(families.map((f) =>fetchFamilyQuota(f, { wait, providers: enabled.filter((p) => f.matches(p)) })));diff --git a/server/services/quotaBurnJobs/providerPick.js b/server/services/quotaBurnJobs/providerPick.jsindex 4a9b82d2d4..4f1d607f73 100644--- a/server/services/quotaBurnJobs/providerPick.js+++ b/server/services/quotaBurnJobs/providerPick.js@@ -40,7 +40,7 @@ import { commandBasename } from '../../lib/providerModels.js';*/export function providerForFamily(providers, { familyId, providerId, prefer = 'tui' }) {const available = (providers || []).filter((provider) =>- provider?.enabled && provider.ollamaBacked !== true && provider.mtplxBacked !== true+ provider?.enabled && provider.ollamaBacked !== true && provider.mtplxBacked !== true && provider.llamaBacked !== true&& (provider.type === 'cli' || provider.type === 'tui'));if (providerId) return available.find((provider) => provider.id === providerId) || null;const inFamily = available.filter((provider) => matchesFamily(provider, familyId));