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 persistent mind runtime telemetry
Adam Eivya000f1d3124d
diff --git a/client/src/components/cos/PersistentMindRuntimePanel.jsx b/client/src/components/cos/PersistentMindRuntimePanel.jsxnew file mode 100644index 0000000000..614acfcb70--- /dev/null+++ b/client/src/components/cos/PersistentMindRuntimePanel.jsx@@ -0,0 +1,93 @@+import { Brain, Cpu, Gauge } from 'lucide-react';+import { formatBytes } from '../../utils/formatters.js';++const number = (value) => Number.isFinite(value) ? value.toLocaleString() : '—';++const residencyLabel = (runtime) => {+ if (runtime?.inference?.active) return 'Running now';+ const status = runtime?.inference?.residency?.status;+ if (status === 'loaded') return 'Loaded in memory';+ if (status === 'not-loaded') return 'Not loaded';+ if (status === 'provider-managed') return 'Provider-managed';+ if (status === 'unconfigured') return 'Not configured';+ return 'Status unknown';+};++export function PersistentMindThoughtStatus({ state, model }) {+ const thinking = state?.status === 'thinking' && Boolean(state.activeTurnId);+ const label = thinking+ ? `Thinking${model ? ` with ${model}` : ''}`+ : state?.status === 'waiting' ? 'Waiting for the next wake'+ : state?.status === 'paused' ? 'Mind paused'+ : state?.status === 'idle' ? 'Mind idle'+ : state?.status === 'disabled' ? 'Mind disabled'+ : 'Mind status unknown';++ return (+ <span+ role="status"+ aria-busy={thinking}+ className={`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-medium ${thinking ? 'border-port-accent/60 bg-port-accent/10 text-port-accent' : 'border-port-border text-port-text-muted'}`}+ >+ <Brain size={14} className={thinking ? 'animate-pulse motion-reduce:animate-none' : ''} aria-hidden="true" />+ <span>{label}</span>+ {thinking && (+ <span className="inline-flex gap-0.5" aria-hidden="true">+ {[0, 1, 2].map((index) => (+ <span+ key={index}+ className="h-1 w-1 animate-bounce rounded-full bg-current motion-reduce:animate-none"+ style={{ animationDelay: `${index * 120}ms` }}+ />+ ))}+ </span>+ )}+ </span>+ );+}++export default function PersistentMindRuntimePanel({ runtime, error, loading, onOpenContext }) {+ const context = runtime?.context;+ const memory = runtime?.system?.memory;+ const processMemory = runtime?.system?.process;+ const residency = runtime?.inference?.residency;+ const usagePercent = Number.isFinite(memory?.usagePercent) ? memory.usagePercent : null;++ return (+ <section aria-label="Persistent mind runtime" className="grid gap-3 md:grid-cols-3">+ <button type="button" onClick={onOpenContext} className="rounded border border-port-border bg-port-card p-3 text-left hover:bg-port-border/20">+ <span className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-port-accent"><Brain size={15} aria-hidden="true" /> Effective context</span>+ <span className="mt-2 block text-lg font-semibold text-port-text">~{number(context?.approximateTokens)} tokens</span>+ <span className="mt-1 block text-xs text-port-text-muted">+ {number(context?.chars)} / {number(context?.maxChars)} characters · {number(context?.memoryCount)} curated memories · summary {context?.summaryState || 'unknown'}+ </span>+ </button>++ <div className="rounded border border-port-border bg-port-card p-3">+ <span className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-port-accent"><Gauge size={15} aria-hidden="true" /> System memory</span>+ <span className="mt-2 block text-lg font-semibold text-port-text">{memory ? `${formatBytes(memory.used)} / ${formatBytes(memory.total)}` : '—'}</span>+ <div className="mt-2 h-1.5 overflow-hidden rounded-full bg-port-border" role="progressbar" aria-label="System memory used" aria-valuemin="0" aria-valuemax="100" aria-valuenow={usagePercent ?? undefined}>+ <div className="h-full rounded-full bg-port-accent transition-[width]" style={{ width: `${usagePercent ?? 0}%` }} />+ </div>+ <span className="mt-1 block text-xs text-port-text-muted">{usagePercent === null ? 'Usage unavailable' : `${usagePercent}% used`} · PortOS RSS {processMemory ? formatBytes(processMemory.rss) : '—'} · heap {processMemory ? formatBytes(processMemory.heapUsed) : '—'}</span>+ </div>++ <div className="rounded border border-port-border bg-port-card p-3">+ <span className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-port-accent"><Cpu size={15} aria-hidden="true" /> Model activity</span>+ <span className="mt-2 block text-lg font-semibold text-port-text">{residencyLabel(runtime)}</span>+ <span className="mt-1 block break-words text-xs text-port-text-muted">+ {runtime?.inference?.providerId || 'No provider'} · {runtime?.inference?.model || 'No model'}+ {residency?.backend ? ` · ${residency.backend}` : ''}+ {residency?.memoryBytes ? ` · ${formatBytes(residency.memoryBytes)}` : ''}+ </span>+ {runtime?.system?.cpu && <span className="mt-1 block text-xs text-port-text-muted">Host load {runtime.system.cpu.loadAvg1m.toFixed(2)} across {runtime.system.cpu.cores} cores</span>}+ </div>++ {(loading || error) && (+ <p className={`md:col-span-3 text-xs ${error ? 'text-port-warning' : 'text-port-text-muted'}`}>+ {error ? `Live telemetry delayed: ${error}. Showing the last successful snapshot when available.` : 'Refreshing live telemetry…'}+ </p>+ )}+ </section>+ );+}diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsxindex dd10d46a48..efb305f722 100644--- a/client/src/components/cos/tabs/MindTab.jsx+++ b/client/src/components/cos/tabs/MindTab.jsx@@ -10,6 +10,7 @@ import Banner from '../../ui/Banner';import TabPills from '../../ui/TabPills';import PersistentMindContextPanel from '../PersistentMindContextPanel';import PersistentMindProfileControls from '../PersistentMindProfileControls';+import PersistentMindRuntimePanel, { PersistentMindThoughtStatus } from '../PersistentMindRuntimePanel';const PAGE_LIMIT = 200;const MAX_BACKFILL_PAGES = 5;@@ -81,9 +82,16 @@ export default function MindTab() {const [lifecycleError, setLifecycleError] = useState(null);const [profileSaving, setProfileSaving] = useState(false);const [showActivity, setShowActivity] = useState(false);+ const [runtime, setRuntime] = useState(null);+ const [runtimeError, setRuntimeError] = useState(null);+ const [runtimeLoading, setRuntimeLoading] = useState(true);const cursorRef = useRef(null);const loadPendingRef = useRef(false);const deferredLoadRef = useRef(false);+ const runtimePendingRef = useRef(false);+ const deferredRuntimeRef = useRef(false);+ const runtimeLoadedRef = useRef(false);+ const runtimeMountedRef = useRef(true);const draftIdRef = useRef(null);const loadHistory = useCallback(async ({ reset = false } = {}) => {@@ -129,10 +137,46 @@ export default function MindTab() {}}, []);+ const loadRuntime = useCallback(async () => {+ if (runtimePendingRef.current) {+ deferredRuntimeRef.current = true;+ return;+ }+ runtimePendingRef.current = true;+ if (!runtimeLoadedRef.current) setRuntimeLoading(true);+ try {+ const response = await api.getPersistentMindRuntime({ silent: true });+ if (!runtimeMountedRef.current) return;+ setRuntime(response);+ runtimeLoadedRef.current = true;+ setRuntimeError(null);+ } catch (error) {+ if (runtimeMountedRef.current) {+ setRuntimeError(error?.message || 'Could not refresh runtime telemetry');+ }+ } finally {+ if (runtimeMountedRef.current) setRuntimeLoading(false);+ runtimePendingRef.current = false;+ if (runtimeMountedRef.current && deferredRuntimeRef.current) {+ deferredRuntimeRef.current = false;+ void loadRuntime();+ }+ }+ }, []);+useEffect(() => { void loadHistory({ reset: true }); }, [loadHistory]);+ useEffect(() => () => { runtimeMountedRef.current = false; }, []);+ useEffect(() => {+ void loadRuntime();+ const interval = setInterval(() => { void loadRuntime(); }, 10_000);+ return () => clearInterval(interval);+ }, [loadRuntime]);useEffect(() => {- const refresh = () => { void loadHistory(); };+ const refresh = () => {+ void loadHistory();+ void loadRuntime();+ };socket.on('connect', refresh);socket.on('cos:mind:event', refresh);socket.on('cos:mind:status', refresh);@@ -141,7 +185,7 @@ export default function MindTab() {socket.off('cos:mind:event', refresh);socket.off('cos:mind:status', refresh);};- }, [loadHistory, socket]);+ }, [loadHistory, loadRuntime, socket]);const submit = async (event) => {event.preventDefault();@@ -177,6 +221,7 @@ export default function MindTab() {setText('');draftIdRef.current = null;await loadHistory();+ void loadRuntime();} catch (error) {setSubmitError(error?.message || 'The input was not accepted');} finally {@@ -207,6 +252,7 @@ export default function MindTab() {if (action === 'resume') await api.resumePersistentMind({ silent: true });if (action === 'stop') await api.stopPersistentMind({ silent: true });await loadHistory();+ void loadRuntime();} catch (error) {setLifecycleError(error?.message || `Could not ${action} the persistent mind`);} finally {@@ -270,12 +316,23 @@ export default function MindTab() {<p className="mt-2 text-xs text-port-text-muted">{mind ? `${mind.profile?.providerId || 'No provider'} · ${mind.profile?.model || 'No model'} · ${mind.profile?.effort || 'provider default'} · autonomy ${mind.autonomyMode}` : 'Profile unavailable'}</p>+ <div className="mt-3">+ <PersistentMindThoughtStatus+ state={state}+ model={state?.activeTurnId && state.activeTurnId === runtime?.inference?.turnId+ ? runtime.inference.model+ : mind?.profile?.model}+ />+ </div></div><div className="flex flex-wrap gap-2" role="group" aria-label="Persistent mind lifecycle">{state?.started && !isPaused && <ActionButton label="Pause" icon={CirclePause} pending={lifecyclePending === 'pause'} onClick={() => runLifecycle('pause')} />}{state?.started && isPaused && <ActionButton label="Resume" icon={CirclePlay} pending={lifecyclePending === 'resume'} onClick={() => runLifecycle('resume')} />}{state?.started && <ActionButton label="Stop" icon={Square} pending={lifecyclePending === 'stop'} onClick={() => runLifecycle('stop')} />}- <ActionButton label="Reload" icon={RefreshCw} pending={loading} onClick={() => loadHistory({ reset: true })} />+ <ActionButton label="Reload" icon={RefreshCw} pending={loading || runtimeLoading} onClick={() => {+ void loadHistory({ reset: true });+ void loadRuntime();+ }} /></div></header>@@ -286,6 +343,8 @@ export default function MindTab() {{loadError && <Banner tone="error" title="Conversation unavailable">{loadError}. Existing messages are preserved; retry when the connection recovers.</Banner>}{lifecycleError && <Banner tone="error" title="Action failed">{lifecycleError}</Banner>}+ <PersistentMindRuntimePanel runtime={runtime} error={runtimeError} loading={runtimeLoading} onOpenContext={() => changeView('context')} />+{activeView === 'setup' && (<section aria-labelledby="mind-profile-heading" className="rounded border border-port-border bg-port-card p-4"><div className="mb-3">diff --git a/client/src/components/cos/tabs/MindTab.test.jsx b/client/src/components/cos/tabs/MindTab.test.jsxindex 1973579bf8..b9874884ef 100644--- a/client/src/components/cos/tabs/MindTab.test.jsx+++ b/client/src/components/cos/tabs/MindTab.test.jsx@@ -17,6 +17,7 @@ const api = vi.hoisted(() => ({getProviders: vi.fn(),updateCosConfig: vi.fn(),getPersistentMindContext: vi.fn(),+ getPersistentMindRuntime: vi.fn(),createPersistentMindMemory: vi.fn(),updatePersistentMindMemory: vi.fn(),}));@@ -99,6 +100,21 @@ describe('MindTab', () => {rollups: [],harness: { type: 'api', label: 'Direct API', recommendation: 'recommended', detail: 'Structured and reliable.' },});+ api.getPersistentMindRuntime.mockResolvedValue({+ observedAt: '2026-08-27T12:00:00.000Z',+ inference: {+ active: false,+ providerId: 'demo',+ model: 'demo-model',+ residency: { status: 'provider-managed', backend: null, loaded: null, memoryBytes: null },+ },+ context: { chars: 19, maxChars: 32000, approximateTokens: 5, summaryState: 'empty', memoryCount: 0 },+ system: {+ memory: { total: 8 * 1024 ** 3, used: 4 * 1024 ** 3, free: 4 * 1024 ** 3, usagePercent: 50 },+ process: { rss: 256 * 1024 ** 2, heapUsed: 64 * 1024 ** 2, heapTotal: 128 * 1024 ** 2 },+ cpu: { cores: 8, loadAvg1m: 1.25 },+ },+ });api.createPersistentMindMemory.mockResolvedValue({ success: true });api.updatePersistentMindMemory.mockResolvedValue({ success: true });});@@ -250,6 +266,38 @@ describe('MindTab', () => {expect(screen.getByText('Here is the recommendation.')).toBeInTheDocument();});+ it('animates active thought status and shows context, system, and loaded-model telemetry', async () => {+ api.getPersistentMind.mockResolvedValue(response({+ state: { enabled: true, started: true, status: 'thinking', pauseReason: null, activeTurnId: 'mind-turn-1' },+ }));+ api.getPersistentMindRuntime.mockResolvedValue({+ observedAt: '2026-08-27T12:00:00.000Z',+ inference: {+ active: true,+ turnId: 'mind-turn-1',+ providerId: 'ollama',+ model: 'demo-model',+ residency: { status: 'loaded', backend: 'ollama', loaded: true, memoryBytes: 2 * 1024 ** 3 },+ },+ context: { chars: 12000, maxChars: 32000, approximateTokens: 3000, summaryState: 'ready', memoryCount: 4 },+ system: {+ memory: { total: 8 * 1024 ** 3, used: 4 * 1024 ** 3, free: 4 * 1024 ** 3, usagePercent: 50 },+ process: { rss: 256 * 1024 ** 2, heapUsed: 64 * 1024 ** 2, heapTotal: 128 * 1024 ** 2 },+ cpu: { cores: 8, loadAvg1m: 1.25 },+ },+ });+ renderTab();++ const thoughtStatus = await screen.findByRole('status');+ expect(thoughtStatus).toHaveTextContent('Thinking with demo-model');+ expect(thoughtStatus).toHaveAttribute('aria-busy', 'true');+ expect(thoughtStatus.querySelector('.animate-pulse')).toBeInTheDocument();+ expect(screen.getByText('~3,000 tokens')).toBeInTheDocument();+ expect(screen.getByText('4 GB / 8 GB')).toBeInTheDocument();+ expect(screen.getByText('Running now')).toBeInTheDocument();+ expect(screen.getByText(/ollama · 2 GB/)).toBeInTheDocument();+ });+it('loads the editable effective context from the URL-backed context view', async () => {renderTab('/cos/mind?view=context');expect(await screen.findByRole('heading', { name: 'Identity and operating prompt' })).toBeInTheDocument();diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 7b7cd82812..c4d0f6c440 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -41,7 +41,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiApps.js` | App CRUD + PM2 ops (start/stop/restart/logs) + local open actions (editor, Claude Code, folder, Xcode) + `getAppIssues` (open GitHub/GitLab issues for the Issues tab). || `apiWorkspaceContexts.js` | Per-project working-context save/restore (branch, shells, tasks). || `apiAccounts.js` | Platform accounts. |-| `apiAgents.js` | Running-agent process management, CoS run-event diagnostics, and persistent-mind conversation/lifecycle calls. |+| `apiAgents.js` | Running-agent process management, CoS run-event diagnostics, and persistent-mind conversation, lifecycle, context, and runtime-telemetry calls. || `apiCommands.js` | CLI command dispatch. || `apiDashboard.js` | Dashboard state. || `apiDatabase.js` | Database introspection. |diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.jsindex f031d30c68..b5bfaf5d9f 100644--- a/client/src/services/apiAgents.js+++ b/client/src/services/apiAgents.js@@ -66,6 +66,7 @@ export const repairRunRecords = (body = {}, options = {}) =>export const getPersistentMind = (filters = {}, options = {}) =>request(`/cos/mind${runEventQuery(filters)}`, options);export const getPersistentMindContext = (options = {}) => request('/cos/mind/context', options);+export const getPersistentMindRuntime = (options = {}) => request('/cos/mind/runtime', options);export const sendPersistentMindMessage = (body, options = {}) =>request('/cos/mind/messages', { method: 'POST', body: JSON.stringify(body), ...options });export const addPersistentMindAnnotation = (body, options = {}) =>diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.jsindex 6d8ed8fcbd..29ff3528f3 100644--- a/server/routes/cosMindRoutes.js+++ b/server/routes/cosMindRoutes.js@@ -27,6 +27,7 @@ import {} from '../services/persistentMindContext.js';import { getProviderById } from '../services/providers.js';import { persistentMindHarnessInfo } from '../services/persistentMindAdapter.js';+import { inspectPersistentMindRuntime } from '../services/persistentMindRuntime.js';import {enqueuePersistentMindMessage,getPersistentMindState,@@ -150,6 +151,15 @@ router.get('/mind/context', asyncHandler(async (_req, res) => {});}));+router.get('/mind/runtime', asyncHandler(async (_req, res) => {+ const [root, state] = await Promise.all([loadState(), getPersistentMindState()]);+ const prompt = normalizePersistentMindPrompt(root.config?.persistentMindPrompt);+ const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);+ const providerId = state.activeTurn?.providerId || profile.providerId;+ const provider = providerId ? await getProviderById(providerId) : null;+ res.json(await inspectPersistentMindRuntime({ state, profile, prompt, provider }));+}));+router.post('/mind/memories', asyncHandler(async (req, res) => {const input = validateRequest(memoryInputSchema, req.body);const memory = await createPersistentMindMemory(input);diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.jsindex 0d7c3b8f88..1cf4aa26fd 100644--- a/server/routes/cosMindRoutes.test.js+++ b/server/routes/cosMindRoutes.test.js@@ -21,6 +21,7 @@ const mocks = vi.hoisted(() => ({pausePersistentMind: vi.fn(),resumePersistentMind: vi.fn(),stopPersistentMind: vi.fn(),+ inspectPersistentMindRuntime: vi.fn(),}));vi.mock('../services/agentRunEventLog.js', () => ({@@ -54,6 +55,9 @@ vi.mock('../services/persistentMindSupervisor.js', () => ({resumePersistentMind: mocks.resumePersistentMind,stopPersistentMind: mocks.stopPersistentMind,}));+vi.mock('../services/persistentMindRuntime.js', () => ({+ inspectPersistentMindRuntime: mocks.inspectPersistentMindRuntime,+}));import cosMindRoutes from './cosMindRoutes.js';@@ -97,6 +101,17 @@ describe('persistent mind routes', () => {mocks.pausePersistentMind.mockResolvedValue({ success: true });mocks.resumePersistentMind.mockResolvedValue({ success: true });mocks.stopPersistentMind.mockResolvedValue({ success: true });+ mocks.inspectPersistentMindRuntime.mockResolvedValue({+ observedAt: '2026-08-27T12:00:00.000Z',+ inference: {+ active: false,+ providerId: 'demo',+ model: 'demo-model',+ residency: { status: 'provider-managed', backend: null, loaded: null },+ },+ context: { chars: 9, maxChars: 32000, approximateTokens: 3, summaryState: 'empty', memoryCount: 1 },+ system: { memory: { total: 100, used: 40, free: 60, usagePercent: 40 } },+ });});it('serves a bounded cursor snapshot with only the safe profile fields', async () => {@@ -134,6 +149,30 @@ describe('persistent mind routes', () => {}));});+ it('exposes live context, system, inference, and model-residency telemetry', async () => {+ mocks.getPersistentMindState.mockResolvedValue({+ enabled: true,+ started: true,+ status: 'thinking',+ activeTurn: { id: 'turn-1', providerId: 'ollama', model: 'active-model' },+ });+ mocks.getProviderById.mockResolvedValue({ id: 'ollama', type: 'api' });+ const res = await get('/mind/runtime');+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({+ inference: { active: false, providerId: 'demo', model: 'demo-model', residency: { status: 'provider-managed' } },+ context: { approximateTokens: 3, memoryCount: 1 },+ system: { memory: { usagePercent: 40 } },+ });+ expect(mocks.inspectPersistentMindRuntime).toHaveBeenCalledWith(expect.objectContaining({+ state: expect.objectContaining({ status: 'thinking' }),+ profile: expect.objectContaining({ providerId: 'demo', model: 'demo-model' }),+ prompt: expect.objectContaining({ identity: 'Resident mind' }),+ provider: expect.objectContaining({ id: 'ollama' }),+ }));+ expect(mocks.getProviderById).toHaveBeenCalledWith('ollama');+ });+it('creates and edits only validated persistent-mind memories', async () => {const created = await post('/mind/memories', { content: 'A new fact' });expect(created.status).toBe(201);diff --git a/server/services/persistentMindRuntime.js b/server/services/persistentMindRuntime.jsnew file mode 100644index 0000000000..ed31dd9382--- /dev/null+++ b/server/services/persistentMindRuntime.js@@ -0,0 +1,122 @@+/** Live, machine-local telemetry for the persistent Chief-of-Staff mind. */++import os from 'os';+import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';+import { getMemoryStats } from '../lib/memoryStats.js';+import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';+import { PERSISTENT_MIND_TRAJECTORY_LIMITS } from '../lib/persistentMindTrajectory.js';+import {+ getLastLoadedModelsError as getOllamaResidencyError,+ getLoadedModels as getLoadedOllamaModels,+} from './ollamaManager.js';+import {+ getLastLoadedModelsError as getLmStudioResidencyError,+ getLoadedModels as getLoadedLmStudioModels,+ modelIdsReferToSameRepo,+} from './lmStudioManager.js';+import { preparePersistentMindContext, readPersistentMindMemories } from './persistentMindContext.js';++const normalizeOllamaModel = (value) => String(value || '').trim().toLowerCase().replace(/:latest$/, '');++export function persistentMindLocalBackend(provider) {+ return localRuntimeForProvider(provider)?.kind || null;+}++export function persistentMindModelMatches(backend, configuredModel, residentModel) {+ const residentId = residentModel?.id || residentModel?.name;+ if (!configuredModel || !residentId) return false;+ if (backend === 'ollama') return normalizeOllamaModel(configuredModel) === normalizeOllamaModel(residentId);+ if (backend === 'lmstudio') return modelIdsReferToSameRepo(configuredModel, residentId);+ return String(configuredModel).trim() === String(residentId).trim();+}++async function inspectModelResidency(provider, model) {+ if (!provider || !model) {+ return { status: 'unconfigured', backend: null, loaded: null, memoryBytes: null, expiresAt: null };+ }+ const runtime = localRuntimeForProvider(provider);+ if (!runtime) {+ return { status: 'provider-managed', backend: null, loaded: null, memoryBytes: null, expiresAt: null };+ }+ const backend = runtime.kind;+ let models;+ let error;+ if (backend === 'ollama') {+ models = await getLoadedOllamaModels();+ error = getOllamaResidencyError();+ } else if (backend === 'lmstudio') {+ models = await getLoadedLmStudioModels(true);+ error = getLmStudioResidencyError();+ } else {+ const probe = await probeOpenAiModels(runtime.endpoint, { apiKey: provider.apiKey || '' });+ models = Array.isArray(probe.models) ? probe.models.map((id) => ({ id })) : [];+ error = Array.isArray(probe.models) ? null : probe.error || 'Local model residency could not be read';+ }+ if (error) {+ return { status: 'unknown', backend, loaded: null, memoryBytes: null, expiresAt: null };+ }+ const resident = models.find((candidate) => persistentMindModelMatches(backend, model, candidate));+ return {+ status: resident ? 'loaded' : 'not-loaded',+ backend,+ loaded: Boolean(resident),+ memoryBytes: resident && Number.isFinite(resident.sizeVram ?? resident.size)+ ? resident.sizeVram ?? resident.size+ : null,+ expiresAt: resident?.expiresAt || null,+ };+}++export async function inspectPersistentMindRuntime({ state, profile, prompt, provider } = {}) {+ const activeTurn = state?.activeTurn || null;+ const activeModel = activeTurn?.model || profile?.model;+ const [memories, memory, residency] = await Promise.all([+ readPersistentMindMemories(),+ getMemoryStats(),+ inspectModelResidency(provider, activeModel),+ ]);+ const context = await preparePersistentMindContext({+ identity: prompt?.identity || '',+ instructions: prompt?.instructions || '',+ memories,+ });+ const processMemory = process.memoryUsage();+ const totalMemory = Number(memory.total) || 0;+ const usedMemory = Number(memory.used) || 0;++ return {+ observedAt: new Date().toISOString(),+ inference: {+ active: Boolean(activeTurn),+ turnId: activeTurn?.id || null,+ startedAt: activeTurn?.startedAt || null,+ providerId: activeTurn?.providerId || profile?.providerId || null,+ model: activeTurn?.model || profile?.model || null,+ residency,+ },+ context: {+ chars: context.chars,+ maxChars: PERSISTENT_MIND_TRAJECTORY_LIMITS.maxContextChars,+ approximateTokens: context.approximateTokens,+ summaryState: context.summaryState,+ memoryCount: memories.length,+ },+ system: {+ memory: {+ total: totalMemory,+ used: usedMemory,+ free: Number(memory.free) || 0,+ usagePercent: totalMemory > 0 ? Math.round((usedMemory / totalMemory) * 100) : null,+ },+ process: {+ rss: processMemory.rss,+ heapUsed: processMemory.heapUsed,+ heapTotal: processMemory.heapTotal,+ },+ cpu: {+ cores: os.cpus().length,+ loadAvg1m: os.loadavg()[0],+ },+ },+ };+}diff --git a/server/services/persistentMindRuntime.test.js b/server/services/persistentMindRuntime.test.jsnew file mode 100644index 0000000000..8bfea8090d--- /dev/null+++ b/server/services/persistentMindRuntime.test.js@@ -0,0 +1,118 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ getMemoryStats: vi.fn(),+ getLoadedOllamaModels: vi.fn(),+ getOllamaResidencyError: vi.fn(),+ getLoadedLmStudioModels: vi.fn(),+ getLmStudioResidencyError: vi.fn(),+ probeOpenAiModels: vi.fn(),+ preparePersistentMindContext: vi.fn(),+ readPersistentMindMemories: vi.fn(),+}));++vi.mock('../lib/memoryStats.js', () => ({ getMemoryStats: mocks.getMemoryStats }));+vi.mock('../lib/openAiModelsProbe.js', () => ({ probeOpenAiModels: mocks.probeOpenAiModels }));+vi.mock('./ollamaManager.js', () => ({+ getLoadedModels: mocks.getLoadedOllamaModels,+ getLastLoadedModelsError: mocks.getOllamaResidencyError,+}));+vi.mock('./lmStudioManager.js', () => ({+ getLoadedModels: mocks.getLoadedLmStudioModels,+ getLastLoadedModelsError: mocks.getLmStudioResidencyError,+ modelIdsReferToSameRepo: (left, right) => String(left).split('/').pop().toLowerCase() === String(right).split('/').pop().toLowerCase(),+}));+vi.mock('./persistentMindContext.js', () => ({+ preparePersistentMindContext: mocks.preparePersistentMindContext,+ readPersistentMindMemories: mocks.readPersistentMindMemories,+}));++import {+ inspectPersistentMindRuntime,+ persistentMindLocalBackend,+ persistentMindModelMatches,+} from './persistentMindRuntime.js';++describe('persistent mind runtime telemetry', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.getMemoryStats.mockResolvedValue({ total: 1000, used: 400, free: 600 });+ mocks.getLoadedOllamaModels.mockResolvedValue([]);+ mocks.getLoadedLmStudioModels.mockResolvedValue([]);+ mocks.getOllamaResidencyError.mockReturnValue(null);+ mocks.getLmStudioResidencyError.mockReturnValue(null);+ mocks.probeOpenAiModels.mockResolvedValue({ reachable: true, models: [], error: null });+ mocks.readPersistentMindMemories.mockResolvedValue([{ id: 'memory-1' }]);+ mocks.preparePersistentMindContext.mockResolvedValue({ chars: 1200, approximateTokens: 300, summaryState: 'ready' });+ });++ it('only treats the configured local endpoints as directly observable backends', () => {+ expect(persistentMindLocalBackend({ id: 'ollama', endpoint: 'http://localhost:11434/v1' })).toBe('ollama');+ expect(persistentMindLocalBackend({ id: 'lmstudio', endpoint: 'http://localhost:1234/v1' })).toBe('lmstudio');+ expect(persistentMindLocalBackend({ command: 'opencode', llamaBacked: true, endpoint: 'http://localhost:5568/v1' })).toBe('llama');+ expect(persistentMindLocalBackend({ id: 'ollama', endpoint: 'http://example.com:11434/v1' })).toBeNull();+ expect(persistentMindLocalBackend({ id: 'codex' })).toBeNull();+ });++ it('reconciles Ollama latest tags and LM Studio repository ids', () => {+ expect(persistentMindModelMatches('ollama', 'Qwen3:latest', { id: 'qwen3' })).toBe(true);+ expect(persistentMindModelMatches('lmstudio', 'publisher/example-model', { id: 'other/example-model' })).toBe(true);+ expect(persistentMindModelMatches('ollama', 'qwen3', { id: 'other-model' })).toBe(false);+ });++ it('reports active inference, exact context size, memory usage, and local model residency', async () => {+ mocks.getLoadedOllamaModels.mockResolvedValue([{+ id: 'QWEN3', sizeVram: 200, expiresAt: '2026-08-27T13:00:00.000Z',+ }]);+ const runtime = await inspectPersistentMindRuntime({+ state: { activeTurn: { id: 'turn-1', startedAt: '2026-08-27T12:00:00.000Z', providerId: 'ollama', model: 'qwen3' } },+ profile: { providerId: 'ollama', model: 'configured-model' },+ prompt: { identity: 'Resident mind', instructions: 'Stay grounded.' },+ provider: { id: 'ollama', endpoint: 'http://localhost:11434/v1' },+ });++ expect(runtime).toMatchObject({+ inference: {+ active: true,+ turnId: 'turn-1',+ providerId: 'ollama',+ model: 'qwen3',+ residency: { status: 'loaded', backend: 'ollama', loaded: true, memoryBytes: 200 },+ },+ context: { chars: 1200, maxChars: 32000, approximateTokens: 300, summaryState: 'ready', memoryCount: 1 },+ system: { memory: { total: 1000, used: 400, free: 600, usagePercent: 40 } },+ });+ expect(mocks.preparePersistentMindContext).toHaveBeenCalledWith({+ identity: 'Resident mind', instructions: 'Stay grounded.', memories: [{ id: 'memory-1' }],+ });+ });++ it('does not misreport a failed local residency probe as an unloaded model', async () => {+ mocks.getOllamaResidencyError.mockReturnValue('Ollama unavailable');+ const runtime = await inspectPersistentMindRuntime({+ state: { activeTurn: null },+ profile: { providerId: 'ollama', model: 'qwen3' },+ prompt: {},+ provider: { id: 'ollama', endpoint: 'http://localhost:11434/v1' },+ });+ expect(runtime.inference.residency).toMatchObject({ status: 'unknown', loaded: null });+ });++ it('reports model residency for other local OpenAI-compatible runtimes', async () => {+ mocks.probeOpenAiModels.mockResolvedValue({ reachable: true, models: ['dflash'], error: null });+ const runtime = await inspectPersistentMindRuntime({+ state: { activeTurn: null },+ profile: { providerId: 'opencode-llama', model: 'dflash' },+ prompt: {},+ provider: {+ id: 'opencode-llama',+ command: 'opencode',+ llamaBacked: true,+ endpoint: 'http://localhost:5568/v1',+ },+ });++ expect(mocks.probeOpenAiModels).toHaveBeenCalledWith('http://localhost:5568/v1', { apiKey: '' });+ expect(runtime.inference.residency).toMatchObject({ status: 'loaded', backend: 'llama', loaded: true });+ });+});