From 0dafd649daba21611b1bbcc67ff2f08b43cc0133 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Tue, 17 Nov 2026 04:24:28 +0800 Subject: [PATCH] fix(python): readable environment creation log and status refresh after creating one (#3837) Tool output is shown as a terminal would show the line: backspaces erase (conda's spinner), a carriage return rewrites the line (pip progress) and ANSI sequences are dropped. The interpreter status widget re-reads interpreters when one is created or added in Settings. A conda environment lives outside the project, so no file event announced it, and when the configured path was already set the widget kept showing "Invalid interpreter" and an interpreter list without it. --- .../settings/__tests__/pythonStatus.test.tsx | 20 +++++++++++++ .../settings/__tests__/terminalLine.test.ts | 15 ++++++++++ .../settings/languages/PythonStatus.tsx | 14 ++++++++-- src/features/settings/languages/api.ts | 28 ++++++++++++++++++- 4 files changed, 74 insertions(+), 3 deletions(-) create mode 100644 src/features/settings/__tests__/terminalLine.test.ts diff --git a/src/features/settings/__tests__/pythonStatus.test.tsx b/src/features/settings/__tests__/pythonStatus.test.tsx index e29890e17..4f45c909b 100644 --- a/src/features/settings/__tests__/pythonStatus.test.tsx +++ b/src/features/settings/__tests__/pythonStatus.test.tsx @@ -34,6 +34,7 @@ vi.mock("@/workbench/contributions", () => ({ })); import { isStatusWidgetAvailable } from "@/workbench/statusBarWidgets"; import { activatePythonStatus, interpreterChoices, isPythonPath, nearMember } from "../languages/PythonStatus"; +import { rememberSdk, useSdks } from "../languages/api"; let dispose: () => void; beforeEach(() => { @@ -50,6 +51,7 @@ beforeEach(() => { afterEach(() => { cleanup(); dispose(); + useSdks.setState({ byKind: {} }); }); const mount = () => { @@ -210,6 +212,24 @@ describe("Python interpreter status", () => { await act(async () => finish([{ path: "/old/python", name: "Python 3.12" } as Sdk])); expect(screen.queryByRole("button")).toBeNull(); }); + it("picks up an environment created outside the project", async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + try { + const python = "C:\\Users\\me\\miniconda3\\envs\\demo\\python.exe"; + useProject.setState({ settings: { languages: { python: { interpreter: python } } } as never }); + mocks.files.mockResolvedValue([{ path: "/project/main.py" }]); + mount(); + await screen.findByRole("button", { name: "Python Interpreter: Invalid interpreter" }); + // conda creates the environment in its envs directory, the configured path stays the same. + mocks.effective.mockResolvedValue(python); + act(() => rememberSdk("python", { path: python, name: "Python 3.12 (demo)", source: "conda" } as Sdk)); + await act(() => vi.advanceTimersByTimeAsync(400)); + await screen.findByRole("button", { name: "Python Interpreter: Python 3.12 (demo)" }); + expect(mocks.detect).toHaveBeenCalledTimes(2); + } finally { + vi.useRealTimers(); + } + }); it("opens the Python page for both settings entries", async () => { const run = vi.fn(); const off = registerAction({ id: "file.settings", title: "Settings…", run }); diff --git a/src/features/settings/__tests__/terminalLine.test.ts b/src/features/settings/__tests__/terminalLine.test.ts new file mode 100644 index 000000000..0a0697bc7 --- /dev/null +++ b/src/features/settings/__tests__/terminalLine.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from "vitest"; +import { terminalLine } from "../languages/api"; + +describe("terminalLine", () => { + it.each([ + ["Solving environment: -\b\\\b|\b/\bdone", "Solving environment: done"], + ["Downloading 10%\rDownloading 55%\rDownloading 100%", "Downloading 100%"], + ["Collecting pip\r\n", "Collecting pip"], + ["\x1b[32mSuccessfully installed\x1b[0m six", "Successfully installed six"], + ["\x1b]0;conda\x07Preparing transaction", "Preparing transaction"], + ["progress 99%\rdone", "doneress 99%"], + ["\tindented\x07", "\tindented"], + ])("renders %j as %j", (raw, line) => expect(terminalLine(raw)).toBe(line)); + it.each(["", "\b\b", "\x1b[2K\r", " "])("drops %j", (raw) => expect(terminalLine(raw)).toBeNull()); +}); diff --git a/src/features/settings/languages/PythonStatus.tsx b/src/features/settings/languages/PythonStatus.tsx index 87abdd1c3..7c7e1aec1 100644 --- a/src/features/settings/languages/PythonStatus.tsx +++ b/src/features/settings/languages/PythonStatus.tsx @@ -8,7 +8,7 @@ import { notifications, registerStatusItem } from "@/workbench/contributions"; import { useEditorRegistry } from "@/editor/api"; import { BarButton, Menu, type MenuItem } from "@/ui"; import { Icon } from "@/ui/icons"; -import { effectivePython, interpreterTarget, targetChoices, type Sdk } from "./api"; +import { effectivePython, interpreterTarget, targetChoices, useSdks, type Sdk } from "./api"; import { tildify } from "./components"; import { validateRunTargets } from "@/platform/remoteSettings"; import { interpreterIcon, interpreterPathKey } from "./interpreters"; @@ -117,7 +117,10 @@ function PythonStatus() { visible || configured ? await Promise.all([ effectivePython(nearMember(members, active)), - (detected ??= call(commands.sdkDetect("python"))), + (detected ??= call(commands.sdkDetect("python"))).then((found) => [ + ...(useSdks.getState().byKind.python ?? []), + ...found, + ]), ]) : [null, [] as Sdk[]]; if (live && sequence === request) usePopup.setState({ status: { root, configured, visible, python, sdks } }); @@ -147,6 +150,13 @@ function PythonStatus() { detected = undefined; schedule(); }), + // An environment created or added in Settings may live outside the project (conda's + // envs directory), so no file event announces it; the configured path may not change. + useSdks.subscribe((s, prev) => { + if (s.byKind.python === prev.byKind.python) return; + detected = undefined; + schedule(); + }), ]; return () => { live = false; diff --git a/src/features/settings/languages/api.ts b/src/features/settings/languages/api.ts index edd9ffce1..d5baa8c76 100644 --- a/src/features/settings/languages/api.ts +++ b/src/features/settings/languages/api.ts @@ -85,13 +85,39 @@ export interface Streamed { cancel: () => void; } +/** + * A line of tool output as a terminal shows it: backspaces erase (conda's `-\|/` spinner), + * a carriage return starts the line over (pip's progress bar), colour and other control + * sequences go. Null when nothing visible is left. + */ +export function terminalLine(raw: string): string | null { + // eslint-disable-next-line no-control-regex + const plain = raw.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g, ""); + let line = ""; + for (const segment of plain.split("\r")) { + if (!segment) continue; + let text = ""; + for (const ch of segment) { + if (ch === "\b") text = text.slice(0, -1); + // eslint-disable-next-line no-control-regex + else if (ch === "\t" || !/[\x00-\x1f\x7f]/.test(ch)) text += ch; + } + // A carriage return overwrites from the line start; the last non-empty rewrite wins. + if (text.trim()) line = text.length >= line.length ? text : text + line.slice(text.length); + } + return line.trim() ? line.trimEnd() : null; +} + function streamed( run: (request: ReturnType, ch: Channel) => Promise, onLine: (line: string) => void, ): Streamed { const request = nextRequestId(); const channel = new Channel(); - channel.onmessage = onLine; + channel.onmessage = (raw) => { + const line = terminalLine(raw); + if (line !== null) onLine(line); + }; return { promise: run(request, channel), cancel: () => void commands.cancelRequest(request) }; }