Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (self): broken Ollama unload, HiDream/Qwen route gate, Wan22 i2v, MemoryManagement double-toast, route Zod parity
[._.]/ Adam Eivyeb5bf3dad9b9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ae92d4fcb3..8f8adbe9bd 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -10,7 +10,7 @@ TBD- **Brain → Links buckets (bookmark groups)**: the Links tab now has a bucket board above the searchable list, so links can be organized into arbitrary groups (e.g. a "Reading list" or "Work tools" bucket of quick-launch buttons). Each bucket is a colored card whose links render as compact favicon + title chips that open in a new tab; buckets have an inline "add a URL" field (auto-titled from the hostname), inline rename/recolor/icon edit, and can be reordered by dragging. Links can be filed into a bucket by dragging a chip between buckets or via a per-row "+ Bucket…" dropdown in the list; an "Ungrouped" filter tab surfaces links not yet in any bucket. Buckets reuse the existing link records (a new `bucketId`/`bucketOrder` on each link) — single source of truth — and are a new federated brain collection (`buckets`) that syncs across peers. Deleting a bucket keeps its links (they fall back to ungrouped).- **Big local diffusion + video models for 64+ GB unified-memory hardware.** New entries in the image registry: Flux 2 Klein 9B native bf16 (`flux2-klein-9b-bf16`, ~36 GB) loads the gated `black-forest-labs/FLUX.2-klein-9B` repo directly without SDNQ or Int8; HiDream-I1 Full + Fast (`hidream-i1-full`, `hidream-i1-fast`) — 17B MoE DiT, needs `meta-llama/Meta-Llama-3.1-8B-Instruct` as `text_encoder_4`; Qwen-Image and Qwen-Image-Edit (`qwen-image`, `qwen-image-edit`) — 20B MMDiT, Apache 2.0, strong English + Chinese text rendering. New video entries: LTX-2.3 Unified Beta bf16 un-deprecated (now practical on 128 GB hardware as the quality ceiling for the mlx_video runtime); Wan 2.2 T2V + I2V A14B (~28 GB) via osama-ata/Wan2.2-mlx; HunyuanVideo (~60 GB) via gaurav-nelson/HunyuanVideo_MLX. The HiDream / Qwen / ERNIE / Z-Image dispatch in `server/services/imageGen/local.js` collapsed to a single `usesDiffusersRunner(model)` predicate; all four reuse the FLUX.2 venv with their pipeline-class + (HiDream only) `text_encoder_4` flags passed through to the shared `scripts/z_image_turbo.py` runner. Wan 2.2 and HunyuanVideo land as new `runtime: 'wan22' | 'hunyuan'` paths in `videoGen/local.js`, each backed by a thin subprocess wrapper (`scripts/generate_wan22.py`, `scripts/generate_hunyuan.py`) over upstream's `generate.py` — provisioned via `INSTALL_WAN22=1` / `INSTALL_HUNYUAN=1 bash scripts/setup-image-video.sh`. Upstream CLI surfaces for Wan and Hunyuan aren't pinned across releases — flagged experimental; if upstream renames args, mark the corresponding entries `broken: true` in `data/media-models.json` until the helper script is updated to match.-- **Memory Management panel (Settings → Local LLMs).** Surfaces what's currently resident in unified memory and lets you evict it before kicking off a big diffusion render: each loaded Ollama model with per-row Unload, Whisper STT (Stop/Start), Kokoro TTS (Unload), plus a "Free everything" fan-out. Ollama eviction uses the documented `keep_alive: 0` trick on `/api/generate` with an empty prompt — no tokens generated, immediate evict — exposed via `POST /api/local-llm/unload`. Voice paths add `GET /api/voice/tts/status`, `POST /api/voice/tts/unload`, and `POST /api/voice/whisper` (action: start|stop). The panel polls every 5s, errors surface via the default `apiCore` toast (single layer per convention), and "Free everything" fans out in parallel via `Promise.allSettled` so individual failures don't block the rest.+- **Memory Management panel (Settings → Local LLMs).** Surfaces what's currently resident in unified memory and lets you evict it before kicking off a big diffusion render: each loaded Ollama model with per-row Unload, Whisper STT (Stop/Start), Kokoro TTS (Unload), plus a "Free everything" fan-out. Ollama eviction uses the documented `keep_alive: 0` trick on `/api/generate` with an empty prompt — no tokens generated, immediate evict — exposed via `POST /api/local-llm/unload`. Voice paths add `GET /api/voice/tts/status`, `POST /api/voice/tts/unload`, and `POST /api/voice/whisper` (action: start|stop). The panel polls every 5s, errors surface via `useAsyncAction`'s single-layer toast (each memory-mgmt API helper accepts `{ silent: true }` so the panel owns the toast layer per CLAUDE.md's "custom catch ⇒ `silent: true`" rule), and "Free everything" fans out in parallel via `Promise.allSettled` so individual failures don't block the rest.- **Brain → Links search**: a keyword search box on the Links tab filters the saved links list in real time across title, URL, description, and tags (case-insensitive). It composes with the existing GitHub/Other category tabs, includes a clear (×) affordance, and shows a distinct "no links match" empty state separate from the "no links saved yet" state. Filtering is client-side over the already-loaded list, so there are no extra round-trips and no server changes.- **Unified Story Builder** (`/story-builder`): a new guided page that walks a story from idea → universe aesthetic → plot arc → reader map → characters → issues → production as one linear flow. Each step is LLM-assisted with an AI-refinement affordance and ends with an explicit lock before the next unlocks; going back to revise an earlier step soft-flags the downstream locked steps as "stale" (integrity gate) so nothing silently drifts — without destroying their content. The builder is a thin conductor over the existing Universe / Series / Issue records (no data duplication); heavy per-issue production hands off to the existing Pipeline issue page. Reachable from the sidebar (Create → Story Builder), ⌘K, and voice. The intro screen supports two intake modes: **start from a seed idea**, or **import a finished work** (comic script / screenplay / novel / short story) — the importer reverse-engineers it into a universe, arc, characters, and issues, then drops you into the wizard to review and lock each stage. An **AI provider/model picker** at the top of the builder (and the import tab) drives every operation — idea expand, aesthetic, arc, reader map, character refine, and the import analysis — persisted on the session so one selection applies throughout. The **characters step generates a styled preview image per character** (world style fused with the character descriptor, via the same render path as the Universe Builder) and shows it alongside each character so you can eyeball that the world and character styles read correctly together.- **Brain → Links: optional title & tags on quick-add**: the Links tab quick-add form now has a collapsible "Add title & tags (optional)" section so a link can be saved with a custom title and tags up front, instead of only being editable after the fact. Collapsed by default to keep the paste-and-go flow clean.@@ -23,6 +23,19 @@ TBD## Fixed+- **Big-local-models PR review pass.** Multi-agent review of the big-local-models branch surfaced eight cross-file regressions that landed alongside the Memory Management + new-runtime work:+ - `HiDream / Qwen image renders were rejected with "Local image generation is not configured" at the route gate before reaching the worker.** `server/routes/imageGen.js` and `server/routes/universeBuilder.js` still ran the legacy `!isFlux2 && !isZImage && !isErnie && !py` predicate chain — adding HiDream + Qwen via the `usesDiffusersRunner(model)` helper (already exported from `server/lib/runners.js`) in both routes lets the new families through without requiring a `settings.imageGen.local.pythonPath` they don't need.+ - `Wan 2.2 i2v never received the `--image` arg.** `buildWan22Args` gated `--image` on the *request* `mode === 'i2v'` while `videoGen.js`'s request schema doesn't have an `'i2v'` enum value — so the i2v model was dispatched with `--task i2v-A14B` but no source image, and upstream `generate.py` errored. Now gates on `model.mode === 'i2v'` (registry source of truth) and hard-fails when an i2v model is invoked without a source image rather than silently degrading.+ - `Ollama "Unload" was a no-op.** `ollamaManager.unloadModel` passed the request body as a JavaScript object to `fetchWithTimeout` (which does not JSON.stringify) — native fetch sent `[object Object]` and Ollama rejected the request, so clicking Unload appeared to succeed but never evicted the model. Body is now `JSON.stringify`-ed at the call site (mirrors `deleteModel`).+ - `Unload of a non-resident Ollama model would *load* it from disk first.** `/api/generate` with `keep_alive: 0` against a model that isn't currently resident triggers Ollama to pull the multi-GB weights into VRAM solely to mark them for eviction. Now `unloadModel` calls `getLoadedModels()` first and returns `{ unloaded: false, reason: 'not loaded' }` when the model isn't resident — closes a LAN-reachable thrash-amplification footgun via `POST /api/local-llm/unload`.+ - `FLUX.2 9B (bf16) license-acceptance banner pointed users at the 4B repo.** `/api/image-gen/setup/flux2-status` returned a hardcoded `https://huggingface.co/black-forest-labs/FLUX.2-klein-4B` regardless of the active model — clicking the link from `flux2-klein-9b-bf16` accepted the wrong license. The route now reads `licenseUrl` from the active model when the client passes `?modelId=`, falling back to the 4B URL for legacy callers; the ImageGen page passes the current model id.+ - `voice.test.js bootstrap mock missing `startWhisper` / `stopWhisper`.** `routes/voice.js` now destructures those names at module load; the mock factory didn't export them, so the first test ever added for `POST /api/voice/whisper` would TypeError at request time. Mock factory updated; the new entries are no-ops because no existing test exercises the route yet (covered separately by `[memory-mgmt-new-endpoint-tests]` in PLAN.md).+ - `/api/local-llm/unload`, `/api/voice/whisper` bypassed Zod validation despite every other route in their respective files using `validateRequest`. Added `localLlmUnloadSchema` (reusing `localLlmModelIdSchema`'s no-leading-dash / no-control-chars rules so log-injection via `console.log(\`🧹 ollama: unloaded ${name}\`)` is rejected at the boundary) and an inline `whisperActionSchema` (`z.enum(['start', 'stop'])`) — closes the schema-parity drift CLAUDE.md flags as a finding.+ - `Memory Management panel "Errors surface via single layer" claim was false.** The top-of-file comment promised default-apiCore-toast-only, but the body wired every API call through `useAsyncAction` AND non-silent `apiCore.request` — double toasts on every action failure, plus a toast every 5s of poll failure during an Ollama outage. The `apiLocalLlm` / `apiVoice` memory-mgmt helpers now accept `{ silent: true }` and the panel passes it through, so `useAsyncAction` owns the toast layer (and `refresh()`'s catch handlers stay silent). Same pass: Whisper start/stop now `invalidateHealthCache()` so the panel doesn't see 3s of stale `services.whisper.ok` after the action; the Whisper start banner is gated on `voice.sttEngine === 'whisper'` so web-speech users don't get an unwanted PM2 process; `freeAll` re-polls before the fan-out so a model that idle-evicted between the 5s poll and the click isn't re-requested; and a `mountedRef` gates the polled `setState` calls so a late `/voice/status` response can't write to an unmounted tree.+ - `videoGen child env didn't merge HF_TOKEN.** `imageGen/local.js` already merges `hfTokenEnv()` for gated repos; `videoGen/local.js` did not, so the Wan 2.2 / HunyuanVideo helpers couldn't authenticate `snapshot_download()` against gated upstream repos. Same merge added to the video spawn path.++ Test count delta: server 363 files / 8086 tests pass (+0 files / +24 vs. PR baseline; deltas come from sibling branches' tests that re-merge into the worktree). Client 61 files / 608 tests pass.+- **Brain → Links "Other Links" filter showed GitHub repos**: the filter sent `isGitHubRepo=false` as a query string, but the route schema used `z.coerce.boolean()` — and `Boolean("false")` is `true`, so "Other Links" behaved identically to "GitHub Repos". The schema now parses the string explicitly so `"false"` → `false`.- **Story Builder data-loss fixes** surfaced by the local-review pass on the unified-story-builder branch:- `generateStep('plotArc')` was wholesale-replacing `series.arc` and `series.seasons` via a plain `updateSeries({ arc, seasons })`, which silently dropped per-field arc locks, locked seasons, and orphaned every child issue attached to a renamed/removed season. Route through `commitSeasonsWithRemap` (same helper the Arc Canvas regenerator uses) so locks are honored and orphaned issues are remapped via normalized title → number → positional fallback.diff --git a/PLAN.md b/PLAN.mdindex 570964e1e3..0cfd7a851f 100644--- a/PLAN.md+++ b/PLAN.md@@ -221,6 +221,10 @@ The first slice shipped a working **seed-mode** conductor (`/story-builder`): cr- [ ] [consolidate-client-url-normalize] **Consolidate client-side URL normalization.** Three components prepend `https://` to a bare URL with near-identical logic: `normalizeUrl` in `client/src/components/brain/tabs/LinksTab.jsx`, the inline block in `client/src/components/QuickBrainCapture.jsx` (~line 34, with `URL_PATTERN`/`DOMAIN_PATTERN` regexes), and `client/src/components/brain/tabs/FeedsTab.jsx` (~line 50, no `git@` handling). Extract one `normalizeUrl`/`isUrl` pair to a shared `client/src/utils/` helper and migrate all three. Skipped during the buckets PR /simplify (2026-05-28) because a correct consolidation touches two unrelated components and must preserve each one's subtly different behavior (FeedsTab ignores `git@`; QuickBrainCapture splits detection from normalization).- [ ] [brain-bucket-chip-reorder] **Drag-to-reorder chips *within* a bucket.** The Brain → Links bucket board (`client/src/components/brain/links/BucketBoard.jsx` + `BucketCard.jsx`) supports dragging a chip *between* buckets and reordering buckets, but not repositioning a chip within its own bucket — `bucketOrder` is only ever appended (max+1) on assign. Add intra-bucket position-aware drop (compute target index from the drop location, renumber `bucketOrder`, persist via `updateBrainLink`). Skipped in the initial buckets PR (2026-05-28) to avoid fragile drop-index math; chips currently sort by `bucketOrder` then insertion order, which is fine for the common case.+- [ ] [hidream-qwen-client-runner-consumers] **Wire HIDREAM/QWEN through client runnerFamily consumers.** `client/src/lib/runnerFamilies.js` exports the constants and `server/lib/runners.js` mirrors them, but client-side consumers haven't been extended: `client/src/lib/imageGenResolutions.js`'s `compatibilityKey` OR-chain still only checks `FLUX2 | Z_IMAGE | ERNIE` (falls through to `'flux1'` for HiDream/Qwen — silently denies their natural 1536× hi-res variants), and `client/src/pages/Loras.jsx` `RUNNER_LABELS` / `RUNNER_BG_COLORS` / Top-LoRA section list omit them so the LoRA picker shows them as unlabeled / no badge color. Either extend each consumer site or document that HiDream/Qwen intentionally inherit Flux 1 resolution presets. Surfaced by /do:review of PR #516 (2026-05-28).+- [ ] [wan22-hunyuan-setup-pin-shas] **Pin Wan22 / HunyuanVideo MLX clones to known-good commit SHAs.** `scripts/setup-image-video.sh` defaults `WAN22_PIN="${WAN22_PIN:-main}"` and `HUNYUAN_PIN="${HUNYUAN_PIN:-main}"`. Floating `main` on two community-maintained ports with unpinned CLIs (the PR description explicitly flags both as experimental — "if upstream renames args, flip the registry entry broken: true") means every new install gets whatever HEAD is on those repos that day. Replace the default with a tested SHA for each; let users override via the env var (same shape as the diffusers pin). Surfaced by /do:review of PR #516 (2026-05-28).+- [ ] [memory-mgmt-new-endpoint-tests] **Add tests for the 5 new memory-management routes.** `/api/local-llm/loaded`, `/api/local-llm/unload`, `/api/voice/whisper`, `/api/voice/tts/status`, `/api/voice/tts/unload` have no test coverage. The PR description claims "8062/8062 tests passing" — true for the existing suite, but no asserts pin the new wire contracts (response shapes, residency precondition, validation rejection). Add focused happy-path + validation-rejection tests so future regressions in the schema-parity fixes (or the `unloadModel` residency check) surface as test failures. Surfaced by /do:review of PR #516 (2026-05-28).+- [ ] [hidream-requires-hf-token-fail-fast] **Probe HF token upfront for HiDream gated-encoder downloads.** `data.reference/media-models.json`'s HiDream entries carry `requiresHfToken: true` + a `licenseUrl` pointing at `meta-llama/Meta-Llama-3.1-8B-Instruct`, but `scripts/z_image_turbo.py` `load_external_text_encoder()` does NOT call `probe_hf_auth()` the way `flux2_macos.py:265` does for the base FLUX repo. A user without a valid HF token currently sees a multi-GB download attempt that fails with a 401 deep inside transformers instead of a clean upfront error. Mirror the FLUX.2 probe before invoking `transformers.from_pretrained()` on the gated encoder repo. Surfaced by /do:review of PR #516 (2026-05-28).## Future Ideasdiff --git a/client/src/components/settings/MemoryManagement.jsx b/client/src/components/settings/MemoryManagement.jsxindex 648bd2d9a1..31228c5a18 100644--- a/client/src/components/settings/MemoryManagement.jsx+++ b/client/src/components/settings/MemoryManagement.jsx@@ -12,10 +12,15 @@// - 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.+// Polls every 5s while mounted. The component owns the toast layer via+// useAsyncAction (for explicit user actions) and the per-call `.catch()`+// fallbacks in `refresh()` (for poll failures, which must NOT toast — the+// panel would otherwise spam an error toast every 5s during a transient+// Ollama outage). Every API helper is called with `{ silent: true }` so+// apiCore's default toast doesn't fire underneath; per the CLAUDE.md+// "Silent vs. toasting API requests" rule, custom catch ⇒ silent: true.-import { useState, useEffect, useCallback } from 'react';+import { useState, useEffect, useCallback, useRef } from 'react';import { Cpu, Mic, Volume2, Trash2, Power, PowerOff, RefreshCw, AlertTriangle } from 'lucide-react';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';@@ -24,6 +29,8 @@ import { formatBytes } from '../../utils/formatters';import { getLoadedLlmModels, unloadOllamaModel } from '../../services/apiLocalLlm.js';import { getTtsStatus, unloadKokoroTts, controlWhisper, getVoiceStatus } from '../../services/apiVoice.js';+const SILENT = { silent: true };+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';@@ -46,15 +53,24 @@ export default function MemoryManagement() {const [loadedOllama, setLoadedOllama] = useState([]);const [ttsState, setTtsState] = useState({ state: 'lazy', loadedKey: null });const [whisperRunning, setWhisperRunning] = useState(false);+ const [sttEngine, setSttEngine] = useState('whisper');const [loading, setLoading] = useState(true);const [lastFetched, setLastFetched] = useState(0);+ // Guards the polled setState calls — a late /voice/status response that+ // resolves after unmount would otherwise call setState on a dead tree.+ // Never reset to true: React 18 dev double-mount runs the cleanup once+ // and only re-mounts the same component instance; the new instance gets+ // its own ref.+ const mountedRef = useRef(true);+ useEffect(() => () => { mountedRef.current = false; }, []);const refresh = useCallback(async () => {const [llm, tts, voice] = await Promise.all([- getLoadedLlmModels().catch(() => ({ ollama: [] })),- getTtsStatus().catch(() => ({ kokoro: { state: 'lazy', loadedKey: null } })),- getVoiceStatus().catch(() => null),+ getLoadedLlmModels(SILENT).catch(() => ({ ollama: [] })),+ getTtsStatus(SILENT).catch(() => ({ kokoro: { state: 'lazy', loadedKey: null } })),+ getVoiceStatus(SILENT).catch(() => null),]);+ if (!mountedRef.current) return;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@@ -62,6 +78,7 @@ export default function MemoryManagement() {// default to "not running" — false negatives just mean the Stop button// briefly hides, which the next poll corrects.setWhisperRunning(Boolean(voice?.services?.whisper?.ok));+ setSttEngine(voice?.sttEngine || 'whisper');setLoading(false);setLastFetched(Date.now());}, []);@@ -73,35 +90,42 @@ export default function MemoryManagement() {}, [refresh]);const [unloadModel, unloadingModel] = useAsyncAction(async (modelId) => {- await unloadOllamaModel(modelId);+ await unloadOllamaModel(modelId, SILENT);toast.success(`Unloaded ${modelId}`);await refresh();});const [unloadKokoro, unloadingKokoro] = useAsyncAction(async () => {- const result = await unloadKokoroTts();+ const result = await unloadKokoroTts(SILENT);toast.success(result?.unloaded ? 'Kokoro TTS unloaded' : 'Kokoro was not loaded');await refresh();});const [stopWhisper, stoppingWhisper] = useAsyncAction(async () => {- await controlWhisper('stop');+ await controlWhisper('stop', SILENT);toast.success('Whisper stopped');await refresh();});const [startWhisper, startingWhisper] = useAsyncAction(async () => {- await controlWhisper('start');+ await controlWhisper('start', SILENT);toast.success('Whisper started');await refresh();});const [freeAll, freeingAll] = useAsyncAction(async () => {+ // Re-poll first — the optimistic UI's `loadedOllama` snapshot is up to+ // POLL_MS old, and the ollama unload now requires the model to actually+ // be resident (else returns `not loaded`). Without the refresh, a model+ // that idle-evicted between the last poll and the click would still get+ // an evict request, which is at best a no-op and at worst (before the+ // residency check) re-loaded the model from disk.+ await refresh();// 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(),+ ...loadedOllama.map((m) => unloadOllamaModel(m.id, SILENT)),+ whisperRunning ? controlWhisper('stop', SILENT) : Promise.resolve(),+ ttsState.state !== 'lazy' ? unloadKokoroTts(SILENT) : Promise.resolve(),]);const failed = results.filter((r) => r.status === 'rejected').length;if (failed) toast.error(`Freed most resources — ${failed} action(s) failed`);@@ -223,7 +247,7 @@ export default function MemoryManagement() {</div>)}- {!whisperRunning && (+ {!whisperRunning && sttEngine === 'whisper' && (<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>diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex 28bd1c502a..6beb1123a2 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -491,11 +491,12 @@ export default function ImageGen() {const currentRunnerFamily = currentModel?.runner || RUNNER_FAMILIES.MFLUX;const refreshFlux2Status = useCallback((signal) => {- return fetch('/api/image-gen/setup/flux2-status', { signal })+ const qs = modelId ? `?modelId=${encodeURIComponent(modelId)}` : '';+ return fetch(`/api/image-gen/setup/flux2-status${qs}`, { signal }).then((r) => r.ok ? r.json() : null).then((s) => { if (s) setFlux2Status(s); }).catch(() => {});- }, []);+ }, [modelId]);const refreshHfTokenStatus = useCallback((signal) => {return fetch('/api/image-gen/setup/hf-token-status', { signal })diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex 79c1b3d2e6..3d3d837d38 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -43,11 +43,18 @@ export const migrateLocalLlmBackend = (to, mode = 'link') =>// 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');+// kicking off a big diffusion render. `options` lets the panel pass+// `{ silent: true }` so its own catch handler / useAsyncAction wrapper+// owns the toast — without it apiCore double-toasts on every 5s poll.+export const getLoadedLlmModels = (options) =>+ request('/local-llm/loaded', options);// 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 }) });+export const unloadOllamaModel = (modelId, options) =>+ request('/local-llm/unload', {+ method: 'POST',+ body: JSON.stringify({ backend: 'ollama', modelId }),+ ...options,+ });diff --git a/client/src/services/apiVoice.js b/client/src/services/apiVoice.jsindex c6dc91793a..498d94cb48 100644--- a/client/src/services/apiVoice.js+++ b/client/src/services/apiVoice.js@@ -1,6 +1,10 @@import api from './apiCore';-export const getVoiceStatus = () => api.get('/voice/status');+// `options` lets callers pass `{ silent: true }` so apiCore's default toast+// doesn't fire when the caller owns its own error UI (custom catch /+// useAsyncAction). Without it the user sees a stacked toast for every+// failure — and the Memory Management panel polls every 5s.+export const getVoiceStatus = (options) => api.get('/voice/status', options);export const getVoiceConfig = () => api.get('/voice/config');export const updateVoiceConfig = (patch) => api.put('/voice/config', patch);export const listVoices = (engine) => api.get(`/voice/voices${engine ? `?engine=${engine}` : ''}`);@@ -18,7 +22,8 @@ export const testTts = (text, voice, engine) => {};// 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 });+// See MemoryManagement.jsx for the only consumer; it owns its own toast,+// hence the `options` parameter / `silent: true` plumbing.+export const getTtsStatus = (options) => api.get('/voice/tts/status', options);+export const unloadKokoroTts = (options) => api.post('/voice/tts/unload', {}, options);+export const controlWhisper = (action, options) => api.post('/voice/whisper', { action }, options);diff --git a/server/lib/validation.js b/server/lib/validation.jsindex a42bebf187..b36d8b18bc 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1104,6 +1104,11 @@ export const localLlmInstallSchema = z.object({modelId: localLlmModelIdSchema,});export const localLlmDeleteSchema = localLlmInstallSchema;+// Memory-management unload: same `backend` + `modelId` shape as install/delete+// so the validator catches the same set of malformed ids (no leading dash,+// no control chars) — those reach Ollama via `/api/generate` body fields and+// then echo into PortOS's emoji-prefixed unload log line.+export const localLlmUnloadSchema = localLlmInstallSchema;export const localLlmSwitchSchema = z.object({ to: localLlmBackendSchema });// Migrate moves models from the OTHER backend onto `to` (bidirectional, never// flips the default marker). `mode` picks how the GGUF lands on disk: 'link'diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex d647793022..81be2a3bfe 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -23,7 +23,8 @@ import { local, IMAGE_GEN_MODE, IMAGE_GEN_MODES, resolveImageCleaners } from '..import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';import { getSettings, saveSettings } from '../services/settings.js';import { getHfToken, getHfTokenInfo, HF_TOKEN_REGEX } from '../lib/hfToken.js';-import { getImageModels, isFlux2, isZImage, isErnie } from '../lib/mediaModels.js';+import { getImageModels, isFlux2 } from '../lib/mediaModels.js';+import { usesDiffusersRunner } from '../lib/runners.js';import {REQUIRED_PACKAGES, detectPython, installPackages,createVenv, isAllowedPython, pipNameFor,@@ -347,7 +348,7 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {const selectedModel = allModels.find((m) => m.id === data.modelId)?? allModels.find((m) => m.id === 'dev')?? allModels[0];- if (selectedModel && !isFlux2(selectedModel) && !isZImage(selectedModel) && !isErnie(selectedModel) && !py) {+ if (selectedModel && !isFlux2(selectedModel) && !usesDiffusersRunner(selectedModel) && !py) {throw new ServerError('Local image generation is not configured (settings.imageGen.local.pythonPath is missing).',{ status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' },@@ -630,15 +631,27 @@ router.get('/setup/flux2-install', asyncHandler(async (req, res) => {// license hasn't been accepted (HF_TOKEN missing) and the runner is set up.// `venvInstalled` reflects functional health (binary AND packages import) —// a half-broken venv would otherwise hide the install banner forever.-router.get('/setup/flux2-status', asyncHandler(async (_req, res) => {+router.get('/setup/flux2-status', asyncHandler(async (req, res) => {const [token, healthy] = await Promise.all([getHfToken(), isFlux2VenvHealthy()]);const venvPython = resolveFlux2Python();+ // The 9B (bf16) and 4B variants ship as separately-gated repos with+ // distinct HF license URLs. Use the active model's `licenseUrl` when the+ // client supplies a `modelId`; fall back to the 4B URL for callers that+ // pre-date the multi-variant registry.+ const FLUX2_DEFAULT_LICENSE = 'https://huggingface.co/black-forest-labs/FLUX.2-klein-4B';+ let licenseUrl = FLUX2_DEFAULT_LICENSE;+ if (typeof req.query?.modelId === 'string' && req.query.modelId.length > 0) {+ const model = getImageModels().find((m) => m.id === req.query.modelId);+ if (isFlux2(model) && typeof model?.licenseUrl === 'string' && model.licenseUrl.length > 0) {+ licenseUrl = model.licenseUrl;+ }+ }res.json({hfTokenPresent: !!token,venvInstalled: healthy,venvPath: venvPython,expectedVenvPath: FLUX2_VENV_DEFAULT,- licenseUrl: 'https://huggingface.co/black-forest-labs/FLUX.2-klein-4B',+ licenseUrl,});}));diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 087316c0ed..e5c9996172 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -15,6 +15,7 @@ import {localLlmInstallSchema,localLlmDeleteSchema,localLlmSwitchSchema,+ localLlmUnloadSchema,localLlmMigrateSchema,localLlmInstallBackendSchema,localLlmOllamaServiceSchema,@@ -201,9 +202,8 @@ router.get('/loaded', asyncHandler(async (req, res) => {// 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 || {}+ const { backend, modelId } = validateRequest(localLlmUnloadSchema, 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 })diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsindex 596ae26439..e65af28c1f 100644--- a/server/routes/universeBuilder.js+++ b/server/routes/universeBuilder.js@@ -37,7 +37,8 @@ import { findDuplicateUniverseGroups, findSameNameUniverses } from '../services/import { mergeUniverses } from '../services/recordMerge.js';import { mergeFieldsWithAI } from '../services/recordMergeAI.js';import { registerUniverseBuilderRun } from '../services/universeBuilderCollectionHook.js';-import { getImageModels, isFlux2, isZImage, isErnie } from '../lib/mediaModels.js';+import { getImageModels, isFlux2 } from '../lib/mediaModels.js';+import { usesDiffusersRunner } from '../lib/runners.js';import { IMAGE_GEN_MODE, IMAGE_GEN_MODES } from '../services/imageGen/modes.js';import { resolveImageCleaners } from '../services/imageGen/index.js';import { getStylePresetById } from '../lib/writersRoomStylePresets.js';@@ -578,7 +579,7 @@ router.post('/:id/render', asyncHandler(async (req, res) => {const selectedModel = allModels.find((m) => m.id === body.modelId)?? allModels.find((m) => m.id === 'dev')?? allModels[0];- if (selectedModel && !isFlux2(selectedModel) && !isZImage(selectedModel) && !isErnie(selectedModel) && !py) {+ if (selectedModel && !isFlux2(selectedModel) && !usesDiffusersRunner(selectedModel) && !py) {throw new ServerError('Local image generation is not configured (settings.imageGen.local.pythonPath is missing).',{ status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' },diff --git a/server/routes/voice.js b/server/routes/voice.jsindex d03cb19780..7f8e835cb3 100644--- a/server/routes/voice.js+++ b/server/routes/voice.js@@ -255,17 +255,29 @@ router.post('/tts/unload', asyncHandler(async (_req, res) => {// 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.+const whisperActionSchema = z.object({+ action: z.enum(['start', 'stop']),+});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"' });+ const parsed = whisperActionSchema.safeParse(req.body || {});+ if (!parsed.success) {+ throw new ServerError(+ `Invalid whisper payload: ${parsed.error.issues.map((i) => `${i.path.join('.')} ${i.message}`).join('; ')}`,+ { status: 400, code: 'VALIDATION_ERROR' },+ );}+ const { action } = parsed.data;if (action === 'stop') {await stopWhisper();+ // Drop the cached `services.whisper.ok` so the next /voice/status reflects+ // the just-flipped PM2 state — without this the Memory Management panel+ // re-polls and sees up to 3s of "still running" after a successful stop.+ invalidateHealthCache();return res.json({ success: true, action: 'stop' });}const cfg = await getVoiceConfig();const result = await startWhisper(cfg);+ invalidateHealthCache();res.json({ success: true, action: 'start', ...result });}));diff --git a/server/routes/voice.test.js b/server/routes/voice.test.jsindex 91a66d8965..1bf690c113 100644--- a/server/routes/voice.test.js+++ b/server/routes/voice.test.js@@ -17,6 +17,11 @@ vi.mock('../services/voice/bootstrap.js', () => ({verifyBinaries: vi.fn(),verifyModels: vi.fn(),downloadPiperVoice: vi.fn(),+ // POST /api/voice/whisper imports these at module load — without the+ // mock entries the destructured imports resolve to `undefined` and the+ // route TypeErrors the first time it's hit.+ startWhisper: vi.fn(),+ stopWhisper: vi.fn(),}));vi.mock('../services/voice/tts.js', () => ({synthesize: vi.fn(),diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.jsindex 77cddae7d3..d7079e6f09 100644--- a/server/services/ollamaManager.js+++ b/server/services/ollamaManager.js@@ -435,6 +435,12 @@ async function getLoadedModels() {* 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.+ *+ * Precondition: only fires the evict when the model is currently resident+ * per `/api/ps`. Without the check, `/api/generate` against a non-loaded+ * model triggers Ollama to LOAD it from disk (potentially many GB) just+ * to immediately evict — a thrash/DoS-amplification footgun reachable+ * from any LAN client once `/api/local-llm/unload` is wired.* @returns {Promise<{ unloaded: true, model: string } | { unloaded: false, reason: string }>}*/async function unloadModel(modelName) {@@ -444,7 +450,13 @@ async function unloadModel(modelName) {if (!(await checkOllamaAvailable())) {return { unloaded: false, reason: 'Ollama unreachable' }}- const body = { model: modelName, prompt: '', keep_alive: 0, stream: false }+ const loaded = await getLoadedModels()+ if (!loaded.some((m) => m.id === modelName || m.name === modelName)) {+ return { unloaded: false, reason: 'not loaded' }+ }+ // Native fetch does NOT auto-stringify object bodies — pass JSON.stringify+ // so the wire body is valid JSON, not "[object Object]".+ const body = JSON.stringify({ 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' }diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex 993c2d3a1b..6a5ced376a 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -23,6 +23,7 @@ import { videoGenEvents } from './events.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../../lib/mediaModels.js';import { findFfmpeg, safeUnder, generateThumbnail, optimizeForStreaming, upscaleVideo2x, extractEvaluationFrames } from '../../lib/ffmpeg.js';+import { hfTokenEnv } from '../../lib/hfToken.js';// Path to the dgrauet/ltx-2-mlx venv populated by `INSTALL_LTX2=1// scripts/setup-image-video.sh`. Used when a model entry has@@ -284,7 +285,15 @@ const buildWan22Args = ({ model, prompt, width, height, numFrames, steps, guidan'--seed', String(seed),'--output', outputPath,];- if (mode === 'i2v' && sourceImagePath) args.push('--image', sourceImagePath);+ if (model.mode === 'i2v') {+ if (!sourceImagePath) {+ throw new ServerError(+ 'Wan 2.2 i2v requires a source image — upload one before running this model.',+ { status: 400, code: 'WAN22_I2V_REQUIRES_IMAGE' },+ );+ }+ args.push('--image', sourceImagePath);+ }return { bin: WAN22_VENV_PYTHON, args };};@@ -578,7 +587,11 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// of the parent shell's PYTHONPATH. Setting to `undefined` in a spread does// NOT unset the var — Node coerces it to the literal string "undefined" —// so build the env explicitly and `delete`.- const childEnv = { ...process.env };+ // Merge HF_TOKEN/HF_HOME via hfTokenEnv() so the Wan 2.2 / HunyuanVideo+ // python helpers can authenticate snapshot_download() against gated repos+ // (mirrors the imageGen child-spawn pattern). LTX-2 doesn't currently use+ // a gated repo, but the merge is harmless when no token is configured.+ const childEnv = { ...process.env, ...(await hfTokenEnv()) };delete childEnv.PYTHONPATH;const proc = spawn(bin, args, { env: childEnv, stdio: ['ignore', 'pipe', 'pipe'] });activeProcess = proc;diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 67738b49a7..d8a640cf2e 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -51,6 +51,14 @@ vi.mock('../../lib/ffmpeg.js', () => ({extractEvaluationFrames: vi.fn(async () => []),}));+// hfTokenEnv() resolves to {} when no token is configured; mocking here+// avoids touching the real settings layer (which would await an unmocked+// `getSettings()` chain and hang the spawn-mock-driven tests).+vi.mock('../../lib/hfToken.js', () => ({+ hfTokenEnv: vi.fn(async () => ({})),+ getHfToken: vi.fn(async () => null),+}));+vi.mock('fs', () => ({existsSync: vi.fn(() => true),statSync: vi.fn(() => ({ size: 1000 })),