Repository navigation
Expand file tree
/
Copy pathsetup.ts
More file actions
389 lines (354 loc) · 13.7 KB
/
Copy pathsetup.ts
File metadata and controls
389 lines (354 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/**
* Global test setup for Vitest.
*
* - Extends expect with @testing-library/jest-dom matchers
* - Starts local HTTP mock backend for API mocking
* - Silences console output during tests (unless DEBUG_TESTS=1)
* - Mocks Tauri-specific modules that aren't available in test env
* - Resets rate limiter module-level state between tests
*/
import '@testing-library/jest-dom/vitest';
import { cleanup, configure } from '@testing-library/react';
import type React from 'react';
import { afterAll, afterEach, beforeEach, vi } from 'vitest';
// @ts-ignore - test-only JS module outside app/src
import {
clearRequestLog,
resetMockBehavior,
startMockServer,
stopMockServer,
} from '../../../scripts/mock-api-core.mjs';
// The full Vitest run is executed under v8 coverage instrumentation with a
// single worker (see test/vitest.config.ts), which makes individual renders
// markedly slower than an isolated, un-instrumented file run. Testing Library's
// default 1000ms async-utility timeout is too tight in that environment, so
// `findBy*`/`waitFor` assertions in render-heavy suites (e.g. the workflow
// orchestration tab) flake intermittently — and which test trips first is
// non-deterministic. Raising the global async-util budget removes that whole
// class of false timeouts without masking real failures: `waitFor`/`findBy`
// still resolve the instant their condition is met, this only widens the
// ceiling before they give up (well within the 30s testTimeout).
configure({ asyncUtilTimeout: 5000 });
const DEFAULT_TEST_MOCK_API_PORT = 5005;
function readMockApiPort() {
const rawPort = process.env.VITEST_MOCK_API_PORT ?? process.env.MOCK_API_PORT;
const port = rawPort ? Number(rawPort) : DEFAULT_TEST_MOCK_API_PORT;
return Number.isInteger(port) && port > 0 ? port : DEFAULT_TEST_MOCK_API_PORT;
}
const mockApiServer = await startMockServer(readMockApiPort(), { retryIfInUse: true });
const mockApiUrl = `http://localhost:${mockApiServer.port}`;
process.env.VITEST_MOCK_API_URL = mockApiUrl;
process.env.VITE_BACKEND_URL = mockApiUrl;
// Mock import.meta.env defaults for tests
vi.stubEnv('DEV', true);
vi.stubEnv('MODE', 'test');
vi.stubEnv('VITE_BACKEND_URL', mockApiUrl);
function createStorageMock(): Storage {
const store = new Map<string, string>();
return {
get length() {
return store.size;
},
clear() {
store.clear();
},
getItem(key: string) {
return store.has(key) ? store.get(key)! : null;
},
key(index: number) {
return Array.from(store.keys())[index] ?? null;
},
removeItem(key: string) {
store.delete(key);
},
setItem(key: string, value: string) {
store.set(String(key), String(value));
},
};
}
function ensureStorage(name: 'localStorage' | 'sessionStorage') {
const current = globalThis[name];
if (
current &&
typeof current.getItem === 'function' &&
typeof current.setItem === 'function' &&
typeof current.removeItem === 'function' &&
typeof current.clear === 'function'
) {
return;
}
Object.defineProperty(globalThis, name, {
value: createStorageMock(),
configurable: true,
writable: true,
});
}
ensureStorage('localStorage');
ensureStorage('sessionStorage');
// Polyfill window.matchMedia — used by Rive (@rive-app/react-webgl2) and
// some media-query hooks; not implemented in jsdom.
if (typeof window.matchMedia === 'undefined') {
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn((query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
}
// Polyfill ResizeObserver for cmdk/Radix components in jsdom
if (typeof globalThis.ResizeObserver === 'undefined') {
globalThis.ResizeObserver = class ResizeObserver {
observe() {}
unobserve() {}
disconnect() {}
};
}
// Polyfill scrollIntoView for cmdk in jsdom
if (typeof Element !== 'undefined' && !Element.prototype.scrollIntoView) {
Element.prototype.scrollIntoView = function () {};
}
// assistant-ui's thread viewport scrolls after a send. jsdom exposes scroll
// metrics but not the imperative `scrollTo` method used by that primitive.
if (typeof HTMLElement !== 'undefined' && !HTMLElement.prototype.scrollTo) {
HTMLElement.prototype.scrollTo = function () {};
}
// Lexical measures the DOM selection after controlled composer updates. jsdom
// implements Range but omits its layout methods.
if (typeof Range !== 'undefined' && !Range.prototype.getBoundingClientRect) {
Range.prototype.getBoundingClientRect = () => new DOMRect();
}
if (typeof Range !== 'undefined' && !Range.prototype.getClientRects) {
Range.prototype.getClientRects = () => [] as unknown as DOMRectList;
}
// Polyfill the Pointer Capture API for Radix primitives in jsdom.
// Radix's Select, Slider, Toggle and DropdownMenu call these unconditionally
// on pointerdown; jsdom implements none of them, so without this the very
// first pointer interaction throws instead of opening the control.
if (typeof Element !== 'undefined' && !Element.prototype.hasPointerCapture) {
Element.prototype.hasPointerCapture = () => false;
Element.prototype.setPointerCapture = () => {};
Element.prototype.releasePointerCapture = () => {};
}
// Polyfill IntersectionObserver for Radix lazy-mount internals in jsdom.
if (typeof globalThis.IntersectionObserver === 'undefined') {
globalThis.IntersectionObserver = class IntersectionObserver {
readonly root = null;
readonly rootMargin = '';
readonly thresholds: readonly number[] = [];
observe() {}
unobserve() {}
disconnect() {}
takeRecords(): IntersectionObserverEntry[] {
return [];
}
} as unknown as typeof IntersectionObserver;
}
// Polyfill PointerEvent for @testing-library/user-event's pointer sequences
// against Radix triggers. jsdom 28 still ships no PointerEvent constructor, so
// user-event falls back to MouseEvent and Radix's pointer handlers never fire.
if (typeof globalThis.PointerEvent === 'undefined') {
globalThis.PointerEvent = class PointerEvent extends MouseEvent {
readonly pointerId: number;
readonly pointerType: string;
readonly isPrimary: boolean;
constructor(type: string, params: PointerEventInit = {}) {
super(type, params);
this.pointerId = params.pointerId ?? 1;
this.pointerType = params.pointerType ?? 'mouse';
this.isPrimary = params.isPrimary ?? true;
}
} as unknown as typeof PointerEvent;
}
// The hardened `isTauri()` (in `utils/tauriCommands/common.ts`) checks both
// `coreIsTauri()` and `window.__TAURI_INTERNALS__.invoke`. Many existing test
// files mock `@tauri-apps/api/core::isTauri` to `true` to exercise the
// Tauri branch; without a matching IPC handle on `window` they would now
// regress to the non-Tauri path. Seed a no-op handle once globally so the
// IPC-readiness check passes by default. Tests that *want* the CEF gap
// behaviour can `delete window.__TAURI_INTERNALS__` in a `beforeEach`.
(
window as unknown as { __TAURI_INTERNALS__: { invoke: () => Promise<unknown> } }
).__TAURI_INTERNALS__ = { invoke: vi.fn(() => Promise.resolve()) };
// Mock Tauri APIs (not available in test env)
vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn(), isTauri: vi.fn(() => false) }));
vi.mock('@tauri-apps/api/event', () => ({
listen: vi.fn().mockResolvedValue(vi.fn()),
emit: vi.fn(),
}));
vi.mock('@tauri-apps/plugin-deep-link', () => ({ onOpenUrl: vi.fn(), getCurrent: vi.fn() }));
vi.mock('@tauri-apps/plugin-opener', () => ({ open: vi.fn() }));
vi.mock('@tauri-apps/plugin-os', () => ({ platform: vi.fn().mockResolvedValue('macos') }));
// Mock tauriCommands to prevent Tauri API calls in tests
vi.mock('../utils/tauriCommands', () => ({
isTauri: vi.fn(() => false),
storeSession: vi.fn().mockResolvedValue(undefined),
getSessionToken: vi.fn().mockResolvedValue(null),
getAuthState: vi.fn().mockResolvedValue({ is_authenticated: false }),
logout: vi.fn().mockResolvedValue(undefined),
syncMemoryClientToken: vi.fn().mockResolvedValue(undefined),
openhumanServiceInstall: vi.fn().mockResolvedValue({ result: { state: 'Running' }, logs: [] }),
openhumanServiceStart: vi.fn().mockResolvedValue({ result: { state: 'Running' }, logs: [] }),
openhumanServiceStop: vi.fn().mockResolvedValue({ result: { state: 'Stopped' }, logs: [] }),
openhumanServiceStatus: vi.fn().mockResolvedValue({ result: { state: 'Running' }, logs: [] }),
openhumanServiceUninstall: vi
.fn()
.mockResolvedValue({ result: { state: 'NotInstalled' }, logs: [] }),
openhumanAgentServerStatus: vi.fn().mockResolvedValue({ result: { running: true }, logs: [] }),
openhumanUpdateMeetSettings: vi
.fn()
.mockResolvedValue({
result: { config: {}, workspace_dir: '/tmp', config_path: '/tmp/cfg.toml' },
logs: [],
}),
openhumanGetMeetSettings: vi
.fn()
.mockResolvedValue({
result: {
auto_orchestrator_handoff: false,
auto_join_policy: 'ask_each_time',
auto_summarize_policy: 'ask',
listen_only_default: true,
ingest_backend_transcripts: false,
},
logs: [],
}),
exchangeToken: vi.fn(),
invoke: vi.fn(),
}));
// Mock the config module
vi.mock('../utils/config', () => ({
CORE_RPC_URL: 'http://127.0.0.1:7788/rpc',
CORE_RPC_TIMEOUT_MS: 30_000,
IS_DEV: true,
IS_DEV_LIKE: true,
IS_PROD: false,
E2E_DEFAULT_CORE_MODE: '',
E2E_RESTART_APP_AS_RELOAD: false,
DEV_FORCE_ONBOARDING: false,
CHAT_ATTACHMENTS_ENABLED: true,
DERIVED_TRANSCRIPT_ENABLED: true,
SKILLS_GITHUB_REPO: 'test/skills',
GA_MEASUREMENT_ID: undefined,
OPENPANEL_API_URL: 'https://panel.tinyhumans.ai/api',
OPENPANEL_CLIENT_ID: undefined,
SENTRY_DSN: undefined,
SENTRY_RELEASE: 'openhuman@test',
SENTRY_SMOKE_TEST: false,
BACKEND_URL: mockApiUrl,
TELEGRAM_BOT_USERNAME: 'openhuman_bot',
LATEST_APP_DOWNLOAD_URL: 'https://github.com/tinyhumansai/openhuman/releases/latest',
OPENHUMAN_GITHUB_REPO_URL: 'https://github.com/tinyhumansai/openhuman',
APP_VERSION: '0.0.0-test',
APP_BINARY_VERSION: '0.0.0-test',
APP_ENVIRONMENT: 'test',
BUILD_SHA: 'test',
CORE_CARGO_VERSION: '0.0.0-test',
TAURI_CARGO_VERSION: '0.0.0-test',
DEV_JWT_TOKEN: undefined,
MASCOT_VOICE_ID: 'JBFqnCBsd6RMkjVDRZzb',
MASCOT_VOICE_MODEL_ID: 'eleven_multilingual_v2',
MASCOT_MANIFEST_URL:
'https://raw.githubusercontent.com/tinyhumansai/mascots/main/dist/mascots.json',
VOICE_MODE_FLAG_ENABLED: false,
// Production defaults, so a test that does not care about the voice entry
// point sees what a shipped build sees.
HUMAN_VOICE_REALTIME_ENABLED: true,
HUMAN_VOICE_SHOW_BOTH: false,
}));
vi.mock('../services/backendUrl', () => ({
getBackendUrl: vi.fn().mockImplementation(() => Promise.resolve(mockApiUrl)),
}));
// Mock redux-persist to avoid CJS/ESM issues in vitest
vi.mock('redux-persist', async () => {
const actual = await vi.importActual<Record<string, unknown>>('redux-persist');
return {
...actual,
// Override persistReducer to just return the base reducer
persistReducer: (_config: unknown, reducer: (s: unknown, a: unknown) => unknown) => reducer,
// Override persistStore to return a no-op persistor
persistStore: () => ({
subscribe: () => () => {},
getState: () => ({}),
dispatch: () => {},
purge: () => Promise.resolve(),
flush: () => Promise.resolve(),
pause: () => {},
persist: () => {},
}),
};
});
// Mock redux-persist integration
vi.mock('redux-persist/integration/react', () => ({
PersistGate: ({
children,
}: {
children: React.ReactNode;
loading?: unknown;
persistor?: unknown;
}) => children,
}));
// Mock redux-logger to avoid noisy test output
vi.mock('redux-logger', () => ({
createLogger: () => () => (next: (action: unknown) => unknown) => (action: unknown) =>
next(action),
}));
// Mock Sentry
vi.mock('@sentry/react', () => ({
init: vi.fn(),
ErrorBoundary: ({
children,
}: {
children: React.ReactNode;
fallback?: unknown;
onError?: unknown;
}) => children,
withScope: vi.fn(),
captureException: vi.fn(),
setTag: vi.fn(),
setUser: vi.fn(),
}));
// Silence console during tests to keep output clean. `debug`/`info` are
// included because error-path diagnostics across the app (e.g. VoicePanel
// "voice settings load failed", threadSlice "title refresh failed") use
// `console.debug`, which otherwise floods the test output with expected noise.
if (!process.env.DEBUG_TESTS) {
vi.spyOn(console, 'log').mockImplementation(() => {});
vi.spyOn(console, 'info').mockImplementation(() => {});
vi.spyOn(console, 'debug').mockImplementation(() => {});
vi.spyOn(console, 'warn').mockImplementation(() => {});
vi.spyOn(console, 'error').mockImplementation(() => {});
}
// Shared mock API server lifecycle for unit tests (default)
afterEach(() => {
clearRequestLog();
cleanup();
// Re-seed the IPC handle after any test that may have deleted it
// (e.g. tests exercising the CEF-gap branch of `isTauri()`). Without
// this, sibling tests in the same jsdom worker would silently regress
// to the non-Tauri path. Per graycyrus review on PR #1556.
(
window as unknown as { __TAURI_INTERNALS__: { invoke: () => Promise<unknown> } }
).__TAURI_INTERNALS__ = { invoke: vi.fn(() => Promise.resolve()) };
});
afterAll(async () => {
await stopMockServer();
});
// Reset rate limiter per-request counter before each test.
beforeEach(async () => {
resetMockBehavior();
try {
const { resetRequestCallCount } = await import('../lib/mcp/rateLimiter');
if (typeof resetRequestCallCount === 'function') {
resetRequestCallCount();
}
} catch {
// Module may be fully mocked in some test files — safe to skip
}
});