5080-signal-shutdown-extension-cleanup.test.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import chalk from "chalk";
  5. import { afterEach, describe, expect, test, vi } from "vitest";
  6. import { APP_NAME } from "../../../src/config.ts";
  7. import type { SessionManager } from "../../../src/core/session-manager.ts";
  8. import { InteractiveMode } from "../../../src/modes/interactive/interactive-mode.ts";
  9. // Regression for https://github.com/earendil-works/pi/issues/5080
  10. //
  11. // On SIGTERM/SIGHUP the graceful shutdown must emit `session_shutdown`
  12. // (runtimeHost.dispose) BEFORE touching the terminal. Extension teardown such
  13. // as removing a socket does not write to the tty, so it must not be skipped if
  14. // a later terminal-restore write fails on a dead or stalled terminal. The
  15. // interactive quit path (Ctrl+D, /quit) keeps the opposite order to preserve
  16. // the final TUI frame.
  17. type ShutdownThis = {
  18. isShuttingDown: boolean;
  19. unregisterSignalHandlers: () => void;
  20. runtimeHost: { dispose: () => Promise<void> };
  21. ui: { terminal: { drainInput: (ms: number) => Promise<void> } };
  22. stop: () => void;
  23. sessionManager: SessionManager;
  24. };
  25. type InteractiveModePrototypeWithShutdown = {
  26. shutdown(this: ShutdownThis, options?: { fromSignal?: boolean }): Promise<void>;
  27. };
  28. const interactiveModePrototype = InteractiveMode.prototype as unknown;
  29. const tempDirs: string[] = [];
  30. const originalStdoutIsTTY = Object.getOwnPropertyDescriptor(process.stdout, "isTTY");
  31. class ProcessExitError extends Error {}
  32. function createSessionManager(options: { sessionFile?: string } = {}): SessionManager {
  33. return {
  34. isPersisted: () => options.sessionFile !== undefined,
  35. getSessionFile: () => options.sessionFile,
  36. getSessionId: () => "test-session",
  37. getSessionDir: () => "/tmp/pi-sessions",
  38. usesDefaultSessionDir: () => true,
  39. } as unknown as SessionManager;
  40. }
  41. function createTempFile(): string {
  42. const dir = mkdtempSync(join(tmpdir(), "pi-shutdown-resume-hint-"));
  43. tempDirs.push(dir);
  44. const file = join(dir, "session.jsonl");
  45. writeFileSync(file, "\n");
  46. return file;
  47. }
  48. function setStdoutIsTTY(value: boolean): void {
  49. Object.defineProperty(process.stdout, "isTTY", { configurable: true, value });
  50. }
  51. function restoreStdoutIsTTY(): void {
  52. if (originalStdoutIsTTY) {
  53. Object.defineProperty(process.stdout, "isTTY", originalStdoutIsTTY);
  54. } else {
  55. Reflect.deleteProperty(process.stdout, "isTTY");
  56. }
  57. }
  58. function createContext(order: string[], sessionManager = createSessionManager()): ShutdownThis {
  59. return {
  60. isShuttingDown: false,
  61. unregisterSignalHandlers: vi.fn(),
  62. runtimeHost: {
  63. dispose: vi.fn(async () => {
  64. order.push("dispose");
  65. }),
  66. },
  67. ui: {
  68. terminal: {
  69. drainInput: vi.fn(async () => {
  70. order.push("drainInput");
  71. }),
  72. },
  73. },
  74. stop: vi.fn(() => {
  75. order.push("stop");
  76. }),
  77. sessionManager,
  78. };
  79. }
  80. async function callShutdown(context: ShutdownThis, options?: { fromSignal?: boolean }): Promise<void> {
  81. try {
  82. await (interactiveModePrototype as InteractiveModePrototypeWithShutdown).shutdown.call(context, options);
  83. } catch (error) {
  84. if (!(error instanceof ProcessExitError)) throw error;
  85. }
  86. }
  87. describe("InteractiveMode.shutdown ordering (#5080)", () => {
  88. afterEach(() => {
  89. vi.restoreAllMocks();
  90. restoreStdoutIsTTY();
  91. for (const dir of tempDirs.splice(0)) {
  92. rmSync(dir, { recursive: true, force: true });
  93. }
  94. });
  95. test("signal-triggered shutdown emits session_shutdown before terminal writes", async () => {
  96. vi.spyOn(process, "exit").mockImplementation((() => {
  97. throw new ProcessExitError();
  98. }) as typeof process.exit);
  99. const order: string[] = [];
  100. const context = createContext(order);
  101. await callShutdown(context, { fromSignal: true });
  102. expect(order).toEqual(["dispose", "drainInput", "stop"]);
  103. expect(context.isShuttingDown).toBe(true);
  104. expect(context.unregisterSignalHandlers).toHaveBeenCalledTimes(1);
  105. });
  106. test("interactive quit stops the TUI before emitting session_shutdown", async () => {
  107. vi.spyOn(process, "exit").mockImplementation((() => {
  108. throw new ProcessExitError();
  109. }) as typeof process.exit);
  110. const order: string[] = [];
  111. const context = createContext(order);
  112. await callShutdown(context);
  113. expect(order).toEqual(["drainInput", "stop", "dispose"]);
  114. });
  115. test("interactive quit prints a resume hint for persisted sessions", async () => {
  116. vi.spyOn(process, "exit").mockImplementation((() => {
  117. throw new ProcessExitError();
  118. }) as typeof process.exit);
  119. const stdoutWrite = vi
  120. .spyOn(process.stdout, "write")
  121. .mockImplementation((() => true) as typeof process.stdout.write);
  122. setStdoutIsTTY(true);
  123. const order: string[] = [];
  124. const context = createContext(order, createSessionManager({ sessionFile: createTempFile() }));
  125. await callShutdown(context);
  126. expect(order).toEqual(["drainInput", "stop", "dispose"]);
  127. expect(stdoutWrite).toHaveBeenCalledWith(
  128. `${chalk.dim("To resume this session:")} ${APP_NAME} --session test-session\n`,
  129. );
  130. });
  131. test("signal-triggered shutdown does not print a resume hint", async () => {
  132. vi.spyOn(process, "exit").mockImplementation((() => {
  133. throw new ProcessExitError();
  134. }) as typeof process.exit);
  135. const stdoutWrite = vi
  136. .spyOn(process.stdout, "write")
  137. .mockImplementation((() => true) as typeof process.stdout.write);
  138. setStdoutIsTTY(true);
  139. const order: string[] = [];
  140. const context = createContext(order, createSessionManager({ sessionFile: createTempFile() }));
  141. await callShutdown(context, { fromSignal: true });
  142. for (const call of stdoutWrite.mock.calls) {
  143. expect(call[0]).not.toContain("To resume this session:");
  144. }
  145. });
  146. test("re-entrant shutdown is a no-op", async () => {
  147. vi.spyOn(process, "exit").mockImplementation((() => {
  148. throw new ProcessExitError();
  149. }) as typeof process.exit);
  150. const order: string[] = [];
  151. const context = createContext(order);
  152. context.isShuttingDown = true;
  153. await callShutdown(context, { fromSignal: true });
  154. expect(order).toEqual([]);
  155. expect(context.runtimeHost.dispose).not.toHaveBeenCalled();
  156. });
  157. });