Elffuss BraidHub

kikocis/continue public

main · 13.7 KiBRawPermalink
1import { render } from "ink-testing-library";
2import React from "react";
3import { vi } from "vitest";
4
5import { TUIChat } from "../TUIChat.js";
6
7import { MockRemoteServer } from "./mockRemoteServer.js";
8import {
9 MockApiClient,
10 mockAssistant,
11 MockLlmApi,
12 MockMCPService,
13} from "./TUIChat.setup.js";
14
15// Shared mock FileIndex to avoid duplication
16const MOCK_FILE_INDEX = {
17 files: [
18 { path: "README.md", displayName: "README.md" },
19 { path: "src/index.ts", displayName: "src/index.ts" },
20 { path: "package.json", displayName: "package.json" },
21 ],
22 isIndexing: false,
23 error: null,
24};
25
26// Define RenderResult type to match ink-testing-library's Instance
27interface RenderResult {
28 stdin: {
29 write: (data: string) => void;
30 };
31 lastFrame: () => string | undefined;
32 rerender: (element: React.ReactElement) => void;
33 unmount: () => void;
34}
35
36export type TestMode = "normal" | "remote" | "both";
37
38export interface TestContext {
39 mode: "normal" | "remote";
40 renderResult: RenderResult;
41 server?: MockRemoteServer;
42 remoteUrl?: string;
43}
44
45export interface TestOptions {
46 mode?: TestMode;
47 serverSetup?: (server: MockRemoteServer) => void;
48 props?: any;
49}
50
51/**
52 * Runs a test in the specified mode(s)
53 * @param name Test name
54 * @param testFn Test function that receives the test context
55 * @param options Test options including mode and server setup
56 */
57export function runTest(
58 name: string,
59 testFn: (ctx: TestContext) => void | Promise<void>,
60 options: TestOptions = {},
61) {
62 const { mode = "both", serverSetup, props = {} } = options;
63 const modes = mode === "both" ? ["normal", "remote"] : [mode];
64
65 modes.forEach((testMode) => {
66 describe(`[${testMode.toUpperCase()} MODE]`, () => {
67 it(name, async () => {
68 // Import mocks from Vitest setup
69 const { useServices, useService } = await import(
70 "../../hooks/useService.js"
71 );
72 const mockUseServices = useServices as any;
73 const mockUseService = useService as any;
74
75 if (testMode === "remote") {
76 // Set up remote mode - use different mocks
77 mockUseServices.mockReturnValue({
78 services: {},
79 loading: false,
80 error: null,
81 allReady: true,
82 });
83
84 mockUseService.mockReturnValue({
85 value: null,
86 state: "idle",
87 error: null,
88 reload: vi.fn(() => Promise.resolve()),
89 });
90
91 const server = new MockRemoteServer();
92 const port = await server.start();
93 const remoteUrl = `http://localhost:${port}`;
94
95 // Apply any server setup
96 if (serverSetup) {
97 serverSetup(server);
98 }
99
100 let renderResult: RenderResult | null = null;
101 try {
102 renderResult = render(
103 React.createElement(TUIChat, { remoteUrl, ...props }),
104 ) as RenderResult;
105
106 await testFn({
107 mode: "remote",
108 renderResult,
109 server,
110 remoteUrl,
111 });
112 } finally {
113 // Clean up render instance first
114 if (renderResult) {
115 renderResult.unmount();
116 }
117 // Then stop the server
118 await server.stop();
119 }
120 } else {
121 // Normal mode - set up service mocks with ready services
122 mockUseServices.mockReturnValue({
123 services: {
124 auth: { authConfig: null, isAuthenticated: false },
125 config: { config: mockAssistant },
126 model: {
127 llmApi: new MockLlmApi(),
128 model: { provider: "test", name: "test" },
129 },
130 mcp: { mcpService: new MockMCPService() },
131 apiClient: { apiClient: new MockApiClient() },
132 },
133 loading: false,
134 error: null,
135 allReady: true,
136 });
137
138 mockUseService.mockImplementation(
139 (serviceName: string) =>
140 ({
141 value: (() => {
142 switch (serviceName) {
143 case "auth":
144 return { authConfig: null, isAuthenticated: false };
145 case "config":
146 return { config: mockAssistant };
147 case "model":
148 return {
149 llmApi: new MockLlmApi(),
150 model: { provider: "test", name: "test" },
151 };
152 case "mcp":
153 return { mcpService: new MockMCPService() };
154 case "apiClient":
155 return { apiClient: new MockApiClient() };
156 case "fileIndex":
157 return MOCK_FILE_INDEX;
158 default:
159 return null;
160 }
161 })(),
162 state: "ready" as const,
163 error: null,
164 reload: vi.fn(() => Promise.resolve()),
165 }) as any,
166 );
167
168 let renderResult: RenderResult | null = null;
169 try {
170 renderResult = render(
171 React.createElement(TUIChat, { ...props }),
172 ) as RenderResult;
173
174 await testFn({
175 mode: "normal",
176 renderResult,
177 });
178 } finally {
179 // Clean up render instance
180 if (renderResult) {
181 renderResult.unmount();
182 }
183 }
184 }
185 });
186 });
187 });
188}
189
190/**
191 * Runs a test suite in the specified mode(s)
192 * @param suiteName Suite name
193 * @param suiteFn Suite function that can use runTest
194 * @param defaultOptions Default options for all tests in the suite
195 */
196export function runTestSuite(
197 suiteName: string,
198 suiteFn: () => void,
199 defaultOptions: TestOptions = {},
200) {
201 const modes =
202 defaultOptions.mode === "both" || !defaultOptions.mode
203 ? ["normal", "remote"]
204 : [defaultOptions.mode];
205
206 modes.forEach((mode) => {
207 describe(`${suiteName} [${mode.toUpperCase()} MODE]`, () => {
208 // Store original functions to restore later
209 const originalRunTest = global.runTest;
210 const originalDescribe = (global as any).describe;
211
212 beforeAll(async () => {
213 const { useServices, useService } = await import(
214 "../../hooks/useService.js"
215 );
216 const mockUseServices = useServices as any;
217 const mockUseService = useService as any;
218
219 // Override runTest to only run in the current mode
220 global.runTest = (
221 name: string,
222 testFn: any,
223 options: TestOptions = {},
224 ) => {
225 // If test specifies a mode, only run if it matches current mode
226 const testMode = options.mode || "both";
227 if (testMode === "both" || testMode === mode) {
228 it(name, async () => {
229 if (mode === "remote") {
230 // Set up remote mode
231 mockUseServices.mockReturnValue({
232 services: {},
233 loading: false,
234 error: null,
235 allReady: true,
236 });
237
238 mockUseService.mockReturnValue({
239 value: null,
240 state: "idle",
241 error: null,
242 reload: vi.fn(() => Promise.resolve()),
243 });
244
245 const server = new MockRemoteServer();
246 const port = await server.start();
247 const remoteUrl = `http://localhost:${port}`;
248
249 // Apply any server setup
250 if (options.serverSetup) {
251 options.serverSetup(server);
252 }
253
254 let renderResult: RenderResult | null = null;
255 try {
256 renderResult = render(
257 React.createElement(TUIChat, {
258 remoteUrl,
259 ...options.props,
260 }),
261 ) as RenderResult;
262
263 await testFn({
264 mode: "remote",
265 renderResult,
266 server,
267 remoteUrl,
268 });
269 } finally {
270 // Clean up render instance first
271 if (renderResult) {
272 renderResult.unmount();
273 }
274 // Then stop the server
275 await server.stop();
276 }
277 } else {
278 // Normal mode
279 mockUseServices.mockReturnValue({
280 services: {
281 auth: { authConfig: null, isAuthenticated: false },
282 config: { config: mockAssistant },
283 model: {
284 llmApi: new MockLlmApi(),
285 model: { provider: "test", name: "test" },
286 },
287 mcp: { mcpService: new MockMCPService() },
288 apiClient: { apiClient: new MockApiClient() },
289 },
290 loading: false,
291 error: null,
292 allReady: true,
293 });
294
295 mockUseService.mockImplementation(
296 (serviceName: string) =>
297 ({
298 value: (() => {
299 switch (serviceName) {
300 case "auth":
301 return { authConfig: null, isAuthenticated: false };
302 case "config":
303 return { config: mockAssistant };
304 case "model":
305 return {
306 llmApi: new MockLlmApi(),
307 model: { provider: "test", name: "test" },
308 };
309 case "mcp":
310 return { mcpService: new MockMCPService() };
311 case "apiClient":
312 return { apiClient: new MockApiClient() };
313 case "fileIndex":
314 return MOCK_FILE_INDEX;
315 default:
316 return null;
317 }
318 })(),
319 state: "ready" as const,
320 error: null,
321 reload: vi.fn(() => Promise.resolve()),
322 }) as any,
323 );
324
325 let renderResult: RenderResult | null = null;
326 try {
327 renderResult = render(
328 React.createElement(TUIChat, { ...options.props }),
329 ) as RenderResult;
330
331 await testFn({
332 mode: "normal",
333 renderResult,
334 });
335 } finally {
336 // Clean up render instance
337 if (renderResult) {
338 renderResult.unmount();
339 }
340 }
341 }
342 });
343 }
344 };
345
346 // Override describe to prevent nested mode descriptions
347 (global as any).describe = ((name: string, fn: () => void) => {
348 // Just run the function directly, don't create another describe block
349 fn();
350 }) as any;
351 });
352
353 afterAll(() => {
354 global.runTest = originalRunTest;
355 (global as any).describe = originalDescribe;
356 });
357
358 suiteFn();
359 });
360 });
361}
362
363/**
364 * Helper to wait for server state changes in remote mode
365 */
366export async function waitForServerState(
367 server: MockRemoteServer,
368 predicate: (state: any) => boolean,
369 timeout: number = 5000,
370): Promise<void> {
371 const startTime = Date.now();
372
373 while (Date.now() - startTime < timeout) {
374 const state = (server as any).state || {};
375 if (predicate(state)) {
376 return;
377 }
378 await new Promise((resolve) => setTimeout(resolve, 50));
379 }
380
381 const finalState = (server as any).state || {};
382 throw new Error(
383 `Timeout waiting for server state: ${JSON.stringify(finalState)}`,
384 );
385}
386
387/**
388 * Helper to simulate user typing and sending a message
389 */
390export async function sendMessage(
391 ctx: TestContext,
392 message: string,
393 waitTime: number = 100,
394): Promise<void> {
395 const { renderResult } = ctx;
396
397 renderResult.stdin.write(message);
398 renderResult.stdin.write("\r");
399
400 // In remote mode, wait for the message to be processed
401 if (ctx.mode === "remote" && ctx.server) {
402 try {
403 await waitForServerState(
404 ctx.server,
405 (state) =>
406 state.messages?.some?.(
407 (m: any) => m.content === message && m.role === "user",
408 ),
409 2000,
410 );
411 } catch (error) {
412 // If waiting fails, continue anyway - the server might be slow
413 console.warn(
414 "Warning: Message might not have been processed by server:",
415 error,
416 );
417 }
418 // Extra wait for UI to poll and update
419 await new Promise((resolve) => setTimeout(resolve, 600)); // Slightly more than polling interval
420 }
421
422 await new Promise((resolve) => setTimeout(resolve, waitTime));
423}
424
425/**
426 * Helper to check if UI shows remote mode indicators
427 */
428export function expectRemoteMode(frame: string | undefined) {
429 if (!frame) throw new Error("Frame is undefined");
430
431 // Should show cyan color and remote indicator
432 expect(frame).toContain("◉");
433 expect(frame).toContain("Remote Mode");
434}
435
436/**
437 * Helper to check if UI shows normal mode indicators
438 */
439export function expectNormalMode(frame: string | undefined) {
440 if (!frame) throw new Error("Frame is undefined");
441
442 // Should show normal indicator
443 expect(frame).toContain("●");
444 expect(frame).toContain("Continue CLI");
445}
446
447// Make runTest available globally for test files
448declare global {
449 var runTest: (
450 name: string,
451 testFn: (ctx: TestContext) => void | Promise<void>,
452 options?: TestOptions,
453 ) => void;
454}
455
456global.runTest = runTest;