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 system resources dashboard (#4451)
[._.]/ Adam Eivy476ad544fe42
diff --git a/.changelog/next/added-system-resources-dashboard.md b/.changelog/next/added-system-resources-dashboard.mdnew file mode 100644index 0000000000..3514ea74d5--- /dev/null+++ b/.changelog/next/added-system-resources-dashboard.md@@ -0,0 +1 @@+- Added a System Resources dashboard for storage reports, AI cleanup triage, model memory management, and live job queuesdiff --git a/client/src/App.jsx b/client/src/App.jsxindex 38e35fb31c..048601548a 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -305,7 +305,9 @@ export default function App() {<Route path="instances" element={<Instances />} /><Route path="workspace-contexts" element={<WorkspaceContexts />} /><Route path="workspace-contexts/:appId" element={<WorkspaceContexts />} />- <Route path="system-health" element={<SystemHealthPage />} />+ <Route path="system-health" element={<Navigate to="/system-resources/overview" replace />} />+ <Route path="system-resources" element={<Navigate to="/system-resources/overview" replace />} />+ <Route path="system-resources/:tab" element={<SystemHealthPage />} /><Route path="capabilities" element={<CapabilityMap />} /><Route path="loops" element={<Loops />} /><Route path="meatspace" element={<Navigate to="/meatspace/overview" replace />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 42592f5201..8c5a0b8a01 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -274,7 +274,7 @@ const navItems = [{ to: '/devtools/quota-burn', label: 'Quota Burn', icon: Flame },{ to: '/security', label: 'Security', icon: Camera },{ to: '/shell', label: 'Shell', icon: SquareTerminal },- { to: '/system-health', label: 'System Health', icon: Activity },+ { to: '/system-resources', label: 'System Resources', icon: Activity },{ to: '/uploads', label: 'Uploads', icon: Upload },{ to: '/devtools/usage', label: 'Usage', icon: BarChart3 },{ to: '/devtools/video-download', label: 'Video Downloader', icon: Film },diff --git a/client/src/components/Layout.test.jsx b/client/src/components/Layout.test.jsxindex 8e7f3d75ba..7c2be38e72 100644--- a/client/src/components/Layout.test.jsx+++ b/client/src/components/Layout.test.jsx@@ -138,6 +138,16 @@ describe('Layout — pinned single nav rows', () => {});});+describe('Layout — System Resources location state', () => {+ it('keeps Dev Tools expanded and System Resources active on every subtab', async () => {+ await renderLayout('/system-resources/storage');++ const link = screen.getByRole('link', { name: 'System Resources' });+ expect(link).toHaveAttribute('href', '/system-resources');+ expect(link.className).toContain('text-port-accent');+ });+});+describe('Layout — persistent mobile touch targets', () => {const expectAtLeast44px = (element) => {expect(element.className).toContain('min-w-[44px]');diff --git a/client/src/components/SystemHealthWidget.jsx b/client/src/components/SystemHealthWidget.jsxindex e399f97426..e045f244bb 100644--- a/client/src/components/SystemHealthWidget.jsx+++ b/client/src/components/SystemHealthWidget.jsx@@ -137,7 +137,7 @@ const SystemHealthWidget = memo(function SystemHealthWidget({ dashboardState })<RefreshCw size={15} className={refreshing ? 'animate-spin' : ''} aria-hidden="true" /></button><Link- to="/system-health"+ to="/system-resources/overview"className="flex items-center gap-1 text-sm text-port-accent hover:text-port-accent/80 transition-colors min-h-[40px] px-2"><span className="hidden sm:inline">Details</span>@@ -267,7 +267,11 @@ const SystemHealthWidget = memo(function SystemHealthWidget({ dashboardState }){/* Disk Usage */}{system.disk && (- <div className="bg-port-bg/50 rounded-lg p-3">+ <Link+ to="/system-resources/storage"+ aria-label="Open disk usage report"+ className="block rounded-lg bg-port-bg/50 p-3 transition-colors hover:bg-port-bg/80 focus:outline-none focus:ring-2 focus:ring-port-accent/60"+ ><div className="flex items-center gap-2 mb-1"><Database size={14} className="text-cyan-400" /><span className="text-xs text-gray-500">Disk</span>@@ -284,7 +288,7 @@ const SystemHealthWidget = memo(function SystemHealthWidget({ dashboardState })style={{ width: `${system.disk.usagePercent}%` }}/></div>- </div>+ </Link>)}</div>diff --git a/client/src/components/SystemHealthWidget.test.jsx b/client/src/components/SystemHealthWidget.test.jsxindex d829468828..99df33dfd3 100644--- a/client/src/components/SystemHealthWidget.test.jsx+++ b/client/src/components/SystemHealthWidget.test.jsx@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import { render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { MemoryRouter } from 'react-router';-import SystemHealthWidget from './SystemHealthWidget';+import SystemHealthWidget from './SystemHealthWidget.jsx';const HEALTH = {overallHealth: 'healthy',@@ -54,4 +54,10 @@ describe('SystemHealthWidget', () => {expect(screen.getByText('55%')).toBeInTheDocument();});++ it('links details to overview and disk usage directly to storage', () => {+ renderWidget({ health: HEALTH, refetchHealth: vi.fn() });+ expect(screen.getByRole('link', { name: 'Open disk usage report' })).toHaveAttribute('href', '/system-resources/storage');+ expect(screen.getByRole('link', { name: /Details/ })).toHaveAttribute('href', '/system-resources/overview');+ });});diff --git a/client/src/components/cos/tabs/SortableTaskItem.jsx b/client/src/components/cos/tabs/SortableTaskItem.jsxindex 40c11c9d09..192791ea49 100644--- a/client/src/components/cos/tabs/SortableTaskItem.jsx+++ b/client/src/components/cos/tabs/SortableTaskItem.jsx@@ -3,7 +3,7 @@ import { useSortable } from '@dnd-kit/sortable';import { dndTransformToCss } from '../../../lib/dndTransform';import TaskItem from './TaskItem';-export default function SortableTaskItem({ task, onRefresh, providers, durations, apps }) {+export default function SortableTaskItem({ task, selected = false, onRefresh, providers, durations, apps }) {const [isEditing, setIsEditing] = useState(false);const {attributes,@@ -25,6 +25,7 @@ export default function SortableTaskItem({ task, onRefresh, providers, durations<div ref={setNodeRef} style={style}><TaskItemtask={task}+ selected={selected}onRefresh={onRefresh}providers={providers}durations={durations}diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsxindex 8ef34e8e0b..a6ea652c2c 100644--- a/client/src/components/cos/tabs/TaskItem.jsx+++ b/client/src/components/cos/tabs/TaskItem.jsx@@ -57,6 +57,8 @@ const getTaskEditData = (task) => ({provider: task.metadata?.provider || ''});+export const taskRowId = (taskId, source) => `cos-task-${source}-${encodeURIComponent(taskId)}`;+// Get success rate styling based on percentagefunction getSuccessRateStyle(rate) {if (rate >= 70) return { bg: 'bg-port-success/15', text: 'text-port-success', label: 'high' };@@ -64,7 +66,7 @@ function getSuccessRateStyle(rate) {return { bg: 'bg-port-error/15', text: 'text-port-error', label: 'low' };}-export default function TaskItem({ task, isSystem, onRefresh, providers, durations, dragHandleProps, apps, onEditingChange }) {+export default function TaskItem({ task, isSystem, selected = false, onRefresh, providers, durations, dragHandleProps, apps, onEditingChange }) {// System tasks are persisted in COS-TASKS.md. Every task// mutation must name that source; otherwise the API's user-queue default// searches TASKS.md and reports the system task as missing.@@ -269,9 +271,16 @@ export default function TaskItem({ task, isSystem, onRefresh, providers, duratio};return (- <div className={`bg-port-card border rounded-lg p-4 ${- requiresApproval ? 'border-yellow-500/50' : 'border-port-border'- }`}>+ <div+ id={taskRowId(task.id, taskSource)}+ tabIndex={selected ? -1 : undefined}+ aria-current={selected ? 'true' : undefined}+ className={`bg-port-card border rounded-lg p-4 ${+ selected+ ? 'border-port-accent ring-2 ring-port-accent/30'+ : requiresApproval ? 'border-yellow-500/50' : 'border-port-border'+ }`}+ ><div className="flex items-start gap-3">{/* Drag handle - only show for user tasks. */}{dragHandleProps && !isSystem && (diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsxindex 9e04a13843..e9f75ec21c 100644--- a/client/src/components/cos/tabs/TasksTab.jsx+++ b/client/src/components/cos/tabs/TasksTab.jsx@@ -1,4 +1,5 @@import { useState, useEffect, useMemo } from 'react';+import { useSearchParams } from 'react-router';import { Play, ChevronDown, ChevronRight } from 'lucide-react';import toast from '../../ui/Toast';import {@@ -16,7 +17,7 @@ import {verticalListSortingStrategy,} from '@dnd-kit/sortable';import * as api from '../../../services/api';-import TaskItem from './TaskItem';+import TaskItem, { taskRowId } from './TaskItem';import SortableTaskItem from './SortableTaskItem';import TaskAddForm from '../TaskAddForm';import { MicroGlyph, SchematicLabel } from '../../micrographics';@@ -37,6 +38,7 @@ function SectionGlyph({ status }) {}export default function TasksTab({ tasks, onRefresh, providers, apps }) {+ const [searchParams] = useSearchParams();const [userTasksLocal, setUserTasksLocal] = useState([]);const [durations, setDurations] = useState(null);const [showCompletedUserTasks, setShowCompletedUserTasks] = useState(false);@@ -52,6 +54,18 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {// Memoize task arrays to prevent unnecessary re-rendersconst userTasks = useMemo(() => tasks.user?.tasks || [], [tasks.user?.tasks]);const cosTasks = useMemo(() => tasks.cos?.tasks || [], [tasks.cos?.tasks]);+ const selectedTaskId = searchParams.get('task');+ const requestedSource = searchParams.get('source');+ const selectedTaskSource = useMemo(() => {+ if (!selectedTaskId) return null;+ if (requestedSource === 'user' || requestedSource === 'internal') return requestedSource;+ if (userTasks.some((task) => task.id === selectedTaskId)) return 'user';+ if (cosTasks.some((task) => task.id === selectedTaskId)) return 'internal';+ return null;+ }, [cosTasks, requestedSource, selectedTaskId, userTasks]);+ const isTaskSelected = (task, source) => (+ task.id === selectedTaskId && source === selectedTaskSource+ );// Split tasks by status for system tasksconst pendingSystemTasks = useMemo(() =>@@ -100,6 +114,33 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {setUserTasksLocal(userTasks);}, [userTasks]);+ // Queue summary links identify one concrete task. Completed sections are+ // collapsed by default, so open the relevant one before attempting to focus+ // and center the row.+ useEffect(() => {+ if (!selectedTaskId || !selectedTaskSource) return;+ const selected = (selectedTaskSource === 'user' ? userTasks : cosTasks)+ .find((task) => task.id === selectedTaskId);+ if (selected?.status !== 'completed') return;+ if (selectedTaskSource === 'user') setShowCompletedUserTasks(true);+ else setShowCompletedSystemTasks(true);+ }, [cosTasks, selectedTaskId, selectedTaskSource, userTasks]);++ useEffect(() => {+ if (!selectedTaskId || !selectedTaskSource) return;+ const row = document.getElementById(taskRowId(selectedTaskId, selectedTaskSource));+ if (!row) return;+ row.scrollIntoView?.({ block: 'center' });+ row.focus({ preventScroll: true });+ }, [+ cosTasks,+ selectedTaskId,+ selectedTaskSource,+ showCompletedSystemTasks,+ showCompletedUserTasks,+ userTasksLocal,+ ]);+// Drag and drop sensorsconst sensors = useSensors(useSensor(PointerSensor, {@@ -190,7 +231,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {><div className="space-y-1.5">{pendingUserTasksLocal.map(task => (- <SortableTaskItem key={task.id} task={task} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />+ <SortableTaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />))}</div></SortableContext>@@ -210,7 +251,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {</div><div className="p-2 space-y-1.5">{activeUserTasksLocal.map(task => (- <TaskItem key={task.id} task={task} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />+ <TaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />))}</div></div>@@ -227,7 +268,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {</div><div className="p-2 space-y-1.5">{blockedUserTasksLocal.map(task => (- <TaskItem key={task.id} task={task} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />+ <TaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />))}</div></div>@@ -250,7 +291,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {{showCompletedUserTasks && (<div className="p-2 space-y-1.5">{completedUserTasksLocal.map(task => (- <TaskItem key={task.id} task={task} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />+ <TaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />))}</div>)}@@ -283,7 +324,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {</div><div className="p-2 space-y-1.5">{pendingSystemTasks.map(task => (- <TaskItem key={task.id} task={task} isSystem onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />+ <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />))}</div></div>@@ -300,7 +341,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {</div><div className="p-2 space-y-1.5">{activeSystemTasks.map(task => (- <TaskItem key={task.id} task={task} isSystem onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />+ <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />))}</div></div>@@ -317,7 +358,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {</div><div className="p-2 space-y-1.5">{blockedSystemTasks.map(task => (- <TaskItem key={task.id} task={task} isSystem onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />+ <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />))}</div></div>@@ -340,7 +381,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {{showCompletedSystemTasks && (<div className="p-2 space-y-1.5">{completedSystemTasks.map(task => (- <TaskItem key={task.id} task={task} isSystem onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />+ <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />))}</div>)}diff --git a/client/src/components/cos/tabs/TasksTab.test.jsx b/client/src/components/cos/tabs/TasksTab.test.jsxindex f1108152f6..5fb89299ee 100644--- a/client/src/components/cos/tabs/TasksTab.test.jsx+++ b/client/src/components/cos/tabs/TasksTab.test.jsx@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';// Regression coverage for #2519 — the "Run Now" evaluate button must only toast// success after the request resolves.@@ -17,6 +18,11 @@ vi.mock('../TaskAddForm', () => ({ default: () => null }));const TasksTab = (await import('./TasksTab')).default;const emptyTasks = { user: { tasks: [] }, cos: { tasks: [] } };+const renderTab = (props = {}, route = '/cos/tasks') => render(+ <MemoryRouter initialEntries={[route]}>+ <TasksTab tasks={emptyTasks} onRefresh={vi.fn()} providers={[]} apps={[]} {...props} />+ </MemoryRouter>,+);beforeEach(() => {vi.clearAllMocks();@@ -26,7 +32,7 @@ beforeEach(() => {describe('TasksTab Run Now', () => {it('does not toast success when the evaluate request fails', async () => {api.forceCosEvaluate.mockRejectedValue(new Error('offline'));- render(<TasksTab tasks={emptyTasks} onRefresh={vi.fn()} providers={[]} apps={[]} />);+ renderTab();fireEvent.click(screen.getByRole('button', { name: /Run tasks now/i }));@@ -36,7 +42,7 @@ describe('TasksTab Run Now', () => {it('toasts success only after the evaluate request resolves', async () => {api.forceCosEvaluate.mockResolvedValue({ success: true });- render(<TasksTab tasks={emptyTasks} onRefresh={vi.fn()} providers={[]} apps={[]} />);+ renderTab();fireEvent.click(screen.getByRole('button', { name: /Run tasks now/i }));@@ -45,4 +51,14 @@ describe('TasksTab Run Now', () => {// Must pass { silent: true } so the custom catch is the only error toast.expect(api.forceCosEvaluate).toHaveBeenCalledWith({ silent: true });});++ it('opens and focuses the task identified by the queue deep link', async () => {+ const task = { id: 'task-example', description: 'Review an example task', status: 'completed', metadata: {} };+ renderTab({ tasks: { user: { tasks: [task] }, cos: { tasks: [] } } }, '/cos/tasks?task=task-example&source=user');++ await waitFor(() => expect(document.getElementById('cos-task-user-task-example')).not.toBeNull());+ const row = document.getElementById('cos-task-user-task-example');+ expect(row).toHaveAttribute('aria-current', 'true');+ expect(row).toHaveFocus();+ });});diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsxindex f55a28580c..2a72febfe1 100644--- a/client/src/components/media/MediaJobsQueue.jsx+++ b/client/src/components/media/MediaJobsQueue.jsx@@ -77,11 +77,23 @@ function modelLabel(params) {export default function MediaJobsQueue({ kind, recentLimit = 10, className = '' }) {const [jobs, setJobs] = useState([]);const [loading, setLoading] = useState(true);+ const [hasSnapshot, setHasSnapshot] = useState(false);+ const [loadError, setLoadError] = useState(false);const [showRecent, setShowRecent] = useState(false);const fetchJobs = useCallback(async () => {- const data = await listMediaJobs(kind ? { kind } : {}).catch(() => null);- if (data) setJobs(data);+ const outcome = await listMediaJobs(kind ? { kind } : {}).then(+ (value) => ({ value }),+ () => ({ error: true }),+ );+ if (outcome.error || !Array.isArray(outcome.value)) {+ setLoadError(true);+ setLoading(false);+ return;+ }+ setJobs(outcome.value);+ setHasSnapshot(true);+ setLoadError(false);setLoading(false);}, [kind]);@@ -166,7 +178,9 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''<div className="flex items-center gap-2 min-w-0"><ListOrdered className="w-4 h-4 text-port-accent shrink-0" /><h2 className="text-xs font-medium text-gray-400 uppercase tracking-wide truncate">{headerLabel}</h2>- <span className="text-xs text-port-text-muted">{formatCounts(live, recent, failedCount)}</span>+ <span className="text-xs text-port-text-muted">+ {loadError && !hasSnapshot ? 'status unavailable' : formatCounts(live, recent, failedCount)}+ </span></div><div className="flex items-center gap-1 shrink-0">{queuedCount > 0 && (@@ -189,8 +203,16 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''</div></div>- {loading ? (+ {loadError && hasSnapshot && (+ <div className="rounded border border-port-warning/30 bg-port-warning/10 px-3 py-2 text-xs text-port-warning">+ Queue refresh failed. Showing the last known snapshot.+ </div>+ )}++ {loading && !hasSnapshot ? (<div className="text-xs"><BrailleSpinner text="Loading…" /></div>+ ) : loadError && !hasSnapshot ? (+ <div className="text-xs text-port-warning">Queue status unavailable.</div>) : live.length === 0 && recent.length === 0 ? (<div className="text-port-text-muted text-xs">No {kind || 'media'} {kind === 'training' ? 'runs' : 'renders'} queued.diff --git a/client/src/components/media/MediaJobsQueue.test.jsx b/client/src/components/media/MediaJobsQueue.test.jsxindex 322cc03f69..1d685565af 100644--- a/client/src/components/media/MediaJobsQueue.test.jsx+++ b/client/src/components/media/MediaJobsQueue.test.jsx@@ -82,6 +82,17 @@ const failedCodexDefaultEffortJob = {params: { prompt: 'a fox', mode: 'codex', model: 'gpt-5.6-luna' },};+describe('MediaJobsQueue — unavailable state', () => {+ it('does not report a failed queue probe as an empty queue', async () => {+ listMediaJobs.mockRejectedValue(new Error('offline'));++ render(<MediaJobsQueue kind="image" />);++ expect(await screen.findByText('Queue status unavailable.')).toBeInTheDocument();+ expect(screen.queryByText('No image renders queued.')).not.toBeInTheDocument();+ });+});+describe('MediaJobsQueue — Codex reasoning-effort retry control', () => {it('surfaces the job effort in the row label', async () => {const user = userEvent.setup();diff --git a/client/src/components/settings/MemoryManagement.jsx b/client/src/components/settings/MemoryManagement.jsxindex f89be12aff..dbe17d2788 100644--- a/client/src/components/settings/MemoryManagement.jsx+++ b/client/src/components/settings/MemoryManagement.jsx@@ -4,6 +4,7 @@//// Sources of residency this panel covers:// - Ollama models (multiple can be loaded simultaneously) → /api/local-llm/loaded+// - LM Studio models → /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//@@ -20,20 +21,40 @@// 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';import { useAsyncAction } from '../../hooks/useAsyncAction.js';import useMounted from '../../hooks/useMounted.js';import { formatBytes } from '../../utils/formatters';-import { getLoadedLlmModels, unloadOllamaModel } from '../../services/apiLocalLlm.js';+import {+ getLoadedLlmModels,+ unloadLmStudioModel,+ unloadOllamaModel,+} from '../../services/apiLocalLlm.js';import { getTtsStatus, unloadKokoroTts, controlWhisper, getVoiceStatus } from '../../services/apiVoice.js';const SILENT = { silent: true };const POLL_MS = 5000;+const EMPTY_SNAPSHOT = {+ loadedOllama: [],+ loadedLmStudio: [],+ ttsState: { state: 'lazy', loadedKey: null },+ whisperRunning: false,+ sttEngine: 'whisper',+ unavailableSources: [],+};++const SOURCE_LABELS = {+ ollama: 'Ollama',+ lmstudio: 'LM Studio',+ tts: 'text-to-speech',+ voice: 'voice services',+};+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 }) {@@ -50,49 +71,93 @@ function Row({ icon: Icon, title, subtitle, status, action, danger }) {);}-export default function MemoryManagement() {+export default function MemoryManagement({ onLoadedModelsChange } = {}) {const [loadedOllama, setLoadedOllama] = useState([]);+ const [loadedLmStudio, setLoadedLmStudio] = 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);+ const [unavailableSources, setUnavailableSources] = useState([]);// Guards the polled setState calls — a late /voice/status response that// resolves after unmount would otherwise call setState on a dead tree.// useMounted resets the ref to true on every mount so React 18 StrictMode's// mount→cleanup→remount cycle doesn't leave it permanently false (which// would otherwise keep the panel stuck on "Loading memory status…" in dev).const mountedRef = useMounted();+ const snapshotRef = useRef(EMPTY_SNAPSHOT);+ const refreshGenerationRef = useRef(0);+ const priorityRefreshRef = useRef(false);// Returns the fresh snapshot so callers (notably freeAll) can act on the// values without waiting for React's async setState to flush — reading// component state immediately after `await refresh()` would still see// the prior poll's snapshot.- const refresh = useCallback(async () => {- const [llm, tts, voice] = await Promise.all([- getLoadedLlmModels(SILENT).catch(() => ({ ollama: [] })),- getTtsStatus(SILENT).catch(() => ({ kokoro: { state: 'lazy', loadedKey: null } })),- getVoiceStatus(SILENT).catch(() => null),+ const refresh = useCallback(async (options = {}) => {+ const priority = options?.priority === true;+ // "Free everything" needs one authoritative pre-action snapshot. Do not+ // let the 5s interval start a newer poll while that priority refresh is in+ // flight, or the caller would have to act on an older last-known snapshot.+ if (!priority && priorityRefreshRef.current) return snapshotRef.current;+ if (priority) priorityRefreshRef.current = true;+ const generation = ++refreshGenerationRef.current;+ const [llmResult, ttsResult, voiceResult] = await Promise.allSettled([+ getLoadedLlmModels(SILENT),+ getTtsStatus(SILENT),+ getVoiceStatus(SILENT),]);+ // A later-started poll/action refresh owns the UI. Return its current+ // snapshot to stale callers instead of letting an old response resurrect a+ // model that was just unloaded.+ if (generation !== refreshGenerationRef.current) {+ if (priority) priorityRefreshRef.current = false;+ return snapshotRef.current;+ }++ const previous = snapshotRef.current;+ const llm = llmResult.status === 'fulfilled' ? llmResult.value : null;+ const tts = ttsResult.status === 'fulfilled' ? ttsResult.value : null;+ const voice = voiceResult.status === 'fulfilled' ? voiceResult.value : null;+ const llmValid = Array.isArray(llm?.ollama) && Array.isArray(llm?.lmstudio);+ const ttsValid = typeof tts?.kokoro?.state === 'string';+ const voiceValid = voice != null && typeof voice === 'object';+ const llmSourceErrors = llmValid && Array.isArray(llm.sourceErrors) ? llm.sourceErrors : [];+ const failedSources = [+ ...(!llmValid ? ['ollama', 'lmstudio'] : llmSourceErrors),+ ...(!ttsValid ? ['tts'] : []),+ ...(!voiceValid ? ['voice'] : []),+ ];const snapshot = {- loadedOllama: Array.isArray(llm?.ollama) ? llm.ollama : [],- ttsState: tts?.kokoro || { state: 'lazy', loadedKey: null },+ loadedOllama: llmValid && !llmSourceErrors.includes('ollama') ? llm.ollama : previous.loadedOllama,+ loadedLmStudio: llmValid && !llmSourceErrors.includes('lmstudio') ? llm.lmstudio : previous.loadedLmStudio,+ ttsState: ttsValid ? tts.kokoro : previous.ttsState,// 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.- whisperRunning: Boolean(voice?.services?.whisper?.ok),- sttEngine: voice?.sttEngine || 'whisper',+ whisperRunning: voiceValid ? Boolean(voice.services?.whisper?.ok) : previous.whisperRunning,+ sttEngine: voiceValid ? (voice.sttEngine || 'whisper') : previous.sttEngine,+ unavailableSources: [...new Set(failedSources)],};+ snapshotRef.current = snapshot;+ if (priority) priorityRefreshRef.current = false;if (!mountedRef.current) return snapshot;setLoadedOllama(snapshot.loadedOllama);+ setLoadedLmStudio(snapshot.loadedLmStudio);setTtsState(snapshot.ttsState);setWhisperRunning(snapshot.whisperRunning);setSttEngine(snapshot.sttEngine);+ setUnavailableSources(snapshot.unavailableSources);setLoading(false);setLastFetched(Date.now());+ onLoadedModelsChange?.({+ ollama: snapshot.loadedOllama,+ lmstudio: snapshot.loadedLmStudio,+ sourceErrors: snapshot.unavailableSources.filter((source) => source === 'ollama' || source === 'lmstudio'),+ });return snapshot;- }, []);+ }, [mountedRef, onLoadedModelsChange]);useEffect(() => {refresh();@@ -105,6 +170,11 @@ export default function MemoryManagement() {toast.success(`Unloaded ${modelId}`);await refresh();});+ const [unloadLmStudio, unloadingLmStudio] = useAsyncAction(async (modelId) => {+ await unloadLmStudioModel(modelId, SILENT);+ toast.success(`Unloaded ${modelId}`);+ await refresh();+ });const [unloadKokoro, unloadingKokoro] = useAsyncAction(async () => {const result = await unloadKokoroTts(SILENT);toast.success(result?.unloaded ? 'Kokoro TTS unloaded' : 'Kokoro was not loaded');@@ -127,19 +197,24 @@ export default function MemoryManagement() {// snapshot rather than component state — React's async setState in// refresh() won't have flushed by the time `loadedOllama` etc. is// referenced in this same closure.- const fresh = (await refresh()) || { loadedOllama: [], whisperRunning: false, ttsState: { state: 'lazy' } };+ const fresh = (await refresh({ priority: true })) || EMPTY_SNAPSHOT;+ const sourceUnknown = (source) => fresh.unavailableSources.includes(source);// 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; the trailing refresh() then shows what actually got freed.// Per-step toasts would also stack four-deep on success which is noise.const results = await Promise.allSettled([- ...fresh.loadedOllama.map((m) => unloadOllamaModel(m.id, SILENT)),- fresh.whisperRunning ? controlWhisper('stop', SILENT) : Promise.resolve(),- fresh.ttsState.state !== 'lazy' ? unloadKokoroTts(SILENT) : Promise.resolve(),+ ...(!sourceUnknown('ollama') ? fresh.loadedOllama.map((m) => unloadOllamaModel(m.id, SILENT)) : []),+ ...(!sourceUnknown('lmstudio') ? fresh.loadedLmStudio.map((m) => unloadLmStudioModel(m.id, SILENT)) : []),+ !sourceUnknown('voice') && fresh.whisperRunning ? controlWhisper('stop', SILENT) : Promise.resolve(),+ !sourceUnknown('tts') && fresh.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`);+ if (fresh.unavailableSources.length > 0) {+ const labels = fresh.unavailableSources.map((source) => SOURCE_LABELS[source] || source).join(', ');+ toast.error(`Freed verified resources only — could not verify ${labels}`);+ } else if (failed) toast.error(`Freed most resources — ${failed} action(s) failed`);else toast.success('Freed all memory-resident models');await refresh();});@@ -154,12 +229,13 @@ export default function MemoryManagement() {);}- const anythingLoaded = loadedOllama.length > 0 || whisperRunning || ttsState.state !== 'lazy';+ const anythingLoaded = loadedOllama.length > 0 || loadedLmStudio.length > 0+ || whisperRunning || ttsState.state !== 'lazy';const anyActionRunning =- unloadingModel || unloadingKokoro || stoppingWhisper || startingWhisper || freeingAll;+ unloadingModel || unloadingLmStudio || unloadingKokoro || stoppingWhisper || startingWhisper || freeingAll;return (- <div className="bg-port-card border border-port-border rounded mb-4">+ <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>@@ -190,7 +266,18 @@ export default function MemoryManagement() {</div></div>- {loadedOllama.length === 0 && !whisperRunning && ttsState.state === 'lazy' ? (+ {unavailableSources.length > 0 && (+ <div className="mx-3 mt-3 flex items-start gap-2 rounded border border-port-warning/30 bg-port-warning/10 px-3 py-2 text-xs text-port-warning">+ <AlertTriangle className="mt-0.5 h-3 w-3 shrink-0" />+ <span>+ Status unavailable for {unavailableSources.map((source) => SOURCE_LABELS[source] || source).join(', ')}.+ Last known values remain visible; unknown resources are excluded from Free everything.+ </span>+ </div>+ )}++ {loadedOllama.length === 0 && loadedLmStudio.length === 0+ && !whisperRunning && ttsState.state === 'lazy' && unavailableSources.length === 0 ? (<div className="px-3 py-3 text-xs text-gray-500 italic">Nothing memory-resident — full unified memory is available for diffusion.</div>@@ -208,6 +295,28 @@ export default function MemoryManagement() {type="button"onClick={() => unloadModel(m.id)}disabled={anyActionRunning}+ aria-label={`Unload ${m.name || m.id}`}+ className={`${btnClass} text-gray-300 border border-port-border hover:bg-port-border/40`}+ >+ Unload+ </button>+ }+ danger+ />+ ))}+ {loadedLmStudio.map((m) => (+ <Row+ key={`lmstudio:${m.id}`}+ icon={Cpu}+ title={m.id}+ subtitle="LM Studio"+ status="loaded"+ action={+ <button+ type="button"+ onClick={() => unloadLmStudio(m.id)}+ disabled={anyActionRunning}+ aria-label={`Unload ${m.id}`}className={`${btnClass} text-gray-300 border border-port-border hover:bg-port-border/40`}>Unload@@ -258,7 +367,7 @@ export default function MemoryManagement() {</div>)}- {!whisperRunning && sttEngine === 'whisper' && (+ {!whisperRunning && sttEngine === 'whisper' && !unavailableSources.includes('voice') && (<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/components/settings/MemoryManagement.test.jsx b/client/src/components/settings/MemoryManagement.test.jsxnew file mode 100644index 0000000000..69c3305e91--- /dev/null+++ b/client/src/components/settings/MemoryManagement.test.jsx@@ -0,0 +1,87 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';++vi.mock('../../services/apiLocalLlm.js', () => ({+ getLoadedLlmModels: vi.fn(),+ unloadLmStudioModel: vi.fn(),+ unloadOllamaModel: vi.fn(),+}));++vi.mock('../../services/apiVoice.js', () => ({+ getTtsStatus: vi.fn(async () => ({ kokoro: { state: 'lazy', loadedKey: null } })),+ unloadKokoroTts: vi.fn(),+ controlWhisper: vi.fn(),+ getVoiceStatus: vi.fn(async () => ({ sttEngine: 'piper', services: {} })),+}));++vi.mock('../ui/Toast', () => ({+ default: { success: vi.fn(), error: vi.fn() },+}));++import { getLoadedLlmModels, unloadLmStudioModel } from '../../services/apiLocalLlm.js';+import { getTtsStatus, getVoiceStatus } from '../../services/apiVoice.js';+import toast from '../ui/Toast';+import MemoryManagement from './MemoryManagement.jsx';++describe('MemoryManagement', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getLoadedLlmModels.mockResolvedValue({+ ollama: [],+ lmstudio: [{ id: 'example/lmstudio-model', state: 'loaded' }],+ });+ unloadLmStudioModel.mockResolvedValue({ success: true });+ getTtsStatus.mockResolvedValue({ kokoro: { state: 'lazy', loadedKey: null } });+ getVoiceStatus.mockResolvedValue({ sttEngine: 'piper', services: {} });+ });++ it('shows and unloads LM Studio models from the unified residency endpoint', async () => {+ render(<MemoryManagement />);++ expect(await screen.findByText('example/lmstudio-model')).toBeInTheDocument();+ expect(screen.getByText('LM Studio')).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Unload example/lmstudio-model' }));++ await waitFor(() => expect(unloadLmStudioModel).toHaveBeenCalledWith(+ 'example/lmstudio-model',+ { silent: true },+ ));+ });++ it('never claims memory is free when fresh status probes fail', async () => {+ render(<MemoryManagement />);+ expect(await screen.findByText('example/lmstudio-model')).toBeInTheDocument();++ getLoadedLlmModels.mockRejectedValueOnce(new Error('LLM status failed'));+ getTtsStatus.mockRejectedValueOnce(new Error('TTS status failed'));+ getVoiceStatus.mockRejectedValueOnce(new Error('voice status failed'));+ fireEvent.click(screen.getByRole('button', { name: 'Free everything' }));++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('could not verify')));+ expect(unloadLmStudioModel).not.toHaveBeenCalled();+ expect(toast.success).not.toHaveBeenCalledWith('Freed all memory-resident models');+ expect(screen.queryByText(/full unified memory is available/i)).not.toBeInTheDocument();+ });++ it('ignores an older refresh that resolves after a newer snapshot', async () => {+ render(<MemoryManagement />);+ expect(await screen.findByText('example/lmstudio-model')).toBeInTheDocument();++ let resolveSlow;+ getLoadedLlmModels+ .mockImplementationOnce(() => new Promise((resolve) => { resolveSlow = resolve; }))+ .mockResolvedValueOnce({ ollama: [], lmstudio: [{ id: 'newer-model', state: 'loaded' }] });++ const refresh = screen.getByRole('button', { name: 'Refresh' });+ fireEvent.click(refresh);+ fireEvent.click(refresh);+ expect(await screen.findByText('newer-model')).toBeInTheDocument();++ await act(async () => {+ resolveSlow({ ollama: [], lmstudio: [{ id: 'older-model', state: 'loaded' }] });+ await Promise.resolve();+ });+ expect(screen.queryByText('older-model')).not.toBeInTheDocument();+ expect(screen.getByText('newer-model')).toBeInTheDocument();+ });+});diff --git a/client/src/components/system-resources/CleanupControl.jsx b/client/src/components/system-resources/CleanupControl.jsxnew file mode 100644index 0000000000..033ea36217--- /dev/null+++ b/client/src/components/system-resources/CleanupControl.jsx@@ -0,0 +1,57 @@+import { ExternalLink, Trash2 } from 'lucide-react';+import { Link } from 'react-router';+import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';++export default function CleanupControl({+ candidate,+ busy,+ disabled = false,+ confirming,+ onRequest,+ onCancel,+ onConfirm,+}) {+ if (confirming) {+ return (+ <ConfirmButtonPair+ prompt="Remove?"+ confirmText="Remove"+ busyText="Removing"+ busy={busy || disabled}+ confirmIcon={Trash2}+ ariaLabel={`Confirm removal of ${candidate.label}`}+ onConfirm={onConfirm}+ onCancel={onCancel}+ />+ );+ }++ if (candidate.action) {+ return (+ <button+ type="button"+ onClick={onRequest}+ disabled={busy || disabled}+ aria-label={`Remove ${candidate.label}`}+ className="inline-flex min-h-[36px] items-center gap-1.5 rounded-lg border border-port-error/40 px-2.5 py-1.5 text-xs text-port-error transition-colors hover:bg-port-error/10 disabled:opacity-50"+ >+ <Trash2 size={13} />+ Remove+ </button>+ );+ }++ if (candidate.managePath) {+ return (+ <Link+ to={candidate.managePath}+ aria-label={`Review ${candidate.label}`}+ className="inline-flex min-h-[36px] items-center gap-1.5 rounded-lg border border-port-border px-2.5 py-1.5 text-xs text-gray-300 transition-colors hover:bg-port-border/40"+ >+ Review <ExternalLink size={12} />+ </Link>+ );+ }++ return <span className="text-xs text-gray-600">Report only</span>;+}diff --git a/client/src/components/system-resources/ModelsPanel.jsx b/client/src/components/system-resources/ModelsPanel.jsxnew file mode 100644index 0000000000..8651c36723--- /dev/null+++ b/client/src/components/system-resources/ModelsPanel.jsx@@ -0,0 +1,164 @@+import { useMemo, useState } from 'react';+import { AlertTriangle, Box, Download, HardDrive, RefreshCw } from 'lucide-react';+import { Link } from 'react-router';+import MemoryManagement from '../settings/MemoryManagement.jsx';+import Banner from '../ui/Banner.jsx';+import CleanupControl from './CleanupControl.jsx';+import { formatBytes } from '../../utils/formatters.js';++const BACKEND_LABEL = {+ huggingface: 'Hugging Face',+ lora: 'LoRA',+ ollama: 'Ollama',+ lmstudio: 'LM Studio',+};++const normalizeLmStudioRepo = (value) => String(value || '')+ .split('/').pop()+ .trim()+ .toLowerCase()+ .replace(/[-.]gguf$/i, '')+ .replace(/[-.]mlx[-.].*$/i, '');++function InventoryEmpty({ loading, onRun }) {+ return (+ <section className="rounded-2xl border border-dashed border-port-accent/40 bg-port-accent/5 px-5 py-7 text-center">+ <Download className="mx-auto mb-3 text-port-accent" size={25} />+ <h3 className="font-semibold text-white">Inventory downloaded models</h3>+ <p className="mx-auto mt-2 max-w-xl text-sm text-gray-400">Scan Hugging Face, LoRA, Ollama, and LM Studio storage to see what is installed.</p>+ <button+ type="button"+ onClick={onRun}+ disabled={loading}+ className="mt-4 inline-flex min-h-[40px] items-center gap-2 rounded-lg bg-port-accent px-4 py-2 text-sm font-medium text-white hover:bg-port-accent/80 disabled:opacity-50"+ >+ <RefreshCw size={14} className={loading ? 'animate-spin' : ''} />+ {loading ? 'Scanning…' : 'Run model inventory'}+ </button>+ </section>+ );+}++export default function ModelsPanel({ report, loading, onRunReport, cleanup }) {+ const [residency, setResidency] = useState(null);+ const candidates = new Map((report?.cleanupCandidates || []).map((item) => [item.id, item]));+ const loaded = useMemo(() => ({+ ollama: new Set((residency?.ollama || []).flatMap((model) => [model.id, model.name]).filter(Boolean)),+ lmstudio: new Set((residency?.lmstudio || []).flatMap((model) => [+ model.id,+ normalizeLmStudioRepo(model.id),+ ]).filter(Boolean)),+ }), [residency]);+ const modelSourceErrors = (report?.sourceErrors || []).filter((source) => (+ source.startsWith('ollama')+ || source.startsWith('lmstudio')+ || source === 'huggingface'+ || source === 'loras'+ ));++ return (+ <div className="space-y-4">+ <MemoryManagement onLoadedModelsChange={setResidency} />++ {!report ? <InventoryEmpty loading={loading} onRun={onRunReport} /> : (+ <section className="rounded-2xl border border-port-border bg-port-card p-4 sm:p-5">+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">+ <div>+ <div className="flex items-center gap-2">+ <HardDrive size={17} className="text-port-accent" />+ <h3 className="font-semibold text-white">Downloaded model inventory</h3>+ </div>+ <p className="mt-1 text-xs text-gray-500">+ {report.models.downloaded.length} item{report.models.downloaded.length === 1 ? '' : 's'} · {Number.isFinite(report.models.totals.all) ? formatBytes(report.models.totals.all) : 'size unavailable'}+ </p>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <Link to="/media/models" className="min-h-[36px] rounded-lg border border-port-border px-3 py-2 text-xs text-gray-300 hover:bg-port-border/40">Media models</Link>+ <Link to="/settings/local-llm" className="min-h-[36px] rounded-lg border border-port-border px-3 py-2 text-xs text-gray-300 hover:bg-port-border/40">Local LLM settings</Link>+ <button+ type="button"+ onClick={onRunReport}+ disabled={loading || cleanup.locked}+ className="inline-flex min-h-[36px] items-center gap-1.5 rounded-lg border border-port-border px-3 py-2 text-xs text-gray-300 hover:bg-port-border/40 disabled:opacity-50"+ >+ <RefreshCw size={13} className={loading ? 'animate-spin' : ''} /> Refresh+ </button>+ </div>+ </div>++ {modelSourceErrors.length > 0 && (+ <Banner className="mt-4" tone="warning" icon={AlertTriangle}>+ Some model sources are unavailable: {modelSourceErrors.join(', ')}. Visible rows may be partial, and uncertain models cannot be removed.+ </Banner>+ )}++ <div className="mt-4 space-y-2">+ {report.models.downloaded.length === 0 ? (+ <p className="rounded-xl bg-port-bg/40 p-4 text-sm text-gray-500">+ {modelSourceErrors.length > 0+ ? 'No model inventory is available from the sources that responded.'+ : 'No downloaded models were found in the known stores.'}+ </p>+ ) : report.models.downloaded.map((model) => {+ const reportCandidate = candidates.get(model.id) || {+ ...model,+ label: model.name,+ estimatedBytes: model.sizeBytes,+ action: null,+ manualOnly: true,+ };+ const isLocal = model.backend === 'ollama' || model.backend === 'lmstudio';+ const sourceUnknown = isLocal && residency?.sourceErrors?.includes(model.backend);+ const liveKnown = isLocal && residency != null && !sourceUnknown;+ const liveLoaded = model.backend === 'ollama'+ ? loaded.ollama.has(model.action?.modelId || model.id.replace(/^ollama:/, ''))+ : loaded.lmstudio.has(model.action?.modelId || model.id.replace(/^lmstudio:/, ''))+ || loaded.lmstudio.has(normalizeLmStudioRepo(model.action?.modelId || model.id));+ const effectiveLoaded = liveKnown ? liveLoaded : Boolean(model.loaded);+ const residencyUnknown = sourceUnknown || (!liveKnown && Boolean(model.residencyUnknown));+ const action = isLocal+ ? (!effectiveLoaded && !residencyUnknown && !model.inventoryUnknown+ ? (liveKnown ? (model.action || reportCandidate.action) : reportCandidate.action)+ : null)+ : reportCandidate.action;+ const candidate = isLocal ? {+ ...reportCandidate,+ loaded: effectiveLoaded,+ busy: effectiveLoaded || residencyUnknown,+ manualOnly: !action,+ action,+ } : reportCandidate;+ return (+ <div key={model.id} className="flex flex-col gap-3 rounded-xl bg-port-bg/40 p-3 sm:flex-row sm:items-center">+ <div className="rounded-lg bg-port-accent/10 p-2 text-port-accent"><Box size={16} /></div>+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2">+ <span className="truncate font-medium text-gray-200">{model.name}</span>+ <span className="rounded bg-port-border px-1.5 py-0.5 text-[10px] uppercase text-gray-400">{BACKEND_LABEL[model.backend] || model.backend}</span>+ {effectiveLoaded && <span className="rounded bg-purple-500/10 px-1.5 py-0.5 text-[10px] uppercase text-purple-300">loaded</span>}+ {residencyUnknown && <span className="rounded bg-port-warning/10 px-1.5 py-0.5 text-[10px] uppercase text-port-warning">status unknown</span>}+ </div>+ {model.detail && <p className="mt-0.5 truncate text-xs text-gray-500">{model.detail}</p>}+ </div>+ <div className="text-sm font-semibold tabular-nums text-white">+ {Number.isFinite(model.sizeBytes) ? `${model.sizeIsEstimate ? '≈' : ''}${formatBytes(model.sizeBytes)}` : 'Size unavailable'}+ </div>+ <CleanupControl+ candidate={candidate}+ busy={cleanup.busyId === candidate.id}+ disabled={cleanup.locked}+ confirming={cleanup.isConfirming(candidate.id)}+ onRequest={() => cleanup.request(candidate.id)}+ onCancel={cleanup.cancel}+ onConfirm={() => cleanup.confirm(candidate)}+ />+ </div>+ );+ })}+ </div>+ <p className="mt-3 text-[11px] text-gray-600">≈ Size is an upper-bound estimate when model tags may share underlying layers.</p>+ </section>+ )}+ </div>+ );+}diff --git a/client/src/components/system-resources/ModelsPanel.test.jsx b/client/src/components/system-resources/ModelsPanel.test.jsxnew file mode 100644index 0000000000..735ce2e96c--- /dev/null+++ b/client/src/components/system-resources/ModelsPanel.test.jsx@@ -0,0 +1,78 @@+import { describe, expect, it, vi } from 'vitest';+import { act, render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++const memory = vi.hoisted(() => ({ publish: null }));+vi.mock('../settings/MemoryManagement.jsx', () => ({+ default: ({ onLoadedModelsChange }) => {+ memory.publish = onLoadedModelsChange;+ return <div>Memory status</div>;+ },+}));++const ModelsPanel = (await import('./ModelsPanel.jsx')).default;++const model = {+ id: 'ollama:example:latest',+ backend: 'ollama',+ name: 'Example model',+ sizeBytes: 1024,+ loaded: false,+ managePath: '/settings/local-llm',+ action: { type: 'local-model', backend: 'ollama', modelId: 'example:latest' },+};+const report = {+ generatedAt: '2026-08-16T00:00:00.000Z',+ sourceErrors: [],+ models: { downloaded: [model], totals: { all: 1024 } },+ cleanupCandidates: [{+ ...model,+ label: model.name,+ estimatedBytes: model.sizeBytes,+ action: model.action,+ busy: false,+ manualOnly: false,+ }],+};+const cleanup = {+ busyId: null,+ locked: false,+ isConfirming: vi.fn(() => false),+ request: vi.fn(),+ cancel: vi.fn(),+ confirm: vi.fn(),+};++describe('ModelsPanel live residency', () => {+ it('revokes a stale delete action when the model becomes resident', () => {+ render(+ <MemoryRouter>+ <ModelsPanel report={report} loading={false} onRunReport={vi.fn()} cleanup={cleanup} />+ </MemoryRouter>,+ );++ expect(screen.getByRole('button', { name: 'Remove Example model' })).toBeInTheDocument();++ act(() => memory.publish({+ ollama: [{ id: 'example:latest', name: 'example:latest' }],+ lmstudio: [],+ sourceErrors: [],+ }));++ expect(screen.getByText('loaded')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Remove Example model' })).not.toBeInTheDocument();+ });++ it('fails closed when live residency becomes unknown', () => {+ render(+ <MemoryRouter>+ <ModelsPanel report={report} loading={false} onRunReport={vi.fn()} cleanup={cleanup} />+ </MemoryRouter>,+ );++ act(() => memory.publish({ ollama: [], lmstudio: [], sourceErrors: ['ollama'] }));++ expect(screen.getByText('status unknown')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Remove Example model' })).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/system-resources/QueuesPanel.jsx b/client/src/components/system-resources/QueuesPanel.jsxnew file mode 100644index 0000000000..738fbac7df--- /dev/null+++ b/client/src/components/system-resources/QueuesPanel.jsx@@ -0,0 +1,148 @@+import { useCallback, useMemo, useState } from 'react';+import { AlertTriangle, Bot, ExternalLink, ListOrdered, PauseCircle, Play, RefreshCw } from 'lucide-react';+import { Link } from 'react-router';+import MediaJobsQueue from '../media/MediaJobsQueue.jsx';+import BrailleSpinner from '../BrailleSpinner.jsx';+import Banner from '../ui/Banner.jsx';+import toast from '../ui/Toast.jsx';+import { useAutoRefetch } from '../../hooks/useAutoRefetch.js';+import * as api from '../../services/api.js';++const taskLabel = (task) => task.title || task.description || task.prompt || task.id;++function CountCard({ label, value, tone = 'text-white' }) {+ return (+ <div className="rounded-xl border border-port-border bg-port-card p-4">+ <div className="text-[11px] uppercase tracking-wide text-gray-500">{label}</div>+ <div className={`mt-1 text-2xl font-bold ${tone}`}>{value}</div>+ </div>+ );+}++export default function QueuesPanel() {+ const [spawningId, setSpawningId] = useState(null);+ const [queueError, setQueueError] = useState(null);+ const fetchTasks = useCallback(() => api.getCosTasks({ silent: true }).then(+ (next) => {+ setQueueError(null);+ return next;+ },+ (error) => {+ setQueueError(error?.message || 'Agent queue status is unavailable');+ throw error;+ },+ ), []);+ const { data, loading, refetch } = useAutoRefetch(+ fetchTasks,+ 5000,+ );+ const tasks = useMemo(() => {+ const user = data?.user?.tasks || [];+ const internal = data?.cos?.tasks || [];+ return [+ ...user.map((task) => ({ ...task, source: 'user' })),+ ...internal.map((task) => ({ ...task, source: 'internal' })),+ ];+ }, [data]);+ const pending = tasks.filter((task) => task.status === 'pending');+ const running = tasks.filter((task) => task.status === 'in_progress');+ const awaitingApproval = pending.filter((task) => task.approvalRequired);+ const queueKnown = data != null;++ const runNow = async (task) => {+ setSpawningId(task.id);+ const result = await api.forceSpawnTask(task.id, { silent: true }).catch((error) => {+ toast.error(error?.message || 'Could not start task');+ return null;+ });+ setSpawningId(null);+ if (!result) return;+ toast.success(`Spawning ${task.id}`);+ refetch();+ };++ return (+ <div className="space-y-4">+ <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">+ <CountCard label="Agent pending" value={queueKnown ? pending.length : '—'} tone={queueKnown && pending.length ? 'text-port-warning' : 'text-white'} />+ <CountCard label="Agent running" value={queueKnown ? running.length : '—'} tone={queueKnown && running.length ? 'text-port-accent' : 'text-white'} />+ <CountCard label="Need approval" value={queueKnown ? awaitingApproval.length : '—'} tone={queueKnown && awaitingApproval.length ? 'text-purple-300' : 'text-white'} />+ <CountCard label="Queue sources" value={queueKnown ? '2' : '—'} />+ </div>++ <MediaJobsQueue className="min-h-[120px]" />++ <section className="rounded-2xl border border-port-border bg-port-card p-4 sm:p-5">+ <div className="flex items-center justify-between gap-3">+ <div className="flex items-center gap-2">+ <Bot size={17} className="text-port-accent" />+ <div>+ <h3 className="font-semibold text-white">Agent task queue</h3>+ <p className="text-xs text-gray-500">User tasks and autonomous system work.</p>+ </div>+ </div>+ <div className="flex items-center gap-1">+ <Link to="/cos/tasks" className="inline-flex min-h-[36px] items-center gap-1 rounded-lg px-2 text-xs text-port-accent hover:bg-port-accent/10">+ Full queue <ExternalLink size={12} />+ </Link>+ <button type="button" onClick={refetch} className="grid h-9 w-9 place-items-center rounded-lg text-gray-400 hover:bg-port-border/40 hover:text-white" aria-label="Refresh agent queue">+ <RefreshCw size={14} />+ </button>+ </div>+ </div>++ {queueError && (+ <Banner className="mt-4" tone="warning" icon={AlertTriangle}>+ Agent queue refresh failed. {queueKnown ? 'Showing the last known snapshot.' : 'Counts and pending work are unknown.'}+ </Banner>+ )}++ {loading && !queueKnown ? (+ <div className="mt-4 text-sm text-gray-400"><BrailleSpinner text="Loading agent queue…" /></div>+ ) : !queueKnown ? (+ <div className="mt-4 rounded-xl bg-port-warning/5 p-4 text-sm text-port-warning">+ Agent queue status is unavailable.+ </div>+ ) : pending.length === 0 ? (+ <div className="mt-4 flex items-center gap-2 rounded-xl bg-port-success/5 p-4 text-sm text-port-success">+ <ListOrdered size={16} /> No pending agent tasks.+ </div>+ ) : (+ <div className="mt-4 space-y-2">+ {pending.map((task) => (+ <div key={`${task.source}:${task.id}`} className="flex flex-col gap-3 rounded-xl bg-port-bg/40 p-3 sm:flex-row sm:items-center">+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2">+ <span className="font-mono text-xs text-gray-500">{task.id}</span>+ <span className="rounded bg-port-border px-1.5 py-0.5 text-[10px] uppercase text-gray-400">{task.source}</span>+ {task.approvalRequired && <span className="rounded bg-purple-500/10 px-1.5 py-0.5 text-[10px] uppercase text-purple-300">approval required</span>}+ </div>+ <p className="mt-1 line-clamp-2 text-sm text-gray-200">{taskLabel(task)}</p>+ </div>+ {task.approvalRequired ? (+ <Link+ to={`/cos/tasks?task=${encodeURIComponent(task.id)}&source=${task.source}`}+ aria-label={`Review task ${task.id}`}+ className="inline-flex min-h-[36px] items-center justify-center gap-1 rounded-lg border border-purple-500/30 px-3 py-1.5 text-xs text-purple-300 hover:bg-purple-500/10"+ >+ <PauseCircle size={13} /> Review+ </Link>+ ) : (+ <button+ type="button"+ onClick={() => runNow(task)}+ disabled={spawningId != null}+ aria-label={spawningId === task.id ? `Starting task ${task.id}` : `Run task ${task.id} now`}+ className="inline-flex min-h-[36px] items-center justify-center gap-1.5 rounded-lg bg-port-accent/15 px-3 py-1.5 text-xs font-medium text-port-accent hover:bg-port-accent/25 disabled:opacity-50"+ >+ <Play size={13} /> {spawningId === task.id ? 'Starting…' : 'Run now'}+ </button>+ )}+ </div>+ ))}+ </div>+ )}+ </section>+ </div>+ );+}diff --git a/client/src/components/system-resources/QueuesPanel.test.jsx b/client/src/components/system-resources/QueuesPanel.test.jsxnew file mode 100644index 0000000000..399d875b2c--- /dev/null+++ b/client/src/components/system-resources/QueuesPanel.test.jsx@@ -0,0 +1,52 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++const api = vi.hoisted(() => ({+ getCosTasks: vi.fn(),+ forceSpawnTask: vi.fn(),+}));++vi.mock('../../services/api.js', () => api);+vi.mock('../media/MediaJobsQueue.jsx', () => ({+ default: () => <div>Media queue</div>,+}));++const QueuesPanel = (await import('./QueuesPanel.jsx')).default;++const renderPanel = () => render(+ <MemoryRouter>+ <QueuesPanel />+ </MemoryRouter>,+);++describe('QueuesPanel', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('renders an unknown state instead of a false empty queue after a failed probe', async () => {+ api.getCosTasks.mockRejectedValue(new Error('offline'));++ renderPanel();++ expect(await screen.findByText('Agent queue status is unavailable.')).toBeInTheDocument();+ expect(screen.queryByText('No pending agent tasks.')).not.toBeInTheDocument();+ expect(screen.getAllByText('—')).toHaveLength(4);+ });++ it('gives repeated task actions unique names and task-specific deep links', async () => {+ api.getCosTasks.mockResolvedValue({+ user: { tasks: [{ id: 'user/42', description: 'Run an example task', status: 'pending' }] },+ cos: { tasks: [{ id: 'review-7', description: 'Review an example task', status: 'pending', approvalRequired: true }] },+ });++ renderPanel();++ expect(await screen.findByRole('button', { name: 'Run task user/42 now' })).toBeInTheDocument();+ expect(screen.getByRole('link', { name: 'Review task review-7' })).toHaveAttribute(+ 'href',+ '/cos/tasks?task=review-7&source=internal',+ );+ });+});diff --git a/client/src/components/system-resources/StoragePanel.jsx b/client/src/components/system-resources/StoragePanel.jsxnew file mode 100644index 0000000000..50938f8c68--- /dev/null+++ b/client/src/components/system-resources/StoragePanel.jsx@@ -0,0 +1,304 @@+import { useEffect, useRef, useState } from 'react';+import { AlertTriangle, Bot, CheckCircle2, Database, HardDrive, RefreshCw, ShieldCheck, Sparkles } from 'lucide-react';+import { Link } from 'react-router';+import ProviderModelSelector from '../ProviderModelSelector.jsx';+import Banner from '../ui/Banner.jsx';+import CleanupControl from './CleanupControl.jsx';+import useProviderModels from '../../hooks/useProviderModels.js';+import { formatBytes } from '../../utils/formatters.js';+import * as api from '../../services/api.js';+import toast from '../ui/Toast.jsx';++const RISK_STYLE = {+ low: 'bg-port-success/10 text-port-success',+ medium: 'bg-port-warning/10 text-port-warning',+ high: 'bg-port-error/10 text-port-error',+};++const storageSize = (bytes) => (Number.isFinite(bytes) ? formatBytes(bytes) : 'Unavailable');++function ReportEmpty({ loading, onRun }) {+ return (+ <section className="rounded-2xl border border-dashed border-port-accent/40 bg-port-accent/5 px-5 py-8 text-center">+ <HardDrive className="mx-auto mb-3 text-port-accent" size={28} />+ <h3 className="font-semibold text-white">Build a storage inventory</h3>+ <p className="mx-auto mt-2 max-w-2xl text-sm text-gray-400">+ Scan PortOS data, PostgreSQL, model stores, package caches, dependencies, and aggregate Downloads usage.+ The report does not inspect personal filenames.+ </p>+ <button+ type="button"+ onClick={onRun}+ disabled={loading}+ className="mt-4 inline-flex min-h-[40px] items-center gap-2 rounded-lg bg-port-accent px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-port-accent/80 disabled:opacity-50"+ >+ <RefreshCw size={15} className={loading ? 'animate-spin' : ''} />+ {loading ? 'Scanning…' : 'Run system report'}+ </button>+ </section>+ );+}++function DiskGauge({ filesystem }) {+ if (!filesystem) return null;+ const pct = Math.min(100, Math.max(0, filesystem.usagePercent));+ const color = pct >= 98 ? '#ef4444' : pct >= 90 ? '#f59e0b' : '#22c55e';+ return (+ <section className="rounded-2xl border border-port-border bg-port-card p-5">+ <div className="grid items-center gap-5 md:grid-cols-[160px_1fr]">+ <div+ className="relative mx-auto grid h-36 w-36 place-items-center rounded-full"+ style={{ background: `conic-gradient(${color} ${pct}%, rgba(75,85,99,.25) ${pct}% 100%)` }}+ role="meter"+ aria-label={`${pct}% disk used`}+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={pct}+ >+ <div className="grid h-28 w-28 place-items-center rounded-full bg-port-card text-center">+ <div>+ <div className="text-3xl font-bold text-white">{pct}%</div>+ <div className="text-xs text-gray-500">disk used</div>+ </div>+ </div>+ </div>+ <div>+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">+ <Metric label="Used" value={formatBytes(filesystem.usedBytes)} />+ <Metric label="Free" value={formatBytes(filesystem.freeBytes)} tone="text-port-success" />+ <Metric label="Capacity" value={formatBytes(filesystem.totalBytes)} className="col-span-2 sm:col-span-1" />+ </div>+ <p className="mt-4 text-xs leading-relaxed text-gray-500">+ Known-area totals below may overlap: LoRAs are part of PortOS data, and model stores may use shared layers or hardlinks.+ </p>+ </div>+ </div>+ </section>+ );+}++function Metric({ label, value, tone = 'text-white', className = '' }) {+ return (+ <div className={`rounded-xl bg-port-bg/50 p-3 ${className}`}>+ <div className="text-[11px] uppercase tracking-wide text-gray-500">{label}</div>+ <div className={`mt-1 text-lg font-semibold ${tone}`}>{value}</div>+ </div>+ );+}++function StorageAreas({ areas }) {+ const max = Math.max(1, ...(areas || []).map((area) => area.sizeBytes || 0));+ return (+ <section className="rounded-2xl border border-port-border bg-port-card p-4 sm:p-5">+ <div className="mb-4 flex items-center gap-2">+ <Database size={17} className="text-port-accent" />+ <h3 className="font-semibold text-white">Known storage areas</h3>+ </div>+ <div className="space-y-3">+ {(areas || []).map((area) => (+ <div key={area.id} className="rounded-xl bg-port-bg/40 p-3">+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-sm font-medium text-gray-200">{area.label}</span>+ {area.protected && <span className="rounded bg-port-border px-1.5 py-0.5 text-[10px] uppercase text-gray-500">protected</span>}+ </div>+ <p className="mt-0.5 text-xs text-gray-500">{area.note}</p>+ </div>+ <div className="shrink-0 text-sm font-semibold tabular-nums text-white">{storageSize(area.sizeBytes)}</div>+ </div>+ <div className="mt-2 h-1.5 overflow-hidden rounded-full bg-port-border/60">+ <div+ className="h-full rounded-full bg-gradient-to-r from-port-accent to-cyan-400"+ style={{ width: area.status === 'unavailable' ? '0%' : `${Math.max(1, ((area.sizeBytes || 0) / max) * 100)}%` }}+ />+ </div>+ {area.managePath && (+ <Link to={area.managePath} className="mt-2 inline-block text-xs text-port-accent hover:text-port-accent/80">+ Manage {area.label.toLowerCase()} →+ </Link>+ )}+ </div>+ ))}+ </div>+ </section>+ );+}++function CandidateRows({ candidates, cleanup }) {+ return (+ <section className="rounded-2xl border border-port-border bg-port-card p-4 sm:p-5">+ <div className="mb-1 flex items-center gap-2">+ <ShieldCheck size={17} className="text-port-success" />+ <h3 className="font-semibold text-white">Cleanup candidates</h3>+ </div>+ <p className="mb-4 text-xs text-gray-500">Only known, bounded PortOS categories get one-click removal. Every destructive action asks for confirmation.</p>+ <div className="space-y-2">+ {(candidates || []).length === 0 ? (+ <p className="rounded-xl bg-port-bg/40 p-4 text-sm text-gray-500">No managed cleanup candidates were found.</p>+ ) : candidates.map((candidate) => (+ <div key={candidate.id} className="flex flex-col gap-3 rounded-xl bg-port-bg/40 p-3 sm:flex-row sm:items-center">+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2">+ <span className="font-medium text-gray-200">{candidate.label}</span>+ <span className={`rounded px-1.5 py-0.5 text-[10px] font-medium uppercase ${RISK_STYLE[candidate.risk] || RISK_STYLE.medium}`}>+ {candidate.risk} risk+ </span>+ {candidate.loaded && <span className="rounded bg-purple-500/10 px-1.5 py-0.5 text-[10px] uppercase text-purple-300">loaded</span>}+ {candidate.busy && <span className="rounded bg-port-warning/10 px-1.5 py-0.5 text-[10px] uppercase text-port-warning">busy</span>}+ </div>+ <div className="mt-1 text-sm font-semibold tabular-nums text-white">{storageSize(candidate.estimatedBytes)}</div>+ <p className="mt-1 text-xs leading-relaxed text-gray-500">{candidate.reason}</p>+ </div>+ <CleanupControl+ candidate={candidate}+ busy={cleanup.busyId === candidate.id}+ disabled={cleanup.locked}+ confirming={cleanup.isConfirming(candidate.id)}+ onRequest={() => cleanup.request(candidate.id)}+ onCancel={cleanup.cancel}+ onConfirm={() => cleanup.confirm(candidate)}+ />+ </div>+ ))}+ </div>+ </section>+ );+}++function AiTriage({ report, onReport }) {+ const [effort, setEffort] = useState('');+ const [running, setRunning] = useState(false);+ const [triage, setTriage] = useState(null);+ const reportGeneratedAtRef = useRef(report.generatedAt);+ reportGeneratedAtRef.current = report.generatedAt;+ const {+ providers, selectedProviderId, selectedModel, availableModels,+ setSelectedProviderId, setSelectedModel, loading,+ } = useProviderModels({ silent: true, withEffort: true });++ useEffect(() => {+ setTriage((current) => (+ current && current.reportGeneratedAt !== report.generatedAt ? null : current+ ));+ }, [report.generatedAt]);++ const run = async () => {+ if (!selectedProviderId) {+ toast.error('Choose an enabled AI provider first');+ return;+ }+ const startingReportGeneratedAt = reportGeneratedAtRef.current;+ setRunning(true);+ const result = await api.triageSystemResources({+ providerId: selectedProviderId,+ model: selectedModel || undefined,+ effort: effort || undefined,+ }, { silent: true }).catch((error) => {+ toast.error(error?.message || 'AI triage failed');+ return null;+ });+ setRunning(false);+ if (!result || reportGeneratedAtRef.current !== startingReportGeneratedAt) return;+ setTriage({ reportGeneratedAt: result.report.generatedAt, result: result.triage });+ onReport(result.report);+ };++ return (+ <section className="overflow-hidden rounded-2xl border border-purple-500/30 bg-gradient-to-br from-purple-500/10 via-port-card to-port-card p-4 sm:p-5">+ <div className="flex items-start gap-3">+ <div className="rounded-lg bg-purple-500/15 p-2 text-purple-300"><Bot size={19} /></div>+ <div className="min-w-0 flex-1">+ <h3 className="font-semibold text-white">AI cleanup triage</h3>+ <p className="mt-1 text-xs leading-relaxed text-gray-400">+ The selected model receives only aggregate metrics and the bounded candidate list—never paths, filenames, record names, or file contents.+ </p>+ </div>+ </div>+ <div className="mt-4">+ <ProviderModelSelector+ providers={providers}+ selectedProviderId={selectedProviderId}+ selectedModel={selectedModel}+ availableModels={availableModels}+ onProviderChange={setSelectedProviderId}+ onModelChange={setSelectedModel}+ disabled={loading || running}+ effort={effort}+ onEffortChange={setEffort}+ layout="stacked"+ label="Triage provider"+ />+ </div>+ <button+ type="button"+ onClick={run}+ disabled={loading || running || !selectedProviderId || report.cleanupCandidates.length === 0}+ className="mt-4 inline-flex min-h-[40px] items-center gap-2 rounded-lg bg-purple-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-purple-400 disabled:opacity-50"+ >+ <Sparkles size={15} className={running ? 'animate-pulse' : ''} />+ {running ? 'Analyzing candidates…' : 'Ask AI to triage'}+ </button>++ {triage && (+ <div className="mt-5 space-y-3 border-t border-purple-500/20 pt-4">+ <p className="text-sm leading-relaxed text-gray-200">{triage.result.summary}</p>+ {triage.result.recommendations.map((item, index) => (+ <div key={item.candidate.id} className="rounded-xl border border-port-border bg-port-bg/50 p-3">+ <div className="flex items-start gap-2">+ <span className="mt-0.5 grid h-5 w-5 shrink-0 place-items-center rounded-full bg-purple-500/20 text-[11px] font-bold text-purple-300">{index + 1}</span>+ <div>+ <div className="flex flex-wrap items-center gap-2">+ <span className="font-medium text-white">{item.candidate.label}</span>+ <span className="text-xs uppercase text-purple-300">{item.priority}</span>+ <span className="text-xs text-gray-500">{storageSize(item.candidate.estimatedBytes)}</span>+ </div>+ <p className="mt-1 text-xs text-gray-300">{item.reason}</p>+ <p className="mt-1 text-xs text-gray-500">Tradeoff: {item.tradeoff}</p>+ </div>+ </div>+ </div>+ ))}+ {triage.result.cautions.length > 0 && (+ <div className="rounded-xl bg-port-warning/10 p-3 text-xs text-port-warning">+ {triage.result.cautions.map((caution) => <div key={caution}>• {caution}</div>)}+ </div>+ )}+ </div>+ )}+ </section>+ );+}++export default function StoragePanel({ report, loading, onRunReport, onReport, cleanup }) {+ if (!report) return <ReportEmpty loading={loading} onRun={onRunReport} />;+ const generated = new Date(report.generatedAt).toLocaleString();+ return (+ <div className="space-y-4">+ <div className="flex flex-col gap-3 rounded-xl border border-port-border bg-port-card p-3 sm:flex-row sm:items-center sm:justify-between">+ <div>+ <div className="flex items-center gap-2 text-sm text-gray-200"><CheckCircle2 size={15} className="text-port-success" /> Report ready</div>+ <div className="mt-0.5 text-xs text-gray-500">Generated {generated}</div>+ </div>+ <button+ type="button"+ onClick={onRunReport}+ disabled={loading || cleanup.locked}+ className="inline-flex min-h-[40px] items-center justify-center gap-2 rounded-lg border border-port-border px-3 py-2 text-sm text-gray-300 transition-colors hover:bg-port-border/40 disabled:opacity-50"+ >+ <RefreshCw size={14} className={loading ? 'animate-spin' : ''} />+ {loading ? 'Scanning…' : 'Refresh report'}+ </button>+ </div>+ {report.sourceErrors.length > 0 && (+ <Banner tone="warning" icon={AlertTriangle}>Some sources were unavailable: {report.sourceErrors.join(', ')}. Other totals remain usable.</Banner>+ )}+ <DiskGauge filesystem={report.filesystem} />+ <div className="grid gap-4 xl:grid-cols-2">+ <StorageAreas areas={report.storageAreas} />+ <CandidateRows candidates={report.cleanupCandidates} cleanup={cleanup} />+ </div>+ <AiTriage report={report} onReport={onReport} />+ </div>+ );+}diff --git a/client/src/components/system-resources/StoragePanel.test.jsx b/client/src/components/system-resources/StoragePanel.test.jsxnew file mode 100644index 0000000000..649359fcf9--- /dev/null+++ b/client/src/components/system-resources/StoragePanel.test.jsx@@ -0,0 +1,107 @@+import { useState } from 'react';+import { describe, expect, it, vi } from 'vitest';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { MemoryRouter } from 'react-router';++const api = vi.hoisted(() => ({ triageSystemResources: vi.fn() }));+vi.mock('../../services/api.js', () => api);+vi.mock('../../hooks/useProviderModels.js', () => ({+ default: () => ({+ providers: [{ id: 'codex', name: 'Codex' }],+ selectedProviderId: 'codex',+ selectedModel: '',+ availableModels: [],+ setSelectedProviderId: vi.fn(),+ setSelectedModel: vi.fn(),+ loading: false,+ }),+}));+vi.mock('../ProviderModelSelector.jsx', () => ({ default: () => <div>Triage provider</div> }));++const StoragePanel = (await import('./StoragePanel.jsx')).default;++const candidate = {+ id: 'data:cache',+ label: 'Cache',+ kind: 'data',+ estimatedBytes: 1024,+ risk: 'low',+ reason: 'Reproducible cache.',+ loaded: false,+ busy: false,+ manualOnly: false,+ managePath: '/data',+ action: { type: 'data-category', key: 'cache' },+};+const makeReport = (generatedAt) => ({+ generatedAt,+ filesystem: { totalBytes: 1000, usedBytes: 700, freeBytes: 300, usagePercent: 70 },+ sourceErrors: [],+ storageAreas: [],+ cleanupCandidates: [candidate],+});+const cleanup = {+ busyId: null,+ locked: false,+ isConfirming: vi.fn(() => false),+ request: vi.fn(),+ cancel: vi.fn(),+ confirm: vi.fn(),+};++function Harness() {+ const [report, setReport] = useState(makeReport('2026-08-16T00:00:00.000Z'));+ return (+ <StoragePanel+ report={report}+ loading={false}+ onRunReport={() => setReport(makeReport('2026-08-16T00:01:00.000Z'))}+ onReport={setReport}+ cleanup={cleanup}+ />+ );+}++describe('StoragePanel AI triage freshness', () => {+ it('clears recommendations when a newer report replaces their candidate snapshot', async () => {+ const user = userEvent.setup();+ const report = makeReport('2026-08-16T00:00:00.000Z');+ api.triageSystemResources.mockResolvedValue({+ report,+ triage: {+ summary: 'Remove the cache first.',+ recommendations: [{ candidate, priority: 'first', reason: 'Safe space.', tradeoff: 'Re-download later.' }],+ cautions: [],+ },+ });+ render(<MemoryRouter><Harness /></MemoryRouter>);++ await user.click(screen.getByRole('button', { name: 'Ask AI to triage' }));+ expect(await screen.findByText('Remove the cache first.')).toBeInTheDocument();++ await user.click(screen.getByRole('button', { name: 'Refresh report' }));+ expect(screen.queryByText('Remove the cache first.')).not.toBeInTheDocument();+ });++ it('discards an in-flight triage response after the report is refreshed', async () => {+ const user = userEvent.setup();+ let finishTriage;+ api.triageSystemResources.mockReturnValue(new Promise((resolve) => { finishTriage = resolve; }));+ render(<MemoryRouter><Harness /></MemoryRouter>);++ await user.click(screen.getByRole('button', { name: 'Ask AI to triage' }));+ await user.click(screen.getByRole('button', { name: 'Refresh report' }));+ finishTriage({+ report: makeReport('2026-08-16T00:00:00.000Z'),+ triage: {+ summary: 'Obsolete advice.',+ recommendations: [],+ cautions: [],+ },+ });++ expect(await screen.findByRole('button', { name: 'Ask AI to triage' })).toBeEnabled();+ expect(screen.queryByText('Obsolete advice.')).not.toBeInTheDocument();+ });+});diff --git a/client/src/hooks/useNavWorkingSet.js b/client/src/hooks/useNavWorkingSet.jsindex 51c672bb01..99feed9498 100644--- a/client/src/hooks/useNavWorkingSet.js+++ b/client/src/hooks/useNavWorkingSet.js@@ -16,6 +16,13 @@ const readList = (key) => {// in-memory React state still updates and the app never crashes on a write.const writeList = (key, list) => safeWriteStorage(key, JSON.stringify(list));+const LEGACY_NAV_PATHS = {+ '/system-health': '/system-resources',+};++const migratePath = (path) => LEGACY_NAV_PATHS[path] || path;+const migratePaths = (paths) => [...new Set(paths.map(migratePath))];+/*** Sidebar working-set state (Pinned + Recent), persisted to localStorage.* @param {(path: string) => ({ path, label, icon } | null)} resolveNavEntry@@ -29,11 +36,11 @@ export function useNavWorkingSet(resolveNavEntry) {// Record the initial visit synchronously so it's present on first render.// The useEffect below handles subsequent navigations only.const [recentPaths, setRecentPaths] = useState(() => {- const initial = recordVisit(location.pathname, readList(RECENT_KEY));+ const initial = recordVisit(location.pathname, migratePaths(readList(RECENT_KEY)));writeList(RECENT_KEY, initial);return initial;});- const [pinnedPaths, setPinnedPaths] = useState(() => readList(PINNED_KEY));+ const [pinnedPaths, setPinnedPaths] = useState(() => migratePaths(readList(PINNED_KEY)));// Track the last recorded path to skip the initial effect (already handled above).const lastRecordedRef = useRef(location.pathname);diff --git a/client/src/hooks/useNavWorkingSet.test.jsx b/client/src/hooks/useNavWorkingSet.test.jsxindex 8548baad7c..8a43e8debd 100644--- a/client/src/hooks/useNavWorkingSet.test.jsx+++ b/client/src/hooks/useNavWorkingSet.test.jsx@@ -42,6 +42,14 @@ describe('useNavWorkingSet', () => {expect(result.current.pinned.map((r) => r.path)).toEqual(['/b']);});+ it('migrates the legacy System Health pin to System Resources', () => {+ localStorage.setItem(PINNED_KEY, JSON.stringify(['/system-health']));+ const { result } = renderHook(() => useNavWorkingSet(resolveNavEntry), { wrapper });++ expect(result.current.pinned.map((row) => row.path)).toEqual(['/system-resources']);+ expect(result.current.isPinned('/system-resources')).toBe(true);+ });+it('excludes pinned and the current path from recent', () => {localStorage.setItem(RECENT_KEY, JSON.stringify(['/start', '/x', '/y']));localStorage.setItem(PINNED_KEY, JSON.stringify(['/x']));diff --git a/client/src/pages/SystemHealthPage.jsx b/client/src/pages/SystemHealthPage.jsxindex 1e03c182a1..66031e8f9f 100644--- a/client/src/pages/SystemHealthPage.jsx+++ b/client/src/pages/SystemHealthPage.jsx@@ -1,11 +1,15 @@-import { useEffect, useState, useRef } from 'react';-import { Link } from 'react-router';-import { Activity, AlertTriangle, CheckCircle, XCircle, HardDrive, Cpu, Database, ServerCog, Zap, RefreshCw } from 'lucide-react';+import { useCallback, useEffect, useState, useRef } from 'react';+import { Link, Navigate, NavLink, useParams } from 'react-router';+import { Activity, AlertTriangle, Boxes, CheckCircle, XCircle, HardDrive, Cpu, Database, ListOrdered, RefreshCw, ServerCog, Zap } from 'lucide-react';import * as api from '../services/api';import toast from '../components/ui/Toast';import PageSkeleton from '../components/ui/PageSkeleton';import Banner from '../components/ui/Banner';import { useAutoRefetch } from '../hooks/useAutoRefetch';+import { useConfirmDelete } from '../hooks/useConfirmDelete.js';+import StoragePanel from '../components/system-resources/StoragePanel.jsx';+import ModelsPanel from '../components/system-resources/ModelsPanel.jsx';+import QueuesPanel from '../components/system-resources/QueuesPanel.jsx';const HEALTH_STYLE = {healthy: { color: 'text-port-success', bg: 'bg-port-success/10', icon: CheckCircle, label: 'Healthy' },@@ -19,7 +23,7 @@ const HEALTH_STYLE = {// `forge` is intentionally absent — its message already embeds gh's own remedy// text and there is no in-app page that fixes it.const REMEDIATION = {- disk: { to: '/data', label: 'Disk usage breakdown' },+ disk: { to: '/system-resources/storage', label: 'Disk usage breakdown' },memory: { to: '/devtools/processes', label: 'All processes' },cpu: { to: '/devtools/processes', label: 'All processes' },process: { to: '/devtools/processes', label: 'All processes' },@@ -46,7 +50,144 @@ function barTone(pct, warn, critical) {return 'bg-port-success';}-export default function SystemHealthPage() {+const RESOURCE_TABS = [+ { id: 'overview', label: 'Overview', icon: Activity },+ { id: 'storage', label: 'Storage', icon: HardDrive },+ { id: 'models', label: 'Models', icon: Boxes },+ { id: 'queues', label: 'Queues', icon: ListOrdered },+];++export default function SystemResourcesPage() {+ const { tab = 'overview' } = useParams();+ const [report, setReport] = useState(null);+ const [reportLoading, setReportLoading] = useState(false);+ const [cleanupBusyId, setCleanupBusyId] = useState(null);+ const reportRequestGenerationRef = useRef(0);+ const cleanupBusyRef = useRef(null);+ const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();++ const runReport = useCallback(async () => {+ const generation = ++reportRequestGenerationRef.current;+ cancelDelete();+ setReportLoading(true);+ const outcome = await api.runSystemResourceReport({ silent: true }).then(+ (value) => ({ value }),+ (error) => ({ error }),+ );+ // Explicit refreshes and post-cleanup reconciliation can overlap. Only the+ // newest request may own the report or loading state; an older disk scan+ // must not resurrect candidates the newer scan already removed.+ if (generation !== reportRequestGenerationRef.current) return outcome.value || null;+ setReportLoading(false);+ if (outcome.error) {+ toast.error(outcome.error?.message || 'System report failed');+ return null;+ }+ if (outcome.value) setReport(outcome.value);+ return outcome.value || null;+ }, [cancelDelete]);++ const removeCandidate = useCallback(async (candidate) => {+ const action = candidate.action;+ if (!action || cleanupBusyRef.current) return;+ cleanupBusyRef.current = candidate.id;+ setCleanupBusyId(candidate.id);+ const result = await (async () => {+ if (action.type === 'data-category') {+ return api.purgeDataCategory(action.key, {}, { silent: true });+ }+ if (action.type === 'hf-model') {+ return api.deleteCachedModel(action.dirName, { silent: true });+ }+ if (action.type === 'lora') {+ return api.deleteLora(action.filename, { silent: true });+ }+ if (action.type === 'local-model') {+ return api.deleteLocalLlmModel(action.backend, action.modelId, { silent: true });+ }+ return null;+ })().catch((error) => {+ toast.error(error?.message || `Could not remove ${candidate.label}`);+ return null;+ });+ if (!result) {+ cleanupBusyRef.current = null;+ setCleanupBusyId(null);+ return;+ }+ // Invalidate every server-issued action immediately. The old row must not+ // become clickable again during the follow-up scan, and unmounting Storage+ // also drops any AI recommendations tied to the obsolete report.+ setReport(null);+ toast.success(`${candidate.label} removed`);+ await runReport();+ cleanupBusyRef.current = null;+ setCleanupBusyId(null);+ }, [runReport]);++ const cleanup = {+ busyId: cleanupBusyId,+ locked: cleanupBusyId != null || reportLoading,+ isConfirming,+ request: requestDelete,+ cancel: cancelDelete,+ confirm: (candidate) => confirmDelete(() => removeCandidate(candidate)),+ };++ const validTab = RESOURCE_TABS.some((item) => item.id === tab);+ if (!validTab) return <Navigate to="/system-resources/overview" replace />;++ return (+ <div className="mx-auto max-w-7xl space-y-4">+ <header className="overflow-hidden rounded-2xl border border-port-border bg-gradient-to-r from-port-card via-port-card to-port-accent/10 p-4 sm:p-5">+ <div className="flex items-start gap-3">+ <div className="rounded-xl bg-port-accent/15 p-2.5 text-port-accent"><ServerCog size={22} /></div>+ <div>+ <h1 className="text-xl font-bold text-white">System Resources</h1>+ <p className="mt-1 max-w-3xl text-sm text-gray-400">+ Health, disk intelligence, loaded models, and active work queues in one control center.+ </p>+ </div>+ </div>+ <nav aria-label="System resources sections" className="mt-5 grid grid-cols-4 border-b border-port-border sm:flex sm:gap-1">+ {RESOURCE_TABS.map(({ id, label, icon: Icon }) => (+ <NavLink+ key={id}+ to={`/system-resources/${id}`}+ className={({ isActive }) => `flex min-h-[40px] items-center justify-center gap-1 border-b-2 px-1 py-2 text-xs transition-colors sm:shrink-0 sm:gap-1.5 sm:px-3 sm:text-sm ${+ isActive ? 'border-port-accent text-white' : 'border-transparent text-gray-500 hover:text-gray-200'+ }`}+ >+ <Icon size={14} /> {label}+ </NavLink>+ ))}+ </nav>+ </header>++ {tab === 'overview' && <SystemHealthOverview />}+ {tab === 'storage' && (+ <StoragePanel+ report={report}+ loading={reportLoading}+ onRunReport={runReport}+ onReport={setReport}+ cleanup={cleanup}+ />+ )}+ {tab === 'models' && (+ <ModelsPanel+ report={report}+ loading={reportLoading}+ onRunReport={runReport}+ cleanup={cleanup}+ />+ )}+ {tab === 'queues' && <QueuesPanel />}+ </div>+ );+}++function SystemHealthOverview() {const [draft, setDraft] = useState(null);const [saving, setSaving] = useState(false);const [refreshing, setRefreshing] = useState(false);@@ -131,7 +272,7 @@ export default function SystemHealthPage() {<div className="flex flex-wrap items-center justify-between gap-3"><h2 className="text-xl font-bold text-white flex items-center gap-2"><ServerCog size={20} />- System Health+ Live health</h2><div className="flex flex-wrap items-center justify-end gap-2"><button@@ -243,10 +384,10 @@ export default function SystemHealthPage() {<span className="text-xs text-gray-500">Tune to your machine. Defaults: 85/95 mem, 90/98 disk.</span></div><div className="grid grid-cols-2 sm:grid-cols-4 gap-3">- <ThresholdField label="Memory warn %" value={draft?.memoryWarn} onChange={(v) => setDraft(d => ({ ...d, memoryWarn: v }))} />- <ThresholdField label="Memory critical %" value={draft?.memoryCritical} onChange={(v) => setDraft(d => ({ ...d, memoryCritical: v }))} />- <ThresholdField label="Disk warn %" value={draft?.diskWarn} onChange={(v) => setDraft(d => ({ ...d, diskWarn: v }))} />- <ThresholdField label="Disk critical %" value={draft?.diskCritical} onChange={(v) => setDraft(d => ({ ...d, diskCritical: v }))} />+ <ThresholdField id="system-health-memory-warn" label="Memory warn %" value={draft?.memoryWarn} onChange={(v) => setDraft(d => ({ ...d, memoryWarn: v }))} />+ <ThresholdField id="system-health-memory-critical" label="Memory critical %" value={draft?.memoryCritical} onChange={(v) => setDraft(d => ({ ...d, memoryCritical: v }))} />+ <ThresholdField id="system-health-disk-warn" label="Disk warn %" value={draft?.diskWarn} onChange={(v) => setDraft(d => ({ ...d, diskWarn: v }))} />+ <ThresholdField id="system-health-disk-critical" label="Disk critical %" value={draft?.diskCritical} onChange={(v) => setDraft(d => ({ ...d, diskCritical: v }))} /></div>{!draftValid && (<p className="mt-2 text-xs text-port-error">Warn thresholds must be lower than critical thresholds.</p>@@ -290,11 +431,12 @@ function ResourceCard({ icon: Icon, label, pct, warn, critical, sub }) {);}-function ThresholdField({ label, value, onChange }) {+function ThresholdField({ id, label, value, onChange }) {return (- <label className="flex flex-col gap-1 text-xs text-gray-400">+ <label htmlFor={id} className="flex flex-col gap-1 text-xs text-gray-400"><span>{label}</span><input+ id={id}type="number"min={50}max={99}diff --git a/client/src/pages/SystemHealthPage.test.jsx b/client/src/pages/SystemHealthPage.test.jsxindex ff09c86526..48698ac8eb 100644--- a/client/src/pages/SystemHealthPage.test.jsx+++ b/client/src/pages/SystemHealthPage.test.jsx@@ -1,7 +1,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, within, waitFor } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';-import { MemoryRouter } from 'react-router';+import { MemoryRouter, Route, Routes } from 'react-router';const HEALTH = {overallHealth: 'warning',@@ -21,6 +21,24 @@ const withWarnings = warnings => ({ ...HEALTH, warnings });vi.mock('../services/api', () => ({getSystemHealth: vi.fn(),updateHealthThresholds: vi.fn(() => Promise.resolve({})),+ runSystemResourceReport: vi.fn(),+ triageSystemResources: vi.fn(),+ purgeDataCategory: vi.fn(),+ deleteCachedModel: vi.fn(),+ deleteLora: vi.fn(),+ deleteLocalLlmModel: vi.fn(),+}));++vi.mock('../hooks/useProviderModels', () => ({+ default: () => ({+ providers: [],+ selectedProviderId: '',+ selectedModel: '',+ availableModels: [],+ setSelectedProviderId: vi.fn(),+ setSelectedModel: vi.fn(),+ loading: false,+ }),}));vi.mock('../components/ui/Toast', () => ({@@ -30,9 +48,11 @@ vi.mock('../components/ui/Toast', () => ({import * as api from '../services/api';import SystemHealthPage from './SystemHealthPage';-const renderPage = () => render(- <MemoryRouter>- <SystemHealthPage />+const renderPage = (path = '/system-resources/overview') => render(+ <MemoryRouter initialEntries={[path]}>+ <Routes>+ <Route path="/system-resources/:tab" element={<SystemHealthPage />} />+ </Routes></MemoryRouter>);@@ -49,7 +69,7 @@ describe('SystemHealthPage remediation links', () => {const banner = (await screen.findByText('Disk usage at or above 90%')).parentElement;// The alert itself carries the link, not just the drill-in nav below it.- expect(within(banner).getByRole('link', { name: /Disk usage breakdown/ })).toHaveAttribute('href', '/data');+ expect(within(banner).getByRole('link', { name: /Disk usage breakdown/ })).toHaveAttribute('href', '/system-resources/storage');});it('links memory, process and app alerts to their own remediation page', async () => {@@ -104,4 +124,76 @@ describe('SystemHealthPage remediation links', () => {await waitFor(() => expect(screen.getByText('55%')).toBeInTheDocument());expect(api.getSystemHealth).toHaveBeenCalledTimes(2);});++ it('keeps the active section in the URL and runs storage scans explicitly', async () => {+ api.runSystemResourceReport.mockResolvedValue({+ generatedAt: '2026-08-16T00:00:00.000Z',+ filesystem: { totalBytes: 1000, usedBytes: 750, freeBytes: 250, usagePercent: 75 },+ summary: { managedReclaimableBytes: 100 },+ storageAreas: [{+ id: 'cache', label: 'Cache', kind: 'cache', sizeBytes: 100,+ status: 'ready', managePath: null, protected: false, note: 'Reproducible data.',+ }],+ cleanupCandidates: [],+ sourceErrors: [],+ models: { downloaded: [], loaded: [], totals: { all: 0 } },+ queues: { media: { queued: 0, running: 0 }, agents: null },+ });+ renderPage('/system-resources/storage');++ expect(screen.getByRole('link', { name: /Storage/ })).toHaveAttribute('href', '/system-resources/storage');+ expect(api.runSystemResourceReport).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Run system report' }));+ await waitFor(() => expect(api.runSystemResourceReport).toHaveBeenCalledWith({ silent: true }));+ expect(await screen.findByText('Known storage areas')).toBeInTheDocument();+ });++ it('locks every cleanup action and invalidates stale rows until reconciliation finishes', async () => {+ let finishRemoval;+ let finishRescan;+ const removal = new Promise((resolve) => { finishRemoval = resolve; });+ const rescan = new Promise((resolve) => { finishRescan = resolve; });+ const candidate = (key) => ({+ id: `data:${key}`,+ label: `Cache ${key.toUpperCase()}`,+ kind: 'data',+ estimatedBytes: 100,+ risk: 'low',+ reason: 'Reproducible cache.',+ loaded: false,+ busy: false,+ manualOnly: false,+ managePath: '/data',+ action: { type: 'data-category', key },+ });+ const firstReport = {+ generatedAt: '2026-08-16T00:00:00.000Z',+ filesystem: { totalBytes: 1000, usedBytes: 750, freeBytes: 250, usagePercent: 75 },+ summary: { managedReclaimableBytes: 200 },+ storageAreas: [],+ cleanupCandidates: [candidate('a'), candidate('b')],+ sourceErrors: [],+ models: { downloaded: [], loaded: [], totals: { all: 0 } },+ queues: { media: { queued: 0, running: 0 }, agents: null },+ };+ api.runSystemResourceReport+ .mockResolvedValueOnce(firstReport)+ .mockReturnValueOnce(rescan);+ api.purgeDataCategory.mockReturnValue(removal);+ renderPage('/system-resources/storage');++ fireEvent.click(screen.getByRole('button', { name: 'Run system report' }));+ expect(await screen.findByRole('button', { name: 'Remove Cache A' })).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Remove Cache A' }));+ fireEvent.click(within(screen.getByRole('group', { name: 'Confirm removal of Cache A' })).getByRole('button', { name: 'Remove' }));++ await waitFor(() => expect(api.purgeDataCategory).toHaveBeenCalledWith('a', {}, { silent: true }));+ expect(screen.getByRole('button', { name: 'Remove Cache B' })).toBeDisabled();++ await act(async () => { finishRemoval({ success: true }); });+ await waitFor(() => expect(screen.queryByText('Cache A')).not.toBeInTheDocument());+ expect(screen.queryByRole('button', { name: 'Remove Cache B' })).not.toBeInTheDocument();++ await act(async () => { finishRescan({ ...firstReport, generatedAt: '2026-08-16T00:01:00.000Z', cleanupCandidates: [] }); });+ });});diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex 0d3360866f..4c699a16f7 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -30,8 +30,8 @@ export const getLocalLlmHuggingFaceSearch = (backend, q = '', category = 'all',export const installLocalLlmModel = (backend, modelId, options) =>request('/local-llm/install', { method: 'POST', body: JSON.stringify({ backend, modelId }), ...options });-export const deleteLocalLlmModel = (backend, modelId) =>- request('/local-llm/delete', { method: 'POST', body: JSON.stringify({ backend, modelId }) });+export const deleteLocalLlmModel = (backend, modelId, options = {}) =>+ request('/local-llm/delete', { method: 'POST', body: JSON.stringify({ backend, modelId }), ...options });export const installLocalLlmBackend = (backend) =>request('/local-llm/install-backend', { method: 'POST', body: JSON.stringify({ backend }) });@@ -63,9 +63,7 @@ export const migrateLocalLlmBackend = (to, mode = 'link') =>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.+// Force a local backend to evict a model immediately.export const unloadOllamaModel = (modelId, options) =>request('/local-llm/unload', {method: 'POST',@@ -73,6 +71,13 @@ export const unloadOllamaModel = (modelId, options) =>...options,});+export const unloadLmStudioModel = (modelId, options) =>+ request('/lmstudio/unload', {+ method: 'POST',+ body: JSON.stringify({ modelId }),+ ...options,+ });+export const testLocalLlmModel = (payload, options) =>request('/local-llm/test', { method: 'POST', body: JSON.stringify(payload), ...options });diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 3f750a1f67..8b45d6db4c 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -24,6 +24,15 @@ export const getCharacter = ({ skills = true, metrics = true, ...options } = {})// Healthexport const checkHealth = (options) => request('/system/health', options);export const getSystemHealth = (options) => request('/system/health/details', options);+export const runSystemResourceReport = (options = {}) => request('/system-resources/report', {+ method: 'POST',+ ...options,+});+export const triageSystemResources = (payload, options = {}) => request('/system-resources/triage', {+ method: 'POST',+ body: JSON.stringify(payload),+ ...options,+});export const getNetworkExposure = (options) => request('/network-exposure/status', options);export const getCapabilities = (options) => request('/capabilities', options);export const updateHealthThresholds = (thresholds, options = {}) => request('/system/health/thresholds', {@@ -147,7 +156,11 @@ export const restoreDatabase = (data, options) => request('/backup/restore-db',export const getDataOverview = () => request('/data');export const getDataCategory = (key) => request(`/data/${key}`);export const archiveDataCategory = (key, opts) => request(`/data/${key}/archive`, { method: 'POST', body: JSON.stringify(opts || {}) });-export const purgeDataCategory = (key, opts) => request(`/data/${key}`, { method: 'DELETE', body: JSON.stringify(opts || {}) });+export const purgeDataCategory = (key, opts, options = {}) => request(`/data/${key}`, {+ method: 'DELETE',+ body: JSON.stringify(opts || {}),+ ...options,+});export const getDataBackups = () => request('/data/backups');export const deleteDataBackup = (filename) => request(`/data/backups/${filename}`, { method: 'DELETE' });diff --git a/server/index.js b/server/index.jsindex 8499570d59..338421f242 100644--- a/server/index.js+++ b/server/index.js@@ -13,6 +13,7 @@ import alertsRoutes from './routes/alerts.js';import appleHealthRoutes from './routes/appleHealth.js';import avatarRoutes from './routes/avatar.js';import systemHealthRoutes from './routes/systemHealth.js';+import systemResourcesRoutes from './routes/systemResources.js';import capabilitiesRoutes from './routes/capabilities.js';import agentContextMcpRoutes from './routes/agentContextMcp.js';import appsRoutes from './routes/apps/index.js';@@ -235,6 +236,7 @@ app.use('/api/auth', authRoutes);app.use('/api/alerts', alertsRoutes);app.use('/api/avatar', avatarRoutes);app.use('/api/system', systemHealthRoutes);+app.use('/api/system-resources', systemResourcesRoutes);app.use('/api/capabilities', capabilitiesRoutes);app.use('/api/agent-context', agentContextMcpRoutes);app.use('/api/apps', appsRoutes);diff --git a/server/lib/README.md b/server/lib/README.mdindex e00f9a29c7..d143a44d32 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -159,7 +159,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from every `pruneTombstoned*` path — universe/series/issue/collection) so the side store doesn't grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. || `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. || `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |-| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), `saveBase64Upload(dir, { filename, data }, { allowedExtensions, maxBytes })` + `serveLocalFile(res, dir, filename, opts?)` (shared attachment upload/serve pipeline — allowlist, size cap, `<uuid8>-name`, containment guard, nosniff/disposition), extension allowlists (`ATTACHMENT_ALLOWED_EXTENSIONS`, `SONGBOOK_ATTACHMENT_EXTENSIONS`), `assertSafeFilename(name, {extensions, subject})` (throwing basename/traversal/extension gate) plus its non-throwing twin `isSafeFilename(name, extensions)` for read-only callers that must report a bad stored name as data rather than 400 the request — both share one implementation so the gate and the verdict can't drift, and `isTopLevelEntryName(name)` is that shared traversal half on its own, for callers that can't allowlist extensions (arbitrary user assets, directory entries) but still must refuse separators so no intermediate component is left for a symlink to redirect, `readFileTail(path, maxBytes)` (bounded-memory tail read for append-only logs/spools with no size ceiling — null on error vs `''` for an empty file; shared by the agent-transcript cap, the TUI failure analyzer, and the Codex rollout scan), JSONL append/read/write helpers, dir scans, hashes (`sha256File` streams above 512 KB; `sha256Text` is its in-memory twin for strings/Buffers), JSON helpers. `readJSONFile(path, default)` swallows every failure into `default`; `readJSONFileStrict(path, default)` → `{ ok, value }` (or `readJSONFile(…, { strict: true })`, which throws) tells "absent → trustworthy empty" apart from "present-but-unreadable/corrupt" — use it whenever the result is counted or shown, so a bad read can't report a fake 0. `tryReadFileStrict(path, encoding?)` → `{ ok, value }` is the same distinction for RAW bytes (the strict twin of `tryReadFile`, #4115): `ok && value !== null` read, `ok && value === null` absent, `!ok` present-but-unreadable. Reach for either whenever the value is counted, displayed, OR written back — a read-modify-write that swallows an unreadable file persists the empty default over real data. Which call sites were audited and why the rest are safe: [docs/decisions/2026-08-14-strict-json-reads-for-counted-values.md](../../docs/decisions/2026-08-14-strict-json-reads-for-counted-values.md). Most paths/file work goes through here. The slashdo command/lib loaders live in `slashdoLoader.js`. |+| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), `saveBase64Upload(dir, { filename, data }, { allowedExtensions, maxBytes })` + `serveLocalFile(res, dir, filename, opts?)` (shared attachment upload/serve pipeline — allowlist, size cap, `<uuid8>-name`, containment guard, nosniff/disposition), extension allowlists (`ATTACHMENT_ALLOWED_EXTENSIONS`, `SONGBOOK_ATTACHMENT_EXTENSIONS`), `assertSafeFilename(name, {extensions, subject})` (throwing basename/traversal/extension gate) plus its non-throwing twin `isSafeFilename(name, extensions)` for read-only callers that must report a bad stored name as data rather than 400 the request — both share one implementation so the gate and the verdict can't drift, and `isTopLevelEntryName(name)` is that shared traversal half on its own, for callers that can't allowlist extensions (arbitrary user assets, directory entries) but still must refuse separators so no intermediate component is left for a symlink to redirect, `readFileTail(path, maxBytes)` (bounded-memory tail read for append-only logs/spools with no size ceiling — null on error vs `''` for an empty file; shared by the agent-transcript cap, the TUI failure analyzer, and the Codex rollout scan), JSONL append/read/write helpers, `dirSize(path, { strict })` (forgiving by default; strict reporting mode rejects failed scans instead of forging zero), hashes (`sha256File` streams above 512 KB; `sha256Text` is its in-memory twin for strings/Buffers), JSON helpers. `readJSONFile(path, default)` swallows every failure into `default`; `readJSONFileStrict(path, default)` → `{ ok, value }` (or `readJSONFile(…, { strict: true })`, which throws) tells "absent → trustworthy empty" apart from "present-but-unreadable/corrupt" — use it whenever the result is counted or shown, so a bad read can't report a fake 0. `tryReadFileStrict(path, encoding?)` → `{ ok, value }` is the same distinction for RAW bytes (the strict twin of `tryReadFile`, #4115): `ok && value !== null` read, `ok && value === null` absent, `!ok` present-but-unreadable. Reach for either whenever the value is counted, displayed, OR written back — a read-modify-write that swallows an unreadable file persists the empty default over real data. Which call sites were audited and why the rest are safe: [docs/decisions/2026-08-14-strict-json-reads-for-counted-values.md](../../docs/decisions/2026-08-14-strict-json-reads-for-counted-values.md). Most paths/file work goes through here. The slashdo command/lib loaders live in `slashdoLoader.js`. || `icloudFile.js` | Guards against blocking reads of **evicted (dataless) cloud files**. macOS Optimize-Mac-Storage offloads a file in an iCloud ubiquity container (or a `~/Library/CloudStorage` File Provider mount); the path and `size` remain but no blocks are local, and the first **data access** BLOCKS in the kernel until materialization completes — indefinitely and uncancellably when iCloud is wedged. Four such reads exhaust libuv's 4-thread fs pool and every later `fs` call in the process queues forever, including the `express.static` read that serves the UI bundle (the whole UI hangs while memory-only routes still answer). Retry-on-error can't help: the read doesn't fail, it hangs. `readIfMaterialized(path, {encoding, label})` screens with a `stat()` (safe — never materializes) and rejects with `err.code === ICLOUD_NOT_MATERIALIZED` instead of issuing the read, kicking a background `brctl download` so the next cycle succeeds; concurrent callers for one path+encoding share a single read. `isUbiquityPath(path)` resolves the containing directory's real path (memoized) rather than substring-matching, so a **symlinked** route into iCloud — `~/Documents/...` under "Desktop & Documents Folders" sync — is still recognized. `isDatalessStats(stats)` is the raw predicate (`size > 0 && blocks === 0`) and is **not safe alone** (a sparse or `decmpfs`-compressed ordinary file matches it); pair it with the platform + cloud-root scoping via `isEvictedStats(path, stats)`, which is what a caller holding a `Stats` should use, or `isSuspectedDataless(path)` which does the `stat` itself. `requestMaterialization(path, {label, retryAfterExit, onFailure})` is the fire-and-forget `brctl download` every brctl caller shares — read paths kick it (default `retryAfterExit: true`) to heal an evicted file, per-path-deduped in a shared in-flight map capped at 4 concurrent children (an evicted vault walk would otherwise fork one per note) and each killed at `DOWNLOAD_DEADLINE_MS` so a wedged `brctl` can't hold every slot for the life of the process; the boot/settings pin in `mortalLoomStore` passes `retryAfterExit: false` so it is NOT tracked in that shared map (it owns a single-sticky-path dedupe at its call site) plus an `onFailure` hook to clear that sticky path on a failed/killed download. `claimBrctlMissingWarning()` returns `true` on the first call only, so the "brctl not found on PATH" warning fires at most once per process across every brctl caller (the fire-and-forget path here and the awaited `materializeAndWait`). `materializeAndWait(path, {label, timeoutMs})` is the **awaited, bounded** counterpart used by WRITE paths (`mortalLoomStore` before overwriting its store, `obsidian.updateNote` before overwriting a note): a write must not silently skip, so it materializes and waits rather than firing and forgetting, bounded by `MATERIALIZE_TIMEOUT_MS` (20s — much tighter than the background `DOWNLOAD_DEADLINE_MS` because a caller is blocked on it) and run in a child process, which is what makes the wait cancellable when the kernel write it replaces would not be. It resolves `true` only on brctl exit-0, which means the download was **accepted, not completed** — always re-screen before trusting the file. Measured (#3706, #3713), and recorded in the module docblock's syscall table: `stat`/`open`/`rename`/`unlink` never materialize, while `read`, `write` (including after `O_TRUNC` — truncating does NOT skip the download), `link`, and `clonefile` all do. `unlink` being free is a measurement, not the POSIX inference — `link` is pure metadata too and it *does* materialize — so delete paths need no screen. The docblock also carries the reproduction recipe: `brctl evict <path>` works (undocumented, like `brctl download`), which is what makes the evict/measure/heal loop scriptable. Consumed by `services/mortalLoomStore.js` and `services/obsidian.js`. || `boundedStateMap.js` | `createBoundedStateMap({ maxSize, ttlMs })` — a `Map` that self-evicts so a per-key state cache can't grow one entry per key forever. Lazy TTL + LRU eviction on `get`/`set` (no timers); `get` doubles as the LRU touch. Used by the moltbook/moltworld rate-limiters to bound their per-agent state. || `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. |diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 9c5b2eeffb..f50c851182 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -1815,9 +1815,21 @@ export async function listDirectoryByExtension(dir, { extensions, mapEntry, requ// node's recursive readdir on large trees (hundreds of GB / 200k+ files).// Returns 0 + logs on failure (missing tool, permission denied, timeout) so// the Media Models endpoint stays responsive even on unusual systems instead-// of throwing and 500ing the whole route.-export async function dirSize(path) {- if (!existsSync(path)) return 0;+// of throwing and 500ing the whole route. Counted/reporting callers can pass+// `{ strict: true }` to reject instead, preserving failed-vs-legitimately-empty.+export async function dirSize(path, { strict = false } = {}) {+ if (strict) {+ const present = await stat(path).then(+ () => true,+ (err) => {+ if (err?.code === 'ENOENT') return false;+ throw err;+ },+ );+ if (!present) return 0;+ } else if (!existsSync(path)) {+ return 0;+ }if (IS_WIN) {// Pass the path via an env var so a literal apostrophe in the path can't// close the PowerShell string and inject commands.@@ -1826,17 +1838,28 @@ export async function dirSize(path) {'(Get-ChildItem -Recurse -File $Env:DIRSIZE_TARGET | Measure-Object -Property Length -Sum).Sum',], { encoding: 'utf8', timeout: 60_000, env: { ...process.env, DIRSIZE_TARGET: path } }).catch((err) => ({ error: err }));if (result.error) {+ if (strict) throw result.error;console.log(`⚠️ dirSize(${path}) failed: ${result.error.message}`);return 0;}- return parseInt(result.stdout.trim(), 10) || 0;+ const bytes = parseInt(result.stdout.trim(), 10);+ if (!Number.isFinite(bytes) || bytes < 0) {+ if (strict) throw new Error(`Could not parse directory size for ${path}`);+ return 0;+ }+ return bytes;}const result = await execFileAsync('du', ['-sk', path], { encoding: 'utf8', timeout: 60_000 }).catch((err) => ({ error: err }));if (result.error) {+ if (strict) throw result.error;console.log(`⚠️ dirSize(${path}) failed: ${result.error.message}`);return 0;}- const kb = parseInt(result.stdout.split('\t')[0], 10) || 0;+ const kb = parseInt(result.stdout.split('\t')[0], 10);+ if (!Number.isFinite(kb) || kb < 0) {+ if (strict) throw new Error(`Could not parse directory size for ${path}`);+ return 0;+ }return kb * 1024;}diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex e2de6d48f4..b167ea112d 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -23,6 +23,7 @@ vi.mock('fs/promises', async (importOriginal) => {readFile: vi.fn((...args) => actual.readFile(...args)),rename: vi.fn((...args) => actual.rename(...args)),readdir: vi.fn((...args) => actual.readdir(...args)),+ stat: vi.fn((...args) => actual.stat(...args)),};});import {@@ -47,6 +48,7 @@ import {writeJSONLines,formatDuration,readFileTail,+ dirSize,sha256File,resolveImageInputPath,resolveScreenshot,@@ -77,7 +79,7 @@ beforeAll(async () => {});const restoreFsMocks = () => {- for (const name of ['readFile', 'rename', 'readdir', 'mkdir']) {+ for (const name of ['readFile', 'rename', 'readdir', 'mkdir', 'stat']) {fsPromises[name].mockReset();fsPromises[name].mockImplementation((...args) => realFsPromises[name](...args));}@@ -1008,6 +1010,23 @@ describe('fileUtils', () => {});});+ describe('dirSize strict scans', () => {+ afterEach(() => restoreFsMocks());++ it('rejects an unreadable path instead of reporting a real zero', async () => {+ const error = Object.assign(new Error('permission denied'), { code: 'EACCES' });+ fsPromises.stat.mockRejectedValue(error);++ await expect(dirSize('/example/unreadable', { strict: true })).rejects.toBe(error);+ });++ it('treats a confirmed missing path as an empty directory', async () => {+ fsPromises.stat.mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' }));++ await expect(dirSize('/example/missing', { strict: true })).resolves.toBe(0);+ });+ });+// CONVENTION: this block writes fixtures into the REAL `data/images`,// `data/image-refs`, and `data/templates` roots because `PATHS` is module-// evaluated and not easily overridable. Two rules to keep dev/CI worktreesdiff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex e8e3d96b13..a5b7ed2526 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -243,7 +243,10 @@ export const NAV_COMMANDS = [{ id: 'nav.loops', path: '/loops', label: 'Loops', section: 'Dev Tools', aliases: ['loops'] },{ id: 'nav.devtools.processes', path: '/devtools/processes', label: 'Processes', section: 'Dev Tools', aliases: ['devtools-processes', 'processes'] },{ id: 'nav.security', path: '/security', label: 'Security', section: 'Dev Tools', aliases: ['security'] },- { id: 'nav.system-health', path: '/system-health', label: 'System Health', section: 'Dev Tools', aliases: ['system-health', 'system-status', 'memory-usage', 'disk-usage', 'cpu-usage'], keywords: ['memory', 'cpu', 'disk', 'thresholds', 'top processes', 'resource usage'] },+ { id: 'nav.system-health', path: '/system-resources/overview', label: 'System Resources', section: 'Dev Tools', aliases: ['system-resources', 'system-health', 'system-status', 'memory-usage', 'cpu-usage'], keywords: ['health', 'memory', 'cpu', 'disk', 'thresholds', 'top processes', 'resource usage'] },+ { id: 'nav.system-resources.storage', path: '/system-resources/storage', label: 'Storage Report', section: 'Dev Tools', aliases: ['disk-usage', 'storage-report', 'disk-cleanup'], keywords: ['disk', 'storage', 'space', 'cleanup', 'cache', 'data usage', 'ai triage'] },+ { id: 'nav.system-resources.models', path: '/system-resources/models', label: 'Model Resources', section: 'Dev Tools', aliases: ['model-resources', 'loaded-models', 'downloaded-models', 'model-memory'], keywords: ['ollama', 'lm studio', 'hugging face', 'lora', 'unload', 'delete model', 'vram'] },+ { id: 'nav.system-resources.queues', path: '/system-resources/queues', label: 'Active Queues', section: 'Dev Tools', aliases: ['active-queues', 'job-queues', 'pending-jobs', 'render-queue'], keywords: ['media jobs', 'agent tasks', 'pending', 'running', 'cancel', 'run now'] },{ id: 'nav.cos.jobs', path: '/cos/jobs', label: 'System Tasks', section: 'Chief of Staff', aliases: ['cos-jobs', 'system-tasks'] },{ id: 'nav.uploads', path: '/uploads', label: 'Uploads', section: 'Dev Tools', aliases: ['uploads'] },diff --git a/server/lib/navManifest.test.js b/server/lib/navManifest.test.jsindex 70cf79cd25..70884f929a 100644--- a/server/lib/navManifest.test.js+++ b/server/lib/navManifest.test.js@@ -137,6 +137,12 @@ describe('resolveNavCommand — fuzzy matching', () => {expect(resolveNavCommand('goals')?.path).toBe('/goals/list');});+ it('resolves every canonical System Resources section name', () => {+ expect(resolveNavCommand('system resources')?.path).toBe('/system-resources/overview');+ expect(resolveNavCommand('model resources')?.path).toBe('/system-resources/models');+ expect(resolveNavCommand('active queues')?.path).toBe('/system-resources/queues');+ });+it('resolves Universe Builder to the /universes index path', () => {// Promoted out of /media/universe-builder; renamed to /universes when the// list/table index landed (command id stays nav.create.universe-builder).diff --git a/server/routes/imageVideoModels.js b/server/routes/imageVideoModels.jsindex 6292814025..375d3315ea 100644--- a/server/routes/imageVideoModels.js+++ b/server/routes/imageVideoModels.js@@ -10,25 +10,24 @@import { Router } from 'express';import { existsSync } from 'fs';-import { readdir, stat, rm } from 'fs/promises';+import { rm } from 'fs/promises';import { join } from 'path';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { PATHS, formatBytes, dirSize } from '../lib/fileUtils.js';+import { PATHS } from '../lib/fileUtils.js';import { getHfCacheRoot } from '../lib/hfCache.js';import {getImageModels,getVideoModels,isUserModelEntry,- loadMediaModels,patchUserModelEntry,removeUserModelEntry,} from '../lib/mediaModels.js';import { publicTextEncoderOption, videoTextEncoderOptions } from '../lib/videoTextEncoders.js';-import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';import { emptyToUndefined, validateRequest } from '../lib/validation.js';import { ADDABLE_IMAGE_RUNNERS, ADDABLE_VIDEO_RUNTIMES, searchHuggingfaceModels } from '../lib/huggingfaceModel.js';import { addModelFromHuggingface } from '../services/mediaModelInstall.js';+import { getMediaModelStorage } from '../services/mediaModelStorage.js';const router = Router();@@ -38,85 +37,8 @@ const router = Router();// would make a downloaded encoder impossible to delete from this UI.const HF_HUB_DIR = getHfCacheRoot;-// Friendly labels for known models, derived from the media-models registry.-// HF stores cache dirs as `models--<org>--<name>` (slashes replaced with --).-// Image gen still has a few well-known repos (Flux) that the registry tracks-// only by short id, so we add those here as a small static fallback.-const buildAppModels = () => {- const reg = loadMediaModels();- const out = {- 'black-forest-labs--FLUX.1-schnell': 'Flux 1 Schnell (Image)',- 'black-forest-labs--FLUX.1-dev': 'Flux 1 Dev (Image)',- };- const addEntry = (m, suffix) => {- if (!m.repo) return;- out[m.repo.replace(/\//g, '--')] = `${m.name} ${suffix}`;- };- for (const m of [...(reg.video?.macos || []), ...(reg.video?.windows || [])]) addEntry(m, '(Video)');- for (const t of (reg.textEncoders || [])) addEntry({ name: t.label, repo: t.repo }, '(Text Encoder)');- return out;-};-const APP_MODELS = buildAppModels();-router.get('/', asyncHandler(async (_req, res) => {- const hubDir = HF_HUB_DIR();-- const entries = existsSync(hubDir)- ? (await readdir(hubDir)).filter((f) => f.startsWith('models--'))- : [];-- const [models, loras, totalImages, totalVideos] = await Promise.all([- mapWithConcurrency(entries, 4, async (dirName) => {- const fullPath = join(hubDir, dirName);- const modelKey = dirName.replace('models--', '');- const [org, ...nameParts] = modelKey.split('--');- const name = nameParts.join('--');- const size = await dirSize(fullPath);- return {- id: dirName,- org,- name,- repo: `${org}/${name}`,- label: APP_MODELS[modelKey] || null,- size,- sizeHuman: formatBytes(size),- };- }),- (async () => {- const out = [];- if (!existsSync(PATHS.loras)) return out;- for (const f of await readdir(PATHS.loras)) {- if (!f.endsWith('.safetensors')) continue;- const s = await stat(join(PATHS.loras, f));- out.push({- filename: f,- name: f.replace(/^lora-/, '').replace(/\.safetensors$/, ''),- size: s.size,- sizeHuman: formatBytes(s.size),- });- }- return out;- })(),- dirSize(PATHS.images),- dirSize(PATHS.videos),- ]);- models.sort((a, b) => b.size - a.size);-- const totalModels = models.reduce((sum, m) => sum + m.size, 0);- const totalLoras = loras.reduce((sum, l) => sum + l.size, 0);-- res.json({- models,- loras,- hubDir,- diskUsage: {- models: formatBytes(totalModels),- loras: formatBytes(totalLoras),- images: formatBytes(totalImages),- videos: formatBytes(totalVideos),- total: formatBytes(totalModels + totalLoras + totalImages + totalVideos),- },- });+ res.json(await getMediaModelStorage());}));// GET /registry — the media-model registry as the manager UI needs it:diff --git a/server/routes/lmstudio.js b/server/routes/lmstudio.jsindex 74d94cefdb..67d5ca224f 100644--- a/server/routes/lmstudio.js+++ b/server/routes/lmstudio.js@@ -86,6 +86,9 @@ router.post('/unload', asyncHandler(async (req, res) => {const { modelId } = validateRequest(lmStudioModelIdSchema, req.body)const result = await lmStudioManager.unloadModel(modelId)+ if (!result.success) {+ throw new ServerError(result.error || 'Unload failed', { status: 502, context: { modelId } })+ }res.json(result)}))diff --git a/server/routes/lmstudio.test.js b/server/routes/lmstudio.test.jsindex 90ac3a8374..cf43b468e1 100644--- a/server/routes/lmstudio.test.js+++ b/server/routes/lmstudio.test.js@@ -120,6 +120,26 @@ describe('lmstudio routes', () => {});});+ describe('POST /api/lmstudio/unload', () => {+ it('surfaces manager failures as an unsuccessful request', async () => {+ lmStudioManager.unloadModel.mockResolvedValue({ success: false, error: 'model is busy' });++ const res = await request(app).post('/api/lmstudio/unload').send({ modelId: 'example/model' });++ expect(res.status).toBe(502);+ expect(res.body.error).toContain('model is busy');+ });++ it('returns a successful unload result', async () => {+ lmStudioManager.unloadModel.mockResolvedValue({ success: true, modelId: 'example/model' });++ const res = await request(app).post('/api/lmstudio/unload').send({ modelId: 'example/model' });++ expect(res.status).toBe(200);+ expect(res.body).toEqual({ success: true, modelId: 'example/model' });+ });+ });+describe('POST /api/lmstudio/completion', () => {it('rejects a missing prompt', async () => {const res = await request(app).post('/api/lmstudio/completion').send({});diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex e015070a68..bff5c21250 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -36,7 +36,15 @@ import { listUserModels } from '../services/audioModels.js'import { ENGINES } from '../services/pipeline/musicGen.js'import { abortSignalFromResponse } from '../lib/requestAbort.js'import { awaitWritableDrain } from '../lib/streamBackpressure.js'-import { getLoadedModels as getLoadedOllamaModels, unloadModel as unloadOllamaModel } from '../services/ollamaManager.js'+import {+ getLastLoadedModelsError as getOllamaResidencyError,+ getLoadedModels as getLoadedOllamaModels,+ unloadModel as unloadOllamaModel,+} from '../services/ollamaManager.js'+import {+ getLastLoadedModelsError as getLmStudioResidencyError,+ getLoadedModels as getLoadedLmStudioModels,+} from '../services/lmStudioManager.js'const router = Router()@@ -272,13 +280,23 @@ router.post('/migrate', asyncHandler(async (req, res) => {res.json(result)}))-// GET /api/local-llm/loaded — models currently resident in memory.+// GET /api/local-llm/loaded — models currently resident in memory across both+// local backends. The endpoint stays 200 for a partial outage, but names the+// affected source explicitly so an unknown residency state is never mistaken+// for a trustworthy empty list by cleanup controls.// 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 })+router.get('/loaded', asyncHandler(async (_req, res) => {+ const [ollama, lmstudio] = await Promise.all([+ getLoadedOllamaModels(),+ getLoadedLmStudioModels(true),+ ])+ const sourceErrors = [+ ...(getOllamaResidencyError() ? ['ollama'] : []),+ ...(getLmStudioResidencyError() ? ['lmstudio'] : []),+ ]+ res.json({ ollama, lmstudio, sourceErrors })}))// POST /api/local-llm/unload — body: { backend: 'ollama', modelId }.diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.jsindex 36e5b18cc2..ab55fc67c6 100644--- a/server/routes/localLlm.test.js+++ b/server/routes/localLlm.test.js@@ -6,6 +6,7 @@ import { runLocalLlmTest, compareLocalLlmModels } from '../services/localLlmPlayimport { listModels, listVisionModels, listToolUseModels } from '../services/localLlm.js';import { enrichCatalogWithVariants } from '../services/huggingFaceCatalog.js';import { getLoadedModels, unloadModel } from '../services/ollamaManager.js';+import { getLoadedModels as getLoadedLmStudioModels } from '../services/lmStudioManager.js';import { localLlmCompareSchema, localLlmTestSchema } from '../lib/validation.js';import { errorEvents } from '../lib/errorHandler.js';@@ -34,10 +35,16 @@ vi.mock('../services/localLlmPlayground.js', () => ({}));vi.mock('../services/ollamaManager.js', () => ({+ getLastLoadedModelsError: vi.fn(() => null),getLoadedModels: vi.fn(async () => []),unloadModel: vi.fn(),}));+vi.mock('../services/lmStudioManager.js', () => ({+ getLastLoadedModelsError: vi.fn(() => null),+ getLoadedModels: vi.fn(async () => []),+}));+// Mock the HF catalog service so /catalog tests don't hit the network. The no-op// enrichCatalogWithVariants simulates the offline/failed-enrichment case (it leaves// the catalog's getCatalog overlay untouched), which is exactly when the route's@@ -237,17 +244,20 @@ describe('local LLM memory-management routes', () => {vi.clearAllMocks();});- it('GET /loaded reports the models Ollama currently has resident', async () => {+ it('GET /loaded reports models both local backends currently have resident', async () => {// Mirror the real getLoadedModels() field set so the fixture documents the// pass-through contract and would catch any future field-stripping.const resident = { id: 'llama3.2', name: 'llama3.2', size: 4096, sizeVram: 4096, expiresAt: null };+ const lmStudioResident = { id: 'example/lmstudio', state: 'loaded' };getLoadedModels.mockResolvedValue([resident]);+ getLoadedLmStudioModels.mockResolvedValue([lmStudioResident]);const res = await request(makeApp()).get('/api/local-llm/loaded');expect(res.status).toBe(200);- expect(res.body).toEqual({ ollama: [resident] });+ expect(res.body).toEqual({ ollama: [resident], lmstudio: [lmStudioResident], sourceErrors: [] });expect(getLoadedModels).toHaveBeenCalledTimes(1);+ expect(getLoadedLmStudioModels).toHaveBeenCalledWith(true);});it('POST /unload evicts a resident model and echoes the service result', async () => {diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex fcc8f00f3a..558d04884b 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -19,7 +19,7 @@ import { getHttpsEnabledAtBoot } from '../lib/httpsState.js';// 75-85% band on a host with a couple of LLMs loaded, and big SSDs commonly// run >85% before being a real problem. Earlier thresholds (75/90 mem,// 85/95 disk) fired warnings on every healthy laptop. Users can override-// these from /system-health (persisted to settings.json under `health`).+// these from /system-resources/overview (persisted to settings.json under `health`).const DEFAULT_THRESHOLDS = {memoryWarn: 85,memoryCritical: 95,diff --git a/server/routes/systemResources.js b/server/routes/systemResources.jsnew file mode 100644index 0000000000..599dabb3a9--- /dev/null+++ b/server/routes/systemResources.js@@ -0,0 +1,62 @@+/**+ * System Resources — explicit storage report and AI-assisted cleanup triage.+ *+ * Both routes are POSTs because a report performs bounded, potentially slow+ * disk scans. Nothing runs at boot or merely because a dashboard widget polls.+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { EFFORT_LEVELS } from '../lib/providerModels.js';+import { onClientDisconnect } from '../lib/sseDownload.js';+import { stopRun } from '../services/runner.js';+import { getSystemResourceReport, triageSystemResources } from '../services/systemResources.js';++const router = Router();+const emptyBodySchema = z.object({}).strict();++const blankToUndefined = (value) => {+ const trimmed = (value ?? '').trim();+ return trimmed || undefined;+};++export const systemResourceTriageSchema = z.object({+ providerId: z.string().trim().min(1).max(128),+ model: z.string().max(256).optional().transform(blankToUndefined),+ effort: z.string().max(64).optional().transform(blankToUndefined)+ .refine((value) => value === undefined || EFFORT_LEVELS.includes(value), 'Unsupported effort level'),+}).strict();++router.post('/report', asyncHandler(async (req, res) => {+ validateRequest(emptyBodySchema, req.body || {});+ res.json(await getSystemResourceReport({ force: true }));+}));++router.post('/triage', asyncHandler(async (req, res) => {+ const input = validateRequest(systemResourceTriageSchema, req.body || {});+ const activeRunIds = new Set();+ let clientGone = false;+ const stop = (runId) => stopRun(runId).catch((err) => {+ console.error(`❌ Failed to stop disconnected system-resource triage run ${runId}: ${err.message}`);+ });+ onClientDisconnect(req, res, () => {+ clientGone = true;+ for (const runId of activeRunIds) stop(runId);+ });+ const result = await triageSystemResources({+ ...input,+ onRunCreated: (runId) => {+ activeRunIds.add(runId);+ if (clientGone) stop(runId);+ },+ onRunSettled: (runId) => activeRunIds.delete(runId),+ }).catch((err) => {+ if (clientGone) return null;+ throw err;+ });+ if (!clientGone && result && !res.writableEnded && !res.destroyed) res.json(result);+}));++export default router;diff --git a/server/routes/systemResources.test.js b/server/routes/systemResources.test.jsnew file mode 100644index 0000000000..2f99bf2c9e--- /dev/null+++ b/server/routes/systemResources.test.js@@ -0,0 +1,98 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++const lifecycle = vi.hoisted(() => ({ onDisconnect: null, stopRun: vi.fn(async () => true) }));++vi.mock('../services/systemResources.js', () => ({+ getSystemResourceReport: vi.fn(),+ triageSystemResources: vi.fn(),+}));+vi.mock('../lib/sseDownload.js', () => ({+ onClientDisconnect: vi.fn((_req, _res, callback) => { lifecycle.onDisconnect = callback; }),+}));+vi.mock('../services/runner.js', () => ({+ stopRun: lifecycle.stopRun,+}));++const resources = await import('../services/systemResources.js');+const { default: routes } = await import('./systemResources.js');++const makeApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/system-resources', routes);+ app.use(errorMiddleware);+ return app;+};++describe('system resources routes', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ lifecycle.onDisconnect = null;+ });++ it('runs a fresh report only when explicitly requested', async () => {+ resources.getSystemResourceReport.mockResolvedValue({ generatedAt: '2026-08-16T00:00:00.000Z' });+ const response = await request(makeApp()).post('/api/system-resources/report').send({});+ expect(response.status).toBe(200);+ expect(resources.getSystemResourceReport).toHaveBeenCalledWith({ force: true });+ });++ it('rejects report input instead of accepting filesystem hints', async () => {+ const response = await request(makeApp()).post('/api/system-resources/report').send({ path: '/example' });+ expect(response.status).toBe(400);+ expect(resources.getSystemResourceReport).not.toHaveBeenCalled();+ });++ it('normalizes optional picker values before AI triage', async () => {+ resources.triageSystemResources.mockResolvedValue({ triage: { summary: 'Healthy' } });+ const response = await request(makeApp()).post('/api/system-resources/triage').send({+ providerId: 'codex',+ model: ' ',+ effort: '',+ });+ expect(response.status).toBe(200);+ expect(resources.triageSystemResources).toHaveBeenCalledWith(expect.objectContaining({+ providerId: 'codex',+ model: undefined,+ effort: undefined,+ onRunCreated: expect.any(Function),+ onRunSettled: expect.any(Function),+ }));+ });++ it('stops active and late-created AI runs after a client disconnect', async () => {+ let hooks;+ resources.triageSystemResources.mockImplementation(async (input) => {+ hooks = input;+ input.onRunCreated('run-active');+ return { triage: { summary: 'Healthy' } };+ });++ const response = await request(makeApp()).post('/api/system-resources/triage').send({ providerId: 'codex' });+ expect(response.status).toBe(200);++ lifecycle.onDisconnect();+ hooks.onRunCreated('run-late');+ await Promise.resolve();++ expect(lifecycle.stopRun).toHaveBeenCalledWith('run-active');+ expect(lifecycle.stopRun).toHaveBeenCalledWith('run-late');+ hooks.onRunSettled('run-active');+ hooks.onRunSettled('run-late');+ });++ it('rejects unsupported effort and unknown fields', async () => {+ const badEffort = await request(makeApp()).post('/api/system-resources/triage').send({+ providerId: 'codex', effort: 'turbo',+ });+ const extra = await request(makeApp()).post('/api/system-resources/triage').send({+ providerId: 'codex', path: '/private/example',+ });+ expect(badEffort.status).toBe(400);+ expect(extra.status).toBe(400);+ expect(resources.triageSystemResources).not.toHaveBeenCalled();+ });+});diff --git a/server/services/dataManager.js b/server/services/dataManager.jsindex aebbfb0070..77fd8f6fb4 100644--- a/server/services/dataManager.js+++ b/server/services/dataManager.js@@ -166,29 +166,53 @@ export async function resolveCategoryBusy(categoryKey) {// Validate category key contains only safe charactersconst SAFE_NAME = /^[a-z0-9_-]+$/;-async function getDirSizeAndCount(dirPath) {- if (!existsSync(dirPath)) return { size: 0, fileCount: 0 };+async function getDirSizeAndCount(dirPath, { strict = false } = {}) {+ if (strict) {+ const present = await stat(dirPath).then(+ () => true,+ (err) => {+ if (err?.code === 'ENOENT') return false;+ throw err;+ },+ );+ if (!present) return { size: 0, fileCount: 0 };+ } else if (!existsSync(dirPath)) {+ return { size: 0, fileCount: 0 };+ }const [duOut, findOut] = await Promise.all([execFileAsync('du', ['-sk', dirPath], { timeout: 30000 }).then(r => r.stdout.trim())- .catch(() => '0'),+ .catch((err) => {+ if (strict) throw err;+ return '0';+ }),execFileAsync('find', [dirPath, '-type', 'f'], { timeout: 30000 }).then(r => r.stdout.trim().split('\n').filter(Boolean).length)- .catch(() => 0)+ .catch((err) => {+ if (strict) throw err;+ return 0;+ })]);- const kb = typeof duOut === 'string' ? (parseInt(duOut.split('\t')[0], 10) || 0) : 0;+ const kb = typeof duOut === 'string' ? parseInt(duOut.split('\t')[0], 10) : NaN;+ if (!Number.isFinite(kb) || kb < 0) {+ if (strict) throw new Error(`Could not parse directory size for ${dirPath}`);+ return { size: 0, fileCount: typeof findOut === 'number' ? findOut : 0 };+ }const fileCount = typeof findOut === 'number' ? findOut : (parseInt(findOut, 10) || 0);return { size: kb * 1024, fileCount };}-export async function getDataOverview() {- const entries = await readdir(DATA_DIR, { withFileTypes: true }).catch(() => []);+export async function getDataOverview({ strict = false } = {}) {+ const entries = await readdir(DATA_DIR, { withFileTypes: true }).catch((err) => {+ if (strict) throw err;+ return [];+ });const dirs = entries.filter(e => e.isDirectory());// Parallel: get total size + per-directory sizes in one batchconst [totalResult, ...dirResults] = await Promise.all([- getDirSizeAndCount(DATA_DIR),- ...dirs.map(d => getDirSizeAndCount(join(DATA_DIR, d.name)))+ getDirSizeAndCount(DATA_DIR, { strict }),+ ...dirs.map(d => getDirSizeAndCount(join(DATA_DIR, d.name), { strict }))]);// Busy state ships with the overview so the Data Manager can drop the Purgediff --git a/server/services/dataManager.strict.test.js b/server/services/dataManager.strict.test.jsnew file mode 100644index 0000000000..c172dc1f80--- /dev/null+++ b/server/services/dataManager.strict.test.js@@ -0,0 +1,74 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdirSync, mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';++const mocks = vi.hoisted(() => ({ execFile: vi.fn(), statErrorPath: null }));+const testDataRoot = mkdtempSync(join(tmpdir(), 'datamanager-strict-test-'));++vi.mock('fs/promises', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ stat: vi.fn((path, ...args) => {+ if (path === mocks.statErrorPath) {+ return Promise.reject(Object.assign(new Error('stat access denied'), { code: 'EACCES' }));+ }+ return actual.stat(path, ...args);+ }),+ };+});+vi.mock('../lib/childProcess.js', () => ({ execFile: mocks.execFile }));+vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return makePathsProxy(actual, { dataRoot: testDataRoot });+});+vi.mock('./dataManagerBusy.js', () => ({+ imageCleanTmpBusy: vi.fn(async () => ({ busy: false })),+ trainingRunsBusy: vi.fn(async () => ({ busy: false })),+ updateDetachedBusy: vi.fn(async () => ({ busy: false })),+}));++const { getDataOverview } = await import('./dataManager.js');++afterAll(() => rmSync(testDataRoot, { recursive: true, force: true }));++beforeEach(() => {+ mocks.statErrorPath = null;+ rmSync(testDataRoot, { recursive: true, force: true });+ mkdirSync(join(testDataRoot, 'cache'), { recursive: true });+ mkdirSync(join(testDataRoot, 'runs'), { recursive: true });+ mocks.execFile.mockReset().mockImplementation((command, args, _options, callback) => {+ const target = command === 'find' ? args[0] : args[args.length - 1];+ if (target === join(testDataRoot, 'runs')) {+ callback(new Error('permission denied'));+ return;+ }+ callback(null, {+ stdout: command === 'du' ? `1\t${target}\n` : `${join(target, 'example.json')}\n`,+ stderr: '',+ });+ });+});++describe('dataManager strict overview', () => {+ it('keeps the default endpoint forgiving when a category scan fails', async () => {+ const overview = await getDataOverview();++ expect(overview.categories.find((category) => category.key === 'runs')).toMatchObject({+ size: 0,+ fileCount: 0,+ });+ });++ it('rejects the same failed category scan for fail-closed report callers', async () => {+ await expect(getDataOverview({ strict: true })).rejects.toThrow('permission denied');+ });++ it('preserves access failures during strict existence checks as unknown', async () => {+ mocks.statErrorPath = join(testDataRoot, 'runs');++ await expect(getDataOverview({ strict: true })).rejects.toThrow('stat access denied');+ });+});diff --git a/server/services/lmStudioManager.js b/server/services/lmStudioManager.jsindex 38fc8ce88b..e3ab975d3d 100644--- a/server/services/lmStudioManager.js+++ b/server/services/lmStudioManager.js@@ -9,7 +9,7 @@ import { homedir } from 'os'import { join, basename, resolve, relative, isAbsolute, sep } from 'path'import { existsSync } from 'fs'import { readdir, stat, copyFile, link, rm, rmdir } from 'fs/promises'-import { ensureDir } from '../lib/fileUtils.js'+import { dirSize, ensureDir } from '../lib/fileUtils.js'import { cosEvents } from './cosEvents.js'import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'import {@@ -36,6 +36,7 @@ let isAvailable = null// availableModels below so an idle LM Studio (server up, 0 models loaded)// doesn't re-hit /api/v0/models on every status poll.let loadedModels = null+let lastLoadedModelsError = null// null = not yet fetched; any array (even empty) = a cached result. Lets the// catalog-overlay path (queried per keystroke) reuse the list instead of// re-hitting /api/v0/models each time. Busted to null by resetCache().@@ -82,11 +83,11 @@ async function lmStudioRequest(endpoint, options = {}) {* Check if LM Studio is available* @returns {Promise<boolean>} - True if available*/-async function checkLMStudioAvailable() {+async function checkLMStudioAvailable(forceRefresh = false) {const now = Date.now()- // Use cached result if recent (within AVAILABILITY_CACHE_TTL_MS)- if (lastCheckAt && now - lastCheckAt < AVAILABILITY_CACHE_TTL_MS && isAvailable !== null) {+ // Use cached result if recent (within AVAILABILITY_CACHE_TTL_MS).+ if (!forceRefresh && lastCheckAt && now - lastCheckAt < AVAILABILITY_CACHE_TTL_MS && isAvailable !== null) {return isAvailable}@@ -117,15 +118,17 @@ async function getLoadedModels(forceRefresh = false) {return loadedModels}- const available = await checkLMStudioAvailable()+ const available = await checkLMStudioAvailable(forceRefresh)if (!available) {// Don't cache — unavailable is transient, so the next call re-probes.+ lastLoadedModelsError = status.lastError || 'LM Studio is unavailable'return []}// Use native REST API for richer model info (type, state, architecture)- const nativeModels = await lmStudioRequest('/api/v0/models').catch(() => null)+ const nativeModels = await lmStudioRequest('/api/v0/models').catch((err) => ({ _err: err.message }))if (nativeModels?.data) {+ lastLoadedModelsError = nullloadedModels = nativeModels.data.filter(model => model.state === 'loaded').map(model => ({@@ -142,8 +145,9 @@ async function getLoadedModels(forceRefresh = false) {}// Fallback to OpenAI-compat endpoint- const response = await lmStudioRequest('/v1/models').catch(() => null)+ const response = await lmStudioRequest('/v1/models').catch((err) => ({ _err: err.message }))if (response?.data) {+ lastLoadedModelsError = nullloadedModels = response.data.map(model => ({id: model.id,object: model.object,@@ -155,9 +159,15 @@ async function getLoadedModels(forceRefresh = false) {// Both list endpoints failed — return empty WITHOUT caching (loadedModels// stays null) so the next call retries instead of pinning a bogus empty.+ lastLoadedModelsError = nativeModels?._err || response?._err || 'LM Studio loaded-model endpoints returned no data'return []}+/** Last loaded-model probe error (null only after a trustworthy list). */+function getLastLoadedModelsError() {+ return lastLoadedModelsError+}+/*** Get all downloaded models (loaded and not-loaded).* @param {boolean} [forceRefresh] - bypass the cache (callers that read live@@ -166,7 +176,7 @@ async function getLoadedModels(forceRefresh = false) {*/async function getAvailableModels(forceRefresh = false) {if (!forceRefresh && availableModels !== null) return availableModels- const available = await checkLMStudioAvailable()+ const available = await checkLMStudioAvailable(forceRefresh)if (!available) {// Unreachable is surfaced by the availability probe (`available`), not here.lastListError = null@@ -478,6 +488,7 @@ function updateConfig(newConfig) {function resetCache() {isAvailable = nullloadedModels = null+ lastLoadedModelsError = nullavailableModels = nulllastListError = nulllastCheckAt = null@@ -507,6 +518,38 @@ async function getModelsDir() {return candidates[1] // sensible default even if it doesn't exist yet}+/**+ * Enumerate the exact `<publisher>/<repo>` folders LM Studio can delete.+ * This is disk-native so a stopped daemon does not erase downloaded inventory,+ * and one row always represents the whole repo folder (including every quant).+ */+async function listStoredModels() {+ const modelsDir = await getModelsDir()+ const root = await stat(modelsDir).then((entry) => entry.isDirectory(), (err) => {+ if (err?.code === 'ENOENT') return false+ throw err+ })+ if (!root) return []++ const publishers = (await readdir(modelsDir, { withFileTypes: true }))+ .filter((entry) => entry.isDirectory())+ const nested = await Promise.all(publishers.map(async (publisher) => {+ const publisherDir = join(modelsDir, publisher.name)+ const repos = (await readdir(publisherDir, { withFileTypes: true }))+ .filter((entry) => entry.isDirectory())+ return Promise.all(repos.map(async (repo) => {+ const id = `${publisher.name}/${repo.name}`+ return {+ id,+ publisher: publisher.name,+ name: repo.name,+ size: await dirSize(join(publisherDir, repo.name), { strict: true }),+ }+ }))+ }))+ return nested.flat().sort((a, b) => b.size - a.size)+}+const normalizeRepoKey = (s) => String(s || '').split('/').pop().trim()@@ -514,6 +557,12 @@ const normalizeRepoKey = (s) => String(s || '').replace(/[-.]gguf$/i, '').replace(/[-.]mlx[-.].*$/i, '')+function modelIdsReferToSameRepo(left, right) {+ const leftKey = normalizeRepoKey(left)+ const rightKey = normalizeRepoKey(right)+ return Boolean(leftKey && rightKey && leftKey === rightKey)+}+async function findModelDir(modelsDir, modelId) {// Reject `.`/`..` traversal segments before joining — mirrors the stricter// findDeletableModelDirs guard so the read path can't resolve outside the@@ -686,6 +735,7 @@ async function importModelFromGguf({ lmstudioId, ggufPath, projectorPath, mode =export {checkLMStudioAvailable,getLoadedModels,+ getLastLoadedModelsError,getAvailableModels,downloadModel,loadModel,@@ -699,6 +749,9 @@ export {resetCache,isAppInstalled,getLastListError,+ getModelsDir,+ listStoredModels,+ modelIdsReferToSameRepo,resolveLocalModel,importModelFromGguf,deleteModel,diff --git a/server/services/lmStudioManager.test.js b/server/services/lmStudioManager.test.jsindex ad393e82f1..0a9bd1f93e 100644--- a/server/services/lmStudioManager.test.js+++ b/server/services/lmStudioManager.test.js@@ -25,6 +25,7 @@ afterEach(() => {if (originalUrl === undefined) delete process.env.LM_STUDIO_URL;else process.env.LM_STUDIO_URL = originalUrl;fs.rmSync(tempDir, { recursive: true, force: true });+ vi.unstubAllGlobals();});const writeFile = (rel, content = 'gguf') => {@@ -64,6 +65,46 @@ describe('lmStudioManager local model resolution', () => {});});+describe('lmStudioManager stored model inventory', () => {+ it('reports one folder-scoped row for a repo containing multiple quantizations', async () => {+ writeFile('example/model-GGUF/model-Q4_K_M.gguf', 'q4');+ writeFile('example/model-GGUF/model-Q8_0.gguf', 'q8');+ const { listStoredModels } = await import('./lmStudioManager.js');++ const rows = await listStoredModels();++ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({ id: 'example/model-GGUF', name: 'model-GGUF' });+ expect(rows[0].size).toBeGreaterThan(0);+ });++ it('re-probes availability when a caller force-refreshes the inventory', async () => {+ const fetchMock = vi.fn(async (url) => ({+ ok: true,+ json: async () => ({ data: [] }),+ }));+ vi.stubGlobal('fetch', fetchMock);+ const { getAvailableModels } = await import('./lmStudioManager.js');++ await getAvailableModels();+ await getAvailableModels(true);++ const availabilityCalls = fetchMock.mock.calls+ .filter(([url]) => String(url).endsWith('/v1/models'));+ expect(availabilityCalls).toHaveLength(2);+ });+});++describe('lmStudioManager residency status', () => {+ it('keeps a failed loaded-model probe distinct from a trustworthy empty list', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('offline'); }));+ const { getLoadedModels, getLastLoadedModelsError } = await import('./lmStudioManager.js');++ await expect(getLoadedModels(true)).resolves.toEqual([]);+ expect(getLastLoadedModelsError()).toMatch(/offline|unavailable/i);+ });+});+describe('lmStudioManager deleteModel', () => {it('removes the model folder on disk and prunes the empty publisher dir', async () => {writeFile('nomic-ai/nomic-embed-text-v1.5-GGUF/model-Q4_K_M.gguf');diff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex 274155643b..4b0660a3c2 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -949,10 +949,24 @@ export async function installModel(backend, modelId, onProgress) {export async function deleteModel(backend, modelId) {if (!isBackend(backend)) return { success: false, error: `Unknown backend: ${backend}` }if (backend === 'ollama') {+ const loaded = await ollamaManager.getLoadedModels()+ if (ollamaManager.getLastLoadedModelsError()) {+ return { success: false, error: 'Could not verify Ollama model residency; refresh the backend before deleting.', modelId }+ }+ if (loaded.some((model) => model.id === modelId || model.name === modelId)) {+ return { success: false, error: 'Model is loaded; unload it before deleting.', modelId }+ }const result = await ollamaManager.deleteModel(modelId)if (result.success) refreshOllamaBackedProviders()return result}+ const loaded = await lmStudioManager.getLoadedModels(true)+ if (lmStudioManager.getLastLoadedModelsError()) {+ return { success: false, error: 'Could not verify LM Studio model residency; refresh the backend before deleting.', modelId }+ }+ if (loaded.some((model) => lmStudioManager.modelIdsReferToSameRepo(model.id, modelId))) {+ return { success: false, error: 'Model is loaded; unload it before deleting.', modelId }+ }// LM Studio has no delete in its REST API and the `lms` CLI has no `rm`// command — deleteModel removes the model's on-disk folder directly.return lmStudioManager.deleteModel(modelId)diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.jsindex f823c3e6ad..6ad79e6002 100644--- a/server/services/localLlm.test.js+++ b/server/services/localLlm.test.js@@ -24,6 +24,8 @@ const mocks = vi.hoisted(() => ({getModelCapabilities: vi.fn(async () => []),pullModel: vi.fn(async (id) => ({ success: true, modelId: id })),deleteModel: vi.fn(async (id) => ({ success: true, modelId: id })),+ getLoadedModels: vi.fn(async () => []),+ getLastLoadedModelsError: vi.fn(() => null),getStatus: vi.fn(async () => ({ available: true, baseUrl: 'x', version: '1', modelCount: 0, models: [] })),startServer: vi.fn(async () => ({ success: true, running: true })),stopServer: vi.fn(async () => ({ success: true, running: false })),@@ -36,6 +38,11 @@ const mocks = vi.hoisted(() => ({},lmstudio: {getAvailableModels: vi.fn(async () => []),+ getLoadedModels: vi.fn(async () => []),+ getLastLoadedModelsError: vi.fn(() => null),+ modelIdsReferToSameRepo: vi.fn((left, right) => String(left).split('/').pop().replace(/-GGUF$/i, '').toLowerCase()+ === String(right).split('/').pop().replace(/-GGUF$/i, '').toLowerCase()),+ deleteModel: vi.fn(async (id) => ({ success: true, modelId: id })),downloadModel: vi.fn(async (id) => ({ success: true, modelId: id })),getStatus: vi.fn(async () => ({ available: false, baseUrl: 'y', loadedModels: 0 })),resetCache: vi.fn(),@@ -219,6 +226,38 @@ describe('localLlm', () => {await svc.deleteModel('ollama', 'llama3.2');expect(mocks.ollama.deleteModel).toHaveBeenCalledWith('llama3.2');});+ it('refuses to delete a model whose live residency check says loaded', async () => {+ mocks.ollama.getLoadedModels.mockResolvedValueOnce([{ id: 'llama3.2', name: 'llama3.2' }]);++ const result = await svc.deleteModel('ollama', 'llama3.2');++ expect(result).toMatchObject({ success: false, error: expect.stringContaining('unload') });+ expect(mocks.ollama.deleteModel).not.toHaveBeenCalled();+ });+ it('fails closed when model residency could not be verified', async () => {+ mocks.ollama.getLastLoadedModelsError.mockReturnValueOnce('probe failed');++ const result = await svc.deleteModel('ollama', 'llama3.2');++ expect(result).toMatchObject({ success: false, error: expect.stringContaining('verify') });+ expect(mocks.ollama.deleteModel).not.toHaveBeenCalled();+ });+ it('refuses an LM Studio folder delete when a normalized API alias is loaded', async () => {+ mocks.lmstudio.getLoadedModels.mockResolvedValueOnce([{ id: 'openai/example-model' }]);++ const result = await svc.deleteModel('lmstudio', 'lmstudio-community/example-model-GGUF');++ expect(result).toMatchObject({ success: false, error: expect.stringContaining('unload') });+ expect(mocks.lmstudio.deleteModel).not.toHaveBeenCalled();+ });+ it('fails closed when LM Studio residency could not be verified', async () => {+ mocks.lmstudio.getLastLoadedModelsError.mockReturnValueOnce('probe failed');++ const result = await svc.deleteModel('lmstudio', 'example/model-GGUF');++ expect(result).toMatchObject({ success: false, error: expect.stringContaining('verify') });+ expect(mocks.lmstudio.deleteModel).not.toHaveBeenCalled();+ });it('rejects an unknown backend', async () => {expect((await svc.installModel('nope', 'x')).success).toBe(false);});diff --git a/server/services/mediaModelStorage.js b/server/services/mediaModelStorage.jsnew file mode 100644index 0000000000..ed84a588d8--- /dev/null+++ b/server/services/mediaModelStorage.js@@ -0,0 +1,126 @@+/**+ * Read-only storage inventory for downloaded media models.+ *+ * The Media Models route and System Resources report both need the same view of+ * Hugging Face cache directories. Keep that knowledge here so cache overrides,+ * friendly labels, and byte totals cannot drift between the two surfaces.+ */++import { existsSync } from 'fs';+import { readdir, stat } from 'fs/promises';+import { join } from 'path';+import { PATHS, dirSize, formatBytes } from '../lib/fileUtils.js';+import { getHfCacheRoot } from '../lib/hfCache.js';+import { loadMediaModels } from '../lib/mediaModels.js';+import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';++const buildAppModels = () => {+ const registry = loadMediaModels();+ const labels = {+ 'black-forest-labs--FLUX.1-schnell': 'Flux 1 Schnell (Image)',+ 'black-forest-labs--FLUX.1-dev': 'Flux 1 Dev (Image)',+ };+ const addEntry = (entry, suffix) => {+ if (!entry.repo) return;+ labels[entry.repo.replace(/\//g, '--')] = `${entry.name} ${suffix}`;+ };+ for (const model of [...(registry.video?.macos || []), ...(registry.video?.windows || [])]) {+ addEntry(model, '(Video)');+ }+ for (const encoder of registry.textEncoders || []) {+ addEntry({ name: encoder.label, repo: encoder.repo }, '(Text Encoder)');+ }+ return labels;+};++const APP_MODELS = buildAppModels();++export async function listHfModelStorage({ strict = false } = {}) {+ const hubDir = getHfCacheRoot();+ const hubPresent = strict+ ? await stat(hubDir).then(+ (entry) => entry.isDirectory(),+ (err) => {+ if (err?.code === 'ENOENT') return false;+ throw err;+ },+ )+ : existsSync(hubDir);+ const entries = hubPresent+ ? (await readdir(hubDir)).filter((name) => name.startsWith('models--'))+ : [];++ const models = await mapWithConcurrency(entries, 4, async (dirName) => {+ const modelKey = dirName.replace('models--', '');+ const [org, ...nameParts] = modelKey.split('--');+ const name = nameParts.join('--');+ const size = await dirSize(join(hubDir, dirName), { strict });+ return {+ id: dirName,+ org,+ name,+ repo: `${org}/${name}`,+ label: APP_MODELS[modelKey] || null,+ size,+ sizeHuman: formatBytes(size),+ };+ });++ models.sort((a, b) => b.size - a.size);+ return {+ hubDir,+ models,+ totalBytes: models.reduce((sum, model) => sum + model.size, 0),+ };+}++export async function listLoraStorage({ strict = false } = {}) {+ const rootPresent = strict+ ? await stat(PATHS.loras).then(+ (entry) => entry.isDirectory(),+ (err) => {+ if (err?.code === 'ENOENT') return false;+ throw err;+ },+ )+ : existsSync(PATHS.loras);+ if (!rootPresent) return { loras: [], totalBytes: 0 };+ const loras = [];+ for (const filename of await readdir(PATHS.loras)) {+ if (!filename.endsWith('.safetensors')) continue;+ const info = await stat(join(PATHS.loras, filename));+ loras.push({+ filename,+ name: filename.replace(/^lora-/, '').replace(/\.safetensors$/, ''),+ size: info.size,+ sizeHuman: formatBytes(info.size),+ });+ }+ loras.sort((a, b) => b.size - a.size);+ return {+ loras,+ totalBytes: loras.reduce((sum, lora) => sum + lora.size, 0),+ };+}++export async function getMediaModelStorage() {+ const [hf, loraStorage, totalImages, totalVideos] = await Promise.all([+ listHfModelStorage(),+ listLoraStorage(),+ dirSize(PATHS.images),+ dirSize(PATHS.videos),+ ]);++ return {+ models: hf.models,+ loras: loraStorage.loras,+ hubDir: hf.hubDir,+ diskUsage: {+ models: formatBytes(hf.totalBytes),+ loras: formatBytes(loraStorage.totalBytes),+ images: formatBytes(totalImages),+ videos: formatBytes(totalVideos),+ total: formatBytes(hf.totalBytes + loraStorage.totalBytes + totalImages + totalVideos),+ },+ };+}diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.jsindex 7177dc7df6..694dac49ea 100644--- a/server/services/ollamaManager.js+++ b/server/services/ollamaManager.js@@ -82,6 +82,7 @@ let isAvailable = null// null sentinel (not `.length`) lets a genuine "0 models installed" result cache// too — otherwise the catalog-overlay path re-hits /api/tags on every keystroke.let installedModels = null+let lastLoadedModelsError = nulllet lastCheckAt = nulllet managedProcess = nulllet managedProcessPid = null@@ -212,6 +213,7 @@ function resetAvailabilityCache() {isAvailable = nulllastCheckAt = nullinstalledModels = null+ lastLoadedModelsError = null}async function waitForAvailability(expected, timeoutMs) {@@ -768,9 +770,16 @@ async function getEmbeddings(text, options = {}) {* @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 []+ if (!(await checkOllamaAvailable())) {+ lastLoadedModelsError = status.lastError || 'Ollama is unavailable'+ return []+ }+ const data = await ollamaRequest('/api/ps').catch((err) => ({ _err: err.message }))+ if (!Array.isArray(data?.models)) {+ lastLoadedModelsError = data?._err || 'Ollama residency endpoint returned no model list'+ return []+ }+ lastLoadedModelsError = nullreturn data.models.map((m) => ({id: m.name || m.model,name: m.name || m.model,@@ -780,6 +789,11 @@ async function getLoadedModels() {}))}+/** Last `/api/ps` error (null only after a trustworthy residency list). */+function getLastLoadedModelsError() {+ return lastLoadedModelsError+}+/*** Force Ollama to evict a specific model from memory immediately.* Uses the documented `keep_alive: 0` trick — issuing any generate/chat@@ -801,6 +815,9 @@ async function unloadModel(modelName) {return { unloaded: false, reason: 'Ollama unreachable' }}const loaded = await getLoadedModels()+ if (getLastLoadedModelsError()) {+ return { unloaded: false, reason: 'Could not verify whether the model is loaded' }+ }if (!loaded.some((m) => m.id === modelName || m.name === modelName)) {return { unloaded: false, reason: 'not loaded' }}@@ -1045,6 +1062,57 @@ function getModelsDir() {return process.env.OLLAMA_MODELS || join(homedir(), '.ollama', 'models')}+/**+ * Enumerate Ollama manifests directly from disk so a stopped daemon does not+ * erase downloaded inventory. A corrupt or unreadable manifest rejects the+ * scan: counted UI must not turn unreadable state into a trustworthy empty.+ */+async function listStoredModels() {+ const manifestsDir = join(getModelsDir(), 'manifests')+ const root = await stat(manifestsDir).then((entry) => entry.isDirectory(), (err) => {+ if (err?.code === 'ENOENT') return false+ throw err+ })+ if (!root) return []++ const registries = (await readdir(manifestsDir, { withFileTypes: true }))+ .filter((entry) => entry.isDirectory())+ const models = []+ for (const registry of registries) {+ const registryDir = join(manifestsDir, registry.name)+ const namespaces = (await readdir(registryDir, { withFileTypes: true }))+ .filter((entry) => entry.isDirectory())+ for (const namespace of namespaces) {+ const namespaceDir = join(registryDir, namespace.name)+ const names = (await readdir(namespaceDir, { withFileTypes: true }))+ .filter((entry) => entry.isDirectory())+ for (const name of names) {+ const nameDir = join(namespaceDir, name.name)+ const tags = (await readdir(nameDir, { withFileTypes: true }))+ .filter((entry) => entry.isFile())+ for (const tag of tags) {+ const manifest = await readJSONFile(join(nameDir, tag.name), null, { logError: false, strict: true })+ if (!manifest) throw new Error(`Ollama manifest disappeared during inventory: ${tag.name}`)+ const sizes = manifestBlobRefs(manifest).map((blob) => blob.size)+ const size = sizes.length > 0 && sizes.every(Number.isFinite)+ ? sizes.reduce((sum, value) => sum + value, 0)+ : null+ const localRegistry = registry.name === 'registry.ollama.ai'+ const localNamespace = namespace.name === 'library'+ const base = localRegistry && localNamespace+ ? name.name+ : localRegistry+ ? `${namespace.name}/${name.name}`+ : `${registry.name}/${namespace.name}/${name.name}`+ const id = `${base}:${tag.name}`+ models.push({ id, name: id, size })+ }+ }+ }+ }+ return models.sort((a, b) => (b.size || 0) - (a.size || 0))+}+const fileExists = (p) => stat(p).then((s) => s.isFile()).catch(() => false)const readManifest = (p) => readJSONFile(p, null, { logError: false })// One expression for the canonical manifest path, so the recovery writer and@@ -1268,6 +1336,7 @@ export {getInstalledModels,getModelCapabilities,getLoadedModels,+ getLastLoadedModelsError,unloadModel,pullModel,deleteModel,@@ -1285,6 +1354,8 @@ export {ensureProviderReady,isOllamaProvider,getServiceStatus,+ getModelsDir,+ listStoredModels,getEmbeddings,isBootstrapConflictError,isPullDeadlineError,diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.jsindex 0b812e6bb5..c8850d3148 100644--- a/server/services/ollamaManager.test.js+++ b/server/services/ollamaManager.test.js@@ -87,6 +87,22 @@ async function loadManager() {const loadPullModel = () => loadManager().then((mod) => mod.pullModel)+describe('ollamaManager residency status', () => {+ afterEach(() => vi.unstubAllGlobals())++ it('keeps a failed /api/ps probe distinct from a trustworthy empty list', async () => {+ vi.stubGlobal('fetch', vi.fn(async (url) => {+ if (String(url).endsWith('/api/version')) return versionResponse()+ if (String(url).endsWith('/api/ps')) throw new Error('ps offline')+ throw new Error(`unexpected fetch: ${url}`)+ }))+ const { getLoadedModels, getLastLoadedModelsError } = await loadManager()++ await expect(getLoadedModels()).resolves.toEqual([])+ expect(getLastLoadedModelsError()).toMatch(/ps offline/i)+ })+})+describe('ollamaManager.pullModel transient-error retry', () => {beforeEach(() => { vi.useFakeTimers() })afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals() })@@ -297,6 +313,25 @@ describe('ollamaManager HF pull recovery', () => {})})+ describe('listStoredModels', () => {+ it('enumerates manifests from disk while the daemon is stopped', async () => {+ await mkdir(join(modelsDir, 'manifests', 'registry.ollama.ai', 'library', 'example'), { recursive: true })+ await writeFile(+ join(modelsDir, 'manifests', 'registry.ollama.ai', 'library', 'example', 'latest'),+ JSON.stringify(manifest()),+ )+ const { listStoredModels } = await loadManager()++ const rows = await listStoredModels()++ expect(rows).toEqual([expect.objectContaining({+ id: 'example:latest',+ name: 'example:latest',+ size: configBody.length + weightsBody.length,+ })])+ })+ })+describe('finalizeHuggingFacePull', () => {it('fetches the missing config blob and writes the manifest Ollama never wrote', async () => {await placeWeights()diff --git a/server/services/reviewQueue.js b/server/services/reviewQueue.jsindex ca46b46773..24641eadd0 100644--- a/server/services/reviewQueue.js+++ b/server/services/reviewQueue.js@@ -280,7 +280,7 @@ const PRODUCERS = [{source: 'health',label: 'Health anomalies',- drillTo: '/system-health',+ drillTo: '/system-resources/overview',async gather() {// System/health alerts; only surface the ones worth interrupting for.const { alerts = [] } = await getAlertsCached();@@ -300,7 +300,9 @@ const PRODUCERS = [summary: (alert.detail || alert.message || '').slice(0, 200),timestamp: alert.timestamp || null,severity: alert.severity === 'critical' ? 'critical' : 'high',- drillTo: alert.link || '/system-health',+ drillTo: alert.type === 'system_resource'+ ? '/system-resources/overview'+ : alert.link || '/system-resources/overview',...(alertType ? { meta: { alertType } } : {})};}diff --git a/server/services/reviewQueue.test.js b/server/services/reviewQueue.test.jsindex 6221c409aa..62fac311d7 100644--- a/server/services/reviewQueue.test.js+++ b/server/services/reviewQueue.test.js@@ -142,7 +142,7 @@ describe('reviewQueue.buildQueue', () => {const queue = await buildQueue();const healthRows = queue.items.filter(i => i.source === 'health');expect(healthRows).toHaveLength(1);- expect(healthRows[0]).toMatchObject({ severity: 'critical', summary: '95% used', drillTo: '/apps' });+ expect(healthRows[0]).toMatchObject({ severity: 'critical', summary: '95% used', drillTo: '/system-resources/overview' });expect(queue.items.find(i => i.source === 'backup')).toMatchObject({ title: 'Backup failed', summary: 'disk full' });});diff --git a/server/services/systemResources.js b/server/services/systemResources.jsnew file mode 100644index 0000000000..f30bc8caab--- /dev/null+++ b/server/services/systemResources.js@@ -0,0 +1,659 @@+/**+ * System Resources report + AI-assisted cleanup triage.+ *+ * The report is deliberately bounded to storage PortOS already understands:+ * classified data categories, PostgreSQL, model stores, package caches,+ * runtime dependencies, and aggregate browser-download usage. It never walks+ * arbitrary home-directory files and never sends filesystem paths or personal+ * record names to an AI provider.+ */++import os from 'os';+import { statfs } from 'fs/promises';+import { join } from 'path';+import { z } from 'zod';+import { query } from '../lib/db.js';+import { PATHS, dirSize } from '../lib/fileUtils.js';+import { ServerError } from '../lib/errorHandler.js';+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';+import { getDataOverview } from './dataManager.js';+import { listHfModelStorage, listLoraStorage } from './mediaModelStorage.js';+import * as ollamaManager from './ollamaManager.js';+import * as lmStudioManager from './lmStudioManager.js';+import { listJobs } from './mediaJobQueue/index.js';+import * as cos from './cos.js';++export const REPORT_CACHE_TTL_MS = 30_000;++const LOW_RISK_DATA_CATEGORIES = new Set([+ 'autofixer',+ 'browser-downloads',+ 'browser-profile',+ 'cache',+ 'conflict-journal',+ 'image-clean-tmp',+ 'insights',+ 'jira-reports',+ 'review',+ 'runs',+ 'screenshots',+ 'tools',+ 'update-detached',+ 'video-thumbnails',+]);++const TRIAGE_RESPONSE_SCHEMA = z.object({+ summary: z.string().trim().min(1).max(1400),+ recommendations: z.array(z.object({+ candidateId: z.string().trim().min(1).max(320),+ priority: z.enum(['first', 'next', 'optional']),+ reason: z.string().trim().min(1).max(600),+ tradeoff: z.string().trim().min(1).max(600),+ }).strict()).max(8),+ cautions: z.array(z.string().trim().min(1).max(500)).max(8),+}).strict();++const finiteOrNull = (value) => {+ if (value == null || value === '') return null;+ const number = Number(value);+ return Number.isFinite(number) && number >= 0 ? number : null;+};++const sumBytes = (values) => values.reduce(+ (sum, value) => sum + (Number.isFinite(value) ? value : 0),+ 0,+);++const sumKnownBytes = (values) => {+ const known = values.filter(Number.isFinite);+ return known.length > 0 ? sumBytes(known) : null;+};++function filesystemFrom(stats) {+ if (!stats) return null;+ const totalBytes = finiteOrNull(stats.blocks * stats.bsize);+ const freeBytes = finiteOrNull(stats.bavail * stats.bsize);+ if (!totalBytes || freeBytes == null) return null;+ const usedBytes = Math.max(0, totalBytes - freeBytes);+ return {+ totalBytes,+ usedBytes,+ freeBytes,+ usagePercent: Math.round((usedBytes / totalBytes) * 100),+ };+}++const backendState = (value) => (value == null ? 'unavailable' : 'ready');++function dataCleanupCandidates(categories) {+ if (!Array.isArray(categories)) return [];+ return categories+ .filter((category) => category.deletable && category.size > 0)+ .map((category) => {+ const oneClick = category.purgeScope === 'category'+ && !category.busy+ && LOW_RISK_DATA_CATEGORIES.has(category.key);+ const manualReview = category.purgeScope === 'items';+ return {+ id: `data:${category.key}`,+ label: category.label,+ kind: 'data',+ estimatedBytes: category.size,+ risk: oneClick ? 'low' : manualReview ? 'high' : 'medium',+ reason: category.description,+ loaded: false,+ busy: Boolean(category.busy),+ manualOnly: !oneClick,+ managePath: '/data',+ action: oneClick ? { type: 'data-category', key: category.key } : null,+ };+ });+}++function modelCleanupCandidates(downloaded) {+ return downloaded.map((model) => ({+ id: model.id,+ label: model.name,+ kind: 'model',+ estimatedBytes: model.sizeBytes,+ risk: model.risk || 'medium',+ reason: model.loaded+ ? 'Model weights are installed and the model is currently resident in memory.'+ : model.residencyUnknown+ ? 'PortOS could not verify whether this model is resident. Refresh the backend before deleting it.'+ : model.inventoryUnknown+ ? 'The backend reported this model, but its on-disk folder could not be verified for safe cleanup.'+ : model.cleanupReason || 'Downloaded model weights can be installed again later, but re-downloading may be slow or bandwidth-intensive.',+ loaded: model.loaded,+ busy: model.loaded || model.residencyUnknown,+ manualOnly: model.loaded || model.residencyUnknown || model.inventoryUnknown,+ managePath: model.managePath,+ action: model.loaded || model.residencyUnknown || model.inventoryUnknown ? null : model.action,+ }));+}++export function buildCleanupCandidates({ categories, downloadedModels, npmCacheBytes }) {+ const candidates = [+ ...dataCleanupCandidates(categories),+ ...modelCleanupCandidates(downloadedModels),+ ];+ if (Number.isFinite(npmCacheBytes) && npmCacheBytes > 0) {+ candidates.push({+ id: 'cache:npm',+ label: 'npm download cache',+ kind: 'cache',+ estimatedBytes: npmCacheBytes,+ risk: 'low',+ reason: 'Package tarballs are re-downloadable. PortOS reports this cache but does not delete global package-manager state in-app.',+ loaded: false,+ busy: false,+ manualOnly: true,+ managePath: null,+ action: null,+ });+ }+ return candidates.sort((a, b) => (b.estimatedBytes || 0) - (a.estimatedBytes || 0));+}++const normalizeLmStudioRepo = (value) => String(value || '')+ .split('/').pop()+ .trim()+ .toLowerCase()+ .replace(/[-.]gguf$/i, '')+ .replace(/[-.]mlx[-.].*$/i, '');++function downloadedModelInventory({+ hf,+ loraStorage,+ ollamaStatus,+ ollamaStored,+ ollamaLoaded,+ ollamaResidencyError,+ lmStudioModels,+ lmStudioStored,+ lmStudioLoaded,+ lmStudioResidencyError,+}) {+ const ollamaLoadedIds = new Set((ollamaLoaded || []).flatMap((model) => [model.id, model.name]).filter(Boolean));+ const lmStudioLoadedIds = new Set((lmStudioLoaded || []).flatMap((model) => [+ model.id,+ normalizeLmStudioRepo(model.id),+ ]).filter(Boolean));++ const huggingFace = (hf?.models || []).map((model) => ({+ id: `hf:${model.id}`,+ backend: 'huggingface',+ name: model.label || model.repo,+ detail: model.repo,+ sizeBytes: model.size,+ sizeIsEstimate: false,+ loaded: false,+ managePath: '/media/models',+ action: { type: 'hf-model', dirName: model.id },+ }));+ const loras = (loraStorage?.loras || []).map((model) => ({+ id: `lora:${model.filename}`,+ backend: 'lora',+ name: model.name,+ detail: 'LoRA adapter',+ sizeBytes: model.size,+ sizeIsEstimate: false,+ risk: 'high',+ cleanupReason: 'A trained or imported LoRA adapter may be the only copy and can take hours to reproduce.',+ loaded: false,+ managePath: '/media/loras',+ action: { type: 'lora', filename: model.filename },+ }));+ const ollamaApi = new Map((ollamaStatus?.models || []).map((model) => [model.id, model]));+ const ollamaDiskModels = Array.isArray(ollamaStored) ? ollamaStored : [];+ const ollamaRows = [+ ...ollamaDiskModels,+ ...(ollamaStatus?.models || []).filter((model) => !ollamaDiskModels.some((stored) => stored.id === model.id))+ .map((model) => ({ ...model, inventoryUnknown: true })),+ ];+ const ollama = ollamaRows.map((stored) => {+ const model = ollamaApi.get(stored.id) || stored;+ return {+ id: `ollama:${stored.id}`,+ backend: 'ollama',+ name: model.name || stored.name || stored.id,+ detail: [model.params, model.quantization, model.family].filter(Boolean).join(' · '),+ sizeBytes: finiteOrNull(stored.size ?? model.size),+ // Ollama layers can be shared between tags, so the per-model size is an+ // upper-bound estimate rather than guaranteed reclaimed bytes.+ sizeIsEstimate: true,+ loaded: !ollamaResidencyError && ollamaLoadedIds.has(stored.id),+ residencyUnknown: Boolean(ollamaResidencyError),+ inventoryUnknown: !Array.isArray(ollamaStored) || Boolean(stored.inventoryUnknown),+ managePath: '/settings/local-llm',+ action: ollamaStatus?.available+ ? { type: 'local-model', backend: 'ollama', modelId: stored.id }+ : null,+ };+ });++ const lmStudioApiGroups = new Map();+ for (const model of (lmStudioModels || [])) {+ const key = normalizeLmStudioRepo(model.id);+ const group = lmStudioApiGroups.get(key) || { models: [], ids: new Set(), quantizations: new Set() };+ group.models.push(model);+ group.ids.add(model.id);+ if (model.quantization) group.quantizations.add(model.quantization);+ lmStudioApiGroups.set(key, group);+ }+ const lmStudioDiskModels = Array.isArray(lmStudioStored) ? lmStudioStored : [];+ const diskKeys = new Set(lmStudioDiskModels.map((model) => normalizeLmStudioRepo(model.id)));+ const lmStudioRows = [+ ...lmStudioDiskModels,+ ...[...lmStudioApiGroups.entries()]+ .filter(([key]) => !diskKeys.has(key))+ .map(([, group]) => ({+ id: [...group.ids][0],+ name: [...group.ids][0],+ size: group.models.map((model) => finiteOrNull(model.size)).find(Number.isFinite) ?? null,+ inventoryUnknown: true,+ })),+ ];+ const lmstudio = lmStudioRows.map((stored) => {+ const group = lmStudioApiGroups.get(normalizeLmStudioRepo(stored.id));+ const quantizations = group ? [...group.quantizations] : [];+ const loaded = !lmStudioResidencyError && (+ lmStudioLoadedIds.has(stored.id)+ || lmStudioLoadedIds.has(normalizeLmStudioRepo(stored.id))+ || group?.models.some((model) => model.state === 'loaded')+ );+ return {+ id: `lmstudio:${stored.id}`,+ backend: 'lmstudio',+ name: stored.name || stored.id,+ detail: [+ quantizations.length ? `${quantizations.length} quantization${quantizations.length === 1 ? '' : 's'}: ${quantizations.join(', ')}` : null,+ 'removes the whole model folder',+ ].filter(Boolean).join(' · '),+ sizeBytes: finiteOrNull(stored.size),+ sizeIsEstimate: Boolean(stored.inventoryUnknown),+ loaded,+ residencyUnknown: Boolean(lmStudioResidencyError),+ inventoryUnknown: !Array.isArray(lmStudioStored) || Boolean(stored.inventoryUnknown),+ cleanupReason: 'Deleting this entry removes the whole LM Studio model folder, including every downloaded quantization in it.',+ managePath: '/settings/local-llm',+ action: { type: 'local-model', backend: 'lmstudio', modelId: stored.id },+ };+ });+ return [...huggingFace, ...loras, ...ollama, ...lmstudio]+ .sort((a, b) => (b.sizeBytes || 0) - (a.sizeBytes || 0));+}++function loadedModelInventory({ ollamaLoaded, lmStudioLoaded }) {+ return [+ ...(ollamaLoaded || []).map((model) => ({+ id: `ollama:${model.id}`,+ backend: 'ollama',+ name: model.name || model.id,+ memoryBytes: finiteOrNull(model.sizeVram ?? model.size),+ expiresAt: model.expiresAt || null,+ })),+ ...(lmStudioLoaded || []).map((model) => ({+ id: `lmstudio:${model.id}`,+ backend: 'lmstudio',+ name: model.id,+ memoryBytes: null,+ expiresAt: null,+ })),+ ];+}++function mediaQueueSummary(jobs) {+ const live = jobs.filter((job) => job.status === 'queued' || job.status === 'running');+ const byKind = Object.fromEntries(['image', 'video', 'training', 'audio'].map((kind) => {+ const matching = live.filter((job) => job.kind === kind);+ return [kind, {+ queued: matching.filter((job) => job.status === 'queued').length,+ running: matching.filter((job) => job.status === 'running').length,+ }];+ }));+ return {+ queued: live.filter((job) => job.status === 'queued').length,+ running: live.filter((job) => job.status === 'running').length,+ byKind,+ };+}++function agentQueueSummary(tasks, status) {+ if (!tasks) return null;+ return {+ pendingUser: tasks.user?.grouped?.pending?.length || 0,+ pendingSystem: tasks.cos?.grouped?.pending?.length || 0,+ awaitingApproval: tasks.cos?.awaitingApproval?.length || 0,+ inProgress: (tasks.user?.grouped?.in_progress?.length || 0)+ + (tasks.cos?.grouped?.in_progress?.length || 0),+ activeAgents: status ? status.activeAgents || 0 : null,+ pausedAgents: status ? status.pausedAgents || 0 : null,+ daemonRunning: status?.running ?? null,+ daemonPaused: status?.paused ?? null,+ };+}++export async function buildSystemResourceReport() {+ const npmCachePath = process.env.npm_config_cache || join(os.homedir(), '.npm');+ const dependencyPaths = [+ join(PATHS.root, 'node_modules'),+ join(PATHS.root, 'client', 'node_modules'),+ join(PATHS.root, 'server', 'node_modules'),+ ];++ const [+ diskStats,+ dataOverview,+ databaseRow,+ hf,+ loraStorage,+ ollamaStatus,+ ollamaStored,+ ollamaLoaded,+ ollamaBytes,+ lmStudioAvailable,+ lmStudioModels,+ lmStudioStored,+ lmStudioLoaded,+ lmStudioBytes,+ npmCacheBytes,+ dependencySizes,+ browserDownloadsBytes,+ cosTasks,+ cosStatus,+ ] = await Promise.all([+ statfs('/').catch(() => null),+ getDataOverview({ strict: true }).catch(() => null),+ query('SELECT pg_database_size(current_database()) AS bytes')+ .then((result) => result.rows[0] || null)+ .catch(() => null),+ listHfModelStorage({ strict: true }).catch(() => null),+ listLoraStorage({ strict: true }).catch(() => null),+ ollamaManager.getStatus(true).catch(() => null),+ ollamaManager.listStoredModels().catch(() => null),+ ollamaManager.getLoadedModels().catch(() => null),+ dirSize(ollamaManager.getModelsDir(), { strict: true }).catch(() => null),+ lmStudioManager.checkLMStudioAvailable(true).catch(() => null),+ lmStudioManager.getAvailableModels(true).catch(() => null),+ lmStudioManager.listStoredModels().catch(() => null),+ lmStudioManager.getLoadedModels(true).catch(() => null),+ lmStudioManager.getModelsDir().then((path) => dirSize(path, { strict: true })).catch(() => null),+ dirSize(npmCachePath, { strict: true }).catch(() => null),+ Promise.all(dependencyPaths.map((path) => dirSize(path, { strict: true }).catch(() => null))),+ dirSize(PATHS.browserDownloads, { strict: true }).catch(() => null),+ cos.getAllTasks().catch(() => null),+ cos.getStatus().catch(() => null),+ ]);++ const filesystem = filesystemFrom(diskStats);+ const databaseBytes = finiteOrNull(databaseRow?.bytes);+ const dependenciesBytes = sumKnownBytes(dependencySizes);+ const ollamaResidencyError = ollamaLoaded == null+ ? 'Ollama residency probe failed'+ : ollamaManager.getLastLoadedModelsError();+ const lmStudioResidencyError = lmStudioLoaded == null+ ? 'LM Studio residency probe failed'+ : lmStudioManager.getLastLoadedModelsError();+ const lmStudioListError = lmStudioModels == null+ ? 'LM Studio model inventory failed'+ : lmStudioManager.getLastListError();+ const downloadedModels = downloadedModelInventory({+ hf,+ loraStorage,+ ollamaStatus,+ ollamaStored,+ ollamaLoaded,+ ollamaResidencyError,+ lmStudioModels,+ lmStudioStored,+ lmStudioLoaded,+ lmStudioResidencyError,+ });+ const loadedModels = loadedModelInventory({ ollamaLoaded, lmStudioLoaded });+ const categories = dataOverview?.categories || null;+ const cleanupCandidates = buildCleanupCandidates({+ categories,+ downloadedModels,+ npmCacheBytes,+ });+ const mediaQueue = mediaQueueSummary(listJobs());+ const agentQueue = agentQueueSummary(cosTasks, cosStatus);+ const modelBytes = sumKnownBytes([hf?.totalBytes, loraStorage?.totalBytes, ollamaBytes, lmStudioBytes]);+ const storageAreas = [+ {+ id: 'portos-data', label: 'PortOS data', kind: 'data',+ sizeBytes: finiteOrNull(dataOverview?.totalSize), status: backendState(dataOverview),+ managePath: '/data', protected: false,+ note: 'Generated media, records, backups, worktrees, caches, and other classified app data.',+ },+ {+ id: 'postgres', label: 'PostgreSQL', kind: 'database',+ sizeBytes: databaseBytes, status: backendState(databaseRow),+ managePath: '/settings/database', protected: true,+ note: 'Primary relational records and vector indexes.',+ },+ {+ id: 'huggingface', label: 'Hugging Face models', kind: 'model',+ sizeBytes: finiteOrNull(hf?.totalBytes), status: backendState(hf),+ managePath: '/media/models', protected: false,+ note: 'Image, video, audio, and text-encoder weights in the shared Hub cache.',+ },+ {+ id: 'loras', label: 'LoRA adapters', kind: 'model',+ sizeBytes: finiteOrNull(loraStorage?.totalBytes), status: backendState(loraStorage),+ managePath: '/media/loras', protected: false,+ note: 'Fine-tuning adapters in PortOS data. This total also appears inside PortOS data.',+ },+ {+ id: 'ollama', label: 'Ollama models', kind: 'model',+ sizeBytes: finiteOrNull(ollamaBytes), status: backendState(ollamaBytes),+ managePath: '/settings/local-llm', protected: false,+ note: 'Local language-model manifests and shared blobs.',+ },+ {+ id: 'lmstudio', label: 'LM Studio models', kind: 'model',+ sizeBytes: finiteOrNull(lmStudioBytes), status: backendState(lmStudioBytes),+ managePath: '/settings/local-llm', protected: false,+ note: 'Downloaded GGUF or MLX model directories.',+ },+ {+ id: 'npm-cache', label: 'npm cache', kind: 'cache',+ sizeBytes: finiteOrNull(npmCacheBytes), status: backendState(npmCacheBytes),+ managePath: null, protected: false,+ note: 'Global package download cache; reported only, never deleted in-app.',+ },+ {+ id: 'dependencies', label: 'PortOS dependencies', kind: 'runtime',+ sizeBytes: dependenciesBytes,+ status: dependencySizes.every(Number.isFinite) ? 'ready' : 'unavailable',+ managePath: null, protected: true,+ note: 'Installed Node.js dependencies required by the running app.',+ },+ {+ id: 'browser-downloads', label: 'Browser downloads', kind: 'personal',+ sizeBytes: finiteOrNull(browserDownloadsBytes), status: backendState(browserDownloadsBytes),+ managePath: null, protected: true,+ note: 'Aggregate Downloads-folder usage. File names are never inspected or sent to AI.',+ },+ ];+ const storageErrors = storageAreas+ .filter((area) => area.status === 'unavailable')+ .map((area) => area.id);+ const sourceErrors = [...new Set([+ ...storageErrors,+ ...(!filesystem ? ['filesystem'] : []),+ ...(!ollamaStatus?.available ? ['ollama-backend'] : []),+ ...(ollamaStored == null ? ['ollama-inventory'] : []),+ ...(ollamaResidencyError ? ['ollama-residency'] : []),+ ...(lmStudioAvailable !== true ? ['lmstudio-backend'] : []),+ ...(lmStudioStored == null ? ['lmstudio-inventory'] : []),+ ...(lmStudioListError ? ['lmstudio-catalog'] : []),+ ...(lmStudioResidencyError ? ['lmstudio-residency'] : []),+ ...(cosTasks == null ? ['agent-queue'] : []),+ ...(cosStatus == null ? ['agent-status'] : []),+ ])];+ const managedReclaimableBytes = sumBytes(cleanupCandidates+ .filter((candidate) => candidate.risk === 'low' && candidate.action)+ .map((candidate) => candidate.estimatedBytes));+ const queuedAgents = agentQueue+ // Awaiting-approval tasks are already part of pendingSystem. Keep the+ // review count as a useful breakdown without counting those tasks twice in+ // the top-line queued total.+ ? agentQueue.pendingUser + agentQueue.pendingSystem+ : 0;++ return {+ generatedAt: new Date().toISOString(),+ filesystem,+ summary: {+ knownFootprintBytes: sumKnownBytes(storageAreas.map((area) => area.sizeBytes)),+ footprintMayOverlap: true,+ portosDataBytes: finiteOrNull(dataOverview?.totalSize),+ databaseBytes,+ modelBytes,+ managedReclaimableBytes,+ loadedModels: loadedModels.length,+ queuedJobs: agentQueue ? mediaQueue.queued + queuedAgents : null,+ runningJobs: agentQueue ? mediaQueue.running + agentQueue.inProgress : null,+ },+ storageAreas,+ dataCategories: categories,+ models: {+ downloaded: downloadedModels,+ loaded: loadedModels,+ totals: {+ huggingface: finiteOrNull(hf?.totalBytes),+ loras: finiteOrNull(loraStorage?.totalBytes),+ ollama: finiteOrNull(ollamaBytes),+ lmstudio: finiteOrNull(lmStudioBytes),+ all: modelBytes,+ },+ },+ queues: { media: mediaQueue, agents: agentQueue },+ cleanupCandidates,+ sourceErrors,+ };+}++let reportCache = null;+let reportCacheAt = 0;+let reportInFlight = null;++export function resetSystemResourceReportCache() {+ reportCache = null;+ reportCacheAt = 0;+ reportInFlight = null;+}++export function getSystemResourceReport({ force = false } = {}) {+ if (!force && reportCache && Date.now() - reportCacheAt < REPORT_CACHE_TTL_MS) {+ return Promise.resolve(reportCache);+ }+ if (!reportInFlight) {+ reportInFlight = buildSystemResourceReport().then(+ (report) => {+ reportCache = report;+ reportCacheAt = Date.now();+ reportInFlight = null;+ return report;+ },+ (error) => {+ reportInFlight = null;+ throw error;+ },+ );+ }+ return reportInFlight;+}++export function buildSystemResourceTriagePrompt(report) {+ const candidates = report.cleanupCandidates.slice(0, 50).map((candidate, index) => ({+ // Deliberately opaque. A model id or LoRA filename can contain a personal+ // project name, so even candidate identifiers stay machine-local.+ id: `candidate-${index + 1}`,+ kind: candidate.kind,+ estimatedBytes: candidate.estimatedBytes,+ risk: candidate.risk,+ loaded: candidate.loaded,+ busy: candidate.busy,+ manualOnly: candidate.manualOnly,+ actionable: Boolean(candidate.action),+ }));+ const context = {+ filesystem: report.filesystem,+ summary: report.summary,+ queues: report.queues,+ unavailableSources: report.sourceErrors,+ candidates,+ };+ return `You are triaging disk pressure for a private, single-user PortOS installation.++Rank only the cleanup candidates supplied below. Never invent a path, file, command, candidate id, or deletion action. Treat byte counts as estimates: model layers and hardlinks can overlap, and deleting one tagged model may reclaim less than its displayed size. Do not recommend deleting a loaded or busy item until it is unloaded or idle. Respect risk: prefer low-risk reproducible caches, explain rebuild/download costs, and put protected or user-authored data behind manual review. If free space is healthy, say so and keep recommendations conservative.++Return ONLY JSON with this exact shape:+{+ "summary": "short assessment",+ "recommendations": [+ { "candidateId": "one supplied id", "priority": "first|next|optional", "reason": "why it helps", "tradeoff": "what is lost or rebuilt" }+ ],+ "cautions": ["important caveat"]+}++SYSTEM REPORT (no filesystem paths or personal filenames):+${JSON.stringify(context, null, 2)}`;+}++export async function triageSystemResources({+ providerId,+ model,+ effort,+ onRunCreated,+ onRunSettled,+} = {}) {+ const report = await getSystemResourceReport();+ const triageCandidates = report.cleanupCandidates.slice(0, 50);+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });+ assertProvider(provider, {+ message: 'No AI provider is configured for system-resource triage',+ code: 'NO_PROVIDER',+ });++ const result = await runPromptThroughProvider({+ provider,+ model: selectedModel,+ effort,+ prompt: buildSystemResourceTriagePrompt(report),+ source: 'system-resource-triage',+ responseSchema: TRIAGE_RESPONSE_SCHEMA,+ onRunCreated,+ onRunSettled,+ });+ const parsed = TRIAGE_RESPONSE_SCHEMA.parse(JSON.parse(result.text));+ const candidatesById = new Map(triageCandidates.map((candidate, index) => [`candidate-${index + 1}`, candidate]));+ const seen = new Set();+ const recommendations = parsed.recommendations.flatMap((recommendation) => {+ const candidate = candidatesById.get(recommendation.candidateId);+ if (!candidate || seen.has(candidate.id)) return [];+ seen.add(candidate.id);+ return [{ ...recommendation, candidateId: candidate.id, candidate }];+ });+ if (parsed.recommendations.length > 0 && recommendations.length === 0) {+ throw new ServerError('AI triage did not reference any known cleanup candidate', {+ status: 502,+ code: 'LLM_OUTPUT_CONTRACT',+ });+ }++ return {+ report,+ triage: {+ summary: parsed.summary,+ recommendations,+ cautions: parsed.cautions,+ runId: result.runId,+ providerId: result.provider?.id || provider.id,+ model: result.model || selectedModel,+ },+ };+}diff --git a/server/services/systemResources.test.js b/server/services/systemResources.test.jsnew file mode 100644index 0000000000..96b5d0e44e--- /dev/null+++ b/server/services/systemResources.test.js@@ -0,0 +1,284 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('fs/promises', async (importOriginal) => ({+ ...(await importOriginal()),+ statfs: vi.fn(async () => ({ blocks: 1000, bsize: 100, bavail: 250 })),+}));+vi.mock('../lib/db.js', () => ({+ query: vi.fn(async () => ({ rows: [{ bytes: '4096' }] })),+}));+vi.mock('../lib/fileUtils.js', () => ({+ PATHS: {+ root: '/example/portos',+ browserDownloads: '/example/Downloads',+ },+ dirSize: vi.fn(async (path) => path.includes('Downloads') ? 900 : 100),+}));+vi.mock('../lib/promptRunner.js', () => ({+ resolveProviderAndModel: vi.fn(async () => ({ provider: { id: 'codex' }, selectedModel: 'gpt-example' })),+ assertProvider: vi.fn(),+ runPromptThroughProvider: vi.fn(async () => ({+ text: JSON.stringify({+ summary: 'Start with the reproducible cache.',+ recommendations: [{+ candidateId: 'candidate-2',+ priority: 'first',+ reason: 'It is low risk.',+ tradeoff: 'It will be rebuilt.',+ }],+ cautions: [],+ }),+ runId: 'run-example',+ provider: { id: 'codex' },+ model: 'gpt-example',+ })),+}));+vi.mock('./dataManager.js', () => ({+ getDataOverview: vi.fn(async () => ({+ totalSize: 500,+ categories: [{+ key: 'cache', label: 'Remote API Cache', description: 'Reproducible metadata',+ size: 300, deletable: true, purgeScope: 'category', busy: false,+ }],+ })),+}));+vi.mock('./mediaModelStorage.js', () => ({+ listHfModelStorage: vi.fn(async () => ({+ totalBytes: 700,+ models: [{ id: 'models--example--public', repo: 'example/public', label: null, size: 700 }],+ })),+ listLoraStorage: vi.fn(async () => ({+ totalBytes: 200,+ loras: [{ filename: 'private-project.safetensors', name: 'Private Project', size: 200 }],+ })),+}));+vi.mock('./ollamaManager.js', () => ({+ getStatus: vi.fn(async () => ({ available: true, models: [{ id: 'example:latest', name: 'Example', size: 100 }] })),+ listStoredModels: vi.fn(async () => [{ id: 'example:latest', name: 'Example', size: 100 }]),+ getLoadedModels: vi.fn(async () => [{ id: 'example:latest', name: 'Example', sizeVram: 80 }]),+ getLastLoadedModelsError: vi.fn(() => null),+ getModelsDir: vi.fn(() => '/example/ollama'),+}));+vi.mock('./lmStudioManager.js', () => ({+ checkLMStudioAvailable: vi.fn(async () => true),+ getAvailableModels: vi.fn(async () => [{ id: 'example/lmstudio', name: 'LM Example', size: 120 }]),+ listStoredModels: vi.fn(async () => [{ id: 'example/lmstudio', name: 'lmstudio', size: 120 }]),+ getLoadedModels: vi.fn(async () => []),+ getLastLoadedModelsError: vi.fn(() => null),+ getLastListError: vi.fn(() => null),+ getModelsDir: vi.fn(async () => '/example/lmstudio'),+}));+vi.mock('./mediaJobQueue/index.js', () => ({+ listJobs: vi.fn(() => [+ { id: 'image-1', kind: 'image', status: 'queued' },+ { id: 'video-1', kind: 'video', status: 'running' },+ ]),+}));+vi.mock('./cos.js', () => ({+ getAllTasks: vi.fn(async () => ({+ user: { grouped: { pending: [{ id: 'task-1' }], in_progress: [] } },+ cos: {+ grouped: { pending: [{ id: 'approval-1', approvalRequired: true }], in_progress: [] },+ awaitingApproval: [{ id: 'approval-1', approvalRequired: true }],+ },+ })),+ getStatus: vi.fn(async () => ({ running: true, paused: false, activeAgents: 0, pausedAgents: 0 })),+}));++const promptRunner = await import('../lib/promptRunner.js');+const fsPromises = await import('fs/promises');+const db = await import('../lib/db.js');+const fileUtils = await import('../lib/fileUtils.js');+const dataManager = await import('./dataManager.js');+const mediaModelStorage = await import('./mediaModelStorage.js');+const ollamaManager = await import('./ollamaManager.js');+const lmStudioManager = await import('./lmStudioManager.js');+const cos = await import('./cos.js');+const {+ buildCleanupCandidates,+ buildSystemResourceReport,+ buildSystemResourceTriagePrompt,+ resetSystemResourceReportCache,+ triageSystemResources,+} = await import('./systemResources.js');++describe('system resource reporting', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetSystemResourceReportCache();+ fileUtils.dirSize.mockImplementation(async (path) => path.includes('Downloads') ? 900 : 100);+ ollamaManager.getStatus.mockResolvedValue({+ available: true,+ models: [{ id: 'example:latest', name: 'Example', size: 100 }],+ });+ ollamaManager.listStoredModels.mockResolvedValue([{ id: 'example:latest', name: 'Example', size: 100 }]);+ ollamaManager.getLoadedModels.mockResolvedValue([{ id: 'example:latest', name: 'Example', sizeVram: 80 }]);+ ollamaManager.getLastLoadedModelsError.mockReturnValue(null);+ lmStudioManager.checkLMStudioAvailable.mockResolvedValue(true);+ lmStudioManager.getAvailableModels.mockResolvedValue([{ id: 'example/lmstudio', name: 'LM Example', size: 120 }]);+ lmStudioManager.listStoredModels.mockResolvedValue([{ id: 'example/lmstudio', name: 'lmstudio', size: 120 }]);+ lmStudioManager.getLoadedModels.mockResolvedValue([]);+ lmStudioManager.getLastLoadedModelsError.mockReturnValue(null);+ lmStudioManager.getLastListError.mockReturnValue(null);+ });++ it('combines storage, model residency, and live queue summaries', async () => {+ const report = await buildSystemResourceReport();+ expect(dataManager.getDataOverview).toHaveBeenCalledWith({ strict: true });+ expect(lmStudioManager.checkLMStudioAvailable).toHaveBeenCalledWith(true);+ expect(lmStudioManager.getAvailableModels).toHaveBeenCalledWith(true);+ expect(report.filesystem).toEqual({+ totalBytes: 100000,+ usedBytes: 75000,+ freeBytes: 25000,+ usagePercent: 75,+ });+ expect(report.summary).toMatchObject({ loadedModels: 1, queuedJobs: 3, runningJobs: 1 });+ expect(report.queues.agents).toMatchObject({ pendingSystem: 1, awaitingApproval: 1 });+ expect(report.models.downloaded.map((model) => model.backend)).toEqual(+ expect.arrayContaining(['huggingface', 'lora', 'ollama', 'lmstudio']),+ );+ expect(report.cleanupCandidates.find((item) => item.id === 'ollama:example:latest')).toMatchObject({+ loaded: true,+ action: null,+ });+ expect(report.cleanupCandidates.find((item) => item.id === 'lora:private-project.safetensors')).toMatchObject({+ risk: 'high',+ });+ });++ it('only enables one-click data purges for the conservative allowlist', () => {+ const candidates = buildCleanupCandidates({+ categories: [+ { key: 'cache', label: 'Cache', description: 'Safe', size: 50, deletable: true, purgeScope: 'category', busy: false },+ { key: 'backup', label: 'Backups', description: 'Review', size: 500, deletable: true, purgeScope: 'category', busy: false },+ ],+ downloadedModels: [],+ npmCacheBytes: 0,+ });+ expect(candidates.find((item) => item.id === 'data:cache').action).toEqual({ type: 'data-category', key: 'cache' });+ expect(candidates.find((item) => item.id === 'data:backup').action).toBeNull();+ });++ it('keeps downloaded models visible while an offline backend blocks unsafe cleanup', async () => {+ ollamaManager.getStatus.mockResolvedValue({ available: false, models: [] });+ ollamaManager.getLoadedModels.mockResolvedValue([]);+ ollamaManager.getLastLoadedModelsError.mockReturnValue('backend unavailable');++ const report = await buildSystemResourceReport();+ const model = report.models.downloaded.find((item) => item.id === 'ollama:example:latest');+ const candidate = report.cleanupCandidates.find((item) => item.id === model.id);++ expect(model).toMatchObject({ name: 'Example', residencyUnknown: true });+ expect(candidate).toMatchObject({ busy: true, manualOnly: true, action: null });+ expect(report.sourceErrors).toEqual(expect.arrayContaining(['ollama-backend', 'ollama-residency']));+ });++ it('aggregates LM Studio quantizations into one folder-scoped cleanup row', async () => {+ lmStudioManager.getAvailableModels.mockResolvedValue([+ { id: 'example/lmstudio', quantization: 'Q4_K_M', state: 'not-loaded' },+ { id: 'example/lmstudio', quantization: 'Q8_0', state: 'not-loaded' },+ ]);++ const report = await buildSystemResourceReport();+ const rows = report.models.downloaded.filter((item) => item.backend === 'lmstudio');++ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({+ id: 'lmstudio:example/lmstudio',+ action: { type: 'local-model', backend: 'lmstudio', modelId: 'example/lmstudio' },+ });+ expect(rows[0].detail).toContain('2 quantizations');+ expect(rows[0].detail).toContain('whole model folder');+ });++ it('surfaces strict size-scan failures instead of reporting a ready zero', async () => {+ fileUtils.dirSize.mockImplementation(async (path) => {+ if (path === '/example/portos/node_modules') return null;+ return path.includes('Downloads') ? 900 : 100;+ });++ const report = await buildSystemResourceReport();+ const dependencies = report.storageAreas.find((area) => area.id === 'dependencies');++ expect(dependencies).toMatchObject({ status: 'unavailable' });+ expect(report.sourceErrors).toContain('dependencies');+ });++ it('surfaces a failed filesystem capacity probe as unknown', async () => {+ fsPromises.statfs.mockRejectedValueOnce(new Error('statfs unavailable'));++ const report = await buildSystemResourceReport();++ expect(report.filesystem).toBeNull();+ expect(report.sourceErrors).toContain('filesystem');+ });++ it('marks an unreadable PortOS data scan unavailable', async () => {+ dataManager.getDataOverview.mockRejectedValueOnce(new Error('permission denied'));++ const report = await buildSystemResourceReport();+ const dataArea = report.storageAreas.find((area) => area.id === 'portos-data');++ expect(dataArea).toMatchObject({ sizeBytes: null, status: 'unavailable' });+ expect(report.sourceErrors).toContain('portos-data');+ expect(report.cleanupCandidates.some((candidate) => candidate.kind === 'data')).toBe(false);+ });++ it('preserves failed agent queue and status probes as unknown', async () => {+ cos.getAllTasks.mockRejectedValueOnce(new Error('task store unavailable'));+ cos.getStatus.mockRejectedValueOnce(new Error('daemon status unavailable'));++ const report = await buildSystemResourceReport();++ expect(report.queues.agents).toBeNull();+ expect(report.summary).toMatchObject({ queuedJobs: null, runningJobs: null });+ expect(report.sourceErrors).toEqual(expect.arrayContaining(['agent-queue', 'agent-status']));+ });++ it('keeps daemon status unknown when only the COS status probe fails', async () => {+ cos.getStatus.mockRejectedValueOnce(new Error('daemon status unavailable'));++ const report = await buildSystemResourceReport();++ expect(report.queues.agents).toMatchObject({+ activeAgents: null,+ pausedAgents: null,+ daemonRunning: null,+ daemonPaused: null,+ });+ expect(report.sourceErrors).toContain('agent-status');+ });++ it('returns an unknown footprint instead of zero when every area scan fails', async () => {+ dataManager.getDataOverview.mockRejectedValueOnce(new Error('data unavailable'));+ db.query.mockRejectedValueOnce(new Error('database unavailable'));+ mediaModelStorage.listHfModelStorage.mockRejectedValueOnce(new Error('cache unavailable'));+ mediaModelStorage.listLoraStorage.mockRejectedValueOnce(new Error('lora store unavailable'));+ fileUtils.dirSize.mockResolvedValue(null);++ const report = await buildSystemResourceReport();++ expect(report.storageAreas.every((area) => area.sizeBytes == null)).toBe(true);+ expect(report.summary.knownFootprintBytes).toBeNull();+ });++ it('keeps model names, ids, filenames, and paths out of the AI prompt', async () => {+ const report = await buildSystemResourceReport();+ const prompt = buildSystemResourceTriagePrompt(report);+ expect(prompt).toContain('candidate-1');+ expect(prompt).not.toContain('private-project.safetensors');+ expect(prompt).not.toContain('Private Project');+ expect(prompt).not.toContain('example:latest');+ expect(prompt).not.toContain('/example/');+ });++ it('maps opaque AI candidate ids back to server-issued cleanup candidates', async () => {+ const result = await triageSystemResources({ providerId: 'codex' });+ expect(promptRunner.runPromptThroughProvider).toHaveBeenCalledWith(expect.objectContaining({+ source: 'system-resource-triage',+ }));+ expect(result.triage.recommendations[0].candidate).toMatchObject({ id: 'data:cache' });+ expect(result.triage.recommendations[0].candidateId).toBe('data:cache');+ });+});