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

test: fake the timers in the two suites that slept 5.4s of real time (#5733)

Adam Eivya52201cd3ac7
diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsx
index a392e8824a..41c2573524 100644
--- a/client/src/pages/ChiefOfStaff.jsx
+++ b/client/src/pages/ChiefOfStaff.jsx
@@ -77,6 +77,12 @@ const CANVAS_AVATAR_STYLES = new Set([
// Shared brand gradient for the "CoS" wordmark headings (clipped to text).
const COS_TITLE_GRADIENT = 'linear-gradient(135deg, #6366f1, #8b5cf6, #06b6d4)';
+// How long the avatar keeps "speaking" after an event that gives it something to
+// say. Exported so tests drain the timer by this value rather than a literal —
+// a hardcoded drain that no longer covers the timer lets a state update escape
+// act() again.
+export const SPEAKING_MS = 2000;
+
function TabLoadFallback({ label }) {
return <div className="flex items-center justify-center py-12"><BrailleSpinner text={`Loading ${label}`} /></div>;
}
@@ -357,7 +363,7 @@ export default function ChiefOfStaff() {
const shortDesc = taskDesc ? taskDesc.substring(0, 60) + (taskDesc.length > 60 ? '...' : '') : 'Working on task...';
setStatusMessage(`Running: ${shortDesc}`);
setSpeaking(true);
- setTimeout(() => setSpeaking(false), 2000);
+ setTimeout(() => setSpeaking(false), SPEAKING_MS);
// Track active agent metadata for dynamic avatar resolution
if (data?.metadata) setActiveAgentMeta(data.metadata);
// Initialize empty output buffer for new agent
@@ -392,7 +398,7 @@ export default function ChiefOfStaff() {
const success = data?.result?.success;
setStatusMessage(success ? "Task completed successfully" : "Task failed - checking errors...");
setSpeaking(true);
- setTimeout(() => setSpeaking(false), 2000);
+ setTimeout(() => setSpeaking(false), SPEAKING_MS);
// Clear active agent metadata so avatar reverts to default
setActiveAgentMeta(null);
// Clean up live output buffer for completed agent to prevent memory growth
@@ -415,7 +421,7 @@ export default function ChiefOfStaff() {
setAgentState('investigating');
setStatusMessage(summarizeHealthIssues(data.issues));
setSpeaking(true);
- setTimeout(() => setSpeaking(false), 2000);
+ setTimeout(() => setSpeaking(false), SPEAKING_MS);
}
};
socket.on('cos:health:check', handleHealthCheck);
@@ -474,7 +480,7 @@ export default function ChiefOfStaff() {
setAgentState('thinking');
setStatusMessage("Starting daemon - scanning for tasks...");
setSpeaking(true);
- setTimeout(() => setSpeaking(false), 2000);
+ setTimeout(() => setSpeaking(false), SPEAKING_MS);
fetchData();
}
};
@@ -530,7 +536,7 @@ export default function ChiefOfStaff() {
setAgentState('thinking');
setStatusMessage("Evaluating tasks...");
setSpeaking(true);
- setTimeout(() => setSpeaking(false), 2000);
+ setTimeout(() => setSpeaking(false), SPEAKING_MS);
} catch (err) {
toast.error(err.message);
}
diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsx
index 3b506eb1ef..9edd49e53a 100644
--- a/client/src/pages/ChiefOfStaff.test.jsx
+++ b/client/src/pages/ChiefOfStaff.test.jsx
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor, fireEvent, act, within } from '@testing-library/react';
import { MemoryRouter, Routes, Route } from 'react-router';
@@ -61,7 +61,7 @@ vi.mock('../hooks/useProviderModels', () => ({
}),
}));
-const ChiefOfStaff = (await import('./ChiefOfStaff')).default;
+const { default: ChiefOfStaff, SPEAKING_MS } = await import('./ChiefOfStaff');
const config = {
avatarStyle: 'svg',
@@ -104,6 +104,16 @@ beforeEach(() => {
localLlm.getToolUseModels.mockResolvedValue({ models: [] });
});
+// Tests that drain a debounce or the avatar's speaking timer install fake timers
+// (see `withFakeTimers` below); this restores real ones for everyone else.
+afterEach(() => vi.useRealTimers());
+
+// `shouldAdvanceTime` keeps the clock ticking on its own so testing-library's
+// `waitFor`/`findBy*` — which poll on a (now faked) interval and do not know how
+// to pump vitest's clock — still resolve, while `advanceTimersByTimeAsync` can
+// still jump a timer window instantly instead of sleeping through it.
+const withFakeTimers = () => vi.useFakeTimers({ shouldAdvanceTime: true });
+
const renderConfigTab = () => render(
<MemoryRouter initialEntries={['/cos/config']}>
<Routes>
@@ -561,6 +571,7 @@ describe('ChiefOfStaff task-change subscriptions', () => {
});
it('coalesces a burst of task-store changes into a single refetch', async () => {
+ withFakeTimers();
renderTasksTab();
await waitFor(() => expect(api.getCosTasks).toHaveBeenCalled());
const before = api.getCosTasks.mock.calls.length;
@@ -578,7 +589,7 @@ describe('ChiefOfStaff task-change subscriptions', () => {
// running task's federation lease heartbeat), so the burst must settle into
// one refresh rather than one per event. Any extra flush would land inside
// the 400ms window the first one already closed.
- await act(async () => { await new Promise(resolve => setTimeout(resolve, 200)); });
+ await act(async () => { await vi.advanceTimersByTimeAsync(200); });
expect(api.getCosTasks.mock.calls.length).toBe(before + 1);
});
@@ -789,6 +800,7 @@ describe('ChiefOfStaff Issues card', () => {
// The live path: a health check finishing while the page is open pushes the
// issue over the socket rather than through fetchData.
it('names the issue arriving on a live health-check socket event', async () => {
+ withFakeTimers();
renderWithIssues([]);
// Wait for the clean first paint so the socket handler is registered.
for (const card of await issueCards()) expect(within(card).getByText('0')).toBeInTheDocument();
@@ -805,7 +817,7 @@ describe('ChiefOfStaff Issues card', () => {
expect(within(card).getByText('1')).toBeInTheDocument();
}
// Drain the >0 branch's speaking timer so no state update escapes act.
- await act(async () => { await new Promise((resolve) => setTimeout(resolve, 2100)); });
+ await act(async () => { await vi.advanceTimersByTimeAsync(SPEAKING_MS + 100); });
});
// Without these, deleting the `tone` prop would leave every tile neutral gray
@@ -843,6 +855,7 @@ describe('ChiefOfStaff Issues card', () => {
// health (tile, avatar state, status bubble) must come from the merged
// snapshot, or the bubble names an older issue than the tile is counting.
it('does not let a slow health read clobber a fresher socket-delivered check', async () => {
+ withFakeTimers();
const staleWarning = { type: 'warning', category: 'memory', message: 'Stale issue from the older read' };
api.getCosStatus.mockResolvedValue({ running: true, config, stats: {} });
// The slow read carries the OLDER timestamp; the socket event below is newer.
@@ -860,7 +873,8 @@ describe('ChiefOfStaff Issues card', () => {
await act(async () => {
handleHealthCheck({ metrics: { timestamp: '2026-01-02T00:00:00.000Z' }, issues: [memoryWarning] });
});
- await act(async () => { await new Promise((resolve) => setTimeout(resolve, 2100)); });
+ // Drain the >0 branch's speaking timer so no state update escapes act.
+ await act(async () => { await vi.advanceTimersByTimeAsync(SPEAKING_MS + 100); });
// Now force the slow batch to run again with its stale payload — the merge
// must keep the socket's newer check, for the tile AND the bubble.
diff --git a/server/lib/aiToolkit/providerStatus.test.js b/server/lib/aiToolkit/providerStatus.test.js
index b4271c514c..68c880fd22 100644
--- a/server/lib/aiToolkit/providerStatus.test.js
+++ b/server/lib/aiToolkit/providerStatus.test.js
@@ -860,14 +860,22 @@ describe('Provider Status Service', () => {
});
describe('init', () => {
+ // Fake time, not a real sleep: the recovery window under test is 1000ms and
+ // a real 1100ms sleep left only 100ms of slack on a loaded runner. Same
+ // pattern as the `stale recovery on read` describe below.
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
it('should clean up expired statuses on init', async () => {
// Mark provider unavailable with very short wait time
await statusService.markUsageLimit('test-provider', {
message: 'Test'
});
- // Wait for recovery time to pass
- await new Promise(resolve => setTimeout(resolve, 1100));
+ // Advance past the 1000ms defaultUsageLimitWait recovery window. 1100 (not
+ // 1001) keeps the intent — "past the window" — legible; with fake time the
+ // extra 100ms is free.
+ await vi.advanceTimersByTimeAsync(1100);
// Create new service and init (should clean up expired status)
const newService = createProviderStatusService({
@@ -876,7 +884,16 @@ describe('Provider Status Service', () => {
defaultUsageLimitWait: 1000
});
- await newService.init();
+ const loaded = await newService.init();
+
+ // init() itself must reset the expired entry in the cache it returns.
+ // Asserting only isAvailable() would pass even with the init cleanup
+ // deleted, because every reader re-applies the same recovery check on
+ // read (see server/lib/aiToolkit/AGENTS.md).
+ expect(loaded.providers['test-provider']).toMatchObject({
+ available: true,
+ reason: 'ok'
+ });
// Provider should now be available
expect(newService.isAvailable('test-provider')).toBe(true);