Skip to content

Commit 7aa8e24

Browse files
Prevent caching of terminals closed during activation (#1867) (#1948)
## Summary Closing a newly created execution terminal while its environment was still activating could leave that disposed terminal cached. Subsequent execution requests for the same environment and working directory would fail with `Terminal has already been disposed` instead of creating a replacement. ### Root Cause 1. `create()` showed the terminal and awaited `autoActivateOnTerminalOpen`. If the terminal closed while activation was awaiting completion, the close event fired before the caller attached its `onDidCloseTerminal` listener. 2. `create()` returned the now-disposed terminal, which was then stored in `projectTerminals` or `dedicatedTerminals`. 3. Subsequent `runInTerminal` requests fetched the dead terminal from cache and failed permanently. ### Fix - Attached an immediate `onDidCloseTerminal` listener during `create()` to detect closure during asynchronous initialization. - Rejected `create()` if the terminal closed or exited (`exitStatus !== undefined`) during initialization so a disposed terminal is never returned or cached. - Validated cached terminals (`exitStatus === undefined`) in `getProjectTerminal` and `getDedicatedTerminal`. Any exited terminal is evicted from cache and recreated cleanly. - Added regression tests verifying that interrupted activation does not leave a disposed terminal cached, and retries create a live replacement. Fixes #1867 ## Validation - `npm run compile-tests` passes with 0 errors. - Unit test suite `Terminal closed during activation lifecycle (Fixes #1867)` (4 tests) passing. - Existing terminal test suite (17 tests) passing. - ESLint passed with 0 errors and 0 warnings.
1 parent 8e087da commit 7aa8e24

2 files changed

Lines changed: 254 additions & 18 deletions

File tree

‎src/features/terminal/terminalManager.ts‎

Lines changed: 49 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import * as fsapi from 'fs-extra';
22
import * as path from 'path';
3-
import { Disposable, EventEmitter, ProgressLocation, Terminal, Uri } from 'vscode';
3+
import { Disposable, EventEmitter, l10n, ProgressLocation, Terminal, Uri } from 'vscode';
44
import { PythonEnvironment, PythonEnvironmentApi, PythonProject, PythonTerminalCreateOptions } from '../../api';
55
import { ActivationStrings } from '../../common/localize';
66
import { traceInfo, traceVerbose } from '../../common/logging';
@@ -297,24 +297,39 @@ export class TerminalManagerImpl implements TerminalManager {
297297
env: envVars,
298298
});
299299

300-
if (autoActType === ACT_TYPE_COMMAND) {
301-
if (options.disableActivation) {
302-
this.skipActivationOnOpen.add(newTerminal);
303-
return newTerminal;
300+
let closedDuringInit = false;
301+
const closeListener = onDidCloseTerminal((t) => {
302+
if (t === newTerminal) {
303+
closedDuringInit = true;
304304
}
305+
});
305306

306-
// We add it to skip activation on open to prevent double activation.
307-
// We can activate it ourselves since we are creating it.
308-
this.skipActivationOnOpen.add(newTerminal);
307+
try {
308+
if (autoActType === ACT_TYPE_COMMAND) {
309+
if (options.disableActivation) {
310+
this.skipActivationOnOpen.add(newTerminal);
311+
return newTerminal;
312+
}
309313

310-
// Show terminal before activation so users can see the activation happening, requested script running.
311-
// Necessary for scenarios such as when terminal is awaiting user input, etc.
312-
newTerminal.show();
314+
// We add it to skip activation on open to prevent double activation.
315+
// We can activate it ourselves since we are creating it.
316+
this.skipActivationOnOpen.add(newTerminal);
313317

314-
await this.autoActivateOnTerminalOpen(newTerminal, environment);
315-
}
318+
// Show terminal before activation so users can see the activation happening, requested script running.
319+
// Necessary for scenarios such as when terminal is awaiting user input, etc.
320+
newTerminal.show();
316321

317-
return newTerminal;
322+
await this.autoActivateOnTerminalOpen(newTerminal, environment);
323+
}
324+
325+
if (closedDuringInit || newTerminal.exitStatus !== undefined) {
326+
throw new Error(l10n.t('Terminal has already been disposed'));
327+
}
328+
329+
return newTerminal;
330+
} finally {
331+
closeListener.dispose();
332+
}
318333
}
319334

320335
private dedicatedTerminals = new Map<string, Terminal>();
@@ -329,7 +344,10 @@ export class TerminalManagerImpl implements TerminalManager {
329344
if (!createNew) {
330345
const terminal = this.dedicatedTerminals.get(key);
331346
if (terminal) {
332-
return terminal;
347+
if (terminal.exitStatus === undefined) {
348+
return terminal;
349+
}
350+
this.dedicatedTerminals.delete(key);
333351
}
334352
}
335353

@@ -355,11 +373,16 @@ export class TerminalManagerImpl implements TerminalManager {
355373
}
356374

357375
const newTerminal = await this.create(environment, { cwd, name });
376+
if (newTerminal.exitStatus !== undefined) {
377+
throw new Error(l10n.t('Terminal has already been disposed'));
378+
}
358379
this.dedicatedTerminals.set(key, newTerminal);
359380

360381
const disable = onDidCloseTerminal((terminal) => {
361382
if (terminal === newTerminal) {
362-
this.dedicatedTerminals.delete(key);
383+
if (this.dedicatedTerminals.get(key) === newTerminal) {
384+
this.dedicatedTerminals.delete(key);
385+
}
363386
disable.dispose();
364387
}
365388
});
@@ -378,17 +401,25 @@ export class TerminalManagerImpl implements TerminalManager {
378401
if (!createNew) {
379402
const terminal = this.projectTerminals.get(key);
380403
if (terminal) {
381-
return terminal;
404+
if (terminal.exitStatus === undefined) {
405+
return terminal;
406+
}
407+
this.projectTerminals.delete(key);
382408
}
383409
}
384410
const stat = await fsapi.stat(uri.fsPath);
385411
const cwd = stat.isDirectory() ? uri.fsPath : path.dirname(uri.fsPath);
386412
const newTerminal = await this.create(environment, { cwd });
413+
if (newTerminal.exitStatus !== undefined) {
414+
throw new Error(l10n.t('Terminal has already been disposed'));
415+
}
387416
this.projectTerminals.set(key, newTerminal);
388417

389418
const disable = onDidCloseTerminal((terminal) => {
390419
if (terminal === newTerminal) {
391-
this.projectTerminals.delete(key);
420+
if (this.projectTerminals.get(key) === newTerminal) {
421+
this.projectTerminals.delete(key);
422+
}
392423
disable.dispose();
393424
}
394425
});

‎src/test/features/terminal/terminalManager.unit.test.ts‎

Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -763,3 +763,208 @@ suite('TerminalManager - initialize() skips pseudoterminals', () => {
763763
assert.strictEqual(terminalActivation.activateCalls, 0, 'Should not activate any pseudoterminals');
764764
});
765765
});
766+
767+
768+
suite('Terminal closed during activation lifecycle (Fixes #1867)', () => {
769+
let terminalActivation: TestTerminalActivation;
770+
let onDidCloseEmitter: EventEmitter<Terminal>;
771+
let terminalManager: TerminalManagerImpl;
772+
let tempRoot: string;
773+
let projectDir: string;
774+
let projectUri: Uri;
775+
776+
setup(async () => {
777+
terminalActivation = new TestTerminalActivation();
778+
onDidCloseEmitter = new EventEmitter<Terminal>();
779+
780+
sinon.stub(terminalUtils, 'getAutoActivationType').returns(terminalUtils.ACT_TYPE_COMMAND);
781+
sinon.stub(terminalUtils, 'waitForShellIntegration').resolves(false);
782+
sinon.stub(activationUtils, 'isActivatableEnvironment').returns(true);
783+
sinon.stub(shellDetector, 'identifyTerminalShell').returns('bash');
784+
sinon.stub(windowApis, 'onDidOpenTerminal').returns(new Disposable(() => {}));
785+
sinon.stub(windowApis, 'onDidCloseTerminal').callsFake((listener) => onDidCloseEmitter.event(listener));
786+
sinon.stub(windowApis, 'onDidChangeWindowState').returns(new Disposable(() => {}));
787+
sinon.stub(windowApis, 'terminals').returns([]);
788+
sinon.stub(windowApis, 'withProgress').callsFake(async (_options, task) => {
789+
const mockProgress = { report: () => {} };
790+
const mockCancellationToken = {
791+
isCancellationRequested: false,
792+
onCancellationRequested: () => new Disposable(() => {}),
793+
};
794+
return task(mockProgress as never, mockCancellationToken as never);
795+
});
796+
sinon.stub(workspaceApis, 'onDidChangeConfiguration').returns(new Disposable(() => {}));
797+
798+
tempRoot = await fsapi.mkdtemp(path.join(os.tmpdir(), 'py-envs-1867-'));
799+
projectDir = path.join(tempRoot, 'workspace');
800+
await fsapi.ensureDir(projectDir);
801+
projectUri = Uri.file(projectDir);
802+
803+
terminalManager = new TerminalManagerImpl(terminalActivation, [], []);
804+
});
805+
806+
teardown(async () => {
807+
sinon.restore();
808+
terminalActivation.dispose();
809+
onDidCloseEmitter.dispose();
810+
await fsapi.remove(tempRoot);
811+
});
812+
813+
function createMockEnv(): PythonEnvironment {
814+
return {
815+
envId: { id: 'test-env', managerId: 'test-manager' },
816+
name: 'Test Env',
817+
displayName: 'Test Env',
818+
displayPath: '/bin/python',
819+
version: '3.12.0',
820+
environmentPath: Uri.file('/bin/python'),
821+
sysPrefix: '/bin',
822+
execInfo: {
823+
run: { executable: '/bin/python' },
824+
activation: [{ executable: '/bin/activate' }],
825+
},
826+
};
827+
}
828+
829+
test('create() rejects if terminal is closed while activation is in progress', async () => {
830+
let createdTerminal: Terminal | undefined;
831+
sinon.stub(windowApis, 'createTerminal').callsFake(() => {
832+
const t = {
833+
name: 'Python',
834+
creationOptions: {},
835+
show: sinon.stub(),
836+
sendText: sinon.stub(),
837+
exitStatus: undefined,
838+
} as unknown as Terminal;
839+
createdTerminal = t;
840+
return t;
841+
});
842+
843+
// Simulate terminal close during activation
844+
sinon.stub(terminalActivation, 'activate').callsFake(async (t) => {
845+
onDidCloseEmitter.fire(t);
846+
});
847+
848+
const env = createMockEnv();
849+
await assert.rejects(
850+
async () => {
851+
await terminalManager.create(env, { cwd: projectDir });
852+
},
853+
(error: Error) => error.message.includes('disposed'),
854+
);
855+
assert.ok(createdTerminal);
856+
});
857+
858+
test('getProjectTerminal creates fresh replacement after terminal was closed during activation', async () => {
859+
let createCount = 0;
860+
sinon.stub(windowApis, 'createTerminal').callsFake(() => {
861+
createCount++;
862+
return {
863+
name: `Python ${createCount}`,
864+
creationOptions: {},
865+
show: sinon.stub(),
866+
sendText: sinon.stub(),
867+
exitStatus: undefined,
868+
} as unknown as Terminal;
869+
});
870+
871+
let shouldFailActivation = true;
872+
sinon.stub(terminalActivation, 'activate').callsFake(async (t) => {
873+
if (shouldFailActivation) {
874+
(t as { exitStatus?: { reason: number } }).exitStatus = { reason: 1 };
875+
onDidCloseEmitter.fire(t);
876+
}
877+
});
878+
879+
const env = createMockEnv();
880+
881+
// First attempt fails because terminal was closed during activation
882+
await assert.rejects(async () => {
883+
await terminalManager.getProjectTerminal(projectUri, env);
884+
});
885+
886+
// Second attempt: activation succeeds, fresh terminal should be created and cached
887+
shouldFailActivation = false;
888+
const liveTerminal = await terminalManager.getProjectTerminal(projectUri, env);
889+
assert.strictEqual(createCount, 2);
890+
assert.strictEqual(liveTerminal.name, 'Python 2');
891+
892+
// Third attempt: should reuse the live cached terminal without creating a 3rd
893+
const reusedTerminal = await terminalManager.getProjectTerminal(projectUri, env);
894+
assert.strictEqual(reusedTerminal, liveTerminal);
895+
assert.strictEqual(createCount, 2);
896+
});
897+
898+
test('getDedicatedTerminal creates fresh replacement after terminal was closed during activation', async () => {
899+
let createCount = 0;
900+
sinon.stub(windowApis, 'createTerminal').callsFake(() => {
901+
createCount++;
902+
return {
903+
name: `Python: file ${createCount}`,
904+
creationOptions: {},
905+
show: sinon.stub(),
906+
sendText: sinon.stub(),
907+
exitStatus: undefined,
908+
} as unknown as Terminal;
909+
});
910+
911+
let shouldFailActivation = true;
912+
sinon.stub(terminalActivation, 'activate').callsFake(async (t) => {
913+
if (shouldFailActivation) {
914+
(t as { exitStatus?: { reason: number } }).exitStatus = { reason: 1 };
915+
onDidCloseEmitter.fire(t);
916+
}
917+
});
918+
919+
const env = createMockEnv();
920+
const scriptPath = path.join(projectDir, 'script.py');
921+
await fsapi.writeFile(scriptPath, 'print(1)');
922+
const fileUri = Uri.file(scriptPath);
923+
924+
const config = { get: sinon.stub().returns(false) } as unknown as WorkspaceConfiguration;
925+
sinon.stub(workspaceApis, 'getConfiguration').returns(config);
926+
927+
// First attempt fails
928+
await assert.rejects(async () => {
929+
await terminalManager.getDedicatedTerminal(fileUri, projectUri, env);
930+
});
931+
932+
// Second attempt succeeds with new terminal
933+
shouldFailActivation = false;
934+
const liveTerminal = await terminalManager.getDedicatedTerminal(fileUri, projectUri, env);
935+
assert.strictEqual(createCount, 2);
936+
assert.strictEqual(liveTerminal.name, 'Python: file 2');
937+
938+
// Subsequent attempt reuses the live terminal
939+
const reused = await terminalManager.getDedicatedTerminal(fileUri, projectUri, env);
940+
assert.strictEqual(reused, liveTerminal);
941+
assert.strictEqual(createCount, 2);
942+
});
943+
944+
test('getProjectTerminal evicts cached terminal if exitStatus is defined and recreates replacement', async () => {
945+
let createCount = 0;
946+
sinon.stub(windowApis, 'createTerminal').callsFake(() => {
947+
createCount++;
948+
return {
949+
name: `Python ${createCount}`,
950+
creationOptions: {},
951+
show: sinon.stub(),
952+
sendText: sinon.stub(),
953+
exitStatus: undefined,
954+
} as unknown as Terminal;
955+
});
956+
957+
const env = createMockEnv();
958+
959+
const term1 = await terminalManager.getProjectTerminal(projectUri, env);
960+
assert.strictEqual(term1.name, 'Python 1');
961+
962+
// Mark term1 as exited without close event
963+
(term1 as { exitStatus?: { reason: number } }).exitStatus = { reason: 0 };
964+
965+
// Next call should evict exited term1 and create replacement
966+
const term2 = await terminalManager.getProjectTerminal(projectUri, env);
967+
assert.strictEqual(createCount, 2);
968+
assert.strictEqual(term2.name, 'Python 2');
969+
});
970+
});

0 commit comments

Comments
 (0)