Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 107 additions & 1 deletion packages/core/src/services/web-terminal-registry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,20 @@ describe('WebTerminalRegistry', () => {
},
onData: vi.fn((listener) => {
onData = listener;
return { dispose: disposeData };
// Capture this session's spy by value: the describe-scope `disposeData`
// variable is reassigned every test, and a deferred exit-time release
// from a previous session may fire during a later test — it must hit
// its own spy, not the current one. Same reason the detach guard
// checks listener identity before clearing the shared `onData`.
const disposeDataSpy = disposeData;
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
return {
// Model node-pty's disposable detaching the listener, so a test can
// tell a synchronous dispose apart from the deferred one.
dispose: () => {
if (onData === listener) onData = () => {};
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
disposeDataSpy();
},
};
}),
onExit: vi.fn((listener) => {
onExit = listener;
Expand Down Expand Up @@ -406,6 +419,99 @@ describe('WebTerminalRegistry', () => {
expect(kill).not.toHaveBeenCalled();
});

it('frees an exited session at exit time, not at the idle reclaim', async () => {
osPlatform.mockReturnValue('win32');
const registry = new WebTerminalRegistry();
await registry.create({
terminalId: 'terminal:exit-release',
workspaceCwd: '/workspace',
});

onExit({ exitCode: 0 });
// Real timers and no clock advance, so the 15-minute idle reclaim cannot
// have fired: anything released now was released at exit time. See #11353.
await new Promise<void>((resolve) => setImmediate(resolve));

// Nothing may signal the exited shell's possibly-recycled pid: no
// taskkill, no process-group kill, no ptyProcess.kill().
expect(spawnSync).not.toHaveBeenCalled();
expect(kill).not.toHaveBeenCalled();
expect(nativeKill).toHaveBeenCalledOnce();
expect(conoutDispose).toHaveBeenCalledOnce();
expect(disposeData).toHaveBeenCalledOnce();
expect(disposeExit).toHaveBeenCalledOnce();
// The session itself stays in the map for scrollback replay — release()
// did not run.
expect(registry.readSnapshot('terminal:exit-release')).toMatchObject({
exited: true,
exitCode: 0,
});
});

it('still replays buffered scrollback after the exit-time release', async () => {
osPlatform.mockReturnValue('win32');
const registry = new WebTerminalRegistry();
await registry.create({
terminalId: 'terminal:exit-replay',
workspaceCwd: '/workspace',
});
onData('final output');
onExit({ exitCode: 3 });
await new Promise<void>((resolve) => setImmediate(resolve));

// Both halves matter: the release ran at exit time, AND the reconnect
// replay it must not break still returns the buffered scrollback.
expect(conoutDispose).toHaveBeenCalledOnce();
expect(registry.readSnapshot('terminal:exit-replay')).toMatchObject({
output: 'final output',
exited: true,
exitCode: 3,
});
});

it('releases an exited session exactly once across exit and release()', async () => {
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
osPlatform.mockReturnValue('win32');
const registry = new WebTerminalRegistry();
await registry.create({
terminalId: 'terminal:exit-then-release',
workspaceCwd: '/workspace',
});
onExit({ exitCode: 0 });
await new Promise<void>((resolve) => setImmediate(resolve));

// A later release() — tab close, workspace drain, or dispose() — must not
// repeat the exit-time release. disposeData/disposeExit pin the flag:
// nativeKill/conoutDispose alone could not, since releaseConPtyHost
// already self-dedupes on the pty object.
expect(registry.release('terminal:exit-then-release')).toBe(true);
expect(nativeKill).toHaveBeenCalledOnce();
expect(conoutDispose).toHaveBeenCalledOnce();
expect(disposeData).toHaveBeenCalledOnce();
expect(disposeExit).toHaveBeenCalledOnce();
});

it('lets output queued behind onExit reach the scrollback before the release', async () => {
osPlatform.mockReturnValue('win32');
const registry = new WebTerminalRegistry();
await registry.create({
terminalId: 'terminal:exit-trailing',
workspaceCwd: '/workspace',
});

// node-pty can deliver queued onData callbacks after onExit; the release
// is deferred one tick precisely so this tail still lands. With a
// synchronous dispose the fake's disposable detaches the listener and the
// tail is lost, so this test fails if the defer is removed.
onExit({ exitCode: 0 });
onData('trailing');
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
await new Promise<void>((resolve) => setImmediate(resolve));

expect(registry.readSnapshot('terminal:exit-trailing')).toMatchObject({
output: 'trailing',
exited: true,
});
});

it('forwards live output and bounds unacknowledged PTY input', async () => {
const registry = new WebTerminalRegistry();
await registry.create({
Expand Down
54 changes: 40 additions & 14 deletions packages/core/src/services/web-terminal-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ interface PtySession {
reclaimTimer?: ReturnType<typeof setTimeout>;
dataDisposable?: { dispose(): void };
exitDisposable?: { dispose(): void };
/** Set once the PTY-side resources are freed; guards the double release. */
ptyReleased?: boolean;
}

interface SpawnedWebTerminalPty extends WebTerminalPty {
Expand Down Expand Up @@ -270,6 +272,18 @@ export class WebTerminalRegistry {
session.exited = true;
session.exitCode = e.exitCode;
for (const listener of [...session.exitListeners]) listener(e);
// Free the PTY's resources at exit time rather than at the idle
// reclaim: exited sessions do not count against the admission cap, so
// their accumulation inside the 15-minute reclaim window is unbounded.
// Nothing needs the PTY once the shell has exited — write()/resize()
// short-circuit on `exited`, and readSnapshot() replays the JS-side
// buffer — so the session itself stays in the map for scrollback
// replay. Deferred one tick because onExit can arrive slightly before
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
// trailing onData callbacks node-pty still has queued (the race the
// shell-tool path drains before finalizing); disposing dataDisposable
// synchronously here could truncate the tail of that replay. See
// #11353.
setImmediate(() => this.releasePtyResources(session)).unref?.();
};
let dataDisposable: { dispose(): void } | undefined;
let exitDisposable: { dispose(): void } | undefined;
Expand Down Expand Up @@ -458,8 +472,6 @@ export class WebTerminalRegistry {
listener({ exitCode: 143, signal: 15 });
}
}
session.dataDisposable?.dispose();
session.exitDisposable?.dispose();
session.outputListeners.clear();
session.exitListeners.clear();
if (!session.exited) {
Expand All @@ -468,19 +480,19 @@ export class WebTerminalRegistry {
// false, so a terminal released before its shell's first output byte (tab
// closed during slow pwsh startup, or a workspace drain) still has a
// kill() queued in node-pty's `_deferreds`. The wrapper's kill() notes
// the close only when it really ran; releaseHost then disposes the worker
// a deferred kill would strand, and skips the native close so the queued
// kill() stays the single closer — never a second close.
session.pty.releaseHost?.();
} else {
// The shell already exited, so nothing may signal its (possibly recycled)
// pid — but node-pty does not release its conout worker thread on a
// natural exit, so without this every terminal the user exits leaks one
// for the life of the CLI. Same defect as the shell-tool path in
// shellExecutionService. The conhost.exe half is not freed here (the
// native baton is already gone); see releaseConPtyHost. See #11303.
session.pty.releaseHost?.();
// the close only when it really ran; releasePtyResources' releaseHost
// then disposes the worker a deferred kill would strand, and skips the
// native close so the queued kill() stays the single closer — never a
// second close.
}
// On the exited arm the shell is already gone, so nothing may signal its
// (possibly recycled) pid — but node-pty does not release its conout
// worker thread on a natural exit, so without releaseHost every terminal
// the user exits leaks one for the life of the CLI. Same defect as the
// shell-tool path in shellExecutionService. The conhost.exe half is not
// freed here (the native baton is already gone); see releaseConPtyHost.
// See #11303.
this.releasePtyResources(session);
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
return true;
}

Expand All @@ -502,6 +514,20 @@ export class WebTerminalRegistry {
this.cancelledCreations.delete(terminalId);
}

/**
* Dispose a session's PTY-side resources exactly once, keeping the session
* and its buffer for scrollback replay. An exited session reaches this
* twice — handleExit's deferred release at exit time, then release() on tab
* close, reclaim, workspace drain, or dispose() — hence the flag.
*/
private releasePtyResources(session: PtySession): void {
if (session.ptyReleased) return;
session.ptyReleased = true;
session.dataDisposable?.dispose();
session.exitDisposable?.dispose();
session.pty.releaseHost?.();
}

private clearReclaim(session: PtySession): void {
if (session.reclaimTimer) {
clearTimeout(session.reclaimTimer);
Expand Down
Loading