@devries-cameron20 / t3code Mirror · read-only / commits / 47d98aca3a
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 08:00 UTC

fix(server): Windows terminal kill no longer waits on timeouts (#18519)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Max Weinbach committed Oct 16, 2026 at 19:17 UTC 47d98aca3a145507949f0ce2b3ab3fad096c76ca
5 files changed +264 -50
apps/server/src/terminal/Manager.test.ts
+102 -1
@@ -28,13 +28,15 @@ import * as PlatformError from "effect/PlatformError";
28 import * as Path from "effect/Path";
29 import * as Queue from "effect/Queue";
30 import * as Ref from "effect/Ref";
31 +import * as References from "effect/References";
32 import * as Schedule from "effect/Schedule";
33 import * as Schema from "effect/Schema";
34 import * as Scope from "effect/Scope";
35 import * as Stream from "effect/Stream";
36 +import * as SynchronizedRef from "effect/SynchronizedRef";
37 import * as TestClock from "effect/testing/TestClock";
38 import { ChildProcessSpawner } from "effect/process";
37 -import { expect } from "vite-plus/test";
39 +import { expect, vi } from "vite-plus/test";
40
41 import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
42 import * as ServerConfig from "../config.ts";
@@ -44,6 +46,11 @@ import * as ServerSettings from "../serverSettings.ts";
46 import * as TerminalManager from "./Manager.ts";
47 import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
48
49 +vi.mock("effect/SynchronizedRef", async (importOriginal) => {
50 + const original = await importOriginal<typeof SynchronizedRef>();
51 + return { ...original, make: vi.fn(original.make) };
52 +});
53 +
54 const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
55
56 class WaitForConditionError extends Data.TaggedError("WaitForConditionError")<{
@@ -61,6 +68,7 @@ class FakePtyProcess implements PtyAdapter.PtyProcess {
68 private readonly exitListeners = new Set<(event: PtyAdapter.PtyExitEvent) => void>();
69 killed = false;
70 exitOnSubscribe: PtyAdapter.PtyExitEvent | undefined;
71 + onKill: ((signal?: string) => void) | undefined;
72
73 constructor(pid: number) {
74 this.pid = pid;
@@ -83,6 +91,7 @@ class FakePtyProcess implements PtyAdapter.PtyProcess {
91 kill(signal?: string): void {
92 this.killed = true;
93 this.killSignals.push(signal);
94 + this.onKill?.(signal);
95 }
96
97 onData(callback: (data: string) => void): () => void {
@@ -106,6 +115,10 @@ class FakePtyProcess implements PtyAdapter.PtyProcess {
115 }
116 }
117
118 + get exitListenerCount(): number {
119 + return this.exitListeners.size;
120 + }
121 +
122 emitExit(event: PtyAdapter.PtyExitEvent): void {
123 for (const listener of this.exitListeners) {
124 listener(event);
@@ -1792,6 +1805,94 @@ it.layer(
1805 }).pipe(Effect.provide(TestClock.layer())),
1806 );
1807
1808 + it.effect("skips SIGKILL when the process exits during the grace period", () =>
1809 + Effect.gen(function* () {
1810 + const { manager, ptyAdapter } = yield* createManager(5, { processKillGraceMs: 10_000 });
1811 + yield* manager.open(openInput());
1812 + const process = ptyAdapter.processes[0];
1813 + expect(process).toBeDefined();
1814 + if (!process) return;
1815 +
1816 + const sigterm = yield* Deferred.make<void>();
1817 + process.onKill = (signal) => {
1818 + if (signal === "SIGTERM") Deferred.doneUnsafe(sigterm, Effect.void);
1819 + };
1820 +
1821 + yield* manager.close({ threadId: "thread-1" });
1822 + yield* Deferred.await(sigterm);
1823 + process.emitExit({ exitCode: 0, signal: 15 });
1824 + yield* TestClock.adjust("10 seconds");
1825 +
1826 + assert.deepEqual(process.killSignals, ["SIGTERM"]);
1827 + }).pipe(Effect.provide(TestClock.layer())),
1828 + );
1829 +
1830 + it.effect("does not retain a kill fiber that finishes before registration", () =>
1831 + Effect.gen(function* () {
1832 + let managerState:
1833 + | SynchronizedRef.SynchronizedRef<{
1834 + killFibers: Map<PtyAdapter.PtyProcess, Fiber.Fiber<void, never>>;
1835 + }>
1836 + | undefined;
1837 + const originalMake = <A>(value: A) => Effect.sync(() => SynchronizedRef.makeUnsafe(value));
1838 + const makeSpy = vi.spyOn(SynchronizedRef, "make").mockImplementation((value) =>
1839 + originalMake(value).pipe(
1840 + Effect.map((ref) => {
1841 + if (typeof value === "object" && value !== null && "killFibers" in value) {
1842 + managerState = ref as typeof managerState;
1843 + }
1844 + return ref;
1845 + }),
1846 + ),
1847 + );
1848 + yield* Effect.addFinalizer(() => Effect.sync(() => makeSpy.mockRestore()));
1849 + for (const budget of [10, 15, 20, 25, 30, 40, 50, 75, 100, 150, 200, 500]) {
1850 + const { manager, ptyAdapter } = yield* createManager();
1851 + yield* manager.open(openInput());
1852 + const process = ptyAdapter.processes[0]!;
1853 + process.onKill = () => process.emitExit({ exitCode: 0, signal: 15 });
1854 + // Vary the caller's operation budget to cover child completion before
1855 + // and after the parent resumes its registration step.
1856 + yield* manager
1857 + .close({ threadId: "thread-1" })
1858 + .pipe(Effect.provideService(References.MaxOpsBeforeYield, budget));
1859 + yield* Effect.yieldNow;
1860 + expect(managerState).toBeDefined();
1861 + yield* Fiber.awaitAll(SynchronizedRef.getUnsafe(managerState!).killFibers.values());
1862 + expect(SynchronizedRef.getUnsafe(managerState!).killFibers.size, `budget ${budget}`).toBe(
1863 + 0,
1864 + );
1865 + expect(process.killSignals).toEqual(["SIGTERM"]);
1866 + }
1867 + }),
1868 + );
1869 +
1870 + it.effect("releases the exit listener when kill escalation is interrupted", () =>
1871 + Effect.gen(function* () {
1872 + const scope = yield* Scope.make("sequential");
1873 + const { manager, ptyAdapter } = yield* createManager(5, {
1874 + processKillGraceMs: 10_000,
1875 + }).pipe(Effect.provideService(Scope.Scope, scope));
1876 + yield* manager.open(openInput());
1877 + const process = ptyAdapter.processes[0];
1878 + expect(process).toBeDefined();
1879 + if (!process) return;
1880 +
1881 + const sigterm = yield* Deferred.make<void>();
1882 + process.onKill = (signal) => {
1883 + if (signal === "SIGTERM") Deferred.doneUnsafe(sigterm, Effect.void);
1884 + };
1885 + yield* manager.close({ threadId: "thread-1" });
1886 + yield* Deferred.await(sigterm);
1887 + assert.isAbove(process.exitListenerCount, 0);
1888 +
1889 + yield* Scope.close(scope, Exit.void);
1890 +
1891 + assert.equal(process.exitListenerCount, 0);
1892 + assert.deepEqual(process.killSignals, ["SIGTERM"]);
1893 + }).pipe(Effect.provide(TestClock.layer())),
1894 + );
1895 +
1896 it.effect("publishes closed events when terminals are explicitly closed", () =>
1897 Effect.gen(function* () {
1898 const { manager, getEvents } = yield* createManager();
apps/server/src/terminal/Manager.ts
+64 -41
@@ -41,6 +41,7 @@ import { mergePathEntries } from "@t3tools/shared/shell";
41 import { acpRegistryManagedBinaryDirectories } from "@t3tools/provider-acp-registry/server";
42 import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
43 import * as DateTime from "effect/DateTime";
44 +import * as Deferred from "effect/Deferred";
45 import * as Context from "effect/Context";
46 import * as Effect from "effect/Effect";
47 import * as Base64Url from "effect/encoding/Base64Url";
@@ -1566,6 +1567,11 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
1567 fiber: Fiber.Fiber<void, never>,
1568 ) {
1569 yield* modifyManagerState((state) => {
1570 + // The child may finish (and run its finalizer) before this registration.
1571 + // Check inside the synchronized update so completed fibers are not retained.
1572 + if (fiber.pollUnsafe() !== undefined) {
1573 + return [undefined, state] as const;
1574 + }
1575 const killFibers = new Map(state.killFibers);
1576 killFibers.set(process, fiber);
1577 return [undefined, { ...state, killFibers }] as const;
@@ -1577,49 +1583,66 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
1583 threadId: string,
1584 terminalId: string,
1585 ) {
1580 - const terminated = yield* Effect.try({
1581 - try: () => process.kill("SIGTERM"),
1582 - catch: (cause) =>
1583 - new TerminalProcessSignalError({
1584 - cause,
1585 - signal: "SIGTERM",
1586 - terminalPid: process.pid,
1587 - }),
1588 - }).pipe(
1589 - Effect.as(true),
1590 - Effect.catch((error) =>
1591 - Effect.logWarning("failed to kill terminal process", {
1592 - threadId,
1593 - terminalId,
1594 - signal: "SIGTERM",
1595 - cause: error,
1596 - }).pipe(Effect.as(false)),
1597 - ),
1598 - );
1599 - if (!terminated) {
1600 - return;
1601 - }
1602 -
1603 - yield* Effect.sleep(processKillGraceMs);
1586 + // Subscribe before SIGTERM so an immediate exit is not missed. Released with
1587 + // Effect.ensuring because a JS `finally` does not run when the fiber is interrupted.
1588 + const exited = Deferred.makeUnsafe<void>();
1589 + const unsubscribeExit = process.onExit(() => {
1590 + Deferred.doneUnsafe(exited, Effect.void);
1591 + });
1592 + yield* Effect.gen(function* () {
1593 + const terminated = yield* Effect.try({
1594 + try: () => process.kill("SIGTERM"),
1595 + catch: (cause) =>
1596 + new TerminalProcessSignalError({
1597 + cause,
1598 + signal: "SIGTERM",
1599 + terminalPid: process.pid,
1600 + }),
1601 + }).pipe(
1602 + Effect.as(true),
1603 + Effect.catch((error) =>
1604 + Effect.logWarning("failed to kill terminal process", {
1605 + threadId,
1606 + terminalId,
1607 + signal: "SIGTERM",
1608 + cause: error,
1609 + }).pipe(Effect.as(false)),
1610 + ),
1611 + );
1612 + if (!terminated) {
1613 + return;
1614 + }
1615
1605 - yield* Effect.try({
1606 - try: () => process.kill("SIGKILL"),
1607 - catch: (cause) =>
1608 - new TerminalProcessSignalError({
1609 - cause,
1610 - signal: "SIGKILL",
1611 - terminalPid: process.pid,
1612 - }),
1613 - }).pipe(
1614 - Effect.catch((error) =>
1615 - Effect.logWarning("failed to force-kill terminal process", {
1616 - threadId,
1617 - terminalId,
1618 - signal: "SIGKILL",
1619 - cause: error,
1616 + const exitedBeforeGrace = yield* Deferred.await(exited).pipe(
1617 + Effect.as(true),
1618 + Effect.timeoutOrElse({
1619 + duration: processKillGraceMs,
1620 + orElse: () => Effect.succeed(false),
1621 }),
1621 - ),
1622 - );
1622 + );
1623 + if (exitedBeforeGrace) {
1624 + return;
1625 + }
1626 +
1627 + yield* Effect.try({
1628 + try: () => process.kill("SIGKILL"),
1629 + catch: (cause) =>
1630 + new TerminalProcessSignalError({
1631 + cause,
1632 + signal: "SIGKILL",
1633 + terminalPid: process.pid,
1634 + }),
1635 + }).pipe(
1636 + Effect.catch((error) =>
1637 + Effect.logWarning("failed to force-kill terminal process", {
1638 + threadId,
1639 + terminalId,
1640 + signal: "SIGKILL",
1641 + cause: error,
1642 + }),
1643 + ),
1644 + );
1645 + }).pipe(Effect.ensuring(Effect.sync(unsubscribeExit)));
1646 });
1647
1648 const startKillEscalation = Effect.fn("terminal.startKillEscalation")(function* (
apps/server/src/terminal/nodePtyConsoleList.test.ts new
+70
@@ -0,0 +1,70 @@
1 +import * as NodeEvents from "node:events";
2 +import * as NodeModule from "node:module";
3 +
4 +import { afterEach, describe, expect, it } from "vite-plus/test";
5 +
6 +// Exercises the patched console-list helper in patches/node-pty@1.2.0-beta.15.patch.
7 +// The agent calls `require("child_process").fork` at call time, so replacing it on
8 +// the shared CJS module stands in for the forked helper on every platform.
9 +const requireCjs = NodeModule.createRequire(import.meta.url);
10 +const childProcess: typeof import("node:child_process") = requireCjs("child_process");
11 +const {
12 + WindowsPtyAgent,
13 +}: {
14 + WindowsPtyAgent: {
15 + prototype: { _getConsoleProcessList(this: { _innerPid: number }): Promise<number[]> };
16 + };
17 +} = requireCjs("node-pty/lib/windowsPtyAgent.js");
18 +const originalFork = childProcess.fork;
19 +
20 +const SHELL_PID = 4242;
21 +
22 +function getConsoleProcessList(
23 + driveHelper: (helper: NodeEvents.EventEmitter) => void,
24 +): Promise<number[]> {
25 + const helper = Object.assign(new NodeEvents.EventEmitter(), { kill: () => true });
26 + childProcess.fork = (() => {
27 + queueMicrotask(() => driveHelper(helper));
28 + return helper;
29 + }) as unknown as typeof childProcess.fork;
30 + return WindowsPtyAgent.prototype._getConsoleProcessList.call({ _innerPid: SHELL_PID });
31 +}
32 +
33 +describe("node-pty console process list helper", () => {
34 + afterEach(() => {
35 + childProcess.fork = originalFork;
36 + });
37 +
38 + it("returns the helper's list when it replies and then closes", async () => {
39 + const list = await getConsoleProcessList((helper) => {
40 + helper.emit("message", { consoleProcessList: [SHELL_PID, 5001, 5002] });
41 + helper.emit("exit", 0, null);
42 + helper.emit("close", 0, null);
43 + });
44 + expect(list).toEqual([SHELL_PID, 5001, 5002]);
45 + });
46 +
47 + it("keeps waiting for the reply when exit arrives before the IPC message", async () => {
48 + const list = await getConsoleProcessList((helper) => {
49 + helper.emit("exit", 0, null);
50 + helper.emit("message", { consoleProcessList: [SHELL_PID, 5001] });
51 + helper.emit("close", 0, null);
52 + });
53 + expect(list).toEqual([SHELL_PID, 5001]);
54 + });
55 +
56 + it("falls back to the shell PID when the helper closes without replying", async () => {
57 + const list = await getConsoleProcessList((helper) => {
58 + helper.emit("exit", 1, null);
59 + helper.emit("close", 1, null);
60 + });
61 + expect(list).toEqual([SHELL_PID]);
62 + });
63 +
64 + it("falls back to the shell PID when the helper fails to spawn", async () => {
65 + const list = await getConsoleProcessList((helper) => {
66 + helper.emit("error", Object.assign(new Error("spawn ENOENT"), { code: "ENOENT" }));
67 + });
68 + expect(list).toEqual([SHELL_PID]);
69 + });
70 +});
patches/node-pty@1.2.0-beta.15.patch
+25 -5
@@ -17,7 +17,7 @@ diff --git a/lib/windowsConoutConnection.js b/lib/windowsConoutConnection.js
17 diff --git a/lib/windowsPtyAgent.js b/lib/windowsPtyAgent.js
18 --- a/lib/windowsPtyAgent.js
19 +++ b/lib/windowsPtyAgent.js
20 -@@ -218,8 +218,14 @@
20 +@@ -218,13 +218,31 @@
21 return Promise.resolve([]);
22 }
23 return new Promise(function (resolve) {
@@ -25,11 +25,31 @@ diff --git a/lib/windowsPtyAgent.js b/lib/windowsPtyAgent.js
25 + // Node's watch mode sends its own messages over the helper's IPC channel.
26 + var agentEnv = Object.assign({}, process.env);
27 + delete agentEnv.WATCH_REPORT_DEPENDENCIES;
28 -+ var agent = (0, child_process_1.fork)(path.join(__dirname, 'conpty_console_list_agent'), [_this._innerPid.toString()], { env: agentEnv, execArgv: [] });
28 ++ var settled = false;
29 ++ var finish = function (list) {
30 ++ if (settled) return;
31 ++ settled = true;
32 ++ clearTimeout(timeout);
33 ++ resolve(list);
34 ++ };
35 ++ var agent = (0, child_process_1.fork)(path.join(__dirname, 'conpty_console_list_agent'), [_this._innerPid.toString()], { env: agentEnv, execArgv: [], windowsHide: true });
36 agent.on('message', function (message) {
30 -+ if (!Array.isArray(message.consoleProcessList)) {
37 +- clearTimeout(timeout);
38 +- resolve(message.consoleProcessList);
39 ++ if (!message || !Array.isArray(message.consoleProcessList)) {
40 + return;
41 + }
33 - clearTimeout(timeout);
34 - resolve(message.consoleProcessList);
42 ++ finish(message.consoleProcessList);
43 ++ });
44 ++ agent.on('error', function () {
45 ++ finish([_this._innerPid]);
46 ++ });
47 ++ agent.on('close', function () {
48 ++ finish([_this._innerPid]);
49 });
50 + var timeout = setTimeout(function () {
51 + // Something went wrong, just send back the shell PID
52 + agent.kill();
53 +- resolve([_this._innerPid]);
54 ++ finish([_this._innerPid]);
55 + }, 5000);
pnpm-lock.yaml
+3 -3
@@ -165,7 +165,7 @@ patchedDependencies:
165 expo-audio@58.0.9: 2c2f8c73a23d48804c8b537b8cd73c25eb331aa47d82eaa481c6766cb81e5add
166 expo-sharing@58.0.19: ad248759641ddd71b8331c09dbb3b18c8a551785f2df507533805babd3c0c124
167 expo-widgets@58.0.20: 8623cb034b720c5ef2da8012c765805a7298909bd92eaf8381f64dbde41b77dd
168 - node-pty@1.2.0-beta.15: f2fe901c61cde17986240002d05c172d5d0272d83ffaab8d0ebeb922763be414
168 + node-pty@1.2.0-beta.15: f1e680afec85f650699ea756f91f469844ec4c976f4f168492a45c6b3f67d651
169 react-native-gesture-handler@3.3.0: abe20e1d1c23549297cbbc818e14fe479b41455930d9663135d6b40fe359b626
170 react-native-keyboard-controller@1.22.7: f28d08f1233e3cce8b9324b4357d2b10f1ee040b8051bc87235b0fb95069b9bb
171 react-native-webview@14.0.1: 81caa279ec3dc1f81209062133b66e8f824e13f106cca57f1fa732a72c2ab378
@@ -692,7 +692,7 @@ importers:
692 version: 6.2.2
693 node-pty:
694 specifier: ^1.2.0-beta.15
695 - version: 1.2.0-beta.15(patch_hash=f2fe901c61cde17986240002d05c172d5d0272d83ffaab8d0ebeb922763be414)
695 + version: 1.2.0-beta.15(patch_hash=f1e680afec85f650699ea756f91f469844ec4c976f4f168492a45c6b3f67d651)
696 playwright-core:
697 specifier: 1.60.0
698 version: 1.60.0
@@ -21427,7 +21427,7 @@ snapshots:
21427
21428 node-mock-http@1.0.5: {}
21429
21430 - node-pty@1.2.0-beta.15(patch_hash=f2fe901c61cde17986240002d05c172d5d0272d83ffaab8d0ebeb922763be414):
21430 + node-pty@1.2.0-beta.15(patch_hash=f1e680afec85f650699ea756f91f469844ec4c976f4f168492a45c6b3f67d651):
21431 dependencies:
21432 node-addon-api: 7.1.1
21433