bash-close-hang-windows.test.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import { execFileSync } from "node:child_process";
  2. import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  6. import { executeBashWithOperations } from "../src/core/bash-executor.ts";
  7. import { createBashTool, createLocalBashOperations } from "../src/core/tools/bash.ts";
  8. function toBashSingleQuotedArg(value: string): string {
  9. return `'${value.replace(/\\/g, "/").replace(/'/g, `'"'"'`)}'`;
  10. }
  11. function createInheritedStdioCommand(pidFile: string): string {
  12. const pidFileArg = toBashSingleQuotedArg(pidFile);
  13. return (
  14. 'node -e "' +
  15. "const fs=require('fs');" +
  16. "const {spawn}=require('child_process');" +
  17. "const child=spawn(process.execPath,['-e','setTimeout(()=>{},60000)'],{stdio:'inherit',detached:true});" +
  18. "fs.writeFileSync(process.argv[1], String(child.pid));" +
  19. "child.unref();" +
  20. "console.log('child-exiting');" +
  21. '" ' +
  22. pidFileArg
  23. );
  24. }
  25. function cleanupDetachedChild(pidFile: string): void {
  26. if (!existsSync(pidFile)) {
  27. return;
  28. }
  29. const pid = Number.parseInt(readFileSync(pidFile, "utf-8").trim(), 10);
  30. if (Number.isFinite(pid) && pid > 0) {
  31. try {
  32. execFileSync("taskkill", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore" });
  33. } catch {
  34. // Process may have already exited.
  35. }
  36. }
  37. }
  38. async function withTimeout<T>(promise: Promise<T>, ms: number, onTimeout: () => void): Promise<T> {
  39. return new Promise<T>((resolve, reject) => {
  40. const timeoutId = setTimeout(() => {
  41. onTimeout();
  42. reject(new Error(`Timed out after ${ms}ms`));
  43. }, ms);
  44. promise.then(
  45. (value) => {
  46. clearTimeout(timeoutId);
  47. resolve(value);
  48. },
  49. (error: unknown) => {
  50. clearTimeout(timeoutId);
  51. reject(error);
  52. },
  53. );
  54. });
  55. }
  56. function getTextOutput(result: { content?: Array<{ type: string; text?: string }> }): string {
  57. return (
  58. result.content
  59. ?.filter((block) => block.type === "text")
  60. .map((block) => block.text ?? "")
  61. .join("\n") ?? ""
  62. );
  63. }
  64. describe.skipIf(process.platform !== "win32")("Windows child-process close handling", () => {
  65. let testDir: string;
  66. beforeEach(() => {
  67. testDir = join(tmpdir(), `coding-agent-bash-close-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
  68. mkdirSync(testDir, { recursive: true });
  69. });
  70. afterEach(() => {
  71. rmSync(testDir, { recursive: true, force: true });
  72. });
  73. it("executeBash resolves after the shell exits even if inherited stdio handles stay open", async () => {
  74. const pidFile = join(testDir, "executor-grandchild.pid");
  75. const command = createInheritedStdioCommand(pidFile);
  76. const controller = new AbortController();
  77. try {
  78. const result = await withTimeout(
  79. executeBashWithOperations(command, process.cwd(), createLocalBashOperations(), {
  80. signal: controller.signal,
  81. }),
  82. 3000,
  83. () => {
  84. controller.abort();
  85. },
  86. );
  87. expect(result.output).toContain("child-exiting");
  88. expect(result.exitCode).toBe(0);
  89. expect(result.cancelled).toBe(false);
  90. } finally {
  91. controller.abort();
  92. cleanupDetachedChild(pidFile);
  93. }
  94. });
  95. it("bash tool resolves after the shell exits even if inherited stdio handles stay open", async () => {
  96. const pidFile = join(testDir, "tool-grandchild.pid");
  97. const command = createInheritedStdioCommand(pidFile);
  98. const controller = new AbortController();
  99. const bashTool = createBashTool(testDir);
  100. try {
  101. const result = await withTimeout(bashTool.execute("test-call", { command }, controller.signal), 3000, () => {
  102. controller.abort();
  103. });
  104. expect(getTextOutput(result)).toContain("child-exiting");
  105. } finally {
  106. controller.abort();
  107. cleanupDetachedChild(pidFile);
  108. }
  109. });
  110. it("times out cleanly when PATH cannot resolve taskkill", async () => {
  111. const pathKey = Object.keys(process.env).find((key) => key.toLowerCase() === "path") ?? "PATH";
  112. const originalPath = process.env[pathKey];
  113. process.env[pathKey] = "C:\\path-without-system32";
  114. try {
  115. const operations = createLocalBashOperations();
  116. await expect(
  117. operations.exec("Start-Sleep -Seconds 30", testDir, {
  118. onData: () => {},
  119. timeout: 0.2,
  120. }),
  121. ).rejects.toThrow("timeout:0.2");
  122. await expect(
  123. operations.exec("Write-Output 'runtime-alive'", testDir, {
  124. onData: () => {},
  125. }),
  126. ).resolves.toEqual({ exitCode: 0 });
  127. } finally {
  128. if (originalPath === undefined) {
  129. delete process.env[pathKey];
  130. } else {
  131. process.env[pathKey] = originalPath;
  132. }
  133. }
  134. });
  135. it("checks PowerShell 5 requirements before executing command side effects", async () => {
  136. const systemRoot = process.env.SystemRoot ?? process.env.windir ?? "C:\\Windows";
  137. const powershell = join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
  138. const operations = createLocalBashOperations({ shellPath: powershell });
  139. for (const [name, requirement] of [
  140. ["version", "#requires -Version 999"],
  141. ["module", "#requires -Modules DefinitelyMissingMavisModule"],
  142. ] as const) {
  143. const marker = join(testDir, `${name}-must-not-run.txt`);
  144. const quotedMarker = marker.replaceAll("'", "''");
  145. let output = "";
  146. const result = await operations.exec(
  147. `${requirement}\nSet-Content -LiteralPath '${quotedMarker}' -Value 'SHOULD_NOT_RUN'`,
  148. testDir,
  149. {
  150. onData: (chunk) => {
  151. output += chunk.toString("utf8");
  152. },
  153. },
  154. );
  155. expect(result.exitCode).not.toBe(0);
  156. expect(existsSync(marker)).toBe(false);
  157. expect(output.toLowerCase()).toMatch(/required|module/);
  158. }
  159. });
  160. it("does not expose fixed launcher variables to the PowerShell command", async () => {
  161. const systemRoot = process.env.SystemRoot ?? process.env.windir ?? "C:\\Windows";
  162. const powershell = join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
  163. const operations = createLocalBashOperations({ shellPath: powershell });
  164. let output = "";
  165. const result = await operations.exec(
  166. "if ($null -eq (Get-Variable -Name '__mavisSource' -ErrorAction SilentlyContinue)) { 'clean' } else { throw 'polluted' }",
  167. testDir,
  168. {
  169. onData: (chunk) => {
  170. output += chunk.toString("utf8");
  171. },
  172. },
  173. );
  174. expect(result.exitCode).toBe(0);
  175. expect(output).toContain("clean");
  176. });
  177. });