TypeScript
fix(server): Windows terminal kill no longer waits on timeouts (#18519)
Max Weinbach47d98aca3a14
diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.tsindex b803a7ee209..65197ab61fa 100644--- a/apps/server/src/terminal/Manager.test.ts+++ b/apps/server/src/terminal/Manager.test.ts@@ -28,13 +28,15 @@ import * as PlatformError from "effect/PlatformError";import * as Path from "effect/Path";import * as Queue from "effect/Queue";import * as Ref from "effect/Ref";+import * as References from "effect/References";import * as Schedule from "effect/Schedule";import * as Schema from "effect/Schema";import * as Scope from "effect/Scope";import * as Stream from "effect/Stream";+import * as SynchronizedRef from "effect/SynchronizedRef";import * as TestClock from "effect/testing/TestClock";import { ChildProcessSpawner } from "effect/process";-import { expect } from "vite-plus/test";+import { expect, vi } from "vite-plus/test";import * as ServerSecretStore from "../auth/ServerSecretStore.ts";import * as ServerConfig from "../config.ts";@@ -44,6 +46,11 @@ import * as ServerSettings from "../serverSettings.ts";import * as TerminalManager from "./Manager.ts";import * as PtyAdapter from "@t3tools/shared/PtyAdapter";+vi.mock("effect/SynchronizedRef", async (importOriginal) => {+ const original = await importOriginal<typeof SynchronizedRef>();+ return { ...original, make: vi.fn(original.make) };+});+const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));class WaitForConditionError extends Data.TaggedError("WaitForConditionError")<{@@ -61,6 +68,7 @@ class FakePtyProcess implements PtyAdapter.PtyProcess {private readonly exitListeners = new Set<(event: PtyAdapter.PtyExitEvent) => void>();killed = false;exitOnSubscribe: PtyAdapter.PtyExitEvent | undefined;+ onKill: ((signal?: string) => void) | undefined;constructor(pid: number) {this.pid = pid;@@ -83,6 +91,7 @@ class FakePtyProcess implements PtyAdapter.PtyProcess {kill(signal?: string): void {this.killed = true;this.killSignals.push(signal);+ this.onKill?.(signal);}onData(callback: (data: string) => void): () => void {@@ -106,6 +115,10 @@ class FakePtyProcess implements PtyAdapter.PtyProcess {}}+ get exitListenerCount(): number {+ return this.exitListeners.size;+ }+emitExit(event: PtyAdapter.PtyExitEvent): void {for (const listener of this.exitListeners) {listener(event);@@ -1792,6 +1805,94 @@ it.layer(}).pipe(Effect.provide(TestClock.layer())),);+ it.effect("skips SIGKILL when the process exits during the grace period", () =>+ Effect.gen(function* () {+ const { manager, ptyAdapter } = yield* createManager(5, { processKillGraceMs: 10_000 });+ yield* manager.open(openInput());+ const process = ptyAdapter.processes[0];+ expect(process).toBeDefined();+ if (!process) return;++ const sigterm = yield* Deferred.make<void>();+ process.onKill = (signal) => {+ if (signal === "SIGTERM") Deferred.doneUnsafe(sigterm, Effect.void);+ };++ yield* manager.close({ threadId: "thread-1" });+ yield* Deferred.await(sigterm);+ process.emitExit({ exitCode: 0, signal: 15 });+ yield* TestClock.adjust("10 seconds");++ assert.deepEqual(process.killSignals, ["SIGTERM"]);+ }).pipe(Effect.provide(TestClock.layer())),+ );++ it.effect("does not retain a kill fiber that finishes before registration", () =>+ Effect.gen(function* () {+ let managerState:+ | SynchronizedRef.SynchronizedRef<{+ killFibers: Map<PtyAdapter.PtyProcess, Fiber.Fiber<void, never>>;+ }>+ | undefined;+ const originalMake = <A>(value: A) => Effect.sync(() => SynchronizedRef.makeUnsafe(value));+ const makeSpy = vi.spyOn(SynchronizedRef, "make").mockImplementation((value) =>+ originalMake(value).pipe(+ Effect.map((ref) => {+ if (typeof value === "object" && value !== null && "killFibers" in value) {+ managerState = ref as typeof managerState;+ }+ return ref;+ }),+ ),+ );+ yield* Effect.addFinalizer(() => Effect.sync(() => makeSpy.mockRestore()));+ for (const budget of [10, 15, 20, 25, 30, 40, 50, 75, 100, 150, 200, 500]) {+ const { manager, ptyAdapter } = yield* createManager();+ yield* manager.open(openInput());+ const process = ptyAdapter.processes[0]!;+ process.onKill = () => process.emitExit({ exitCode: 0, signal: 15 });+ // Vary the caller's operation budget to cover child completion before+ // and after the parent resumes its registration step.+ yield* manager+ .close({ threadId: "thread-1" })+ .pipe(Effect.provideService(References.MaxOpsBeforeYield, budget));+ yield* Effect.yieldNow;+ expect(managerState).toBeDefined();+ yield* Fiber.awaitAll(SynchronizedRef.getUnsafe(managerState!).killFibers.values());+ expect(SynchronizedRef.getUnsafe(managerState!).killFibers.size, `budget ${budget}`).toBe(+ 0,+ );+ expect(process.killSignals).toEqual(["SIGTERM"]);+ }+ }),+ );++ it.effect("releases the exit listener when kill escalation is interrupted", () =>+ Effect.gen(function* () {+ const scope = yield* Scope.make("sequential");+ const { manager, ptyAdapter } = yield* createManager(5, {+ processKillGraceMs: 10_000,+ }).pipe(Effect.provideService(Scope.Scope, scope));+ yield* manager.open(openInput());+ const process = ptyAdapter.processes[0];+ expect(process).toBeDefined();+ if (!process) return;++ const sigterm = yield* Deferred.make<void>();+ process.onKill = (signal) => {+ if (signal === "SIGTERM") Deferred.doneUnsafe(sigterm, Effect.void);+ };+ yield* manager.close({ threadId: "thread-1" });+ yield* Deferred.await(sigterm);+ assert.isAbove(process.exitListenerCount, 0);++ yield* Scope.close(scope, Exit.void);++ assert.equal(process.exitListenerCount, 0);+ assert.deepEqual(process.killSignals, ["SIGTERM"]);+ }).pipe(Effect.provide(TestClock.layer())),+ );+it.effect("publishes closed events when terminals are explicitly closed", () =>Effect.gen(function* () {const { manager, getEvents } = yield* createManager();diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.tsindex a9145663d92..0be928ce98a 100644--- a/apps/server/src/terminal/Manager.ts+++ b/apps/server/src/terminal/Manager.ts@@ -41,6 +41,7 @@ import { mergePathEntries } from "@t3tools/shared/shell";import { acpRegistryManagedBinaryDirectories } from "@t3tools/provider-acp-registry/server";import { getTerminalLabel } from "@t3tools/shared/terminalLabels";import * as DateTime from "effect/DateTime";+import * as Deferred from "effect/Deferred";import * as Context from "effect/Context";import * as Effect from "effect/Effect";import * as Base64Url from "effect/encoding/Base64Url";@@ -1566,6 +1567,11 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(funcfiber: Fiber.Fiber<void, never>,) {yield* modifyManagerState((state) => {+ // The child may finish (and run its finalizer) before this registration.+ // Check inside the synchronized update so completed fibers are not retained.+ if (fiber.pollUnsafe() !== undefined) {+ return [undefined, state] as const;+ }const killFibers = new Map(state.killFibers);killFibers.set(process, fiber);return [undefined, { ...state, killFibers }] as const;@@ -1577,49 +1583,66 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(functhreadId: string,terminalId: string,) {- const terminated = yield* Effect.try({- try: () => process.kill("SIGTERM"),- catch: (cause) =>- new TerminalProcessSignalError({- cause,- signal: "SIGTERM",- terminalPid: process.pid,- }),- }).pipe(- Effect.as(true),- Effect.catch((error) =>- Effect.logWarning("failed to kill terminal process", {- threadId,- terminalId,- signal: "SIGTERM",- cause: error,- }).pipe(Effect.as(false)),- ),- );- if (!terminated) {- return;- }-- yield* Effect.sleep(processKillGraceMs);+ // Subscribe before SIGTERM so an immediate exit is not missed. Released with+ // Effect.ensuring because a JS `finally` does not run when the fiber is interrupted.+ const exited = Deferred.makeUnsafe<void>();+ const unsubscribeExit = process.onExit(() => {+ Deferred.doneUnsafe(exited, Effect.void);+ });+ yield* Effect.gen(function* () {+ const terminated = yield* Effect.try({+ try: () => process.kill("SIGTERM"),+ catch: (cause) =>+ new TerminalProcessSignalError({+ cause,+ signal: "SIGTERM",+ terminalPid: process.pid,+ }),+ }).pipe(+ Effect.as(true),+ Effect.catch((error) =>+ Effect.logWarning("failed to kill terminal process", {+ threadId,+ terminalId,+ signal: "SIGTERM",+ cause: error,+ }).pipe(Effect.as(false)),+ ),+ );+ if (!terminated) {+ return;+ }- yield* Effect.try({- try: () => process.kill("SIGKILL"),- catch: (cause) =>- new TerminalProcessSignalError({- cause,- signal: "SIGKILL",- terminalPid: process.pid,- }),- }).pipe(- Effect.catch((error) =>- Effect.logWarning("failed to force-kill terminal process", {- threadId,- terminalId,- signal: "SIGKILL",- cause: error,+ const exitedBeforeGrace = yield* Deferred.await(exited).pipe(+ Effect.as(true),+ Effect.timeoutOrElse({+ duration: processKillGraceMs,+ orElse: () => Effect.succeed(false),}),- ),- );+ );+ if (exitedBeforeGrace) {+ return;+ }++ yield* Effect.try({+ try: () => process.kill("SIGKILL"),+ catch: (cause) =>+ new TerminalProcessSignalError({+ cause,+ signal: "SIGKILL",+ terminalPid: process.pid,+ }),+ }).pipe(+ Effect.catch((error) =>+ Effect.logWarning("failed to force-kill terminal process", {+ threadId,+ terminalId,+ signal: "SIGKILL",+ cause: error,+ }),+ ),+ );+ }).pipe(Effect.ensuring(Effect.sync(unsubscribeExit)));});const startKillEscalation = Effect.fn("terminal.startKillEscalation")(function* (diff --git a/apps/server/src/terminal/nodePtyConsoleList.test.ts b/apps/server/src/terminal/nodePtyConsoleList.test.tsnew file mode 100644index 00000000000..b412f3c8502--- /dev/null+++ b/apps/server/src/terminal/nodePtyConsoleList.test.ts@@ -0,0 +1,70 @@+import * as NodeEvents from "node:events";+import * as NodeModule from "node:module";++import { afterEach, describe, expect, it } from "vite-plus/test";++// Exercises the patched console-list helper in patches/[email protected].+// The agent calls `require("child_process").fork` at call time, so replacing it on+// the shared CJS module stands in for the forked helper on every platform.+const requireCjs = NodeModule.createRequire(import.meta.url);+const childProcess: typeof import("node:child_process") = requireCjs("child_process");+const {+ WindowsPtyAgent,+}: {+ WindowsPtyAgent: {+ prototype: { _getConsoleProcessList(this: { _innerPid: number }): Promise<number[]> };+ };+} = requireCjs("node-pty/lib/windowsPtyAgent.js");+const originalFork = childProcess.fork;++const SHELL_PID = 4242;++function getConsoleProcessList(+ driveHelper: (helper: NodeEvents.EventEmitter) => void,+): Promise<number[]> {+ const helper = Object.assign(new NodeEvents.EventEmitter(), { kill: () => true });+ childProcess.fork = (() => {+ queueMicrotask(() => driveHelper(helper));+ return helper;+ }) as unknown as typeof childProcess.fork;+ return WindowsPtyAgent.prototype._getConsoleProcessList.call({ _innerPid: SHELL_PID });+}++describe("node-pty console process list helper", () => {+ afterEach(() => {+ childProcess.fork = originalFork;+ });++ it("returns the helper's list when it replies and then closes", async () => {+ const list = await getConsoleProcessList((helper) => {+ helper.emit("message", { consoleProcessList: [SHELL_PID, 5001, 5002] });+ helper.emit("exit", 0, null);+ helper.emit("close", 0, null);+ });+ expect(list).toEqual([SHELL_PID, 5001, 5002]);+ });++ it("keeps waiting for the reply when exit arrives before the IPC message", async () => {+ const list = await getConsoleProcessList((helper) => {+ helper.emit("exit", 0, null);+ helper.emit("message", { consoleProcessList: [SHELL_PID, 5001] });+ helper.emit("close", 0, null);+ });+ expect(list).toEqual([SHELL_PID, 5001]);+ });++ it("falls back to the shell PID when the helper closes without replying", async () => {+ const list = await getConsoleProcessList((helper) => {+ helper.emit("exit", 1, null);+ helper.emit("close", 1, null);+ });+ expect(list).toEqual([SHELL_PID]);+ });++ it("falls back to the shell PID when the helper fails to spawn", async () => {+ const list = await getConsoleProcessList((helper) => {+ helper.emit("error", Object.assign(new Error("spawn ENOENT"), { code: "ENOENT" }));+ });+ expect(list).toEqual([SHELL_PID]);+ });+});diff --git a/patches/[email protected] b/patches/[email protected]index 2232766cdb6..12544760799 100644--- a/patches/[email protected]+++ b/patches/[email protected]@@ -17,7 +17,7 @@ diff --git a/lib/windowsConoutConnection.js b/lib/windowsConoutConnection.jsdiff --git a/lib/windowsPtyAgent.js b/lib/windowsPtyAgent.js--- a/lib/windowsPtyAgent.js+++ b/lib/windowsPtyAgent.js-@@ -218,8 +218,14 @@+@@ -218,13 +218,31 @@return Promise.resolve([]);}return new Promise(function (resolve) {@@ -25,11 +25,31 @@ diff --git a/lib/windowsPtyAgent.js b/lib/windowsPtyAgent.js+ // Node's watch mode sends its own messages over the helper's IPC channel.+ var agentEnv = Object.assign({}, process.env);+ delete agentEnv.WATCH_REPORT_DEPENDENCIES;-+ var agent = (0, child_process_1.fork)(path.join(__dirname, 'conpty_console_list_agent'), [_this._innerPid.toString()], { env: agentEnv, execArgv: [] });++ var settled = false;++ var finish = function (list) {++ if (settled) return;++ settled = true;++ clearTimeout(timeout);++ resolve(list);++ };++ var agent = (0, child_process_1.fork)(path.join(__dirname, 'conpty_console_list_agent'), [_this._innerPid.toString()], { env: agentEnv, execArgv: [], windowsHide: true });agent.on('message', function (message) {-+ if (!Array.isArray(message.consoleProcessList)) {+- clearTimeout(timeout);+- resolve(message.consoleProcessList);++ if (!message || !Array.isArray(message.consoleProcessList)) {+ return;+ }- clearTimeout(timeout);- resolve(message.consoleProcessList);++ finish(message.consoleProcessList);++ });++ agent.on('error', function () {++ finish([_this._innerPid]);++ });++ agent.on('close', function () {++ finish([_this._innerPid]);});+ var timeout = setTimeout(function () {+ // Something went wrong, just send back the shell PID+ agent.kill();+- resolve([_this._innerPid]);++ finish([_this._innerPid]);+ }, 5000);diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2352964b28d..b429e4a0b8d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -165,7 +165,7 @@ patchedDependencies:[email protected]: 2c2f8c73a23d48804c8b537b8cd73c25eb331aa47d82eaa481c6766cb81e5add[email protected]: ad248759641ddd71b8331c09dbb3b18c8a551785f2df507533805babd3c0c124[email protected]: 8623cb034b720c5ef2da8012c765805a7298909bd92eaf8381f64dbde41b77dd- [email protected]: f2fe901c61cde17986240002d05c172d5d0272d83ffaab8d0ebeb922763be414+ [email protected]: f1e680afec85f650699ea756f91f469844ec4c976f4f168492a45c6b3f67d651[email protected]: abe20e1d1c23549297cbbc818e14fe479b41455930d9663135d6b40fe359b626[email protected]: f28d08f1233e3cce8b9324b4357d2b10f1ee040b8051bc87235b0fb95069b9bb[email protected]: 81caa279ec3dc1f81209062133b66e8f824e13f106cca57f1fa732a72c2ab378@@ -692,7 +692,7 @@ importers:version: 6.2.2node-pty:specifier: ^1.2.0-beta.15- version: 1.2.0-beta.15(patch_hash=f2fe901c61cde17986240002d05c172d5d0272d83ffaab8d0ebeb922763be414)+ version: 1.2.0-beta.15(patch_hash=f1e680afec85f650699ea756f91f469844ec4c976f4f168492a45c6b3f67d651)playwright-core:specifier: 1.60.0version: 1.60.0@@ -21427,7 +21427,7 @@ snapshots:- [email protected](patch_hash=f2fe901c61cde17986240002d05c172d5d0272d83ffaab8d0ebeb922763be414):+ [email protected](patch_hash=f1e680afec85f650699ea756f91f469844ec4c976f4f168492a45c6b3f67d651):dependencies:node-addon-api: 7.1.1