Skip to content

Commit 0f91bbe

Browse files
committed
fix(server): an idle terminal no longer scans the process table every second
Once two snapshots find a shell at its prompt with no child, the 1 s poll skips the snapshot until the shell gets input or output.
1 parent 3ff5b3c commit 0f91bbe

2 files changed

Lines changed: 120 additions & 5 deletions

File tree

‎apps/server/src/terminal/Manager.test.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1083,7 +1083,13 @@ it.layer(
10831083
yield* manager.open(openInput());
10841084
expect((yield* getEvents).some((event) => event.type === "activity")).toBe(false);
10851085

1086+
// A child starts after input; an idle shell is not snapshotted again until then.
10861087
inspect = { hasRunningSubprocess: true, childCommand: "vim", processIds: [100, 101] };
1088+
yield* manager.write({
1089+
threadId: "thread-1",
1090+
terminalId: DEFAULT_TERMINAL_ID,
1091+
data: "vim\r",
1092+
});
10871093
yield* waitFor(
10881094
Effect.map(getEvents, (events) =>
10891095
events.some(
@@ -1111,6 +1117,68 @@ it.layer(
11111117
}),
11121118
);
11131119

1120+
it.effect("skips process snapshots while an idle shell gets no input or output", () =>
1121+
Effect.gen(function* () {
1122+
let snapshots = 0;
1123+
let processes: Array<{ pid: number; ppid: number; name: string }> = [];
1124+
const { manager, ptyAdapter } = yield* createManager(5, {
1125+
processKillGraceMs: 0,
1126+
subprocessPollIntervalMs: 1_000,
1127+
processTable: Effect.sync(() => {
1128+
snapshots += 1;
1129+
return processes;
1130+
}),
1131+
}).pipe(Effect.provide(layerWithHostPlatform("linux")));
1132+
const events = yield* Queue.unbounded<TerminalEvent>();
1133+
const unsubscribe = yield* manager.subscribe((event) =>
1134+
Queue.offer(events, event).pipe(Effect.asVoid),
1135+
);
1136+
yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1137+
const takeEvent = Effect.fn(function* (type: TerminalEvent["type"]) {
1138+
while (true) {
1139+
const event = yield* Queue.take(events);
1140+
if (event.type === type) return event;
1141+
}
1142+
});
1143+
1144+
yield* manager.open(openInput());
1145+
const shell = ptyAdapter.processes[0]!;
1146+
const shellOnly = [{ pid: shell.pid, ppid: 1, name: "zsh" }];
1147+
processes = shellOnly;
1148+
1149+
// Two snapshots confirm the shell is idle, then polling stops snapshotting.
1150+
yield* TestClock.adjust("5 seconds");
1151+
assert.equal(snapshots, 2);
1152+
1153+
// Output resumes snapshots until two more find the shell idle again.
1154+
shell.emitData("prompt$ ");
1155+
yield* takeEvent("output");
1156+
yield* TestClock.adjust("3 seconds");
1157+
assert.equal(snapshots, 4);
1158+
1159+
// A command started from input is found, and polled every tick while it runs.
1160+
processes = [...shellOnly, { pid: 100, ppid: shell.pid, name: "sleep" }];
1161+
yield* manager.write({
1162+
threadId: "thread-1",
1163+
terminalId: DEFAULT_TERMINAL_ID,
1164+
data: "sleep 9\r",
1165+
});
1166+
yield* TestClock.adjust("1 second");
1167+
const started = yield* takeEvent("activity");
1168+
assert.isTrue(started.type === "activity" && started.hasRunningSubprocess);
1169+
yield* TestClock.adjust("2 seconds");
1170+
assert.equal(snapshots, 7);
1171+
1172+
// Its exit is seen at once, and the quiet shell stops being snapshotted again.
1173+
processes = shellOnly;
1174+
yield* TestClock.adjust("1 second");
1175+
const finished = yield* takeEvent("activity");
1176+
assert.isTrue(finished.type === "activity" && !finished.hasRunningSubprocess);
1177+
yield* TestClock.adjust("4 seconds");
1178+
assert.equal(snapshots, 9);
1179+
}).pipe(Effect.provide(TestClock.layer())),
1180+
);
1181+
11141182
it.effect("does not invoke subprocess polling until a terminal session is running", () =>
11151183
Effect.gen(function* () {
11161184
let checks = 0;

‎apps/server/src/terminal/Manager.ts‎

Lines changed: 52 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,17 @@ function advanceEventSequence(session: TerminalSessionState): {
412412
return { updatedAt, sequence: session.eventSequence };
413413
}
414414

415+
// Changes whenever a session gets input or emits an event, such as output.
416+
function terminalActivityMark(session: TerminalSessionState): number {
417+
return session.eventSequence + session.inputCount;
418+
}
419+
420+
interface QuietTerminalSession {
421+
readonly pid: number;
422+
readonly mark: number;
423+
readonly idleSnapshots: number;
424+
}
425+
415426
function cleanupProcessHandles(session: TerminalSessionState): void {
416427
session.unsubscribeData?.();
417428
session.unsubscribeData = null;
@@ -2377,14 +2388,31 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
23772388
}
23782389
});
23792390

2391+
// Running sessions the last snapshots found without a child process, with the
2392+
// activity mark they had. A shell at its prompt starts a child only after input
2393+
// or output, so while every running session is quiet the poll skips the
2394+
// process-table snapshot. Requiring two idle snapshots covers a child forked
2395+
// just after the snapshot that followed the input.
2396+
let quietSessions = new Map<string, QuietTerminalSession>();
2397+
const isQuiet = (session: TerminalSessionState & { pid: number }) => {
2398+
const quiet = quietSessions.get(toSessionKey(session.threadId, session.terminalId));
2399+
return (
2400+
quiet !== undefined &&
2401+
quiet.idleSnapshots >= 2 &&
2402+
quiet.pid === session.pid &&
2403+
quiet.mark === terminalActivityMark(session) &&
2404+
!session.hasRunningSubprocess
2405+
);
2406+
};
2407+
23802408
const pollSubprocessActivity = Effect.fn("terminal.pollSubprocessActivity")(function* () {
23812409
const state = yield* readManagerState;
23822410
const runningSessions = [...state.sessions.values()].filter(
23832411
(session): session is TerminalSessionState & { pid: number } =>
23842412
session.status === "running" && Number.isInteger(session.pid),
23852413
);
23862414

2387-
if (runningSessions.length === 0) {
2415+
if (runningSessions.every(isQuiet)) {
23882416
return true;
23892417
}
23902418

@@ -2409,6 +2437,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
24092437
}
24102438

24112439
const { inspector: subprocessInspector, snapshotSucceeded } = inspectorOption.value;
2440+
const idleSessionPids = new Map<string, number>();
24122441

24132442
const checkSubprocessActivity = Effect.fn("terminal.checkSubprocessActivity")(function* (
24142443
session: TerminalSessionState & { pid: number },
@@ -2431,6 +2460,9 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
24312460
}
24322461

24332462
const next = inspectResult.value;
2463+
if (!next.hasRunningSubprocess) {
2464+
idleSessionPids.set(toSessionKey(session.threadId, session.terminalId), terminalPid);
2465+
}
24342466
yield* registerTerminalProcesses({
24352467
threadId: session.threadId,
24362468
terminalId: session.terminalId,
@@ -2477,6 +2509,23 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
24772509
concurrency: "unbounded",
24782510
discard: true,
24792511
});
2512+
2513+
// Read marks after this poll's own activity events, so they count as seen.
2514+
const liveSessions = (yield* readManagerState).sessions;
2515+
const nextQuietSessions = new Map<string, QuietTerminalSession>();
2516+
for (const [key, pid] of idleSessionPids) {
2517+
const session = liveSessions.get(key);
2518+
if (session?.status !== "running" || session.pid !== pid) continue;
2519+
const mark = terminalActivityMark(session);
2520+
const previous = quietSessions.get(key);
2521+
nextQuietSessions.set(key, {
2522+
pid,
2523+
mark,
2524+
idleSnapshots:
2525+
previous?.pid === pid && previous.mark === mark ? previous.idleSnapshots + 1 : 1,
2526+
});
2527+
}
2528+
quietSessions = nextQuietSessions;
24802529
return snapshotSucceeded;
24812530
});
24822531

@@ -3103,10 +3152,8 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
31033152
(input.terminalId === undefined || session.terminalId === input.terminalId),
31043153
);
31053154
if (running.length === 0) return;
3106-
const activityMark = (session: TerminalSessionState) =>
3107-
session.eventSequence + session.inputCount;
31083155
const marks = new Map(
3109-
running.map((session) => [session.terminalId, activityMark(session)]),
3156+
running.map((session) => [session.terminalId, terminalActivityMark(session)]),
31103157
);
31113158
// Inspect now instead of trusting the last poll, so a command started
31123159
// since then keeps its terminal.
@@ -3117,7 +3164,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
31173164
inspector(session.pid).pipe(
31183165
Effect.flatMap((result) =>
31193166
result.hasRunningSubprocess ||
3120-
activityMark(session) !== marks.get(session.terminalId)
3167+
terminalActivityMark(session) !== marks.get(session.terminalId)
31213168
? Effect.void
31223169
: closeSession(input.threadId, session.terminalId, false),
31233170
),

0 commit comments

Comments
 (0)