From dcbc225b9312c5e3ed93b555308782051e0f8eaa Mon Sep 17 00:00:00 2001 From: Andreas <183095001+AndreasReichel@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:05:56 +0100 Subject: [PATCH 1/2] Fire onDidChangeEnvironment when a refresh auto-selects a project venv When a project has no persisted venv selection, get() returns the global fallback until a refresh finds a venv in the project, e.g. one created after VS Code started. loadEnvMap() then mapped the project to that venv without firing onDidChangeEnvironment, so consumers that cache the interpreter (e.g. Pylint) kept the old one. Fixes #2046 Co-Authored-By: Claude Opus 5.5 --- .../builtin/builtInEnvironmentManager.ts | 11 ++++++ .../venvManager.autoSelect.unit.test.ts | 36 ++++++++++++++++++- 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/src/managers/builtin/builtInEnvironmentManager.ts b/src/managers/builtin/builtInEnvironmentManager.ts index 7a2a61fef..2ebf19769 100644 --- a/src/managers/builtin/builtInEnvironmentManager.ts +++ b/src/managers/builtin/builtInEnvironmentManager.ts @@ -822,6 +822,7 @@ export class BuiltInEnvironmentManager implements EnvironmentManager { : this.baseManager.getEnvironments('global')); await this.loadGlobalEnv(globals); + const previousEnvs = new Map(this.fsPathToEnv); this.fsPathToEnv.forEach((_env, key) => { if (isCurrent(key)) { this.fsPathToEnv.delete(key); @@ -890,6 +891,16 @@ export class BuiltInEnvironmentManager implements EnvironmentManager { ) ?? projectEnvs[0]; if (found) { this.fsPathToEnv.set(normalizedPath, found); + // A venv created in the project after the last refresh replaces the global fallback + // that get() returned so far, so consumers have to be told. + const previousEnv = previousEnvs.get(normalizedPath) ?? this.globalEnv; + if (previousEnv?.envId.id !== found.envId.id) { + events.push(() => { + if (isCurrent(normalizedPath)) { + this._onDidChangeEnvironment.fire({ uri: project.uri, old: previousEnv, new: found }); + } + }); + } } } } diff --git a/src/test/managers/builtin/venvManager.autoSelect.unit.test.ts b/src/test/managers/builtin/venvManager.autoSelect.unit.test.ts index 9c8b0b258..afe0c4fa9 100644 --- a/src/test/managers/builtin/venvManager.autoSelect.unit.test.ts +++ b/src/test/managers/builtin/venvManager.autoSelect.unit.test.ts @@ -5,7 +5,13 @@ import assert from 'assert'; import * as path from 'path'; import * as sinon from 'sinon'; import { LogOutputChannel, Uri } from 'vscode'; -import { EnvironmentManager, PythonEnvironment, PythonEnvironmentApi, PythonProject } from '../../../api'; +import { + DidChangeEnvironmentEventArgs, + EnvironmentManager, + PythonEnvironment, + PythonEnvironmentApi, + PythonProject, +} from '../../../api'; import { VENV_MANAGER_ID } from '../../../common/constants'; import { normalizePath } from '../../../common/utils/pathUtils'; import * as windowApis from '../../../common/window.apis'; @@ -102,4 +108,32 @@ suite('VenvManager auto-selection for a project', () => { assert.strictEqual((await manager.get(projectUri))?.envId.id, brokenRoot.envId.id); }); + + test('fires onDidChangeEnvironment when a refresh finds a venv created in the project', async () => { + const rootVenv = makeVenv(venvIn(), '3.12.14'); + const find = sinon.stub(venvUtils, 'findVirtualEnvironments').resolves([]); + const manager = await createManager(); + const events: DidChangeEnvironmentEventArgs[] = []; + manager.onDidChangeEnvironment((e) => events.push(e)); + + find.resolves([rootVenv]); + await manager.refresh(undefined); + + assert.strictEqual(events.length, 1); + assert.strictEqual(events[0].uri?.fsPath, projectUri.fsPath); + assert.strictEqual(events[0].new?.envId.id, rootVenv.envId.id); + assert.strictEqual((await manager.get(projectUri))?.envId.id, rootVenv.envId.id); + }); + + test('does not fire onDidChangeEnvironment when a refresh finds the same venv again', async () => { + const rootVenv = makeVenv(venvIn(), '3.12.14'); + sinon.stub(venvUtils, 'findVirtualEnvironments').resolves([rootVenv]); + const manager = await createManager(); + const events: DidChangeEnvironmentEventArgs[] = []; + manager.onDidChangeEnvironment((e) => events.push(e)); + + await manager.refresh(undefined); + + assert.strictEqual(events.length, 0); + }); }); From 490fa2b5346815149a4ce2750ba2d82955cd9d18 Mon Sep 17 00:00:00 2001 From: Andreas <183095001+AndreasReichel@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:56:51 +0100 Subject: [PATCH 2/2] Compare interpreters, not ids, and report the old global fallback Discovery gives environment items new random ids on every refresh, so comparing ids fired onDidChangeEnvironment on every refresh that found the same venv. Compare manager, interpreter path and version instead. loadGlobalEnv() replaces this.globalEnv before the project map is built, so the event reported the new global as `old` when the global Python changed in the same refresh. Save the previous global first. Also rename previousEnvs to previousProjectEnvs, as suggested in review. Co-Authored-By: Claude Opus 5.5 --- .../builtin/builtInEnvironmentManager.ts | 21 ++++++-- .../venvManager.autoSelect.unit.test.ts | 49 ++++++++++++++++--- 2 files changed, 59 insertions(+), 11 deletions(-) diff --git a/src/managers/builtin/builtInEnvironmentManager.ts b/src/managers/builtin/builtInEnvironmentManager.ts index 2ebf19769..ba31ae568 100644 --- a/src/managers/builtin/builtInEnvironmentManager.ts +++ b/src/managers/builtin/builtInEnvironmentManager.ts @@ -75,6 +75,18 @@ import { setVenvForWorkspaces, } from './venvUtils'; +/** + * Discovery creates new environment items with random ids on every refresh, so compare what + * identifies the interpreter instead. + */ +function isSameInterpreter(a: PythonEnvironment | undefined, b: PythonEnvironment): boolean { + return ( + a?.envId.managerId === b.envId.managerId && + normalizePath(a.environmentPath.fsPath) === normalizePath(b.environmentPath.fsPath) && + a.version === b.version + ); +} + export class BuiltInEnvironmentManager implements EnvironmentManager { readonly capabilities: Capabilities = { [EnvironmentCapability.List]: supportedCapability, @@ -820,9 +832,10 @@ export class BuiltInEnvironmentManager implements EnvironmentManager { const globals = await (toolExecution && tools?.getEnvironments ? tools.getEnvironments('global') : this.baseManager.getEnvironments('global')); + const previousGlobalEnv = this.globalEnv; await this.loadGlobalEnv(globals); - const previousEnvs = new Map(this.fsPathToEnv); + const previousProjectEnvs = new Map(this.fsPathToEnv); this.fsPathToEnv.forEach((_env, key) => { if (isCurrent(key)) { this.fsPathToEnv.delete(key); @@ -892,9 +905,9 @@ export class BuiltInEnvironmentManager implements EnvironmentManager { if (found) { this.fsPathToEnv.set(normalizedPath, found); // A venv created in the project after the last refresh replaces the global fallback - // that get() returned so far, so consumers have to be told. - const previousEnv = previousEnvs.get(normalizedPath) ?? this.globalEnv; - if (previousEnv?.envId.id !== found.envId.id) { + // that get() returned so far, so consumers have to be notified. + const previousEnv = previousProjectEnvs.get(normalizedPath) ?? previousGlobalEnv; + if (!isSameInterpreter(previousEnv, found)) { events.push(() => { if (isCurrent(normalizedPath)) { this._onDidChangeEnvironment.fire({ uri: project.uri, old: previousEnv, new: found }); diff --git a/src/test/managers/builtin/venvManager.autoSelect.unit.test.ts b/src/test/managers/builtin/venvManager.autoSelect.unit.test.ts index afe0c4fa9..d827a06b7 100644 --- a/src/test/managers/builtin/venvManager.autoSelect.unit.test.ts +++ b/src/test/managers/builtin/venvManager.autoSelect.unit.test.ts @@ -12,7 +12,7 @@ import { PythonEnvironmentApi, PythonProject, } from '../../../api'; -import { VENV_MANAGER_ID } from '../../../common/constants'; +import { SYSTEM_MANAGER_ID, VENV_MANAGER_ID } from '../../../common/constants'; import { normalizePath } from '../../../common/utils/pathUtils'; import * as windowApis from '../../../common/window.apis'; import { BuiltInEnvironmentManager } from '../../../managers/builtin/builtInEnvironmentManager'; @@ -30,9 +30,9 @@ suite('VenvManager auto-selection for a project', () => { return Uri.file(path.join(projectUri.fsPath, ...segments, '.venv')).fsPath; } - function makeVenv(prefix: string, version: string): PythonEnvironment { + function makeVenv(prefix: string, version: string, id = prefix): PythonEnvironment { return createMockPythonEnvironment({ - id: prefix, + id, name: '.venv', envPath: path.join(prefix, bin, 'python'), sysPrefix: prefix, @@ -41,7 +41,20 @@ suite('VenvManager auto-selection for a project', () => { }); } - async function createManager(): Promise { + function makeGlobal(prefix: string, version: string): PythonEnvironment { + return createMockPythonEnvironment({ + id: prefix, + name: 'python', + envPath: path.join(prefix, 'python'), + sysPrefix: prefix, + version, + managerId: SYSTEM_MANAGER_ID, + }); + } + + async function createManager( + getGlobals: sinon.SinonStub = sinon.stub().resolves([]), + ): Promise { const project = { name: 'project', uri: projectUri } as PythonProject; const projectRoot = normalizePath(projectUri.fsPath); const api = { @@ -51,7 +64,7 @@ suite('VenvManager auto-selection for a project', () => { }, getPythonProjects: () => [project], } as unknown as PythonEnvironmentApi; - const baseManager = { getEnvironments: sinon.stub().resolves([]) } as unknown as EnvironmentManager; + const baseManager = { getEnvironments: getGlobals } as unknown as EnvironmentManager; const log = { info: sinon.stub(), warn: sinon.stub(), error: sinon.stub() } as unknown as LogOutputChannel; const manager = new BuiltInEnvironmentManager( {} as NativePythonFinder, @@ -125,13 +138,35 @@ suite('VenvManager auto-selection for a project', () => { assert.strictEqual((await manager.get(projectUri))?.envId.id, rootVenv.envId.id); }); - test('does not fire onDidChangeEnvironment when a refresh finds the same venv again', async () => { + test('reports the global fallback from before the refresh as the old environment', async () => { + const oldGlobal = makeGlobal(path.resolve('python312'), '3.12.14'); + const newGlobal = makeGlobal(path.resolve('python313'), '3.13.15'); const rootVenv = makeVenv(venvIn(), '3.12.14'); - sinon.stub(venvUtils, 'findVirtualEnvironments').resolves([rootVenv]); + const getGlobals = sinon.stub().resolves([oldGlobal]); + const find = sinon.stub(venvUtils, 'findVirtualEnvironments').resolves([]); + const manager = await createManager(getGlobals); + const events: DidChangeEnvironmentEventArgs[] = []; + manager.onDidChangeEnvironment((e) => events.push(e)); + + getGlobals.resolves([oldGlobal, newGlobal]); + find.resolves([rootVenv]); + await manager.refresh(undefined); + + assert.strictEqual(events.length, 1); + assert.strictEqual(events[0].old?.envId.id, oldGlobal.envId.id); + assert.strictEqual(events[0].new?.envId.id, rootVenv.envId.id); + }); + + test('does not fire onDidChangeEnvironment when a refresh finds the same venv again', async () => { + const find = sinon + .stub(venvUtils, 'findVirtualEnvironments') + .resolves([makeVenv(venvIn(), '3.12.14', 'first')]); const manager = await createManager(); const events: DidChangeEnvironmentEventArgs[] = []; manager.onDidChangeEnvironment((e) => events.push(e)); + // Discovery creates a new item with a new id for the same interpreter. + find.resolves([makeVenv(venvIn(), '3.12.14', 'second')]); await manager.refresh(undefined); assert.strictEqual(events.length, 0);