import { afterEach, describe, expect, it, vi } from "vitest"; const state = vi.hoisted(() => ({ exit: undefined as | ((event: { exitCode: number; signal?: number }) => void) | undefined, pid: 0, })); vi.mock("@lydell/node-pty", () => ({ spawn: vi.fn() })); import { spawn } from "@lydell/node-pty"; import { openTerminal } from "../terminal.ts"; function mockPty() { return { get pid() { return state.pid; }, write: vi.fn(), resize: vi.fn(), pause: vi.fn(), resume: vi.fn(), kill: vi.fn(), onData: vi.fn(() => ({ dispose() {} })), onExit: vi.fn((callback) => { state.exit = callback; return { dispose() {} }; }), }; } async function terminal() { return openTerminal( { kind: "terminal", command: process.execPath }, process.cwd(), { changed() {}, data() {}, exit() {} }, ); } afterEach(() => { state.exit = undefined; state.pid = 0; vi.restoreAllMocks(); vi.useRealTimers(); }); describe("terminal lifecycle", () => { it("exposes a live pid getter once the PTY agent assigns it", async () => { vi.mocked(spawn).mockReturnValue(mockPty() as never); const handle = await terminal(); expect(handle.pid).toBeUndefined(); state.pid = 4242; expect(handle.pid).toBe(4242); state.exit?.({ exitCode: 0 }); await handle.dispose(); }); it("shares concurrent stop attempts and retries after an unsuccessful attempt", async () => { vi.useFakeTimers(); const pty = mockPty(); vi.mocked(spawn).mockReturnValue(pty as never); const handle = await terminal(); const first = handle.stop(); expect(handle.stop()).toBe(first); await vi.advanceTimersByTimeAsync(1_500); expect(await first).toBe(false); const retry = handle.stop(); state.exit?.({ exitCode: 0 }); await expect(retry).resolves.toBe(true); expect(pty.kill).toHaveBeenCalledTimes(3); await handle.dispose(); }); it("preserves ordinary spawn failures while identifying native binding failures", async () => { const missing = new Error("File not found: missing.exe"); vi.mocked(spawn).mockImplementation(() => { throw missing; }); await expect(terminal()).rejects.toBe(missing); vi.mocked(spawn).mockImplementation(() => { throw new Error("Failed to load native module: conpty.node"); }); await expect(terminal()).rejects.toMatchObject({ message: expect.stringContaining( "Native terminal support is unavailable", ), cause: expect.any(Error), }); }); });