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