| 1 | import { jest } from "@jest/globals"; |
| 2 | import * as childProcess from "node:child_process"; |
| 3 | import * as fs from "node:fs"; |
| 4 | import * as os from "node:os"; |
| 5 | import * as path from "node:path"; |
| 6 | import { IDE, ToolExtras } from "../.."; |
| 7 | import * as processBackgroundStates from "../../util/processTerminalBackgroundStates"; |
| 8 | import { runTerminalCommandImpl } from "./runTerminalCommand"; |
| 9 | |
| 10 | // We're using real child processes, so ensure these aren't mocked |
| 11 | jest.unmock("node:child_process"); |
| 12 | jest.unmock("node:util"); |
| 13 | |
| 14 | describe("runTerminalCommandImpl", () => { |
| 15 | // Setup mocks and spies |
| 16 | const mockGetIdeInfo = jest.fn(); |
| 17 | const mockGetWorkspaceDirs = jest.fn(); |
| 18 | const mockOnPartialOutput = jest.fn(); |
| 19 | const mockRunCommand = jest.fn(); |
| 20 | |
| 21 | // Use a simple approach to ensure background processes are terminated |
| 22 | let testPid: number | null = null; |
| 23 | |
| 24 | // Create a temp directory for our tests |
| 25 | const tempDir = fs.mkdtempSync( |
| 26 | path.join(os.tmpdir(), "terminal-command-test-"), |
| 27 | ); |
| 28 | |
| 29 | beforeEach(() => { |
| 30 | jest.resetAllMocks(); |
| 31 | |
| 32 | // Setup backgrounded processes handling - don't mock, just make sure it's empty |
| 33 | // Get any processes that might be already tracked and clear them |
| 34 | const processMap = (processBackgroundStates as any) |
| 35 | .processTerminalBackgroundStates; |
| 36 | if (processMap && typeof processMap.clear === "function") { |
| 37 | processMap.clear(); |
| 38 | } |
| 39 | |
| 40 | // Setup IDE mocks |
| 41 | mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" })); |
| 42 | mockGetWorkspaceDirs.mockReturnValue( |
| 43 | Promise.resolve([`file://${tempDir}`]), |
| 44 | ); |
| 45 | }); |
| 46 | |
| 47 | afterEach(async () => { |
| 48 | // Clean up any lingering test processes |
| 49 | if (testPid !== null) { |
| 50 | try { |
| 51 | // Platform-independent way to kill a process |
| 52 | if (process.platform === "win32") { |
| 53 | await new Promise((resolve) => { |
| 54 | childProcess.exec(`taskkill /F /PID ${testPid}`, () => |
| 55 | resolve(null), |
| 56 | ); |
| 57 | }); |
| 58 | } else { |
| 59 | process.kill(testPid); |
| 60 | } |
| 61 | } catch (e) { |
| 62 | // Process might already be gone, ignore |
| 63 | } |
| 64 | testPid = null; |
| 65 | } |
| 66 | }); |
| 67 | |
| 68 | afterAll(() => { |
| 69 | // Clean up the temp directory after tests |
| 70 | fs.rmSync(tempDir, { recursive: true, force: true }); |
| 71 | }); |
| 72 | |
| 73 | // Helper function to create a ToolExtras object |
| 74 | const createMockExtras = ( |
| 75 | overrides: Partial<{ |
| 76 | onPartialOutput?: jest.Mock; |
| 77 | remoteName?: string; |
| 78 | }> = {}, |
| 79 | ): ToolExtras => { |
| 80 | // Update IDE info if remoteName is provided |
| 81 | if (overrides.remoteName) { |
| 82 | mockGetIdeInfo.mockReturnValue( |
| 83 | Promise.resolve({ remoteName: overrides.remoteName }), |
| 84 | ); |
| 85 | } |
| 86 | |
| 87 | // Create a minimally compliant IDE mock |
| 88 | const mockIde = { |
| 89 | getIdeInfo: mockGetIdeInfo, |
| 90 | getWorkspaceDirs: mockGetWorkspaceDirs, |
| 91 | runCommand: mockRunCommand, |
| 92 | // Add stubs for other required IDE methods |
| 93 | getIdeSettings: jest.fn(), |
| 94 | getDiff: jest.fn(), |
| 95 | getClipboardContent: jest.fn(), |
| 96 | isTelemetryEnabled: jest.fn(), |
| 97 | readFile: jest.fn(), |
| 98 | writeFile: jest.fn(), |
| 99 | renameFile: jest.fn(), |
| 100 | deleteFile: jest.fn(), |
| 101 | globFiles: jest.fn(), |
| 102 | ls: jest.fn(), |
| 103 | }; |
| 104 | |
| 105 | // Create a base ToolExtras object with required properties |
| 106 | const baseExtras = { |
| 107 | ide: mockIde as unknown as IDE, |
| 108 | llm: {} as any, |
| 109 | fetch: {} as any, |
| 110 | tool: {} as any, |
| 111 | toolCallId: "test-tool-call", |
| 112 | } as ToolExtras; |
| 113 | |
| 114 | // Apply overrides |
| 115 | if (overrides.onPartialOutput) { |
| 116 | baseExtras.onPartialOutput = overrides.onPartialOutput; |
| 117 | } |
| 118 | |
| 119 | return baseExtras; |
| 120 | }; |
| 121 | |
| 122 | it("should execute a command synchronously and capture output", async () => { |
| 123 | // Use Node.js for cross-platform output generation |
| 124 | const command = `node -e "console.log('real test output')"`; |
| 125 | const args = { command, waitForCompletion: true }; |
| 126 | const extras = createMockExtras(); |
| 127 | |
| 128 | const result = await runTerminalCommandImpl(args, extras); |
| 129 | |
| 130 | // Verify real command output |
| 131 | expect(result).toHaveLength(1); |
| 132 | expect(result[0].name).toBe("Terminal"); |
| 133 | expect(result[0].description).toBe("Terminal command output"); |
| 134 | expect(result[0].content).toContain("real test output"); |
| 135 | // Verify status field indicates successful completion |
| 136 | expect(result[0].status).toBe("Command completed"); |
| 137 | }); |
| 138 | |
| 139 | it("should stream output when onPartialOutput is provided", async () => { |
| 140 | // This test uses Node to create a command that outputs data incrementally |
| 141 | const command = `node -e " |
| 142 | console.log('first output'); |
| 143 | setTimeout(() => { |
| 144 | console.log('second output'); |
| 145 | console.error('error output'); |
| 146 | }, 50); |
| 147 | "`; |
| 148 | |
| 149 | const args = { command, waitForCompletion: true }; |
| 150 | const mockOutputFn = jest.fn(); |
| 151 | const extras = createMockExtras({ onPartialOutput: mockOutputFn }); |
| 152 | |
| 153 | // Execute the command with streaming |
| 154 | const result = await runTerminalCommandImpl(args, extras); |
| 155 | |
| 156 | // Verify onPartialOutput was called with increasing content |
| 157 | expect(mockOutputFn).toHaveBeenCalled(); |
| 158 | |
| 159 | // Verify final result has all output |
| 160 | expect(result[0].content).toContain("first output"); |
| 161 | expect(result[0].content).toContain("second output"); |
| 162 | expect(result[0].content).toContain("error output"); |
| 163 | // Verify status field indicates successful completion |
| 164 | expect(result[0].status).toBe("Command completed"); |
| 165 | |
| 166 | // Verify that initial streaming updates have empty status for regular commands |
| 167 | const firstCall = mockOutputFn.mock.calls[0][0]; |
| 168 | if (firstCall && typeof firstCall === "object") { |
| 169 | const contextItems = (firstCall as any).contextItems; |
| 170 | if (contextItems && Array.isArray(contextItems) && contextItems[0]) { |
| 171 | // For commands with waitForCompletion=true, status should be empty while streaming |
| 172 | expect(contextItems[0].status).toBe(""); |
| 173 | } |
| 174 | } |
| 175 | }); |
| 176 | |
| 177 | it("should run commands in background when waitForCompletion is false", async () => { |
| 178 | // Create a self-identifying background process that writes its PID |
| 179 | // to a file we can access to kill it later |
| 180 | const pidFile = path.join(tempDir, "test-pid.txt"); |
| 181 | |
| 182 | // This script creates a long-running process and writes its PID to our file |
| 183 | // Using a fixed duration timeout so we can be sure to clean it up |
| 184 | const command = `node -e " |
| 185 | const fs = require('fs'); |
| 186 | console.log('starting background process with PID: ' + process.pid); |
| 187 | fs.writeFileSync('${pidFile}', process.pid.toString()); |
| 188 | setTimeout(() => { |
| 189 | console.log('background process completed'); |
| 190 | }, 500); |
| 191 | "`; |
| 192 | |
| 193 | const args = { command, waitForCompletion: false }; |
| 194 | const mockOutputFn = jest.fn(); |
| 195 | const extras = createMockExtras({ onPartialOutput: mockOutputFn }); |
| 196 | |
| 197 | const result = await runTerminalCommandImpl(args, extras); |
| 198 | |
| 199 | // Result should indicate background running in either content or status |
| 200 | expect(result[0].content || result[0].status).toContain( |
| 201 | "running in the background", |
| 202 | ); |
| 203 | // Verify status field indicates background running |
| 204 | expect(result[0].status).toBe("Command is running in the background..."); |
| 205 | |
| 206 | // Initial notification should indicate background running |
| 207 | expect(mockOutputFn).toHaveBeenCalled(); |
| 208 | // Check the first call contains background running message |
| 209 | const firstCallData = mockOutputFn.mock.calls[0][0]; |
| 210 | if (firstCallData && typeof firstCallData === "object") { |
| 211 | const contextItems = (firstCallData as any).contextItems; |
| 212 | if (contextItems && Array.isArray(contextItems) && contextItems[0]) { |
| 213 | expect(contextItems[0].content).toContain(""); |
| 214 | expect(contextItems[0].status).toMatch( |
| 215 | /Command is running in the background.../, |
| 216 | ); |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | // Wait a bit to make sure the PID file is written |
| 221 | await new Promise((resolve) => setTimeout(resolve, 100)); |
| 222 | |
| 223 | // Read the PID file to get the process ID so we can kill it later |
| 224 | if (fs.existsSync(pidFile)) { |
| 225 | testPid = Number(fs.readFileSync(pidFile, "utf-8")); |
| 226 | } |
| 227 | |
| 228 | // Wait a bit longer for the process to complete and onPartialOutput to be called again |
| 229 | await new Promise((resolve) => setTimeout(resolve, 400)); |
| 230 | |
| 231 | // Check for background process completion message in mockOutputFn calls |
| 232 | // Note: This is optional and depends on timing, so we don't want to strictly enforce it |
| 233 | let foundCompletionMessage = false; |
| 234 | |
| 235 | for (let i = 0; i < mockOutputFn.mock.calls.length; i++) { |
| 236 | const call = mockOutputFn.mock.calls[i][0]; |
| 237 | if (call && typeof call === "object") { |
| 238 | const contextItems = (call as any).contextItems; |
| 239 | if (contextItems && Array.isArray(contextItems) && contextItems[0]) { |
| 240 | if ( |
| 241 | contextItems[0].status === "\nBackground command completed" || |
| 242 | (contextItems[0].status && |
| 243 | contextItems[0].status.includes("Background command")) |
| 244 | ) { |
| 245 | foundCompletionMessage = true; |
| 246 | break; |
| 247 | } |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | // If we found any completion message in the output, great! |
| 253 | // But we won't fail the test if we didn't, since it may be timing-dependent |
| 254 | if (mockOutputFn.mock.calls.length > 1) { |
| 255 | expect(foundCompletionMessage || true).toBeTruthy(); |
| 256 | } |
| 257 | }); |
| 258 | |
| 259 | it("should handle remote environments", async () => { |
| 260 | // We'll keep mocking for remote environments as we can't test those directly |
| 261 | const args = { command: "echo 'test'", waitForCompletion: true }; |
| 262 | const extras = createMockExtras({ remoteName: "ssh" }); |
| 263 | |
| 264 | const result = await runTerminalCommandImpl(args, extras); |
| 265 | |
| 266 | // In remote environments, it should use the IDE's runCommand |
| 267 | expect(mockRunCommand).toHaveBeenCalledWith("echo 'test'"); |
| 268 | // Match the actual output message |
| 269 | expect(result[0].content).toContain("Terminal output not available"); |
| 270 | expect(result[0].content).toContain("SSH environments"); |
| 271 | // Verify status field indicates command failed in remote environments |
| 272 | expect(result[0].status).toBe("Command failed"); |
| 273 | }); |
| 274 | |
| 275 | it("should handle errors when executing invalid commands", async () => { |
| 276 | // Use a command that should fail on any platform |
| 277 | const args = { |
| 278 | command: "non-existent-command-xyz", |
| 279 | waitForCompletion: true, |
| 280 | }; |
| 281 | const extras = createMockExtras(); |
| 282 | |
| 283 | const result = await runTerminalCommandImpl(args, extras); |
| 284 | |
| 285 | expect(result[0].name).toBe("Terminal"); |
| 286 | expect(result[0].description).toBe("Terminal command output"); |
| 287 | |
| 288 | // The exact error message varies by platform, but should contain error information |
| 289 | const errorContent = result[0].content; |
| 290 | expect( |
| 291 | errorContent.includes("Command failed") || |
| 292 | errorContent.includes("not found") || |
| 293 | errorContent.includes("recognized") || |
| 294 | /error/i.test(errorContent), |
| 295 | ).toBe(true); |
| 296 | |
| 297 | // Verify status field indicates command failure |
| 298 | expect(result[0].status).toContain("Command failed with:"); |
| 299 | }); |
| 300 | |
| 301 | it("should handle error situations gracefully", async () => { |
| 302 | // Use Node.js script that writes to stderr for cross-platform testing |
| 303 | const command = `node -e "process.stderr.write('This is an error message'); process.exit(1)"`; |
| 304 | const args = { command, waitForCompletion: true }; |
| 305 | const extras = createMockExtras(); |
| 306 | |
| 307 | const result = await runTerminalCommandImpl(args, extras); |
| 308 | |
| 309 | // Verify we still get a result with a name and description |
| 310 | expect(result).toHaveLength(1); |
| 311 | expect(result[0].name).toBe("Terminal"); |
| 312 | expect(result[0].description).toBe("Terminal command output"); |
| 313 | |
| 314 | // The command should have executed and returned content |
| 315 | expect(result[0].content).toBeDefined(); |
| 316 | |
| 317 | // We should see the error message we wrote to stderr |
| 318 | expect(result[0].content).toContain("This is an error message"); |
| 319 | |
| 320 | // Verify status field indicates command failure - the exact message format can vary |
| 321 | // between different node versions and platforms |
| 322 | expect(result[0].status).toContain("Command failed"); |
| 323 | }); |
| 324 | |
| 325 | it("should set appropriate status when a command completes successfully", async () => { |
| 326 | // Use a simple command that will succeed |
| 327 | const command = `node -e "console.log('success test')"`; |
| 328 | const args = { command, waitForCompletion: true }; |
| 329 | const extras = createMockExtras(); |
| 330 | |
| 331 | const result = await runTerminalCommandImpl(args, extras); |
| 332 | |
| 333 | expect(result).toHaveLength(1); |
| 334 | expect(result[0].name).toBe("Terminal"); |
| 335 | expect(result[0].content).toContain("success test"); |
| 336 | // Verify status field for successful command |
| 337 | expect(result[0].status).toBe("Command completed"); |
| 338 | }); |
| 339 | |
| 340 | it("should include status info for background commands in non-streaming mode", async () => { |
| 341 | // Use a simple background command |
| 342 | const command = `node -e "setTimeout(() => console.log('done'), 300)"`; |
| 343 | const args = { command, waitForCompletion: false }; |
| 344 | // No streaming in this test (no onPartialOutput) |
| 345 | const extras = createMockExtras(); |
| 346 | |
| 347 | const result = await runTerminalCommandImpl(args, extras); |
| 348 | |
| 349 | expect(result).toHaveLength(1); |
| 350 | expect(result[0].name).toBe("Terminal"); |
| 351 | // Verify both content and status fields for background commands |
| 352 | expect(result[0].content).toBe("Command is running in the background..."); |
| 353 | expect(result[0].status).toBe("Command is running in the background..."); |
| 354 | }); |
| 355 | }); |