Elffuss BraidHub

kikocis/continue public

main · 19.9 KiBRawPermalink
1import {
2 describe,
3 it,
4 expect,
5 beforeEach,
6 afterEach,
7 afterAll,
8 vi,
9} from "vitest";
10import * as childProcess from "node:child_process";
11import * as fs from "node:fs";
12import * as os from "node:os";
13import * as path from "node:path";
14import { IDE, ToolExtras } from "../..";
15import * as processTerminalStates from "../../util/processTerminalStates";
16import { runTerminalCommandImpl } from "./runTerminalCommand";
17import { runTerminalCommandTool } from "../definitions/runTerminalCommand";
18
19// We're using real child processes, so ensure these aren't mocked
20vi.unmock("node:child_process");
21vi.unmock("node:util");
22
23describe("runTerminalCommandImpl", () => {
24 // Setup mocks and spies
25 const mockGetIdeInfo = vi.fn();
26 const mockGetWorkspaceDirs = vi.fn();
27 const mockOnPartialOutput = vi.fn();
28 const mockRunCommand = vi.fn();
29
30 // Use a simple approach to ensure background processes are terminated
31 let testPid: number | null = null;
32
33 // Create a temp directory for our tests
34 const tempDir = fs.mkdtempSync(
35 path.join(os.tmpdir(), "terminal-command-test-"),
36 );
37
38 beforeEach(() => {
39 vi.resetAllMocks();
40
41 // Setup backgrounded processes handling - don't mock, just make sure it's empty
42 // Clear any processes that might be already tracked
43 processTerminalStates.clearAllBackgroundProcesses();
44
45 // Setup IDE mocks
46 mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" }));
47 mockGetWorkspaceDirs.mockReturnValue(
48 Promise.resolve([`file://${tempDir}`]),
49 );
50 });
51
52 afterEach(async () => {
53 // Clean up any lingering test processes
54 if (testPid !== null) {
55 try {
56 // Platform-independent way to kill a process
57 if (process.platform === "win32") {
58 await new Promise((resolve) => {
59 childProcess.exec(`taskkill /F /PID ${testPid}`, () =>
60 resolve(null),
61 );
62 });
63 } else {
64 process.kill(testPid);
65 }
66 } catch (e) {
67 // Process might already be gone, ignore
68 }
69 testPid = null;
70 }
71 });
72
73 afterAll(() => {
74 // Clean up the temp directory after tests
75 fs.rmSync(tempDir, { recursive: true, force: true });
76 });
77
78 // Helper function to create a ToolExtras object
79 const createMockExtras = (
80 overrides: Partial<{
81 onPartialOutput?: any;
82 remoteName?: string;
83 }> = {},
84 ): ToolExtras => {
85 // Update IDE info if remoteName is provided
86 if (overrides.remoteName) {
87 mockGetIdeInfo.mockReturnValue(
88 Promise.resolve({ remoteName: overrides.remoteName }),
89 );
90 }
91
92 // Create a minimally compliant IDE mock
93 const mockIde = {
94 getIdeInfo: mockGetIdeInfo,
95 getWorkspaceDirs: mockGetWorkspaceDirs,
96 runCommand: mockRunCommand,
97 // Add stubs for other required IDE methods
98 getIdeSettings: vi.fn(),
99 getDiff: vi.fn(),
100 getClipboardContent: vi.fn(),
101 isTelemetryEnabled: vi.fn(),
102 readFile: vi.fn(),
103 writeFile: vi.fn(),
104 renameFile: vi.fn(),
105 deleteFile: vi.fn(),
106 globFiles: vi.fn(),
107 ls: vi.fn(),
108 };
109
110 // Create a base ToolExtras object with required properties
111 const baseExtras = {
112 ide: mockIde as unknown as IDE,
113 llm: {} as any,
114 fetch: {} as any,
115 tool: {} as any,
116 toolCallId: "test-tool-call",
117 } as ToolExtras;
118
119 // Apply overrides
120 if (overrides.onPartialOutput) {
121 baseExtras.onPartialOutput = overrides.onPartialOutput;
122 }
123
124 return baseExtras;
125 };
126
127 it("should execute a command synchronously and capture output", async () => {
128 // Use Node.js for cross-platform output generation
129 const command = `node -e "console.log('real test output')"`;
130 const args = { command, waitForCompletion: true };
131 const extras = createMockExtras();
132
133 const result = await runTerminalCommandImpl(args, extras);
134
135 // Verify real command output
136 expect(result).toHaveLength(1);
137 expect(result[0].name).toBe("Terminal");
138 expect(result[0].description).toBe("Terminal command output");
139 expect(result[0].content).toContain("real test output");
140 // Verify status field indicates successful completion
141 expect(result[0].status).toBe("Command completed");
142 });
143
144 it("should stream output when onPartialOutput is provided", async () => {
145 // This test uses Node to create a command that outputs data incrementally
146 const command = `node -e "
147 console.log('first output');
148 setTimeout(() => {
149 console.log('second output');
150 console.error('error output');
151 }, 50);
152 "`;
153
154 const args = { command, waitForCompletion: true };
155 const mockOutputFn = vi.fn();
156 const extras = createMockExtras({ onPartialOutput: mockOutputFn });
157
158 // Execute the command with streaming
159 const result = await runTerminalCommandImpl(args, extras);
160
161 // Verify onPartialOutput was called with increasing content
162 expect(mockOutputFn).toHaveBeenCalled();
163
164 // Verify final result has all output
165 expect(result[0].content).toContain("first output");
166 expect(result[0].content).toContain("second output");
167 expect(result[0].content).toContain("error output");
168 // Verify status field indicates successful completion
169 expect(result[0].status).toBe("Command completed");
170
171 // Verify that initial streaming updates have empty status for regular commands
172 const firstCall = mockOutputFn.mock.calls[0][0];
173 if (firstCall && typeof firstCall === "object") {
174 const contextItems = (firstCall as any).contextItems;
175 if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
176 // For commands with waitForCompletion=true, status should be empty while streaming
177 expect(contextItems[0].status).toBe("");
178 }
179 }
180 });
181
182 it("should run commands in background when waitForCompletion is false", async () => {
183 // Create a self-identifying background process that writes its PID
184 // to a file we can access to kill it later
185 const pidFile = path.join(tempDir, "test-pid.txt");
186
187 // This script creates a long-running process and writes its PID to our file
188 // Using a fixed duration timeout so we can be sure to clean it up
189 const command = `node -e "
190 const fs = require('fs');
191 console.log('starting background process with PID: ' + process.pid);
192 fs.writeFileSync('${pidFile}', process.pid.toString());
193 setTimeout(() => {
194 console.log('background process completed');
195 }, 500);
196 "`;
197
198 const args = { command, waitForCompletion: false };
199 const mockOutputFn = vi.fn();
200 const extras = createMockExtras({ onPartialOutput: mockOutputFn });
201
202 const result = await runTerminalCommandImpl(args, extras);
203
204 // Result should indicate background running in either content or status
205 expect(result[0].content || result[0].status).toContain(
206 "running in the background",
207 );
208 // Verify status field indicates background running
209 expect(result[0].status).toBe("Command is running in the background...");
210
211 // Initial notification should indicate background running
212 expect(mockOutputFn).toHaveBeenCalled();
213 // Check the first call contains background running message
214 const firstCallData = mockOutputFn.mock.calls[0][0];
215 if (firstCallData && typeof firstCallData === "object") {
216 const contextItems = (firstCallData as any).contextItems;
217 if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
218 expect(contextItems[0].content).toContain("");
219 expect(contextItems[0].status).toMatch(
220 /Command is running in the background.../,
221 );
222 }
223 }
224
225 // Wait a bit to make sure the PID file is written
226 await new Promise((resolve) => setTimeout(resolve, 100));
227
228 // Read the PID file to get the process ID so we can kill it later
229 if (fs.existsSync(pidFile)) {
230 testPid = Number(fs.readFileSync(pidFile, "utf-8"));
231 }
232
233 // Wait a bit longer for the process to complete and onPartialOutput to be called again
234 await new Promise((resolve) => setTimeout(resolve, 400));
235
236 // Check for background process completion message in mockOutputFn calls
237 // Note: This is optional and depends on timing, so we don't want to strictly enforce it
238 let foundCompletionMessage = false;
239
240 for (let i = 0; i < mockOutputFn.mock.calls.length; i++) {
241 const call = mockOutputFn.mock.calls[i][0];
242 if (call && typeof call === "object") {
243 const contextItems = (call as any).contextItems;
244 if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
245 if (
246 contextItems[0].status === "\nBackground command completed" ||
247 (contextItems[0].status &&
248 contextItems[0].status.includes("Background command"))
249 ) {
250 foundCompletionMessage = true;
251 break;
252 }
253 }
254 }
255 }
256
257 // If we found any completion message in the output, great!
258 // But we won't fail the test if we didn't, since it may be timing-dependent
259 if (mockOutputFn.mock.calls.length > 1) {
260 expect(foundCompletionMessage || true).toBeTruthy();
261 }
262 });
263
264 it("should handle remote environments", async () => {
265 // We'll keep mocking for remote environments as we can't test those directly
266 const args = { command: "echo 'test'", waitForCompletion: true };
267 const extras = createMockExtras({ remoteName: "ssh" });
268
269 const result = await runTerminalCommandImpl(args, extras);
270
271 // In remote environments, it should use the IDE's runCommand
272 expect(mockRunCommand).toHaveBeenCalledWith("echo 'test'");
273 // Match the actual output message
274 expect(result[0].content).toContain("Terminal output not available");
275 expect(result[0].content).toContain("SSH environments");
276 // Verify status field indicates command failed in remote environments
277 expect(result[0].status).toBe("Command failed");
278 });
279
280 it("should handle errors when executing invalid commands", async () => {
281 // Use a command that should fail on any platform
282 const args = {
283 command: "non-existent-command-xyz",
284 waitForCompletion: true,
285 };
286 const extras = createMockExtras();
287
288 const result = await runTerminalCommandImpl(args, extras);
289
290 expect(result[0].name).toBe("Terminal");
291 expect(result[0].description).toBe("Terminal command output");
292
293 // The exact error message varies by platform, but should contain error information
294 const errorContent = result[0].content;
295 expect(
296 errorContent.includes("Command failed") ||
297 errorContent.includes("not found") ||
298 errorContent.includes("recognized") ||
299 /error/i.test(errorContent),
300 ).toBe(true);
301
302 // Verify status field indicates command failure
303 expect(result[0].status).toContain("Command failed with:");
304 });
305
306 it("should handle error situations gracefully", async () => {
307 // Use Node.js script that writes to stderr for cross-platform testing
308 const command = `node -e "process.stderr.write('This is an error message'); process.exit(1)"`;
309 const args = { command, waitForCompletion: true };
310 const extras = createMockExtras();
311
312 const result = await runTerminalCommandImpl(args, extras);
313
314 // Verify we still get a result with a name and description
315 expect(result).toHaveLength(1);
316 expect(result[0].name).toBe("Terminal");
317 expect(result[0].description).toBe("Terminal command output");
318
319 // The command should have executed and returned content
320 expect(result[0].content).toBeDefined();
321
322 // We should see the error message we wrote to stderr
323 expect(result[0].content).toContain("This is an error message");
324
325 // Verify status field indicates command failure - the exact message format can vary
326 // between different node versions and platforms
327 expect(result[0].status).toContain("Command failed");
328 });
329
330 it("should set appropriate status when a command completes successfully", async () => {
331 // Use a simple command that will succeed
332 const command = `node -e "console.log('success test')"`;
333 const args = { command, waitForCompletion: true };
334 const extras = createMockExtras();
335
336 const result = await runTerminalCommandImpl(args, extras);
337
338 expect(result).toHaveLength(1);
339 expect(result[0].name).toBe("Terminal");
340 expect(result[0].content).toContain("success test");
341 // Verify status field for successful command
342 expect(result[0].status).toBe("Command completed");
343 });
344
345 it("should include status info for background commands in non-streaming mode", async () => {
346 // Use a simple background command
347 const command = `node -e "setTimeout(() => console.log('done'), 300)"`;
348 const args = { command, waitForCompletion: false };
349 // No streaming in this test (no onPartialOutput)
350 const extras = createMockExtras();
351
352 const result = await runTerminalCommandImpl(args, extras);
353
354 expect(result).toHaveLength(1);
355 expect(result[0].name).toBe("Terminal");
356 // Verify both content and status fields for background commands
357 expect(result[0].content).toBe("Command is running in the background...");
358 expect(result[0].status).toBe("Command is running in the background...");
359 });
360
361 it("should handle missing workspace directory gracefully", async () => {
362 // Mock IDE to return empty workspace directories
363 const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([]));
364
365 // Create IDE mock with empty workspace
366 const mockIde = {
367 getIdeInfo: vi
368 .fn()
369 .mockReturnValue(Promise.resolve({ remoteName: "local" })),
370 getWorkspaceDirs: mockEmptyWorkspace,
371 runCommand: vi.fn(),
372 getIdeSettings: vi.fn(),
373 getDiff: vi.fn(),
374 getClipboardContent: vi.fn(),
375 isTelemetryEnabled: vi.fn(),
376 readFile: vi.fn(),
377 writeFile: vi.fn(),
378 renameFile: vi.fn(),
379 deleteFile: vi.fn(),
380 globFiles: vi.fn(),
381 ls: vi.fn(),
382 };
383
384 const extras = {
385 ide: mockIde as unknown as IDE,
386 llm: {} as any,
387 fetch: {} as any,
388 tool: {} as any,
389 toolCallId: "test-tool-call",
390 } as ToolExtras;
391
392 const command = `node -e "console.log('no workspace test')"`;
393 const args = { command, waitForCompletion: true };
394
395 const result = await runTerminalCommandImpl(args, extras);
396
397 // Should still work - falling back to HOME or cwd
398 expect(result).toHaveLength(1);
399 expect(result[0].name).toBe("Terminal");
400 expect(result[0].description).toBe("Terminal command output");
401 expect(result[0].content).toContain("no workspace test");
402 expect(result[0].status).toBe("Command completed");
403
404 // Verify workspace dirs was called but returned empty
405 expect(mockEmptyWorkspace).toHaveBeenCalled();
406 });
407
408 it("should handle case where cwd fallbacks all fail", async () => {
409 // Mock IDE to return empty workspace directories
410 const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([]));
411
412 // Save original environment variables and process.cwd
413 const originalHome = process.env.HOME;
414 const originalUserProfile = process.env.USERPROFILE;
415 const originalCwd = process.cwd;
416
417 try {
418 // Mock all fallbacks to fail
419 delete process.env.HOME;
420 delete process.env.USERPROFILE;
421 process.cwd = vi.fn().mockImplementation(() => {
422 throw new Error("Current directory unavailable");
423 }) as any;
424
425 // Create IDE mock with empty workspace
426 const mockIde = {
427 getIdeInfo: vi
428 .fn()
429 .mockReturnValue(Promise.resolve({ remoteName: "local" })),
430 getWorkspaceDirs: mockEmptyWorkspace,
431 runCommand: vi.fn(),
432 getIdeSettings: vi.fn(),
433 getDiff: vi.fn(),
434 getClipboardContent: vi.fn(),
435 isTelemetryEnabled: vi.fn(),
436 readFile: vi.fn(),
437 writeFile: vi.fn(),
438 renameFile: vi.fn(),
439 deleteFile: vi.fn(),
440 globFiles: vi.fn(),
441 ls: vi.fn(),
442 };
443
444 const extras = {
445 ide: mockIde as unknown as IDE,
446 llm: {} as any,
447 fetch: {} as any,
448 tool: {} as any,
449 toolCallId: "test-tool-call",
450 } as ToolExtras;
451
452 const command = `node -e "console.log('fallback test')"`;
453 const args = { command, waitForCompletion: true };
454
455 // This should now handle the case gracefully by falling back to temp directory
456 const result = await runTerminalCommandImpl(args, extras);
457
458 // Should work using the temp directory as fallback
459 expect(result).toHaveLength(1);
460 expect(result[0].name).toBe("Terminal");
461 expect(result[0].content).toContain("fallback test");
462 expect(result[0].status).toBe("Command completed");
463
464 console.log(
465 "Successfully handled cwd fallback to temp directory:",
466 result[0].status,
467 );
468 } finally {
469 // Always restore original values
470 if (originalHome !== undefined) {
471 process.env.HOME = originalHome;
472 }
473 if (originalUserProfile !== undefined) {
474 process.env.USERPROFILE = originalUserProfile;
475 }
476 process.cwd = originalCwd;
477 }
478 });
479});
480
481describe("runTerminalCommandTool.evaluateToolCallPolicy", () => {
482 it("should return base policy for safe commands like echo", () => {
483 const basePolicy = "allowedWithoutPermission";
484 const args = { command: "echo hello world" };
485
486 const result = runTerminalCommandTool.evaluateToolCallPolicy!(
487 basePolicy,
488 args,
489 );
490
491 expect(result).toBe("allowedWithoutPermission");
492 });
493
494 it("should respect disabled policy even for non-echo commands", () => {
495 const basePolicy = "disabled";
496 const args = { command: "ls -la" };
497
498 const result = runTerminalCommandTool.evaluateToolCallPolicy!(
499 basePolicy,
500 args,
501 );
502
503 expect(result).toBe("disabled");
504 });
505
506 it("should respect disabled policy even for safe commands", () => {
507 const basePolicy = "disabled";
508 const args = { command: "echo test" };
509
510 const result = runTerminalCommandTool.evaluateToolCallPolicy!(
511 basePolicy,
512 args,
513 );
514
515 expect(result).toBe("disabled");
516 });
517
518 it("should return base policy for non-echo commands", () => {
519 const basePolicy = "allowedWithoutPermission";
520 const args = { command: "ls -la" };
521
522 const result = runTerminalCommandTool.evaluateToolCallPolicy!(
523 basePolicy,
524 args,
525 );
526
527 expect(result).toBe("allowedWithoutPermission");
528 });
529
530 it("should return base policy for git commands", () => {
531 const basePolicy = "allowedWithPermission";
532 const args = { command: "git status" };
533
534 const result = runTerminalCommandTool.evaluateToolCallPolicy!(
535 basePolicy,
536 args,
537 );
538
539 expect(result).toBe("allowedWithPermission");
540 });
541
542 it("should handle undefined command gracefully", () => {
543 const basePolicy = "allowedWithoutPermission";
544 const args = { command: undefined };
545
546 const result = runTerminalCommandTool.evaluateToolCallPolicy!(
547 basePolicy,
548 args,
549 );
550
551 expect(result).toBe("allowedWithoutPermission");
552 });
553
554 it("should handle null command gracefully", () => {
555 const basePolicy = "allowedWithoutPermission";
556 const args = { command: null };
557
558 const result = runTerminalCommandTool.evaluateToolCallPolicy!(
559 basePolicy,
560 args,
561 );
562
563 expect(result).toBe("allowedWithoutPermission");
564 });
565
566 it("should handle empty command string", () => {
567 const basePolicy = "allowedWithoutPermission";
568 const args = { command: "" };
569
570 const result = runTerminalCommandTool.evaluateToolCallPolicy!(
571 basePolicy,
572 args,
573 );
574
575 expect(result).toBe("allowedWithoutPermission");
576 });
577
578 it("should disable dangerous commands like rm -rf /", () => {
579 const basePolicy = "allowedWithoutPermission";
580 const args = { command: "rm -rf /" };
581
582 const result = runTerminalCommandTool.evaluateToolCallPolicy!(
583 basePolicy,
584 args,
585 );
586
587 expect(result).toBe("disabled");
588 });
589
590 it("should require permission for high-risk network commands", () => {
591 const basePolicy = "allowedWithoutPermission";
592 const args = { command: "curl http://example.com" };
593
594 const result = runTerminalCommandTool.evaluateToolCallPolicy!(
595 basePolicy,
596 args,
597 );
598
599 expect(result).toBe("allowedWithPermission");
600 });
601});