From cfaf05c84bd6af3a2cc19da3e265e7060d6d0b21 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Sat, 5 Dec 2026 23:15:08 +0800 Subject: [PATCH 01/22] fix(process): fit a long PATH into cmd.exe's limit for batch programs on Windows (#8225) cmd.exe ignores an inherited variable longer than 8191 characters, so a .cmd language server started with a long PATH couldn't find node. For a batch program whose PATH is too long, later duplicates (without case) and missing local directories are now dropped, keeping the order, and if that's not enough the longest directories take their 8.3 short form until it fits. Native programs keep their PATH. Windows CI ran the batch launch test on this change; its only failures were the CRLF tests fixed on main by #8238. Fixes #8155 --- crates/ide-core/src/process.rs | 102 +++++++++++++++++++++++++++++---- 1 file changed, 90 insertions(+), 12 deletions(-) diff --git a/crates/ide-core/src/process.rs b/crates/ide-core/src/process.rs index ddb2dc5912..c2ea891f8c 100644 --- a/crates/ide-core/src/process.rs +++ b/crates/ide-core/src/process.rs @@ -37,13 +37,16 @@ pub fn prepare(cmd: &mut Command) -> &mut Command { cmd } +/// cmd.exe drops an inherited variable longer than this outright, and batch files (`.cmd`, +/// `.bat`) always run through it. +#[cfg_attr(not(windows), allow(dead_code))] +const CMD_ENV_LIMIT: usize = 8191; + #[cfg(windows)] fn compact_batch_path(cmd: &mut Command) { - use std::os::windows::ffi::OsStrExt; use std::path::{Component, Prefix}; - // Rust runs these files through cmd.exe, which drops inherited variables over this limit. - const CMD_ENV_LIMIT: usize = 8191; + // Rust runs these files through cmd.exe. let extension = Path::new(cmd.get_program()).extension(); if !extension.is_some_and(|ext| ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat")) { return; @@ -52,25 +55,80 @@ fn compact_batch_path(cmd: &mut Command) { Some((_, path)) => path.map(OsStr::to_owned), None => std::env::var_os("PATH"), }; - let Some(path) = path.filter(|p| p.encode_wide().count() > CMD_ENV_LIMIT) else { return }; - - // The IDE includes possible locations of as-yet uninstalled tools. Prune paths that are - // missing now, keeping search precedence and leaving UNC and relative paths alone. - let dirs = std::env::split_paths(&path).filter(|dir| { + let Some(path) = path else { return }; + // The IDE includes possible locations of as-yet uninstalled tools: drop the ones missing + // now, leaving UNC and relative paths alone. + let present = |dir: &Path| { let local = dir.is_absolute() && matches!(dir.components().next(), Some(Component::Prefix(p)) if matches!(p.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_))); !local || !std::fs::symlink_metadata(dir) .is_err_and(|e| matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory)) - }); - if let Ok(compact) = std::env::join_paths(dirs) - && compact.encode_wide().count() <= CMD_ENV_LIMIT - { + }; + if let Some(compact) = compact_path_list(&path, CMD_ENV_LIMIT, present, short_path) { cmd.env("PATH", compact); } } +/// The 8.3 form of `dir`, when the volume has one. +#[cfg(windows)] +fn short_path(dir: &Path) -> Option { + use std::os::windows::ffi::{OsStrExt, OsStringExt}; + use windows_sys::Win32::Storage::FileSystem::GetShortPathNameW; + + let wide: Vec = dir.as_os_str().encode_wide().chain(Some(0)).collect(); + let mut buf = vec![0u16; wide.len()]; + let len = u32::try_from(buf.len()).ok()?; + // SAFETY: both buffers are valid for their lengths and `wide` is NUL-terminated. + let written = unsafe { GetShortPathNameW(wide.as_ptr(), buf.as_mut_ptr(), len) } as usize; + // 0 is an error; a value of at least the buffer's length is the size a longer form needs. + if written == 0 || written >= buf.len() { + return None; + } + buf.truncate(written); + Some(OsString::from_wide(&buf).into()) +} + +/// `path` (a `PATH` list) made to fit `limit` UTF-16 units where it is longer: later +/// duplicates (without case on Windows) and directories `present` rejects are dropped, keeping +/// the search order; when that is still too long, directories take `shorten`'s form, longest +/// first, until it fits. `None` when `path` fits already or nothing got shorter. +#[cfg_attr(not(windows), allow(dead_code))] +fn compact_path_list( + path: &OsStr, + limit: usize, + present: impl Fn(&Path) -> bool, + shorten: impl Fn(&Path) -> Option, +) -> Option { + let width = |s: &OsStr| s.to_string_lossy().encode_utf16().count(); + let original = width(path); + if original <= limit { + return None; + } + let mut seen = std::collections::HashSet::new(); + let mut dirs: Vec = std::env::split_paths(path) + .filter(|d| !d.as_os_str().is_empty() && seen.insert(path_entry_key(d)) && present(d)) + .collect(); + let mut joined = std::env::join_paths(&dirs).ok()?; + if width(&joined) > limit { + let mut longest: Vec = (0..dirs.len()).collect(); + longest.sort_by_key(|&i| std::cmp::Reverse(width(dirs[i].as_os_str()))); + let mut total = width(&joined); + for i in longest { + if total <= limit { + break; + } + if let Some(short) = shorten(&dirs[i]).filter(|s| width(s.as_os_str()) < width(dirs[i].as_os_str())) { + total -= width(dirs[i].as_os_str()) - width(short.as_os_str()); + dirs[i] = short; + } + } + joined = std::env::join_paths(&dirs).ok()?; + } + (width(&joined) < original).then_some(joined) +} + /// Starts the child as the leader of its own process group on Unix, so [`kill_tree`] and /// [`terminate_tree`] reach what it starts in turn (`gh` → `git`, `npm` → `node`, `mvnw` → /// the JVM). A no-op elsewhere: on Windows the tree is found from the child's process id. @@ -1295,6 +1353,26 @@ mod tests { assert_eq!(session, pid, "the child leads its own session"); } + #[test] + fn compacts_a_path_too_long_for_cmd() { + let sep = if cfg!(windows) { ";" } else { ":" }; + let join = |dirs: &[&str]| OsString::from(dirs.join(sep)); + let long = |name: &str| format!("/tools/{}/{name}", "x".repeat(40)); + let (a, b, c, gone) = (long("a"), long("b"), long("c"), long("gone")); + let present = |d: &Path| !d.ends_with("gone"); + let never = |_: &Path| None; + // Fits already: left alone. + assert_eq!(compact_path_list(&join(&[&a, &b]), 200, present, never), None); + // Later duplicates and missing directories go, the order stays. + let path = join(&[&a, &gone, &b, &a, &format!("{b}/"), "", &c]); + assert_eq!(compact_path_list(&path, 160, present, never), Some(join(&[&a, &b, &c]))); + // Still too long: the longest directories take their short form until it fits. + let shorten = |d: &Path| Some(std::path::PathBuf::from(format!("/S/{}", d.file_name()?.to_string_lossy()))); + let path = join(&[&a, &format!("{b}-longer"), &c]); + assert_eq!(compact_path_list(&path, 120, present, shorten), Some(join(&[&a, "/S/b-longer", &c]))); + assert_eq!(compact_path_list(&path, 60, present, shorten), Some(join(&["/S/a", "/S/b-longer", "/S/c"]))); + } + #[test] fn process_alive_tells_live_from_dead_pids() { assert!(process_alive(std::process::id())); From c931cbecc0a0bf5db15d64caefb4dd12668ba7d8 Mon Sep 17 00:00:00 2001 From: Bert Verhelst Date: Sat, 5 Dec 2026 16:17:06 +0100 Subject: [PATCH 02/22] fix(run): keep the dependency install prompt inside the IDE (#8242) Branch switches rewrite lockfiles, so the "Dependencies changed since the last install" prompt came back each time and, with the IDE in the background, was mirrored to an OS notification. Notifications can now pass system: false to stay in the balloon and the Notifications tool window, and the install prompt does (IDEA keeps system notifications for finished builds, tests and long tasks). The package.json check now also counts overrides, resolutions, pnpm overrides/patches/extensions/peer rules, bundled deps, *Meta and workspaces, ignoring key order; baselines move to a v2 store. Co-authored-by: bertyhell <1710840+bertyhell@users.noreply.github.com> --- src/features/run/npmInstall.test.ts | 52 ++++++++++++++++++++++++- src/features/run/npmInstall.ts | 40 +++++++++++++++++-- src/workbench/contributions.ts | 6 +++ src/workbench/notificationStore.test.ts | 9 ++++- src/workbench/notificationStore.ts | 5 ++- 5 files changed, 105 insertions(+), 7 deletions(-) diff --git a/src/features/run/npmInstall.test.ts b/src/features/run/npmInstall.test.ts index 8a4dc059e0..18d08d1df6 100644 --- a/src/features/run/npmInstall.test.ts +++ b/src/features/run/npmInstall.test.ts @@ -17,7 +17,13 @@ vi.mock("./store", () => run); import { emitLocalIdeEvent, type IdeEvent, type RunConfig } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { provideNotificationService } from "@/workbench/contributions"; -import { installDue, isWorkspaceMember, pnpmWorkspacePackages, registerNpmInstall } from "./npmInstall"; +import { + dependencySignature, + installDue, + isWorkspaceMember, + pnpmWorkspacePackages, + registerNpmInstall, +} from "./npmInstall"; const ok = (data: T) => Promise.resolve({ status: "ok" as const, data }); const err = () => Promise.resolve({ status: "error" as const, error: { kind: "notFound", message: "" } }); @@ -99,6 +105,8 @@ it("asks once for a fresh clone and installs with the detected package manager i await open(); expect(titles()).toEqual(["Dependencies are not installed"]); expect(notify.mock.calls[0]![0].body).toBe("Run 'pnpm install' to install them."); + // In the IDE only: branch switches would otherwise raise an OS notification each time. + expect(notify.mock.calls[0]![0].system).toBe(false); await fsChanged("/p/package.json"); expect(titles()).toHaveLength(1); @@ -134,6 +142,48 @@ it("asks when the lockfile changes after the install (a pull), not for package.j expect(titles()).toHaveLength(2); }); +it("signs only what an install resolves from, ignoring key order", () => { + const sig = (extra: object) => dependencySignature(JSON.parse(pkg({ react: "^19.0.0", vite: "^7.0.0" }, extra))); + const base = sig({}); + expect(sig({ version: "2.0.0", scripts: { build: "vite build" }, engines: { node: ">=22" } })).toBe(base); + expect(sig({ dependencies: { vite: "^7.0.0", react: "^19.0.0" } })).toBe(base); + for (const extra of [ + { overrides: { lodash: "4.17.21" } }, + { resolutions: { lodash: "4.17.21" } }, + { pnpm: { overrides: { lodash: "4.17.21" } } }, + { pnpm: { patchedDependencies: { react: "patches/react.patch" } } }, + { peerDependencies: { react: "*" } }, + { workspaces: ["packages/*"] }, + ]) + expect(sig(extra), JSON.stringify(extra)).not.toBe(base); + expect(sig({ pnpm: { onlyBuiltDependencies: ["esbuild"] } })).toBe(base); +}); + +it("asks for an overrides change, not for a package with only overrides", async () => { + write("/p/package.json", 1_000, pkg({}, { overrides: { lodash: "4.17.21" } })); + await open(); + expect(notify).not.toHaveBeenCalled(); + dispose(); + + write("/p/package.json", 1_000, pkg({ react: "^19.0.0" })); + write("/p/node_modules/.package-lock.json", 2_000); + await open(); + write("/p/package.json", 60_000, pkg({ react: "^19.0.0" }, { overrides: { lodash: "4.17.21" } })); + await fsChanged("/p/package.json"); + expect(titles()).toEqual(["Dependencies changed since the last install"]); +}); + +it("does not take baselines stored before the signature widened as changed", async () => { + localStorage.setItem( + "openidea.npmInstall.v1", + JSON.stringify({ baseline: { "/p/package.json": JSON.stringify([{ react: "^19.0.0" }, null, null, null]) } }), + ); + write("/p/package.json", 60_000, pkg({ react: "^19.0.0" }, { version: "1.0.1" })); + write("/p/node_modules/.package-lock.json", 2_000); + await open(); + expect(notify).not.toHaveBeenCalled(); +}); + it("asks once at the workspace root for a member's dependency change", async () => { write("/p/package.json", 1_000, pkg({}, { workspaces: ["packages/*"] })); write("/p/yarn.lock", 1_000); diff --git a/src/features/run/npmInstall.ts b/src/features/run/npmInstall.ts index 3ce81986cc..778840d7a6 100644 --- a/src/features/run/npmInstall.ts +++ b/src/features/run/npmInstall.ts @@ -16,10 +16,26 @@ const LOCKS = ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "ya /** Rewritten by every install: npm, pnpm, Yarn classic, Yarn's node-modules linker. */ const MARKERS = [".package-lock.json", ".modules.yaml", ".yarn-integrity", ".yarn-state.yml"]; const DEP_FIELDS = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"] as const; +/** What an install resolves from, compared between checks: the dependency lists plus overrides, patches and workspaces. */ +const INSTALL_FIELDS = [ + ...DEP_FIELDS, + "bundleDependencies", + "bundledDependencies", + "peerDependenciesMeta", + "dependenciesMeta", + "overrides", + "resolutions", + "workspaces", + "pnpm.overrides", + "pnpm.patchedDependencies", + "pnpm.packageExtensions", + "pnpm.peerDependencyRules", +]; // ponytail: bun writes bun.lock just after node_modules and leaves no marker, so a lockfile this // close to the install counts as written by it. const SLACK_MS = 2000; -const STORE_KEY = "openidea.npmInstall.v1"; +// v2: the signature gained `INSTALL_FIELDS` beyond `DEP_FIELDS`; v1 baselines would all read as changed. +const STORE_KEY = "openidea.npmInstall.v2"; export type InstallDue = "missing" | "stale" | null; @@ -38,9 +54,25 @@ export function installDue(f: { return Math.max(f.lockAt ?? 0, f.editedAt ?? 0) > f.installedAt + SLACK_MS ? "stale" : null; } -/** The dependency fields of a `package.json`, as compared between checks (scripts and the rest do not count). */ +/** `value` as JSON with object keys sorted, so reordering entries is no change. */ +const canonical = (value: unknown): unknown => + Array.isArray(value) + ? value.map(canonical) + : value && typeof value === "object" + ? Object.fromEntries( + Object.keys(value) + .sort() + .map((k) => [k, canonical((value as Record)[k])]), + ) + : value; + +/** The install fields of a `package.json`, as compared between checks (scripts, version and the rest do not count). */ export function dependencySignature(pkg: Record | null): string { - return JSON.stringify(DEP_FIELDS.map((f) => pkg?.[f] ?? null)); + const at = (path: string) => + path + .split(".") + .reduce((v, k) => (v && typeof v === "object" ? (v as Record)[k] : undefined), pkg); + return JSON.stringify(INSTALL_FIELDS.map((f) => canonical(at(f) ?? null))); } interface Store { @@ -276,6 +308,8 @@ function check(root: string) { group: "run", level: "warning", key, + // Branch switches rewrite lockfiles: this waits for the user's return, not the desktop. + system: false, title: due === "missing" ? "Dependencies are not installed" : "Dependencies changed since the last install", body: rel ? tx`Run '${command}' in '${rel}' to install them.` : tx`Run '${command}' to install them.`, actions: [ diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index 86c966ba9d..19e857cac5 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -989,6 +989,12 @@ export interface NotificationService { userInitiated?: boolean; /** Skip the chime even when "Play sound" is on (e.g. native OS sound already played). */ silent?: boolean; + /** + * Set to false to keep it inside the IDE: no OS notification (or the dock badge that comes + * with one) and no chime while OpenIDEA is in the background. For state the user only needs + * on return, such as dependencies to install after a branch switch. + */ + system?: boolean; }): void; /** Hides the balloon of the notification with `key` (it stays in the log), e.g. once its cause is gone. */ expire?(key: string): void; diff --git a/src/workbench/notificationStore.test.ts b/src/workbench/notificationStore.test.ts index 4f06099688..98fd8405e5 100644 --- a/src/workbench/notificationStore.test.ts +++ b/src/workbench/notificationStore.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { notify } from "./notificationStore"; +import { notify, useNotifications } from "./notificationStore"; const { showSystemNotification } = vi.hoisted(() => ({ showSystemNotification: vi.fn(async (_title: string, _body: string) => ({ status: "ok", data: null })), @@ -68,6 +68,13 @@ describe("system toast coalescing", () => { expect(showSystemNotification.mock.calls[1]![0]).toBe("Edit 29"); }); + it("keeps a notification with `system: false` inside the IDE", () => { + const id = notify({ level: "warning", title: "Dependencies changed since the last install", system: false }); + vi.advanceTimersByTime(3000); + expect(showSystemNotification).not.toHaveBeenCalled(); + expect(useNotifications.getState().items.find((x) => x.id === id)).toMatchObject({ balloon: true, read: false }); + }); + it("falls back to the count alone when a balloon has no body", () => { notify({ level: "warning", title: "Cannot reload Maven projects" }); notify({ level: "warning", title: "Cannot reload Gradle projects" }); diff --git a/src/workbench/notificationStore.ts b/src/workbench/notificationStore.ts index cf0a19482e..1bfc7f5aaf 100644 --- a/src/workbench/notificationStore.ts +++ b/src/workbench/notificationStore.ts @@ -206,8 +206,9 @@ export function notify(n: Parameters[0]): number // OS toast owns the chime when system notifications are on and the app is backgrounded. const systemOn = useProject.getState().settings?.notifications?.systemNotifications !== false; const backgrounded = typeof document !== "undefined" && !document.hasFocus(); - if (balloon && prefs.sound && !n.silent && !(systemOn && backgrounded)) playSound(); - if (balloon && isTauri()) { + const system = n.system !== false; + if (balloon && prefs.sound && !n.silent && !(backgrounded && (systemOn || !system))) playSound(); + if (balloon && system && isTauri()) { // In the UI language, as the balloon shows it; a plugin's own text stays as written. const shown = (text: string) => (n.verbatim ? text : txTemplate(text)); const plain = typeof n.body === "string" ? shown(n.body) : ""; From fb91ace8aa26ee14b15077f12378e636d898ccf0 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Sat, 5 Dec 2026 23:29:10 +0800 Subject: [PATCH 03/22] fix(agents): don't let a late model request abort a newer model's discovery (#8249) load_levels hands the catalog request to a blocking task, which can run after a newer selection's request; the late one then superseded and aborted the newer discovery, failing it with "The agent did not report settings for the selected model" (the intermittent Windows failure of rapid_idle_model_switches_share_discovery_and_never_apply_a_stale_completion). Model requests now take a ticket when made; an older one neither changes the requested model nor supersedes the running flight. --- crates/ide-agent/src/catalogs.rs | 57 +++++++++++++++++++++++++++++--- crates/ide-agent/src/tests.rs | 50 ++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 4 deletions(-) diff --git a/crates/ide-agent/src/catalogs.rs b/crates/ide-agent/src/catalogs.rs index b49517ffe7..afba6f84b4 100644 --- a/crates/ide-agent/src/catalogs.rs +++ b/crates/ide-agent/src/catalogs.rs @@ -25,6 +25,8 @@ type Key = (PathBuf, PathBuf, String); #[derive(Default)] pub struct AgentCatalogs { state: Mutex, + /// Orders model requests by when they were made, not when they reach `state`. + tickets: std::sync::atomic::AtomicU64, #[cfg(test)] clock_ms: std::sync::atomic::AtomicU64, } @@ -49,6 +51,8 @@ struct Entry { abort: Option, flight_model: Option, requested_model: Option, + /// Ticket of the newest model request applied: an older one arriving late can't supersede it. + model_ticket: u64, model_failures: HashMap, catalog: Option, } @@ -254,11 +258,13 @@ impl AgentCatalogs { } let unavailable = || "The agent did not report settings for the selected model".to_owned(); let spec = shared.spec(provider).ok_or_else(unavailable)?; + // Taken now: the blocking task may run after a newer selection's request. + let ticket = self.ticket(); let flight = { let catalogs = self.clone(); let shared = shared.clone(); let model = model.to_owned(); - tokio::task::spawn_blocking(move || catalogs.request(&shared, spec, false, Some(&model)).1) + tokio::task::spawn_blocking(move || catalogs.request_with(&shared, spec, false, Some(&model), ticket).1) .await .map_err(|e| e.to_string())? }; @@ -331,12 +337,49 @@ impl AgentCatalogs { } /// Start or join a lookup. No queued refresh can outlive the request that asked for it. + /// The model the running discovery of `provider` looks up, if one is running. + #[cfg(test)] + pub(crate) fn flight_model(&self, shared: &Shared, provider: &str) -> Option> { + let state = self.state.lock(); + let entry = state.entries.get(&Self::key(shared, provider))?; + entry.flight.as_ref().map(|_| entry.flight_model.clone()) + } + + #[cfg(test)] + pub(crate) fn request_as_of( + self: &Arc, + shared: &Arc, + spec: provider::ProviderSpec, + model: &str, + ticket: u64, + ) -> Option> { + self.request_with(shared, spec, false, Some(model), ticket).1 + } + + pub(crate) fn ticket(&self) -> u64 { + self.tickets.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1 + } + pub(crate) fn request( self: &Arc, shared: &Arc, spec: provider::ProviderSpec, force: bool, model: Option<&str>, + ) -> (AgentModelCatalog, Option>) { + let ticket = self.ticket(); + self.request_with(shared, spec, force, model, ticket) + } + + /// [`Self::request`] for a request made when `ticket` was taken. A model request older than + /// the newest one applied neither changes the requested model nor supersedes its flight. + fn request_with( + self: &Arc, + shared: &Arc, + spec: provider::ProviderSpec, + force: bool, + model: Option<&str>, + ticket: u64, ) -> (AgentModelCatalog, Option>) { let key = Self::key(shared, &spec.id); let context = LaunchContext::new(spec.clone(), &shared.paths.project_root); @@ -388,6 +431,7 @@ impl AgentCatalogs { abort: None, flight_model: None, requested_model: None, + model_ticket: 0, model_failures: HashMap::new(), }, ); @@ -404,10 +448,15 @@ impl AgentCatalogs { || (!fresh && catalog.model_option().is_none()) }) .map(str::to_owned); - if model.is_some() && entry.requested_model.as_deref() != model { - entry.requested_model = model.map(str::to_owned); + let stale = model.is_some() && ticket < entry.model_ticket; + if model.is_some() && !stale { + entry.model_ticket = ticket; + if entry.requested_model.as_deref() != model { + entry.requested_model = model.map(str::to_owned); + } } - let superseded = model.is_some() + let superseded = !stale + && model.is_some() && entry.flight.is_some() && (entry.flight_model.is_some() || target.is_some()) && entry.flight_model.as_deref() != target.as_deref(); diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index 15f887b53a..75da86cc4b 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -4455,6 +4455,56 @@ async fn rapid_idle_model_switches_share_discovery_and_never_apply_a_stale_compl restored.shutdown(); } +/// A model request reaches the catalogs from a blocking task, so it may arrive after a newer +/// selection's; arriving late, it must not supersede (and abort) the newer discovery. +#[tokio::test(flavor = "multi_thread")] +async fn a_late_model_request_never_supersedes_a_newer_discovery() { + let tmp = tempfile::tempdir().unwrap(); + let agent = Arc::new(FakeAgent::default()); + *agent.model_options.lock() = HashMap::from([ + ("big".into(), effort_options(&["low", "high"], "high")), + ("small".into(), effort_options(&["minimal", "medium"], "minimal")), + ("plain".into(), vec![]), + ]); + let mgr = manager(tmp.path(), agent.clone()); + let task = mgr + .create(NewAgentTask { + prompt: text("again"), + provider: "claude-acp".into(), + isolation: Isolation::Local, + ..Default::default() + }) + .await + .unwrap(); + wait_for(&mgr, &task.id, AgentStatus::Ready).await; + mgr.shutdown(); + let restored = Arc::new(manager(tmp.path(), agent.clone())); + let (catalogs, shared) = (restored.shared.paths.catalogs.clone(), restored.shared.clone()); + let spec = || shared.spec("claude-acp").unwrap(); + + let late = catalogs.ticket(); + let (release, gate) = std::sync::mpsc::channel(); + *agent.model_config_gate.lock() = Some(gate); + let newer = { + let (catalogs, shared) = (catalogs.clone(), shared.clone()); + tokio::spawn(async move { catalogs.load_levels(&shared, "claude-acp", "plain").await }) + }; + tokio::time::timeout(Duration::from_secs(5), async { + while agent.model_config_gate.lock().is_some() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert_eq!(catalogs.flight_model(&shared, "claude-acp"), Some(Some("plain".into()))); + + catalogs.request_as_of(&shared, spec(), "small", late); + assert_eq!(catalogs.flight_model(&shared, "claude-acp"), Some(Some("plain".into())), "not superseded"); + release.send(()).unwrap(); + assert_eq!(newer.await.unwrap().unwrap(), Vec::::new()); + restored.shutdown(); +} + #[tokio::test(flavor = "multi_thread")] async fn explicit_service_tier_reaches_the_session_even_when_it_matches_the_reported_default() { for value in [None, Some("false"), Some("true")] { From aa124276b297a9141d81f0bfcb4406cc2b721225 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Sat, 5 Dec 2026 23:44:53 +0800 Subject: [PATCH 04/22] feat(vcs): nest repositories under their directories in the grouped Branches pane (#8254) With Group by Repository on, the Log's Branches pane listed each repository by its full project-relative path. Repositories now sit under the directories their paths share; a directory with a single child joins its name to the child's, so projects whose repositories share no directories look the same as before. Closes #7751 --- src/features/vcs/__tests__/multiRoot.test.ts | 47 ++++++++++++++++++- src/features/vcs/branches.ts | 48 ++++++++++++++++---- 2 files changed, 86 insertions(+), 9 deletions(-) diff --git a/src/features/vcs/__tests__/multiRoot.test.ts b/src/features/vcs/__tests__/multiRoot.test.ts index 4152c6f3c7..a9e29dc5ce 100644 --- a/src/features/vcs/__tests__/multiRoot.test.ts +++ b/src/features/vcs/__tests__/multiRoot.test.ts @@ -14,7 +14,7 @@ vi.mock("@/platform/ipc", async (original) => { }; }); import { commitKey, graphCommit, mergeRepoLogs, type RepoCommit } from "../multiRoot"; -import { buildRepositoryBranchTree } from "../branches"; +import { branchGroupKeys, buildRepositoryBranchTree, type BranchTreeNode } from "../branches"; import { emptyFilters, goToRefRepositories, @@ -245,6 +245,51 @@ describe("multi-root Git log", () => { }); }); +describe("repository directories in the Branches pane", () => { + const tree = (names: string[]) => + buildRepositoryBranchTree( + names.map((name) => ({ root: `/project/${name}`, name, branches: [branch("main")], tags: [] })), + () => [], + ).find((r) => r.key === "g:local")!.children!; + const shape = (nodes: readonly BranchTreeNode[]): unknown[] => + nodes.map((n) => (n.kind === "folder" ? { [n.label]: shape(n.children!) } : n.label)); + + it("nests repositories under the directories they share", () => { + expect( + shape( + tree([ + "app", + "source-code/idea/abc", + "source-code/idea/def", + "source-code/webstorm/abc", + "source-code/webstorm/def", + "source-code/webstorm/ghi", + ]), + ), + ).toEqual(["app", { "source-code": [{ idea: ["abc", "def"] }, { webstorm: ["abc", "def", "ghi"] }] }]); + }); + + it("joins directories with a single child into one row", () => { + expect(shape(tree(["a/b/one", "a/b/two", "c/d/three", "front"]))).toEqual([ + { "a/b": ["one", "two"] }, + "c/d/three", + "front", + ]); + }); + + it("keeps each repository's node and keys unique", () => { + const local = tree(["x/one", "x/two", "y/one"]); + const repos = branchGroupKeys(local); + expect(new Set(repos).size).toBe(repos.length); + const folder = local.find((n) => n.kind === "folder")!; + expect(folder.children!.map((n) => [n.kind, n.repo])).toEqual([ + ["repository", "/project/x/one"], + ["repository", "/project/x/two"], + ]); + expect(local[1]).toMatchObject({ kind: "repository", label: "y/one", repo: "/project/y/one" }); + }); +}); + describe("Git log background refresh", () => { it("keeps history and selection visible until the replacement is ready", async () => { useVcs.setState({ roots: ["/project/front"] }); diff --git a/src/features/vcs/branches.ts b/src/features/vcs/branches.ts index ece04e2a82..0265bec551 100644 --- a/src/features/vcs/branches.ts +++ b/src/features/vcs/branches.ts @@ -577,18 +577,50 @@ export function buildRepositoryBranchTree( label, kind: "group", ref: null, - children: trees.map((r) => ({ - key: `${key}:${r.root}`, - label: r.name, - kind: "repository", - ref: null, - repo: r.root, - children: scope(r.nodes.find((n) => n.key === key)?.children ?? [], r.root), - })), + children: byDirectory( + trees.map((r) => ({ + path: r.name.split("/"), + node: { + key: `${key}:${r.root}`, + label: r.name, + kind: "repository", + ref: null, + repo: r.root, + children: scope(r.nodes.find((n) => n.key === key)?.children ?? [], r.root), + }, + })), + `${key}:dir:`, + ), })), ]; } +/** + * Repositories under the directories their names share. A directory holding one repository + * or one directory joins its name to the child's, so repositories without shared directories + * keep their full name on one row. + */ +function byDirectory(entries: readonly { path: string[]; node: BranchTreeNode }[], key: string): BranchTreeNode[] { + const rows = new Map(); + entries.forEach((e, i) => { + const row = e.path.length > 1 ? `d:${e.path[0]}` : `r:${i}`; + rows.set(row, [...(rows.get(row) ?? []), e]); + }); + return [...rows].map(([row, inside]): BranchTreeNode => { + const dir = inside[0]!.path[0]!; + if (row.startsWith("r:")) return { ...inside[0]!.node, label: dir }; + const dirKey = `${key}${dir}`; + const children = byDirectory( + inside.map((e) => ({ ...e, path: e.path.slice(1) })), + `${dirKey}/`, + ); + const only = children.length === 1 ? children[0]! : null; + return only + ? { ...only, label: `${dir}/${only.label}` } + : { key: dirKey, label: dir, kind: "folder", ref: null, children }; + }); +} + /** * One tree for several repositories: each branch and tag listed once, with the * repositories that have it (`repos`). Its `branch` is the `current` repository's when that From 251f3953fa983ee313864d6a5cd6599db72ac80f Mon Sep 17 00:00:00 2001 From: HyperWin <92534013+HyperWinX@users.noreply.github.com> Date: Sat, 5 Dec 2026 19:46:53 +0400 Subject: [PATCH 05/22] fix(cmake): discover targets when configuration case differs (#8248) A CMake preset's build type (Debug) was compared case-sensitively with the codemodel's configuration names, so a codemodel reporting `debug` / `release` yielded no targets. The profile now picks the configuration with the exact name, else the only one that matches ignoring ASCII case; several case-insensitive matches stay unmatched rather than guessing. Co-authored-by: HyperWinX <92534013+HyperWinX@users.noreply.github.com> --- crates/ide-run/src/detect/cmake/mod.rs | 63 +++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/crates/ide-run/src/detect/cmake/mod.rs b/crates/ide-run/src/detect/cmake/mod.rs index 87626225ad..64d8e5acee 100644 --- a/crates/ide-run/src/detect/cmake/mod.rs +++ b/crates/ide-run/src/detect/cmake/mod.rs @@ -327,11 +327,19 @@ fn targets( return; } let canonical_root = dunce::canonicalize(&source_root).unwrap_or(source_root); + let matched_name = profile.and_then(|profile| { + let names = model.configurations.iter().map(|configuration| configuration.name.as_str()); + names.clone().find(|&name| name == profile.build_type).or_else(|| { + let mut matching = names.filter(|name| name.eq_ignore_ascii_case(&profile.build_type)); + let name = matching.next()?; + matching.next().is_none().then_some(name) + }) + }); for (index, configuration) in model.configurations.iter().enumerate() { let name = configuration.name.as_str(); // The profile's configuration; with CLion's "Default" build type (empty), the first one. let wanted = |p: &CMakeProfile| { - if p.build_type.is_empty() { index == 0 } else { name.is_empty() || name == p.build_type } + if p.build_type.is_empty() { index == 0 } else { name.is_empty() || Some(name) == matched_name } }; if profile.is_some_and(|p| !wanted(p)) { continue; @@ -731,6 +739,59 @@ mod tests { assert!(root.path().join("out/dev/.cmake/api/v1/query/client-openidea/codemodel-v2").is_file()); } + #[test] + fn preset_targets_match_the_codemodel_configuration() { + let root = tempfile::tempdir().unwrap(); + let root = root.path(); + fs::write(root.join("CMakeLists.txt"), "project(app)").unwrap(); + fs::write( + root.join("CMakePresets.json"), + r#"{"version":3,"configurePresets":[{"name":"dev","binaryDir":"out","cacheVariables":{"CMAKE_BUILD_TYPE":"Debug"}}]}"#, + ) + .unwrap(); + let settings = ide_core::settings::CMakeSettings { enabled_presets: vec!["dev".into()], ..Default::default() }; + let profiles = presets::profiles(root, &settings, &[]).unwrap(); + assert_eq!(profiles[0].build_type, "Debug"); + + for (names, expected) in [ + (&["Release", "debug"][..], Some("debug")), + (&["debug", "DEBUG", "Debug"][..], Some("Debug")), + (&["debug", "DEBUG"][..], None), + (&["Release"][..], None), + (&["Release", ""][..], Some("Debug")), + ] { + let configurations: Vec<_> = names + .iter() + .map(|name| serde_json::json!({"name": name, "targets": [{"jsonFile": "app.json"}]})) + .collect(); + file_api::tests::write_reply( + &root.join("out"), + &[( + "codemodel", + 2, + "model.json", + serde_json::json!({"paths": {"source": root}, "configurations": configurations}), + )], + &[( + "app.json", + serde_json::json!({"name": "app", "type": "EXECUTABLE", "artifacts": [{"path": "app"}]}), + )], + ); + let mut configs = Vec::new(); + detect(root, Some(&profiles), &mut configs); + let target_ids: Vec<_> = + configs.iter().filter(|c| c.id.starts_with("cmake:profile:target:")).map(|c| c.id.as_str()).collect(); + if let Some(expected) = expected { + let id = "cmake:profile:target:app:build"; + assert_eq!(target_ids, [id, "cmake:profile:target:app"], "{names:?}"); + let build = configs.iter().find(|c| c.id == id).unwrap(); + assert_eq!(build.args[..6], ["--build", "out", "--target", "app", "--config", expected]); + } else { + assert!(target_ids.is_empty(), "{names:?}"); + } + } + } + #[test] fn the_default_build_type_passes_no_configuration() { let root = tempfile::tempdir().unwrap(); From 1cbb5726319ee6ac0f04cc6eb1d1c9be9f84f40d Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Sat, 5 Dec 2026 23:54:10 +0800 Subject: [PATCH 06/22] fix(settings): import JDKs and Maven settings from JetBrains settings (#8259) Import JetBrains Settings left out the JDKs and Maven settings. It now adds each Java SDK of options/jdk.table.xml whose home is a JDK on this machine (missing ones are listed as not imported), and takes the Maven home, user settings file and local repository from the default project in options/project.default.xml; a wrapper or bundled Maven home stays empty. $USER_HOME$ in those files is replaced by this machine's home folder. Fixes #8169 --- crates/ide-workspace/src/settings.rs | 41 +++++++++- .../app/__tests__/jetbrainsSettings.test.ts | 64 ++++++++++++++++ src/features/app/jetbrainsSettings.tsx | 75 +++++++++++++++++++ src/platform/locales/text/en.json | 2 + src/platform/locales/text/zh.json | 2 + 5 files changed, 182 insertions(+), 2 deletions(-) diff --git a/crates/ide-workspace/src/settings.rs b/crates/ide-workspace/src/settings.rs index 6581182bec..777584e3e1 100644 --- a/crates/ide-workspace/src/settings.rs +++ b/crates/ide-workspace/src/settings.rs @@ -578,7 +578,7 @@ pub struct JetBrainsSettings { } const JETBRAINS_MARKER: &str = "IntelliJ IDEA Global Settings"; -const JETBRAINS_OPTIONS: [&str; 9] = [ +const JETBRAINS_OPTIONS: [&str; 11] = [ "options/editor-font.xml", "options/terminal-font.xml", "options/colors.scheme.xml", @@ -589,7 +589,12 @@ const JETBRAINS_OPTIONS: [&str; 9] = [ "options/mac/keymap.xml", "options/windows/keymap.xml", "options/linux/keymap.xml", + // JDKs, and the default project's Maven settings. + "options/jdk.table.xml", + "options/project.default.xml", ]; +/// Options files whose paths use `$USER_HOME$`, replaced by this machine's home folder when read. +const JETBRAINS_HOME_PATHS: [&str; 2] = ["options/jdk.table.xml", "options/project.default.xml"]; /// Folders whose files are all read: (folder, extension). const JETBRAINS_READ_DIRS: [(&str, &str); 5] = [ ("colors/", ".icls"), @@ -603,7 +608,20 @@ const JETBRAINS_MAX_TEXT: u64 = 4 << 20; /// The settings of a JetBrains IDE: an exported `settings.zip`, or the IDE's own settings folder /// (`options/`, `colors/`, … as an installed IDE keeps them). pub fn read_jetbrains_settings(path: &Path) -> IdeResult { - if path.is_dir() { read_jetbrains_folder(path) } else { read_jetbrains_archive(path) } + let mut settings = if path.is_dir() { read_jetbrains_folder(path) } else { read_jetbrains_archive(path) }?; + if let Some(home) = std::env::home_dir() { + expand_user_home(&mut settings.files, &home.to_string_lossy()); + } + Ok(settings) +} + +fn expand_user_home(files: &mut BTreeMap, home: &str) { + let home = home.trim_end_matches(['/', '\\']); + for name in JETBRAINS_HOME_PATHS { + if let Some(text) = files.get_mut(name) { + *text = text.replace("$USER_HOME$", home); + } + } } /// Plugin ids, one per line: installed from the marketplace (an export writes it), and disabled. @@ -1499,6 +1517,25 @@ mod tests { assert!(read_jetbrains_settings(&empty).is_err(), "a folder without options/ is not a settings folder"); } + #[test] + fn reads_jdks_and_maven_defaults_with_this_machines_home() { + let tmp = tempfile::tempdir().unwrap(); + let options = tmp.path().join("options"); + std::fs::create_dir_all(&options).unwrap(); + std::fs::write(options.join("jdk.table.xml"), r#""#).unwrap(); + std::fs::write( + options.join("project.default.xml"), + r#"