@devries-cameron20 / t3code-1 / commits / f0a3321354
Fork 0

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

fix(server): settling a thread keeps exec and foreground Bash terminals open (#37125)

Julius Marminge committed Nov 15, 2026 at 01:44 UTC f0a33213547ce81ea9c39e4bedb13829cf307f56
2 files changed +130 -11
apps/server/src/terminal/Manager.test.ts
+48
@@ -242,6 +242,7 @@ interface CreateManagerOptions {
242 ReadonlyArray<{ readonly pid: number; readonly ppid: number; readonly name: string }>,
243 never
244 >;
245 + foregroundProcessGroup?: (terminalPid: number) => Effect.Effect<number | null>;
246 subprocessPollIntervalMs?: number;
247 processKillGraceMs?: number;
248 registerTerminalProcesses?: Parameters<
@@ -293,6 +294,8 @@ const createManager = (
294 ? { subprocessInspector: options.subprocessInspector }
295 : {}),
296 ...(options.processTable !== undefined ? { processTable: options.processTable } : {}),
297 + // Fixture pids are not real processes; default to a shell idle at its prompt.
298 + foregroundProcessGroup: options.foregroundProcessGroup ?? ((pid) => Effect.succeed(pid)),
299 ...(options.subprocessPollIntervalMs !== undefined
300 ? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
301 : {}),
@@ -943,6 +946,51 @@ it.layer(
946 }),
947 );
948
949 + it.effect("keeps a terminal whose shell was replaced by exec open on settlement", () =>
950 + Effect.gen(function* () {
951 + const { manager, ptyAdapter } = yield* createManager(5, {
952 + shellResolver: () => "/bin/bash",
953 + processTable: Effect.succeed([{ pid: 9000, ppid: 1, name: "node" }]),
954 + }).pipe(Effect.provide(layerWithHostPlatform("linux")));
955 + yield* manager.open(openInput());
956 +
957 + yield* manager.closeOnSettle({ threadId: "thread-1" });
958 +
959 + expect(ptyAdapter.processes[0]?.killed).toBe(false);
960 + }),
961 + );
962 +
963 + it.effect.each([
964 + { label: "idle prompt", platform: "linux", foregroundProcessGroup: 9000, killed: true },
965 + { label: "foreground job", platform: "linux", foregroundProcessGroup: 100, killed: false },
966 + {
967 + label: "unknown foreground group",
968 + platform: "linux",
969 + foregroundProcessGroup: null,
970 + killed: false,
971 + },
972 + { label: "idle prompt", platform: "darwin", foregroundProcessGroup: 9000, killed: true },
973 + { label: "foreground job", platform: "darwin", foregroundProcessGroup: 100, killed: false },
974 + ] as const)(
975 + "settles a shell with a childless shell-named child by its foreground group: $label ($platform)",
976 + ({ platform, foregroundProcessGroup, killed }) =>
977 + Effect.gen(function* () {
978 + const { manager, ptyAdapter } = yield* createManager(5, {
979 + shellResolver: () => "/bin/bash",
980 + processTable: Effect.succeed([
981 + { pid: 9000, ppid: 1, name: "bash" },
982 + { pid: 100, ppid: 9000, name: "bash" },
983 + ]),
984 + foregroundProcessGroup: () => Effect.succeed(foregroundProcessGroup),
985 + }).pipe(Effect.provide(layerWithHostPlatform(platform)));
986 + yield* manager.open(openInput());
987 +
988 + yield* manager.closeOnSettle({ threadId: "thread-1" });
989 +
990 + expect(ptyAdapter.processes[0]?.killed).toBe(killed);
991 + }),
992 + );
993 +
994 it.effect("labels a running command by its whole process name, spaces included", () =>
995 Effect.gen(function* () {
996 const { manager } = yield* createManager(5, {
apps/server/src/terminal/Manager.ts
+82 -11
@@ -255,6 +255,7 @@ interface TerminalSubprocessInspectResult {
255 interface TerminalSubprocessInspector {
256 (
257 terminalPid: number,
258 + shell: string | null,
259 ): Effect.Effect<TerminalSubprocessInspectResult, TerminalSubprocessCheckError>;
260 }
261
@@ -766,21 +767,48 @@ function processTableSnapshotFromProcesses(
767 return { childrenByParent, commandById };
768 }
769
770 +// A root with one of these names is still an interactive shell, e.g. after `.bashrc` runs `exec zsh`.
771 +const INTERACTIVE_SHELL_NAMES = new Set([
772 + "bash",
773 + "zsh",
774 + "fish",
775 + "sh",
776 + "dash",
777 + "ksh",
778 + "mksh",
779 + "tcsh",
780 + "csh",
781 + "nu",
782 +]);
783 +
784 function deriveSubprocessInspectResult(
785 snapshot: TerminalProcessTableSnapshot,
786 terminalPid: number,
787 + shell: string | null,
788 platform: NodeJS.Platform,
789 + foregroundProcessGroup?: number | null,
790 ): TerminalSubprocessInspectResult {
791 const commandName = (pid: number) =>
792 normalizeChildCommandName(snapshot.commandById.get(pid) ?? "", platform);
793 const shellName = commandName(terminalPid);
777 - // Async prompt themes fork childless shell helpers that are not user commands.
778 - const childPid = (snapshot.childrenByParent.get(terminalPid) ?? []).find(
779 - (pid) =>
780 - shellName === null ||
781 - commandName(pid) !== shellName ||
782 - (snapshot.childrenByParent.get(pid)?.length ?? 0) > 0,
783 - );
794 + // `exec <command>` replaces the shell, leaving the command itself as the root.
795 + const rootIsCommand =
796 + platform !== "win32" &&
797 + shell !== null &&
798 + shellName !== null &&
799 + shellName !== normalizeChildCommandName(shell, platform) &&
800 + !INTERACTIVE_SHELL_NAMES.has(shellName.replace(/^-/, ""));
801 + // Async prompt themes fork childless shell helpers that are not user commands;
802 + // a foreground job owns the terminal's process group, and an unknown one counts as foreground.
803 + const childPid = rootIsCommand
804 + ? terminalPid
805 + : (snapshot.childrenByParent.get(terminalPid) ?? []).find(
806 + (pid) =>
807 + shellName === null ||
808 + commandName(pid) !== shellName ||
809 + (snapshot.childrenByParent.get(pid)?.length ?? 0) > 0 ||
810 + (foregroundProcessGroup !== undefined && foregroundProcessGroup !== terminalPid),
811 + );
812 if (childPid === undefined) {
813 return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
814 }
@@ -803,6 +831,12 @@ function deriveSubprocessInspectResult(
831 };
832 }
833
834 +// Field 8 of /proc/<pid>/stat is the tty's foreground process group; comm (field 2) may hold spaces or parens.
835 +function parseProcStatForegroundProcessGroup(stat: string): number | null {
836 + const tpgid = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[5]);
837 + return Number.isInteger(tpgid) ? tpgid : null;
838 +}
839 +
840 const POSIX_PS_ABSOLUTE_PATHS = ["/bin/ps", "/usr/bin/ps"] as const;
841
842 // Resolve ps once; bare-name spawns repeatedly probe long PATHs during one-second polling.
@@ -1620,6 +1654,7 @@ interface TerminalManagerOptions {
1654 ReadonlyArray<ResourceMonitorProcessTableEntry>,
1655 TerminalSubprocessCheckError
1656 >;
1657 + foregroundProcessGroup?: (terminalPid: number) => Effect.Effect<number | null>;
1658 subprocessPollIntervalMs?: number;
1659 processKillGraceMs?: number;
1660 maxRetainedInactiveSessions?: number;
@@ -1800,6 +1835,30 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
1835 snapshotSucceeded: Result.isSuccess(fallback.snapshot),
1836 })),
1837 );
1838 + const foregroundProcessGroup =
1839 + options.foregroundProcessGroup ??
1840 + ((terminalPid: number) =>
1841 + platform === "linux"
1842 + ? fileSystem.readFileString(`/proc/${terminalPid}/stat`).pipe(
1843 + Effect.map(parseProcStatForegroundProcessGroup),
1844 + Effect.orElseSucceed(() => null),
1845 + )
1846 + : processRunner
1847 + .run({
1848 + command: posixPsCommand ?? "ps",
1849 + args: ["-o", "tpgid=", "-p", String(terminalPid)],
1850 + timeout: CLOSE_IDLE_QUERY_TIMEOUT.posix,
1851 + timeoutBehavior: "timedOutResult",
1852 + })
1853 + .pipe(
1854 + Effect.map((result) => {
1855 + const tpgid = Number(result.stdout.trim());
1856 + return result.code === 0 && !result.timedOut && Number.isInteger(tpgid) && tpgid > 0
1857 + ? tpgid
1858 + : null;
1859 + }),
1860 + Effect.orElseSucceed(() => null),
1861 + ));
1862 const customSubprocessInspector = options.subprocessInspector;
1863 const acquireSubprocessInspector = (
1864 fallbackTimeout: Duration.Input,
@@ -1820,8 +1879,20 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
1879 inspector: Result.map(
1880 snapshot,
1881 (table): TerminalSubprocessInspector =>
1823 - (terminalPid) =>
1824 - Effect.succeed(deriveSubprocessInspectResult(table, terminalPid, platform)),
1882 + (terminalPid, shell) => {
1883 + const result = deriveSubprocessInspectResult(table, terminalPid, shell, platform);
1884 + // Only shell-named childless children are ambiguous; read the foreground group for those alone.
1885 + if (
1886 + result.hasRunningSubprocess ||
1887 + platform === "win32" ||
1888 + (table.childrenByParent.get(terminalPid)?.length ?? 0) === 0
1889 + ) {
1890 + return Effect.succeed(result);
1891 + }
1892 + return Effect.map(foregroundProcessGroup(terminalPid), (group) =>
1893 + deriveSubprocessInspectResult(table, terminalPid, shell, platform, group),
1894 + );
1895 + },
1896 ),
1897 snapshotSucceeded,
1898 queryElapsedMs,
@@ -2946,7 +3017,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
3017 let mark = candidate.mark;
3018 const previous = quietSessions.get(session);
3019 quietSessions.delete(session);
2949 - const inspectResult = yield* subprocessInspector(terminalPid).pipe(
3020 + const inspectResult = yield* subprocessInspector(terminalPid, session.shell).pipe(
3021 Effect.asSome,
3022 Effect.catch((reason) =>
3023 Effect.logWarning("failed to check terminal subprocess activity", {
@@ -3741,7 +3812,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
3812 yield* Effect.forEach(
3813 running,
3814 (session) =>
3744 - inspector(session.pid).pipe(
3815 + inspector(session.pid, session.shell).pipe(
3816 Effect.flatMap((result) =>
3817 result.hasRunningSubprocess ||
3818 terminalActivityMark(session) !== marks.get(session.terminalId)