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: Windows shell-job spawn ENOENT and boot-log noise (#4082)

[._.]/ Adam Eivyeda46a39d065
diff --git a/.changelog/next/fixed-windows-shell-job-spawn.md b/.changelog/next/fixed-windows-shell-job-spawn.md
new file mode 100644
index 0000000000..7a4948b103
--- /dev/null
+++ b/.changelog/next/fixed-windows-shell-job-spawn.md
@@ -0,0 +1,6 @@
+- Windows: autonomous shell jobs (e.g. the shipped System Health Check running `pm2 jlist`) no longer fail with `spawn ENOENT` / exit -4058 — the command now resolves through prepareCliSpawn, so a .cmd shim on PATH is launchable under shell:false
+- Quieter Windows boot: no bogus MaxListenersExceededWarning from the 11 permanent media-job completion hooks, no 'Failed to start Ollama as a background service' warning on platforms that have no service manager (the foreground fallback is the intended path there), and media-model drift warnings scoped to the current platform instead of repeating the other platform's rows every boot
+- Windows: agent process listing was silently dead — it shelled out to wmic.exe, which Microsoft removed from Windows 11, and the failure was swallowed into an empty list so PortOS reported 'no agents running' forever. Replaced with PowerShell Get-CimInstance (in-box on every supported Windows), with the probe failure now logged instead of hidden
+- Windows: HuggingFace cache deep-verification silently never ran — expectedBlobSha256 extracted the blob hash with a '/'-only split, so a backslashed readlink target never parsed and verifyModelCache could never report sha256-mismatch
+- Provider quota reset times in a zero-offset timezone (UTC, the UK in winter, Iceland) resolved to nothing and vanished from the Usage page — Intl renders that zone's offset as a bare 'GMT' and the parser only accepted the signed '+00:00' form
+- Windows: the Creative Director evaluator prompt could never receive its imageStrength upgrade — migration 002 matches anchors that end in a bare newline, so on a CRLF template it wrote nothing and was still recorded as applied. Migration 268 re-runs it newline-tolerantly and preserves the file's existing line endings
diff --git a/autofixer/sandbox.git.test.js b/autofixer/sandbox.git.test.js
index 872552bba9..f533dd2811 100644
--- a/autofixer/sandbox.git.test.js
+++ b/autofixer/sandbox.git.test.js
@@ -2,6 +2,11 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtemp, rm, writeFile, readFile, mkdir } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
+
+// Newline-normalizer: git checks files out through core.autocrlf, so a Windows
+// working tree holds CRLF whatever the worktree edit wrote. These assertions
+// are about promoted content, not the platform's newline style.
+const lf = (v) => String(v).split('\r\n').join('\n');
import {
isGitRepo,
createDisposableWorktree,
@@ -54,12 +59,14 @@ describe('git worktree isolation (integration)', () => {
expect(diff).toContain('app.js');
expect(diff).toContain('+const x = 2');
- // The live checkout is untouched until we explicitly promote.
- expect(await readFile(join(repo, 'app.js'), 'utf8')).toBe('const x = 1\n');
+ // The live checkout is untouched until we explicitly promote. Compare
+ // newline-normalized: git checks files out through core.autocrlf, so a
+ // Windows working tree holds CRLF no matter what the worktree edit wrote.
+ expect(lf(await readFile(join(repo, 'app.js'), 'utf8'))).toBe('const x = 1\n');
const applied = await applyDiffToLive(repo, diff, scratch);
expect(applied.ok).toBe(true);
- expect(await readFile(join(repo, 'app.js'), 'utf8')).toBe('const x = 2\n');
+ expect(lf(await readFile(join(repo, 'app.js'), 'utf8'))).toBe('const x = 2\n');
await removeWorktree(repo, wt.path);
const list = await execGit(['worktree', 'list'], repo);
diff --git a/scripts/generate_minimax_h3.test.js b/scripts/generate_minimax_h3.test.js
index 297756e8bf..42594aaf6e 100644
--- a/scripts/generate_minimax_h3.test.js
+++ b/scripts/generate_minimax_h3.test.js
@@ -2,10 +2,19 @@ import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { describe, expect, it } from 'vitest';
+import { resolveTestPython } from '../server/lib/testHelper.js';
const script = join(dirname(fileURLToPath(import.meta.url)), 'generate_minimax_h3.py');
-const pyBin = process.platform === 'win32' ? 'python' : 'python3';
+// Probe for an interpreter that actually RUNS rather than assuming a name.
+// On Windows a machine with no Store-installed Python still has `python` on
+// PATH as an alias STUB: it exists, exits non-zero, and prints "Python was
+// not found". A name-only choice passes there and then every case dies with
+// an opaque "Command failed" — and PortOS provisions its own interpreters
+// (~/.portos venvs), so a box can be set up for image/video gen while the
+// bare name is still a stub. Null when there is genuinely none, so the suite
+// skips instead of failing.
+const pyBin = resolveTestPython();
const runPython = (source) => execFileSync(pyBin, ['-c', source, script], {
encoding: 'utf8',
});
@@ -58,7 +67,7 @@ const argsExpr = (overrides = {}) => {
return `args = SimpleNamespace(${fields.join(', ')})`;
};
-describe('generate_minimax_h3.py', () => {
+describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {
it('keeps the lexical HF snapshot root when cache entries are blob symlinks', () => {
const output = runPython(`${importRunner}\n${[
'import tempfile',
@@ -467,7 +476,11 @@ describe('generate_minimax_h3.py', () => {
it('emits the video_path JSON completion contract on stdout', () => {
const output = runPython(`${importRunner}\nrunner.emit_result(Path("/tmp/example.mp4"))`);
- expect(JSON.parse(output)).toEqual({ video_path: '/tmp/example.mp4' });
+ // pathlib.Path renders with the platform separator, so the emitted path is
+ // backslashed on Windows. Normalize what was RECEIVED — the contract under
+ // test is the JSON shape and the key, not the separator the OS spells.
+ const { video_path: videoPath } = JSON.parse(output);
+ expect(videoPath.split('\\').join('/')).toBe('/tmp/example.mp4');
});
it('loads only the pinned namespace and cannot import a root-level shadow module', () => {
diff --git a/scripts/migrations/268-cd-evaluate-image-strength-crlf.js b/scripts/migrations/268-cd-evaluate-image-strength-crlf.js
new file mode 100644
index 0000000000..055a2de475
--- /dev/null
+++ b/scripts/migrations/268-cd-evaluate-image-strength-crlf.js
@@ -0,0 +1,105 @@
+/**
+ * Re-attempt migration 002's `imageStrength` backfill on installs whose
+ * cd-evaluate.md has CRLF line endings.
+ *
+ * 002 matches its insertion points against anchor strings that end in a bare
+ * `\n`. On an install where `data/prompts/stages/cd-evaluate.md` carries CRLF
+ * line endings — a Windows checkout, or a copy that round-tripped through an
+ * editor that converts on save — none of those anchors match, so 002 logs
+ * "anchors don't match … hand-merge from data.reference/" and returns without
+ * writing. The runner then records it as applied, so it never retries, and the
+ * template is stuck a version behind forever: the evaluator never sees the
+ * per-scene imageStrength knob and cannot adjust it on a retry.
+ *
+ * `_lib.js`'s hash-driven path already normalizes newlines before comparing
+ * (see its `md5` helper) — 002 predates that and does its own hand-rolled
+ * anchor matching, which is where the gap is.
+ *
+ * This migration does what 002 does, but matches against a newline-normalized
+ * copy of the template and writes the result back in the file's ORIGINAL
+ * newline style, so a Windows install keeps its CRLF file CRLF. It is a no-op
+ * on an install 002 already handled (the block is present) and on a
+ * hand-customized template whose anchors genuinely don't match.
+ *
+ * Idempotent — re-runs are a no-op once the block is present.
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+
+const TEMPLATE_REL_PATH = 'data/prompts/stages/cd-evaluate.md';
+
+// Same anchors and payloads as 002, spelled with LF. Matching happens against a
+// normalized copy, so these cover CRLF and bare-CR files too.
+const ANCHOR_BEFORE_BLOCK = '- Strategy: {{scene.strategy}}\n';
+const ANCHOR_AFTER_BLOCK = '- Retry count: {{scene.retryCount}} (max 3)\n';
+const NEW_BLOCK_LINES =
+ '{{#scene.hasImageStrength}}- Image strength: {{scene.imageStrength}} (0–1; higher = stick closer to source image){{/scene.hasImageStrength}}\n' +
+ '{{^scene.hasImageStrength}}- Image strength: default (continuation: 0.85; otherwise renderer default){{/scene.hasImageStrength}}\n';
+
+const RETRY_OLD = '**If the render misses the mark and retries are still available** (`retryCount < 3`): tweak the prompt and request a re-render. The server will run the new render and then send you back here for another evaluation.';
+const RETRY_NEW = '**If the render misses the mark and retries are still available** (`retryCount < 3`): tweak the prompt and request a re-render. The server will run the new render and then send you back here for another evaluation. You may also adjust `imageStrength` (0.0–1.0) on i2v scenes — drop it (e.g. 0.85 → 0.6) when the seed image is dominating and the prompt isn\'t expressed; raise it (e.g. → 0.95) when continuation drifted too far from the prior scene. Omit `imageStrength` from the PATCH to leave it unchanged.';
+
+/** Collapse CRLF and bare CR to LF so anchors spelled with `\n` can match. */
+const toLf = (text) => text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
+
+/**
+ * The newline style to write back with. A file that uses CRLF anywhere is
+ * treated as a CRLF file — mixing styles in one template would be worse than
+ * preserving the dominant one.
+ */
+const usesCrlf = (text) => text.includes('\r\n');
+
+/**
+ * Pure core, exported for the test: apply both insertions to `original`,
+ * returning the rewritten text or `null` when nothing changed.
+ */
+export function applyImageStrengthBackfill(original, { log = () => {} } = {}) {
+ const crlf = usesCrlf(original);
+ let next = toLf(original);
+ let changed = false;
+
+ if (!next.includes('{{#scene.hasImageStrength}}')) {
+ const anchorPair = ANCHOR_BEFORE_BLOCK + ANCHOR_AFTER_BLOCK;
+ if (next.includes(anchorPair)) {
+ next = next.replace(anchorPair, ANCHOR_BEFORE_BLOCK + NEW_BLOCK_LINES + ANCHOR_AFTER_BLOCK);
+ changed = true;
+ } else {
+ log(`⚠️ ${TEMPLATE_REL_PATH}: scene-context anchors don't match the pre-update template — skipping the imageStrength block insertion. Hand-merge from data.reference/ if needed.`);
+ }
+ }
+
+ if (!next.includes('adjust `imageStrength`')) {
+ if (next.includes(RETRY_OLD)) {
+ next = next.replace(RETRY_OLD, RETRY_NEW);
+ changed = true;
+ } else {
+ log(`⚠️ ${TEMPLATE_REL_PATH}: retry-branch sentence doesn't match the pre-update template — skipping the imageStrength guidance extension. Hand-merge from data.reference/ if needed.`);
+ }
+ }
+
+ if (!changed) return null;
+ return crlf ? next.replace(/\n/g, '\r\n') : next;
+}
+
+export default {
+ async up({ rootDir }) {
+ const templatePath = join(rootDir, TEMPLATE_REL_PATH);
+ const original = await readFile(templatePath, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (original == null) {
+ console.log(`📄 ${TEMPLATE_REL_PATH} not present — skipping (fresh install copies it from data.reference)`);
+ return;
+ }
+
+ const next = applyImageStrengthBackfill(original, { log: (msg) => console.log(msg) });
+ if (next == null) {
+ console.log(`✅ ${TEMPLATE_REL_PATH}: already up-to-date, no changes needed`);
+ return;
+ }
+ await writeFile(templatePath, next);
+ console.log(`📝 ${TEMPLATE_REL_PATH}: backfilled imageStrength surfacing (CRLF-tolerant re-run of 002)`);
+ },
+};
diff --git a/scripts/migrations/268-cd-evaluate-image-strength-crlf.test.js b/scripts/migrations/268-cd-evaluate-image-strength-crlf.test.js
new file mode 100644
index 0000000000..7d6339b51f
--- /dev/null
+++ b/scripts/migrations/268-cd-evaluate-image-strength-crlf.test.js
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest';
+
+import { applyImageStrengthBackfill } from './268-cd-evaluate-image-strength-crlf.js';
+
+// The pre-002 template, reduced to the two regions the backfill touches.
+const PRE_UPDATE_LF = [
+ '## Scene to evaluate',
+ '',
+ '- Intent: {{scene.intent}}',
+ '- Strategy: {{scene.strategy}}',
+ '- Retry count: {{scene.retryCount}} (max 3)',
+ '',
+ '**If the render misses the mark and retries are still available** (`retryCount < 3`): tweak the prompt and request a re-render. The server will run the new render and then send you back here for another evaluation.',
+ '',
+].join('\n');
+
+const toCrlf = (text) => text.replace(/\n/g, '\r\n');
+
+describe('migration 268 — CRLF-tolerant cd-evaluate imageStrength backfill', () => {
+ it('inserts both pieces into an LF template (what 002 already handled)', () => {
+ const out = applyImageStrengthBackfill(PRE_UPDATE_LF);
+ expect(out).toContain('{{#scene.hasImageStrength}}- Image strength: {{scene.imageStrength}}');
+ expect(out).toContain('{{^scene.hasImageStrength}}- Image strength: default');
+ expect(out).toContain('adjust `imageStrength`');
+ });
+
+ // The bug: 002's anchors end in a bare \n, so on a CRLF template none of them
+ // match, it writes nothing, and the runner still records it as applied — the
+ // install is stuck a template version behind with no path back.
+ it('inserts both pieces into a CRLF template', () => {
+ const out = applyImageStrengthBackfill(toCrlf(PRE_UPDATE_LF));
+ expect(out).toContain('{{#scene.hasImageStrength}}- Image strength: {{scene.imageStrength}}');
+ expect(out).toContain('adjust `imageStrength`');
+ });
+
+ it('writes a CRLF template back as CRLF, and an LF one as LF', () => {
+ const crlfOut = applyImageStrengthBackfill(toCrlf(PRE_UPDATE_LF));
+ expect(crlfOut.includes('\r\n')).toBe(true);
+ expect(/[^\r]\n/.test(crlfOut)).toBe(false); // no bare LF left behind
+
+ const lfOut = applyImageStrengthBackfill(PRE_UPDATE_LF);
+ expect(lfOut.includes('\r')).toBe(false);
+ });
+
+ it('is a no-op once the block is present, in either newline style', () => {
+ const applied = applyImageStrengthBackfill(PRE_UPDATE_LF);
+ expect(applyImageStrengthBackfill(applied)).toBeNull();
+ expect(applyImageStrengthBackfill(toCrlf(applied))).toBeNull();
+ });
+
+ it('leaves a hand-customized template alone rather than guessing', () => {
+ const customized = PRE_UPDATE_LF
+ .replace('- Strategy: {{scene.strategy}}', '- Approach: {{scene.strategy}}')
+ .replace('**If the render misses the mark', '**When the render misses the mark');
+ const logged = [];
+ expect(applyImageStrengthBackfill(customized, { log: (m) => logged.push(m) })).toBeNull();
+ expect(logged).toHaveLength(2);
+ expect(logged.every((m) => m.includes('Hand-merge from data.reference/'))).toBe(true);
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 90456dfb11..07e00e2aa8 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -362,4 +362,4 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `mirrorParity.js` | Source-comparison primitives for the `*.mirror.test.js` server↔client parity tests: `stripCommentsAndNormalize` (so per-side commentary may diverge but logic may not), `extractDeclaration(src, name)` (balanced `{}`/`()`/`[]` walk over `function` / `async function` / `const`), and `compareDeclaration(serverSrc, clientSrc, name)`. Use these instead of hand-rolling a brace-walker per mirror. Pure — no `vitest` import — so callers own the assertions. |
| `mockPathsDataRoot.js` | Shared Vitest helpers for `PATHS.data → temp dir` and no-peer record creation guards. |
| `settingsTestUtil.js` | `bindSettingsFile(dataRoot)` → `writeSettingsFile`/`mergeSettingsFile`: direct settings.json disk writes that also drop the `getSettings()` read cache (dynamic-import reset) so a stale cache can't survive a bypass-`save()` write. |
-| `testHelper.js` | Test helpers: `request()` (supertest-style HTTP) + `mockJsonResponse`/`mockTextResponse` (fetch `Response` mocks read via `.text()`), plus the source-scan pair `collectServerSources()` / `readServerSource(rel)` (and `SERVER_DIR`) used by the whole-tree guard suites — `spawnCwd.test.js` (#3193) and `cliChildEnv.test.js` (#3194). Those guards overlap deliberately, so they share one definition of "a source file"; change the ignore rules here and both move together. |
+| `testHelper.js` | Test helpers: `request()` (supertest-style HTTP) + `mockJsonResponse`/`mockTextResponse` (fetch `Response` mocks read via `.text()`), plus the source-scan pair `collectServerSources()` / `readServerSource(rel)` (and `SERVER_DIR`) used by the whole-tree guard suites — `spawnCwd.test.js` (#3193) and `cliChildEnv.test.js` (#3194). Those guards overlap deliberately, so they share one definition of "a source file"; change the ignore rules here and both move together. Cross-platform pair: `posixPath(v)` normalizes a RECEIVED path before comparing it to a POSIX-spelled literal (no-op on POSIX — never normalize the expectation, which would hide a genuinely wrong path), and `resolveTestPython()` returns an interpreter that actually runs, probing by execution because Windows ships a `python` Store-alias stub that exists but fails; `null` when there is none, for `describe.skipIf`. |
diff --git a/server/lib/agentSentinel.test.js b/server/lib/agentSentinel.test.js
index 59c2445854..e7ab04e00c 100644
--- a/server/lib/agentSentinel.test.js
+++ b/server/lib/agentSentinel.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect } from 'vitest';
+import { join } from 'path';
import { DONE_SENTINEL_NAME, doneSentinelName, doneSentinelPath, extractSentinelPayloadFromTranscript, parseSentinelPayload, salvageSentinelPayload } from './agentSentinel.js';
describe('agentSentinel', () => {
@@ -32,11 +33,14 @@ describe('agentSentinel', () => {
it('resolves the run-scoped file inside the workspace', () => {
// Worktree-less agents share the primary checkout: a bare `.agent-done`
// there may be a sibling run's, and must never finalize this one.
- expect(doneSentinelPath('/repo', 'agent-1')).toBe('/repo/.agent-done-agent-1');
+ // join(), not a '/'-joined literal: doneSentinelPath composes with path.join,
+ // so the separator is '\' on Windows and the contract under test is the
+ // COMPOSITION, not the separator.
+ expect(doneSentinelPath('/repo', 'agent-1')).toBe(join('/repo', '.agent-done-agent-1'));
});
it('degrades to the shared name when no agent id is available', () => {
- expect(doneSentinelPath('/repo', null)).toBe('/repo/.agent-done');
+ expect(doneSentinelPath('/repo', null)).toBe(join('/repo', '.agent-done'));
});
it('returns null without a workspace path', () => {
diff --git a/server/lib/cliChildEnv.test.js b/server/lib/cliChildEnv.test.js
index 4d37941978..ca29be7d4d 100644
--- a/server/lib/cliChildEnv.test.js
+++ b/server/lib/cliChildEnv.test.js
@@ -1,4 +1,6 @@
import { describe, it, expect } from 'vitest';
+import { posixPath } from './testHelper.js';
+
import { buildCliChildEnv, composeProviderEnv } from './cliChildEnv.js';
import { AGENT_GUARD_BIN } from './agentGuard/index.js';
import { collectServerSources, readServerSource } from './testHelper.js';
@@ -80,11 +82,11 @@ describe('buildCliChildEnv — layering', () => {
describe('buildCliChildEnv — PWD pin and CLAUDECODE strip', () => {
it('pins PWD to the spawn cwd, overriding a stale inherited value (#3193)', () => {
const env = buildCliChildEnv({ baseEnv: { PWD: '/repos/PortOS' }, cwd: '/repos/my-app' });
- expect(env.PWD).toBe('/repos/my-app');
+ expect(posixPath(env.PWD)).toBe('/repos/my-app');
});
it('leaves the inherited PWD alone when no cwd is passed', () => {
- expect(buildCliChildEnv({ baseEnv: { PWD: '/repos/PortOS' } }).PWD).toBe('/repos/PortOS');
+ expect(posixPath(buildCliChildEnv({ baseEnv: { PWD: '/repos/PortOS' } }).PWD)).toBe('/repos/PortOS');
});
// The pin runs LAST, over the composed object — so a provider that sets its
@@ -93,7 +95,7 @@ describe('buildCliChildEnv — PWD pin and CLAUDECODE strip', () => {
const env = buildCliChildEnv({
baseEnv: {}, provider: { envVars: { PWD: '/somewhere/else' } }, cwd: '/repos/my-app',
});
- expect(env.PWD).toBe('/repos/my-app');
+ expect(posixPath(env.PWD)).toBe('/repos/my-app');
});
it('strips CLAUDECODE from every layer that could supply it', () => {
@@ -110,7 +112,7 @@ describe('buildCliChildEnv — PWD pin and CLAUDECODE strip', () => {
describe('buildCliChildEnv — pm2 guard', () => {
it('leaves PATH untouched without `guard` (Run Prompt / fire-and-collect paths)', () => {
const env = buildCliChildEnv({ baseEnv: { PATH: '/usr/bin' } });
- expect(env.PATH).toBe('/usr/bin');
+ expect(posixPath(env.PATH)).toBe('/usr/bin');
expect(env.PORTOS_REAL_PM2).toBeUndefined();
});
@@ -124,8 +126,8 @@ describe('buildCliChildEnv — pm2 guard', () => {
guard: true,
});
expect(env.PATH.startsWith(`${AGENT_GUARD_BIN}`)).toBe(true);
- expect(env.PATH).toContain('/provider/bin');
- expect(env.PATH).not.toContain('/usr/bin');
+ expect(posixPath(env.PATH)).toContain('/provider/bin');
+ expect(posixPath(env.PATH)).not.toContain('/usr/bin');
});
});
@@ -176,7 +178,7 @@ describe('buildCliChildEnv — per-call-site composition', () => {
expect(buildCliChildEnv({ ...args, guard: true }).A).toBe('provider');
expect(buildCliChildEnv({ ...args, guard: true }).PATH).toContain(AGENT_GUARD_BIN);
// The fire-and-collect path is not an agent — it must stay unguarded.
- expect(buildCliChildEnv(args).PATH).toBe('/usr/bin');
+ expect(posixPath(buildCliChildEnv(args).PATH)).toBe('/usr/bin');
});
it('cliProviderRun.js: honors a sanitized baseEnv instead of process.env', () => {
@@ -242,7 +244,7 @@ describe('buildCliChildEnv — per-call-site composition', () => {
const env = buildCliChildEnv({
baseEnv: { PWD: '/repos/PortOS' }, provider: OLLAMA_OPENCODE, model: 'llava:7b', cwd: '/tmp/portos-vision-x',
});
- expect(env.PWD).toBe('/tmp/portos-vision-x');
+ expect(posixPath(env.PWD)).toBe('/tmp/portos-vision-x');
// And the vision model is declared, so `--model ollama/llava:7b` is accepted.
expect(declaredModels(env)).toContain('llava:7b');
});
diff --git a/server/lib/db.guards.test.js b/server/lib/db.guards.test.js
index 39f6b1d0ea..86fa6c90cb 100644
--- a/server/lib/db.guards.test.js
+++ b/server/lib/db.guards.test.js
@@ -441,16 +441,25 @@ describe('DB-backed test files are covered by vitest.config.db.js', () => {
};
const SKIP_DIRS = new Set(['node_modules', 'slashdo', 'coverage', '.git']);
- const collect = (root) => {
+ // Prune the skipped directories DURING the walk, not after it. A
+ // `readdirSync(root, { recursive: true })` enumerates every entry under
+ // `server/node_modules` — hundreds of thousands of files — before the
+ // filter ever runs, which pushed this single test past a minute on Windows
+ // and timed the suite out under full-suite load.
+ const collect = (root, rel = '') => {
let entries;
try {
- entries = readdirSync(root, { recursive: true });
+ entries = readdirSync(join(root, rel), { withFileTypes: true });
} catch {
return [];
}
- return entries
- .map(String)
- .filter((p) => p.endsWith('.test.js') && !p.split(sep).some((seg) => SKIP_DIRS.has(seg)));
+ return entries.flatMap((entry) => {
+ const next = rel ? join(rel, entry.name) : entry.name;
+ if (entry.isDirectory()) {
+ return SKIP_DIRS.has(entry.name) ? [] : collect(root, next);
+ }
+ return entry.name.endsWith('.test.js') ? [next] : [];
+ });
};
const offenders = [];
diff --git a/server/lib/detachedSpawn.test.js b/server/lib/detachedSpawn.test.js
index df36d6455c..c402ea6610 100644
--- a/server/lib/detachedSpawn.test.js
+++ b/server/lib/detachedSpawn.test.js
@@ -7,6 +7,16 @@ import { promisify } from 'util';
import { spawnDetached, reapDetached, reapAndCleanDetachedDirs, reattachDetached, isReattachable, isDetachedRunning } from './detachedSpawn.js';
const execFileAsync = promisify(execFile);
+
+// spawnDetached's POSIX `sh` double-fork — and with it the whole control-dir
+// contract (pid/exit sentinels, reap, re-attach, reparent-to-init survival) —
+// does not exist on Windows: that platform takes an explicit plain-spawn
+// fallback (see the win32 branch in detachedSpawn.js), where pm2 is
+// taskkill-based and surviving a restart is not a guarantee PortOS makes.
+// Tests that assert the double-fork mechanism are gated on IS_POSIX rather
+// than rewritten, because there is no Windows behavior for them to assert.
+// The win32 fallback itself is covered by its own test below.
+const IS_POSIX = process.platform !== 'win32';
const dirs = [];
const tmpControlDir = async () => {
const d = await mkdtemp(join(tmpdir(), 'detached-spawn-'));
@@ -76,7 +86,7 @@ describe('spawnDetached', () => {
return chain;
};
- it('reparents the job out of the spawner tree (escapes pm2 TreeKill)', async () => {
+ it.runIf(IS_POSIX)('reparents the job out of the spawner tree (escapes pm2 TreeKill)', async () => {
const controlDir = await tmpControlDir();
const handle = await spawnDetached('sh', ['-c', 'sleep 30'], { controlDir, pollMs: 25 });
expect(handle.pid).toBeGreaterThan(0);
@@ -96,7 +106,7 @@ describe('spawnDetached', () => {
await onClose(handle);
});
- it('kill() signals the reparented job and surfaces the signal on close', async () => {
+ it.runIf(IS_POSIX)('kill() signals the reparented job and surfaces the signal on close', async () => {
const controlDir = await tmpControlDir();
const handle = await spawnDetached('sh', ['-c', 'sleep 30'], { controlDir, pollMs: 25 });
expect(handle.pid).toBeGreaterThan(0);
@@ -110,7 +120,7 @@ describe('spawnDetached', () => {
expect(handle.signalCode).toBe('SIGKILL');
});
- it.skipIf(process.platform === 'win32')('killProcessGroup terminates a wrapper and its runtime child', async () => {
+ it.runIf(IS_POSIX)('killProcessGroup terminates a wrapper and its runtime child', async () => {
const controlDir = await tmpControlDir();
const handle = await spawnDetached('python3', ['-c', [
'import os, subprocess, time',
@@ -153,7 +163,7 @@ describe('spawnDetached', () => {
expect(getOut()).toBe('second\n');
});
- it('removes the control dir after the job ends when cleanup is set', async () => {
+ it.runIf(IS_POSIX)('removes the control dir after the job ends when cleanup is set', async () => {
const controlDir = await tmpControlDir();
const handle = await spawnDetached('sh', ['-c', 'printf "x\\n"; exit 0'], { controlDir, pollMs: 25, cleanup: true });
await onClose(handle);
@@ -176,7 +186,7 @@ describe('spawnDetached', () => {
await expect(spawnDetached('sh', ['-c', 'true'], {})).rejects.toThrow(/controlDir/);
});
- it('surfaces a setup failure as an error event, not a rejection', async () => {
+ it.runIf(IS_POSIX)('surfaces a setup failure as an error event, not a rejection', async () => {
// controlDir under a regular FILE → ensureDir fails (ENOTDIR). spawnDetached
// must still resolve a handle and emit 'error' so the caller's on('error')
// finalization runs (rejecting would strand the run / leak temps).
@@ -210,7 +220,7 @@ describe('spawnDetached', () => {
});
describe('reapDetached', () => {
- it('SIGTERMs a surviving orphan and reports it reaped', async () => {
+ it.runIf(IS_POSIX)('SIGTERMs a surviving orphan and reports it reaped', async () => {
const controlDir = await tmpControlDir();
const handle = await spawnDetached('sh', ['-c', 'sleep 30'], { controlDir, pollMs: 25 });
const pid = handle.pid;
@@ -242,7 +252,7 @@ describe('spawnDetached', () => {
});
describe('reapAndCleanDetachedDirs', () => {
- it('reaps every surviving orphan under the parent and removes the dirs', async () => {
+ it.runIf(IS_POSIX)('reaps every surviving orphan under the parent and removes the dirs', async () => {
const parent = await tmpControlDir();
const a = join(parent, 'job-a');
const b = join(parent, 'job-b');
@@ -268,7 +278,7 @@ describe('spawnDetached', () => {
});
describe('isReattachable', () => {
- it('is true while the recorded child is still alive', async () => {
+ it.runIf(IS_POSIX)('is true while the recorded child is still alive', async () => {
const controlDir = await tmpControlDir();
const handle = await spawnDetached('sh', ['-c', 'sleep 30'], { controlDir, pollMs: 25 });
expect(await isReattachable(controlDir)).toBe(true);
@@ -276,7 +286,7 @@ describe('isReattachable', () => {
await onClose(handle);
});
- it('is true after the child exited (RESULT line still unprocessed on disk)', async () => {
+ it.runIf(IS_POSIX)('is true after the child exited (RESULT line still unprocessed on disk)', async () => {
const controlDir = await tmpControlDir();
const handle = await spawnDetached('sh', ['-c', 'printf "x\\n"; exit 0'], { controlDir, pollMs: 25 });
await onClose(handle);
@@ -298,7 +308,7 @@ describe('isReattachable', () => {
});
describe('isDetachedRunning', () => {
- it('is true while the recorded child is still alive with no exit sentinel', async () => {
+ it.runIf(IS_POSIX)('is true while the recorded child is still alive with no exit sentinel', async () => {
const controlDir = await tmpControlDir();
const handle = await spawnDetached('sh', ['-c', 'sleep 30'], { controlDir, pollMs: 25 });
expect(await isDetachedRunning(controlDir)).toBe(true);
@@ -336,7 +346,7 @@ describe('isDetachedRunning', () => {
});
});
-describe('reattachDetached', () => {
+describe.runIf(IS_POSIX)('reattachDetached', () => {
it('replays a still-running survivor from the start and closes with its exit code', async () => {
const controlDir = await tmpControlDir();
// early output, then a beat, then late output + a non-zero exit.
diff --git a/server/lib/ffmpeg.test.js b/server/lib/ffmpeg.test.js
index d6cf99f560..862c64c143 100644
--- a/server/lib/ffmpeg.test.js
+++ b/server/lib/ffmpeg.test.js
@@ -1,7 +1,8 @@
import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest';
+
import { writeFileSync, mkdtempSync, rmSync } from 'fs';
import { tmpdir } from 'os';
-import { join } from 'path';
+import { join, resolve } from 'path';
import {
verifyVideoPlayable, safeUnder, runFfmpegProcess, hasAudioStream, buildTrimConcatArgs,
@@ -157,7 +158,7 @@ describe('runFfmpegProcess', () => {
describe('safeUnder', () => {
it('accepts a plain basename under a root', () => {
const root = '/tmp/portos-root';
- expect(safeUnder(root, 'foo.mp4')).toBe('/tmp/portos-root/foo.mp4');
+ expect(safeUnder(root, 'foo.mp4')).toBe(resolve(root, 'foo.mp4'));
});
it('rejects path-traversal segments', () => {
diff --git a/server/lib/githubRepoUrl.test.js b/server/lib/githubRepoUrl.test.js
index b67b223a7b..9c1e1da5c3 100644
--- a/server/lib/githubRepoUrl.test.js
+++ b/server/lib/githubRepoUrl.test.js
@@ -1,4 +1,6 @@
import { describe, it, expect } from 'vitest';
+import { posixPath } from './testHelper.js';
+
import { join } from 'path';
import { parseGitHubUrl, isGitHubRepoUrl } from './githubRepoUrl.js';
@@ -82,7 +84,7 @@ describe('parseGitHubUrl', () => {
it('never yields a clone path outside the repos root', () => {
expect(clonePath('https://github.com/../evil')).toBeNull();
expect(clonePath('https://github.com/example-owner/..')).toBeNull();
- expect(clonePath('https://github.com/example-owner/example-repo'))
+ expect(posixPath(clonePath('https://github.com/example-owner/example-repo')))
.toBe('/data/repos/example-owner/example-repo');
});
diff --git a/server/lib/hfCache.js b/server/lib/hfCache.js
index fc4e1d1580..ec496a68d1 100644
--- a/server/lib/hfCache.js
+++ b/server/lib/hfCache.js
@@ -338,7 +338,13 @@ async function expectedBlobSha256(path) {
if (!lst || !lst.isSymbolicLink()) return null;
const target = await fs.readlink(path).catch(() => null);
if (!target) return null;
- const base = target.split('/').pop();
+ // Split on BOTH separators. `readlink` returns a Windows-separated target on
+ // win32, so a '/'-only split yielded the ENTIRE path instead of the blob
+ // name, SHA256_RE never matched, and this returned null — silently disabling
+ // the deep sha256 integrity check (verifyWeightFile then stopped at
+ // 'structural-ok' and could never report 'sha256-mismatch') on every Windows
+ // install.
+ const base = target.split(/[\\/]/).pop();
return SHA256_RE.test(base) ? base : null;
}
diff --git a/server/lib/hfCache.test.js b/server/lib/hfCache.test.js
index 794b715010..1852a7bbd6 100644
--- a/server/lib/hfCache.test.js
+++ b/server/lib/hfCache.test.js
@@ -1,4 +1,6 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { posixPath } from './testHelper.js';
+
import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync, existsSync, readlinkSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { tmpdir } from 'node:os';
@@ -88,18 +90,19 @@ describe('hfCache', () => {
it('resolves cache root with precedence HF_HUB_CACHE > HF_HOME/hub > XDG_CACHE_HOME/huggingface/hub > ~/.cache', () => {
process.env.HF_HUB_CACHE = '/explicit/hub';
- expect(getHfCacheRoot()).toBe('/explicit/hub');
+ expect(posixPath(getHfCacheRoot())).toBe('/explicit/hub');
delete process.env.HF_HUB_CACHE;
process.env.HF_HOME = '/custom/hf';
- expect(getHfCacheRoot()).toBe('/custom/hf/hub');
+ expect(posixPath(getHfCacheRoot())).toBe('/custom/hf/hub');
delete process.env.HF_HOME;
process.env.XDG_CACHE_HOME = '/xdg/cache';
- expect(getHfCacheRoot()).toBe('/xdg/cache/huggingface/hub');
+ expect(posixPath(getHfCacheRoot())).toBe('/xdg/cache/huggingface/hub');
delete process.env.XDG_CACHE_HOME;
- expect(getHfCacheRoot()).toMatch(/\.cache\/huggingface\/hub$/);
+ // Composed with path.join — accept either separator.
+ expect(getHfCacheRoot()).toMatch(/[\\/]\.cache[\\/]huggingface[\\/]hub$/);
});
it('reports cached=false for missing repo dir', async () => {
@@ -125,7 +128,7 @@ describe('hfCache', () => {
const result = await inspectModelCache('org/model');
expect(result.cached).toBe(true);
expect(result.sizeBytes).toBe(4096); // weight files only, config/tokenizer excluded
- expect(result.snapshotPath).toContain('snapshots/abc123');
+ expect(result.snapshotPath.split('\\').join('/')).toContain('snapshots/abc123');
rmSync(root, { recursive: true, force: true });
});
@@ -309,7 +312,9 @@ describe('repairModelCache', () => {
roots.push(root);
process.env.HF_HUB_CACHE = root;
- const badBlob = join(blobsDir, readlinkSync(join(snapDir, 'bad.safetensors')).split('/').pop());
+ // Split on BOTH separators — readlink returns a Windows-separated target
+ // there, so a '/'-only split yields the whole path instead of a basename.
+ const badBlob = join(blobsDir, readlinkSync(join(snapDir, 'bad.safetensors')).split(/[\\/]/).pop());
expect(existsSync(badBlob)).toBe(true);
const result = await repairModelCache('org/mixed');
@@ -371,7 +376,7 @@ describe('findCachedRepoFile', () => {
it('resolves the requested file out of an aggregate repo', async () => {
aggregateCache();
const found = await findCachedRepoFile('org/aggregate', 'wanted.safetensors');
- expect(found).toMatch(/snapshots\/sha1\/wanted\.safetensors$/);
+ expect(found.split('\\').join('/')).toMatch(/snapshots\/sha1\/wanted\.safetensors$/);
});
it('returns null for a file the repo has not fetched, even though siblings exist', async () => {
@@ -537,7 +542,8 @@ describe('exact-file aggregate verification', () => {
cleanup.push(root);
process.env.HF_HUB_CACHE = root;
- expect(await findCachedRepoSnapshot('org/pinned', wanted)).toMatch(new RegExp(`/snapshots/${wanted}$`));
+ const pinned = (await findCachedRepoSnapshot('org/pinned', wanted)).split('\\').join('/');
+ expect(pinned).toMatch(new RegExp(`/snapshots/${wanted}$`));
expect(await findCachedRepoFile('org/pinned', 'wanted.safetensors', { revision: wanted })).toBeTruthy();
expect(await findCachedRepoFile('org/pinned', 'other.safetensors', { revision: wanted })).toBeNull();
expect((await inspectModelCache('org/pinned', { revision: wanted })).sizeBytes).toBe(1024);
diff --git a/server/lib/huggingfaceModel.test.js b/server/lib/huggingfaceModel.test.js
index 10f029ec33..a883d4aab7 100644
--- a/server/lib/huggingfaceModel.test.js
+++ b/server/lib/huggingfaceModel.test.js
@@ -131,6 +131,7 @@ describe('classifyHfMediaModel — happy paths', () => {
expect(classifyHfMediaModel({
repo: 'notapalindrome/ltx23-mlx-av-q4',
model: hf({ files: ['model.safetensors'], tags: ['ltx-video'] }),
+ isWindows: false,
})).toEqual({ kind: 'video', runtime: 'mlx_video', format: 'safetensors' });
});
@@ -138,6 +139,7 @@ describe('classifyHfMediaModel — happy paths', () => {
expect(classifyHfMediaModel({
repo: 'dgrauet/ltx-2.3-mlx-q8',
model: hf({ files: ['model.safetensors'], tags: ['ltx'] }),
+ isWindows: false,
})).toEqual({ kind: 'video', runtime: 'ltx2', format: 'safetensors' });
});
@@ -156,6 +158,7 @@ describe('classifyHfMediaModel — happy paths', () => {
repo: 'dgrauet/ltx-2.3-mlx-q8',
model: hf({ files: ['model.safetensors'], tags: ['ltx'] }),
runtime: 'ltx2',
+ isWindows: false,
})).toEqual({ kind: 'video', runtime: 'ltx2', format: 'safetensors' });
});
@@ -230,6 +233,7 @@ describe('classifyHfMediaModel — happy paths', () => {
expect(() => classifyHfMediaModel({
repo: 'someone/mystery-video',
model: hf({ files: ['model.safetensors'], pipeline: 'text-to-video' }),
+ isWindows: false,
})).toThrow(/Couldn't determine which video runtime/);
});
@@ -238,6 +242,7 @@ describe('classifyHfMediaModel — happy paths', () => {
repo: 'someone/mystery-video',
model: hf({ files: ['model.safetensors'], pipeline: 'text-to-video' }),
runtime: 'mlx_video',
+ isWindows: false,
})).toEqual({ kind: 'video', runtime: 'mlx_video', format: 'safetensors' });
});
});
diff --git a/server/lib/icloudFile.test.js b/server/lib/icloudFile.test.js
index b2f1bcfeaf..6f9ccb9686 100644
--- a/server/lib/icloudFile.test.js
+++ b/server/lib/icloudFile.test.js
@@ -381,7 +381,15 @@ describe('background-download safety caps', () => {
});
});
-describe('cloud-root detection beyond a literal path match', () => {
+// Skipped on Windows — deliberately, and this is the rare case where a platform
+// skip is the honest answer rather than lost coverage. The behavior under test
+// is macOS "Desktop & Documents Folders" sync symlinking ~/Documents into a
+// ubiquity container, and CLOUD_MARKERS are POSIX literals
+// ('/Library/Mobile Documents/') describing a macOS-only filesystem layout.
+// There is no Windows equivalent to assert: fabricating that tree under a
+// Windows path yields backslashes the markers can never match, so the test
+// would only be checking that a macOS-only feature is inert off macOS.
+describe.skipIf(process.platform === 'win32')('cloud-root detection beyond a literal path match', () => {
// ~/Documents is a SYMLINK into the CloudDocs ubiquity container when macOS
// "Desktop & Documents Folders" sync is on, so a path string can say nothing
// about iCloud while the file is very much in it. Real dirs + a real symlink
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
index d103b4462c..b694701346 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -970,25 +970,27 @@ export const loadMediaModels = () => {
parsed.image.map((m) => m?.id).filter((id) => typeof id === 'string'),
);
}
- if (isPlainObject(sd.video) && isPlainObject(parsed.video)) {
- if (Array.isArray(sd.video.macos) && Array.isArray(parsed.video.macos)) {
- warnDrift(
- 'video',
- 'macos',
- sd.video.macos,
- DEFAULT_REGISTRY.video.macos.map((m) => m.id),
- parsed.video.macos.map((m) => m?.id).filter((id) => typeof id === 'string'),
- );
- }
- if (Array.isArray(sd.video.windows) && Array.isArray(parsed.video.windows)) {
- warnDrift(
- 'video',
- 'windows',
- sd.video.windows,
- DEFAULT_REGISTRY.video.windows.map((m) => m.id),
- parsed.video.windows.map((m) => m?.id).filter((id) => typeof id === 'string'),
- );
- }
+ // Only the CURRENT platform's video list is worth warning about. The
+ // pickers, downloads, and every edit path read one platform's array
+ // (`getVideoModels`), so drift in the other one is invisible and
+ // unactionable here — and because the warning has no silence-without-
+ // restore path, a Windows box would print the macOS rows on every single
+ // boot forever with nothing the user can usefully do about them. The
+ // machine that actually runs that platform still gets the warning.
+ const driftPlatform = IS_WIN ? 'windows' : 'macos';
+ if (
+ isPlainObject(sd.video) &&
+ isPlainObject(parsed.video) &&
+ Array.isArray(sd.video[driftPlatform]) &&
+ Array.isArray(parsed.video[driftPlatform])
+ ) {
+ warnDrift(
+ 'video',
+ driftPlatform,
+ sd.video[driftPlatform],
+ DEFAULT_REGISTRY.video[driftPlatform].map((m) => m.id),
+ parsed.video[driftPlatform].map((m) => m?.id).filter((id) => typeof id === 'string'),
+ );
}
}
cached = normalizeRegistry(parsed);
diff --git a/server/lib/mockPathsDataRoot.test.js b/server/lib/mockPathsDataRoot.test.js
index c80a56ecd5..925932a212 100644
--- a/server/lib/mockPathsDataRoot.test.js
+++ b/server/lib/mockPathsDataRoot.test.js
@@ -1,4 +1,6 @@
import { describe, it, expect, afterAll } from 'vitest';
+import { posixPath } from './testHelper.js';
+
import { existsSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join, sep } from 'path';
@@ -104,10 +106,10 @@ describe('mockPathsDataRoot', () => {
dataRoot: '/tmp/x',
extraOverrides: { images: '/tmp/x/images', videos: '/tmp/x/videos' },
});
- expect(proxy.PATHS.data).toBe('/tmp/x');
- expect(proxy.PATHS.images).toBe('/tmp/x/images');
- expect(proxy.PATHS.videos).toBe('/tmp/x/videos');
- expect(proxy.PATHS.logs).toBe('/real/logs'); // untouched
+ expect(posixPath(proxy.PATHS.data)).toBe('/tmp/x');
+ expect(posixPath(proxy.PATHS.images)).toBe('/tmp/x/images');
+ expect(posixPath(proxy.PATHS.videos)).toBe('/tmp/x/videos');
+ expect(posixPath(proxy.PATHS.logs)).toBe('/real/logs'); // untouched
});
it('extraOverrides (function) receives the dataRoot', () => {
@@ -115,7 +117,7 @@ describe('mockPathsDataRoot', () => {
dataRoot: '/tmp/x',
extraOverrides: (root) => ({ images: join(root, 'images') }),
});
- expect(proxy.PATHS.images).toBe('/tmp/x/images');
+ expect(posixPath(proxy.PATHS.images)).toBe('/tmp/x/images');
});
it('dataRoot (function) resolves lazily on each PATHS read', () => {
diff --git a/server/lib/pgTools.test.js b/server/lib/pgTools.test.js
index 1263371b5a..3e440a2dba 100644
--- a/server/lib/pgTools.test.js
+++ b/server/lib/pgTools.test.js
@@ -11,6 +11,7 @@
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { posixPath } from './testHelper.js';
// Mock readdir (keg enumeration) and execFileAsync (version probe) so discovery
// runs against a controlled filesystem/version map instead of the host.
@@ -87,13 +88,14 @@ describe('discoverPgDumpCandidates', () => {
'/opt/homebrew/opt/postgresql@15/bin/pg_dump': '15.10',
'/opt/homebrew/opt/postgresql@17/bin/pg_dump': '17.2',
};
- execFileAsync.mockImplementation(async (binary) => ({
- stdout: versions[binary] ? `pg_dump (PostgreSQL) ${versions[binary]}` : '',
- }));
+ execFileAsync.mockImplementation(async (binary) => {
+ const version = versions[posixPath(binary)];
+ return { stdout: version ? `pg_dump (PostgreSQL) ${version}` : '' };
+ });
const candidates = await discoverPgDumpCandidates();
// PATH binary first, then the kegs; the non-postgresql entry is ignored.
expect(candidates[0]).toEqual({ binary: 'pg_dump', major: 15 });
- expect(candidates.map(c => c.binary)).toContain('/opt/homebrew/opt/postgresql@17/bin/pg_dump');
+ expect(posixPath(candidates.map(c => c.binary))).toContain('/opt/homebrew/opt/postgresql@17/bin/pg_dump');
expect(candidates.find(c => c.binary.includes('postgresql@17')).major).toBe(17);
});
});
@@ -112,11 +114,12 @@ describe('resolvePgDump', () => {
'pg_dump': '15.10',
'/opt/homebrew/opt/postgresql@17/bin/pg_dump': '17.2',
};
- execFileAsync.mockImplementation(async (binary) => ({
- stdout: versions[binary] ? `pg_dump (PostgreSQL) ${versions[binary]}` : '',
- }));
+ execFileAsync.mockImplementation(async (binary) => {
+ const version = versions[posixPath(binary)];
+ return { stdout: version ? `pg_dump (PostgreSQL) ${version}` : '' };
+ });
const { binary, satisfies } = await resolvePgDump(17);
- expect(binary).toBe('/opt/homebrew/opt/postgresql@17/bin/pg_dump');
+ expect(posixPath(binary)).toBe('/opt/homebrew/opt/postgresql@17/bin/pg_dump');
expect(satisfies).toBe(true);
});
diff --git a/server/lib/pythonSetup.test.js b/server/lib/pythonSetup.test.js
index 6086c86c2f..6b6a7449b5 100644
--- a/server/lib/pythonSetup.test.js
+++ b/server/lib/pythonSetup.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { posixPath } from './testHelper.js';
// Mutable state read by the hoisted vi.mock factories below. Each test mutates
// it and then `vi.resetModules() + dynamic import` re-evaluates pythonSetup.js
@@ -26,7 +27,11 @@ vi.mock('node:os', async () => {
vi.mock('node:fs', async () => {
const actual = await vi.importActual('node:fs');
- return { ...actual, existsSync: (p) => mockState.presentPaths.has(p) };
+ // pythonSetup composes its candidate paths with path.join/dirname, so on a
+ // Windows host they arrive backslash-separated while presentPaths is seeded
+ // with the POSIX spellings the tests read. Normalize the probe, not the
+ // fixtures — the module's own platform is pinned via mockState.platform.
+ return { ...actual, existsSync: (p) => mockState.presentPaths.has(String(p).split('\\').join('/')) };
});
vi.mock('node:child_process', async () => {
@@ -233,24 +238,24 @@ describe('resolveMfluxPython', () => {
mockState.presentPaths.add('/opt/homebrew/bin/mflux-train');
mockState.presentPaths.add(VENV_TRAIN); // even when the venv also exists, configured wins
const { resolveMfluxPython } = await loadModule();
- expect(resolveMfluxPython('/opt/homebrew/bin/python3')).toBe('/opt/homebrew/bin/python3');
+ expect(posixPath(resolveMfluxPython('/opt/homebrew/bin/python3'))).toBe('/opt/homebrew/bin/python3');
});
it('falls back to the dedicated venv when the configured python lacks mflux-train', async () => {
mockState.presentPaths.add(VENV_TRAIN);
const { resolveMfluxPython } = await loadModule();
- expect(resolveMfluxPython('/opt/homebrew/bin/python3')).toBe(VENV_PY);
+ expect(posixPath(resolveMfluxPython('/opt/homebrew/bin/python3'))).toBe(VENV_PY);
});
it('discovers the dedicated venv even when no python is configured', async () => {
mockState.presentPaths.add(VENV_TRAIN);
const { resolveMfluxPython } = await loadModule();
- expect(resolveMfluxPython(null)).toBe(VENV_PY);
+ expect(posixPath(resolveMfluxPython(null))).toBe(VENV_PY);
});
it('returns the configured path unchanged when neither ships mflux-train (honest "not installed")', async () => {
const { resolveMfluxPython } = await loadModule();
- expect(resolveMfluxPython('/opt/homebrew/bin/python3')).toBe('/opt/homebrew/bin/python3');
+ expect(posixPath(resolveMfluxPython('/opt/homebrew/bin/python3'))).toBe('/opt/homebrew/bin/python3');
});
it('returns null when nothing is configured and no venv exists', async () => {
diff --git a/server/lib/quotaReset.js b/server/lib/quotaReset.js
index fdcc311ca4..ba24da978c 100644
--- a/server/lib/quotaReset.js
+++ b/server/lib/quotaReset.js
@@ -22,7 +22,12 @@ function zoneOffsetMs(epochMs, timeZone) {
hourCycle: 'h23',
}).formatToParts(new Date(epochMs));
const offset = parts.find((part) => part.type === 'timeZoneName')?.value;
- const match = /^GMT([+-])(\d{2}):(\d{2})$/.exec(offset || '');
+ // A zero-offset zone (UTC, Europe/London in winter, Africa/Abidjan, Iceland)
+ // renders as a bare "GMT" — CLDR omits the "+00:00" — so it has to be matched
+ // separately or every such user's reset string resolves to null and the Usage
+ // page loses its reset time entirely. Some ICU builds spell it "UTC".
+ if (/^(?:GMT|UTC)$/.test(offset || '')) return 0;
+ const match = /^(?:GMT|UTC)([+-])(\d{2}):(\d{2})$/.exec(offset || '');
if (!match) return null;
return (Number(match[2]) * 60 + Number(match[3])) * 60 * 1000 * (match[1] === '+' ? 1 : -1);
}
diff --git a/server/lib/quotaReset.test.js b/server/lib/quotaReset.test.js
index 37fad97789..214c40c1cb 100644
--- a/server/lib/quotaReset.test.js
+++ b/server/lib/quotaReset.test.js
@@ -29,6 +29,17 @@ describe('parseHumanReset', () => {
expect(parseHumanReset('2026-07-27T12:00:00.000Z', { now })).toBe('2026-07-27T12:00:00.000Z');
});
+ // A zero-offset zone renders its longOffset as a bare "GMT", not "GMT+00:00",
+ // so an offset parser that only accepts the signed form resolves every reset
+ // in such a zone to null — and the Usage page silently loses its reset time
+ // for anyone in the UK in winter, Iceland, or plain UTC.
+ it('resolves a zone whose offset is exactly zero', () => {
+ expect(parseHumanReset('Jan 27 at 2pm', { now: Date.parse('2026-01-26T12:00:00.000Z'), timezone: 'Europe/London' }))
+ .toBe('2026-01-27T14:00:00.000Z');
+ expect(parseHumanReset('Jul 27 at 2pm', { now, timezone: 'Atlantic/Reykjavik' }))
+ .toBe('2026-07-27T14:00:00.000Z');
+ });
+
it('returns null for a missing or unreadable reset rather than guessing one', () => {
expect(parseHumanReset(null, { now })).toBeNull();
expect(parseHumanReset('', { now })).toBeNull();
diff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.js
index a4b683a3f1..7dc5241b52 100644
--- a/server/lib/spawnCwd.test.js
+++ b/server/lib/spawnCwd.test.js
@@ -1,4 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { posixPath } from './testHelper.js';
+
import { mkdtempSync, rmSync, writeFileSync } from 'fs';
import { tmpdir, homedir } from 'os';
import { join } from 'path';
@@ -141,12 +143,12 @@ describe('withSpawnCwdEnv', () => {
// the app's workspace.
it('pins PWD to the spawn cwd, overriding a stale inherited value', () => {
const env = withSpawnCwdEnv({ PATH: '/usr/bin', PWD: '/repos/PortOS' }, '/repos/my-app');
- expect(env.PWD).toBe('/repos/my-app');
- expect(env.PATH).toBe('/usr/bin');
+ expect(posixPath(env.PWD)).toBe('/repos/my-app');
+ expect(posixPath(env.PATH)).toBe('/usr/bin');
});
it('sets PWD even when the inherited env had none', () => {
- expect(withSpawnCwdEnv({ PATH: '/usr/bin' }, '/repos/my-app').PWD).toBe('/repos/my-app');
+ expect(posixPath(withSpawnCwdEnv({ PATH: '/usr/bin' }, '/repos/my-app').PWD)).toBe('/repos/my-app');
});
// Windows env names are case-insensitive, so a spread of process.env can carry
@@ -158,7 +160,7 @@ describe('withSpawnCwdEnv', () => {
const env = withSpawnCwdEnv({ [variant]: '/repos/PortOS', PATH: '/usr/bin' }, '/repos/my-app');
const pwdKeys = Object.keys(env).filter((k) => /^pwd$/i.test(k));
expect(pwdKeys, `${variant} must not survive alongside PWD`).toEqual(['PWD']);
- expect(env.PWD).toBe('/repos/my-app');
+ expect(posixPath(env.PWD)).toBe('/repos/my-app');
}
});
@@ -168,15 +170,15 @@ describe('withSpawnCwdEnv', () => {
it('leaves the inherited PWD untouched when there is no cwd to pin', () => {
for (const absent of [undefined, null, '']) {
const env = withSpawnCwdEnv({ PWD: '/repos/PortOS', PATH: '/usr/bin' }, absent);
- expect(env.PWD).toBe('/repos/PortOS');
- expect(env.PATH).toBe('/usr/bin');
+ expect(posixPath(env.PWD)).toBe('/repos/PortOS');
+ expect(posixPath(env.PATH)).toBe('/usr/bin');
}
});
it('copies rather than mutating the caller env', () => {
const original = { PWD: '/repos/PortOS' };
const env = withSpawnCwdEnv(original, '/repos/my-app');
- expect(original.PWD).toBe('/repos/PortOS');
+ expect(posixPath(original.PWD)).toBe('/repos/PortOS');
expect(env).not.toBe(original);
});
diff --git a/server/lib/tailscale.js b/server/lib/tailscale.js
index 8a3166935f..ef76182b3c 100644
--- a/server/lib/tailscale.js
+++ b/server/lib/tailscale.js
@@ -6,8 +6,8 @@ import { safeJSONParse } from './fileUtils.js';
const execFileAsync = promisify(execFile);
-const IS_WIN = process.platform === 'win32';
-const TAILSCALE_BIN = IS_WIN ? 'tailscale.exe' : 'tailscale';
+const isWin = () => process.platform === 'win32';
+const tailscaleBin = () => (isWin() ? 'tailscale.exe' : 'tailscale');
export const MACOS_TAILSCALE_APP_BUNDLE = '/Applications/Tailscale.app/Contents/MacOS/Tailscale';
@@ -22,7 +22,11 @@ export const MACOS_TAILSCALE_APP_BUNDLE = '/Applications/Tailscale.app/Contents/
// permitted" when targeting paths like data/certs/). The Homebrew binary is
// the open-source CLI and is not sandboxed, so it can write anywhere the
// shell user can. App-bundle is kept as a last-resort fallback.
-const TAILSCALE_CANDIDATES = IS_WIN
+// Resolved per call rather than frozen at import: hasOnlySandboxedTailscale is
+// gated on `process.platform === 'darwin'`, so pinning the candidate list to
+// whatever platform happened to import the module would have it scan the wrong
+// paths for the platform it just decided it is on.
+const tailscaleCandidates = () => (isWin()
? [
'C:\\Program Files\\Tailscale\\tailscale.exe',
'C:\\Program Files (x86)\\Tailscale\\tailscale.exe'
@@ -32,16 +36,16 @@ const TAILSCALE_CANDIDATES = IS_WIN
'/usr/local/bin/tailscale',
'/usr/bin/tailscale',
MACOS_TAILSCALE_APP_BUNDLE
- ];
+ ]);
export function findTailscale() {
- for (const p of TAILSCALE_CANDIDATES) {
+ for (const p of tailscaleCandidates()) {
if (existsSync(p)) return p;
}
// Use path.delimiter (';' on Windows, ':' elsewhere) so PATH scanning works cross-platform.
for (const dir of (process.env.PATH || '').split(delimiter)) {
if (!dir) continue;
- const p = join(dir, TAILSCALE_BIN);
+ const p = join(dir, tailscaleBin());
if (existsSync(p)) return p;
}
return null;
@@ -98,18 +102,18 @@ export function hasOnlySandboxedTailscale() {
if (process.platform !== 'darwin') return false;
// True iff the MAS app bundle exists AND no unsandboxed binary is
// reachable anywhere. The previous implementation delegated to
- // findTailscale which returns the FIRST candidate in TAILSCALE_CANDIDATES
+ // findTailscale which returns the FIRST candidate in tailscaleCandidates()
// order — so an unsandboxed `tailscale` living in a non-standard $PATH
- // directory (not in TAILSCALE_CANDIDATES) was missed entirely, and we
+ // directory (not in tailscaleCandidates()) was missed entirely, and we
// misclassified the machine as sandboxed-only.
if (!existsSync(MACOS_TAILSCALE_APP_BUNDLE)) return false;
- for (const p of TAILSCALE_CANDIDATES) {
+ for (const p of tailscaleCandidates()) {
if (p === MACOS_TAILSCALE_APP_BUNDLE) continue;
if (existsSync(p)) return false;
}
for (const dir of (process.env.PATH || '').split(delimiter)) {
if (!dir) continue;
- const p = join(dir, TAILSCALE_BIN);
+ const p = join(dir, tailscaleBin());
if (existsSync(p) && p !== MACOS_TAILSCALE_APP_BUNDLE) return false;
}
return true;
diff --git a/server/lib/tailscale.test.js b/server/lib/tailscale.test.js
index 68864c7bf2..517133aba5 100644
--- a/server/lib/tailscale.test.js
+++ b/server/lib/tailscale.test.js
@@ -19,6 +19,14 @@ import {
MACOS_TAILSCALE_APP_BUNDLE
} from './tailscale.js';
+// The candidate list findTailscale walks is platform-dependent, so a test that
+// wants "a Tailscale binary is installed" has to name the candidate for the
+// platform it is running on — a hardcoded POSIX path is simply absent from the
+// Windows list and reads back as not-installed.
+const INSTALLED_CANDIDATE = process.platform === 'win32'
+ ? 'C:\\Program Files\\Tailscale\\tailscale.exe'
+ : '/opt/homebrew/bin/tailscale';
+
describe('findTailscale', () => {
let originalPath;
@@ -32,12 +40,8 @@ describe('findTailscale', () => {
});
it('returns the first matching candidate path', () => {
- const isWin = process.platform === 'win32';
- const expected = isWin
- ? 'C:\\Program Files\\Tailscale\\tailscale.exe'
- : '/opt/homebrew/bin/tailscale';
- existsSync.mockImplementation((p) => p === expected);
- expect(findTailscale()).toBe(expected);
+ existsSync.mockImplementation((p) => p === INSTALLED_CANDIDATE);
+ expect(findTailscale()).toBe(INSTALLED_CANDIDATE);
});
it('falls back to a later candidate when earlier ones are missing', () => {
@@ -152,7 +156,7 @@ describe('getTailscaleStatus / isTailscaleUp', () => {
originalPath = process.env.PATH;
vi.clearAllMocks();
// Default: a Tailscale binary exists at a known candidate path.
- existsSync.mockImplementation((p) => p === '/opt/homebrew/bin/tailscale');
+ existsSync.mockImplementation((p) => p === INSTALLED_CANDIDATE);
});
afterEach(() => {
diff --git a/server/lib/testHelper.js b/server/lib/testHelper.js
index 783b3bd0e6..87a3e50d34 100644
--- a/server/lib/testHelper.js
+++ b/server/lib/testHelper.js
@@ -1,11 +1,17 @@
/**
- * Test HTTP request helper
+ * Shared test helpers: HTTP request harness, fetch-Response mocks, the
+ * server-source scanner used by the whole-tree guard suites, and the two
+ * cross-platform helpers (`posixPath`, `resolveTestPython`) that keep
+ * path- and interpreter-sensitive suites running on Windows as well as POSIX.
+ *
* fetch-based replacement for supertest — creates a real HTTP server on a
* random port, makes a single request, then shuts the server down.
*/
import { createServer } from 'http';
-import { readdirSync, readFileSync } from 'fs';
+import { execFileSync } from 'child_process';
+import { homedir } from 'os';
+import { existsSync, readdirSync, readFileSync } from 'fs';
import { join, relative } from 'path';
import { fileURLToPath } from 'url';
@@ -174,7 +180,14 @@ export function collectServerSources(dir = SERVER_DIR) {
const abs = join(dir, entry.name);
if (entry.isDirectory()) return collectServerSources(abs);
if (!entry.name.endsWith('.js') || entry.name.endsWith('.test.js')) return [];
- return [relative(SERVER_DIR, abs)];
+ // POSIX separators always. These relative paths are IDENTIFIERS, not paths
+ // to open: guard suites compare them against literals like
+ // 'cos-runner/index.js' and list them in EXEMPT/DELEGATES tables. On
+ // Windows `relative()` yields 'cos-runner\index.js', so every one of those
+ // comparisons missed — the guards reported both "the scan no longer finds
+ // these" for live files AND "these spawn without pinning PWD" for exempt
+ // ones. readServerSource joins them back, and Windows accepts '/' there.
+ return [relative(SERVER_DIR, abs).split('\\').join('/')];
});
}
@@ -182,3 +195,66 @@ export function collectServerSources(dir = SERVER_DIR) {
export function readServerSource(rel) {
return readFileSync(join(SERVER_DIR, rel), 'utf8');
}
+
+/**
+ * Normalize a path for comparison against a POSIX-spelled literal.
+ *
+ * The overwhelmingly common Windows test failure is an assertion that names a
+ * path as `'/some/path'` while the code under test built it with `path.join`,
+ * which emits `\` there. Normalizing the RECEIVED value keeps the readable
+ * literal meaningful on both platforms; it is a no-op on POSIX.
+ *
+ * Use it on what the code returned, never on the expectation — a normalized
+ * expectation would also hide a genuinely wrong path.
+ */
+export const posixPath = (value) => String(value).split('\\').join('/');
+
+/**
+ * Resolve a Python interpreter that actually RUNS, or `null` when there is
+ * none — for suites that shell out to one of PortOS's `.py` scripts. Pair it
+ * with `describe.skipIf(!resolveTestPython())`.
+ *
+ * Trusting a name on PATH is not enough on Windows: a machine with no
+ * Store-installed Python still has `python` on PATH as a Microsoft Store ALIAS
+ * STUB, which exists, exits non-zero, and prints "Python was not found". A
+ * `where`-style check passes on that stub and every case then fails with an
+ * opaque "Command failed" — so each candidate is probed by executing something
+ * trivial. The `py` launcher gets the same treatment: it is the standard
+ * Windows entry point but is itself a shim that can point at an uninstalled
+ * version.
+ *
+ * PortOS also provisions its OWN interpreters (`setup:image` / `setup:video`
+ * build venvs under `~/.portos`), so a machine can be fully set up for
+ * image/video gen while the bare `python` name is still a stub. Those are
+ * searched before concluding there is no interpreter — otherwise these suites
+ * silently skip on exactly the machines that exercise the scripts they cover.
+ *
+ * `PORTOS_TEST_PYTHON` overrides the whole search.
+ *
+ * @returns {string|null} a runnable interpreter path/name, or null
+ */
+export function resolveTestPython() {
+ const isWin = process.platform === 'win32';
+ const venvBin = isWin ? ['Scripts', 'python.exe'] : ['bin', 'python3'];
+ const portosPythons = ['venv-flux2', 'venv-mflux', 'venv-video', 'voice']
+ .map((venv) => join(homedir(), '.portos', venv, ...venvBin))
+ .concat(isWin ? [join(homedir(), 'miniconda3', 'python.exe')] : [])
+ .filter((candidate) => existsSync(candidate));
+
+ const candidates = [
+ process.env.PORTOS_TEST_PYTHON,
+ isWin ? 'python' : 'python3',
+ isWin ? 'python3' : 'python',
+ ...(isWin ? ['py'] : []),
+ ...portosPythons,
+ ].filter(Boolean);
+
+ return candidates.find((candidate) => {
+ try {
+ execFileSync(candidate, ['-c', 'pass'], { stdio: 'ignore' });
+ return true;
+ } catch {
+ return false;
+ }
+ }) || null;
+}
diff --git a/server/lib/tuiPromptRunner.test.js b/server/lib/tuiPromptRunner.test.js
index 37e55baed8..b88b3d1c54 100644
--- a/server/lib/tuiPromptRunner.test.js
+++ b/server/lib/tuiPromptRunner.test.js
@@ -82,9 +82,22 @@ vi.mock('./fileUtils.js', async () => {
// Keys are normalized on both sides so a relative or unnormalized path
// from the SUT still hits the seeded entry rather than silently falling
// through to a real (missing-file) read.
+ //
+ // The UNSEEDED reads under the runs dir have to be served from memory too,
+ // for the same reason. Those are the polls that fire before a test seeds
+ // its file; letting them hit the real threadpool means one can still be
+ // in flight when the seed lands, and its late `null` resets the
+ // size-stability baseline that the post-seed poll just established — so
+ // the salvage path sees an unsettled file and finishes as a plain
+ // fallback. That reproduces about one run in three. Everything outside the
+ // runs dir still falls through: the resolveTuiResponseText suite below
+ // drives real files in a temp dir of its own.
tryReadFile: vi.fn(async (filePath, ...rest) => {
const key = resolvePath(filePath);
- return responseFiles.has(key) ? responseFiles.get(key) : actual.tryReadFile(filePath, ...rest);
+ if (responseFiles.has(key)) return responseFiles.get(key);
+ const runsDir = runsTmpDirRef.current;
+ if (runsDir && key.startsWith(resolvePath(runsDir))) return null;
+ return actual.tryReadFile(filePath, ...rest);
}),
};
});
diff --git a/server/package-lock.json b/server/package-lock.json
index 4992281992..bec2788737 100644
--- a/server/package-lock.json
+++ b/server/package-lock.json
@@ -280,9 +280,6 @@
"cpu": [
"arm"
],
- "libc": [
- "glibc"
- ],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -299,9 +296,6 @@
"cpu": [
"arm64"
],
- "libc": [
- "glibc"
- ],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -318,9 +312,6 @@
"cpu": [
"ppc64"
],
- "libc": [
- "glibc"
- ],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -337,9 +328,6 @@
"cpu": [
"riscv64"
],
- "libc": [
- "glibc"
- ],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -356,9 +344,6 @@
"cpu": [
"s390x"
],
- "libc": [
- "glibc"
- ],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -375,9 +360,6 @@
"cpu": [
"x64"
],
- "libc": [
- "glibc"
- ],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -394,9 +376,6 @@
"cpu": [
"arm64"
],
- "libc": [
- "musl"
- ],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -413,9 +392,6 @@
"cpu": [
"x64"
],
- "libc": [
- "musl"
- ],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -432,9 +408,6 @@
"cpu": [
"arm"
],
- "libc": [
- "glibc"
- ],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -457,9 +430,6 @@
"cpu": [
"arm64"
],
- "libc": [
- "glibc"
- ],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -482,9 +452,6 @@
"cpu": [
"ppc64"
],
- "libc": [
- "glibc"
- ],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -507,9 +474,6 @@
"cpu": [
"riscv64"
],
- "libc": [
- "glibc"
- ],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -532,9 +496,6 @@
"cpu": [
"s390x"
],
- "libc": [
- "glibc"
- ],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -557,9 +518,6 @@
"cpu": [
"x64"
],
- "libc": [
- "glibc"
- ],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -582,9 +540,6 @@
"cpu": [
"arm64"
],
- "libc": [
- "musl"
- ],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -607,9 +562,6 @@
"cpu": [
"x64"
],
- "libc": [
- "musl"
- ],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -1029,9 +981,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1049,9 +998,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1069,9 +1015,6 @@
"ppc64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1089,9 +1032,6 @@
"s390x"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1109,9 +1049,6 @@
"x64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1129,9 +1066,6 @@
"x64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -3133,9 +3067,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -3157,9 +3088,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -3181,9 +3109,6 @@
"x64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -3205,9 +3130,6 @@
"x64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MPL-2.0",
"optional": true,
"os": [
diff --git a/server/routes/apps/lifecycle.test.js b/server/routes/apps/lifecycle.test.js
index 5c5a9901f3..1f178f25cc 100644
--- a/server/routes/apps/lifecycle.test.js
+++ b/server/routes/apps/lifecycle.test.js
@@ -1,6 +1,14 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import express from 'express';
import { request } from '../../lib/testHelper.js';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+// The lifecycle route 400s when an app's repoPath does not exist, so these
+// fixtures need a real directory. REAL_DIR is NOT one on Windows — it resolves to
+// <cwd-drive>:\\tmp, present on some machines by accident and absent on the CI
+// runner, which is why this suite passed locally and 400'd there.
+const REAL_DIR = tmpdir();
import lifecycleRoutes from './lifecycle.js';
// Mock the services this router touches. appBuilder is intentionally NOT mocked
@@ -61,7 +69,7 @@ describe('Apps Lifecycle Routes', () => {
id: 'app-001',
name: 'Mixed App',
type: 'express',
- repoPath: '/tmp',
+ repoPath: REAL_DIR,
pm2ProcessNames: ['mixed-web'],
nativeLaunch: {
label: 'Godot',
@@ -82,7 +90,7 @@ describe('Apps Lifecycle Routes', () => {
expect(response.status).toBe(200);
expect(response.body.processName).toBe('mixed-game');
expect(pm2Service.startWithCommand).toHaveBeenCalledWith(
- 'mixed-game', '/tmp', './scripts/game run', { autorestart: false }
+ 'mixed-game', REAL_DIR, './scripts/game run', { autorestart: false }
);
expect(pm2Service.deleteApp).toHaveBeenCalledWith('mixed-game', undefined);
expect(pm2Service.deleteApp.mock.invocationCallOrder[0])
@@ -98,7 +106,7 @@ describe('Apps Lifecycle Routes', () => {
});
it('starts the native target in the app\'s own PM2 home', async () => {
- appsService.getAppById.mockResolvedValue({ ...mockApp, pm2Home: '/tmp/example-pm2' });
+ appsService.getAppById.mockResolvedValue({ ...mockApp, pm2Home: join(REAL_DIR, 'example-pm2') });
pm2Service.getAppStatus.mockResolvedValue({ status: 'stopped' });
pm2Service.deleteApp.mockResolvedValue({ success: true });
pm2Service.startWithCommand.mockResolvedValue({ success: true });
@@ -108,7 +116,7 @@ describe('Apps Lifecycle Routes', () => {
expect(response.status).toBe(200);
expect(pm2Service.startWithCommand).toHaveBeenCalledWith(
- 'mixed-game', '/tmp', './scripts/game run', { autorestart: false, pm2Home: '/tmp/example-pm2' }
+ 'mixed-game', REAL_DIR, './scripts/game run', { autorestart: false, pm2Home: join(REAL_DIR, 'example-pm2') }
);
});
@@ -200,7 +208,7 @@ describe('Apps Lifecycle Routes', () => {
repoPath: '/path/to/repo',
pm2ProcessNames: ['test-app'],
startCommands: ['npm run dev'],
- pm2Home: '/tmp/example-pm2'
+ pm2Home: join(REAL_DIR, 'example-pm2')
};
appsService.getAppById.mockResolvedValue(mockApp);
pm2Service.startWithCommand.mockResolvedValue({ success: true });
@@ -210,7 +218,7 @@ describe('Apps Lifecycle Routes', () => {
expect(response.status).toBe(200);
expect(pm2Service.startWithCommand).toHaveBeenCalledWith(
- 'test-app', '/path/to/repo', 'npm run dev', { pm2Home: '/tmp/example-pm2' }
+ 'test-app', '/path/to/repo', 'npm run dev', { pm2Home: join(REAL_DIR, 'example-pm2') }
);
});
@@ -219,7 +227,7 @@ describe('Apps Lifecycle Routes', () => {
id: 'game-001',
name: 'The Game',
type: 'desktop',
- repoPath: '/tmp', // real dir; no ecosystem config there, and desktop skips it anyway
+ repoPath: REAL_DIR, // real dir; no ecosystem config there, and desktop skips it anyway
pm2ProcessNames: ['the-game'],
startCommands: ['./scripts/game run']
};
@@ -236,7 +244,7 @@ describe('Apps Lifecycle Routes', () => {
// Command-based launch, never the ecosystem web-server path.
expect(pm2Service.startFromEcosystem).not.toHaveBeenCalled();
expect(pm2Service.startWithCommand).toHaveBeenCalledWith(
- 'the-game', '/tmp', './scripts/game run', { autorestart: false }
+ 'the-game', REAL_DIR, './scripts/game run', { autorestart: false }
);
expect(pm2Service.deleteApp).toHaveBeenCalledWith('the-game', undefined);
});
@@ -246,7 +254,7 @@ describe('Apps Lifecycle Routes', () => {
id: 'game-001',
name: 'The Game',
type: 'desktop',
- repoPath: '/tmp',
+ repoPath: REAL_DIR,
pm2ProcessNames: ['the-game'],
startCommands: ['./scripts/game run']
};
@@ -267,7 +275,7 @@ describe('Apps Lifecycle Routes', () => {
id: 'game-001',
name: 'The Game',
type: 'desktop',
- repoPath: '/tmp',
+ repoPath: REAL_DIR,
pm2ProcessNames: ['the-game'],
startCommands: ['./scripts/game run']
};
@@ -367,7 +375,7 @@ describe('Apps Lifecycle Routes', () => {
const mockApp = {
id: 'app-001',
name: 'Test App',
- repoPath: '/tmp',
+ repoPath: REAL_DIR,
buildCommand: 'rm -rf /',
pm2ProcessNames: ['test-app']
};
diff --git a/server/routes/avatar.test.js b/server/routes/avatar.test.js
index b8e8e8ee51..09ab777579 100644
--- a/server/routes/avatar.test.js
+++ b/server/routes/avatar.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { join as joinPath } from 'path';
import express from 'express';
import { Readable } from 'stream';
import { request } from '../lib/testHelper.js';
@@ -109,7 +110,7 @@ describe('avatar routes', () => {
expect(res.status).toBe(200);
expect(res.text).toBe('VARIANT-GLB');
// The resolved path must stay inside the avatar dir with .glb appended.
- expect(createReadStream).toHaveBeenCalledWith('/mock/data/avatar/mini-male-c.glb');
+ expect(createReadStream).toHaveBeenCalledWith(joinPath('/mock/data', 'avatar', 'mini-male-c.glb'));
});
it('rejects path-traversal / illegal variant names with 404', async () => {
diff --git a/server/routes/scaffold.test.js b/server/routes/scaffold.test.js
index 4dcbe28d7b..15c59a034e 100644
--- a/server/routes/scaffold.test.js
+++ b/server/routes/scaffold.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { join } from 'path';
import express from 'express';
import { EventEmitter } from 'events';
import { request } from '../lib/testHelper.js';
@@ -146,7 +147,7 @@ describe('POST /api/scaffold — request validation before filesystem mutation (
expect(res.body.success).toBe(true);
// Validation passed → the route reached the first filesystem mutation
// (directory creation) and registered the app.
- expect(ensureDir).toHaveBeenCalledWith('/tmp/workspace/my-app');
+ expect(ensureDir).toHaveBeenCalledWith(join('/tmp/workspace', 'my-app'));
expect(createApp).toHaveBeenCalledTimes(1);
});
@@ -160,7 +161,7 @@ describe('POST /api/scaffold — request validation before filesystem mutation (
expect(res.status).toBe(200);
expect(scaffoldVite).toHaveBeenCalledTimes(1);
expect(scaffoldVite).toHaveBeenCalledWith(expect.objectContaining({
- repoPath: '/tmp/workspace/my-app',
+ repoPath: join('/tmp/workspace', 'my-app'),
dirName: 'my-app',
parentDir: '/tmp/workspace',
template: 'vite-express',
@@ -177,7 +178,7 @@ describe('POST /api/scaffold — request validation before filesystem mutation (
expect(res.status).toBe(200);
expect(scaffoldPortOS).toHaveBeenCalledWith(expect.objectContaining({
- repoPath: '/tmp/workspace/my-app',
+ repoPath: join('/tmp/workspace', 'my-app'),
name: 'My App',
dirName: 'my-app',
uiPort: 3100,
diff --git a/server/scripts/migrateCreativeDirectorToDB.test.js b/server/scripts/migrateCreativeDirectorToDB.test.js
index 268fe8d853..1828947a5a 100644
--- a/server/scripts/migrateCreativeDirectorToDB.test.js
+++ b/server/scripts/migrateCreativeDirectorToDB.test.js
@@ -7,6 +7,7 @@
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { posixPath as toPosix } from '../lib/testHelper.js';
// In-memory filesystem keyed by absolute path.
let files = {};
@@ -27,17 +28,17 @@ vi.mock('../lib/migrationMarker.js', () => ({
vi.mock('fs/promises', () => ({
readFile: vi.fn(async (path) => {
- if (!(path in files)) {
+ if (!(toPosix(path) in files)) {
const err = new Error('ENOENT');
err.code = 'ENOENT';
throw err;
}
- return files[path];
+ return files[toPosix(path)];
}),
rename: vi.fn(async (from, to) => {
if (renameShouldFail) throw new Error('EACCES: rename failed');
- files[to] = files[from];
- delete files[from];
+ files[toPosix(to)] = files[toPosix(from)];
+ delete files[toPosix(from)];
}),
}));
diff --git a/server/scripts/migrateIssuesToDB.test.js b/server/scripts/migrateIssuesToDB.test.js
index e8fe011b3e..3b87741743 100644
--- a/server/scripts/migrateIssuesToDB.test.js
+++ b/server/scripts/migrateIssuesToDB.test.js
@@ -6,6 +6,7 @@
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { posixPath as toPosix } from '../lib/testHelper.js';
let files = {};
let dirEntries = null;
@@ -15,7 +16,7 @@ let renamed = [];
vi.mock('../lib/fileUtils.js', () => ({
PATHS: { data: '/fake/data' },
- readJSONFile: vi.fn(async (path) => recordsByDir[path] ?? null),
+ readJSONFile: vi.fn(async (path) => recordsByDir[toPosix(path)] ?? null),
}));
// Marker I/O is delegated to migrationMarker.js; mock it against the same
@@ -28,11 +29,11 @@ vi.mock('../lib/migrationMarker.js', () => ({
vi.mock('fs/promises', () => ({
rename: vi.fn(async (from, to) => {
if (renameShouldFail) throw new Error('EACCES');
- renamed.push([from, to]);
+ renamed.push([toPosix(from), toPosix(to)]);
}),
readdir: vi.fn(async () => (dirEntries === null ? [] : dirEntries)),
stat: vi.fn(async (path) => {
- if (path === '/fake/data/pipeline-issues') {
+ if (toPosix(path) === '/fake/data/pipeline-issues') {
if (dirEntries === null) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
return { isDirectory: () => true };
}
diff --git a/server/scripts/migrateSeriesToDB.test.js b/server/scripts/migrateSeriesToDB.test.js
index 49b7c27ba2..5402aeab22 100644
--- a/server/scripts/migrateSeriesToDB.test.js
+++ b/server/scripts/migrateSeriesToDB.test.js
@@ -6,6 +6,7 @@
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { posixPath as toPosix } from '../lib/testHelper.js';
let files = {}; // path → string (markers)
let dirEntries = null; // readdir(legacyDir) result, or null = ENOENT
@@ -14,7 +15,7 @@ let renamed = [];
vi.mock('../lib/fileUtils.js', () => ({
PATHS: { data: '/fake/data' },
- readJSONFile: vi.fn(async (path) => recordsByDir[path] ?? null),
+ readJSONFile: vi.fn(async (path) => recordsByDir[toPosix(path)] ?? null),
}));
// Marker I/O is delegated to migrationMarker.js; mock it against the same
@@ -25,10 +26,10 @@ vi.mock('../lib/migrationMarker.js', () => ({
}));
vi.mock('fs/promises', () => ({
- rename: vi.fn(async (from, to) => { renamed.push([from, to]); }),
+ rename: vi.fn(async (from, to) => { renamed.push([toPosix(from), toPosix(to)]); }),
readdir: vi.fn(async () => (dirEntries === null ? [] : dirEntries)),
stat: vi.fn(async (path) => {
- if (path === '/fake/data/pipeline-series') {
+ if (toPosix(path) === '/fake/data/pipeline-series') {
if (dirEntries === null) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
return { isDirectory: () => true };
}
diff --git a/server/scripts/migrateStoryBuilderToDB.test.js b/server/scripts/migrateStoryBuilderToDB.test.js
index e6a2c0d885..c9d4183570 100644
--- a/server/scripts/migrateStoryBuilderToDB.test.js
+++ b/server/scripts/migrateStoryBuilderToDB.test.js
@@ -6,6 +6,7 @@
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { posixPath as toPosix } from '../lib/testHelper.js';
let files = {};
let dirEntries = null;
@@ -15,7 +16,7 @@ let renamed = [];
vi.mock('../lib/fileUtils.js', () => ({
PATHS: { data: '/fake/data' },
- readJSONFile: vi.fn(async (path) => recordsByDir[path] ?? null),
+ readJSONFile: vi.fn(async (path) => recordsByDir[toPosix(path)] ?? null),
}));
// Marker I/O is delegated to migrationMarker.js; mock it against the same
@@ -28,11 +29,11 @@ vi.mock('../lib/migrationMarker.js', () => ({
vi.mock('fs/promises', () => ({
rename: vi.fn(async (from, to) => {
if (renameShouldFail) throw new Error('EACCES');
- renamed.push([from, to]);
+ renamed.push([toPosix(from), toPosix(to)]);
}),
readdir: vi.fn(async () => (dirEntries === null ? [] : dirEntries)),
stat: vi.fn(async (path) => {
- if (path === '/fake/data/story-builder') {
+ if (toPosix(path) === '/fake/data/story-builder') {
if (dirEntries === null) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
return { isDirectory: () => true };
}
diff --git a/server/scripts/migrateUniversesToDB.test.js b/server/scripts/migrateUniversesToDB.test.js
index ec037fd4e1..71db34cdd6 100644
--- a/server/scripts/migrateUniversesToDB.test.js
+++ b/server/scripts/migrateUniversesToDB.test.js
@@ -7,6 +7,7 @@
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { posixPath as toPosix } from '../lib/testHelper.js';
// In-memory marker/legacy state.
let files = {}; // path → string (markers)
@@ -19,8 +20,8 @@ let renamed = [];
vi.mock('../lib/fileUtils.js', () => ({
PATHS: { data: '/fake/data' },
readJSONFile: vi.fn(async (path) => {
- if (path === '/fake/data/universes/index.json') return typeIndex;
- return recordsByDir[path] ?? null;
+ if (toPosix(path) === '/fake/data/universes/index.json') return typeIndex;
+ return recordsByDir[toPosix(path)] ?? null;
}),
}));
@@ -35,14 +36,14 @@ vi.mock('../lib/migrationMarker.js', () => ({
vi.mock('fs/promises', () => ({
rename: vi.fn(async (from, to) => {
if (renameShouldFail) throw new Error('EACCES');
- renamed.push([from, to]);
+ renamed.push([toPosix(from), toPosix(to)]);
}),
readdir: vi.fn(async () => {
if (dirEntries === null) return [];
return dirEntries;
}),
stat: vi.fn(async (path) => {
- if (path === '/fake/data/universes') {
+ if (toPosix(path) === '/fake/data/universes') {
if (dirEntries === null) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
return { isDirectory: () => true };
}
diff --git a/server/scripts/migrateWritersRoomToDB.test.js b/server/scripts/migrateWritersRoomToDB.test.js
index a3fe0e5628..f68fe73ce9 100644
--- a/server/scripts/migrateWritersRoomToDB.test.js
+++ b/server/scripts/migrateWritersRoomToDB.test.js
@@ -8,6 +8,7 @@
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { posixPath as toPosix } from '../lib/testHelper.js';
const DATA = '/fake/data';
const ROOT = `${DATA}/writers-room`;
@@ -22,7 +23,7 @@ let renamed = [];
vi.mock('../lib/fileUtils.js', () => ({
PATHS: { data: DATA },
- readJSONFile: vi.fn(async (path, fallback) => (path in jsonByPath ? jsonByPath[path] : fallback)),
+ readJSONFile: vi.fn(async (path, fallback) => (toPosix(path) in jsonByPath ? jsonByPath[toPosix(path)] : fallback)),
safeJSONParse: vi.fn((content, fallback) => { try { return JSON.parse(content); } catch { return fallback; } }),
}));
@@ -35,22 +36,22 @@ vi.mock('../lib/migrationMarker.js', () => ({
vi.mock('fs/promises', () => ({
readFile: vi.fn(async (path) => {
- if (!(path in files)) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
- return files[path];
+ if (!(toPosix(path) in files)) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
+ return files[toPosix(path)];
}),
- rename: vi.fn(async (from, to) => { renamed.push([from, to]); files[to] = files[from]; delete files[from]; }),
+ rename: vi.fn(async (from, to) => { renamed.push([toPosix(from), toPosix(to)]); files[toPosix(to)] = files[toPosix(from)]; delete files[toPosix(from)]; }),
readdir: vi.fn(async (path) => {
- if (path === WORKS) return workDirs;
+ if (toPosix(path) === WORKS) return workDirs;
return [];
}),
stat: vi.fn(async (path) => {
- if (path === ROOT || path === WORKS) {
- if (existingDirs.has(path)) return { isDirectory: () => true };
+ if (toPosix(path) === ROOT || toPosix(path) === WORKS) {
+ if (existingDirs.has(toPosix(path))) return { isDirectory: () => true };
const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e;
}
// For parkFileAside existence checks: the source exists if it's in `files`,
// the .imported.json aside does not (unless renamed already).
- if (path in files) return { isFile: () => true };
+ if (toPosix(path) in files) return { isFile: () => true };
const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e;
}),
}));
diff --git a/server/services/agents.js b/server/services/agents.js
index 6683a90ad6..40e0845fd2 100644
--- a/server/services/agents.js
+++ b/server/services/agents.js
@@ -1,9 +1,12 @@
-import { exec } from 'child_process';
+import { exec, execFile } from 'child_process';
import { promisify } from 'util';
import { getSpawnedAgent } from './agentState.js';
import { killAgent } from './agentOrchestrator.js';
const execAsync = promisify(exec);
+// execFile (not exec) for the Windows probe: the PowerShell script rides as a
+// single argv element instead of through a shell command line.
+const execFileAsync = promisify(execFile);
// Agent process patterns to detect
const AGENT_PATTERNS = [
@@ -175,39 +178,75 @@ async function findWindowsProcesses(pattern) {
return [];
}
- // Security: Pattern is validated above to only contain safe characters
- const cmd = `wmic process where "name like '%${safePattern}%'" get ProcessId,ParentProcessId,PercentProcessorTime,WorkingSetSize,CreationDate,CommandLine /format:csv`;
-
- const result = await execAsync(cmd, { windowsHide: true }).catch(() => ({ stdout: '' }));
+ // WMIC, not PowerShell CIM, was the original implementation here — but
+ // Microsoft removed wmic.exe from Windows 11 (it is gone entirely on 24H2+
+ // / build 26xxx), so the command failed with ENOENT, the `.catch()` below
+ // swallowed it into an empty string, and getRunningAgents() reported "no
+ // agents running" forever instead of surfacing an error. Get-CimInstance is
+ // the documented successor, ships in-box on every supported Windows, and
+ // returns ISO-8601 CreationDate (rather than wmic's `YYYYMMDDHHmmss.ffffff`),
+ // which Date.parse handles directly.
+ //
+ // Security: safePattern is validated above to contain only safe characters,
+ // and the script is passed as a single argv element to powershell -Command
+ // rather than through a shell, so there is no interpolation boundary to
+ // escape past.
+ // CreationDate is projected through .ToString('o') rather than emitted raw:
+ // Windows PowerShell 5.1 serializes a DateTime as "\/Date(1786...)\/" while
+ // PowerShell 7 emits ISO-8601, and `powershell` resolves to whichever is
+ // installed. Formatting it in the script pins one shape for both hosts.
+ const script = `Get-CimInstance Win32_Process -Filter "Name LIKE '%${safePattern}%'" `
+ + "| Select-Object ProcessId,ParentProcessId,WorkingSetSize,CommandLine,"
+ + "@{Name='CreationDate';Expression={$_.CreationDate.ToString('o')}} "
+ + '| ConvertTo-Json -Compress';
+
+ const result = await execFileAsync(
+ 'powershell',
+ ['-NoProfile', '-NonInteractive', '-Command', script],
+ { windowsHide: true, maxBuffer: 8 * 1024 * 1024 },
+ ).catch((err) => {
+ // Keep the empty-result behavior (the caller treats [] as "none running"),
+ // but never again fail SILENTLY — a broken process probe is why this was
+ // undiagnosable for so long.
+ console.error(`❌ Windows process probe failed for "${safePattern}": ${err.message}`);
+ return { stdout: '' };
+ });
+
+ const raw = String(result.stdout || '').trim();
+ if (!raw) return [];
+
+ // ConvertTo-Json emits a bare object (not a 1-element array) for a single
+ // match, so normalize before iterating.
+ let parsed;
+ try {
+ parsed = JSON.parse(raw);
+ } catch (err) {
+ console.error(`❌ Windows process probe returned unparseable JSON for "${safePattern}": ${err.message}`);
+ return [];
+ }
+ const rows = Array.isArray(parsed) ? parsed : [parsed];
- const lines = result.stdout.trim().split('\n').filter(Boolean);
const processes = [];
-
- // Skip header line
- for (let i = 1; i < lines.length; i++) {
- const parts = lines[i].split(',');
- if (parts.length >= 7) {
- const command = parts[1];
- const creationDate = parts[2];
- const ppid = parseInt(parts[3], 10);
- const cpu = parseFloat(parts[4]) || 0;
- const memory = parseInt(parts[5], 10) / 1024 / 1024; // Convert to MB
- const pid = parseInt(parts[6], 10);
-
- const startTime = parseWindowsDate(creationDate);
- const runtime = Date.now() - startTime;
-
- processes.push({
- pid,
- ppid,
- cpu,
- memory,
- runtime,
- runtimeFormatted: formatRuntime(runtime),
- command,
- startTime
- });
- }
+ for (const row of rows) {
+ if (!row || typeof row !== 'object') continue;
+ const pid = parseInt(row.ProcessId, 10);
+ if (!Number.isFinite(pid)) continue;
+
+ const startTime = parseWindowsDate(row.CreationDate);
+ const runtime = Date.now() - startTime;
+
+ processes.push({
+ pid,
+ ppid: parseInt(row.ParentProcessId, 10) || 0,
+ // Win32_Process carries no CPU% column (the old wmic query asked for a
+ // PercentProcessorTime that class never had, so this was always 0).
+ cpu: 0,
+ memory: (parseInt(row.WorkingSetSize, 10) || 0) / 1024 / 1024, // → MB
+ runtime,
+ runtimeFormatted: formatRuntime(runtime),
+ command: row.CommandLine || '',
+ startTime,
+ });
}
return processes;
@@ -244,6 +283,19 @@ function parseElapsedTime(etime) {
*/
function parseWindowsDate(dateStr) {
if (!dateStr) return Date.now();
+ // Get-CimInstance | ConvertTo-Json emits ISO-8601 with an offset
+ // ("2026-08-13T21:51:42.098512+00:00"); the legacy wmic path emitted
+ // `YYYYMMDDHHmmss.ffffff`. Accept both — the ISO branch must come first,
+ // because the positional parse below would happily read "2026-08-13T2" as a
+ // date and return garbage rather than failing.
+ // Windows PowerShell 5.1's raw DateTime serialization, kept as a fallback for
+ // any caller that doesn't project through .ToString('o').
+ const epoch = /^\/Date\((-?\d+)\)\/$/.exec(dateStr);
+ if (epoch) return Number(epoch[1]);
+ if (dateStr.includes('-') || dateStr.includes('T')) {
+ const iso = Date.parse(dateStr);
+ if (Number.isFinite(iso)) return iso;
+ }
// Format: YYYYMMDDHHmmss.ffffff
const year = parseInt(dateStr.substring(0, 4), 10);
const month = parseInt(dateStr.substring(4, 6), 10) - 1;
diff --git a/server/services/agents.test.js b/server/services/agents.test.js
index 4bd1fb6fc7..287c09a274 100644
--- a/server/services/agents.test.js
+++ b/server/services/agents.test.js
@@ -2,7 +2,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// Mock child_process before importing agents.js
vi.mock('child_process', () => ({
- exec: vi.fn()
+ exec: vi.fn(),
+ // agents.js probes Windows via execFile(powershell, …) — see findWindowsProcesses.
+ execFile: vi.fn()
}));
// Mock util.promisify so execAsync uses our mocked exec
@@ -30,7 +32,7 @@ vi.mock('./agentOrchestrator.js', () => ({
killAgent: vi.fn().mockResolvedValue({ success: true })
}));
-import { exec } from 'child_process';
+import { exec, execFile } from 'child_process';
import { registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';
import {
getRunningAgents,
@@ -52,9 +54,24 @@ function mockExecWith(stdoutOrFn) {
});
}
+// getRunningAgents branches on process.platform: POSIX shells out to `ps`,
+// Windows to `powershell Get-CimInstance`. Nearly every test here feeds `ps`
+// output, so pin a POSIX platform rather than letting the host decide — on a
+// Windows runner the source took the CIM branch, the `ps` mock was never
+// consulted, and every assertion saw an empty list. The Windows branch has its
+// own test below.
+const ORIGINAL_PLATFORM = Object.getOwnPropertyDescriptor(process, 'platform');
+const pinPlatform = (value) =>
+ Object.defineProperty(process, 'platform', { ...ORIGINAL_PLATFORM, value });
+
describe('agents.js', () => {
beforeEach(() => {
vi.clearAllMocks();
+ pinPlatform('darwin');
+ });
+
+ afterEach(() => {
+ Object.defineProperty(process, 'platform', ORIGINAL_PLATFORM);
});
// ===========================================================================
@@ -359,4 +376,71 @@ describe('agents.js', () => {
expect(result).toBeNull();
});
});
+
+ // ===========================================================================
+ // Windows process probe (Get-CimInstance) — the branch that had no coverage
+ // and was silently dead: it shelled out to wmic.exe, which Microsoft removed
+ // from Windows 11, and the failure was swallowed into an empty list.
+ // ===========================================================================
+ describe('getRunningAgents on Windows', () => {
+ const cimRow = (over = {}) => ({
+ ProcessId: 4242,
+ ParentProcessId: 100,
+ WorkingSetSize: 52428800, // 50 MB
+ CommandLine: 'C:\\Users\\dev\\AppData\\Local\\claude.exe --print hi',
+ CreationDate: '2026-08-13T21:51:42.0985120+00:00',
+ ...over,
+ });
+ const mockCim = (payload) => {
+ execFile.mockImplementation((_bin, _args, _opts, cb) => {
+ const callback = typeof _opts === 'function' ? _opts : cb;
+ callback(null, { stdout: typeof payload === 'string' ? payload : JSON.stringify(payload) });
+ });
+ };
+
+ beforeEach(() => pinPlatform('win32'));
+
+ it('probes with PowerShell, not the removed wmic.exe', async () => {
+ mockCim([cimRow()]);
+ await getRunningAgents();
+ expect(execFile).toHaveBeenCalled();
+ const [bin, args] = execFile.mock.calls[0];
+ expect(bin).toBe('powershell');
+ expect(args.join(' ')).toContain('Get-CimInstance Win32_Process');
+ // wmic is gone on Windows 11 — never reintroduce it here.
+ expect(args.join(' ')).not.toContain('wmic');
+ });
+
+ it('maps a CIM row to the shared process shape', async () => {
+ mockCim([cimRow()]);
+ const agents = await getRunningAgents();
+ const found = agents.find((a) => a.pid === 4242);
+ expect(found).toBeDefined();
+ expect(found.ppid).toBe(100);
+ expect(found.memory).toBeCloseTo(50, 5); // bytes → MB
+ expect(found.startTime).toBe(Date.parse('2026-08-13T21:51:42.0985120+00:00'));
+ expect(Number.isFinite(found.runtime)).toBe(true);
+ });
+
+ it('accepts a single match, which ConvertTo-Json emits as a bare object', async () => {
+ // Not wrapped in an array — the shape that would otherwise be iterated
+ // as an object and yield nothing.
+ mockCim(cimRow({ ProcessId: 777 }));
+ const agents = await getRunningAgents();
+ expect(agents.map((a) => a.pid)).toContain(777);
+ });
+
+ it('survives a failed probe without throwing', async () => {
+ execFile.mockImplementation((_bin, _args, _opts, cb) => {
+ const callback = typeof _opts === 'function' ? _opts : cb;
+ callback(new Error('powershell missing'));
+ });
+ await expect(getRunningAgents()).resolves.toEqual([]);
+ });
+
+ it('survives unparseable probe output without throwing', async () => {
+ mockCim('not json at all');
+ await expect(getRunningAgents()).resolves.toEqual([]);
+ });
+ });
});
diff --git a/server/services/askService.test.js b/server/services/askService.test.js
index ad2942fd2a..0200aa473f 100644
--- a/server/services/askService.test.js
+++ b/server/services/askService.test.js
@@ -381,14 +381,21 @@ describe('runAsk', () => {
}
const [, args] = spawn.mock.calls.at(-1);
+ // Windows has no /dev/stdin, so the spawn helper rewrites grok's sentinel
+ // to a real temp file (see lib/grok.js GROK_STDIN_PROMPT_PATH). Assert the
+ // per-platform value rather than pinning the POSIX one — both paths ship,
+ // so both deserve coverage on their own runner.
+ const expectedPromptFile = process.platform === 'win32'
+ ? expect.stringMatching(/grok-prompt-.*\.txt$/)
+ : '/dev/stdin';
expect(args).toEqual([
'--output-format', 'plain',
'--permission-mode', 'bypassPermissions',
- '--prompt-file', '/dev/stdin',
+ '--prompt-file', expectedPromptFile,
]);
expect(args).not.toContain('--model');
// POSIX delivery: the prompt is piped in via stdin.
- expect(child.stdin.end).toHaveBeenCalled();
+ if (process.platform !== 'win32') expect(child.stdin.end).toHaveBeenCalled();
});
it('runs `agy --model <id> --print <prompt>` with headlessArgs still ahead of the print marker', async () => {
diff --git a/server/services/autonomousJobs/execution.js b/server/services/autonomousJobs/execution.js
index 4142c87abc..6ac5fee00d 100644
--- a/server/services/autonomousJobs/execution.js
+++ b/server/services/autonomousJobs/execution.js
@@ -11,6 +11,7 @@
import { spawn } from 'child_process'
import { PATHS } from '../../lib/fileUtils.js'
+import { prepareCliSpawn, killProcessTree } from '../../lib/bufferedSpawn.js'
import { withSpawnCwdEnv } from '../../lib/spawnCwd.js'
import { validateCommand, redactOutput, ALLOWED_COMMANDS_SORTED } from '../../lib/commandSecurity.js'
import { cosEvents } from '../cosEvents.js'
@@ -71,14 +72,22 @@ async function executeShellJob(job) {
const SHELL_JOB_TIMEOUT_MS = 5 * 60 * 1000
const timeoutMs = SHELL_JOB_TIMEOUT_MS
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). The allowlist
+ // includes AI CLIs, and the inherited PWD only happens to match PATHS.root
+ // when the server was started from its own checkout.
+ const childEnv = withSpawnCwdEnv(process.env, PATHS.root)
+ // Nearly every allowlisted command (`pm2`, `npm`, `gh`, `docker`, …) is a
+ // `.cmd`/`.exe` on Windows, and `spawn()` under `shell: false` does NOT apply
+ // PATHEXT — a bare `pm2` fails ENOENT (exit -4058) forever. Resolve against
+ // the child's own PATH and wrap a batch shim as `cmd.exe /c`. No-op on POSIX.
+ const { command: spawnCommand, args: spawnArgs } =
+ prepareCliSpawn(validation.baseCommand, validation.args || [], childEnv)
+
return new Promise((resolve, reject) => {
let killed = false
- const child = spawn(validation.baseCommand, validation.args || [], {
+ const child = spawn(spawnCommand, spawnArgs, {
cwd: PATHS.root,
- // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). The allowlist
- // includes AI CLIs, and the inherited PWD only happens to match PATHS.root
- // when the server was started from its own checkout.
- env: withSpawnCwdEnv(process.env, PATHS.root),
+ env: childEnv,
shell: false,
windowsHide: true
})
@@ -86,7 +95,12 @@ async function executeShellJob(job) {
const timer = setTimeout(() => {
if (child.exitCode !== null) return
killed = true
- child.kill('SIGKILL')
+ // Kill the TREE, not just the direct child. On Windows the spawn above
+ // is `cmd.exe /c <cmd> <args>`, so the actual command is a GRANDCHILD —
+ // and Windows has no process groups, so killing cmd.exe would orphan a
+ // hung `pm2`/`npm`/`docker` that then outlives the timeout forever.
+ // killProcessTree is taskkill /T /F there and a plain kill on POSIX.
+ killProcessTree(child, 'SIGKILL')
console.error(`⏰ Shell job timed out after ${timeoutMs}ms: ${job.name}`)
}, timeoutMs)
diff --git a/server/services/autonomousJobs/execution.shellSpawn.test.js b/server/services/autonomousJobs/execution.shellSpawn.test.js
new file mode 100644
index 0000000000..b2432e90d5
--- /dev/null
+++ b/server/services/autonomousJobs/execution.shellSpawn.test.js
@@ -0,0 +1,113 @@
+/**
+ * Windows shell-job spawn resolution.
+ *
+ * Every allowlisted shell-job command (`pm2`, `npm`, `gh`, `docker`, …) is a
+ * `.cmd`/`.exe` on Windows, and `spawn()` under `shell: false` does NOT apply
+ * PATHEXT — so a bare `pm2 jlist` failed with `spawn pm2 ENOENT` (exit -4058)
+ * on every run. The shipped "System Health Check" job runs exactly that, so a
+ * Windows install logged the failure every 15 minutes forever.
+ *
+ * These tests pin the fix: the command goes through `prepareCliSpawn` against
+ * the CHILD's env before `spawn()` sees it, and POSIX behavior is unchanged.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { EventEmitter } from 'events'
+
+const spawnMock = vi.fn()
+
+// Partial mock — other modules in this import graph (fileUtils) need the real
+// execFile/exec exports at load time.
+vi.mock('child_process', async (importOriginal) => ({
+ ...(await importOriginal()),
+ spawn: (...args) => spawnMock(...args),
+}))
+vi.mock('./store.js', () => ({
+ loadJobs: vi.fn(async () => ({ jobs: [{ id: 'job-1', name: 'System Health Check' }] })),
+ saveJobs: vi.fn(async () => {}),
+}))
+vi.mock('./crud.js', () => ({ recordJobExecution: vi.fn(async () => {}) }))
+
+const { executeShellJob } = await import('./execution.js')
+
+/** A child that exits 0 immediately, so executeShellJob resolves. */
+function fakeChild() {
+ const child = new EventEmitter()
+ child.stdout = new EventEmitter()
+ child.stderr = new EventEmitter()
+ child.exitCode = null
+ child.kill = vi.fn()
+ setImmediate(() => child.emit('close', 0, null))
+ return child
+}
+
+describe('executeShellJob — Windows CLI shim resolution', () => {
+ beforeEach(() => {
+ spawnMock.mockReset()
+ spawnMock.mockImplementation(() => fakeChild())
+ })
+ afterEach(() => vi.unstubAllEnvs())
+
+ it('spawns the command WITHOUT a shell (the injection guard stays intact)', async () => {
+ await executeShellJob({ id: 'job-1', name: 'System Health Check', command: 'pm2 jlist' })
+ const [, , opts] = spawnMock.mock.calls[0]
+ expect(opts.shell).toBe(false)
+ expect(opts.windowsHide).toBe(true)
+ })
+
+ it('resolves the command against the CHILD env, not process.env', async () => {
+ // The env handed to spawn must be the same object PATH was resolved from,
+ // so a PATH override in the child env is honored rather than silently
+ // resolved against a different PATH.
+ await executeShellJob({ id: 'job-1', name: 'System Health Check', command: 'pm2 jlist' })
+ const [, , opts] = spawnMock.mock.calls[0]
+ expect(opts.env).toBeTruthy()
+ // withSpawnCwdEnv pins PWD to the spawn cwd.
+ expect(opts.env.PWD).toBe(opts.cwd)
+ })
+
+ it('passes parsed args through to spawn', async () => {
+ await executeShellJob({ id: 'job-1', name: 'System Health Check', command: 'pm2 jlist' })
+ const [command, args] = spawnMock.mock.calls[0]
+ // On POSIX prepareCliSpawn is a no-op, so this is the bare pair. On Windows
+ // the pair may be rewritten to `cmd.exe /c <resolved.cmd> …` — in both
+ // cases the original argv must still be reachable in the final command line.
+ expect([command, ...args].join(' ')).toMatch(/pm2.*jlist/)
+ })
+
+ it('routes the spawn through prepareCliSpawn (source contract)', async () => {
+ // prepareCliSpawn is a pure filesystem-backed resolver that no-ops off
+ // win32, so a POSIX CI run can't observe the rewrite behaviorally. Pin the
+ // wiring instead: a future edit that reintroduces `spawn(validation.baseCommand)`
+ // would restore the ENOENT bug with every other test still green.
+ const { readFileSync } = await import('fs')
+ const { fileURLToPath } = await import('url')
+ const src = readFileSync(fileURLToPath(new URL('./execution.js', import.meta.url)), 'utf-8')
+ expect(src).toMatch(/import\s*\{[^}]*\bprepareCliSpawn\b[^}]*\}\s*from\s*'\.\.\/\.\.\/lib\/bufferedSpawn\.js'/)
+ expect(src).toMatch(
+ /const\s*\{\s*command:\s*spawnCommand,\s*args:\s*spawnArgs\s*\}\s*=\s*\n?\s*prepareCliSpawn\(\s*validation\.baseCommand,\s*validation\.args \|\| \[\],\s*childEnv\s*\)/
+ )
+ // The resolved pair must be what spawn() actually receives.
+ expect(src).toMatch(/spawn\(\s*spawnCommand,\s*spawnArgs,/)
+ })
+
+ it('kills the process TREE on timeout, not just the direct child', async () => {
+ // The Windows spawn is `cmd.exe /c <cmd> <args>`, so the real command is a
+ // grandchild; Windows has no process groups, so a bare child.kill() would
+ // orphan a hung pm2/npm/docker past the timeout. Pin the tree-kill wiring.
+ const { readFileSync } = await import('fs')
+ const { fileURLToPath } = await import('url')
+ const src = readFileSync(fileURLToPath(new URL('./execution.js', import.meta.url)), 'utf-8')
+ expect(src).toMatch(/import\s*\{[^}]*\bkillProcessTree\b[^}]*\}\s*from\s*'\.\.\/\.\.\/lib\/bufferedSpawn\.js'/)
+ expect(src).toMatch(/killProcessTree\(\s*child,\s*'SIGKILL'\s*\)/)
+ expect(src, 'the timeout path must not bare-kill the direct child')
+ .not.toMatch(/child\.kill\('SIGKILL'\)/)
+ })
+
+ it('still rejects a command outside the allowlist', async () => {
+ await expect(
+ executeShellJob({ id: 'job-1', name: 'bad', command: 'rm -rf /' })
+ ).rejects.toThrow(/Invalid shell command/)
+ expect(spawnMock).not.toHaveBeenCalled()
+ })
+})
diff --git a/server/services/brainJournal.test.js b/server/services/brainJournal.test.js
index 475c6a5ed4..08eeb31f82 100644
--- a/server/services/brainJournal.test.js
+++ b/server/services/brainJournal.test.js
@@ -393,8 +393,16 @@ describe('brainJournal', () => {
await journal.setJournalContent('2026-04-17', 'content-1');
await journal.setJournalContent('2026-04-17', 'content-2');
- // Wait for background queue to flush
- await new Promise((r) => setTimeout(r, 50));
+ // Poll for the background queue to drain rather than sleeping a flat
+ // 50ms: the two syncs sleep 10ms EACH and only run back-to-back because
+ // they are serialized, so a fixed budget that is fine locally leaves the
+ // second one mid-flight on a slower runner — the assertion then reads
+ // three entries and fails on the sequencing it is meant to prove.
+ const deadline = Date.now() + 5000;
+ while (callOrder.length < 4 && Date.now() < deadline) {
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise((r) => setTimeout(r, 5));
+ }
expect(callOrder).toEqual(['start-1', 'end-1', 'start-2', 'end-2']);
});
diff --git a/server/services/catalogIngestSources.test.js b/server/services/catalogIngestSources.test.js
index 590048da58..c235b1b665 100644
--- a/server/services/catalogIngestSources.test.js
+++ b/server/services/catalogIngestSources.test.js
@@ -258,7 +258,8 @@ describe('ingestFromVoice', () => {
expect(fsp.writeFile).toHaveBeenCalledTimes(1);
expect(mediaKey).toMatch(/^voice-memo-.*\.wav$/);
const writtenPath = fsp.writeFile.mock.calls[0][0];
- expect(writtenPath).toContain('/tmp/data/audio');
+ // Composed with path.join — accept either separator.
+ expect(writtenPath.split('\\').join('/')).toContain('/tmp/data/audio');
});
});
diff --git a/server/services/clinvar.test.js b/server/services/clinvar.test.js
index 7bc65623df..3624d2cfd0 100644
--- a/server/services/clinvar.test.js
+++ b/server/services/clinvar.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { posixPath as toPosix } from '../lib/testHelper.js';
const NOT_SYNCED_ERROR = 'ClinVar database not synced. Click "Sync ClinVar" first.';
const NO_GENOME_ERROR = 'No genome data uploaded.';
@@ -10,7 +11,7 @@ const fileStore = new Map();
vi.mock('../lib/fileUtils.js', () => ({
PATHS: { meatspace: '/mock/meatspace' },
ensureDir: vi.fn().mockResolvedValue(undefined),
- tryReadFile: vi.fn(async (path) => (fileStore.has(path) ? fileStore.get(path) : null)),
+ tryReadFile: vi.fn(async (path) => (fileStore.has(toPosix(path)) ? fileStore.get(toPosix(path)) : null)),
safeJSONParse: (raw, fallback) => {
try {
return JSON.parse(raw);
@@ -22,15 +23,15 @@ vi.mock('../lib/fileUtils.js', () => ({
vi.mock('fs/promises', () => ({
writeFile: vi.fn(async (path, data) => {
- fileStore.set(path, data);
+ fileStore.set(toPosix(path), data);
}),
unlink: vi.fn(async (path) => {
- if (!fileStore.has(path)) {
+ if (!fileStore.has(toPosix(path))) {
const err = new Error('ENOENT');
err.code = 'ENOENT';
throw err;
}
- fileStore.delete(path);
+ fileStore.delete(toPosix(path));
})
}));
diff --git a/server/services/cosAgentFeedback.test.js b/server/services/cosAgentFeedback.test.js
index ee68cfce97..fdd6fa561a 100644
--- a/server/services/cosAgentFeedback.test.js
+++ b/server/services/cosAgentFeedback.test.js
@@ -1,9 +1,10 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
+
const mockCosState = vi.hoisted(() => ({
// Use $TMPDIR (falls back to /tmp) rather than a hardcoded /private/tmp — the
// latter exists on macOS (where /tmp symlinks to it) but not on Linux CI.
- agentsDir: `${process.env.TMPDIR || '/tmp'}/portos-cos-feedback-test-${process.pid}`,
+ agentsDir: `${process.env.TMPDIR || process.env.TEMP || process.env.TMP || '/tmp'}/portos-cos-feedback-test-${process.pid}`,
state: null
}));
diff --git a/server/services/cosAgentIndex.merge.test.js b/server/services/cosAgentIndex.merge.test.js
index 8433541c85..4c36c0f801 100644
--- a/server/services/cosAgentIndex.merge.test.js
+++ b/server/services/cosAgentIndex.merge.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
import { mkdir, rm, writeFile, readFile } from 'fs/promises';
import { join } from 'path';
@@ -7,7 +8,7 @@ import { join } from 'path';
// AGENTS_DIR at a tmpdir so addAgentArchivesToIndex (#1650 receiver hook) never
// touches the real data/cos/agents index.
const mockCosState = vi.hoisted(() => ({
- agentsDir: `${process.env.TMPDIR || '/tmp'}/portos-cos-indexmerge-${process.pid}`,
+ agentsDir: `${process.env.TMPDIR || process.env.TEMP || process.env.TMP || '/tmp'}/portos-cos-indexmerge-${process.pid}`,
}));
vi.mock('./cosState.js', () => ({
diff --git a/server/services/cosAgentLifecycle.test.js b/server/services/cosAgentLifecycle.test.js
index 21c35a68e0..05b5689983 100644
--- a/server/services/cosAgentLifecycle.test.js
+++ b/server/services/cosAgentLifecycle.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
import { mkdir, rm, writeFile, readFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
@@ -9,7 +10,7 @@ const mockCosState = vi.hoisted(() => ({
// where `mkdir(recursive)` then tries to create `/private` at the root and
// hits EACCES. process.env is safe to read inside a vi.hoisted factory
// (imported bindings like `os.tmpdir` are not yet initialized at hoist time).
- agentsDir: `${process.env.TMPDIR || '/tmp'}/portos-cos-agents-test-${process.pid}`,
+ agentsDir: `${process.env.TMPDIR || process.env.TEMP || process.env.TMP || '/tmp'}/portos-cos-agents-test-${process.pid}`,
state: null
}));
@@ -32,7 +33,11 @@ const fsFailures = vi.hoisted(() => ({ dateBucketWritesFail: false }));
vi.mock('fs/promises', async (importOriginal) => {
const actual = await importOriginal();
- const failsFor = (p) => fsFailures.dateBucketWritesFail && /\/\d{4}-\d{2}-\d{2}\//.test(String(p));
+ // Accept either separator: the archive path is composed with path.join, so on
+ // Windows the date bucket reads '\2026-08-14\' and a '/'-only pattern never
+ // matched — the injected failure never fired and completeAgent RESOLVED,
+ // making this rollback test assert nothing.
+ const failsFor = (p) => fsFailures.dateBucketWritesFail && /[\\/]\d{4}-\d{2}-\d{2}[\\/]/.test(String(p));
return {
...actual,
rename: async (from, to, ...rest) => {
diff --git a/server/services/creativeDirector/recovery.test.js b/server/services/creativeDirector/recovery.test.js
index 276676faea..60ceaee562 100644
--- a/server/services/creativeDirector/recovery.test.js
+++ b/server/services/creativeDirector/recovery.test.js
@@ -5,7 +5,9 @@ const mockListProjects = vi.fn();
const mockUpdateScene = vi.fn();
const mockUpdateRun = vi.fn();
const mockUpdateProject = vi.fn();
+const mockUpdatePlanStep = vi.fn();
const mockAdvance = vi.fn();
+const mockAdvancePlanStep = vi.fn();
const mockListJobs = vi.fn();
const mockCancelJob = vi.fn();
const mockUpdateTask = vi.fn();
@@ -15,12 +17,21 @@ vi.mock('./local.js', () => ({
updateScene: (...args) => mockUpdateScene(...args),
updateRun: (...args) => mockUpdateRun(...args),
updateProject: (...args) => mockUpdateProject(...args),
+ updatePlanStep: (...args) => mockUpdatePlanStep(...args),
}));
vi.mock('./completionHook.js', () => ({
advanceAfterSceneSettled: (...args) => mockAdvance(...args),
}));
+// recovery.js pulls planAdvance in through a dynamic import. Left unmocked it
+// loads that module's whole real dependency graph on the first test that
+// reaches the orphan-cancel path — ~8s here in isolation, and past the 30s
+// timeout once the full suite is competing for CPU.
+vi.mock('./planAdvance.js', () => ({
+ advanceAfterPlanStepSettled: (...args) => mockAdvancePlanStep(...args),
+}));
+
vi.mock('../mediaJobQueue/index.js', () => ({
listJobs: (...args) => mockListJobs(...args),
cancelJob: (...args) => mockCancelJob(...args),
@@ -37,10 +48,12 @@ beforeEach(() => {
mockUpdateScene.mockReset().mockResolvedValue(undefined);
mockUpdateRun.mockReset().mockResolvedValue(undefined);
mockAdvance.mockReset().mockResolvedValue(undefined);
+ mockAdvancePlanStep.mockReset().mockResolvedValue(undefined);
mockListJobs.mockReset().mockReturnValue([]);
mockCancelJob.mockReset().mockResolvedValue({ ok: true, status: 'canceled' });
mockUpdateTask.mockReset().mockResolvedValue({ ok: true });
mockUpdateProject.mockReset().mockResolvedValue({ ok: true });
+ mockUpdatePlanStep.mockReset().mockResolvedValue(undefined);
});
describe('recoverInFlightProjects', () => {
diff --git a/server/services/creativeDirector/sceneEvaluator.test.js b/server/services/creativeDirector/sceneEvaluator.test.js
index 81764c8aa0..69a7553253 100644
--- a/server/services/creativeDirector/sceneEvaluator.test.js
+++ b/server/services/creativeDirector/sceneEvaluator.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { resolve as resolvePath } from 'path';
/**
* Tests for the server-side (local-vision) scene evaluator.
@@ -199,7 +200,12 @@ describe('evaluateSceneWithVision', () => {
expect(res.llm).toEqual({ provider: 'ollama', model: 'qwen2.5-vl' });
// Frames passed as absolute paths under the thumbnails dir.
const call = mocks.runPromptThroughProvider.mock.calls[0][0];
- expect(call.screenshots).toEqual(['/data/video-thumbnails/job-1-f1.jpg', '/data/video-thumbnails/job-1-f2.jpg']);
+ // resolve()d by the evaluator, so it carries a drive letter on Windows —
+ // build the expectation the same way rather than pinning a POSIX literal.
+ expect(call.screenshots).toEqual([
+ resolvePath('/data/video-thumbnails/job-1-f1.jpg'),
+ resolvePath('/data/video-thumbnails/job-1-f2.jpg'),
+ ]);
expect(call.source).toBe('cd-scene-evaluate');
});
@@ -221,7 +227,7 @@ describe('evaluateSceneWithVision', () => {
mocks.runPromptThroughProvider.mockResolvedValue({ text: '{"accepted": true}', model: 'qwen2.5-vl', provider: OLLAMA });
await evaluateSceneWithVision(project, { ...scene, evaluationFrames: [] });
const call = mocks.runPromptThroughProvider.mock.calls[0][0];
- expect(call.screenshots).toEqual(['/data/video-thumbnails/job-1.jpg']);
+ expect(call.screenshots).toEqual([resolvePath('/data/video-thumbnails/job-1.jpg')]);
});
});
diff --git a/server/services/digital-twin-avatar-bio.test.js b/server/services/digital-twin-avatar-bio.test.js
index d59342d50e..6d7154c8ac 100644
--- a/server/services/digital-twin-avatar-bio.test.js
+++ b/server/services/digital-twin-avatar-bio.test.js
@@ -71,7 +71,11 @@ const DOCS = {
vi.mock('fs/promises', () => ({
readFile: vi.fn(async (path) => {
- const name = String(path).split('/').pop();
+ // Split on BOTH separators: the service joins DIGITAL_TWIN_DIR with
+ // path.join, so on Windows this is '\twin\SOUL.md' and a '/'-only split
+ // returns the whole string — every doc lookup then missed and the bio fell
+ // back to its "no data yet" placeholders.
+ const name = String(path).split(/[\\/]/).pop();
if (DOCS[name] != null) return DOCS[name];
throw new Error('ENOENT');
}),
diff --git a/server/services/games/artwork.test.js b/server/services/games/artwork.test.js
index 62afa29cb0..3768b5f573 100644
--- a/server/services/games/artwork.test.js
+++ b/server/services/games/artwork.test.js
@@ -6,8 +6,18 @@ const state = vi.hoisted(() => ({
destination: null,
}));
+// Normalize separators AND drop the drive letter at every mock boundary. The
+// service composes these with path.join and anchors the repo with
+// resolve(app.repoPath) — on Windows that yields H:\app\game\… — while the
+// fixtures below are spelled POSIX, so every read/write missed and the service
+// reported the artwork as missing.
+const toPosix = (v) => (typeof v === 'string'
+ ? v.split('\\').join('/').replace(/^[A-Za-z]:/, '')
+ : v);
+
vi.mock('fs/promises', () => ({
- readFile: vi.fn(async (path) => {
+ readFile: vi.fn(async (rawPath) => {
+ const path = toPosix(rawPath);
if (path === '/gallery/title.png') return state.source;
if (path === '/app/game/assets/art/title.png' && state.destination) return state.destination;
throw Object.assign(new Error(`ENOENT: ${path}`), { code: 'ENOENT' });
@@ -17,10 +27,11 @@ vi.mock('fs/promises', () => ({
vi.mock('../../lib/fileUtils.js', () => ({
PATHS: { images: '/gallery' },
- atomicWrite: vi.fn(async (path, bytes) => {
+ atomicWrite: vi.fn(async (rawPath, bytes) => {
+ const path = toPosix(rawPath);
if (path === '/app/game/assets/art/title.png') state.destination = Buffer.from(bytes);
}),
- isPathInsideDir: vi.fn((dir, candidate) => candidate.startsWith(`${dir}/`)),
+ isPathInsideDir: vi.fn((dir, candidate) => toPosix(candidate).startsWith(`${toPosix(dir)}/`)),
}));
vi.mock('../apps.js', () => ({
diff --git a/server/services/games/compile.test.js b/server/services/games/compile.test.js
index d2a280c394..8fd956be66 100644
--- a/server/services/games/compile.test.js
+++ b/server/services/games/compile.test.js
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { posixPath as toPosix } from '../../lib/testHelper.js';
const state = vi.hoisted(() => ({
game: null,
@@ -20,11 +21,15 @@ vi.mock('./store.js', () => ({
vi.mock('../../lib/fileUtils.js', () => ({
PATHS: { images: '/tmp/images', music: '/tmp/music' },
atomicWrite: vi.fn(async () => { state.manifestExists = true; }),
- pathExists: vi.fn(async (path) =>
- path.includes('/manifests/') ? state.manifestExists : true),
+ pathExists: vi.fn(async (rawPath) =>
+ toPosix(rawPath).includes('/manifests/') ? state.manifestExists : true),
readJSONFile: vi.fn(async () => null),
sha256Text: vi.fn((value) => `text-sha:${String(value).length}`),
- sha256File: vi.fn(async (path) => {
+ sha256File: vi.fn(async (rawPath) => {
+ // compile.js builds these with path.join, so on Windows the separators are
+ // backslashes and every '/segment/' matcher below silently takes the wrong
+ // branch — routing the manifest through the sprite/audio cases.
+ const path = toPosix(rawPath);
if (path.includes('/manifests/')) return state.manifestSha256;
const spriteId = path.match(/\/sprites\/([^/]+)\//)?.[1];
if (path.endsWith('title.png')) return 'title-art-sha';
diff --git a/server/services/games/musicPublish.test.js b/server/services/games/musicPublish.test.js
index 2fe69a229b..172b38214f 100644
--- a/server/services/games/musicPublish.test.js
+++ b/server/services/games/musicPublish.test.js
@@ -7,8 +7,21 @@ const state = vi.hoisted(() => ({
destination: null,
}));
+// Normalize separators at every mock boundary. The service composes these
+// paths with path.join, so on Windows it asks for '\\app\\game\\assets\\music\\…'
+// while the fixtures below are spelled POSIX — the reads then missed, and the
+// service reported the audio as "missing or unreadable" instead of publishing.
+// The leading drive letter goes too: publishCore anchors the repo with
+// resolve(app.repoPath), and resolve('/app') on Windows yields 'H:\app' — the
+// drive of the current working directory. These fixtures describe a
+// POSIX-rooted repo, so drop the drive to compare the part that is meaningful.
+const toPosix = (v) => (typeof v === 'string'
+ ? v.split('\\').join('/').replace(/^[A-Za-z]:/, '')
+ : v);
+
vi.mock('fs/promises', () => ({
- readFile: vi.fn(async (path) => {
+ readFile: vi.fn(async (rawPath) => {
+ const path = toPosix(rawPath);
if (path === '/library/example-theme.ogg') return state.source;
if (path === '/app/game/assets/music/example-theme.ogg' && state.destination) return state.destination;
throw Object.assign(new Error(`ENOENT: ${path}`), { code: 'ENOENT' });
@@ -18,10 +31,11 @@ vi.mock('fs/promises', () => ({
vi.mock('../../lib/fileUtils.js', () => ({
PATHS: { music: '/library' },
- atomicWrite: vi.fn(async (path, bytes) => {
+ atomicWrite: vi.fn(async (rawPath, bytes) => {
+ const path = toPosix(rawPath);
if (path === '/app/game/assets/music/example-theme.ogg') state.destination = Buffer.from(bytes);
}),
- isPathInsideDir: vi.fn((dir, candidate) => candidate.startsWith(`${dir}/`)),
+ isPathInsideDir: vi.fn((dir, candidate) => toPosix(candidate).startsWith(`${toPosix(dir)}/`)),
}));
vi.mock('../apps.js', () => ({
diff --git a/server/services/imageGen/cleanGpu.test.js b/server/services/imageGen/cleanGpu.test.js
index 9e74e33310..154d585841 100644
--- a/server/services/imageGen/cleanGpu.test.js
+++ b/server/services/imageGen/cleanGpu.test.js
@@ -74,7 +74,10 @@ describe('enqueueGpuClean', () => {
// No regen lineage — a clean render is not a gallery variant of anything.
expect(params.regenOf).toBeUndefined();
// The init image is staged on disk and pointed at by the params.
- expect(params.initImagePath.startsWith(TMP)).toBe(true);
+ // TMP is spelled POSIX but the service composes the staged path with
+ // path.join, so on Windows it comes back '\tmp\…' — normalize before the
+ // prefix check rather than pinning the separator.
+ expect(params.initImagePath.split('\\').join('/').startsWith(TMP)).toBe(true);
expect(existsSync(params.initImagePath)).toBe(true);
// A clean-meta sidecar records that no mask was staged.
const clean = readdirSync(TMP).find((f) => f.endsWith('-clean.json'));
diff --git a/server/services/imageGen/grok.test.js b/server/services/imageGen/grok.test.js
index ba3536803e..678354568e 100644
--- a/server/services/imageGen/grok.test.js
+++ b/server/services/imageGen/grok.test.js
@@ -1,4 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { posixPath } from '../../lib/testHelper.js';
+
import { mkdir, writeFile, rm, readFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
@@ -23,11 +25,23 @@ const makeFakeChild = () => {
};
vi.mock('child_process', async (importOriginal) => {
const actual = await importOriginal();
+ const { readFileSync } = await import('fs');
return {
...actual,
spawn: vi.fn((bin, args) => {
const child = makeFakeChild();
- spawnCalls.push({ bin, args, child });
+ // On Windows grok cannot read /dev/stdin, so prepareGrokPromptFile writes
+ // the prompt to a temp file and rewrites --prompt-file to point at it —
+ // then unlinks that file once the run closes. Capture its contents HERE,
+ // between the write and the cleanup, so promptOf() can report the prompt
+ // on both platforms instead of reading an always-empty stdin buffer.
+ let promptFromFile = null;
+ const pfIdx = args?.indexOf?.('--prompt-file');
+ const pfPath = pfIdx >= 0 ? args[pfIdx + 1] : null;
+ if (pfPath && pfPath !== '/dev/stdin') {
+ try { promptFromFile = readFileSync(pfPath, 'utf8'); } catch { promptFromFile = null; }
+ }
+ spawnCalls.push({ bin, args, child, promptFromFile });
return child;
}),
};
@@ -51,7 +65,9 @@ const { imageGenEvents } = await import('../imageGenEvents.js');
const flush = () => new Promise((r) => setImmediate(r));
const stagingPathFor = (jobId) => join(tmpdir(), `portos-grok-${jobId}`, 'output.png');
-const promptOf = (i = 0) => spawnCalls[i].child.stdin.written;
+// POSIX delivers the prompt over stdin; Windows through the rewritten
+// --prompt-file temp file (captured at spawn time above).
+const promptOf = (i = 0) => spawnCalls[i].promptFromFile ?? spawnCalls[i].child.stdin.written;
const closeChild = async (i = 0, code = 1) => {
spawnCalls[i].child.exitCode = code;
spawnCalls[i].child.emit('close', code, null);
@@ -101,7 +117,12 @@ describe('grok provider — generateImage', () => {
// prompt via /dev/stdin (POSIX), no --model pin.
expect(args).toEqual(expect.arrayContaining(['--output-format', 'plain']));
expect(args).toEqual(expect.arrayContaining(['--permission-mode', 'bypassPermissions']));
- expect(args).toEqual(expect.arrayContaining(['--prompt-file', '/dev/stdin']));
+ // Windows has no /dev/stdin, so prepareGrokPromptFile rewrites the sentinel
+ // to a real temp file. Assert the per-platform value — both ship.
+ expect(args).toEqual(expect.arrayContaining([
+ '--prompt-file',
+ process.platform === 'win32' ? expect.stringMatching(/grok-prompt-.*\.txt$/) : '/dev/stdin',
+ ]));
expect(args).not.toContain('--model');
// The agent prompt names the tool, the image prompt, and the directed path.
const prompt = promptOf();
@@ -132,7 +153,7 @@ describe('grok provider — generateImage', () => {
it('honors grokPath override (custom binary)', async () => {
await grok.generateImage({ prompt: 'a fox', grokPath: '/opt/custom/grok' });
- expect(spawnCalls[0].bin).toBe('/opt/custom/grok');
+ expect(posixPath(spawnCalls[0].bin)).toBe('/opt/custom/grok');
await closeChild();
});
@@ -193,7 +214,7 @@ describe('grok provider — generateImage', () => {
it('drops a reference path that escapes the gallery (defense-in-depth)', async () => {
await grok.generateImage({ prompt: 'a fox', referenceImagePaths: ['/etc/passwd'] });
const prompt = promptOf();
- expect(prompt).not.toContain('/etc/passwd');
+ expect(posixPath(prompt)).not.toContain('/etc/passwd');
// Nothing survived, so it falls back to plain text-to-image.
expect(prompt).not.toContain('image_edit');
await closeChild();
@@ -203,7 +224,7 @@ describe('grok provider — generateImage', () => {
await grok.generateImage({ prompt: 'cover art', initImagePath: '/etc/passwd', initImageStrength: 0.2 });
const prompt = promptOf();
expect(prompt).not.toContain('image_edit');
- expect(prompt).not.toContain('/etc/passwd');
+ expect(posixPath(prompt)).not.toContain('/etc/passwd');
await closeChild();
});
diff --git a/server/services/imageTo3d/models.test.js b/server/services/imageTo3d/models.test.js
index 27948f9053..fb3dd17560 100644
--- a/server/services/imageTo3d/models.test.js
+++ b/server/services/imageTo3d/models.test.js
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { posixPath } from '../../lib/testHelper.js';
vi.mock('node:fs/promises', async (importOriginal) => ({
...(await importOriginal()),
@@ -130,14 +131,15 @@ describe('image-to-3D model orchestration', () => {
expect(started.status).toBe('generating');
await vi.waitFor(() => expect(current.status).toBe('ready'));
- expect(runTrellis2Generate).toHaveBeenCalledWith(expect.objectContaining({
- imagePath: '/mock/data/images/example.png',
- outputPath: expect.stringMatching(/image-to-3d\/image3d-example\/model\.glb$/),
- // #3032: the resolved HF token (settings-stored included) rides into the child,
- // merged over process.env — without it, gated DINOv3/RMBG-2.0 pulls 401.
- env: expect.objectContaining({ HF_TOKEN: 'hf_from_store', HUGGINGFACE_HUB_TOKEN: 'hf_from_store' }),
- }));
- expect(current.assetPath).toBe('/data/image-to-3d/image3d-example/model.glb');
+ // Read the call back and normalize its paths — matchers compare the raw
+ // received value, which is backslash-separated on Windows.
+ const [generateArgs] = runTrellis2Generate.mock.calls[0];
+ expect(posixPath(generateArgs.imagePath)).toBe('/mock/data/images/example.png');
+ expect(posixPath(generateArgs.outputPath)).toMatch(/image-to-3d\/image3d-example\/model\.glb$/);
+ // #3032: the resolved HF token (settings-stored included) rides into the child,
+ // merged over process.env — without it, gated DINOv3/RMBG-2.0 pulls 401.
+ expect(generateArgs.env).toMatchObject({ HF_TOKEN: 'hf_from_store', HUGGINGFACE_HUB_TOKEN: 'hf_from_store' });
+ expect(posixPath(current.assetPath)).toBe('/data/image-to-3d/image3d-example/model.glb');
expect(current.generationOperationId).toBeNull();
expect(current.runs.at(-1)).toMatchObject({ status: 'completed', percent: 100 });
});
@@ -208,10 +210,12 @@ describe('image-to-3D model orchestration', () => {
// The killed child settles; executeRender's finally then removes the orphaned dir.
rejectRender(Object.assign(new Error('killed'), { code: 'TRELLIS2_GENERATE_FAILED' }));
- await vi.waitFor(() => expect(rm).toHaveBeenCalledWith(
- '/mock/data/image-to-3d/image3d-example',
- expect.objectContaining({ recursive: true, force: true }),
- ));
+ await vi.waitFor(() => {
+ expect(rm).toHaveBeenCalled();
+ const [target, opts] = rm.mock.calls.at(-1);
+ expect(posixPath(target)).toBe('/mock/data/image-to-3d/image3d-example');
+ expect(opts).toMatchObject({ recursive: true, force: true });
+ });
});
it('terminates a render whose delete landed before the kill handle was registered', async () => {
@@ -265,9 +269,7 @@ describe('image-to-3D model orchestration', () => {
...draftRecord(), status: 'ready', name: 'My Beacon', assetPath: '/data/image-to-3d/image3d-example/model.glb',
});
const asset = await getModelAsset('image3d-example');
- expect(asset).toMatchObject({
- path: expect.stringMatching(/image-to-3d\/image3d-example\/model\.glb$/),
- filename: 'my-beacon.glb',
- });
+ expect(posixPath(asset.path)).toMatch(/image-to-3d\/image3d-example\/model\.glb$/);
+ expect(asset.filename).toBe('my-beacon.glb');
});
});
diff --git a/server/services/imageTo3d/trellis2GenerateRunner.test.js b/server/services/imageTo3d/trellis2GenerateRunner.test.js
index a0a20b70f2..977e5359eb 100644
--- a/server/services/imageTo3d/trellis2GenerateRunner.test.js
+++ b/server/services/imageTo3d/trellis2GenerateRunner.test.js
@@ -4,8 +4,16 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { trellis2GenerateRunnerScript } from './trellis2.js';
+import { resolveTestPython } from '../../lib/testHelper.js';
-describe('trellis2GenerateRunner', () => {
+// Probe for an interpreter that actually runs rather than assuming `python3`:
+// on Windows that name is absent and `python` is a Store alias stub that exists
+// but fails, so a hardcoded name turns "no Python here" into an opaque
+// "Command failed" (see resolveTestPython).
+
+const pyBin = resolveTestPython();
+
+describe.skipIf(!pyBin)('trellis2GenerateRunner', () => {
it('preserves direct-script imports while exposing the 4K texture size', () => {
const fixtureDir = mkdtempSync(join(tmpdir(), 'portos-trellis2-runner-'));
const generateScript = join(fixtureDir, 'generate.py');
@@ -22,7 +30,7 @@ describe('trellis2GenerateRunner', () => {
'',
].join('\n'));
- const output = execFileSync('python3', [
+ const output = execFileSync(pyBin, [
trellis2GenerateRunnerScript(),
generateScript,
'--texture-size',
diff --git a/server/services/mediaAnnotations.test.js b/server/services/mediaAnnotations.test.js
index 526216aeef..41a508ae3a 100644
--- a/server/services/mediaAnnotations.test.js
+++ b/server/services/mediaAnnotations.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { posixPath as toPosix } from '../lib/testHelper.js';
const fileStore = new Map();
@@ -6,8 +7,8 @@ vi.mock('../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
- atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
- readJSONFile: vi.fn(async (path, fallback) => fileStore.has(path) ? fileStore.get(path) : fallback),
+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(toPosix(path), data); }),
+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(toPosix(path)) ? fileStore.get(toPosix(path)) : fallback)),
}));
// Stable identity for tests — bypass the disk-backed instances service.
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 352123005c..e2506219ee 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -176,6 +176,14 @@ async function resolveLiveParams(job, safeParams) {
}
export const mediaJobEvents = new EventEmitter();
+// Boot already wires 11 permanent `completed` hooks (universe-builder, catalog
+// image-attach, writers-room, music-video scene image/video, music bed, sprite
+// references, scene frames, and the comicPages/storyboards/seasonCover filename
+// hooks), which trips Node's default limit of 10 and prints a bogus
+// MaxListenersExceededWarning on every start. These are long-lived subscribers,
+// not a leak; per-job waiters add more on top. Matches the caps the sibling
+// emitters already set (imageGenEvents 200, videoGenEvents 50).
+mediaJobEvents.setMaxListeners(100);
// GPU lane: serialized — `running` holds at most one job (the MLX runtime can't
// share VRAM). Codex lane: up to `codexParallelLimit` jobs in `cloudRunning[]`
diff --git a/server/services/mediaModelInstall.test.js b/server/services/mediaModelInstall.test.js
index 918875000a..61da2ad646 100644
--- a/server/services/mediaModelInstall.test.js
+++ b/server/services/mediaModelInstall.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
vi.mock('../lib/hfToken.js', () => ({ getHfToken: vi.fn(async () => '') }));
vi.mock('../lib/mediaModels.js', () => ({ addUserModelEntry: vi.fn((entry) => entry) }));
@@ -12,7 +12,24 @@ const mockFetch = (body) => vi.fn(async () => ({
text: async () => JSON.stringify(body),
}));
-beforeEach(() => { vi.clearAllMocks(); });
+// addModelFromHuggingface reads process.platform per call and REFUSES a video
+// add on Windows (the Windows render path loads a fixed built-in model and
+// cannot use a custom HF repo). These cases assert the non-Windows contract,
+// so pin the platform rather than letting the host decide — otherwise the
+// suite fails on a Windows runner for a reason it is not testing. The refusal
+// itself gets its own case below.
+const ORIGINAL_PLATFORM = Object.getOwnPropertyDescriptor(process, 'platform');
+const pinPlatform = (value) =>
+ Object.defineProperty(process, 'platform', { ...ORIGINAL_PLATFORM, value });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ pinPlatform('darwin');
+});
+
+afterEach(() => {
+ Object.defineProperty(process, 'platform', ORIGINAL_PLATFORM);
+});
describe('addModelFromHuggingface', () => {
it('classifies an LTX safetensors repo, builds a video entry, and registers it', async () => {
@@ -68,4 +85,35 @@ describe('addModelFromHuggingface', () => {
);
expect(result.entry).toMatchObject({ runner: 'qwen', source: 'user' });
});
+
+ describe('on Windows', () => {
+ beforeEach(() => pinPlatform('win32'));
+
+ it('refuses a custom VIDEO model, naming image adds as the supported path', async () => {
+ const fetchImpl = mockFetch({
+ id: 'notapalindrome/ltx23-mlx-av-q4',
+ siblings: [{ rfilename: 'model.safetensors' }],
+ tags: ['ltx-video'],
+ });
+ await expect(addModelFromHuggingface(
+ { url: 'notapalindrome/ltx23-mlx-av-q4' },
+ { fetchImpl },
+ )).rejects.toThrow(/can't be added on Windows/);
+ expect(addUserModelEntry).not.toHaveBeenCalled();
+ });
+
+ it('still allows a custom IMAGE model', async () => {
+ const fetchImpl = mockFetch({
+ id: 'someone/custom',
+ siblings: [{ rfilename: 'model.safetensors' }],
+ tags: [],
+ });
+ const result = await addModelFromHuggingface(
+ { url: 'someone/custom', kind: 'image', runner: 'qwen' },
+ { fetchImpl },
+ );
+ expect(result.kind).toBe('image');
+ expect(addUserModelEntry).toHaveBeenCalled();
+ });
+ });
});
diff --git a/server/services/mediaSketches.test.js b/server/services/mediaSketches.test.js
index 9296c4e634..fcdcfb5daa 100644
--- a/server/services/mediaSketches.test.js
+++ b/server/services/mediaSketches.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { posixPath } from '../lib/testHelper.js';
const fileStore = new Map();
@@ -58,7 +59,7 @@ describe('mediaSketches service', () => {
expect(await svc.getSketchPngPath(KEY)).toBeNull();
await svc.saveSketch(KEY, { width: 10, height: 10, strokes: sampleStrokes, png: PNG_DATA_URL });
const path = await svc.getSketchPngPath(KEY);
- expect(path).toBe('/mock/data/media-sketches/aW1hZ2U6Zm9vLnBuZw.png');
+ expect(posixPath(path)).toBe('/mock/data/media-sketches/aW1hZ2U6Zm9vLnBuZw.png');
// A vectors-only re-save drops the PNG, so the path resolver goes null again.
await svc.saveSketch(KEY, { width: 10, height: 10, strokes: sampleStrokes });
expect(await svc.getSketchPngPath(KEY)).toBeNull();
diff --git a/server/services/messageDrafts.test.js b/server/services/messageDrafts.test.js
index 4e0f5ea696..6b2d45330f 100644
--- a/server/services/messageDrafts.test.js
+++ b/server/services/messageDrafts.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { posixPath as toPosix } from '../lib/testHelper.js';
const fileStore = new Map();
@@ -8,9 +9,9 @@ vi.mock('../lib/uuid.js', () => {
});
vi.mock('../lib/fileUtils.js', () => ({
- tryReadFile: vi.fn(async (path) => fileStore.has(path) ? fileStore.get(path) : null),
+ tryReadFile: vi.fn(async (path) => fileStore.has(toPosix(path)) ? fileStore.get(toPosix(path)) : null),
atomicWrite: vi.fn(async (path, data) => {
- fileStore.set(path, typeof data === 'string' ? data : JSON.stringify(data, null, 2));
+ fileStore.set(toPosix(path), typeof data === 'string' ? data : JSON.stringify(data, null, 2));
}),
ensureDir: vi.fn().mockResolvedValue(undefined),
PATHS: { messages: '/mock/messages' },
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index 43c1cb66e2..ebfd6a9edb 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -304,7 +304,11 @@ async function runServiceStart(controller) {
async function startPersistentService() {
const controller = await getServiceController()
if (!controller.supported) {
- return { success: false, running: await checkOllamaAvailable(true), error: 'No supported Ollama background service manager found.' }
+ // `unsupported` marks an expected platform capability gap (Windows ships no
+ // brew/systemd; so does a Linux box without systemd) rather than a failed
+ // start attempt, so `ensureRunning` can fall back to a foreground
+ // `ollama serve` quietly instead of warning on every boot.
+ return { success: false, unsupported: true, running: await checkOllamaAvailable(true), error: 'No supported Ollama background service manager found.' }
}
resetAvailabilityCache()
@@ -346,7 +350,9 @@ async function startPersistentService() {
async function stopPersistentService() {
const controller = await getServiceController()
if (!controller.supported) {
- return { success: false, running: await checkOllamaAvailable(true), error: 'No supported Ollama background service manager found.' }
+ // Mirrors startPersistentService — same capability gap, same flag, so a
+ // caller can tell "nothing to stop on this platform" from a real failure.
+ return { success: false, unsupported: true, running: await checkOllamaAvailable(true), error: 'No supported Ollama background service manager found.' }
}
const [cmd, args] = controller.stop
@@ -385,7 +391,13 @@ async function ensureRunning({ preferPersistent = false } = {}) {
if (preferPersistent) {
const serviceResult = await startPersistentService()
if (serviceResult.success) return serviceResult
- console.warn(`⚠️ Failed to start Ollama as a background service: ${serviceResult.error}`)
+ // Only a real start FAILURE deserves a warning. `unsupported` just means
+ // this platform has no service manager to try — the normal case on Windows,
+ // where warning made every boot look broken. The `startServer()` fallback
+ // below is the intended path there, not a degraded one.
+ if (!serviceResult.unsupported) {
+ console.warn(`⚠️ Failed to start Ollama as a background service: ${serviceResult.error}`)
+ }
}
return startServer()
}
diff --git a/server/services/referenceRepos.test.js b/server/services/referenceRepos.test.js
index 807023e0cc..d91461a467 100644
--- a/server/services/referenceRepos.test.js
+++ b/server/services/referenceRepos.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { posixPath as toPosix } from '../lib/testHelper.js';
// ─── mocks (must precede the import under test) ──────────────────────────────
@@ -56,8 +57,8 @@ vi.mock('./taskPromptService.js', () => ({
const existsMock = vi.fn(() => false);
const statMock = vi.fn(() => ({ isDirectory: () => true }));
vi.mock('fs', () => ({
- existsSync: (p) => existsMock(p),
- statSync: (p) => statMock(p),
+ existsSync: (p) => existsMock(toPosix(p)),
+ statSync: (p) => statMock(toPosix(p)),
}));
// ─── module under test (after mocks) ─────────────────────────────────────────
diff --git a/server/services/sharing/annotationsSync.test.js b/server/services/sharing/annotationsSync.test.js
index cae2cc107f..474e1042bb 100644
--- a/server/services/sharing/annotationsSync.test.js
+++ b/server/services/sharing/annotationsSync.test.js
@@ -1,16 +1,18 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { posixPath as toPosix } from '../../lib/testHelper.js';
// Mock store for atomicWrite + readJSONFile so we can inspect record writes.
const fileStore = new Map();
+
const writeCalls = [];
vi.mock('../../lib/fileUtils.js', () => ({
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => {
- fileStore.set(path, data);
+ fileStore.set(toPosix(path), data);
writeCalls.push({ path, data });
}),
- readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),
+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(toPosix(path)) ? fileStore.get(toPosix(path)) : fallback)),
PATHS: { data: '/mock/data' },
}));
diff --git a/server/services/sprites/walkFrames.test.js b/server/services/sprites/walkFrames.test.js
index a9fb5ed2d9..22017b4b56 100644
--- a/server/services/sprites/walkFrames.test.js
+++ b/server/services/sprites/walkFrames.test.js
@@ -8,6 +8,7 @@
*/
import { describe, it, expect, vi, afterAll } from 'vitest';
+import { posixPath } from '../../lib/testHelper.js';
import { mkdtempSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -146,7 +147,7 @@ describe('verifyPackagedFrames — byte mode (compile gate)', () => {
expect(frameBytes).toHaveLength(8);
expect(frameBytes[0].toString()).toBe(`frame-${id}-0`);
// Read-once-verify-in-memory: every frame read exactly once, none twice.
- const frameReads = readCalls.filter((p) => p.includes('/frames/'));
+ const frameReads = readCalls.filter((p) => posixPath(p).includes('/frames/'));
expect(frameReads).toHaveLength(8);
expect(new Set(frameReads).size).toBe(8);
});
diff --git a/server/services/supersededLedger.test.js b/server/services/supersededLedger.test.js
index 57539bd50d..1fdd930abb 100644
--- a/server/services/supersededLedger.test.js
+++ b/server/services/supersededLedger.test.js
@@ -8,6 +8,8 @@
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { posixPath } from '../lib/testHelper.js';
+import { join as joinPath } from 'path';
const files = new Map();
vi.mock('../lib/fileUtils.js', () => ({
@@ -22,7 +24,8 @@ import {
isVerdictFresh, partitionSuperseded, formatSupersededForPrompt, recordVerdictInstruction
} from './supersededLedger.js';
-const PATH = '/repo/data/cos/branch-reconcile-verdicts.json';
+// join(), not a literal: the service composes this with path.join.
+const PATH = joinPath('/repo/data/cos', 'branch-reconcile-verdicts.json');
const entry = (over = {}) => ({
branch: 'cos/task-x/agent-dead',
@@ -50,7 +53,7 @@ beforeEach(() => files.clear());
describe('ledgerPath', () => {
it('lands in the install\'s cos data dir', () => {
expect(ledgerPath()).toBe(PATH);
- expect(ledgerPath('/other/cos')).toBe('/other/cos/branch-reconcile-verdicts.json');
+ expect(posixPath(ledgerPath('/other/cos'))).toBe('/other/cos/branch-reconcile-verdicts.json');
});
});
diff --git a/server/services/taskPromptService.test.js b/server/services/taskPromptService.test.js
index 53e82b431f..5a319bbdee 100644
--- a/server/services/taskPromptService.test.js
+++ b/server/services/taskPromptService.test.js
@@ -15,7 +15,9 @@ describe('taskPromptService {worktreesRoot} substitution', () => {
it('resolves {worktreesRoot} to PATHS.worktrees (PortOS shared dir), leaving no literal placeholder', async () => {
// PATHS.worktrees is PortOS's own shared worktrees dir — an absolute path
// ending in data/cos/worktrees — NOT a repo-relative one.
- expect(PATHS.worktrees).toMatch(/\/data\/cos\/worktrees$/);
+ // Accept either separator: PATHS.worktrees is composed with path.join, so
+ // it ends in `data\cos\worktrees` on Windows.
+ expect(PATHS.worktrees).toMatch(/[\\/]data[\\/]cos[\\/]worktrees$/);
const out = await getTaskPrompt('claim-issue');
expect(out).toBe(`before ${PATHS.worktrees}/claim-x after`);
diff --git a/server/services/tools.test.js b/server/services/tools.test.js
index 111ebcf07a..3e56bdb4b6 100644
--- a/server/services/tools.test.js
+++ b/server/services/tools.test.js
@@ -19,7 +19,9 @@ vi.mock('../lib/fileUtils.js', () => ({
atomicWrite: vi.fn().mockResolvedValue(undefined),
PATHS: { tools: '/fake/tools' },
readJSONFile: vi.fn(async (path) => {
- const filename = path.split('/').pop();
+ // tools.js composes this with path.join, so split on either separator —
+ // a '/'-only split returns the whole Windows path and misses every key.
+ const filename = path.split(/[\\/]/).pop();
return mockToolFiles.get(filename) ?? null;
}),
}));
diff --git a/server/services/universeBuilderCollectionHook.test.js b/server/services/universeBuilderCollectionHook.test.js
index f8f3a24d61..31c1f32e8f 100644
--- a/server/services/universeBuilderCollectionHook.test.js
+++ b/server/services/universeBuilderCollectionHook.test.js
@@ -47,7 +47,17 @@ async function waitFor(predicate, { timeoutMs = 2000, intervalMs = 5 } = {}) {
// `await` so async predicates (e.g. getUniverse reads) resolve to a real
// boolean — a bare Promise is always truthy and would short-circuit. Sync
// boolean predicates pass through `await` unchanged.
- if (await predicate()) return;
+ //
+ // A throwing predicate counts as "not true yet", not as a failure: the
+ // sidecar predicates below read a file the hook has not written on the
+ // first poll, and letting that ENOENT escape aborted the wait on the very
+ // condition it exists to wait for. Reproduces only when the hook is slower
+ // than the first poll, i.e. under full-suite load.
+ try {
+ if (await predicate()) return;
+ } catch {
+ // fall through to the next poll
+ }
await new Promise((r) => setTimeout(r, intervalMs));
}
throw new Error('waitFor: predicate never became true');
@@ -377,9 +387,17 @@ describe('universeBuilderCollectionHook', () => {
},
});
- // Untracked run, so synchronize on the observable side effect (the sidecar
- // enrich) rather than activeRuns draining — which is already empty here.
- await waitFor(() => readSidecar(filename).universeName === 'StyleVerse');
+ // Untracked run, so synchronize on the observable side effects rather than
+ // activeRuns draining — which is already empty here. Wait on BOTH the
+ // collection add and the sidecar enrich: the hook performs them
+ // independently and in no guaranteed order, so gating on the sidecar alone
+ // let the collection assertion below run before the item had landed (green
+ // locally, red on the Windows CI runner).
+ await waitFor(async () => {
+ if (readSidecar(filename).universeName !== 'StyleVerse') return false;
+ const pending = await collections.getCollection(c.id);
+ return pending.items.some((it) => it.kind === 'image' && it.ref === filename);
+ });
expect(hook.__testing.getActiveRuns().size).toBe(0);
const col = await collections.getCollection(c.id);
expect(col.items.some((it) => it.kind === 'image' && it.ref === filename)).toBe(true);
diff --git a/server/services/universeBuilderPromote.test.js b/server/services/universeBuilderPromote.test.js
index 7b38a48c39..a1022e887b 100644
--- a/server/services/universeBuilderPromote.test.js
+++ b/server/services/universeBuilderPromote.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
import { rmSync, mkdirSync } from 'fs';
+import { join } from 'path';
import { mockNoPeerSync, mockNoPeers, mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';
// `wrapExports: ['atomicWrite']` exposes a delegating vi.fn at
@@ -452,7 +453,11 @@ describe('universeBuilderPromote — atomicity', () => {
// promote operation triggers. Filter to per-record writes (the universe's
// index.json) — saveTypeIndex writes that happen elsewhere in the test's
// setup are excluded.
- const recordIndexPath = `${tempRoot}/universes/${w.id}/index.json`;
+ // join(), not a '/'-joined template: collectionStore composes this with
+ // path.join, so on Windows the real write path is backslash-separated and
+ // this filter matched nothing — the assertion then compared against an
+ // empty list instead of the write it meant to count.
+ const recordIndexPath = join(tempRoot, 'universes', w.id, 'index.json');
const beforeCalls = spies.atomicWrite.mock.calls.length;
await promoteSvc.promoteVariationToCanon(w.id, {
category: 'landscapes',
diff --git a/server/services/universeCharacterSheetDelete.test.js b/server/services/universeCharacterSheetDelete.test.js
index fda699873a..3e3bfb6f75 100644
--- a/server/services/universeCharacterSheetDelete.test.js
+++ b/server/services/universeCharacterSheetDelete.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { join } from 'path';
// `deleteCharacterReferenceSheet` orchestrates: getUniverse → fs.unlink → purge.
// Stub each collaborator so the orchestration is testable without spinning
@@ -83,7 +84,7 @@ describe('universeCharacterSheet — deleteCharacterReferenceSheet', () => {
const result = await deleteCharacterReferenceSheet('uni-1', 'char-1');
expect(result).toEqual({ filename: 'sheet-X.png', fileDeleted: true, cleared: 1 });
- expect(unlinkMock).toHaveBeenCalledWith('/mock/data/image-refs/sheet-X.png');
+ expect(unlinkMock).toHaveBeenCalledWith(join('/mock/data', 'image-refs', 'sheet-X.png'));
expect(fakeUniverseStore.get('uni-1').characters[0].referenceSheetImageRef).toBeNull();
});
diff --git a/server/services/updateExecutor.test.js b/server/services/updateExecutor.test.js
index 4d260c2b4e..1728f5d4a9 100644
--- a/server/services/updateExecutor.test.js
+++ b/server/services/updateExecutor.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { EventEmitter } from 'events';
vi.mock('child_process', () => ({
@@ -54,7 +54,22 @@ async function startUpdate(...args) {
return { promise };
}
+// executeUpdate branches on process.platform, and every test below except the
+// first asserts the POSIX (spawnDetached) launch path. Pin the platform so
+// they exercise that path on a Windows host too — otherwise they take the
+// powershell branch, the cleared spawn() mock returns undefined, and each one
+// hangs to the timeout. Safe here: updateExecutor.js and its (mocked) deps
+// load no native addon that picks its binary from process.platform.
+const ORIGINAL_PLATFORM = Object.getOwnPropertyDescriptor(process, 'platform');
+const pinPlatform = (value) =>
+ Object.defineProperty(process, 'platform', { value, configurable: true });
+
+afterEach(() => {
+ Object.defineProperty(process, 'platform', ORIGINAL_PLATFORM);
+});
+
beforeEach(() => {
+ pinPlatform('linux');
vi.clearAllMocks();
// Default: marker file not found (tests that need it override this)
readFile.mockRejectedValue(new Error('ENOENT'));
diff --git a/server/services/videoGen/grok.test.js b/server/services/videoGen/grok.test.js
index 150e5ef19f..b7824b956c 100644
--- a/server/services/videoGen/grok.test.js
+++ b/server/services/videoGen/grok.test.js
@@ -1,4 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { posixPath } from '../../lib/testHelper.js';
+
import { mkdir, writeFile, rm, readFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
@@ -20,11 +22,24 @@ const makeFakeChild = () => {
};
vi.mock('child_process', async (importOriginal) => {
const actual = await importOriginal();
+ const { readFileSync } = await import('fs');
return {
...actual,
spawn: vi.fn((bin, args) => {
const child = makeFakeChild();
- spawnCalls.push({ bin, args, child });
+ // On Windows grok cannot read /dev/stdin, so prepareGrokPromptFile writes
+ // the prompt to a temp file and rewrites --prompt-file to point at it —
+ // then unlinks that file once the run closes. Capture its contents HERE,
+ // between the write and the cleanup, so promptOf() can report the prompt
+ // on both platforms instead of reading an always-empty stdin buffer.
+ // (Same capture as imageGen/grok.test.js.)
+ let promptFromFile = null;
+ const pfIdx = args?.indexOf?.('--prompt-file');
+ const pfPath = pfIdx >= 0 ? args[pfIdx + 1] : null;
+ if (pfPath && pfPath !== '/dev/stdin') {
+ try { promptFromFile = readFileSync(pfPath, 'utf8'); } catch { promptFromFile = null; }
+ }
+ spawnCalls.push({ bin, args, child, promptFromFile });
return child;
}),
};
@@ -64,7 +79,8 @@ const { loadHistory } = await import('./history.js');
const flush = () => new Promise((r) => setImmediate(r));
const scratchDirFor = (jobId) => join(tmpdir(), `portos-grok-video-${jobId}`);
const stagingPathFor = (jobId) => join(scratchDirFor(jobId), 'output.mp4');
-const promptOf = (i = 0) => spawnCalls[i].child.stdin.written;
+// Prefer the --prompt-file temp file (Windows) and fall back to stdin (POSIX).
+const promptOf = (i = 0) => spawnCalls[i].promptFromFile ?? spawnCalls[i].child.stdin.written;
const closeChild = async (i = 0, code = 1) => {
spawnCalls[i].child.exitCode = code;
spawnCalls[i].child.emit('close', code, null);
@@ -115,7 +131,7 @@ describe('videoGen/grok — generateVideo', () => {
const prompt = promptOf();
expect(prompt).not.toContain('image_gen');
expect(prompt).toContain('image_to_video');
- expect(prompt).toContain('/abs/frame.png');
+ expect(posixPath(prompt)).toContain('/abs/frame.png');
expect(prompt).toContain('10 seconds');
await closeChild();
});
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 9881ad50c4..bfac3d7f82 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -25,6 +25,27 @@ const MOCK_PATHS = {
const isLtx2Python = (bin) => String(bin)
.includes(join('.portos', 'ltx-2-mlx', '.venv', 'bin', 'python3'));
+// The two chain helpers below used to sleep a flat 100ms for the timeline
+// stitch and then read the concat spawn / stitched history entry out of the
+// mocks. That is enough on an idle machine and not enough on a contended
+// worker during a full-suite run: the stitch had not landed, those reads came
+// back null, and the tests failed on a TypeError rather than an assertion —
+// while passing in isolation. Poll the real completion condition instead (the
+// stitched history entry is written last, after the concat spawn), and fall
+// through on timeout so a genuine regression still fails on its own assertion.
+const stitchedHistoryEntry = (atomicWriteMock) => atomicWriteMock.mock.calls
+ .flatMap(([, payload]) => (Array.isArray(payload) ? payload : []))
+ .find((entry) => entry?.chainedFrom) || null;
+
+async function waitForStitch() {
+ const { atomicWrite } = await import('../../lib/fileUtils.js');
+ const deadline = Date.now() + 5000;
+ while (!stitchedHistoryEntry(vi.mocked(atomicWrite)) && Date.now() < deadline) {
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise((r) => setTimeout(r, 10));
+ }
+}
+
vi.mock('../../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn(async () => {}),
@@ -457,7 +478,7 @@ describe('generateChainedVideo — continuation strategy (context window vs last
const id = innerJobIds[i];
videoGenEvents.emit('completed', { generationId: id, filename: `${id}.mp4`, path: `/data/videos/${id}.mp4` });
}
- await new Promise((r) => setTimeout(r, 100));
+ await waitForStitch();
videoGenEvents.removeAllListeners('started');
const spawns = vi.mocked(spawn).mock.calls;
@@ -782,7 +803,7 @@ describe('generateChainedVideo — per-chunk prompt beats (#3695)', () => {
const id = innerJobIds[i];
videoGenEvents.emit('completed', { generationId: id, filename: `${id}.mp4`, path: `/data/videos/${id}.mp4` });
}
- await new Promise((r) => setTimeout(r, 100));
+ await waitForStitch();
videoGenEvents.removeAllListeners('started');
return spawnMock.mock.calls
diff --git a/server/services/videoGen/prepareParams.test.js b/server/services/videoGen/prepareParams.test.js
index cd259a4c70..f1937a3b73 100644
--- a/server/services/videoGen/prepareParams.test.js
+++ b/server/services/videoGen/prepareParams.test.js
@@ -1,4 +1,10 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { resolve as resolvePath } from 'path';
+
+// These assertions describe the COMPOSITION of a staged path, not its
+// separator. prepareParams builds them with path.join/resolve, which emit '\'
+// on Windows, so compare against a separator-normalized copy.
+const posix = (p) => String(p).split('\\').join('/');
vi.mock('../settings.js', () => ({
getSettings: vi.fn(async () => ({
@@ -79,8 +85,12 @@ const H3_MODEL = {
// Paths unlinked under PATHS.uploads — i.e. the durable copies the service
// staged, as opposed to the OS temp files the multipart parser wrote.
+// Normalize BEFORE filtering: the staged paths are built with path.join, so on
+// Windows they are '\mock\uploads\…' and a startsWith('/mock/uploads/') filter
+// matches nothing — which silently emptied this list and made every assertion
+// below compare against [] instead of the paths it meant to check.
const unlinkedDurablePaths = () => unlink.mock.calls
- .map(([p]) => p)
+ .map(([p]) => posix(p))
.filter((p) => typeof p === 'string' && p.startsWith('/mock/uploads/'));
describe('withStagedRollback', () => {
@@ -129,7 +139,7 @@ describe('prepareVideoGenParams', () => {
expect(prepared.backend).toBe('local');
expect(prepared.effectiveModelId).toBe('ltx2_unified');
expect(prepared.effectiveChunks).toBe(2);
- expect(prepared.sourceImagePath).toMatch(/^\/mock\/uploads\/video-source-.*\.png$/);
+ expect(posix(prepared.sourceImagePath)).toMatch(/^\/mock\/uploads\/video-source-.*\.png$/);
// The start-frame upload rides the legacy single field so already-persisted
// jobs from before the array field still clean up correctly.
expect(prepared.uploadedTempPath).toBe(prepared.sourceImagePath);
@@ -166,7 +176,9 @@ describe('prepareVideoGenParams', () => {
loadHistory.mockResolvedValue([{ id: '11111111-1111-4111-8111-111111111111', filename: 'prior.mp4' }]);
const ic = await prepare({ mode: 'ic-control', icReferenceVideoIds: ['11111111-1111-4111-8111-111111111111'] });
expect(ic.effectiveChunks).toBe(1);
- expect(ic.icReferencePaths).toEqual(['/mock/videos/prior.mp4']);
+ // resolve() stamps a drive letter on Windows, so build the expectation the
+ // same way rather than hardcoding a POSIX absolute path.
+ expect(ic.icReferencePaths).toEqual([resolvePath('/mock/videos/prior.mp4')]);
});
});
diff --git a/server/services/visionCli.test.js b/server/services/visionCli.test.js
index 5f6bfb6565..2b5ee0336c 100644
--- a/server/services/visionCli.test.js
+++ b/server/services/visionCli.test.js
@@ -1,4 +1,6 @@
import { describe, it, expect, vi } from 'vitest';
+import { posixPath } from '../lib/testHelper.js';
+
import { EventEmitter } from 'events';
// Wrap the REAL resolveWindowsExecutable/prepareWindowsSafeSpawn in spies
@@ -42,7 +44,7 @@ describe('buildCliVisionInvocation', () => {
);
expect(inv.command).toBe('codex');
expect(inv.args).toContain('-i');
- expect(inv.args).toContain('/tmp/x/vision-input.png');
+ expect(posixPath(inv.args)).toContain('/tmp/x/vision-input.png');
expect(inv.args).toContain('-m');
expect(inv.args).toContain('gpt-5');
expect(inv.args[inv.args.length - 1]).toBe('describe'); // prompt is positional
@@ -50,7 +52,7 @@ describe('buildCliVisionInvocation', () => {
// under the vision timeout.
expect(inv.args).toEqual(expect.arrayContaining(['-c', 'check_for_update_on_startup=false']));
expect(inv.stdin).toBeNull();
- expect(inv.cwd).toBe('/tmp/x');
+ expect(posixPath(inv.cwd)).toBe('/tmp/x');
});
it('omits -m for the codex-configured-default sentinel (falls back to config.toml)', () => {
@@ -76,7 +78,7 @@ describe('buildCliVisionInvocation', () => {
expect(inv.args).toEqual(expect.arrayContaining(['-p', '-', '--model', 'claude-opus-4-8']));
expect(inv.stdin).toContain('describe');
expect(inv.stdin).toContain('vision-input.png');
- expect(inv.cwd).toBe('/tmp/y');
+ expect(posixPath(inv.cwd)).toBe('/tmp/y');
});
});
diff --git a/server/services/worktreeReap.test.js b/server/services/worktreeReap.test.js
index c431bf969b..bd3d3aec9e 100644
--- a/server/services/worktreeReap.test.js
+++ b/server/services/worktreeReap.test.js
@@ -36,8 +36,14 @@ async function initRepo() {
// realpath-resolve: on macOS mkdtemp returns a /var symlink while
// `git worktree list` records the canonical /private/var path, which would
// break the reaper's startsWith() location checks and our path assertions.
- const dir = realpathSync(await mkdtemp(join(tmpdir(), 'portos-reap-')));
- await execGit(['init', '-b', 'main'], dir);
+ const created = realpathSync(await mkdtemp(join(tmpdir(), 'portos-reap-')));
+ await execGit(['init', '-b', 'main'], created);
+ // Adopt git's spelling of the root. `git worktree list` reports paths the way
+ // git normalized them, and the reaper's containment check compares those
+ // against a root derived from this value — so any disagreement (8.3 short
+ // names like C:\\Users\\RUNNER~1, drive-letter case) makes every worktree look
+ // like it lives somewhere unmanaged and nothing is reaped.
+ const dir = (await execGit(['rev-parse', '--show-toplevel'], created)).stdout.trim() || created;
await execGit(['config', 'user.email', '[email protected]'], dir);
await execGit(['config', 'user.name', 'Test'], dir);
await execGit(['config', 'commit.gpgsign', 'false'], dir);
@@ -134,7 +140,10 @@ describe('reapMergedWorktrees', () => {
const result = await reapMergedWorktrees(dir, { includeClaudeTrees: true });
- expect(result.reaped.map(r => r.branch)).toContain('merged-br');
+ expect(
+ result.reaped.map(r => r.branch),
+ `nothing reaped; skipped = ${JSON.stringify(result.skipped)}`,
+ ).toContain('merged-br');
expect(result.reaped.map(r => r.branch)).not.toContain('pending-br');
expect(skipReason(result, unmergedPath)).toBe('unmerged');
diff --git a/server/services/xcodeScripts.test.js b/server/services/xcodeScripts.test.js
index 63fcaee07b..084e044c16 100644
--- a/server/services/xcodeScripts.test.js
+++ b/server/services/xcodeScripts.test.js
@@ -1,4 +1,5 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { posixPath } from '../lib/testHelper.js';
// Hoisted mocks so promisify wraps the same fns we control in tests
const hoisted = vi.hoisted(() => ({
@@ -292,7 +293,18 @@ describe('xcodeScripts', () => {
});
describe('installScripts', () => {
+ // installScripts and deriveProjectInfo both branch on the platform: Windows
+ // has no chmod and short-circuits the project.yml parse entirely. Every case
+ // here except the explicit win32 one below asserts the POSIX path, so pin
+ // the platform rather than let the host decide which half runs. (Safe — the
+ // module's deps are all mocked and none loads a native addon.)
+ const ORIGINAL_PLATFORM = Object.getOwnPropertyDescriptor(process, 'platform');
+ afterEach(() => {
+ Object.defineProperty(process, 'platform', ORIGINAL_PLATFORM);
+ });
+
beforeEach(() => {
+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
hoisted.execMock.mockReset();
hoisted.execFileMock.mockReset();
readFile.mockReset();
@@ -370,8 +382,9 @@ describe('xcodeScripts', () => {
// writeFile called for each script + .env.example (since deploy.sh installed)
expect(writeFile).toHaveBeenCalledTimes(3);
// chmod called once with both installed paths
- expect(hoisted.execFileMock).toHaveBeenCalledWith(
- 'chmod',
+ const [chmodBin, chmodArgs] = hoisted.execFileMock.mock.calls[0];
+ expect(chmodBin).toBe('chmod');
+ expect(chmodArgs.map(posixPath)).toEqual(
expect.arrayContaining(['+x', '/tmp/x/deploy.sh', '/tmp/x/take_screenshots.sh'])
);
});
@@ -385,7 +398,7 @@ describe('xcodeScripts', () => {
// writeFile only called once (deploy.sh) — not for .env.example
expect(writeFile).toHaveBeenCalledTimes(1);
const calls = writeFile.mock.calls.map(c => c[0]);
- expect(calls).not.toContain('/tmp/x/.env.example');
+ expect(posixPath(calls)).not.toContain('/tmp/x/.env.example');
});
it('derives target name and bundle id from project.yml', async () => {
diff --git a/server/vitest.config.js b/server/vitest.config.js
index 012fdb8b04..1fb8164e76 100644
--- a/server/vitest.config.js
+++ b/server/vitest.config.js
@@ -3,6 +3,15 @@ import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
testTimeout: process.platform === 'win32' ? 30000 : 10000,
+ // hookTimeout tracks testTimeout for the same reason: Windows fs + module
+ // resolution is markedly slower, and vitest's 10s DEFAULT applies to hooks
+ // even when testTimeout has been raised. The image-gen route suites
+ // (clean/watermark/multipart) do a heavy dynamic `import('./imageGen.js')`
+ // plus sharp fixture encoding in beforeAll — comfortably under 10s when run
+ // alone, but over it on a contended Windows worker during a full-suite run,
+ // where they failed with "Hook timed out in 10000ms" and ZERO failing
+ // assertions. That is a runner budget, not a product defect.
+ hookTimeout: process.platform === 'win32' ? 30000 : 10000,
// Print worker console output directly instead of forwarding it to the main
// thread over RPC. This codebase logs heavily from fire-and-forget callbacks
// (the documented `.catch(() => console.log(...))` pattern, PTY/timer hooks,