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: stop the dedicated Qwen host, and report who is using it
[._.]/ Adam Eivy66d72030490b
diff --git a/client/src/components/providers/FleetHostSetup.jsx b/client/src/components/providers/FleetHostSetup.jsxindex eb711f4aa1..f3246dba54 100644--- a/client/src/components/providers/FleetHostSetup.jsx+++ b/client/src/components/providers/FleetHostSetup.jsx@@ -1,7 +1,8 @@import { useCallback, useEffect, useMemo, useState } from 'react';import { Link } from 'react-router';import { CheckCircle2, HelpCircle, Server, XCircle } from 'lucide-react';-import { getFleetLlmHost, getFleetPeerHosts, revealFleetLlmHostKey } from '../../services/apiProviders';+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';@@ -25,6 +26,14 @@ export default function FleetHostSetup({ compact = false, providers = [], onConfconst [installing, setInstalling] = useState(false);const [key, setKey] = useState('');const [revealing, setRevealing] = useState(false);+ // Two-click stop rather than a `confirm()` (which this codebase does not+ // use): the first click arms, the second acts. Stopping the host cuts off+ // every federated peer currently pointed at it, so it should not be one+ // mis-click away — but it must also never be unreachable, which is the state+ // this whole section is fixing.+ const [stopArmed, setStopArmed] = useState(false);+ const [stopping, setStopping] = useState(false);+ const [stopNote, setStopNote] = useState('');const load = useCallback(() => {getFleetLlmHost({ silent: true }).then((value) => { setStatus(value); setError(''); })@@ -62,6 +71,23 @@ export default function FleetHostSetup({ compact = false, providers = [], onConf.catch(() => setError('Could not read the host API key. Complete host setup first.')).finally(() => setRevealing(false));};+ const stop = () => {+ setStopping(true);+ setStopNote('');+ stopFleetLlmHost({ silent: true })+ .then((result) => {+ setStopArmed(false);+ setStopNote(result?.error+ ? result.error+ : 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();+ 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 title = status?.recommendation.title || 'Recommended model host setup';if (compact) {@@ -149,6 +175,34 @@ export default function FleetHostSetup({ compact = false, providers = [], onConf<p className="mt-1 text-xs">{status.queue.active} generating · {status.queue.queued} queued · limit {status.queue.maxActive} active / {status.queue.maxQueued} waiting</p></Banner>)}+ {/* Offered whenever there is anything to turn off — a listening+ queue, a container answering on the runtime port, or just the+ enable marker that would start both again at the next boot.+ Gating this on `serving` would hide it in exactly the state that+ made the host feel unstoppable: container up, model still loading. */}+ {status.stoppable && (+ <section className="rounded-lg border border-port-border p-3 space-y-2 text-sm" aria-label="Stop this machine's model host">+ <h3 className="font-medium">Stop hosting on this machine</h3>+ <p className="text-xs text-gray-400">+ Closes the shared API queue, turns the host off for future restarts, removes the Windows login-recovery task, and stops and removes the vLLM container. The prepared image and weights stay on disk. Any federated instance using this host loses it immediately, and any generation in flight is cancelled.+ </p>+ <div className="flex flex-wrap gap-2 items-center">+ <button+ type="button"+ disabled={stopping || status.setupRunning}+ onClick={() => (stopArmed ? stop() : setStopArmed(true))}+ className={`inline-flex items-center justify-center min-h-[40px] px-3 py-2 rounded-lg text-sm disabled:opacity-50 ${stopArmed ? 'bg-port-error text-white' : 'bg-port-border text-white'}`}+ >+ {stopping ? 'Stopping…' : stopArmed ? 'Confirm stop — disconnect peers now' : 'Stop model host'}+ </button>+ {stopArmed && !stopping && (+ <button type="button" onClick={() => setStopArmed(false)} className="min-h-[40px] px-3 text-sm text-gray-400">Cancel</button>+ )}+ </div>+ {stopNote && <Banner tone="info">{stopNote}</Banner>}+ </section>+ )}+ {(status.enabled || status.listening) && <FleetHostUsage />}{status.hasApiKey && status.endpoint && (<section className="space-y-2 text-sm"><h3 className="font-medium">Use this host from this same machine</h3>diff --git a/client/src/components/providers/FleetHostSetup.test.jsx b/client/src/components/providers/FleetHostSetup.test.jsxindex 9d6c155a21..15035efbc3 100644--- a/client/src/components/providers/FleetHostSetup.test.jsx+++ b/client/src/components/providers/FleetHostSetup.test.jsx@@ -1,10 +1,12 @@import { describe, expect, it, vi } from 'vitest';-import { render, screen, fireEvent } from '@testing-library/react';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';import { MemoryRouter } from 'react-router';const api = vi.hoisted(() => ({getFleetLlmHost: vi.fn(),+ getFleetLlmHostUsage: vi.fn(),getFleetPeerHosts: vi.fn(),revealFleetLlmHostKey: vi.fn(),+ stopFleetLlmHost: vi.fn(),}));vi.mock('../../services/apiProviders', () => api);vi.mock('../install/RuntimeInstallModal', () => ({ default: ({ open, installUrlBase, streamMethod }) => open ? <div data-testid="setup" data-url={installUrlBase} data-method={streamMethod} /> : null }));@@ -49,6 +51,56 @@ describe('dedicated model host setup', () => {expect(await screen.findByRole('link', { name: 'Manage model servers' })).toHaveAttribute('href', href);});+ // The reported bug: the host was enabled from this page, the machine was+ // running and serving, and there was no control anywhere that turned it off.+ it('offers a two-step stop whenever there is something to turn off, and only acts on the second click', async () => {+ api.getFleetLlmHost.mockResolvedValue({ ...state, enabled: true, listening: true, serving: false, stoppable: true });+ api.getFleetLlmHostUsage.mockResolvedValue({ activeRequests: 0, clients: [], recent: [], totals: {}, queue: null });+ api.getFleetPeerHosts.mockResolvedValue({ hosts: [] });+ api.stopFleetLlmHost.mockResolvedValue({ success: true, containerStopped: true });+ render(<MemoryRouter><FleetHostSetup /></MemoryRouter>);++ const arm = await screen.findByRole('button', { name: 'Stop model host' });+ fireEvent.click(arm);+ // Arming alone must not disconnect anyone.+ expect(api.stopFleetLlmHost).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: /Confirm stop/ }));+ await waitFor(() => expect(api.stopFleetLlmHost).toHaveBeenCalledTimes(1));+ expect(await screen.findByText(/image and weights are still on disk/)).toBeInTheDocument();+ });++ it('hides the stop control on a machine that has nothing hosting', async () => {+ api.getFleetLlmHost.mockResolvedValue({ ...state, enabled: false, listening: false, stoppable: false });+ api.getFleetPeerHosts.mockResolvedValue({ hosts: [] });+ render(<MemoryRouter><FleetHostSetup /></MemoryRouter>);+ await screen.findByText(/32 GB RAM/);+ expect(screen.queryByRole('button', { name: 'Stop model host' })).not.toBeInTheDocument();+ });++ it('names the machines using this host, flagging one that matches no peer or tailnet node', async () => {+ api.getFleetLlmHost.mockResolvedValue({ ...state, enabled: true, listening: true, stoppable: true });+ api.getFleetPeerHosts.mockResolvedValue({ hosts: [] });+ api.getFleetLlmHostUsage.mockResolvedValue({+ activeRequests: 1,+ queue: { active: 1, queued: 2 },+ totals: { requests: 40, errors: 0, tokenReports: 12, promptTokens: 1000, completionTokens: 2762 },+ clients: [+ { address: '192.0.2.10', label: 'Workstation GPU', known: true, activeRequests: 1, requests: 30, errors: 0, tokenReports: 12, promptTokens: 1000, completionTokens: 2762, models: ['qwen3.8-27b'], lastSeen: Date.now(), days: [] },+ { address: '192.0.2.99', label: null, known: false, activeRequests: 0, requests: 10, errors: 1, tokenReports: 0, promptTokens: 0, completionTokens: 0, models: [], lastSeen: Date.now(), days: [] },+ ],+ recent: [],+ });+ render(<MemoryRouter><FleetHostSetup /></MemoryRouter>);++ expect(await screen.findByText('Workstation GPU')).toBeInTheDocument();+ expect(screen.getByText('192.0.2.99')).toBeInTheDocument();+ expect(screen.getByText('Unrecognized')).toBeInTheDocument();+ // Thousands-grouped, and the partial token coverage is stated rather than+ // implying the other 28 requests were free.+ expect(screen.getByText('2,762')).toBeInTheDocument();+ expect(screen.getByText('12 of 40 reported counts')).toBeInTheDocument();+ });+it('keeps unsupported hardware on a connection path without offering the CUDA installer', async () => {api.getFleetLlmHost.mockResolvedValue({ ...state, recommendation: { supported: false, title: 'Connect to a model host' } });api.getFleetPeerHosts.mockResolvedValue({ hosts: [] });diff --git a/client/src/components/providers/FleetHostUsage.jsx b/client/src/components/providers/FleetHostUsage.jsxnew file mode 100644index 0000000000..0b511ed5c9--- /dev/null+++ b/client/src/components/providers/FleetHostUsage.jsx@@ -0,0 +1,152 @@+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 { formatCount, formatDurationMs, timeAgo } from '../../utils/formatters';+import Banner from '../ui/Banner';++/**+ * Who is using this machine's GPU.+ *+ * The host's own status card already answers "am I serving?" with a queue+ * depth. This answers the question underneath it — WHICH machine is spending+ * the GPU, how much of it, and when — because on a shared host the depth alone+ * cannot tell an operator whether their own agent or a federated peer is the+ * reason a generation is waiting.+ *+ * Every client is keyed by its address; the label beside it is resolved on the+ * 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 });++ const clients = report?.clients || [];+ const totals = report?.totals;++ return (+ <section className="space-y-3 text-sm" aria-label="Model host usage">+ <div className="flex items-center justify-between gap-2">+ <h3 className="font-medium flex items-center gap-2"><Activity size={16} className="text-port-accent" />Who is using this host</h3>+ <button+ type="button"+ onClick={load}+ disabled={loading}+ className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1.5 text-gray-400 hover:text-white"+ title="Refresh host usage"+ aria-label="Refresh host usage"+ >+ <RefreshCw size={14} className={loading ? 'animate-spin' : ''} />+ </button>+ </div>++ {error && <Banner tone="error">{error}</Banner>}++ {report && (+ <>+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">+ <Stat label="Generating now" value={formatCount(report.activeRequests, { fallback: '0' })} accent={report.activeRequests > 0} />+ <Stat label="Waiting" value={formatCount(report.queue?.queued ?? 0, { fallback: '0' })} />+ <Stat label="Requests served" value={formatCount(totals?.requests, { fallback: '0' })} />+ <Stat+ label="Tokens generated"+ value={formatCount(totals?.completionTokens, { fallback: '0' })}+ note={totals?.requests > 0 && totals.tokenReports < totals.requests+ ? `${formatCount(totals.tokenReports, { fallback: '0' })} of ${formatCount(totals.requests, { fallback: '0' })} reported counts`+ : null}+ />+ </div>++ {clients.length === 0 ? (+ <p className="text-xs text-gray-400">+ No machine has called this host yet. Counts start at the first request and are kept for 30 days.+ </p>+ ) : (+ <ul className="space-y-2">+ {clients.map((client) => (+ <li key={client.address} className="rounded-lg border border-port-border bg-port-bg p-3 space-y-1">+ <div className="flex items-center gap-2 flex-wrap">+ {client.activeRequests > 0+ ? <span className="flex h-2 w-2 rounded-full bg-port-success animate-pulse shrink-0" title="Generating right now" />+ : <span className="flex h-2 w-2 rounded-full bg-port-border shrink-0" />}+ <Server size={14} className="text-port-accent shrink-0" />+ <span className="text-white truncate">{client.label || client.address}</span>+ {!client.known && (+ <span className="inline-flex items-center gap-1 text-[11px] px-1.5 py-0.5 rounded bg-port-warning/20 text-port-warning" title="This address matches no federated peer and no node on this tailnet">+ <AlertTriangle size={11} />Unrecognized+ </span>+ )}+ {client.activeRequests > 0 && (+ <span className="text-[11px] px-1.5 py-0.5 rounded bg-port-success/20 text-port-success">+ {formatCount(client.activeRequests, { fallback: '0' })} generating+ </span>+ )}+ </div>+ <p className="text-xs text-gray-400">+ {formatCount(client.requests, { fallback: '0' })} requests+ {' · '}{formatCount(client.promptTokens, { fallback: '0' })} prompt / {formatCount(client.completionTokens, { fallback: '0' })} generated tokens+ {client.tokenReports < client.requests && ` (counts from ${formatCount(client.tokenReports, { fallback: '0' })})`}+ {client.errors > 0 && ` · ${formatCount(client.errors, { fallback: '0' })} failed`}+ {' · last used '}{timeAgo(client.lastSeen)}+ </p>+ {client.models.length > 0 && (+ <p className="text-xs text-gray-500 truncate">Models: {client.models.join(', ')}</p>+ )}+ </li>+ ))}+ </ul>+ )}++ {report.recent.length > 0 && (+ <details className="rounded-lg border border-port-border bg-port-bg p-3">+ <summary className="cursor-pointer text-xs text-gray-400">Recent requests ({formatCount(report.recent.length, { fallback: '0' })})</summary>+ <ul className="mt-2 space-y-1">+ {report.recent.map((event) => (+ <li key={event.id} className="text-xs text-gray-400 flex flex-wrap gap-x-2">+ <span className="text-gray-300">{event.label || event.address}</span>+ <span>{timeAgo(event.finishedAt)}</span>+ <span>{formatDurationMs(event.durationMs)}</span>+ {/* Null means the response reported no counts, which is not the same as zero. */}+ <span>{event.completionTokens === null ? 'tokens not reported' : `${formatCount(event.completionTokens, { fallback: '0' })} tokens`}</span>+ {typeof event.status === 'number' && event.status >= 400 && (+ <span className="text-port-warning">HTTP {event.status}</span>+ )}+ </li>+ ))}+ </ul>+ </details>+ )}++ <p className="text-xs text-gray-500">+ Counted at the shared API queue, so it covers every machine using this host — including this one. Token counts come from the model's own reply and are missing for a streamed request whose client did not ask for them. Nothing from a request or its response is stored.+ </p>+ </>+ )}+ </section>+ );+}++function Stat({ label, value, note, accent = false }) {+ return (+ <div className="rounded-lg border border-port-border bg-port-bg px-3 py-2">+ <p className={`text-lg font-semibold ${accent ? 'text-port-success' : 'text-white'}`}>{value}</p>+ <p className="text-xs text-gray-400">{label}</p>+ {note && <p className="text-[11px] text-gray-500 mt-0.5">{note}</p>}+ </div>+ );+}diff --git a/client/src/components/settings/LocalLlmRuntimesView.jsx b/client/src/components/settings/LocalLlmRuntimesView.jsxindex f091aeb561..5961ee64ce 100644--- a/client/src/components/settings/LocalLlmRuntimesView.jsx+++ b/client/src/components/settings/LocalLlmRuntimesView.jsx@@ -8,6 +8,7 @@ import { formatBytes } from '../../utils/formatters';import useDownloadPreflightConfirm from '../../hooks/useDownloadPreflightConfirm';import useLocalLlmStatus from '../../hooks/useLocalLlmStatus';import { migrateLocalLlmBackend, controlOllamaService, patchSettingsSlice, getLlamaServerStatus, getLlamaServerUpdateStatus, startLlamaServer, stopLlamaServer, installLlamaServer, upgradeLlamaServer, downloadSpecDecodeModel, cancelSpecDecodeModelDownload, removeSpecDecodeModel, previewLocalLlmDownload, controlLmStudioService, getMtplxServerStatus, startMtplxServer, stopMtplxServer, installMtplx, searchMtplxModels, pullMtplxModel, removeMtplxModel, getSlotstreamServerStatus, startSlotstreamServer, stopSlotstreamServer, installSlotstream, downloadSlotstreamModel, cancelSlotstreamModelDownload, saveRuntimeStartupList } from '../../services/api';+import { getFleetLlmHost, stopFleetLlmHost } from '../../services/apiProviders';import socket from '../../services/socket';import SpecDecodeWeightRow from './SpecDecodeWeightRow.jsx';import RuntimeServersCard from './RuntimeServersCard.jsx';@@ -76,6 +77,11 @@ export default function LocalLlmRuntimesView() {const [llamaStatus, setLlamaStatus] = useState(null);const [mtplxStatus, setMtplxStatus] = useState(null);const [slotstreamStatus, setSlotstreamStatus] = useState(null);+ // The dedicated Qwen host is a docker container rather than a PM2 process, so+ // it is not part of the shared local-LLM status payload — but it IS a local+ // model server, and this is the page an operator comes to when they want to+ // stop one (#7414 moved every other lifecycle control here).+ const [fleetHostStatus, setFleetHostStatus] = useState(null);// Live byte progress for an in-flight `mtplx pull`, driven by the socket. One// at a time on purpose: a checkpoint is tens of gigabytes, so two concurrent// pulls just make both slower.@@ -171,11 +177,21 @@ export default function LocalLlmRuntimesView() {// The three managed runtimes refresh alongside the shared status, so one// Refresh — or one completed action — repaints every row on this view.+ const loadFleetHostStatus = useCallback(() => (+ getFleetLlmHost({ silent: true })+ .then((res) => { if (res) setFleetHostStatus(res); return res; })+ // Silent by design: this row is one of several on a shared card, and a+ // machine with no dedicated host configured must not toast on every+ // refresh of the page.+ .catch(() => null)+ ), []);+const refreshRuntimes = useCallback(() => {loadLlamaStatus();loadMtplxStatus();loadSlotstreamStatus();- }, [loadLlamaStatus, loadMtplxStatus, loadSlotstreamStatus]);+ loadFleetHostStatus();+ }, [loadLlamaStatus, loadMtplxStatus, loadSlotstreamStatus, loadFleetHostStatus]);const {status, loading, loadStatus, runAction, installBackend: installRuntimeBackend,actionInProgress, busy, progressMsg, confirmAction, setConfirmAction,@@ -290,6 +306,20 @@ export default function LocalLlmRuntimesView() {{ start: 'Ollama is running', stop: 'Ollama stopped', enable: 'Ollama will run at login', disable: 'Ollama background service disabled' }[action],{ ollamaService: true });+ // Not silent: a failed stop must say so, and this row has no banner of its+ // own to put it in. The two-step "confirm — disconnect peers now" gate lives+ // on the host setup page, which is also where the inbound-usage report shows+ // who would be cut off; this row is the same one-click Stop the other+ // runtimes on this card offer.+ const stopFleetHost = () => runAction(+ 'runtime-stop-fleet-host',+ () => stopFleetLlmHost(),+ (result) => (result?.error+ ? result.error+ : result?.containerStopped+ ? 'Dedicated Qwen host stopped and its container removed'+ : 'Dedicated Qwen host disabled'),+ ).then(loadFleetHostStatus);const controlLmStudio = (action) => runAction(`runtime-${action}-lmstudio`,() => controlLmStudioService(action),@@ -720,6 +750,8 @@ export default function LocalLlmRuntimesView() {onSaveStartup={saveRuntimeStartup}onSaveIdleWindow={saveIdleWindow}onToggleKeepLoaded={toggleKeepLoaded}+ fleetHostStatus={fleetHostStatus}+ onStopFleetHost={stopFleetHost}/><LocalPersistentMindSetupCard /><HardwareLlmRecommendation />diff --git a/client/src/components/settings/LocalLlmRuntimesView.test.jsx b/client/src/components/settings/LocalLlmRuntimesView.test.jsxindex dac7fff09d..bce52f5a4c 100644--- a/client/src/components/settings/LocalLlmRuntimesView.test.jsx+++ b/client/src/components/settings/LocalLlmRuntimesView.test.jsx@@ -49,6 +49,12 @@ vi.mock('../../services/api', () => ({cancelSpecDecodeModelDownload: vi.fn(),removeSpecDecodeModel: vi.fn(),}));+// The dedicated Qwen host is a docker container, so its status comes from the+// providers API rather than the local-LLM status payload above.+vi.mock('../../services/apiProviders', () => ({+ getFleetLlmHost: vi.fn().mockResolvedValue({ enabled: false, listening: false, runtimeReachable: false, stoppable: false, recommendation: { supported: true } }),+ stopFleetLlmHost: vi.fn().mockResolvedValue({ success: true, containerStopped: true }),+}));vi.mock('../../services/socket', () => ({default: { on: vi.fn(), off: vi.fn() },}));@@ -64,6 +70,7 @@ import {installLocalLlmBackend,patchSettingsSlice,} from '../../services/api';+import { getFleetLlmHost, stopFleetLlmHost } from '../../services/apiProviders';import socket from '../../services/socket';import { clickStartDownload } from '../../test/downloadPreflightConfirm.js';import LocalLlmRuntimesView from './LocalLlmRuntimesView.jsx';@@ -1050,4 +1057,39 @@ describe('LocalLlmRuntimesView llama-server management', () => {expect(await screen.findByText(/pulling manifest/)).toBeInTheDocument();});});++ // The reported dead end: the dedicated Qwen host is enabled from AI Providers+ // and runs as a docker container, so it appeared on no runtime list at all —+ // an operator who came here to stop a local model server found every one they+ // were NOT running and no sign of the one they were.+ describe('dedicated Qwen host row', () => {+ it('shows the host as running and stops it on request', async () => {+ getFleetLlmHost.mockResolvedValue({+ enabled: true,+ listening: true,+ runtimeReachable: true,+ serving: true,+ stoppable: true,+ endpoint: 'http://host-XXXX.example.ts.net:18022/v1',+ queue: { active: 1, queued: 0 },+ recommendation: { supported: true },+ });+ await renderRuntimes();++ const row = screen.getByText('Dedicated Qwen host').closest('div').parentElement;+ expect(within(row).getByText('Running')).toBeInTheDocument();+ expect(within(row).getByText('1 generating · 0 queued')).toBeInTheDocument();++ fireEvent.click(within(row).getByRole('button', { name: /Stop/ }));+ await waitFor(() => expect(stopFleetLlmHost).toHaveBeenCalledTimes(1));+ });++ it('offers no Stop on a machine that is not hosting, and still links to the setup page', async () => {+ getFleetLlmHost.mockResolvedValue({ enabled: false, listening: false, runtimeReachable: false, stoppable: false, recommendation: { supported: true } });+ await renderRuntimes();+ const row = screen.getByText('Dedicated Qwen host').closest('div').parentElement;+ expect(within(row).queryByRole('button', { name: /Stop/ })).not.toBeInTheDocument();+ expect(within(row).getByRole('link', { name: 'Set up host' })).toHaveAttribute('href', '/ai/fleet?fleetStep=host');+ });+ });});diff --git a/client/src/components/settings/RuntimeServersCard.jsx b/client/src/components/settings/RuntimeServersCard.jsxindex 0156c52c43..767a07d4a0 100644--- a/client/src/components/settings/RuntimeServersCard.jsx+++ b/client/src/components/settings/RuntimeServersCard.jsx@@ -1,6 +1,6 @@import { useEffect, useState } from 'react';import { Link } from 'react-router';-import { Cpu, Box, Zap, Gauge, HardDrive, Play, Square, Download, ArrowUpCircle, Power, PowerOff, RefreshCw, Save, Settings2, ExternalLink } from 'lucide-react';+import { Cpu, Box, Zap, Gauge, HardDrive, Play, Square, Download, ArrowUpCircle, Power, PowerOff, RefreshCw, Save, Settings2, ExternalLink, Server } from 'lucide-react';import BrailleSpinner from '../BrailleSpinner';/**@@ -98,6 +98,44 @@ function pm2Row({ id, label, icon, status, platformReason, onStart, onStop, onIn};}+/**+ * The dedicated Qwen host — the one runtime on this page PortOS runs as a+ * DOCKER container rather than a PM2 process.+ *+ * It belongs here for the same reason as the rest: it is a local model server,+ * it is either up or it is not, and it can be stopped. Leaving it off was a+ * real dead end — enabling it lives on AI Providers → Model host setup, so an+ * operator who later came to the page named "Runtimes" to turn their GPU loose+ * again found every server they were NOT running and no sign of the one they+ * were.+ *+ * `onStart` is deliberately absent: a first start can mean cloning a compose+ * project and downloading ~30 GB, and the decision (and its progress stream)+ * belongs on the setup page that names the payload. Getting OUT does not need+ * that ceremony, so Stop is here.+ */+function fleetHostRow({ status, onStop }) {+ const up = Boolean(status?.listening || status?.runtimeReachable);+ const state = up ? 'running'+ : status?.enabled ? 'stopped'+ : status?.recommendation?.supported === false ? 'unsupported' : 'missing';+ return {+ id: 'fleet-host',+ label: 'Dedicated Qwen host',+ icon: Server,+ state,+ endpoint: status?.endpoint || null,+ detail: !up && status?.recommendation?.supported === false+ ? status.recommendation.title+ : up && !status?.serving+ ? 'Container up, model still loading'+ : up && status?.queue+ ? `${status.queue.active} generating · ${status.queue.queued} queued`+ : null,+ onStop: status?.stoppable ? onStop : null,+ };+}+/*** The per-daemon "release the model when nothing is using it" window.*@@ -303,6 +341,8 @@ export default function RuntimeServersCard({onSaveStartup,onSaveIdleWindow,onToggleKeepLoaded,+ fleetHostStatus,+ onStopFleetHost,}) {// Read off each daemon's own status payload — the same place `runAtStartup`// and Ollama's `disabled` come from — so there is no second settings fetch on@@ -399,6 +439,9 @@ export default function RuntimeServersCard({&& `${slotstreamStatus.cachedModels.length} checkpoint${slotstreamStatus.cachedModels.length === 1 ? '' : 's'} cached`,].filter(Boolean).join(' · ') || null,}),+ // Last, and only once its status has landed: an absent payload would+ // otherwise render a "Not installed" row for a host that is serving.+ ...(fleetHostStatus ? [fleetHostRow({ status: fleetHostStatus, onStop: onStopFleetHost })] : []),];return (@@ -422,6 +465,16 @@ export default function RuntimeServersCard({<div className="space-y-2">{rows.map((row) => (<ServerRow key={row.id} row={row} busy={busy} actionInProgress={actionInProgress}>+ {row.id === 'fleet-host' && (+ <Link+ to="/ai/fleet?fleetStep=host"+ className={`${neutralBtn} no-underline`}+ title="Set up, reconfigure or inspect the dedicated Qwen host and its inbound usage"+ >+ <Settings2 size={12} />+ {fleetHostStatus?.stoppable ? 'Host setup & usage' : 'Set up host'}+ </Link>+ )}{row.id === 'ollama' && ollamaService?.supported && (<buttononClick={() => onControlOllama(ollamaRunsAtStartup ? 'disable' : 'enable')}diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 40b2a60ca7..fcc6b5b203 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -53,7 +53,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiPorts.js` | Port scan/detect wrappers (no current UI callers; module kept for the catalog). || `apiHarnesses.js` | Coding-agent harness (CLI/TUI) inventory for Models → Harnesses: installed vs latest version, the providers riding on each, and the model-catalog refresh. Install/update/remove is an SSE stream driven by `RuntimeInstallModal`, not a call here. || `apiModelComparison.js` | Sourced model comparison catalog, provider discovery and validated observation import. |-| `apiProviders.js` | AI provider configuration, plus provider-runtime (CLI) install readiness for the per-card Install buttons, and the Codex / ChatGPT-subscription account calls (`getCodexAccount`, `startCodexLogin`, `cancelCodexLogin`, `codexLogout`) — sign-in STATE only, never a token. `getProviderCatalog` (`GET /providers/catalog`, #7566) is the composition surface `useProviderCatalog` fetches; `createProviderPreset` (`POST /providers/presets`) is the compose popover's "Save as preset". The AI Providers page's three axes (#7567): `setProviderHarnessEnabled` (per-harness enablement; the read rides `getProviderCatalog`), `getProviderBootstraps` / `saveProviderBootstraps` (credential-bootstrap apps), and the service-instance calls (`getProviderServiceDefinitions`, `getProviderServices`, `createProviderService`, `updateProviderService`, `deleteProviderService`, `refreshProviderServiceCatalog`) — every response credential-free, and only the explicit catalog refresh contacts a provider. |+| `apiProviders.js` | AI provider configuration, plus provider-runtime (CLI) install readiness for the per-card Install buttons, and the Codex / ChatGPT-subscription account calls (`getCodexAccount`, `startCodexLogin`, `cancelCodexLogin`, `codexLogout`) — sign-in STATE only, never a token. `getProviderCatalog` (`GET /providers/catalog`, #7566) is the composition surface `useProviderCatalog` fetches; `createProviderPreset` (`POST /providers/presets`) is the compose popover's "Save as preset". The AI Providers page's three axes (#7567): `setProviderHarnessEnabled` (per-harness enablement; the read rides `getProviderCatalog`), `getProviderBootstraps` / `saveProviderBootstraps` (credential-bootstrap apps), and the service-instance calls (`getProviderServiceDefinitions`, `getProviderServices`, `createProviderService`, `updateProviderService`, `deleteProviderService`, `refreshProviderServiceCatalog`) — every response credential-free, and only the explicit catalog refresh contacts a provider. The dedicated-host calls are `getFleetLlmHost` / `getFleetLlmHostUsage` (who is using this machine's GPU right now, and what each caller has spent) / `stopFleetLlmHost` (close the queue, clear the enable marker, drop the Windows login task, remove the container) / `revealFleetLlmHostKey`, plus the peer-side `getFleetPeerHosts` and `revealFleetPeerHostKey`. || `apiPrompts.js` | Prompt Manager: stage templates, variables, and job-skill templates (providers list reuses `apiProviders.getProviders`). || `apiReferenceRepos.js` | Per-app reference-repo registry. || `apiReview.js` | Review hub. |diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.jsindex 5fcdde672e..c0ed8b9c4c 100644--- a/client/src/services/apiProviders.js+++ b/client/src/services/apiProviders.js@@ -178,5 +178,7 @@ export const getCodexModels = (options = {}) => {export const getFleetLlmHost = (options) => request('/providers/fleet-host', options);export const revealFleetLlmHostKey = (options) => request('/providers/fleet-host/key', { method: 'POST', ...options });+export const getFleetLlmHostUsage = (options) => request('/providers/fleet-host/usage', options);+export const stopFleetLlmHost = (options) => request('/providers/fleet-host/stop', { method: 'POST', ...options });export const getFleetPeerHosts = (options) => request('/providers/fleet-peer-hosts', options);export const revealFleetPeerHostKey = (peerId, options) => request(`/providers/fleet-peer-hosts/${encodeURIComponent(peerId)}/key`, { method: 'POST', ...options });diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex e1edd0150a..1e8a8acf5e 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -261,7 +261,9 @@ Apply this checklist to **every new feature that persists data**, and require it### Dedicated inference host-`PORTOS_FLEET_LLM_ENABLED` in the install `.env` is machine-local deployment configuration, alongside `VLLM_QWEN_PROJECT_DIR`. The existing runtime project holds its API key, compose override and model weights; none enters federation sync. Provider records use the existing provider store. The bounded inference queue exists only in memory, with no prompt/response persistence and no restart replay. No new app-native data store or migration is introduced.+`PORTOS_FLEET_LLM_ENABLED` in the install `.env` is machine-local deployment configuration, alongside `VLLM_QWEN_PROJECT_DIR`. The existing runtime project holds its API key, compose override and model weights; none enters federation sync. Provider records use the existing provider store. The bounded inference queue exists only in memory, with no prompt/response persistence and no restart replay.++`data/fleet-host-usage.json` is `file-primary`: the host's INBOUND usage ledger — which machines have called this install's shared inference endpoint, how many requests each made, the token counts their responses reported, 30 days of daily buckets and the last 50 completed requests. It is a bounded counter document, not a relational record set: no foreign keys to app records, no cross-record queries, no search index, and it is rewritten whole by `services/fleetLlmUsage.js` behind a debounce. It is deliberately **machine-local and never federated** — it describes who connected to *this* machine, which is network and identity information about the user's own devices, and each host's answer is only about itself. Clients are keyed by remote address because the gateway authenticates every caller with one shared host key; peer names are resolved at read time from the peer list and the tailnet, never stored. No prompt or response content is ever written. Schema version 1; a payload declaring any other version is refused rather than half-read, so no migration or `data.reference/` seed is needed (an install with no file simply starts counting). Rsync backups include it.### Model comparison reference snapshotdiff --git a/docs/features/fleet-llm-host.md b/docs/features/fleet-llm-host.mdindex 2ad24c28cc..9198732e12 100644--- a/docs/features/fleet-llm-host.md+++ b/docs/features/fleet-llm-host.md@@ -67,7 +67,33 @@ Restrict `:18022` to your clients using Tailscale/network rules. Existing instalOne inference request runs at a time across clients, with at most 16 waiting requests. Waiting expires after two minutes with HTTP 429 and Retry-After; active requests have a ten-minute ceiling. Bodies are limited to 2 MiB. SSE streams pass through, disconnects cancel work, and requests are never persisted or replayed after restart. Each model call acquires a slot; a coding agent's tool execution happens on its client and does not hold a GPU slot. The underlying runtime also uses one sequence as a backstop. Direct runtime calls bypass the gateway and should be reserved for local diagnostics.-To revert dedicated hosting, set `PORTOS_FLEET_LLM_ENABLED=0` in the install's `.env`, restart PortOS, stop the Qwen container, and re-enable the desired providers. This does not delete weights or provider settings.+### Stopping the host++**AI Providers → Model host setup → Stop hosting on this machine**, or the **Dedicated Qwen host** row on **Models → Runtimes**. Both call the same action, which undoes all four things setup armed:++1. closes the shared API queue, so no new peer request is admitted (anything in flight is cancelled);+2. writes `PORTOS_FLEET_LLM_ENABLED=0`, so the queue does not return on the next restart;+3. removes the Windows login-recovery task;+4. stops **and removes** the vLLM container.++Step 4 removes rather than merely stops because setup writes the container with `restart: unless-stopped` — a stopped container comes back the next time the Docker engine starts, which is why turning the host off used to feel impossible. The prepared image and the ~20 GB of weights stay on disk, so starting again takes minutes, not another download.++If Docker is not answering, the first three steps still happen and the action reports that the container could not be stopped — the host is disabled either way. Providers that setup disabled stay disabled; re-enable the ones you want on the AI Providers page.++The setup-page button arms on the first click and acts on the second ("Confirm stop — disconnect peers now"), because stopping cuts off every federated client immediately. The Runtimes row is a one-click Stop like the other runtimes on that card.++### Seeing who is using the host++The host panel shows a **Who is using this host** report while hosting is enabled, read from `GET /api/providers/fleet-host/usage`:++- how many generations are running and waiting right now;+- one row per calling machine — requests, prompt and generated token totals, failures, and when it was last active;+- a live dot on any machine generating at that moment, so a busy GPU can be attributed rather than guessed at;+- the last 50 completed requests, with duration, model and status.++Callers are keyed by their address (every client authenticates with the one shared host key, so the wire carries no per-peer identity) and named from the peer list, falling back to the tailnet's node name. An address matching neither is shown as **Unrecognized** rather than hidden — an unknown machine holding the host key is the case worth seeing.++Token counts come from the model's own reply. A streamed request whose client did not ask for usage reports none, so a row can show requests with no tokens; the panel states how many requests carried counts rather than implying the rest were free. Nothing from a request or response body is stored — the ledger is counts, timestamps, a model id and an HTTP status, kept for 30 days in `data/fleet-host-usage.json` and never federated.## Client setupdiff --git a/server/lib/README.md b/server/lib/README.mdindex 24334efd01..a494006fc5 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -236,6 +236,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `credentialRegistry.js` | Pure catalog of PortOS credentials (`CREDENTIALS`, `CREDENTIAL_IDS`, `CREDENTIAL_TIERS`) — one entry per key/token an install can use (`id`, `label`, `unlocks`, `tier`, `getUrl`, `envVars`, `settingsPath`, `configurePath`, optional `feature`). Sits beside `instanceFeatureRegistry.js` so the two lists stay greppable together. Runtime resolution (settings / repo `.env` / inherited `process.env` / CLI / instance config) lives in `services/credentialInventory.js`. The Settings > Credentials page never receives a value or masked prefix. || `instanceFeatureRegistry.js` | The registry of optional per-install features (`INSTANCE_FEATURES`, `INSTANCE_FEATURE_IDS`, `APP_FEATURE_IDS`) — pure data, so `validation.js` derives its feature schemas from it and `navManifest.js` can be checked against it without a service→lib inversion. Runtime resolution (stored override → auto-detection → `defaultEnabled`) lives in `services/instanceFeatures.js`. A feature id tagged on a nav entry hides that page from ⌘K and the sidebar when the feature is off. || `providerFamilies.js` | Subscription-quota FAMILY identity — `PROVIDER_FAMILIES` (`{ id, label, idPattern, matches }` for claude/codex/agy/grok), `PROVIDER_FAMILY_IDS`, `familyLabel`, `familyForProvider(config)`, `familyForProviderId(id)` (the weaker id-only classifier a Zod schema can use, null when the id names no family) → family id or null (local-runtime wrappers and API-only providers belong to none). The pure half of the registry `services/providerUsage.js` attaches quota `fetch`ers to, so cost attribution and route validation can ask "which plan is this provider on?" without importing the PTY-scrape graph. Distinct from `providerVendors.js`, which is argv-shaped and includes vendors with no subscription quota. |+| `fleetHostUsage.js` | The INBOUND side of the dedicated inference host — who is spending this machine's GPU. `createFleetHostUsageLedger({ now, maxClients, maxRecent, retentionDays })` → `beginRequest` / `endRequest` / `snapshot` / `toJSON` / `hydrate`: a bounded per-client ledger keyed by the socket's remote address (the gateway authenticates every peer with ONE shared host key, so the wire carries no per-peer identity), holding request/error counts, observed token totals, 30 days of daily buckets and the last 50 completed requests. `findReportedUsage(text)` lifts the LAST `usage` object out of an OpenAI-compatible body, searched backwards because a `stream_options.include_usage` stream emits `"usage": null` on every frame before the populated one; `createUsageSniffer()` is the bounded 64 KB tail buffer the gateway taps a response stream with. Tokens are recorded only where the upstream reported them — `tokenReports` counts how many requests carried a reading, so the report can say "12 of 40" rather than implying the rest were free. No prompt or completion text is ever held. Peer NAMES are resolved at report time by `services/fleetLlmUsage.js`; contrast `fleetQuotas.js`, which merges this install's OUTBOUND subscription quotas. || `fleetQuotas.js` | Unifies subscription-quota readings across federated instances — one plan, several machines, each able to read only its own local CLI. `sanitizeQuotaCards` bounds a peer-supplied payload to the wire shape; `mergeFleetQuotaCards(localCards, peerEntries)` folds every peer's reading into this install's cards, taking the FRESHEST reading per limit key (the meters are account-wide, so summing them would multiply one allowance) and SUMMING activity counts (those are per-machine, which is why the provider captions them "does not include other devices"); `fleetNote` writes the caption naming what was combined. `metrics[]` is left local — its values are prose, not addends. Fed by `services/providerQuotaShare.js` (this machine's readings, persisted) and `services/peerUsage.js` (the `usage` sync category that carries them). || `harnessOutput.js` | Parsers for what a coding-agent HARNESS prints about itself: `parseHarnessVersion(stdout)` (the one semver run in a `--version` banner, `null` when unparseable), `compareHarnessVersions(a, b)` (the null-guarding wrapper around `versionUtils.js#compareSemver` — `null` when either side is unparseable, so a version that did not parse never reads as "out of date"), `parseHarnessModels(harnessId, stdout)` + `HARNESS_MODEL_PARSER_IDS` (OpenCode's `provider/model` lines and Grok's bulleted list are parsed here; Antigravity and Cursor DELEGATE to `antigravity.js#parseAntigravityModelList` / `aiToolkit/internal/cursor.js#parseCursorModelList`, which the provider-card refresh has used for far longer), `MAX_MODELS`, and `parseNpmLatestVersion`. Pure: the service layer runs the child and hands the captured stdout here, so the vendor output shapes are pinned by table-driven tests instead of by running six real binaries in CI. Model ids come back in the exact spelling `--model` takes — namespaces kept where the vendor keeps them. Consumed by `services/providerRuntimeInstaller.js` and `services/harnesses.js`. || `providerGateways.js` | `PROVIDER_GATEWAYS` — one row per hosted OpenAI-compatible gateway an OpenCode CLI/TUI wrapper can front-end (`orcarouter`, `openrouter`, `nvidia-nim`), plus `PROVIDER_GATEWAY_IDS`, `gatewayById`, `isGatewayNamespace(ns)`, `gatewayForProvider(config)` → row or null, `isGatewayBackedProvider(config)`, and `attachGatewaySiblingKey(provider, providers)` — the synchronous twin of the toolkit's `withGatewayApiKey` for callers holding an already-loaded (RAW, keyless) collection: a fallback pick armed from such a map executes with its sibling's key instead of going out with no Authorization header. Each row's `id` is simultaneously the OpenCode provider namespace, the `gatewayBacked` marker value, and the id of the sibling `api` record that owns the key — so the sibling lookup is `providers[gateway.id]` and an OrcaRouter key can never satisfy an OpenRouter wrapper. Replaces the `orcarouterBacked` boolean + literal `'orcarouter'` that had been hand-copied across ~15 server and client files (namespace resolution, the OpenCode config builder, both zod schemas, the model-fetcher table, the sibling-key attach, the prerequisite check, and the two "not a local runtime" carve-outs in `cliChildEnv.js`/`localProviderRuntime.js`). Reads the legacy per-gateway boolean FOREVER, so stored records are never rewritten. Distinct from a local runtime (`ollamaBacked`, `vllmBacked`, …): remote, always authenticating, and no thinking toggle. Deliberately mirrored in `aiToolkit/internal/gateways.js` (the vendored toolkit may not import out) — `providerGateways.parity.test.js` fails when the two drift; `client/src/utils/providerGateways.js` re-exports this leaf rather than copying it. DERIVED (#7562) from the `serviceDefinitions.js` rows carrying a `gateway` column, so a gateway is one row in that table; the projected shape is unchanged. Dependency-light: imports only that leaf. |diff --git a/server/lib/fleetHostUsage.js b/server/lib/fleetHostUsage.jsnew file mode 100644index 0000000000..ed2998ae9e--- /dev/null+++ b/server/lib/fleetHostUsage.js@@ -0,0 +1,389 @@+/**+ * Who is spending this machine's GPU, and how much of it.+ *+ * The dedicated inference host (`services/fleetLlmGateway.js`) publishes one+ * OpenAI-compatible endpoint on the tailnet and admits one generation at a+ * time. Until this module existed the only thing it could say about that was+ * `{ active, queued }` — a depth, with no answer to "is another machine using+ * my GPU right now, and which one?". An operator watching their 3090 sit at+ * 100% had no way to attribute it, and no record at all once the request ended.+ *+ * This is the pure half: a bounded ledger keyed by the CLIENT ADDRESS the+ * gateway's socket reports, plus the parser that lifts token counts out of an+ * OpenAI-compatible response. `services/fleetLlmUsage.js` owns the singleton,+ * its persistence, and the peer-name resolution that turns an address into a+ * name a human recognizes — all three of which need a daemon, a peer list or a+ * disk, and none of which this module touches.+ *+ * Three deliberate shapes:+ *+ * - **Addresses are identity, names are decoration.** The gateway+ * authenticates every client with ONE shared host key (that is the whole+ * point of a host key), so the wire carries no per-peer identity. The+ * socket's remote address is the only thing that distinguishes two callers,+ * so it is the ledger's key; a peer NAME is resolved at report time and may+ * change or disappear without rewriting history.+ * - **Tokens are observed, never estimated.** A count is recorded only when+ * the upstream actually reported one. A client whose requests all streamed+ * without `stream_options.include_usage` shows `requests` with null token+ * totals — which is honest — rather than a number invented from body size.+ * `tokenReports` counts how many of its requests carried a reading, so the+ * report can say "12 of 40 requests reported tokens" instead of implying+ * the other 28 were free.+ * - **Bounded on every axis.** Clients, per-client day buckets and the recent+ * event list all have caps, because this ledger is written by remote+ * callers: an unbounded map keyed by remote address is a memory leak with a+ * network interface in front of it.+ *+ * Nothing here records a prompt, a completion, or any part of a request body.+ * The ledger holds counts, timestamps, a model id and an HTTP status.+ */++import { normalizeUsage } from './openAiChatStream.js';++/** Distinct client addresses retained. Oldest-seen is evicted past this. */+export const MAX_CLIENTS = 64;++/** Per-client daily buckets retained, and the age past which a client is dropped. */+export const RETENTION_DAYS = 30;++/** Completed requests kept for the "what just happened" list. */+export const MAX_RECENT = 50;++/**+ * How much of a response body is held while looking for its token counts.+ *+ * `usage` sits at the END of both shapes this has to read — the last SSE frame+ * of a stream, or the tail of a single JSON object — so a rolling tail is+ * enough and a full-body buffer would mean holding every concurrent generation+ * in memory to learn two integers.+ */+export const USAGE_TAIL_BYTES = 64 * 1024;++/**+ * Strip the IPv4-mapped IPv6 prefix Node reports on a dual-stack listener.+ *+ * `server.listen(port, '0.0.0.0')` still yields `::ffff:100.x.x.x` for an IPv4+ * client on some hosts, which would file the same machine under two keys+ * depending on which stack the connection arrived over.+ */+export function normalizeClientAddress(address) {+ if (typeof address !== 'string') return null;+ const trimmed = address.trim().toLowerCase();+ if (trimmed === '') return null;+ const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/.exec(trimmed);+ return mapped ? mapped[1] : trimmed;+}++/** Local calendar day, which is the day an operator reading the report means. */+export function usageDayKey(at) {+ const date = new Date(at);+ if (Number.isNaN(date.getTime())) return null;+ const pad = (n) => String(n).padStart(2, '0');+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;+}++/**+ * Walk a balanced JSON object starting at `start` (which must be `{`).+ *+ * Written by hand rather than by regex because the value being located sits in+ * a text buffer that may be TRUNCATED at its head — there is no whole document+ * to hand to `JSON.parse`, only "the object that begins here".+ *+ * @returns {string|null} the object's source text, or null if it does not close+ * within the buffer.+ */+function readBalancedObject(text, start) {+ let depth = 0;+ let inString = false;+ let escaped = false;+ for (let i = start; i < text.length; i += 1) {+ const ch = text[i];+ if (inString) {+ if (escaped) escaped = false;+ else if (ch === '\\') escaped = true;+ else if (ch === '"') inString = false;+ continue;+ }+ if (ch === '"') inString = true;+ else if (ch === '{') depth += 1;+ else if (ch === '}') {+ depth -= 1;+ if (depth === 0) return text.slice(start, i + 1);+ }+ }+ return null;+}++/**+ * The LAST reported token counts in an OpenAI-compatible response body.+ *+ * Searched from the end because both shapes put the real reading last, and+ * because a stream with `stream_options.include_usage` emits `"usage": null` on+ * every intermediate frame before the single populated one — a forward scan+ * would find a null and stop. A candidate that is null, unparseable, or carries+ * no numeric token field is skipped and the walk continues backwards.+ *+ * @returns {{promptTokens: number|null, completionTokens: number|null}|null}+ */+export function findReportedUsage(text) {+ if (typeof text !== 'string') return null;+ let cursor = text.length;+ while (cursor > 0) {+ const at = text.lastIndexOf('"usage"', cursor - 1);+ if (at < 0) return null;+ cursor = at;+ const colon = text.indexOf(':', at + 7);+ if (colon < 0) continue;+ const brace = text.indexOf('{', colon);+ // A `"usage": null` frame has no object before the next key, so require the+ // brace to be the very next non-whitespace character.+ if (brace < 0 || text.slice(colon + 1, brace).trim() !== '') continue;+ const source = readBalancedObject(text, brace);+ if (!source) continue;+ let parsed = null;+ try {+ parsed = JSON.parse(source);+ } catch {+ continue;+ }+ const usage = normalizeUsage(parsed);+ if (usage.promptTokens !== null || usage.completionTokens !== null) return usage;+ }+ return null;+}++/**+ * A bounded tail buffer fed the response bytes as they stream to the client.+ *+ * Deliberately decode-free per chunk: the bytes are concatenated and decoded+ * once at the end, so a multi-byte character split across a chunk boundary+ * cannot corrupt the JSON the parser then reads. The buffer is trimmed to+ * `maxBytes` as it grows, so a long generation costs a fixed 64 KB rather than+ * its whole transcript.+ */+export function createUsageSniffer({ maxBytes = USAGE_TAIL_BYTES } = {}) {+ let tail = Buffer.alloc(0);+ return {+ push(chunk) {+ if (!chunk || chunk.length === 0) return;+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);+ tail = tail.length === 0 ? buf : Buffer.concat([tail, buf]);+ if (tail.length > maxBytes) tail = tail.subarray(tail.length - maxBytes);+ },+ result() {+ return tail.length === 0 ? null : findReportedUsage(tail.toString('utf8'));+ },+ };+}++const emptyClient = (key, at) => ({+ key,+ firstSeen: at,+ lastSeen: at,+ requests: 0,+ errors: 0,+ activeRequests: 0,+ tokenReports: 0,+ promptTokens: 0,+ completionTokens: 0,+ models: [],+ days: {},+});++const emptyDay = () => ({ requests: 0, promptTokens: 0, completionTokens: 0 });++const finiteOr = (value, fallback) => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback);++/**+ * The ledger itself.+ *+ * `now` is injected so the retention and day-bucket contracts can be tested+ * without sleeping, per the test strategy in AGENTS.md.+ */+export function createFleetHostUsageLedger({+ now = Date.now,+ maxClients = MAX_CLIENTS,+ maxRecent = MAX_RECENT,+ retentionDays = RETENTION_DAYS,+} = {}) {+ /** @type {Map<string, ReturnType<typeof emptyClient>>} */+ const clients = new Map();+ let recent = [];+ let sequence = 0;+ let startedAt = now();++ const clientFor = (key, at) => {+ const existing = clients.get(key);+ if (existing) return existing;+ // Evict the least recently active client rather than the oldest INSERTED+ // one: a machine that connected first and still connects hourly matters+ // more than one that appeared once yesterday.+ if (clients.size >= maxClients) {+ let victimKey = null;+ let victimSeen = Infinity;+ for (const [candidateKey, candidate] of clients) {+ // Never evict a client with a request in flight — its `endRequest`+ // would then resurrect it as a fresh row with a negative-looking count.+ if (candidate.activeRequests > 0) continue;+ if (candidate.lastSeen < victimSeen) { victimSeen = candidate.lastSeen; victimKey = candidateKey; }+ }+ if (victimKey !== null) clients.delete(victimKey);+ }+ const created = emptyClient(key, at);+ clients.set(key, created);+ return created;+ };++ const prune = (at) => {+ const cutoffDay = usageDayKey(at - retentionDays * 24 * 60 * 60 * 1000);+ for (const [key, client] of clients) {+ for (const day of Object.keys(client.days)) {+ if (cutoffDay && day < cutoffDay) delete client.days[day];+ }+ if (client.activeRequests === 0 && cutoffDay && usageDayKey(client.lastSeen) < cutoffDay) clients.delete(key);+ }+ };++ return {+ /**+ * A request has arrived and been admitted. Returns the handle `endRequest`+ * needs; the caller must pass it back exactly once.+ */+ beginRequest({ address, path = null, model = null } = {}) {+ const at = now();+ const key = normalizeClientAddress(address) || 'unknown';+ const client = clientFor(key, at);+ client.lastSeen = at;+ client.activeRequests += 1;+ sequence += 1;+ return { id: `req-${sequence}`, key, path, model, startedAt: at };+ },++ /**+ * The request is done — successfully, with an error status, or because the+ * client hung up. `usage` is whatever the response actually reported, or+ * null; it is never inferred.+ */+ endRequest(handle, { status = null, usage = null, model = null } = {}) {+ if (!handle?.key) return;+ const at = now();+ const client = clients.get(handle.key) || clientFor(handle.key, at);+ client.activeRequests = Math.max(0, client.activeRequests - 1);+ client.requests += 1;+ client.lastSeen = at;+ if (typeof status === 'number' && status >= 400) client.errors += 1;++ const servedModel = model || handle.model;+ if (typeof servedModel === 'string' && servedModel !== '' && !client.models.includes(servedModel)) {+ // Bounded for the same reason the client map is: this value arrives in+ // a request body from another machine.+ client.models = [...client.models, servedModel].slice(-5);+ }++ const day = usageDayKey(at);+ const bucket = client.days[day] || (client.days[day] = emptyDay());+ bucket.requests += 1;++ const prompt = finiteOr(usage?.promptTokens, null);+ const completion = finiteOr(usage?.completionTokens, null);+ if (prompt !== null || completion !== null) {+ client.tokenReports += 1;+ client.promptTokens += prompt ?? 0;+ client.completionTokens += completion ?? 0;+ bucket.promptTokens += prompt ?? 0;+ bucket.completionTokens += completion ?? 0;+ }++ recent = [{+ id: handle.id,+ clientKey: handle.key,+ path: handle.path,+ model: servedModel,+ startedAt: handle.startedAt,+ finishedAt: at,+ durationMs: Math.max(0, at - handle.startedAt),+ status,+ promptTokens: prompt,+ completionTokens: completion,+ }, ...recent].slice(0, maxRecent);++ prune(at);+ },++ /**+ * Everything the report route needs, as plain data. Sorted by most recent+ * activity, which is the order an operator asking "who is on my GPU" reads.+ */+ snapshot() {+ const rows = [...clients.values()]+ .map((client) => ({ ...client, days: { ...client.days } }))+ .sort((a, b) => b.lastSeen - a.lastSeen);+ return {+ since: startedAt,+ activeRequests: rows.reduce((sum, row) => sum + row.activeRequests, 0),+ clients: rows,+ recent: [...recent],+ totals: {+ requests: rows.reduce((sum, row) => sum + row.requests, 0),+ errors: rows.reduce((sum, row) => sum + row.errors, 0),+ tokenReports: rows.reduce((sum, row) => sum + row.tokenReports, 0),+ promptTokens: rows.reduce((sum, row) => sum + row.promptTokens, 0),+ completionTokens: rows.reduce((sum, row) => sum + row.completionTokens, 0),+ },+ };+ },++ /** The persisted shape — the snapshot minus anything that is live state. */+ toJSON() {+ const snapshot = this.snapshot();+ return {+ version: 1,+ since: snapshot.since,+ clients: snapshot.clients.map(({ activeRequests, ...client }) => client),+ recent: snapshot.recent,+ };+ },++ /**+ * Restore a persisted ledger.+ *+ * `activeRequests` is deliberately NOT restored: a connection cannot+ * survive the process that was serving it, so replaying a non-zero count+ * would show a permanent phantom generation on the report.+ */+ hydrate(data) {+ if (!data || typeof data !== 'object' || data.version !== 1) return false;+ clients.clear();+ for (const stored of Array.isArray(data.clients) ? data.clients : []) {+ const key = normalizeClientAddress(stored?.key);+ if (!key) continue;+ const at = finiteOr(stored.lastSeen, 0);+ clients.set(key, {+ ...emptyClient(key, at),+ firstSeen: finiteOr(stored.firstSeen, at),+ lastSeen: at,+ requests: finiteOr(stored.requests, 0),+ errors: finiteOr(stored.errors, 0),+ tokenReports: finiteOr(stored.tokenReports, 0),+ promptTokens: finiteOr(stored.promptTokens, 0),+ completionTokens: finiteOr(stored.completionTokens, 0),+ models: Array.isArray(stored.models) ? stored.models.filter((m) => typeof m === 'string').slice(-5) : [],+ days: stored.days && typeof stored.days === 'object'+ ? Object.fromEntries(Object.entries(stored.days)+ .filter(([, bucket]) => bucket && typeof bucket === 'object')+ .map(([day, bucket]) => [day, {+ requests: finiteOr(bucket.requests, 0),+ promptTokens: finiteOr(bucket.promptTokens, 0),+ completionTokens: finiteOr(bucket.completionTokens, 0),+ }]))+ : {},+ });+ }+ recent = (Array.isArray(data.recent) ? data.recent : []).slice(0, maxRecent);+ startedAt = finiteOr(data.since, startedAt);+ prune(now());+ return true;+ },+ };+}diff --git a/server/lib/fleetHostUsage.test.js b/server/lib/fleetHostUsage.test.jsnew file mode 100644index 0000000000..e6629ea7f9--- /dev/null+++ b/server/lib/fleetHostUsage.test.js@@ -0,0 +1,175 @@+import { describe, it, expect } from 'vitest';+import {+ createFleetHostUsageLedger,+ createUsageSniffer,+ findReportedUsage,+ normalizeClientAddress,+ usageDayKey,+} from './fleetHostUsage.js';++// The parser earns focused tests: it reads two materially different wire+// shapes that a route-level test cannot cheaply produce, and a wrong answer is+// silent — a report that undercounts looks exactly like a quiet host.+describe('findReportedUsage', () => {+ it('reads the usage block of a non-streamed completion', () => {+ const body = JSON.stringify({+ id: 'chatcmpl-1',+ choices: [{ message: { content: 'hello' } }],+ usage: { prompt_tokens: 120, completion_tokens: 34, total_tokens: 154 },+ });+ expect(findReportedUsage(body)).toEqual({ promptTokens: 120, completionTokens: 34 });+ });++ it('takes the final populated frame of a stream whose earlier frames carry usage: null', () => {+ // vLLM with `stream_options.include_usage` emits a null `usage` on every+ // content frame and the real one only at the end. A forward scan stops on+ // the first null and reports nothing.+ const stream = [+ 'data: {"choices":[{"delta":{"content":"he"}}],"usage":null}',+ 'data: {"choices":[{"delta":{"content":"llo"}}],"usage":null}',+ 'data: {"choices":[],"usage":{"prompt_tokens":11,"completion_tokens":7}}',+ 'data: [DONE]',+ '',+ ].join('\n\n');+ expect(findReportedUsage(stream)).toEqual({ promptTokens: 11, completionTokens: 7 });+ });++ it('reports nothing when the stream never carried counts', () => {+ const stream = 'data: {"choices":[{"delta":{"content":"hi"}}]}\n\ndata: [DONE]\n\n';+ expect(findReportedUsage(stream)).toBeNull();+ });++ it('skips a usage value that is not an object rather than throwing', () => {+ expect(findReportedUsage('{"usage":null}')).toBeNull();+ expect(findReportedUsage('{"usage":"n/a"}')).toBeNull();+ });++ it('is not confused by a brace inside a string value', () => {+ const body = '{"choices":[{"message":{"content":"}{ \\" not json"}}],"usage":{"prompt_tokens":3,"completion_tokens":4}}';+ expect(findReportedUsage(body)).toEqual({ promptTokens: 3, completionTokens: 4 });+ });+});++describe('createUsageSniffer', () => {+ it('finds the counts after a generation longer than its tail buffer', () => {+ const sniffer = createUsageSniffer({ maxBytes: 512 });+ for (let i = 0; i < 200; i += 1) {+ sniffer.push(Buffer.from(`data: {"choices":[{"delta":{"content":"chunk ${i}"}}],"usage":null}\n\n`));+ }+ sniffer.push(Buffer.from('data: {"usage":{"prompt_tokens":9,"completion_tokens":400}}\n\n'));+ expect(sniffer.result()).toEqual({ promptTokens: 9, completionTokens: 400 });+ });++ it('decodes once at the end, so a multi-byte character split across chunks stays intact', () => {+ const sniffer = createUsageSniffer();+ const text = Buffer.from('data: {"content":"é","usage":{"prompt_tokens":1,"completion_tokens":2}}');+ sniffer.push(text.subarray(0, 25));+ sniffer.push(text.subarray(25));+ expect(sniffer.result()).toEqual({ promptTokens: 1, completionTokens: 2 });+ });++ it('answers null before anything has streamed', () => {+ expect(createUsageSniffer().result()).toBeNull();+ });+});++describe('normalizeClientAddress', () => {+ it('folds an IPv4-mapped IPv6 address onto the same key as its plain form', () => {+ // A dual-stack listener reports one machine two ways; two rows for one peer+ // would split its totals in half.+ expect(normalizeClientAddress('::ffff:192.0.2.10')).toBe('192.0.2.10');+ expect(normalizeClientAddress('192.0.2.10')).toBe('192.0.2.10');+ });++ it('returns null for a missing address rather than an empty key', () => {+ expect(normalizeClientAddress(undefined)).toBeNull();+ expect(normalizeClientAddress(' ')).toBeNull();+ });+});++describe('createFleetHostUsageLedger', () => {+ const at = (iso) => new Date(iso).getTime();++ it('attributes requests and observed tokens per client', () => {+ const ledger = createFleetHostUsageLedger({ now: () => at('2026-09-20T10:00:00Z') });+ const a = ledger.beginRequest({ address: '192.0.2.10', path: '/v1/chat/completions' });+ const b = ledger.beginRequest({ address: '192.0.2.11', path: '/v1/chat/completions' });+ expect(ledger.snapshot().activeRequests).toBe(2);++ ledger.endRequest(a, { status: 200, usage: { promptTokens: 100, completionTokens: 50 }, model: 'qwen3.8-27b' });+ ledger.endRequest(b, { status: 500, usage: null });++ const snapshot = ledger.snapshot();+ expect(snapshot.activeRequests).toBe(0);+ const first = snapshot.clients.find((c) => c.key === '192.0.2.10');+ expect(first).toMatchObject({ requests: 1, errors: 0, promptTokens: 100, completionTokens: 50, tokenReports: 1, models: ['qwen3.8-27b'] });+ const second = snapshot.clients.find((c) => c.key === '192.0.2.11');+ expect(second).toMatchObject({ requests: 1, errors: 1, tokenReports: 0, promptTokens: 0, completionTokens: 0 });+ expect(snapshot.totals).toMatchObject({ requests: 2, errors: 1, tokenReports: 1, completionTokens: 50 });+ });++ it('counts a request whose response reported nothing without inventing a token total', () => {+ // The regression: treating "no counts reported" as zero makes a busy+ // streaming client read as free, which is worse than reading as unknown.+ const ledger = createFleetHostUsageLedger({ now: () => at('2026-09-20T10:00:00Z') });+ const handle = ledger.beginRequest({ address: '192.0.2.10' });+ ledger.endRequest(handle, { status: 200, usage: null });+ const [client] = ledger.snapshot().clients;+ expect(client.requests).toBe(1);+ expect(client.tokenReports).toBe(0);+ });++ it('buckets by local day and drops buckets past the retention window', () => {+ let clock = at('2026-08-01T12:00:00Z');+ const ledger = createFleetHostUsageLedger({ now: () => clock, retentionDays: 7 });+ ledger.endRequest(ledger.beginRequest({ address: '192.0.2.10' }), { status: 200, usage: { promptTokens: 5, completionTokens: 5 } });+ expect(Object.keys(ledger.snapshot().clients[0].days)).toEqual([usageDayKey(clock)]);++ const old = usageDayKey(clock);+ clock = at('2026-08-20T12:00:00Z');+ ledger.endRequest(ledger.beginRequest({ address: '192.0.2.10' }), { status: 200, usage: null });+ const days = Object.keys(ledger.snapshot().clients[0].days);+ expect(days).not.toContain(old);+ expect(days).toEqual([usageDayKey(clock)]);+ });++ it('never evicts a client with a request in flight when the map is full', () => {+ // Eviction under load would decrement a row that no longer exists and+ // resurrect the client with a phantom count.+ let clock = at('2026-09-20T10:00:00Z');+ const ledger = createFleetHostUsageLedger({ now: () => clock, maxClients: 2 });+ const busy = ledger.beginRequest({ address: '192.0.2.10' });+ clock += 1000;+ ledger.endRequest(ledger.beginRequest({ address: '192.0.2.11' }), { status: 200, usage: null });+ clock += 1000;+ ledger.endRequest(ledger.beginRequest({ address: '192.0.2.12' }), { status: 200, usage: null });++ const keys = ledger.snapshot().clients.map((c) => c.key);+ expect(keys).toContain('192.0.2.10');+ expect(keys).not.toContain('192.0.2.11');++ ledger.endRequest(busy, { status: 200, usage: { promptTokens: 1, completionTokens: 1 } });+ expect(ledger.snapshot().activeRequests).toBe(0);+ });++ it('round-trips through persistence without restoring a phantom in-flight request', () => {+ const clock = at('2026-09-20T10:00:00Z');+ const ledger = createFleetHostUsageLedger({ now: () => clock });+ ledger.endRequest(ledger.beginRequest({ address: '192.0.2.10' }), { status: 200, usage: { promptTokens: 7, completionTokens: 8 }, model: 'qwen3.8-27b' });+ // A connection cannot outlive the process that served it.+ ledger.beginRequest({ address: '192.0.2.10' });+ expect(ledger.snapshot().activeRequests).toBe(1);++ const restored = createFleetHostUsageLedger({ now: () => clock });+ expect(restored.hydrate(JSON.parse(JSON.stringify(ledger.toJSON())))).toBe(true);+ const snapshot = restored.snapshot();+ expect(snapshot.activeRequests).toBe(0);+ expect(snapshot.clients[0]).toMatchObject({ key: '192.0.2.10', requests: 1, promptTokens: 7, completionTokens: 8 });+ });++ it('refuses a payload from an unknown future version rather than half-reading it', () => {+ const ledger = createFleetHostUsageLedger();+ expect(ledger.hydrate({ version: 2, clients: [{ key: '192.0.2.10', requests: 9 }] })).toBe(false);+ expect(ledger.snapshot().clients).toEqual([]);+ });+});diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex 81883e2634..cc51aedf00 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -765,7 +765,15 @@ describe('deferred imports stay deferred (#6156)', () => {// reaches `jevRouter.js`, `untrustedContent.js` and `jev.js` only through// `await import()`. Measured before 115,283, after 115,479; restores the ~400// of headroom the recent entries carry — main had eroded to 17.-const MAX_STATIC_INSTANTIATIONS = 116100;+// 116,100 → 116,500 (fleet host inbound usage): one new lib leaf,+// `fleetHostUsage.js`, one new service (`fleetLlmUsage.js`) and their two+// suites. The leaf's only edge is `openAiChatStream.js` for `normalizeUsage`,+// which `lib/index.js` already re-exports, so nothing gains a subtree — the+// whole share is the two new nodes once per reaching suite plus the two new+// test files' own closures. Measured before 116,066, after 116,111 (+45);+// restores the ~400 of headroom the recent entries carry — main had eroded+// to 34.+const MAX_STATIC_INSTANTIATIONS = 116500;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);diff --git a/server/lib/index.js b/server/lib/index.jsindex afd1bb5d53..95ca6a3277 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -505,6 +505,7 @@ export * from './subscriptionPlanTiers.js';export * from './subscriptionSavings.js';export * from './providerFamilies.js';export * from './fleetQuotas.js';+export * from './fleetHostUsage.js';export * from './harnessOutput.js';export * from './providerGateways.js';export * from './providerHarnesses.js';diff --git a/server/routes/providers.fleetPeerHosts.test.js b/server/routes/providers.fleetPeerHosts.test.jsindex 7c6881aca7..677ea71c47 100644--- a/server/routes/providers.fleetPeerHosts.test.js+++ b/server/routes/providers.fleetPeerHosts.test.js@@ -9,6 +9,8 @@ vi.mock('../services/fleetLlmHost.js', () => ({getFleetLlmHostStatus: vi.fn(),revealFleetLlmKey: vi.fn(),configureFleetLlmHost: vi.fn(),+ getFleetLlmHostUsage: vi.fn(),+ disableFleetLlmHost: vi.fn(),}));const fleetLlmHost = await import('../services/fleetLlmHost.js');@@ -49,6 +51,32 @@ describe('GET /api/providers/fleet-peer-hosts', () => {});});+describe('this host\'s inbound usage and stop controls', () => {+ it('serves the usage report uncached', async () => {+ // Cached, this would answer "nobody is using your GPU" for a minute after+ // someone started — the one window where the page is being read.+ const report = { activeRequests: 1, clients: [{ address: '192.0.2.10', label: 'Workstation GPU', requests: 4 }], recent: [], totals: { requests: 4 } };+ fleetLlmHost.getFleetLlmHostUsage.mockResolvedValue(report);++ const res = await request(buildApp()).get('/api/providers/fleet-host/usage');+ expect(res.status).toBe(200);+ expect(res.body).toEqual(report);+ expect(res.headers['cache-control']).toBe('no-store');+ });++ it('stops the host and returns what happened', async () => {+ fleetLlmHost.disableFleetLlmHost.mockImplementation(async ({ emit }) => {+ emit('Closing the shared API queue — no new peer requests will be admitted.');+ return { success: true, containerStopped: true };+ });++ 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.log[0]).toContain('Closing the shared API queue');+ });+});+describe('POST /api/providers/fleet-peer-hosts/:peerId/key', () => {it('reveals key for a specific peer', async () => {fleetLlmHost.revealFleetPeerHostKey.mockResolvedValue({ apiKey: 'sample-peer-token' });diff --git a/server/routes/providers.js b/server/routes/providers.jsindex a51f089a7a..dfb899937b 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -260,6 +260,22 @@ export function createPortOSProviderRoutes(aiToolkit) {const { getFleetLlmHostStatus } = await import('../services/fleetLlmHost.js');res.set('Cache-Control', 'no-store').json(await getFleetLlmHostStatus());}));+ // Who has been using this machine's GPU. Never cached: the point of the+ // report is what is happening right now.+ router.get('/fleet-host/usage', asyncHandler(async (req, res) => {+ const { getFleetLlmHostUsage } = await import('../services/fleetLlmHost.js');+ res.set('Cache-Control', 'no-store').json(await getFleetLlmHostUsage());+ }));+ // 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');+ 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 });+ }));router.get('/fleet-peer-hosts', asyncHandler(async (req, res) => {const { getFleetPeerHosts } = await import('../services/fleetLlmHost.js');res.set('Cache-Control', 'no-store').json(await getFleetPeerHosts());diff --git a/server/services/fleetLlmGateway.js b/server/services/fleetLlmGateway.jsindex 1d86da8847..82cefab56b 100644--- a/server/services/fleetLlmGateway.js+++ b/server/services/fleetLlmGateway.js@@ -1,11 +1,39 @@import http from 'node:http';import { timingSafeEqual } from 'node:crypto';import { pipeline } from 'node:stream/promises';-import { Readable } from 'node:stream';+import { Readable, Transform } from 'node:stream';++import { createUsageSniffer } from '../lib/fleetHostUsage.js';++/**+ * The generation a job asked for, read from the request body it already holds.+ *+ * Attribution only — the model id is the one field of an inbound body this host+ * records, so the report can say WHICH model a peer spent the GPU on. Nothing+ * else is read, and a body that does not parse simply has no model.+ */+function requestedModel(body) {+ if (!body || body.length === 0) return null;+ try {+ const parsed = JSON.parse(body.toString('utf8'));+ return typeof parsed?.model === 'string' && parsed.model !== '' ? parsed.model : null;+ } catch {+ return null;+ }+}// This is the inference API, independent of federation record/status transport.// Bodies live only for their HTTP request; interrupted streams are never replayed.-export function createFleetLlmGateway({ upstream, apiKey, maxQueued = 16, maxBodyBytes = 2 * 1024 ** 2, waitMs = 120000, runMs = 600000 }) {+//+// `usage` is the inbound ledger (`lib/fleetHostUsage.js`), optional so the+// gateway can be constructed without one. Every ADMITTED generation opens+// exactly one ledger entry and closes it once — including the ones that fail,+// time out, or are cancelled by a client hanging up, because "a peer started 40+// requests and abandoned 39" is precisely the pattern an operator wondering+// 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 }) {const pending = [];let active = null;let closing = false;@@ -30,6 +58,18 @@ export function createFleetLlmGateway({ upstream, apiKey, maxQueued = 16, maxBodconst supplied = Buffer.from(String(header || ''));return apiKey?.length >= 24 && expected.length === supplied.length && timingSafeEqual(expected, supplied);};+ // Closed exactly once per admitted job, from whichever path finishes it+ // first — a normal completion, a 502, or a client that hung up mid-stream.+ const settle = (job, status) => {+ if (!job.ledger || job.settled) return;+ job.settled = true;+ usage.endRequest(job.ledger, {+ status: status ?? job.status ?? null,+ usage: job.sniffer?.result() || null,+ model: job.model,+ });+ onRecorded();+ };const pump = () => {if (active || closing || !pending[0]?.ready) return;const job = pending.shift();@@ -40,6 +80,7 @@ export function createFleetLlmGateway({ upstream, apiKey, maxQueued = 16, maxBodexecute(job).catch(() => reply(job.res, 502, 'Model connection failed or exceeded its time limit.')).finally(() => {clearTimeout(job.runTimer);+ settle(job, job.status ?? 502);active = null;pump();});@@ -52,13 +93,23 @@ export function createFleetLlmGateway({ upstream, apiKey, maxQueued = 16, maxBodsignal: job.controller.signal,redirect: 'error',});+ job.status = response.status;job.res.writeHead(response.status, {'Content-Type': response.headers.get('content-type') || 'application/json','Cache-Control': 'no-store','X-Accel-Buffering': 'no',});- if (response.body) await pipeline(Readable.fromWeb(response.body), job.res, { signal: job.controller.signal });- else job.res.end();+ if (!response.body) return job.res.end();+ // A pass-through tap rather than a tee: the client's stream stays the+ // pipeline's only consumer (so backpressure and cancellation behave exactly+ // as before) and the sniffer just watches the bytes go past, holding a+ // bounded tail of them to read the final `usage` frame out of.+ const source = job.sniffer+ ? Readable.fromWeb(response.body).pipe(new Transform({+ transform(chunk, _enc, done) { job.sniffer.push(chunk); done(null, chunk); },+ }))+ : Readable.fromWeb(response.body);+ await pipeline(source, job.res, { signal: job.controller.signal });};const handle = async (req, res) => {if (!authenticated(req.headers.authorization)) return reply(res, 401, 'A valid model host API key is required.');@@ -75,6 +126,10 @@ export function createFleetLlmGateway({ upstream, apiKey, maxQueued = 16, maxBod}if (closing || pending.length >= maxQueued) return reply(res, 429, 'Model host queue is full. Retry later.');const job = { req, res, path, controller: new AbortController() };+ if (usage) {+ job.ledger = usage.beginRequest({ address: req.socket?.remoteAddress, path });+ job.sniffer = createUsageSniffer();+ }// Reserve before reading the body, so concurrent uploads cannot bypass the cap.pending.push(job);const remove = () => {@@ -82,19 +137,24 @@ export function createFleetLlmGateway({ upstream, apiKey, maxQueued = 16, maxBodif (index >= 0) pending.splice(index, 1);clearTimeout(job.waitTimer);job.controller.abort();+ // 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);pump();};res.on('close', remove);- job.waitTimer = setTimeout(() => { reply(res, 429, 'Model host queue wait expired. Retry later.'); remove(); }, waitMs);+ job.waitTimer = setTimeout(() => { job.status = 429; reply(res, 429, 'Model host queue wait expired. Retry later.'); remove(); }, waitMs);const chunks = [];let bytes = 0;for await (const chunk of req) {bytes += chunk.length;- if (bytes > maxBodyBytes) { reply(res, 413, 'Request exceeds the model host body limit.'); remove(); return; }+ if (bytes > maxBodyBytes) { job.status = 413; reply(res, 413, 'Request exceeds the model host body limit.'); remove(); return; }chunks.push(chunk);}if (job.controller.signal.aborted) return;job.body = req.method === 'POST' ? Buffer.concat(chunks) : undefined;+ job.model = requestedModel(job.body);job.ready = true;// Uploads are bounded and preserve arrival order; pump only complete bodies.pump();@@ -112,6 +172,7 @@ export function createFleetLlmGateway({ upstream, apiKey, maxQueued = 16, maxBodclearTimeout(job.waitTimer);job.controller.abort();reply(job.res, 503, 'Model host is stopping.');+ settle(job, 503);}pending.length = 0;server.closeAllConnections();diff --git a/server/services/fleetLlmGateway.test.js b/server/services/fleetLlmGateway.test.jsindex cb8c5c7f42..9d3eac7299 100644--- a/server/services/fleetLlmGateway.test.js+++ b/server/services/fleetLlmGateway.test.js@@ -80,3 +80,70 @@ describe('shared inference HTTP boundary', () => {await vi.waitFor(() => expect(gateway.status().queued).toBe(0));});});++describe('inbound usage accounting', () => {+ // The whole point of the ledger is attribution the queue depth cannot give,+ // so it is asserted at the HTTP boundary — a unit test of the ledger alone+ // cannot prove the gateway closes every entry it opens.+ const ledgerDouble = () => {+ const open = new Map();+ const closed = [];+ return {+ closed,+ openCount: () => open.size,+ beginRequest({ address, path }) {+ const handle = { id: `h${open.size + closed.length}`, address, path };+ open.set(handle.id, handle);+ return handle;+ },+ endRequest(handle, detail) {+ open.delete(handle.id);+ closed.push({ handle, ...detail });+ },+ };+ };++ 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 pending = post(undefined, JSON.stringify({ model: 'qwen3.8-27b', messages: [] }));+ await vi.waitFor(() => expect(received).toHaveLength(1));+ expect(usage.openCount()).toBe(1);+ received[0].res.end('data: {"choices":[],"usage":{"prompt_tokens":12,"completion_tokens":34}}\n\ndata: [DONE]\n\n');+ await (await pending).text();++ await vi.waitFor(() => expect(usage.closed).toHaveLength(1));+ expect(usage.closed[0]).toMatchObject({+ status: 200,+ model: 'qwen3.8-27b',+ usage: { promptTokens: 12, completionTokens: 34 },+ });+ expect(usage.closed[0].handle.path).toBe('/v1/chat/completions');+ await vi.waitFor(() => expect(gateway.status().active).toBe(0));+ });++ it('closes the entry for a client that hangs up while still queued', async () => {+ // A queued job never reaches the run path, so without its own close it+ // would count as generating forever on the report.+ const usage = ledgerDouble();+ const { post, received, gateway } = await setup({ usage });+ const first = await post();+ const abort = new AbortController();+ const pending = post(abort.signal).catch(() => null);+ await vi.waitFor(() => expect(gateway.status().queued).toBe(1));+ abort.abort();+ await pending;+ await vi.waitFor(() => expect(usage.closed).toHaveLength(1));+ received[0].res.end();+ await first.text();+ await vi.waitFor(() => expect(usage.openCount()).toBe(0));+ });++ it('does not count a /v1/models poll as a generation', async () => {+ const usage = ledgerDouble();+ const { base } = await setup({ usage });+ expect((await fetch(base + '/v1/models', { headers })).status).toBe(200);+ expect(usage.openCount()).toBe(0);+ expect(usage.closed).toHaveLength(0);+ });+});diff --git a/server/services/fleetLlmHost.js b/server/services/fleetLlmHost.jsindex 93f9c67448..a25c0327ed 100644--- a/server/services/fleetLlmHost.js+++ b/server/services/fleetLlmHost.js@@ -10,7 +10,8 @@ import { commandOutput } from '../lib/commandExists.js';import { inspectVllmQwenProject } from '../lib/vllmQwenProject.js';import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';import { runStreamingCommand } from '../lib/streamingSpawn.js';-import { installFleetHostLoginTask, isFleetHostLoginTaskInstalled } from './fleetLlmStartup.js';+import { installFleetHostLoginTask, isFleetHostLoginTaskInstalled, removeFleetHostLoginTask } from './fleetLlmStartup.js';+import { flushFleetHostUsage, getFleetHostUsageLedger, getFleetHostUsageReport, scheduleFleetHostUsagePersist } from './fleetLlmUsage.js';import { ensureFleetDockerIntegration } from './fleetLlmDocker.js';import { createFleetLlmGateway } from './fleetLlmGateway.js';import { peerFetch } from '../lib/peerHttpClient.js';@@ -61,7 +62,11 @@ export async function startFleetLlmHost() {const enabled = parseEnvContents((await tryReadFile(PORTOS_ENV_PATH)) || '').get(ENABLED_KEY) === '1';if (!enabled) return;const { apiKey } = await readHostEnv();- const next = createFleetLlmGateway({ upstream, apiKey });+ // Hydrated before the listener binds, so the first inbound request is+ // 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 });await new Promise((resolve, reject) => {next.server.once('error', reject);next.server.listen(PORTS.FLEET_LLM, '0.0.0.0', resolve);@@ -74,6 +79,70 @@ export async function stopFleetLlmHost() {const previous = gateway;gateway = null;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+ // a debounce timer that a shutdown may never run.+ await flushFleetHostUsage();+}++/** Inbound usage, with this host's live admission state folded in. */+export async function getFleetLlmHostUsage() {+ return getFleetHostUsageReport({ queue: gateway?.status() || null });+}++/**+ * Turn the dedicated host OFF — every part of it, in the order that makes the+ * machine quiet and keeps it quiet.+ *+ * `configureFleetLlmHost` arms four separate things, and until this existed the+ * only way to undo any of them was by hand: the shared API listener, the+ * `PORTOS_FLEET_LLM_ENABLED` marker that brings it back on the next boot, a+ * container written with `restart: unless-stopped` (so stopping Docker does not+ * stop it), and — on Windows — a scheduled task that re-runs the resume path at+ * every login. Stopping only the container leaves three of those to start it+ * again, which is why the host looked impossible to stop.+ *+ * The listener and the marker are cleared FIRST and unconditionally: even if+ * docker is not answering, the host must stop accepting peer requests and must+ * not come back on the next restart. Docker's own step reports its failure as a+ * value, so an unreachable engine leaves the operator disabled-but-with-a-+ * container rather than enabled-and-confused.+ *+ * @returns {Promise<{success: boolean, containerStopped: boolean, error?: string}>}+ */+export async function disableFleetLlmHost({ emit = () => {} } = {}) {+ emit('Closing the shared API queue — no new peer requests will be admitted.');+ await stopFleetLlmHost();+ await upsertPortosEnvLine(ENABLED_KEY, '0');+ emit('Disabled the model host for the next restart.');++ const loginTask = await removeFleetHostLoginTask();+ if (!loginTask.success) emit(`Could not remove the Windows login task (${loginTask.error}) — it will try to resume the host at the next login.`);+ else if (process.platform === 'win32') emit('Removed the Windows login-recovery task.');++ const project = await inspectVllmQwenProject();+ if (!project.composeFile) {+ return { success: true, containerStopped: false, error: 'No prepared compose project was found, so no container was stopped. The API queue is closed and the host will stay off.' };+ }+ const override = join(project.dir, 'compose.portos-host.yaml');+ const files = (await tryReadFile(override)) === null+ ? ['-f', project.composeFile]+ : ['-f', project.composeFile, '-f', override];+ emit('Stopping and removing the vLLM container. Its image and weights stay on disk.');+ // `rm -s -f` stops AND removes: the host container carries+ // `restart: unless-stopped`, so a container merely stopped comes back the+ // next time the Docker engine starts. The weights and the image are+ // untouched — a later setup run starts again in minutes, not 30 GB.+ const stopped = await runStreamingCommand(+ 'docker',+ ['compose', ...files, '--profile', 'single', 'rm', '-s', '-f', 'single'],+ emit,+ { cwd: project.dir, env: { PORT: String(PORTS.VLLM_QWEN) }, timeoutMs: 120000 },+ );+ if (!stopped.success) {+ return { success: true, containerStopped: false, error: `The host is disabled and its API queue is closed, but the container could not be stopped: ${stopped.error}` };+ }+ return { success: true, containerStopped: true };}export async function getFleetLlmHostStatus() {@@ -88,6 +157,13 @@ export async function getFleetLlmHostStatus() {const enabled = parseEnvContents((await tryReadFile(PORTOS_ENV_PATH)) || '').get(ENABLED_KEY) === '1';return {recommendation, specs, enabled, serving: Boolean(gateway && probe?.models?.includes(MODEL)), setupRunning,+ // What a Stop action would actually have to turn off. Reported separately+ // from `serving` because the case the operator hits is precisely the one+ // where those disagree: a container answering on the runtime port while the+ // model has not finished loading still reads `serving: false`, and offering+ // no Stop button there is how the host became impossible to turn off.+ listening: Boolean(gateway), runtimeReachable: Boolean(probe?.reachable),+ 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 },diff --git a/server/services/fleetLlmHost.test.js b/server/services/fleetLlmHost.test.jsindex d87076039d..77dbc4c43c 100644--- a/server/services/fleetLlmHost.test.js+++ b/server/services/fleetLlmHost.test.js@@ -1,6 +1,18 @@-vi.mock('./fleetLlmStartup.js', () => ({ installFleetHostLoginTask: async () => ({ success: true }), isFleetHostLoginTaskInstalled: async () => true }));+vi.mock('./fleetLlmStartup.js', () => ({+ installFleetHostLoginTask: async () => ({ success: true }),+ isFleetHostLoginTaskInstalled: async () => true,+ removeFleetHostLoginTask: async () => { state.loginTaskRemoved = true; return { success: true }; },+}));import { beforeEach, describe, expect, it, vi } from 'vitest';-const state = vi.hoisted(() => ({ providers: [], writes: [], enabled: '', specs: { platform: 'win32', cuda: { gpus: [{ name: 'NVIDIA RTX 3090', vramGb: 24 }] } }, peers: [], peerResponses: new Map() }));+const state = vi.hoisted(() => ({ providers: [], writes: [], enabled: '', loginTaskRemoved: false, specs: { platform: 'win32', cuda: { gpus: [{ name: 'NVIDIA RTX 3090', vramGb: 24 }] } }, peers: [], peerResponses: new Map() }));+// The usage ledger has its own suite and its own disk; here it would only pull+// `readJSONFile` into the narrow `fileUtils` double this file already declares.+vi.mock('./fleetLlmUsage.js', () => ({+ getFleetHostUsageLedger: async () => ({ beginRequest: () => ({}), endRequest: () => {} }),+ getFleetHostUsageReport: async () => ({ clients: [], recent: [], totals: {} }),+ scheduleFleetHostUsagePersist: () => {},+ flushFleetHostUsage: async () => {},+}));vi.mock('./instances.js', () => ({ getPeers: async () => state.peers }));vi.mock('../lib/peerHttpClient.js', () => ({peerFetch: async (url, opts, peer) => {@@ -25,9 +37,9 @@ vi.mock('../lib/streamingSpawn.js', () => ({ runStreamingCommand: vi.fn(async ()vi.mock('./vllmQwenManager.js', () => ({ ensureVllmProjectDir: async () => null, provisionVllmQwenProject: async () => ({ success: true }) }));vi.mock('./providers.js', () => ({ getAllProviders: async () => ({ providers: state.providers }), createProvider: async (record) => state.providers.push(record), updateProvider: async (id, patch) => Object.assign(state.providers.find(p => p.id === id), patch) }));vi.mock('./fleetLlmGateway.js', () => ({ createFleetLlmGateway: () => ({ server: { once() {}, on() {}, listen(_port, _host, done) { done(); } }, status: () => ({ active: 0, queued: 0 }), close: async () => {} }) }));-import { configureFleetLlmHost, getFleetLlmHostStatus, getFleetPeerHosts, revealFleetPeerHostKey, stopFleetLlmHost } from './fleetLlmHost.js';+import { configureFleetLlmHost, disableFleetLlmHost, getFleetLlmHostStatus, getFleetPeerHosts, revealFleetPeerHostKey, stopFleetLlmHost } from './fleetLlmHost.js';import { runStreamingCommand } from '../lib/streamingSpawn.js';-beforeEach(async () => { await stopFleetLlmHost(); state.writes = []; state.enabled = ''; state.providers = []; state.peers = []; state.peerResponses.clear(); vi.clearAllMocks(); });+beforeEach(async () => { await stopFleetLlmHost(); state.writes = []; state.enabled = ''; state.loginTaskRemoved = false; state.providers = []; state.peers = []; state.peerResponses.clear(); vi.clearAllMocks(); });describe('dedicated host setup workflow', () => {it('pins the prepared image, keeps the runtime private and routes only local providers through the queue', async () => {state.providers = [@@ -54,6 +66,37 @@ describe('dedicated host setup workflow', () => {});});+describe('stopping the dedicated host', () => {+ it('clears every thing that would start it again, and removes rather than merely stops the container', async () => {+ await configureFleetLlmHost();+ expect(state.enabled).toBe('PORTOS_FLEET_LLM_ENABLED=1');+ expect((await getFleetLlmHostStatus()).stoppable).toBe(true);+ vi.clearAllMocks();++ await expect(disableFleetLlmHost()).resolves.toEqual({ success: true, containerStopped: true });+ // The marker, the login task and the container are three independent ways+ // the host comes back; leaving any one of them is what made it feel+ // impossible to stop.+ expect(state.enabled).toBe('PORTOS_FLEET_LLM_ENABLED=0');+ expect(state.loginTaskRemoved).toBe(true);+ // `rm -s -f`, not `stop`: the container carries `restart: unless-stopped`,+ // so a stopped one returns the next time the Docker engine starts.+ expect(runStreamingCommand.mock.calls.at(-1)[1]).toEqual(expect.arrayContaining(['rm', '-s', '-f', 'single']));+ const status = await getFleetLlmHostStatus();+ expect(status.enabled).toBe(false);+ expect(status.listening).toBe(false);+ });++ it('still disables the host when docker refuses, and says which half did not happen', async () => {+ await configureFleetLlmHost();+ runStreamingCommand.mockResolvedValueOnce({ success: false, error: 'the Docker daemon is not answering' });+ const result = await disableFleetLlmHost();+ expect(result).toMatchObject({ success: true, containerStopped: false });+ expect(result.error).toContain('could not be stopped');+ expect(state.enabled).toBe('PORTOS_FLEET_LLM_ENABLED=0');+ });+});+describe('fleet peer host discovery', () => {it('returns empty hosts list when no peers exist or no peers are serving', async () => {state.peers = [];diff --git a/server/services/fleetLlmStartup.js b/server/services/fleetLlmStartup.jsindex bbd530af3e..fb30713b7a 100644--- a/server/services/fleetLlmStartup.js+++ b/server/services/fleetLlmStartup.js@@ -16,6 +16,21 @@ export async function installFleetHostLoginTask() {return runStreamingCommand('powershell.exe', ['-NoProfile', '-EncodedCommand', Buffer.from(command, 'utf16le').toString('base64')], undefined, { timeoutMs: 30000 });}+/**+ * Undo the login registration when the host is turned off.+ *+ * Without this, disabling the host leaves a scheduled task that starts PortOS's+ * fleet-host resume path at every login — which is exactly the "it keeps coming+ * back and I can't stop it" shape the Stop action exists to end. A task that is+ * already gone is a success, not an error: `schtasks /Delete` fails on a missing+ * task, and re-reporting that as a failed stop would be wrong.+ */+export async function removeFleetHostLoginTask() {+ if (process.platform !== 'win32') return { success: true };+ if (!(await isFleetHostLoginTaskInstalled())) return { success: true };+ return runStreamingCommand('schtasks.exe', ['/Delete', '/TN', 'PortOS Dedicated Model Host', '/F'], undefined, { timeoutMs: 15000 });+}+export async function isFleetHostLoginTaskInstalled() {if (process.platform !== 'win32') return null;return Boolean(await commandOutput('schtasks.exe', ['/Query', '/TN', 'PortOS Dedicated Model Host', '/FO', 'CSV', '/NH'], { timeoutMs: 5000 }));diff --git a/server/services/fleetLlmUsage.js b/server/services/fleetLlmUsage.jsnew file mode 100644index 0000000000..8d1f5c282d--- /dev/null+++ b/server/services/fleetLlmUsage.js@@ -0,0 +1,167 @@+/**+ * The dedicated inference host's inbound usage record — the answer to "is+ * someone using this machine, and who?".+ *+ * `lib/fleetHostUsage.js` is the bounded ledger and the token parser; this is+ * the side of it that has a disk and a peer list. Three jobs:+ *+ * - **Own the singleton.** One ledger per process, shared by the gateway that+ * writes it and the route that reads it. Hydrated from disk on first touch+ * so the totals survive a restart — the operator's question is "who has+ * been using my GPU", which a counter that resets with PM2 cannot answer.+ * - **Persist it, coalesced.** A busy host completes a request every few+ * seconds; each one would otherwise be a file write. Writes are debounced+ * and serialized through one tail, and a failure is logged and dropped+ * rather than thrown — this is a report, and losing a minute of it must+ * never fail a generation that already succeeded.+ * - **Name the callers.** The gateway authenticates every client with the one+ * shared host key, so the ledger can only key on the socket's remote+ * address. A federated peer record (or the tailnet's own node list) turns+ * that address into a name, at REPORT time — so a peer renamed today reads+ * correctly against traffic from last week, and a peer deleted today still+ * shows its address rather than vanishing from the history.+ *+ * Nothing here is federated. This records which machines connected to THIS+ * host; it is network and identity information about the user's own devices,+ * and it stays in the local `data/` file alongside the rest of the host's+ * machine-local deployment state (`docs/STORAGE.md`).+ */++import { dataPath } from '../lib/paths.js';+import { atomicWrite, readJSONFile } from '../lib/fileUtils.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { createFleetHostUsageLedger, normalizeClientAddress } from '../lib/fleetHostUsage.js';+import { getTailscaleStatus } from '../lib/tailscale.js';++const USAGE_FILE = dataPath('fleet-host-usage.json');++/**+ * Long enough that a steady stream of requests costs one write per window,+ * short enough that a page opened right after a generation shows it.+ */+const PERSIST_DEBOUNCE_MS = 5_000;++const queue = createFileWriteQueue();++let ledger = null;+let hydrating = null;+let persistTimer = null;++/** The process-wide ledger, hydrated from disk exactly once. */+export async function getFleetHostUsageLedger() {+ if (ledger) return ledger;+ if (!hydrating) {+ const next = createFleetHostUsageLedger();+ hydrating = readJSONFile(USAGE_FILE, null, { logError: false }).then((stored) => {+ next.hydrate(stored);+ ledger = next;+ return next;+ });+ }+ return hydrating;+}++async function writeLedger() {+ if (!ledger) return;+ const payload = ledger.toJSON();+ await queue(() => atomicWrite(USAGE_FILE, JSON.stringify(payload, null, 2)))+ // Outside the request lifecycle (a debounce timer), so a throw here would+ // take the process down rather than reach any error middleware.+ .catch((err) => console.error(`❌ Could not persist fleet host usage: ${err.message}`));+}++/** Schedule a coalesced write of the current ledger. */+export function scheduleFleetHostUsagePersist() {+ if (persistTimer) return;+ persistTimer = setTimeout(() => {+ persistTimer = null;+ writeLedger();+ }, PERSIST_DEBOUNCE_MS);+ // Never hold the process open for a usage report.+ persistTimer.unref?.();+}++/** Write immediately — used when the host is being stopped. */+export async function flushFleetHostUsage() {+ if (persistTimer) { clearTimeout(persistTimer); persistTimer = null; }+ await writeLedger();+}++/** Test seam: drop the singleton so the next read re-hydrates. */+export function __resetFleetHostUsage() {+ if (persistTimer) { clearTimeout(persistTimer); persistTimer = null; }+ ledger = null;+ hydrating = null;+}++/**+ * Address → the friendliest name this install can give it.+ *+ * A configured federated peer wins over a bare tailnet node: the peer record+ * carries the name the user chose for that machine in PortOS, while the tailnet+ * only knows its MagicDNS name. A caller matching neither is reported by+ * address alone, flagged `known: false` — an unrecognized machine holding the+ * host key is exactly the thing this report exists to surface.+ */+async function buildAddressIndex() {+ const index = new Map();++ const tailnet = await getTailscaleStatus().catch(() => null);+ for (const node of Array.isArray(tailnet?.peers) ? tailnet.peers : []) {+ for (const ip of Array.isArray(node?.ips) ? node.ips : []) {+ const key = normalizeClientAddress(ip);+ if (key) index.set(key, { label: node.dnsName || ip, source: 'tailnet', peerId: null });+ }+ }++ const { getPeers } = await import('./instances.js').catch(() => ({ getPeers: async () => [] }));+ for (const peer of await getPeers().catch(() => [])) {+ const key = normalizeClientAddress(peer?.address);+ if (!key) continue;+ index.set(key, { label: peer.name || peer.host || peer.address, source: 'peer', peerId: peer.id || null });+ }++ return index;+}++/**+ * The full report: every client that has used this host, what it spent, and+ * what it is doing right now.+ *+ * `queue` is the gateway's live admission state, passed in rather than imported+ * so this module does not depend on the host service that depends on it.+ */+export async function getFleetHostUsageReport({ queue: queueStatus = null } = {}) {+ const current = await getFleetHostUsageLedger();+ const snapshot = current.snapshot();+ const index = await buildAddressIndex();++ const decorate = (key) => index.get(key) || { label: null, source: 'unknown', peerId: null };++ return {+ since: snapshot.since,+ activeRequests: snapshot.activeRequests,+ queue: queueStatus,+ totals: snapshot.totals,+ clients: snapshot.clients.map((client) => {+ const identity = decorate(client.key);+ return {+ ...client,+ address: client.key,+ label: identity.label,+ source: identity.source,+ peerId: identity.peerId,+ known: identity.source !== 'unknown',+ // Sorted so the report can chart a series without re-sorting an object.+ days: Object.entries(client.days)+ .sort(([a], [b]) => (a < b ? -1 : 1))+ .map(([day, bucket]) => ({ day, ...bucket })),+ };+ }),+ recent: snapshot.recent.map((event) => ({+ ...event,+ label: decorate(event.clientKey).label,+ address: event.clientKey,+ })),+ };+}diff --git a/server/services/fleetLlmUsage.test.js b/server/services/fleetLlmUsage.test.jsnew file mode 100644index 0000000000..898ce19dc6--- /dev/null+++ b/server/services/fleetLlmUsage.test.js@@ -0,0 +1,94 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const state = vi.hoisted(() => ({ peers: [], tailnet: { peers: [] }, stored: null, written: [] }));++vi.mock('./instances.js', () => ({ getPeers: async () => state.peers }));+vi.mock('../lib/tailscale.js', () => ({ getTailscaleStatus: async () => state.tailnet }));+vi.mock('../lib/paths.js', () => ({ dataPath: (...parts) => `/example/data/${parts.join('/')}` }));+vi.mock('../lib/fileUtils.js', () => ({+ readJSONFile: async () => state.stored,+ atomicWrite: async (path, value) => state.written.push({ path, value }),+}));++const { __resetFleetHostUsage, flushFleetHostUsage, getFleetHostUsageLedger, getFleetHostUsageReport } = await import('./fleetLlmUsage.js');++beforeEach(() => {+ state.peers = [];+ state.tailnet = { peers: [] };+ state.stored = null;+ state.written = [];+ __resetFleetHostUsage();+});++describe('fleet host usage report', () => {+ it('names a caller from its peer record, falling back to the tailnet and then to nothing', async () => {+ // A peer record carries the name the USER chose for that machine; the+ // tailnet only knows its MagicDNS name. An address matching neither is the+ // case the report exists to surface, so it is flagged, not hidden.+ state.peers = [{ id: 'peer-1', name: 'Workstation GPU', address: '192.0.2.10', port: 5555 }];+ state.tailnet = {+ peers: [+ { dnsName: 'workstation.example.ts.net', ips: ['192.0.2.10'] },+ { dnsName: 'laptop.example.ts.net', ips: ['192.0.2.11'] },+ ],+ };++ const ledger = await getFleetHostUsageLedger();+ for (const address of ['192.0.2.10', '192.0.2.11', '192.0.2.99']) {+ ledger.endRequest(ledger.beginRequest({ address }), { status: 200, usage: { promptTokens: 1, completionTokens: 2 } });+ }++ const report = await getFleetHostUsageReport({ queue: { active: 0, queued: 0 } });+ const byAddress = Object.fromEntries(report.clients.map((c) => [c.address, c]));+ expect(byAddress['192.0.2.10']).toMatchObject({ label: 'Workstation GPU', source: 'peer', peerId: 'peer-1', known: true });+ expect(byAddress['192.0.2.11']).toMatchObject({ label: 'laptop.example.ts.net', source: 'tailnet', known: true });+ expect(byAddress['192.0.2.99']).toMatchObject({ label: null, source: 'unknown', known: false });+ expect(report.queue).toEqual({ active: 0, queued: 0 });+ expect(report.totals).toMatchObject({ requests: 3, completionTokens: 6 });+ });++ it('serves a report from disk after a restart, without a phantom in-flight request', async () => {+ state.stored = {+ version: 1,+ since: Date.parse('2026-09-01T00:00:00Z'),+ clients: [{+ key: '192.0.2.10',+ firstSeen: Date.parse('2026-09-19T00:00:00Z'),+ lastSeen: Date.now(),+ requests: 4,+ errors: 0,+ tokenReports: 4,+ promptTokens: 400,+ completionTokens: 900,+ activeRequests: 3,+ models: ['qwen3.8-27b'],+ days: {},+ }],+ recent: [],+ };++ const report = await getFleetHostUsageReport();+ expect(report.clients[0]).toMatchObject({ address: '192.0.2.10', requests: 4, completionTokens: 900 });+ expect(report.activeRequests).toBe(0);+ });++ it('persists a JSON document with no request or response content in it', async () => {+ const ledger = await getFleetHostUsageLedger();+ ledger.endRequest(+ ledger.beginRequest({ address: '192.0.2.10', path: '/v1/chat/completions' }),+ { status: 200, usage: { promptTokens: 5, completionTokens: 6 }, model: 'qwen3.8-27b' },+ );+ await flushFleetHostUsage();++ expect(state.written).toHaveLength(1);+ const payload = JSON.parse(state.written[0].value);+ expect(payload.version).toBe(1);+ expect(payload.clients[0]).toMatchObject({ key: '192.0.2.10', requests: 1, completionTokens: 6 });+ // A ledger row is counts and metadata. If a prompt ever reached it, this is+ // the assertion that fails.+ expect(payload.clients[0]).not.toHaveProperty('activeRequests');+ expect(Object.keys(payload.recent[0]).sort()).toEqual([+ 'clientKey', 'completionTokens', 'durationMs', 'finishedAt', 'id', 'model', 'path', 'promptTokens', 'startedAt', 'status',+ ]);+ });+});