Elffuss BraidHub

kikocis/continue public

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