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: update fleet host panels through shared notifications (#8669)
[._.]/ Adam Eivy1b27b10b2162
diff --git a/client/src/components/providers/FleetHostRealtime.test.jsx b/client/src/components/providers/FleetHostRealtime.test.jsxnew file mode 100644index 0000000000..1d9e8415cb--- /dev/null+++ b/client/src/components/providers/FleetHostRealtime.test.jsx@@ -0,0 +1,88 @@+import { afterEach, expect, it, vi } from 'vitest';+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+const bus = vi.hoisted(() => {+ const listeners = new Map();+ return {+ on: vi.fn((event, fn) => { if (!listeners.has(event)) listeners.set(event, new Set()); listeners.get(event).add(fn); }),+ off: vi.fn((event, fn) => listeners.get(event)?.delete(fn)),+ emit: vi.fn(),+ deliver: (event) => listeners.get(event)?.forEach(fn => fn({})),+ };+});+const api = vi.hoisted(() => ({+ getFleetLlmHost: vi.fn(), getFleetPeerHosts: vi.fn(), getFleetLlmHostUsage: vi.fn(),+ revealFleetLlmHostKey: vi.fn(), stopFleetLlmHost: vi.fn(),+}));+vi.mock('../../services/socket', () => ({ default: bus }));+vi.mock('../../services/apiProviders', () => api);+vi.mock('../install/RuntimeInstallModal', () => ({ default: () => null }));+import FleetHostSetup from './FleetHostSetup';+import FleetHostUsage from './FleetHostUsage';+const host = {+ recommendation: { supported: true, title: 'Example host', reason: 'Ready' },+ specs: { totalMemoryGb: 32 }, checks: [], queue: { active: 0, queued: 0 },+ enabled: true, stoppable: true,+};+const usage = { clients: [], recent: [], totals: { requests: 12 }, activeRequests: 0, queue: { queued: 0 } };+const settle = () => act(async () => { for (let i = 0; i < 20; i++) await Promise.resolve(); });+afterEach(() => { cleanup(); vi.useRealTimers(); vi.clearAllMocks(); });+it('renders events and stop receipts without timer reads, then reconciles once on reconnect and tab show', async () => {+ vi.useFakeTimers();+ api.getFleetLlmHost.mockResolvedValue(host);+ api.getFleetLlmHostUsage.mockResolvedValue(usage);+ api.stopFleetLlmHost.mockResolvedValue({ success: true, containerStopped: true, status: { ...host, enabled: false, stoppable: false } });+ render(<MemoryRouter><FleetHostSetup /></MemoryRouter>);+ await settle();+ expect(screen.getByRole('button', { name: 'Stop model host' })).toBeInTheDocument();+ const initial = api.getFleetLlmHost.mock.calls.length;+ const initialUsage = api.getFleetLlmHostUsage.mock.calls.length;+ await act(() => vi.advanceTimersByTimeAsync(60_000));+ expect(api.getFleetLlmHost).toHaveBeenCalledTimes(initial);+ expect(api.getFleetLlmHostUsage).toHaveBeenCalledTimes(initialUsage);+ api.getFleetLlmHostUsage.mockResolvedValue({ ...usage, totals: { requests: 9876 } });+ act(() => bus.deliver('fleet-host:usage:changed'));+ await settle();+ expect(screen.getByText('9,876')).toBeInTheDocument();+ const beforeReconnect = api.getFleetLlmHost.mock.calls.length;+ act(() => bus.deliver('connect'));+ await settle();+ expect(api.getFleetLlmHost).toHaveBeenCalledTimes(beforeReconnect + 1);+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });+ fireEvent(document, new Event('visibilitychange'));+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });+ fireEvent(document, new Event('visibilitychange'));+ await settle();+ expect(api.getFleetLlmHost).toHaveBeenCalledTimes(beforeReconnect + 2);+ fireEvent.click(screen.getByRole('button', { name: 'Stop model host' }));+ fireEvent.click(screen.getByRole('button', { name: /Confirm stop/ }));+ await settle();+ expect(screen.queryByRole('button', { name: 'Stop model host' })).not.toBeInTheDocument();+ expect(api.getFleetLlmHost).toHaveBeenCalledTimes(beforeReconnect + 2);+});+it('keeps failed usage distinct from an empty ledger and recovers through notifications', async () => {+ api.getFleetLlmHostUsage.mockRejectedValue(new Error('unavailable'));+ render(<FleetHostUsage />);+ await settle();+ expect(screen.getByText(/report is unavailable/)).toBeInTheDocument();+ expect(screen.queryByText(/No machine has called/)).not.toBeInTheDocument();+ api.getFleetLlmHostUsage.mockResolvedValue(usage);+ act(() => bus.deliver('fleet-host:usage:changed'));+ await settle();+ expect(screen.queryByText(/report is unavailable/)).not.toBeInTheDocument();+ expect(screen.getByText(/No machine has called/)).toBeInTheDocument();+});+it('refreshes compact discovery from configured-peer events and shows failed discovery instead of empty hosts', async () => {+ api.getFleetLlmHost.mockResolvedValue({ ...host, enabled: false });+ api.getFleetPeerHosts.mockResolvedValue({ hosts: [] });+ render(<MemoryRouter><FleetHostSetup compact /></MemoryRouter>);+ await settle();+ api.getFleetPeerHosts.mockResolvedValue({ hosts: [{ peerId: 'example-peer', peerName: 'Example GPU', enabled: true }] });+ act(() => bus.deliver('instances:peers:updated'));+ await settle();+ expect(screen.getByText('Example GPU', { selector: 'span' })).toBeInTheDocument();+ api.getFleetPeerHosts.mockResolvedValue({ hosts: [], unavailable: 1 });+ act(() => bus.deliver('instances:peers:updated'));+ await settle();+ expect(screen.getByText(/Could not discover peer hosts/)).toBeInTheDocument();+});diff --git a/client/src/components/providers/FleetHostSetup.jsx b/client/src/components/providers/FleetHostSetup.jsxindex f3246dba54..a5387d5a79 100644--- a/client/src/components/providers/FleetHostSetup.jsx+++ b/client/src/components/providers/FleetHostSetup.jsx@@ -1,16 +1,21 @@-import { useCallback, useEffect, useMemo, useState } from 'react';+import { useCallback, useMemo, useState } from 'react';import { Link } from 'react-router';import { CheckCircle2, HelpCircle, Server, XCircle } from 'lucide-react';import { getFleetLlmHost, getFleetPeerHosts, revealFleetLlmHostKey, stopFleetLlmHost } from '../../services/apiProviders';import FleetHostUsage from './FleetHostUsage';import { isFleetHostConfigured } from '../../utils/providers';import { copyToClipboard } from '../../lib/clipboard';-import { useAutoRefetch } from '../../hooks/useAutoRefetch';+import { useSocketResource } from '../../hooks/useSocketResource';import RuntimeInstallModal from '../install/RuntimeInstallModal';import Banner from '../ui/Banner';import { PORTS } from '../../lib/ports.js';import { LOCAL_RUNTIME_MANAGE_URLS } from '../../../../server/lib/modelPinMembership.js';+const HOST_EVENTS = ['fleet-host:changed', 'fleet-host:usage:changed'];+const PEER_EVENTS = ['instances:peers:updated'];+const readHost = () => getFleetLlmHost({ silent: true });+const readPeerHosts = () => getFleetPeerHosts({ silent: true });+// A self-host provider (the auto-created Direct API one from `configure()` in// server/services/fleetLlmHost.js, and the OpenCode one from `?selfHost=1`)// is always wired to the loopback queue address, never `status.endpoint` (the@@ -20,8 +25,13 @@ import { LOCAL_RUNTIME_MANAGE_URLS } from '../../../../server/lib/modelPinMemberconst SELF_HOST_ENDPOINT = `http://127.0.0.1:${PORTS.FLEET_LLM}/v1`;export default function FleetHostSetup({ compact = false, providers = [], onConfigured }) {- const [status, setStatus] = useState(null);- const [peerHosts, setPeerHosts] = useState([]);+ const { data: status, error: statusError, refetch: load, updateData: setStatus } = useSocketResource(+ readHost, { namespace: 'fleet-host', events: HOST_EVENTS },+ );+ const { data: peerResult, error: peerError, refetch: loadPeers } = useSocketResource(+ readPeerHosts, { namespace: 'instances', events: PEER_EVENTS, enabled: compact },+ );+ const peerHosts = peerResult?.hosts || [];const [error, setError] = useState('');const [installing, setInstalling] = useState(false);const [key, setKey] = useState('');@@ -34,19 +44,11 @@ export default function FleetHostSetup({ compact = false, providers = [], onConfconst [stopArmed, setStopArmed] = useState(false);const [stopping, setStopping] = useState(false);const [stopNote, setStopNote] = useState('');- const load = useCallback(() => {- getFleetLlmHost({ silent: true })- .then((value) => { setStatus(value); setError(''); })- .catch(() => setError('Could not check this machine. Retry to detect hardware and model readiness.'));- if (compact) {- getFleetPeerHosts({ silent: true })- .then((res) => { setPeerHosts(Array.isArray(res?.hosts) ? res.hosts : []); })- .catch(() => setPeerHosts([]));- }- }, [compact]);- useEffect(() => { load(); }, [load]);- useAutoRefetch(load, 15000, { enabled: !compact && !installing, pollOnly: true, immediate: false });- const completed = useCallback(() => { load(); onConfigured?.(); }, [load, onConfigured]);+ const completed = useCallback((receipt) => {+ if (receipt?.status) setStatus(receipt.status);+ else load();+ onConfigured?.();+ }, [load, setStatus, onConfigured]);const unconfiguredPeerHosts = useMemo(() => {if (!compact) return [];@@ -82,15 +84,19 @@ export default function FleetHostSetup({ compact = false, providers = [], onConf: result?.containerStopped? 'Host stopped. The container was removed; its image and weights are still on disk, so starting it again takes minutes, not another download.': 'Host stopped and disabled.');- load();+ if (result.status) setStatus(result.status);+ else load();onConfigured?.();}).catch(() => setStopNote('Could not stop the host. Check that Docker is responding, then try again.')).finally(() => setStopping(false));};const actionClass = 'inline-flex items-center justify-center min-h-[40px] px-3 py-2 rounded-lg bg-port-accent text-white text-sm disabled:opacity-50';+ const loadError = statusError ? 'Could not check this machine. Retry to detect hardware and model readiness.'+ : (peerError || peerResult?.unavailable) ? 'Could not discover peer hosts. Retry when the peer is available.' : '';const title = status?.recommendation.title || 'Recommended model host setup';if (compact) {+ if (loadError) return <Banner tone="error">{loadError}<button type="button" onClick={() => { load(); loadPeers(); }}>Retry</button></Banner>;if (selfNeedsProvider || unconfiguredPeerHosts.length > 0) {return (<div className="space-y-3" aria-label="Available model hosts">@@ -146,7 +152,7 @@ export default function FleetHostSetup({ compact = false, providers = [], onConf<p>{status?.recommendation.reason || 'Detecting this machine…'}</p>{status && <p className="mt-2 text-xs">{status.specs.platform} · {status.specs.totalMemoryGb ?? 'Unknown'} GB RAM{status.specs.cuda?.gpus?.map((gpu) => ` · ${gpu.name} (${gpu.vramGb ?? '?'} GB VRAM)`).join('')}</p>}</Banner>- {error && <Banner tone="error">{error}</Banner>}+ {(error || loadError) && <Banner tone="error">{error || loadError}</Banner>}<div className="flex flex-wrap gap-2"><button type="button" onClick={load} className="min-h-[40px] px-3 rounded-lg bg-port-border text-sm">Refresh host status</button><Link to={manageHref} className="min-h-[40px] px-3 py-2 text-sm text-port-accent">Manage model servers</Link>diff --git a/client/src/components/providers/FleetHostUsage.jsx b/client/src/components/providers/FleetHostUsage.jsxindex 0b511ed5c9..22da871d6d 100644--- a/client/src/components/providers/FleetHostUsage.jsx+++ b/client/src/components/providers/FleetHostUsage.jsx@@ -1,7 +1,9 @@-import { useCallback, useEffect, useState } from 'react';import { Activity, AlertTriangle, RefreshCw, Server } from 'lucide-react';import { getFleetLlmHostUsage } from '../../services/apiProviders';-import { useAutoRefetch } from '../../hooks/useAutoRefetch';+import { useSocketResource } from '../../hooks/useSocketResource';++const USAGE_EVENTS = ['fleet-host:usage:changed', 'fleet-host:changed'];+const readUsage = () => getFleetLlmHostUsage({ silent: true });import { formatCount, formatDurationMs, timeAgo } from '../../utils/formatters';import Banner from '../ui/Banner';@@ -18,23 +20,11 @@ import Banner from '../ui/Banner';* server from the peer list or the tailnet. A caller matching neither is shown* as unrecognized rather than hidden, which is the case worth seeing.*/-export default function FleetHostUsage({ pollMs = 10000 }) {- const [report, setReport] = useState(null);- const [error, setError] = useState('');- const [loading, setLoading] = useState(false);-- const load = useCallback(() => {- setLoading(true);- // Silent: this panel polls, and a transient failure belongs in its own- // inline banner rather than in a toast every ten seconds.- getFleetLlmHostUsage({ silent: true })- .then((value) => { setReport(value); setError(''); })- .catch(() => setError('Could not read this host\'s usage. It is still serving — only the report is unavailable.'))- .finally(() => setLoading(false));- }, []);-- useEffect(() => { load(); }, [load]);- useAutoRefetch(load, pollMs, { pollOnly: true, immediate: false });+export default function FleetHostUsage() {+ const { data: report, error: loadError, loading, refetch: load } = useSocketResource(+ readUsage, { namespace: 'fleet-host', events: USAGE_EVENTS },+ );+ const error = loadError ? "Could not read this host's usage. The report is unavailable." : '';const clients = report?.clients || [];const totals = report?.totals;diff --git a/client/src/hooks/useInstallStream.js b/client/src/hooks/useInstallStream.jsindex 1a167ec57f..d96e57e9f4 100644--- a/client/src/hooks/useInstallStream.js+++ b/client/src/hooks/useInstallStream.js@@ -14,7 +14,7 @@ import { maybeRedirectToLogin } from '../services/apiCore';* setup-image-video.sh):* { type: 'stage', stage, message? } → advances currentStage + logs it* { type: 'log', message } → appends a log line- * { type: 'complete', message } → done=true, onComplete(), closes+ * { type: 'complete', message } → done=true, onComplete(frame), closes* { type: 'error', message } → error set, closes** Closing the EventSource or aborting the fetch stream (via `close()` on@@ -35,7 +35,7 @@ import { maybeRedirectToLogin } from '../services/apiCore';* @param {string|null} url - SSE endpoint; null/empty leaves the stream closed.* @param {object} opts* @param {boolean} [opts.enabled=true] - when false, the stream stays closed and state resets.- * @param {() => void} [opts.onComplete] - fired once on the `complete` frame.+ * @param {(frame: object) => void} [opts.onComplete] - fired once on the `complete` frame.* @param {number} [opts.maxLogLines=500] - cap on retained log lines.* @param {number} [opts.flushMs=0] - 0 = per-line flush; >0 = debounce window.* @param {'GET'|'POST'} [opts.method='GET'] - GET uses EventSource; POST uses@@ -142,7 +142,7 @@ export function useInstallStream(url, {appendLog({ kind: 'success', text: msg.message });flush();closeThis();- onCompleteRef.current?.();+ onCompleteRef.current?.(msg);} else if (msg.type === 'error') {const message = msg.message || 'Installer failed.';setError(message);diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.jsindex ec952816b5..eca673c712 100644--- a/server/lib/socketEventContracts.js+++ b/server/lib/socketEventContracts.js@@ -44,6 +44,22 @@ const loomRunSnapshot = (production) => Object.freeze({});export const SOCKET_EVENT_CONTRACTS = Object.freeze({+ 'fleet-host:subscribe': {+ direction: 'client-to-server', summary: 'Observe local fleet host readiness while this operator socket is subscribed.',+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },+ },+ 'fleet-host:unsubscribe': {+ direction: 'client-to-server', summary: 'Release this operator socket; stop external probes after the last subscriber leaves.',+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },+ },+ 'fleet-host:changed': {+ direction: 'server-to-client', summary: 'Local host readiness or setup changed; no credentials or records.',+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },+ },+ 'fleet-host:usage:changed': {+ direction: 'server-to-client', summary: 'Local queue or usage ledger changed; read the authenticated usage report.',+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },+ },'reference-sheet:changed': {direction: 'server-to-client',summary: 'Correlated sheet publication outcome after the image copy and character pointer write finish.',diff --git a/server/routes/providers.fleetPeerHosts.test.js b/server/routes/providers.fleetPeerHosts.test.jsindex 677ea71c47..9a8466a0bc 100644--- a/server/routes/providers.fleetPeerHosts.test.js+++ b/server/routes/providers.fleetPeerHosts.test.js@@ -70,9 +70,10 @@ describe('this host\'s inbound usage and stop controls', () => {return { success: true, containerStopped: true };});+ fleetLlmHost.getFleetLlmHostStatus.mockResolvedValue({ enabled: false, stoppable: false });const res = await request(buildApp()).post('/api/providers/fleet-host/stop');expect(res.status).toBe(200);- expect(res.body).toMatchObject({ success: true, containerStopped: true });+ expect(res.body).toMatchObject({ success: true, containerStopped: true, status: { enabled: false, stoppable: false } });expect(res.body.log[0]).toContain('Closing the shared API queue');});});diff --git a/server/routes/providers.js b/server/routes/providers.jsindex d3b31ee805..a69042cf72 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -269,8 +269,8 @@ export function createPortOSProviderRoutes(aiToolkit) {});router.get('/fleet-host', asyncHandler(async (req, res) => {- const { getFleetLlmHostStatus } = await import('../services/fleetLlmHost.js');- res.set('Cache-Control', 'no-store').json(await getFleetLlmHostStatus());+ const { readFleetHostStatus } = await import('../services/fleetHostNotify.js');+ res.set('Cache-Control', 'no-store').json(await readFleetHostStatus());}));// Who has been using this machine's GPU. Never cached: the point of the// report is what is happening right now.@@ -281,12 +281,12 @@ export function createPortOSProviderRoutes(aiToolkit) {// The counterpart to `/fleet-host/setup`: close the queue, clear the// enable marker, drop the login task and remove the container.router.post('/fleet-host/stop', asyncHandler(async (req, res) => {- const { disableFleetLlmHost } = await import('../services/fleetLlmHost.js');+ const { disableFleetLlmHost, getFleetLlmHostStatus } = await import('../services/fleetLlmHost.js');if (runtimeSetupInFlight) throw new ServerError('Model host setup is running — wait for it to finish before stopping the host.', { status: 409, code: 'SETUP_BUSY' });const log = [];const result = await disableFleetLlmHost({ emit: (message) => log.push(message) });resetProviderReadinessCache();- res.set('Cache-Control', 'no-store').json({ ...result, log });+ res.set('Cache-Control', 'no-store').json({ ...result, log, status: await getFleetLlmHostStatus().catch(() => null) });}));router.get('/fleet-peer-hosts', asyncHandler(async (req, res) => {const { getFleetPeerHosts } = await import('../services/fleetLlmHost.js');@@ -302,7 +302,7 @@ export function createPortOSProviderRoutes(aiToolkit) {res.set('Cache-Control', 'no-store').json({ apiKey: await revealFleetLlmKey() });}));router.post('/fleet-host/setup', asyncHandler(async (req, res) => {- const { configureFleetLlmHost } = await import('../services/fleetLlmHost.js');+ const { configureFleetLlmHost, getFleetLlmHostStatus } = await import('../services/fleetLlmHost.js');if (runtimeSetupInFlight) throw new ServerError('Another model setup is running.', { status: 409, code: 'SETUP_BUSY' });runtimeSetupInFlight = true;const { send, safeEnd } = openSseStream(res);@@ -313,7 +313,8 @@ export function createPortOSProviderRoutes(aiToolkit) {isCancelled: () => clientGone,}).catch((err) => ({ success: false, error: err.message })).finally(() => { runtimeSetupInFlight = false; resetProviderReadinessCache(); });- send(result.success ? { type: 'complete', message: 'Host configured. Check model readiness below.' } : { type: 'error', message: result.error });+ const status = await getFleetLlmHostStatus().catch(() => null);+ send(result.success ? { type: 'complete', message: 'Host configured. Check model readiness below.', status } : { type: 'error', message: result.error });safeEnd();}));diff --git a/server/services/fleetHostNotify.js b/server/services/fleetHostNotify.jsnew file mode 100644index 0000000000..c622a16f15--- /dev/null+++ b/server/services/fleetHostNotify.js@@ -0,0 +1,96 @@+/** Local operator subscriptions only; notifications never carry host keys or usage records. */+const subscribers = new Set();+const pendingEvents = new Set();+let timer = null;+let flush = null;+let generation = 0;+let revision = 0;+let cached = null;+let reading = null;+let previous = null;+export const FLEET_HOST_OBSERVE_MS = 15_000;++// The observer and concurrent HTTP consumers share the same probe. A mutation+// during a probe invalidates its answer and drains one fresh read before return.+export function readFleetHostStatus({ refresh = false } = {}) {+ if (refresh) cached = null;+ if (!reading && cached && subscribers.size) {+ const snapshot = cached;+ return import('./fleetLlmHost.js').then(({ getFleetLlmHostQueue }) => ({ ...snapshot, queue: getFleetLlmHostQueue() }));+ }+ if (!reading) {+ reading = (async () => {+ let started;+ let result;+ do {+ started = revision;+ const { getFleetLlmHostStatus } = await import('./fleetLlmHost.js');+ result = await getFleetLlmHostStatus();+ } while (started !== revision);+ cached = result;+ return result;+ })().finally(() => { reading = null; });+ }+ return reading;+}++export function noteFleetHostChanged({ usageOnly = false } = {}) {+ if (!usageOnly) { revision += 1; cached = null; }+ if (!subscribers.size) return;+ pendingEvents.add(usageOnly ? 'fleet-host:usage:changed' : 'fleet-host:changed');+ if (flush) return;+ flush = setTimeout(() => {+ flush = null;+ const events = [...pendingEvents];+ pendingEvents.clear();+ for (const socket of subscribers) {+ if (!socket.connected) continue;+ try {+ for (const event of events) socket.emit(event, {});+ } catch (err) {+ console.error(`❌ Fleet host notification failed: ${err.message}`);+ }+ }+ }, 100);+ flush.unref?.();+}++async function observe() {+ const started = generation;+ const signature = await readFleetHostStatus({ refresh: true })+ .then(value => JSON.stringify(value), () => 'probe-unavailable');+ if (started !== generation || !subscribers.size) return;+ if (previous !== null && previous !== signature) {+ // The sample is already cached; do not discard it and probe again.+ noteFleetHostChanged({ usageOnly: true });+ pendingEvents.add('fleet-host:changed');+ }+ previous = signature;+ timer = setTimeout(() => {+ timer = null;+ observe().catch(err => console.error(`❌ Fleet host observation failed: ${err.message}`));+ }, FLEET_HOST_OBSERVE_MS);+ timer.unref?.();+}++export function registerFleetHostSocket(socket) {+ const release = () => {+ subscribers.delete(socket);+ if (subscribers.size) return;+ generation += 1;+ clearTimeout(timer);+ clearTimeout(flush);+ timer = null;+ flush = null;+ cached = null;+ previous = null;+ pendingEvents.clear();+ };+ socket.on('fleet-host:subscribe', () => {+ const first = subscribers.size === 0;+ subscribers.add(socket);+ if (first) observe().catch(err => console.error(`❌ Fleet host observation failed: ${err.message}`));+ });+ socket.on('fleet-host:unsubscribe', release);+ socket.on('disconnect', release);+}diff --git a/server/services/fleetHostNotify.test.js b/server/services/fleetHostNotify.test.jsnew file mode 100644index 0000000000..6c5c72725b--- /dev/null+++ b/server/services/fleetHostNotify.test.js@@ -0,0 +1,64 @@+import { afterEach, expect, it, vi } from 'vitest';+const read = vi.hoisted(() => vi.fn());+vi.mock('./fleetLlmHost.js', () => ({+ getFleetLlmHostStatus: read,+ getFleetLlmHostQueue: () => ({ active: 1, queued: 2 }),+}));+import { registerFleetHostSocket, readFleetHostStatus, noteFleetHostChanged, FLEET_HOST_OBSERVE_MS } from './fleetHostNotify.js';+const sockets = [];+function connect() {+ const handlers = {};+ const socket = { connected: true, on: (event, fn) => { handlers[event] = fn; }, emit: vi.fn(), handlers };+ registerFleetHostSocket(socket);+ sockets.push(socket);+ return socket;+}+afterEach(() => {+ for (const socket of sockets.splice(0)) socket.handlers.disconnect();+ vi.useRealTimers();+ read.mockReset();+});+it('shares probes across viewers and HTTP reads, reports changed/failing readiness and stops after the last disconnect', async () => {+ vi.useFakeTimers();+ let finish;+ read.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ const a = connect(); const b = connect();+ a.handlers['fleet-host:subscribe']();+ b.handlers['fleet-host:subscribe']();+ const request = readFleetHostStatus();+ await vi.waitFor(() => expect(read).toHaveBeenCalledTimes(1));+ finish({ enabled: false });+ await request;+ read.mockResolvedValue({ enabled: true });+ await vi.advanceTimersByTimeAsync(FLEET_HOST_OBSERVE_MS + 100);+ expect(a.emit).toHaveBeenCalledWith('fleet-host:changed', {});+ expect(b.emit).toHaveBeenCalledWith('fleet-host:changed', {});+ expect(read).toHaveBeenCalledTimes(2);+ await readFleetHostStatus();+ expect(read).toHaveBeenCalledTimes(2);+ a.handlers.disconnect();+ read.mockRejectedValue(new Error('probe unavailable'));+ b.emit.mockClear();+ await vi.advanceTimersByTimeAsync(FLEET_HOST_OBSERVE_MS);+ expect(b.emit).toHaveBeenCalledWith('fleet-host:changed', {});+ b.handlers.disconnect();+ const calls = read.mock.calls.length;+ await vi.advanceTimersByTimeAsync(FLEET_HOST_OBSERVE_MS * 3);+ expect(read).toHaveBeenCalledTimes(calls);+});+it('drains a mutation during a probe and never emits a late sample after unsubscribe', async () => {+ vi.useFakeTimers();+ let finish;+ read.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; })).mockResolvedValue({ enabled: false });+ const a = connect();+ a.handlers['fleet-host:subscribe']();+ const request = readFleetHostStatus();+ await vi.waitFor(() => expect(read).toHaveBeenCalledTimes(1));+ noteFleetHostChanged();+ a.handlers['fleet-host:unsubscribe']();+ finish({ enabled: true });+ await expect(request).resolves.toEqual({ enabled: false });+ await vi.advanceTimersByTimeAsync(FLEET_HOST_OBSERVE_MS * 2);+ expect(a.emit).not.toHaveBeenCalled();+ expect(read).toHaveBeenCalledTimes(2);+});diff --git a/server/services/fleetLlmGateway.js b/server/services/fleetLlmGateway.jsindex 82cefab56b..63fbb97fc6 100644--- a/server/services/fleetLlmGateway.js+++ b/server/services/fleetLlmGateway.js@@ -33,7 +33,7 @@ function requestedModel(body) {// where their GPU went needs to see. Discovery calls (`GET /v1/models`) are NOT// recorded as generations: every connected client polls that on a timer, and// counting them would bury the real traffic.-export function createFleetLlmGateway({ upstream, apiKey, usage = null, onRecorded = () => {}, maxQueued = 16, maxBodyBytes = 2 * 1024 ** 2, waitMs = 120000, runMs = 600000 }) {+export function createFleetLlmGateway({ upstream, apiKey, usage = null, onRecorded = () => {}, onChanged = () => {}, maxQueued = 16, maxBodyBytes = 2 * 1024 ** 2, waitMs = 120000, runMs = 600000 }) {const pending = [];let active = null;let closing = false;@@ -75,6 +75,7 @@ export function createFleetLlmGateway({ upstream, apiKey, usage = null, onRecordconst job = pending.shift();if (!job) return;active = job;+ onChanged();clearTimeout(job.waitTimer);job.runTimer = setTimeout(() => job.controller.abort(), runMs);execute(job).catch(() => reply(job.res, 502, 'Model connection failed or exceeded its time limit.'))@@ -82,6 +83,7 @@ export function createFleetLlmGateway({ upstream, apiKey, usage = null, onRecordclearTimeout(job.runTimer);settle(job, job.status ?? 502);active = null;+ onChanged();pump();});};@@ -132,6 +134,7 @@ export function createFleetLlmGateway({ upstream, apiKey, usage = null, onRecord}// Reserve before reading the body, so concurrent uploads cannot bypass the cap.pending.push(job);+ onChanged();const remove = () => {const index = pending.indexOf(job);if (index >= 0) pending.splice(index, 1);@@ -140,7 +143,7 @@ export function createFleetLlmGateway({ upstream, apiKey, usage = null, onRecord// A job still QUEUED never reaches `pump`'s finally, so close its ledger// entry here. One already running (or already finished) is settled there// instead, and `settle`'s own once-guard makes a second call a no-op.- if (index >= 0) settle(job, job.status ?? 499);+ if (index >= 0) { settle(job, job.status ?? 499); onChanged(); }pump();};res.on('close', remove);@@ -175,6 +178,7 @@ export function createFleetLlmGateway({ upstream, apiKey, usage = null, onRecordsettle(job, 503);}pending.length = 0;+ onChanged();server.closeAllConnections();if (server.listening) await new Promise((resolve) => server.close(resolve));},diff --git a/server/services/fleetLlmGateway.test.js b/server/services/fleetLlmGateway.test.jsindex 9d3eac7299..e3e27d8274 100644--- a/server/services/fleetLlmGateway.test.js+++ b/server/services/fleetLlmGateway.test.js@@ -105,7 +105,8 @@ describe('inbound usage accounting', () => {it('records a completed generation with the model asked for and the tokens the reply reported', async () => {const usage = ledgerDouble();- const { post, received, gateway } = await setup({ usage });+ const changes = [];+ const { post, received, gateway } = await setup({ usage, onChanged: () => changes.push({ queue: gateway.status(), completed: usage.closed.length }) });const pending = post(undefined, JSON.stringify({ model: 'qwen3.8-27b', messages: [] }));await vi.waitFor(() => expect(received).toHaveLength(1));expect(usage.openCount()).toBe(1);@@ -119,6 +120,11 @@ describe('inbound usage accounting', () => {usage: { promptTokens: 12, completionTokens: 34 },});expect(usage.closed[0].handle.path).toBe('/v1/chat/completions');+ await vi.waitFor(() => expect(changes).toEqual(expect.arrayContaining([+ expect.objectContaining({ queue: expect.objectContaining({ queued: 1 }) }),+ expect.objectContaining({ queue: expect.objectContaining({ active: 1 }) }),+ expect.objectContaining({ queue: expect.objectContaining({ active: 0 }), completed: 1 }),+ ])));await vi.waitFor(() => expect(gateway.status().active).toBe(0));});diff --git a/server/services/fleetLlmHost.js b/server/services/fleetLlmHost.jsindex a25c0327ed..230aedc3b9 100644--- a/server/services/fleetLlmHost.js+++ b/server/services/fleetLlmHost.js@@ -1,3 +1,4 @@+import { noteFleetHostChanged } from './fleetHostNotify.js';import { join } from 'node:path';import { readFile } from 'node:fs/promises';import { detectSystemCapabilities } from '../lib/systemCapabilities.js';@@ -66,18 +67,20 @@ export async function startFleetLlmHost() {// recorded against the history already on disk rather than starting a second// ledger that the hydrate would then overwrite.const usage = await getFleetHostUsageLedger();- const next = createFleetLlmGateway({ upstream, apiKey, usage, onRecorded: scheduleFleetHostUsagePersist });+ const next = createFleetLlmGateway({ upstream, apiKey, usage, onRecorded: scheduleFleetHostUsagePersist, onChanged: () => noteFleetHostChanged({ usageOnly: true }) });await new Promise((resolve, reject) => {next.server.once('error', reject);next.server.listen(PORTS.FLEET_LLM, '0.0.0.0', resolve);});next.server.on('error', () => console.error('❌ Fleet inference listener failed'));gateway = next;+ noteFleetHostChanged();}export async function stopFleetLlmHost() {const previous = gateway;gateway = null;+ noteFleetHostChanged();await previous?.close();// The in-flight requests `close()` just cancelled are the newest rows in the// ledger; write them before the listener is gone rather than leaving them to@@ -85,6 +88,10 @@ export async function stopFleetLlmHost() {await flushFleetHostUsage();}+export function getFleetLlmHostQueue() {+ return gateway?.status() || { active: 0, queued: 0, maxActive: 1, maxQueued: 16 };+}+/** Inbound usage, with this host's live admission state folded in. */export async function getFleetLlmHostUsage() {return getFleetHostUsageReport({ queue: gateway?.status() || null });@@ -110,10 +117,15 @@ export async function getFleetLlmHostUsage() {** @returns {Promise<{success: boolean, containerStopped: boolean, error?: string}>}*/-export async function disableFleetLlmHost({ emit = () => {} } = {}) {+export function disableFleetLlmHost(options = {}) {+ return disableHost(options).finally(() => noteFleetHostChanged());+}++async function disableHost({ emit = () => {} } = {}) {emit('Closing the shared API queue — no new peer requests will be admitted.');await stopFleetLlmHost();await upsertPortosEnvLine(ENABLED_KEY, '0');+ noteFleetHostChanged();emit('Disabled the model host for the next restart.');const loginTask = await removeFleetHostLoginTask();@@ -166,7 +178,7 @@ export async function getFleetLlmHostStatus() {stoppable: Boolean(gateway) || Boolean(probe?.reachable) || enabled,endpoint: tailnet.running && tailnet.dnsName ? `http://${tailnet.dnsName}:${PORTS.FLEET_LLM}/v1` : null,model: MODEL, hasApiKey: Boolean(host?.apiKey),- queue: gateway?.status() || { active: 0, queued: 0, maxActive: 1, maxQueued: 16 },+ queue: getFleetLlmHostQueue(),checks: [{ id: 'hardware', label: 'Supported hardware', ok: recommendation.supported },{ id: 'docker', label: 'Docker engine responding', ok: Boolean(docker), detail: docker ? 'Ready' : 'Start Docker Desktop; if it is already running, restart its engine and retry.' },@@ -185,8 +197,8 @@ export async function revealFleetLlmKey() {}export async function getFleetPeerHosts({ timeoutMs = 3000 } = {}) {- const { getPeers } = await import('./instances.js').catch(() => ({ getPeers: async () => [] }));- const peers = await getPeers().catch(() => []);+ const { getPeers } = await import('./instances.js');+ const peers = await getPeers();const candidates = peers.filter((p) => p && p.enabled !== false && p.status !== 'offline');if (candidates.length === 0) return { hosts: [] };@@ -195,9 +207,10 @@ export async function getFleetPeerHosts({ timeoutMs = 3000 } = {}) {return withAbortTimeout(timeoutMs, async (signal) => {const baseUrl = peerBaseUrl(peer);const res = await peerFetch(`${baseUrl}/api/providers/fleet-host`, { signal }, peer);- if (!res.ok) return null;- const status = await res.json().catch(() => null);- if (!status || (!status.serving && !status.enabled)) return null;+ if (!res.ok) throw new Error('Peer host status unavailable');+ const status = await res.json();+ if (!status || typeof status.enabled !== 'boolean' || typeof status.serving !== 'boolean') throw new Error('Invalid peer host status');+ if (!status.serving && !status.enabled) return null;const endpoint = status.endpoint || (peer.host || peer.address? `http://${peer.host || peer.address}:${PORTS.FLEET_LLM}/v1`@@ -216,7 +229,7 @@ export async function getFleetPeerHosts({ timeoutMs = 3000 } = {}) {specs: status.specs || null,queue: status.queue || null,};- }).catch(() => null);+ });}));@@ -224,7 +237,8 @@ export async function getFleetPeerHosts({ timeoutMs = 3000 } = {}) {.filter((r) => r.status === 'fulfilled' && r.value !== null).map((r) => r.value);- return { hosts };+ const unavailable = results.filter(result => result.status === 'rejected').length;+ return { hosts, ...(unavailable ? { unavailable } : {}) };}export async function revealFleetPeerHostKey(peerId, { timeoutMs = 4000 } = {}) {@@ -251,7 +265,8 @@ export async function revealFleetPeerHostKey(peerId, { timeoutMs = 4000 } = {})export async function configureFleetLlmHost({ emit = () => {}, isCancelled = () => false } = {}) {if (setupRunning) throw new Error('Model host setup is already running.');setupRunning = true;- return configure({ emit, isCancelled }).finally(() => { setupRunning = false; });+ noteFleetHostChanged();+ return configure({ emit, isCancelled }).finally(() => { setupRunning = false; noteFleetHostChanged(); });}async function configure({ emit, isCancelled }) {diff --git a/server/services/socket.js b/server/services/socket.jsindex 11e7db8659..992111b16b 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -1,4 +1,5 @@import { registerBrowserStatusSocket } from './browserStatus.js';+import { registerFleetHostSocket } from './fleetHostNotify.js';import { spriteEvents } from './sprites/events.js';import { modelLifecycleEvents } from './modelLifecycleEvents.js';import { meatspaceEvents } from './meatspaceEvents.js';@@ -220,6 +221,7 @@ const SOCKET_HANDLER_REGISTRARS = [registerAuthHandlers,registerReadinessSocket,registerBrowserStatusSocket,+ registerFleetHostSocket,registerVoiceHandlers,registerBuildHandlers,registerImporterHandlers,