Skip to content

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

fix: find the SGLang project inside WSL2 on Windows instead of asking for a UNC path (#5832)

Adam Eivy67c09c00efda
diff --git a/docs/features/sglang-qwen38.md b/docs/features/sglang-qwen38.md
index 4405d25e69..15adbd6775 100644
--- a/docs/features/sglang-qwen38.md
+++ b/docs/features/sglang-qwen38.md
@@ -37,7 +37,8 @@ unmeasured number. If you bring one up on real hardware, write a dated note in
1. Docker with the NVIDIA Container Toolkit. PortOS does not install either —
they are host decisions with driver requirements it cannot judge.
2. Create a project directory. PortOS looks in `~/sglang-qwen38` by default;
- `SGLANG_QWEN_PROJECT_DIR` overrides it.
+ `SGLANG_QWEN_PROJECT_DIR` overrides it. **On Windows, do this inside your WSL2
+ distro** and let PortOS find it — see [Windows](#windows-the-project-lives-in-wsl2).
3. Save the compose file below into it as `docker-compose.yml`.
4. Pull the image and the weights **once, yourself** — roughly 20 GB:
@@ -50,6 +51,40 @@ unmeasured number. If you bring one up on real hardware, write a dated note in
somewhere else entirely? Point `SGLANG_QWEN_WEIGHTS_DIR` at them, so the
readiness check can see them.
+### Windows: the project lives in WSL2
+
+Docker Desktop's engine **is** a WSL2 VM. Prepare this project inside the distro
+— run the commands above there, not in PowerShell — so the compose file and the
+~20 GB of weights sit on the distro's own filesystem. A project on `C:\` is
+reached from inside that VM over a 9p share, which is slow in a way that is
+invisible until it has already cost the download.
+
+**You do not have to tell PortOS where that is.** A native-Win32 PortOS resolves
+the default `~/sglang-qwen38` to a *Windows* home, where the project is not — so
+before the Start button inspects anything, it asks WSL for the default distro's
+name and home (`wsl.exe -e sh -c 'echo "$WSL_DISTRO_NAME"; echo "$HOME"'`),
+checks that `\\wsl.localhost\<distro>\home\<user>` is readable from Windows, and
+records the resulting path in its own `.env`. Node reads that path and `docker
+compose` accepts it as a working directory, so the readiness poll, the Start
+button and the next server restart all resolve the same directory.
+
+It refuses only where it genuinely cannot answer the question — no WSL on the
+host, a default distro that belongs to a container engine (`docker-desktop`,
+recreated on a reset), or a `\\wsl.localhost` share Windows cannot read — and each
+refusal names that host's fix rather than a path template to fill in. Because
+there is no 1-click provisioning path for this stack, those refusals point back
+at this document: PortOS finds a project you prepared, it never creates one.
+
+Set `SGLANG_QWEN_PROJECT_DIR` only to overrule the detected placement, or when
+you prepared the project somewhere other than the default distro's home:
+
+```
+SGLANG_QWEN_PROJECT_DIR=\\wsl.localhost\<distro>\home\<user>\sglang-qwen38
+```
+
+An exported value wins over anything PortOS detected on an earlier run. On Linux
+the default is already correct.
+
## The compose file
Generated from `buildSglangQwenRecipe({ hw: 'h200' })` — that function is the
@@ -147,7 +182,9 @@ button on the provider readiness checklist. That button only ever brings up an
already-prepared project: it refuses on an unsupported card before it reaches
docker, refuses when the compose file is missing, and refuses when it cannot
confirm the weights are on disk. It never pulls the image and never downloads
-weights.
+weights. On Windows it first resolves the WSL2 placement described
+[above](#windows-the-project-lives-in-wsl2), so a project you prepared by hand
+inside the distro is found without any environment variable.
## Use it from an agent (OpenCode)
diff --git a/server/lib/README.md b/server/lib/README.md
index 22b80f4c0b..c73652de28 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -182,11 +182,12 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `mtplxModels.js` | `listMtplxCachedModels({command?})` → `{models, error}` from `mtplx models --json` (walks local directories — pulls no weights, loads no model, but see `mtplxRuntime.js`: on an un-warmed Homebrew wrapper the spawn ITSELF is a several-hundred-megabyte runtime download, so poll callers must gate on `describeMtplxRuntime().ready` first) 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. |
| `mtplxRuntime.js` | `describeMtplxRuntime(binaryPath, {env?})` → `{ready, wrapper, venvPath}` — is MTPLX's own Python runtime on disk, decided by READING the binary rather than running it. Homebrew's `mtplx` is a shell wrapper that lazily bootstraps a version-keyed Python venv (a multi-hundred-megabyte pip install) on its first invocation, and `brew upgrade` re-arms it, so a status poll or an 8s-judged PM2 start is really a package download. This parses the wrapper's own `VENV=` assignment, honours `$MTPLX_BREW_VENV` the way `${MTPLX_BREW_VENV:-…}` does, and tests `<venv>/bin/mtplx` for executability — the wrapper's own `[ ! -x … ]` guard, so the two cannot disagree. Anything unrecognisable (a pip install, a compiled binary, an unparseable script) reports `ready: true, wrapper: false`, i.e. the status quo — never a block over a parse failure. |
| `slotstreamModels.js` | `listSlotstreamCachedModels({cacheDir?})` → `{models, error}` from a local directory walk of the SSD-streaming MoE cache (no network, no model load), `pickSlotstreamCachedModel(models, requested?)` → the checkpoint id to hand `slotstream serve --model`, and `planSlotstreamMemory({totalBytes?, overrideGb?})` → `{targetGb, expectedPeakGb, expectedWarmDecodeToks, auto}` so the LLMs row can show the memory plan instead of hiding it. `models: null` means the cache could not be READ and is deliberately distinct from `[]` (read, and empty), because a start never fetches weights. |
-| `vllmQwenProject.js` | `resolveVllmProjectDir()` / `inspectVllmQwenProject()` → `{dir, hasProject, composeFile, hasWeights, weightsRoot}` for the 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. `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. Also owns WHERE the project lives: `readRecordedVllmProjectDir(envPath?)` / `recordVllmProjectDir(dir, envPath?)` keep PortOS's auto-detected directory as one line in the INSTALL's `.env` (`PATHS.installRoot`, so a worktree-booted server writes where the real install reads), and `vllmProjectDirIsSettled()` answers "is detection still worth a subprocess?" so the manager never re-lists the precedence. That order is `VLLM_QWEN_PROJECT_DIR` (this run's decision) → the record → `~/qwen-serving`; `envPath` is a parameter so a test's sandbox answers instead of the developer's install. Directory reads plus that one config line — never docker, never a registry. Other override: `VLLM_QWEN_WEIGHTS_DIR`. |
+| `recordedProjectDir.js` | Where PortOS remembers a container project it had to go and FIND — one `.env` line per stack in the INSTALL's root (`PATHS.installRoot`, so a worktree-booted server writes where the real install reads). `readRecordedProjectDir(envVar, envPath?)` / `recordProjectDir(envVar, dir, envPath?)` / `projectDirIsSettled(envVar, env?, envPath?)` / `resolveRecordedProjectDir(envVar, defaultDir, env?, envPath?)` are all keyed on the env-var NAME, so the vLLM and SGLang Qwen3.8-27B stacks share one implementation instead of drifting on the precedence rule — exported value (this run's decision) → the record (an earlier run's) → the stack's documented default. Read from the file on every call, never cached: a placement run writes it and the readiness poll in the same process must see it without a restart, and PortOS has no dotenv so `.env` reaches `process.env` for nobody. Writes are atomic and replace the key's line rather than appending (`upsertEnvLine`) — that file also holds the database password. `envPath` is a parameter so a test's sandbox answers instead of the developer's install. Written by `services/wslProjectPlacement.js`. |
+| `vllmQwenProject.js` | `resolveVllmProjectDir()` / `inspectVllmQwenProject()` → `{dir, hasProject, composeFile, hasWeights, weightsRoot}` for the 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. `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. Also owns WHERE the project lives, as this stack's keyed view of `recordedProjectDir.js`: `readRecordedVllmProjectDir(envPath?)` / `recordVllmProjectDir(dir, envPath?)` / `vllmProjectDirIsSettled()`, resolving `VLLM_QWEN_PROJECT_DIR` (this run's decision) → the record → `~/qwen-serving`; `envPath` is a parameter so a test's sandbox answers instead of the developer's install. Directory reads plus that one config line — never docker, never a registry. Other override: `VLLM_QWEN_WEIGHTS_DIR`. |
| `wslDistro.js` | Which WSL2 distro a native-Win32 PortOS should put Linux-side work in. `detectWslProjectDir(leaf)` → `{dir, distro, home}` or `{dir: null, reason}` (`no-wsl` / `no-distro` / `internal-distro` / `unreadable-share`), built from `wsl.exe -e sh -c 'echo "$WSL_DISTRO_NAME"; echo "$HOME"'` — the distro's OWN shell, because `wsl --list` prints UTF-16LE that a UTF-8 reader mangles while an executed program's stdout passes through byte for byte. Verifies the derived `\\wsl.localhost\…` path is readable from Windows before returning it (WSL running and its share answering are separate facts) and refuses a container engine's own distro (`docker-desktop` and friends are recreated on a reset). `parseWslProbe` / `parseWslDistroList` (NUL-stripping the UTF-16 bytes, for an error message only) are exported for their own tests; `WSL_UNC_PREFIX` names the share root for callers writing refusal prose. Exists so the vLLM stack places its ~20 GB of weights on the distro filesystem instead of asking a human to fill in a UNC template — every read from a `C:\` checkout would cross a 9p share. |
| `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, `parseEnvContents(contents)` → a key→value Map (keyed on *mention*, so a commented-out key reads as absent and `KEY=` as an intentional empty), and the two writers over one shared newline guard: `mergeEnvFileContents(existing, defaults)` → `{contents, added, kept, effective}` is **additive only** — an operator's existing key or tuning is never overwritten, and `effective` reports what the container will actually read — while `upsertEnvLine(contents, key, value)` REPLACES one key's line, for a value PortOS owns and re-derives (`vllmQwenProject.js`'s recorded project directory); its replacement is a function, not a string, so a `$`-sequence in the value is written literally. Plus `WSL2_PREPARE_MIN_BYTES` / `WSL2_PREPARE_CONFIG_HINT` for the ceiling `prepare` needs (detected and warned about, never raised). |
-| `sglangQwenProject.js` | `resolveSglangProjectDir()` / `inspectSglangQwenProject()` → `{dir, hasProject, composeFile, hasWeights, weightsRoot}` for the operator's SGLang Qwen3.8-27B project, plus `sglangStartBlockedReason(project)` → the prose refusal (or `null`). Sibling of `vllmQwenProject.js` with the same tri-state `hasWeights` contract (`true` found / `false` caches read and empty / `null` no cache readable) and the same directory-reads-only rule — never docker, never a registry. Differs in that PortOS OWNS this launch line (SGLang publishes an image but no compose project), so the refusals point at the compose file in `docs/features/sglang-qwen38.md` rather than at a `git clone`. Overrides: `SGLANG_QWEN_PROJECT_DIR`, `SGLANG_QWEN_WEIGHTS_DIR`. |
+| `sglangQwenProject.js` | `resolveSglangProjectDir()` / `inspectSglangQwenProject()` → `{dir, hasProject, composeFile, hasWeights, weightsRoot}` for the operator's SGLang Qwen3.8-27B project, plus `sglangStartBlockedReason(project)` → the prose refusal (or `null`). Sibling of `vllmQwenProject.js` with the same tri-state `hasWeights` contract (`true` found / `false` caches read and empty / `null` no cache readable) and the same directory-reads-only rule — never docker, never a registry. Differs in that PortOS OWNS this launch line (SGLang publishes an image but no compose project), so the refusals point at the compose file in `docs/features/sglang-qwen38.md` rather than at a `git clone`. Also this stack's keyed view of `recordedProjectDir.js` — `readRecordedSglangProjectDir(envPath?)` / `recordSglangProjectDir(dir, envPath?)` / `sglangProjectDirIsSettled()` plus `SGLANG_PROJECT_LEAF` — so `resolveSglangProjectDir()` reads `SGLANG_QWEN_PROJECT_DIR` → the UNC path `services/sglangQwenManager.js` detected and recorded on Windows → `~/sglang-qwen38`. Overrides: `SGLANG_QWEN_PROJECT_DIR`, `SGLANG_QWEN_WEIGHTS_DIR`. |
| `sglangQwenRecipe.js` | The `sglang serve` launch line PortOS owns, per NVIDIA card class. `buildSglangQwenRecipe({hw, contextLength, ssmDtype, spec, radixStrategy, host, port})` → `{image, modelName, modelPath, cell, mambaRatio, stateSlots, flags, env}`, and `sglangComposeYaml(recipe)` renders the `docker-compose.yml` from it (one source of truth; a test pins the doc against it). `mambaFullMemoryRatio(...)` derives `--mamba-full-memory-ratio` from the cookbook formula `(S + D) × state_bytes / (L × kv_bytes_per_token)` — load-bearing, because the cookbook default `0.9` under-sizes the GDN state pool at CoS prompt lengths and silently clamps `max_running_requests`. Both Qwen parsers (`--reasoning-parser qwen3`, `--tool-call-parser qwen3_coder` — NOT vLLM's `qwen3_xml`) are baked into every cell: getting them wrong fails silently, with the model emitting raw markup and the agent never calling a tool. `sglangCellForGpu(gpu)` maps a `cudaCapability.js` compute-cap row to a cell (SM 9.x → `h200`, SM ≥10 → `rtx6000`/`rtx5090` by VRAM, Ampere → `null`, which is a refusal: 24 GB stays on vLLM), and `sglangUnsupportedReason({platform, status, gpus})` is the prose for every no — never collapsing a probe `'unknown'` into "no GPU". Pure: no filesystem, no docker, no network. |
| `opencodeStream.js` | OpenCode's `--format json` event stream — ONE parser, shared by `services/localModelAgentBenchmark.js` (which wants chars/tokens) and `services/modelCapabilityTests.js` (which wants a readable transcript). `eventPart` (accepts the flat `{part}` and nested `{properties.part}` envelopes OpenCode has both used), `isToolEvent` / `eventText`, `parseAgentLine` / `parseAgentEvents` (blank and unparsable lines yield nothing rather than throwing), `formatAgentEvent` (one frame → a transcript line a person can read, with the path or command the tool acted on), and `summarizeOpenCodeEvents` (assistant chars, tool calls, and output tokens — `null`, never 0, when OpenCode reported no usage; tool ARGUMENTS are deliberately not counted as answer text). Pure. The runner that produces the stream is `services/opencodeTask.js`. |
| `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. |
diff --git a/server/lib/index.js b/server/lib/index.js
index cab611c94a..d4b36554a4 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -190,6 +190,7 @@ export * from './mtplxModels.js';
export * from './mtplxRuntime.js';
export * from './slotstreamModels.js';
export * from './managedDaemon.js';
+export * from './recordedProjectDir.js';
export * from './vllmQwenProject.js';
export * from './wslDistro.js';
export * from './qwenAgentParsers.js';
diff --git a/server/lib/recordedProjectDir.js b/server/lib/recordedProjectDir.js
new file mode 100644
index 0000000000..cf2b974ba8
--- /dev/null
+++ b/server/lib/recordedProjectDir.js
@@ -0,0 +1,116 @@
+/**
+ * Where PortOS remembers a container project it had to go and FIND — one line
+ * per stack in the install's own `.env`.
+ *
+ * Two runtimes now share this question. On Windows neither the vLLM nor the
+ * SGLang Qwen3.8-27B project lives where its default resolves: Docker Desktop's
+ * engine IS a WSL2 VM, so the compose project and its ~20 GB of weights sit
+ * inside a distro and are reached from Windows as `\\wsl.localhost\<distro>\…`.
+ * `services/wslProjectPlacement.js` asks WSL for that path; this module is where
+ * the answer is written down, so the readiness poll, the Start button and the
+ * next server boot all resolve the directory that run actually used.
+ *
+ * Everything here is keyed on the env-var NAME rather than baked to one stack —
+ * a second copy of this loop is how the two would drift on the precedence rule
+ * below, which is invisible on any non-Windows machine.
+ *
+ * **The precedence is deliberate and identical for every stack:** an exported
+ * value (this run's decision) outranks the record (some earlier run's), which
+ * outranks the documented default. A directory PortOS auto-detected once must
+ * never quietly outlive an operator who exports the variable today.
+ *
+ * PortOS has no dotenv, so `.env` reaches `process.env` for nobody — a reader
+ * that wants a value out of it opens the file, the same way
+ * `services/localLlm.js` reads its `LLM_BACKEND` marker. Read on every call
+ * rather than cached: a placement run writes it, and the readiness poll that
+ * must start seeing the new directory lives in the same process without a
+ * restart between them.
+ */
+
+import { readFileSync } from 'fs';
+import { join } from 'path';
+
+// From the leaf modules, not the `fileUtils.js` aggregate: several route suites
+// replace that whole aggregate with a small literal, and a module-level
+// `PATHS.root` read through it explodes at import time in a suite that never
+// touches this file.
+import { atomicWrite } from './fileCore.js';
+import { PATHS } from './paths.js';
+import { parseEnvContents, upsertEnvLine } from './vllmQwenProvision.js';
+
+/**
+ * PortOS's own `.env` — where an auto-detected project directory is recorded.
+ *
+ * `installRoot`, not `root`: what is recorded here is machine-local runtime state
+ * ("where this machine's WSL project lives"), so it belongs to the install and
+ * not to whichever checkout loaded the code. A server booted from a CoS agent
+ * worktree has no `.env` in its own tree (`lib/paths.js`, #1947), and anchoring
+ * to `root` there would write a throwaway file the real install never reads.
+ */
+export const PORTOS_ENV_PATH = join(PATHS.installRoot, '.env');
+
+/**
+ * The project directory PortOS recorded under `envVar`, or `''` when there is
+ * none.
+ *
+ * @param {string} envVar
+ * @param {string} [envPath]
+ * @returns {string}
+ */
+export function readRecordedProjectDir(envVar, envPath = PORTOS_ENV_PATH) {
+ let contents = '';
+ try { contents = readFileSync(envPath, 'utf8'); } catch { return ''; }
+ return parseEnvContents(contents).get(envVar) || '';
+}
+
+/**
+ * Remember where a project was found, so nothing has to detect it twice.
+ *
+ * `upsertEnvLine` rather than an append: a file accumulating one line per
+ * detection run is a config whose meaning depends on which reader opens it
+ * (some take the first mention, some the last). Atomic, because PortOS's `.env`
+ * also carries the database password and a half-written truncate is readable by
+ * a concurrent boot.
+ *
+ * @param {string} envVar
+ * @param {string} dir
+ * @param {string} [envPath]
+ */
+export async function recordProjectDir(envVar, dir, envPath = PORTOS_ENV_PATH) {
+ let contents = '';
+ try { contents = readFileSync(envPath, 'utf8'); } catch { /* no .env yet */ }
+ await atomicWrite(envPath, upsertEnvLine(contents, envVar, dir));
+}
+
+/**
+ * Whether anything already answers "where does this project live", so a caller
+ * knows whether detecting it is still worth a subprocess.
+ *
+ * Exported so the placement service asks THIS module rather than re-listing the
+ * two sources — a precedence change made in one place and not the other is
+ * invisible on any non-Windows machine.
+ *
+ * @param {string} envVar
+ * @param {NodeJS.ProcessEnv} [env]
+ * @param {string} [envPath]
+ * @returns {boolean}
+ */
+export function projectDirIsSettled(envVar, env = process.env, envPath = PORTOS_ENV_PATH) {
+ return Boolean(String(env?.[envVar] || '').trim() || readRecordedProjectDir(envVar, envPath));
+}
+
+/**
+ * The configured directory, what PortOS recorded, or the stack's documented
+ * default — in that order. The one place that order is written down.
+ *
+ * @param {string} envVar
+ * @param {() => string} defaultDir - evaluated only when neither source answers
+ * @param {NodeJS.ProcessEnv} [env]
+ * @param {string} [envPath]
+ * @returns {string}
+ */
+export function resolveRecordedProjectDir(envVar, defaultDir, env = process.env, envPath = PORTOS_ENV_PATH) {
+ const configured = String(env?.[envVar] || '').trim();
+ if (configured) return configured;
+ return readRecordedProjectDir(envVar, envPath) || defaultDir();
+}
diff --git a/server/lib/sglangQwenProject.js b/server/lib/sglangQwenProject.js
index b05abf0efd..d76d1cc15c 100644
--- a/server/lib/sglangQwenProject.js
+++ b/server/lib/sglangQwenProject.js
@@ -24,14 +24,36 @@
* cache" send the operator to different fixes. `null` is a real deployment
* shape, not a bug: a cache kept in a docker named volume is invisible to a
* PortOS running outside the container, and on Windows the project usually lives
- * inside a WSL2 distro. `SGLANG_QWEN_PROJECT_DIR` / `SGLANG_QWEN_WEIGHTS_DIR`
- * are the answers to those two cases respectively.
+ * inside a WSL2 distro. `SGLANG_QWEN_WEIGHTS_DIR` answers the first.
+ *
+ * **The operator no longer types the Windows UNC path themselves.** The second
+ * case used to be theirs to fix: the default `%USERPROFILE%\sglang-qwen38`
+ * resolves to a *Windows* home, the project is inside a WSL2 distro, and the
+ * refusal handed them a `\\wsl.localhost\<distro>\home\<user>\…` template with
+ * two values to look up. It bit every Windows operator, because SGLang ships no
+ * provisioner and preparing it by hand inside the distro is the only path. Now
+ * `services/sglangQwenManager.js` asks WSL for those two values (the shared
+ * `services/wslProjectPlacement.js` loop) and records the answer through
+ * `recordSglangProjectDir` below, so the readiness poll, the Start button and
+ * the next boot all resolve the directory that run found.
+ *
+ * SGLang gets detect + record only, never placement: there is no provisioner to
+ * clone into the directory, so a host WSL cannot answer for still gets a refusal
+ * pointing at `docs/features/sglang-qwen38.md`.
*/
import { readdir, stat } from 'fs/promises';
import { homedir } from 'os';
import { join } from 'path';
+import {
+ PORTOS_ENV_PATH,
+ projectDirIsSettled,
+ readRecordedProjectDir,
+ recordProjectDir,
+ resolveRecordedProjectDir,
+} from './recordedProjectDir.js';
+
/** Operator override for where the compose project was created. */
export const SGLANG_PROJECT_DIR_ENV = 'SGLANG_QWEN_PROJECT_DIR';
@@ -46,8 +68,46 @@ export const SGLANG_WEIGHTS_DIR_ENV = 'SGLANG_QWEN_WEIGHTS_DIR';
const resolveHome = (env) =>
String(env?.HOME || env?.USERPROFILE || '').trim() || homedir();
+/** The directory name the feature doc uses, inside whichever home holds it. */
+export const SGLANG_PROJECT_LEAF = 'sglang-qwen38';
+
/** Where `docs/features/sglang-qwen38.md` tells the operator to create it. */
-export const sglangDefaultProjectDir = (env = process.env) => join(resolveHome(env), 'sglang-qwen38');
+export const sglangDefaultProjectDir = (env = process.env) => join(resolveHome(env), SGLANG_PROJECT_LEAF);
+
+/**
+ * This stack's view of the shared `.env` record (`lib/recordedProjectDir.js`),
+ * keyed on `SGLANG_QWEN_PROJECT_DIR`.
+ *
+ * @param {string} [envPath]
+ * @returns {string}
+ */
+export function readRecordedSglangProjectDir(envPath = PORTOS_ENV_PATH) {
+ return readRecordedProjectDir(SGLANG_PROJECT_DIR_ENV, envPath);
+}
+
+/**
+ * Remember where this project was found, so nothing has to detect it twice.
+ *
+ * @param {string} dir
+ * @param {string} [envPath]
+ */
+export async function recordSglangProjectDir(dir, envPath = PORTOS_ENV_PATH) {
+ return recordProjectDir(SGLANG_PROJECT_DIR_ENV, dir, envPath);
+}
+
+/**
+ * Whether anything already answers "where does this project live", so the
+ * manager knows whether a WSL probe is still worth a subprocess. Exported so it
+ * asks THIS module rather than re-listing the precedence `resolveSglangProjectDir`
+ * already owns.
+ *
+ * @param {NodeJS.ProcessEnv} [env]
+ * @param {string} [envPath]
+ * @returns {boolean}
+ */
+export function sglangProjectDirIsSettled(env = process.env, envPath = PORTOS_ENV_PATH) {
+ return projectDirIsSettled(SGLANG_PROJECT_DIR_ENV, env, envPath);
+}
/** Compose file names docker itself accepts, in its own precedence order. */
const COMPOSE_FILENAMES = ['docker-compose.yml', 'docker-compose.yaml', 'compose.yml', 'compose.yaml'];
@@ -73,10 +133,22 @@ const LOCAL_WEIGHT_MARKERS = ['model.safetensors.index.json', 'model.safetensors
const isDirectory = (path) => stat(path).then((s) => s.isDirectory(), () => false);
const isFile = (path) => stat(path).then((s) => s.isFile(), () => false);
-/** The configured project directory, or the documented default. */
-export function resolveSglangProjectDir(env = process.env) {
- const configured = String(env?.[SGLANG_PROJECT_DIR_ENV] || '').trim();
- return configured || sglangDefaultProjectDir(env);
+/**
+ * The configured project directory, what PortOS recorded, or the documented
+ * default — in that order.
+ *
+ * The process environment outranks the recorded value deliberately: an operator
+ * who exports this variable (in their shell, or in `ecosystem.config.cjs`) is
+ * making a decision for this run, and a directory PortOS auto-detected on some
+ * earlier run must not quietly outlive it.
+ *
+ * @param {NodeJS.ProcessEnv} [env]
+ * @param {string} [envPath] - which `.env` holds the record; a parameter for the
+ * same reason `resolveHome` reads the passed env — so a test's sandbox answers
+ * instead of whatever the developer's own install happens to have recorded.
+ */
+export function resolveSglangProjectDir(env = process.env, envPath = PORTOS_ENV_PATH) {
+ return resolveRecordedProjectDir(SGLANG_PROJECT_DIR_ENV, () => sglangDefaultProjectDir(env), env, envPath);
}
/**
@@ -121,11 +193,12 @@ async function rootHoldsQwenWeights(root, entries) {
* Inspect the operator's SGLang project without touching docker.
*
* @param {NodeJS.ProcessEnv} [env]
+ * @param {string} [envPath] - which `.env` holds the recorded directory
* @returns {Promise<{dir:string, hasProject:boolean, composeFile:string|null,
* hasWeights:boolean|null, weightsRoot:string|null}>}
*/
-export async function inspectSglangQwenProject(env = process.env) {
- const dir = resolveSglangProjectDir(env);
+export async function inspectSglangQwenProject(env = process.env, envPath = PORTOS_ENV_PATH) {
+ const dir = resolveSglangProjectDir(env, envPath);
const hasProject = await isDirectory(dir);
let composeFile = null;
@@ -176,7 +249,7 @@ export function sglangStartBlockedReason(project) {
return 'the compose file is in place but no Qwen weights are cached yet. Download them in a terminal first — starting compose now would pull roughly 20 GB, which PortOS will not do for you.';
}
if (project.hasWeights === null) {
- return `PortOS cannot read a HuggingFace cache for this project, so it cannot confirm the weights are already downloaded. Set ${SGLANG_WEIGHTS_DIR_ENV} to the directory holding them (a docker named volume is invisible from here), or start it yourself with \`docker compose up -d\` in ${project.dir}.`;
+ return `PortOS cannot read a HuggingFace cache for this project, so it cannot confirm the weights are already downloaded. On Windows it asks WSL where the project lives and records the UNC path for itself — if that record is stale, or the weights live somewhere else entirely (a docker named volume is invisible from here), set ${SGLANG_PROJECT_DIR_ENV} or ${SGLANG_WEIGHTS_DIR_ENV} to where they actually are. Failing that, start it yourself with \`docker compose up -d\` in ${project.dir}.`;
}
return null;
}
diff --git a/server/lib/sglangQwenProject.test.js b/server/lib/sglangQwenProject.test.js
index ea49dc625f..32485e5fb5 100644
--- a/server/lib/sglangQwenProject.test.js
+++ b/server/lib/sglangQwenProject.test.js
@@ -1,12 +1,15 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
-import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'fs';
+import { mkdtempSync, readFileSync, rmSync, mkdirSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import {
inspectSglangQwenProject,
+ readRecordedSglangProjectDir,
+ recordSglangProjectDir,
resolveSglangProjectDir,
sglangDefaultProjectDir,
+ sglangProjectDirIsSettled,
sglangStartBlockedReason,
SGLANG_PROJECT_DIR_ENV,
SGLANG_WEIGHTS_DIR_ENV,
@@ -18,25 +21,65 @@ let root;
* ever be answered by the developer's real HuggingFace cache.
*/
const envAt = (overrides = {}) => ({ HOME: root, USERPROFILE: root, ...overrides });
+/**
+ * The `.env` PortOS records a detected directory in — inside the sandbox, so a
+ * value the developer's own install recorded can never answer an assertion here
+ * (nor can one of these writes land in it).
+ */
+const envPath = () => join(root, '.env');
beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'sglang-project-')); });
afterEach(() => rmSync(root, { recursive: true, force: true }));
describe('resolveSglangProjectDir', () => {
it('defaults to ~/sglang-qwen38', () => {
- expect(resolveSglangProjectDir(envAt())).toBe(sglangDefaultProjectDir(envAt()));
- expect(resolveSglangProjectDir(envAt())).toBe(join(root, 'sglang-qwen38'));
+ expect(resolveSglangProjectDir(envAt(), envPath())).toBe(sglangDefaultProjectDir(envAt()));
+ expect(resolveSglangProjectDir(envAt(), envPath())).toBe(join(root, 'sglang-qwen38'));
});
it('honors the override, ignoring a blank one', () => {
- expect(resolveSglangProjectDir(envAt({ [SGLANG_PROJECT_DIR_ENV]: '/srv/sglang' }))).toBe('/srv/sglang');
- expect(resolveSglangProjectDir(envAt({ [SGLANG_PROJECT_DIR_ENV]: ' ' }))).toBe(join(root, 'sglang-qwen38'));
+ expect(resolveSglangProjectDir(envAt({ [SGLANG_PROJECT_DIR_ENV]: '/srv/sglang' }), envPath())).toBe('/srv/sglang');
+ expect(resolveSglangProjectDir(envAt({ [SGLANG_PROJECT_DIR_ENV]: ' ' }), envPath())).toBe(join(root, 'sglang-qwen38'));
+ });
+
+ it('falls back to the UNC path PortOS detected and recorded for itself', async () => {
+ // The Windows shape: the project is prepared by hand inside a WSL2 distro,
+ // and `~/sglang-qwen38` resolves to a Windows home it is not in.
+ const recorded = '\\\\wsl.localhost\\Example-Distro\\home\\example-user\\sglang-qwen38';
+ await recordSglangProjectDir(recorded, envPath());
+
+ expect(readRecordedSglangProjectDir(envPath())).toBe(recorded);
+ expect(resolveSglangProjectDir(envAt(), envPath())).toBe(recorded);
+ // An exported override still outranks it — that is this run's decision, and
+ // a directory detected on some earlier run must not outlive it.
+ expect(resolveSglangProjectDir(envAt({ [SGLANG_PROJECT_DIR_ENV]: '/srv/sglang' }), envPath())).toBe('/srv/sglang');
+ });
+
+ it('rewrites its own record instead of appending a second line', async () => {
+ writeFileSync(envPath(), 'PGPASSWORD=portos');
+ await recordSglangProjectDir('/srv/first', envPath());
+ await recordSglangProjectDir('/srv/second', envPath());
+
+ const contents = readFileSync(envPath(), 'utf8');
+ expect(contents.match(/^SGLANG_QWEN_PROJECT_DIR=/gm)).toHaveLength(1);
+ expect(readRecordedSglangProjectDir(envPath())).toBe('/srv/second');
+ // The line it was appended after had no trailing newline — splicing onto it
+ // would have corrupted both settings.
+ expect(contents).toContain('PGPASSWORD=portos\n');
+ });
+
+ it('reports nothing settled until something answers', async () => {
+ expect(sglangProjectDirIsSettled(envAt(), envPath())).toBe(false);
+ expect(sglangProjectDirIsSettled(envAt({ [SGLANG_PROJECT_DIR_ENV]: '/srv/sglang' }), envPath())).toBe(true);
+
+ await recordSglangProjectDir('/srv/recorded', envPath());
+ expect(sglangProjectDirIsSettled(envAt(), envPath())).toBe(true);
});
});
describe('inspectSglangQwenProject', () => {
it('reports an absent project without claiming anything about weights', async () => {
- const project = await inspectSglangQwenProject(envAt());
+ const project = await inspectSglangQwenProject(envAt(), envPath());
expect(project).toMatchObject({ hasProject: false, composeFile: null, weightsRoot: null });
// No cache root was readable, so `hasWeights` must be the null sentinel —
// NOT `false`, which would claim the caches were read and found empty.
@@ -47,15 +90,15 @@ describe('inspectSglangQwenProject', () => {
const dir = join(root, 'sglang-qwen38');
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, 'compose.yaml'), '');
- expect((await inspectSglangQwenProject(envAt())).composeFile).toBe('compose.yaml');
+ expect((await inspectSglangQwenProject(envAt(), envPath())).composeFile).toBe('compose.yaml');
writeFileSync(join(dir, 'docker-compose.yml'), '');
- expect((await inspectSglangQwenProject(envAt())).composeFile).toBe('docker-compose.yml');
+ expect((await inspectSglangQwenProject(envAt(), envPath())).composeFile).toBe('docker-compose.yml');
});
it('distinguishes a readable-but-empty cache from an unreadable one', async () => {
const dir = join(root, 'sglang-qwen38');
mkdirSync(join(dir, 'hf-cache'), { recursive: true });
- const project = await inspectSglangQwenProject(envAt());
+ const project = await inspectSglangQwenProject(envAt(), envPath());
expect(project.hasWeights).toBe(false);
expect(project.weightsRoot).toBeNull();
});
@@ -63,7 +106,7 @@ describe('inspectSglangQwenProject', () => {
it('detects the HuggingFace hub layout', async () => {
const hub = join(root, 'sglang-qwen38', 'hf-cache', 'hub');
mkdirSync(join(hub, 'models--Qwen--Qwen3.8-27B-FP8'), { recursive: true });
- const project = await inspectSglangQwenProject(envAt());
+ const project = await inspectSglangQwenProject(envAt(), envPath());
expect(project).toMatchObject({ hasWeights: true, weightsRoot: hub });
});
@@ -71,15 +114,15 @@ describe('inspectSglangQwenProject', () => {
const models = join(root, 'sglang-qwen38', 'models');
mkdirSync(join(models, 'Qwen3.8-27B-FP8'), { recursive: true });
// A directory named after the model but holding no tensors is notes, not weights.
- expect((await inspectSglangQwenProject(envAt())).hasWeights).toBe(false);
+ expect((await inspectSglangQwenProject(envAt(), envPath())).hasWeights).toBe(false);
writeFileSync(join(models, 'Qwen3.8-27B-FP8', 'model.safetensors.index.json'), '{}');
- expect((await inspectSglangQwenProject(envAt())).hasWeights).toBe(true);
+ expect((await inspectSglangQwenProject(envAt(), envPath())).hasWeights).toBe(true);
});
it('checks the explicit weights override first', async () => {
const elsewhere = join(root, 'elsewhere');
mkdirSync(join(elsewhere, 'models--Qwen--Qwen3.8-27B-NVFP4'), { recursive: true });
- const project = await inspectSglangQwenProject(envAt({ [SGLANG_WEIGHTS_DIR_ENV]: elsewhere }));
+ const project = await inspectSglangQwenProject(envAt({ [SGLANG_WEIGHTS_DIR_ENV]: elsewhere }), envPath());
expect(project).toMatchObject({ hasWeights: true, weightsRoot: elsewhere });
});
});
@@ -109,7 +152,10 @@ describe('sglangStartBlockedReason', () => {
const unknown = sglangStartBlockedReason({ ...base, hasWeights: null });
expect(empty).toMatch(/no Qwen weights are cached yet/);
expect(unknown).toMatch(/cannot read a HuggingFace cache/);
+ // Both overrides, because a stale recorded project directory is now one of
+ // the ways this case is reached on Windows.
expect(unknown).toContain(SGLANG_WEIGHTS_DIR_ENV);
+ expect(unknown).toContain(SGLANG_PROJECT_DIR_ENV);
expect(empty).not.toBe(unknown);
});
});
diff --git a/server/lib/vllmQwenProject.js b/server/lib/vllmQwenProject.js
index 0996b1bb8d..915a29bc57 100644
--- a/server/lib/vllmQwenProject.js
+++ b/server/lib/vllmQwenProject.js
@@ -30,26 +30,27 @@
* themselves, which is the documented path anyway.
*
* **The operator no longer types that UNC path themselves.** On Windows,
- * `services/vllmQwenManager.js` asks WSL for it (`lib/wslDistro.js`) and records
- * the answer through `recordVllmProjectDir` below, so every later read — the
- * once-a-minute readiness inspection, the Start button, a restarted server —
- * resolves the same directory the provisioning run actually used. The record is
- * one line in PortOS's own `.env`, kept HERE because "where does this project
- * live" is one question and one module should answer it.
+ * `services/vllmQwenManager.js` asks WSL for it (via the shared
+ * `services/wslProjectPlacement.js` loop) and records the answer through
+ * `recordVllmProjectDir` below, so every later read — the once-a-minute
+ * readiness inspection, the Start button, a restarted server — resolves the same
+ * directory the provisioning run actually used. The record is one line in
+ * PortOS's own `.env`; the mechanics of reading and writing it live in
+ * `lib/recordedProjectDir.js`, shared with the SGLang stack, and this module
+ * states only which variable names THIS project.
*/
-import { readFileSync } from 'fs';
import { readdir, stat } from 'fs/promises';
import { homedir } from 'os';
import { join } from 'path';
-// From the leaf modules, not the `fileUtils.js` aggregate: several route suites
-// replace that whole aggregate with a small literal, and a module-level
-// `PATHS.root` read through it explodes at import time in a suite that never
-// touches this file.
-import { atomicWrite } from './fileCore.js';
-import { PATHS } from './paths.js';
-import { parseEnvContents, upsertEnvLine } from './vllmQwenProvision.js';
+import {
+ PORTOS_ENV_PATH,
+ projectDirIsSettled,
+ readRecordedProjectDir,
+ recordProjectDir,
+ resolveRecordedProjectDir,
+} from './recordedProjectDir.js';
/** Operator override for where the compose project was cloned. */
export const VLLM_PROJECT_DIR_ENV = 'VLLM_QWEN_PROJECT_DIR';
@@ -57,17 +58,6 @@ export const VLLM_PROJECT_DIR_ENV = 'VLLM_QWEN_PROJECT_DIR';
/** The directory name upstream's README uses, inside whichever home holds it. */
export const VLLM_PROJECT_LEAF = 'qwen-serving';
-/**
- * PortOS's own `.env` — where an auto-detected project directory is recorded.
- *
- * `installRoot`, not `root`: what is recorded here is machine-local runtime state
- * ("where this machine's WSL project lives"), so it belongs to the install and
- * not to whichever checkout loaded the code. A server booted from a CoS agent
- * worktree has no `.env` in its own tree (`lib/paths.js`, #1947), and anchoring
- * to `root` there would write a throwaway file the real install never reads.
- */
-export const PORTOS_ENV_PATH = join(PATHS.installRoot, '.env');
-
/**
* Operator override for the HuggingFace cache holding the weights — the answer
* for a stack whose cache is a docker named volume PortOS cannot see.
@@ -86,40 +76,27 @@ const resolveHome = (env) =>
export const vllmDefaultProjectDir = (env = process.env) => join(resolveHome(env), VLLM_PROJECT_LEAF);
/**
- * The project directory PortOS recorded for itself, or `''` when there is none.
+ * This stack's view of the shared `.env` record (`lib/recordedProjectDir.js`),
+ * keyed on `VLLM_QWEN_PROJECT_DIR`.
*
- * Read from the file on every call rather than cached: the provisioning run
- * writes it, and the readiness poll that must start seeing the new directory
- * lives in the same process without a restart between them. PortOS has no
- * dotenv, so `.env` reaches `process.env` for nobody — a module that wants a
- * value out of it reads the file, the same way `services/localLlm.js` reads its
- * `LLM_BACKEND` marker.
+ * Named wrappers rather than call sites passing the key: "which variable names
+ * the vLLM project" is one fact, and it is stated here.
*
* @param {string} [envPath]
* @returns {string}
*/
export function readRecordedVllmProjectDir(envPath = PORTOS_ENV_PATH) {
- let contents = '';
- try { contents = readFileSync(envPath, 'utf8'); } catch { return ''; }
- return parseEnvContents(contents).get(VLLM_PROJECT_DIR_ENV) || '';
+ return readRecordedProjectDir(VLLM_PROJECT_DIR_ENV, envPath);
}
/**
* Remember where this project was placed, so nothing has to detect it twice.
*
- * `upsertEnvLine` rather than an append: a file accumulating one line per
- * provisioning run is a config whose meaning depends on which reader opens it
- * (some take the first mention, some the last). Atomic, because PortOS's `.env`
- * also carries the database password and a half-written truncate is readable by
- * a concurrent boot.
- *
* @param {string} dir
* @param {string} [envPath]
*/
export async function recordVllmProjectDir(dir, envPath = PORTOS_ENV_PATH) {
- let contents = '';
- try { contents = readFileSync(envPath, 'utf8'); } catch { /* no .env yet */ }
- await atomicWrite(envPath, upsertEnvLine(contents, VLLM_PROJECT_DIR_ENV, dir));
+ return recordProjectDir(VLLM_PROJECT_DIR_ENV, dir, envPath);
}
/** Compose file names the upstream project may ship under. */
@@ -165,9 +142,7 @@ const isFile = (path) => stat(path).then((s) => s.isFile(), () => false);
* earlier run must not quietly outlive it.
*/
export function resolveVllmProjectDir(env = process.env, envPath = PORTOS_ENV_PATH) {
- const configured = String(env?.[VLLM_PROJECT_DIR_ENV] || '').trim();
- if (configured) return configured;
- return readRecordedVllmProjectDir(envPath) || vllmDefaultProjectDir(env);
+ return resolveRecordedProjectDir(VLLM_PROJECT_DIR_ENV, () => vllmDefaultProjectDir(env), env, envPath);
}
/**
@@ -179,7 +154,7 @@ export function resolveVllmProjectDir(env = process.env, envPath = PORTOS_ENV_PA
* not the other is invisible on any non-Windows machine.
*/
export function vllmProjectDirIsSettled(env = process.env, envPath = PORTOS_ENV_PATH) {
- return Boolean(String(env?.[VLLM_PROJECT_DIR_ENV] || '').trim() || readRecordedVllmProjectDir(envPath));
+ return projectDirIsSettled(VLLM_PROJECT_DIR_ENV, env, envPath);
}
/**
diff --git a/server/services/localRuntimeSetup.js b/server/services/localRuntimeSetup.js
index 82f1bdbbc1..8106674766 100644
--- a/server/services/localRuntimeSetup.js
+++ b/server/services/localRuntimeSetup.js
@@ -60,6 +60,7 @@ import { describeMtplxRuntime } from '../lib/mtplxRuntime.js';
import { listSlotstreamCachedModels } from '../lib/slotstreamModels.js';
import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';
import { inspectSglangQwenProject, sglangStartBlockedReason } from '../lib/sglangQwenProject.js';
+import { ensureSglangProjectDir } from './sglangQwenManager.js';
import { sglangUnsupportedReason } from '../lib/sglangQwenRecipe.js';
import { getCudaCapability } from '../lib/cudaCapability.js';
import { findCommandOnPath } from '../lib/processEnv.js';
@@ -412,6 +413,12 @@ const SETUP_ROWS = Object.freeze({
const cuda = await getCudaCapability().catch(() => null);
const unsupported = sglangUnsupportedReason({ status: cuda?.status, gpus: cuda?.gpus });
if (unsupported) return { success: false, error: unsupported };
+ // Before the inspection, because on a Windows host this is what decides
+ // WHICH directory gets inspected: the project is prepared by hand inside a
+ // WSL2 distro (Docker Desktop's engine IS that VM), and the default
+ // `%USERPROFILE%\sglang-qwen38` is a Windows path PortOS would find empty.
+ const misplaced = await ensureSglangProjectDir({ emit });
+ if (misplaced) return { success: false, error: misplaced };
// Only ever brings up an ALREADY-prepared project — see
// `lib/sglangQwenProject.js` for why each refusal exists.
const project = await inspectSglangQwenProject();
diff --git a/server/services/localRuntimeSetup.test.js b/server/services/localRuntimeSetup.test.js
index ad757dc7d3..d543128bed 100644
--- a/server/services/localRuntimeSetup.test.js
+++ b/server/services/localRuntimeSetup.test.js
@@ -55,11 +55,20 @@ const vllmManager = vi.hoisted(() => ({
vi.mock('./vllmQwenManager.js', () => vllmManager);
// The SGLang project on disk, and the CUDA probe its start row consults BEFORE
// docker — mocked so no assertion depends on the developer's actual GPU.
+// PARTIAL: the env-var name and directory leaf the placement loop is keyed on
+// are constants this row imports, and the two `.env` helpers must be stubbed so
+// no assertion here can be answered by (or write into) the developer's install.
const sglangProject = vi.hoisted(() => ({
inspectSglangQwenProject: vi.fn(),
sglangStartBlockedReason: vi.fn(() => null),
+ sglangProjectDirIsSettled: vi.fn(() => false),
+ recordSglangProjectDir: vi.fn(async () => {}),
}));
-vi.mock('../lib/sglangQwenProject.js', () => sglangProject);
+vi.mock('../lib/sglangQwenProject.js', async (importOriginal) => ({ ...(await importOriginal()), ...sglangProject }));
+// `wsl.exe`. Mocked because the real one answers on a developer's Windows box —
+// the placement tests would then assert against THAT machine's distro.
+const wsl = vi.hoisted(() => ({ detectWslProjectDir: vi.fn() }));
+vi.mock('../lib/wslDistro.js', async (importOriginal) => ({ ...(await importOriginal()), ...wsl }));
const cuda = vi.hoisted(() => ({ getCudaCapability: vi.fn() }));
vi.mock('../lib/cudaCapability.js', () => cuda);
@@ -71,10 +80,14 @@ const reachable = (models = ['mtplx']) => ({ reachable: true, models, error: nul
const cachedModels = (models) => ({ models, error: null });
const preparedSglangProject = { dir: '/home/example/sglang-qwen38', hasProject: true, composeFile: 'docker-compose.yml', hasWeights: true, weightsRoot: '/home/example/sglang-qwen38/hf-cache/hub' };
+/** What `wsl.exe` says on a Windows host with an ordinary distro. */
+const SGLANG_WSL_DIR = '\\\\wsl.localhost\\Ubuntu\\home\\example\\sglang-qwen38';
beforeEach(() => {
sglangProject.inspectSglangQwenProject.mockResolvedValue(preparedSglangProject);
sglangProject.sglangStartBlockedReason.mockReturnValue(null);
+ sglangProject.sglangProjectDirIsSettled.mockImplementation(() => Boolean(process.env.SGLANG_QWEN_PROJECT_DIR));
+ wsl.detectWslProjectDir.mockResolvedValue({ dir: SGLANG_WSL_DIR, distro: 'Ubuntu', home: '\\\\wsl.localhost\\Ubuntu\\home\\example' });
// Default to the verified Hopper cell; the hardware cases override it.
cuda.getCudaCapability.mockResolvedValue({ status: 'available', gpus: [{ name: 'NVIDIA H200', computeCap: '9.0', vramGb: 141 }] });
// Implementations AND return values (not just call records) survive
@@ -94,6 +107,9 @@ afterEach(() => {
pathLookup.findCommandOnPath.mockReturnValue(null);
commands.commandExists.mockResolvedValue(true);
streaming.runStreamingCommand.mockResolvedValue({ success: true });
+ // The placement loop writes this on a Windows host so the rest of the run
+ // resolves the detected directory; it must not leak into the next test.
+ delete process.env.SGLANG_QWEN_PROJECT_DIR;
});
describe('describeRuntimeSetup', () => {
@@ -775,6 +791,91 @@ describe('sglang — a hardware gate in front of the same never-provision postur
restore();
});
+ it('asks WSL where the hand-prepared project is on Windows, and records the answer', async () => {
+ // The whole point of #5832: SGLang ships no provisioner, so preparing it by
+ // hand INSIDE the distro is the only path — and every Windows operator used
+ // to be handed a `\\wsl.localhost\<distro>\…` template to look up themselves.
+ const restore = pinPlatform('win32');
+ cuda.getCudaCapability.mockResolvedValue(hopper);
+ const lines = [];
+ pathLookup.findCommandOnPath.mockReturnValue('C:\\docker.exe');
+ probe.probeOpenAiModels
+ .mockResolvedValueOnce(unreachable)
+ .mockResolvedValueOnce(unreachable)
+ .mockResolvedValue(reachable(['qwen3.8-27b']));
+
+ const result = await runLocalRuntimeSetup('sglang', { endpoint: sglangEndpoint, emit: (line) => lines.push(line) });
+
+ expect(result.success).toBe(true);
+ expect(wsl.detectWslProjectDir).toHaveBeenCalledWith('sglang-qwen38');
+ expect(sglangProject.recordSglangProjectDir).toHaveBeenCalledWith(SGLANG_WSL_DIR);
+ // Recorded AND applied to this run, so the inspection below it resolves the
+ // detected directory even if the one-line `.env` write had failed.
+ expect(process.env.SGLANG_QWEN_PROJECT_DIR).toBe(SGLANG_WSL_DIR);
+ expect(lines.join('\n')).toContain(SGLANG_WSL_DIR);
+ restore();
+ });
+
+ it('never spends a WSL probe when the directory is already settled', async () => {
+ const restore = pinPlatform('win32');
+ cuda.getCudaCapability.mockResolvedValue(hopper);
+ process.env.SGLANG_QWEN_PROJECT_DIR = SGLANG_WSL_DIR;
+ pathLookup.findCommandOnPath.mockReturnValue('C:\\docker.exe');
+ probe.probeOpenAiModels
+ .mockResolvedValueOnce(unreachable)
+ .mockResolvedValueOnce(unreachable)
+ .mockResolvedValue(reachable(['qwen3.8-27b']));
+
+ await runLocalRuntimeSetup('sglang', { endpoint: sglangEndpoint, emit: () => {} });
+
+ // An exported value is this run's decision, and it outranks the record — so
+ // there is nothing left to detect and no subprocess worth spending.
+ expect(wsl.detectWslProjectDir).not.toHaveBeenCalled();
+ expect(sglangProject.recordSglangProjectDir).not.toHaveBeenCalled();
+ restore();
+ });
+
+ it('refuses before docker when WSL cannot answer, naming that host\'s fix and the feature doc', async () => {
+ const restore = pinPlatform('win32');
+ cuda.getCudaCapability.mockResolvedValue(hopper);
+ wsl.detectWslProjectDir.mockResolvedValue({ dir: null, reason: 'internal-distro', distro: 'docker-desktop', distros: ['Ubuntu'] });
+ pathLookup.findCommandOnPath.mockReturnValue('C:\\docker.exe');
+ probe.probeOpenAiModels.mockResolvedValue(unreachable);
+
+ const result = await runLocalRuntimeSetup('sglang', { endpoint: sglangEndpoint, emit: () => {} });
+
+ // Docker Desktop's own distro is wiped on a reset — and the refusal names
+ // the distro that ISN'T, rather than a `<distro>` placeholder.
+ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/docker-desktop/) });
+ expect(result.error).toMatch(/wsl --set-default/);
+ expect(result.error).toContain('Ubuntu');
+ expect(result.error).toContain('SGLANG_QWEN_PROJECT_DIR');
+ // Never reaches docker, so no image is ever pulled on a host that cannot
+ // hold the project.
+ expect(streaming.runStreamingCommand).not.toHaveBeenCalled();
+ expect(sglangProject.inspectSglangQwenProject).not.toHaveBeenCalled();
+ restore();
+ });
+
+ it('sends a Windows host with no WSL to the feature doc, never to a clone it does not have', async () => {
+ const restore = pinPlatform('win32');
+ cuda.getCudaCapability.mockResolvedValue(hopper);
+ wsl.detectWslProjectDir.mockResolvedValue({ dir: null, reason: 'no-wsl', error: 'spawn wsl.exe ENOENT' });
+ pathLookup.findCommandOnPath.mockReturnValue('C:\\docker.exe');
+ probe.probeOpenAiModels.mockResolvedValue(unreachable);
+
+ const result = await runLocalRuntimeSetup('sglang', { endpoint: sglangEndpoint, emit: () => {} });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatch(/wsl --install -d Ubuntu/);
+ // SGLang has no provisioner, so the refusal must NOT promise that clicking
+ // again places the project — it points at the doc the operator prepares it
+ // from. That clause is the one piece of this refusal that is per-stack.
+ expect(result.error).toContain('docs/features/sglang-qwen38.md');
+ expect(result.error).not.toMatch(/PortOS will place the project inside it/);
+ restore();
+ });
+
it('never installs docker or the container toolkit', async () => {
const restore = pinPlatform('linux');
cuda.getCudaCapability.mockResolvedValue(hopper);
diff --git a/server/services/sglangQwenManager.js b/server/services/sglangQwenManager.js
new file mode 100644
index 0000000000..024cb7b69b
--- /dev/null
+++ b/server/services/sglangQwenManager.js
@@ -0,0 +1,63 @@
+/**
+ * The one thing PortOS does TO the SGLang Qwen3.8-27B project: find out where
+ * it is on a Windows host.
+ *
+ * There is no provisioning counterpart to `services/vllmQwenManager.js` here, on
+ * purpose. SGLang publishes an image and no compose project, so PortOS owns the
+ * launch line (`lib/sglangQwenRecipe.js`) but nothing to clone — the operator
+ * prepares the directory once from `docs/features/sglang-qwen38.md`, and the
+ * checklist's Start button only ever brings up what is already there.
+ *
+ * That is exactly why the Windows placement question bit harder on this stack
+ * than on vLLM's. `%USERPROFILE%\sglang-qwen38` is a *Windows* home; the project
+ * and its ~20 GB of weights are inside a WSL2 distro, because Docker Desktop's
+ * engine IS a WSL2 VM. A native-Win32 PortOS could read neither, so the start
+ * refused and handed the operator a `\\wsl.localhost\<distro>\home\<user>\…`
+ * template with two values to look up. Since there is no 1-click path to fall
+ * back on, EVERY Windows operator hit it.
+ *
+ * `ensureSglangProjectDir` is the same settle → detect → record loop the vLLM
+ * stack uses — literally the same one (`services/wslProjectPlacement.js`) — with
+ * this stack's env-var name, directory leaf, and refusal wording. Detect and
+ * record only: nothing is created, so a host WSL cannot answer for is still
+ * pointed at the feature doc.
+ */
+
+import {
+ recordSglangProjectDir,
+ sglangProjectDirIsSettled,
+ SGLANG_PROJECT_DIR_ENV,
+ SGLANG_PROJECT_LEAF,
+} from '../lib/sglangQwenProject.js';
+import { ensureWslProjectDir } from './wslProjectPlacement.js';
+
+/**
+ * What the shared placement loop needs to speak for this stack.
+ *
+ * `afterInstall` is the one sentence that cannot be shared with vLLM: there the
+ * next click provisions the project into the new distro, here there is nothing
+ * to provision, so it names the doc the operator prepares it from instead.
+ */
+const SGLANG_PLACEMENT = Object.freeze({
+ envVar: SGLANG_PROJECT_DIR_ENV,
+ leaf: SGLANG_PROJECT_LEAF,
+ sizeHint: '~20 GB',
+ afterInstall: 'prepare the project inside it as docs/features/sglang-qwen38.md describes — PortOS finds it there by itself, and never downloads the image or the weights for you',
+});
+
+/**
+ * Settle where this project lives before the start row inspects it.
+ *
+ * @param {{emit?: (line: string) => void}} [ctx]
+ * @returns {Promise<string|null>} the refusal, or `null` once the directory is
+ * settled — the same shape as `sglangStartBlockedReason`, and read back the
+ * same way, through `inspectSglangQwenProject()`.
+ */
+export async function ensureSglangProjectDir({ emit } = {}) {
+ return ensureWslProjectDir({
+ ...SGLANG_PLACEMENT,
+ emit,
+ isSettled: () => sglangProjectDirIsSettled(),
+ record: (dir) => recordSglangProjectDir(dir),
+ });
+}
diff --git a/server/services/vllmQwenManager.js b/server/services/vllmQwenManager.js
index ef91594aaf..23517f399c 100644
--- a/server/services/vllmQwenManager.js
+++ b/server/services/vllmQwenManager.js
@@ -41,7 +41,6 @@ import {
VLLM_PROJECT_DIR_ENV,
VLLM_PROJECT_LEAF,
} from '../lib/vllmQwenProject.js';
-import { detectWslProjectDir, WSL_UNC_PREFIX } from '../lib/wslDistro.js';
import {
generateVllmApiKey,
isWsl2Engine,
@@ -52,6 +51,7 @@ import {
WSL2_PREPARE_MIN_BYTES,
} from '../lib/vllmQwenProvision.js';
import { getAllProviders, updateProvider } from './providers.js';
+import { ensureWslProjectDir } from './wslProjectPlacement.js';
/** Upstream's frozen packaging of patched vLLM + the requantized checkpoint. */
export const VLLM_UPSTREAM_REPO = 'https://github.com/syv-ai/qwen38-27b-rtx3090';
@@ -89,91 +89,42 @@ export async function readVllmQwenSetupState() {
return vllmProjectSetupState(await inspectVllmQwenProject());
}
-/** The real distros to offer, when there are any. */
-const nameDistros = (distros) => (distros?.length
- ? ` PortOS can see ${distros.join(', ')} — \`wsl --set-default <name>\` picks one; otherwise`
- : ' Install one with');
-
/**
- * The lead sentence for each way the WSL question can go unanswered.
+ * What the shared placement loop (`services/wslProjectPlacement.js`) needs to
+ * speak for this stack.
*
- * A table rather than four returns so the tail below is appended exactly once.
- * That tail is the part that must never go missing — a fifth reason added to
- * `detectWslProjectDir` would otherwise ship a refusal that neither rules out
- * `C:\` nor names the override.
+ * `afterInstall` is the one sentence that cannot be shared with SGLang: this is
+ * the stack PortOS provisions, so once a distro exists the next click really
+ * does place the project inside it.
*/
-const PLACEMENT_REFUSALS = Object.freeze({
- 'internal-distro': (f) => `the default WSL distro is \`${f.distro}\`, which is a container engine's own plumbing — it is recreated from scratch on a reset, so ~20 GB of weights must not live there.${nameDistros(f.distros)} \`wsl --install -d Ubuntu\`.`,
- 'unreadable-share': (f, detail) => `the \`${f.distro}\` distro answered, but Windows cannot read ${f.home} — the ${WSL_UNC_PREFIX} share is not responding${detail}. \`wsl --shutdown\` restarts it (that takes the whole VM down, so stop your containers first).`,
- 'no-distro': (f, detail) => `WSL is present but no distro answered${detail}, so there is no Linux filesystem to put this project on.${nameDistros(f.distros)} \`wsl --install -d Ubuntu\`.`,
- 'no-wsl': (_f, detail) => `this stack runs inside WSL2 — Docker Desktop's own engine IS a WSL2 VM — and \`wsl.exe\` did not run on this host${detail}. Install a distro with \`wsl --install -d Ubuntu\`, then click this again and PortOS will place the project inside it for you.`,
+const VLLM_PLACEMENT = Object.freeze({
+ envVar: VLLM_PROJECT_DIR_ENV,
+ leaf: VLLM_PROJECT_LEAF,
+ sizeHint: '~20 GB',
+ afterInstall: 'click this again and PortOS will place the project inside it for you',
});
-/**
- * Why PortOS could not find a Linux-side home for this project on a Windows
- * host — prose the checklist renders verbatim, one fix per case.
- *
- * There is no case for "the operator did not configure a directory" any more.
- * That was the old refusal, and it asked a person to look up two values
- * (`<distro>`, `<user>`) that WSL will state on request. What survives is the
- * set of answers PortOS genuinely cannot supply for itself: a machine with no
- * WSL, a default distro that belongs to a container engine, and a share Windows
- * cannot read.
- *
- * @param {{reason?: string, distro?: string, home?: string, error?: string, distros?: string[]}} found
- * @returns {string}
- */
-export function wslPlacementRefusal(found) {
- const lead = PLACEMENT_REFUSALS[found?.reason] || PLACEMENT_REFUSALS['no-wsl'];
- return `${lead(found || {}, found?.error ? ` (${found.error})` : '')} PortOS will not fall back to the Windows filesystem, where every one of those weight reads would cross a 9p share. To place the project somewhere of your own choosing instead, set ${VLLM_PROJECT_DIR_ENV} and click this again.`;
-}
-
/**
* Settle where this project goes before anything is written to it.
*
* On Windows the answer is never the default `%USERPROFILE%\qwen-serving`:
* Docker Desktop's engine is a WSL2 VM, so a project on the Windows filesystem
* is reached from inside that VM over a 9p share, and the ~20 GB of weights
- * would be written across it once and paged back across it forever. PortOS used
- * to refuse and hand the operator a UNC template to fill in by hand; it now asks
- * WSL for the same two values (`lib/wslDistro.js`) and records the answer, so
- * the readiness poll, the Start button, and the next server boot all resolve the
- * directory this run actually used.
- *
- * Detection runs ONLY when nothing already answers the question — an exported
- * `VLLM_QWEN_PROJECT_DIR` or an earlier recording both win, and neither costs a
- * subprocess. Off Windows there is nothing to detect: the default home is a
- * Linux filesystem already.
+ * would be written across it once and paged back across it forever. See
+ * `services/wslProjectPlacement.js` for the loop, which the SGLang stack shares.
*
* @param {{emit?: (line: string) => void}} [ctx]
* @returns {Promise<string|null>} the refusal, or `null` once the directory is
* settled — the same shape as `vllmStartBlockedReason`, and read back the same
* way, through `inspectVllmQwenProject()`.
*/
-export async function ensureVllmProjectDir({ emit = () => {} } = {}) {
- if (process.platform !== 'win32') return null;
- if (vllmProjectDirIsSettled()) return null;
-
- emit('Windows host — asking WSL where this project belongs, so its ~20 GB of weights land on the distro filesystem rather than on the Windows one.');
- const found = await detectWslProjectDir(VLLM_PROJECT_LEAF);
- if (!found.dir) return wslPlacementRefusal(found);
-
- emit(`Placing it in the \`${found.distro}\` distro, at ${found.dir}.`);
- // This process FIRST, the file second. `resolveVllmProjectDir` reads the env
- // ahead of the record, so every later read in this run — the re-inspection
- // below, the readiness poll, the Start button — resolves the detected
- // directory even when the write fails. Without it, a failed write silently
- // sends the very next inspection back to `%USERPROFILE%\qwen-serving`: the
- // C:\ placement this whole path exists to refuse.
- process.env[VLLM_PROJECT_DIR_ENV] = found.dir;
- // Recording is only what makes the choice outlive this run, so a failed write
- // costs exactly that — not a ~30 GB provision.
- const recordedOk = await recordVllmProjectDir(found.dir).then(() => true, (err) => {
- emit(`Could not record ${VLLM_PROJECT_DIR_ENV} in PortOS's .env (${err.message}) — this run still uses that directory, but set it there yourself or the next restart will look on the Windows filesystem again.`);
- return false;
+export async function ensureVllmProjectDir({ emit } = {}) {
+ return ensureWslProjectDir({
+ ...VLLM_PLACEMENT,
+ emit,
+ isSettled: () => vllmProjectDirIsSettled(),
+ record: (dir) => recordVllmProjectDir(dir),
});
- if (recordedOk) emit(`Recorded ${VLLM_PROJECT_DIR_ENV} in PortOS's .env, so the readiness check and the Start button find it too.`);
- return null;
}
/**
diff --git a/server/services/wslProjectPlacement.js b/server/services/wslProjectPlacement.js
new file mode 100644
index 0000000000..fe8a97677f
--- /dev/null
+++ b/server/services/wslProjectPlacement.js
@@ -0,0 +1,126 @@
+/**
+ * Settle where a container project lives on a Windows host, once, for every
+ * stack that has one.
+ *
+ * On Windows the answer is never the default `%USERPROFILE%\<leaf>`: Docker
+ * Desktop's engine IS a WSL2 VM, so a project on the Windows filesystem is
+ * reached from inside that VM over a 9p share, and tens of gigabytes of weights
+ * would be written across it once and paged back across it forever. PortOS used
+ * to refuse and hand the operator a UNC template with `<distro>` and `<user>`
+ * left as literal angle brackets for them to look up; it now asks WSL for those
+ * two values (`lib/wslDistro.js`) and records the answer
+ * (`lib/recordedProjectDir.js`), so the readiness poll, the Start button, and
+ * the next server boot all resolve the directory this run actually used.
+ *
+ * This module is the loop — settle → detect → record → emit — and it is
+ * deliberately the ONLY copy of it. Two stacks use it today (vLLM, which then
+ * clones into the directory, and SGLang, which only ever finds a hand-prepared
+ * one), and the difference between them is prose, not mechanism.
+ *
+ * It lives in `services/` rather than `lib/` because it spawns a subprocess and
+ * writes a file, neither of which a `lib/` module promises.
+ *
+ * Nothing here throws: every caller runs from an SSE route whose headers are
+ * already flushed, so a failure comes back as the refusal string.
+ */
+
+import { detectWslProjectDir, WSL_UNC_PREFIX } from '../lib/wslDistro.js';
+
+/** The real distros to offer, when there are any. */
+const nameDistros = (distros) => (distros?.length
+ ? ` PortOS can see ${distros.join(', ')} — \`wsl --set-default <name>\` picks one; otherwise`
+ : ' Install one with');
+
+/**
+ * The lead sentence for each way the WSL question can go unanswered.
+ *
+ * A table rather than four returns so the shared tail below is appended exactly
+ * once. That tail is the part that must never go missing — a fifth reason added
+ * to `detectWslProjectDir` would otherwise ship a refusal that neither rules out
+ * `C:\` nor names the override.
+ *
+ * Only `no-wsl` needs a per-stack word, and only in its last clause: what the
+ * operator does once a distro exists differs between a stack PortOS provisions
+ * for them and one they prepare by hand.
+ */
+const PLACEMENT_REFUSALS = Object.freeze({
+ 'internal-distro': (f, _detail, { sizeHint }) => `the default WSL distro is \`${f.distro}\`, which is a container engine's own plumbing — it is recreated from scratch on a reset, so ${sizeHint} of weights must not live there.${nameDistros(f.distros)} \`wsl --install -d Ubuntu\`.`,
+ 'unreadable-share': (f, detail) => `the \`${f.distro}\` distro answered, but Windows cannot read ${f.home} — the ${WSL_UNC_PREFIX} share is not responding${detail}. \`wsl --shutdown\` restarts it (that takes the whole VM down, so stop your containers first).`,
+ 'no-distro': (f, detail) => `WSL is present but no distro answered${detail}, so there is no Linux filesystem to put this project on.${nameDistros(f.distros)} \`wsl --install -d Ubuntu\`.`,
+ 'no-wsl': (_f, detail, { afterInstall }) => `this stack runs inside WSL2 — Docker Desktop's own engine IS a WSL2 VM — and \`wsl.exe\` did not run on this host${detail}. Install a distro with \`wsl --install -d Ubuntu\`, then ${afterInstall}.`,
+});
+
+/**
+ * Why PortOS could not find a Linux-side home for this project on a Windows
+ * host — prose the checklist renders verbatim, one fix per case.
+ *
+ * There is no case for "the operator did not configure a directory" any more.
+ * That was the old refusal, and it asked a person to look up two values
+ * (`<distro>`, `<user>`) that WSL will state on request. What survives is the
+ * set of answers PortOS genuinely cannot supply for itself: a machine with no
+ * WSL, a default distro that belongs to a container engine, and a share Windows
+ * cannot read.
+ *
+ * @param {{reason?: string, distro?: string, home?: string, error?: string, distros?: string[]}} found
+ * @param {{envVar: string, sizeHint: string, afterInstall: string}} stack
+ * @returns {string}
+ */
+function wslPlacementRefusal(found, stack) {
+ const lead = PLACEMENT_REFUSALS[found?.reason] || PLACEMENT_REFUSALS['no-wsl'];
+ const detail = found?.error ? ` (${found.error})` : '';
+ return `${lead(found || {}, detail, stack)} PortOS will not fall back to the Windows filesystem, where every one of those weight reads would cross a 9p share. To place the project somewhere of your own choosing instead, set ${stack.envVar} and click this again.`;
+}
+
+/**
+ * Settle where one stack's project goes before anything is written to it.
+ *
+ * Detection runs ONLY when nothing already answers the question — an exported
+ * env var or an earlier recording both win, and neither costs a subprocess. Off
+ * Windows there is nothing to detect: the default home is already on a Linux
+ * filesystem.
+ *
+ * @param {object} stack
+ * @param {string} stack.envVar - the operator override / record key, e.g. `VLLM_QWEN_PROJECT_DIR`
+ * @param {string} stack.leaf - the directory name inside the distro's home
+ * @param {string} stack.sizeHint - the payload named in the progress line, e.g. `~20 GB`
+ * @param {string} stack.afterInstall - completes "Install a distro with …, then ___."
+ * @param {() => boolean} stack.isSettled - does anything already answer this?
+ * @param {(dir: string) => Promise<unknown>} stack.record - persist the answer
+ * @param {(line: string) => void} [stack.emit]
+ * @returns {Promise<string|null>} the refusal, or `null` once the directory is
+ * settled — the same shape as each stack's `*StartBlockedReason`, and read
+ * back the same way, through that stack's own inspection.
+ */
+export async function ensureWslProjectDir({
+ envVar,
+ leaf,
+ sizeHint,
+ afterInstall,
+ isSettled,
+ record,
+ emit = () => {},
+}) {
+ if (process.platform !== 'win32') return null;
+ if (isSettled()) return null;
+
+ emit(`Windows host — asking WSL where this project belongs, so its ${sizeHint} of weights sit on the distro filesystem rather than on the Windows one.`);
+ const found = await detectWslProjectDir(leaf);
+ if (!found.dir) return wslPlacementRefusal(found, { envVar, sizeHint, afterInstall });
+
+ emit(`Using the \`${found.distro}\` distro, at ${found.dir}.`);
+ // This process FIRST, the file second. Every stack's resolver reads the env
+ // ahead of the record, so every later read in this run — the re-inspection
+ // that follows, the readiness poll, the Start button — resolves the detected
+ // directory even when the write fails. Without it, a failed write silently
+ // sends the very next inspection back to `%USERPROFILE%\<leaf>`: the C:\
+ // placement this whole path exists to refuse.
+ process.env[envVar] = found.dir;
+ // Recording is only what makes the choice outlive this run, so a failed write
+ // costs exactly that — not a multi-tens-of-gigabytes provision.
+ const recordedOk = await record(found.dir).then(() => true, (err) => {
+ emit(`Could not record ${envVar} in PortOS's .env (${err.message}) — this run still uses that directory, but set it there yourself or the next restart will look on the Windows filesystem again.`);
+ return false;
+ });
+ if (recordedOk) emit(`Recorded ${envVar} in PortOS's .env, so the readiness check and the Start button find it too.`);
+ return null;
+}