@devries-cameron20 / t3code Mirror · read-only / commits / 05f0d9be28
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 22, 12:00 UTC

fix(terminal): retain and pace slow fallback process queries (#24640)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 29, 2026 at 22:08 UTC 05f0d9be28218bdf5e91aa39462e23073379b48a
2 files changed +293 -110
apps/server/src/terminal/Manager.test.ts
+153
@@ -10,20 +10,25 @@ import {
10 TerminalProviderInstanceNotFoundError,
11 } from "@t3tools/contracts";
12 import * as HostProcess from "@t3tools/shared/HostProcess";
13 +import * as Clock from "effect/Clock";
14 import * as Deferred from "effect/Deferred";
15 +import * as Duration from "effect/Duration";
16 import * as Effect from "effect/Effect";
17 import * as Base64Url from "effect/encoding/Base64Url";
18 import * as Exit from "effect/Exit";
19 import * as Fiber from "effect/Fiber";
20 import * as FileSystem from "effect/FileSystem";
21 import * as Layer from "effect/Layer";
22 +import * as Option from "effect/Option";
23 import * as PlatformError from "effect/PlatformError";
24 import * as Path from "effect/Path";
25 +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
26 import * as Ref from "effect/Ref";
27 import * as Schema from "effect/Schema";
28 import * as Scope from "effect/Scope";
29 import * as Stream from "effect/Stream";
30 import * as SynchronizedRef from "effect/SynchronizedRef";
31 +import * as TestClock from "effect/testing/TestClock";
32 import { expect, vi } from "vite-plus/test";
33
34 import * as ProcessRunner from "../processRunner.ts";
@@ -756,6 +761,154 @@ it.layer(
761 }),
762 );
763
764 + // Answers process-table queries after `queryDuration`, honoring the caller's
765 + // timeout the way ProcessRunner's `timedOutResult` mode does.
766 + const slowProcessTable = (
767 + platform: "linux" | "win32",
768 + queryDuration: Duration.Input,
769 + queries: Array<{ start: number; end?: number }>,
770 + started: ReadonlyArray<Deferred.Deferred<void>>,
771 + ): ProcessRunner.ProcessRunner["Service"] => ({
772 + run: (input) =>
773 + Effect.gen(function* () {
774 + const query: { start: number; end?: number } = { start: yield* Clock.currentTimeMillis };
775 + queries.push(query);
776 + const deferred = started[queries.length - 1];
777 + if (deferred) yield* Deferred.succeed(deferred, undefined);
778 + const completed = yield* Effect.sleep(queryDuration).pipe(
779 + Effect.timeoutOption(input.timeout ?? "1 hour"),
780 + );
781 + query.end = yield* Clock.currentTimeMillis;
782 + return {
783 + stdout: Option.isNone(completed)
784 + ? ""
785 + : platform === "win32"
786 + ? "100|9000|node.exe\n"
787 + : " 100 9000 node\n",
788 + stderr: "",
789 + code: Option.isSome(completed) ? ChildProcessSpawner.ExitCode(0) : null,
790 + timedOut: Option.isNone(completed),
791 + stdoutTruncated: false,
792 + stderrTruncated: false,
793 + stdoutInvalidUtf8: false,
794 + stderrInvalidUtf8: false,
795 + };
796 + }),
797 + });
798 +
799 + const createFallbackManager = (
800 + platform: "linux" | "win32",
801 + runner: ProcessRunner.ProcessRunner["Service"],
802 + ) =>
803 + createManager(5, { subprocessPollIntervalMs: 1_000, processKillGraceMs: 0 }).pipe(
804 + Effect.provideService(ProcessRunner.ProcessRunner, runner),
805 + Effect.provide(layerWithHostPlatform(platform)),
806 + );
807 +
808 + it.effect.each(["linux", "win32"] as const)(
809 + "reports activity from a slow but successful %s process-table query",
810 + (platform) =>
811 + Effect.gen(function* () {
812 + const started = yield* Deferred.make<void>();
813 + const queries: Array<{ start: number; end?: number }> = [];
814 + const { manager, getEvents } = yield* createFallbackManager(
815 + platform,
816 + slowProcessTable(platform, "5 seconds", queries, [started]),
817 + );
818 +
819 + yield* manager.open(openInput());
820 + yield* TestClock.adjust("1 second");
821 + yield* Deferred.await(started);
822 + yield* TestClock.adjust("5 seconds");
823 +
824 + expect(
825 + (yield* getEvents).some(
826 + (event) =>
827 + event.type === "activity" && event.hasRunningSubprocess && event.label === "node",
828 + ),
829 + ).toBe(true);
830 + yield* manager.close({ threadId: "thread-1" });
831 + }).pipe(Effect.provide(TestClock.layer())),
832 + );
833 +
834 + it.effect("idles at least as long as a slow process-table query took before the next", () =>
835 + Effect.gen(function* () {
836 + const started = yield* Deferred.make<void>();
837 + const queries: Array<{ start: number; end?: number }> = [];
838 + const { manager } = yield* createFallbackManager(
839 + "linux",
840 + slowProcessTable("linux", "5 seconds", queries, [started]),
841 + );
842 +
843 + yield* manager.open(openInput());
844 + yield* TestClock.adjust("1 second");
845 + yield* Deferred.await(started);
846 + yield* TestClock.adjust("5 seconds");
847 + yield* TestClock.adjust(Duration.millis(19_999));
848 +
849 + expect(queries).toHaveLength(1);
850 + yield* TestClock.adjust("1 millis");
851 + const [slow, next] = queries;
852 + expect(next?.start).toBe(slow!.end! + 20_000);
853 + yield* manager.close({ threadId: "thread-1" });
854 + }).pipe(Effect.provide(TestClock.layer())),
855 + );
856 +
857 + it.effect("ends a hung process-table query and paces the retry", () =>
858 + Effect.gen(function* () {
859 + const started = yield* Deferred.make<void>();
860 + const queries: Array<{ start: number; end?: number }> = [];
861 + const { manager } = yield* createFallbackManager(
862 + "win32",
863 + slowProcessTable("win32", "1 day", queries, [started]),
864 + );
865 +
866 + yield* manager.open(openInput());
867 + yield* TestClock.adjust("1 second");
868 + yield* Deferred.await(started);
869 + yield* TestClock.adjust("2 minutes");
870 + yield* TestClock.adjust("2 minutes");
871 +
872 + const [hung, next] = queries;
873 + expect(hung!.end! - hung!.start).toBe(15_000);
874 + expect(next!.start - hung!.end!).toBe(60_000);
875 + yield* manager.close({ threadId: "thread-1" });
876 + }).pipe(Effect.provide(TestClock.layer())),
877 + );
878 +
879 + it.effect.each([
880 + ["linux", 1_000],
881 + ["win32", 1_500],
882 + ] as const)(
883 + "bounds closeIdle's %s query so other operations on the thread still run",
884 + ([platform, budgetMs]) =>
885 + Effect.gen(function* () {
886 + const started = yield* Deferred.make<void>();
887 + const queries: Array<{ start: number; end?: number }> = [];
888 + const { manager, ptyAdapter } = yield* createFallbackManager(
889 + platform,
890 + slowProcessTable(platform, "1 day", queries, [started]),
891 + );
892 + yield* manager.open(openInput());
893 +
894 + const closing = yield* manager
895 + .closeIdle({ threadId: "thread-1" })
896 + .pipe(Effect.forkChild({ startImmediately: true }));
897 + yield* Deferred.await(started);
898 + const resizing = yield* manager
899 + .resize({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, cols: 80, rows: 30 })
900 + .pipe(Effect.forkChild({ startImmediately: true }));
901 + yield* TestClock.adjust(Duration.millis(budgetMs));
902 +
903 + expect(closing.pollUnsafe()).toBeDefined();
904 + expect(resizing.pollUnsafe()).toBeDefined();
905 + expect(queries[0]!.end! - queries[0]!.start).toBe(budgetMs);
906 + expect(ptyAdapter.processes[0]!.resizeCalls).toEqual([{ cols: 80, rows: 30 }]);
907 + expect(ptyAdapter.processes[0]!.killed).toBe(false);
908 + yield* manager.close({ threadId: "thread-1" });
909 + }).pipe(Effect.provide(TestClock.layer())),
910 + );
911 +
912 it.effect("keeps terminals that get input or output while closeIdle checks them", () =>
913 Effect.gen(function* () {
914 const ptyAdapter = new FakePtyAdapter();
apps/server/src/terminal/Manager.ts
+140 -110
@@ -46,6 +46,7 @@ import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
46 import * as DateTime from "effect/DateTime";
47 import * as Deferred from "effect/Deferred";
48 import * as Context from "effect/Context";
49 +import * as Duration from "effect/Duration";
50 import * as Effect from "effect/Effect";
51 import * as Base64Url from "effect/encoding/Base64Url";
52 import * as Equal from "effect/Equal";
@@ -55,6 +56,7 @@ import * as FileSystem from "effect/FileSystem";
56 import * as Layer from "effect/Layer";
57 import * as Option from "effect/Option";
58 import * as Path from "effect/Path";
59 +import * as Result from "effect/Result";
60 import * as Schema from "effect/Schema";
61 import * as Scope from "effect/Scope";
62 import * as Stream from "effect/Stream";
@@ -95,6 +97,12 @@ const MAX_HISTORY_CHUNK_LENGTH = 16 * 1024;
97 const DEFAULT_PERSIST_DEBOUNCE_MS = 250;
98 const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
99 const MAX_SUBPROCESS_POLL_INTERVAL_MS = 60_000;
100 +// `ps` and WMI can take seconds on a loaded host and their tables are still
101 +// valid then; the timeout only ends a query that is truly stuck.
102 +const PROCESS_TABLE_QUERY_TIMEOUT = "15 seconds";
103 +// closeIdle queries while holding the thread lock, so it keeps a short budget
104 +// rather than stalling other operations on that thread behind a slow table.
105 +const CLOSE_IDLE_QUERY_TIMEOUT = { posix: "1 second", win32: "1500 millis" } as const;
106 // Discover children started without terminal input or output.
107 const QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS = 30;
108 const DEFAULT_PROCESS_KILL_GRACE_MS = 1_000;
@@ -675,8 +683,17 @@ interface TerminalProcessTableSnapshot {
683 readonly commandById: ReadonlyMap<number, string>;
684 }
685
678 -function subprocessSnapshotPollDelayMs(pollIntervalMs: number, failureCount: number): number {
679 - return Math.min(pollIntervalMs * 2 ** failureCount, MAX_SUBPROCESS_POLL_INTERVAL_MS);
686 +// Idles at least four times as long as the last fallback query took, so a slow
687 +// process table never keeps the poll loop busy most of the time.
688 +function subprocessSnapshotPollDelayMs(
689 + pollIntervalMs: number,
690 + failureCount: number,
691 + queryElapsedMs: number,
692 +): number {
693 + return Math.min(
694 + Math.max(pollIntervalMs * 2 ** failureCount, queryElapsedMs * 4),
695 + MAX_SUBPROCESS_POLL_INTERVAL_MS,
696 + );
697 }
698
699 function parsePosixProcessTable(stdout: string): TerminalProcessTableSnapshot {
@@ -764,6 +781,7 @@ const resolvePosixPsCommand = Effect.fn("terminal.resolvePosixPsCommand")(functi
781
782 const posixProcessTableSnapshot = Effect.fn("terminal.posixProcessTableSnapshot")(function* (
783 psCommand: string,
784 + timeout: Duration.Input,
785 ): Effect.fn.Return<
786 TerminalProcessTableSnapshot,
787 TerminalSubprocessCheckError,
@@ -774,7 +792,7 @@ const posixProcessTableSnapshot = Effect.fn("terminal.posixProcessTableSnapshot"
792 .run({
793 command: psCommand,
794 args: ["-eo", "pid=,ppid=,comm="],
777 - timeout: "1 second",
795 + timeout,
796 maxOutputBytes: 524_288,
797 outputMode: "truncate",
798 timeoutBehavior: "timedOutResult",
@@ -800,48 +818,46 @@ const posixProcessTableSnapshot = Effect.fn("terminal.posixProcessTableSnapshot"
818 return parsePosixProcessTable(result.stdout);
819 });
820
803 -const windowsProcessTableSnapshot = Effect.fn("terminal.windowsProcessTableSnapshot")(
804 - function* (): Effect.fn.Return<
805 - TerminalProcessTableSnapshot,
806 - TerminalSubprocessCheckError,
807 - ProcessRunner.ProcessRunner
808 - > {
809 - const processRunner = yield* ProcessRunner.ProcessRunner;
810 - const command =
811 - 'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output "$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)" }';
812 - const result = yield* processRunner
813 - .run({
814 - command: "powershell.exe",
815 - args: ["-NoProfile", "-NonInteractive", "-Command", command],
816 - timeout: "1500 millis",
817 - maxOutputBytes: 262_144,
818 - outputMode: "truncate",
819 - timeoutBehavior: "timedOutResult",
820 - })
821 - .pipe(
822 - Effect.mapError(
823 - (cause) => new TerminalSubprocessCheckError({ cause, command: "powershell" }),
824 - ),
825 - );
826 - if (result.code !== 0 || result.timedOut || result.stdoutTruncated) {
827 - return yield* new TerminalSubprocessCheckError({
828 - command: "powershell",
829 - exitCode: result.code,
830 - timedOut: result.timedOut,
831 - stdoutTruncated: result.stdoutTruncated,
832 - });
833 - }
834 - const processes = result.stdout.split(/\r?\n/g).flatMap((line) => {
835 - const [pidRaw, ppidRaw, name = ""] = line.trim().split("|", 3);
836 - const pid = Number(pidRaw);
837 - const ppid = Number(ppidRaw);
838 - return Number.isInteger(pid) && pid > 0 && Number.isInteger(ppid)
839 - ? [{ pid, ppid, name }]
840 - : [];
821 +const windowsProcessTableSnapshot = Effect.fn("terminal.windowsProcessTableSnapshot")(function* (
822 + timeout: Duration.Input,
823 +): Effect.fn.Return<
824 + TerminalProcessTableSnapshot,
825 + TerminalSubprocessCheckError,
826 + ProcessRunner.ProcessRunner
827 +> {
828 + const processRunner = yield* ProcessRunner.ProcessRunner;
829 + const command =
830 + 'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output "$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)" }';
831 + const result = yield* processRunner
832 + .run({
833 + command: "powershell.exe",
834 + args: ["-NoProfile", "-NonInteractive", "-Command", command],
835 + timeout,
836 + maxOutputBytes: 262_144,
837 + outputMode: "truncate",
838 + timeoutBehavior: "timedOutResult",
839 + })
840 + .pipe(
841 + Effect.mapError(
842 + (cause) => new TerminalSubprocessCheckError({ cause, command: "powershell" }),
843 + ),
844 + );
845 + if (result.code !== 0 || result.timedOut || result.stdoutTruncated) {
846 + return yield* new TerminalSubprocessCheckError({
847 + command: "powershell",
848 + exitCode: result.code,
849 + timedOut: result.timedOut,
850 + stdoutTruncated: result.stdoutTruncated,
851 });
842 - return processTableSnapshotFromProcesses(processes);
843 - },
844 -);
852 + }
853 + const processes = result.stdout.split(/\r?\n/g).flatMap((line) => {
854 + const [pidRaw, ppidRaw, name = ""] = line.trim().split("|", 3);
855 + const pid = Number(pidRaw);
856 + const ppid = Number(ppidRaw);
857 + return Number.isInteger(pid) && pid > 0 && Number.isInteger(ppid) ? [{ pid, ppid, name }] : [];
858 + });
859 + return processTableSnapshotFromProcesses(processes);
860 +});
861
862 interface TerminalHistoryChunk {
863 data: string;
@@ -1557,54 +1573,74 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
1573 },
1574 );
1575 // Share one process table per poll; per-terminal scans can exhaust PIDs on busy hosts.
1560 - const fallbackProcessTableSnapshot = (
1561 - platform === "win32"
1562 - ? windowsProcessTableSnapshot()
1563 - : posixProcessTableSnapshot(yield* resolvePosixPsCommand())
1564 - ).pipe(Effect.provideService(ProcessRunner.ProcessRunner, processRunner));
1565 - const fetchProcessTableSnapshot: Effect.Effect<
1566 - {
1567 - readonly snapshot: TerminalProcessTableSnapshot;
1568 - readonly snapshotSucceeded: boolean;
1569 - },
1570 - TerminalSubprocessCheckError
1571 - > = options.processTable
1572 - ? options.processTable.pipe(
1573 - Effect.map((entries) => ({
1574 - snapshot: processTableSnapshotFromProcesses(entries),
1575 - snapshotSucceeded: true,
1576 - })),
1577 - Effect.catch(() =>
1578 - fallbackProcessTableSnapshot.pipe(
1579 - Effect.map((snapshot) => ({ snapshot, snapshotSucceeded: false })),
1576 + // Timed on success and failure so the poll loop can pace the next query.
1577 + const posixPsCommand = platform === "win32" ? undefined : yield* resolvePosixPsCommand();
1578 + const fallbackProcessTableSnapshot = (timeout: Duration.Input) =>
1579 + (posixPsCommand === undefined
1580 + ? windowsProcessTableSnapshot(timeout)
1581 + : posixProcessTableSnapshot(posixPsCommand, timeout)
1582 + ).pipe(
1583 + Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
1584 + Effect.result,
1585 + Effect.timed,
1586 + Effect.map(([elapsed, snapshot]) => ({
1587 + snapshot,
1588 + queryElapsedMs: Duration.toMillis(elapsed),
1589 + })),
1590 + );
1591 + // `fallbackTimeout` only bounds the ps/WMI fallback; a native process table
1592 + // or custom inspector is unaffected.
1593 + const fetchProcessTableSnapshot = (
1594 + fallbackTimeout: Duration.Input,
1595 + ): Effect.Effect<{
1596 + readonly snapshot: Result.Result<TerminalProcessTableSnapshot, TerminalSubprocessCheckError>;
1597 + readonly snapshotSucceeded: boolean;
1598 + readonly queryElapsedMs: number;
1599 + }> =>
1600 + options.processTable
1601 + ? options.processTable.pipe(
1602 + Effect.map((entries) => ({
1603 + snapshot: Result.succeed(processTableSnapshotFromProcesses(entries)),
1604 + snapshotSucceeded: true,
1605 + queryElapsedMs: 0,
1606 + })),
1607 + Effect.catch(() =>
1608 + fallbackProcessTableSnapshot(fallbackTimeout).pipe(
1609 + Effect.map((fallback) => ({ ...fallback, snapshotSucceeded: false })),
1610 + ),
1611 ),
1581 - ),
1582 - )
1583 - : fallbackProcessTableSnapshot.pipe(
1584 - Effect.map((snapshot) => ({ snapshot, snapshotSucceeded: true })),
1585 - );
1612 + )
1613 + : fallbackProcessTableSnapshot(fallbackTimeout).pipe(
1614 + Effect.map((fallback) => ({
1615 + ...fallback,
1616 + snapshotSucceeded: Result.isSuccess(fallback.snapshot),
1617 + })),
1618 + );
1619 const customSubprocessInspector = options.subprocessInspector;
1587 - const acquireSubprocessInspector: Effect.Effect<
1588 - {
1589 - readonly inspector: TerminalSubprocessInspector;
1590 - readonly snapshotSucceeded: boolean;
1591 - },
1592 - TerminalSubprocessCheckError
1593 - > =
1620 + const acquireSubprocessInspector = (
1621 + fallbackTimeout: Duration.Input,
1622 + ): Effect.Effect<{
1623 + readonly inspector: Result.Result<TerminalSubprocessInspector, TerminalSubprocessCheckError>;
1624 + readonly snapshotSucceeded: boolean;
1625 + readonly queryElapsedMs: number;
1626 + }> =>
1627 customSubprocessInspector !== undefined
1595 - ? Effect.succeed({ inspector: customSubprocessInspector, snapshotSucceeded: true })
1628 + ? Effect.succeed({
1629 + inspector: Result.succeed(customSubprocessInspector),
1630 + snapshotSucceeded: true,
1631 + queryElapsedMs: 0,
1632 + })
1633 : Effect.map(
1597 - fetchProcessTableSnapshot,
1598 - ({
1599 - snapshot,
1600 - snapshotSucceeded,
1601 - }): {
1602 - readonly inspector: TerminalSubprocessInspector;
1603 - readonly snapshotSucceeded: boolean;
1604 - } => ({
1605 - inspector: (terminalPid) =>
1606 - Effect.succeed(deriveSubprocessInspectResult(snapshot, terminalPid, platform)),
1634 + fetchProcessTableSnapshot(fallbackTimeout),
1635 + ({ snapshot, snapshotSucceeded, queryElapsedMs }) => ({
1636 + inspector: Result.map(
1637 + snapshot,
1638 + (table): TerminalSubprocessInspector =>
1639 + (terminalPid) =>
1640 + Effect.succeed(deriveSubprocessInspectResult(table, terminalPid, platform)),
1641 + ),
1642 snapshotSucceeded,
1643 + queryElapsedMs,
1644 }),
1645 );
1646 const subprocessPollIntervalMs =
@@ -2632,39 +2668,29 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2668 }));
2669
2670 if (runningSessions.length === 0) {
2635 - return true;
2671 + return { snapshotSucceeded: true, queryElapsedMs: 0 };
2672 }
2673 if (
2674 runningSessions.every(({ session }) => isQuiet(session)) &&
2675 skippedQuietTicks < QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS - 1
2676 ) {
2677 skippedQuietTicks += 1;
2642 - return true;
2678 + return { snapshotSucceeded: true, queryElapsedMs: 0 };
2679 }
2680 skippedQuietTicks = 0;
2681
2646 - const inspectorOption = yield* acquireSubprocessInspector.pipe(
2647 - Effect.asSome,
2648 - Effect.catch((reason) =>
2649 - Effect.logWarning("failed to snapshot processes for terminal subprocess polling", {
2650 - reason,
2651 - }).pipe(
2652 - Effect.as(
2653 - Option.none<{
2654 - readonly inspector: TerminalSubprocessInspector;
2655 - readonly snapshotSucceeded: boolean;
2656 - }>(),
2657 - ),
2658 - ),
2659 - ),
2682 + const { inspector, snapshotSucceeded, queryElapsedMs } = yield* acquireSubprocessInspector(
2683 + PROCESS_TABLE_QUERY_TIMEOUT,
2684 );
2661 -
2662 - if (Option.isNone(inspectorOption)) {
2685 + if (Result.isFailure(inspector)) {
2686 + yield* Effect.logWarning("failed to snapshot processes for terminal subprocess polling", {
2687 + reason: inspector.failure,
2688 + });
2689 quietSessions = new WeakMap();
2664 - return false;
2690 + return { snapshotSucceeded: false, queryElapsedMs };
2691 }
2692
2667 - const { inspector: subprocessInspector, snapshotSucceeded } = inspectorOption.value;
2693 + const subprocessInspector = inspector.success;
2694 const checkSubprocessActivity = Effect.fn("terminal.checkSubprocessActivity")(function* (
2695 candidate: (typeof runningSessions)[number],
2696 ) {
@@ -2760,7 +2786,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2786 discard: true,
2787 });
2788
2763 - return snapshotSucceeded;
2789 + return { snapshotSucceeded, queryElapsedMs };
2790 });
2791
2792 const hasRunningSessions = readManagerState.pipe(
@@ -2775,13 +2801,14 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2801 Effect.flatMap((active) =>
2802 active
2803 ? pollSubprocessActivity().pipe(
2778 - Effect.flatMap((snapshotSucceeded) => {
2804 + Effect.flatMap(({ snapshotSucceeded, queryElapsedMs }) => {
2805 subprocessSnapshotFailureCount = snapshotSucceeded
2806 ? 0
2807 : Math.min(subprocessSnapshotFailureCount + 1, 30);
2808 const delayMs = subprocessSnapshotPollDelayMs(
2809 subprocessPollIntervalMs,
2810 subprocessSnapshotFailureCount,
2811 + queryElapsedMs,
2812 );
2813 return Effect.sleep(delayMs);
2814 }),
@@ -3417,7 +3444,10 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
3444 running.map((session) => [session.terminalId, terminalActivityMark(session)]),
3445 );
3446 // Inspect now so commands started after the last poll still protect their terminals.
3420 - const { inspector } = yield* acquireSubprocessInspector;
3447 + const { inspector: inspectorResult } = yield* acquireSubprocessInspector(
3448 + platform === "win32" ? CLOSE_IDLE_QUERY_TIMEOUT.win32 : CLOSE_IDLE_QUERY_TIMEOUT.posix,
3449 + );
3450 + const inspector = yield* Effect.fromResult(inspectorResult);
3451 yield* Effect.forEach(
3452 running,
3453 (session) =>