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

add Memory Management panel: unload Ollama / stop Whisper / unload Kokoro

[._.]/ Adam Eivyd6cd714240ad
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index 46c0866943..6ee7b02ec5 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -8,6 +8,7 @@ import {
deleteLocalLlmModel, switchLocalLlmBackend, migrateLocalLlmBackend, installLocalLlmBackend, upgradeLocalLlmBackend, controlOllamaService
} from '../../services/api';
import socket from '../../services/socket';
+import MemoryManagement from './MemoryManagement.jsx';
const BACKENDS = [
{ id: 'ollama', label: 'Ollama', icon: Cpu },
@@ -420,6 +421,7 @@ export function LocalLlmTab() {
return (
<div className="space-y-4">
+ <MemoryManagement />
{/* Backends — status + switch/migrate */}
<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">
diff --git a/client/src/components/settings/MemoryManagement.jsx b/client/src/components/settings/MemoryManagement.jsx
new file mode 100644
index 0000000000..648bd2d9a1
--- /dev/null
+++ b/client/src/components/settings/MemoryManagement.jsx
@@ -0,0 +1,243 @@
+// Panel that surfaces what's currently resident in unified memory and lets
+// the user evict it. The motivating workflow: "I want to render with FLUX.2
+// 9B bf16 (~36 GB) — what's holding memory right now that I can free?"
+//
+// Sources of residency this panel covers:
+// - Ollama models (multiple can be loaded simultaneously) → /api/local-llm/loaded
+// - Whisper STT (PM2 process `portos-whisper`) → /api/voice/status + /api/voice/whisper
+// - Kokoro TTS (in-process kokoro-js) → /api/voice/tts/status + /api/voice/tts/unload
+//
+// Things NOT covered here on purpose:
+// - Gemma text encoder for LTX video — only loaded inside the render subprocess, not resident
+// - Piper TTS — spawned per-synthesis, no persistent process
+// - Browser / Codex / Claude Code workers — managed elsewhere, not memory-pressure relevant
+//
+// Polls every 5s while mounted. Errors surface via the default apiCore toast
+// (no custom catch), so a single layer wins per the project convention.
+
+import { useState, useEffect, useCallback } from 'react';
+import { Cpu, Mic, Volume2, Trash2, Power, PowerOff, RefreshCw, AlertTriangle } from 'lucide-react';
+import toast from '../ui/Toast';
+import BrailleSpinner from '../BrailleSpinner';
+import { useAsyncAction } from '../../hooks/useAsyncAction.js';
+import { formatBytes } from '../../utils/formatters';
+import { getLoadedLlmModels, unloadOllamaModel } from '../../services/apiLocalLlm.js';
+import { getTtsStatus, unloadKokoroTts, controlWhisper, getVoiceStatus } from '../../services/apiVoice.js';
+
+const POLL_MS = 5000;
+
+const btnClass = 'flex items-center gap-1.5 px-2 py-1 text-xs font-medium rounded transition-colors disabled:opacity-50';
+
+function Row({ icon: Icon, title, subtitle, status, action, danger }) {
+ return (
+ <div className="flex items-center gap-3 py-2 px-3 border-b border-port-border/50 last:border-b-0">
+ <Icon className={`w-4 h-4 ${danger ? 'text-port-warning' : 'text-gray-400'} shrink-0`} />
+ <div className="flex-1 min-w-0">
+ <div className="text-sm text-gray-200 truncate">{title}</div>
+ {subtitle ? <div className="text-xs text-gray-500 truncate">{subtitle}</div> : null}
+ </div>
+ <div className="text-xs text-gray-400 mr-2 shrink-0">{status}</div>
+ {action}
+ </div>
+ );
+}
+
+export default function MemoryManagement() {
+ const [loadedOllama, setLoadedOllama] = useState([]);
+ const [ttsState, setTtsState] = useState({ state: 'lazy', loadedKey: null });
+ const [whisperRunning, setWhisperRunning] = useState(false);
+ const [loading, setLoading] = useState(true);
+ const [lastFetched, setLastFetched] = useState(0);
+
+ const refresh = useCallback(async () => {
+ const [llm, tts, voice] = await Promise.all([
+ getLoadedLlmModels().catch(() => ({ ollama: [] })),
+ getTtsStatus().catch(() => ({ kokoro: { state: 'lazy', loadedKey: null } })),
+ getVoiceStatus().catch(() => null),
+ ]);
+ setLoadedOllama(Array.isArray(llm?.ollama) ? llm.ollama : []);
+ setTtsState(tts?.kokoro || { state: 'lazy', loadedKey: null });
+ // voice.services.whisper.ok is the "PM2 process responsive" probe in
+ // checkAll(). When the service block is missing (status fetch failed) we
+ // default to "not running" — false negatives just mean the Stop button
+ // briefly hides, which the next poll corrects.
+ setWhisperRunning(Boolean(voice?.services?.whisper?.ok));
+ setLoading(false);
+ setLastFetched(Date.now());
+ }, []);
+
+ useEffect(() => {
+ refresh();
+ const t = setInterval(refresh, POLL_MS);
+ return () => clearInterval(t);
+ }, [refresh]);
+
+ const [unloadModel, unloadingModel] = useAsyncAction(async (modelId) => {
+ await unloadOllamaModel(modelId);
+ toast.success(`Unloaded ${modelId}`);
+ await refresh();
+ });
+ const [unloadKokoro, unloadingKokoro] = useAsyncAction(async () => {
+ const result = await unloadKokoroTts();
+ toast.success(result?.unloaded ? 'Kokoro TTS unloaded' : 'Kokoro was not loaded');
+ await refresh();
+ });
+ const [stopWhisper, stoppingWhisper] = useAsyncAction(async () => {
+ await controlWhisper('stop');
+ toast.success('Whisper stopped');
+ await refresh();
+ });
+ const [startWhisper, startingWhisper] = useAsyncAction(async () => {
+ await controlWhisper('start');
+ toast.success('Whisper started');
+ await refresh();
+ });
+ const [freeAll, freeingAll] = useAsyncAction(async () => {
+ // Fan out in parallel — the operations don't depend on each other and
+ // doing them serially would visibly stall on whisper's PM2-delete step.
+ // Per-step errors get swallowed here because freeAll is the "best effort"
+ // path; refresh() then shows what actually got freed. Per-step toasts
+ // would also stack four-deep on success which is just noise.
+ const results = await Promise.allSettled([
+ ...loadedOllama.map((m) => unloadOllamaModel(m.id)),
+ whisperRunning ? controlWhisper('stop') : Promise.resolve(),
+ ttsState.state !== 'lazy' ? unloadKokoroTts() : Promise.resolve(),
+ ]);
+ const failed = results.filter((r) => r.status === 'rejected').length;
+ if (failed) toast.error(`Freed most resources — ${failed} action(s) failed`);
+ else toast.success('Freed all memory-resident models');
+ await refresh();
+ });
+
+ if (loading) {
+ return (
+ <div className="bg-port-card border border-port-border rounded p-3 mb-4">
+ <div className="flex items-center gap-2 text-sm text-gray-400">
+ <BrailleSpinner /> Loading memory status…
+ </div>
+ </div>
+ );
+ }
+
+ const anythingLoaded = loadedOllama.length > 0 || whisperRunning || ttsState.state !== 'lazy';
+ const anyActionRunning =
+ unloadingModel || unloadingKokoro || stoppingWhisper || startingWhisper || freeingAll;
+
+ return (
+ <div className="bg-port-card border border-port-border rounded mb-4">
+ <div className="flex items-center justify-between px-3 py-2 border-b border-port-border">
+ <div>
+ <div className="text-sm font-semibold text-gray-200">Memory Management</div>
+ <div className="text-xs text-gray-500">
+ Free unified memory before running large diffusion / video models
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={refresh}
+ disabled={anyActionRunning}
+ className={`${btnClass} text-gray-400 hover:text-gray-200 hover:bg-port-border/40`}
+ title={`Last refreshed ${Math.max(0, Math.floor((Date.now() - lastFetched) / 1000))}s ago`}
+ >
+ <RefreshCw className="w-3 h-3" />
+ Refresh
+ </button>
+ <button
+ type="button"
+ onClick={freeAll}
+ disabled={!anythingLoaded || anyActionRunning}
+ className={`${btnClass} text-port-warning border border-port-warning/50 hover:bg-port-warning/10`}
+ >
+ <Trash2 className="w-3 h-3" />
+ Free everything
+ </button>
+ </div>
+ </div>
+
+ {loadedOllama.length === 0 && !whisperRunning && ttsState.state === 'lazy' ? (
+ <div className="px-3 py-3 text-xs text-gray-500 italic">
+ Nothing memory-resident — full unified memory is available for diffusion.
+ </div>
+ ) : (
+ <div>
+ {loadedOllama.map((m) => (
+ <Row
+ key={`ollama:${m.id}`}
+ icon={Cpu}
+ title={m.name}
+ subtitle="Ollama"
+ status={formatBytes(m.sizeVram ?? m.size ?? 0)}
+ action={
+ <button
+ type="button"
+ onClick={() => unloadModel(m.id)}
+ disabled={anyActionRunning}
+ className={`${btnClass} text-gray-300 border border-port-border hover:bg-port-border/40`}
+ >
+ Unload
+ </button>
+ }
+ danger
+ />
+ ))}
+ {whisperRunning && (
+ <Row
+ icon={Mic}
+ title="Whisper STT"
+ subtitle="PM2 process portos-whisper — voice transcription"
+ status="running"
+ action={
+ <button
+ type="button"
+ onClick={stopWhisper}
+ disabled={anyActionRunning}
+ className={`${btnClass} text-gray-300 border border-port-border hover:bg-port-border/40`}
+ >
+ <PowerOff className="w-3 h-3" />
+ Stop
+ </button>
+ }
+ danger
+ />
+ )}
+ {ttsState.state !== 'lazy' && (
+ <Row
+ icon={Volume2}
+ title="Kokoro TTS"
+ subtitle={ttsState.loadedKey || 'kokoro-js ONNX in-process'}
+ status={ttsState.state === 'loading' ? 'loading…' : 'loaded'}
+ action={
+ <button
+ type="button"
+ onClick={unloadKokoro}
+ disabled={anyActionRunning || ttsState.state === 'loading'}
+ className={`${btnClass} text-gray-300 border border-port-border hover:bg-port-border/40`}
+ >
+ Unload
+ </button>
+ }
+ danger
+ />
+ )}
+ </div>
+ )}
+
+ {!whisperRunning && (
+ <div className="px-3 py-2 border-t border-port-border/50 flex items-center gap-2 text-xs text-gray-500">
+ <AlertTriangle className="w-3 h-3 text-port-warning shrink-0" />
+ <span className="flex-1">Whisper is stopped — voice transcription is offline.</span>
+ <button
+ type="button"
+ onClick={startWhisper}
+ disabled={anyActionRunning}
+ className={`${btnClass} text-gray-300 border border-port-border hover:bg-port-border/40`}
+ >
+ <Power className="w-3 h-3" />
+ Start Whisper
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index 8acc39dbbb..79c1b3d2e6 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -40,3 +40,14 @@ export const switchLocalLlmBackend = (to) =>
// 'copy' makes an independent duplicate. Never changes the default backend.
export const migrateLocalLlmBackend = (to, mode = 'link') =>
request('/local-llm/migrate', { method: 'POST', body: JSON.stringify({ to, mode }) });
+
+// Memory-management — models currently resident in VRAM/unified memory.
+// Used by the Memory Management panel to show what's eating space before
+// kicking off a big diffusion render.
+export const getLoadedLlmModels = () => request('/local-llm/loaded');
+
+// Force Ollama to evict a model immediately. LM Studio has its own
+// /api/lmstudio/unload endpoint (see apiCore default export usage in
+// LocalLlmTab) — we don't proxy it through this module.
+export const unloadOllamaModel = (modelId) =>
+ request('/local-llm/unload', { method: 'POST', body: JSON.stringify({ backend: 'ollama', modelId }) });
diff --git a/client/src/services/apiVoice.js b/client/src/services/apiVoice.js
index 125d9e71be..c6dc91793a 100644
--- a/client/src/services/apiVoice.js
+++ b/client/src/services/apiVoice.js
@@ -16,3 +16,9 @@ export const testTts = (text, voice, engine) => {
if (engine) body.engine = engine;
return api.post('/voice/test', body, { responseType: 'arraybuffer', silent: true });
};
+
+// Memory-management — Kokoro residency + unload, Whisper transient stop/start.
+// See MemoryManagement.jsx for the only consumer.
+export const getTtsStatus = () => api.get('/voice/tts/status');
+export const unloadKokoroTts = () => api.post('/voice/tts/unload', {});
+export const controlWhisper = (action) => api.post('/voice/whisper', { action });
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index 5b0264935a..087316c0ed 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -25,6 +25,7 @@ import { searchHuggingFaceModels } from '../services/huggingFaceCatalog.js'
import {
getStatus, listModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend, upgradeBackend, controlOllamaServer
} from '../services/localLlm.js'
+import { getLoadedModels as getLoadedOllamaModels, unloadModel as unloadOllamaModel } from '../services/ollamaManager.js'
const router = Router()
@@ -186,4 +187,26 @@ router.post('/migrate', asyncHandler(async (req, res) => {
res.json(result)
}))
+// GET /api/local-llm/loaded — models currently resident in memory.
+// Distinct from /catalog (disk-installed) — only flags what's eating VRAM
+// right now so the Memory Management panel can show what to unload before
+// kicking off a big diffusion render.
+router.get('/loaded', asyncHandler(async (req, res) => {
+ const loaded = await getLoadedOllamaModels()
+ res.json({ ollama: loaded })
+}))
+
+// POST /api/local-llm/unload — body: { backend: 'ollama', modelId }.
+// Forces Ollama to evict the named model immediately (`keep_alive: 0`).
+// LM Studio's unload lives at POST /api/lmstudio/unload — we don't proxy
+// it here to keep each backend's quirks behind its own router.
+router.post('/unload', asyncHandler(async (req, res) => {
+ const { backend, modelId } = req.body || {}
+ if (backend !== 'ollama') return res.status(400).json({ error: 'backend must be "ollama" (use /api/lmstudio/unload for LM Studio)' })
+ if (typeof modelId !== 'string' || modelId.length === 0) return res.status(400).json({ error: 'modelId is required' })
+ const result = await unloadOllamaModel(modelId)
+ if (!result.unloaded) return res.status(502).json({ error: result.reason || 'unload failed', modelId })
+ res.json({ success: true, ...result })
+}))
+
export default router
diff --git a/server/routes/voice.js b/server/routes/voice.js
index 46e2a797e7..d03cb19780 100644
--- a/server/routes/voice.js
+++ b/server/routes/voice.js
@@ -10,8 +10,9 @@ import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { getVoiceConfig, updateVoiceConfig } from '../services/voice/config.js';
import { checkAll, invalidateHealthCache } from '../services/voice/health.js';
-import { reconcile, verifyBinaries, verifyModels, downloadPiperVoice } from '../services/voice/bootstrap.js';
+import { reconcile, verifyBinaries, verifyModels, downloadPiperVoice, startWhisper, stopWhisper } from '../services/voice/bootstrap.js';
import { synthesize, listVoices, VALID_ENGINES } from '../services/voice/tts.js';
+import { readyState as kokoroReadyState, unloadKokoro, loadedModelKey as kokoroLoadedKey } from '../services/voice/tts-kokoro.js';
import { findPiperVoice } from '../services/voice/piper-voices.js';
import { speakProactive, HHMM_RE, MAX_PROACTIVE_TEXT_LEN } from '../services/voice/proactiveSpeech.js';
@@ -230,4 +231,42 @@ router.post('/speak', asyncHandler(async (req, res) => {
res.json(result);
}));
+// GET /api/voice/tts/status — Kokoro residency snapshot (lazy/loading/loaded
+// plus the model key currently cached). Piper has no resident model — it
+// spawns per-synthesis — so it's not represented here.
+router.get('/tts/status', asyncHandler(async (_req, res) => {
+ res.json({
+ kokoro: {
+ state: kokoroReadyState(),
+ loadedKey: kokoroLoadedKey(),
+ },
+ });
+}));
+
+// POST /api/voice/tts/unload — drop the cached Kokoro instance so unified
+// memory can host a big diffusion model instead. The next synthesizeKokoro
+// call pays the ~2–3s cold start. No-op if nothing was loaded.
+router.post('/tts/unload', asyncHandler(async (_req, res) => {
+ res.json(unloadKokoro());
+}));
+
+// POST /api/voice/whisper — body: { action: 'stop' | 'start' }.
+// Memory-management lever: stop frees ~1.5 GB of whisper.cpp + GGML model
+// weights for the duration. Start re-binds the PM2 process using current
+// voice.stt config. Distinct from /api/voice/config (which persists enabled
+// state) — this is a transient stop, voice.enabled stays true.
+router.post('/whisper', asyncHandler(async (req, res) => {
+ const action = (req.body?.action || '').toString();
+ if (action !== 'start' && action !== 'stop') {
+ return res.status(400).json({ error: 'action must be "start" or "stop"' });
+ }
+ if (action === 'stop') {
+ await stopWhisper();
+ return res.json({ success: true, action: 'stop' });
+ }
+ const cfg = await getVoiceConfig();
+ const result = await startWhisper(cfg);
+ res.json({ success: true, action: 'start', ...result });
+}));
+
export default router;
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index 603fc4f61e..77cddae7d3 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -411,6 +411,48 @@ async function getVersion() {
return data?.version || null
}
+/**
+ * List models currently loaded into VRAM/unified memory (Ollama's `/api/ps`).
+ * Distinct from getInstalledModels(): a model on disk doesn't occupy memory
+ * until it's referenced by a request.
+ * @returns {Promise<Array<{ id, name, size, sizeVram, expiresAt }>>}
+ */
+async function getLoadedModels() {
+ if (!(await checkOllamaAvailable())) return []
+ const data = await ollamaRequest('/api/ps').catch(() => null)
+ if (!Array.isArray(data?.models)) return []
+ return data.models.map((m) => ({
+ id: m.name || m.model,
+ name: m.name || m.model,
+ size: m.size ?? null,
+ sizeVram: m.size_vram ?? null,
+ expiresAt: m.expires_at || null
+ }))
+}
+
+/**
+ * Force Ollama to evict a specific model from memory immediately.
+ * Uses the documented `keep_alive: 0` trick — issuing any generate/chat
+ * request with keep_alive=0 expires the model the moment the request
+ * resolves. We send an empty prompt so no tokens are generated.
+ * @returns {Promise<{ unloaded: true, model: string } | { unloaded: false, reason: string }>}
+ */
+async function unloadModel(modelName) {
+ if (typeof modelName !== 'string' || modelName.length === 0) {
+ return { unloaded: false, reason: 'missing model name' }
+ }
+ if (!(await checkOllamaAvailable())) {
+ return { unloaded: false, reason: 'Ollama unreachable' }
+ }
+ const body = { model: modelName, prompt: '', keep_alive: 0, stream: false }
+ const result = await ollamaRequest('/api/generate', { method: 'POST', body }).catch((err) => ({ _err: err }))
+ if (result && result._err) {
+ return { unloaded: false, reason: result._err.message || 'request failed' }
+ }
+ console.log(`🧹 ollama: unloaded ${modelName} (keep_alive=0)`)
+ return { unloaded: true, model: modelName }
+}
+
/**
* Pull a model, streaming progress. Resolves once the pull finishes.
* During a transient-error backoff the callback fires with `retrying: true`
@@ -735,6 +777,8 @@ async function getStatus(forceRefresh = false) {
export {
getInstalledModels,
+ getLoadedModels,
+ unloadModel,
pullModel,
deleteModel,
getStatus,
diff --git a/server/services/voice/tts-kokoro.js b/server/services/voice/tts-kokoro.js
index 4cd29a0f24..4395406eb5 100644
--- a/server/services/voice/tts-kokoro.js
+++ b/server/services/voice/tts-kokoro.js
@@ -78,3 +78,19 @@ export const readyState = () => {
return loaded ? 'loaded' : 'loading';
};
export const isReady = () => loaded;
+export const loadedModelKey = () => loadedKey;
+
+// Drop the cached TTS instance so its ONNX weights can be GC'd. Next
+// synthesizeKokoro() call will pay the ~2–3s cold-start tax. Idempotent —
+// safe to call when nothing is loaded.
+//
+// Surface the post-unload state so the API caller can tell the difference
+// between "was loaded, now released" and "wasn't loaded to begin with".
+export const unloadKokoro = () => {
+ const wasLoaded = modelPromise !== null;
+ modelPromise = null;
+ loadedKey = null;
+ loaded = false;
+ if (wasLoaded) console.log('🧹 kokoro: unloaded (next synthesis will reload)');
+ return { unloaded: wasLoaded };
+};