fix(run): honor configured Node.js package manager in install prompts and config names (#7782)

An explicit Package manager in Settings > Languages & Frameworks > Node.js changed the spawned command, but the dependency-install notification and its run config, the package.json gutter fallback and detected npm run configuration names still showed the lockfile-detected manager. The configured manager now comes first in the gutter fallback, the install prompt rechecks when the setting changes (keeping an Ignore for the same dependency state), and detected config names have their leading package manager rewritten (bun run dev -> npm run dev, also after a workspace prefix).

Co-authored-by: xirf <[email protected]>
Цей коміт міститься в:
Anka Tamaтаxirf authored and GitHub committed 2026-12-03 18:38:19 +08:00
1 джерело 21c4b08a5d
коміт fe1b5eacf8
6 files changed
+111 -11

No files matched your search

+12
Переглянути файл
@@ -2074,6 +2074,16 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
apply_to_run_configs_in(configs, root, None, s)
}
/// Replaces the leading package manager token in a detected npm config's display name
/// (`"bun run dev"` or `"packages/web: bun run dev"`).
fn rewrite_package_manager_name(name: &mut String, old: &str, new: &str) {
if let Some(rest) = name.strip_prefix(old).and_then(|s| s.strip_prefix(' ')) {
*name = format!("{new} {rest}");
} else if let Some((prefix, rest)) = name.rsplit_once(&format!(": {old} ")) {
*name = format!("{prefix}: {new} {rest}");
}
}
/// [`apply_to_run_configs`] with an inherited fallback project: a workspace member
/// (`root`) with no Python of its own (no interpreter setting, virtualenv or pin)
/// runs on the primary project's (`fallback`) — the module SDK a member without its
@@ -2124,7 +2134,9 @@ pub fn apply_to_run_configs_in(configs: &mut [RunConfig], root: &Path, fallback:
&& c.kind == "npm"
&& c.detected
&& matches!(c.command.as_str(), "npm" | "pnpm" | "yarn" | "bun")
&& c.command != pm
{
rewrite_package_manager_name(&mut c.name, &c.command, pm);
c.command = pm.to_owned();
}
if c.extras.target.is_none() {
+25
Переглянути файл
@@ -594,6 +594,31 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
assert_eq!(configs[9].args, ["-m", "celery", "-A", "proj", "worker"]);
}
#[test]
fn package_manager_override_updates_detected_npm_config_names() {
let tmp = tempfile::tempdir().unwrap();
let mut s = Settings::default();
s.languages.node.package_manager = "npm".into();
let mut install = run("npm", "bun", &["install"]);
install.name = "bun install".into();
let mut dev = run("npm", "bun", &["run", "dev"]);
dev.name = "bun run dev".into();
let mut workspace = run("npm", "bun", &["run", "build"]);
workspace.name = "packages/web: bun run build".into();
let mut user = run("npm", "bun", &["run", "custom"]);
user.name = "bun run custom".into();
user.detected = false;
let mut configs = vec![install, dev, workspace, user];
apply_to_run_configs(&mut configs, tmp.path(), &s);
assert_eq!((configs[0].command.as_str(), configs[0].name.as_str()), ("npm", "npm install"));
assert_eq!((configs[1].command.as_str(), configs[1].name.as_str()), ("npm", "npm run dev"));
assert_eq!((configs[2].command.as_str(), configs[2].name.as_str()), ("npm", "packages/web: npm run build"));
assert_eq!((configs[3].command.as_str(), configs[3].name.as_str()), ("bun", "bun run custom"));
}
#[test]
fn saved_python_configs_keep_their_explicit_interpreter() {
let temp = tempfile::tempdir().unwrap();
+14 -2
Переглянути файл
@@ -179,12 +179,18 @@ describe("scriptPackageManager", () => {
expect(scriptPackageManager(null, ["bun.lock", "yarn.lock"])).toBe("yarn");
expect(scriptPackageManager(null, [])).toBe("npm");
});
it("prefers an explicit configured package manager over declarations and lockfiles", () => {
expect(scriptPackageManager({ packageManager: "pnpm@9" }, ["yarn.lock"], "npm")).toBe("npm");
expect(scriptPackageManager({ packageManager: "pnpm@9" }, ["yarn.lock"], "")).toBe("pnpm");
expect(scriptPackageManager({ packageManager: "pnpm@9" }, ["yarn.lock"], "unknown")).toBe("pnpm");
});
});
describe("scriptMenuItems", () => {
beforeEach(() => {
vi.spyOn(store, "loadConfigs").mockResolvedValue();
useProject.setState({ project: { root: "/project" } as never });
useProject.setState({ project: { root: "/project" } as never, settings: null });
store.useRun.setState({ configs: [] });
vi.spyOn(commands, "fsReadDir").mockResolvedValue({
status: "ok",
@@ -194,7 +200,7 @@ describe("scriptMenuItems", () => {
});
afterEach(() => {
vi.restoreAllMocks();
useProject.setState({ project: null });
useProject.setState({ project: null, settings: null });
store.useRun.setState({ configs: [] });
});
@@ -204,6 +210,12 @@ describe("scriptMenuItems", () => {
expect(commands.fsReadDir).toHaveBeenCalledWith("/project/");
});
it("uses the configured Node.js package manager for an undetected script", async () => {
useProject.setState({ settings: { languages: { node: { packageManager: "npm" } } } as never });
const items = await scriptMenuItems({ name: "new", line: 0 }, "/project/package.json", "{}");
expect(items).toMatchObject([{ label: "Run 'npm run new'" }, { label: "Debug 'npm run new'" }]);
});
it("inherits the backend's workspace manager from a sibling script", async () => {
store.useRun.setState({ configs: [cfg({ command: "yarn", cwd: "packages/web" })] });
const items = await scriptMenuItems(
+9 -3
Переглянути файл
@@ -10,6 +10,7 @@ import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { call, commands, type RunConfig } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { validateLanguages } from "@/platform/languageSettings";
import { useProject } from "@/platform/project";
import { gutterIconMarkup, showContextMenu, type MenuItem } from "@/ui";
import { runIconsShown } from "./runGutter";
@@ -184,10 +185,13 @@ function safeParse(text: string): PackageJson | null {
}
}
/** Same precedence as backend detection for a package: declaration, then lockfile. */
export function scriptPackageManager(pkg: PackageJson | null, files: readonly string[]): string {
const PACKAGE_MANAGERS = new Set(["npm", "pnpm", "yarn", "bun"]);
/** Same precedence as backend detection for a package: configured setting, declaration, then lockfile. */
export function scriptPackageManager(pkg: PackageJson | null, files: readonly string[], configured = ""): string {
if (PACKAGE_MANAGERS.has(configured)) return configured;
const pm = typeof pkg?.packageManager === "string" ? pkg.packageManager.split("@")[0] : "";
if (pm === "pnpm" || pm === "yarn" || pm === "bun" || pm === "npm") return pm;
if (pm && PACKAGE_MANAGERS.has(pm)) return pm;
if (files.includes("pnpm-lock.yaml")) return "pnpm";
if (files.includes("yarn.lock")) return "yarn";
if (files.includes("bun.lock") || files.includes("bun.lockb")) return "bun";
@@ -262,9 +266,11 @@ export async function scriptMenuItems(entry: ScriptEntry, path: string, content:
: null;
const packageDir = rootPkg ? `${root}/` : path.slice(0, -"package.json".length);
const files = await call(commands.fsReadDir(packageDir)).catch(() => []);
const configured = validateLanguages(useProject.getState().settings?.languages).node.packageManager;
pm = scriptPackageManager(
rootPkg ?? pkg,
files.filter((f) => f.kind === "file" || f.targetKind === "file").map((f) => f.name),
configured,
);
}
const label = matched?.name ?? `${pm} run ${entry.name}`;
+38 -3
Переглянути файл
@@ -72,11 +72,11 @@ beforeEach(() => {
afterEach(() => {
dispose?.();
vi.clearAllMocks();
useProject.setState({ project: null });
useProject.setState({ project: null, settings: null });
});
const open = async (root = "/p") => {
useProject.setState({ project: { root, trusted: true } as never });
const open = async (root = "/p", settings: unknown = null) => {
useProject.setState({ project: { root, trusted: true } as never, settings: settings as never });
dispose = registerNpmInstall();
await vi.waitFor(() => expect(ipc.fsReadDir).toHaveBeenCalled());
await settle();
@@ -238,3 +238,38 @@ it("checks packages right under the project root, each on its own outside a pnpm
body: "Run 'npm install' in 'web' to install them.",
});
});
it("uses the configured Node.js package manager in the install prompt and command", async () => {
write("/p/package.json", 1_000, pkg({ react: "^19.0.0" }));
write("/p/bun.lock", 1_000);
await open("/p", { languages: { node: { packageManager: "npm" } } });
expect(titles()).toEqual(["Dependencies are not installed"]);
expect(notify.mock.calls[0]![0].body).toBe("Run 'npm install' to install them.");
act("Install");
await vi.waitFor(() => expect(run.startRun).toHaveBeenCalled());
expect(run.startRun.mock.calls[0]![0]).toMatchObject({
kind: "npm",
name: "npm install",
command: "npm",
args: ["install"],
cwd: "/p",
});
});
it("updates an active install prompt when the package manager setting changes unless ignored", async () => {
write("/p/package.json", 1_000, pkg({ react: "^19.0.0" }));
write("/p/bun.lock", 1_000);
await open("/p", { languages: { node: { packageManager: "npm" } } });
expect(notify.mock.calls.at(-1)![0].body).toBe("Run 'npm install' to install them.");
useProject.setState({ settings: { languages: { node: { packageManager: "pnpm" } } } as never });
await settle();
expect(notify).toHaveBeenCalledTimes(2);
expect(notify.mock.calls.at(-1)![0].body).toBe("Run 'pnpm install' to install them.");
act("Ignore");
useProject.setState({ settings: { languages: { node: { packageManager: "yarn" } } } as never });
await settle();
expect(notify).toHaveBeenCalledTimes(2);
});
+13 -3
Переглянути файл
@@ -6,6 +6,7 @@
import { registerActions } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { call, commands, isTauri, onIdeEvent, type RunConfig } from "@/platform/ipc";
import { validateLanguages } from "@/platform/languageSettings";
import { useProject } from "@/platform/project";
import { maybeEditorService, notifications } from "@/workbench/contributions";
import { scriptPackageManager } from "./npmGutter";
@@ -167,6 +168,8 @@ const installing = new Set<string>();
/** Root and state already notified this session. */
const notified = new Set<string>();
const configuredPackageManager = () => validateLanguages(useProject.getState().settings?.languages).node.packageManager;
async function inspect(root: string) {
const files = await listDir(root);
const nodeModules = files.get("node_modules");
@@ -211,7 +214,7 @@ async function inspect(root: string) {
});
return {
due,
pm: scriptPackageManager(rootPkg, [...files.keys()]),
pm: scriptPackageManager(rootPkg, [...files.keys()], configuredPackageManager()),
state: JSON.stringify([due, lockAt, pkgs.map((p) => [p.path, p.signature])]),
};
}
@@ -264,7 +267,7 @@ function check(root: string) {
notifications().expire?.(key);
return;
}
const seen = `${root}\n${state}`;
const seen = `${root}\n${pm}\n${state}`;
if (installing.has(root) || notified.has(seen) || readStore().ignored[root] === state) return;
notified.add(seen);
const command = `${pm} install`;
@@ -394,7 +397,14 @@ export function registerNpmInstall(): () => void {
}),
onIdeEvent("projectTrustChanged", () => recheck()),
useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root) void open();
if (s.project?.root !== prev.project?.root) {
void open();
} else if (
validateLanguages(s.settings?.languages).node.packageManager !==
validateLanguages(prev.settings?.languages).node.packageManager
) {
recheck();
}
}),
];
return () => disposers.forEach((d) => d());