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: let the readiness checklist clone, build and prepare the vLLM Qwen3.8-27B stack (#4767)
[._.]/ Adam Eivy1357abb69ed7
diff --git a/client/src/components/providers/ProviderReadiness.jsx b/client/src/components/providers/ProviderReadiness.jsxindex 4912ef8602..21f9dafdcc 100644--- a/client/src/components/providers/ProviderReadiness.jsx+++ b/client/src/components/providers/ProviderReadiness.jsx@@ -26,11 +26,13 @@* can move the provider onto the served id, or press "Serve as …" to relaunch* the daemon on the weights it already has under the id they picked.*- * That includes the case where the daemon is installed but has NO model weights- * cached: the server can't start, so `setup.action` is `pull-start` and the- * button downloads the runtime's own default checkpoint before starting it.- * Offering a bare "Start" there was a catch-22 — the start could only ever fail,- * and its error message was the only place the missing weights were named.+ * That includes the case where the daemon is installed but nothing usable is on+ * disk: the server can't start, so `setup.action` is one of the PROVISIONING+ * actions and the button fetches what is missing before starting it — MTPLX's+ * default checkpoint (`pull-start`), or the whole vLLM compose project+ * (`provision-start`: clone, build, prepare). Offering a bare "Start" there was+ * a catch-22 — the start could only ever fail, and its error message was the+ * only place the missing payload was named.*/import { Link } from 'react-router';@@ -38,6 +40,7 @@ import { CheckCircle2, Download, HelpCircle, RefreshCw, Wand2, Wrench, XCircle }import Banner from '../ui/Banner';import Pill from '../ui/Pill';+const ICONS = {true: { Icon: CheckCircle2, cls: 'text-port-success' },false: { Icon: XCircle, cls: 'text-port-error' },@@ -145,13 +148,14 @@ export default function ProviderReadiness({ readiness, onAutoSetup, onUseServedMtype="button"onClick={() => onAutoSetup(setup)}className={ACTION_CLASS}- // A weights download is the one action here that spends gigabytes,- // so the button says so before it is clicked rather than after.- title={setup.action === 'pull-start'- ? `Fetches ${label}'s own default checkpoint — a multi-gigabyte download — then starts the server on ${endpoint}.`+ // Provisioning is the one thing here that spends gigabytes, so the+ // button says so before it is clicked rather than after. The label+ // already names the payload; this says where it lands.+ title={setup.provisions+ ? `${setup.actionLabel} — a multi-gigabyte download onto this host, then ${label} starts on ${endpoint}.`: `PortOS runs this on ${endpoint} for you — no terminal needed.`}>- {setup.action === 'pull-start' ? <Download size={12} /> : <Wand2 size={12} />}+ {setup.provisions ? <Download size={12} /> : <Wand2 size={12} />}{setup.actionLabel}</button>)}diff --git a/client/src/components/providers/ProviderReadiness.test.jsx b/client/src/components/providers/ProviderReadiness.test.jsxindex e65d53ad3b..6329551124 100644--- a/client/src/components/providers/ProviderReadiness.test.jsx+++ b/client/src/components/providers/ProviderReadiness.test.jsx@@ -83,7 +83,7 @@ describe('ProviderReadiness', () => {// The replacement spends gigabytes, so the label and the tooltip both say// so up front rather than after the click.const onAutoSetup = vi.fn();- const setup = { runtime: 'mtplx', label: 'MTPLX', action: 'pull-start', actionLabel: 'Download the default model & start MTPLX', blockedReason: null };+ const setup = { runtime: 'mtplx', label: 'MTPLX', action: 'pull-start', actionLabel: 'Download the default model & start MTPLX', provisions: true, blockedReason: null };renderWithRouter(<ProviderReadinessreadiness={readiness({@@ -108,6 +108,36 @@ describe('ProviderReadiness', () => {expect(onAutoSetup).toHaveBeenCalledWith(setup);});+ it('gives every provisioning action the download treatment, whatever it is called', () => {+ // `provisions` comes from the server's own action table+ // (`localRuntimeSetup.js`), so a new gigabyte-spending action cannot be+ // added there and silently render here as an ordinary one-click fix.+ const setup = {+ runtime: 'vllm',+ label: 'vLLM (Qwen3.8-27B)',+ action: 'provision-start',+ actionLabel: 'Clone, build & prepare vLLM (Qwen3.8-27B) (~30 GB), then start',+ provisions: true,+ blockedReason: null,+ };+ renderWithRouter(+ <ProviderReadiness readiness={readiness({ label: 'vLLM (Qwen3.8-27B)', manageUrl: null, setup })} onAutoSetup={vi.fn()} />,+ );++ const button = screen.getByRole('button', { name: /Clone, build & prepare/ });+ expect(button.getAttribute('title')).toMatch(/multi-gigabyte download/);+ expect(button.getAttribute('title')).not.toMatch(/no terminal needed/);+ });++ it('leaves an ordinary install or start alone', () => {+ const setup = { runtime: 'llama', label: 'llama.cpp', action: 'install-start', actionLabel: 'Install & start llama.cpp', provisions: false, blockedReason: null };+ renderWithRouter(+ <ProviderReadiness readiness={readiness({ label: 'llama.cpp', manageUrl: null, setup })} onAutoSetup={vi.fn()} />,+ );++ expect(screen.getByRole('button', { name: /Install & start llama.cpp/ }).getAttribute('title')).toMatch(/no terminal needed/);+ });+it('offers a one-click default-model match when the daemon is serving a different id', () => {const onUseServedModel = vi.fn();const mismatch = readiness({diff --git a/docs/features/qwen38-rtx3090.md b/docs/features/qwen38-rtx3090.mdindex a79d0e045f..79431d022c 100644--- a/docs/features/qwen38-rtx3090.md+++ b/docs/features/qwen38-rtx3090.md@@ -63,17 +63,42 @@ would.## Setup-### 1. Prepare the stack (operator, on the 3090 host)+### 1. Prepare the stack (on the 3090 host)-This step is yours, in a terminal. PortOS does not clone the project, build the-~9.5 GB image, or download the ~20 GB of weights — those are decisions with a-bandwidth and disk cost, and a button that started them by surprise would be the-wrong default.+The host itself is yours: Docker, the NVIDIA Container Toolkit (driver ≥ 580 /+CUDA 13), and — on Windows — WSL2. PortOS will not install any of those; they are+operator decisions with driver requirements it cannot judge, and the readiness+checklist's **Install** button keeps saying so.-On Windows you need WSL2 with Docker and the NVIDIA Container Toolkit (driver-≥ 580 / CUDA 13); on Linux, the same toolkit natively. Run the commands below-*inside the WSL2 distro*, not in PowerShell — the compose project and its-20 GB of weights belong on the Linux filesystem.+The *project* on top of them can go either way.++#### 1-click, from the checklist++On a host that already has Docker and the NVIDIA runtime, the provider+readiness checklist offers **"Clone, build & prepare vLLM (Qwen3.8-27B) (~30 GB),+then start"**. The label names the payload because the click IS the consent — this+is the one button in PortOS that spends tens of gigabytes. It clones this repo,+writes the `.env` below (including the settings in §1a, which is the point), builds+the image, runs `prepare`, and brings the container up, streaming every line.++It is idempotent: re-running skips whatever already landed, and `prepare`'s+download resumes, so a cancelled run costs minutes rather than the 20 GB. An+existing `.env` is never overwritten — only keys it does not already mention are+appended, so your `GPU_UTIL`, `DFLASH_TOKENS` or your own `VLLM_API_KEY` survive.+The API key it generates is written straight onto the two seeded providers, so+step 2 below is just "enable it".++Two things it deliberately will not do. On Windows it refuses unless+`VLLM_QWEN_PROJECT_DIR` is set (§1c): the default `~/qwen-serving` resolves to a+*Windows* home, and 20 GB of weights reached from the WSL2 VM across a 9p share is+a mistake that costs 20 GB to discover. And it never raises the WSL2 memory+ceiling — see §1a for why that one stays manual.++#### By hand++Still fully supported, and the explanation of what the button does. Run the+commands below *inside the WSL2 distro*, not in PowerShell — the compose project+and its 20 GB of weights belong on the Linux filesystem.```bashgit clone https://github.com/syv-ai/qwen38-27b-rtx3090 ~/qwen-serving@@ -155,7 +180,10 @@ op itself works correctly when called directly. Upstream lists this as anescape hatch for memory trouble; on WSL2 it is a precondition for starting atall.-**Raise the VM's memory ceiling before running `prepare`.** The+**Raise the VM's memory ceiling before running `prepare` — including before the+1-click action.** This is the one step PortOS detects and warns about but never+performs, because `wsl --shutdown` takes the whole VM down, including a+PostgreSQL container a PortOS install may be using. Therequantization step is CPU-side and memory-hungry — `quant_lm_head.py` holds awhole 2.5 GB shard plus several float32 copies of a 248k-row `lm_head` — andWSL2 defaults to a ceiling of half the host's RAM. On a 32 GB machine that 16 GB@@ -216,9 +244,10 @@ workload that fits.### 2. Enable the provider (PortOS)1. On **AI Providers**, enable **OpenCode vLLM TUI (Qwen3.8-27B)**.-2. Paste the `VLLM_API_KEY` from your `.env` into the provider's API key field.- PortOS injects it into the spawned OpenCode's `provider.vllm.options.apiKey`;- without it the container answers 401 and the model list stays empty.+2. Check the API key field. The 1-click path already filled it in; after a+ by-hand setup, paste the `VLLM_API_KEY` from your `.env`. PortOS injects it+ into the spawned OpenCode's `provider.vllm.options.apiKey`; without it the+ container answers 401 and the model list stays empty.3. Click **Refresh Models**. The served model should appear; the seeded alias is`qwen3.8-27b`, so update the default model if your container publishes adifferent id.@@ -243,7 +272,8 @@ The provider card's requirements checklist probes `:18020` directly. Its**Start** button runs `docker compose --profile single up -d` — but only when itcan see a prepared project (a compose file in `~/qwen-serving`, or wherever`VLLM_QWEN_PROJECT_DIR` points) **and** confirm the weights are already on disk.-It never builds and never downloads. `prepare` writes them into the project's own+It never builds and never downloads — that is the separate,+explicitly-named provisioning action above. `prepare` writes them into the project's own`models/` directory (compose bind-mounts `${MODELS_DIR:-./models}`), which iswhat PortOS looks at; the `qwen-cache` docker volume alongside it holds only thetorch.compile / Triton / FlashInfer JIT caches. If PortOS cannot read thatdiff --git a/server/lib/README.md b/server/lib/README.mdindex 2caa9d615b..91c1062da9 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -138,11 +138,12 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `providerFamilies.js` | Subscription-quota FAMILY identity — `PROVIDER_FAMILIES` (`{ id, label, matches }` for claude/codex/agy/grok), `PROVIDER_FAMILY_IDS`, `familyLabel`, `familyForProvider(config)` → 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. || `providerTranscriptUsage.js` | Parsers for the real per-message token counts the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Both de-duplicate a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, and Codex's `total_token_usage` is cumulative and repeated. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. || `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring bare model ids under the selected local provider (`ollama` or `mtplx`) for marked OpenCode providers. Fixes --model rejection. |-| `localProviderRuntime.js` | Which LOCAL daemon a provider talks to, and where — `LOCAL_RUNTIMES` (llama.cpp / Ollama / LM Studio / MTPLX / vLLM: label, binary, canonical base URL read from `opencodeConfig.js` rather than re-typed, manage/docs links, model-download hint), `localBackendForProvider` + `localEndpointPort` + `isLocalInstanceHost` (moved here from `services/localModelHealing.js`, which re-exports them, so the healing path and the readiness checklist classify a provider identically — loopback/bind-all only, so a LAN/Tailscale peer on port 11434 is NOT claimed as a local daemon), `localRuntimeKind(provider)` (the `*Backed` markers first, then that classifier; `orcarouter` excluded as a remote API), `localRuntimeForProvider(provider)` → the row with the endpoint the provider ITSELF configures (`OPENCODE_CONFIG_CONTENT`'s `baseURL`, `ANTHROPIC_BASE_URL`, or `endpoint`), then the `OLLAMA_URL`/`OLLAMA_HOST`/`LM_STUDIO_URL` override the backend managers read, then the canonical default — and `null` when that resolved endpoint fails `isLocalInstanceEndpoint` (an API provider on another machine has no local daemon to check, whatever its name says) — plus `normalizeOpenAiBaseUrl`. Pure; the probing half is `services/providerReadiness.js`. |+| `localProviderRuntime.js` | Which LOCAL daemon a provider talks to, and where — `LOCAL_RUNTIMES` (llama.cpp / Ollama / LM Studio / MTPLX / vLLM: label, binary, canonical base URL read from `opencodeConfig.js` rather than re-typed, manage/docs links, model-download hint), `localBackendForProvider` + `localEndpointPort` + `isLocalInstanceHost` (moved here from `services/localModelHealing.js`, which re-exports them, so the healing path and the readiness checklist classify a provider identically — loopback/bind-all only, so a LAN/Tailscale peer on port 11434 is NOT claimed as a local daemon), `localRuntimeKind(provider)` (the `*Backed` markers first, then that classifier; `orcarouter` excluded as a remote API), `localRuntimeForProvider(provider)` → the row with the endpoint the provider ITSELF configures (`OPENCODE_CONFIG_CONTENT`'s `baseURL`, `ANTHROPIC_BASE_URL`, or `endpoint`), then the `OLLAMA_URL`/`OLLAMA_HOST`/`LM_STUDIO_URL` override the backend managers read, then the canonical default — and `null` when that resolved endpoint fails `isLocalInstanceEndpoint` (an API provider on another machine has no local daemon to check, whatever its name says) — plus `normalizeOpenAiBaseUrl`. Pure; the probing half is `services/providerReadiness.js`. Optional `setupStateDetail` overrides `providerReadiness`'s per-state prose for a runtime whose local setup is not a model cache (vLLM's is a compose project). || `managedDaemon.js` | Shared mechanism for the local daemons PortOS runs as optional PM2 processes (`services/llamaServerManager.js` → `portos-llama-server`, `services/mtplxServerManager.js` → `portos-mtplx`). `createDaemonLogBuffer({maxLines?})` is the bounded timestamped ring buffer of what PortOS logged around a launch, plus `withPm2Logs(output)` → that buffer followed by anything `pm2 logs` has which it doesn't already hold, deduped and re-capped (PM2's lines are a VIEW, never folded into the buffer — PM2 owns them and re-reads them every status call). `pm2ArgValue(args, flag)` reads one value back out of a PM2 process's recorded argv so a manager can recover a still-online daemon's launch config after a PortOS restart; `null` means the flag was absent, which a relaunch must leave off rather than defaulting. Deliberately mechanism only — what a launch line means and when a daemon may start is exactly what differs between the two. || `mtplxModels.js` | `listMtplxCachedModels({command?})` → `{models, error}` from `mtplx models --json` (a local directory listing — no network, no model load) and `pickMtplxCachedModel(models)` → the repo id to hand `mtplx serve --model`. `models: null` means the cache could not be READ (no binary, command failed, unparseable) and is deliberately distinct from `[]` (read, and empty), because `services/localRuntimeSetup.js` starts MTPLX on its own default in the first case and refuses with the `mtplx pull` command in the second. Exists because `mtplx serve` defaults `--model` to one hard-coded checkpoint and exits 1 before binding when that repo is not cached — even on a host holding a different MTP model that serves fine. Picks only entries MTPLX itself calls complete (`validation.ok !== false`, so a half-finished pull is not served), preferring one with a recorded `mtplx_runtime.json` exactness contract. `describeMtplxCache(cache)` → `{state: 'unknown'\|'empty'\|'partial'\|'ready', model, count, error}` folds both into the one value `services/providerReadiness.js` puts on the checklist and `describeRuntimeSetup` picks a button from — so an empty cache is named up front instead of only inside the failure of a Start that could never work. |-| `vllmQwenProject.js` | `resolveVllmProjectDir()` / `inspectVllmQwenProject()` → `{dir, hasProject, composeFile, hasWeights, weightsRoot}` for the operator-cloned syv-ai/qwen38-27b-rtx3090 compose project, plus `vllmStartBlockedReason(project)` → the prose refusal (or `null`). Directory reads only — never runs docker or touches a registry. `hasWeights` is tri-state: `true` found / `false` caches read and empty / `null` no cache readable (a docker-volume cache is invisible from a native-Win32 PortOS), and `services/localRuntimeSetup.js` refuses to `docker compose up` on anything but `true` so the start button can never kick off the ~20 GB prepare. Overrides: `VLLM_QWEN_PROJECT_DIR`, `VLLM_QWEN_WEIGHTS_DIR`. |+| `vllmQwenProject.js` | `resolveVllmProjectDir()` / `inspectVllmQwenProject()` → `{dir, hasProject, composeFile, hasWeights, weightsRoot}` for the operator-cloned syv-ai/qwen38-27b-rtx3090 compose project, plus `vllmStartBlockedReason(project)` → the prose refusal (or `null`), and `vllmProjectSetupState(project)` → `ready`/`empty`/`unknown` for the readiness checklist. Directory reads only — never runs docker or touches a registry. `hasWeights` is tri-state: `true` found / `false` caches read and empty / `null` no cache readable (a docker-volume cache is invisible from a native-Win32 PortOS), and `services/localRuntimeSetup.js` refuses to `docker compose up` on anything but `true` so the start button can never kick off the ~20 GB prepare. Overrides: `VLLM_QWEN_PROJECT_DIR`, `VLLM_QWEN_WEIGHTS_DIR`. || `qwenAgentParsers.js` | The tool-call / reasoning parser flags a local runtime MUST carry to serve a Qwen3-family model to a coding agent — one table PortOS owns instead of three docs. `QWEN_AGENT_PARSERS` maps runtime → `{toolCallParser, reasoningParser, enableAutoToolChoice}` (vLLM `qwen3_xml` + `--enable-auto-tool-choice`, SGLang `qwen3_coder` + `--reasoning-parser qwen3`, llama both `null` — a positive "no such flag today", not a placeholder). `parserFlagsFor(runtime)` returns the argv fragment (always an array, so no caller type-checks) and `vllmExtraArgs()` its string form for the compose project's `.env` `EXTRA_ARGS`; an unknown runtime THROWS, because the failure it prevents is silent — a parser-less server answers fluently and returns tool markup as ordinary text with `tool_calls: null`, so the agent never touches a file. Spellings are empirical (`docs/research/2026-08-21-qwen38-rtx3090-vllm.md`, `…-sglang-qwen38-27b.md`); never auto-detect one from the chat template — that is how `hermes` got picked. Pure. |+| `vllmQwenProvision.js` | The `.env` half of provisioning that same project: `generateVllmApiKey()`, `isWsl2Engine()` (win32 counts — Docker Desktop's engine IS a WSL2 VM), `vllmEnvDefaults({apiKey, wsl2})` → the load-bearing tool-parser/pin-memory/alloc-conf settings, and `mergeEnvFileContents(existing, defaults)` → `{contents, added, kept, effective}`. **Additive only** — an operator's existing key or tuning is never overwritten, and `effective` reports what the container will actually read. Plus `WSL2_PREPARE_MIN_BYTES` / `WSL2_PREPARE_CONFIG_HINT` for the ceiling `prepare` needs (detected and warned about, never raised). || `openAiModelsProbe.js` | `probeOpenAiModels(baseUrl, { timeoutMs, apiKey })` → `{ reachable, models, error }` — the one `GET {base}/models` probe for the local OpenAI-compatible daemons, shared by `services/providerReadiness.js` and `services/llamaServerManager.js`. Distinguishes unreachable from reachable-but-unlistable (`models: null`) from up-with-nothing-loaded (`[]`), names the real transport failure via `describeFetchError` (undici reports every one as a bare `fetch failed`), and cancels an unread body on a non-OK response. `apiKey` attaches a Bearer header for a key-gated daemon (vLLM's compose stack), and a 401/403 answers `reachable: true` with `error: 'authentication required'` — a server that refused the request is definitively running, and calling it unreachable would send the user to start it again. Consolidated after the two copies drifted — one passed its timeout as a `timeout` key inside the fetch init object, where it is not an option, silently running a 500ms poll loop on the 15s default. || `openAiChatStream.js` | `streamOpenAiChat({ endpoint, apiKey, model, messages, temperature, maxTokens, extraBody, signal, onChunk, onStats })` → the streamed text — one streaming `POST {base}/chat/completions` against any local OpenAI-compatible daemon; `streamOllamaChat(...)` is the assessment-only native `/api/chat` transport that preserves Ollama's exact eval counts and nanosecond timings. Also exports `buildMessages`, `parseStreamFrame`, `parseOllamaStreamFrame`, `normalizeUsage` (snake/camel/Ollama token-count keys → `{completionTokens, promptTokens}`, `null` = not reported), and `resolvePartialOutput`. Registering `onStats` on the OpenAI path asks for token counts; a daemon that rejects `stream_options` is retried once without it and remembered per endpoint. Sibling of `openAiModelsProbe.js`. Shared by `services/localLlmPlayground.js` (provider-backed runs with a `/runs` record) and its `runEndpointLlmTest` (a bare loopback daemon PortOS holds no provider record for, which is how `services/localModelAssessments.js` measures llama.cpp / MTPLX / vLLM). An abort mid-stream throws with `.partialOutput` carrying what already streamed. || `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: layers `baseEnv → before → Ollama-Claude defaults → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. The Ollama-Claude layer raises Claude Code's default output ceiling to 65,536 tokens so a thinking-capable local model cannot finish its reasoning past the stock 32K ceiling and die before its final tool call; an explicit provider env value wins. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |diff --git a/server/lib/index.js b/server/lib/index.jsindex bb5146ea60..1ac2ce4e80 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -159,6 +159,7 @@ export * from './mtplxModels.js';export * from './managedDaemon.js';export * from './vllmQwenProject.js';export * from './qwenAgentParsers.js';+export * from './vllmQwenProvision.js';export * from './openAiModelsProbe.js';export * from './openAiChatStream.js';// `runners.js` re-defines `isFlux2`/`isZImage`/`isErnie` that also live indiff --git a/server/lib/localProviderRuntime.js b/server/lib/localProviderRuntime.jsindex 92ec68d803..66cfe0e7d0 100644--- a/server/lib/localProviderRuntime.js+++ b/server/lib/localProviderRuntime.js@@ -179,7 +179,15 @@ export const LOCAL_RUNTIMES = Object.freeze({// operator-owned ~20 GB prepare step, not something PortOS downloads.manageUrl: null,docsUrl: 'https://github.com/atomantic/PortOS/blob/main/docs/features/qwen38-rtx3090.md',- modelsHint: 'Clone syv-ai/qwen38-27b-rtx3090 and run its prepare step once — PortOS never pulls the image or the ~20 GB of weights.',+ modelsHint: 'Clone syv-ai/qwen38-27b-rtx3090 and run its prepare step once — or let the checklist do it, which is the only path that spends the ~30 GB.',+ // What each local-setup state MEANS for this runtime, overriding+ // `providerReadiness`'s model-cache prose. The thing that is missing here is+ // a whole compose project, not a checkpoint, and "no weights cached" would+ // send the operator looking for a download that was never the first step.+ setupStateDetail: Object.freeze({+ empty: 'No prepared compose project was found — its image and the ~20 GB of weights are not on disk yet.',+ ready: 'The compose project is built and its weights are on disk; this can be confirmed once the container is running.',+ }),// One container, one checkpoint — but its served id is baked into the// compose project, so PortOS has no launch line of its own to rename.servesOneModel: true,diff --git a/server/lib/vllmQwenProject.js b/server/lib/vllmQwenProject.jsindex 81281609d9..b6d0c25261 100644--- a/server/lib/vllmQwenProject.js+++ b/server/lib/vllmQwenProject.js@@ -194,3 +194,34 @@ export function vllmStartBlockedReason(project) {}return null;}++/**+ * The same inspection, reduced to the four-state vocabulary the readiness+ * checklist speaks (`services/localRuntimeSetup.js`'s `readRuntimeWeights`).+ *+ * `'empty'` is what makes the checklist offer the provisioning action, so it+ * must mean "provisioning is exactly the fix" and nothing looser:+ *+ * - **no project directory at all** — the ordinary first-run shape. Nothing+ * to clone over, so the clone/build/prepare sequence is precisely right.+ * - **a project whose caches read empty** — cloned, never prepared.+ *+ * Everything else is `'unknown'`, never `'empty'`. A directory that exists but+ * holds no compose file is one PortOS does not recognize, and cloning into it+ * would either fail or scatter a checkout across the operator's files; a cache+ * that could not be READ (the normal Windows shape before+ * `VLLM_QWEN_PROJECT_DIR` points at the UNC path) is not a cache that is empty,+ * and treating it as one would offer to re-download ~20 GB that is already+ * there. Both keep today's behavior: the Start button appears and refuses with+ * the reason, which is the message that actually helps.+ *+ * @param {{hasProject?:boolean, composeFile?:string|null, hasWeights?:boolean|null}} project+ * @returns {'ready'|'empty'|'unknown'}+ */+export function vllmProjectSetupState(project) {+ if (!project?.hasProject) return 'empty';+ if (!project.composeFile) return 'unknown';+ if (project.hasWeights === true) return 'ready';+ if (project.hasWeights === false) return 'empty';+ return 'unknown';+}diff --git a/server/lib/vllmQwenProject.test.js b/server/lib/vllmQwenProject.test.jsindex acbf20ad5d..81ac7a4fe6 100644--- a/server/lib/vllmQwenProject.test.js+++ b/server/lib/vllmQwenProject.test.js@@ -9,6 +9,7 @@ import {inspectVllmQwenProject,resolveVllmProjectDir,vllmDefaultProjectDir,+ vllmProjectSetupState,vllmStartBlockedReason,} from './vllmQwenProject.js';@@ -157,3 +158,34 @@ describe('inspectVllmQwenProject', () => {expect(project.hasWeights).toBe(true);});});++describe('vllmProjectSetupState', () => {+ const project = (over = {}) => ({ dir: '/home/example/qwen-serving', hasProject: true, composeFile: 'docker-compose.yml', hasWeights: true, weightsRoot: null, ...over });++ it('reports a prepared project as ready', () => {+ expect(vllmProjectSetupState(project())).toBe('ready');+ });++ it('reports the two states where cloning/building/preparing IS the fix', () => {+ // Nothing cloned at all — the ordinary first-run shape.+ expect(vllmProjectSetupState(project({ hasProject: false, composeFile: null, hasWeights: null }))).toBe('empty');+ // Cloned, never prepared.+ expect(vllmProjectSetupState(project({ hasWeights: false }))).toBe('empty');+ });++ it('never reports a cache it could not READ as empty', () => {+ // The normal Windows shape before VLLM_QWEN_PROJECT_DIR points at the UNC+ // path. Calling this `empty` would offer to re-download ~20 GB that is+ // already on disk; `unknown` keeps the Start button and its real refusal.+ expect(vllmProjectSetupState(project({ hasWeights: null }))).toBe('unknown');+ });++ it('never offers to clone into a directory it does not recognize', () => {+ // A directory that exists but holds no compose file is not this project.+ expect(vllmProjectSetupState(project({ composeFile: null, hasWeights: null }))).toBe('unknown');+ });++ it('treats a missing inspection as empty rather than throwing', () => {+ expect(vllmProjectSetupState(null)).toBe('empty');+ });+});diff --git a/server/lib/vllmQwenProvision.js b/server/lib/vllmQwenProvision.jsnew file mode 100644index 0000000000..90a4e7d649--- /dev/null+++ b/server/lib/vllmQwenProvision.js@@ -0,0 +1,176 @@+/**+ * The `.env` half of provisioning the vLLM Qwen3.8-27B compose project.+ *+ * `vllmQwenProject.js` answers "is this project prepared?" by reading directory+ * entries. This module answers the next question — "what must its `.env` say+ * before `docker compose build` is worth running?" — and nothing else: it+ * generates the container's API key, decides which variables this host needs,+ * and merges them into whatever `.env` is already there.+ *+ * **Every value here is load-bearing, and each one fails somewhere other than+ * its cause** (`docs/research/2026-08-21-qwen38-rtx3090-vllm.md` is the record+ * of finding each by hitting it):+ *+ * - `EXTRA_ARGS=--enable-auto-tool-choice --tool-call-parser qwen3_xml` —+ * without it vLLM rejects the agent's very first turn; with `hermes` instead+ * of `qwen3_xml` the server starts, answers, and silently never emits a tool+ * call, because Qwen3.8 writes XML where that parser expects Hermes JSON.+ * - `VLLM_WSL2_ENABLE_PIN_MEMORY=1` — vLLM disables pinned host memory on WSL,+ * its GPU model runner needs UVA buffers that require it, and compose's+ * `unless-stopped` turns the resulting `RuntimeError: UVA is not available`+ * into a quiet crash-loop rather than one visible failure.+ * - `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False` — expandable segments+ * need CUDA VMM APIs WSL2 only partly implements, so weight loading dies+ * inside `gptq_marlin_repack` with what reads as an out-of-memory error and+ * is not one.+ *+ * **Merging is additive, never destructive.** An operator who already tuned+ * `GPU_UTIL`, `DFLASH_TOKENS`, or their own `VLLM_API_KEY` keeps every one of+ * them; only keys the file does not already mention are appended. That is the+ * same shape `scripts/setup-data.js` uses for seeded JSON, and it is why the+ * generated key is a *fallback*: `mergeEnvFileContents` reports the values that+ * ended up in effect, so the caller propagates the key the container will+ * actually use rather than the one it happened to generate.+ */++import { randomBytes } from 'crypto';++/** Bytes of entropy in a generated key — matches the doc's `openssl rand -hex 24`. */+const API_KEY_BYTES = 24;++/** The variable the container reads its bearer token from. */+export const VLLM_API_KEY_VAR = 'VLLM_API_KEY';++/**+ * A fresh bearer token for the container. Hex rather than base64 so it survives+ * an unquoted `.env` line, a compose interpolation, and an `Authorization`+ * header without any escaping.+ */+export const generateVllmApiKey = () => randomBytes(API_KEY_BYTES).toString('hex');++/**+ * Whether this PortOS is driving a WSL2-hosted engine, and therefore needs the+ * two mandatory WSL2 variables above.+ *+ * The feature doc's shell snippet tests `/proc/version` for `microsoft`, which+ * is correct for an operator typing inside the distro. It is NOT sufficient+ * here: PortOS commonly runs as a native Win32 process driving Docker Desktop,+ * whose engine is a WSL2 VM — there is no `/proc/version` to match, and omitting+ * the two variables on that host produces exactly the silent crash-loop they+ * exist to prevent. So win32 counts too, and the file read is what covers a+ * PortOS running inside the distro itself.+ *+ * @param {{platform?: string, procVersion?: string|null}} [host]+ * @returns {boolean}+ */+export function isWsl2Engine({ platform = process.platform, procVersion = null } = {}) {+ if (platform === 'win32') return true;+ return /microsoft/i.test(String(procVersion || ''));+}++/**+ * Every key the provisioning step wants present, in write order.+ *+ * @param {{apiKey: string, wsl2?: boolean}} options+ * @returns {Array<[string, string]>}+ */+export function vllmEnvDefaults({ apiKey, wsl2 = false }) {+ return [+ [VLLM_API_KEY_VAR, apiKey],+ ['SPEC', 'dflash2'],+ ['PREFIX_CACHE', '1'],+ ['EXTRA_ARGS', '--enable-auto-tool-choice --tool-call-parser qwen3_xml'],+ ...(wsl2+ ? [+ ['VLLM_WSL2_ENABLE_PIN_MEMORY', '1'],+ ['PYTORCH_CUDA_ALLOC_CONF', 'expandable_segments:False'],+ ]+ : []),+ ];+}++/**+ * Which keys a `.env` already mentions.+ *+ * Deliberately keyed on *mention*, not on truthiness: a commented-out key is+ * treated as absent (it is not in effect), while a key set to the empty string+ * is treated as present, because an operator who wrote `EXTRA_ARGS=` meant it.+ * Collapsing those two into one state is the footgun this module exists to+ * avoid — its whole contract is that it never overrules a decision already in+ * the file.+ *+ * @param {string} contents+ * @returns {Map<string, string>} key → value, with surrounding quotes stripped+ */+export function parseEnvContents(contents) {+ const found = new Map();+ for (const line of String(contents || '').split('\n')) {+ const trimmed = line.trim();+ if (!trimmed || trimmed.startsWith('#')) continue;+ const idx = trimmed.indexOf('=');+ if (idx <= 0) continue;+ const key = trimmed.slice(0, idx).trim();+ let value = trimmed.slice(idx + 1).trim();+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {+ value = value.slice(1, -1);+ }+ // First mention wins, matching how a shell sourcing the file top-to-bottom+ // would NOT — but compose reads the last one. Either way the value is the+ // operator's, and this module only needs to know it must not add the key.+ if (!found.has(key)) found.set(key, value);+ }+ return found;+}++/**+ * Append the missing defaults to an existing `.env`, changing nothing else.+ *+ * @param {string} existing - current file contents (`''` when there is no file)+ * @param {Array<[string, string]>} defaults - from `vllmEnvDefaults`+ * @returns {{contents: string, added: string[], kept: string[], effective: Record<string, string>}}+ * `added`/`kept` are key NAMES only, so a caller can log them; `effective` is+ * what the container will read, and holds the secret.+ */+export function mergeEnvFileContents(existing, defaults) {+ const current = parseEnvContents(existing);+ const added = [];+ const kept = [];+ const effective = {};+ const lines = [];++ for (const [key, value] of defaults) {+ if (current.has(key)) {+ kept.push(key);+ effective[key] = current.get(key);+ continue;+ }+ added.push(key);+ effective[key] = value;+ lines.push(`${key}=${value}`);+ }++ const base = String(existing || '');+ if (lines.length === 0) return { contents: base, added, kept, effective };++ // A file that does not end in a newline would otherwise splice the first new+ // key onto the operator's last line and silently corrupt both.+ const separator = base.length === 0 || base.endsWith('\n') ? '' : '\n';+ return { contents: `${base}${separator}${lines.join('\n')}\n`, added, kept, effective };+}++/**+ * The `.wslconfig` ceiling `prepare` needs.+ *+ * The requantization step holds a whole 2.5 GB shard plus several float32 copies+ * of a 248k-row `lm_head`, and WSL2 defaults its VM to half the host's RAM. Below+ * this the step is SIGKILLed and reports only `Killed` / exit 137 — a symptom+ * that names nothing about WSL. PortOS never raises the ceiling itself: that+ * means editing `%UserProfile%\.wslconfig` and running `wsl --shutdown`, which+ * takes the whole VM down including a PostgreSQL container this install may be+ * using.+ */+export const WSL2_PREPARE_MIN_BYTES = 24 * 1024 * 1024 * 1024;++/** The block to paste, named in the warning so the fix is copy-pasteable. */+export const WSL2_PREPARE_CONFIG_HINT =+ 'Give the WSL2 VM ~24 GB in %UserProfile%\\.wslconfig ([wsl2] memory=24GB, swap=16GB) and run `wsl --shutdown` for it to take effect — stop your containers first, that takes the whole VM down.';diff --git a/server/lib/vllmQwenProvision.test.js b/server/lib/vllmQwenProvision.test.jsnew file mode 100644index 0000000000..944e4b500d--- /dev/null+++ b/server/lib/vllmQwenProvision.test.js@@ -0,0 +1,125 @@+import { describe, expect, it } from 'vitest';++import {+ generateVllmApiKey,+ isWsl2Engine,+ mergeEnvFileContents,+ parseEnvContents,+ vllmEnvDefaults,+ VLLM_API_KEY_VAR,+} from './vllmQwenProvision.js';++const defaults = (wsl2 = false) => vllmEnvDefaults({ apiKey: 'generated-key', wsl2 });++describe('generateVllmApiKey', () => {+ it('mints a fresh 24-byte hex token each call', () => {+ const a = generateVllmApiKey();+ const b = generateVllmApiKey();+ expect(a).toMatch(/^[0-9a-f]{48}$/);+ expect(b).not.toBe(a);+ });+});++describe('isWsl2Engine', () => {+ it('counts win32 — Docker Desktop\'s engine IS a WSL2 VM', () => {+ // The feature doc's shell snippet tests /proc/version, which a native-Win32+ // PortOS cannot read at all. Trusting only that test is what would omit the+ // two mandatory WSL2 variables on exactly the host that needs them, and the+ // symptom is a quiet compose crash-loop rather than an error.+ expect(isWsl2Engine({ platform: 'win32', procVersion: null })).toBe(true);+ });++ it('matches a WSL2 distro by its own /proc/version', () => {+ expect(isWsl2Engine({ platform: 'linux', procVersion: 'Linux version 5.15.0-microsoft-standard-WSL2' })).toBe(true);+ });++ it('is false on native Linux and on darwin', () => {+ expect(isWsl2Engine({ platform: 'linux', procVersion: 'Linux version 6.8.0-generic' })).toBe(false);+ expect(isWsl2Engine({ platform: 'linux', procVersion: null })).toBe(false);+ expect(isWsl2Engine({ platform: 'darwin', procVersion: null })).toBe(false);+ });+});++describe('vllmEnvDefaults', () => {+ it('always carries the tool-parser line, which is the setting agents die without', () => {+ const keys = Object.fromEntries(defaults());+ expect(keys.EXTRA_ARGS).toBe('--enable-auto-tool-choice --tool-call-parser qwen3_xml');+ expect(keys.SPEC).toBe('dflash2');+ expect(keys.PREFIX_CACHE).toBe('1');+ expect(keys[VLLM_API_KEY_VAR]).toBe('generated-key');+ });++ it('adds the WSL2 pair only for a WSL2 engine', () => {+ expect(Object.fromEntries(defaults(false))).not.toHaveProperty('VLLM_WSL2_ENABLE_PIN_MEMORY');+ expect(Object.fromEntries(defaults(true))).toMatchObject({+ VLLM_WSL2_ENABLE_PIN_MEMORY: '1',+ PYTORCH_CUDA_ALLOC_CONF: 'expandable_segments:False',+ });+ });+});++describe('parseEnvContents', () => {+ it('reads plain, quoted, and whitespace-padded assignments', () => {+ const found = parseEnvContents(' A=1\nB="two"\nC=\'three\'\n');+ expect(Object.fromEntries(found)).toEqual({ A: '1', B: 'two', C: 'three' });+ });++ it('treats a present-but-empty value as SET and a commented-out key as absent', () => {+ // The distinction the whole module turns on: `EXTRA_ARGS=` is a decision the+ // operator made, `# EXTRA_ARGS=…` is a line that is not in effect.+ const found = parseEnvContents('EXTRA_ARGS=\n# SPEC=dflash2\n');+ expect(found.has('EXTRA_ARGS')).toBe(true);+ expect(found.get('EXTRA_ARGS')).toBe('');+ expect(found.has('SPEC')).toBe(false);+ });++ it('ignores blank lines and lines with no key', () => {+ expect([...parseEnvContents('\n\n=orphan\nnot-an-assignment\n').keys()]).toEqual([]);+ });+});++describe('mergeEnvFileContents', () => {+ it('appends only the missing keys and reports both sides by name', () => {+ const result = mergeEnvFileContents('SPEC=custom\n', defaults());+ expect(result.kept).toEqual(['SPEC']);+ expect(result.added).toEqual([VLLM_API_KEY_VAR, 'PREFIX_CACHE', 'EXTRA_ARGS']);+ expect(result.contents.startsWith('SPEC=custom\n')).toBe(true);+ expect(result.contents.match(/^SPEC=/gm)).toHaveLength(1);+ });++ it('never overwrites an operator value — and reports THEIRS as effective', () => {+ // The caller propagates `effective`, so a project that already had a key+ // keeps serving on it and the providers are pointed at that one.+ const result = mergeEnvFileContents('VLLM_API_KEY=operator-chosen\nGPU_UTIL=0.93\n', defaults());+ expect(result.effective[VLLM_API_KEY_VAR]).toBe('operator-chosen');+ expect(result.contents).toContain('GPU_UTIL=0.93');+ expect(result.contents.match(/^VLLM_API_KEY=/gm)).toHaveLength(1);+ });++ it('writes every default into an absent file', () => {+ const result = mergeEnvFileContents('', defaults(true));+ expect(result.kept).toEqual([]);+ expect(result.added).toHaveLength(6);+ expect(result.contents).toBe([+ 'VLLM_API_KEY=generated-key',+ 'SPEC=dflash2',+ 'PREFIX_CACHE=1',+ 'EXTRA_ARGS=--enable-auto-tool-choice --tool-call-parser qwen3_xml',+ 'VLLM_WSL2_ENABLE_PIN_MEMORY=1',+ 'PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False',+ '',+ ].join('\n'));+ });++ it('does not splice onto a file that lacks a trailing newline', () => {+ const result = mergeEnvFileContents('GPU_UTIL=0.93', [['SPEC', 'dflash2']]);+ expect(result.contents).toBe('GPU_UTIL=0.93\nSPEC=dflash2\n');+ });++ it('returns the file untouched when nothing is missing', () => {+ const existing = 'VLLM_API_KEY=k\nSPEC=s\nPREFIX_CACHE=0\nEXTRA_ARGS=--whatever\n';+ const result = mergeEnvFileContents(existing, defaults());+ expect(result.contents).toBe(existing);+ expect(result.added).toEqual([]);+ });+});diff --git a/server/services/localRuntimeSetup.js b/server/services/localRuntimeSetup.jsindex b75094112b..a89c55ef4a 100644--- a/server/services/localRuntimeSetup.js+++ b/server/services/localRuntimeSetup.js@@ -38,22 +38,29 @@* here is the same PM2 process (`portos-mtplx`) the Models → LLMs page can* stop, log, and persist across a reboot — the two surfaces cannot drift* onto different install commands or a daemon only one of them can see.- * - **The vLLM container is never provisioned.** Its start row brings up an- * already-prepared compose project and nothing else: no image pull, no- * weight download, no docker/WSL2/NVIDIA-toolkit install. A project that is- * not demonstrably prepared is refused with the command that prepares it.+ * - **The vLLM container is never provisioned by a Start.** Its start row+ * brings up an already-prepared compose project and nothing else: no image+ * build, no weight download, no docker/WSL2/NVIDIA-toolkit install. A+ * project that is not demonstrably prepared is refused — and, since #4767,+ * the checklist then offers the separate action that DOES provision it,+ * "Clone, build & prepare … (~30 GB), then start", which is the same+ * name-the-payload consent shape as MTPLX's `pull-start`. `install()` still+ * refuses: Docker Desktop, the NVIDIA Container Toolkit and WSL2 are+ * host-level operator decisions with driver requirements PortOS cannot+ * judge, and this provisions the PROJECT on a host already capable of+ * running it.*/import { LOCAL_RUNTIMES, localEndpointPort } from '../lib/localProviderRuntime.js';import { describeMtplxCache, listMtplxCachedModels } from '../lib/mtplxModels.js';import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';-import { inspectVllmQwenProject, vllmStartBlockedReason } from '../lib/vllmQwenProject.js';import { findCommandOnPath } from '../lib/processEnv.js';import { runStreamingCommand } from '../lib/streamingSpawn.js';import { installLlamaServer } from './llamaServerManager.js';import { installMtplx, startMtplxServer, MTPLX_UNSUPPORTED_REASON } from './mtplxServerManager.js';import { controlOllamaServer, installBackend } from './localLlm.js';import { isAppInstalled as isLmStudioAppInstalled } from './lmStudioManager.js';+import { provisionVllmQwenProject, readVllmQwenSetupState, startVllmQwenProject } from './vllmQwenManager.js';/** A short command that only asks a running daemon to do something. */const CONTROL_TIMEOUT_MS = 60 * 1000;@@ -99,18 +106,98 @@ const MTPLX_NO_MODEL_ERROR = 'no model weights are cached, so its server exits bconst mtplxPartialCacheError = (count) =>`its cache holds ${count} model${count === 1 ? '' : 's'}, but none passed its own file check — an interrupted download leaves a partial pack behind. Use “Download the default model & start MTPLX” on the checklist to re-fetch it, or pick another checkpoint on the MTPLX card in Models → LLMs.`;-/** What each `action` is called on the button and in the log. */-const ACTION_LABELS = {- install: (label) => `Install ${label}`,- start: (label) => `Start ${label}`,- 'install-start': (label) => `Install & start ${label}`,- // Names the download so the click IS the consent — the one action here that- // spends bandwidth measured in gigabytes.- 'pull-start': (label) => `Download the default model & start ${label}`,-};+/**+ * The provisioning actions: the ones whose click IS the consent, because each+ * spends bandwidth measured in gigabytes.+ *+ * A row owns at most ONE of them, declared as `row.provision = { action, run }`+ * — and `describeRuntimeSetup` offers it only when that runtime's own offline+ * read proves a plain Start cannot work. Everything+ * needed to report the step lives in one entry so the button label and the+ * progress lines cannot drift into describing different amounts of bandwidth.+ */+const PROVISION_STEPS = Object.freeze({+ 'pull-start': Object.freeze({+ // Names the download so the click IS the consent.+ label: (label) => `Download the default model & start ${label}`,+ refused: (label) => `PortOS cannot download model weights for ${label}.`,+ failed: (label, error) => `${label} model download failed: ${error}`,+ done: (label) => `${label}'s default checkpoint is cached.`,+ cancelled: 'Cancelled after the download — the weights are cached, but nothing was started.',+ }),+ 'provision-start': Object.freeze({+ // The payload named before the click: a ~9.5 GB image built on this host+ // plus ~20 GB of weights. `install()` still refuses — this provisions the+ // PROJECT on a host whose docker / NVIDIA / WSL2 setup is already the+ // operator's own decision.+ label: (label) => `Clone, build & prepare ${label} (~30 GB), then start`,+ refused: (label) => `PortOS cannot provision a compose project for ${label}.`,+ failed: (label, error) => `${label} provisioning failed: ${error}`,+ done: (label) => `${label}'s compose project is built and prepared.`,+ cancelled: 'Cancelled after the prepare step — the project is ready, but nothing was started.',+ }),+});++/**+ * What each action actually DOES, and what it is called on the button.+ *+ * The capabilities are declared rather than spelled: `setupHint` used to ask+ * whether an action name *contained* `install` or `start`, which worked only+ * because every name happened to. `provision-start` broke the coincidence+ * (it covers the download that `pull` used to stand for), and the next action+ * named `bootstrap` or `prepare` would break it again — silently, since a+ * missing hint fails no test. Declaring the three axes means a new action must+ * answer them, and `describeRuntimeSetup` can hand the client `provisions`+ * instead of the client re-deriving it from the name.+ */+const ACTION_CAPABILITIES = Object.freeze({+ install: Object.freeze({ label: (label) => `Install ${label}`, installs: true, starts: false, provisions: false }),+ start: Object.freeze({ label: (label) => `Start ${label}`, installs: false, starts: true, provisions: false }),+ 'install-start': Object.freeze({ label: (label) => `Install & start ${label}`, installs: true, starts: true, provisions: false }),+ ...Object.fromEntries(Object.entries(PROVISION_STEPS).map(([action, step]) => [+ action,+ Object.freeze({ label: step.label, installs: false, starts: true, provisions: true }),+ ])),+});/** Every action `runLocalRuntimeSetup` accepts — route validation reads this. */-export const SETUP_ACTIONS = Object.freeze(Object.keys(ACTION_LABELS));+export const SETUP_ACTIONS = Object.freeze(Object.keys(ACTION_CAPABILITIES));++/**+ * Does this action cover `installs` / `starts` / `provisions`?+ *+ * Exported so `providerReadiness.js` points each unmet check at the button that+ * fixes it by asking THIS table, rather than matching substrings of the name.+ */+export const actionCovers = (action, capability) => ACTION_CAPABILITIES[action]?.[capability] === true;++/**+ * The provisioning action a row owns, or `null` when it has no such step.+ *+ * A row declares BOTH halves or neither — there is no default. An implicit+ * `pull-start` fallback would hand a new row "Download the default model &+ * start X" and `X model download failed:` for a step that is not a download,+ * which is the exact mislabeling PROVISION_STEPS exists to end.+ */+const rowProvisionAction = (row) => row?.provision?.action || null;++/**+ * Fetch MTPLX's OWN default verified checkpoint — no repo id from the request,+ * so this cannot be pointed at an arbitrary download. Runs only for the+ * `pull-start` action, which the user clicks by its full name.+ */+async function pullMtplxDefaultCheckpoint({ emit, isCancelled }) {+ const binary = findCommandOnPath('mtplx');+ if (!binary) return { success: false, error: '`mtplx` was not found on PortOS\'s PATH. Restart PortOS so it picks up the new bin directory, then try again.' };+ emit('Downloading MTPLX\'s default verified checkpoint. This is a multi-gigabyte download and can take a long while — leave this window open to watch it.');+ // `mtplx pull` redraws one progress line with a bare `\r`; splitting on+ // newlines alone would leave the stream silent for the whole download.+ // `isCancelled` is load-bearing here, not decoration: this is the one step+ // that can run for HOURS, and the route holds its single-setup lock until this+ // promise settles. Without it, closing the modal leaves the download running+ // and every other runtime's setup button refused for the rest of it.+ return runStreamingCommand(binary, ['pull'], emit, { timeoutMs: WEIGHTS_TIMEOUT_MS, splitRe: PROGRESS_SPLIT_RE, isCancelled });+}/*** One row per local runtime PortOS can set up on its own.@@ -119,6 +206,11 @@ export const SETUP_ACTIONS = Object.freeze(Object.keys(ACTION_LABELS));* `install` and `start` are async steps taking `({ emit, endpoint, isCancelled })`* and returning `{ success, error?, note? }`; `start: null` means PortOS cannot* start this runtime unattended and the checklist keeps its existing link.+ *+ * `provision: { action, run }` is the optional gigabyte-spending step: `action`+ * names its PROVISION_STEPS entry (which supplies every string reported about+ * it) and `run` takes `({ emit, isCancelled })`. Multi-step work belongs in a+ * manager module — this table stays a table.*/const SETUP_ROWS = Object.freeze({mtplx: Object.freeze({@@ -141,24 +233,12 @@ const SETUP_ROWS = Object.freeze({async weights() {return describeMtplxCache(await listMtplxCachedModels()).state;},- /**- * Fetch MTPLX's OWN default verified checkpoint — no repo id from the- * request, so this cannot be pointed at an arbitrary download. Runs only- * for the `pull-start` action, which the user clicks by its full name.- */- async pull({ emit, isCancelled }) {- const binary = findCommandOnPath('mtplx');- if (!binary) return { success: false, error: '`mtplx` was not found on PortOS\'s PATH. Restart PortOS so it picks up the new bin directory, then try again.' };- emit('Downloading MTPLX\'s default verified checkpoint. This is a multi-gigabyte download and can take a long while — leave this window open to watch it.');- // `mtplx pull` redraws one progress line with a bare `\r`; splitting on- // newlines alone would leave the stream silent for the whole download.- // `isCancelled` is load-bearing here, not decoration: this is the one- // step that can run for HOURS, and the route holds its single-setup lock- // until this promise settles. Without it, closing the modal leaves the- // download running and every other runtime's setup button refused for the- // rest of it.- return runStreamingCommand(binary, ['pull'], emit, { timeoutMs: WEIGHTS_TIMEOUT_MS, splitRe: PROGRESS_SPLIT_RE, isCancelled });- },+ provision: Object.freeze({+ action: 'pull-start',+ async run({ emit, isCancelled }) {+ return pullMtplxDefaultCheckpoint({ emit, isCancelled });+ },+ }),async start({ emit, endpoint, isCancelled }) {// `mtplx serve` defaults `--model` to ONE hard-coded checkpoint and exits// 1 before binding when that repo is not in its cache — even on a machine@@ -210,25 +290,18 @@ const SETUP_ROWS = Object.freeze({// requirements PortOS cannot judge, and the payload is a ~9.5 GB image.return {success: false,- error: 'PortOS does not install this stack. On the RTX 3090 host, set up WSL2 (or Linux) with Docker and the NVIDIA Container Toolkit, then follow docs/features/qwen38-rtx3090.md to clone and prepare syv-ai/qwen38-27b-rtx3090.',+ error: 'PortOS does not install this stack. On the RTX 3090 host, set up WSL2 (or Linux) with Docker and the NVIDIA Container Toolkit — then the checklist can clone, build and prepare the compose project for you (see docs/features/qwen38-rtx3090.md).',};},- async start({ emit, isCancelled }) {- // Only ever brings up an ALREADY-prepared project — see- // `lib/vllmQwenProject.js` for why each refusal below exists.- const project = await inspectVllmQwenProject();- const blocked = vllmStartBlockedReason(project);- if (blocked) return { success: false, error: blocked };- if (isCancelled()) return { success: false, error: 'Cancelled before the container was started.' };- emit(`Starting the vLLM container from ${project.dir} (${project.composeFile}).`);- emit('The image and weights are already on disk — this only brings the service up.');- return runStreamingCommand(- 'docker',- ['compose', '--profile', 'single', 'up', '-d'],- emit,- { timeoutMs: CONTROL_TIMEOUT_MS, cwd: project.dir },- );- },+ // What is on disk, in the checklist's four-state vocabulary — a directory+ // read, exactly like MTPLX's cache read above. `'empty'` is what makes the+ // checklist offer `provision-start`, and `vllmProjectSetupState` is careful+ // to report it only where cloning/building/preparing IS the fix.+ weights: readVllmQwenSetupState,+ // This row's gigabyte-spending step is a compose provisioning run, not a+ // model download — hence its own PROVISION_STEPS entry.+ provision: Object.freeze({ action: 'provision-start', run: provisionVllmQwenProject }),+ start: startVllmQwenProject,}),ollama: Object.freeze({@@ -290,8 +363,15 @@ const SETUP_ROWS = Object.freeze({* @returns {Promise<'unknown'|'empty'|'partial'|'ready'>}*/export async function readRuntimeWeights(kind) {- const read = SETUP_ROWS[kind]?.weights;- return read ? read() : 'unknown';+ const row = SETUP_ROWS[kind];+ // A platform that cannot run the runtime discards this answer anyway+ // (`describeRuntimeSetup` returns `blockedReason` and ignores `weights`), and+ // the read is not free: vLLM's walks the compose project's candidate cache+ // roots, which on the documented Windows shape is a dozen syscalls across a+ // 9p share. Docker is on PATH almost everywhere, so without this gate a Mac+ // would sweep for an RTX 3090 project once a minute, forever.+ if (!row?.weights || !platformSupported(row)) return 'unknown';+ return row.weights();}/** The cache states that make a start impossible. */@@ -333,21 +413,26 @@ export function describeRuntimeSetup(kind, { installed, running, weights = 'unknif (!needsInstall && !needsStart) return null;if (!platformSupported(row)) {- return { runtime: kind, label: runtime.label, action: null, actionLabel: null, blockedReason: row.unsupportedReason };+ return { runtime: kind, label: runtime.label, action: null, actionLabel: null, provisions: false, blockedReason: row.unsupportedReason };}// Only offered once the binary is here: the cache cannot be read without it,// so an uninstalled runtime's `weights` says nothing and `install-start`// stays the honest first step.- const needsWeights = Boolean(row.pull) && !needsInstall && needsStart && weightsBlockStart(weights);- const action = needsWeights ? 'pull-start'+ const provision = rowProvisionAction(row);+ const needsWeights = Boolean(provision) && !needsInstall && needsStart && weightsBlockStart(weights);+ const action = needsWeights ? provision: needsInstall && needsStart ? 'install-start': needsInstall ? 'install' : 'start';return {runtime: kind,label: runtime.label,action,- actionLabel: ACTION_LABELS[action](runtime.label),+ actionLabel: ACTION_CAPABILITIES[action].label(runtime.label),+ // Whether this click spends gigabytes, answered HERE rather than re-derived+ // from the action name in the client — a hand-kept mirror over there would+ // silently downgrade the next provisioning button to an ordinary one.+ provisions: actionCovers(action, 'provisions'),blockedReason: null,};}@@ -366,8 +451,9 @@ export function describeRuntimeSetup(kind, { installed, running, weights = 'unkn* @param {{endpoint: string, emit: (line: string) => void, isCancelled?: () => boolean, action?: string}} ctx* `isCancelled` is checked between steps so a closed modal does not go on to* start a daemon nobody is watching for. `action` is the one the checklist's- * button named; only `pull-start` adds a step (the model download), and it is- * opt-in precisely so no other action can spend gigabytes of bandwidth. Omit+ * button named; only a PROVISION_STEPS action adds a step (MTPLX's model+ * download, vLLM's clone/build/prepare), and each is opt-in precisely so no+ * other action can spend gigabytes of bandwidth. Omit* it (`null`) and this resolves the action the checklist would offer right* now — see the resolution comment below.* @returns {Promise<{success: boolean, error?: string, message?: string}>}@@ -389,12 +475,16 @@ export async function runLocalRuntimeSetup(kind, { endpoint, emit = () => {}, is}if (!platformSupported(row)) return { success: false, error: row.unsupportedReason };+ const provision = rowProvisionAction(row);+// Refuse a step this runtime does not have BEFORE anything is installed. A// `pull-start` aimed at Ollama would otherwise run Ollama's install on its way// to being refused, and llama.cpp (`start: null`) would return the- // install-succeeded message without ever refusing at all.- if (action === 'pull-start' && !row.pull) {- return { success: false, error: `PortOS cannot download model weights for ${runtime.label}.` };+ // install-succeeded message without ever refusing at all. The mismatch check+ // is by ACTION, not merely by "has a pull": vLLM owns `provision-start`, so a+ // `pull-start` aimed at it is just as wrong as one aimed at Ollama.+ if (actionCovers(action, 'provisions') && action !== provision) {+ return { success: false, error: PROVISION_STEPS[action].refused(runtime.label) };}// Same two signals `providerReadiness.js` uses: the binary on PATH, plus LM@@ -413,7 +503,7 @@ export async function runLocalRuntimeSetup(kind, { endpoint, emit = () => {}, is// `installed &&` mirrors `describeRuntimeSetup`'s own gate: the cache cannot// be read without the binary, so an uninstalled runtime never resolves to a// download — and never spends a cache read to learn that.- const resolved = action || (row.pull && installed && weightsBlockStart(await row.weights()) ? 'pull-start' : 'install-start');+ const resolved = action || (provision && installed && weightsBlockStart(await row.weights()) ? provision : 'install-start');if (!installed) {const result = await row.install({ emit, endpoint: target, isCancelled });@@ -429,15 +519,16 @@ export async function runLocalRuntimeSetup(kind, { endpoint, emit = () => {}, is}if (isCancelled()) return { success: false, error: 'Cancelled after the install — nothing was started.' };- // The ONLY path that downloads weights, and it runs only because the user+ // The ONLY path that spends gigabytes, and it runs only because the user// clicked a button that says so. `describeRuntimeSetup` offers it exactly- // when the cache is provably unusable, which is the state where a plain- // Start would exit before binding a port.- if (resolved === 'pull-start') {- const pulled = await row.pull({ emit, isCancelled });- if (!pulled.success) return { success: false, error: `${runtime.label} model download failed: ${pulled.error}` };- emit(`${runtime.label}'s default checkpoint is cached.`);- if (isCancelled()) return { success: false, error: 'Cancelled after the download — the weights are cached, but nothing was started.' };+ // when the runtime's own offline read is provably unusable, which is the+ // state where a plain Start would exit before binding a port.+ if (resolved === provision) {+ const step = PROVISION_STEPS[provision];+ const pulled = await row.provision.run({ emit, isCancelled });+ if (!pulled.success) return { success: false, error: step.failed(runtime.label, pulled.error) };+ emit(step.done(runtime.label));+ if (isCancelled()) return { success: false, error: step.cancelled };}// The install step may have started it (Ollama's Homebrew service does), sodiff --git a/server/services/localRuntimeSetup.test.js b/server/services/localRuntimeSetup.test.jsindex 265c3f2372..860b34dd54 100644--- a/server/services/localRuntimeSetup.test.js+++ b/server/services/localRuntimeSetup.test.js@@ -44,13 +44,15 @@ const mtplx = vi.hoisted(() => ({MTPLX_UNSUPPORTED_REASON: 'MTPLX runs only on macOS with Apple Silicon.',}));vi.mock('./mtplxServerManager.js', () => mtplx);-// The vLLM compose project on disk. Mocked so the suite never stats a real-// checkout, and so each start case can pick its own refusal.-const vllmProject = vi.hoisted(() => ({- inspectVllmQwenProject: vi.fn(),- vllmStartBlockedReason: vi.fn(() => null),+// The vLLM compose project's clone / build / prepare / start. Mocked so this+// suite asserts what the REGISTRY does — offers the action, refuses the wrong+// one, delegates — while the manager's own suite covers what it does on disk.+const vllmManager = vi.hoisted(() => ({+ readVllmQwenSetupState: vi.fn(async () => 'ready'),+ provisionVllmQwenProject: vi.fn(async () => ({ success: true })),+ startVllmQwenProject: vi.fn(async () => ({ success: true })),}));-vi.mock('../lib/vllmQwenProject.js', () => vllmProject);+vi.mock('./vllmQwenManager.js', () => vllmManager);import { describeRuntimeSetup, readRuntimeWeights, runLocalRuntimeSetup, SETUP_ACTIONS, SETUP_RUNTIME_KINDS } from './localRuntimeSetup.js';@@ -59,15 +61,15 @@ const reachable = (models = ['mtplx']) => ({ reachable: true, models, error: nulconst cachedModels = (models) => ({ models, error: null });-const preparedVllmProject = { dir: '/home/example/qwen-serving', hasProject: true, composeFile: 'docker-compose.yml', hasWeights: true, weightsRoot: '/home/example/qwen-serving/models' };beforeEach(() => {- vllmProject.inspectVllmQwenProject.mockResolvedValue(preparedVllmProject);- vllmProject.vllmStartBlockedReason.mockReturnValue(null);// Implementations AND return values (not just call records) survive// `clearAllMocks`, so a probe implementation left over from an earlier test// would drive this module's poll loop for its full timeout.probe.probeOpenAiModels.mockReset();+ vllmManager.readVllmQwenSetupState.mockResolvedValue('ready');+ vllmManager.provisionVllmQwenProject.mockResolvedValue({ success: true });+ vllmManager.startVllmQwenProject.mockResolvedValue({ success: true });mtplxCache.listMtplxCachedModels.mockResolvedValue(cachedModels([{ repo_id: 'Example/MTP-Model', validation: { ok: true } }]));mtplx.installMtplx.mockResolvedValue({ success: true });mtplx.startMtplxServer.mockResolvedValue({ success: true, endpoint: 'http://127.0.0.1:8000/v1' });@@ -92,6 +94,7 @@ describe('describeRuntimeSetup', () => {label: 'MTPLX',action: 'install-start',actionLabel: 'Install & start MTPLX',+ provisions: false,blockedReason: null,});restore();@@ -476,7 +479,7 @@ describe('runLocalRuntimeSetup', () => {});it('exposes every action the route may accept', () => {- expect([...SETUP_ACTIONS].sort()).toEqual(['install', 'install-start', 'pull-start', 'start']);+ expect([...SETUP_ACTIONS].sort()).toEqual(['install', 'install-start', 'provision-start', 'pull-start', 'start']);});it('refuses when every cached MTPLX model is an incomplete download', async () => {@@ -539,60 +542,120 @@ describe('runLocalRuntimeSetup', () => {});});-describe('vllm — the container is brought up, never provisioned', () => {+describe('vllm — the registry offers it, the manager does it', () => {const vllmEndpoint = 'http://127.0.0.1:18020/v1';+ const run = async (action = null) => runLocalRuntimeSetup('vllm', { endpoint: vllmEndpoint, emit: () => {}, action });+it('is unsupported on darwin, and says where Mac users should go instead', () => {const restore = pinPlatform('darwin');expect(describeRuntimeSetup('vllm', { installed: false, running: false })).toMatchObject({runtime: 'vllm',action: null,+ provisions: false,blockedReason: expect.stringMatching(/MTPLX or llama.cpp DSpark/),});restore();});- it('offers a start button on a Linux/Windows host with docker present', () => {+ it('offers a plain start on a Linux/Windows host with a prepared project', () => {const restore = pinPlatform('linux');- expect(describeRuntimeSetup('vllm', { installed: true, running: false })).toMatchObject({+ expect(describeRuntimeSetup('vllm', { installed: true, running: false, weights: 'ready' })).toMatchObject({runtime: 'vllm',action: 'start',+ provisions: false,blockedReason: null,});restore();});- it('brings up an already-prepared compose project in its own directory', async () => {+ it('offers the provisioning button — naming the payload — when nothing is prepared', () => {+ const restore = pinPlatform('linux');+ expect(describeRuntimeSetup('vllm', { installed: true, running: false, weights: 'empty' })).toEqual({+ runtime: 'vllm',+ label: 'vLLM (Qwen3.8-27B)',+ action: 'provision-start',+ actionLabel: 'Clone, build & prepare vLLM (Qwen3.8-27B) (~30 GB), then start',+ // The client renders the download icon and the payload tooltip off THIS+ // flag, so it never re-derives the answer from the action's spelling.+ provisions: true,+ blockedReason: null,+ });+ expect(SETUP_ACTIONS).toContain('provision-start');+ restore();+ });++ it('reads its setup state from the manager, and not at all on an unsupported platform', async () => {+ const linux = pinPlatform('linux');+ vllmManager.readVllmQwenSetupState.mockResolvedValue('empty');+ expect(await readRuntimeWeights('vllm')).toBe('empty');+ linux();++ // Docker is on PATH almost everywhere, so a Mac would otherwise sweep the+ // compose project's cache roots once a minute for a card it cannot have.+ const darwin = pinPlatform('darwin');+ vllmManager.readVllmQwenSetupState.mockClear();+ expect(await readRuntimeWeights('vllm')).toBe('unknown');+ expect(vllmManager.readVllmQwenSetupState).not.toHaveBeenCalled();+ darwin();+ });++ it('provisions then starts, through the manager, for the provision-start action', async () => {const restore = pinPlatform('linux');pathLookup.findCommandOnPath.mockReturnValue('/usr/bin/docker');probe.probeOpenAiModels- .mockResolvedValueOnce(unreachable) // initial- .mockResolvedValueOnce(unreachable) // after "install"- .mockResolvedValue(reachable(['qwen3.8-27b'])); // confirm+ .mockResolvedValueOnce(unreachable)+ .mockResolvedValueOnce(unreachable)+ .mockResolvedValue(reachable(['qwen3.8-27b']));- const result = await runLocalRuntimeSetup('vllm', { endpoint: vllmEndpoint, emit: () => {} });+ const result = await run('provision-start');expect(result.success).toBe(true);- expect(streaming.runStreamingCommand).toHaveBeenCalledWith(- 'docker',- ['compose', '--profile', 'single', 'up', '-d'],- expect.any(Function),- expect.objectContaining({ cwd: preparedVllmProject.dir }),- );+ expect(vllmManager.provisionVllmQwenProject).toHaveBeenCalledTimes(1);+ expect(vllmManager.startVllmQwenProject).toHaveBeenCalledTimes(1);restore();});- it('refuses to run compose when the project is not demonstrably prepared', async () => {+ it('never provisions behind a plain start', async () => {+ const restore = pinPlatform('linux');+ pathLookup.findCommandOnPath.mockReturnValue('/usr/bin/docker');+ vllmManager.readVllmQwenSetupState.mockResolvedValue('ready');+ probe.probeOpenAiModels+ .mockResolvedValueOnce(unreachable)+ .mockResolvedValueOnce(unreachable)+ .mockResolvedValue(reachable(['qwen3.8-27b']));++ await run(null);++ // The whole point: ~30 GB is never spent on a button that did not say so.+ expect(vllmManager.provisionVllmQwenProject).not.toHaveBeenCalled();+ expect(vllmManager.startVllmQwenProject).toHaveBeenCalledTimes(1);+ restore();+ });++ it('surfaces the manager\'s start refusal verbatim', async () => {const restore = pinPlatform('linux');pathLookup.findCommandOnPath.mockReturnValue('/usr/bin/docker');probe.probeOpenAiModels.mockResolvedValue(unreachable);- vllmProject.vllmStartBlockedReason.mockReturnValue('no Qwen weights are cached yet');+ vllmManager.readVllmQwenSetupState.mockResolvedValue('ready');+ vllmManager.startVllmQwenProject.mockResolvedValue({ success: false, error: 'no Qwen weights are cached yet' });- const result = await runLocalRuntimeSetup('vllm', { endpoint: vllmEndpoint, emit: () => {} });+ const result = await run(null);expect(result).toMatchObject({ success: false, error: expect.stringMatching(/no Qwen weights are cached/) });- // The whole point: a 20 GB pull is never started on the user's behalf.- expect(streaming.runStreamingCommand).not.toHaveBeenCalled();+ expect(vllmManager.provisionVllmQwenProject).not.toHaveBeenCalled();+ restore();+ });++ it('refuses a pull-start aimed at vLLM — its provisioning step is not a model download', async () => {+ const restore = pinPlatform('linux');+ pathLookup.findCommandOnPath.mockReturnValue('/usr/bin/docker');+ probe.probeOpenAiModels.mockResolvedValue(unreachable);++ const result = await run('pull-start');++ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/cannot download model weights/) });+ expect(vllmManager.provisionVllmQwenProject).not.toHaveBeenCalled();restore();});@@ -601,10 +664,10 @@ describe('vllm — the container is brought up, never provisioned', () => {pathLookup.findCommandOnPath.mockReturnValue(null); // docker not on PATHprobe.probeOpenAiModels.mockResolvedValue(unreachable);- const result = await runLocalRuntimeSetup('vllm', { endpoint: vllmEndpoint, emit: () => {} });+ const result = await run('provision-start');expect(result).toMatchObject({ success: false, error: expect.stringMatching(/does not install this stack/) });- expect(streaming.runStreamingCommand).not.toHaveBeenCalled();+ expect(vllmManager.provisionVllmQwenProject).not.toHaveBeenCalled();expect(localLlm.installBackend).not.toHaveBeenCalled();restore();});diff --git a/server/services/providerReadiness.js b/server/services/providerReadiness.jsindex 078d1b7f52..71c59ee42d 100644--- a/server/services/providerReadiness.js+++ b/server/services/providerReadiness.js@@ -37,7 +37,7 @@ import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';import { isConfiguredDefaultModel } from '../lib/providerModels.js';import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';import { findCommandOnPath } from '../lib/processEnv.js';-import { describeRuntimeSetup, readRuntimeWeights, weightsBlockStart } from './localRuntimeSetup.js';+import { actionCovers, describeRuntimeSetup, readRuntimeWeights, weightsBlockStart } from './localRuntimeSetup.js';import { isAppInstalled as isLmStudioAppInstalled } from './lmStudioManager.js';/**@@ -188,10 +188,17 @@ export function servedModelId(provider, kind) {* prose. `covers` is the action the check needs: an install-only button does* nothing for a `server` check.*/-function setupHint(setup, covers) {+function setupHint(setup, capability) {if (!setup) return null;if (setup.blockedReason) return setup.blockedReason;- return setup.action?.includes(covers) ? `Use “${setup.actionLabel}” below — PortOS does this for you.` : null;+ // `capability` is one of `installs` / `starts` / `provisions`, asked of the+ // action table rather than matched against the action's spelling. The old+ // substring test worked only because every action name happened to contain+ // the word — `provision-start` does not contain `pull`, and a hint that+ // vanishes when an action is renamed fails no test.+ return actionCovers(setup.action, capability)+ ? `Use “${setup.actionLabel}” below — PortOS does this for you.`+ : null;}/**@@ -201,6 +208,13 @@ function setupHint(setup, covers) {* `null` when there is nothing to add, so the caller keeps its own prose.*/function weightsDetail(runtime, weights) {+ // A runtime whose local setup is not "a model cache" describes its own states+ // — vLLM's is a compose project that was never cloned or prepared, and+ // "no model weights cached" would send the operator after a download that was+ // never the first step. Keyed by STATE rather than one override per divergence,+ // so the next runtime supplies whichever states read wrong for it.+ const override = runtime.setupStateDetail?.[weights];+ if (override) return override;if (weights === 'empty') return `${runtime.label} has no model weights cached, so its server exits before it binds a port.`;if (weights === 'partial') return `${runtime.label}'s cache holds only an unfinished download — no complete checkpoint to serve.`;if (weights === 'ready') return 'Weights are cached locally; this can be confirmed once the server is running.';@@ -214,7 +228,7 @@ function runtimeCheck(runtime, { onPath, appInstalled, installed, reachable, set: reachable ? `Something is already serving ${runtime.endpoint}.`: `\`${runtime.command}\` was not found on PortOS's PATH.`;const fixHint = installed ? null- : setupHint(setup, 'install')+ : setupHint(setup, 'installs')|| (runtime.manageUrl ? `Install ${runtime.label} from Models → LLMs.`: `Use the setup button below to install ${runtime.label}.`);return { id: 'runtime', label: `${runtime.label} installed`, ok: installed, detail, fixHint };@@ -244,7 +258,7 @@ function serverCheck(runtime, { installed, result, setup, weights = 'unknown' })label: `${runtime.label} server responding`,ok: false,detail: `Nothing answered at ${runtime.endpoint}${result.error ? ` (${result.error})` : ''}.${blocked ? ` ${blocked}` : ''}`,- fixHint: setupHint(setup, 'start') || fallback,+ fixHint: setupHint(setup, 'starts') || fallback,};}@@ -268,7 +282,7 @@ function modelCheck(runtime, wanted, served, probeError = null, { weights = 'unk: weightsDetail(runtime, weights) || 'Cannot be checked until the server responds.';// An unservable cache is the ONE unknown here that has a fix: the download// that makes a start possible at all.- const fixHint = weightsBlockStart(weights) ? setupHint(setup, 'pull') : null;+ const fixHint = weightsBlockStart(weights) ? setupHint(setup, 'provisions') : null;return { id: 'model', label, ok: null, detail, fixHint };}if (served.includes(wanted)) {diff --git a/server/services/vllmQwenManager.js b/server/services/vllmQwenManager.jsnew file mode 100644index 0000000000..ad3e8f9c6b--- /dev/null+++ b/server/services/vllmQwenManager.js@@ -0,0 +1,283 @@+/**+ * Everything PortOS does TO the vLLM Qwen3.8-27B compose project.+ *+ * `lib/vllmQwenProject.js` reads what is on disk and `lib/vllmQwenProvision.js`+ * decides what the `.env` must say; this module is the side of it that runs+ * commands — the same split `mtplxServerManager.js` and `llamaServerManager.js`+ * have from `localRuntimeSetup.js`, whose registry stays a table of rows rather+ * than growing one runtime's orchestration inline.+ *+ * Two things it does and nothing else does:+ *+ * - **Provision** (`provisionVllmQwenProject`) — clone, write `.env`, build,+ * prepare. This is the ~30 GB, and it runs ONLY behind the checklist's+ * `provision-start` action, whose button names the payload before the click.+ * `install()` in the registry still refuses: Docker Desktop, the NVIDIA+ * Container Toolkit and WSL2 are host-level operator decisions with driver+ * requirements PortOS cannot judge. This provisions the PROJECT on a host+ * that is already capable of running it.+ * - **Start** (`startVllmQwenProject`) — `docker compose up` on a project that+ * is demonstrably prepared, and a refusal naming the fix on anything else.+ *+ * Neither ever throws: both run from an SSE route whose headers are already+ * flushed, so every failure comes back as a value the caller turns into a+ * terminal frame.+ */++import { totalmem } from 'os';+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 {+ inspectVllmQwenProject,+ vllmProjectSetupState,+ vllmStartBlockedReason,+ VLLM_PROJECT_DIR_ENV,+} from '../lib/vllmQwenProject.js';+import {+ generateVllmApiKey,+ isWsl2Engine,+ mergeEnvFileContents,+ vllmEnvDefaults,+ VLLM_API_KEY_VAR,+ WSL2_PREPARE_CONFIG_HINT,+ WSL2_PREPARE_MIN_BYTES,+} from '../lib/vllmQwenProvision.js';+import { getAllProviders, updateProvider } from './providers.js';++/** Upstream's frozen packaging of patched vLLM + the requantized checkpoint. */+export const VLLM_UPSTREAM_REPO = 'https://github.com/syv-ai/qwen38-27b-rtx3090';++/** A daemon question, and a compose `up` on an image that is already built. */+const CONTROL_TIMEOUT_MS = 60 * 1000;++/**+ * Bound on the clone. Generous, but nothing like the build/prepare budget — the+ * checkout is source and a compose file; the 30 GB arrives in the two steps+ * after it.+ */+const CLONE_TIMEOUT_MS = 30 * 60 * 1000;++/**+ * The image build and the weights prepare. Sized for a slow domestic line rather+ * than a fast one — a bound that kills a 20 GB download at 90% is worse than no+ * bound at all, and closing the modal cancels between steps anyway.+ */+const PROVISION_TIMEOUT_MS = 6 * 60 * 60 * 1000;++/**+ * Split docker's output on bare `\r` too, so a layer-pull or tqdm progress bar+ * that redraws one line surfaces each redraw instead of going silent for the+ * length of the download (`lib/streamLines.js`).+ */+const PROGRESS_SPLIT_RE = /[\r\n]+/;++/**+ * What is on disk, in the four-state vocabulary the readiness checklist speaks+ * (`localRuntimeSetup.js`'s `readRuntimeWeights`). A directory read — it never+ * runs docker or contacts a registry.+ */+export async function readVllmQwenSetupState() {+ return vllmProjectSetupState(await inspectVllmQwenProject());+}++/**+ * Why PortOS must not clone this project to a Windows path.+ *+ * Docker Desktop's engine is a WSL2 VM. A project cloned onto the Windows+ * filesystem is reached from inside that VM over a 9p share, so `prepare` would+ * write ~20 GB of weights across it and the server would page them back the same+ * way — the documented layout is the Linux filesystem, and this is a mistake that+ * costs 20 GB to discover and 20 GB to undo. An operator who genuinely wants a+ * Windows path can still have one: setting the override IS that decision, so the+ * refusal only fires when nothing was configured at all.+ *+ * @returns {string|null} the refusal, or `null` when the placement is the+ * operator's own explicit choice (or the host is not Windows).+ */+export function vllmWindowsPlacementRefusal(dir, env = process.env, platform = process.platform) {+ if (platform !== 'win32') return null;+ if (String(env?.[VLLM_PROJECT_DIR_ENV] || '').trim()) return null;+ return `on Windows this project and its ~20 GB of weights belong on the WSL2 filesystem, not the Windows one — cloning to ${dir} would leave every weight read crossing a 9p share. Set ${VLLM_PROJECT_DIR_ENV} to the distro's UNC path (\\\\wsl.localhost\\<distro>\\home\\<user>\\qwen-serving) and click this again.`;+}++/**+ * Make the project's `.env` say everything the container needs, without+ * overruling a single thing the operator already wrote there.+ *+ * The generated API key is a fallback: `mergeEnvFileContents` reports the value+ * that ended up IN EFFECT, so a file that already carried a key keeps it and the+ * caller propagates that one.+ *+ * Only key NAMES are ever emitted — the returned `effective` holds the token.+ */+async function ensureVllmEnvFile(dir, emit) {+ const envPath = join(dir, '.env');+ const existing = (await tryReadFile(envPath)) || '';+ // The feature doc's snippet tests `/proc/version`; `isWsl2Engine` also counts+ // win32, where Docker Desktop's engine IS a WSL2 VM and there is no+ // `/proc/version` for PortOS to read — see that module for why omitting the+ // two WSL2 variables there produces a silent crash-loop rather than an error.+ // So the file is only opened where it can exist.+ const wsl2 = isWsl2Engine({ procVersion: process.platform === 'linux' ? await tryReadFile('/proc/version') : null });+ const merged = mergeEnvFileContents(existing, vllmEnvDefaults({ apiKey: generateVllmApiKey(), wsl2 }));++ if (merged.added.length > 0) {+ // Atomic, and mode-preserving: this file holds the container's bearer token,+ // and a truncate-in-place is readable half-written by a concurrent+ // `docker compose`.+ await atomicWrite(envPath, merged.contents);+ emit(`Wrote ${merged.added.length} missing setting${merged.added.length === 1 ? '' : 's'} to .env: ${merged.added.join(', ')}.`);+ }+ if (merged.kept.length > 0) {+ emit(`Left the .env values already set for ${merged.kept.join(', ')} exactly as they were.`);+ }+ return { ...merged, wsl2 };+}++/**+ * Name the WSL2 memory ceiling right before the step it kills.+ *+ * Raising it is an operator decision PortOS never takes: it means editing+ * `%UserProfile%\.wslconfig` and running `wsl --shutdown`, which takes the whole+ * VM down — including a PostgreSQL container this install may be using. So:+ * detect, name the values, and let them decide.+ */+function warnAboutWsl2PrepareMemory(emit) {+ const vmBytes = totalmem();+ // `formatBytes` is 1024-based, like WSL2_PREPARE_MIN_BYTES and like the "~24 GB"+ // named in the hint — a 1000-based number here would read as 25 GB for a VM+ // sitting exactly on the floor.+ emit(process.platform === 'linux' && vmBytes < WSL2_PREPARE_MIN_BYTES+ ? `Warning: this WSL2 VM sees only ${formatBytes(vmBytes)} of RAM. The prepare step is CPU-side and memory-hungry, and under ~24 GB it is SIGKILLed with a bare "Killed" (exit 137) that names nothing about WSL. ${WSL2_PREPARE_CONFIG_HINT}`+ : `WSL2 backs this engine. If the prepare step dies with a bare "Killed" (exit 137), its VM memory ceiling is the cause. ${WSL2_PREPARE_CONFIG_HINT}`);+}++/**+ * Put the container's key on the seeded vLLM providers so the operator never+ * copies it by hand — the one manual step left in `docs/features/qwen38-rtx3090.md`.+ *+ * The key is a secret: it is stored and never emitted. Providers already+ * carrying this exact key are skipped, so a re-run writes nothing.+ */+async function applyVllmApiKeyToProviders(apiKey, emit) {+ if (!apiKey) return 0;+ const data = await getAllProviders().catch((err) => {+ emit(`Could not read the provider list to store the container's API key (${err.message}) — paste it from .env onto the vLLM providers yourself.`);+ return null;+ });+ const all = Array.isArray(data?.providers) ? data.providers : [];+ const targets = all.filter((p) => p?.vllmBacked === true && p.apiKey !== apiKey);+ let stored = 0;+ for (const provider of targets) {+ // A failed provider write must not undo a successful 30 GB provision — this+ // is a convenience (the key is in `.env` either way), so it reports and+ // carries on rather than throwing out of the whole run.+ // eslint-disable-next-line no-await-in-loop -- two seeded records, each a serialized file write+ const written = await updateProvider(provider.id, { apiKey }).then(() => true, (err) => {+ emit(`Could not store the API key on ${provider.id} (${err.message}) — paste it from .env onto that provider yourself.`);+ return false;+ });+ if (written) stored += 1;+ }+ if (stored > 0) {+ emit(`Stored the container's API key on ${stored} vLLM provider${stored === 1 ? '' : 's'} — it is never printed here.`);+ }+ return stored;+}++/**+ * Clone / build / prepare the upstream compose project, streaming every step.+ *+ * Each step is skipped when it has already landed, which is what makes a re-run+ * cheap: upstream's `prepare` is itself idempotent and its download resumes, so+ * a cancelled run costs minutes rather than the 20 GB.+ *+ * `isCancelled` is checked BETWEEN steps and never handed to the build or the+ * prepare. Killing those mid-flight is how a half-written image layer or a+ * partial checkout gets left behind, and the wait is exactly what the operator+ * signed up for when they clicked a button reading "~30 GB".+ *+ * @param {{emit: (line: string) => void, isCancelled: () => boolean}} ctx+ * @returns {Promise<{success: boolean, error?: string}>}+ */+export async function provisionVllmQwenProject({ emit, isCancelled }) {+ // Docker must ANSWER, not merely be on PATH: a stopped Docker Desktop leaves+ // the binary there, and every step below would then fail one at a time with a+ // message about compose rather than about the daemon.+ const docker = await runStreamingCommand('docker', ['version', '--format', '{{.Server.Version}}'], undefined, { timeoutMs: CONTROL_TIMEOUT_MS });+ if (!docker.success) {+ return { success: false, error: `the Docker daemon is not answering (${docker.error}). Start Docker Desktop (or dockerd) and try again — PortOS does not install it.` };+ }++ let project = await inspectVllmQwenProject();+ const dir = project.dir;+ const alreadyPrepared = vllmProjectSetupState(project) === 'ready';++ if (!project.hasProject) {+ const misplaced = vllmWindowsPlacementRefusal(dir);+ if (misplaced) return { success: false, error: misplaced };+ const git = findCommandOnPath('git');+ if (!git) return { success: false, error: '`git` was not found on PortOS\'s PATH, so the compose project cannot be cloned.' };+ emit(`Cloning ${VLLM_UPSTREAM_REPO} into ${dir}…`);+ const cloned = await runStreamingCommand(git, ['clone', VLLM_UPSTREAM_REPO, dir], emit, { timeoutMs: CLONE_TIMEOUT_MS, splitRe: PROGRESS_SPLIT_RE });+ if (!cloned.success) return { success: false, error: `cloning ${VLLM_UPSTREAM_REPO} failed: ${cloned.error}` };+ project = await inspectVllmQwenProject();+ } else {+ emit(alreadyPrepared+ ? `The project at ${dir} is already built and prepared — checking its .env, then starting it.`+ : `Reusing the existing checkout at ${dir}.`);+ }++ if (!project.composeFile) {+ return { success: false, error: `${dir} holds no docker-compose file, so there is nothing to build. Point ${VLLM_PROJECT_DIR_ENV} at a syv-ai/qwen38-27b-rtx3090 checkout.` };+ }++ // Before the build, so the image and `prepare` both see the final settings.+ // Runs on the already-prepared path too: `EXTRA_ARGS` is exactly the setting a+ // project prepared before this existed is most likely to be missing, and+ // without it every agent turn is rejected.+ const env = await ensureVllmEnvFile(dir, emit);+ await applyVllmApiKeyToProviders(env.effective[VLLM_API_KEY_VAR], emit);++ if (alreadyPrepared) return { success: true };+ if (isCancelled()) return { success: false, error: 'cancelled before the image was built' };++ emit('Building the vLLM image (~9.5 GB, built here — there is no registry to pull it from).');+ const built = await runStreamingCommand('docker', ['compose', 'build'], emit, { timeoutMs: PROVISION_TIMEOUT_MS, cwd: dir, splitRe: PROGRESS_SPLIT_RE });+ if (!built.success) return { success: false, error: `docker compose build failed: ${built.error}` };++ if (isCancelled()) return { success: false, error: 'cancelled after the image build — the image is kept, and re-running resumes from here' };++ if (env.wsl2) warnAboutWsl2PrepareMemory(emit);+ emit('Downloading and requantizing the weights (~20 GB). This step is idempotent and its download resumes, so it is safe to leave running.');+ const prepared = await runStreamingCommand('docker', ['compose', 'run', '--rm', 'prepare'], emit, { timeoutMs: PROVISION_TIMEOUT_MS, cwd: dir, splitRe: PROGRESS_SPLIT_RE });+ if (!prepared.success) return { success: false, error: `docker compose run --rm prepare failed: ${prepared.error}` };++ return { success: true };+}++/**+ * Bring up an ALREADY-prepared project, and nothing else — see+ * `lib/vllmQwenProject.js` for why each refusal exists. No image build, no+ * weight download: those are `provisionVllmQwenProject`, behind their own button.+ *+ * @param {{emit: (line: string) => void, isCancelled: () => boolean}} ctx+ * @returns {Promise<{success: boolean, error?: string}>}+ */+export async function startVllmQwenProject({ emit, isCancelled }) {+ const project = await inspectVllmQwenProject();+ const blocked = vllmStartBlockedReason(project);+ if (blocked) return { success: false, error: blocked };+ if (isCancelled()) return { success: false, error: 'Cancelled before the container was started.' };+ emit(`Starting the vLLM container from ${project.dir} (${project.composeFile}).`);+ emit('The image and weights are already on disk — this only brings the service up.');+ return runStreamingCommand(+ 'docker',+ ['compose', '--profile', 'single', 'up', '-d'],+ emit,+ { timeoutMs: CONTROL_TIMEOUT_MS, cwd: project.dir },+ );+}diff --git a/server/services/vllmQwenManager.test.js b/server/services/vllmQwenManager.test.jsnew file mode 100644index 0000000000..3ce5e650e3--- /dev/null+++ b/server/services/vllmQwenManager.test.js@@ -0,0 +1,328 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { pinPlatform } from '../lib/testHelper.js';++const pathLookup = vi.hoisted(() => ({+ findCommandOnPath: vi.fn(() => null),+ safeChildProcessEnv: (extra = {}) => ({ ...extra }),+ safeChildProcessOptions: (opts = {}) => opts,+}));+vi.mock('../lib/processEnv.js', () => pathLookup);++const streaming = vi.hoisted(() => ({ runStreamingCommand: vi.fn(async () => ({ success: true })) }));+vi.mock('../lib/streamingSpawn.js', () => streaming);++// The compose project on disk. Mocked so the suite never stats a real checkout.+// PARTIAL for the rest of the module: `vllmProjectSetupState` is a pure+// classifier, and stubbing it would let a wrong reading of a real inspection+// pass here.+const project = vi.hoisted(() => ({ inspectVllmQwenProject: vi.fn(), vllmStartBlockedReason: vi.fn(() => null) }));+vi.mock('../lib/vllmQwenProject.js', async (importOriginal) => ({ ...(await importOriginal()), ...project }));++// The two side effects: the `.env` write and the provider records the generated+// key lands on. `tryReadFile`/`formatBytes` stay real — they are pure readers.+const files = vi.hoisted(() => ({ atomicWrite: vi.fn(async () => {}), tryReadFile: vi.fn(async () => null) }));+vi.mock('../lib/fileUtils.js', async (importOriginal) => ({ ...(await importOriginal()), ...files }));++const providers = vi.hoisted(() => ({+ getAllProviders: vi.fn(async () => ({ activeProvider: null, providers: [] })),+ updateProvider: vi.fn(async () => ({})),+}));+vi.mock('./providers.js', () => providers);++import { provisionVllmQwenProject, readVllmQwenSetupState, startVllmQwenProject, VLLM_UPSTREAM_REPO } from './vllmQwenManager.js';++const DIR = '/home/example/qwen-serving';+const emptyProject = { dir: DIR, hasProject: false, composeFile: null, hasWeights: null, weightsRoot: null };+const clonedProject = { ...emptyProject, hasProject: true, composeFile: 'docker-compose.yml', hasWeights: false };+const preparedProject = { ...clonedProject, hasWeights: true, weightsRoot: `${DIR}/models` };++/** The docker argv lists, in the order they were run. */+const dockerCalls = () => streaming.runStreamingCommand.mock.calls+ .filter(([cmd]) => cmd === 'docker')+ .map(([, args]) => args.join(' '));++/** A run against a host with nothing cloned yet. */+const stageFreshProject = () => project.inspectVllmQwenProject+ .mockResolvedValueOnce(emptyProject) // the provisioning step's own look+ .mockResolvedValue(clonedProject); // the re-read after the clone++const provision = async (lines = []) => provisionVllmQwenProject({+ emit: (line) => lines.push(line),+ isCancelled: () => false,+});++/** Everything the run streamed to the modal. */+const emitted = (lines) => lines.join('\n');++let restorePlatform = () => {};++beforeEach(() => {+ restorePlatform = pinPlatform('linux');+ pathLookup.findCommandOnPath.mockImplementation((cmd) => (cmd === 'docker' || cmd === 'git' ? `/usr/bin/${cmd}` : null));+ project.inspectVllmQwenProject.mockResolvedValue(preparedProject);+ project.vllmStartBlockedReason.mockReturnValue(null);+ files.tryReadFile.mockResolvedValue(null);+ providers.getAllProviders.mockResolvedValue({ activeProvider: null, providers: [] });+ streaming.runStreamingCommand.mockResolvedValue({ success: true });+});++afterEach(() => {+ restorePlatform();+ vi.clearAllMocks();+ delete process.env.VLLM_QWEN_PROJECT_DIR;+});++describe('readVllmQwenSetupState', () => {+ it('reports empty when nothing is cloned, and when a checkout was never prepared', async () => {+ project.inspectVllmQwenProject.mockResolvedValue(emptyProject);+ expect(await readVllmQwenSetupState()).toBe('empty');++ project.inspectVllmQwenProject.mockResolvedValue(clonedProject);+ expect(await readVllmQwenSetupState()).toBe('empty');+ });++ it('never reports a cache it could not READ as empty', async () => {+ // The normal Windows shape before VLLM_QWEN_PROJECT_DIR points at the UNC+ // path. Calling this `empty` would offer to re-download ~20 GB that is+ // already on disk.+ project.inspectVllmQwenProject.mockResolvedValue({ ...clonedProject, hasWeights: null });+ expect(await readVllmQwenSetupState()).toBe('unknown');+ });++ it('reports ready for a prepared project', async () => {+ expect(await readVllmQwenSetupState()).toBe('ready');+ });+});++describe('provisionVllmQwenProject', () => {+ it('clones, writes .env, builds, prepares — in that order', async () => {+ stageFreshProject();+ const lines = [];++ const result = await provision(lines);++ expect(result.success).toBe(true);+ expect(streaming.runStreamingCommand).toHaveBeenCalledWith(+ '/usr/bin/git',+ ['clone', VLLM_UPSTREAM_REPO, DIR],+ expect.any(Function),+ expect.objectContaining({ splitRe: expect.any(RegExp) }),+ );+ expect(dockerCalls()).toEqual([+ 'version --format {{.Server.Version}}',+ 'compose build',+ 'compose run --rm prepare',+ ]);+ expect(emitted(lines)).toMatch(/~9\.5 GB/);+ });++ it('writes the tool-parser line every time, and the WSL2 pair only on a WSL2 engine', async () => {+ stageFreshProject();++ await provision();++ const [envPath, contents] = files.atomicWrite.mock.calls[0];+ expect(String(envPath)).toMatch(/[\\/]\.env$/);+ // Without this the agent's first turn is rejected; with `hermes` instead it+ // silently never emits a tool call at all.+ expect(contents).toContain('EXTRA_ARGS=--enable-auto-tool-choice --tool-call-parser qwen3_xml');+ expect(contents).toContain('SPEC=dflash2');+ expect(contents).toContain('PREFIX_CACHE=1');+ // Native Linux does not need — and must not be given — the WSL2 pair.+ expect(contents).not.toContain('VLLM_WSL2_ENABLE_PIN_MEMORY');+ });++ it('adds the two mandatory WSL2 variables when Docker Desktop backs it', async () => {+ restorePlatform();+ restorePlatform = pinPlatform('win32');+ process.env.VLLM_QWEN_PROJECT_DIR = '\\\\wsl.localhost\\example\\home\\example\\qwen-serving';+ stageFreshProject();+ const lines = [];++ await provision(lines);++ const contents = files.atomicWrite.mock.calls[0][1];+ // Both are preconditions for starting at all on WSL2, and each fails in a+ // way that points somewhere other than WSL — a quiet crash-loop and a+ // fake-looking OOM respectively.+ expect(contents).toContain('VLLM_WSL2_ENABLE_PIN_MEMORY=1');+ expect(contents).toContain('PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False');+ // The VM memory ceiling is named before the step it kills, never raised —+ // `wsl --shutdown` would take down this install's own PostgreSQL container.+ expect(emitted(lines)).toMatch(/\.wslconfig/);+ });++ it('keeps every value an existing .env already had, and propagates THAT key', async () => {+ files.tryReadFile.mockImplementation(async (path) => (+ String(path).endsWith('.env') ? 'GPU_UTIL=0.93\nVLLM_API_KEY=operator-chosen-key\n' : null+ ));+ providers.getAllProviders.mockResolvedValue({+ activeProvider: null,+ providers: [+ { id: 'opencode-vllm', vllmBacked: true, apiKey: '' },+ { id: 'opencode-vllm-tui', vllmBacked: true, apiKey: '' },+ { id: 'anthropic', apiKey: 'untouched' },+ ],+ });+ stageFreshProject();+ const lines = [];++ await provision(lines);++ const contents = files.atomicWrite.mock.calls[0][1];+ expect(contents).toContain('GPU_UTIL=0.93');+ // Exactly one VLLM_API_KEY line, and it is the operator's.+ expect(contents.match(/^VLLM_API_KEY=/gm)).toHaveLength(1);+ expect(contents).toContain('VLLM_API_KEY=operator-chosen-key');+ // The key the CONTAINER will read is the one the providers get.+ expect(providers.updateProvider.mock.calls).toEqual([+ ['opencode-vllm', { apiKey: 'operator-chosen-key' }],+ ['opencode-vllm-tui', { apiKey: 'operator-chosen-key' }],+ ]);+ // It is a secret: stored, never streamed to the modal.+ expect(emitted(lines)).not.toContain('operator-chosen-key');+ });++ it('generates a key when the .env has none, and never prints it', async () => {+ providers.getAllProviders.mockResolvedValue({+ activeProvider: null,+ providers: [{ id: 'opencode-vllm-tui', vllmBacked: true, apiKey: '' }],+ });+ stageFreshProject();+ const lines = [];++ await provision(lines);++ const generated = providers.updateProvider.mock.calls[0][1].apiKey;+ expect(generated).toMatch(/^[0-9a-f]{48}$/);+ expect(files.atomicWrite.mock.calls[0][1]).toContain(`VLLM_API_KEY=${generated}`);+ expect(emitted(lines)).not.toContain(generated);+ });++ it('carries on when a provider write fails — the key is in .env either way', async () => {+ providers.getAllProviders.mockResolvedValue({+ activeProvider: null,+ providers: [{ id: 'opencode-vllm-tui', vllmBacked: true, apiKey: '' }],+ });+ providers.updateProvider.mockRejectedValue(new Error('providers.json is locked'));+ stageFreshProject();+ const lines = [];++ const result = await provision(lines);++ // A convenience failing must not undo a successful 30 GB provision.+ expect(result.success).toBe(true);+ expect(emitted(lines)).toMatch(/paste it from \.env/);+ });++ it('skips the build and the prepare when the project is already prepared', async () => {+ const result = await provision();++ expect(result.success).toBe(true);+ // Idempotent: the daemon check and nothing else.+ expect(dockerCalls()).toEqual(['version --format {{.Server.Version}}']);+ // The .env is still topped up — EXTRA_ARGS is exactly the setting a project+ // prepared before this existed is most likely to be missing.+ expect(files.atomicWrite).toHaveBeenCalled();+ });++ it('refuses to clone onto the Windows filesystem when no project dir was configured', async () => {+ restorePlatform();+ restorePlatform = pinPlatform('win32');+ project.inspectVllmQwenProject.mockResolvedValue(emptyProject);++ const result = await provision();++ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/VLLM_QWEN_PROJECT_DIR/) });+ expect(dockerCalls()).toEqual(['version --format {{.Server.Version}}']);+ expect(files.atomicWrite).not.toHaveBeenCalled();+ });++ it('refuses before cloning anything when the Docker daemon is not answering', async () => {+ project.inspectVllmQwenProject.mockResolvedValue(emptyProject);+ streaming.runStreamingCommand.mockResolvedValueOnce({ success: false, error: 'exit 1: cannot connect to the Docker daemon' });++ const result = await provision();++ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/Docker daemon is not answering/) });+ expect(streaming.runStreamingCommand).toHaveBeenCalledTimes(1);+ });++ it('refuses when git is missing rather than half-cloning', async () => {+ project.inspectVllmQwenProject.mockResolvedValue(emptyProject);+ pathLookup.findCommandOnPath.mockImplementation((cmd) => (cmd === 'docker' ? '/usr/bin/docker' : null));++ const result = await provision();++ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/`git` was not found/) });+ });++ it('stops when the clone produced no compose file', async () => {+ project.inspectVllmQwenProject+ .mockResolvedValueOnce(emptyProject)+ .mockResolvedValue({ ...emptyProject, hasProject: true });++ const result = await provision();++ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/no docker-compose file/) });+ expect(files.atomicWrite).not.toHaveBeenCalled();+ });++ it('reports the build failure rather than going on to prepare', async () => {+ stageFreshProject();+ streaming.runStreamingCommand.mockImplementation(async (cmd, args) => (+ args.join(' ') === 'compose build' ? { success: false, error: 'exit 1: no CUDA base image' } : { success: true }+ ));++ const result = await provision();++ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/docker compose build failed/) });+ expect(dockerCalls()).not.toContain('compose run --rm prepare');+ });++ it('cancels between steps, and never kills a build or a prepare mid-flight', async () => {+ stageFreshProject();++ const result = await provisionVllmQwenProject({ emit: () => {}, isCancelled: () => true });++ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/cancelled/) });+ // Neither long step may be handed the predicate — killing them is what+ // leaves a half-written image layer behind.+ for (const [, args, , options] of streaming.runStreamingCommand.mock.calls) {+ if (['compose build', 'compose run --rm prepare'].includes(args.join(' '))) {+ expect(options?.isCancelled).toBeUndefined();+ }+ }+ });+});++describe('startVllmQwenProject', () => {+ it('brings up an already-prepared compose project in its own directory', async () => {+ const result = await startVllmQwenProject({ emit: () => {}, isCancelled: () => false });++ expect(result.success).toBe(true);+ expect(streaming.runStreamingCommand).toHaveBeenCalledWith(+ 'docker',+ ['compose', '--profile', 'single', 'up', '-d'],+ expect.any(Function),+ expect.objectContaining({ cwd: DIR }),+ );+ });++ it('refuses to run compose when the project is not demonstrably prepared', async () => {+ project.vllmStartBlockedReason.mockReturnValue('no Qwen weights are cached yet');++ const result = await startVllmQwenProject({ emit: () => {}, isCancelled: () => false });++ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/no Qwen weights are cached/) });+ // The whole point: a 20 GB pull is never started on the user's behalf.+ expect(streaming.runStreamingCommand).not.toHaveBeenCalled();+ });++ it('does not start a container nobody is waiting for', async () => {+ const result = await startVllmQwenProject({ emit: () => {}, isCancelled: () => true });++ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/Cancelled/) });+ expect(streaming.runStreamingCommand).not.toHaveBeenCalled();+ });+});