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: guide dedicated Qwen hosts with persistent serving and a shared API queue
[._.]/ Adam Eivy3c5bb176a5b6
diff --git a/.env.example b/.env.exampleindex 421c41b9f9..a23c9f6220 100644--- a/.env.example+++ b/.env.example@@ -310,3 +310,7 @@ PGPASSWORD=portos# Auto-generated and appended to .env on the first vault write if unset. Back# it up: losing it makes every encrypted vault value unrecoverable.# PRIVACY_VAULT_KEY=<64 hex chars>++# Set by AI Providers > Model host setup after successful dedicated setup.+# Restores the authenticated queue; the container restart policy restores Qwen.+# PORTOS_FLEET_LLM_ENABLED=0diff --git a/client/src/components/providers/FleetHostSetup.jsx b/client/src/components/providers/FleetHostSetup.jsxnew file mode 100644index 0000000000..9f57382d3f--- /dev/null+++ b/client/src/components/providers/FleetHostSetup.jsx@@ -0,0 +1,101 @@+import { useCallback, useEffect, useState } from 'react';+import { Link } from 'react-router';+import { CheckCircle2, HelpCircle, Server, XCircle } from 'lucide-react';+import { getFleetLlmHost, revealFleetLlmHostKey } from '../../services/apiProviders';+import { copyToClipboard } from '../../lib/clipboard';+import { useAutoRefetch } from '../../hooks/useAutoRefetch';+import RuntimeInstallModal from '../install/RuntimeInstallModal';+import Banner from '../ui/Banner';++export default function FleetHostSetup({ compact = false, onConfigured }) {+ const [status, setStatus] = useState(null);+ const [error, setError] = useState('');+ const [installing, setInstalling] = useState(false);+ const [key, setKey] = useState('');+ const [revealing, setRevealing] = useState(false);+ const load = useCallback(() => getFleetLlmHost({ silent: true })+ .then((value) => { setStatus(value); setError(''); })+ .catch(() => setError('Could not check this machine. Retry to detect hardware and model readiness.')), []);+ useEffect(() => { load(); }, [load]);+ useAutoRefetch(load, 15000, { enabled: !compact && !installing, pollOnly: true, immediate: false });+ const completed = useCallback(() => { load(); onConfigured?.(); }, [load, onConfigured]);+ const reveal = () => {+ setRevealing(true);+ revealFleetLlmHostKey({ silent: true }).then(({ apiKey }) => setKey(apiKey))+ .catch(() => setError('Could not read the host API key. Complete host setup first.'))+ .finally(() => setRevealing(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) return (+ <section className="rounded-xl border border-port-border bg-port-card p-3 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between" aria-label="Recommended model host">+ <div className="min-w-0">+ <p className="text-sm font-medium text-white flex items-center gap-2"><Server size={16} />{title}</p>+ <p className="text-xs text-gray-400 mt-1">{status?.serving ? 'Serving · shared request queue enabled' : 'Use one dedicated model host from your other PortOS instances.'}</p>+ </div>+ <Link to="/ai/fleet?fleetStep=host" className={actionClass}>Model host setup</Link>+ </section>+ );+ return (+ <div className="space-y-4">+ <Banner tone={status?.serving ? 'success' : 'info'} icon={Server} title={title}>+ <p>{status?.recommendation.reason || 'Detecting this machine…'}</p>+ {status && <p className="mt-2 text-xs">{status.specs.platform} · {status.specs.totalMemoryGb ?? 'Unknown'} GB RAM{status.specs.cuda?.gpus?.map((gpu) => ` · ${gpu.name} (${gpu.vramGb ?? '?'} GB VRAM)`).join('')}</p>}+ </Banner>+ {error && <Banner tone="error">{error}</Banner>}+ <div className="flex flex-wrap gap-2">+ <button type="button" onClick={load} className="min-h-[40px] px-3 rounded-lg bg-port-border text-sm">Refresh host status</button>+ <Link to="/models/llms" className="min-h-[40px] px-3 py-2 text-sm text-port-accent">Manage loaded models</Link>+ </div>+ {status && (+ <>+ <ul className="space-y-2 text-sm">+ {status.checks.map((check) => {+ const Icon = check.ok === true ? CheckCircle2 : check.ok === false ? XCircle : HelpCircle;+ return <li key={check.id} className="flex gap-2"><Icon size={16} className={check.ok === true ? 'text-port-success shrink-0' : 'text-gray-400 shrink-0'} /><span>{check.label}{check.detail && <span className="block text-xs text-gray-400">{check.detail}</span>}</span></li>;+ })}+ </ul>+ {status.recommendation.supported && (+ <section className="rounded-lg border border-port-border p-3 space-y-3 text-sm">+ <p>Reserve this GPU for Qwen. Setup reuses prepared weights, fills in missing runtime settings, keeps the container loaded, and creates a local API provider. A new install can download about 30 GB.</p>+ <p className="text-xs text-gray-400">One active generation across all clients; up to 16 requests wait for at most two minutes. Disconnecting cancels the request. Requests are held in memory and are not replayed after a restart. Other GPU models must be unloaded first. Setup disables competing local providers so they do not reload automatically.</p>+ <button type="button" disabled={installing || status.setupRunning || status.serving} onClick={() => setInstalling(true)} className={actionClass}>+ {status.serving ? 'Model host is serving' : 'Set up dedicated host · download if needed'}+ </button>+ <p className="text-xs text-gray-400">Docker and its GPU drivers must be installed. PortOS can start Docker Desktop, but an engine failure, driver installation or Windows restart may need an action on the host. Enable Docker startup with Windows for reboot recovery.</p>+ </section>+ )}+ {status.enabled && (+ <Banner tone={status.serving ? 'success' : 'warning'}>+ {status.serving ? 'Ready for client connections.' : 'Configured; model is loading or unavailable. Refresh until all checks pass.'}+ <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>+ )}+ <section className="space-y-3 text-sm">+ <h3 className="font-medium">Connect another PortOS instance</h3>+ <ol className="list-decimal pl-5 space-y-2">+ <li>On the other instance, open <strong>AI Providers → Model host setup → Connect client</strong>.</li>+ <li>Use the queued API endpoint below and the host key. Choose <strong>Direct API</strong> for text calls or <strong>OpenCode TUI</strong> for coding agents. The coding tools run on that client.</li>+ <li>Refresh models, then test a small request before assigning agent tasks.</li>+ </ol>+ {status.endpoint ? (+ <div className="rounded-lg bg-port-bg p-3 space-y-2">+ <p className="break-all font-mono text-xs">{status.endpoint}</p>+ <p>Model: <code>{status.model}</code></p>+ <button type="button" onClick={() => copyToClipboard(status.endpoint)} className="text-port-accent min-h-[40px]">Copy API endpoint</button>+ </div>+ ) : <Banner tone="warning">Connect Tailscale on this host to obtain its client API address.</Banner>}+ <p className="text-xs text-gray-400">Restrict this API port to your client machines with Tailscale/network rules. Use this queued endpoint for local and remote providers; direct runtime connections bypass admission control.</p>+ <button type="button" disabled={!status.hasApiKey || revealing} onClick={key ? () => setKey('') : reveal} className="min-h-[40px] px-3 rounded-lg bg-port-border disabled:opacity-50">{key ? 'Hide API key' : 'Reveal host API key'}</button>+ {key && <div className="rounded-lg bg-port-bg p-3"><code className="text-xs break-all">{key}</code><button type="button" onClick={() => copyToClipboard(key)} className="block min-h-[40px] text-port-accent">Copy API key</button></div>}+ </section>+ </>+ )}+ <RuntimeInstallModal open={installing} runtime="vllm" label="Dedicated Qwen host" title="Set up dedicated Qwen host"+ onClose={() => setInstalling(false)} onComplete={completed} streamMethod="POST"+ installUrlBase="/api/providers/fleet-host/setup" flushMs={250}+ description="Prepare missing weights (~30 GB on a fresh install), reserve the GPU and enable the shared API queue."+ doneText="Host configured. Check readiness while the model loads." />+ </div>+ );+}diff --git a/client/src/components/providers/FleetHostSetup.test.jsx b/client/src/components/providers/FleetHostSetup.test.jsxnew file mode 100644index 0000000000..1b4a49c719--- /dev/null+++ b/client/src/components/providers/FleetHostSetup.test.jsx@@ -0,0 +1,36 @@+import { describe, expect, it, vi } from 'vitest';+import { render, screen, fireEvent } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+const api = vi.hoisted(() => ({ getFleetLlmHost: vi.fn(), revealFleetLlmHostKey: 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 }));+import FleetHostSetup from './FleetHostSetup';+const state = {+ recommendation: { supported: true, title: 'Qwen3.8-27B · vLLM + DFlash 2', reason: 'Validated RTX 3090 recipe' },+ specs: { platform: 'win32', totalMemoryGb: 32, cuda: { gpus: [{ name: 'RTX 3090', vramGb: 24 }] } },+ checks: [{ id: 'docker', label: 'Docker engine responding', ok: false, detail: 'Restart Docker Desktop' }],+ endpoint: 'http://host-XXXX.example.ts.net:18022/v1', model: 'qwen3.8-27b', hasApiKey: true,+ queue: { active: 0, queued: 0, maxActive: 1, maxQueued: 16 },+};+describe('dedicated model host setup', () => {+ it('shows hardware and blockers, starts setup only on click and reveals credentials only on request', async () => {+ api.getFleetLlmHost.mockResolvedValue(state);+ api.revealFleetLlmHostKey.mockResolvedValue({ apiKey: 'example-private-token' });+ render(<MemoryRouter><FleetHostSetup /></MemoryRouter>);+ expect(await screen.findByText(/32 GB RAM/)).toBeInTheDocument();+ expect(screen.getByText('Restart Docker Desktop')).toBeInTheDocument();+ expect(screen.queryByTestId('setup')).not.toBeInTheDocument();+ expect(api.revealFleetLlmHostKey).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: /Set up dedicated host/ }));+ expect(screen.getByTestId('setup')).toHaveAttribute('data-method', 'POST');+ expect(screen.getByTestId('setup')).toHaveAttribute('data-url', '/api/providers/fleet-host/setup');+ fireEvent.click(screen.getByRole('button', { name: 'Reveal host API key' }));+ expect(await screen.findByText('example-private-token')).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' } });+ render(<MemoryRouter><FleetHostSetup /></MemoryRouter>);+ await screen.findByText('Connect to a model host');+ expect(screen.queryByRole('button', { name: /Set up dedicated host/ })).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/providers/FleetProviderSetup.jsx b/client/src/components/providers/FleetProviderSetup.jsxindex bdcb537475..33c8e1ab25 100644--- a/client/src/components/providers/FleetProviderSetup.jsx+++ b/client/src/components/providers/FleetProviderSetup.jsx@@ -1,7 +1,8 @@import { useMemo, useState } from 'react';import { Link } from 'react-router';-import { ExternalLink, Network, Server, WandSparkles } from 'lucide-react';+import { Network, WandSparkles } from 'lucide-react';import Drawer from '../Drawer';+import FleetHostSetup from './FleetHostSetup';import useDrawerTab from '../../hooks/useDrawerTab';import { FormField } from '../ui/FormField';import Banner from '../ui/Banner';@@ -16,7 +17,7 @@ const FLEET_TABS = [];const FLEET_TAB_IDS = FLEET_TABS.map(({ id }) => id);const DEFAULT_MODEL = 'qwen3.8-27b';-const DEFAULT_PORT = 18020;+const DEFAULT_PORT = PORTS.FLEET_LLM;const endpointForPeer = (peer) => {const rawHost = String(peer?.host || peer?.address || '').trim();@@ -80,7 +81,7 @@ export const buildFleetProvider = ({ name, endpoint, apiKey, model, harness }) =};};-export default function FleetProviderSetup({ peers = [], onClose, onCreate }) {+export default function FleetProviderSetup({ peers = [], onClose, onCreate, onConfigured }) {const [activeTab, setActiveTab] = useDrawerTab('fleetStep', 'architecture', FLEET_TAB_IDS);const [selectedPeerId, setSelectedPeerId] = useState('');const [endpointInput, setEndpointInput] = useState('');@@ -129,7 +130,7 @@ export default function FleetProviderSetup({ peers = [], onClose, onCreate }) {<DraweropenonClose={onClose}- title="Fleet LLM setup"+ title="Model host setup"subtitle="Use one dedicated GPU host from every PortOS instance"size="lg"tabs={FLEET_TABS}@@ -142,7 +143,7 @@ export default function FleetProviderSetup({ peers = [], onClose, onCreate }) {<div className="space-y-4 text-sm text-gray-300"><Banner tone="success" icon={WandSparkles}><p className="font-medium">Recommended for one RTX 3090: vLLM + Qwen3.8-27B + DFlash2 on the host, OpenCode TUI on coding clients.</p>- <p className="mt-1 text-port-success/80">Use a direct API provider instead when PortOS only needs text synthesis. Both connect straight to the same authenticated OpenAI-compatible endpoint over Tailscale.</p>+ <p className="mt-1 text-port-success/80">Use a direct API provider instead when PortOS only needs text synthesis. Both use the host’s authenticated OpenAI-compatible queue over Tailscale.</p></Banner><div className="grid gap-3 sm:grid-cols-2">@@ -169,43 +170,12 @@ export default function FleetProviderSetup({ peers = [], onClose, onCreate }) {</div><p className="text-xs text-gray-500">- The runtime is reached directly rather than proxied through PortOS. That avoids an extra hop and lets OpenCode use the standard OpenAI-compatible tool stream.+ The host queues API requests from every instance and forwards one generation at a time to its resident model. Use the queued endpoint to share one capacity limit.</p></div>)}- {activeTab === 'host' && (- <div className="space-y-4 text-sm text-gray-300">- <Banner tone="info" icon={Server}>- Do this on the dedicated RTX 3090 PortOS instance. No model download or provider call happens from this walkthrough.- </Banner>- <ol className="list-decimal pl-5 space-y-3">- <li>Open <strong>Load Samples</strong> on AI Providers and add <strong>OpenCode vLLM TUI (Qwen3.8-27B)</strong>.</li>- <li>Use that card’s setup checklist to prepare the vLLM stack. Set <code>SPEC=dflash2</code>, <code>PREFIX_CACHE=1</code>, and a strong <code>VLLM_API_KEY</code>.</li>- <li>Keep the runtime bound on port <code>18020</code>. The stack listens on the network; use Tailscale ACLs and the API key to limit clients.</li>- <li>Because this is a dedicated host, configure the container to restart unless stopped. Do not do that on a mixed media workstation: the model occupies nearly the whole GPU.</li>- <li>Confirm <code>/v1/models</code> answers through the host’s MagicDNS name or Tailscale IP before configuring clients.</li>- </ol>- <div className="flex flex-wrap gap-3">- <a- href="https://github.com/atomantic/PortOS/blob/main/docs/features/fleet-llm-host.md"- target="_blank"- rel="noreferrer"- className="inline-flex items-center gap-1.5 text-port-accent hover:underline"- >- Fleet host guide <ExternalLink size={13} />- </a>- <a- href="https://github.com/syv-ai/qwen38-27b-rtx3090"- target="_blank"- rel="noreferrer"- className="inline-flex items-center gap-1.5 text-port-accent hover:underline"- >- Runtime source <ExternalLink size={13} />- </a>- </div>- </div>- )}+ {activeTab === 'host' && <FleetHostSetup onConfigured={onConfigured} />}{activeTab === 'client' && (<form onSubmit={submit} className="space-y-4">@@ -238,7 +208,7 @@ export default function FleetProviderSetup({ peers = [], onClose, onCreate }) {setSelectedPeerId('');setEndpointInput(event.target.value);}}- placeholder="http://gpu-host.example.ts.net:18020/v1"+ placeholder="http://gpu-host.example.ts.net:18022/v1"className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"/></FormField>diff --git a/client/src/lib/ports.js b/client/src/lib/ports.jsindex 0c2f493eb2..4f63d9bde1 100644--- a/client/src/lib/ports.js+++ b/client/src/lib/ports.js@@ -10,6 +10,7 @@// synchronously at module scope for form defaults and static help text, before// any API round-trip could resolve.export const PORTS = Object.freeze({+ FLEET_LLM: 18022, // Queued, authenticated model host APIAPI: 5555, // Express API server (HTTPS when a Tailscale cert is active)API_LOCAL: 5553, // Loopback-only HTTP mirror of API — binds only when HTTPS is onUI: 5554, // Vite dev server (client)diff --git a/client/src/lib/ports.parity.test.js b/client/src/lib/ports.parity.test.jsindex 09ae412df6..eb2536493c 100644--- a/client/src/lib/ports.parity.test.js+++ b/client/src/lib/ports.parity.test.js@@ -23,7 +23,7 @@ describe('client/src/lib/ports.js mirror parity', () => {});it('mirrors only the UI-facing subset', () => {- expect(Object.keys(PORTS).sort()).toEqual(['API', 'API_LOCAL', 'UI']);+ expect(Object.keys(PORTS).sort()).toEqual(['API', 'API_LOCAL', 'FLEET_LLM', 'UI']);});it('defaults a new peer to the API port', () => {diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsxindex e62bb715f6..6a6e996e52 100644--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@ -20,6 +20,7 @@ import ProviderCard from '../components/providers/ProviderCard';import ProviderForm from '../components/providers/ProviderForm';import CollapsibleSection from '../components/ui/CollapsibleSection';import FleetProviderSetup from '../components/providers/FleetProviderSetup';+import FleetHostSetup from '../components/providers/FleetHostSetup';// The two local apps an API provider can front. Their installer lives on the// Models → LLMs page (it starts the service too), so the provider card@@ -713,6 +714,8 @@ export default function AIProviders() {<div className="flex-1 overflow-auto p-4 space-y-6">+ <FleetHostSetup compact />+{/* Sample Providers Panel */}{showSamples && (<div className="bg-port-card border border-port-border rounded-xl p-4 space-y-4">@@ -1065,6 +1068,7 @@ export default function AIProviders() {peers={fleetPeers}onClose={closeForm}onCreate={handleCreateFleetProvider}+ onConfigured={loadData}/>)}{/* The readiness checklist's one-click fix. Same streaming modal as thediff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsxindex 5cc5e0884d..cc3a37d75f 100644--- a/client/src/pages/AIProviders.test.jsx+++ b/client/src/pages/AIProviders.test.jsx@@ -35,6 +35,7 @@ const toast = vi.hoisted(() => ({}));vi.mock('../services/api', () => api);+vi.mock('../services/apiProviders', () => ({ getFleetLlmHost: vi.fn(() => new Promise(() => {})), revealFleetLlmHostKey: vi.fn() }));vi.mock('../components/ui/Toast', () => ({default: toast,}));@@ -575,8 +576,8 @@ describe('fleet LLM setup walkthrough', () => {it('creates an OpenCode provider whose actual baseURL points at the selected peer', async () => {renderPage('/ai/fleet');- expect(await screen.findByRole('heading', { name: 'Fleet LLM setup' })).toBeInTheDocument();- expect(screen.getByText(/Recommended for one RTX 3090/)).toBeInTheDocument();+ expect(await screen.findByRole('heading', { name: 'Model host setup' })).toBeInTheDocument();+fireEvent.click(screen.getByRole('tab', { name: 'Connect client' }));fireEvent.change(await screen.findByLabelText('Known PortOS peer'), { target: { value: 'peer-example' } });@@ -588,7 +589,7 @@ describe('fleet LLM setup walkthrough', () => {expect(created).toMatchObject({type: 'tui',command: 'opencode',- endpoint: 'http://gpu-host.example.ts.net:18020/v1',+ endpoint: 'http://gpu-host.example.ts.net:18022/v1',apiKey: 'example-secret',defaultModel: 'qwen3.8-27b',vllmBacked: true,@@ -596,8 +597,8 @@ describe('fleet LLM setup walkthrough', () => {enabled: true,});expect(JSON.parse(created.envVars.OPENCODE_CONFIG_CONTENT).provider.vllm.options.baseURL)- .toBe('http://gpu-host.example.ts.net:18020/v1');- await waitFor(() => expect(screen.queryByRole('heading', { name: 'Fleet LLM setup' })).not.toBeInTheDocument());+ .toBe('http://gpu-host.example.ts.net:18022/v1');+ await waitFor(() => expect(screen.queryByRole('heading', { name: 'Model host setup' })).not.toBeInTheDocument());expect(toast.success).toHaveBeenCalledWith('Fleet GPU · OpenCode TUI is connected to the fleet GPU host');});@@ -614,7 +615,7 @@ describe('fleet LLM setup walkthrough', () => {expect(created).toMatchObject({name: 'Fleet GPU · API',type: 'api',- endpoint: 'http://gpu-host.example.ts.net:18020/v1',+ endpoint: 'http://gpu-host.example.ts.net:18022/v1',vllmBacked: true,});expect(created).not.toHaveProperty('command');diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.jsindex e67bf1d0b0..fc768c3cf1 100644--- a/client/src/services/apiProviders.js+++ b/client/src/services/apiProviders.js@@ -84,3 +84,6 @@ export const getCodexModels = (options = {}) => {const { fresh = false, ...rest } = options;return request(`/providers/codex/models${fresh ? '?fresh=1' : ''}`, rest);};++export const getFleetLlmHost = (options) => request('/providers/fleet-host', options);+export const revealFleetLlmHostKey = (options) => request('/providers/fleet-host/key', { method: 'POST', ...options });diff --git a/docs/PORTS.md b/docs/PORTS.mdindex 9deca01efc..ce8aa73212 100644--- a/docs/PORTS.md+++ b/docs/PORTS.md@@ -39,7 +39,8 @@ Common port labels:| 5564 | portos-slotstream | - | Loopback SSD-streaming MoE runtime. Optional PM2 process, started/stopped from Models → LLMs. Never 11434 — that port is a PortOS-managed Ollama. || 5568 | portos-llama-server | - | Loopback llama.cpp speculative-decoding server. Optional PM2 process, started/stopped from Models → LLMs. || 8000 | portos-mtplx | - | Loopback MTPLX OpenAI-compatible API (upstream's own default, kept so the shipped provider presets match). Optional PM2 process, started/stopped from Models → LLMs. See [features/mtplx.md](./features/mtplx.md). |-| 18020 | vLLM (Docker) | - | Loopback vLLM Qwen3.8-27B / DFlash 2 container on an RTX 3090 host. Operator-started (`docker compose --profile single up -d`) — PortOS never brings it up on boot. See [features/qwen38-rtx3090.md](./features/qwen38-rtx3090.md). |+| 18022 | PortOS model host | - | Opt-in bearer-authenticated inference queue for dedicated hosts; one active generation. See [fleet host](./features/fleet-llm-host.md). |+| 18020 | vLLM (Docker) | - | Loopback vLLM Qwen3.8-27B / DFlash 2 container on an RTX 3090 host. Started explicitly from host setup or by the operator. Dedicated hosting opts into Docker restart persistence. See [features/qwen38-rtx3090.md](./features/qwen38-rtx3090.md). || 18021 | SGLang (Docker) | - | Loopback SGLang Qwen3.8-27B container on a Hopper/Blackwell host. Operator-started (`docker compose up -d`) — PortOS never brings it up on boot. See [features/sglang-qwen38.md](./features/sglang-qwen38.md). |## How `:5555`, `:5553`, and `:5554` Relatediff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex cc46b283ac..8b6fbd20b1 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -216,3 +216,7 @@ Apply this checklist to **every new feature that persists data**, and require it- [Backup & Restore](./BACKUP.md) — what gets backed up (data/ files + mandatory Postgres dump) and how restore works.- [`docs/plans/2026-06-06-create-postgres-storage-inventory.md`](./plans/2026-06-06-create-postgres-storage-inventory.md) — full inventory + migration phases.- [`server/lib/README.md`](../server/lib/README.md) — storage helpers (`collectionStore`, `fileUtils`, `db.js`, `assetHash`).++### 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.diff --git a/docs/features/fleet-llm-host.md b/docs/features/fleet-llm-host.mdindex 7631c7812e..11d1accf58 100644--- a/docs/features/fleet-llm-host.md+++ b/docs/features/fleet-llm-host.md@@ -1,20 +1,20 @@# Dedicated LLM host for a PortOS fleetOne PortOS machine with a capable GPU can serve every other install on the-tailnet. Clients connect directly to the model runtime's OpenAI-compatible API;+tailnet. Clients connect to the host's queued OpenAI-compatible API;PortOS federation supplies the known-peer address, but it does not proxy promptsor responses through `:5555`.For one RTX 3090, the default stack is:```text-PortOS clients ── Tailscale ──> vLLM :18020 ──> Qwen3.8-27B + DFlash2+PortOS clients ── Tailscale ──> queue :18022 ──> private vLLM :18020 ──> Qwen3.8-27B + DFlash2│├─ OpenCode TUI provider: coding agents and tool use└─ API provider: text generation, analysis, and thinking workflows```-Open **Settings → AI Providers → Fleet setup** on each client to create either+Open **Settings → AI Providers → Model host setup** on each client to create eitherprovider. The walkthrough can prefill the endpoint from an existing PortOS peerand writes it into both the provider record and OpenCode's actual `baseURL`.@@ -53,35 +53,26 @@ Other existing PortOS paths remain useful, but solve different problems:## Host setup-Follow [vLLM Qwen3.8-27B on an RTX 3090](./qwen38-rtx3090.md) for installation-and WSL2 requirements. For a fleet host, these settings are load-bearing:--1. Set a strong `VLLM_API_KEY`. The runtime listens on `0.0.0.0`; never expose- it to the LAN or tailnet without the key.-2. Use `SPEC=dflash2` and `PREFIX_CACHE=1`. Keep the normal seven-token draft- depth for agent work; `DFLASH_TOKENS=15` trades away request slots and context- for prompt-reproduction workloads.-3. Keep model id `qwen3.8-27b`, or enter the actual id in the client walkthrough.-4. Confirm `http://<gpu-host>:18020/v1/models` answers from another tailnet- machine with the bearer key.-5. On a **dedicated** host, configure the container with `restart:- unless-stopped` (or Docker's equivalent) and ensure Docker starts at boot.--The last step is intentionally different from PortOS's mixed-workstation-default. Qwen3.8 occupies nearly all 24 GB of VRAM, so PortOS never auto-starts-the container on a machine that may also render images or video. A dedicated-fleet host has made the opposite allocation decision: availability is its job.--Use Tailscale ACLs to restrict `:18020` to the client machines. The API key is-still required: the tailnet authenticates machines, while the key prevents an-unrelated process on one of those machines from consuming the model.+Open **AI Providers → Model host setup → Host**. The banner is visible above the provider list and detects GPU/platform capabilities. On Windows/Linux with an RTX 3090 (24 GB), the recommended action prepares missing weights, preserves the prepared image by digest, selects DFlash 2 and prefix caching, and starts a persistent container. The recorded warm agent-prompt result was **105.3 tok/s**; this is a measured reference, not a speed guarantee for every prompt.++Setup binds the underlying runtime to loopback `:18020` and exposes a bearer-authenticated queue on `:18022`. It creates a direct API provider and moves existing local vLLM providers (including OpenCode's baseURL) through the queue. Competing local LM Studio/Ollama/llama/SGLang/SlotStream providers are disabled; their configurations remain available. Unload other GPU models before starting. PortOS no longer enables the default local backend at boot while dedicated hosting is enabled.++The status panel checks Docker, prepared weights/key, the loaded model, Tailscale and queue listener. Copy the endpoint and explicitly reveal/copy the key only when connecting a client. The key never appears in the status payload. Driver installation, Docker engine repair, Windows reboot and enabling Docker Desktop startup may still require host interaction. Once Docker starts, the container's `unless-stopped` policy restores the model; PortOS restores the queue from its machine-local opt-in flag. Cold model initialization can take 5–7 minutes. Boot makes no generation requests.++Restrict `:18022` to your clients using Tailscale/network rules. Existing installations using a directly exposed `:18020` must run host setup before changing clients to `:18022`. Older clients can enter the queue URL manually; no federation schema upgrade is required. Prompts and responses use this separately configured inference API, never federation record sync.++### Queue behavior++One 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.## Client setupOn each client PortOS:1. Add the GPU host under **Instances** if it is not already a peer.-2. Open **AI Providers → Fleet setup → Connect client**.+2. Open **AI Providers → Model host setup → Connect client**.3. Select the peer (or enter its MagicDNS/IP endpoint), paste the host's`VLLM_API_KEY`, and keep the served model id in sync.4. Choose **OpenCode TUI** for CoS coding agents. Choose **Direct API** for@@ -106,6 +97,5 @@ driver updates, container restarts, and network maintenance. PortOS should routearound that outage rather than cold-start another large model on each client.No cold-bootstrap request is involved in this feature. Opening the walkthrough-only reads the saved peer list. The model is contacted only when the user clicks-Refresh Models, Test, or starts a real task.+reads saved configuration, machine health and model discovery. Generation happens only when the user clicks Test or starts a real task.diff --git a/ecosystem.config.cjs b/ecosystem.config.cjsindex ca0af4e881..c41c2bbc3e 100644--- a/ecosystem.config.cjs+++ b/ecosystem.config.cjs@@ -124,6 +124,8 @@ const PORTS = {EIDOVERSE_HOST: 5563, // Optional HTTPS/WebSocket bridge to Eidoverse Worlds on :8940SLOTSTREAM: 5564, // Loopback SSD-streaming MoE runtime (never 11434 — that collides with Ollama)LLAMA_SERVER: 5568, // Loopback llama.cpp speculative-decoding server+ FLEET_LLM: 18022, // Authenticated shared inference queue for dedicated hosts+VLLM_QWEN: 18020, // Loopback vLLM Qwen3.8-27B (DFlash 2) container — started by the operator, never by PortOSSGLANG_QWEN: 18021, // Loopback SGLang Qwen3.8-27B container (Hopper/Blackwell) — started by the operator, never by PortOSPOSTGRES: pgMode === 'native' ? 5432 : 5561 // Active PostgreSQL port (unused in file mode)diff --git a/server/index.js b/server/index.jsindex 63bcceb235..78e4cc4419 100644--- a/server/index.js+++ b/server/index.js@@ -491,4 +491,7 @@ getBuildIdentity().catch((err) => console.error(`❌ Build identity probe failed// process itself. See services/bootstrap.js.runBootSequence({ io, httpServer, localHttpServer, httpsEnabled, port: PORT, host: HOST, spawnerReady });+// Opt-in listener only: restores host configuration without generating tokens.+import('./services/fleetLlmHost.js').then(({ startFleetLlmHost }) => startFleetLlmHost())+ .catch(() => console.error('❌ Dedicated model host listener could not start; open AI Providers → Model host setup.'));registerShutdownHandlers({ io, httpServer, localHttpServer });diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex da46b5d321..1ca60c6edc 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -13838,6 +13838,30 @@"server/routes/providers.js"]},+ {+ "method": "GET",+ "path": "/api/providers/fleet-host",+ "mountPath": "/api/providers",+ "sources": [+ "server/routes/providers.js"+ ]+ },+ {+ "method": "POST",+ "path": "/api/providers/fleet-host/key",+ "mountPath": "/api/providers",+ "sources": [+ "server/routes/providers.js"+ ]+ },+ {+ "method": "POST",+ "path": "/api/providers/fleet-host/setup",+ "mountPath": "/api/providers",+ "sources": [+ "server/routes/providers.js"+ ]+ },{"method": "POST","path": "/api/providers/opencode/install",@@ -17634,8 +17658,8 @@],"stats": {"mounts": 148,- "operations": 2184,- "declarations": 2192,+ "operations": 2187,+ "declarations": 2195,"sourceFiles": 231}}diff --git a/server/lib/ports.js b/server/lib/ports.jsindex 40ec42f54e..0bae117bb8 100644--- a/server/lib/ports.js+++ b/server/lib/ports.js@@ -19,7 +19,9 @@ export const PORTS = {EIDOVERSE_HOST: 5563, // Optional HTTPS/WebSocket bridge to Eidoverse Worlds on :8940SLOTSTREAM: 5564, // Loopback SSD-streaming MoE runtime (never 11434 — that collides with Ollama)LLAMA_SERVER: 5568, // Loopback llama.cpp speculative-decoding server- VLLM_QWEN: 18020, // Loopback vLLM Qwen3.8-27B (DFlash 2) container — operator-started, never by PortOS+ FLEET_LLM: 18022, // Authenticated shared inference queue for dedicated hosts++ VLLM_QWEN: 18020, // Loopback vLLM Qwen3.8-27B (DFlash 2) container — opt-in dedicated host setupSGLANG_QWEN: 18021, // Loopback SGLang Qwen3.8-27B container (Hopper/Blackwell) — operator-started, never by PortOSPOSTGRES_NATIVE: 5432 // System PostgreSQL (PGMODE=native)};diff --git a/server/routes/providers.js b/server/routes/providers.jsindex 7653d4773a..d4c6891576 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -162,6 +162,32 @@ const presentProvider = (provider, capabilities = captureSystemCapabilities()) =*/export function createPortOSProviderRoutes(aiToolkit) {const router = Router();++ router.get('/fleet-host', asyncHandler(async (req, res) => {+ const { getFleetLlmHostStatus } = await import('../services/fleetLlmHost.js');+ res.set('Cache-Control', 'no-store').json(await getFleetLlmHostStatus());+ }));+ // Explicit reveal; secrets are never included in status, URLs or install logs.+ router.post('/fleet-host/key', asyncHandler(async (req, res) => {+ const { revealFleetLlmKey } = await import('../services/fleetLlmHost.js');+ res.set('Cache-Control', 'no-store').json({ apiKey: await revealFleetLlmKey() });+ }));+ router.post('/fleet-host/setup', asyncHandler(async (req, res) => {+ const { configureFleetLlmHost } = await import('../services/fleetLlmHost.js');+ if (runtimeSetupInFlight) throw new ServerError('Another model setup is running.', { status: 409, code: 'SETUP_BUSY' });+ runtimeSetupInFlight = true;+ const { send, safeEnd } = openSseStream(res);+ let clientGone = false;+ onClientDisconnect(req, res, () => { clientGone = true; });+ const result = await configureFleetLlmHost({+ emit: (message) => send({ type: 'log', message }),+ isCancelled: () => clientGone,+ }).catch((err) => ({ success: false, error: err.message }))+ .finally(() => { runtimeSetupInFlight = false; resetProviderReadinessCache(); });+ send(result.success ? { type: 'complete', message: 'Host configured. Check model readiness below.' } : { type: 'error', message: result.error });+ safeEnd();+ }));+const providerService = aiToolkit.services.providers;const providerStatusService = aiToolkit.services.providerStatus;diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 6e1fa4f05a..f06db07a37 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -22,6 +22,7 @@* queue an AI provider call. Boot only loads on-disk state and ARMS schedulers;* every scheduler here is off by default or user-configured.*/+import { readPortosEnvValue } from '../lib/portosEnv.js';import { join } from 'path';import { resolveInstallRoot } from '../lib/dataRoot.js';import { PORTS } from '../lib/ports.js';@@ -279,6 +280,7 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD// the Ollama server is not a provider CALL — nothing is inferred until the// user asks for it.ensureLocalLlmBackend: () => {+ if (readPortosEnvValue('PORTOS_FLEET_LLM_ENABLED') === '1') return;const activeLocalLlmBackend = getLocalLlmBackend();ensureBackendProvider(activeLocalLlmBackend).catch((err) =>console.error(`⚠️ Failed to enable local LLM backend provider: ${err.message}`));@@ -878,6 +880,8 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>// -shutdown would `pm2 stop` a model server the user never asked to lose,// and PortOS is about to stop being the thing that could restart it.stopIdleReaper();+ await import('./fleetLlmHost.js').then(({ stopFleetLlmHost }) => stopFleetLlmHost())+ .catch(() => console.error('❌ Dedicated model host shutdown failed'));// Same reasoning for the hosted-session sweeper: a tick mid-shutdown would// emit into a namespace we are about to close.stopHostedSessionSweep();diff --git a/server/services/fleetLlmGateway.js b/server/services/fleetLlmGateway.jsnew file mode 100644index 0000000000..1d86da8847--- /dev/null+++ b/server/services/fleetLlmGateway.js@@ -0,0 +1,121 @@+import http from 'node:http';+import { timingSafeEqual } from 'node:crypto';+import { pipeline } from 'node:stream/promises';+import { Readable } from 'node:stream';++// 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 }) {+ const pending = [];+ let active = null;+ let closing = false;+ let discovery = null;+ // Coalesce discovery independently: a long generation must not make clients+ // mark a healthy provider offline just because /models waits for its slot.+ const models = () => {+ if (!discovery) discovery = fetch(upstream + '/v1/models', {+ headers: { Authorization: 'Bearer ' + apiKey }, redirect: 'error', signal: AbortSignal.timeout(5000),+ }).then(async (response) => ({ status: response.status, body: await response.text() }))+ .finally(() => { discovery = null; });+ return discovery;+ };+ const reply = (res, status, message) => {+ if (res.destroyed || res.writableEnded) return;+ if (res.headersSent) return res.destroy();+ res.writeHead(status, { 'Content-Type': 'application/json', ...(status === 429 ? { 'Retry-After': '10' } : {}) });+ res.end(JSON.stringify({ error: { message, type: 'fleet_host_error' } }));+ };+ const authenticated = (header) => {+ const expected = Buffer.from(`Bearer ${apiKey}`);+ const supplied = Buffer.from(String(header || ''));+ return apiKey?.length >= 24 && expected.length === supplied.length && timingSafeEqual(expected, supplied);+ };+ const pump = () => {+ if (active || closing || !pending[0]?.ready) return;+ const job = pending.shift();+ if (!job) return;+ active = job;+ clearTimeout(job.waitTimer);+ job.runTimer = setTimeout(() => job.controller.abort(), runMs);+ execute(job).catch(() => reply(job.res, 502, 'Model connection failed or exceeded its time limit.'))+ .finally(() => {+ clearTimeout(job.runTimer);+ active = null;+ pump();+ });+ };+ const execute = async (job) => {+ const response = await fetch(`${upstream}${job.path}`, {+ method: job.req.method,+ headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },+ body: job.body,+ signal: job.controller.signal,+ redirect: 'error',+ });+ 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();+ };+ const handle = async (req, res) => {+ if (!authenticated(req.headers.authorization)) return reply(res, 401, 'A valid model host API key is required.');+ const path = req.url;+ if (req.method === 'GET' && path === '/v1/models' && !closing) {+ const result = await models().catch(() => null);+ if (!result) return reply(res, 502, 'Model discovery is unavailable.');+ if (res.destroyed) return;+ res.writeHead(result.status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });+ return res.end(result.body);+ }+ if (!((req.method === 'GET' && path === '/v1/models') || (req.method === 'POST' && path === '/v1/chat/completions'))) {+ return reply(res, 404, 'Use /v1/models or /v1/chat/completions.');+ }+ if (closing || pending.length >= maxQueued) return reply(res, 429, 'Model host queue is full. Retry later.');+ const job = { req, res, path, controller: new AbortController() };+ // Reserve before reading the body, so concurrent uploads cannot bypass the cap.+ pending.push(job);+ const remove = () => {+ const index = pending.indexOf(job);+ if (index >= 0) pending.splice(index, 1);+ clearTimeout(job.waitTimer);+ job.controller.abort();+ pump();+ };+ res.on('close', remove);+ job.waitTimer = setTimeout(() => { 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; }+ chunks.push(chunk);+ }+ if (job.controller.signal.aborted) return;+ job.body = req.method === 'POST' ? Buffer.concat(chunks) : undefined;+ job.ready = true;+ // Uploads are bounded and preserve arrival order; pump only complete bodies.+ pump();+ };+ const server = http.createServer((req, res) => {+ handle(req, res).catch(() => { reply(res, 400, 'Request could not be read.'); res.destroy(); });+ });+ server.requestTimeout = waitMs;+ return {+ server,+ status: () => ({ active: active ? 1 : 0, queued: pending.length, maxActive: 1, maxQueued }),+ close: async () => {+ closing = true;+ for (const job of [...pending, ...(active ? [active] : [])]) {+ clearTimeout(job.waitTimer);+ job.controller.abort();+ reply(job.res, 503, 'Model host is stopping.');+ }+ pending.length = 0;+ server.closeAllConnections();+ if (server.listening) await new Promise((resolve) => server.close(resolve));+ },+ };+}diff --git a/server/services/fleetLlmGateway.test.js b/server/services/fleetLlmGateway.test.jsnew file mode 100644index 0000000000..cb8c5c7f42--- /dev/null+++ b/server/services/fleetLlmGateway.test.js@@ -0,0 +1,82 @@+import http from 'node:http';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { createFleetLlmGateway } from './fleetLlmGateway.js';++const key = 'example-api-key-with-32-characters';+const headers = { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' };+const resources = [];+const listen = async (server) => {+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ return `http://127.0.0.1:${server.address().port}`;+};+afterEach(async () => {+ for (const close of resources.reverse()) await close();+ resources.length = 0;+});+async function setup(options = {}) {+ const received = [];+ const upstream = http.createServer((req, res) => {+ if (req.url === '/v1/models') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end('{"data":[{"id":"example-model"}]}'); return; }+ received.push({ req, res });+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });+ res.write('data: {"choices":[]}\n\n');+ });+ const target = await listen(upstream);+ resources.push(async () => { upstream.closeAllConnections(); await new Promise((resolve) => upstream.close(resolve)); });+ const gateway = createFleetLlmGateway({ upstream: target, apiKey: key, ...options });+ const base = await listen(gateway.server);+ resources.push(gateway.close);+ const post = (signal, body = '{}') => fetch(base + '/v1/chat/completions', { method: 'POST', headers, body, signal });+ return { received, gateway, base, post };+}++describe('shared inference HTTP boundary', () => {+ it('serializes independent clients, preserves SSE, rejects overload and cancels active inference', async () => {+ const { post, received, gateway, base } = await setup({ maxQueued: 1 });+ expect((await fetch(base + '/v1/models')).status).toBe(401);+ const firstAbort = new AbortController();+ const first = await post(firstAbort.signal);+ const reader = first.body.getReader();+ expect(new TextDecoder().decode((await reader.read()).value)).toContain('data:');+ expect((await fetch(base + '/v1/models', { headers })).status).toBe(200);+ expect(gateway.status().active).toBe(1);+ const second = post();+ await vi.waitFor(() => expect(gateway.status().queued).toBe(1));+ expect(received).toHaveLength(1);+ const overflow = await post();+ expect(overflow.status).toBe(429);+ expect(overflow.headers.get('retry-after')).toBe('10');+ firstAbort.abort();+ const next = await second;+ await vi.waitFor(() => expect(received).toHaveLength(2));+ expect(received[0].res.destroyed).toBe(true);+ received[1].res.end('data: [DONE]\n\n');+ expect(await next.text()).toContain('[DONE]');+ await vi.waitFor(() => expect(gateway.status()).toMatchObject({ active: 0, queued: 0 }));+ });++ it('removes a disconnected queued client without forwarding its prompt', async () => {+ const { post, received, gateway } = await setup();+ 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(gateway.status().queued).toBe(0));+ received[0].res.end();+ await first.text();+ expect(received).toHaveLength(1);+ });++ it('bounds queue waiting and body size without occupying a generation slot', async () => {+ const { post, received, gateway } = await setup({ waitMs: 100, maxBodyBytes: 32 });+ expect((await post(undefined, 'x'.repeat(33))).status).toBe(413);+ const first = await post();+ expect((await post()).status).toBe(429);+ expect(received).toHaveLength(1);+ received[0].res.end();+ await first.text();+ await vi.waitFor(() => expect(gateway.status().queued).toBe(0));+ });+});diff --git a/server/services/fleetLlmHost.js b/server/services/fleetLlmHost.jsnew file mode 100644index 0000000000..324269b720--- /dev/null+++ b/server/services/fleetLlmHost.js@@ -0,0 +1,160 @@+import { join } from 'node:path';+import { readFile } from 'node:fs/promises';+import { detectSystemCapabilities } from '../lib/systemCapabilities.js';+import { getCudaUtilization } from '../lib/cudaCapability.js';+import { getTailscaleStatus } from '../lib/tailscale.js';+import { PORTS } from '../lib/ports.js';+import { PORTOS_ENV_PATH, parseEnvContents, upsertEnvLine, upsertPortosEnvLine } from '../lib/portosEnv.js';+import { atomicWrite, tryReadFile } from '../lib/fileUtils.js';+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 { createFleetLlmGateway } from './fleetLlmGateway.js';++const ENABLED_KEY = 'PORTOS_FLEET_LLM_ENABLED';+const MODEL = 'qwen3.8-27b';+const upstream = `http://127.0.0.1:${PORTS.VLLM_QWEN}`;+let gateway = null;+let setupRunning = false;++export function recommendFleetLlmHost(specs) {+ const gpu = specs.cuda?.gpus?.find((item) => /RTX 3090\b/i.test(item.name || '') && item.vramGb >= 23);+ if (gpu && ['win32', 'linux'].includes(specs.platform)) return {+ runtime: 'vllm', supported: true, title: 'Qwen3.8-27B · vLLM + DFlash 2',+ reason: 'Validated RTX 3090 recipe with structured tool calls and prefix caching. Recorded warm decode: 105 tokens/sec; actual speed depends on context and workload.',+ };+ if (specs.appleSilicon) return { runtime: 'mtplx', supported: false, title: 'MTPLX on Apple Silicon', reason: 'Use the managed MTPLX setup on Models → LLMs. Automated dedicated hosting currently supports the validated RTX 3090 recipe.' };+ return { runtime: null, supported: false, title: specs.cuda?.status === 'unknown' ? 'Hardware detection needs attention' : 'Connect to a model host', reason: 'No validated automatic Qwen3.8-27B host recipe matches this machine. Connect to an existing host, or compare installed models on Models → Performance.' };+}++async function readHostEnv() {+ const project = await inspectVllmQwenProject();+ const env = parseEnvContents(await readFile(join(project.dir, '.env'), 'utf8'));+ const apiKey = env.get('VLLM_API_KEY');+ if (!apiKey || apiKey.length < 24) throw new Error('The runtime needs an API key of at least 24 characters. Run recommended setup to configure it.');+ return { project, env, apiKey };+}++export async function startFleetLlmHost() {+ if (gateway) return;+ const enabled = parseEnvContents((await tryReadFile(PORTOS_ENV_PATH)) || '').get(ENABLED_KEY) === '1';+ if (!enabled) return;+ const { apiKey } = await readHostEnv();+ const next = createFleetLlmGateway({ upstream, apiKey });+ await new Promise((resolve, reject) => {+ next.server.once('error', reject);+ next.server.listen(PORTS.FLEET_LLM, '0.0.0.0', resolve);+ });+ next.server.on('error', () => console.error('❌ Fleet inference listener failed'));+ gateway = next;+}++export async function stopFleetLlmHost() {+ const previous = gateway;+ gateway = null;+ await previous?.close();+}++export async function getFleetLlmHostStatus() {+ const [specs, tailnet, docker] = await Promise.all([+ detectSystemCapabilities(), getTailscaleStatus(),+ commandOutput('docker', ['version', '--format', '{{.Server.Version}}'], { timeoutMs: 5000 }),+ ]);+ const recommendation = recommendFleetLlmHost(specs);+ const host = recommendation.supported && docker ? await readHostEnv().catch(() => null) : null;+ const probe = host ? await probeOpenAiModels(`${upstream}/v1`, { apiKey: host.apiKey, timeoutMs: 4000 }) : null;+ const enabled = parseEnvContents((await tryReadFile(PORTOS_ENV_PATH)) || '').get(ENABLED_KEY) === '1';+ return {+ recommendation, specs, enabled, serving: Boolean(gateway && probe?.models?.includes(MODEL)), setupRunning,+ 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 },+ checks: [+ { id: 'hardware', label: 'Supported hardware', ok: recommendation.supported },+ { id: 'docker', label: 'Docker engine responding', ok: Boolean(docker), detail: docker ? 'Ready' : 'Start Docker Desktop; if it is already running, restart its engine and retry.' },+ { id: 'weights', label: 'Prepared model and API key', ok: host ? host.project.hasWeights : null },+ { id: 'runtime', label: 'Qwen model loaded', ok: probe ? Boolean(probe.models?.includes(MODEL)) : null },+ { id: 'tailnet', label: 'Tailscale connected', ok: tailnet.running },+ { id: 'gateway', label: 'Shared API queue listening', ok: Boolean(gateway) },+ ],+ };+}++export async function revealFleetLlmKey() {+ const { apiKey } = await readHostEnv();+ return apiKey;+}++export async function configureFleetLlmHost({ emit = () => {}, isCancelled = () => false } = {}) {+ if (setupRunning) throw new Error('Model host setup is already running.');+ setupRunning = true;+ return configure({ emit, isCancelled }).finally(() => { setupRunning = false; });+}++async function configure({ emit, isCancelled }) {+ const recommendation = recommendFleetLlmHost(await detectSystemCapabilities());+ if (!recommendation.supported) throw new Error(recommendation.reason);+ const { ensureVllmProjectDir, provisionVllmQwenProject } = await import('./vllmQwenManager.js');+ emit('Checking Docker and the prepared model. This setup reserves the GPU for inference.');+ let docker = await commandOutput('docker', ['version', '--format', '{{.Server.Version}}'], { timeoutMs: 5000 });+ if (!docker && process.platform === 'win32') {+ emit('Starting Docker Desktop…');+ await runStreamingCommand('docker', ['desktop', 'start'], undefined, { timeoutMs: 60000 });+ docker = await commandOutput('docker', ['version', '--format', '{{.Server.Version}}'], { timeoutMs: 15000 });+ }+ if (!docker) throw new Error('Docker engine is not responding. Open Docker Desktop and restart the engine, then retry. If its runtime socket is stuck, restart Windows. Prepared weights will be reused.');+ const misplaced = await ensureVllmProjectDir({ emit });+ if (misplaced) throw new Error(misplaced);+ const prepared = await provisionVllmQwenProject({ emit, isCancelled });+ if (!prepared.success) throw new Error(prepared.error);+ if (isCancelled()) throw new Error('Setup cancelled before starting the model.');+ const { project, apiKey } = await readHostEnv();+ const probe = await probeOpenAiModels(`${upstream}/v1`, { apiKey, timeoutMs: 3000 });+ if (!probe.reachable) {+ const gpu = await getCudaUtilization({ refresh: true });+ if (gpu.gpus?.some((item) => item.memoryUsedMib > 3000)) throw new Error('Another application is holding GPU memory. Unload its model on Models → LLMs, then retry.');+ }+ let contents = await readFile(join(project.dir, '.env'), 'utf8');+ for (const [key, value] of [['SPEC', 'dflash2'], ['PREFIX_CACHE', '1'], ['MAX_SEQS', '1']]) contents = upsertEnvLine(contents, key, value);+ await atomicWrite(join(project.dir, '.env'), contents);+ // !override replaces the public mapping, rather than appending another.+ const composeText = await commandOutput('docker', ['compose', '-f', project.composeFile, '--profile', 'single', 'config', '--format', 'json'], { cwd: project.dir, env: { ...process.env, PORT: String(PORTS.VLLM_QWEN) }, timeoutMs: 10000 });+ const compose = JSON.parse(composeText || '{}');+ const image = compose.services?.single?.image;+ if (!image) throw new Error('The prepared compose project has no single-user image.');+ const imageId = await commandOutput('docker', ['image', 'inspect', image, '--format', '{{.Id}}'], { timeoutMs: 10000 });+ if (!/^sha256:[a-f0-9]{64}$/.test(imageId || '')) throw new Error('The prepared runtime image is missing. Build it with the runtime setup checklist first.');+ const override = join(project.dir, 'compose.portos-host.yaml');+ await atomicWrite(override, `services:\n single:\n image: ${imageId}\n ports: !override\n - "127.0.0.1:${PORTS.VLLM_QWEN}:${PORTS.VLLM_QWEN}"\n restart: unless-stopped\n`);+ emit('Starting the prepared image with one generation slot and a private runtime port. Cold startup can take 5–7 minutes.');+ const started = await runStreamingCommand('docker', ['compose', '-f', project.composeFile, '-f', override, '--profile', 'single', 'up', '-d', '--no-deps', '--no-build', '--pull', 'never', 'single'], emit, { cwd: project.dir, env: { PORT: String(PORTS.VLLM_QWEN) }, timeoutMs: 60000 });+ if (!started.success) throw new Error(started.error);+ await upsertPortosEnvLine(ENABLED_KEY, '1');+ await startFleetLlmHost();+ const { getAllProviders, createProvider, updateProvider } = await import('./providers.js');+ const { providers } = await getAllProviders();+ const endpoint = `http://127.0.0.1:${PORTS.FLEET_LLM}/v1`;+ const existing = providers.find((provider) => provider.type === 'api' && provider.endpoint === endpoint);+ const record = { name: 'Dedicated Qwen API', type: 'api', endpoint, apiKey, models: [MODEL], defaultModel: MODEL, vllmBacked: true, enabled: true, thinking: false, temperature: 0.7, timeout: 600000 };+ const { localRuntimeForProvider } = await import('../lib/localProviderRuntime.js');+ for (const provider of providers) {+ const localRuntime = localRuntimeForProvider(provider);+ if (['lmstudio', 'ollama', 'llama', 'sglang', 'slotstream'].includes(localRuntime?.kind)) {+ await updateProvider(provider.id, { enabled: false });+ continue;+ }+ if (!provider.vllmBacked || localRuntime?.kind !== 'vllm') continue;+ const envVars = { ...provider.envVars };+ if (envVars.OPENCODE_CONFIG_CONTENT) {+ const config = JSON.parse(envVars.OPENCODE_CONFIG_CONTENT);+ if (config.provider?.vllm) config.provider.vllm.options = { ...config.provider.vllm.options, baseURL: endpoint };+ envVars.OPENCODE_CONFIG_CONTENT = JSON.stringify(config);+ }+ await updateProvider(provider.id, { endpoint, apiKey, envVars, thinking: false, temperature: 0.7 });+ }+ if (existing) await updateProvider(existing.id, record);+ else await createProvider(record);+ emit('Persistent container and shared API queue configured. Refresh host status until Qwen is loaded, then connect another instance. Docker must start with Windows for reboot recovery.');+ return { success: true };+}diff --git a/server/services/fleetLlmHost.test.js b/server/services/fleetLlmHost.test.jsnew file mode 100644index 0000000000..ca01dcc7d1--- /dev/null+++ b/server/services/fleetLlmHost.test.js@@ -0,0 +1,43 @@+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 }] } } }));+vi.mock('../lib/systemCapabilities.js', () => ({ detectSystemCapabilities: async () => state.specs }));+vi.mock('../lib/cudaCapability.js', () => ({ getCudaUtilization: async () => ({ gpus: [{ memoryUsedMib: 1000 }] }) }));+vi.mock('../lib/tailscale.js', () => ({ getTailscaleStatus: async () => ({ running: true, dnsName: 'host-XXXX.example.ts.net' }) }));+vi.mock('../lib/fileUtils.js', () => ({ PATHS: { root: '/example' }, atomicWrite: async (path, value) => state.writes.push({ path, value }), tryReadFile: async () => state.enabled }));+vi.mock('node:fs/promises', () => ({ readFile: async () => 'VLLM_API_KEY=example-api-key-with-32-characters\n' }));+vi.mock('../lib/portosEnv.js', async (original) => ({ ...(await original()), upsertPortosEnvLine: async (key, value) => { state.enabled = `${key}=${value}`; } }));+vi.mock('../lib/commandExists.js', () => ({ commandOutput: async (_cmd, args) => args.includes('config') ? JSON.stringify({ services: { single: { image: 'example-runtime' } } }) : args.includes('inspect') ? 'sha256:' + 'a'.repeat(64) : '1.0' }));+vi.mock('../lib/vllmQwenProject.js', () => ({ inspectVllmQwenProject: async () => ({ dir: '/example', composeFile: '/example/compose.yaml', hasWeights: true }) }));+vi.mock('../lib/openAiModelsProbe.js', () => ({ probeOpenAiModels: async () => ({ reachable: true, models: ['qwen3.8-27b'] }) }));+vi.mock('../lib/streamingSpawn.js', () => ({ runStreamingCommand: vi.fn(async () => ({ success: true })) }));+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, stopFleetLlmHost } from './fleetLlmHost.js';+import { runStreamingCommand } from '../lib/streamingSpawn.js';+beforeEach(async () => { await stopFleetLlmHost(); state.writes = []; state.enabled = ''; state.providers = []; 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 = [+ { id: 'local', vllmBacked: true, endpoint: 'http://127.0.0.1:18020/v1' },+ { id: 'remote', vllmBacked: true, endpoint: 'http://host-XXXX.example.ts.net:18020/v1', apiKey: 'remote-secret' },+ { id: 'lmstudio', enabled: true, endpoint: 'http://127.0.0.1:1234/v1' },+ ];+ await expect(configureFleetLlmHost()).resolves.toEqual({ success: true });+ expect(state.writes.find(w => w.path.endsWith('.yaml')).value).toContain('127.0.0.1:18020:18020');+ expect(state.writes.find(w => w.path.endsWith('.yaml')).value).toContain('image: sha256:');+ expect(runStreamingCommand.mock.calls.at(-1)[1]).toEqual(expect.arrayContaining(['--no-build', '--pull', 'never']));+ expect(state.providers[0].endpoint).toBe('http://127.0.0.1:18022/v1');+ expect(state.providers[1]).toMatchObject({ endpoint: 'http://host-XXXX.example.ts.net:18020/v1', apiKey: 'remote-secret' });+ expect(state.providers[2].enabled).toBe(false);+ expect(state.providers.at(-1)).toMatchObject({ type: 'api', enabled: true, defaultModel: 'qwen3.8-27b' });+ const status = await getFleetLlmHostStatus();+ expect(status.serving).toBe(true);+ expect(JSON.stringify(status)).not.toContain('example-api-key');+ });+ it('cancels before starting a persistent runtime or enabling the gateway', async () => {+ await expect(configureFleetLlmHost({ isCancelled: () => true })).rejects.toThrow('cancelled');+ expect(runStreamingCommand).not.toHaveBeenCalled();+ expect(state.enabled).toBe('');+ });+});diff --git a/server/services/vllmQwenManager.js b/server/services/vllmQwenManager.jsindex 23517f399c..9b0c79e73e 100644--- a/server/services/vllmQwenManager.js+++ b/server/services/vllmQwenManager.js@@ -30,7 +30,7 @@ import { join } from 'path';import { atomicWrite, formatBytes, tryReadFile } from '../lib/fileUtils.js';import { runStreamingCommand } from '../lib/streamingSpawn.js';import { findCommandOnPath } from '../lib/processEnv.js';-import { localEndpointPort } from '../lib/localProviderRuntime.js';+import { localEndpointPort, localRuntimeForProvider } from '../lib/localProviderRuntime.js';import { PORTS } from '../lib/ports.js';import {inspectVllmQwenProject,@@ -193,7 +193,7 @@ async function applyVllmApiKeyToProviders(apiKey, emit) {return null;});const all = Array.isArray(data?.providers) ? data.providers : [];- const targets = all.filter((p) => p?.vllmBacked === true && p.apiKey !== apiKey);+ const targets = all.filter((p) => p?.vllmBacked === true && localRuntimeForProvider(p)?.kind === 'vllm' && p.apiKey !== apiKey);let stored = 0;for (const provider of targets) {// A failed provider write must not undo a successful 30 GB provision — thisdiff --git a/server/services/vllmQwenManager.test.js b/server/services/vllmQwenManager.test.jsindex af4d4dd2de..f502cd732c 100644--- a/server/services/vllmQwenManager.test.js+++ b/server/services/vllmQwenManager.test.js@@ -184,6 +184,7 @@ describe('provisionVllmQwenProject', () => {{ id: 'opencode-vllm', vllmBacked: true, apiKey: '' },{ id: 'opencode-vllm-tui', vllmBacked: true, apiKey: '' },{ id: 'anthropic', apiKey: 'untouched' },+ { id: 'remote-vllm', vllmBacked: true, endpoint: 'http://host-XXXX.example.ts.net:18022/v1', apiKey: 'remote-secret' },],});stageFreshProject();