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(tests): remove flaky, env-dependent and never-running tests; fix DST day-count bug

atomanticagent0aa5f3911551
diff --git a/client/src/components/dashboardWidgets.realtime.test.jsx b/client/src/components/dashboardWidgets.realtime.test.jsx
index 0851ae33bf..b4dee8d3d8 100644
--- a/client/src/components/dashboardWidgets.realtime.test.jsx
+++ b/client/src/components/dashboardWidgets.realtime.test.jsx
@@ -99,8 +99,11 @@ describe('dashboard resource subscriptions', () => {
});
it('advances overdue coloring and schedule countdowns with no network reads', async () => {
- vi.setSystemTime(new Date('2026-01-01T12:00:00Z'));
- api.listThreads.mockResolvedValue({ threads: [{ id: 'example', title: 'Example deadline', status: 'open', dueAt: '2026-01-01T12:00:30Z' }], total: 1 });
+ // Local noon, not a UTC instant: the widget prints the due date in the
+ // machine's zone, so 12:00Z reads "Jan 2" anywhere east of UTC+12.
+ const now = new Date(2026, 0, 1, 12, 0, 0);
+ vi.setSystemTime(now);
+ api.listThreads.mockResolvedValue({ threads: [{ id: 'example', title: 'Example deadline', status: 'open', dueAt: new Date(now.getTime() + 30000).toISOString() }], total: 1 });
api.getCosUpcomingTasks.mockResolvedValue([{ taskType: 'example', description: 'Example task', status: 'scheduled', eligibleAt: Date.now() + 120000 }]);
render(<MemoryRouter><OpenThreadsWidget /><UpcomingTasksWidget /></MemoryRouter>);
await flush();
diff --git a/client/src/hooks/useAutoRefetch.test.jsx b/client/src/hooks/useAutoRefetch.test.jsx
index db474c852f..673f8780ee 100644
--- a/client/src/hooks/useAutoRefetch.test.jsx
+++ b/client/src/hooks/useAutoRefetch.test.jsx
@@ -13,6 +13,12 @@ const fireVisibilityChange = () => {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+// Tests that assert an EXACT call count while a short interval is ticking run on
+// fake time. On the real clock a loaded worker can stretch a 20ms sleep past
+// several ticks (or past the 60ms interval itself), so "exactly one fetch so
+// far" became a race between the test's own timers and the hook's.
+const advance = (ms) => act(async () => { await vi.advanceTimersByTimeAsync(ms); });
+
// A fetchFn whose every call stays pending until the test settles it, with a
// live count of overlapping calls.
const deferredFetch = () => {
@@ -36,6 +42,7 @@ describe('useAutoRefetch', () => {
});
afterEach(() => {
+ vi.useRealTimers();
setVisibility('visible');
});
@@ -56,36 +63,41 @@ describe('useAutoRefetch', () => {
});
it('skips fetches while the tab is hidden and refires when visible', async () => {
+ vi.useFakeTimers();
const fetchFn = vi.fn().mockResolvedValue('x');
renderHook(() => useAutoRefetch(fetchFn, 20));
- await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(1));
+ await advance(0);
+ expect(fetchFn).toHaveBeenCalledTimes(1);
setVisibility('hidden');
- await new Promise((r) => setTimeout(r, 80));
+ await advance(80);
const callsWhileHidden = fetchFn.mock.calls.length;
expect(callsWhileHidden).toBe(1);
setVisibility('visible');
act(() => fireVisibilityChange());
- await waitFor(() => expect(fetchFn.mock.calls.length).toBeGreaterThan(callsWhileHidden));
+ await advance(0);
+ expect(fetchFn.mock.calls.length).toBeGreaterThan(callsWhileHidden);
});
it('skips entirely when enabled is false and starts/stops on toggle', async () => {
const fetchFn = vi.fn().mockResolvedValue('x');
+ vi.useFakeTimers();
const { rerender } = renderHook(
({ enabled }) => useAutoRefetch(fetchFn, 20, { enabled }),
{ initialProps: { enabled: false } },
);
- await new Promise((r) => setTimeout(r, 80));
+ await advance(80);
expect(fetchFn).not.toHaveBeenCalled();
rerender({ enabled: true });
- await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(1));
+ await advance(0);
+ expect(fetchFn).toHaveBeenCalledTimes(1);
rerender({ enabled: false });
const callsAfterDisable = fetchFn.mock.calls.length;
- await new Promise((r) => setTimeout(r, 80));
+ await advance(80);
expect(fetchFn).toHaveBeenCalledTimes(callsAfterDisable);
});
@@ -146,15 +158,17 @@ describe('useAutoRefetch', () => {
});
it('skips the on-mount fetch when immediate is false', async () => {
+ vi.useFakeTimers();
const fetchFn = vi.fn().mockResolvedValue('x');
renderHook(() => useAutoRefetch(fetchFn, 60, { immediate: false }));
// Give the effect a chance to run; no fetch should fire yet.
- await new Promise((r) => setTimeout(r, 20));
+ await advance(20);
expect(fetchFn).not.toHaveBeenCalled();
// The interval still ticks after `intervalMs`.
- await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(1), { timeout: 500 });
+ await advance(40);
+ expect(fetchFn).toHaveBeenCalledTimes(1);
});
it('exposes a refetch handle that fetches on demand and updates data', async () => {
@@ -266,32 +280,37 @@ describe('useAutoRefetch', () => {
});
it('skips while hidden and refires on visibility', async () => {
+ vi.useFakeTimers();
const fetchFn = vi.fn().mockResolvedValue(null);
renderHook(() => useAutoRefetch(fetchFn, 20, { pollOnly: true }));
- await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(1));
+ await advance(0);
+ expect(fetchFn).toHaveBeenCalledTimes(1);
setVisibility('hidden');
- await new Promise((r) => setTimeout(r, 80));
+ await advance(80);
const callsWhileHidden = fetchFn.mock.calls.length;
expect(callsWhileHidden).toBe(1);
setVisibility('visible');
act(() => fireVisibilityChange());
- await waitFor(() => expect(fetchFn.mock.calls.length).toBeGreaterThan(callsWhileHidden));
+ await advance(0);
+ expect(fetchFn.mock.calls.length).toBeGreaterThan(callsWhileHidden);
});
it('respects enabled toggling', async () => {
const fetchFn = vi.fn().mockResolvedValue(null);
+ vi.useFakeTimers();
const { rerender } = renderHook(
({ enabled }) => useAutoRefetch(fetchFn, 20, { enabled, pollOnly: true }),
{ initialProps: { enabled: false } },
);
- await new Promise((r) => setTimeout(r, 80));
+ await advance(80);
expect(fetchFn).not.toHaveBeenCalled();
rerender({ enabled: true });
- await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(1));
+ await advance(0);
+ expect(fetchFn).toHaveBeenCalledTimes(1);
});
it('exposes a working refetch that swallows errors via warn', async () => {
diff --git a/client/src/utils/timeWindow.test.js b/client/src/utils/timeWindow.test.js
index 9680667a2f..2cce51a8fd 100644
--- a/client/src/utils/timeWindow.test.js
+++ b/client/src/utils/timeWindow.test.js
@@ -1,5 +1,3 @@
-// @vitest-environment node
-
import { describe, it, expect, beforeEach } from 'vitest';
import { isInTimeWindow, isValidTimeString, MORNING_DEFAULT_WINDOW, pickActiveLayoutId, recordManualLayoutPick, TIME_STRING_RE } from './timeWindow.js';
@@ -60,13 +58,7 @@ describe('MORNING_DEFAULT_WINDOW', () => {
});
});
-// These describes need window.localStorage. The client's jsdom vitest runs
-// them in full (verified 13/13 tests pass under jsdom). The server's node-
-// env vitest also picks up `client/src/**/*.test.js` (see server/vitest.config.js
-// include list) and would crash here without the skip.
-const hasLocalStorage = typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';
-
-describe.skipIf(!hasLocalStorage)('pickActiveLayoutId', () => {
+describe('pickActiveLayoutId', () => {
beforeEach(() => { window.localStorage.clear(); });
const layouts = [
@@ -104,7 +96,7 @@ describe.skipIf(!hasLocalStorage)('pickActiveLayoutId', () => {
});
});
-describe.skipIf(!hasLocalStorage)('recordManualLayoutPick — stale key pruning', () => {
+describe('recordManualLayoutPick — stale key pruning', () => {
beforeEach(() => { window.localStorage.clear(); });
it('removes prior-day userPick keys when recording today', () => {
diff --git a/scripts/generate_minimax_h3.test.js b/scripts/generate_minimax_h3.test.js
index 30d380075b..e33ef440e2 100644
--- a/scripts/generate_minimax_h3.test.js
+++ b/scripts/generate_minimax_h3.test.js
@@ -1087,7 +1087,8 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {
// what the filesystem will do, so readiness is proven by an actual write.
// POSIX-only: `os.chmod` on Windows toggles a file's read-only bit and cannot
// make a directory unwritable.
- it.skipIf(process.platform === 'win32')('disables the cache when its existing directory refuses a write', () => {
+ // Root ignores the 0o500 mode, so the write succeeds and nothing is refused.
+ it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('disables the cache when its existing directory refuses a write', () => {
const output = runPython(`${importRunner}\n${[
'import os, sys, tempfile',
captureWarnings,
diff --git a/server/lib/cliProviderRun.test.js b/server/lib/cliProviderRun.test.js
index e113d88b09..60a2bbb2c9 100644
--- a/server/lib/cliProviderRun.test.js
+++ b/server/lib/cliProviderRun.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi } from 'vitest';
+import { isProcessAlive } from '../test/processAlive.js';
// Wrap the REAL resolveWindowsExecutable in a spy (not a stub) so every
// existing real-spawn test below is unaffected (a no-op pass-through on the
@@ -355,8 +356,7 @@ describe('runCliProviderPrompt — credential-bootstrap process-group teardown',
// Signal 0 probes for existence without delivering anything. The group
// SIGTERM has to have reached the `sleep`, not just the trapping wrapper.
await new Promise(resolve => setTimeout(resolve, 200));
- let alive = true;
- try { process.kill(grandchildPid, 0); } catch { alive = false; }
+ const alive = isProcessAlive(grandchildPid);
if (alive) process.kill(grandchildPid, 'SIGKILL');
expect(alive).toBe(false);
});
diff --git a/server/lib/detachedSpawn.test.js b/server/lib/detachedSpawn.test.js
index f7c0ab7f96..3b3ab20deb 100644
--- a/server/lib/detachedSpawn.test.js
+++ b/server/lib/detachedSpawn.test.js
@@ -13,6 +13,7 @@ import { pathToFileURL } from 'url';
import { pinPlatform } from './testHelper.js';
import { killProcessTree } from './bufferedSpawn.js';
import { spawnDetached, reapDetached, reapAndCleanDetachedDirs, reattachDetached, isReattachable, isDetachedRunning, __detachedSpawnTesting } from './detachedSpawn.js';
+import { isProcessAlive } from '../test/processAlive.js';
// Only a win32 cancel reaches killProcessTree, so stubbing it is inert for
// every POSIX test here — and it lets the win32 tests assert the delegation on
@@ -75,9 +76,7 @@ const waitUntil = async (predicate, { timeoutMs = 5000 } = {}) => {
// `process.kill(pid, 0)` is the portable liveness probe; the `ps`-based helpers
// below are POSIX-only and unusable in the win32 tests.
-const isAliveForTest = (pid) => {
- try { process.kill(pid, 0); return true; } catch { return false; }
-};
+const isAliveForTest = isProcessAlive;
// Best-effort: kill whatever detached child a test left running under this
// control dir, and WAIT for it to actually exit, before the control dir gets
diff --git a/server/lib/ffmpeg.test.js b/server/lib/ffmpeg.test.js
index 644866bedc..5dbaa39d1c 100644
--- a/server/lib/ffmpeg.test.js
+++ b/server/lib/ffmpeg.test.js
@@ -347,14 +347,21 @@ describe('bt709TagFilter / supportsSetparamsFilter', () => {
});
it('caches a real probe result instead of re-shelling out per encode', async () => {
+ // Time an UNCACHED probe on this host and compare a burst of cached calls to
+ // it, rather than to an absolute budget: a fixed millisecond ceiling fails on
+ // a contended worker (GC pause, CPU steal) with no cache regression at all,
+ // while the ratio holds because both sides slow down together.
+ const probeStarted = performance.now();
const first = await supportsSetparamsFilter();
+ const uncachedMs = performance.now() - probeStarted;
// Only a real answer is cached, so this is only assertable when the host
// actually has ffmpeg — a missing binary is "unknown", not "unsupported".
if (!first) return;
- const started = Date.now();
- expect(await supportsSetparamsFilter()).toBe(true);
- // A cache hit is a property read; a second `-filters` listing is not.
- expect(Date.now() - started).toBeLessThan(50);
+ const burstStarted = performance.now();
+ for (let i = 0; i < 50; i += 1) expect(await supportsSetparamsFilter()).toBe(true);
+ // A cache hit is a property read; a second `-filters` listing per call is
+ // fifty process spawns, which cannot come in under one.
+ expect(performance.now() - burstStarted).toBeLessThan(uncachedMs);
});
it('pins all three properties in the filter string', () => {
diff --git a/server/lib/streamingSpawn.test.js b/server/lib/streamingSpawn.test.js
index 7f3c0ee380..82faae1934 100644
--- a/server/lib/streamingSpawn.test.js
+++ b/server/lib/streamingSpawn.test.js
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import { runStreamingCommand } from './streamingSpawn.js';
+import { isProcessAlive } from '../test/processAlive.js';
const NODE = process.execPath;
@@ -116,10 +117,7 @@ describe('runStreamingCommand — process-group teardown', () => {
// pid is what lets the assertion probe the real outcome.
const FORKING_WRAPPER = ['-c', 'sleep 30 & echo $!; wait'];
- const probeAlive = (pid) => {
- // Signal 0 tests for existence without delivering anything.
- try { process.kill(pid, 0); return true; } catch { return false; }
- };
+ const probeAlive = isProcessAlive;
it.skipIf(process.platform === 'win32')('takes the grandchild down with the wrapper on timeout', async () => {
let grandchildPid = null;
diff --git a/server/lib/tribeCadence.js b/server/lib/tribeCadence.js
index 12650d3c64..6a01e9ca92 100644
--- a/server/lib/tribeCadence.js
+++ b/server/lib/tribeCadence.js
@@ -35,7 +35,11 @@ export function daysSinceDate(dateStr) {
if (Number.isNaN(start.getTime())) return null;
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
- return Math.floor((today - start) / 86400000);
+ // Both operands are LOCAL midnights, so the gap is a whole number of days give
+ // or take an hour when a DST change falls between them (23h or 25h days).
+ // `floor` turned a spring-forward crossing into one day too few — rounding
+ // recovers the calendar-day count in every zone.
+ return Math.round((today - start) / 86400000);
}
// Cadence health for a tribe member: external / missing / overdue / soon /
diff --git a/server/services/beeperAttachments.js b/server/services/beeperAttachments.js
index 922db38975..fbf866a3f6 100644
--- a/server/services/beeperAttachments.js
+++ b/server/services/beeperAttachments.js
@@ -270,14 +270,20 @@ async function streamAssetToStore(mxcId, { maxBytes, extension }) {
}
};
+ const out = createWriteStream(tmpPath);
const failure = await pipeline(
Readable.fromWeb(response.body),
counter,
- createWriteStream(tmpPath),
+ out,
).then(() => null).catch((err) => err);
clearIdle();
if (failure) {
+ // pipeline can reject while the file's async open is still in flight (an
+ // abort landing right after the stream was created); the fd then opens and
+ // creates the file AFTER the rm below, leaving an orphan partial. A
+ // destroyed stream always emits 'close', so wait for it before removing.
+ if (!out.closed) await new Promise((resolve) => out.once('close', resolve));
await rm(tmpPath, { force: true }).catch(() => {});
throw exceeded ? failure : new ServerError(
`Attachment download failed: ${failure.message}`,
diff --git a/server/services/forgeAuth.test.js b/server/services/forgeAuth.test.js
index 60483e4d1a..2b16a97931 100644
--- a/server/services/forgeAuth.test.js
+++ b/server/services/forgeAuth.test.js
@@ -50,9 +50,13 @@ describe('forge credential resolution', () => {
it('pins the repository owner for PR operations without mutating ambient auth', async () => {
githubAccount();
const forge = await resolveForgeForRepo('/example/repo');
+ // The resolver strips every other ambient token; derive the expectation the
+ // same way so a CI/proxy environment that exports GITHUB_TOKEN can't fail it.
+ const expectedEnv = { ...process.env, GH_TOKEN: 'test-owner-token' };
+ for (const key of ['GITHUB_TOKEN', 'GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN']) delete expectedEnv[key];
expect(forge).toEqual({
cli: 'gh', host: 'github.com', owner: 'example-owner', account: 'example-owner',
- env: { ...process.env, GH_TOKEN: 'test-owner-token' }, identity: null
+ env: expectedEnv, identity: null
});
expect(spawn).toHaveBeenNthCalledWith(3, 'gh', ['auth', 'token', '-u', 'example-owner', '-h', 'github.com'], { shell: false });
expect(process.env.GH_TOKEN).toBe('test-ambient-token');
diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.js
index 37667dea9a..3dadae2cb4 100644
--- a/server/services/imageGen/codex.test.js
+++ b/server/services/imageGen/codex.test.js
@@ -625,7 +625,8 @@ describe('codex provider — image harvest', () => {
// "Cannot redefine property: copyFile" because module namespaces aren't
// configurable in ESM. macOS/Linux are the platforms PortOS actually
// runs on; this regression-locks the fix where it matters.
- const itPosix = process.platform === 'win32' ? it.skip : it;
+ // Also skip as root: root ignores the 0o555 mode, so the copy never fails.
+ const itPosix = process.platform === 'win32' || process.getuid?.() === 0 ? it.skip : it;
itPosix('routes async errors in the close handler through finalizeJobFailure (no unhandled rejections)', async () => {
const sessionId = '11111111-1111-4111-8111-111111111111';
const codexDir = join(TEST_HOME, '.codex', 'generated_images', sessionId);
diff --git a/server/services/videoGen/ref2vaWrapper.test.js b/server/services/videoGen/ref2vaWrapper.test.js
index 8ec66d4ad3..21873712f8 100644
--- a/server/services/videoGen/ref2vaWrapper.test.js
+++ b/server/services/videoGen/ref2vaWrapper.test.js
@@ -6,6 +6,7 @@ import { fileURLToPath } from 'url';
import { promisify } from 'util';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { findFfmpeg, findFfprobe } from '../../lib/ffmpeg.js';
+import { isProcessAlive } from '../../test/processAlive.js';
import {
composeRef2vaSegments,
MAX_REF2VA_XFADE_INPUTS,
@@ -104,9 +105,7 @@ describe('MiniMax H3 Ref2VA arbitrary-length wrapper', () => {
expect(wrapperProcess.exitCode != null || wrapperProcess.signalCode != null).toBe(true);
}, { timeout: 5000, interval: 25 });
await vi.waitFor(() => {
- let alive = true;
- try { process.kill(runtimePid, 0); } catch { alive = false; }
- expect(alive).toBe(false);
+ expect(isProcessAlive(runtimePid)).toBe(false);
}, { timeout: 5000, interval: 25 });
}, 25000);
diff --git a/server/test/processAlive.js b/server/test/processAlive.js
new file mode 100644
index 0000000000..01973fad8a
--- /dev/null
+++ b/server/test/processAlive.js
@@ -0,0 +1,23 @@
+import { readFileSync } from 'node:fs';
+
+// Liveness probe for tests that assert a child was killed. `process.kill(pid, 0)`
+// succeeds for a ZOMBIE — a dead child nobody has reaped yet. Where PID 1 is not
+// an init that reaps orphans (a container or microVM whose entrypoint is the
+// app), a killed grandchild stays a zombie forever, so a bare signal-0 probe
+// reports "still alive" for a process that is in fact gone. Treat state `Z`
+// (Linux /proc) as dead; elsewhere fall back to the signal-0 answer.
+export function isProcessAlive(pid) {
+ try {
+ process.kill(pid, 0);
+ } catch {
+ return false;
+ }
+ try {
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
+ // The comm field is parenthesised and may itself contain spaces/parens, so
+ // the state letter is the first token after the LAST ')'.
+ return stat.slice(stat.lastIndexOf(')') + 2, stat.lastIndexOf(')') + 3) !== 'Z';
+ } catch {
+ return true;
+ }
+}