Skip to content
TypeScript

fix(server): an idle terminal no longer scans the process table every second (#21242)

tiliakoosd1cac663a783
diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts
index 94af3c5bfca..0a097147945 100644
--- a/apps/server/src/terminal/Manager.test.ts
+++ b/apps/server/src/terminal/Manager.test.ts
@@ -302,6 +302,9 @@ interface CreateManagerOptions {
>;
subprocessPollIntervalMs?: number;
processKillGraceMs?: number;
+ registerTerminalProcesses?: Parameters<
+ typeof TerminalManager.makeWithOptions
+ >[0]["registerTerminalProcesses"];
maxRetainedInactiveSessions?: number;
historyByteLimit?: number;
ptyAdapter?: FakePtyAdapter;
@@ -352,6 +355,9 @@ const createManager = (
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
: {}),
processKillGraceMs: options.processKillGraceMs ?? 1,
+ ...(options.registerTerminalProcesses !== undefined
+ ? { registerTerminalProcesses: options.registerTerminalProcesses }
+ : {}),
...(options.maxRetainedInactiveSessions !== undefined
? { maxRetainedInactiveSessions: options.maxRetainedInactiveSessions }
: {}),
@@ -1225,47 +1231,143 @@ it.layer(
}),
);
- it.effect("emits subprocess activity events when child-process state changes", () =>
+ it.effect("skips snapshots only when every terminal is quiet and wakes on input or output", () =>
Effect.gen(function* () {
- let inspect: {
- readonly hasRunningSubprocess: boolean;
- readonly childCommand: string | null;
- readonly processIds: ReadonlyArray<number>;
- } = { hasRunningSubprocess: false, childCommand: null, processIds: [] };
- const { manager, getEvents } = yield* createManager(5, {
- subprocessInspector: () => Effect.succeed(inspect),
- subprocessPollIntervalMs: 20,
- });
-
+ let snapshots = 0;
+ let processes: Array<{ pid: number; ppid: number; name: string }> = [];
+ let duringSnapshot: Effect.Effect<void> = Effect.void;
+ const { manager, ptyAdapter, getEvents } = yield* createManager(5, {
+ processKillGraceMs: 0,
+ subprocessPollIntervalMs: 1_000,
+ processTable: Effect.gen(function* () {
+ snapshots += 1;
+ const snapshot = processes;
+ yield* duringSnapshot;
+ return snapshot;
+ }),
+ }).pipe(Effect.provide(layerWithHostPlatform("linux")));
+ const activity = yield* Queue.unbounded<Extract<TerminalEvent, { type: "activity" }>>();
+ const output = yield* Deferred.make<void>();
+ const unsubscribe = yield* manager.subscribe((event) =>
+ event.type === "activity"
+ ? Queue.offer(activity, event).pipe(Effect.asVoid)
+ : event.type === "output"
+ ? Deferred.succeed(output, undefined).pipe(Effect.asVoid)
+ : Effect.void,
+ );
+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
yield* manager.open(openInput());
- expect((yield* getEvents).some((event) => event.type === "activity")).toBe(false);
+ yield* manager.open(openInput({ terminalId: "second" }));
+ const [first, second] = ptyAdapter.processes;
+ const shells = ptyAdapter.processes.map(({ pid }) => ({ pid, ppid: 1, name: "zsh" }));
+ processes = shells;
+
+ yield* TestClock.adjust("1 second");
+ assert.equal(snapshots, 1);
+ yield* TestClock.adjust("1 second");
+ assert.equal(snapshots, 2);
+ yield* TestClock.adjust("3 seconds");
+ assert.equal(snapshots, 2);
+ expect((yield* getEvents).filter((event) => event.type === "activity")).toEqual([]);
+
+ processes = [...shells, { pid: 100, ppid: second!.pid, name: "vim" }];
+ yield* manager.write({ threadId: "thread-1", terminalId: "second", data: "vim\r" });
+ yield* TestClock.adjust("1 second");
+ expect(yield* Queue.take(activity)).toMatchObject({
+ terminalId: "second",
+ hasRunningSubprocess: true,
+ label: "vim",
+ });
+ yield* TestClock.adjust("2 seconds");
+ assert.equal(snapshots, 5);
+
+ processes = shells;
+ yield* TestClock.adjust("1 second");
+ expect(yield* Queue.take(activity)).toMatchObject({
+ terminalId: "second",
+ hasRunningSubprocess: false,
+ label: "second",
+ });
+ yield* TestClock.adjust("3 seconds");
+ assert.equal(snapshots, 7);
+
+ processes = [...shells, { pid: 101, ppid: first!.pid, name: "node" }];
+ first!.emitData("server started\r\n");
+ yield* Deferred.await(output);
+ yield* TestClock.adjust("1 second");
+ expect(yield* Queue.take(activity)).toMatchObject({
+ terminalId: DEFAULT_TERMINAL_ID,
+ hasRunningSubprocess: true,
+ label: "node",
+ });
+ assert.equal(snapshots, 8);
- inspect = { hasRunningSubprocess: true, childCommand: "vim", processIds: [100, 101] };
- yield* waitFor(
- Effect.map(getEvents, (events) =>
- events.some(
- (event) =>
- event.type === "activity" &&
- event.hasRunningSubprocess === true &&
- event.label === "vim",
- ),
- ),
- "1200 millis",
- );
+ processes = shells;
+ duringSnapshot = Effect.gen(function* () {
+ duringSnapshot = Effect.void;
+ yield* manager.write({
+ threadId: "thread-1",
+ terminalId: DEFAULT_TERMINAL_ID,
+ data: "next command\r",
+ });
+ }).pipe(Effect.orDie);
+ yield* TestClock.adjust("1 second");
+ expect(yield* Queue.take(activity)).toMatchObject({ hasRunningSubprocess: false });
+ // Input during inspection still needs two subsequent unchanged snapshots.
+ yield* TestClock.adjust("2 seconds");
+ assert.equal(snapshots, 11);
+ yield* TestClock.adjust("3 seconds");
+ assert.equal(snapshots, 11);
+ }).pipe(Effect.provide(TestClock.layer())),
+ );
- inspect = { hasRunningSubprocess: false, childCommand: null, processIds: [] };
- yield* waitFor(
- Effect.map(getEvents, (events) =>
- events.some(
- (event) =>
- event.type === "activity" &&
- event.hasRunningSubprocess === false &&
- event.label === "Terminal 1",
- ),
- ),
- "1200 millis",
+ it.effect("discovers and registers a silent child within 30 quiet ticks", () =>
+ Effect.gen(function* () {
+ let snapshots = 0;
+ let processes: Array<{ pid: number; ppid: number; name: string }> = [];
+ const registered = yield* Deferred.make<{
+ readonly threadId: string;
+ readonly terminalId: string;
+ readonly processIds: ReadonlyArray<number>;
+ }>();
+ const { manager, ptyAdapter } = yield* createManager(5, {
+ processKillGraceMs: 0,
+ subprocessPollIntervalMs: 1_000,
+ processTable: Effect.sync(() => {
+ snapshots += 1;
+ return processes;
+ }),
+ registerTerminalProcesses: (input) =>
+ input.processIds.includes(100)
+ ? Deferred.succeed(registered, input).pipe(Effect.asVoid)
+ : Effect.void,
+ }).pipe(Effect.provide(layerWithHostPlatform("linux")));
+ const activity = yield* Queue.unbounded<Extract<TerminalEvent, { type: "activity" }>>();
+ const unsubscribe = yield* manager.subscribe((event) =>
+ event.type === "activity" ? Queue.offer(activity, event).pipe(Effect.asVoid) : Effect.void,
);
- }),
+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
+ yield* manager.open(openInput());
+ const shell = ptyAdapter.processes[0]!;
+ processes = [{ pid: shell.pid, ppid: 1, name: "zsh" }];
+ yield* TestClock.adjust("2 seconds");
+ assert.equal(snapshots, 2);
+
+ processes = [...processes, { pid: 100, ppid: shell.pid, name: "node" }];
+ yield* TestClock.adjust("30 seconds");
+ assert.equal(snapshots, 3);
+ assert.isTrue(yield* Deferred.isDone(registered));
+ expect(yield* Deferred.await(registered)).toEqual({
+ threadId: "thread-1",
+ terminalId: DEFAULT_TERMINAL_ID,
+ processIds: [shell.pid, 100],
+ });
+ expect(yield* Queue.take(activity)).toMatchObject({
+ terminalId: DEFAULT_TERMINAL_ID,
+ hasRunningSubprocess: true,
+ label: "node",
+ });
+ }).pipe(Effect.provide(TestClock.layer())),
);
it.effect("does not invoke subprocess polling until a terminal session is running", () =>
diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts
index fc798714b58..b6f123d1ff7 100644
--- a/apps/server/src/terminal/Manager.ts
+++ b/apps/server/src/terminal/Manager.ts
@@ -98,6 +98,8 @@ const MAX_HISTORY_CHUNK_LENGTH = 16 * 1024;
const DEFAULT_PERSIST_DEBOUNCE_MS = 250;
const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
const MAX_SUBPROCESS_POLL_INTERVAL_MS = 60_000;
+// Discover children started without terminal input or output.
+const QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS = 30;
const DEFAULT_PROCESS_KILL_GRACE_MS = 1_000;
const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128;
const DEFAULT_OPEN_COLS = 120;
@@ -438,6 +440,16 @@ function advanceEventSequence(session: TerminalSessionState): {
return { updatedAt, sequence: session.eventSequence };
}
+function terminalActivityMark(session: TerminalSessionState): number {
+ return session.eventSequence + session.inputCount;
+}
+
+interface QuietTerminalSession {
+ readonly process: PtyAdapter.PtyProcess | null;
+ readonly mark: number;
+ readonly idleSnapshots: number;
+}
+
function cleanupProcessHandles(session: TerminalSessionState): void {
session.unsubscribeData?.();
session.unsubscribeData = null;
@@ -2485,16 +2497,46 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
}
});
+ // Two unchanged snapshots cover children forked just after the first snapshot.
+ // Process identity prevents a restarted shell from inheriting quiet state.
+ let quietSessions = new WeakMap<TerminalSessionState, QuietTerminalSession>();
+ let skippedQuietTicks = 0;
+ const isQuiet = (session: TerminalSessionState & { pid: number }) => {
+ const quiet = quietSessions.get(session);
+ return (
+ quiet !== undefined &&
+ quiet.idleSnapshots === 2 &&
+ quiet.process === session.process &&
+ quiet.mark === terminalActivityMark(session) &&
+ !session.hasRunningSubprocess
+ );
+ };
+
const pollSubprocessActivity = Effect.fn("terminal.pollSubprocessActivity")(function* () {
const state = yield* readManagerState;
- const runningSessions = [...state.sessions.values()].filter(
- (session): session is TerminalSessionState & { pid: number } =>
- session.status === "running" && Number.isInteger(session.pid),
- );
+ const runningSessions = [...state.sessions.values()]
+ .filter(
+ (session): session is TerminalSessionState & { pid: number } =>
+ session.status === "running" && Number.isInteger(session.pid),
+ )
+ .map((session) => ({
+ session,
+ terminalPid: session.pid,
+ process: session.process,
+ mark: terminalActivityMark(session),
+ }));
if (runningSessions.length === 0) {
return true;
}
+ if (
+ runningSessions.every(({ session }) => isQuiet(session)) &&
+ skippedQuietTicks < QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS - 1
+ ) {
+ skippedQuietTicks += 1;
+ return true;
+ }
+ skippedQuietTicks = 0;
const inspectorOption = yield* acquireSubprocessInspector.pipe(
Effect.asSome,
@@ -2513,15 +2555,18 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
);
if (Option.isNone(inspectorOption)) {
+ quietSessions = new WeakMap();
return false;
}
const { inspector: subprocessInspector, snapshotSucceeded } = inspectorOption.value;
-
const checkSubprocessActivity = Effect.fn("terminal.checkSubprocessActivity")(function* (
- session: TerminalSessionState & { pid: number },
+ candidate: (typeof runningSessions)[number],
) {
- const terminalPid = session.pid;
+ const { session, terminalPid, process } = candidate;
+ let mark = candidate.mark;
+ const previous = quietSessions.get(session);
+ quietSessions.delete(session);
const inspectResult = yield* subprocessInspector(terminalPid).pipe(
Effect.asSome,
Effect.catch((reason) =>
@@ -2534,7 +2579,12 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
),
);
- if (Option.isNone(inspectResult)) {
+ if (
+ Option.isNone(inspectResult) ||
+ session.status !== "running" ||
+ session.pid !== terminalPid ||
+ session.process !== process
+ ) {
return;
}
@@ -2551,8 +2601,10 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
);
if (
Option.isNone(liveSession) ||
+ liveSession.value !== session ||
liveSession.value.status !== "running" ||
liveSession.value.pid !== terminalPid ||
+ liveSession.value.process !== process ||
(liveSession.value.hasRunningSubprocess === next.hasRunningSubprocess &&
liveSession.value.childCommandLabel === nextChildLabel)
) {
@@ -2562,6 +2614,8 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
liveSession.value.hasRunningSubprocess = next.hasRunningSubprocess;
liveSession.value.childCommandLabel = nextChildLabel;
const eventStamp = advanceEventSequence(liveSession.value);
+ // Only this poll's own event may advance the mark without waking it.
+ mark += 1;
return [
Option.some({
@@ -2579,12 +2633,28 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
if (Option.isSome(event)) {
yield* publishEvent(event.value);
}
+
+ if (
+ snapshotSucceeded &&
+ !next.hasRunningSubprocess &&
+ session.status === "running" &&
+ session.pid === terminalPid &&
+ session.process === process &&
+ terminalActivityMark(session) === mark
+ ) {
+ quietSessions.set(session, {
+ process,
+ mark,
+ idleSnapshots: previous?.process === process && previous.mark === mark ? 2 : 1,
+ });
+ }
});
yield* Effect.forEach(runningSessions, checkSubprocessActivity, {
concurrency: "unbounded",
discard: true,
});
+
return snapshotSucceeded;
});
@@ -3267,10 +3337,8 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
(input.terminalId === undefined || session.terminalId === input.terminalId),
);
if (running.length === 0) return;
- const activityMark = (session: TerminalSessionState) =>
- session.eventSequence + session.inputCount;
const marks = new Map(
- running.map((session) => [session.terminalId, activityMark(session)]),
+ running.map((session) => [session.terminalId, terminalActivityMark(session)]),
);
// Inspect now instead of trusting the last poll, so a command started
// since then keeps its terminal.
@@ -3281,7 +3349,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
inspector(session.pid).pipe(
Effect.flatMap((result) =>
result.hasRunningSubprocess ||
- activityMark(session) !== marks.get(session.terminalId)
+ terminalActivityMark(session) !== marks.get(session.terminalId)
? Effect.void
: closeSession(input.threadId, session.terminalId, false),
),