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

refactor: consolidate server test process.platform pins onto pinPlatform helper (#4085)

[._.]/ Adam Eivyb5f9c431aa78
diff --git a/server/lib/README.md b/server/lib/README.md
index f775f94b47..44702edb33 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -363,4 +363,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. 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`. |
+| `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 trio: `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`; `pinPlatform(value)` pins `process.platform` and returns a restore that reinstates the ORIGINAL descriptor (deleting the pin when there was none) — it carries the one hazard every hand-rolled pin had to rediscover: never pin above an import that loads a native addon, which picks its prebuilt binary off the platform at load time (#4085). |
diff --git a/server/lib/aiToolkit/providers.cliPathResolve.test.js b/server/lib/aiToolkit/providers.cliPathResolve.test.js
index d7a8820b94..f738a51c40 100644
--- a/server/lib/aiToolkit/providers.cliPathResolve.test.js
+++ b/server/lib/aiToolkit/providers.cliPathResolve.test.js
@@ -16,18 +16,21 @@ vi.mock('child_process', async (importOriginal) => {
import { execFile } from 'child_process';
import { createProviderService } from './providers.js';
+import { pinPlatform } from '../testHelper.js';
// Temp dir, NOT a cwd-rooted one — see providerStatus.test.js (#3823).
let TEST_DATA_DIR;
describe('testProvider — cli command resolution (cross-platform PATH)', () => {
let providerService;
- let originalPlatform;
+ // Captured before any pin so the restore is the pristine descriptor, whether
+ // or not a given case pinned.
+ let restorePlatform = () => {};
let originalPath;
let fakePathDir;
beforeEach(async () => {
- originalPlatform = process.platform;
+ restorePlatform = pinPlatform(process.platform);
TEST_DATA_DIR = await mkdtemp(join(tmpdir(), 'portos-cli-resolve-'));
providerService = createProviderService({ dataDir: TEST_DATA_DIR, providersFile: 'providers.json' });
// testProvider's win32 path now ALSO does its own filesystem-based
@@ -42,15 +45,13 @@ describe('testProvider — cli command resolution (cross-platform PATH)', () =>
});
afterEach(async () => {
- Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
+ restorePlatform();
process.env.PATH = originalPath;
if (fakePathDir) await rm(fakePathDir, { recursive: true, force: true });
vi.mocked(execFile).mockReset();
if (TEST_DATA_DIR) await rm(TEST_DATA_DIR, { recursive: true, force: true });
});
- const setPlatform = (value) => Object.defineProperty(process, 'platform', { value, configurable: true });
-
// execFile's callback is always its last argument — the version probe now
// passes an extra `{ shell }` options object (4 args) while the which/where
// lookup stays at 3, so find the callback positionally instead of assuming
@@ -75,7 +76,7 @@ describe('testProvider — cli command resolution (cross-platform PATH)', () =>
providerService.createProvider({ name: 'Claude CLI', type: 'cli', command });
it('uses `where` (not `which`) on win32 and reports success when the command resolves', async () => {
- setPlatform('win32');
+ pinPlatform('win32');
stubExec({ lookup: 'C:\\Users\\Joe\\.local\\bin\\claude.exe\r\n' });
const p = await makeCliProvider();
@@ -91,7 +92,7 @@ describe('testProvider — cli command resolution (cross-platform PATH)', () =>
});
it('takes the first line when `where` returns multiple matches', async () => {
- setPlatform('win32');
+ pinPlatform('win32');
stubExec({ lookup: 'C:\\a\\claude.exe\r\nC:\\b\\claude.exe\r\n' });
const p = await makeCliProvider();
@@ -102,7 +103,7 @@ describe('testProvider — cli command resolution (cross-platform PATH)', () =>
});
it('re-resolves to the real .cmd shim when `where`s first match is an unspawnable extension-less stub (#1865 root cause)', async () => {
- setPlatform('win32');
+ pinPlatform('win32');
// npm ships a bare POSIX shell-script stub (for Git Bash/WSL) alongside
// the real `.cmd` wrapper — `where` can return the stub first, which is
// exactly the literal scenario from the issue's reported error text.
@@ -127,7 +128,7 @@ describe('testProvider — cli command resolution (cross-platform PATH)', () =>
});
it('falls back to the where-resolved path when no extension-bearing match exists on PATH', async () => {
- setPlatform('win32');
+ pinPlatform('win32');
// fakePathDir intentionally has no claude.* files — resolveWindowsExecutable
// finds nothing, so testProvider must fall back to the `where` result.
stubExec({ lookup: 'C:\\Users\\Joe\\.local\\bin\\claude.exe\r\n' });
@@ -140,7 +141,7 @@ describe('testProvider — cli command resolution (cross-platform PATH)', () =>
});
it('invokes the resolved path for the version probe (so win32 runs the exact .exe)', async () => {
- setPlatform('win32');
+ pinPlatform('win32');
stubExec({ lookup: 'C:\\Users\\Joe\\.local\\bin\\claude.exe\r\n' });
const p = await makeCliProvider();
@@ -152,7 +153,7 @@ describe('testProvider — cli command resolution (cross-platform PATH)', () =>
});
it('uses `which` on non-win32 platforms', async () => {
- setPlatform('linux');
+ pinPlatform('linux');
stubExec({ lookup: '/usr/local/bin/claude\n' });
const p = await makeCliProvider();
@@ -166,7 +167,7 @@ describe('testProvider — cli command resolution (cross-platform PATH)', () =>
});
it('reports not-found when the lookup resolves nothing', async () => {
- setPlatform('win32');
+ pinPlatform('win32');
stubExec({ lookup: null });
const p = await makeCliProvider('claude');
@@ -177,7 +178,7 @@ describe('testProvider — cli command resolution (cross-platform PATH)', () =>
});
it('falls back to "available" when the binary spawns but supports no version flag', async () => {
- setPlatform('linux');
+ pinPlatform('linux');
vi.mocked(execFile).mockImplementation((cmd, ...rest) => {
const cb = lastCallback(rest);
if (cmd === 'which' || cmd === 'where') return cb(null, { stdout: '/usr/local/bin/claude\n', stderr: '' });
@@ -195,7 +196,7 @@ describe('testProvider — cli command resolution (cross-platform PATH)', () =>
});
it('reports failure when the resolved path cannot be spawned (Windows .cmd/.bat shim)', async () => {
- setPlatform('win32');
+ pinPlatform('win32');
vi.mocked(execFile).mockImplementation((cmd, ...rest) => {
const cb = lastCallback(rest);
if (cmd === 'which' || cmd === 'where') return cb(null, { stdout: 'C:\\Users\\Joe\\AppData\\npm\\claude.cmd\r\n', stderr: '' });
diff --git a/server/lib/detachedSpawn.test.js b/server/lib/detachedSpawn.test.js
index c402ea6610..e9ea9ad35f 100644
--- a/server/lib/detachedSpawn.test.js
+++ b/server/lib/detachedSpawn.test.js
@@ -4,6 +4,7 @@ import { tmpdir } from 'os';
import { join } from 'path';
import { execFile } from 'child_process';
import { promisify } from 'util';
+import { pinPlatform } from './testHelper.js';
import { spawnDetached, reapDetached, reapAndCleanDetachedDirs, reattachDetached, isReattachable, isDetachedRunning } from './detachedSpawn.js';
const execFileAsync = promisify(execFile);
@@ -200,8 +201,7 @@ describe('spawnDetached', () => {
});
it('falls back to a plain spawn on win32 (no POSIX sh double-fork)', async () => {
- const original = process.platform;
- Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
+ const restorePlatform = pinPlatform('win32');
try {
const controlDir = await tmpControlDir();
// Real `sh` exists on the test runner, so the plain-spawn fallback runs;
@@ -215,7 +215,7 @@ describe('spawnDetached', () => {
expect(code).toBe(0);
expect(getOut()).toBe('hi\n');
} finally {
- Object.defineProperty(process, 'platform', { value: original, configurable: true });
+ restorePlatform();
}
});
diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.js
index 9f1342cf69..7a2650ad81 100644
--- a/server/lib/fileUtils.test.js
+++ b/server/lib/fileUtils.test.js
@@ -4,6 +4,7 @@ import { mkdtempSync, rmSync, writeFileSync, readFileSync, readdirSync } from 'f
import { join } from 'path';
import { tmpdir, homedir } from 'os';
import { createHash } from 'crypto';
+import { pinPlatform } from './testHelper.js';
import * as fsPromises from 'fs/promises';
// Mock fs/promises so the `ensureDir` regression test can force `mkdir` to
// throw a spurious Windows error, and the readJSONFileStrict tests can force a
@@ -1316,11 +1317,8 @@ describe('Windows swap-window retries (#4095)', () => {
let tmpRoot;
let restorePlatform = null;
- const fakePlatform = (value) => {
- const original = Object.getOwnPropertyDescriptor(process, 'platform');
- Object.defineProperty(process, 'platform', { value, configurable: true });
- restorePlatform = () => Object.defineProperty(process, 'platform', original);
- };
+ // Parks the restore for afterEach; each case pins exactly once.
+ const fakePlatform = (value) => { restorePlatform = pinPlatform(value); };
beforeEach(() => {
tmpRoot = mkdtempSync(join(tmpdir(), 'fileutils-winswap-'));
diff --git a/server/lib/grok.test.js b/server/lib/grok.test.js
index 29cfa6eaa4..dcec0d246c 100644
--- a/server/lib/grok.test.js
+++ b/server/lib/grok.test.js
@@ -1,5 +1,6 @@
-import { describe, it, expect, afterEach } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { existsSync, readFileSync } from 'fs';
+import { pinPlatform } from './testHelper.js';
import {
GROK_API_ID,
@@ -104,12 +105,13 @@ describe('grok — ensureGrokTuiArgs', () => {
});
describe('grok — prepareGrokPromptFile', () => {
- const realPlatform = process.platform;
- const setPlatform = (p) => Object.defineProperty(process, 'platform', { value: p, configurable: true });
- afterEach(() => setPlatform(realPlatform));
+ // Captured before any pin so the restore reinstates the pristine descriptor.
+ let restorePlatform = () => {};
+ beforeEach(() => { restorePlatform = pinPlatform(process.platform); });
+ afterEach(() => restorePlatform());
it('is a stdin no-op on POSIX (prompt delivered via /dev/stdin)', () => {
- setPlatform('darwin');
+ pinPlatform('darwin');
const args = ['--prompt-file', '/dev/stdin'];
const res = prepareGrokPromptFile(args, 'hello');
expect(res.useStdin).toBe(true);
@@ -117,7 +119,7 @@ describe('grok — prepareGrokPromptFile', () => {
});
it('is a no-op for a non-grok argv even on Windows', () => {
- setPlatform('win32');
+ pinPlatform('win32');
const args = ['-p', '-'];
const res = prepareGrokPromptFile(args, 'hello');
expect(res.useStdin).toBe(true);
@@ -125,7 +127,7 @@ describe('grok — prepareGrokPromptFile', () => {
});
it('writes a temp file and rewrites the separated sentinel on Windows', () => {
- setPlatform('win32');
+ pinPlatform('win32');
const args = ['--output-format', 'plain', '--prompt-file', '/dev/stdin'];
const res = prepareGrokPromptFile(args, 'my prompt body');
expect(res.useStdin).toBe(false);
@@ -139,7 +141,7 @@ describe('grok — prepareGrokPromptFile', () => {
});
it('rewrites the joined --prompt-file=/dev/stdin form on Windows too', () => {
- setPlatform('win32');
+ pinPlatform('win32');
const args = ['--output-format', 'plain', '--prompt-file=/dev/stdin'];
const res = prepareGrokPromptFile(args, 'joined body');
expect(res.useStdin).toBe(false);
@@ -153,7 +155,7 @@ describe('grok — prepareGrokPromptFile', () => {
});
it('uses a unique temp filename per call (no collision under concurrency)', () => {
- setPlatform('win32');
+ pinPlatform('win32');
const mk = () => prepareGrokPromptFile(['--prompt-file', '/dev/stdin'], 'x');
const a = mk(); const b = mk();
const fileA = a.args[a.args.indexOf('--prompt-file') + 1];
diff --git a/server/lib/setupScriptRunner.test.js b/server/lib/setupScriptRunner.test.js
index 3cec2e98c2..9a63901be1 100644
--- a/server/lib/setupScriptRunner.test.js
+++ b/server/lib/setupScriptRunner.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { EventEmitter } from 'events';
+import { pinPlatform } from './testHelper.js';
// Mock the collaborators so the behavior under test is observable without
// launching bash, probing the filesystem for a Python, or firing a real kill.
@@ -30,7 +31,7 @@ const REAL_PLATFORM = process.platform;
* load, so each platform needs its own module instance.
*/
async function loadFor(platform) {
- Object.defineProperty(process, 'platform', { value: platform, configurable: true });
+ pinPlatform(platform); // restored by the afterEach below, however often it runs
vi.resetModules();
return import('./setupScriptRunner.js');
}
@@ -43,7 +44,13 @@ function makeFakeChild({ pid = 4321, killed = false } = {}) {
return child;
}
+// Capture the pristine descriptor once per test: loadFor() pins as a side
+// effect and can run more than once in a case, so the restore has to come from
+// before any of those pins, not from the last one.
+let restorePlatform = () => {};
+
beforeEach(() => {
+ restorePlatform = pinPlatform(process.platform);
spawnMock.mockReset();
spawnMock.mockImplementation(() => makeFakeChild());
detectPythonSyncMock.mockReset();
@@ -53,7 +60,7 @@ beforeEach(() => {
});
afterEach(() => {
- Object.defineProperty(process, 'platform', { value: REAL_PLATFORM, configurable: true });
+ restorePlatform();
delete process.env.PYTHON_BIN;
});
diff --git a/server/lib/tailscale.test.js b/server/lib/tailscale.test.js
index 517133aba5..402762bdad 100644
--- a/server/lib/tailscale.test.js
+++ b/server/lib/tailscale.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { pinPlatform } from './testHelper.js';
vi.mock('fs', () => ({
existsSync: vi.fn()
@@ -101,23 +102,22 @@ describe('isSandboxedTailscale', () => {
describe('hasOnlySandboxedTailscale', () => {
let originalPath;
- let originalPlatform;
+ let restorePlatform = () => {};
beforeEach(() => {
originalPath = process.env.PATH;
- originalPlatform = process.platform;
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ restorePlatform = pinPlatform('darwin');
process.env.PATH = '';
vi.clearAllMocks();
});
afterEach(() => {
process.env.PATH = originalPath;
- Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
+ restorePlatform();
});
it('returns false on non-darwin platforms', () => {
- Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
+ pinPlatform('linux'); // afterEach restores the pristine descriptor
existsSync.mockReturnValue(true);
expect(hasOnlySandboxedTailscale()).toBe(false);
});
diff --git a/server/lib/testHelper.js b/server/lib/testHelper.js
index 87a3e50d34..cbaa8c159f 100644
--- a/server/lib/testHelper.js
+++ b/server/lib/testHelper.js
@@ -1,8 +1,9 @@
/**
* 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.
+ * server-source scanner used by the whole-tree guard suites, and the three
+ * cross-platform helpers (`posixPath`, `resolveTestPython`, `pinPlatform`) that
+ * keep path-, interpreter- and platform-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.
@@ -209,6 +210,41 @@ export function readServerSource(rel) {
*/
export const posixPath = (value) => String(value).split('\\').join('/');
+/**
+ * Pin `process.platform` for a test, and return the restore.
+ *
+ * const restore = pinPlatform('darwin');
+ * try { … } finally { restore(); }
+ *
+ * // describe-scope pinning
+ * let restorePlatform = () => {};
+ * beforeEach(() => { restorePlatform = pinPlatform('linux'); });
+ * afterEach(() => restorePlatform());
+ *
+ * **Never pin before importing a module that loads a native addon.** Those pick
+ * their prebuilt binary from `process.platform` at load time, so pinning
+ * `'darwin'` ahead of a `sharp` import sends it looking for a `darwin-x64`
+ * binary and breaks the whole run on Linux (cost a CI round-trip in #4082).
+ * Pin inside the test — or inside a `beforeEach` — never at module scope above
+ * a static import, and never before an `await import(…)` of such a module.
+ *
+ * The restore reinstates the ORIGINAL descriptor, so a suite that pins a value
+ * over Node's own accessor leaves the accessor behind, not a frozen snapshot of
+ * whatever it read. When `process` carried no own `platform` descriptor, the
+ * restore deletes the pinned one rather than fabricating a value.
+ *
+ * @param {string} value - the platform to report, e.g. `'darwin'` / `'win32'`
+ * @returns {() => void} restore — idempotent, safe to call from `afterEach`
+ */
+export function pinPlatform(value) {
+ const original = Object.getOwnPropertyDescriptor(process, 'platform');
+ Object.defineProperty(process, 'platform', { value, configurable: true });
+ return () => {
+ if (original) Object.defineProperty(process, 'platform', original);
+ else delete process.platform;
+ };
+}
+
/**
* 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
diff --git a/server/lib/testHelper.test.js b/server/lib/testHelper.test.js
new file mode 100644
index 0000000000..4541b73a66
--- /dev/null
+++ b/server/lib/testHelper.test.js
@@ -0,0 +1,130 @@
+/**
+ * Covers `pinPlatform` and the repo-wide rule that no test hand-rolls the pin
+ * it replaces (#4085). Twelve suites each re-implemented
+ * `getOwnPropertyDescriptor` → `defineProperty` → restore, so the one hazard
+ * that matters — never pin above an import that loads a native addon, which
+ * picks its prebuilt binary off `process.platform` at load time — had to be
+ * rediscovered at every site. It now lives on the helper's doc comment, and
+ * the guard below keeps new sites from routing around it.
+ */
+
+import { describe, it, expect, afterEach } from 'vitest';
+import { execFileSync } from 'child_process';
+import { readFileSync } from 'fs';
+import { join, dirname, relative, sep } from 'path';
+import { fileURLToPath } from 'url';
+import { pinPlatform } from './testHelper.js';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+// Derived, not hardcoded: this file quotes the forbidden spelling in its own
+// pattern below, so a stale literal would let it report itself as an offender
+// after a rename. `git ls-files` prints POSIX separators; `relative()` yields
+// backslashes on Windows, so normalize before comparing.
+const SELF = relative(REPO_ROOT, fileURLToPath(import.meta.url)).split(sep).join('/');
+const HELPER = 'server/lib/testHelper.js';
+
+describe('pinPlatform', () => {
+ let restore = () => {};
+ afterEach(() => restore());
+
+ it('reports the pinned platform and restores the original descriptor', () => {
+ const before = Object.getOwnPropertyDescriptor(process, 'platform');
+ restore = pinPlatform('win32');
+ expect(process.platform).toBe('win32');
+
+ restore();
+ restore = () => {};
+ // The ORIGINAL descriptor, not a data-property snapshot of its value: a
+ // restore that writes `{ value: <read>, configurable: true }` leaves the
+ // accessor Node installed permanently replaced for the rest of the worker.
+ expect(Object.getOwnPropertyDescriptor(process, 'platform')).toEqual(before);
+ });
+
+ it('deletes the pin when there was no own descriptor to restore', () => {
+ // Node always gives `process` an own `platform`, so stage the case the
+ // helper has to survive rather than assume it can't happen.
+ const saved = Object.getOwnPropertyDescriptor(process, 'platform');
+ delete process.platform;
+ expect(Object.getOwnPropertyDescriptor(process, 'platform')).toBeUndefined();
+
+ const undo = pinPlatform('freebsd');
+ expect(process.platform).toBe('freebsd');
+ undo();
+
+ expect(Object.getOwnPropertyDescriptor(process, 'platform')).toBeUndefined();
+ Object.defineProperty(process, 'platform', saved);
+ });
+
+ it('unwinds nested pins in reverse order', () => {
+ const before = process.platform;
+ const undoOuter = pinPlatform('linux');
+ const undoInner = pinPlatform('darwin');
+ expect(process.platform).toBe('darwin');
+
+ undoInner();
+ expect(process.platform).toBe('linux');
+ undoOuter();
+ expect(process.platform).toBe(before);
+ });
+
+ it('is idempotent, so an afterEach can call it after an inline restore', () => {
+ const before = process.platform;
+ const undo = pinPlatform('aix');
+ undo();
+ undo();
+ expect(process.platform).toBe(before);
+ });
+});
+
+describe('platform-pin guard', () => {
+ // Scope to what the server runner globs (`server/vitest.config.js`); client
+ // tests run in jsdom, where `process.platform` isn't a branch worth pinning.
+ const SCOPED_TESTS = execFileSync('git', ['ls-files', '*.test.js'], {
+ cwd: REPO_ROOT,
+ encoding: 'utf8',
+ })
+ .split('\n')
+ .filter((p) => /^(server|scripts|lib|autofixer)\//.test(p))
+ .filter((p) => !p.startsWith('lib/slashdo/') && p !== SELF);
+
+ const HAND_ROLLED_PIN = /defineProperty\s*\(\s*process\s*,\s*['"`]platform['"`]/;
+
+ it('finds test files to scan', () => {
+ // Fails loudly if the glob or the path filter stops matching, rather than
+ // reporting a vacuous pass over zero files.
+ expect(SCOPED_TESTS.length).toBeGreaterThan(100);
+ });
+
+ it('detects the spelling it forbids', () => {
+ // Bypass probe: proves the pattern bites, so the empty-offenders assertion
+ // below can't pass because the regex quietly stopped matching anything.
+ expect(HAND_ROLLED_PIN.test(
+ "Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });"
+ )).toBe(true);
+ expect(HAND_ROLLED_PIN.test("restore = pinPlatform('win32');")).toBe(false);
+ });
+
+ it('no test hand-rolls a process.platform pin', () => {
+ const offenders = SCOPED_TESTS.filter(
+ (rel) => HAND_ROLLED_PIN.test(readFileSync(join(REPO_ROOT, rel), 'utf8'))
+ );
+ expect(offenders, [
+ 'These tests pin process.platform by hand. Use the shared helper instead:',
+ '',
+ " import { pinPlatform } from '<path>/lib/testHelper.js';",
+ " const restore = pinPlatform('win32'); // inline: call restore() in finally",
+ " beforeEach(() => { restore = pinPlatform('win32'); }); // block-scoped",
+ '',
+ 'It restores the ORIGINAL descriptor and documents the native-addon hazard',
+ `that a hand-rolled pin has to rediscover every time. See ${HELPER} (#4085).`,
+ ].join('\n')).toEqual([]);
+ });
+
+ it('the helper still owns the only pin, and still documents the hazard', () => {
+ // Both halves of the consolidation: the mechanism lives here, and the
+ // warning that motivated centralizing it stays attached to it.
+ const source = readFileSync(join(REPO_ROOT, HELPER), 'utf8');
+ expect(HAND_ROLLED_PIN.test(source)).toBe(true);
+ expect(source).toMatch(/native addon/);
+ });
+});
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 475f999819..2d75a890ba 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import express from 'express';
-import { request } from '../lib/testHelper.js';
+import { pinPlatform, request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import imageGenRoutes from './imageGen.js';
import * as fileUtils from '../lib/fileUtils.js';
@@ -1154,11 +1154,11 @@ describe('Image Gen Routes', () => {
describe('GET /setup/check (arch fields)', () => {
// The route's archMismatch logic gates on `process.platform === 'darwin'` —
// override it so the assertions run identically on Linux CI and a dev Mac.
- const originalPlatform = process.platform;
+ let restorePlatform = () => {};
let probePythonHealth, detectArm64Python;
beforeEach(async () => {
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ restorePlatform = pinPlatform('darwin');
const mod = await import('../lib/pythonSetup.js');
probePythonHealth = mod.probePythonHealth;
detectArm64Python = mod.detectArm64Python;
@@ -1167,7 +1167,7 @@ describe('Image Gen Routes', () => {
});
afterEach(() => {
- Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
+ restorePlatform();
hostArchHolder.value = 'arm64';
});
@@ -1207,7 +1207,7 @@ describe('Image Gen Routes', () => {
});
it('does not flag archMismatch on non-darwin even when interpreter arch differs', async () => {
- Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
+ pinPlatform('linux'); // afterEach restores the pristine descriptor
probePythonHealth.mockResolvedValueOnce({
installed: [], missing: [], missingPip: [],
externallyManaged: false, interpreterArch: 'x86_64',
diff --git a/server/services/agents.test.js b/server/services/agents.test.js
index 287c09a274..826dfa4dba 100644
--- a/server/services/agents.test.js
+++ b/server/services/agents.test.js
@@ -33,6 +33,7 @@ vi.mock('./agentOrchestrator.js', () => ({
}));
import { exec, execFile } from 'child_process';
+import { pinPlatform } from '../lib/testHelper.js';
import { registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';
import {
getRunningAgents,
@@ -60,18 +61,16 @@ function mockExecWith(stdoutOrFn) {
// 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 });
+let restorePlatform = () => {};
describe('agents.js', () => {
beforeEach(() => {
vi.clearAllMocks();
- pinPlatform('darwin');
+ restorePlatform = pinPlatform('darwin');
});
afterEach(() => {
- Object.defineProperty(process, 'platform', ORIGINAL_PLATFORM);
+ restorePlatform();
});
// ===========================================================================
diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.js
index 7970b9306c..39ef0532aa 100644
--- a/server/services/localLlm.test.js
+++ b/server/services/localLlm.test.js
@@ -3,6 +3,7 @@ import os from 'os';
import path from 'path';
import fs from 'fs';
import { EventEmitter } from 'events';
+import { pinPlatform } from '../lib/testHelper.js';
// vi.mock factories are hoisted above the module body, so the mutable holder
// and the mock objects must come from vi.hoisted (which runs first). The
@@ -399,14 +400,13 @@ describe('localLlm', () => {
});
it('returns a download hint on an unsupported platform (no install attempted)', async () => {
- const orig = Object.getOwnPropertyDescriptor(process, 'platform');
- Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
+ const restorePlatform = pinPlatform('win32');
try {
const r = await svc.installBackend('lmstudio');
expect(r.success).toBe(false);
expect(r.error).toMatch(/lmstudio\.ai/); // surfaces the manual download link
} finally {
- Object.defineProperty(process, 'platform', orig);
+ restorePlatform();
}
});
@@ -414,8 +414,7 @@ describe('localLlm', () => {
// Repro of the real Ollama install failure: `brew install ollama` poured
// the formula but exited 1 (mlx dep + cleanup/env-hint noise), so PortOS
// wrongly reported failure for a successful install.
- const orig = Object.getOwnPropertyDescriptor(process, 'platform');
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ const restorePlatform = pinPlatform('darwin');
cp.spawn = () => fakeChild({ code: 1, lines: ['Pouring ollama…', '🍺 ollama installed', 'brew cleanup hint'] });
// `brew --version` (gate) and `brew list --versions ollama` (presence) succeed.
cp.execFile = (_cmd, _args, _opts, cb) => cb(null, { stdout: 'ollama 0.30.10', stderr: '' });
@@ -424,13 +423,12 @@ describe('localLlm', () => {
expect(r.success).toBe(true);
expect(r.backend).toBe('ollama');
} finally {
- Object.defineProperty(process, 'platform', orig);
+ restorePlatform();
}
});
it('still reports failure when `brew install` exits non-zero AND the package is absent', async () => {
- const orig = Object.getOwnPropertyDescriptor(process, 'platform');
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ const restorePlatform = pinPlatform('darwin');
cp.spawn = () => fakeChild({ code: 1, lines: ['Error: download failed'] });
// brew --version succeeds (gate passes); brew list rejects (not installed).
cp.execFile = (_cmd, args, _opts, cb) =>
@@ -440,7 +438,7 @@ describe('localLlm', () => {
expect(r.success).toBe(false);
expect(r.error).toMatch(/Homebrew install failed/);
} finally {
- Object.defineProperty(process, 'platform', orig);
+ restorePlatform();
}
});
});
diff --git a/server/services/mediaModelInstall.test.js b/server/services/mediaModelInstall.test.js
index 61da2ad646..9cd446889d 100644
--- a/server/services/mediaModelInstall.test.js
+++ b/server/services/mediaModelInstall.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { pinPlatform } from '../lib/testHelper.js';
vi.mock('../lib/hfToken.js', () => ({ getHfToken: vi.fn(async () => '') }));
vi.mock('../lib/mediaModels.js', () => ({ addUserModelEntry: vi.fn((entry) => entry) }));
@@ -18,17 +19,15 @@ const mockFetch = (body) => vi.fn(async () => ({
// 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 });
+let restorePlatform = () => {};
beforeEach(() => {
vi.clearAllMocks();
- pinPlatform('darwin');
+ restorePlatform = pinPlatform('darwin');
});
afterEach(() => {
- Object.defineProperty(process, 'platform', ORIGINAL_PLATFORM);
+ restorePlatform();
});
describe('addModelFromHuggingface', () => {
diff --git a/server/services/mortalLoomStore.test.js b/server/services/mortalLoomStore.test.js
index cca299c009..720cd0c911 100644
--- a/server/services/mortalLoomStore.test.js
+++ b/server/services/mortalLoomStore.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach, afterEach } from 'vitest';
import { EventEmitter } from 'events';
+import { pinPlatform } from '../lib/testHelper.js';
let existsResult = true;
// Queue of return values for sequential existsSync() calls. When empty, falls
@@ -283,14 +284,11 @@ describe('updateStore', () => {
// pre-existing guard behavior exactly as it was. The darwin materialize
// behavior gets its own describe block below. (process.platform overrides
// aren't restored by vi.restoreAllMocks(), so capture+restore explicitly.)
- let originalPlatformDescriptor;
+ let restorePlatform = () => {};
beforeEach(() => {
- originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
- Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
- });
- afterEach(() => {
- if (originalPlatformDescriptor) Object.defineProperty(process, 'platform', originalPlatformDescriptor);
+ restorePlatform = pinPlatform('linux');
});
+ afterEach(() => restorePlatform());
it('seeds a fresh store when the file does not exist', async () => {
existsResult = false;
@@ -404,18 +402,17 @@ describe('updateStore — iCloud on-demand materialize (darwin)', () => {
return child;
};
- let originalPlatformDescriptor;
+ let restorePlatform = () => {};
let originalTimeout;
beforeEach(() => {
- originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ restorePlatform = pinPlatform('darwin');
originalTimeout = store.MATERIALIZE_TIMEOUT_MS;
store._setMaterializeTimeoutForTest(50);
store._resetMortalLoomInitForTest();
writeFileMock.mockResolvedValue(undefined);
});
afterEach(() => {
- if (originalPlatformDescriptor) Object.defineProperty(process, 'platform', originalPlatformDescriptor);
+ restorePlatform();
store._setMaterializeTimeoutForTest(originalTimeout);
});
@@ -687,28 +684,24 @@ describe('initMortalLoomStore — brctl pinning', () => {
return child;
};
- // process.platform overrides aren't restored by vi.restoreAllMocks(). Capture
- // the original property descriptor before each test and restore it in
- // afterEach so an assertion failure can't leak the mutated platform into
- // unrelated test files (mirrors the updateExecutor.test.js pattern).
- let originalPlatformDescriptor;
+ // process.platform overrides aren't restored by vi.restoreAllMocks(). Each
+ // case here pins its own platform and parks the restore, which afterEach runs
+ // so an assertion failure can't leak the mutated platform into unrelated test
+ // files (mirrors the updateExecutor.test.js pattern).
+ let restorePlatform = () => {};
beforeEach(() => {
settingsEvents.removeAllListeners('settings:updated');
store._resetMortalLoomInitForTest();
// The shared icloudFile state (including the once-per-process "brctl missing"
// flag folded from the store's old local flag) is reset in the file-level
// beforeEach above, so every block — this one included — starts clean.
- originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
- });
- afterEach(() => {
- if (originalPlatformDescriptor) {
- Object.defineProperty(process, 'platform', originalPlatformDescriptor);
- }
+ restorePlatform = () => {};
});
+ afterEach(() => restorePlatform());
it('spawns brctl download when sync is enabled (darwin only)', async () => {
// Force darwin so the platform guard doesn't short-circuit the test.
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ restorePlatform = pinPlatform('darwin');
const child = makeFakeChild();
spawnMock.mockReturnValue(child);
@@ -728,7 +721,7 @@ describe('initMortalLoomStore — brctl pinning', () => {
});
it('re-pins when settings:updated flips enabled on with a new path', async () => {
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ restorePlatform = pinPlatform('darwin');
spawnMock.mockReturnValue(makeFakeChild());
settings = { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } };
@@ -750,7 +743,7 @@ describe('initMortalLoomStore — brctl pinning', () => {
// assertion passed for the wrong reason. Fix: call init() so the listener
// IS attached and the platform guard inside pinAgainstEviction is the
// thing under test on both the immediate-pin and the event-driven path.
- Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
+ restorePlatform = pinPlatform('linux');
settings = { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } };
await store.initMortalLoomStore();
@@ -766,7 +759,7 @@ describe('initMortalLoomStore — brctl pinning', () => {
// settings:updated event can re-pin. Earlier code set initialized=true
// and ran the await BEFORE attaching the listener, so a throw left the
// listener gone forever.
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ restorePlatform = pinPlatform('darwin');
spawnMock.mockReturnValue(makeFakeChild());
const { getSettings } = await import('./settings.js');
@@ -787,7 +780,7 @@ describe('initMortalLoomStore — brctl pinning', () => {
// twice. A transient failure on the second read could skip the boot
// pin even though the first read confirmed sync enabled. Reading once
// and deriving both fields collapses the partial-failure window.
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ restorePlatform = pinPlatform('darwin');
spawnMock.mockReturnValue(makeFakeChild());
const { getSettings } = await import('./settings.js');
@@ -807,7 +800,7 @@ describe('initMortalLoomStore — brctl pinning', () => {
// isMortalLoomEnabled() rejects, didInitialPin must stay false so a
// subsequent initMortalLoomStore() call can retry the pin. The listener
// must NOT be re-attached (otherwise events fire twice).
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ restorePlatform = pinPlatform('darwin');
spawnMock.mockReturnValue(makeFakeChild());
const { getSettings } = await import('./settings.js');
@@ -834,7 +827,7 @@ describe('initMortalLoomStore — brctl pinning', () => {
// back on (without changing the path) silently no-ops. Settings.json
// listeners must clear `lastPinnedPath` on disable so a subsequent
// enable with the same path materializes again.
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ restorePlatform = pinPlatform('darwin');
spawnMock.mockReturnValue(makeFakeChild());
settings = { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } };
@@ -852,7 +845,7 @@ describe('initMortalLoomStore — brctl pinning', () => {
});
it('clears lastPinnedPath when brctl is signal-killed so a later event can retry', async () => {
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ restorePlatform = pinPlatform('darwin');
const child = makeFakeChild();
spawnMock.mockReturnValue(child);
@@ -875,7 +868,7 @@ describe('initMortalLoomStore — brctl pinning', () => {
// Operators in a sandboxed darwin env had no signal that pinning was a
// no-op. Now we surface ENOENT once per process, then dedupe via
// brctlMissingWarned so settings churn doesn't spam the same warning.
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ restorePlatform = pinPlatform('darwin');
const child1 = makeFakeChild();
const child2 = makeFakeChild();
@@ -905,7 +898,7 @@ describe('initMortalLoomStore — brctl pinning', () => {
// spurious re-spawn on the next settings:updated for the same current
// path. Capturing `path` in the closure and comparing before clearing
// confines each handler's cache invalidation to its own path.
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ restorePlatform = pinPlatform('darwin');
const child1 = makeFakeChild();
const child2 = makeFakeChild();
@@ -934,7 +927,7 @@ describe('initMortalLoomStore — brctl pinning', () => {
// failure clear the second A pin's sticky state, so the next settings:updated
// for A would wrongly spawn a duplicate. The per-attempt generation guard
// confines each failure's cache-clear to the pin that is still current.
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ restorePlatform = pinPlatform('darwin');
const childA1 = makeFakeChild();
const childB = makeFakeChild();
@@ -960,7 +953,7 @@ describe('initMortalLoomStore — brctl pinning', () => {
// mortalloom.path can land as a number / array / object. Calling .trim()
// on a non-string throws — and an unhandled throw inside the EventEmitter
// listener can crash the process. Listener must normalize via type-check.
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ restorePlatform = pinPlatform('darwin');
spawnMock.mockReturnValue(makeFakeChild());
settings = { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } };
@@ -988,7 +981,7 @@ describe('initMortalLoomStore — brctl pinning', () => {
// paths. A configured path outside `/Library/Mobile Documents/` (here the
// suite's ordinary `/icloud/...` fixture, which isHealablePath declines) must
// not be handed a doomed download.
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ restorePlatform = pinPlatform('darwin');
spawnMock.mockReturnValue(makeFakeChild());
settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };
@@ -1002,7 +995,7 @@ describe('initMortalLoomStore — brctl pinning', () => {
// EMFILE — but equally a path that is non-healable at boot and healable once its
// ubiquity container syncs in), the pin must NOT leave its sticky path set, or the
// SAME path would be deduped as "already pinned" forever and never retry.
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ restorePlatform = pinPlatform('darwin');
// First spawn throws → the helper catches it and returns false (declined).
spawnMock.mockImplementationOnce(() => { throw Object.assign(new Error('EMFILE'), { code: 'EMFILE' }); });
diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.js
index 7eb747af02..1b1e039a04 100644
--- a/server/services/ollamaManager.test.js
+++ b/server/services/ollamaManager.test.js
@@ -3,6 +3,7 @@ import { mkdtemp, mkdir, rm, readFile, writeFile, stat } from 'fs/promises'
import { createHash } from 'crypto'
import { tmpdir } from 'os'
import { join } from 'path'
+import { pinPlatform } from '../lib/testHelper.js'
// startPersistentService / getServiceStatus shell out via promisify(execFile).
// Route every exec call through a per-test impl so the homebrew service flow can
@@ -525,14 +526,13 @@ describe('ollamaManager.isBootstrapConflictError', () => {
})
describe('ollamaManager.startPersistentService bootstrap recovery (homebrew)', () => {
- let originalPlatform
+ let restorePlatform = () => {}
beforeEach(() => {
// Force the homebrew controller branch regardless of CI host OS.
- originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true })
+ restorePlatform = pinPlatform('darwin')
})
afterEach(() => {
- Object.defineProperty(process, 'platform', originalPlatform)
+ restorePlatform()
vi.unstubAllGlobals()
execMock.impl = () => {}
})
diff --git a/server/services/updateExecutor.test.js b/server/services/updateExecutor.test.js
index 1728f5d4a9..f2087d78b8 100644
--- a/server/services/updateExecutor.test.js
+++ b/server/services/updateExecutor.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { EventEmitter } from 'events';
+import { pinPlatform } from '../lib/testHelper.js';
vi.mock('child_process', () => ({
spawn: vi.fn()
@@ -60,16 +61,12 @@ async function startUpdate(...args) {
// 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 });
+let restorePlatform = () => {};
-afterEach(() => {
- Object.defineProperty(process, 'platform', ORIGINAL_PLATFORM);
-});
+afterEach(() => restorePlatform());
beforeEach(() => {
- pinPlatform('linux');
+ restorePlatform = pinPlatform('linux');
vi.clearAllMocks();
// Default: marker file not found (tests that need it override this)
readFile.mockRejectedValue(new Error('ENOENT'));
@@ -79,28 +76,23 @@ beforeEach(() => {
describe('executeUpdate', () => {
it('spawns powershell on Windows (plain spawn, not spawnDetached)', async () => {
- const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
- try {
- Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
- const child = createMockChild();
- child.unref = vi.fn();
- spawn.mockReturnValue(child);
-
- const { promise } = await startUpdate('v1.0.0', () => {});
- child.emit('close', 0);
- await promise;
-
- expect(spawn).toHaveBeenCalledWith(
- 'powershell',
- expect.arrayContaining(['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File']),
- expect.any(Object)
- );
- expect(spawnDetached).not.toHaveBeenCalled();
- } finally {
- if (originalPlatformDescriptor) {
- Object.defineProperty(process, 'platform', originalPlatformDescriptor);
- }
- }
+ // Re-pin over the file-level linux default; the file-level afterEach still
+ // restores the pristine descriptor, so a failure here can't leak win32.
+ pinPlatform('win32');
+ const child = createMockChild();
+ child.unref = vi.fn();
+ spawn.mockReturnValue(child);
+
+ const { promise } = await startUpdate('v1.0.0', () => {});
+ child.emit('close', 0);
+ await promise;
+
+ expect(spawn).toHaveBeenCalledWith(
+ 'powershell',
+ expect.arrayContaining(['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File']),
+ expect.any(Object)
+ );
+ expect(spawnDetached).not.toHaveBeenCalled();
});
// Regression for the reconcile "shuts down but never restarts" failure: a
diff --git a/server/services/xcodeScripts.test.js b/server/services/xcodeScripts.test.js
index 084e044c16..d59f2c3f19 100644
--- a/server/services/xcodeScripts.test.js
+++ b/server/services/xcodeScripts.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { posixPath } from '../lib/testHelper.js';
+import { pinPlatform, posixPath } from '../lib/testHelper.js';
// Hoisted mocks so promisify wraps the same fns we control in tests
const hoisted = vi.hoisted(() => ({
@@ -298,13 +298,13 @@ describe('xcodeScripts', () => {
// 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);
- });
+ // Pinned in beforeEach, so a case that re-pins (the win32 one below) still
+ // restores through this single afterEach.
+ let restorePlatform = () => {};
+ afterEach(() => restorePlatform());
beforeEach(() => {
- Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ restorePlatform = pinPlatform('darwin');
hoisted.execMock.mockReset();
hoisted.execFileMock.mockReset();
readFile.mockReset();
@@ -521,32 +521,19 @@ describe('xcodeScripts', () => {
});
it('emits Windows-specific message when running on win32', async () => {
- // Capture the original property descriptor so we can restore it exactly,
- // and ensure our override is configurable so the restore can replace it.
- const originalDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
- Object.defineProperty(process, 'platform', {
- value: 'win32',
- configurable: true,
- writable: true,
- enumerable: true
- });
- try {
- existsSync.mockImplementation(() => false);
- const result = await installScripts(
- { type: 'xcode', repoPath: 'C:/tmp/x', name: 'MyApp' },
- ['deploy.sh']
- );
- // deriveProjectInfo short-circuits on win32 — uses appName directly
- expect(result.installed).toContain('deploy.sh');
- expect(result.errors.some(e => e.includes('chmod is not supported on Windows'))).toBe(true);
- // execFile should NOT have been called for chmod on Windows
- expect(hoisted.execFileMock).not.toHaveBeenCalled();
- } finally {
- // Restore the exact original descriptor so no test state leaks
- if (originalDescriptor) {
- Object.defineProperty(process, 'platform', originalDescriptor);
- }
- }
+ // Re-pin over the block's darwin default; the block's afterEach restores
+ // the pristine descriptor either way, so no state leaks on a failure.
+ pinPlatform('win32');
+ existsSync.mockImplementation(() => false);
+ const result = await installScripts(
+ { type: 'xcode', repoPath: 'C:/tmp/x', name: 'MyApp' },
+ ['deploy.sh']
+ );
+ // deriveProjectInfo short-circuits on win32 — uses appName directly
+ expect(result.installed).toContain('deploy.sh');
+ expect(result.errors.some(e => e.includes('chmod is not supported on Windows'))).toBe(true);
+ // execFile should NOT have been called for chmod on Windows
+ expect(hoisted.execFileMock).not.toHaveBeenCalled();
});
});
});