From fe1b5eacf83a899c5d0b8d82b84b83ca4f278090 Mon Sep 17 00:00:00 2001 From: Anka Tama Date: Thu, 3 Dec 2026 17:38:19 +0700 Subject: [PATCH] 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 <55616872+xirf@users.noreply.github.com> --- crates/ide-sdk/src/apply.rs | 12 +++++++++ crates/ide-sdk/src/tests.rs | 25 ++++++++++++++++++ src/features/run/npmGutter.test.ts | 16 +++++++++-- src/features/run/npmGutter.ts | 12 ++++++--- src/features/run/npmInstall.test.ts | 41 ++++++++++++++++++++++++++--- src/features/run/npmInstall.ts | 16 ++++++++--- 6 files changed, 111 insertions(+), 11 deletions(-) diff --git a/crates/ide-sdk/src/apply.rs b/crates/ide-sdk/src/apply.rs index e0f314d4ed..e5b3e3696f 100644 --- a/crates/ide-sdk/src/apply.rs +++ b/crates/ide-sdk/src/apply.rs @@ -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() { diff --git a/crates/ide-sdk/src/tests.rs b/crates/ide-sdk/src/tests.rs index cbfab0071b..dc5e96c26e 100644 --- a/crates/ide-sdk/src/tests.rs +++ b/crates/ide-sdk/src/tests.rs @@ -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(); diff --git a/src/features/run/npmGutter.test.ts b/src/features/run/npmGutter.test.ts index dce77a5995..04a1eaa419 100644 --- a/src/features/run/npmGutter.test.ts +++ b/src/features/run/npmGutter.test.ts @@ -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( diff --git a/src/features/run/npmGutter.ts b/src/features/run/npmGutter.ts index 7a6b7769f1..d10876edbb 100644 --- a/src/features/run/npmGutter.ts +++ b/src/features/run/npmGutter.ts @@ -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}`; diff --git a/src/features/run/npmInstall.test.ts b/src/features/run/npmInstall.test.ts index 3f89ff8db2..8a4dc059e0 100644 --- a/src/features/run/npmInstall.test.ts +++ b/src/features/run/npmInstall.test.ts @@ -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); +}); diff --git a/src/features/run/npmInstall.ts b/src/features/run/npmInstall.ts index 5fde8b91ad..3ce81986cc 100644 --- a/src/features/run/npmInstall.ts +++ b/src/features/run/npmInstall.ts @@ -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(); /** Root and state already notified this session. */ const notified = new Set(); +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());