Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: share model and provider status observations across viewers (#8668)

[._.]/ Adam Eivyc0a2c6042ed1
diff --git a/client/src/components/settings/MemoryManagement.jsx b/client/src/components/settings/MemoryManagement.jsx
index 1d21fef98b..5dab2f65d4 100644
--- a/client/src/components/settings/MemoryManagement.jsx
+++ b/client/src/components/settings/MemoryManagement.jsx
@@ -13,20 +13,15 @@
// - Piper TTS — spawned per-synthesis, no persistent process
// - Browser / Codex / Claude Code workers — managed elsewhere, not memory-pressure relevant
//
-// Polls every 5s while mounted. The component owns the toast layer via
-// useAsyncAction (for explicit user actions) and the per-call `.catch()`
-// fallbacks in `refresh()` (for poll failures, which must NOT toast — the
-// panel would otherwise spam an error toast every 5s during a transient
-// Ollama outage). Every API helper is called with `{ silent: true }` so
-// apiCore's default toast doesn't fire underneath; per the AGENTS.md
-// "Silent vs. toasting API requests" rule, custom catch ⇒ silent: true.
+// Shared server samples drive updates; explicit actions own their toast layer.
import { useState, 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 { useAutoRefetch } from '../../hooks/useAutoRefetch.js';
+import { useSocketResource } from '../../hooks/useSocketResource.js';
+import { useSocketSubscription } from '../../hooks/useSocketSubscription.js';
import useMounted from '../../hooks/useMounted.js';
import { formatBytes } from '../../utils/formatters';
import {
@@ -38,7 +33,7 @@ import { getTtsStatus, unloadKokoroTts, controlWhisper, getVoiceStatus } from '.
const SILENT = { silent: true };
-const POLL_MS = 5000;
+const MEMORY_EVENTS = ['loaded-models:changed', 'voice-readiness:changed'];
const EMPTY_SNAPSHOT = {
loadedOllama: [],
@@ -86,7 +81,7 @@ export default function MemoryManagement({ onLoadedModelsChange } = {}) {
// (so "Free everything" still skips their unknown residency) but are excluded
// from the "Status unavailable" banner — the nag the user opted out of.
const [disabledSources, setDisabledSources] = useState([]);
- // Guards the polled setState calls — a late /voice/status response that
+ // Guards asynchronous 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
@@ -99,21 +94,21 @@ export default function MemoryManagement({ onLoadedModelsChange } = {}) {
// 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.
+ // the prior snapshot.
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
+ // let a socket event start a newer read 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),
+ getLoadedLlmModels(priority ? { ...SILENT, fresh: true } : SILENT),
getTtsStatus(SILENT),
getVoiceStatus(SILENT),
]);
- // A later-started poll/action refresh owns the UI. Return its current
+ // A later-started event/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) {
@@ -129,7 +124,7 @@ export default function MemoryManagement({ onLoadedModelsChange } = {}) {
const ttsValid = typeof tts?.kokoro?.state === 'string';
const voiceValid = voice != null && typeof voice === 'object';
const llmSourceErrors = llmValid && Array.isArray(llm.sourceErrors) ? llm.sourceErrors : [];
- // Distinguish "field absent" from "present-but-empty" so a later failed poll
+ // Distinguish "field absent" from "present-but-empty" so a later failed read
// keeps the last-known disabled backends (the outage is the very scenario
// the banner suppression exists for) while an explicit [] clears them.
const llmDisabledSources = Array.isArray(llm?.disabled) ? llm.disabled : previous.disabledSources;
@@ -145,7 +140,7 @@ export default function MemoryManagement({ onLoadedModelsChange } = {}) {
// 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.
+ // button briefly hides, which the next observation corrects.
whisperRunning: voiceValid ? Boolean(voice.services?.whisper?.ok) : previous.whisperRunning,
sttEngine: voiceValid ? (voice.sttEngine || 'whisper') : previous.sttEngine,
unavailableSources: [...new Set(failedSources)],
@@ -171,7 +166,8 @@ export default function MemoryManagement({ onLoadedModelsChange } = {}) {
return snapshot;
}, [mountedRef, onLoadedModelsChange]);
- useAutoRefetch(refresh, POLL_MS, { pollOnly: true });
+ useSocketSubscription('voice-readiness');
+ useSocketResource(refresh, { namespace: 'loaded-models', events: MEMORY_EVENTS });
const [unloadModel, unloadingModel] = useAsyncAction(async (modelId) => {
await unloadOllamaModel(modelId, SILENT);
@@ -199,8 +195,8 @@ export default function MemoryManagement({ onLoadedModelsChange } = {}) {
await refresh();
});
const [freeAll, freeingAll] = useAsyncAction(async () => {
- // Re-poll first — the optimistic UI's `loadedOllama` snapshot is up to
- // POLL_MS old, and the ollama unload now requires the model to actually
+ // Re-read first — the optimistic UI's `loadedOllama` snapshot is up to
+ // one observation old, and the ollama unload now requires the model to actually
// be resident (else returns `not loaded`). Read from the returned
// snapshot rather than component state — React's async setState in
// refresh() won't have flushed by the time `loadedOllama` etc. is
diff --git a/client/src/components/settings/MemoryManagement.test.jsx b/client/src/components/settings/MemoryManagement.test.jsx
index aa47d19734..c570e88afd 100644
--- a/client/src/components/settings/MemoryManagement.test.jsx
+++ b/client/src/components/settings/MemoryManagement.test.jsx
@@ -1,3 +1,6 @@
+import socket from '../../services/socket';
+vi.mock('../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));
+const socketEvent = event => { for (const [name, handler] of socket.on.mock.calls) if (name === event) handler({}); };
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
@@ -85,6 +88,20 @@ describe('MemoryManagement', () => {
expect(screen.getByText('newer-model')).toBeInTheDocument();
});
+ it('does not let a pre-unload socket read resurrect the model', async () => {
+ render(<MemoryManagement />);
+ expect(await screen.findByText('example/lmstudio-model')).toBeInTheDocument();
+ let resolveOld;
+ getLoadedLlmModels.mockImplementationOnce(() => new Promise(resolve => { resolveOld = resolve; }));
+ act(() => socketEvent('loaded-models:changed'));
+ await waitFor(() => expect(resolveOld).toBeTypeOf('function'));
+ getLoadedLlmModels.mockResolvedValue({ ollama: [], lmstudio: [] });
+ fireEvent.click(screen.getByRole('button', { name: 'Unload example/lmstudio-model' }));
+ await waitFor(() => expect(screen.queryByText('example/lmstudio-model')).not.toBeInTheDocument());
+ await act(async () => resolveOld({ ollama: [], lmstudio: [{ id: 'example/lmstudio-model' }] }));
+ expect(screen.queryByText('example/lmstudio-model')).not.toBeInTheDocument();
+ });
+
it('hides the unavailability banner for a user-disabled backend', async () => {
// A backend the user marked disabled opts out of the availability nag. Its
// failed residency still lands in unavailableSources (the "Free everything"
@@ -110,29 +127,33 @@ describe('MemoryManagement', () => {
expect(screen.queryByText(/full unified memory is available/i)).not.toBeInTheDocument();
});
- // #5697 — this poll used to be a raw `useEffect` + `setInterval`, so it kept
- // probing the local LLM / TTS / voice status endpoints every 5s from a tab
- // nobody was looking at. It is the unconditional (always-`enabled`) half of
- // the migration; MediaJobsQueue covers the gated half.
- describe('hidden-tab polling', () => {
+ describe('socket reconciliation', () => {
beforeEach(() => { vi.useFakeTimers(); });
afterEach(() => { vi.useRealTimers(); });
- it('pauses the residency poll while the tab is hidden and re-fires on return', async () => {
+ it('updates on events, reconnect and tab show without any timer-driven fetch', async () => {
render(<MemoryManagement />);
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
expect(getLoadedLlmModels).toHaveBeenCalledTimes(1);
- const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');
await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
expect(getLoadedLlmModels).toHaveBeenCalledTimes(1);
+ getLoadedLlmModels.mockResolvedValue({ ollama: [], lmstudio: [{ id: 'event-model' }] });
+ await act(async () => { socketEvent('loaded-models:changed'); });
+ expect(screen.getByText('event-model')).toBeInTheDocument();
+ await act(async () => { socketEvent('connect'); });
+ expect(getLoadedLlmModels).toHaveBeenCalledTimes(3);
+ const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');
+ act(() => document.dispatchEvent(new Event('visibilitychange')));
+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
+ expect(getLoadedLlmModels).toHaveBeenCalledTimes(3);
visibility.mockReturnValue('visible');
await act(async () => {
document.dispatchEvent(new Event('visibilitychange'));
await vi.advanceTimersByTimeAsync(0);
});
- expect(getLoadedLlmModels).toHaveBeenCalledTimes(2);
+ expect(getLoadedLlmModels).toHaveBeenCalledTimes(4);
visibility.mockRestore();
});
});
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index e1848cc721..6c504e9f2f 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback, useMemo } from 'react';
+import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { Link, useLocation, useNavigate, useParams } from 'react-router';
import { Bot, Cpu, Gauge, Network, Package, Plus } from 'lucide-react';
import toast from '../components/ui/Toast';
@@ -12,7 +12,8 @@ import { copyToClipboard } from '../lib/clipboard';
import { formatCount } from '../utils/formatters';
import { isHttpsUrl } from '../utils/urlNormalize';
import useLocalModels from '../hooks/useLocalModels';
-import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import useMounted from '../hooks/useMounted.js';
+import { useSocketResource } from '../hooks/useSocketResource';
import EmptyState from '../components/EmptyState';
import Banner from '../components/ui/Banner';
import ModelsTabsHeader, { ModelsSectionLayout } from '../components/models/ModelsTabsHeader';
@@ -35,6 +36,10 @@ import ProviderCompatibilityMatrix from '../components/providers/ProviderCompati
import ProviderComposePopover from '../components/providers/ProviderComposePopover';
import DefaultProviderHelper from '../components/providers/DefaultProviderHelper';
+const STATUS_EVENTS = ['provider-status:changed'];
+const READINESS_EVENTS = ['provider-readiness:changed'];
+const ACCOUNT_EVENTS = ['codex-account:changed'];
+
// The two local apps an API provider can front. Their installer lives on the
// Models → LLMs page (it starts the service too), so the provider card
// links there instead of offering an install of its own.
@@ -116,6 +121,9 @@ export default function AIProviders() {
[sampleProviders],
);
const hasCodexSubscriptionProvider = providers.some(isCodexSubscriptionProvider);
+ const [observationUnavailable, setObservationUnavailable] = useState({});
+ const observationRevision = useRef({ account: 0, readiness: 0, status: 0 });
+ const observationMounted = useMounted();
const mergeCodexCatalog = useCallback((catalog) => {
if (!Array.isArray(catalog)) return;
@@ -145,8 +153,10 @@ export default function AIProviders() {
// normal client library always has this function; the guard makes a mixed
// client/server upgrade leave the established provider controls intact.
if (typeof api.getCodexAccount !== 'function') return undefined;
+ const revision = ++observationRevision.current.account;
setCodexAccountLoading(true);
const result = await api.getCodexAccount({ fresh, silent: true }).catch(() => null);
+ if (!observationMounted.current || revision !== observationRevision.current.account) return;
const readiness = result?.readiness && typeof result.readiness === 'object' ? result.readiness : null;
setCodexAccount(readiness);
setCodexAccountLoading(false);
@@ -155,8 +165,7 @@ export default function AIProviders() {
}, [loadCodexModels]);
useEffect(() => {
- if (hasCodexSubscriptionProvider) loadCodexAccount();
- else {
+ if (!hasCodexSubscriptionProvider) {
setCodexAccount(undefined);
setCodexModels(null);
}
@@ -271,6 +280,7 @@ export default function AIProviders() {
setLoading(providers.length === 0);
setLoadError(false);
let providersFailed = false;
+ const statusRevision = ++observationRevision.current.status;
const [providersData, appsData, statusData, orchestrationProfilesData] = await Promise.all([
api.getProviders({ fresh: true }).catch(() => {
providersFailed = true;
@@ -295,7 +305,7 @@ export default function AIProviders() {
: null);
}
setApps(appsData);
- setStatuses(statusData.providers || {});
+ if (statusRevision === observationRevision.current.status) setStatuses(statusData.providers || {});
const profList = Array.isArray(orchestrationProfilesData)
? orchestrationProfilesData
: orchestrationProfilesData?.profiles || [];
@@ -307,29 +317,36 @@ export default function AIProviders() {
// when a provider fails elsewhere and clears itself once its recovery window
// passes (the server expires `estimatedRecovery` on read), without a full reload.
const refreshStatuses = useCallback(async () => {
- const statusData = await api.getProviderStatuses().catch(() => null);
+ const revision = ++observationRevision.current.status;
+ const statusData = await api.getProviderStatuses({ silent: true }).catch(() => null);
+ if (!observationMounted.current || revision !== observationRevision.current.status) return;
+ setObservationUnavailable(previous => ({ ...previous, status: !statusData?.providers }));
if (statusData?.providers) setStatuses(statusData.providers);
}, []);
// Local-daemon readiness (is llama-server / Ollama actually up and serving the
// model this provider names?). Off the critical path like the runtime probes,
- // and re-polled on the same cadence as the status map so starting a daemon
+ // and reconciled from the shared observer so starting a daemon
// from the Models → Runtimes page clears the card's checklist on its own.
const loadReadiness = useCallback(async () => {
+ const revision = ++observationRevision.current.readiness;
const data = await api.getProviderReadiness({ silent: true }).catch(() => null);
- setReadiness(data?.readiness && typeof data.readiness === 'object' ? data.readiness : {});
+ if (!observationMounted.current || revision !== observationRevision.current.readiness) return;
+ const valid = data?.readiness && typeof data.readiness === 'object';
+ setObservationUnavailable(previous => ({ ...previous, readiness: !valid }));
+ if (valid) setReadiness(data.readiness);
}, []);
- // `useAutoRefetch` rather than a raw interval so both polls pause while the
- // tab is hidden — a readiness tick costs one HTTP probe per distinct local
- // endpoint, which a backgrounded settings tab should not keep spending.
- const pollCards = useCallback(() => Promise.all([
- refreshStatuses(),
- loadReadiness(),
- hasCodexSubscriptionProvider ? loadCodexAccount() : Promise.resolve(),
- ]), [refreshStatuses, loadReadiness, hasCodexSubscriptionProvider, loadCodexAccount]);
- // The Harnesses view renders none of what the poll refreshes, so it pauses there.
- useAutoRefetch(pollCards, 20000, { pollOnly: true, enabled: activeTab !== 'harnesses' });
+ useSocketResource(refreshStatuses, {
+ namespace: 'provider-status', events: STATUS_EVENTS, enabled: activeTab !== 'harnesses',
+ });
+ useSocketResource(loadReadiness, {
+ namespace: 'provider-readiness', events: READINESS_EVENTS, enabled: activeTab !== 'harnesses',
+ });
+ useSocketResource(() => loadCodexAccount(), {
+ namespace: 'codex-account', events: ACCOUNT_EVENTS,
+ enabled: activeTab !== 'harnesses' && hasCodexSubscriptionProvider,
+ });
// Clear a provider's bench (runtime unavailability) so the next call retries it.
// Note: if the underlying cause persists (e.g. an invalid model id), the very
@@ -338,6 +355,7 @@ export default function AIProviders() {
setRecovering(prev => ({ ...prev, [id]: true }));
const result = await api.recoverProvider(id, { silent: true }).catch(() => null);
if (result) {
+ observationRevision.current.status += 1;
setStatuses(prev => ({ ...prev, [id]: { ...prev[id], available: true, reason: 'ok', message: 'Provider available', timeUntilRecovery: null } }));
toast.success('Provider marked available — it will be retried on the next call');
} else {
@@ -411,6 +429,7 @@ export default function AIProviders() {
authUrl: isHttpsUrl(result.login.authUrl) ? result.login.authUrl : null,
verificationUrl: isHttpsUrl(result.login.verificationUrl) ? result.login.verificationUrl : null,
};
+ observationRevision.current.account += 1;
setCodexAccount((current) => ({
...(current && typeof current === 'object' ? current : {}),
status: 'login-pending',
@@ -427,6 +446,7 @@ export default function AIProviders() {
toast.error('Could not cancel ChatGPT sign-in');
return;
}
+ observationRevision.current.account += 1;
setCodexAccount(result.readiness);
};
@@ -438,6 +458,7 @@ export default function AIProviders() {
toast.error('Could not log out of ChatGPT');
return;
}
+ observationRevision.current.account += 1;
setCodexAccount(result.readiness);
toast.success('ChatGPT subscription signed out');
};
@@ -498,7 +519,7 @@ export default function AIProviders() {
// `prerequisitesMet`, the codex account) and un-group a unified card. The
// model and catalog fields fan out to every mode in the group server-side
// (`sharedModeUpdates`), so they are applied to the siblings here too rather
- // than leaving them showing the pre-refresh catalog until the next poll.
+ // than leaving them showing the pre-refresh catalog until the next observation.
// `modelCatalog` is the unscoped full list when model access hides entries;
// the editor saves from it, so it must move with each refresh.
// `modelContextWindows` is copied even when absent — a refresh that pruned it
@@ -636,7 +657,7 @@ export default function AIProviders() {
};
// A daemon was just installed/started. Only the readiness checklist changed —
- // re-poll it so the card's banner collapses to the "ready" pill on its own.
+ // re-read it so the card's banner collapses to the "ready" pill on its own.
const handleRuntimeSetupComplete = () => {
toast.success(`${settingUpRuntime?.label || 'Local runtime'} is set up`);
loadReadiness();
@@ -670,7 +691,7 @@ export default function AIProviders() {
// its readiness (runtime install state + credentials + the runtime bench,
// folded into the state that drives the card's color, its badge and its
// section), and the id lookup the cards use for fallback/sibling references.
- // Memoized because this page re-renders on the 20s status poll and on every
+ // Memoized because this page re-renders on status events and on every
// keystroke in the ad-hoc runner's prompt box.
const { providersById, runtimeByProviderId, cardStateByProviderId, presetSections } = useMemo(() => {
const byId = Object.fromEntries(providers.map(p => [p.id, p]));
@@ -824,6 +845,9 @@ export default function AIProviders() {
<PageHeader icon={Bot} title="AI Providers" actions={headerActions} />
<ModelsTabsHeader activeTab="providers" />
+ {activeTab !== 'harnesses' && Object.values(observationUnavailable).some(Boolean) && (
+ <Banner variant="warning">Provider readiness status unavailable. Showing the last known state.</Banner>
+ )}
<div className="px-4 pt-3">
<ProviderPageTabs activeTab={activeTab} />
</div>
diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsx
index 3aa282bc54..e7c3f2ea40 100644
--- a/client/src/pages/AIProviders.test.jsx
+++ b/client/src/pages/AIProviders.test.jsx
@@ -1,3 +1,5 @@
+import socket from '../services/socket';
+const socketEvent = event => { for (const [name, handler] of socket.on.mock.calls) if (name === event) handler({}); };
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { act, render, screen, fireEvent, waitFor, within } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router';
@@ -66,6 +68,7 @@ vi.mock('../services/socket', () => ({
default: {
on: vi.fn(),
off: vi.fn(),
+ emit: vi.fn(),
},
}));
vi.mock('../hooks/useLocalModels', () => ({
@@ -2373,3 +2376,38 @@ describe('default provider helper and card highlight', () => {
expect(scrollSpy).toHaveBeenCalled();
});
});
+
+
+it('shares readiness subscriptions and reconciles events, reconnect and tab show without polling', async () => {
+ vi.clearAllMocks();
+ api.getProviders.mockResolvedValue({ providers: [], activeProvider: null });
+ api.getApps.mockResolvedValue([]);
+ api.getProviderStatuses.mockResolvedValue({ providers: {} });
+ api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });
+ api.getProviderReadiness.mockResolvedValue({ readiness: {} });
+
+ await renderPage();
+ vi.useFakeTimers();
+ const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');
+ try {
+ const count = api.getProviderReadiness.mock.calls.length;
+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
+ expect(api.getProviderReadiness).toHaveBeenCalledTimes(count);
+ api.getProviderReadiness.mockRejectedValueOnce(new Error('unavailable'));
+ await act(async () => { socketEvent('provider-readiness:changed'); });
+ expect(screen.getByText(/Provider readiness status unavailable/)).toBeInTheDocument();
+ expect(api.getProviderReadiness).toHaveBeenCalledTimes(count + 1);
+ await act(async () => { socketEvent('connect'); });
+ expect(api.getProviderReadiness).toHaveBeenCalledTimes(count + 2);
+ expect(screen.queryByText(/Provider readiness status unavailable/)).not.toBeInTheDocument();
+ visibility.mockReturnValue('hidden');
+ act(() => document.dispatchEvent(new Event('visibilitychange')));
+ visibility.mockReturnValue('visible');
+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));
+ expect(api.getProviderReadiness).toHaveBeenCalledTimes(count + 3);
+ expect(socket.emit).toHaveBeenCalledWith('provider-readiness:subscribe');
+ } finally {
+ visibility.mockRestore();
+ vi.useRealTimers();
+ }
+});
diff --git a/client/src/pages/LocalLlmPlayground.jsx b/client/src/pages/LocalLlmPlayground.jsx
index af6746171c..40c17ab68e 100644
--- a/client/src/pages/LocalLlmPlayground.jsx
+++ b/client/src/pages/LocalLlmPlayground.jsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { useAutoRefetch } from '../hooks/useAutoRefetch.js';
+import { useSocketResource } from '../hooks/useSocketResource.js';
import useMounted from '../hooks/useMounted';
import { Link, useSearchParams } from 'react-router';
import { ArrowLeft, ArrowRightLeft, Brain, Check, ChevronDown, Clock, Copy, Cpu, Gauge, MessageSquare, Play, RefreshCw, Send, TriangleAlert, X } from 'lucide-react';
@@ -15,6 +15,8 @@ import { filterHardwareCompatibleModels } from '../utils/systemCapabilities';
import { compareLocalLlmModels, getLoadedLlmModels, getLocalLlmCatalog, getLocalLlmStatus, streamLocalLlmTest } from '../services/api';
import { getNavPageForPath } from '../../../server/lib/navManifest.js';
+const LOADED_EVENTS = ['loaded-models:changed'];
+
const BACKEND_LABEL = { ollama: 'Ollama', lmstudio: 'LM Studio' };
const DEFAULT_PROMPT = 'Write a short, vivid paragraph about a lighthouse computer waking up at dawn.';
// Single source for the timeout choices so the collapsed Advanced-options
@@ -238,9 +240,9 @@ export default function LocalLlmPlayground() {
const [loadingStatus, setLoadingStatus] = useState(true);
const [modelLoadError, setModelLoadError] = useState('');
// Ollama models currently resident in VRAM/unified memory (from `/api/ps`),
- // polled so the sidebar can flag which models are warm — and which one is
+ // observed so the sidebar can flag which models are warm — and which one is
// actively serving the in-flight run.
- const [loadedModels, setLoadedModels] = useState([]);
+
const [selectedTargets, setSelectedTargets] = useState(() => parseTargetsParam(searchParams));
const [activeMode, setActiveMode] = useState(() => searchParams.get('mode') === 'compare' ? 'compare' : 'chat');
const [runMode, setRunMode] = useState('round-robin');
@@ -313,15 +315,12 @@ export default function LocalLlmPlayground() {
useEffect(() => { loadStatus(); }, [loadStatus]);
- const refreshLoaded = useCallback(() => {
- return getLoadedLlmModels({ silent: true })
- .then((res) => { if (mountedRef.current) setLoadedModels(res?.ollama || []); })
- .catch(() => { if (mountedRef.current) setLoadedModels([]); });
- }, []);
-
- // Poll which models are warm in memory. A faster cadence while a run is busy
- // so the "serving" flag and freed-slot countdown stay live; relaxed when idle.
- useAutoRefetch(refreshLoaded, busy ? 2000 : 6000, { pollOnly: true });
+ const loadedResource = useSocketResource(
+ () => getLoadedLlmModels({ silent: true }),
+ { namespace: 'loaded-models', events: LOADED_EVENTS },
+ );
+ const loadedModels = loadedResource.data?.ollama || [];
+ const loadedUnknown = loadedResource.error || loadedResource.data?.sourceErrors?.includes('ollama');
const installedTargets = useMemo(() => {
const models = [];
@@ -349,12 +348,12 @@ export default function LocalLlmPlayground() {
// shared `normalizeCatalogId` reconciles `:latest` and casing on both sides.
const loadedByKey = useMemo(() => {
const map = new Map();
- for (const m of loadedModels) {
+ for (const m of loadedUnknown ? [] : loadedModels) {
const key = normalizeCatalogId('ollama', m.id || m.name);
if (key) map.set(key, m);
}
return map;
- }, [loadedModels]);
+ }, [loadedModels, loadedUnknown]);
useEffect(() => {
if (loadingStatus || status == null) return;
@@ -519,13 +518,14 @@ export default function LocalLlmPlayground() {
<h1 className="text-lg md:text-2xl font-bold text-white truncate">Local LLM Playground</h1>
<p className="text-xs md:text-sm text-gray-500 truncate">
{selectedTargets.length} model{selectedTargets.length === 1 ? '' : 's'} selected
- {loadedModels.length > 0 && (
+ {loadedUnknown && <span className="text-port-warning"> · Memory status unavailable</span>}
+ {!loadedUnknown && loadedModels.length > 0 && (
<span className="text-port-success"> · {loadedModels.length} in memory</span>
)}
</p>
</div>
</div>
- <button onClick={() => { loadStatus(); refreshLoaded(); }} disabled={loadingStatus} className="p-2 text-gray-400 hover:text-white transition-colors" title="Refresh models" aria-label="Refresh models">
+ <button onClick={() => { loadStatus(); loadedResource.refetch(); }} disabled={loadingStatus} className="p-2 text-gray-400 hover:text-white transition-colors" title="Refresh models" aria-label="Refresh models">
<RefreshCw size={16} className={loadingStatus ? 'animate-spin' : ''} />
</button>
</div>
diff --git a/client/src/pages/LocalLlmPlayground.test.jsx b/client/src/pages/LocalLlmPlayground.test.jsx
index 23a3b4f30c..0308de357e 100644
--- a/client/src/pages/LocalLlmPlayground.test.jsx
+++ b/client/src/pages/LocalLlmPlayground.test.jsx
@@ -1,3 +1,6 @@
+import socket from '../services/socket';
+vi.mock('../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));
+const socketEvent = event => { for (const [name, handler] of socket.on.mock.calls) if (name === event) handler({}); };
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor, fireEvent, act } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
@@ -274,3 +277,33 @@ describe('LocalLlmPlayground', () => {
await act(async () => { releaseRun(); });
});
});
+
+
+it('reconciles loaded models on events, reconnect and tab show without polling', async () => {
+ vi.useFakeTimers();
+ const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');
+ try {
+ const view = renderPlayground();
+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });
+ expect(getLoadedLlmModels).toHaveBeenCalledTimes(1);
+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
+ expect(getLoadedLlmModels).toHaveBeenCalledTimes(1);
+ getLoadedLlmModels.mockResolvedValue({ ollama: [{ id: 'command-r-plus:104b' }] });
+ await act(async () => { socketEvent('loaded-models:changed'); });
+ expect(screen.getByText(/1 in memory/)).toBeInTheDocument();
+ getLoadedLlmModels.mockRejectedValueOnce(new Error('unavailable'));
+ await act(async () => { socketEvent('connect'); });
+ expect(screen.getByText(/Memory status unavailable/)).toBeInTheDocument();
+ visibility.mockReturnValue('hidden');
+ act(() => document.dispatchEvent(new Event('visibilitychange')));
+ visibility.mockReturnValue('visible');
+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));
+ expect(screen.queryByText(/Memory status unavailable/)).not.toBeInTheDocument();
+ expect(getLoadedLlmModels).toHaveBeenCalledTimes(4);
+ view.unmount();
+ expect(socket.emit).toHaveBeenCalledWith('loaded-models:unsubscribe');
+ } finally {
+ visibility.mockRestore();
+ vi.useRealTimers();
+ }
+});
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index cc3451daa2..9636caf140 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -261,9 +261,9 @@ export const migrateLocalLlmBackend = (to, mode = 'link') =>
// Used by the Memory Management panel to show what's eating space before
// kicking off a big diffusion render. `options` lets the panel pass
// `{ silent: true }` so its own catch handler / useAsyncAction wrapper
-// owns the toast — without it apiCore double-toasts on every 5s poll.
-export const getLoadedLlmModels = (options) =>
- request('/local-llm/loaded', options);
+// owns the toast when a status read fails.
+export const getLoadedLlmModels = ({ fresh = false, ...options } = {}) =>
+ request(`/local-llm/loaded${fresh ? '?fresh=1' : ''}`, options);
// Force a local backend to evict a model immediately.
export const unloadOllamaModel = (modelId, options) =>
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index ec952816b5..c52b6f7952 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -207,6 +207,81 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({
summary: 'Release browser observation; the last subscriber stops the observer.',
payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
},
+ 'loaded-models:subscribe': {
+ direction: 'client-to-server',
+ summary: 'Start shared observation while a viewer is mounted.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'loaded-models:unsubscribe': {
+ direction: 'client-to-server',
+ summary: 'Release observation; the last viewer stops sampling.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'loaded-models:changed': {
+ direction: 'server-to-client',
+ summary: 'Shared sample changed or failed; reconcile through the existing status endpoint.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'voice-readiness:subscribe': {
+ direction: 'client-to-server',
+ summary: 'Start shared observation while a viewer is mounted.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'voice-readiness:unsubscribe': {
+ direction: 'client-to-server',
+ summary: 'Release observation; the last viewer stops sampling.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'voice-readiness:changed': {
+ direction: 'server-to-client',
+ summary: 'Shared sample changed or failed; reconcile through the existing status endpoint.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'provider-readiness:subscribe': {
+ direction: 'client-to-server',
+ summary: 'Start shared observation while a viewer is mounted.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'provider-readiness:unsubscribe': {
+ direction: 'client-to-server',
+ summary: 'Release observation; the last viewer stops sampling.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'provider-readiness:changed': {
+ direction: 'server-to-client',
+ summary: 'Shared sample changed or failed; reconcile through the existing status endpoint.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'provider-status:subscribe': {
+ direction: 'client-to-server',
+ summary: 'Start shared observation while a viewer is mounted.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'provider-status:unsubscribe': {
+ direction: 'client-to-server',
+ summary: 'Release observation; the last viewer stops sampling.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'provider-status:changed': {
+ direction: 'server-to-client',
+ summary: 'Shared sample changed or failed; reconcile through the existing status endpoint.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'codex-account:subscribe': {
+ direction: 'client-to-server',
+ summary: 'Start shared observation while a viewer is mounted.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'codex-account:unsubscribe': {
+ direction: 'client-to-server',
+ summary: 'Release observation; the last viewer stops sampling.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'codex-account:changed': {
+ direction: 'server-to-client',
+ summary: 'Shared sample changed or failed; reconcile through the existing status endpoint.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
'readiness:subscribe': {
direction: 'client-to-server',
summary: 'Observe health and capability readiness while a view is mounted.',
diff --git a/server/routes/lmstudio.js b/server/routes/lmstudio.js
index 67d5ca224f..596796cb5d 100644
--- a/server/routes/lmstudio.js
+++ b/server/routes/lmstudio.js
@@ -1,3 +1,4 @@
+import { observeModelMutations } from '../services/modelObservation.js';
/**
* LM Studio Routes
*
@@ -19,6 +20,7 @@ import {
} from '../lib/validation.js'
const router = Router()
+router.use(observeModelMutations('loaded-models', 'provider-readiness'));
/**
* GET /api/lmstudio/status
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index 4773fcf435..808b85aaa2 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -1,3 +1,4 @@
+import { observeModelResource, observeModelMutations } from '../services/modelObservation.js';
/**
* Local LLM Routes
*
@@ -116,6 +117,7 @@ const jevHeadStore = () => import('../services/jevHeads.js')
const jevTrainer = () => import('../services/jevTraining.js')
const router = Router()
+router.use(observeModelMutations('loaded-models', 'provider-readiness'));
const layaService = () => import('../services/layaMlx.js')
router.get('/laya-mlx/status', asyncHandler(async (_req, res) => {
@@ -634,7 +636,7 @@ router.post('/migrate', asyncHandler(async (req, res) => {
// reclaimed a model it can't even see. The `disabled` field names the backends
// the user opted out of availability warnings for, so the panel stays quiet
// about them WITHOUT weakening that cleanup guard.
-router.get('/loaded', asyncHandler(async (_req, res) => {
+const loadedObservation = observeModelResource('loaded-models', async () => {
const settings = await getSettings().catch(() => ({}))
const ollamaDisabled = Boolean(settings.localLlm?.ollama?.disabled)
const lmStudioDisabled = Boolean(settings.localLlm?.lmstudio?.disabled)
@@ -650,7 +652,10 @@ router.get('/loaded', asyncHandler(async (_req, res) => {
...(ollamaDisabled ? ['ollama'] : []),
...(lmStudioDisabled ? ['lmstudio'] : []),
]
- res.json({ ollama, lmstudio, sourceErrors, disabled })
+ return { ollama, lmstudio, sourceErrors, disabled }
+}, 2000);
+router.get('/loaded', asyncHandler(async (req, res) => {
+ res.json(await loadedObservation.read({ fresh: req.query.fresh === '1' }));
}))
// POST /api/local-llm/unload — body: { backend: 'ollama', modelId }.
diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.js
index b2ead68c29..bc14799ea0 100644
--- a/server/routes/localLlm.test.js
+++ b/server/routes/localLlm.test.js
@@ -1,3 +1,5 @@
+import { EventEmitter } from 'node:events';
+import { registerModelObservationSocket } from '../services/modelObservation.js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import express from 'express';
import { request } from '../lib/testHelper.js';
@@ -424,6 +426,39 @@ describe('local LLM memory-management routes', () => {
vi.clearAllMocks();
});
+ it('shares residency samples across socket viewers and fences the unload response', async () => {
+ getLoadedModels.mockResolvedValue([{ id: 'example-model' }]);
+ getLoadedLmStudioModels.mockResolvedValue([]);
+ const first = new EventEmitter();
+ const second = new EventEmitter();
+ first.connected = second.connected = true;
+ registerModelObservationSocket(first);
+ registerModelObservationSocket(second);
+ first.emit('loaded-models:subscribe');
+ second.emit('loaded-models:subscribe');
+ try {
+ const app = makeApp();
+ const [a, b] = await Promise.all([
+ request(app).get('/api/local-llm/loaded'),
+ request(app).get('/api/local-llm/loaded'),
+ ]);
+ expect(a.body.ollama).toEqual([{ id: 'example-model' }]);
+ expect(b.body).toEqual(a.body);
+ expect(getLoadedModels).toHaveBeenCalledTimes(1);
+ expect(getLoadedLmStudioModels).toHaveBeenCalledTimes(1);
+ unloadModel.mockImplementationOnce(async () => {
+ getLoadedModels.mockResolvedValue([]);
+ return { unloaded: true, model: 'example-model' };
+ });
+ await request(app).post('/api/local-llm/unload').send({ backend: 'ollama', modelId: 'example-model' });
+ const after = await request(app).get('/api/local-llm/loaded');
+ expect(after.body.ollama).toEqual([]);
+ } finally {
+ first.emit('disconnect');
+ second.emit('disconnect');
+ }
+ });
+
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.
diff --git a/server/routes/providers.js b/server/routes/providers.js
index d3b31ee805..b39b20c0d9 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -1,3 +1,4 @@
+import { observeModelResource, observeModelMutations } from '../services/modelObservation.js';
import { providerModeGroups } from '../lib/aiToolkit/internal/providerModes.js';
import { tuiModeAddition } from '../lib/providerModePairing.js';
import { buildProviderGraphPreview, toManagementPreviewDto } from '../lib/providerGraphPreview.js';
@@ -319,6 +320,14 @@ export function createPortOSProviderRoutes(aiToolkit) {
const providerService = aiToolkit.services.providers;
const providerStatusService = aiToolkit.services.providerStatus;
+ router.use(observeModelMutations('provider-readiness', 'provider-status', 'codex-account'));
+ const readinessObservation = observeModelResource('provider-readiness', async () => {
+ const data = await providerService.getAllProviders();
+ return { readiness: await getProviderReadinessMap(data.providers) };
+ });
+ const accountObservation = observeModelResource('codex-account', async ({ fresh }) => ({
+ readiness: await getCodexAccountReadiness({ fresh }),
+ }));
// Sanitized GET routes — intercept toolkit GET endpoints to strip secrets
/**
@@ -681,8 +690,7 @@ export function createPortOSProviderRoutes(aiToolkit) {
res.json({ readiness: provider ? await getProviderReadinessMap([provider]) : {} });
return;
}
- const data = await providerService.getAllProviders();
- res.json({ readiness: await getProviderReadinessMap(data.providers) });
+ res.json(await readinessObservation.read());
}));
/**
@@ -777,7 +785,7 @@ export function createPortOSProviderRoutes(aiToolkit) {
* no account id, no email, no credential path.
*/
router.get('/codex/account', asyncHandler(async (req, res) => {
- res.json({ readiness: await getCodexAccountReadiness({ fresh: req.query.fresh === '1' }) });
+ res.json(await accountObservation.read({ fresh: req.query.fresh === '1' }));
}));
/**
@@ -1065,17 +1073,20 @@ export function createPortOSProviderRoutes(aiToolkit) {
res.json(await clearModelPin(pinId));
}));
- router.get('/status', asyncHandler(async (req, res) => {
+ const statusObservation = observeModelResource('provider-status', async () => {
const statuses = providerStatusService.getAllStatuses();
// Enrich with time until recovery
- const enriched = { ...statuses };
+ const enriched = { ...statuses, providers: { ...statuses.providers } };
for (const [providerId, status] of Object.entries(enriched.providers)) {
enriched.providers[providerId] = {
...presentProviderStatus(status),
timeUntilRecovery: providerStatusService.getTimeUntilRecovery(providerId)
};
}
- res.json(enriched);
+ return enriched;
+ });
+ router.get('/status', asyncHandler(async (_req, res) => {
+ res.json(await statusObservation.read());
}));
router.get('/:id/status', asyncHandler(async (req, res) => {
diff --git a/server/routes/voice.js b/server/routes/voice.js
index 9ff54830f9..e8b6f22e3f 100644
--- a/server/routes/voice.js
+++ b/server/routes/voice.js
@@ -1,3 +1,4 @@
+import { observeModelResource, observeModelMutations } from '../services/modelObservation.js';
/**
* Voice Routes
*
@@ -36,6 +37,7 @@ import { findPiperVoice } from '../services/voice/piper-voices.js';
import { speakProactive, HHMM_RE, MAX_PROACTIVE_TEXT_LEN } from '../services/voice/proactiveSpeech.js';
const router = Router();
+router.use(observeModelMutations('voice-readiness'));
const facetimeActionSchema = z.object({}).strict();
@@ -166,18 +168,21 @@ router.put('/config', asyncHandler(async (req, res) => {
}));
// GET /api/voice/status — reachability + enabled flag + binary/model presence
-router.get('/status', asyncHandler(async (_req, res) => {
+const voiceObservation = observeModelResource('voice-readiness', async () => {
const cfg = await getVoiceConfig();
const [services, bins] = await Promise.all([checkAll(cfg), verifyBinaries(cfg)]);
const models = verifyModels(cfg);
- res.json({
+ return {
enabled: cfg.enabled,
sttEngine: cfg.stt.engine,
ttsEngine: cfg.tts.engine,
services,
binaries: bins,
models,
- });
+ };
+}, 5000);
+router.get('/status', asyncHandler(async (_req, res) => {
+ res.json(await voiceObservation.read());
}));
router.get('/facetime/status', asyncHandler(async (_req, res) => {
diff --git a/server/services/codexAppServer.js b/server/services/codexAppServer.js
index c3d2b285a1..360ba3a6e7 100644
--- a/server/services/codexAppServer.js
+++ b/server/services/codexAppServer.js
@@ -1,3 +1,4 @@
+import { invalidateModelObservation } from './modelObservation.js';
/**
* PortOS's client for the Codex **app-server** — the JSON-RPC-over-stdio
* endpoint OpenAI documents for embedding Codex in a product.
@@ -218,10 +219,12 @@ const handleNotification = (method, params) => {
routeTurnNotification(method, params);
if (method === CODEX_NOTIFICATIONS.accountUpdated || method === CODEX_NOTIFICATIONS.rateLimitsUpdated) {
readinessCache = null;
+ invalidateModelObservation('codex-account');
return;
}
if (method !== CODEX_NOTIFICATIONS.loginCompleted) return;
readinessCache = null;
+ invalidateModelObservation('codex-account');
// A sign-in that actually completed changed the ACCOUNT, whoever started it —
// so the cached catalog belongs to whoever was signed in before, and an
// auth/quota bench was benching a subscription that is no longer the current
diff --git a/server/services/lmStudioManager.js b/server/services/lmStudioManager.js
index b5701e2b04..0760695085 100644
--- a/server/services/lmStudioManager.js
+++ b/server/services/lmStudioManager.js
@@ -1,3 +1,4 @@
+import { invalidateModelObservation } from './modelObservation.js';
/**
* LM Studio Manager Service
*
@@ -309,6 +310,8 @@ async function loadModel(modelId) {
console.log(`📦 Model loaded: ${modelId}`)
cosEvents.emit('lmstudio:modelLoaded', { modelId })
+ invalidateModelObservation('loaded-models')
+ invalidateModelObservation('provider-readiness')
return { success: true, modelId, ...response }
}
@@ -399,6 +402,8 @@ async function loadModelWithArgs(modelId, args = []) {
else tunedLoads.delete(modelId)
console.log(`📦 LM Studio loaded ${modelId}${signature ? ` (${signature})` : ` without ${carried}`}`)
cosEvents.emit('lmstudio:modelLoaded', { modelId })
+ invalidateModelObservation('loaded-models')
+ invalidateModelObservation('provider-readiness')
return { success: true }
}
@@ -441,6 +446,8 @@ async function unloadModel(modelId) {
tunedLoads.delete(modelId)
console.log(`📤 Model unloaded: ${modelId}`)
cosEvents.emit('lmstudio:modelUnloaded', { modelId })
+ invalidateModelObservation('loaded-models')
+ invalidateModelObservation('provider-readiness')
return { success: true, modelId }
}
@@ -987,6 +994,8 @@ async function deleteModel(modelId) {
await rmdir(join(dir, '..')).catch(() => {})
console.log(`🗑️ LM Studio deleted: ${modelId} (${dir})`)
cosEvents.emit('lmstudio:modelDeleted', { modelId })
+ invalidateModelObservation('loaded-models')
+ invalidateModelObservation('provider-readiness')
return { success: true, modelId }
}
diff --git a/server/services/modelObservation.js b/server/services/modelObservation.js
new file mode 100644
index 0000000000..f1aaebeda9
--- /dev/null
+++ b/server/services/modelObservation.js
@@ -0,0 +1,126 @@
+/**
+ * Demand-driven samples shared by HTTP readers and socket viewers. Readers
+ * inspect external state only: subscribing never loads a model or runs AI.
+ * No sample payload goes over the socket; existing authenticated routes retain
+ * their projections and failure semantics.
+ */
+const resources = new Map();
+const groups = new Map();
+const signature = value => JSON.stringify(value, (key, item) =>
+ ['timestamp', 'checkedAt', 'responseTime', 'latencyMs'].includes(key) ? undefined : item);
+
+export function observeModelResource(namespace, probe, intervalMs = 20_000) {
+ const subscribers = groups.get(namespace) ?? new Set();
+ groups.set(namespace, subscribers);
+ let pending = null;
+ let sample = null;
+ let sampled = false;
+ let revision = 0;
+ let timer = null;
+ let lastSignature;
+ let sampledAt = 0;
+
+ const notify = () => {
+ for (const socket of subscribers) {
+ if (!socket.connected) continue;
+ socket.emit(`${namespace}:changed`, {});
+ }
+ };
+ const schedule = () => {
+ if (!subscribers.size || timer) return;
+ timer = setTimeout(() => {
+ timer = null;
+ read({ fresh: true }).catch(() => {});
+ }, intervalMs);
+ timer.unref?.();
+ };
+ const read = ({ fresh = false } = {}) => {
+ if (pending) return pending;
+ if (!fresh && subscribers.size && sampled && Date.now() - sampledAt < intervalMs) {
+ return sample.error ? Promise.reject(sample.error) : Promise.resolve(sample.value);
+ }
+ pending = Promise.resolve().then(async () => {
+ let result;
+ let started;
+ // A mutation fences both the cached sample and reads already in flight.
+ // Every waiter gets the post-mutation sample, never the discarded result.
+ do {
+ started = revision;
+ result = await Promise.resolve().then(() => probe({ fresh })).then(value => ({ value }), error => ({ error }));
+ } while (started !== revision);
+ const nextSignature = result.error ? 'probe-unavailable' : signature(result.value);
+ sample = result;
+ sampled = true;
+ sampledAt = Date.now();
+ if (nextSignature !== lastSignature) {
+ lastSignature = nextSignature;
+ notify();
+ }
+ if (result.error) throw result.error;
+ return result.value;
+ }).finally(() => {
+ pending = null;
+ schedule();
+ });
+ return pending;
+ };
+ const invalidate = () => {
+ revision += 1;
+ sampled = false;
+ if (subscribers.size) read({ fresh: true }).catch(() => {});
+ };
+ const stop = () => {
+ clearTimeout(timer);
+ timer = null;
+ sampled = false;
+ lastSignature = undefined;
+ // An in-flight read can drain, but cannot schedule without subscribers.
+ };
+ const resource = { read, invalidate, stop };
+ resources.set(namespace, resource);
+ if (subscribers.size) read().catch(() => {});
+ return resource;
+}
+
+export function invalidateModelObservation(namespace) {
+ resources.get(namespace)?.invalidate();
+}
+
+// Register only named resources, never arbitrary client-supplied probe targets.
+export function registerModelObservationSocket(socket) {
+ const register = namespace => {
+ const subscribers = groups.get(namespace) ?? new Set();
+ groups.set(namespace, subscribers);
+ socket.on(`${namespace}:subscribe`, () => {
+ subscribers.add(socket);
+ resources.get(namespace)?.read().catch(() => {});
+ });
+ const release = () => {
+ subscribers.delete(socket);
+ if (!subscribers.size) resources.get(namespace)?.stop();
+ };
+ socket.on(`${namespace}:unsubscribe`, release);
+ socket.on('disconnect', release);
+ };
+ register('loaded-models');
+ register('voice-readiness');
+ register('provider-readiness');
+ register('provider-status');
+ register('codex-account');
+}
+
+/** Mutations invalidate even on failure: an external action may partially apply. */
+export function observeModelMutations(...namespaces) {
+ return (req, res, next) => {
+ if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method)) {
+ res.once('finish', () => namespaces.forEach(invalidateModelObservation));
+ }
+ next();
+ };
+}
+
+export function resetModelObservationsForTests() {
+ for (const resource of resources.values()) resource.stop();
+ resources.clear();
+ groups.clear();
+}
diff --git a/server/services/modelObservation.test.js b/server/services/modelObservation.test.js
new file mode 100644
index 0000000000..505e751feb
--- /dev/null
+++ b/server/services/modelObservation.test.js
@@ -0,0 +1,89 @@
+import { EventEmitter } from 'node:events';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { observeModelResource, registerModelObservationSocket, resetModelObservationsForTests } from './modelObservation.js';
+
+function viewer() {
+ const socket = new EventEmitter();
+ socket.connected = true;
+ socket.frames = [];
+ socket.on('loaded-models:changed', payload => socket.frames.push(payload));
+ registerModelObservationSocket(socket);
+ return socket;
+}
+const flush = () => vi.advanceTimersByTimeAsync(0);
+
+describe('shared model observations through socket subscriptions and HTTP reads', () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => { resetModelObservationsForTests(); vi.useRealTimers(); });
+
+ it('shares one external sample across viewers and stops after the final disconnect', async () => {
+ const probe = vi.fn().mockResolvedValue({ ollama: [] });
+ const resource = observeModelResource('loaded-models', probe, 2000);
+ expect(probe).not.toHaveBeenCalled();
+ const first = viewer();
+ const second = viewer();
+ first.emit('loaded-models:subscribe');
+ second.emit('loaded-models:subscribe');
+ await Promise.all([resource.read(), resource.read()]);
+ expect(probe).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(probe).toHaveBeenCalledTimes(2);
+ expect(first.frames).toEqual([{}]); // unchanged samples stay quiet
+ first.emit('loaded-models:unsubscribe');
+ probe.mockResolvedValue({ ollama: [{ id: 'example-model' }] });
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(first.frames).toHaveLength(1);
+ expect(second.frames).toHaveLength(2);
+ second.emit('disconnect');
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect(probe).toHaveBeenCalledTimes(3);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('publishes probe failures and recovery without converting failure into empty data', async () => {
+ const probe = vi.fn().mockResolvedValue({ ollama: [] });
+ const resource = observeModelResource('loaded-models', probe, 2000);
+ const socket = viewer();
+ socket.emit('loaded-models:subscribe');
+ await flush();
+ probe.mockRejectedValue(new Error('unavailable'));
+ await vi.advanceTimersByTimeAsync(2000);
+ await expect(resource.read()).rejects.toThrow('unavailable');
+ expect(socket.frames).toHaveLength(2);
+ expect(probe).toHaveBeenCalledTimes(2); // failure reads share the sample too
+ probe.mockResolvedValue({ ollama: [] });
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(socket.frames).toHaveLength(3);
+ await expect(resource.read()).resolves.toEqual({ ollama: [] });
+ });
+
+ it('fences an in-flight pre-unload sample for every waiting viewer', async () => {
+ let resolveOld;
+ const probe = vi.fn().mockImplementationOnce(() => new Promise(resolve => { resolveOld = resolve; }))
+ .mockResolvedValue({ ollama: [] });
+ const resource = observeModelResource('loaded-models', probe, 2000);
+ const socket = viewer();
+ socket.emit('loaded-models:subscribe');
+ const read = resource.read();
+ await flush();
+ resource.invalidate();
+ resolveOld({ ollama: [{ id: 'unloaded-model' }] });
+ await expect(read).resolves.toEqual({ ollama: [] });
+ expect(probe).toHaveBeenCalledTimes(2);
+ expect(socket.frames).toEqual([{}]);
+ });
+
+ it('does not restart observation when the last viewer leaves during a read', async () => {
+ let resolve;
+ const resource = observeModelResource('loaded-models', () => new Promise(done => { resolve = done; }), 2000);
+ const socket = viewer();
+ socket.emit('loaded-models:subscribe');
+ const read = resource.read();
+ await flush();
+ socket.emit('disconnect');
+ resolve({ ollama: [] });
+ await read;
+ expect(socket.frames).toEqual([]);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index 32e7a6f90b..8f659fb3db 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -1,3 +1,4 @@
+import { invalidateModelObservation } from './modelObservation.js';
/**
* Ollama Manager Service
*
@@ -1357,6 +1358,7 @@ async function unloadModel(modelName) {
return { unloaded: false, reason: result._err.message || 'request failed' }
}
console.log(`🧹 ollama: unloaded ${modelName} (keep_alive=0)`)
+ invalidateModelObservation('loaded-models')
return { unloaded: true, model: modelName }
}
diff --git a/server/services/providerReadiness.js b/server/services/providerReadiness.js
index 2aac75359d..4eb203bc96 100644
--- a/server/services/providerReadiness.js
+++ b/server/services/providerReadiness.js
@@ -1,3 +1,4 @@
+import { invalidateModelObservation } from './modelObservation.js';
/**
* "Is everything this provider needs actually installed and running?"
*
@@ -516,6 +517,7 @@ function memoize(fn) {
* which change exactly what these caches remember.
*/
export function resetProviderReadinessCache() {
+ invalidateModelObservation('provider-readiness');
// The endpoint listing cache lives in `lib/openAiModelsProbeCache.js` — the
// dispatch path's context gate shares it, and a daemon relaunched at a
// different context size must invalidate BOTH readers or a run is gated on
diff --git a/server/services/providerStatus.js b/server/services/providerStatus.js
index 57221675db..a6e9d9e34b 100644
--- a/server/services/providerStatus.js
+++ b/server/services/providerStatus.js
@@ -1,3 +1,4 @@
+import { invalidateModelObservation } from './modelObservation.js';
/**
* Compatibility shim for PortOS services that import from providerStatus.js.
*
@@ -17,6 +18,7 @@ let boundStatusEvents = null;
const forwardStatusChanged = (data) => {
providerStatusEvents.emit('status:changed', data);
+ invalidateModelObservation('provider-status');
};
function getProviderStatusService() {
diff --git a/server/services/socket.js b/server/services/socket.js
index 11e7db8659..b2951ee598 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -1,3 +1,4 @@
+import { registerModelObservationSocket } from './modelObservation.js';
import { registerBrowserStatusSocket } from './browserStatus.js';
import { spriteEvents } from './sprites/events.js';
import { modelLifecycleEvents } from './modelLifecycleEvents.js';
@@ -219,6 +220,7 @@ function registerLifecycleHandlers(socket, _io) {
const SOCKET_HANDLER_REGISTRARS = [
registerAuthHandlers,
registerReadinessSocket,
+ registerModelObservationSocket,
registerBrowserStatusSocket,
registerVoiceHandlers,
registerBuildHandlers,
diff --git a/server/services/voice/health.js b/server/services/voice/health.js
index 9c92bce0d8..de79170d4d 100644
--- a/server/services/voice/health.js
+++ b/server/services/voice/health.js
@@ -1,3 +1,4 @@
+import { invalidateModelObservation } from '../modelObservation.js';
// Voice stack health checks — whisper.cpp + LLM provider + (when active) Piper.
import { existsSync } from 'fs';
@@ -72,4 +73,7 @@ export const checkAll = async (cfg) => {
return out;
};
-export const invalidateHealthCache = () => { cache = null; };
+export const invalidateHealthCache = () => {
+ cache = null;
+ invalidateModelObservation('voice-readiness');
+};