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
fix: recover dedicated model hosting through WSL integration and Windows login
[._.]/ Adam Eivy33af7679ab72
diff --git a/client/src/components/providers/FleetHostSetup.jsx b/client/src/components/providers/FleetHostSetup.jsxindex 9f57382d3f..7bf5d72285 100644--- a/client/src/components/providers/FleetHostSetup.jsx+++ b/client/src/components/providers/FleetHostSetup.jsx@@ -59,10 +59,10 @@ export default function FleetHostSetup({ compact = false, onConfigured }) {<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 type="button" disabled={installing || status.setupRunning} onClick={() => setInstalling(true)} className={actionClass}>+ {status.serving ? 'Reapply recommended host setup' : '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>+ <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. Setup registers PortOS recovery at Windows login. Keep Docker startup with Windows enabled.</p></section>)}{status.enabled && (diff --git a/docs/features/fleet-llm-host.md b/docs/features/fleet-llm-host.mdindex 11d1accf58..4da6a261fb 100644--- a/docs/features/fleet-llm-host.md+++ b/docs/features/fleet-llm-host.md@@ -57,7 +57,7 @@ Open **AI Providers → Model host setup → Host**. The banner is visible aboveSetup 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.+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. Setup enables the model distro in Docker Desktop, wakes it before retrying a failed WSL integration, and registers a Windows login task to restore PortOS and the prepared container. The login task waits for Docker, never downloads weights or generates tokens, and does nothing when the dedicated-host flag is disabled. 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.diff --git a/scripts/resume-fleet-host.js b/scripts/resume-fleet-host.jsnew file mode 100644index 0000000000..c0fc492ea9--- /dev/null+++ b/scripts/resume-fleet-host.js@@ -0,0 +1,24 @@+// Invoked by the dedicated host's Windows login task; never generates tokens.+import { join } from 'node:path';+import { PATHS } from '../server/lib/fileUtils.js';+import { readPortosEnvValue } from '../server/lib/portosEnv.js';+import { commandOutput } from '../server/lib/commandExists.js';+import { runStreamingCommand } from '../server/lib/streamingSpawn.js';+import { inspectVllmQwenProject } from '../server/lib/vllmQwenProject.js';+import { ensureFleetDockerIntegration } from '../server/services/fleetLlmDocker.js';+import { PORTS } from '../server/lib/ports.js';++if (readPortosEnvValue('PORTOS_FLEET_LLM_ENABLED') === '1') {+ const restored = await runStreamingCommand(process.execPath, [join(PATHS.root, 'node_modules/pm2/bin/pm2'), 'resurrect'], undefined, { timeoutMs: 60000 });+ if (!restored.success) throw new Error('Could not restore PortOS processes.');+ let dockerReady = false;+ for (let attempt = 0; attempt < 60 && !dockerReady; attempt++) {+ dockerReady = Boolean(await commandOutput('docker', ['version', '--format', '{{.Server.Version}}'], { timeoutMs: 3000 }));+ if (!dockerReady) await new Promise((resolve) => setTimeout(resolve, 2000));+ }+ if (!dockerReady) throw new Error('Docker did not start. Open the model host setup guide.');+ const project = await inspectVllmQwenProject();+ await ensureFleetDockerIntegration(project);+ const started = await runStreamingCommand('docker', ['compose', '-f', project.composeFile, '-f', join(project.dir, 'compose.portos-host.yaml'), '--profile', 'single', 'up', '-d', '--no-deps', '--no-build', '--pull', 'never', 'single'], undefined, { cwd: project.dir, env: { PORT: String(PORTS.VLLM_QWEN) }, timeoutMs: 60000 });+ if (!started.success) throw new Error('Could not restore the prepared Qwen container. Open the model host setup guide.');+}diff --git a/server/services/fleetLlmDocker.js b/server/services/fleetLlmDocker.jsnew file mode 100644index 0000000000..864a822e69--- /dev/null+++ b/server/services/fleetLlmDocker.js@@ -0,0 +1,50 @@+import http from 'node:http';+import { commandOutput } from '../lib/commandExists.js';++// Docker Desktop's local settings API. No TCP management port is exposed.+function desktopRequest(path, body, pipe = 'dockerBackendApiServer') {+ return new Promise((resolve, reject) => {+ const req = http.request({ socketPath: `\\\\.\\pipe\\${pipe}`, path, method: body ? 'POST' : 'GET', headers: { 'Content-Type': 'application/json' }, timeout: 45000 }, (res) => {+ let text = '';+ res.on('data', (chunk) => { text += chunk; });+ res.on('error', reject);+ res.on('end', () => {+ if (res.statusCode !== 200) return reject(new Error('Docker Desktop settings API is unavailable.'));+ Promise.resolve().then(() => text ? JSON.parse(text) : null).then(resolve, reject);+ });+ });+ req.on('error', reject);+ req.on('timeout', () => req.destroy(new Error('Docker Desktop settings request timed out.')));+ req.end(body ? JSON.stringify(body) : undefined);+ });+}++export async function ensureFleetDockerIntegration(project, { emit = () => {} } = {}) {+ if (process.platform !== 'win32') return;+ const distro = /^\\\\wsl(?:\.localhost|\$)\\([^\\]+)\\/i.exec(project.dir)?.[1];+ if (!distro) return;+ // Wake the distro before Docker launches its agent: early systemd startup+ // can otherwise time out Docker's first whoami command (WSL #14541).+ await commandOutput('wsl.exe', ['-d', distro, '-e', 'true'], { timeoutMs: 45000 });+ const ready = () => commandOutput('wsl.exe', ['-d', distro, '-e', 'docker', 'version', '--format', '{{.Server.Version}}'], { timeoutMs: 5000 });+ if (await ready()) return;+ emit('Enabling Docker access to the WSL model files…');+ const settings = await desktopRequest('/app/settings');+ const integration = settings?.wslIntegration;+ if (!Array.isArray(integration?.distros)) throw new Error('Enable this model distro in Docker Desktop → Settings → Resources → WSL integration, then retry.');+ if (!integration.distros.includes(distro)) {+ await desktopRequest('/app/settings', { wslIntegration: { ...integration, distros: [...integration.distros, distro] } });+ }+ if (await ready()) return;+ const error = await desktopRequest('/error', undefined, 'errorReporter').catch(() => null);+ if (error?.actions?.includes('Restart the WSL integration')) {+ emit('Retrying Docker WSL integration now that the distro is awake…');+ await desktopRequest('/action', { action: 'Restart the WSL integration' }, 'errorReporter');+ }+ // The Desktop action returns before its proxy has bound the socket.+ for (let attempt = 0; attempt < 10; attempt++) {+ if (await ready()) return;+ await new Promise((resolve) => setTimeout(resolve, 1000));+ }+ throw new Error('Docker WSL integration is not ready. In Docker Desktop, restart the WSL integration, then retry host setup.');+}diff --git a/server/services/fleetLlmDocker.test.js b/server/services/fleetLlmDocker.test.jsnew file mode 100644index 0000000000..a736e69a35--- /dev/null+++ b/server/services/fleetLlmDocker.test.js@@ -0,0 +1,36 @@+import { EventEmitter } from 'node:events';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { pinPlatform } from '../lib/testHelper.js';+const state = vi.hoisted(() => ({ requests: [], ready: [], settings: null }));+vi.mock('../lib/commandExists.js', () => ({ commandOutput: vi.fn(async (_cmd, args) => args.includes('docker') ? state.ready.shift() : '') }));+vi.mock('node:http', () => ({ default: { request: (options, callback) => {+ const req = new EventEmitter();+ req.destroy = () => {};+ req.end = (body) => {+ state.requests.push({ path: options.path, body: body ? JSON.parse(body) : undefined });+ const res = new EventEmitter(); res.statusCode = 200;+ const data = options.path === '/app/settings' && !body ? state.settings : options.path === '/error' ? { actions: ['Restart the WSL integration'] } : null;+ callback(res);+ queueMicrotask(() => { res.emit('data', JSON.stringify(data)); res.emit('end'); });+ };+ return req;+} } }));+import { ensureFleetDockerIntegration } from './fleetLlmDocker.js';+let restore;+beforeEach(() => { restore = pinPlatform('win32'); state.requests = []; state.ready = []; state.settings = { wslIntegration: { distros: ['OtherDistro'], enableIntegrationWithDefaultWslDistro: false } }; });+afterEach(() => restore());+it('preserves existing integrations and retries only the offered WSL recovery action after warming the distro', async () => {+ state.ready = [null, null, '1.0'];+ await ensureFleetDockerIntegration({ dir: '\\\\wsl.localhost\\ExampleDistro\\home\\example\\qwen-serving' });+ expect(state.requests).toContainEqual({ path: '/app/settings', body: { wslIntegration: { distros: ['OtherDistro', 'ExampleDistro'], enableIntegrationWithDefaultWslDistro: false } } });+ expect(state.requests).toContainEqual({ path: '/action', body: { action: 'Restart the WSL integration' } });+});+it('leaves healthy integrations alone and refuses an incompatible Desktop settings schema', async () => {+ const project = { dir: '\\\\wsl.localhost\\ExampleDistro\\home\\example\\qwen-serving' };+ state.ready = ['1.0'];+ await ensureFleetDockerIntegration(project);+ expect(state.requests).toEqual([]);+ state.settings = {};+ await expect(ensureFleetDockerIntegration(project)).rejects.toThrow('Enable this model distro');+ expect(state.requests.every(r => !r.body)).toBe(true);+});diff --git a/server/services/fleetLlmHost.js b/server/services/fleetLlmHost.jsindex 324269b720..d35256dd91 100644--- a/server/services/fleetLlmHost.js+++ b/server/services/fleetLlmHost.js@@ -10,6 +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 { ensureFleetDockerIntegration } from './fleetLlmDocker.js';import { createFleetLlmGateway } from './fleetLlmGateway.js';const ENABLED_KEY = 'PORTOS_FLEET_LLM_ENABLED';@@ -57,9 +59,10 @@ export async function stopFleetLlmHost() {}export async function getFleetLlmHostStatus() {- const [specs, tailnet, docker] = await Promise.all([+ const [specs, tailnet, docker, loginTask] = await Promise.all([detectSystemCapabilities(), getTailscaleStatus(),commandOutput('docker', ['version', '--format', '{{.Server.Version}}'], { timeoutMs: 5000 }),+ isFleetHostLoginTaskInstalled(),]);const recommendation = recommendFleetLlmHost(specs);const host = recommendation.supported && docker ? await readHostEnv().catch(() => null) : null;@@ -76,6 +79,7 @@ export async function getFleetLlmHostStatus() {{ 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 },+ ...(specs.platform === 'win32' ? [{ id: 'startup', label: 'Windows login recovery registered', ok: loginTask }] : []),{ id: 'gateway', label: 'Shared API queue listening', ok: Boolean(gateway) },],};@@ -106,6 +110,7 @@ async function configure({ emit, isCancelled }) {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);+ await ensureFleetDockerIntegration(await inspectVllmQwenProject(), { emit });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.');@@ -130,6 +135,8 @@ async function configure({ emit, isCancelled }) {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);+ const loginTask = await installFleetHostLoginTask();+ if (!loginTask.success) throw new Error('The model started, but Windows login startup could not be configured: ' + loginTask.error);await upsertPortosEnvLine(ENABLED_KEY, '1');await startFleetLlmHost();const { getAllProviders, createProvider, updateProvider } = await import('./providers.js');diff --git a/server/services/fleetLlmHost.test.js b/server/services/fleetLlmHost.test.jsindex ca01dcc7d1..822002501b 100644--- a/server/services/fleetLlmHost.test.js+++ b/server/services/fleetLlmHost.test.js@@ -1,3 +1,4 @@+vi.mock('./fleetLlmStartup.js', () => ({ installFleetHostLoginTask: async () => ({ success: true }), isFleetHostLoginTaskInstalled: async () => 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 }] } } }));vi.mock('../lib/systemCapabilities.js', () => ({ detectSystemCapabilities: async () => state.specs }));diff --git a/server/services/fleetLlmStartup.js b/server/services/fleetLlmStartup.jsnew file mode 100644index 0000000000..bbd530af3e--- /dev/null+++ b/server/services/fleetLlmStartup.js@@ -0,0 +1,22 @@+import { join } from 'node:path';+import { PATHS } from '../lib/fileUtils.js';+import { commandOutput } from '../lib/commandExists.js';+import { runStreamingCommand } from '../lib/streamingSpawn.js';++export async function installFleetHostLoginTask() {+ if (process.platform !== 'win32') return { success: true };+ const saved = await runStreamingCommand(process.execPath, [join(PATHS.root, 'node_modules/pm2/bin/pm2'), 'save'], undefined, { timeoutMs: 15000 });+ if (!saved.success) return saved;+ const quote = (value) => `'${value.replaceAll("'", "''")}'`;+ const script = join(PATHS.root, 'scripts', 'resume-fleet-host.js');+ // The hidden launcher avoids opening a terminal at each interactive login.+ const launch = `& ${quote(process.execPath)} ${quote(script)}`;+ const argument = '-NoProfile -WindowStyle Hidden -EncodedCommand ' + Buffer.from(launch, 'utf16le').toString('base64');+ const command = `$ErrorActionPreference='Stop'; $taskUser=[System.Security.Principal.WindowsIdentity]::GetCurrent().Name; $action=New-ScheduledTaskAction -Execute 'powershell.exe' -Argument ${quote(argument)} -WorkingDirectory ${quote(PATHS.root)}; $trigger=New-ScheduledTaskTrigger -AtLogOn -User $taskUser; $principal=New-ScheduledTaskPrincipal -UserId $taskUser -LogonType Interactive -RunLevel Limited; $settings=New-ScheduledTaskSettingsSet -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Minutes 10) -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1); Register-ScheduledTask -TaskName 'PortOS Dedicated Model Host' -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null`;+ return runStreamingCommand('powershell.exe', ['-NoProfile', '-EncodedCommand', Buffer.from(command, 'utf16le').toString('base64')], undefined, { timeoutMs: 30000 });+}++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 }));+}