Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: keep incomplete Slotstream checkpoints unavailable until retry finishes (#7211)
[._.]/ Adam Eivy87b90beb6175
diff --git a/server/lib/README.md b/server/lib/README.mdindex e8efd646b5..f7c91b8111 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -229,7 +229,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `mtplxModels.js` | `services/localCachedModels.js` owns provider-refresh discovery and gates it on runtime readiness without loading the process manager. `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) `servableMtplxCachedModels(models)` → the rows MTPLX itself calls complete, and `pickMtplxCachedModel(models)` → the one 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. || `slotstreamCatalog.js` | `SLOTSTREAM_CATALOG` — the curated mixture-of-experts checkpoints worth streaming from SSD (the technique only pays off on MoE: a dense model of the same size would stream every layer for every token). `resolveSlotstreamRepo(idOrRepo)` maps a catalog id or an `owner/name` repo id to a repo (null for anything else), `slotstreamModelDirName(repo)` flattens it to the single-segment cache directory whose NAME is the id a start hands `--model`, and `selectSlotstreamRepoFiles(siblings)` picks the `.safetensors`/config/tokenizer files a checkpoint is made of while dropping mirrored `original/`, GGUF, ONNX, and PyTorch copies of the same weights (which can double a 100 GB+ pull) and any name that is not a plain relative path. |-| `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. |+| `slotstreamModels.js` | `isServableCheckpoint(dir)` checks configuration, weights and indexed shards; `SLOTSTREAM_INCOMPLETE_MARKER` keeps interrupted downloads unavailable until retry completes. `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. || `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. |diff --git a/server/lib/slotstreamModels.js b/server/lib/slotstreamModels.jsindex f771c363c2..5ecd50af21 100644--- a/server/lib/slotstreamModels.js+++ b/server/lib/slotstreamModels.js@@ -8,7 +8,7 @@* deliberately not the same as `[]` (read, and empty).*/-import { readdir, stat } from 'fs/promises';+import { readdir, readFile, stat } from 'fs/promises';import { homedir, totalmem } from 'os';import { join } from 'path';@@ -62,21 +62,37 @@ export function planSlotstreamMemory({ totalBytes, overrideGb } = {}) {};}-/**- * Whether a cache subdirectory holds something a start could actually serve.- *- * A `.partial` (or its `.etag` sidecar) means a download is running or was- * abandoned mid-file, so the directory is NOT a checkpoint yet — listing it- * would clear the card's empty-cache warning and offer `--model` a directory- * that exits before binding a port. A directory with no completed file at all- * is the same story. A hand-placed checkpoint never carries a `.partial`, so- * this cannot hide one.- */-async function isServableCheckpoint(dir) {+/** Persists across failed transfers, cancellation, restart, and partial-file GC. */+export const SLOTSTREAM_INCOMPLETE_MARKER = '.portos-download-incomplete';++/** Local structural admission, also used before a downloader clears its marker. */+export async function isServableCheckpoint(dir, { ignoreIncomplete = false } = {}) {const entries = await readdir(dir).catch(() => null);- if (!entries) return false;- const complete = entries.filter((name) => !name.endsWith('.partial') && !name.endsWith('.partial.etag'));- return complete.length > 0 && complete.length === entries.length;+ if (!entries || (!ignoreIncomplete && entries.includes(SLOTSTREAM_INCOMPLETE_MARKER))) return false;+ if (entries.some((name) => name.endsWith('.partial') || name.endsWith('.partial.etag'))) return false;+ const nonemptyFile = async (name) => {+ const info = await stat(join(dir, name)).catch(() => null);+ return Boolean(info?.isFile() && info.size > 0);+ };+ if (!(await nonemptyFile('config.json'))) return false;+ const weights = entries.filter((name) => name.endsWith('.safetensors'));+ const indexes = entries.filter((name) => name.endsWith('.safetensors.index.json'));+ if (!weights.length && !indexes.length) return false;+ for (const name of weights) if (!(await nonemptyFile(name))) return false;+ for (const name of indexes) {+ const index = await readFile(join(dir, name), 'utf8').then(JSON.parse).catch(() => null);+ const map = index?.weight_map;+ if (!map || typeof map !== 'object' || Array.isArray(map)) return false;+ const shards = Object.values(map);+ if (!shards.length) return false;+ for (const shard of new Set(shards)) {+ // Index values are data: only checkpoint-relative safetensors paths qualify.+ if (typeof shard !== 'string' || !shard.endsWith('.safetensors') ||+ /^[/\\]/.test(shard) || shard.split(/[/\\]/).some((part) => !part || part === '..' || part === '.') ||+ !(await nonemptyFile(shard))) return false;+ }+ }+ return true;}/**diff --git a/server/lib/slotstreamModels.test.js b/server/lib/slotstreamModels.test.jsindex 59907e27f7..d7277947c7 100644--- a/server/lib/slotstreamModels.test.js+++ b/server/lib/slotstreamModels.test.js@@ -50,12 +50,28 @@ describe('listSlotstreamCachedModels', () => {dir = join(tmpdir(), `portos-slotstream-cache-${Date.now()}`);await mkdir(join(dir, 'qwen-moe'), { recursive: true });await writeFile(join(dir, 'qwen-moe', 'model.safetensors'), 'weights');+ await writeFile(join(dir, 'qwen-moe', 'config.json'), '{}');await writeFile(join(dir, 'notes.txt'), 'not a checkpoint');const cache = await listSlotstreamCachedModels({ cacheDir: dir });expect(cache.error).toBeNull();expect(cache.models).toEqual([expect.objectContaining({ id: 'qwen-moe' })]);});+ it('requires all indexed shards while preserving manual checkpoints', async () => {+ dir = join(tmpdir(), `slotstream-index-${Date.now()}`);+ const model = join(dir, 'manual');+ await mkdir(model, { recursive: true });+ await writeFile(join(model, 'config.json'), '{}');+ expect((await listSlotstreamCachedModels({ cacheDir: dir })).models).toEqual([]);+ await writeFile(join(model, 'one.safetensors'), 'weights');+ await writeFile(join(model, 'model.safetensors.index.json'), JSON.stringify({ weight_map: { a: 'one.safetensors', b: 'two.safetensors' } }));+ expect((await listSlotstreamCachedModels({ cacheDir: dir })).models).toEqual([]);+ await writeFile(join(model, 'two.safetensors'), 'weights');+ expect((await listSlotstreamCachedModels({ cacheDir: dir })).models).toHaveLength(1);+ await writeFile(join(model, 'model.safetensors.index.json'), '{broken');+ expect((await listSlotstreamCachedModels({ cacheDir: dir })).models).toEqual([]);+ });+it('hides a directory a download has not finished filling', async () => {// Reporting one would clear the card's empty-cache warning and offer// `--model` a directory that exits before it binds a port.@@ -68,6 +84,7 @@ describe('listSlotstreamCachedModels', () => {await mkdir(join(dir, 'empty'), { recursive: true });await mkdir(join(dir, 'complete'), { recursive: true });await writeFile(join(dir, 'complete', 'model.safetensors'), 'weights');+ await writeFile(join(dir, 'complete', 'config.json'), '{}');const cache = await listSlotstreamCachedModels({ cacheDir: dir });expect(cache.error).toBeNull();diff --git a/server/services/slotstreamModelManager.js b/server/services/slotstreamModelManager.jsindex 1e5f6a0456..dddd8328aa 100644--- a/server/services/slotstreamModelManager.js+++ b/server/services/slotstreamModelManager.js@@ -19,7 +19,7 @@* so a completed download is servable with no restart.*/-import { rm, stat } from 'fs/promises';+import { mkdir, rm, stat, writeFile } from 'fs/promises';import { join, resolve, sep } from 'path';import { ServerError } from '../lib/errorHandler.js';import { withAbortTimeout } from '../lib/abortTimeout.js';@@ -40,7 +40,7 @@ import {slotstreamCatalogEntry,slotstreamModelDirName,} from '../lib/slotstreamCatalog.js';-import { slotstreamCacheDir } from '../lib/slotstreamModels.js';+import { isServableCheckpoint, SLOTSTREAM_INCOMPLETE_MARKER, slotstreamCacheDir } from '../lib/slotstreamModels.js';import { getHfToken } from './hfToken.js';export { SLOTSTREAM_CATALOG };@@ -215,7 +215,8 @@ export async function previewSlotstreamDownload({ model = null, cacheDir } = {})files: plan.files.length,// Finished files only — see planRepoDownload. This flag DISABLES Confirm,// so counting a `.partial` here would strand a resumable download.- alreadyDownloaded: plan.totalBytes > 0 && plan.finishedBytes === plan.totalBytes,+ alreadyDownloaded: plan.totalBytes > 0 && plan.finishedBytes === plan.totalBytes &&+ await isServableCheckpoint(plan.modelDir),};}@@ -254,6 +255,11 @@ export async function downloadSlotstreamModel({ model = null, cacheDir, onProgreexpectedBytes: Math.max(0, plan.totalBytes - carried),}));+ slot.throwIfAborted();+ await mkdir(plan.modelDir, { recursive: true });+ const marker = join(plan.modelDir, SLOTSTREAM_INCOMPLETE_MARKER);+ await writeFile(marker, 'Download incomplete; retry to finish.\n');+// Primitives, not a built frame: `onBytes` runs once per stream chunk, so// constructing the object and its message before the throttle would// allocate millions of frames per checkpoint to discard all but ~4 a second.@@ -278,6 +284,7 @@ export async function downloadSlotstreamModel({ model = null, cacheDir, onProgre// checkpoint rather than restarting at each file.let completedBytes = carried;for (const entry of plan.files) {+ slot.throwIfAborted();if (await isFinishedOnDisk(entry.destPath, entry.bytes)) continue;// Anything else at the destination is a dead mid-file write (or a file// whose size the Hub never reported, so completeness is unknowable) —@@ -302,9 +309,19 @@ export async function downloadSlotstreamModel({ model = null, cacheDir, onProgreemitProgress(done, entry.file);},});+ if (entry.bytes > 0 && bytes !== entry.bytes) {+ throw new Error(`Incomplete Slotstream file: ${entry.file} (${bytes}/${entry.bytes} bytes)`);+ }completedBytes += Math.max(0, bytes - resumedFrom);}+ slot.throwIfAborted();+ if (!(await isServableCheckpoint(plan.modelDir, { ignoreIncomplete: true }))) {+ throw new Error('Slotstream checkpoint is missing configuration or complete weights. Retry the download.');+ }+ slot.throwIfAborted();+ await rm(marker);+console.log(`✅ Slotstream checkpoint ready: ${repo} → ${plan.modelDir}`);onProgress({event: 'complete',diff --git a/server/services/slotstreamModelManager.test.js b/server/services/slotstreamModelManager.test.jsindex 965dadf750..194949e99a 100644--- a/server/services/slotstreamModelManager.test.js+++ b/server/services/slotstreamModelManager.test.js@@ -5,7 +5,7 @@ import { join } from 'path';vi.mock('./hfToken.js', () => ({ getHfToken: async () => null }));-const { listSlotstreamCachedModels } = await import('../lib/slotstreamModels.js');+const { listSlotstreamCachedModels, SLOTSTREAM_INCOMPLETE_MARKER } = await import('../lib/slotstreamModels.js');const {cancelSlotstreamModelDownload,downloadSlotstreamModel,@@ -185,6 +185,49 @@ describe('downloadSlotstreamModel', () => {expect(isSlotstreamDownloadInFlight(join(cacheDir, DIR_NAME))).toBe(false);});+ it('keeps failed checkpoints unavailable and retries without fetching completed files', async () => {+ installFetch({ 'config.json': CONFIG });+ expect((await downloadSlotstreamModel({ model: REPO, cacheDir })).success).toBe(false);+ expect((await listSlotstreamCachedModels({ cacheDir })).models).toEqual([]);+ expect(await readFile(join(cacheDir, DIR_NAME, 'config.json'), 'utf8')).toBe(CONFIG);+ installFetch();+ expect((await downloadSlotstreamModel({ model: REPO, cacheDir })).success).toBe(true);+ expect(fetched.some((url) => url.endsWith('/config.json'))).toBe(false);+ expect((await listSlotstreamCachedModels({ cacheDir })).models).toHaveLength(1);+ });++ it('allows retry when all files landed but completion was interrupted', async () => {+ const modelDir = join(cacheDir, DIR_NAME);+ await mkdir(modelDir, { recursive: true });+ for (const [name, body] of Object.entries(FILES)) await writeFile(join(modelDir, name), body);+ await writeFile(join(modelDir, SLOTSTREAM_INCOMPLETE_MARKER), 'interrupted');+ expect((await previewSlotstreamDownload({ model: REPO, cacheDir })).alreadyDownloaded).toBe(false);+ expect((await listSlotstreamCachedModels({ cacheDir })).models).toEqual([]);+ expect((await downloadSlotstreamModel({ model: REPO, cacheDir })).success).toBe(true);+ expect(fetched.every((url) => url.includes('/api/models/'))).toBe(true);+ expect((await listSlotstreamCachedModels({ cacheDir })).models).toHaveLength(1);+ });++ it.each(['write', 'remove'])('fails closed when marker %s fails', async (phase) => {+ const marker = join(cacheDir, DIR_NAME, SLOTSTREAM_INCOMPLETE_MARKER);+ if (phase === 'write') await mkdir(marker, { recursive: true });+ else {+ const realFetch = globalThis.fetch;+ vi.stubGlobal('fetch', vi.fn(async (url) => {+ if (String(url).endsWith('/model.safetensors')) {+ await rm(marker);+ await mkdir(marker);+ }+ return realFetch(url);+ }));+ }+ const frames = [];+ expect((await downloadSlotstreamModel({ model: REPO, cacheDir, onProgress: (f) => frames.push(f) })).success).toBe(false);+ expect(frames.at(-1).event).toBe('error');+ expect((await listSlotstreamCachedModels({ cacheDir })).models).toEqual([]);+ if (phase === 'write') expect(fetched.every((url) => url.includes('/api/models/'))).toBe(true);+ });+it.each(['headers', 'body'])('times out hanging metadata %s, emits an error, and releases the exclusive slot', async (phase) => {vi.useFakeTimers();vi.stubGlobal('fetch', vi.fn(async (_url, { signal }) => {@@ -344,6 +387,10 @@ describe('downloadSlotstreamModel', () => {// The bytes that landed are kept, so pressing download again resumes rather// than restarting a multi-gigabyte shard from zero.expect((await readFile(shardPartial, 'utf8')).length).toBeGreaterThan(0);+ await rm(shardPartial);+ await rm(`${shardPartial}.etag`, { force: true });+ expect((await listSlotstreamCachedModels({ cacheDir })).models).toEqual([]);+ expect(await readFile(join(cacheDir, DIR_NAME, SLOTSTREAM_INCOMPLETE_MARKER), 'utf8')).toBeTruthy();});it('reports no cancellation when nothing is downloading', () => {diff --git a/server/services/slotstreamServerManager.test.js b/server/services/slotstreamServerManager.test.jsindex c18efb3d2e..249e1f7872 100644--- a/server/services/slotstreamServerManager.test.js+++ b/server/services/slotstreamServerManager.test.js@@ -1,4 +1,4 @@-import { mkdtemp, rm } from 'fs/promises';+import { mkdir, mkdtemp, rm, writeFile } from 'fs/promises';import { tmpdir } from 'os';import { join } from 'path';import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';@@ -212,6 +212,21 @@ describe('slotstreamServerManager', () => {expect(execPm2Calls.some((args) => args[0] === 'start')).toBe(false);});+ it('refuses incomplete checkpoints using the real cache inventory', async () => {+ const cacheDir = join(testLogDir, 'cache');+ const modelDir = join(cacheDir, 'incomplete');+ await mkdir(modelDir, { recursive: true });+ await writeFile(join(modelDir, 'config.json'), '{}');+ slotstreamModels.listSlotstreamCachedModels.mockRestore();+ const readCache = slotstreamModels.listSlotstreamCachedModels;+ vi.spyOn(slotstreamModels, 'listSlotstreamCachedModels').mockImplementation(() => readCache({ cacheDir }));+ await expect(startSlotstreamServer({ model: 'incomplete' })).rejects.toThrow(/no model weights cached/i);+ await writeFile(join(modelDir, 'model.safetensors'), 'weights');+ await writeFile(join(modelDir, slotstreamModels.SLOTSTREAM_INCOMPLETE_MARKER), 'interrupted');+ await expect(startSlotstreamServer({ model: 'incomplete' })).rejects.toThrow(/no model weights cached/i);+ expect(execPm2Calls.some((args) => args[0] === 'start')).toBe(false);+ });+it('refuses an explicit checkpoint that is not cached, rather than letting the runtime fetch it', async () => {const err = await startSlotstreamServer({ model: 'not-on-disk' }).catch((e) => e);expect(err.message).toMatch(/never downloads weights/i);