2791-fswatch-error-crash.test.ts 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import { execFileSync } from "node:child_process";
  2. import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } 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. /**
  7. * Regression test for https://github.com/earendil-works/pi-mono/issues/2791
  8. *
  9. * fs.watch() returns an FSWatcher (EventEmitter). If the watcher emits an
  10. * 'error' event after creation and no error handler is attached, Node.js
  11. * treats it as an uncaught exception and terminates the process.
  12. *
  13. * We test this by spawning a child process that:
  14. * 1. Sets up a custom theme with the watcher enabled
  15. * 2. Finds the FSWatcher via process._getActiveHandles()
  16. * 3. Emits a synthetic 'error' event on it
  17. * 4. If the watcher has no error handler -> crash (exit != 0) -> bug present
  18. * 5. If the watcher has an error handler -> clean exit (exit 0) -> bug fixed
  19. */
  20. describe("issue #2791 fs.watch error event crashes process", () => {
  21. let tempRoot: string;
  22. beforeEach(() => {
  23. tempRoot = mkdtempSync(join(tmpdir(), "pi-2791-"));
  24. const agentDir = join(tempRoot, "agent");
  25. const themesDir = join(agentDir, "themes");
  26. mkdirSync(themesDir, { recursive: true });
  27. // Copy dark.json as "custom-test" theme
  28. const darkThemePath = join(__dirname, "../../../src/modes/interactive/theme/dark.json");
  29. const darkTheme = JSON.parse(readFileSync(darkThemePath, "utf-8"));
  30. darkTheme.name = "custom-test";
  31. writeFileSync(join(themesDir, "custom-test.json"), JSON.stringify(darkTheme, null, 2));
  32. });
  33. afterEach(() => {
  34. rmSync(tempRoot, { recursive: true, force: true });
  35. });
  36. it("process should survive an error event on the theme FSWatcher", () => {
  37. const themeModulePath = join(__dirname, "../../../src/modes/interactive/theme/theme.ts").replace(/\\/g, "/");
  38. const agentDir = join(tempRoot, "agent").replace(/\\/g, "/");
  39. // Script that sets up the watcher and emits a synthetic error on it.
  40. // If no .on('error') handler is attached, EventEmitter.emit('error')
  41. // throws, which either crashes the process or gets caught by our try/catch.
  42. const scriptPath = join(tempRoot, "test-watcher-error.mts");
  43. writeFileSync(
  44. scriptPath,
  45. `
  46. import { setTheme, stopThemeWatcher } from "${themeModulePath}";
  47. process.env.PI_CODING_AGENT_DIR = "${agentDir}";
  48. setTheme("custom-test", true);
  49. // Find the FSWatcher among active handles
  50. const handles = (process as any)._getActiveHandles();
  51. const fsWatcher = handles.find((h: any) => h.constructor?.name === "FSWatcher");
  52. if (!fsWatcher) {
  53. process.stderr.write("no FSWatcher found among active handles\\n");
  54. process.exit(2);
  55. }
  56. const errorListenerCount = fsWatcher.listenerCount("error");
  57. if (errorListenerCount === 0) {
  58. process.stderr.write("BUG: FSWatcher has no error handler (issue #2791)\\n");
  59. }
  60. // Emitting 'error' on an EventEmitter with no error listener throws.
  61. // This simulates an async OS error (e.g. ReadDirectoryChangesW invalidation).
  62. try {
  63. fsWatcher.emit("error", new Error("simulated OS watcher failure"));
  64. } catch {
  65. process.stderr.write("error event was unhandled and threw\\n");
  66. process.exit(1);
  67. }
  68. stopThemeWatcher();
  69. process.exit(0);
  70. `,
  71. );
  72. let _stdout = "";
  73. let stderr = "";
  74. let exitCode: number;
  75. try {
  76. _stdout = execFileSync(process.execPath, [scriptPath], {
  77. timeout: 10000,
  78. encoding: "utf-8",
  79. env: { ...process.env, PI_CODING_AGENT_DIR: agentDir },
  80. stdio: ["pipe", "pipe", "pipe"],
  81. });
  82. exitCode = 0;
  83. } catch (err: unknown) {
  84. const e = err as { status: number; stdout: string; stderr: string };
  85. _stdout = e.stdout ?? "";
  86. stderr = e.stderr ?? "";
  87. exitCode = e.status ?? 1;
  88. }
  89. expect(exitCode, `Child crashed (exit ${exitCode}). stderr: ${stderr.trim()}`).toBe(0);
  90. });
  91. });